text
stringlengths
14
6.51M
unit Server.Models.Cadastros.ClientesGravar; interface uses System.Classes, DB, System.SysUtils, Generics.Collections, /// orm dbcbr.mapping.attributes, dbcbr.types.mapping, ormbr.types.lazy, ormbr.types.nullable, dbcbr.mapping.register, Server.Models.Base.TabelaBase; type [Entity] [Table('CLIENTES','')] [PrimaryKey('CODIGO', NotInc, NoSort, False, 'Chave primária')] TClientesGravar = class(TTabelaBase) private fCPF_CNPJ: String; FFANTASIA: String; fPESSOA: String; fAtivo: String; FRAZAO: String; fIE_RG: String; fCOD_ERP: string; fDataBase: String; //fid: Integer; fOPERADOR: Integer; fOBS_OPERADOR: String; fOBS_ADMIN: String; fDATACAD: TDateTime; fDESC_FONE2: String; fDESC_FONE3: String; fDESC_FONE1: String; fFONE2: String; fFONE3: String; fFONE1: String; fBAIRRO: String; fCEP: String; fEND_RUA: String; fCOMPLEMENTO: String; fCIDADE: String; fESTADO: String; fCONTATO_MAIL: String; fEMAIL: String; fWEBSITE: String; fDESCFAX: String; fFAX: String; fAREA2: integer; fAREA3: integer; fAREA1: integer; fAREAFAX: integer; fSEGMENTO: Integer; fCOD_MIDIA: Integer; fGRUPO: Integer; FCOD_CAMPANHA: integer; FCOD_UNIDADE: integer; { Private declarations } protected function Getid: Integer; procedure Setid(const Value: Integer); public constructor create; destructor destroy; override; { Public declarations } [Restrictions([NotNull, Unique])] [Column('CODIGO', ftInteger)] [Dictionary('CODIGO','','','','',taCenter)] property id: Integer read Getid write Setid; [Column('RAZAO', ftString, 100)] [Dictionary('RAZAO','Mensagem de validação','','','',taLeftJustify)] property RAZAO: String read FRAZAO write FRAZAO; [Column('FANTASIA', ftString, 3)] property FANTASIA:String read FFANTASIA write FFANTASIA; [Column('PESSOA', ftString, 3)] property PESSOA:String read fPESSOA write fPESSOA; [Column('ATIVO', ftString, 3)] property Ativo:String read fAtivo write fAtivo; [Column('CPF_CNPJ', ftString, 16)] property CPF_CNPJ:String read fCPF_CNPJ write fCPF_CNPJ; [Column('IE_RG', ftString, 20)] property IE_RG:String read fIE_RG write fIE_RG; [Column('COD_ERP', ftString, 10)] property COD_ERP:string read fCOD_ERP write fCOD_ERP; [Column('OPERADOR', ftInteger, 10)] property OPERADOR:Integer read fOPERADOR write fOPERADOR; [Column('OBS_OPERADOR', ftString, 255)] property OBS_OPERADOR:String read fOBS_OPERADOR write fOBS_OPERADOR; [Column('OBS_ADMIN', ftString, 255)] property OBS_ADMIN:String read fOBS_ADMIN write fOBS_ADMIN; [Column('DATACAD', ftDateTime)] property DATACAD:TDateTime read fDATACAD write fDATACAD; [Column('FONE1', ftString, 12)] property FONE1:String read fFONE1 write fFONE1; [Column('FONE2', ftString, 12)] property FONE2:String read fFONE2 write fFONE2; [Column('FONE3', ftString, 12)] property FONE3:String read fFONE3 write fFONE3; [Column('FAX', ftString, 12)] property FAX:String read fFAX write fFAX; [Column('DESC_FONE1', ftString, 30)] property DESC_FONE1:String read fDESC_FONE1 write fDESC_FONE1; [Column('DESC_FONE2', ftString, 30)] property DESC_FONE2:String read fDESC_FONE2 write fDESC_FONE2; [Column('DESC_FONE3', ftString, 30)] property DESC_FONE3:String read fDESC_FONE3 write fDESC_FONE3; [Column('DESCFAX', ftString, 30)] property DESCFAX:String read fDESCFAX write fDESCFAX; [Column('AREA1', ftInteger)] property AREA1:integer read fAREA1 write fAREA1; [Column('AREA2', ftInteger)] property AREA2:integer read fAREA2 write fAREA2; [Column('AREA3', ftInteger)] property AREA3:integer read fAREA3 write fAREA3; [Column('AREAFAX', ftInteger)] property AREAFAX:integer read fAREAFAX write fAREAFAX; [Column('END_RUA', ftString, 100)] property END_RUA:String read fEND_RUA write fEND_RUA; [Column('CIDADE', ftString, 60)] property CIDADE:String read fCIDADE write fCIDADE; [Column('BAIRRO', ftString, 60)] property BAIRRO:String read fBAIRRO write fBAIRRO; [Column('ESTADO', ftString, 2)] property ESTADO:String read fESTADO write fESTADO; [Column('CEP', ftString, 15)] property CEP:String read fCEP write fCEP; [Column('COMPLEMENTO', ftString, 100)] property COMPLEMENTO:String read fCOMPLEMENTO write fCOMPLEMENTO; [Column('CONTATO_MAIL', ftString)] property CONTATO_MAIL:String read fCONTATO_MAIL write fCONTATO_MAIL; [Column('WEBSITE', ftString)] property WEBSITE:String read fWEBSITE write fWEBSITE; [Column('EMAIL', ftString)] property EMAIL:String read fEMAIL write fEMAIL; [Column('GRUPO', ftInteger)] property GRUPO:Integer read fGRUPO write fGRUPO; [Column('COD_MIDIA', ftInteger)] property COD_MIDIA:Integer read fCOD_MIDIA write fCOD_MIDIA; [Column('SEGMENTO', ftInteger)] property SEGMENTO:Integer read fSEGMENTO write fSEGMENTO; [Column('COD_CAMPANHA', ftInteger)] property COD_CAMPANHA:Integer read FCOD_CAMPANHA write FCOD_CAMPANHA; [Column('COD_UNIDADE', ftInteger)] property COD_UNIDADE:Integer read FCOD_UNIDADE write FCOD_UNIDADE; end; implementation { TClientesGravar } constructor TClientesGravar.create; begin end; destructor TClientesGravar.destroy; begin inherited; end; function TClientesGravar.Getid: Integer; begin Result := fid; end; procedure TClientesGravar.Setid(const Value: Integer); begin fid := Value; end; initialization TRegisterClass.RegisterEntity(TClientesGravar); end.
unit UfrmListBoxDlg; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, UUtils, Vcl.AppEvnts; type TfrmListBoxDlg = class(TForm) pnlHeaderMessage: TPanel; pnlButtons: TPanel; pnlFooterMessage: TPanel; btnYes: TButton; btnNo: TButton; btnOk: TButton; lblHeader: TLabel; lblFooter: TLabel; lbItems: TListBox; pnlEdit: TPanel; edtItem: TEdit; btnCancel: TButton; ApplicationEvents1: TApplicationEvents; procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure lbItemsDblClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure edtItemChange(Sender: TObject); procedure ApplicationEvents1Idle(Sender: TObject; var Done: Boolean); private FHeader: string; FTitle: string; FFooter: string; FButtons: TMemoDlgBtn; FSelectionType: TSelectionType; FStorageName: string; FMessageText: TStringList; procedure SetButtons(const Value: TMemoDlgBtn); procedure SetFooter(const Value: string); procedure SetHeader(const Value: string); procedure SetTitle(const Value: string); function GetMessageText: TStrings; function GetSelectedItem: string; procedure SetSelectedItem(const Value: string); procedure SetSelectionType(const Value: TSelectionType); { Private declarations } protected procedure Refilter; procedure ReallignButtons; procedure OnChangeMessageText(Sender: TObject); public constructor CreateWithGoal(AOwner: TComponent; strStorageName: string); virtual; property StorageName: string read FStorageName; property SelectionType: TSelectionType read FSelectionType write SetSelectionType; property Title: string read FTitle write SetTitle; property Header: string read FHeader write SetHeader; property Footer: string read FFooter write SetFooter; property MessageText: TStrings read GetMessageText; property Buttons: TMemoDlgBtn read FButtons write SetButtons; property SelectedItem: string read GetSelectedItem write SetSelectedItem; { Public declarations } end; implementation uses StrUtils, GNUGetText {$IFNDEF SIMPLE} , USettings {$ENDIF} ; {$R *.dfm} procedure TfrmListBoxDlg.ApplicationEvents1Idle(Sender: TObject; var Done: Boolean); begin if FSelectionType in [stSingle] then begin btnYes.Enabled := lbItems.ItemIndex <> -1; btnOk.Enabled := lbItems.ItemIndex <> -1; end; if FSelectionType in [stAllowNew] then begin btnYes.Enabled := (lbItems.ItemIndex <> -1) or (edtItem.Text <> ''); btnOk.Enabled := (lbItems.ItemIndex <> -1) or (edtItem.Text <> ''); end; Done := true; end; constructor TfrmListBoxDlg.CreateWithGoal(AOwner: TComponent; strStorageName: string); begin Create(AOwner); FStorageName := strStorageName; end; procedure TfrmListBoxDlg.edtItemChange(Sender: TObject); begin Refilter; end; procedure TfrmListBoxDlg.FormCreate(Sender: TObject); begin //ChangeBidiAsNeeded(Self); TranslateComponent(self); //AutoFitButtonCaptions(Self); FHeader := ''; FTitle := Application.Title; FFooter := ''; FButtons := mdOK; FSelectionType := stSingle; ReallignButtons; FMessageText := TStringList.Create; FMessageText.OnChange := OnChangeMessageText; {$IFNDEF SIMPLE} CreateFormState(Self, 'TfrmListBoxDlg' + StorageName); {$ENDIF} end; procedure TfrmListBoxDlg.FormDestroy(Sender: TObject); begin FreeAndNil(FMessageText); end; procedure TfrmListBoxDlg.FormResize(Sender: TObject); begin ReallignButtons; end; procedure TfrmListBoxDlg.FormShow(Sender: TObject); begin pnlHeaderMessage.Visible := FHeader <> ''; pnlFooterMessage.Visible := FFooter <> ''; pnlEdit.Visible := FSelectionType in [stSingle, stAllowNew, stMultiAllowNew]; if FSelectionType in [stSingle, stAllowNew, stMultiAllowNew] then edtItem.SetFocus else lbItems.SetFocus; ReallignButtons; end; function TfrmListBoxDlg.GetMessageText: TStrings; begin Result := FMessageText; end; function TfrmListBoxDlg.GetSelectedItem: string; var slSelected: TStringList; i: integer; begin if FSelectionType in [stMulti, stMultiAllowNew] then begin slSelected := TStringList.Create; try slSelected.Delimiter := ','; slSelected.StrictDelimiter := True; lbItems.ItemIndex := -1; for i := 0 to lbItems.Items.Count - 1 do begin if lbItems.Selected[i] then begin slSelected.Add(lbItems.Items[i]); end; end; if FSelectionType = stMultiAllowNew then begin if (edtItem.Text <> '') and (lbItems.Items.IndexOf(edtItem.Text) = -1) then slSelected.Add(edtItem.Text); end; Result := slSelected.DelimitedText; finally FreeAndNil(slSelected); end; end else begin if (FSelectionType = stAllowNew) and (edtItem.Focused or (lbItems.ItemIndex = -1)) then begin Result := edtItem.Text; end else begin if lbItems.ItemIndex <> -1 then Result := lbItems.Items[lbItems.ItemIndex] else Result := ''; end; end; end; procedure TfrmListBoxDlg.lbItemsDblClick(Sender: TObject); begin case Buttons of mdYesNo: ModalResult := mrYes; mdOK, mdOKCancel: ModalResult := mrOk; else ModalResult := mrNone; end; end; procedure TfrmListBoxDlg.OnChangeMessageText(Sender: TObject); begin lbItems.Items.Assign(FMessageText); edtItem.Text := ''; end; procedure TfrmListBoxDlg.ReallignButtons; const CButtonWidth = 75; CButtonSpace = 5; var aButtonArray: TButtonArray; i: integer; iTotalButtonWidth: integer; begin case FButtons of mdYesNo: begin SetLength(aButtonArray, 2); aButtonArray[0] := btnYes; aButtonArray[1] := btnNo; end; mdOK: begin SetLength(aButtonArray, 1); aButtonArray[0] := btnOk; end; mdOKCancel: begin SetLength(aButtonArray, 2); aButtonArray[0] := btnOk; aButtonArray[1] := btnCancel; end; end; btnYes.Visible := FButtons = mdYesNo; btnNo.Visible := FButtons = mdYesNo; btnOk.Visible := FButtons in [mdOK, mdOKCancel]; btnCancel.Visible := FButtons in [mdOK, mdOKCancel]; iTotalButtonWidth := Length(aButtonArray) * (CButtonWidth + CButtonSpace) - CButtonSpace; for i := 0 to Length(aButtonArray) - 1 do begin if BiDiMode = bdRightToLeft then aButtonArray[i].Left := (Self.Width div 2) + (iTotalButtonWidth div 2) - (i+1) * (CButtonWidth + CButtonSpace) else aButtonArray[i].Left := (Self.Width div 2) - (iTotalButtonWidth div 2) + i * (CButtonWidth + CButtonSpace); aButtonArray[i].Width := CButtonWidth; if i = 0 then aButtonArray[i].Default := True else if i = (Length(aButtonArray) - 1) then aButtonArray[i].Cancel := True; end; end; procedure TfrmListBoxDlg.Refilter; var i: integer; strSelected, strItem: string; strFilter: string; begin if FSelectionType in [stSingle, stAllowNew] then begin if lbItems.ItemIndex <> -1 then strSelected := lbItems.Items[lbItems.ItemIndex] else strSelected := ''; strFilter := edtItem.Text; if strFilter = '' then begin lbItems.Items.Assign(FMessageText); end else begin lbItems.Items.Clear; for i := 0 to FMessageText.Count -1 do begin strItem := FMessageText[i]; if ContainsText(strItem, strFilter) then lbItems.Items.Add(strItem) end; end; lbItems.ItemIndex := lbItems.Items.IndexOf(strSelected); end; end; procedure TfrmListBoxDlg.SetButtons(const Value: TMemoDlgBtn); begin if FButtons <> Value then begin FButtons := Value; ReallignButtons; end; end; procedure TfrmListBoxDlg.SetFooter(const Value: string); begin if (FFooter <> Value) then begin FFooter := Value; lblFooter.Caption := FFooter; end; end; procedure TfrmListBoxDlg.SetHeader(const Value: string); begin if (FHeader <> Value) then begin FHeader := Value; lblHeader.Caption := FHeader; end; end; procedure TfrmListBoxDlg.SetSelectedItem(const Value: string); var index,i: integer; slSelected: TStringList; begin if FSelectionType in [stMulti, stMultiAllowNew] then begin slSelected := TStringList.Create; try slSelected.StrictDelimiter := True; lbItems.ItemIndex := -1; slSelected.CommaText := Value; for i := 0 to slSelected.Count - 1 do begin index := lbItems.Items.IndexOf(slSelected[i]); if index <> -1 then begin lbItems.Selected[index] := true; if lbItems.ItemIndex = -1 then lbItems.ItemIndex := index; end; end; finally FreeAndNil(slSelected); end; end else begin index := lbItems.Items.IndexOf(Value); if index <> -1 then begin lbItems.ItemIndex := index; end else begin if FSelectionType in [stAllowNew, stMultiAllowNew] then edtItem.Text := Value; lbItems.ItemIndex := index; end; end; end; procedure TfrmListBoxDlg.SetSelectionType(const Value: TSelectionType); begin FSelectionType := Value; lbItems.MultiSelect := FSelectionType in [stMulti, stMultiAllowNew]; ReallignButtons; end; procedure TfrmListBoxDlg.SetTitle(const Value: string); begin if (FTitle <> Value) then begin FTitle := Value; Caption := FTitle; end; end; end.
unit CursorLabel; { ---------------------------------------------------------- Display cursor label component (c) J. Dempster 2002 ---------------------------------------------------------- Multi-line label used to display cursor readout values 6.6.02 } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type TCursorLabel = class(TGraphicControl) private { Private declarations } FLines : TStringList ; // Lines of text displayed by label FAlignment : TAlignment ; // Alignment of text within label protected { Protected declarations } procedure Paint ; override ; public { Public declarations } Constructor Create(AOwner : TComponent) ; override ; Destructor Destroy ; override ; procedure Clear ; procedure Add( s : string ) ; published { Published declarations } //Property Font : TFont Read FFont Write FFont ; property Alignment : TAlignment read FAlignment write FAlignment ; property Height default 150 ; property Width default 200 ; property AutoSize ; property Color ; property Font ; property HelpContext ; property Hint ; property Left ; property Name ; property ShowHint ; property Top ; property Visible ; //property NumLines : Integer ; Read FNumLines Write FNumLines ; end; procedure Register; implementation procedure Register; begin RegisterComponents('Samples', [TCursorLabel]); end; constructor TCursorLabel.Create(AOwner : TComponent) ; { -------------------------------------------------- Initialise component's internal objects and fields -------------------------------------------------- } begin inherited Create(AOwner) ; // Create string list to hold lines of text FLines := TStringList.Create ; FLines.Add('Cursor') ; FAlignment := taCenter ; end ; destructor TCursorLabel.Destroy ; { ------------------------------------ Tidy up when component is destroyed ----------------------------------- } begin FLines.Free ; { Call inherited destructor } inherited Destroy ; end ; procedure TCursorLabel.Paint ; // ------------ // Display text // ------------ var i,MaxWidth,y,x,xMid : Integer ; begin // Adjust height of label Height := FLines.Count*Canvas.TextHeight('X') + 1 ; if Height <= 0 then Height := Canvas.TextHeight('X') + 1 ; // Set text background colour Canvas.Brush.Color := Color ; Canvas.FillRect( Rect(0,0,Width-1,Height-1) ) ; // Adjust width of label to accomodate text MaxWidth := 0 ; for i := 0 to FLines.Count-1 do if MaxWidth < Canvas.TextWidth(FLines.Strings[i]) then MaxWidth := Canvas.TextWidth(FLines.Strings[i]) ; MaxWidth := MaxWidth + Canvas.TextWidth('XX') ; if Width < MaxWidth then Width := MaxWidth ; // Display lines of text (centred) y := 0 ; xMid := Width div 2 ; for i := 0 to FLines.Count-1 do begin case FAlignment of taCenter : Begin x := xMid - Canvas.TextWidth(FLines.Strings[i]) div 2 ; end ; taLeftJustify : Begin x := Canvas.TextWidth('X') ; end ; else Begin x := Width - Canvas.TextWidth(FLines.Strings[i]+'X') ; end ; end ; Canvas.TextOut(x,y,FLines.Strings[i]) ; y := y + Canvas.TextHeight(FLines.Strings[i]) ; end ; end ; procedure TCursorLabel.Clear ; // ----------------------- // Clear all lines of text // ----------------------- begin FLines.Clear ; end ; procedure TCursorLabel.Add( s : string ) ; // ------------------------- // Add line of text to label // ------------------------- begin FLines.Add(s) ; end ; end.
program gol; uses crt, sysutils, strutils; type Cell = (dead, alive); Board = Array of Array of Cell; function initialBoard(starr : Array of AnsiString; h, w : Integer) : Board; var res : Board; i, j : Integer; begin SetLength(res, h, w); for i := 0 to h - 1 do for j := 0 to w - 1 do res[i,j] := dead; for i := 0 to Length(starr)-1 do for j := 1 to Length(starr[i]) do if starr[i,j] = '#' then res[i,j-1] := alive; Exit(res); end; function countNeighbors(b : Board; row, col : Integer) : Integer; var i, j, h, w : Integer; begin countNeighbors := 0; h := Length(b); w := Length(b[0]); if b[row, col] = alive then countNeighbors -= 1; for i := -1 to 1 do for j := -1 to 1 do if b[(row+i+h) mod h, (col+j+w) mod w] = alive then countNeighbors += 1; end; function nextState(b : Board) : Board; var i, j, n : Integer; newb : Board; begin SetLength(newb, Length(b), Length(b[0])); for i := 0 to Length(b)-1 do newb[i] := Copy(b[i]); for i := 0 to Length(newb) - 1 do for j := 0 to Length(newb[i]) - 1 do begin n := countNeighbors(b, i, j); if (b[i,j] = alive) and ((n < 2) or (n > 3)) then newb[i,j] := dead else if (b[i,j] = dead) and (n = 3) then newb[i,j] := alive; end; Exit(newb); end; procedure showBoard(b : Board; chrAlive, chrDead : Char); var i, j : Integer; begin for i := 0 to Length(b)-1 do begin for j := 0 to Length(b[i])-1 do if b[i,j] = alive then write(chrAlive) else write(chrDead); writeln(); end; end; var { constants } inp : Text; header, tempstr : AnsiString; initstr, headspl : Array of AnsiString; height, width : Integer; chrAlive : Char = '#'; chrDead : Char = '.'; world : Board; begin setLength(initstr, 0); assign(inp, 'input.txt'); reset(inp); readln(inp, header); while not EOF(inp) do begin readln(inp, tempstr); setLength(initstr, Length(initstr)+1); initstr[Length(initstr)-1] := tempstr; end; close(inp); headspl := SplitString(header, ' '); height := StrToInt(headspl[0]); width := StrToInt(headspl[1]); world := initialBoard(initstr, height, width); showBoard(world, chrAlive, chrDead); while True do begin write(#27, '[', height, 'A'); world := nextState(world); showBoard(world, chrAlive, chrDead); delay(250); if KeyPressed and (Readkey = ^C) then break; end; end.
unit IWBSCommon; interface // if you have JsonDataObjects from https://github.com/ahausladen/JsonDataObjects // include in your application: define JsonDataObjects // don't enable here, we don't want to include in package uses System.Classes, System.SysUtils, System.StrUtils, {$IFDEF IWBS_JSONDATAOBJECTS}JsonDataObjects, {$ENDIF} IWRenderContext, IWControl, IWHTML40Interfaces; const EOL = #13#10; type TIWBSTextAlignment = (bstaDefault, bstaLeft, bstaCenter, bstaRight, bstaJustify, bstaNowrap); TIWBSTextCase = (bstcDefault, bstcLowercase, bstcUppercase, bstcCapitalize); TIWBSSize = (bsszDefault, bsszLg, bsszMd, bsszSm, bsszXs); TIWBSRelativeSize = (bsrzDefault, bsrzLg, bsrzSm); TIWBSResizeDirection = (bsrdDefault, bsrdNone, bsrdBoth, bsrdVertical, bsrdHorizontal); const aIWBSRelativeSize: array[bsrzDefault..bsrzSm] of string = ('', 'lg', 'sm'); aIWBSSize: array[bsszDefault..bsszXs] of string = ('', 'lg', 'md', 'sm', 'xs'); aIWBSTextAlignment: array[bstaDefault..bstaNowrap] of string = ('', 'text-left', 'text-center', 'text-right', 'text-justify', 'text-nowrap'); aIWBSTextCase: array[bstcDefault..bstcCapitalize] of string = ('', 'text-lowercase', 'text-uppercase', 'text-capitalize'); aIWBSResizeDirection: array[bsrdDefault..bsrdHorizontal] of string = ('', 'none', 'both', 'vertical', 'horizontal'); type TIWBSScriptParams = class(TStringList) {$IFDEF IWBS_JSONDATAOBJECTS} private function GetJson(const Name: string): TJsonObject; procedure SetJson(const Name: string; const Value: TJsonObject); public constructor Create; property Json[const Name: string]: TJsonObject read GetJson write SetJson; {$ENDIF} end; TIWBSGridOptions = class(TPersistent) private FGridXSOffset: integer; FGridXSSpan: integer; FGridSMOffset: integer; FGridSMSpan: integer; FGridMDOffset: integer; FGridMDSpan: integer; FGridLGOffset: integer; FGridLGSpan: integer; public constructor Create; function GetClassString: string; class function GetGridClassString(AGridXSOffset, AGridSMOffset, AGridMDOffset, AGridLGOffset, AGridXSSpan, AGridSMSpan, AGridMDSpan, AGridLGSpan: integer): string; published property GridXSOffset: integer read FGridXSOffset write FGridXSOffset default 0; property GridXSSpan: integer read FGridXSSpan write FGridXSSpan default 0; property GridSMOffset: integer read FGridSMOffset write FGridSMOffset default 0; property GridSMSpan: integer read FGridSMSpan write FGridSMSpan default 0; property GridMDOffset: integer read FGridMDOffset write FGridMDOffset default 0; property GridMDSpan: integer read FGridMDSpan write FGridMDSpan default 0; property GridLGOffset: integer read FGridLGOffset write FGridLGOffset default 0; property GridLGSpan: integer read FGridLGSpan write FGridLGSpan default 0; end; IIWBSComponent = interface(IIWHTML40Control) ['{12925CB3-58EC-4B56-B032-478892548906}'] procedure AsyncRemoveControl; procedure AsyncRefreshControl; procedure InternalRenderScript(AContext: TIWCompContext; const AHTMLName: string; AScript: TStringList); function HTMLControlImplementation: TIWHTMLControlImplementation; function GetCustomAsyncEvents: TOwnedCollection; procedure SetCustomAsyncEvents(const Value: TOwnedCollection); function IsStoredCustomAsyncEvents: Boolean; function GetCustomRestEvents: TOwnedCollection; procedure SetCustomRestEvents(const Value: TOwnedCollection); function IsStoredCustomRestEvents: Boolean; function GetScript: TStringList; procedure SetScript(const AValue: TStringList); function GetScriptParams: TIWBSScriptParams; procedure SetScriptParams(const AValue: TIWBSScriptParams); function GetStyle: TStringList; procedure SetStyle(const AValue: TStringList); function get_Visible: Boolean; procedure set_Visible(Value: Boolean); property CustomAsyncEvents: TOwnedCollection read GetCustomAsyncEvents write SetCustomAsyncEvents; property CustomRestEvents: TOwnedCollection read GetCustomRestEvents write SetCustomRestEvents; property Script: TStringList read GetScript write SetScript; property ScriptParams: TIWBSScriptParams read GetScriptParams write SetScriptParams; property Style: TStringList read GetStyle write SetStyle; property Visible: boolean read get_Visible write set_Visible; end; TIWBSCommon = class public class procedure AddCssClass(var ACss: string; const AClass: string); class procedure AsyncRemoveControl(const AHTMLName: string); class function RenderStyle(AComponent: IIWBSComponent): string; class procedure ReplaceParams(const AHTMLName: string; AScript: TStrings; AParams: TStrings); class procedure SetNotVisible(AParams: TStrings); class procedure ValidateParamName(const AName: string); class procedure ValidateTagName(const AName: string); end; procedure SetAsyncDisabled(AContext: TIWCompContext; const HTMLName: string; Value: boolean; var OldValue: boolean); procedure SetAsyncReadOnly(AContext: TIWCompContext; const HTMLName: string; Value: boolean; var OldValue: boolean); procedure SetAsyncVisible(AContext: TIWCompContext; const HTMLName: string; Value: boolean; var OldValue: boolean); procedure SetAsyncClass(AContext: TIWCompContext; const HTMLName: string; const Value: string; var OldValue: string); procedure SetAsyncStyle(AContext: TIWCompContext; const HTMLName: string; const Value: string; var OldValue: string); procedure SetAsyncChecked(AContext: TIWCompContext; const HTMLName: string; const Value: boolean; var OldValue: boolean); procedure SetAsyncText(AContext: TIWCompContext; const HTMLName: string; const Value: string; var OldValue: string); procedure SetAsyncHtml(AContext: TIWCompContext; const HTMLName: string; const Value: string; var OldValue: string); implementation uses IW.Common.System, IWBaseHTMLControl, IWBSUtils; {$region 'TIWBSGridOptions'} constructor TIWBSGridOptions.Create; begin FGridXSOffset := 0; FGridXSSpan := 0; FGridSMOffset := 0; FGridSMSpan := 0; FGridMDOffset := 0; FGridMDSpan := 0; FGridLGOffset := 0; FGridLGSpan := 0; end; class function TIWBSGridOptions.GetGridClassString(AGridXSOffset, AGridSMOffset, AGridMDOffset, AGridLGOffset, AGridXSSpan, AGridSMSpan, AGridMDSpan, AGridLGSpan: integer): string; procedure AddCssValue(var s: string; const Value: string); begin if s <> '' then s := s + ' '; s := s + Value; end; begin Result := ''; if AGridXSOffset > 0 then AddCssValue(Result, 'col-xs-offset-'+IntToStr(AGridXSOffset)); if AGridSMOffset > 0 then AddCssValue(Result, 'col-sm-offset-'+IntToStr(AGridSMOffset)); if AGridMDOffset > 0 then AddCssValue(Result, 'col-md-offset-'+IntToStr(AGridMDOffset)); if AGridLGOffset > 0 then AddCssValue(Result, 'col-lg-offset-'+IntToStr(AGridLGOffset)); if (AGridXSSpan > 0) then AddCssValue(Result, 'col-xs-'+IntToStr(AGridXSSpan)); if (AGridSMSpan > 0) then AddCssValue(Result, 'col-sm-'+IntToStr(AGridSMSpan)); if (AGridMDSpan > 0) then AddCssValue(Result, 'col-md-'+IntToStr(AGridMDSpan)); if (AGridLGSpan > 0) then AddCssValue(Result, 'col-lg-'+IntToStr(AGridLGSpan)); end; function TIWBSGridOptions.GetClassString: string; begin Result := GetGridClassString(FGridXSOffset, FGridSMOffset, FGridMDOffset, FGridLGOffset, FGridXSSpan, FGridSMSpan, FGridMDSpan, FGridLGSpan); end; {$endregion} {$region 'AsyncRender functions'} procedure SetAsyncDisabled(AContext: TIWCompContext; const HTMLName: string; Value: boolean; var OldValue: boolean); begin if OldValue <> Value then begin AContext.WebApplication.CallBackResponse.AddJavaScriptToExecute('$("#'+HTMLName+'").prop("disabled",'+iif(Value,'true','false')+');'); OldValue := Value; end; end; procedure SetAsyncReadOnly(AContext: TIWCompContext; const HTMLName: string; Value: boolean; var OldValue: boolean); begin if OldValue <> Value then begin AContext.WebApplication.CallBackResponse.AddJavaScriptToExecute('$("#'+HTMLName+'").prop("readonly",'+iif(Value,'true','false')+');'); OldValue := Value; end; end; procedure SetAsyncVisible(AContext: TIWCompContext; const HTMLName: string; Value: boolean; var OldValue: boolean); begin if OldValue <> Value then begin AContext.WebApplication.CallBackResponse.AddJavaScriptToExecute('$("#'+HTMLName+'").css("visibility","'+iif(Value,'','hidden')+'");'); AContext.WebApplication.CallBackResponse.AddJavaScriptToExecute('$("#'+HTMLName+'").css("display","'+iif(Value,'','none')+'");'); OldValue := Value; end; end; procedure SetAsyncText(AContext: TIWCompContext; const HTMLName: string; const Value: string; var OldValue: string); begin if OldValue <> Value then begin AContext.WebApplication.CallBackResponse.AddJavaScriptToExecute('$("#'+HTMLName+'").val("'+TIWBaseHTMLControl.TextToJSStringLiteral(Value)+'");'); OldValue := Value; end; end; procedure SetAsyncHtml(AContext: TIWCompContext; const HTMLName: string; const Value: string; var OldValue: string); begin if OldValue <> Value then begin AContext.WebApplication.CallBackResponse.AddJavaScriptToExecuteAsCDATA('$("#'+HTMLName+'").html("'+IWBSTextToJsParamText(Value)+'");'); OldValue := Value; end; end; procedure SetAsyncClass(AContext: TIWCompContext; const HTMLName: string; const Value: string; var OldValue: string); begin if OldValue <> Value then begin AContext.WebApplication.CallBackResponse.AddJavaScriptToExecute('$("#'+HTMLName+'").toggleClass("'+Value+'");'); OldValue := Value; end; end; procedure SetAsyncStyle(AContext: TIWCompContext; const HTMLName: string; const Value: string; var OldValue: string); begin if OldValue <> Value then begin AContext.WebApplication.CallBackResponse.AddJavaScriptToExecute('$("#'+HTMLName+'").prop("style","'+Value+'");'); OldValue := Value; end; end; procedure SetAsyncChecked(AContext: TIWCompContext; const HTMLName: string; const Value: boolean; var OldValue: boolean); begin if OldValue <> Value then begin AContext.WebApplication.CallBackResponse.AddJavaScriptToExecute('$("#'+HTMLName+'").prop("checked",'+iif(Value,'true','false')+');'); OldValue := Value; end; end; {$endregion} {$region 'TIWBSCommon'} class procedure TIWBSCommon.AddCssClass(var ACss: string; const AClass: string); begin if ACss <> '' then ACss := ACss+' '; ACss := ACss+AClass; end; class procedure TIWBSCommon.AsyncRemoveControl(const AHTMLName: string); begin IWBSExecuteAsyncJScript('AsyncDestroyControl("'+AHTMLName+'");'); end; class function TIWBSCommon.RenderStyle(AComponent: IIWBSComponent): string; var xStyle: TStringList; i: integer; begin Result := ''; xStyle := TStringList.Create; try xStyle.Assign(AComponent.Style); // here render z-index if AComponent.ZIndex <> 0 then xStyle.Values['z-index'] := IntToStr(AComponent.Zindex); for i := 0 to xStyle.Count-1 do begin if Result <> '' then Result := Result + ';'; Result := Result + xStyle[i]; end; finally xStyle.Free; end; end; class procedure TIWBSCommon.ReplaceParams(const AHTMLName: string; AScript: TStrings; AParams: TStrings); var i: integer; s: string; begin if AScript.Count > 0 then begin s := AScript.Text; s := ReplaceText(s,'%HTMLNAME%',AHTMLName); for i := 0 to AParams.Count-1 do {$IFDEF IWBS_JSONDATAOBJECTS} if AParams.Objects[i] is TJsonObject then s := ReplaceText(s,'%'+AParams[i]+'%',TJsonObject(AParams.Objects[i]).ToJSON) else {$ENDIF} s := ReplaceText(s,'%'+AParams.Names[i]+'%',AParams.ValueFromIndex[i]); AScript.Text := s; end; end; class procedure TIWBSCommon.ValidateParamName(const AName: string); var i: integer; begin for i := 1 to Length(AName) do if not CharInSet(AName[i], ['.','0'..'9','A'..'Z','a'..'z']) then raise Exception.Create('Invalid character in param name '+AName); end; class procedure TIWBSCommon.ValidateTagName(const AName: string); var i: integer; begin if AName = '' then Exception.Create('Tag name could not be empty'); for i := 1 to Length(AName) do if ((i = 1) and not CharInSet(AName[i], ['A'..'Z','a'..'z'])) or ((i > 1) and not CharInSet(AName[i], ['0'..'9','A'..'Z','a'..'z'])) then raise Exception.Create('Invalid character in tag name '+AName); end; class procedure TIWBSCommon.SetNotVisible(AParams: TStrings); var LStyle: string; begin LStyle := AParams.Values['style']; LStyle := Trim(LStyle); if (LStyle <> '') and not AnsiEndsStr(';', LStyle) then LStyle := LStyle+';'; if not AnsiContainsStr(LStyle, 'visibility:') then LStyle := LStyle + 'visibility: hidden;'; if not AnsiContainsStr(LStyle, 'display:') then LStyle := LStyle + 'display: none;'; AParams.Values['style'] := LStyle; end; {$endregion} {$region 'TIWBSScriptParams'} {$IFDEF IWBS_JSONDATAOBJECTS} constructor TIWBSScriptParams.Create; begin inherited; Duplicates := dupError; OwnsObjects := True; Sorted := True; end; function TIWBSScriptParams.GetJson(const Name: string): TJsonObject; var i: integer; begin i := IndexOf(Name); if i < 0 then begin Result := TJsonObject.Create; AddObject(Name, Result); end else if Objects[i] = nil then begin Result := TJsonObject.Create; Objects[i] := Result; end else Result := TJsonObject(Objects[i]); end; procedure TIWBSScriptParams.SetJson(const Name: string; const Value: TJsonObject); begin Json[Name].Assign(Value); end; {$ENDIF} {$endregion} end.
{******************************************************************************* 作者: dmzn@ylsoft.com 2007-10-09 描述: 项目通用常,变量定义单元 *******************************************************************************} unit USysConst; interface uses SysUtils, Classes, UMgrLog; const cSBar_Date = 0; //日期面板索引 cSBar_Time = 1; //时间面板索引 cImg_Pack = 2; //参数包索引 cImg_Time = 3; //时间点索引 type TSysParam = record FProgID : string; //程序标识 FAppTitle : string; //程序标题栏提示 FMainTitle : string; //主窗体标题 FHintText : string; //提示文本 FCopyRight : string; //主窗体提示内容 end; //系统参数 TWriteDebugLog = procedure (const nMsg: string) of object; //调试日志 //------------------------------------------------------------------------------ var gPath: string; //程序所在路径 gSysParam:TSysParam; //程序环境参数 gDebugLog: TWriteDebugLog; //调试日志 //------------------------------------------------------------------------------ ResourceString sProgID = 'DMZN'; //默认标识 sAppTitle = 'DMZN'; //程序标题 sMainCaption = 'DMZN'; //主窗口标题 sHint = '提示'; //对话框标题 sWarn = '警告'; //== sAsk = '询问'; //询问对话框 sError = '未知错误'; //错误对话框 sDate = '日期:【%s】'; //任务栏日期 sTime = '时间:【%s】'; //任务栏时间 sUser = '用户:【%s】'; //任务栏用户 sLogDir = 'Logs\'; //日志目录 sLogExt = '.log'; //日志扩展名 sLogField = #9; //记录分隔符 sImageDir = 'Images\'; //图片目录 sReportDir = 'Report\'; //报表目录 sBackupDir = 'Backup\'; //备份目录 sBackupFile = 'Bacup.idx'; //备份索引 sConfigFile = 'Config.Ini'; //主配置文件 sConfigSec = 'Config'; //主配置小节 sVerifyCode = ';Verify:'; //校验码标记 sFormConfig = 'FormInfo.ini'; //窗体配置 sSetupSec = 'Setup'; //配置小节 sDBConfig = 'DBConn.ini'; //数据连接 sTimeConfig = 'Times.xml'; //时间小节 sPortConfig = 'Ports.Ini'; //端口配置 sDTRun = '正常'; sDTNone = '未发现'; //读头状态 sInvalidConfig = '配置文件无效或已经损坏'; //配置文件无效 sCloseQuery = '确定要退出程序吗?'; //主窗口退出 implementation 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) @abstract(Website : http://www.ormbr.com.br) @abstract(Telagram : https://t.me/ormbr) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } {$INCLUDE ..\ormbr.inc} unit ormbr.dataset.base.adapter; interface uses DB, Rtti, TypInfo, {Delphi 2010} Classes, SysUtils, StrUtils, Variants, Generics.Collections, /// orm ormbr.dataset.events, ormbr.dataset.abstract, ormbr.session.abstract, dbcbr.mapping.classes; type // M - Object M TDataSetBaseAdapter<M: class, constructor> = class(TDataSetAbstract<M>) private // Objeto para captura dos eventos do dataset passado pela interface FOrmDataSetEvents: TDataSet; // Controle de paginação vindo do banco de dados FPageSize: Integer; // procedure ExecuteOneToOne(AObject: M; AProperty: TRttiProperty; ADatasetBase: TDataSetBaseAdapter<M>); procedure ExecuteOneToMany(AObject: M; AProperty: TRttiProperty; ADatasetBase: TDataSetBaseAdapter<M>; ARttiType: TRttiType); procedure GetMasterValues; // function FindEvents(AEventName: string): Boolean; function GetAutoNextPacket: Boolean; procedure SetAutoNextPacket(const Value: Boolean); procedure ValideFieldEvents(const AFieldEvents: TFieldEventsMappingList); protected // Classe para controle de evento interno com os eventos da interface do dataset FDataSetEvents: TDataSetEvents; // Usado em relacionamento mestre-detalhe, guarda qual objeto pai FOwnerMasterObject: TObject; // Uso interno para fazer mapeamento do registro dataset FCurrentInternal: M; FMasterObject: TDictionary<string, TDataSetBaseAdapter<M>>; FLookupsField: TList<TDataSetBaseAdapter<M>>; FInternalIndex: Integer; FAutoNextPacket: Boolean; FCheckedFieldEvents: Boolean; procedure DoBeforeApplyUpdates(DataSet: TDataSet); overload; virtual; abstract; procedure DoAfterApplyUpdates(DataSet: TDataSet; AErrors: Integer); overload; virtual; abstract; procedure DoBeforeApplyUpdates(Sender: TObject; var OwnerData: OleVariant); overload; virtual; abstract; procedure DoAfterApplyUpdates(Sender: TObject; var OwnerData: OleVariant); overload; virtual; abstract; procedure DoBeforeScroll(DataSet: TDataSet); virtual; procedure DoAfterScroll(DataSet: TDataSet); virtual; procedure DoBeforeOpen(DataSet: TDataSet); virtual; procedure DoAfterOpen(DataSet: TDataSet); virtual; procedure DoBeforeClose(DataSet: TDataSet); virtual; procedure DoAfterClose(DataSet: TDataSet); virtual; procedure DoBeforeDelete(DataSet: TDataSet); virtual; procedure DoAfterDelete(DataSet: TDataSet); virtual; procedure DoBeforeInsert(DataSet: TDataSet); virtual; procedure DoAfterInsert(DataSet: TDataSet); virtual; procedure DoBeforeEdit(DataSet: TDataSet); virtual; procedure DoAfterEdit(DataSet: TDataSet); virtual; procedure DoBeforePost(DataSet: TDataSet); virtual; procedure DoAfterPost(DataSet: TDataSet); virtual; procedure DoBeforeCancel(DataSet: TDataSet); virtual; procedure DoAfterCancel(DataSet: TDataSet); virtual; procedure DoNewRecord(DataSet: TDataSet); virtual; procedure OpenDataSetChilds; virtual; abstract; procedure EmptyDataSetChilds; virtual; abstract; procedure GetDataSetEvents; virtual; procedure SetDataSetEvents; virtual; procedure DisableDataSetEvents; virtual; procedure EnableDataSetEvents; virtual; procedure ApplyInserter(const MaxErros: Integer); virtual; abstract; procedure ApplyUpdater(const MaxErros: Integer); virtual; abstract; procedure ApplyDeleter(const MaxErros: Integer); virtual; abstract; procedure ApplyInternal(const MaxErros: Integer); virtual; abstract; procedure Insert; virtual; procedure Append; virtual; procedure Post; virtual; procedure Edit; virtual; procedure Delete; virtual; procedure Close; virtual; procedure Cancel; virtual; procedure SetAutoIncValueChilds; virtual; procedure SetMasterObject(const AValue: TObject); procedure FillMastersClass(const ADatasetBase: TDataSetBaseAdapter<M>; AObject: M); function IsAssociationUpdateCascade(ADataSetChild: TDataSetBaseAdapter<M>; AColumnsNameRef: string): Boolean; virtual; procedure OpenIDInternal(const AID: Variant); overload; virtual; abstract; public constructor Create(ADataSet: TDataSet; APageSize: Integer; AMasterObject: TObject); overload; override; destructor Destroy; override; procedure OpenSQLInternal(const ASQL: string); virtual; abstract; procedure OpenWhereInternal(const AWhere: string; const AOrderBy: string = ''); virtual; abstract; procedure RefreshRecordInternal(const AObject: TObject); virtual; procedure RefreshRecord; virtual; procedure NextPacket; overload; virtual; abstract; procedure Save(AObject: M); virtual; procedure LoadLazy(const AOwner: M); virtual; abstract; procedure EmptyDataSet; virtual; abstract; procedure CancelUpdates; virtual; procedure ApplyUpdates(const MaxErros: Integer); virtual; abstract; procedure AddLookupField(const AFieldName: string; const AKeyFields: string; const ALookupDataSet: TObject; const ALookupKeyFields: string; const ALookupResultField: string; const ADisplayLabel: string = ''); function Current: M; // ObjectSet function Find: TObjectList<M>; overload; virtual; function Find(const AID: Integer): M; overload; virtual; function Find(const AID: String): M; overload; virtual; function FindWhere(const AWhere: string; const AOrderBy: string = ''): TObjectList<M>; virtual; // Property property AutoNextPacket: Boolean read GetAutoNextPacket write SetAutoNextPacket; end; implementation uses ormbr.bind, ormbr.dataset.fields, ormbr.dataset.consts, ormbr.objects.helper, ormbr.objects.utils, ormbr.rtti.helper, dbcbr.mapping.explorer, dbcbr.mapping.attributes, dbcbr.types.mapping; { TDataSetBaseAdapter<M> } constructor TDataSetBaseAdapter<M>.Create(ADataSet: TDataSet; APageSize: Integer; AMasterObject: TObject); begin FOrmDataSet := ADataSet; FPageSize := APageSize; FOrmDataSetEvents := TDataSet.Create(nil); FMasterObject := TDictionary<string, TDataSetBaseAdapter<M>>.Create; FLookupsField := TList<TDataSetBaseAdapter<M>>.Create; FCurrentInternal := M.Create; TBind.Instance.SetInternalInitFieldDefsObjectClass(ADataSet, FCurrentInternal); TBind.Instance.SetDataDictionary(ADataSet, FCurrentInternal); FDataSetEvents := TDataSetEvents.Create; FAutoNextPacket := True; // Variável que identifica o campo que guarda o estado do registro. FInternalIndex := 0; FCheckedFieldEvents := False; if AMasterObject <> nil then SetMasterObject(AMasterObject); inherited Create(ADataSet, APageSize, AMasterObject); end; destructor TDataSetBaseAdapter<M>.Destroy; begin FOrmDataSet := nil; FOwnerMasterObject := nil; FDataSetEvents.Free; FOrmDataSetEvents.Free; FCurrentInternal.Free; FMasterObject.Clear; FMasterObject.Free; FLookupsField.Clear; FLookupsField.Free; inherited; end; procedure TDataSetBaseAdapter<M>.Save(AObject: M); begin // Aualiza o DataSet com os dados a variável interna FOrmDataSet.Edit; TBind.Instance.SetPropertyToField(AObject, FOrmDataSet); FOrmDataSet.Post; end; procedure TDataSetBaseAdapter<M>.Cancel; begin FOrmDataSet.Cancel; end; procedure TDataSetBaseAdapter<M>.CancelUpdates; begin FSession.ModifiedFields.Items[M.ClassName].Clear; end; procedure TDataSetBaseAdapter<M>.Close; begin FOrmDataSet.Close; end; procedure TDataSetBaseAdapter<M>.AddLookupField(const AFieldName: string; const AKeyFields: string; const ALookupDataSet: TObject; const ALookupKeyFields: string; const ALookupResultField: string; const ADisplayLabel: string); var LColumn: TColumnMapping; LColumns: TColumnMappingList; begin // Guarda o datasetlookup em uma lista para controle interno FLookupsField.Add(TDataSetBaseAdapter<M>(ALookupDataSet)); LColumns := TMappingExplorer.GetMappingColumn(FLookupsField.Last.FCurrentInternal.ClassType); if LColumns = nil then Exit; for LColumn in LColumns do begin if LColumn.ColumnName <> ALookupResultField then Continue; DisableDataSetEvents; FOrmDataSet.Close; try TFieldSingleton .GetInstance .AddLookupField(AFieldName, FOrmDataSet, AKeyFields, FLookupsField.Last.FOrmDataSet, ALookupKeyFields, ALookupResultField, LColumn.FieldType, LColumn.Size, ADisplayLabel); finally FOrmDataSet.Open; EnableDataSetEvents; end; // Abre a tabela do TLookupField FLookupsField.Last.OpenSQLInternal(''); end; end; procedure TDataSetBaseAdapter<M>.Append; begin FOrmDataSet.Append; end; procedure TDataSetBaseAdapter<M>.EnableDataSetEvents; var LClassType: TRttiType; LProperty: TRttiProperty; LPropInfo: PPropInfo; LMethod: TMethod; LMethodNil: TMethod; begin LClassType := TRttiSingleton.GetInstance.GetRttiType(FOrmDataSet.ClassType); for LProperty in LClassType.GetProperties do begin if LProperty.PropertyType.TypeKind <> tkMethod then Continue; if not FindEvents(LProperty.Name) then Continue; LPropInfo := GetPropInfo(FOrmDataSet, LProperty.Name); if LPropInfo = nil then Continue; LMethod := GetMethodProp(FOrmDataSetEvents, LPropInfo); if not Assigned(LMethod.Code) then Continue; LMethodNil.Code := nil; SetMethodProp(FOrmDataSet, LPropInfo, LMethod); SetMethodProp(FOrmDataSetEvents, LPropInfo, LMethodNil); end; end; procedure TDataSetBaseAdapter<M>.FillMastersClass( const ADatasetBase: TDataSetBaseAdapter<M>; AObject: M); var LRttiType: TRttiType; LProperty: TRttiProperty; LAssociation: Association; begin LRttiType := TRttiSingleton.GetInstance.GetRttiType(AObject.ClassType); for LProperty in LRttiType.GetProperties do begin for LAssociation in LProperty.GetAssociation do begin if LAssociation = nil then Continue; if LAssociation.Multiplicity in [OneToOne, ManyToOne] then ExecuteOneToOne(AObject, LProperty, ADatasetBase) else if LAssociation.Multiplicity in [OneToMany, ManyToMany] then ExecuteOneToMany(AObject, LProperty, ADatasetBase, LRttiType); end; end; end; procedure TDataSetBaseAdapter<M>.ExecuteOneToOne(AObject: M; AProperty: TRttiProperty; ADatasetBase: TDataSetBaseAdapter<M>); var LBookMark: TBookmark; LValue: TValue; LObject: TObject; LDataSetChild: TDataSetBaseAdapter<M>; begin if ADatasetBase.FCurrentInternal.ClassType <> AProperty.PropertyType.AsInstance.MetaclassType then Exit; LValue := AProperty.GetNullableValue(TObject(AObject)); if not LValue.IsObject then Exit; LObject := LValue.AsObject; LBookMark := ADatasetBase.FOrmDataSet.Bookmark; ADatasetBase.FOrmDataSet.First; ADatasetBase.FOrmDataSet.BlockReadSize := MaxInt; try while not ADatasetBase.FOrmDataSet.Eof do begin // Popula o objeto M e o adiciona na lista e objetos com o registro do DataSet. TBind.Instance.SetFieldToProperty(ADatasetBase.FOrmDataSet, LObject); // Próximo registro ADatasetBase.FOrmDataSet.Next; end; finally ADatasetBase.FOrmDataSet.GotoBookmark(LBookMark); ADatasetBase.FOrmDataSet.FreeBookmark(LBookMark); ADatasetBase.FOrmDataSet.BlockReadSize := 0; end; // Populando em hierarquia de vários níveis for LDataSetChild in ADatasetBase.FMasterObject.Values do LDataSetChild.FillMastersClass(LDataSetChild, LObject); end; procedure TDataSetBaseAdapter<M>.ExecuteOneToMany(AObject: M; AProperty: TRttiProperty; ADatasetBase: TDataSetBaseAdapter<M>; ARttiType: TRttiType); var LBookMark: TBookmark; LPropertyType: TRttiType; LObjectType: TObject; LObjectList: TObject; LDataSetChild: TDataSetBaseAdapter<M>; LDataSet: TDataSet; begin LPropertyType := AProperty.PropertyType; LPropertyType := AProperty.GetTypeValue(LPropertyType); if not LPropertyType.IsInstance then raise Exception .Create('Not in instance ' + LPropertyType.Parent.ClassName + ' - ' + LPropertyType.Name); // if ADatasetBase.FCurrentInternal.ClassType <> LPropertyType.AsInstance.MetaclassType then Exit; LDataSet := ADatasetBase.FOrmDataSet; LBookMark := LDataSet.Bookmark; LDataSet.First; LDataSet.BlockReadSize := MaxInt; try while not LDataSet.Eof do begin LObjectType := LPropertyType.AsInstance.MetaclassType.Create; LObjectType.MethodCall('Create', []); // Popula o objeto M e o adiciona na lista e objetos com o registro do DataSet. TBind.Instance.SetFieldToProperty(LDataSet, LObjectType); LObjectList := AProperty.GetNullableValue(TObject(AObject)).AsObject; LObjectList.MethodCall('Add', [LObjectType]); // Populando em hierarquia de vários níveis for LDataSetChild in ADatasetBase.FMasterObject.Values do LDataSetChild.FillMastersClass(LDataSetChild, LObjectType); // Próximo registro LDataSet.Next; end; finally LDataSet.BlockReadSize := 0; LDataSet.GotoBookmark(LBookMark); LDataSet.FreeBookmark(LBookMark); end; end; procedure TDataSetBaseAdapter<M>.DisableDataSetEvents; var LClassType: TRttiType; LProperty: TRttiProperty; LPropInfo: PPropInfo; LMethod: TMethod; LMethodNil: TMethod; begin LClassType := TRttiSingleton.GetInstance.GetRttiType(FOrmDataSet.ClassType); for LProperty in LClassType.GetProperties do begin if LProperty.PropertyType.TypeKind <> tkMethod then Continue; if not FindEvents(LProperty.Name) then Continue; LPropInfo := GetPropInfo(FOrmDataSet, LProperty.Name); if LPropInfo = nil then Continue; LMethod := GetMethodProp(FOrmDataSet, LPropInfo); if not Assigned(LMethod.Code) then Continue; LMethodNil.Code := nil; SetMethodProp(FOrmDataSet, LPropInfo, LMethodNil); SetMethodProp(FOrmDataSetEvents, LPropInfo, LMethod); end; end; function TDataSetBaseAdapter<M>.Find: TObjectList<M>; begin Result := FSession.Find; end; function TDataSetBaseAdapter<M>.Find(const AID: Integer): M; begin Result := FSession.Find(AID); end; function TDataSetBaseAdapter<M>.FindEvents(AEventName: string): Boolean; begin Result := MatchStr(AEventName, ['AfterCancel' ,'AfterClose' ,'AfterDelete' , 'AfterEdit' ,'AfterInsert' ,'AfterOpen' , 'AfterPost' ,'AfterRefresh' ,'AfterScroll' , 'BeforeCancel' ,'BeforeClose' ,'BeforeDelete', 'BeforeEdit' ,'BeforeInsert' ,'BeforeOpen' , 'BeforePost' ,'BeforeRefresh','BeforeScroll', 'OnCalcFields' ,'OnDeleteError','OnEditError' , 'OnFilterRecord','OnNewRecord' ,'OnPostError']); end; function TDataSetBaseAdapter<M>.FindWhere(const AWhere, AOrderBy: string): TObjectList<M>; begin Result := FSession.FindWhere(AWhere, AOrderBy); end; procedure TDataSetBaseAdapter<M>.DoAfterClose(DataSet: TDataSet); begin if Assigned(FDataSetEvents.AfterClose) then FDataSetEvents.AfterClose(DataSet); end; procedure TDataSetBaseAdapter<M>.DoAfterDelete(DataSet: TDataSet); begin if Assigned(FDataSetEvents.AfterDelete) then FDataSetEvents.AfterDelete(DataSet); end; procedure TDataSetBaseAdapter<M>.DoAfterEdit(DataSet: TDataSet); begin if Assigned(FDataSetEvents.AfterEdit) then FDataSetEvents.AfterEdit(DataSet); end; procedure TDataSetBaseAdapter<M>.DoAfterInsert(DataSet: TDataSet); begin if Assigned(FDataSetEvents.AfterInsert) then FDataSetEvents.AfterInsert(DataSet); end; procedure TDataSetBaseAdapter<M>.DoAfterOpen(DataSet: TDataSet); begin if Assigned(FDataSetEvents.AfterOpen) then FDataSetEvents.AfterOpen(DataSet); end; procedure TDataSetBaseAdapter<M>.DoAfterPost(DataSet: TDataSet); begin if Assigned(FDataSetEvents.AfterPost) then FDataSetEvents.AfterPost(DataSet); end; procedure TDataSetBaseAdapter<M>.DoAfterScroll(DataSet: TDataSet); begin if Assigned(FDataSetEvents.AfterScroll) then FDataSetEvents.AfterScroll(DataSet); if FPageSize = -1 then Exit; if not (FOrmDataSet.State in [dsBrowse]) then Exit; if not FOrmDataSet.Eof then Exit; if FOrmDataSet.IsEmpty then Exit; if not FAutoNextPacket then Exit; // Controle de paginação de registros retornados do banco de dados NextPacket; end; procedure TDataSetBaseAdapter<M>.Insert; begin FOrmDataSet.Insert; end; procedure TDataSetBaseAdapter<M>.DoBeforeCancel(DataSet: TDataSet); var LChild: TDataSetBaseAdapter<M>; LLookup: TDataSetBaseAdapter<M>; begin if Assigned(FDataSetEvents.BeforeCancel) then FDataSetEvents.BeforeCancel(DataSet); // Executa comando Cancel em cascata if not Assigned(FMasterObject) then Exit; if FMasterObject.Count = 0 then Exit; for LChild in FMasterObject.Values do begin if not (LChild.FOrmDataSet.State in [dsInsert, dsEdit]) then Continue; LChild.Cancel; end; end; procedure TDataSetBaseAdapter<M>.DoAfterCancel(DataSet: TDataSet); begin if Assigned(FDataSetEvents.AfterCancel) then FDataSetEvents.AfterCancel(DataSet); end; procedure TDataSetBaseAdapter<M>.DoBeforeClose(DataSet: TDataSet); var LChild: TDataSetBaseAdapter<M>; LLookup: TDataSetBaseAdapter<M>; begin if Assigned(FDataSetEvents.BeforeClose) then FDataSetEvents.BeforeClose(DataSet); // Executa o comando Close em cascata if Assigned(FLookupsField) then if FLookupsField.Count > 0 then for LChild in FLookupsField do LChild.Close; if Assigned(FMasterObject) then if FMasterObject.Count > 0 then for LChild in FMasterObject.Values do LChild.Close; end; procedure TDataSetBaseAdapter<M>.DoBeforeDelete(DataSet: TDataSet); begin if Assigned(FDataSetEvents.BeforeDelete) then FDataSetEvents.BeforeDelete(DataSet); end; procedure TDataSetBaseAdapter<M>.DoBeforeEdit(DataSet: TDataSet); var LFieldEvents: TFieldEventsMappingList; begin if Assigned(FDataSetEvents.BeforeEdit) then FDataSetEvents.BeforeEdit(DataSet); // Checa o Attributo "FieldEvents" nos TFields somente uma vez if FCheckedFieldEvents then Exit; // ForeingnKey da Child LFieldEvents := TMappingExplorer.GetMappingFieldEvents(FCurrentInternal.ClassType); if LFieldEvents = nil then Exit; ValideFieldEvents(LFieldEvents); FCheckedFieldEvents := True; end; procedure TDataSetBaseAdapter<M>.DoBeforeInsert(DataSet: TDataSet); var LFieldEvents: TFieldEventsMappingList; begin if Assigned(FDataSetEvents.BeforeInsert) then FDataSetEvents.BeforeInsert(DataSet); // Checa o Attributo "FieldEvents()" nos TFields somente uma vez if FCheckedFieldEvents then Exit; // ForeingnKey da Child LFieldEvents := TMappingExplorer.GetMappingFieldEvents(FCurrentInternal.ClassType); if LFieldEvents = nil then Exit; ValideFieldEvents(LFieldEvents); FCheckedFieldEvents := True; end; procedure TDataSetBaseAdapter<M>.DoBeforeOpen(DataSet: TDataSet); begin if Assigned(FDataSetEvents.BeforeOpen) then FDataSetEvents.BeforeOpen(DataSet); end; procedure TDataSetBaseAdapter<M>.DoBeforePost(DataSet: TDataSet); var LDataSetChild: TDataSetBaseAdapter<M>; LField: TField; begin // Muda o Status do registro, para identificação do ORMBr dos registros que // sofreram alterações. LField := FOrmDataSet.Fields[FInternalIndex]; case FOrmDataSet.State of dsInsert: begin LField.AsInteger := Integer(FOrmDataSet.State); end; dsEdit: begin if LField.AsInteger = -1 then LField.AsInteger := Integer(FOrmDataSet.State); end; end; // Dispara o evento do componente if Assigned(FDataSetEvents.BeforePost) then FDataSetEvents.BeforePost(DataSet); // Aplica o Post() em todas as sub-tabelas relacionadas caso estejam em // modo Insert ou Edit. if not FOrmDataSet.Active then Exit; // Tratamento dos datasets filhos. for LDataSetChild in FMasterObject.Values do begin if LDataSetChild.FOrmDataSet = nil then Continue; if not LDataSetChild.FOrmDataSet.Active then Continue; if not (LDataSetChild.FOrmDataSet.State in [dsInsert, dsEdit]) then Continue; LDataSetChild.FOrmDataSet.Post; end; end; procedure TDataSetBaseAdapter<M>.DoBeforeScroll(DataSet: TDataSet); begin if Assigned(FDataSetEvents.BeforeScroll) then FDataSetEvents.BeforeScroll(DataSet); end; procedure TDataSetBaseAdapter<M>.DoNewRecord(DataSet: TDataSet); begin if Assigned(FDataSetEvents.OnNewRecord) then FDataSetEvents.OnNewRecord(DataSet); // Busca valor da tabela master, caso aqui seja uma tabela detalhe. if FMasterObject.Count > 0 then GetMasterValues; end; procedure TDataSetBaseAdapter<M>.Delete; begin FOrmDataSet.Delete; end; procedure TDataSetBaseAdapter<M>.Edit; begin FOrmDataSet.Edit; end; procedure TDataSetBaseAdapter<M>.GetDataSetEvents; begin // Scroll Events if Assigned(FOrmDataSet.BeforeScroll) then FDataSetEvents.BeforeScroll := FOrmDataSet.BeforeScroll; if Assigned(FOrmDataSet.AfterScroll) then FDataSetEvents.AfterScroll := FOrmDataSet.AfterScroll; // Open Events if Assigned(FOrmDataSet.BeforeOpen) then FDataSetEvents.BeforeOpen := FOrmDataSet.BeforeOpen; if Assigned(FOrmDataSet.AfterOpen) then FDataSetEvents.AfterOpen := FOrmDataSet.AfterOpen; // Close Events if Assigned(FOrmDataSet.BeforeClose) then FDataSetEvents.BeforeClose := FOrmDataSet.BeforeClose; if Assigned(FOrmDataSet.AfterClose) then FDataSetEvents.AfterClose := FOrmDataSet.AfterClose; // Delete Events if Assigned(FOrmDataSet.BeforeDelete) then FDataSetEvents.BeforeDelete := FOrmDataSet.BeforeDelete; if Assigned(FOrmDataSet.AfterDelete) then FDataSetEvents.AfterDelete := FOrmDataSet.AfterDelete; // Post Events if Assigned(FOrmDataSet.BeforePost) then FDataSetEvents.BeforePost := FOrmDataSet.BeforePost; if Assigned(FOrmDataSet.AfterPost) then FDataSetEvents.AfterPost := FOrmDataSet.AfterPost; // Cancel Events if Assigned(FOrmDataSet.BeforeCancel) then FDataSetEvents.BeforeCancel := FOrmDataSet.BeforeCancel; if Assigned(FOrmDataSet.AfterCancel) then FDataSetEvents.AfterCancel := FOrmDataSet.AfterCancel; // Insert Events if Assigned(FOrmDataSet.BeforeInsert) then FDataSetEvents.BeforeInsert := FOrmDataSet.BeforeInsert; if Assigned(FOrmDataSet.AfterInsert) then FDataSetEvents.AfterInsert := FOrmDataSet.AfterInsert; // Edit Events if Assigned(FOrmDataSet.BeforeEdit) then FDataSetEvents.BeforeEdit := FOrmDataSet.BeforeEdit; if Assigned(FOrmDataSet.AfterEdit) then FDataSetEvents.AfterEdit := FOrmDataSet.AfterEdit; // NewRecord Events if Assigned(FOrmDataSet.OnNewRecord) then FDataSetEvents.OnNewRecord := FOrmDataSet.OnNewRecord end; function TDataSetBaseAdapter<M>.IsAssociationUpdateCascade( ADataSetChild: TDataSetBaseAdapter<M>; AColumnsNameRef: string): Boolean; var LForeignKey: TForeignKeyMapping; LForeignKeys: TForeignKeyMappingList; begin Result := False; // ForeingnKey da Child LForeignKeys := TMappingExplorer.GetMappingForeignKey(ADataSetChild.FCurrentInternal.ClassType); if LForeignKeys = nil then Exit; for LForeignKey in LForeignKeys do begin if not LForeignKey.FromColumns.Contains(AColumnsNameRef) then Continue; if LForeignKey.RuleUpdate = Cascade then Exit(True); end; end; function TDataSetBaseAdapter<M>.GetAutoNextPacket: Boolean; begin Result := FAutoNextPacket; end; function TDataSetBaseAdapter<M>.Current: M; var LDataSetChild: TDataSetBaseAdapter<M>; begin if not FOrmDataSet.Active then Exit(FCurrentInternal); if FOrmDataSet.RecordCount = 0 then Exit(FCurrentInternal); TBind.Instance .SetFieldToProperty(FOrmDataSet, TObject(FCurrentInternal)); for LDataSetChild in FMasterObject.Values do LDataSetChild.FillMastersClass(LDataSetChild, FCurrentInternal); Result := FCurrentInternal; end; procedure TDataSetBaseAdapter<M>.Post; begin FOrmDataSet.Post; end; procedure TDataSetBaseAdapter<M>.RefreshRecord; var LPrimaryKey: TPrimaryKeyMapping; LParams: TParams; lFor: Integer; begin inherited; if FOrmDataSet.RecordCount = 0 then Exit; LPrimaryKey := TMappingExplorer.GetMappingPrimaryKey(FCurrentInternal.ClassType); if LPrimaryKey = nil then Exit; FOrmDataSet.DisableControls; DisableDataSetEvents; LParams := TParams.Create(nil); try for LFor := 0 to LPrimaryKey.Columns.Count -1 do begin with LParams.Add as TParam do begin Name := LPrimaryKey.Columns.Items[LFor]; ParamType := ptInput; DataType := FOrmDataSet.FieldByName(LPrimaryKey.Columns.Items[LFor]).DataType; Value := FOrmDataSet.FieldByName(LPrimaryKey.Columns.Items[LFor]).Value; end; end; if LParams.Count > 0 then FSession.RefreshRecord(LParams); finally LParams.Clear; LParams.Free; FOrmDataSet.EnableControls; EnableDataSetEvents; end; end; procedure TDataSetBaseAdapter<M>.RefreshRecordInternal(const AObject: TObject); begin end; procedure TDataSetBaseAdapter<M>.SetAutoIncValueChilds; var LAssociation: TAssociationMapping; LAssociations: TAssociationMappingList; LDataSetChild: TDataSetBaseAdapter<M>; LFor: Integer; begin // Association LAssociations := TMappingExplorer.GetMappingAssociation(FCurrentInternal.ClassType); if LAssociations = nil then Exit; for LAssociation in LAssociations do begin if not (CascadeAutoInc in LAssociation.CascadeActions) then Continue; LDataSetChild := FMasterObject.Items[LAssociation.ClassNameRef]; if LDataSetChild <> nil then begin for LFor := 0 to LAssociation.ColumnsName.Count -1 do begin if LDataSetChild.FOrmDataSet .FindField(LAssociation.ColumnsNameRef[LFor]) = nil then Continue; LDataSetChild.FOrmDataSet.DisableControls; LDataSetChild.FOrmDataSet.First; try while not LDataSetChild.FOrmDataSet.Eof do begin LDataSetChild.FOrmDataSet.Edit; LDataSetChild.FOrmDataSet .FieldByName(LAssociation.ColumnsNameRef[LFor]).Value := FOrmDataSet.FieldByName(LAssociation.ColumnsName[LFor]).Value; LDataSetChild.FOrmDataSet.Post; LDataSetChild.FOrmDataSet.Next; end; finally LDataSetChild.FOrmDataSet.First; LDataSetChild.FOrmDataSet.EnableControls; end; end; end; // Populando em hierarquia de vários níveis if LDataSetChild.FMasterObject.Count > 0 then LDataSetChild.SetAutoIncValueChilds; end; end; procedure TDataSetBaseAdapter<M>.SetAutoNextPacket(const Value: Boolean); begin FAutoNextPacket := Value; end; procedure TDataSetBaseAdapter<M>.SetDataSetEvents; begin FOrmDataSet.BeforeScroll := DoBeforeScroll; FOrmDataSet.AfterScroll := DoAfterScroll; FOrmDataSet.BeforeClose := DoBeforeClose; FOrmDataSet.BeforeOpen := DoBeforeOpen; FOrmDataSet.AfterOpen := DoAfterOpen; FOrmDataSet.AfterClose := DoAfterClose; FOrmDataSet.BeforeDelete := DoBeforeDelete; FOrmDataSet.AfterDelete := DoAfterDelete; FOrmDataSet.BeforeInsert := DoBeforeInsert; FOrmDataSet.AfterInsert := DoAfterInsert; FOrmDataSet.BeforeEdit := DoBeforeEdit; FOrmDataSet.AfterEdit := DoAfterEdit; FOrmDataSet.BeforePost := DoBeforePost; FOrmDataSet.AfterPost := DoAfterPost; FOrmDataSet.OnNewRecord := DoNewRecord; end; procedure TDataSetBaseAdapter<M>.GetMasterValues; var LAssociation: TAssociationMapping; LAssociations: TAssociationMappingList; LDataSetMaster: TDataSetBaseAdapter<M>; LField: TField; LFor: Integer; begin if not Assigned(FOwnerMasterObject) then Exit; LDataSetMaster := TDataSetBaseAdapter<M>(FOwnerMasterObject); LAssociations := TMappingExplorer.GetMappingAssociation(LDataSetMaster.FCurrentInternal.ClassType); if LAssociations = nil then Exit; for LAssociation in LAssociations do begin if not (CascadeAutoInc in LAssociation.CascadeActions) then Continue; for LFor := 0 to LAssociation.ColumnsName.Count -1 do begin LField := LDataSetMaster .FOrmDataSet.FindField(LAssociation.ColumnsName.Items[LFor]); if LField = nil then Continue; FOrmDataSet .FieldByName(LAssociation.ColumnsNameRef.Items[LFor]).Value := LField.Value; end; end; end; procedure TDataSetBaseAdapter<M>.SetMasterObject(const AValue: TObject); var LOwnerObject: TDataSetBaseAdapter<M>; begin if FOwnerMasterObject = AValue then Exit; if FOwnerMasterObject <> nil then begin LOwnerObject := TDataSetBaseAdapter<M>(FOwnerMasterObject); if LOwnerObject.FMasterObject.ContainsKey(FCurrentInternal.ClassName) then begin LOwnerObject.FMasterObject.Remove(FCurrentInternal.ClassName); LOwnerObject.FMasterObject.TrimExcess; end; end; if AValue <> nil then TDataSetBaseAdapter<M>(AValue).FMasterObject.Add(FCurrentInternal.ClassName, Self); FOwnerMasterObject := AValue; end; procedure TDataSetBaseAdapter<M>.ValideFieldEvents(const AFieldEvents: TFieldEventsMappingList); var LFor: Integer; LField: TField; begin for LFor := 0 to AFieldEvents.Count -1 do begin LField := FOrmDataSet.FindField(AFieldEvents.Items[LFor].FieldName); if LField = nil then Continue; if onSetText in AFieldEvents.Items[LFor].Events then if not Assigned(LField.OnSetText) then raise Exception.CreateFmt(cFIELDEVENTS, ['OnSetText()', LField.FieldName]); if onGetText in AFieldEvents.Items[LFor].Events then if not Assigned(LField.OnGetText) then raise Exception.CreateFmt(cFIELDEVENTS, ['OnGetText()', LField.FieldName]); if onChange in AFieldEvents.Items[LFor].Events then if not Assigned(LField.OnChange) then raise Exception.CreateFmt(cFIELDEVENTS, ['OnChange()', LField.FieldName]); if onValidate in AFieldEvents.Items[LFor].Events then if not Assigned(LField.OnValidate) then raise Exception.CreateFmt(cFIELDEVENTS, ['OnValidate()', LField.FieldName]); end; end; function TDataSetBaseAdapter<M>.Find(const AID: String): M; begin Result := FSession.Find(AID); end; end.
unit VN.Types.ViewStore; interface uses VN.Types, VN.Types.ViewNavigatorInfo, System.Generics.Collections; type TViewsStore = class private FViews: TObjectDictionary<string, TvnViewInfo>; public constructor Create; destructor Destroy; override; procedure AddView(const AName: string; ANavClass: TvnControlClass; ACreateDestroyTime: TvnCreateDestroyTime = TvnCreateDestroyTime.OnShowHide); function FindView(const AName: string; out Return: TvnViewInfo): Boolean; end; implementation uses System.SysUtils; { TViewsStore } procedure TViewsStore.AddView(const AName: string; ANavClass: TvnControlClass; ACreateDestroyTime: TvnCreateDestroyTime); var AInfo: TvnViewInfo; begin { TODO -oOwner -cGeneral : При совпадении имени вьюшки - нужно разрушить существующую и зарегистрировать новую } AInfo := TvnViewInfo.Create(AName.ToLower, ANavClass, ACreateDestroyTime); FViews.Add(AInfo.Name, AInfo); end; constructor TViewsStore.Create; begin FViews := TObjectDictionary<string, TvnViewInfo>.Create([doOwnsValues]); end; destructor TViewsStore.Destroy; begin FreeAndNil(FViews); end; function TViewsStore.FindView(const AName: string; out Return: TvnViewInfo): Boolean; var LLoweredName: string; begin LLoweredName := AName.ToLower; Result := FViews.ContainsKey(LLoweredName); if Result then Return := FViews[LLoweredName]; end; end.
unit xe_PBX05; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore, Vcl.Menus, Vcl.StdCtrls, cxCheckBox, cxButtons, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLabel, Vcl.ExtCtrls, dxSkinOffice2010Silver, dxSkinSharp; type Tfrm_PBX05 = class(TForm) Panel1: TPanel; PnlInBound: TPanel; Shape23: TShape; Shape31: TShape; Shape32: TShape; cxLabel20: TcxLabel; cxLabel22: TcxLabel; cxLabel31: TcxLabel; PnlTitle: TPanel; cxLblActive: TLabel; btnCancel: TcxButton; btnSave: TcxButton; cb_Gubun: TcxComboBox; cb_Name: TcxComboBox; cb_Use: TcxComboBox; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnSaveClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure cb_GubunPropertiesChange(Sender: TObject); procedure cb_NamePropertiesChange(Sender: TObject); procedure PnlTitleMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } gIn_ID : string; procedure proc_Init; procedure proc_ResultMsg(AData, AResult : string); end; var frm_PBX05: Tfrm_PBX05; implementation {$R *.dfm} uses main, xe_Func, xe_GNL, CidSi415Lib, xe_PBX, xe_Msg; procedure Tfrm_PBX05.btnCancelClick(Sender: TObject); begin close; end; procedure Tfrm_PBX05.btnSaveClick(Sender: TObject); var sParam, sStr, sTmp : string; iTmp : integer; begin Try sParam := ''; sParam := 'IVR_SYS_MENT_TYPE'; { case cb_Gubun.ItemIndex of 0 : sTmp := 'MENT_HOLIDAY' ; 1 : sTmp := 'MENT_LUNCH' ; 2 : sTmp := 'MENT_NOTICE' ; 4 : sTmp := 'MENT_OUT_WORK' ; 5 : sTmp := 'MENT_SYSTEM_ERR'; end; } iTmp := frm_PBX.FSYSMente.slCodeName.IndexOf(cb_Gubun.Text); sTmp := frm_PBX.FSYSMente.slCodeID[iTmp]; sParam := sParam + '│' + sTmp; sParam := sParam + '│' + cb_Name.Text; if cb_Use.ItemIndex = 0 then sParam := sParam + '│' + 'N' else sParam := sParam + '│' + 'Y' ; sStr := fSI_6820_Send('6820', sParam); except End; end; procedure Tfrm_PBX05.cb_GubunPropertiesChange(Sender: TObject); var i, iTmp : integer; sTmp : string; begin if cb_Gubun.Tag = 99 then exit; cb_Name.Properties.Items.Clear; iTmp := frm_PBX.FMenteCombo.slCodeName.IndexOf(cb_Gubun.Text); sTmp := frm_PBX.FMenteCombo.slCodeID[iTmp]; { case cb_Gubun.ItemIndex of 0 : sTmp := 'MENT_HOLIDAY' ; 1 : sTmp := 'MENT_LUNCH' ; 2 : sTmp := 'MENT_NOTICE' ; 4 : sTmp := 'MENT_OUT_WORK' ; 5 : sTmp := 'MENT_SYSTEM_ERR'; end; } for i:=0 to frm_PBX.FMente.slCategory.Count -1 do begin if (frm_PBX.FMente.slCodeID[i] = sTmp) then begin cb_Name.Properties.Items.Add(frm_PBX.FMente.slFilename[i]); end; end; cb_Name.ItemIndex := 0; end; procedure Tfrm_PBX05.cb_NamePropertiesChange(Sender: TObject); begin cb_Use.ItemIndex := 0; //변경 시 미사용으로 초기화 end; procedure Tfrm_PBX05.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure Tfrm_PBX05.FormCreate(Sender: TObject); var Save: Integer; begin //==================================================== // 폼 타이틀 제거.. Save := GetWindowLong(Handle, gwl_Style); if (Save and ws_Caption) = ws_Caption then begin case BorderStyle of bsSingle, bsSizeable: SetWindowLong(Handle, gwl_Style, Save and (not (ws_Caption)) or ws_border); end; Height := Height - getSystemMetrics(sm_cyCaption); Refresh; end; proc_Init; end; procedure Tfrm_PBX05.FormDestroy(Sender: TObject); begin Frm_PBX05 := Nil; end; procedure Tfrm_PBX05.FormShow(Sender: TObject); begin fSetFont(Frm_PBX05, GS_FONTNAME); end; procedure Tfrm_PBX05.PnlTitleMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin ReleaseCapture; PostMessage(self.Handle, WM_SYSCOMMAND, $F012, 0); end; procedure Tfrm_PBX05.proc_Init; var i, iTmp : integer; sTmp : string; begin cb_Gubun.Tag := 99; cb_Gubun.Properties.Items.Clear; for i:=0 to frm_PBX.FSYSMente.slCategory.Count -1 do begin if frm_PBX.FSYSMente.slCategory[i] = 'IVR_SYS_MENT_TYPE' then begin iTmp := cb_Gubun.Properties.Items.IndexOf(frm_PBX.FSYSMente.slCodeName[i]); if iTmp < 0 then cb_Gubun.Properties.Items.Add(frm_PBX.FSYSMente.slCodeName[i]); sTmp := frm_PBX.FSYSMente.slCodeName[i]; end; end; cb_Gubun.ItemIndex := -1; cb_Gubun.Tag := 98; cb_Name.Clear; cb_Use.ItemIndex := 0; end; procedure Tfrm_PBX05.proc_ResultMsg(AData, AResult: string); begin if (AResult = '00') or (AResult = '90') then begin GMessagebox('수정되었습니다.', CDMSI); frm_PBX.btn_8.click; btnCancel.click; end else begin GMessagebox(Format('수정 중 오류발생'#13#10'[에러코드]%s', [ AResult]), CDMSI); end; end; end.
Unit GrowView; Interface Uses Objects, App, Views, Dialogs, Drivers, Crt, convert; Type PGrowView = ^TGrowView ; TGrowView = Object( TView ) Constructor Init( Var R : TRect ; Atotal : Longint ) ; Procedure Draw ; Virtual ; Function GetPalette : PPalette ; Virtual ; Procedure Update( Newvalue : Longint ) ; Function Percent( Xvalue,xtotal:longint):integer; Private Total : Longint ; Value : Longint ; Numblock : Integer ; Function Calcblock : Integer ; End; Const CGrowView = #6#9; {This Palette Maps Into The TDialog Palette And Produces A Black 'Background' Bar With Yellow Blocks.} Implementation Constructor TGrowView.init( Var R : TRect ; Atotal : Longint ) ; Begin Inherited Init( R ) ; Total := Atotal ; { Remember The 100% Value } Value := 0 ; { Current Value Is 0 } Numblock := 0 ; { No Colored Blocks So Far } End ; { Calculate The Number Of Colored Blocks For The Current 'Value' } Function TGrowView.Calcblock : Integer ; Begin Calcblock := Value * Size.x div Total ; End ; Function TGrowView.percent; Begin Percent:= xvalue * 100 div xtotal ; End ; Procedure TGrowView.Draw ; Var R : TRect ; B : TDrawbuffer ; Begin Movechar( B, 'þ', Getcolor( 1 ), Size.x ) ; Movechar( B, #0 , Getcolor( 2 ), Numblock ) ; Writeline( 0, 0, Size.x, Size.y, B ) ; End ; Function TGrowView.GetPalette: PPalette ; Const P : String[ Length(cGrowView) ] = CGrowView ; Begin GetPalette := Addr(p); End ; { This Object Was Originally Written In My Graphical Turbo Vision Variant. In This Graphical World, Drawing Is Very Expensive (In Terms Of Execution Time) Compared To Calculating. I Therefor Try To Avoid To ReDraw The Progress Bar If It Is Not Necessary. The Optimisations In The Graphical Variant Are More Complicated Then What I Left In Here. } Procedure TGrowView.Update( Newvalue : Longint ); Var Newblock : Integer ; Begin { An Update Request : Did My Situation Change ? } If (NewValue <> Value) Then Begin { Yes It Did, Remember The New Situation } Value := Newvalue ; { Calculate The New Number Of Colored Blocks } Newblock := Calcblock ; { If This Number Didn't Change We Don't Need To ReDraw } If (Newblock <> Numblock) Then Begin { Pitty, We Do Need The ReDraw. } Numblock := Newblock ; Draw ; End ; 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) @abstract(Website : http://www.ormbr.com.br) @abstract(Telagram : https://t.me/ormbr) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit dbcbr.mapping.popular; interface uses DB, Classes, Rtti, TypInfo, SysUtils, StrUtils, Generics.Collections, dbcbr.mapping.attributes, dbcbr.mapping.classes, dbcbr.rtti.helper, dbcbr.types.mapping; type TMappingPopular = class public function PopularTable(ARttiType: TRttiType): TTableMapping; function PopularView(ARttiType: TRttiType): TViewMapping; function PopularOrderBy(ARttiType: TRttiType): TOrderByMapping; function PopularSequence(ARttiType: TRttiType): TSequenceMapping; function PopularPrimaryKey(ARttiType: TRttiType): TPrimaryKeyMapping; function PopularNotServerUse(ARttiType: TRttiType): Boolean; // function PopularForeignKey(ARttiType: TRttiType): TForeignKeyMappingList; function PopularIndexe(ARttiType: TRttiType): TIndexeMappingList; function PopularCheck(ARttiType: TRttiType): TCheckMappingList; function PopularColumn(ARttiType: TRttiType; AClass: TClass): TColumnMappingList; function PopularCalcField(ARttiType: TRttiType): TCalcFieldMappingList; function PopularAssociation(ARttiType: TRttiType): TAssociationMappingList; function PopularJoinColumn(ARttiType: TRttiType): TJoinColumnMappingList; function PopularTrigger(ARttiType: TRttiType): TTriggerMappingList; function PopularFieldEvents(ARttiType: TRttiType): TFieldEventsMappingList; function PopularEnumeration(ARttiType: TRttiType): TEnumerationMappingList; function PopularPrimaryKeyColumns(ARttiType: TRttiType; AClass: TClass): TPrimaryKeyColumnsMapping; function PopularLazy(ARttiType: TRttiType; var AFieldName: String): TLazyMapping; end; implementation uses dbcbr.mapping.explorer; { TMappingPopular } function TMappingPopular.PopularCalcField(ARttiType: TRttiType): TCalcFieldMappingList; var LProperty: TRttiProperty; LAttrib: TCustomAttribute; begin Result := nil; for LProperty in ARttiType.GetProperties do begin for LAttrib in LProperty.GetAttributes do begin if not (LAttrib is CalcField) then // CalcField Continue; if Result = nil then Result := TCalcFieldMappingList.Create; Result.Add(TCalcFieldMapping.Create); Result.Last.FieldName := CalcField(LAttrib).FieldName; Result.Last.FieldType := CalcField(LAttrib).FieldType; Result.Last.Size := CalcField(LAttrib).Size; Result.Last.CalcProperty := LProperty; Result.Last.CalcDictionary := LProperty.GetDictionary; end; end; end; function TMappingPopular.PopularCheck(ARttiType: TRttiType): TCheckMappingList; var LAttrib: TCustomAttribute; begin Result := nil; for LAttrib in ARttiType.GetAttributes do begin if not (LAttrib is Check) then // Check Continue; if Result = nil then Result := TCheckMappingList.Create; Result.Add(TCheckMapping.Create(Check(LAttrib).Name, Check(LAttrib).Condition, Check(LAttrib).Description)); end; end; function TMappingPopular.PopularColumn(ARttiType: TRttiType; AClass: TClass): TColumnMappingList; var LProperty: TRttiProperty; LAttrib: TCustomAttribute; LColumn: Column; begin Result := nil; for LProperty in ARttiType.GetProperties do begin for LAttrib in LProperty.GetAttributes do begin if not (LAttrib is Column) then // Column Continue; LColumn := Column(LAttrib); if Result = nil then Result := TColumnMappingList.Create; Result.Add(TColumnMapping.Create); Result.Last.ColumnName := LColumn.ColumnName; Result.Last.FieldType := LColumn.FieldType; Result.Last.Scale := LColumn.Scale; Result.Last.Size := LColumn.Size; Result.Last.Precision := LColumn.Precision; Result.Last.ColumnProperty := LProperty; Result.Last.FieldIndex := Result.Count -1; Result.Last.IsJoinColumn := LProperty.IsJoinColumn; Result.Last.IsNotNull := LProperty.IsNotNull; Result.Last.IsUnique := LProperty.IsUnique; Result.Last.IsNoUpdate := LProperty.IsNoUpdate; Result.Last.IsNoInsert := LProperty.IsNoInsert; Result.Last.IsCheck := LProperty.IsCheck; Result.Last.IsNoValidate := LProperty.IsNoValidate; Result.Last.IsHidden := LProperty.IsHidden; Result.Last.IsPrimaryKey := LProperty.IsPrimaryKey(AClass); Result.Last.IsNullable := LProperty.IsNullable; Result.Last.IsLazy := LProperty.IsLazy; Result.Last.IsVirtualData := LProperty.IsVirtualData; Result.Last.DefaultValue := ''; Result.Last.ColumnDictionary := LProperty.GetDictionary; if Result.Last.ColumnDictionary <> nil then Result.Last.DefaultValue := Result.Last.ColumnDictionary.DefaultExpression end; end; end; function TMappingPopular.PopularEnumeration(ARttiType: TRttiType): TEnumerationMappingList; var LProperty: TRttiProperty; LAttrib: TCustomAttribute; begin Result := nil; for LProperty in ARttiType.GetProperties do begin for LAttrib in LProperty.GetAttributes do begin if not (LAttrib is Enumeration) then // Enumeration Continue; if Result = nil then Result := TEnumerationMappingList.Create; Result.Add(TEnumerationMapping.Create(LProperty.PropertyType.AsOrdinal, Enumeration(LAttrib).EnumType, Enumeration(LAttrib).EnumValues)); end; end; end; function TMappingPopular.PopularFieldEvents(ARttiType: TRttiType): TFieldEventsMappingList; var LProperty: TRttiProperty; LAttrib: TCustomAttribute; begin Result := nil; for LProperty in ARttiType.GetProperties do begin for LAttrib in LProperty.GetAttributes do begin if not (LAttrib is FieldEvents) then // FieldEvents Continue; if Result = nil then Result := TFieldEventsMappingList.Create; Result.Add(TFieldEventsMapping.Create(Column(LProperty.GetColumn).ColumnName, FieldEvents(LAttrib).Events)); end; end; end; function TMappingPopular.PopularForeignKey(ARttiType: TRttiType): TForeignKeyMappingList; var LProperty: TRttiProperty; LAttrib: TCustomAttribute; begin Result := nil; /// Atributos da classe for LAttrib in ARttiType.GetAttributes do begin if not (LAttrib is ForeignKey) then // ForeignKey Continue; if Result = nil then Result := TForeignKeyMappingList.Create; Result.Add(TForeignKeyMapping.Create(ForeignKey(LAttrib).Name, ForeignKey(LAttrib).TableNameRef, ForeignKey(LAttrib).FromColumns, ForeignKey(LAttrib).ToColumns, ForeignKey(LAttrib).RuleDelete, ForeignKey(LAttrib).RuleUpdate, ForeignKey(LAttrib).Description)); end; /// Atributos das propriedades for LProperty in ARttiType.GetProperties do begin for LAttrib in LProperty.GetAttributes do begin if not (LAttrib is ForeignKey) then // ForeignKey Continue; if Result = nil then Result := TForeignKeyMappingList.Create; Result.Add(TForeignKeyMapping.Create(ForeignKey(LAttrib).Name, ForeignKey(LAttrib).TableNameRef, ForeignKey(LAttrib).FromColumns, ForeignKey(LAttrib).ToColumns, ForeignKey(LAttrib).RuleDelete, ForeignKey(LAttrib).RuleUpdate, ForeignKey(LAttrib).Description)); end; end; end; function TMappingPopular.PopularIndexe(ARttiType: TRttiType): TIndexeMappingList; var LAttrib: TCustomAttribute; begin Result := nil; for LAttrib in ARttiType.GetAttributes do begin if not (LAttrib is Indexe) then // Indexe Continue; if Result = nil then Result := TIndexeMappingList.Create; Result.Add(TIndexeMapping.Create(Indexe(LAttrib).Name, Indexe(LAttrib).Columns, Indexe(LAttrib).SortingOrder, Indexe(LAttrib).Unique, Indexe(LAttrib).Description)); end; end; function TMappingPopular.PopularJoinColumn(ARttiType: TRttiType): TJoinColumnMappingList; var LProperty: TRttiProperty; LAttrib: TCustomAttribute; begin Result := nil; for LProperty in ARttiType.GetProperties do begin for LAttrib in LProperty.GetAttributes do begin if not (LAttrib is JoinColumn) then // JoinColumn Continue; if Length(JoinColumn(LAttrib).RefTableName) = 0 then Continue; if Result = nil then Result := TJoinColumnMappingList.Create; Result.Add(TJoinColumnMapping.Create(JoinColumn(LAttrib).ColumnName, JoinColumn(LAttrib).RefTableName, JoinColumn(LAttrib).RefColumnName, JoinColumn(LAttrib).RefColumnNameSelect, JoinColumn(LAttrib).Join, JoinColumn(LAttrib).AliasColumn, JoinColumn(LAttrib).AliasRefTable)); end; end; end; function TMappingPopular.PopularLazy(ARttiType: TRttiType; var AFieldName: String): TLazyMapping; var LField: TRttiField; begin Result := nil; for LField in ARttiType.GetFields do begin if not LField.IsLazy then Continue; AFieldName := LField.FieldType.Handle.NameFld.ToString; Result := TLazyMapping.Create(LField); end; end; function TMappingPopular.PopularNotServerUse(ARttiType: TRttiType): Boolean; var LAttrib: TCustomAttribute; begin Result := False; for LAttrib in ARttiType.GetAttributes do begin if not (LAttrib is NotServerUse) then // NotServerUse Continue; Result := True; Break; end; end; function TMappingPopular.PopularOrderBy(ARttiType: TRttiType): TOrderByMapping; var LAttrib: TCustomAttribute; begin Result := nil; for LAttrib in ARttiType.GetAttributes do begin if not (LAttrib is OrderBy) then // OrderBy Continue; Result := TOrderByMapping.Create; Result.ColumnsName := OrderBy(LAttrib).ColumnsName; Break; end; end; function TMappingPopular.PopularPrimaryKey( ARttiType: TRttiType): TPrimaryKeyMapping; var LAttrib: TCustomAttribute; begin Result := nil; for LAttrib in ARttiType.GetAttributes do begin if not (LAttrib is PrimaryKey) then // PrimaryKey Continue; Result := TPrimaryKeyMapping.Create(PrimaryKey(LAttrib).Columns, PrimaryKey(LAttrib).SequenceType = AutoInc, PrimaryKey(LAttrib).SequenceType = TableInc, PrimaryKey(LAttrib).SequenceType = GuidInc, PrimaryKey(LAttrib).SortingOrder, PrimaryKey(LAttrib).Unique, PrimaryKey(LAttrib).Description); Break; end; end; function TMappingPopular.PopularPrimaryKeyColumns( ARttiType: TRttiType; AClass: TClass): TPrimaryKeyColumnsMapping; var LColumns: TColumnMappingList; LColumn: TColumnMapping; begin LColumns := TMappingExplorer.GetMappingColumn(AClass); if LColumns = nil then Exit(nil); Result := TPrimaryKeyColumnsMapping.Create; for LColumn in LColumns do begin if not LColumn.IsPrimaryKey then Continue; Result.Columns.Add(LColumn); end; end; function TMappingPopular.PopularSequence(ARttiType: TRttiType): TSequenceMapping; var LAttrib: TCustomAttribute; LTable: Table; begin Result := nil; LTable := nil; for LAttrib in ARttiType.GetAttributes do begin if LAttrib is Table then // Table LTable := Table(LAttrib); if not (LAttrib is Sequence) then // Sequence Continue; Result := TSequenceMapping.Create; Result.Name := Sequence(LAttrib).Name; Result.Initial := Sequence(LAttrib).Initial; Result.Increment := Sequence(LAttrib).Increment; Break; end; if (Result <> nil) and (LTable <> nil) then Result.TableName := LTable.Name; end; function TMappingPopular.PopularAssociation(ARttiType: TRttiType): TAssociationMappingList; var LRttiType: TRttiType; LProperty: TRttiProperty; LAssociation: TCustomAttribute; LColumns: TArray<string>; begin Result := nil; for LProperty in ARttiType.GetProperties do begin for LAssociation in LProperty.GetAttributes do begin SetLength(LColumns, 0); if not (LAssociation is Association) then // Association Continue; if Length(Association(LAssociation).ColumnsNameRef) = 0 then Continue; if Result = nil then Result := TAssociationMappingList.Create; LRttiType := LProperty.PropertyType; LRttiType := LProperty.GetTypeValue(LRttiType); if LRttiType <> nil then Result.Add(TAssociationMapping.Create(Association(LAssociation).Multiplicity, Association(LAssociation).ColumnsName, Association(LAssociation).ColumnsNameRef, LRttiType.AsInstance.MetaclassType.ClassName, LProperty, Association(LAssociation).Lazy, LProperty.GetCascadeActions)) else Result.Add(TAssociationMapping.Create(Association(LAssociation).Multiplicity, Association(LAssociation).ColumnsName, Association(LAssociation).ColumnsNameRef, LProperty.PropertyType.Name, LProperty, Association(LAssociation).Lazy, LProperty.GetCascadeActions)); end; end; end; function TMappingPopular.PopularTable(ARttiType: TRttiType): TTableMapping; var LAttrib: TCustomAttribute; begin Result := nil; for LAttrib in ARttiType.GetAttributes do begin if not ((LAttrib is Table) or (LAttrib is View)) then // Table Continue; Result := TTableMapping.Create; Result.Name := Table(LAttrib).Name; Result.Description := Table(LAttrib).Description; Result.Schema := ''; Break; end; end; function TMappingPopular.PopularTrigger(ARttiType: TRttiType): TTriggerMappingList; var LAttrib: TCustomAttribute; begin Result := nil; for LAttrib in ARttiType.GetAttributes do begin if not (LAttrib is Trigger) then // Trigger Continue; if Result = nil then Result := TTriggerMappingList.Create; Result.Add(TTriggerMapping.Create(Trigger(LAttrib).Name, '')); end; end; function TMappingPopular.PopularView(ARttiType: TRttiType): TViewMapping; var LAttrib: TCustomAttribute; begin Result := nil; for LAttrib in ARttiType.GetAttributes do begin if not (LAttrib is View) then // View Continue; Result := TViewMapping.Create; Result.Name := View(LAttrib).Name; Result.Description := View(LAttrib).Description; Result.Script := ''; Break; end; end; end.
unit BlocksUnit; interface uses System.Classes, System.Contnrs, Generics.Collections, SeSHA256; type TCrypto = (tcBitcoin); TNet = (tnMainNet, tnTestNet); TBlockChainFiles = class; TBlockFile = class(TObject) parent: TBlockChainFiles; aFileName: string; aBlockNumber: integer; afs: TBufferedFileStream; end; TBlockChainFiles = class(TList<TBlockFile>) end; TBlockHeader = record versionNumber: UInt32; aPreviousBlockHash: T32; // reverse please aMerkleRoot: T32; // reverse please time: UInt32; // UnixTime DifficultyTarget: UInt32; nonce: UInt32; end; TInput = class(TObject) aTXID: T32; aVOUT: UInt32; CoinBaseLength: uint64; CoinBase: PByte; destructor Destroy; override; end; TOutput = class(TObject) nValue: uint64; OutputScriptLength: uint64; OutputScript: PByte; destructor Destroy; override; end; TInputs = class(TObjectList) private function GetInput(index: integer): TInput; public function NewInput: TInput; property items[index: integer]: TInput read GetInput; default; end; TOutputs = class(TObjectList) private function GetOutput(index: integer): TOutput; public function NewOutput: TOutput; property items[index: integer]: TOutput read GetOutput; default; end; TTransaction = class(TObject) version: UInt32; inputs: TInputs; outputs: TOutputs; public constructor Create; destructor Destroy; override; end; TBlockTransactions = class(TObjectList) private function GetTransaction(index: integer): TTransaction; public function NewTransaction: TTransaction; property items[index: integer]: TTransaction read GetTransaction; default; end; TBlockRecord = class(TObject) nblock: uint64; blocktype: TCrypto; network: TNet; headerLenght: UInt32; hash: string; header: TBlockHeader; transactions: TBlockTransactions; ninputs, noutputs: uint64; public constructor Create; destructor Destroy; override; end; TStartFileBlockFoundNotify = procedure(const aBlockFiles: TList<String>) of object; TFoundFileBlockNotify = procedure(const aBlockFile: TBlockFile; var next: boolean) of object; TEndFilesBlockFoundNotify = procedure(const aBlockFiles: tstringlist) of object; TFoundBlockNotify = procedure(const aBlock: TBlockRecord; var findnext: boolean) of object; TBlockProcessStepNotify = procedure(const aPos, asize: int64) of object; TBlocks = class(tthread) private // File block events fOnStartProcessFiles: TStartFileBlockFoundNotify; fOnAfterFileBlockProcessed: TFoundFileBlockNotify; fOnMagicBlockFound: TFoundBlockNotify; fBlockProcessStep: TBlockProcessStepNotify; // fEndProcessBlockFile: TEndProcessBlockFile; fOnEndProc: TNotifyEvent; fOnStartProc: TNotifyEvent; fOnBeforeFileBlockProcess: TFoundFileBlockNotify; procedure InternalProcessBlock(const aBlockFile: TBlockFile); public aBlockChainFiles: TBlockChainFiles; BlocksDir: string; aBlocksDirectory: string; procedure Execute; override; // Inicio y fin del parseo property OnStartingParsingBlockfiles: TNotifyEvent read fOnStartProc write fOnStartProc; property OnFinishedParsingBlockFiles: TNotifyEvent read fOnEndProc write fOnEndProc; // Start process all files property OnStartProcessFiles: TStartFileBlockFoundNotify read fOnStartProcessFiles write fOnStartProcessFiles; // before process a file property OnBeforeFileBlockProcess: TFoundFileBlockNotify read fOnBeforeFileBlockProcess write fOnBeforeFileBlockProcess; // after a processed file property OnAfterFileBlockProcessed: TFoundFileBlockNotify read fOnAfterFileBlockProcessed write fOnAfterFileBlockProcessed; // Block found property OnMagicBlockFound: TFoundBlockNotify read fOnMagicBlockFound write fOnMagicBlockFound; property OnBlockProcessStep: TBlockProcessStepNotify read fBlockProcessStep write fBlockProcessStep; end; implementation uses WinApi.Windows, SysUtils, dialogs, dateutils, MainFormUnit, System.hash, inifiles; procedure TBlocks.Execute; var searchResult: TSearchRec; aBlockFile: TBlockFile; aBlockFiles: TList<string>; aBlockFil: string; next: boolean; files: string; begin aBlockChainFiles := TBlockChainFiles.Create; // Start parsing component if Assigned(OnStartingParsingBlockfiles) then Synchronize( procedure begin OnStartingParsingBlockfiles(self); end); SetCurrentDir(aBlocksDirectory); files := 'blk?????.dat'; // files := 'blk00074.dat'; if findfirst(files, faAnyFile, searchResult) = 0 then begin aBlockFiles := TList<String>.Create; repeat aBlockFiles.Add(aBlocksDirectory + '\' + searchResult.Name); until findnext(searchResult) <> 0; // Must free up resources used by these successful finds System.SysUtils.FindClose(searchResult); // Start parsing all files if Assigned(OnStartProcessFiles) then Synchronize( procedure begin OnStartProcessFiles(aBlockFiles); end); for aBlockFil in aBlockFiles do begin aBlockFile := TBlockFile.Create; aBlockFile.parent := aBlockChainFiles; aBlockChainFiles.Add(aBlockFile); aBlockFile.aFileName := aBlockFil; aBlockFile.aBlockNumber := aBlockFiles.IndexOf(aBlockFil) + 1; // Start parsing a file if Assigned(fOnBeforeFileBlockProcess) then Synchronize( procedure begin fOnBeforeFileBlockProcess(aBlockFile, next); end); aBlockFile.afs := TBufferedFileStream.Create(aBlockFile.aFileName, fmOpenRead); try InternalProcessBlock(aBlockFile); finally aBlockFile.afs.Free; end; if Assigned(OnAfterFileBlockProcessed) then Synchronize( procedure begin OnAfterFileBlockProcessed(aBlockFile, next); end); aBlockFile.Free; if next = false then break; end; aBlockFiles.Free; end; if Assigned(OnFinishedParsingBlockFiles) then Synchronize( procedure begin OnFinishedParsingBlockFiles(self); end); end; procedure TBlocks.InternalProcessBlock(const aBlockFile: TBlockFile); var state, car: byte; aBlock: TBlockRecord; cont: boolean; aTransaction: TTransaction; aseq: longword; aInput: TInput; aOutput: TOutput; tb: THeader; var alocktime: UInt32; txCount, k: uint64; function ReadVarValue: uint64; var atxCount: UInt8; atxCount2: UInt16; atxCount4: UInt32; begin aBlockFile.afs.Read(atxCount, 1); if atxCount < $FD then result := atxCount else case atxCount of $FD: begin aBlockFile.afs.Read(atxCount2, 2); result := atxCount2; end; $FE: begin aBlockFile.afs.Read(atxCount4, 4); result := atxCount4; end; $FF: aBlockFile.afs.Read(result, 8); end; end; begin state := 0; cont := true; while (cont = true) and (aBlockFile.afs.Read(car, 1) = 1) do begin case state of 0: if car = $F9 then inc(state); 1: if car = $BE then inc(state) else state := 0; 2: if car = $B4 then inc(state) else state := 0; 3: if car = $D9 then begin if Assigned(OnBlockProcessStep) then Synchronize( procedure begin OnBlockProcessStep(aBlockFile.afs.Position, aBlockFile.afs.Size); end); aBlock := TBlockRecord.Create; aBlockFile.afs.Read(aBlock.headerLenght, 4); // Read the header fields aBlockFile.afs.Read(aBlock.header, HEADERSIZE); // Re-read the header to calculate hash aBlockFile.afs.Seek(-HEADERSIZE, soCurrent); aBlockFile.afs.Read(tb, HEADERSIZE); // double header hash aBlock.hash := reversehash(SHA256ToStr(CalcSHA256(SHA256ToBinaryStr(CalcHeaderSHA256(tb))))); // tx count txCount := ReadVarValue; while (txCount > 0) do begin aTransaction := aBlock.transactions.NewTransaction; // Read the transaction version aBlockFile.afs.Read(aTransaction.version, 4); // Read the inputs aBlock.ninputs := ReadVarValue; if aBlock.ninputs > 0 then for k := 0 to aBlock.ninputs - 1 do begin aInput := aTransaction.inputs.NewInput; aBlockFile.afs.Read(aInput.aTXID, 32); aBlockFile.afs.Read(aInput.aVOUT, 4); aInput.CoinBaseLength := ReadVarValue; GetMem(aInput.CoinBase, aInput.CoinBaseLength); aBlockFile.afs.Read(aInput.CoinBase^, aInput.CoinBaseLength); // No need store the seq aBlockFile.afs.Read(aseq, 4); end; // tx out count aBlock.noutputs := ReadVarValue; if aBlock.noutputs > 0 then for k := 0 to aBlock.noutputs - 1 do begin aOutput := aTransaction.outputs.NewOutput; aBlockFile.afs.Read(aOutput.nValue, 8); // in satoshis aOutput.OutputScriptLength := ReadVarValue; GetMem(aOutput.OutputScript, aOutput.OutputScriptLength); aBlockFile.afs.Read(aOutput.OutputScript^, aOutput.OutputScriptLength); end; aBlockFile.afs.Read(alocktime, 4); dec(txCount); end; // Fire the block found event if Assigned(OnMagicBlockFound) then Synchronize( procedure begin OnMagicBlockFound(aBlock, cont); end); // Free the block so user must copy or use it and forget aBlock.Free; state := 0; end; end; end; end; { TBlockRecord } constructor TBlockRecord.Create; begin transactions := TBlockTransactions.Create; end; destructor TBlockRecord.Destroy; begin transactions.Free; inherited; end; { TBlockTransactions } function TBlockTransactions.GetTransaction(index: integer): TTransaction; begin result := inherited items[index] as TTransaction; end; function TBlockTransactions.NewTransaction: TTransaction; begin result := TTransaction.Create; self.Add(result); end; { TTransaction } constructor TTransaction.Create; begin inputs := TInputs.Create; outputs := TOutputs.Create; end; destructor TTransaction.Destroy; begin inputs.Free; outputs.Free; end; { TOutputs } function TOutputs.GetOutput(index: integer): TOutput; begin result := TOutput(inherited items[index]); end; function TOutputs.NewOutput: TOutput; begin result := TOutput.Create; self.Add(result); end; { TInputs } function TInputs.GetInput(index: integer): TInput; begin result := TInput(inherited items[index]); end; function TInputs.NewInput: TInput; begin result := TInput.Create; self.Add(result); end; destructor TInput.Destroy; begin FreeMem(CoinBase); inherited; end; destructor TOutput.Destroy; begin FreeMem(OutputScript); inherited; end; end.
unit HtmlTags; interface uses Classes, DomCore; { Provides a singleton database of known HTML tag, and information about them. The list of known HTML tags are provided through the global function: function HtmlTagList: THtmlTagList; And known list of URL schemes through: function URLSchemes: TURLSchemes; Version history --------------- 12/21/2021 - Changed from global variables to singleton functions. - URLSchemes now, like HtmlTagList, populates itself during its constructor. - Searching for tag names in HtmlTagList is now case insensitive } type TTagID = type Integer; const UNKNOWN_TAG = 0; A_TAG = 1; ABBR_TAG = 2; ACRONYM_TAG = 3; ADDRESS_TAG = 4; APPLET_TAG = 5; AREA_TAG = 6; B_TAG = 7; BASE_TAG = 8; BASEFONT_TAG = 9; BDO_TAG = 10; BIG_TAG = 11; BLOCKQUOTE_TAG = 12; BODY_TAG = 13; BR_TAG = 14; BUTTON_TAG = 15; CAPTION_TAG = 16; CENTER_TAG = 17; CITE_TAG = 18; CODE_TAG = 19; COL_TAG = 20; COLGROUP_TAG = 21; DD_TAG = 22; DEL_TAG = 23; DFN_TAG = 24; DIR_TAG = 25; DIV_TAG = 26; DL_TAG = 27; DT_TAG = 28; EM_TAG = 29; FIELDSET_TAG = 30; FONT_TAG = 31; FORM_TAG = 32; FRAME_TAG = 33; FRAMESET_TAG = 34; H1_TAG = 35; H2_TAG = 36; H3_TAG = 37; H4_TAG = 38; H5_TAG = 39; H6_TAG = 40; HEAD_TAG = 41; HR_TAG = 42; HTML_TAG = 43; I_TAG = 44; IFRAME_TAG = 45; IMG_TAG = 46; INPUT_TAG = 47; INS_TAG = 48; ISINDEX_TAG = 49; KBD_TAG = 50; LABEL_TAG = 51; LEGEND_TAG = 52; LI_TAG = 53; LINK_TAG = 54; MAP_TAG = 55; MENU_TAG = 56; META_TAG = 57; NOFRAMES_TAG = 58; NOSCRIPT_TAG = 59; OBJECT_TAG = 60; OL_TAG = 61; OPTGROUP_TAG = 62; OPTION_TAG = 63; P_TAG = 64; PARAM_TAG = 65; PRE_TAG = 66; Q_TAG = 67; S_TAG = 68; SAMP_TAG = 69; SCRIPT_TAG = 70; SELECT_TAG = 71; SMALL_TAG = 72; SPAN_TAG = 73; STRIKE_TAG = 74; STRONG_TAG = 75; STYLE_TAG = 76; SUB_TAG = 77; SUP_TAG = 78; TABLE_TAG = 79; TBODY_TAG = 80; TD_TAG = 81; TEXTAREA_TAG = 82; TFOOT_TAG = 83; TH_TAG = 84; THEAD_TAG = 85; TITLE_TAG = 86; TR_TAG = 87; TT_TAG = 88; U_TAG = 89; UL_TAG = 90; VAR_TAG = 91; TEMPLATE_TAG = 92; BlockTags = [ADDRESS_TAG, BLOCKQUOTE_TAG, CENTER_TAG, DIV_TAG, DL_TAG, FIELDSET_TAG, {FORM_TAG,} H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HR_TAG, NOSCRIPT_TAG, OL_TAG, PRE_TAG, TABLE_TAG, UL_TAG]; BlockParentTags = [ADDRESS_TAG, BLOCKQUOTE_TAG, CENTER_TAG, DIV_TAG, DL_TAG, FIELDSET_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HR_TAG, LI_TAG, NOSCRIPT_TAG, OL_TAG, PRE_TAG, TD_TAG, TH_TAG, UL_TAG]; HeadTags = [BASE_TAG, LINK_TAG, META_TAG, SCRIPT_TAG, STYLE_TAG, TITLE_TAG]; {Elements forbidden from having an end tag, and therefore are empty; from HTML 4.01 spec} EmptyTags = [AREA_TAG, BASE_TAG, BASEFONT_TAG, BR_TAG, COL_TAG, FRAME_TAG, HR_TAG, IMG_TAG, INPUT_TAG, ISINDEX_TAG, LINK_TAG, META_TAG, PARAM_TAG]; PreserveWhiteSpaceTags = [PRE_TAG]; NeedFindParentTags = [COL_TAG, COLGROUP_TAG, DD_TAG, DT_TAG, LI_TAG, OPTION_TAG, P_TAG, TABLE_TAG, TBODY_TAG, TD_TAG, TFOOT_TAG, TH_TAG, THEAD_TAG, TR_TAG]; ListItemParentTags = [DIR_TAG, MENU_TAG, OL_TAG, UL_TAG]; DefItemParentTags = [DL_TAG]; //<dl name="Description list"><dt name="Description term">word</dt><dd name="Decription details">definition</dd></dl> TableSectionParentTags = [TABLE_TAG]; ColParentTags = [COLGROUP_TAG]; RowParentTags = [TABLE_TAG, TBODY_TAG, TFOOT_TAG, THEAD_TAG]; CellParentTags = [TR_TAG]; OptionParentTags = [OPTGROUP_TAG, SELECT_TAG]; const MAX_TAGS_COUNT = 128; MAX_FLAGS_COUNT = 32; type THtmlTagSet = set of 0..MAX_TAGS_COUNT - 1; THtmlTagFlags = set of 0..MAX_FLAGS_COUNT - 1; THtmlTag = class private FName: TDomString; FNumber: TTagID; FParserFlags: THtmlTagFlags; FFormatterFlags: THtmlTagFlags; public constructor Create(const AName: TDomString; ANumber: Integer; AParserFlags, AFormatterFlags: THtmlTagFlags); property Name: TDomString read FName; property Number: TTagID read FNumber; property ParserFlags: THtmlTagFlags read FParserFlags; property FormatterFlags: THtmlTagFlags read FFormatterFlags; end; TCompareTag = function(Tag: THtmlTag): Integer of object; THtmlTagList = class private FList: TList; FUnknownTag: THtmlTag; FSearchName: TDomString; FSearchNumber: Integer; function CompareName(Tag: THtmlTag): Integer; function CompareNumber(Tag: THtmlTag): Integer; function GetTag(Compare: TCompareTag): THtmlTag; procedure InitializeTagList(AList: TList); public constructor Create; destructor Destroy; override; function GetTagByName(const Name: TDomString): THtmlTag; function GetTagID(const Name: UnicodeString): TTagID; function GetTagByNumber(Number: Integer): THtmlTag; end; TURLSchemes = class(TStringList) private FMaxLen: Integer; public constructor Create; function Add(const S: String): Integer; override; function IsURL(const S: String): Boolean; function GetScheme(const S: String): String; property MaxLen: Integer read FMaxLen; end; //Global singleton lists of HTML tags and URL schemes function HtmlTagList: THtmlTagList; function URLSchemes: TURLSchemes; implementation uses SysUtils; constructor THtmlTag.Create(const AName: TDomString; ANumber: Integer; AParserFlags, AFormatterFlags: THtmlTagFlags); begin inherited Create; FName := AName; FNumber := ANumber end; constructor THtmlTagList.Create; begin inherited Create; { HTML tag names in HTML are returned as canonical UPPERCASE. https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-104682815 > The HTML DOM returns the tagName of an HTML element in the canonical uppercase form, > regardless of the case in the source HTML document. } FList := TList.Create; InitializeTagList(FList); FUnknownTag := THtmlTag.Create('', UNKNOWN_TAG, [], []) end; procedure THtmlTagList.InitializeTagList(AList: TList); begin AList.Capacity := MAX_TAGS_COUNT; AList.Add(THtmlTag.Create('a', A_TAG, [], [])); AList.Add(THtmlTag.Create('abbr', ABBR_TAG, [], [])); AList.Add(THtmlTag.Create('acronym', ACRONYM_TAG, [], [])); //16.2. Non-conforming. Use ABBR instead. AList.Add(THtmlTag.Create('address', ADDRESS_TAG, [], [])); AList.Add(THtmlTag.Create('applet', APPLET_TAG, [], [])); //16.2. Non-confirming. Use EMBED or OBJECT instead. HTMLUnknownElement AList.Add(THtmlTag.Create('area', AREA_TAG, [], [])); AList.Add(THtmlTag.Create('b', B_TAG, [], [])); AList.Add(THtmlTag.Create('base', BASE_TAG, [], [])); AList.Add(THtmlTag.Create('basefont', BASEFONT_TAG, [], [])); AList.Add(THtmlTag.Create('bdo', BDO_TAG, [], [])); AList.Add(THtmlTag.Create('big', BIG_TAG, [], [])); AList.Add(THtmlTag.Create('blockquote', BLOCKQUOTE_TAG, [], [])); AList.Add(THtmlTag.Create('body', BODY_TAG, [], [])); AList.Add(THtmlTag.Create('br', BR_TAG, [], [])); AList.Add(THtmlTag.Create('button', BUTTON_TAG, [], [])); AList.Add(THtmlTag.Create('caption', CAPTION_TAG, [], [])); AList.Add(THtmlTag.Create('center', CENTER_TAG, [], [])); AList.Add(THtmlTag.Create('cite', CITE_TAG, [], [])); AList.Add(THtmlTag.Create('code', CODE_TAG, [], [])); AList.Add(THtmlTag.Create('col', COL_TAG, [], [])); AList.Add(THtmlTag.Create('colgroup', COLGROUP_TAG, [], [])); AList.Add(THtmlTag.Create('dd', DD_TAG, [], [])); AList.Add(THtmlTag.Create('del', DEL_TAG, [], [])); AList.Add(THtmlTag.Create('dfn', DFN_TAG, [], [])); AList.Add(THtmlTag.Create('dir', DIR_TAG, [], [])); //16.2. Non-conforming. Use UL instead. AList.Add(THtmlTag.Create('div', DIV_TAG, [], [])); AList.Add(THtmlTag.Create('dl', DL_TAG, [], [])); AList.Add(THtmlTag.Create('dt', DT_TAG, [], [])); AList.Add(THtmlTag.Create('em', EM_TAG, [], [])); AList.Add(THtmlTag.Create('fieldset', FIELDSET_TAG, [], [])); AList.Add(THtmlTag.Create('font', FONT_TAG, [], [])); AList.Add(THtmlTag.Create('form', FORM_TAG, [], [])); AList.Add(THtmlTag.Create('frame', FRAME_TAG, [], [])); //16.3. Non-conforming. Either use IFRAME and CSS instead, or use server-side includes AList.Add(THtmlTag.Create('frameset', FRAMESET_TAG, [], [])); //16.3. Non-conforming. Either use IFRAME and CSS instead, or use server-side includes AList.Add(THtmlTag.Create('h1', H1_TAG, [], [])); AList.Add(THtmlTag.Create('h2', H2_TAG, [], [])); AList.Add(THtmlTag.Create('h3', H3_TAG, [], [])); AList.Add(THtmlTag.Create('h4', H4_TAG, [], [])); AList.Add(THtmlTag.Create('h5', H5_TAG, [], [])); AList.Add(THtmlTag.Create('h6', H6_TAG, [], [])); AList.Add(THtmlTag.Create('head', HEAD_TAG, [], [])); AList.Add(THtmlTag.Create('hr', HR_TAG, [], [])); AList.Add(THtmlTag.Create('html', HTML_TAG, [], [])); AList.Add(THtmlTag.Create('i', I_TAG, [], [])); AList.Add(THtmlTag.Create('iframe', IFRAME_TAG, [], [])); AList.Add(THtmlTag.Create('img', IMG_TAG, [], [])); AList.Add(THtmlTag.Create('input', INPUT_TAG, [], [])); AList.Add(THtmlTag.Create('ins', INS_TAG, [], [])); AList.Add(THtmlTag.Create('isindex', ISINDEX_TAG, [], [])); //16.3. Non-conforming. Use an explicit form and text control combination instead. AList.Add(THtmlTag.Create('kbd', KBD_TAG, [], [])); AList.Add(THtmlTag.Create('label', LABEL_TAG, [], [])); AList.Add(THtmlTag.Create('legend', LEGEND_TAG, [], [])); AList.Add(THtmlTag.Create('li', LI_TAG, [], [])); AList.Add(THtmlTag.Create('link', LINK_TAG, [], [])); AList.Add(THtmlTag.Create('map', MAP_TAG, [], [])); AList.Add(THtmlTag.Create('menu', MENU_TAG, [], [])); AList.Add(THtmlTag.Create('meta', META_TAG, [], [])); AList.Add(THtmlTag.Create('noframes', NOFRAMES_TAG, [], [])); //16.3. Non-conforming. Either use IFRAME and CSS instead, or use server-side includes AList.Add(THtmlTag.Create('noscript', NOSCRIPT_TAG, [], [])); AList.Add(THtmlTag.Create('object', OBJECT_TAG, [], [])); AList.Add(THtmlTag.Create('ol', OL_TAG, [], [])); AList.Add(THtmlTag.Create('optgroup', OPTGROUP_TAG, [], [])); AList.Add(THtmlTag.Create('option', OPTION_TAG, [], [])); AList.Add(THtmlTag.Create('p', P_TAG, [], [])); AList.Add(THtmlTag.Create('param', PARAM_TAG, [], [])); AList.Add(THtmlTag.Create('pre', PRE_TAG, [], [])); AList.Add(THtmlTag.Create('q', Q_TAG, [], [])); AList.Add(THtmlTag.Create('s', S_TAG, [], [])); AList.Add(THtmlTag.Create('samp', SAMP_TAG, [], [])); AList.Add(THtmlTag.Create('script', SCRIPT_TAG, [], [])); AList.Add(THtmlTag.Create('select', SELECT_TAG, [], [])); AList.Add(THtmlTag.Create('small', SMALL_TAG, [], [])); AList.Add(THtmlTag.Create('span', SPAN_TAG, [], [])); AList.Add(THtmlTag.Create('strike', STRIKE_TAG, [], [])); AList.Add(THtmlTag.Create('strong', STRONG_TAG, [], [])); AList.Add(THtmlTag.Create('style', STYLE_TAG, [], [])); AList.Add(THtmlTag.Create('sub', SUB_TAG, [], [])); AList.Add(THtmlTag.Create('sup', SUP_TAG, [], [])); AList.Add(THtmlTag.Create('table', TABLE_TAG, [], [])); AList.Add(THtmlTag.Create('tbody', TBODY_TAG, [], [])); AList.Add(THtmlTag.Create('td', TD_TAG, [], [])); AList.Add(THtmlTag.Create('template', TEMPLATE_TAG, [], [])); AList.Add(THtmlTag.Create('textarea', TEXTAREA_TAG, [], [])); AList.Add(THtmlTag.Create('tfoot', TFOOT_TAG, [], [])); AList.Add(THtmlTag.Create('th', TH_TAG, [], [])); AList.Add(THtmlTag.Create('thead', THEAD_TAG, [], [])); AList.Add(THtmlTag.Create('title', TITLE_TAG, [], [])); AList.Add(THtmlTag.Create('tr', TR_TAG, [], [])); AList.Add(THtmlTag.Create('tt', TT_TAG, [], [])); AList.Add(THtmlTag.Create('u', U_TAG, [], [])); AList.Add(THtmlTag.Create('ul', UL_TAG, [], [])); AList.Add(THtmlTag.Create('var', VAR_TAG, [], [])); end; destructor THtmlTagList.Destroy; var I: Integer; begin for I := FList.Count - 1 downto 0 do THtmlTag(FList[I]).Free; FList.Free; FUnknownTag.Free; inherited Destroy end; function THtmlTagList.GetTag(Compare: TCompareTag): THtmlTag; var I, Low, High, Rel: Integer; begin Low := -1; High := FList.Count - 1; while High - Low > 1 do begin I := (High + Low) div 2; Result := FList[I]; Rel := Compare(Result); if Rel < 0 then High := I else if Rel > 0 then Low := I else Exit end; if High >= 0 then begin Result := FList[High]; if Compare(Result) = 0 then Exit end; Result := nil end; function THtmlTagList.CompareName(Tag: THtmlTag): Integer; begin // Result := CompareStr(FSearchName, Tag.Name) Result := CompareText(FSearchName, Tag.Name); //html is case insensitive end; function THtmlTagList.CompareNumber(Tag: THtmlTag): Integer; begin Result := FSearchNumber - Tag.Number end; function THtmlTagList.GetTagByName(const Name: TDomString): THtmlTag; begin FSearchName := Name; Result := GetTag(CompareName); if Result = nil then Result := FUnknownTag end; function THtmlTagList.GetTagByNumber(Number: Integer): THtmlTag; begin FSearchNumber := Number; Result := GetTag(CompareNumber) end; function THtmlTagList.GetTagID(const Name: UnicodeString): TTagID; begin //returns 0 for unknown tags Result := GetTagByName(Name).Number; end; function TURLSchemes.Add(const S: String): Integer; begin if Length(S) > FMaxLen then FMaxLen := Length(S); Result := inherited Add(S) end; function TURLSchemes.IsURL(const S: String): Boolean; begin Result := IndexOf(LowerCase(S)) >= 0 end; constructor TURLSchemes.Create; begin inherited Create; Self.Add('http'); Self.Add('https'); Self.Add('ftp'); Self.Add('mailto'); Self.Add('news'); Self.Add('nntp'); Self.Add('gopher'); end; function TURLSchemes.GetScheme(const S: String): String; const SchemeChars = [Ord('A')..Ord('Z'), Ord('a')..Ord('z')]; var I: Integer; begin Result := ''; for I := 1 to MaxLen + 1 do begin if I > Length(S) then Exit; if S[I] = ':' then begin if IsURL(Copy(S, 1, I - 1)) then Result := Copy(S, 1, I - 1); Exit end end end; var g_HtmlTagList: THtmlTagList = nil; function HtmlTagList: THtmlTagList; var list: THtmlTagList; begin if g_HtmlTagList = nil then begin list := THtmlTagList.Create; g_HtmlTagList := list; end; Result := g_HtmlTagList; end; var g_URLSchemes: TURLSchemes = nil; function URLSchemes: TURLSchemes; var list: TUrlSchemes; begin if g_URLSchemes = nil then begin list := TURLSchemes.Create; g_URLSchemes := list; end; Result := g_URLSchemes; end; initialization finalization FreeAndNil(g_HtmlTagList); FreeAndNil(g_URLSchemes); end.
unit UStackListWithManagedTypes; interface type { A list that should live on the stack. It can hold a configurable amount of data. The number of bytes of data it can contain is equal to the size of the TSize type parameter. The TSize type parameter has no other purpose. You can use one of the predefined T*Bytes types (where * is the number of bytes), or define your own size type. } TStackList<T; TSize: record> = record private type P = ^T; private FData: TSize; FCapacity: Integer; FCount: Integer; function GetItem(const AIndex: Integer): T; public { Initializes the list. You *must* call this method before using this list. It acts like a constructor. You also *must* call Finalize when you are done with the list. } procedure Initialize; { Finalizes the list. You *must* call this method when you are done with the list. It acts like a destructor and releases any managed items the list may contain. } procedure Finalize; { Clears the list } procedure Clear; { Adds an item to the list. Raises EInvalidOperation if the list is full and the item cannot be added. } procedure Add(const AItem: T); { The number of items in the list. } property Count: Integer read FCount; { The items in the list. Raises EArgumentOutOfRangeException if AIndex is invalid. } property Items[const AIndex: Integer]: T read GetItem; default; end; type { Some predefined types that can be used as the TSize type parameter for the TStackList<T, TSize> type. } T128Bytes = record Data: array [0..127] of Byte end; T256Bytes = record Data: array [0..255] of Byte end; T512Bytes = record Data: array [0..511] of Byte end; T1024Bytes = record Data: array [0..1023] of Byte end; implementation uses System.Classes, System.SysUtils; { TStackList<T, TSize> } procedure TStackList<T, TSize>.Add(const AItem: T); var Target: P; begin if (FCount >= FCapacity) then raise EInvalidOperation.Create('List is full'); Target := @FData; Inc(Target, FCount); Target^ := AItem; Inc(FCount); end; procedure TStackList<T, TSize>.Clear; begin { If T is a managed type, then we need to finalize all items in the list. This will decrease reference counts and free memory where needed. } if IsManagedType(T) then begin FinalizeArray(@FData, TypeInfo(T), FCount); FillChar(FData, FCount * SizeOf(T), 0); end; FCount := 0; end; procedure TStackList<T, TSize>.Finalize; begin Clear; end; function TStackList<T, TSize>.GetItem(const AIndex: Integer): T; var Item: P; begin if (AIndex < 0) or (AIndex >= FCount) then raise EArgumentOutOfRangeException.Create('List index out of range'); Item := @FData; Inc(Item, AIndex); Result := Item^; end; procedure TStackList<T, TSize>.Initialize; begin if IsManagedType(TSize) then raise EInvalidOperation.Create('A stack based collection cannot use a managed type for its TSize parameter'); FCapacity := SizeOf(FData) div SizeOf(T); FCount := 0; { The FData field may contain random data, which causes access violations when T is a managed type. So we need to clear it. Note that IsManagedType is a compiler-magic function. This means that the if-condition is performed at compile time, and the FillChar statement is not compiled at all if T is not a managed type. } if IsManagedType(T) then FillChar(FData, SizeOf(FData), 0); end; end.
unit UClouFileOnlineCheck; interface uses classes, SysUtils, UModelUtil, UFileBaseInfo, UMyUtil, SyncObjs; type // 递归 目录的 过期文件 TFindCloudFileOnlineCheck = class private FullPath : string; CloudPcPath, CloudPcID : string; TempCloudFolderInfo : TTempCloudFolderInfo; public constructor Create( _FullPath : string ); procedure SetCloudPcInfo( _CloudPcPath, _CloudPcID : string ); procedure Update; private procedure FindTempCloudFolderInfo; procedure CheckFileLostConn; procedure CheckFolderLostConn; procedure DeleteTempCloudFolderInfo; protected function CheckNextSearch : Boolean; procedure CloudFileCheck( FileInfo : TTempCloudFileInfo ); end; // 检测处理 TCloudFileOnlineCheckHandle = class public OnlinePcID : string; CloudPcPathList : TStringList; public constructor Create( _OnlinePcID : string ); procedure Update; private procedure FindCloudPcPathList; procedure CheckCloudPcPathList; procedure DeleteCloudPcPathList; end; // 检测线程 TCloudFileOnlineCheckThread = class( TThread ) public constructor Create; destructor Destroy; override; protected procedure Execute; override; private procedure CheckOnliePcHandle( OnlinePcID : string ); end; // 检测 上线 Pc 文件 TMyCloudFileOnlineCheckInfo = class public IsRun : Boolean; public Lock : TCriticalSection; OnlineCheckPcIDList : TStringList; public CloudFileOnlineCheckThread : TCloudFileOnlineCheckThread; public constructor Create; procedure StopCheck; destructor Destroy; override; public procedure AddOnlinePc( PcID : string ); function getCheckPcID : string; end; var MyCloudFileOnlineCheckInfo : TMyCloudFileOnlineCheckInfo; implementation uses UMyBackupInfo, UMyClient, UMyNetPcInfo, UMyCloudPathInfo; { TBackupFileLostConnScan } procedure TFindCloudFileOnlineCheck.CloudFileCheck( FileInfo : TTempCloudFileInfo ); var FilePath, FileStatus : string; FileSize : Int64; FileTime : TDateTime; CloudFileOnlineCheckMsg : TCloudFileOnlineCheckMsg; begin FileSize := FileInfo.FileSize; FileTime := FileInfo.LastWriteTime; FileStatus := FileInfo.FileStatus; FilePath := MyFilePath.getPath( FullPath ) + FileInfo.FileName; // 发送文件 检测 CloudFileOnlineCheckMsg := TCloudFileOnlineCheckMsg.Create; CloudFileOnlineCheckMsg.SetPcID( PcInfo.PcID ); CloudFileOnlineCheckMsg.SetFilePath( FilePath ); CloudFileOnlineCheckMsg.SetFileInfo( FileSize, FileTime ); CloudFileOnlineCheckMsg.SetFileStatus( FileStatus ); MyClient.SendMsgToPc( CloudPcID, CloudFileOnlineCheckMsg ); end; procedure TFindCloudFileOnlineCheck.CheckFileLostConn; var FileHash : TTempCloudFileHash; p : TTempCloudFilePair; begin FileHash := TempCloudFolderInfo.TempCloudFileHash; for p in FileHash do begin // 程序结束 if not CheckNextSearch then Break; // 云文件 检测 CloudFileCheck( p.Value ); end; end; procedure TFindCloudFileOnlineCheck.CheckFolderLostConn; var TempFolderHash : TTempCloudFolderHash; p : TTempCloudFolderPair; ChildPath : string; FindCloudFileOnlineCheck : TFindCloudFileOnlineCheck; begin TempFolderHash := TempCloudFolderInfo.TempCloudFolderHash; for p in TempFolderHash do begin if not CheckNextSearch then Break; ChildPath := MyFilePath.getPath( FullPath ) + p.Value.FileName; // 递归目录 FindCloudFileOnlineCheck := TFindCloudFileOnlineCheck.Create( ChildPath ); FindCloudFileOnlineCheck.SetCloudPcInfo( CloudPcPath, CloudPcID ); FindCloudFileOnlineCheck.Update; FindCloudFileOnlineCheck.Free; end; end; function TFindCloudFileOnlineCheck.CheckNextSearch: Boolean; begin Sleep(100); Result := MyCloudFileOnlineCheckInfo.IsRun and MyNetPcInfoReadUtil.ReadIsOnline( CloudPcID ); end; constructor TFindCloudFileOnlineCheck.Create(_FullPath: string); begin FullPath := _FullPath; end; procedure TFindCloudFileOnlineCheck.DeleteTempCloudFolderInfo; begin TempCloudFolderInfo.Free; end; procedure TFindCloudFileOnlineCheck.FindTempCloudFolderInfo; var CloudFolderPath : string; FindTempCloudFolderInfo : TFindCloudFolderInfo; begin if FullPath = '' then CloudFolderPath := CloudPcPath else CloudFolderPath := MyFilePath.getPath( CloudPcPath ) + FullPath; // 读取缓存数据 TempCloudFolderInfo := MyCloudFolderInfoUtil.ReadTempFolderInfo( CloudFolderPath ); end; procedure TFindCloudFileOnlineCheck.SetCloudPcInfo(_CloudPcPath, _CloudPcID: string); begin CloudPcPath := _CloudPcPath; CloudPcID := _CloudPcID; end; procedure TFindCloudFileOnlineCheck.Update; begin // 读取 缓存数据 FindTempCloudFolderInfo; // 分配 Job CheckFileLostConn; // 分配 子目录 Job CheckFolderLostConn; // 删除缓存数据 DeleteTempCloudFolderInfo; end; { TBackupFileOnlineCheckThread } procedure TCloudFileOnlineCheckThread.CheckOnliePcHandle( OnlinePcID : string ); var BackupFileOnlineCheckHandle : TCloudFileOnlineCheckHandle; begin BackupFileOnlineCheckHandle := TCloudFileOnlineCheckHandle.Create( OnlinePcID ); BackupFileOnlineCheckHandle.Update; BackupFileOnlineCheckHandle.Free; end; constructor TCloudFileOnlineCheckThread.Create; begin inherited Create( True ) end; destructor TCloudFileOnlineCheckThread.Destroy; begin Terminate; Resume; WaitFor; inherited; end; procedure TCloudFileOnlineCheckThread.Execute; var OnlinePcID : string; begin while not Terminated do begin OnlinePcID := MyCloudFileOnlineCheckInfo.getCheckPcID; // 不存在 新上线机器 if OnlinePcID = '' then begin if not Terminated then Suspend; Continue; end; // 程序结束 if Terminated then Break; // 检测上线 Pc CheckOnliePcHandle( OnlinePcID ); end; inherited; end; { TMyBackupFileOnlineCheckInfo } procedure TMyCloudFileOnlineCheckInfo.AddOnlinePc(PcID: string); var PcIndex : Integer; begin Lock.Enter; PcIndex := OnlineCheckPcIDList.IndexOf( PcID ); if PcIndex < 0 then OnlineCheckPcIDList.Add( PcID ); Lock.Leave; CloudFileOnlineCheckThread.Resume; end; constructor TMyCloudFileOnlineCheckInfo.Create; begin IsRun := True; Lock := TCriticalSection.Create; OnlineCheckPcIDList := TStringList.Create; CloudFileOnlineCheckThread := TCloudFileOnlineCheckThread.Create; end; destructor TMyCloudFileOnlineCheckInfo.Destroy; begin IsRun := False; OnlineCheckPcIDList.Free; Lock.Free; inherited; end; function TMyCloudFileOnlineCheckInfo.getCheckPcID: string; begin Lock.Enter; if OnlineCheckPcIDList.Count > 0 then begin Result := OnlineCheckPcIDList[ 0 ]; OnlineCheckPcIDList.Delete( 0 ); end else Result := ''; Lock.Leave; end; procedure TMyCloudFileOnlineCheckInfo.StopCheck; begin IsRun := False; CloudFileOnlineCheckThread.Free; end; { TBackupFileOnlineCheckHandle } procedure TCloudFileOnlineCheckHandle.CheckCloudPcPathList; var i : Integer; CloudPcPath : string; FindCloudFileOnlineCheck : TFindCloudFileOnlineCheck; begin for i := 0 to CloudPcPathList.Count - 1 do begin CloudPcPath := CloudPcPathList[i]; FindCloudFileOnlineCheck := TFindCloudFileOnlineCheck.Create( '' ); FindCloudFileOnlineCheck.SetCloudPcInfo( CloudPcPath, OnlinePcID ); FindCloudFileOnlineCheck.Update; FindCloudFileOnlineCheck.Free; end; end; constructor TCloudFileOnlineCheckHandle.Create( _OnlinePcID : string ); begin OnlinePcID := _OnlinePcID; end; procedure TCloudFileOnlineCheckHandle.DeleteCloudPcPathList; begin CloudPcPathList.Free; end; procedure TCloudFileOnlineCheckHandle.FindCloudPcPathList; begin CloudPcPathList := MyCloudPathInfoUtil.ReadPcCloudPathList( OnlinePcID ); end; procedure TCloudFileOnlineCheckHandle.Update; begin // 读取 缓存数据 FindCloudPcPathList; // 递归检测 Pc 云路径 CheckCloudPcPathList; // 删除 缓存数据 DeleteCloudPcPathList; end; end.
unit POOCalculadora.Model.Calculadora.Calculadora; interface uses System.SysUtils, POOCalculadora.Model.Calculadora.Interfaces, System.Generics.Collections, POOCalculadora.Model.Classs.Eventos; type TCalculadora = class(TInterfacedObject, iCalculadora, iCalculadoraDisplay) private FLista : TList<Double>; FEvDisplayTotal : TEvDisplayTotal; public constructor Create; destructor Destroy; override; class function New : iCalculadora; function Add(Value : String) : iCalculadora; overload; function Add(Value : Integer) : iCalculadora; overload; function Add(Value : Currency) : iCalculadora; overload; function Somar : iOperacoes; function Subtrair : iOperacoes; function Multiplicar : iOperacoes; function Dividir : iOperacoes; function Display : iCalculadoraDisplay; function Resultado(Value : TEvDisplayTotal) : iCalculadoraDisplay; function EndDisplay : iCalculadora; end; implementation uses POOCalculadora.Model.Calculadora.Dividir, POOCalculadora.Model.Calculadora.Multiplicar, POOCalculadora.Model.Calculadora.Somar, POOCalculadora.Model.Calculadora.Subtrair; { TCalculadora } function TCalculadora.Add(Value: String): iCalculadora; begin Result := Self; FLista.Add(Value.ToDouble); end; function TCalculadora.Add(Value: Currency): iCalculadora; begin Result := Self; FLista.Add(Value); end; function TCalculadora.Add(Value: Integer): iCalculadora; begin Result := Self; FLista.Add(Value.ToDouble); end; constructor TCalculadora.Create; begin FLista := TList<Double>.Create; end; destructor TCalculadora.Destroy; begin FLista.Free; inherited; end; function TCalculadora.Display: iCalculadoraDisplay; begin Result := Self; end; function TCalculadora.Dividir: iOperacoes; begin Result := TDividir.New(FLista).Display.Resultado(FEvDisplayTotal).EndDisplay; end; function TCalculadora.EndDisplay: iCalculadora; begin Result := Self; end; function TCalculadora.Multiplicar: iOperacoes; begin Result := TMultiplicar.New(FLista).Display.Resultado(FEvDisplayTotal).EndDisplay; end; class function TCalculadora.New: iCalculadora; begin Result := Self.Create; end; function TCalculadora.Resultado(Value: TEvDisplayTotal): iCalculadoraDisplay; begin Result := Self; FEvDisplayTotal := Value; end; function TCalculadora.Somar: iOperacoes; begin Result := TSomar.New(FLista).Display.Resultado(FEvDisplayTotal).EndDisplay; end; function TCalculadora.Subtrair: iOperacoes; begin Result := TSubtrair.New(FLista).Display.Resultado(FEvDisplayTotal).EndDisplay; end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [PRODUTO] do PAF The MIT License Copyright: Copyright (C) 2010 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 1.0 *******************************************************************************} unit EcfProdutoVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, DB, SysUtils, UnidadeProdutoVO; type [TEntity] [TTable('PRODUTO')] TEcfProdutoVO = class(TVO) private FID: Integer; FID_UNIDADE_PRODUTO: Integer; FGTIN: String; FCODIGO_INTERNO: String; FNOME: String; FDESCRICAO: String; FDESCRICAO_PDV: String; FVALOR_VENDA: Extended; FQUANTIDADE_ESTOQUE: Extended; FESTOQUE_MINIMO: Extended; FESTOQUE_MAXIMO: Extended; FIAT: String; FIPPT: String; FNCM: String; FTIPO_ITEM_SPED: String; FTAXA_IPI: Extended; FTAXA_ISSQN: Extended; FTAXA_PIS: Extended; FTAXA_COFINS: Extended; FTAXA_ICMS: Extended; FCST: String; FCSOSN: String; FTOTALIZADOR_PARCIAL: String; FECF_ICMS_ST: String; FCODIGO_BALANCA: Integer; FPAF_P_ST: String; FLOGSS: String; FUnidadeProdutoSigla: String; FUnidadeEcfProdutoVO: TUnidadeProdutoVO; public constructor Create; override; destructor Destroy; override; [TId('ID')] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('GTIN', 'Gtin', 112, [ldGrid, ldLookup, ldCombobox], False)] property Gtin: String read FGTIN write FGTIN; [TColumn('DESCRICAO_PDV', 'Descricao Pdv', 240, [ldGrid, ldLookup, ldCombobox], False)] property DescricaoPdv: String read FDESCRICAO_PDV write FDESCRICAO_PDV; [TColumn('ID_UNIDADE_PRODUTO', 'Id Unidade Produto', 80, [], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdUnidadeProduto: Integer read FID_UNIDADE_PRODUTO write FID_UNIDADE_PRODUTO; [TColumnDisplay('UNIDADE_PRODUTO.SIGLA', 'Unidade', 100, [ldGrid, ldLookup], ftString, 'UnidadeEcfProdutoVO.TUnidadeEcfProdutoVO', True)] property UnidadeProdutoSigla: String read FUnidadeProdutoSigla write FUnidadeProdutoSigla; [TColumn('CODIGO_INTERNO', 'Codigo Interno', 100, [], False)] property CodigoInterno: String read FCODIGO_INTERNO write FCODIGO_INTERNO; [TColumn('NOME', 'Nome', 450, [], False)] property Nome: String read FNOME write FNOME; [TColumn('DESCRICAO', 'Descricao', 450, [], False)] property Descricao: String read FDESCRICAO write FDESCRICAO; [TColumn('VALOR_VENDA', 'Valor Venda', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorVenda: Extended read FVALOR_VENDA write FVALOR_VENDA; [TColumn('QUANTIDADE_ESTOQUE', 'Qtd Estoque', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property QuantidadeEstoque: Extended read FQUANTIDADE_ESTOQUE write FQUANTIDADE_ESTOQUE; [TColumn('ESTOQUE_MINIMO', 'Estoque Min', 128, [], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property EstoqueMinimo: Extended read FESTOQUE_MINIMO write FESTOQUE_MINIMO; [TColumn('ESTOQUE_MAXIMO', 'Estoque Max', 128, [], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property EstoqueMaximo: Extended read FESTOQUE_MAXIMO write FESTOQUE_MAXIMO; [TColumn('IAT', 'Iat', 50, [ldGrid, ldLookup, ldCombobox], False)] property Iat: String read FIAT write FIAT; [TColumn('IPPT', 'Ippt', 50, [ldGrid, ldLookup, ldCombobox], False)] property Ippt: String read FIPPT write FIPPT; [TColumn('NCM', 'Ncm', 80, [ldGrid, ldLookup, ldCombobox], False)] property Ncm: String read FNCM write FNCM; [TColumn('TIPO_ITEM_SPED', 'Tipo Item Sped', 16, [], False)] property TipoItemSped: String read FTIPO_ITEM_SPED write FTIPO_ITEM_SPED; [TColumn('TAXA_IPI', 'Taxa Ipi', 128, [], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property AliquotaIpi: Extended read FTAXA_IPI write FTAXA_IPI; [TColumn('TAXA_ISSQN', 'Taxa Issqn', 128, [], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property AliquotaIssqn: Extended read FTAXA_ISSQN write FTAXA_ISSQN; [TColumn('TAXA_PIS', 'Taxa Pis', 128, [], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property AliquotaPis: Extended read FTAXA_PIS write FTAXA_PIS; [TColumn('TAXA_COFINS', 'Taxa Cofins', 128, [], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property AliquotaCofins: Extended read FTAXA_COFINS write FTAXA_COFINS; [TColumn('TAXA_ICMS', 'Taxa Icms', 128, [], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property AliquotaICMS: Extended read FTAXA_ICMS write FTAXA_ICMS; [TColumn('CST', 'Cst', 50, [ldGrid, ldLookup, ldCombobox], False)] property Cst: String read FCST write FCST; [TColumn('CSOSN', 'Csosn', 50, [ldGrid, ldLookup, ldCombobox], False)] property Csosn: String read FCSOSN write FCSOSN; [TColumn('TOTALIZADOR_PARCIAL', 'Totalizador Parcial', 120, [ldGrid, ldLookup, ldCombobox], False)] property TotalizadorParcial: String read FTOTALIZADOR_PARCIAL write FTOTALIZADOR_PARCIAL; [TColumn('ECF_ICMS_ST', 'Ecf Icms St', 32, [], False)] property EcfIcmsSt: String read FECF_ICMS_ST write FECF_ICMS_ST; [TColumn('CODIGO_BALANCA', 'Codigo Balanca', 80, [], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property CodigoBalanca: Integer read FCODIGO_BALANCA write FCODIGO_BALANCA; [TColumn('PAF_P_ST', 'Paf P St', 8, [], False)] property PafProdutoST: String read FPAF_P_ST write FPAF_P_ST; [TColumn('LOGSS', 'Log', 8, [], False)] property HashRegistro: String read FLOGSS write FLOGSS; [TAssociation('ID', 'ID_UNIDADE_PRODUTO')] property UnidadeEcfProdutoVO: TUnidadeProdutoVO read FUnidadeEcfProdutoVO write FUnidadeEcfProdutoVO; end; implementation constructor TEcfProdutoVO.Create; begin inherited; FUnidadeEcfProdutoVO := TUnidadeProdutoVO.Create; end; destructor TEcfProdutoVO.Destroy; begin FreeAndNil(FUnidadeEcfProdutoVO); inherited; end; initialization Classes.RegisterClass(TEcfProdutoVO); finalization Classes.UnRegisterClass(TEcfProdutoVO); 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 ------------------------------------------------------------------------------- } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, StdCtrls, Vcl.ExtCtrls; type TStreamExchangeClientForm = class(TForm) CheckBox1: TCheckBox; Memo1: TMemo; Button_SendStream: TButton; IdTCPClient1: TIdTCPClient; BuildButton: TButton; Image1: TImage; ClientSendFileEdit: TEdit; ClientReceiveFileEdit: TEdit; Label1: TLabel; Label2: TLabel; procedure CheckBox1Click(Sender: TObject); procedure IdTCPClient1Connected(Sender: TObject); procedure IdTCPClient1Disconnected(Sender: TObject); procedure Button_SendStreamClick(Sender: TObject); procedure BuildButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ClientSendFileEditExit(Sender: TObject); procedure ClientReceiveFileEditExit(Sender: TObject); private procedure SetClientState(aState: Boolean); { Private declarations } public { Public declarations } aFs_s: TFileStream; aFs_r: TFileStream; 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 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); 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.ClientReceiveFileEditExit(Sender: TObject); begin file_receive := ClientReceiveFileEdit.text; end; procedure TStreamExchangeClientForm.ClientSendFileEditExit(Sender: TObject); begin /// file_send := ClientSendFileEdit.text; if fileexists(file_send) then begin Image1.Picture.LoadFromFile(file_send); end else begin Memo1.Lines.Add('uups the file for sending does not exist... ') end; 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.FormCreate(Sender: TObject); begin ClientReceiveFileEdit.text := 'C:\temp\test_c_r.bmp'; ClientSendFileEdit.text := 'C:\temp\test_c_s.bmp'; ClientReceiveFileEditExit(Sender); ClientSendFileEditExit(Sender); aFs_s := TFileStream.Create(file_send, fmOpenReadWrite); aFs_r := TFileStream.Create(file_receive, fmCreate); 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 uGnArray; interface uses Generics.Collections, SysUtils, uGnStructures, uGnEnumerator, uGnGenerics, uGnStrConst; type EArray = class(Exception); IGnArray<_T> = interface(IGnContainer) // setters getters function GetData: Pointer; function GetDataSize: NativeUInt; function GetItemSize: NativeUInt; function GetItem(const AIndex: NativeUInt): _T; procedure SetItem(const AIndex: NativeUInt; AItem: _T); // --- function GetEnumerator: TEnumerator<_T>; function Append(const AItem: _T): NativeUInt; overload; function Append(const AItems: array of _T): NativeUInt; overload; procedure Insert(const AIndex: NativeUInt; const AItem: _T); procedure Delete(const AIndex: NativeUInt); procedure Swap(const AIndex1, AIndex2: NativeUInt); procedure Shuffle; function GetList: IGnList<_T>; property Items[const AIndex: NativeUInt]: _T read GetItem write SetItem; default; property Data: Pointer read GetData; property DataSize: NativeUInt read GetDataSize; property ItemSize: NativeUInt read GetItemSize; end; TGnAbstractArray<_T> = class abstract(TInterfacedObject, IGnContainer) strict private FItemSize: NativeUInt; strict protected FItems: array of _T; FItemsLength : NativeUInt; FCapability : NativeUInt; FCount: NativeUInt; procedure Grow; overload; virtual; procedure Grow(const ANeedCount: NativeUint); overload; virtual; function GetCount: NativeUInt; function GetItemSize: NativeUInt; public constructor Create; destructor Destroy; override; function IsEmpty: Boolean; inline; procedure Clear; virtual; property Capability: NativeUInt read FCapability write FCapability; property Count: NativeUInt read GetCount; property ItemSize: NativeUInt read GetItemSize; end; TGnArrayList<_T> = class; TGnArray<_T> = class(TGnAbstractArray<_T>, IGnArray<_T>) public type IGnArraySpec = IGnArray<_T>; IGnListSpec = IGnList<_T>; TGnArrayListSpec = TGnArrayList<_T>; TEnumeratorSpec = TGnEnumerator<_T, NativeInt>; TFreeProc = procedure (const AItem: _T); strict private FFreeProc: TFreeProc; function EnumGetCurrent(const AItem: NativeInt): _T; function EnumMoveNext(var AItem: NativeInt): Boolean; strict protected function GetData: Pointer; function GetDataSize: NativeUInt; function GetItem(const AIndex: NativeUInt): _T; procedure SetItem(const AIndex: NativeUInt; AItem: _T); public function GetEnumerator: TEnumerator<_T>; function Append(const AItem: _T): NativeUInt; overload; function Append(const AItems: array of _T): NativeUInt; overload; procedure Insert(const AIndex: NativeUInt; const AItem: _T); virtual; procedure Delete(const AIndex: NativeUInt); procedure Swap(const AIndex1, AIndex2: NativeUInt); inline; procedure Clear; override; procedure Shuffle; virtual; function GetList: IGnListSpec; property Items[const AIndex: NativeUInt]: _T read GetItem write SetItem; default; property Data: Pointer read GetData; property DataSize: NativeUInt read GetDataSize; property FreeProc: TFreeProc read FFreeProc write FFreeProc; end; TGnArray_ShortInt = TGnArray<ShortInt>; TGnArray_SmallInt = TGnArray<SmallInt>; TGnArray_Integer = TGnArray<Integer>; TGnArray_Byte = TGnArray<Byte>; TGnArray_Word = TGnArray<Word>; TGnArray_Cardinal = TGnArray<Cardinal>; TGnArray_String = TGnArray<string>; TGnArray_Char = TGnArray<Char>; IGnShortedArray<_T> = interface(IGnArray<_T>) // setters getters procedure SetSorted(const ASorted: Boolean); function GetSorted: Boolean; // --- function Min: NativeInt; function Max: NativeInt; function IndexOf(const AItem: _T): NativeInt; function IsEqual(const AArray: IGnShortedArray<_T>): Boolean; function Contains(const AElement: _T): Boolean; procedure Sort; property Sorted: Boolean read GetSorted write SetSorted; end; TGnSortedArray<_T> = class(TGnArray<_T>, IGnShortedArray<_T>) public type IGnShortedArraySpec = IGnShortedArray<_T>; TCompareFunc = function(const ALeft, ARight: _T): TValueRelationship of object; strict private FSorted: Boolean; FCompareFunc: TCompareFunc; FSearchFunc: function (const AItem: _T): NativeInt of object; function LineralSearch(const AItem: _T): NativeInt; function BinarySearch(const AItem: _T): NativeInt; procedure BubbleSort; procedure SetSorted(const ASorted: Boolean); function GetSorted: Boolean; public constructor Create(const ACompareFunc: TCompareFunc); reintroduce; virtual; function Min: NativeInt; function Max: NativeInt; function IndexOf(const AItem: _T): NativeInt; function Append(const AItem: _T): NativeUInt; overload; function Append(const AItems: array of _T): NativeUInt; overload; procedure Insert(const AIndex: NativeUInt; const AItem: _T); override; procedure Shuffle; override; function IsEqual(const AArray: IGnShortedArray<_T>): Boolean; function Contains(const AElement: _T): Boolean; procedure Sort; property Sorted: Boolean read GetSorted write SetSorted; property CompareFunc: TCompareFunc read FCompareFunc; end; TGnSortedArray_ShortInt = class(TGnSortedArray<ShortInt>) public constructor Create; reintroduce; end; TGnSortedArray_SmallInt = class(TGnSortedArray<SmallInt>) public constructor Create; reintroduce; end; TGnSortedArray_Integer = class(TGnSortedArray<Integer>) public constructor Create; reintroduce; end; TGnSortedArray_Byte = class(TGnSortedArray<Byte>) public constructor Create; reintroduce; end; TGnSortedArray_Word = class(TGnSortedArray<Word>) public constructor Create; reintroduce; end; TGnSortedArray_Cardinal = class(TGnSortedArray<Cardinal>) public constructor Create; reintroduce; end; TGnSortedArray_String = class(TGnSortedArray<string>) public constructor Create; reintroduce; end; TGnSortedArray_Char = class(TGnSortedArray<Char>) public constructor Create; reintroduce; end; TGnArrayList<_T> = class(TInterfacedObject, IGnList<_T>) public type IGnArraySpec = IGnArray<_T>; IGnListSpec = IGnList<_T>; strict private FArray: IGnArraySpec; FIndex: NativeUInt; function GetCurrent: _T; function GetCount: NativeUInt; public constructor Create(const AArray: IGnArraySpec); procedure Clear; function IsEmpty: Boolean; function Next: Boolean; function Prev: Boolean; function First: Boolean; function Last: Boolean; function IsLast: Boolean; function IsFirst: Boolean; property Current: _T read GetCurrent; property Count: NativeUInt read GetCount; end; TGnArrayList_ShortInt = TGnArrayList<ShortInt>; TGnArrayList_SmallInt = TGnArrayList<SmallInt>; TGnArrayList_Integer = TGnArrayList<Integer>; TGnArrayList_Byte = TGnArrayList<Byte>; TGnArrayList_Word = TGnArrayList<Word>; TGnArrayList_Cardinal = TGnArrayList<Cardinal>; implementation { TGnAbstractArray<_T> } constructor TGnAbstractArray<_T>.Create; begin inherited Create; FCapability := cBaseCapability; FItemSize := SizeOf(_T); end; destructor TGnAbstractArray<_T>.Destroy; begin Clear; inherited; end; procedure TGnAbstractArray<_T>.Grow; begin if FCount >= FItemsLength then begin Inc(FItemsLength, FCapability); SetLength(FItems, FItemsLength); end; end; function TGnAbstractArray<_T>.GetCount: NativeUInt; begin Result := FCount; end; function TGnAbstractArray<_T>.GetItemSize: NativeUInt; begin Result := FItemSize; end; procedure TGnAbstractArray<_T>.Grow(const ANeedCount: NativeUint); var BlankItems: NativeUInt; begin BlankItems := FItemsLength - FCount; if BlankItems < ANeedCount then begin FItemsLength := FItemsLength + ANeedCount - BlankItems + FCapability; SetLength(FItems, FItemsLength); end; end; function TGnAbstractArray<_T>.IsEmpty: Boolean; begin Result := FCount = 0; end; procedure TGnAbstractArray<_T>.Clear; begin SetLength(FItems, 0); FCount := 0; FItemsLength := 0; end; { TGnArray<_T> } function TGnArray<_T>.EnumGetCurrent(const AItem: NativeInt): _T; begin Result := FItems[AItem]; end; function TGnArray<_T>.EnumMoveNext(var AItem: NativeInt): Boolean; begin Inc(AItem); Result := NativeUInt(AItem) < FCount; end; function TGnArray<_T>.GetItem(const AIndex: NativeUInt): _T; begin Assert(AIndex < FCount, 'TGnArray<_T>.GetItem'); Result := FItems[AIndex]; end; function TGnArray<_T>.GetList: IGnListSpec; begin Result := TGnArrayList<_T>.Create(Self); end; function TGnArray<_T>.GetData: Pointer; begin Result := @FItems[0]; end; function TGnArray<_T>.GetDataSize: NativeUInt; begin Result := FCount * ItemSize; end; function TGnArray<_T>.GetEnumerator: TEnumerator<_T>; begin Result := TEnumeratorSpec.Create(-1, EnumGetCurrent, EnumMoveNext); end; function TGnArray<_T>.Append(const AItem: _T): NativeUInt; begin Grow; FItems[FCount] := AItem; Result := FCount; Inc(FCount); end; function TGnArray<_T>.Append(const AItems: array of _T): NativeUInt; var Item: _T; begin Grow(Length(AItems)); Result := FCount; for Item in AItems do begin FItems[FCount] := Item; Inc(FCount); end; end; procedure TGnArray<_T>.Clear; var Item: _T; begin if Assigned(FFreeProc) then begin for Item in FItems do FFreeProc(Item); end; inherited; end; procedure TGnArray<_T>.Insert(const AIndex: NativeUInt; const AItem: _T); var CountMove: NativeUInt; begin Assert(AIndex <= FCount, 'TGnArray<_T>.Insert: AIndex > FCount'); Grow; CountMove := FCount - AIndex; if CountMove > 0 then System.Move(FItems[AIndex], FItems[AIndex + 1], CountMove * ItemSize); FItems[AIndex] := AItem; Inc(FCount); end; procedure TGnArray<_T>.Delete(const AIndex: NativeUInt); var CountMove: NativeUInt; begin Assert(AIndex < FCount, 'TGnArray<_T>.Delete: AIndex > FCount'); CountMove := FCount - AIndex - 1; if CountMove > 0 then begin FItems[AIndex] := Default(_T); System.Move(FItems[AIndex + 1], FItems[AIndex], CountMove * ItemSize); end; Dec(FCount); end; procedure TGnArray<_T>.Swap(const AIndex1, AIndex2: NativeUInt); var Temp: _T; begin Temp := FItems[AIndex1]; FItems[AIndex1] := FItems[AIndex2]; FItems[AIndex2] := Temp; end; procedure TGnArray<_T>.SetItem(const AIndex: NativeUInt; AItem: _T); begin Assert(AIndex < FCount, 'TGnArray<_T>.SetItem'); FItems[AIndex] := AItem; end; procedure TGnArray<_T>.Shuffle; var i, RndIndex: NativeInt; TempItem: _T; begin for i := FCount - 1 downto 0 do begin RndIndex := Random(i + 1); TempItem := FItems[RndIndex]; FItems[RndIndex] := FItems[i]; FItems[i] := TempItem; end; end; { TGnSortedArray<_T> } function TGnSortedArray<_T>.Append(const AItem: _T): NativeUInt; begin inherited; Sorted := False; end; function TGnSortedArray<_T>.Append(const AItems: array of _T): NativeUInt; begin inherited; Sorted := False; end; function TGnSortedArray<_T>.BinarySearch(const AItem: _T): NativeInt; var L, R, M: NativeInt; // Left, Right and Middle indexes Compare: TValueRelationship; begin L := 0; R := FCount - 1; while L <= R do begin M := (L + R) div 2; Compare := FCompareFunc(FItems[M], AItem); if Compare = 0 then Exit(M); if Compare > 0 then R := M - 1 else L := M + 1; end; Result := -1; end; procedure TGnSortedArray<_T>.BubbleSort; var i, j: NativeInt; begin for i := 0 to FCount - 2 do for j := 0 to Int64(FCount) - 2 - i do if FCompareFunc(FItems[j], FItems[j + 1]) > 0 then Swap(j, j + 1); end; function TGnSortedArray<_T>.Contains(const AElement: _T): Boolean; begin Result := FSearchFunc(AElement) >= 0; end; constructor TGnSortedArray<_T>.Create(const ACompareFunc: TCompareFunc); begin inherited Create; FCompareFunc := ACompareFunc; FSearchFunc := LineralSearch; end; function TGnSortedArray<_T>.GetSorted: Boolean; begin Result := FSorted; end; function TGnSortedArray<_T>.IndexOf(const AItem: _T): NativeInt; begin Result := FSearchFunc(AItem); end; procedure TGnSortedArray<_T>.Insert(const AIndex: NativeUInt; const AItem: _T); begin inherited; Sorted := False; end; function TGnSortedArray<_T>.IsEqual(const AArray: IGnShortedArray<_T>): Boolean; var i: NativeUInt; begin if FCount <> AArray.Count then Exit(False); if FCount = 0 then Exit(True); for i := 0 to FCount - 1 do begin if FCompareFunc(FItems[i], AArray[i]) <> 0 then Exit(False); end; Result := True; end; function TGnSortedArray<_T>.LineralSearch(const AItem: _T): NativeInt; begin for Result := 0 to FCount - 1 do if FCompareFunc(FItems[Result], AItem) = 0 then Exit; Result := -1; end; function TGnSortedArray<_T>.Max: NativeInt; var i: Integer; begin if FCount = 0 then Exit(-1); Result := 0; for i := 1 to FCount - 1 do if FCompareFunc(FItems[Result], FItems[i]) < 0 then Result := i; end; function TGnSortedArray<_T>.Min: NativeInt; var i: Integer; begin if FCount = 0 then Exit(-1); Result := 0; for i := 1 to FCount - 1 do if FCompareFunc(FItems[Result], FItems[i]) > 0 then Result := i; end; procedure TGnSortedArray<_T>.SetSorted(const ASorted: Boolean); begin if FSorted = ASorted then Exit; FSorted := ASorted; if FSorted then begin FSearchFunc := BinarySearch; BubbleSort; end else FSearchFunc := LineralSearch; end; procedure TGnSortedArray<_T>.Shuffle; begin inherited; Sorted := False; end; procedure TGnSortedArray<_T>.Sort; begin Sorted := True; end; { TGnSortedArray_ShortInt } constructor TGnSortedArray_ShortInt.Create; begin inherited Create(GnComparer.Compare); end; { TGnSortedArray_SmallInt } constructor TGnSortedArray_SmallInt.Create; begin inherited Create(GnComparer.Compare); end; { TGnSortedArray_Integer } constructor TGnSortedArray_Integer.Create; begin inherited Create(GnComparer.Compare); end; { TGnSortedArray_Byte } constructor TGnSortedArray_Byte.Create; begin inherited Create(GnComparer.Compare); end; { TGnSortedArray_Word } constructor TGnSortedArray_Word.Create; begin inherited Create(GnComparer.Compare); end; { TGnSortedArray_Cardinal } constructor TGnSortedArray_Cardinal.Create; begin inherited Create(GnComparer.Compare); end; { TGnArrayList<_T> } procedure TGnArrayList<_T>.Clear; begin FArray.Clear; end; constructor TGnArrayList<_T>.Create(const AArray: IGnArraySpec); begin inherited Create; FArray := AArray; end; function TGnArrayList<_T>.First: Boolean; begin FIndex := 0; Result := not FArray.IsEmpty; end; function TGnArrayList<_T>.GetCount: NativeUInt; begin Result := FArray.Count; end; function TGnArrayList<_T>.GetCurrent: _T; begin Assert(not FArray.IsEmpty, 'TGnArrayList<_T>.GetCurrent'); Result := FArray[FIndex]; end; function TGnArrayList<_T>.IsEmpty: Boolean; begin Result := FArray.IsEmpty; end; function TGnArrayList<_T>.IsFirst: Boolean; begin Assert(not FArray.IsEmpty, 'TGnArrayList<_T>.IsFirst'); Result := FIndex = 0; end; function TGnArrayList<_T>.IsLast: Boolean; begin Assert(not FArray.IsEmpty, 'TGnArrayList<_T>.IsLast'); Result := FIndex >= FArray.Count - 1; end; function TGnArrayList<_T>.Last: Boolean; begin FIndex := FArray.Count - 1; Result := not FArray.IsEmpty; end; function TGnArrayList<_T>.Next: Boolean; begin Result := FIndex + 1 < FArray.Count; if Result then Inc(FIndex); end; function TGnArrayList<_T>.Prev: Boolean; begin Result := FIndex > 0; if Result then Dec(FIndex); end; { TGnSortedArray_String } constructor TGnSortedArray_String.Create; begin inherited Create(GnComparer.Compare_String); end; { TGnSortedArray_Char } constructor TGnSortedArray_Char.Create; begin inherited Create(GnComparer.Compare_Char); 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/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: JvgImageGroup.PAS, released on 2003-01-15. The Initial Developer of the Original Code is Andrey V. Chudin, [chudin att yandex dott ru] Portions created by Andrey V. Chudin are Copyright (C) 2003 Andrey V. Chudin. All Rights Reserved. Contributor(s): Michael Beck [mbeck att bigfoot dott com]. You may retrieve the latest version of this file at the Project JEDI's JVCL home page, located at http://jvcl.delphi-jedi.org Known Issues: -----------------------------------------------------------------------------} // $Id: JvgImageGroup.pas 12537 2009-10-03 09:55:35Z ahuser $ unit JvgImageGroup; {$I jvcl.inc} interface uses {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, JvComponent, JvgTypes, JvgUtils, JvgCommClasses; type TJvgImageGroup = class(TJvGraphicControl) private FImageList: TImageList; // FPassiveMask: TBitmap; // FActiveMask: TBitmap; // FSelectedMask: TBitmap; // FSingleSelected: Boolean; FTransparent: Boolean; FTransparentColor: TColor; FMasked: Boolean; FMaskedColor: TColor; FDisabledMaskColor: TColor; FAutoTrColor: TglAutoTransparentColor; FFastDraw: Boolean; FNeedRemakeBackground: Boolean; FImage: TBitmap; // OldWidth, OldHeight, // OldLeft, OldTop: Integer; // procedure SmthChanged(Sender: TObject); procedure SetImageList(Value: TImageList); procedure SetTransparent(Value: Boolean); procedure SetTransparentColor(Value: TColor); procedure SetMasked(Value: Boolean); procedure SetMaskedColor(Value: TColor); procedure SetDisabledMaskColor(Value: TColor); procedure SetAutoTrColor(Value: TglAutoTransparentColor); procedure SetFastDraw(Value: Boolean); protected procedure Paint; override; procedure WMSize(var Msg: TMessage); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure CreateResBitmap; procedure RemakeBackground; published property Images: TImageList read FImageList write SetImageList; property Transparent: Boolean read FTransparent write SetTransparent default False; property TransparentColor: TColor read FTransparentColor write SetTransparentColor default clOlive; property Masked: Boolean read FMasked write SetMasked default False; property MaskedColor: TColor read FMaskedColor write SetMaskedColor default clOlive; property DisabledMaskColor: TColor read FDisabledMaskColor write SetDisabledMaskColor default clBlack; property AutoTransparentColor: TglAutoTransparentColor read FAutoTrColor write SetAutoTrColor default ftcLeftBottomPixel; property FastDraw: Boolean read FFastDraw write SetFastDraw default False; property Align; property DragCursor; property DragMode; property Enabled; property ParentShowHint; property PopupMenu; property ShowHint; property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$URL: https://jvcl.svn.sourceforge.net/svnroot/jvcl/branches/JVCL3_47_PREPARATION/run/JvgImageGroup.pas $'; Revision: '$Revision: 12537 $'; Date: '$Date: 2009-10-03 11:55:35 +0200 (sam. 03 oct. 2009) $'; LogPath: 'JVCL\run' ); {$ENDIF UNITVERSIONING} implementation uses Math; constructor TJvgImageGroup.Create(AOwner: TComponent); begin inherited Create(AOwner); // ControlStyle := ControlStyle + [{csReplicatable,}csOpaque]; Width := 105; Height := 105; FImage := TBitmap.Create; //...defaults FTransparent := False; FTransparentColor := clOlive; FMasked := False; FMaskedColor := clOlive; FDisabledMaskColor := clBlack; FAutoTrColor := ftcLeftBottomPixel; FFastDraw := False; end; destructor TJvgImageGroup.Destroy; begin FImage.Free; inherited Destroy; end; procedure TJvgImageGroup.WMSize(var Msg: TMessage); begin if csDesigning in ComponentState then CreateResBitmap; end; procedure TJvgImageGroup.Paint; begin // if fNeedRebuildImage then CreateResBitmap; BitBlt(Canvas.Handle, 0, 0, Width, Height, FImage.Canvas.Handle, 0, 0, SRCCOPY); end; procedure TJvgImageGroup.RemakeBackground; begin FNeedRemakeBackground := True; Repaint; end; procedure TJvgImageGroup.CreateResBitmap; var I: Integer; Bitmap: TBitmap; begin if (FImageList = nil) or (FImageList.Count = 0) then Exit; Bitmap := TBitmap.Create; FImage.Width := FImageList.Width * FImageList.Count; FImage.Height := FImageList.Height; Width := Max(FImage.Width, Width); Height := Max(FImage.Height, Height); with FImage do begin Canvas.Brush.Color := clBtnFace; Canvas.Brush.Style := bsSolid; Canvas.FillRect(Bounds(0, 0, Width, Height)); end; if FTransparent then GetParentImageRect(Self, Bounds(Left, Top, FImage.Width, FImage.Height), FImage.Canvas.Handle); for I := 0 to FImageList.Count - 1 do begin FImageList.GetBitmap(I, Bitmap); if FMasked then JvgUtils.ChangeBitmapColor(FImage, FMaskedColor, clBtnFace); CreateBitmapExt(FImage.Canvas.Handle, Bitmap, ClientRect, I * FImageList.Width, 0, fwoNone, fdsDefault, FTransparent, FTransparentColor, FDisabledMaskColor); end; Bitmap.Free; end; { procedure TJvgImageGroup.SmthChanged(Sender: TObject); begin Invalidate; end; } procedure TJvgImageGroup.SetImageList(Value: TImageList); begin FImageList := Value; // SetAutoTrColor( FAutoTrColor ); Invalidate; end; procedure TJvgImageGroup.SetTransparent(Value: Boolean); begin if FTransparent <> Value then begin FTransparent := Value; Invalidate; end; end; procedure TJvgImageGroup.SetTransparentColor(Value: TColor); begin if FTransparentColor <> Value then begin // FAutoTrColor:=ftcUser; FTransparentColor := Value; Invalidate; end; end; procedure TJvgImageGroup.SetMasked(Value: Boolean); begin if FMasked <> Value then begin FMasked := Value; Invalidate; end; end; procedure TJvgImageGroup.SetMaskedColor(Value: TColor); begin if FMaskedColor <> Value then begin FMaskedColor := Value; Invalidate; end; end; procedure TJvgImageGroup.SetDisabledMaskColor(Value: TColor); begin if FDisabledMaskColor <> Value then begin FDisabledMaskColor := Value; Invalidate; end; end; procedure TJvgImageGroup.SetAutoTrColor(Value: TglAutoTransparentColor); //var x, y : Integer; begin { FAutoTrColor := Value; if (FAutoTrColor=ftcUser)or((FBitmap.Width or FBitmap.Height)=0)then Exit; case FAutoTrColor of ftcLeftTopPixel: begin x:=0; y:=0; end; ftcLeftBottomPixel: begin x:=0; y:=FBitmap.Height-1; end; ftcRightTopPixel: begin x:=FBitmap.Width-1; y:=0; end; ftcRightBottomPixel: begin x:=FBitmap.Width-1; y:=FBitmap.Height-1; end; end; FTransparentColor := GetPixel(FBitmap.Canvas.Handle,x,y); Invalidate;} end; procedure TJvgImageGroup.SetFastDraw(Value: Boolean); begin FFastDraw := Value; end; {$IFDEF UNITVERSIONING} initialization RegisterUnitVersion(HInstance, UnitVersioning); finalization UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
{$i deltics.io.text.inc} unit Deltics.IO.Text.Interfaces; interface uses Deltics.StringEncodings, Deltics.StringTypes, Deltics.IO.Streams, Deltics.IO.Text.Types; type IStream = Deltics.IO.Streams.IStream; ITextReader = interface ['{CA26B554-81FE-4511-B5C9-9B854A819CF8}'] function get_EOF: Boolean; function get_Location: TCharLocation; function get_Source: IStream; function get_SourceEncoding: TEncoding; property EOF: Boolean read get_EOF; property Location: TCharLocation read get_Location; property Source: IStream read get_Source; property SourceEncoding: TEncoding read get_SourceEncoding; end; IUtf8Reader = interface(ITextReader) function IsWhitespace(const aChar: Utf8Char): Boolean; procedure MoveBack; function NextChar: Utf8Char; function NextCharAfter(const aFilter: TUtf8CharFilterFn): Utf8Char; function NextCharSkippingWhitespace: Utf8Char; function NextWideChar: WideChar; function PeekChar: Utf8Char; function PeekCharSkippingWhitespace: Utf8Char; function ReadLine: Utf8String; procedure Skip(const aNumChars: Integer); procedure SkipWhitespace; procedure SkipChar; end; IUnicodeReader = interface(ITextReader) ['{719165A6-AD65-4C7F-8D8B-8A680031B5FD}'] function IsWhitespace(const aChar: WideChar): Boolean; function NextChar: WideChar; function NextCharAfter(const aFilter: TWideCharFilterFn): WideChar; function NextCharSkippingWhitespace: WideChar; procedure MoveBack; function PeekChar: WideChar; function PeekCharSkippingWhitespace: WideChar; function ReadLine: UnicodeString; procedure Skip(const aNumChars: Integer); procedure SkipWhitespace; procedure SkipChar; end; implementation end.
unit CryptMod; interface Uses System.SysUtils, Classes, Dialogs, System.Math, DCPrc4, DCPSha1, DCPSha256, DCPSha512, DCPMD5, DeviceSN; // MsgLog; Type TCryptDlgMode = (DLG_ECRYPT, DLG_DECRYPT); Type TAlgoType = (UNTYPE, RC4_SHA1, RC4_SHA256, RC4_SHA512); type TSignature = record hash_uncrypt: AnsiString; hash_encrypt: AnsiString; Algo: TAlgoType; Checked: Boolean; end; PSignature = ^TSignature; Var SignMaxLength: SmallInt = 72; const AlgoName: array [TAlgoType] of string = ('UNTYPE', 'RC4_SHA1', 'RC4_SHA256', 'RC4_SHA512'); function GetKey: AnsiString; function CheckHash(hash: AnsiString; l: integer): Boolean; function DigestToTxt(Digest: Array of byte): AnsiString; function GetMD5Hash(AStrData: AnsiString): AnsiString; function GetSHA1Hash(AStrData: AnsiString): AnsiString; function GetTrashStr(Count: integer): AnsiString; function GetAlgoType(StrAlgo: String): TAlgoType; function GetSignature(Sign: String; PSign: PSignature): Boolean; function EncryptRC4_SHA1(AKey, AStrValue: AnsiString): AnsiString; function EncryptRC4_SHA256(AKey, AStrValue: AnsiString): AnsiString; function EncryptRC4_SHA512(AKey, AStrValue: AnsiString): AnsiString; function DecryptRC4_SHA1(AKey, AStrValue: AnsiString): AnsiString; function DecryptRC4_SHA256(AKey, AStrValue: AnsiString): AnsiString; function DecryptRC4_SHA512(AKey, AStrValue: AnsiString): AnsiString; implementation function GetKey: AnsiString; var VolumeSN: String; WinUserName: String; ComputerName: String; begin VolumeSN := GetVolumeDriveSN(GetSystemDrive + '\'); WinUserName := GetWinUserName; ComputerName := GetComputerNetName; Result := GetMD5Hash(AnsiLowerCase(WinUserName + ':' + ComputerName + ':' + VolumeSN)); end; function CheckHash(hash: AnsiString; l: integer): Boolean; var sh: set of AnsiChar; i: integer; begin Result := false; sh := ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'a', 'b', 'c', 'd', 'e', 'f']; if Length(hash) <> l then Exit; for i := 1 to Length(hash) do if Not(hash[i] in sh) then Exit; Result := True; end; function DigestToTxt(Digest: Array of byte): AnsiString; var i: integer; begin for i := 0 to Length(Digest) - 1 do Result := Result + IntToHex(Digest[i], 2); end; function GetMD5Hash(AStrData: AnsiString): AnsiString; var MD5: TDCP_md5; Digest: array [0 .. 15] of byte; begin try MD5 := TDCP_md5.Create(Nil); MD5.Init; MD5.UpdateStr(AStrData); MD5.Final(Digest); Result := DigestToTxt(Digest); finally MD5.Free; end; end; function GetSHA1Hash(AStrData: AnsiString): AnsiString; var SHA1: TDCP_sha1; Digest: array[0..19] of byte; begin try SHA1 := TDCP_sha1.Create(Nil); SHA1.Init; SHA1.UpdateStr(AStrData); SHA1.Final(Digest); Result := DigestToTxt(Digest); finally SHA1.Free; end; end; function EncryptRC4_SHA1(AKey, AStrValue: AnsiString): AnsiString; var RC4: TDCP_rc4; begin try RC4 := TDCP_rc4.Create(Nil); RC4.InitStr(AKey, TDCP_sha1); Result := RC4.EncryptString(AStrValue); finally RC4.Free; end; end; function EncryptRC4_SHA256(AKey, AStrValue: AnsiString): AnsiString; var RC4: TDCP_rc4; begin try RC4 := TDCP_rc4.Create(Nil); RC4.InitStr(AKey, TDCP_sha1); Result := RC4.EncryptString(AStrValue); finally RC4.Free; end; end; function EncryptRC4_SHA512(AKey, AStrValue: AnsiString): AnsiString; var RC4: TDCP_rc4; begin try RC4 := TDCP_rc4.Create(Nil); RC4.InitStr(AKey, TDCP_sha1); Result := RC4.EncryptString(AStrValue); finally RC4.Free; end; end; function DecryptRC4_SHA1(AKey, AStrValue: AnsiString): AnsiString; var RC4: TDCP_rc4; begin try RC4 := TDCP_rc4.Create(Nil); RC4.InitStr(AKey, TDCP_sha1); Result := RC4.DecryptString(AStrValue); finally RC4.Free; end; end; function DecryptRC4_SHA256(AKey, AStrValue: AnsiString): AnsiString; var RC4: TDCP_rc4; begin try RC4 := TDCP_rc4.Create(Nil); RC4.InitStr(AKey, TDCP_sha256); Result := RC4.DecryptString(AStrValue); finally RC4.Free; end; end; function DecryptRC4_SHA512(AKey, AStrValue: AnsiString): AnsiString; var RC4: TDCP_rc4; begin try RC4 := TDCP_rc4.Create(Nil); RC4.InitStr(AKey, TDCP_sha512); Result := RC4.DecryptString(AStrValue); finally RC4.Free; end; end; function GetTrashStr(Count: integer): AnsiString; var i: integer; begin Randomize; for i := 1 to Count do Result := Result + AnsiChar(Chr(RandomRange(33, 126))) end; function GetAlgoType(StrAlgo: String): TAlgoType; var i: ShortInt; begin Result := UNTYPE; for i := 0 to Length(AlgoName) - 1 do if StrAlgo = AlgoName[TAlgoType(i)] then begin Result := TAlgoType(i); Exit; end; end; function GetSignature(Sign: String; PSign: PSignature): Boolean; var st: TStrings; begin Result := false; PSign.Checked := false; if Length(Sign) < SignMaxLength then begin Exit; end; if 'sign:' <> copy(Sign, 1, Length('sign:')) then begin Exit; end; try st := TStringList.Create; st.Text := StringReplace(Sign, ';', #13, [rfReplaceAll]); if st.Count < 4 then begin Exit; end; if CheckHash(st.Strings[1], 32) then begin PSign.hash_uncrypt := st.Strings[1]; end else Exit; if CheckHash(st.Strings[2], 32) then begin PSign.hash_encrypt := st.Strings[2] end else Exit; if GetAlgoType(st.Strings[3]) <> UNTYPE then begin PSign.Algo := GetAlgoType(st.Strings[3]); end else Exit; finally st.Free; end; PSign.Checked := True; Result := True; end; end.
unit DbIntfSample.Domain.Interfaces.DatabaseComponents; interface type IQuery = interface; TTransactionIsolationLevel = (ReadCommited, Snapshot); IDbConnection = interface(IUnknown) procedure SetConfiguration(ASGDB, AConnectionString: string); function CreateQuery(sql: string = ''): IQuery; procedure Open; end; IQuery = interface(IUnknown) procedure Open; end; TSGDBSupport = record const Firebird = 'Firebird'; Interbase = 'Interbase'; end; implementation end.
unit UFormNetworkPcDetail; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, UIconUtil, siComp; type TfrmNetworkPcDetail = class(TForm) Panel1: TPanel; edtComputerName: TEdit; iPcStatus: TImage; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; lbComputerID: TLabel; lbReachable: TLabel; lbIp: TLabel; lbPort: TLabel; lbLastOnlineTime: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; lbTotalShace: TLabel; lbAvailableSpace: TLabel; lbCloudConsumpition: TLabel; lbUsedSpace: TLabel; lvMyBackup: TListView; siLang_frmNetworkPcDetail: TsiLang; procedure FormCreate(Sender: TObject); procedure siLang_frmNetworkPcDetailChangeLanguage(Sender: TObject); private procedure BindToolbar; procedure BindSort; public { Public declarations } end; var frmNetworkPcDetail: TfrmNetworkPcDetail; implementation uses UMainForm, UFormUtil; {$R *.dfm} { TfrmNetworkPcDetail } procedure TfrmNetworkPcDetail.BindSort; begin ListviewUtil.BindSort( lvMyBackup ); // ListviewUtil.BindSort( lvBackupToMe ); end; procedure TfrmNetworkPcDetail.BindToolbar; begin lvMyBackup.SmallImages := MyIcon.getSysIcon; // lvBackupToMe.SmallImages := MyIcon.getSysIcon; end; procedure TfrmNetworkPcDetail.FormCreate(Sender: TObject); var NewIcon : TIcon; begin BindToolbar; BindSort; NewIcon := TIcon.Create; frmMainForm.ilTb24.GetIcon( 6, NewIcon ); Icon := NewIcon; NewIcon.Free; siLang_frmNetworkPcDetailChangeLanguage( nil ); end; procedure TfrmNetworkPcDetail.siLang_frmNetworkPcDetailChangeLanguage( Sender: TObject); begin with lvMyBackup do begin Columns[0].Caption := siLang_frmNetworkPcDetail.GetText( 'lvBackupItem' ); Columns[1].Caption := siLang_frmNetworkPcDetail.GetText( 'lvTotalSize' ); Columns[2].Caption := siLang_frmNetworkPcDetail.GetText( 'lvBackupSize' ); Columns[3].Caption := siLang_frmNetworkPcDetail.GetText( 'lvPercentage' ); end; end; end.
unit uData; {$mode objfpc}{$H+} interface uses Classes, SysUtils, IniFiles; Type TFirma = Record User, Lizenz: String; end; TKabel = Array[0..7] of String; TLizenz = class fFirma : TFirma; fPath, fFilename : String; private function GetFirma: TFirma; procedure SetFirma(Value: TFirma); public constructor Create; destructor Done; property Firma: TFirma read GetFirma write SetFirma; end; TPlan = class fKabel : array of TKabel; fData : record Filename, Geraet : String; index : int64; end; private function GetKabel : TKabel; function GetFile : String; procedure SetKabel(Value: TKabel); procedure Setfile(Value: String); public constructor Create; destructor Done; property Kabel: TKabel read GetKabel write SetKabel; property _File: String read GetFile write SetFile; // property UpDate end; implementation { TLizenz } constructor TLizenz.Create; begin inherited; fFilename:= Format('%s', ['Setting.svp']); if FileExists(fFilename) then fFirma:= GetFirma; end; Destructor TLizenz.Done; begin inherited; end; function TLizenz.GetFirma: TFirma; var s: String; begin s:= Format('[%s]', ['Lizenznehmer']); if FileExists(FPath + fFilename) then begin with TIniFile.Create(fFilename) do try fFirma.User := ReadString(s, 'Firma' , ' '); fFirma.Lizenz := ReadString(s, 'Lizenz', ' '); finally Free; end; end; Result:= fFirma; end; procedure TLizenz.SetFirma(Value: TFirma); var s: String; begin s:= Format('[%s]', ['Lizenznehmer']); if FileExists(fFilename) then DeleteFile(fFilename); with TIniFile.Create(fFilename) do try WriteString(s, 'Firma', Value.User); WriteString(s, 'Lizenz', Value.Lizenz); finally Free; end; end; { TPlan } constructor TPlan.Create; var Temp : TStringlist; i : Integer; begin inherited; if fData.Filename <> '' then begin fData.Filename:= Format('%s', [fData.Geraet + '.vpl']); if FileExists(fData.Filename) then begin Temp:= TStringlist.Create; Temp.LoadFromFile(fData.Filename); i:= Temp.Capacity div 9; SetLength(fKabel, i); end; end else SetLength(fKabel, 10); end; destructor TPlan.Done; begin inherited; end; function TPlan.GetKabel: TKabel; begin end; function TPlan.GetFile: String; begin result:= fData.Filename; end; procedure TPlan.SetKabel(Value: TKabel); var s: String; begin fData.Filename:= Format('%s', [fData.Geraet + '.vpl']); s:= Format('[%s]', ['Verdrahtung']); if FileExists(fData.Filename) then DeleteFile(fData.Filename); with TIniFile.Create(fData.Filename) do try WriteString(s, 'Quelle' , Value[0]); WriteString(s, 'Kontaktart Quelle' , Value[1]); WriteString(s, 'Leitungstyp' , Value[2]); WriteString(s, 'Leitungsquerschnitt' , Value[3]); WriteString(s, 'Leitungslänge' , Value[4]); WriteString(s, 'Leitungsfarbe' , Value[5]); WriteString(s, 'Kontaktart Ziel' , Value[6]); WriteString(s, 'Zielkontakt' , Value[7]); finally Free; end; end; procedure TPlan.Setfile(Value: String); begin fData.Filename:= Value; end; end.
unit CommonObjectSelectFilter; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ComCtrls, ExtCtrls, CommonFilter, ImgList, BaseObjects {$IFDEF VER150} , Variants {$ENDIF} ; type TfrmObjectSelect = class(TFrame) pnlLeft: TPanel; lswSearch: TListView; pnlButtons: TPanel; prg: TProgressBar; pnlSearch: TPanel; Label1: TLabel; spdbtnDeselectAll: TSpeedButton; edtName: TEdit; imgLst: TImageList; chbxFilterSelected: TCheckBox; sbtnShowFilter: TSpeedButton; sbtnDetach: TSpeedButton; sbtnExecute: TSpeedButton; procedure lswSearchKeyPress(Sender: TObject; var Key: Char); procedure lswSearchMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure spdbtnDeselectAllClick(Sender: TObject); procedure edtNameChange(Sender: TObject); procedure lswSearchInfoTip(Sender: TObject; Item: TListItem; var InfoTip: String); procedure sbtnSelectAllClick(Sender: TObject); procedure chbxFilterSelectedClick(Sender: TObject); procedure sbtnDetachClick(Sender: TObject); procedure sbtnExecuteClick(Sender: TObject); procedure sbtnShowFilterClick(Sender: TObject); // procedure pnlButtonsClick(Sender: TObject); private FActiveButton: TSpeedButton; FOnReloadData: TNotifyEvent; FSQL: string; fFilterValues: OleVariant; FActiveImageIndex: integer; FSelectImmediately: boolean; procedure SetActiveButton(const Value: TSpeedButton); function GetActiveObject: TIdObject; function GetActiveObjectName: string; private { Private declarations } FFilterID: integer; Filters: TWellFilters; AreaListItems: TListItems; procedure btnClickAction(Sender: TObject); procedure CreateButtons(FilterTable: variant); property ActiveButton: TSpeedButton read FActiveButton write SetActiveButton; function GetCurrentlySelected: string; procedure LoadSettings; public { Public declarations } procedure Reload(AFilterID: integer; SavePreviousValues: boolean); procedure Prepare; property FilterID: integer read FFilterID write FFilterID; property FilterValues: OleVariant read fFilterValues write FFilterValues; property ActiveObject: TIdObject read GetActiveObject; property ActiveObjectName: string read GetActiveObjectName; property ActiveImageIndex: integer read FActiveImageIndex write FActiveImageIndex; constructor Create(AOwner:TComponent); override; destructor Destroy; override; property OnReloadData: TNotifyEvent read FOnReloadData write FOnReloadData; property SQL: string read FSQL write FSQL; property SelectImmediately: boolean read FSelectImmediately write FSelectImmediately; procedure SetState(AState: boolean); procedure Clear; end; implementation uses CommonFilterContentForm, Facade, StringUtils; {$R *.DFM} { TfrmObjectSelect } function CreateFilterTable: variant; var sFilter: string; begin // таблица задействованных таблиц // 0 - идентификатор // 1 - аглицкое название // 2 - название ключа // 3 - русское название // 4 - ограничение при скачивании справочника // 5 - индекс картинки // 6 - строка сортировки Result := varArrayCreate([0,8,0,10],varVariant); Result[0,0] := 0; Result[1,0] := 'TBL_TIME'; Result[2,0] := 'DTM_ENTERING_DATE'; Result[3,0] := 'Время'; Result[4,0] := ''; Result[5,0] := 0; Result[6,0] := ''; Result[7, 0] := ''; Result[8, 0] := 1; Result[0,1] := 1; Result[1,1] := 'SPD_GET_AREA_DICT'; Result[2,1] := 'AREA_ID'; Result[3,1] := 'Площади'; Result[4,1] := ''; Result[5,1] := 1; Result[6,1] := ''; Result[7,1] := ''; Result[8,1] := 1; Result[0,2] := 2; Result[1,2] := 'TBL_NEW_PETROL_REGION_DICT'; Result[2,2] := 'PETROL_REGION_ID'; Result[3,2] := 'Новые НГР'; Result[4,2] := ''; Result[5,2] := 2; Result[6,2] := ''; Result[7,2] := ''; Result[8,2] := 1; Result[0,3] := 6; Result[1,3] := 'TBL_NEW_PETROL_REGION_DICT'; Result[2,3] := 'MAIN_REGION_ID'; Result[3,3] := 'Новые НГО'; // включаем насильственно идентификатор региона Result[4,3] := 'NUM_REGION_TYPE = 2'; Result[5,3] := 6; Result[6,3] := ''; Result[7,3] := ''; Result[8,3] := 1; Result[0,4] := 3; Result[1,4] := 'TBL_NEW_TECTONIC_STRUCT_DICT'; Result[2,4] := 'STRUCT_ID'; Result[3,4] := 'Новые тект. структуры'; Result[4,4] := 'NUM_STRUCT_TYPE=3 OR NUM_STRUCT_TYPE=4'; Result[5,4] := 3; Result[6,4] := 'vch_Struct_Full_Name'; Result[7,4] := ''; Result[8,4] := 1; Result[0,5] := 4; Result[1,5] := 'TBL_DISTRICT_DICT'; Result[2,5] := 'DISTRICT_ID'; Result[3,5] := 'Географические регионы'; Result[4,5] := ''; Result[5,5] := 4; Result[6,5] := ''; Result[7,5] := ''; Result[8,5] := 1; Result[0,6] := 5; Result[1,6] := 'TBL_ORGANIZATION_DICT'; Result[2,6] := 'ORGANIZATION_ID'; Result[3,6] := 'Недропользователь'; Result[4,6] := ''; Result[5,6] := 5; Result[6,6] := 'vch_Org_Full_Name'; Result[7,6] := ''; Result[8,6] := 1; Result[0,7] := 7; Result[1,7] := 'VW_STRATIGRAPHY_NAME_DICT'; Result[2,7] := 'STRATON_ID'; Result[3,7] := 'Страт. подразделение'; sFilter := '(rf_trim(VCH_STRATON_INDEX) <> ' + QuotedStr('') + ')'; Result[4,7] := sFilter + ' AND (TAXONOMY_UNIT_ID in (1, 2, 3, 4, 5, 6, 7, 17, 18, 19, 40,41,42,43,44,45,46,47,48,0,49,50,51,53,56,57,58,70))'; Result[5,7] := 7; Result[6,7] := 'VCH_STRATON_FULL_NAME'; Result[7,7] := 'Well_UIN in (select Well_UIN from tbl_subdivision_component sc where (%s) and sc.num_depth > 0)'; Result[8,7] := 3; Result[0,8] := 2; Result[1,8] := 'SPD_GET_PETROL_REGION_DICT'; Result[2,8] := 'OLD_NGR_ID'; Result[3,8] := 'Старые НГР'; Result[4,8] := ''; Result[5,8] := 2; Result[6,8] := ''; Result[7,8] := ''; Result[8,8] := 1; Result[0,9] := 6; Result[1,9] := 'TBL_PETROLIFEROUS_REGION_DICT'; Result[2,9] := 'OLD_NGO_ID'; Result[3,9] := 'Старые НГО'; // включаем насильственно идентификатор региона Result[4,9] := 'NUM_REGION_TYPE = 2'; Result[5,9] := 6; Result[6,9] := ''; Result[7,9] := ''; Result[8,9] := 1; Result[0,10] := 3; Result[1,10] := 'SPD_GET_TECTONIC_STRUCT_DICT'; Result[2,10] := 'OLD_TSTRUCT_ID'; Result[3,10] := 'Старые тектонические структуры'; Result[4,10] := 'NUM_STRUCT_TYPE=3 OR NUM_STRUCT_TYPE=4'; Result[5,10] := 3; Result[6,10] := 'vch_Struct_Full_Name'; Result[7,10] := ''; Result[8,10] := 1; end; procedure TfrmObjectSelect.btnClickAction(Sender: TObject); begin ActiveButton := (Sender as TSpeedButton); end; constructor TfrmObjectSelect.Create(AOwner: TComponent); begin inherited; FSelectImmediately := true; end; procedure TfrmObjectSelect.CreateButtons(FilterTable: variant); var i, iHB,iTop: integer; btn: TSpeedButton; begin iHB := varArrayHighBound(FilterTable,2); pnlButtons.Height := (iHB+1)*21+14; iTop := 7; //btn := nil; for i:=iHB downto 0 do begin btn := TSpeedButton.Create(pnlButtons); with btn do begin btn.Parent := pnlButtons; btn.ParentFont := false; btn.Font.Name := 'Arial'; btn.Font.Style := []; btn.Flat := false; Width := pnlButtons.Width - 2; Height:= 21; Top := pnlButtons.Height - 21 - iTop; Left := 1; Visible:=true; GroupIndex:=1; Caption := FilterTable[3,i]; Tag := FilterTable[0,i]; Margin := 3; Spacing := 7; Anchors := [akTop, akLeft, akRight]; if (FilterTable[5,i]>-1) and (FilterTable[5,i]<ImgLst.Count) then ImgLst.GetBitmap(FilterTable[5,i],Glyph); OnClick := btnClickAction; end; inc(iTop,21); end; FActiveButton := nil; FActiveButton := (pnlButtons.Controls[9] as TSpeedButton); end; destructor TfrmObjectSelect.Destroy; begin if Assigned(Filters) then begin Filters.Free; Filters := nil; end; inherited; end; procedure TfrmObjectSelect.Reload(AFilterID: integer; SavePreviousValues: boolean); begin FilterID := AFilterID; if FilterID>-1 then begin Filters.LoadFilter(FilterID, SavePreviousValues, FilterValues); ActiveImageIndex := Filters.CurrentFilter.ImageIndex; end; if FilterID = 1 then AreaListItems := lswSearch.Items; if Assigned(Filters.CurrentFilter) then FilterValues := Filters.CurrentFilter.FilterValues; FSQL := Filters.CreateSQLFilter; TMainFacade.GetInstance.SystemSettings.SectionByName['OSF'].SectionValues.Values['FilterId'] := IntToStr(Filters.CurrentFilter.ID); TMainFacade.GetInstance.SystemSettings.SectionByName['OSF'].SectionValues.Values['FilterValues'] := Filters.CurrentFilter.FilterNumbers; if Assigned(FOnReloadData) then FOnReloadData(Self); end; procedure TfrmObjectSelect.SetActiveButton(const Value: TSpeedButton); begin if (FActiveButton <> Value) then begin if Assigned(Filters.CurrentFilter) then Filters.CurrentFilter.SearchText := edtName.Text; FilterID := Value.Tag; Reload(FilterID, true); if Assigned(Filters.CurrentFilter) then edtName.Text := Filters.CurrentFilter.SearchText; edtName.SelectAll; FActiveButton := Value; FActiveButton.Down := true; end; end; procedure TfrmObjectSelect.lswSearchKeyPress(Sender: TObject; var Key: Char); begin if (Key=#32) and (lswSearch.Selected<>nil) and SelectImmediately then Reload(-1, true); end; procedure TfrmObjectSelect.lswSearchMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Item: TListItem; begin if ((Button = mbLeft) or (Button = mbRight)) and (X<=20)then begin Item := lswSearch.GetItemAt(X,Y); if (Item<>nil) and SelectImmediately then Reload(-1, true); end; end; procedure TfrmObjectSelect.spdbtnDeselectAllClick(Sender: TObject); begin SetState(false); end; procedure TfrmObjectSelect.edtNameChange(Sender: TObject); var Item: TListItem; begin Item:=lswSearch.FindCaption(0, AnsiUpperCase(trim(edtName.Text)), true,true,true); if Item<>nil then begin Item.Focused:=true; Item.Selected:=true; lswSearch.Scroll(0,Item.Position.Y); end; end; function TfrmObjectSelect.GetCurrentlySelected: string; var i: integer; begin Result := ''; with lswSearch do for i:=0 to Items.Count - 1 do if Items[i].Checked then Result := Result + #13 + #10 + Items[i].Caption+','; if Result<>'' then Result := 'Выбраны: '+Copy (Result, 0, Length(Result)-1); end; procedure TfrmObjectSelect.lswSearchInfoTip(Sender: TObject; Item: TListItem; var InfoTip: String); begin InfoTip := GetCurrentlySelected; if Assigned(Item) and (lswSearch.StringWidth(Item.Caption)>lswSearch.Width-60) then InfoTip := Item.Caption+#13+#10+InfoTip; end; procedure TfrmObjectSelect.Prepare; var vFilterTable: variant; begin vFilterTable := CreateFilterTable; Filters := TWellFilters.Create('', '', vFilterTable,lswSearch, prg); CreateButtons(vFilterTable); LoadSettings; end; procedure TfrmObjectSelect.SetState(AState: boolean); var i: integer; begin for i:=0 to lswSearch.Items.Count - 1 do lswSearch.Items[i].Checked := AState; if SelectImmediately then Reload(-1, true); end; procedure TfrmObjectSelect.sbtnSelectAllClick(Sender: TObject); begin SetState(true); end; procedure TfrmObjectSelect.Clear; begin SetState(False); end; function TfrmObjectSelect.GetActiveObject: TIdObject; begin Result := nil; end; procedure TfrmObjectSelect.chbxFilterSelectedClick(Sender: TObject); begin Filters.FilterLastSelectedObjects := chbxFilterSelected.Checked; if SelectImmediately then Reload(-1, true); end; procedure TfrmObjectSelect.sbtnDetachClick(Sender: TObject); begin FSelectImmediately := sbtnDetach.Down; end; procedure TfrmObjectSelect.sbtnExecuteClick(Sender: TObject); begin Reload(-1, true); end; procedure TfrmObjectSelect.sbtnShowFilterClick(Sender: TObject); begin if not Assigned(frmFilterContent) then frmFilterContent := TfrmFilterContent.Create(Self); frmFilterContent.WellFilters := Filters; frmFilterContent.Show; end; function TfrmObjectSelect.GetActiveObjectName: string; var i : integer; begin Result := ''; for i := 0 to lswSearch.Items.Count - 1 do if lswSearch.Items.Item[i].Selected then begin Result := lswSearch.Items.Item[i].Caption; break; end; end; procedure TfrmObjectSelect.LoadSettings; var sFilterType, sFilterValues: string; i: integer; fltr: TWellFilter; begin sFilterType := TMainFacade.GetInstance.SystemSettings.SectionByName['OSF'].SectionValues.Values['FilterId']; sFilterValues := TMainFacade.GetInstance.SystemSettings.SectionByName['OSF'].SectionValues.Values['FilterValues']; try FilterID := StrToInt(sFilterType); FilterValues := Split(sFilterValues, ','); Reload(FilterID, false); except Reload(1, False); end; end; end.
unit FormEditProfile; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, FrameEditProfile, ActnList,SeisProfile,SeisMaterial,FormEvent, StdCtrls; type TfrmEditProfile = class(TForm) frmEditAllProfile: TFrame8; actlstEditProfile: TActionList; actCheckProfile: TAction; actSelectProfile: TAction; actAddProfile: TAction; actUpProfile: TAction; actDelProfile: TAction; btnSPAdd: TButton; actAddCoord: TAction; actUpCoord: TAction; actSelectCoord: TAction; actDelCoord: TAction; actSPAdd: TAction; btn1: TButton; procedure actAddCoordExecute(Sender: TObject); procedure actAddProfileExecute(Sender: TObject); procedure actCheckProfileExecute(Sender: TObject); procedure actDelCoordExecute(Sender: TObject); procedure actDelProfileExecute(Sender: TObject); procedure actSelectCoordExecute(Sender: TObject); procedure actSelectProfileExecute(Sender: TObject); procedure actSPAddExecute(Sender: TObject); procedure actUpCoordExecute(Sender: TObject); procedure actUpProfileExecute(Sender: TObject); procedure btn1Click(Sender: TObject); procedure ClearForm; procedure FormActivate(Sender: TObject); private { Private declarations } FOnMyEvent:TMyEvent; FSeisProfiles:TSeismicProfiles; FSeisProfileCoords:TSeismicProfileCoordinates; public { Public declarations } property OnMyEvent:TMyEvent read FOnMyEvent write FOnMyEvent; property SeisProfiles:TSeismicProfiles read FSeisProfiles write FSeisProfiles; property SeisProfileCoords:TSeismicProfileCoordinates read FSeisProfileCoords write FSeisProfileCoords; end; var frmEditProfile: TfrmEditProfile; implementation {$R *.dfm} uses Facade; procedure TfrmEditProfile.actAddCoordExecute(Sender: TObject); var spc:TSeismicProfileCoordinate;i,m:Integer; begin spc:=SeisProfileCoords.Add as TSeismicProfileCoordinate; m:=SeisProfileCoords.Items[0].ID; for i:=1 to SeisProfileCoords.Count-1 do if SeisProfileCoords.Items[i].ID<m then m:=SeisProfileCoords.Items[i].ID; if m>0 then spc.ID:=-1 else spc.ID:=m-1; spc.SeismicProfile:=frmEditAllProfile.cbbSelectProfile.Items.Objects[frmEditAllProfile.cbbSelectProfile.ItemIndex] as TSeismicProfile; spc.CoordNumber:=StrToInt(frmEditAllProfile.edtNumberCoord.Text); spc.CoordX:=StrToFloat(frmEditAllProfile.edtCoordX.Text); spc.CoordY:=StrToFloat(frmEditAllProfile.edtCoordY.Text); frmEditAllProfile.lstCoordProfile.Items.AddObject(spc.List,spc as TSeismicProfileCoordinate); end; procedure TfrmEditProfile.actAddProfileExecute(Sender: TObject); var sp:TSeismicProfile;i,m:Integer; begin sp:=SeisProfiles.Add as TSeismicProfile; m:=SeisProfiles.Items[0].ID; for i:=1 to SeisProfiles.Count-1 do if SeisProfiles.Items[i].ID<m then m:=SeisProfiles.Items[i].ID; if m>0 then sp.ID:=-1 else sp.ID:=m-1; sp.SeisProfileNumber:=StrToInt(frmEditAllProfile.edtNumberProfile.Text); sp.PiketBegin:=StrToInt(frmEditAllProfile.edtBeginPiket.Text); sp.PiketEnd:=StrToInt(frmEditAllProfile.edtEndPiket.Text); sp.SeisProfileLenght:=StrToFloat(frmEditAllProfile.edtLengthProfile.Text); sp.DateEntry:=Now; sp.SeisProfileComment:=frmEditAllProfile.edtCommentProfile.Text; if frmEditAllProfile.cbbSeisMaterial.ItemIndex<>-1 then sp.SeismicMaterial:=TMainFacade.GetInstance.AllSeismicMaterials.ItemsByID[Integer(TSeismicMaterial(frmEditAllProfile.cbbSeisMaterial.Items.Objects[frmEditAllProfile.cbbSeisMaterial.ItemIndex]).ID)] as TSeismicMaterial; sp.SeismicProfileType:=TMainFacade.GetInstance.AllSeismicProfileTypes.ItemsByID[Integer(TSeismicProfileType(frmEditAllProfile.cbbTypeProfile.Items.Objects[frmEditAllProfile.cbbTypeProfile.ItemIndex]).ID)] as TSeismicProfileType; //TMainFacade.GetInstance.ALLSeismicProfiles.Add(sp); //sp.ID:=sp.Update(); //TMainFacade.GetInstance.ALLSeismicProfiles.ItemsById[Integer(sp.ID)].Assign(sp); //if Assigned(FOnMyEvent) then FOnMyEvent(Sender); //actCheckProfileExecute(frmEditAllProfile); //actCheckProfileExecute(frmEditAllProfile); ClearForm; frmEditAllProfile.cbbSelectProfile.Items.AddObject(sp.List,sp as TSeismicProfile); frmEditAllProfile.cbbSelectProfile.ItemIndex:=frmEditAllProfile.cbbSelectProfile.Items.Count-1; actSelectProfileExecute(frmEditAllProfile); end; procedure TfrmEditProfile.actCheckProfileExecute(Sender: TObject); var i:Integer; begin if frmEditAllProfile.rgProfile.ItemIndex=0 then begin frmEditAllProfile.cbbSelectProfile.Clear; TMainFacade.GetInstance.ALLSeismicProfiles.MakeList(frmEditAllProfile.cbbSelectProfile.Items); end else begin frmEditAllProfile.cbbSelectProfile.Clear; for i:=0 to TMainFacade.GetInstance.ALLSeismicProfiles.Count-1 do if (not Assigned(TMainFacade.GetInstance.ALLSeismicProfiles.Items[i].SeismicMaterial)) then frmEditAllProfile.cbbSelectProfile.Items.AddObject(TMainFacade.GetInstance.ALLSeismicProfiles.Items[i].List,TMainFacade.GetInstance.ALLSeismicProfiles.Items[i] as TSeismicProfile); end; ClearForm; end; procedure TfrmEditProfile.actDelCoordExecute(Sender: TObject); begin if ((frmEditAllProfile.lstCoordProfile.Items.Objects[frmEditAllProfile.lstCoordProfile.ItemIndex] as TSeismicProfileCoordinate).ID)<=0 then SeisProfileCoords.MarkDeleted(SeisProfileCoords.ItemsByID[(frmEditAllProfile.lstCoordProfile.Items.Objects[frmEditAllProfile.lstCoordProfile.ItemIndex] as TSeismicProfileCoordinate).ID] as TSeismicProfileCoordinate) else begin SeisProfileCoords.MarkDeleted(SeisProfileCoords.ItemsByID[(frmEditAllProfile.lstCoordProfile.Items.Objects[frmEditAllProfile.lstCoordProfile.ItemIndex] as TSeismicProfileCoordinate).ID] as TSeismicProfileCoordinate) //TMainFacade.GetInstance.AllSeismicProfileCoordinates.MarkDeleted(TMainFacade.GetInstance.AllSeismicProfileCoordinates.ItemsByID[(frmEditAllProfile.lstCoordProfile.Items.Objects[frmEditSMExemple.lstElement.ItemIndex] as TElementExemple).ID] as TElementExemple) end; frmEditAllProfile.lstCoordProfile.DeleteSelected; end; procedure TfrmEditProfile.actDelProfileExecute(Sender: TObject); var i:Integer; begin if (frmEditAllProfile.cbbSelectProfile.Items.Objects[frmEditAllProfile.cbbSelectProfile.ItemIndex] as TSeismicProfile).ID>0 then for i:=0 to TMainFacade.GetInstance.ALLSeismicProfiles.Count-1 do if TMainFacade.GetInstance.ALLSeismicProfiles.Items[i].ID=(frmEditAllProfile.cbbSelectProfile.Items.Objects[frmEditAllProfile.cbbSelectProfile.ItemIndex] as TSeismicProfile).ID then begin TMainFacade.GetInstance.ALLSeismicProfiles.MarkDeleted(i); Break; end; frmEditAllProfile.cbbSelectProfile.DeleteSelected; frmEditAllProfile.lstCoordProfile.Clear; ClearForm; end; procedure TfrmEditProfile.actSelectCoordExecute(Sender: TObject); begin frmEditAllProfile.edtNumberCoord.Text:=IntToStr((frmEditAllProfile.lstCoordProfile.Items.Objects[frmEditAllProfile.lstCoordProfile.ItemIndex] as TSeismicProfileCoordinate).CoordNumber); frmEditAllProfile.edtCoordX.Text:=FloatToStr((frmEditAllProfile.lstCoordProfile.Items.Objects[frmEditAllProfile.lstCoordProfile.ItemIndex] as TSeismicProfileCoordinate).CoordX); frmEditAllProfile.edtCoordY.Text:=FloatToStr((frmEditAllProfile.lstCoordProfile.Items.Objects[frmEditAllProfile.lstCoordProfile.ItemIndex] as TSeismicProfileCoordinate).CoordY); end; procedure TfrmEditProfile.actSelectProfileExecute(Sender: TObject); var i,j:Integer; begin for i:=0 to SeisProfiles.Count-1 do if SeisProfiles.Items[i].ID=(frmEditAllProfile.cbbSelectProfile.Items.Objects[frmEditAllProfile.cbbSelectProfile.ItemIndex] as TSeismicProfile).ID then Break; frmEditAllProfile.edtNumberProfile.Text:=IntToStr(SeisProfiles.Items[i].SeisProfileNumber); frmEditAllProfile.edtBeginPiket.Text:=IntToStr(SeisProfiles.Items[i].PiketBegin); frmEditAllProfile.edtEndPiket.Text:=IntToStr(SeisProfiles.Items[i].PiketEnd); frmEditAllProfile.edtLengthProfile.Text:=FloatToStr(SeisProfiles.Items[i].SeisProfileLenght); frmEditAllProfile.edtCommentProfile.Text:=SeisProfiles.Items[i].SeisProfileComment; if Assigned(SeisProfiles.Items[i].SeismicProfileType) then begin for j:=0 to frmEditAllProfile.cbbTypeProfile.Items.Count-1 do if (frmEditAllProfile.cbbTypeProfile.Items.Objects[j] as TSeismicProfileType).ID=SeisProfiles.Items[i].SeismicProfileType.ID then begin frmEditAllProfile.cbbTypeProfile.ItemIndex:=j; Break; end; end else frmEditAllProfile.cbbTypeProfile.ItemIndex:=-1; if Assigned(SeisProfiles.Items[i].SeismicMaterial) then begin for j:=0 to frmEditAllProfile.cbbSeisMaterial.Items.Count do if (frmEditAllProfile.cbbSeisMaterial.Items.Objects[j] as TSeismicMaterial).ID=SeisProfiles.Items[i].SeismicMaterial.ID then begin frmEditAllProfile.cbbSeisMaterial.ItemIndex:=j; Break; end; end else frmEditAllProfile.cbbSeisMaterial.ItemIndex:=-1; frmEditAllProfile.lstCoordProfile.Clear; for j:=0 to SeisProfileCoords.Count-1 do if (SeisProfileCoords.Items[j].SeismicProfile.ID=SeisProfiles.Items[i].ID) then frmEditAllProfile.lstCoordProfile.Items.AddObject(SeisProfileCoords.Items[j].List,SeisProfileCoords.Items[j] as TSeismicProfileCoordinate); end; procedure TfrmEditProfile.actSPAddExecute(Sender: TObject); var i,j,id:integer;sp:TSeismicProfile;spc:TSeismicProfileCoordinate;Addsp,Addspc,Del:Boolean; begin for i:=0 to TMainFacade.GetInstance.ALLSeismicProfiles.DeletedObjects.Count-1 do TMainFacade.GetInstance.ALLSeismicProfiles.DeletedObjects.Remove(TMainFacade.GetInstance.ALLSeismicProfiles.DeletedObjects.Items[0] as TSeismicProfile); TMainFacade.GetInstance.ALLSeismicProfiles.DeletedObjects.Clear; for i:=0 to frmEditAllProfile.cbbSelectProfile.Items.Count-1 do begin if (frmEditAllProfile.cbbSelectProfile.Items.Objects[i] as TSeismicProfile).ID<=0 then Addsp:=True else Addsp:=False; if Addsp then begin sp:=TMainFacade.GetInstance.ALLSeismicProfiles.Add as TSeismicProfile; end else begin sp:=TSeismicProfile.Create(TMainFacade.GetInstance.ALLSeismicProfiles) as TSeismicProfile; end; sp.Assign(frmEditAllProfile.cbbSelectProfile.Items.Objects[i] as TSeismicProfile); if Addsp then sp.ID:=sp.Update() else begin sp.Update(); TMainFacade.GetInstance.ALLSeismicProfiles.ItemsByID[sp.ID].Assign(sp); end; for j:=0 to SeisProfileCoords.Count-1 do if (frmEditAllProfile.cbbSelectProfile.Items.Objects[i] as TSeismicProfile).ID=SeisProfileCoords.Items[j].SeismicProfile.ID then begin if SeisProfileCoords.Items[j].ID<=0 then Addspc:=True else Addspc:=False; if Addspc then begin spc:=TMainFacade.GetInstance.AllSeismicProfileCoordinates.Add as TSeismicProfileCoordinate; end else begin spc:=TSeismicProfileCoordinate.Create(TMainFacade.GetInstance.AllSeismicProfileCoordinates) as TSeismicProfileCoordinate; end; spc.Assign(SeisProfileCoords.Items[j]); spc.SeismicProfile.Assign(TMainFacade.GetInstance.ALLSeismicProfiles.ItemsByID[sp.ID] as TSeismicProfile); if Addspc then spc.ID:=spc.Update() else begin spc.Update(); TMainFacade.GetInstance.AllSeismicProfileCoordinates.ItemsByID[spc.ID].Assign(spc); end; end; end; if Assigned(FOnMyEvent) then FOnMyEvent(Sender); Close; end; procedure TfrmEditProfile.actUpCoordExecute(Sender: TObject); var i:Integer; begin for i:=0 to SeisProfileCoords.Count-1 do if SeisProfileCoords.Items[i].CoordNumber=(frmEditAllProfile.lstCoordProfile.Items.Objects[frmEditAllProfile.lstCoordProfile.ItemIndex] as TSeismicProfileCoordinate).CoordNumber then begin SeisProfileCoords.Items[i].CoordNumber:=StrToInt(frmEditAllProfile.edtNumberCoord.Text); SeisProfileCoords.Items[i].CoordX:=StrToFloat(frmEditAllProfile.edtCoordX.Text); SeisProfileCoords.Items[i].CoordY:=StrToFloat(frmEditAllProfile.edtCoordY.Text); frmEditAllProfile.lstCoordProfile.Items.Objects[frmEditAllProfile.lstCoordProfile.ItemIndex]:=SeisProfileCoords.Items[i] as TSeismicProfileCoordinate; frmEditAllProfile.lstCoordProfile.Items.Strings[frmEditAllProfile.lstCoordProfile.ItemIndex]:=SeisProfileCoords.Items[i].List; end; end; procedure TfrmEditProfile.actUpProfileExecute(Sender: TObject); var sp:TSeismicProfile; begin sp:=TSeismicProfile.Create(SeisProfiles) as TSeismicProfile; sp.Assign(SeisProfiles.ItemsById[Integer(TSeismicProfile(frmEditAllProfile.cbbSelectProfile.Items.Objects[frmEditAllProfile.cbbSelectProfile.ItemIndex]).ID)] as TSeismicProfile); sp.SeisProfileNumber:=StrToInt(frmEditAllProfile.edtNumberProfile.Text); sp.PiketBegin:=StrToInt(frmEditAllProfile.edtBeginPiket.Text); sp.PiketEnd:=StrToInt(frmEditAllProfile.edtEndPiket.Text); sp.SeisProfileLenght:=StrToFloat(frmEditAllProfile.edtLengthProfile.Text); sp.SeisProfileComment:=frmEditAllProfile.edtCommentProfile.Text; if frmEditAllProfile.cbbSeisMaterial.ItemIndex<>-1 then sp.SeismicMaterial:=TMainFacade.GetInstance.AllSeismicMaterials.ItemsByID[Integer(TSeismicMaterial(frmEditAllProfile.cbbSeisMaterial.Items.Objects[frmEditAllProfile.cbbSeisMaterial.ItemIndex]).ID)] as TSeismicMaterial else sp.SeismicMaterial:=nil; sp.SeismicProfileType:=TMainFacade.GetInstance.AllSeismicProfileTypes.ItemsByID[Integer(TSeismicProfileType(frmEditAllProfile.cbbTypeProfile.Items.Objects[frmEditAllProfile.cbbTypeProfile.ItemIndex]).ID)] as TSeismicProfileType; //sp.Update(); SeisProfiles.ItemsById[Integer(sp.ID)].Assign(sp); frmEditAllProfile.cbbSelectProfile.Clear; //TMainFacade.GetInstance.ALLSeismicProfiles.MakeList(frmEditAllProfile.cbbSelectProfile.Items); //if Assigned(FOnMyEvent) then FOnMyEvent(Sender); //actCheckProfileExecute(frmEditAllProfile); //actCheckProfileExecute(frmEditAllProfile); ClearForm; SeisProfiles.MakeList(frmEditAllProfile.cbbSelectProfile.Items); end; procedure TfrmEditProfile.btn1Click(Sender: TObject); begin Close; end; procedure TfrmEditProfile.ClearForm; begin with frmEditAllProfile do begin edtNumberProfile.Text:=''; edtBeginPiket.Text:=''; edtEndPiket.Text:=''; edtLengthProfile.Text:=''; edtCommentProfile.Text:=''; cbbSeisMaterial.ItemIndex:=-1; cbbTypeProfile.ItemIndex:=-1; edtCoordX.Text:=''; edtCoordY.Text:=''; edtNumberCoord.Text:=''; lstCoordProfile.Clear; end end; procedure TfrmEditProfile.FormActivate(Sender: TObject); var i,j:Integer;ob:TSeismicProfile;ob2:TSeismicProfileCoordinate; begin SeisProfiles:=TSeismicProfiles.Create; SeisProfileCoords:=TSeismicProfileCoordinates.Create; for i:=0 to TMainFacade.GetInstance.ALLSeismicProfiles.Count-1 do begin ob:=SeisProfiles.Add as TSeismicProfile; ob.Assign(TMainFacade.GetInstance.ALLSeismicProfiles.Items[i] as TSeismicProfile); end; for j:=0 to TMainFacade.GetInstance.AllSeismicProfileCoordinates.Count-1 do begin ob2:=SeisProfileCoords.Add as TSeismicProfileCoordinate; ob2.Assign(TMainFacade.GetInstance.AllSeismicProfileCoordinates.Items[j] as TSeismicProfileCoordinate); end; end; end.
unit htmlayout_h; interface uses Windows, Messages; const HLN_CREATE_CONTROL = $AFF + $01; HLN_LOAD_DATA = $AFF + $02; HLN_CONTROL_CREATED = $AFF + $03; HLN_DATA_LOADED = $AFF + $04; HLN_DOCUMENT_COMPLETE = $AFF + $05; HLN_UPDATE_UI = $AFF + $06; HLN_DESTROY_CONTROL = $AFF + $07; HLN_ATTACH_BEHAVIOR = $AFF + $08; HLN_BEHAVIOR_CHANGED = $AFF + $09; HLN_DIALOG_CREATED = $AFF + $10; HLN_DIALOG_CLOSE_RQ = $AFF + $0A; HLN_DOCUMENT_LOADED = $AFF + $0B; HWND_TRY_DEFAULT = 0; HWND_DISCARD_CREATION = 1; LOAD_OK = 0; LOAD_DISCARD = 1; type HELEMENT = Pointer; HTMLAYOUT_NOTIFY = function (uMsg: UINT; wParam: WPARAM; lParam: LPARAM; vParam: Pointer): LRESULT; stdcall; LPHTMLAYOUT_NOTIFY = ^HTMLAYOUT_NOTIFY; NMHL_CREATE_CONTROL = packed record hdr: NMHDR; helement: HELEMENT; inHwndParent: HWND; outControlHwnd: HWND; reserved1: DWORD; reserved2: DWORD; end; LPNMHL_CREATE_CONTROL = ^NMHL_CREATE_CONTROL; NMHL_DESTROY_CONTROL = packed record hdr: NMHDR; helement: HELEMENT; inHwndParent: HWND; reserved1: DWORD; end; LPNMHL_DESTROY_CONTROL = ^NMHL_DESTROY_CONTROL; NMHL_LOAD_DATA = packed record hdr: NMHDR; uri: PChar; outData: Pointer; outDataSize: DWORD; dataType: UINT; principal: HELEMENT; initiator: HELEMENT; end; LPNMHL_LOAD_DATA = ^NMHL_LOAD_DATA; NMHL_DATA_LOADED = packed record hdr: NMHDR; uri: PChar; data: Pointer; dataSize: DWORD; dataType: UINT; status: UINT; end; LPNMHL_DATA_LOADED = ^NMHL_DATA_LOADED; NMHL_ATTACH_BEHAVIOR = packed record hdr: NMHDR; element: HELEMENT; behaviorName: PChar; //elementProc: end; LPNMHL_ATTACH_BEHAVIOR = ^NMHL_ATTACH_BEHAVIOR; function HTMLayoutInit(hModule: THandle; start: Boolean): Integer; stdcall; external 'htmlayout.dll'; function HTMLayoutClassNameA: PChar; stdcall; external 'htmlayout.dll'; function HTMLayoutClassNameW: PChar; stdcall; external 'htmlayout.dll'; function HTMLayoutProcND(hWnd: HWND; msg: UINT; wParam: WPARAM; lParam: LPARAM; pbHandled: PBOOL): Integer; stdcall; external 'htmlayout.dll'; function HTMLayoutSetCallback(hWndHTMLayout: HWND; cb: LPHTMLAYOUT_NOTIFY; cbParam: Pointer): Integer; stdcall; external 'htmlayout.dll'; function HTMLayoutLoadHtml(hWndHTMLayout: HWND; html: PChar; size: UINT): Boolean; stdcall; external 'htmlayout.dll'; function HTMLayoutLoadFile(hWndHTMLayout: HWND; filename: PChar): Boolean; stdcall; external 'htmlayout.dll'; function HTMLayoutClassNameT:PChar; implementation function HTMLayoutClassNameT:PChar; begin Result := HTMLayoutClassNameA; end; end.
unit GraphTester; interface uses System.UITypes, {$IFDEF FMX} FMX.Graphics, FMX.Types, {$ELSE}Graphics, Controls, {$ENDIF} Generics.Collections, Math, FHIR.Ui.Graph; type TRandomData = class (TFGraphDataProvider) private FData : TList<TFGraphDataPoint>; FXmin : Double; FXmax : Double; FYmin : Double; FYmax : Double; FName : String; function pointFactory(i : integer):TFGraphDataPoint; procedure checkLimits; public constructor Create(name : String); destructor Destroy; override; procedure addMore; function name : String; override; function HasDuplicateXValues : boolean; override; function count : integer; override; function dataCount : integer; override; function getPoint( i : integer) : TFGraphDataPoint; override; procedure prepare; override; function getMinXValue : Double; override; function getMaxXValue : Double; override; function getMinYValue : Double; override; function getMaxYValue : Double; override; end; TFGraphTester = {static} class public class procedure configure(graph : TFGraph); class procedure addMarks(graph : TFGraph); class procedure addSeries(graph : TFGraph); class procedure addBand(graph : TFGraph); end; implementation { TRandomData } procedure TRandomData.addMore; var i, b : integer; begin b := FData.Count; for i := 0 to 10 do FData.Add(pointFactory(i+b)); checkLimits; change; end; procedure TRandomData.checkLimits; var p : TFGraphDataPoint; begin FXmin := 0; FXMax := FData.Count + 1; FYMin := MaxInt; FYMax := -MaxInt; for p in FData do begin if p.error = '' then begin FYMin := min(FYMin, p.y); FYMax := max(FYMax, p.y); end; end; end; function TRandomData.count: integer; begin result := FData.count; end; constructor TRandomData.Create(name : String); var i : integer; begin inherited Create; FName := name; FData := TList<TFGraphDataPoint>.create; for i := 0 to 10 do FData.Add(pointFactory(i)); checkLimits; end; function TRandomData.datacount: integer; begin result := count - 1; end; destructor TRandomData.Destroy; begin FData.Free; inherited; end; function TRandomData.getMaxXValue: Double; begin result := FXmax; end; function TRandomData.getMaxYValue: Double; begin result := FYmax; end; function TRandomData.getMinXValue: Double; begin result := FXmin; end; function TRandomData.getMinYValue: Double; begin result := FYmin; end; function TRandomData.getPoint(i: integer): TFGraphDataPoint; begin result := FData[i]; end; function TRandomData.HasDuplicateXValues: boolean; begin result := false; end; function TRandomData.name: String; begin result := FName; end; function TRandomData.pointFactory(i: integer): TFGraphDataPoint; begin result.id := i; result.x := i; if i = 5 then result.error := 'Communication Error' else result.y := i + random * 4; end; procedure TRandomData.prepare; begin // nothing end; { TFGraphTester } class procedure TFGraphTester.addMarks(graph: TFGraph); begin graph.Annotations.Add(graph.createMark(0.5, 0.5, 0.9, 0.9, clRed, 'Test 1', mtLine, mpUpRight, dtAfter)); graph.Annotations.Add(graph.createMark(0.5, 0.5, 0.9, 0.1, clGreen, 'Test 2', mtLine, mpUpRight, dtAfter)); graph.Annotations.Add(graph.createMark(0.5, 0.5, 0.1, 0.9, clBlue, 'Test 3', mtLine, mpUpRight, dtAfter)); graph.Annotations.Add(graph.createMark(0.5, 0.5, 0.1, 0.1, clGray, 'Test 4', mtLine, mpUpRight, dtAfter)); end; class procedure TFGraphTester.addSeries(graph: TFGraph); var n : string; begin n := 'Test Data'; if graph.Series.Count > 0 then n := 'Second test Data'; graph.Series.Add(graph.createSeries(TRandomData.create(n))); graph.Series.last.RegressionType := rg_passingBablok; graph.Series.last.LegendStatus := lsAll; graph.Series.last.DrawPoints := true; graph.Series.last.PointShape := ps_Square; end; class procedure TFGraphTester.configure(graph: TFGraph); begin graph.Name := 'TestChart'; {$IFDEF FMX} graph.align := TAlignLayout.Client; graph.Legend.borderColor := TAlphaColors.Maroon; {$ELSE} graph.align := alClient; graph.Legend.borderColor := clMaroon; {$ENDIF} graph.Appearance.ShowMarks := true; graph.Appearance.TitleFont.Size := 12; graph.XAxis.AutoSizing := true; graph.YAxis1.AutoSizing := true; graph.YAxis2.ShowAxis := true; graph.Dimensions.RightMargin := 80; graph.Dimensions.TopMargin := 80; graph.Dimensions.LeftMargin := 80; graph.Dimensions.BottomMargin := 80; graph.Legend.visible := true; graph.Legend.borderStyle := psSolid; graph.Legend.Layout := lsDown; graph.Legend.top := 20; graph.Legend.left := 20; graph.Legend.top := 20; graph.Legend.height := 0; graph.Legend.width := 0; end; class procedure TFGraphTester.addBand(graph : TFGraph); var band : TFGraphBand; begin band := TFGraphBand.Create; try band.YAxis2 := false; band.color := clGreen; band.Min := 0.5; band.Max := 0.75; band.opacity := 0.1; graph.Bands.Add(band.link); finally band.Free; end; end; end.
{ Catarinka TStringListCache Caches multiple string lists, allowing them to be loaded or saved together to an external JSON file Copyright (c) 2003-2017 Felipe Daragon License: 3-clause BSD See https://github.com/felipedaragon/catarinka/ for details } unit CatStringListCache; interface {$I Catarinka.inc} uses {$IFDEF DXE2_OR_UP} System.Classes, System.SysUtils, unitObjectCache, CatJSON; {$ELSE} Classes, SysUtils, unitObjectCache, CatJSON; {$ENDIF} type TStringListCache = class protected fCache: TObjectCache; fNameList: TStringList; public function GetList(const AName:string):TStringList; procedure ClearLists; overload; procedure ClearLists(const Key:array of string); overload; procedure LoadFromFile(const AFilename:string); procedure SaveToFile(const AFilename:string); constructor Create(ACapacity : Integer = 1000; OwnsObjects : boolean = true); destructor Destroy; override; property Cache: TObjectCache read fCache; property Lists[const AName: string]: TStringList read GetList; default; end; type TCachedStringList = class (TStringList) private ID: string; end; implementation uses CatStringLoop; const cCacheKeyPrefix = 'cache.'; cIDListKey = 'idlist'; procedure TStringListCache.ClearLists; var csl: TCachedStringList; m, c: integer; begin m := fCache.Count; for c := m - 1 downto 0 do begin csl := fCache.ObjectAt(c) as TCachedStringList; csl.Clear; end; end; procedure TStringListCache.ClearLists(const Key:array of string); var X: Byte; begin for X := Low(Key) to High(Key) do if not (Key[X] = '') then getlist(Key[X]).clear; end; procedure TStringListCache.LoadFromFile(const AFilename:string); var slp:TStringLoop; sl:TStringList; j:TCatJSON; begin fCache.Clear; fNameList.Clear; j := TCatJSON.Create; j.LoadFromFile(AFilename); slp := TStringLoop.Create; slp.LoadFromString(j[cIDListKey]); while slp.Found do begin sl := GetList(slp.Current); sl.Text:= j[cCacheKeyPrefix+slp.Current]; end; slp.Free; j.Free; end; procedure TStringListCache.SaveToFile(const AFilename:string); var slp:TStringLoop; j:TCatJSON; csl: TCachedStringList; m, c: integer; begin j := TCatJSON.Create; j.SetValue(cIDListKey,fNameList.Text); m := fCache.Count; for c := m - 1 downto 0 do begin csl := fCache.ObjectAt(c) as TCachedStringList; j.SetValue(cCacheKeyPrefix+csl.ID, csl.text); end; j.SaveToFile(AFilename); j.Free; end; function TStringListCache.GetList(const AName:string):TStringList; var csl: TCachedStringList; m, c: integer; begin result:= nil; m := fCache.Count; for c := m - 1 downto 0 do begin csl := fCache.ObjectAt(c) as TCachedStringList; if csl.ID = aName then result:= csl; end; if result = nil then begin csl := TCachedStringList.Create; csl.id := AName; fCache.Add(csl); fNameList.Add(AName); result := csl; end; end; constructor TStringListCache.Create(ACapacity : Integer = 1000; OwnsObjects : boolean = true); begin fCache := TObjectCache.Create(ACapacity, OwnsObjects); fNameList:= TStringList.Create; end; destructor TStringListCache.Destroy; begin fNameList.Free; fCache.free; inherited; end; end.
unit uFrmFormasPagamento; {$mode objfpc}{$H+} interface uses Classes, SysUtils, db, Forms, Controls, Graphics, Dialogs, Buttons, ExtCtrls, StdCtrls, DBCtrls, DBGrids; type { TFrmFormasPagamento } TFrmFormasPagamento = class(TForm) BtnAltFormPag: TBitBtn; BtnCanFormPag: TBitBtn; BtnConFormPag: TBitBtn; BtnExcFormPag: TBitBtn; BtnIncFormPag: TBitBtn; BtnSairFormPag: TBitBtn; cbxDiasVencFormPag: TDBComboBox; cbxNParcFormPag: TDBComboBox; DBComboBox1: TDBComboBox; edtIdFormPag: TDBEdit; EdtDescFormPag: TDBEdit; DBGrid1: TDBGrid; ImageList1: TImageList; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Panel1: TPanel; procedure BtnAltFormPagClick(Sender: TObject); procedure BtnCanFormPagClick(Sender: TObject); procedure BtnConFormPagClick(Sender: TObject); procedure BtnExcFormPagClick(Sender: TObject); procedure BtnIncFormPagClick(Sender: TObject); private procedure habilitaEdicaoFormPag(Status: boolean); procedure controlaBotoesFormPag; public end; var FrmFormasPagamento: TFrmFormasPagamento; implementation uses uFrmDataModule; {$R *.lfm} { TFrmFormasPagamento } procedure TFrmFormasPagamento.BtnIncFormPagClick(Sender: TObject); begin FrmDataM.dsFormasPagamento.DataSet.Insert; controlaBotoesFormPag; habilitaEdicaoFormPag(True); end; procedure TFrmFormasPagamento.BtnAltFormPagClick(Sender: TObject); begin FrmDataM.dsFormasPagamento.DataSet.Edit; controlaBotoesFormPag; habilitaEdicaoFormPag(True); end; procedure TFrmFormasPagamento.BtnCanFormPagClick(Sender: TObject); begin FrmDataM.dsFormasPagamento.DataSet.Cancel; controlaBotoesFormPag; habilitaEdicaoFormPag(True); end; procedure TFrmFormasPagamento.BtnConFormPagClick(Sender: TObject); begin FrmDataM.dsFormasPagamento.DataSet.Post; controlaBotoesFormPag; habilitaEdicaoFormPag(False); end; procedure TFrmFormasPagamento.BtnExcFormPagClick(Sender: TObject); begin if MessageDlg('Você deseja realmente excluir essa Forma de Pagamento?', mtWarning, [mbYes, mbNo], 0) = mrYes then begin FrmDataM.dsFormasPagamento.DataSet.Delete; controlaBotoesFormPag; habilitaEdicaoFormPag(False); end; end; procedure TFrmFormasPagamento.habilitaEdicaoFormPag(Status: boolean); var i: integer; begin for i := 0 to ComponentCount - 1 do begin if Components[i] is TDBEdit then begin TDBEdit(Components[i]).Enabled := Status; TDBEdit(Components[i]).Color := clWhite; TDBEdit(Components[i]).Font.Color := clBlack; end else if Components[i] is TDBComboBox then begin TDBComboBox(Components[i]).Enabled := Status; TDBComboBox(Components[i]).Color := clWhite; TDBComboBox(Components[i]).Font.Color := clBlack; end; end; end; procedure TFrmFormasPagamento.controlaBotoesFormPag; begin BtnIncFormPag.Enabled:= not (FrmDataM.dsFormasPagamento.State in [dsInsert, dsEdit]); BtnExcFormPag.Enabled:= not (FrmDataM.dsFormasPagamento.DataSet.State in [dsInsert, dsEdit]); BtnAltFormPag.Enabled:= not (FrmDataM.dsFormasPagamento.State in [dsInsert, dsEdit]); BtnCanFormPag.Enabled:= (FrmDataM.dsFormasPagamento.State in [dsInsert, dsEdit]); BtnConFormPag.Enabled:= (FrmDataM.dsFormasPagamento.State in [dsInsert, dsEdit]); end; end.
const eps = 1e-8; // точность function Power (base: double; N: integer): double; // степень N по основанию base var k: integer; P: double; begin P := 1.0; for k := 1 to N do P := P * base; Power := P; end; var n: integer; xold, xnew: double; begin xnew := 0.0; n := 1; repeat xold := xnew; xnew := Power (1.0 + 1.0/n, n); writeln ('limit:', xnew : 20 : 8, ' itteration: ', n); inc (n); until abs (xnew - xold) < eps; writeln ('limit is (approximately):', xnew : 20 : 8); readln; 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) @abstract(Website : http://www.ormbr.com.br) @abstract(Telagram : https://t.me/ormbr) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit ormbr.mapping.explorer; interface uses DB, Rtti, Classes, TypInfo, SysUtils, Generics.Collections, /// ormbr ormbr.mapping.classes, ormbr.mapping.popular, ormbr.mapping.explorerstrategy, ormbr.mapping.repository, ormbr.mapping.register; type TMappingExplorer = class(TMappingExplorerStrategy) private class var FInstance: IMappingExplorerStrategy; private FRepositoryMapping: TMappingRepository; FPopularMapping: TMappingPopular; FTableMapping: TDictionary<string, TTableMapping>; FOrderByMapping: TDictionary<string, TOrderByMapping>; FSequenceMapping: TDictionary<string, TSequenceMapping>; FPrimaryKeyMapping: TDictionary<string, TPrimaryKeyMapping>; FForeingnKeyMapping: TDictionary<string, TForeignKeyMappingList>; FIndexeMapping: TDictionary<string, TIndexeMappingList>; FCheckMapping: TDictionary<string, TCheckMappingList>; FColumnMapping: TDictionary<string, TColumnMappingList>; FCalcFieldMapping: TDictionary<string, TCalcFieldMappingList>; FAssociationMapping: TDictionary<string, TAssociationMappingList>; FJoinColumnMapping: TDictionary<string, TJoinColumnMappingList>; FTriggerMapping: TDictionary<string, TTriggerMappingList>; FViewMapping: TDictionary<string, TViewMapping>; FEnumerationMapping: TDictionary<string, TEnumerationMapping>; constructor CreatePrivate; protected function GetRepositoryMapping: TMappingRepository; override; public { Public declarations } constructor Create; destructor Destroy; override; class function GetInstance: IMappingExplorerStrategy; function GetMappingTable(const AClass: TClass): TTableMapping; override; function GetMappingOrderBy(const AClass: TClass): TOrderByMapping; override; function GetMappingSequence(const AClass: TClass): TSequenceMapping; override; function GetMappingPrimaryKey(const AClass: TClass): TPrimaryKeyMapping; override; function GetMappingForeignKey(const AClass: TClass): TForeignKeyMappingList; override; function GetMappingColumn(const AClass: TClass): TColumnMappingList; override; function GetMappingCalcField(const AClass: TClass): TCalcFieldMappingList; override; function GetMappingAssociation(const AClass: TClass): TAssociationMappingList; override; function GetMappingJoinColumn(const AClass: TClass): TJoinColumnMappingList; override; function GetMappingIndexe(const AClass: TClass): TIndexeMappingList; override; function GetMappingCheck(const AClass: TClass): TCheckMappingList; override; function GetMappingTrigger(const AClass: TClass): TTriggerMappingList; override; function GetMappingView(const AClass: TClass): TViewMapping; override; function GetMappingEnumeration(const ARttiType: TRttiType): TEnumerationMapping; override; property Repository: TMappingRepository read GetRepositoryMapping; end; implementation uses ormbr.mapping.rttiutils, ormbr.objects.helper; { TMappingExplorer } constructor TMappingExplorer.Create; begin raise Exception.Create('Para usar o MappingEntity use o método TMappingExplorerClass.GetInstance()'); end; constructor TMappingExplorer.CreatePrivate; begin inherited; FRepositoryMapping := TMappingRepository.Create(TRegisterClass.GetAllEntityClass, TRegisterClass.GetAllViewClass); FPopularMapping := TMappingPopular.Create(Self); FTableMapping := TObjectDictionary<string, TTableMapping>.Create([doOwnsValues]); FOrderByMapping := TObjectDictionary<string, TOrderByMapping>.Create([doOwnsValues]); FSequenceMapping := TObjectDictionary<string, TSequenceMapping>.Create([doOwnsValues]); FPrimaryKeyMapping := TObjectDictionary<string, TPrimaryKeyMapping>.Create([doOwnsValues]); FForeingnKeyMapping := TObjectDictionary<string, TForeignKeyMappingList>.Create([doOwnsValues]); FColumnMapping := TObjectDictionary<string, TColumnMappingList>.Create([doOwnsValues]); FCalcFieldMapping := TObjectDictionary<string, TCalcFieldMappingList>.Create([doOwnsValues]); FAssociationMapping := TObjectDictionary<string, TAssociationMappingList>.Create([doOwnsValues]); FJoinColumnMapping := TObjectDictionary<string, TJoinColumnMappingList>.Create([doOwnsValues]); FIndexeMapping := TObjectDictionary<string, TIndexeMappingList>.Create([doOwnsValues]); FCheckMapping := TObjectDictionary<string, TCheckMappingList>.Create([doOwnsValues]); FTriggerMapping := TObjectDictionary<string, TTriggerMappingList>.Create([doOwnsValues]); FViewMapping := TObjectDictionary<string, TViewMapping>.Create([doOwnsValues]); FEnumerationMapping := TObjectDictionary<string, TEnumerationMapping>.Create([doOwnsValues]); end; destructor TMappingExplorer.Destroy; begin FPopularMapping.Free; FTableMapping.Free; FOrderByMapping.Free; FSequenceMapping.Free; FPrimaryKeyMapping.Free; FForeingnKeyMapping.Free; FColumnMapping.Free; FCalcFieldMapping.Free; FAssociationMapping.Free; FJoinColumnMapping.Free; FIndexeMapping.Free; FTriggerMapping.Free; FCheckMapping.Free; FViewMapping.Free; FEnumerationMapping.Free; if Assigned(FRepositoryMapping) then FRepositoryMapping.Free; inherited; end; class function TMappingExplorer.GetInstance: IMappingExplorerStrategy; begin if not Assigned(FInstance) then FInstance := TMappingExplorer.CreatePrivate; Result := FInstance; end; function TMappingExplorer.GetMappingPrimaryKey(const AClass: TClass): TPrimaryKeyMapping; var LRttiType: TRttiType; begin if FPrimaryKeyMapping.ContainsKey(AClass.ClassName) then Exit(FPrimaryKeyMapping[AClass.ClassName]); LRttiType := TRttiSingleton.GetInstance.GetRttiType(AClass); Result := FPopularMapping.PopularPrimaryKey(LRttiType); /// Add List if Result <> nil then FPrimaryKeyMapping.Add(AClass.ClassName, Result); end; function TMappingExplorer.GetMappingSequence(const AClass: TClass): TSequenceMapping; var LRttiType: TRttiType; begin if FSequenceMapping.ContainsKey(AClass.ClassName) then Exit(FSequenceMapping[AClass.ClassName]); LRttiType := TRttiSingleton.GetInstance.GetRttiType(AClass); Result := FPopularMapping.PopularSequence(LRttiType); /// Add List if Result <> nil then FSequenceMapping.Add(AClass.ClassName, Result); end; function TMappingExplorer.GetMappingCalcField(const AClass: TClass): TCalcFieldMappingList; var LRttiType: TRttiType; begin if FCalcFieldMapping.ContainsKey(AClass.ClassName) then Exit(FCalcFieldMapping[AClass.ClassName]); LRttiType := TRttiSingleton.GetInstance.GetRttiType(AClass); Result := FPopularMapping.PopularCalcField(LRttiType, AClass); /// Add List if Result <> nil then FCalcFieldMapping.Add(AClass.ClassName, Result); end; function TMappingExplorer.GetMappingCheck(const AClass: TClass): TCheckMappingList; var LRttiType: TRttiType; begin if FCheckMapping.ContainsKey(AClass.ClassName) then Exit(FCheckMapping[AClass.ClassName]); LRttiType := TRttiSingleton.GetInstance.GetRttiType(AClass); Result := FPopularMapping.PopularCheck(LRttiType); /// Add List if Result <> nil then FCheckMapping.Add(AClass.ClassName, Result); end; function TMappingExplorer.GetMappingColumn(const AClass: TClass): TColumnMappingList; var LRttiType: TRttiType; begin if FColumnMapping.ContainsKey(AClass.ClassName) then Exit(FColumnMapping[AClass.ClassName]); LRttiType := TRttiSingleton.GetInstance.GetRttiType(AClass); Result := FPopularMapping.PopularColumn(LRttiType, AClass); /// Add List if Result <> nil then FColumnMapping.Add(AClass.ClassName, Result); end; function TMappingExplorer.GetMappingEnumeration(const ARttiType: TRttiType): TEnumerationMapping; begin if FEnumerationMapping.ContainsKey(ARttiType.Name) then Exit(FEnumerationMapping[ARttiType.Name]); Result := FPopularMapping.PopularEnumeration(ARttiType); /// Add List if Result <> nil then FEnumerationMapping.Add(ARttiType.Name, Result); end; function TMappingExplorer.GetMappingForeignKey(const AClass: TClass): TForeignKeyMappingList; var LRttiType: TRttiType; begin if FForeingnKeyMapping.ContainsKey(AClass.ClassName) then Exit(FForeingnKeyMapping[AClass.ClassName]); LRttiType := TRttiSingleton.GetInstance.GetRttiType(AClass); Result := FPopularMapping.PopularForeignKey(LRttiType); /// Add List if Result <> nil then FForeingnKeyMapping.Add(AClass.ClassName, Result); end; function TMappingExplorer.GetMappingIndexe(const AClass: TClass): TIndexeMappingList; var LRttiType: TRttiType; begin if FIndexeMapping.ContainsKey(AClass.ClassName) then Exit(FIndexeMapping[AClass.ClassName]); LRttiType := TRttiSingleton.GetInstance.GetRttiType(AClass); Result := FPopularMapping.PopularIndexe(LRttiType); /// Add List if Result <> nil then FIndexeMapping.Add(AClass.ClassName, Result); end; function TMappingExplorer.GetMappingJoinColumn(const AClass: TClass): TJoinColumnMappingList; var LRttiType: TRttiType; begin if FJoinColumnMapping.ContainsKey(AClass.ClassName) then Exit(FJoinColumnMapping[AClass.ClassName]); LRttiType := TRttiSingleton.GetInstance.GetRttiType(AClass); Result := FPopularMapping.PopularJoinColumn(LRttiType); /// Add List if Result <> nil then FJoinColumnMapping.Add(AClass.ClassName, Result); end; function TMappingExplorer.GetMappingOrderBy(const AClass: TClass): TOrderByMapping; var LRttiType: TRttiType; begin if FOrderByMapping.ContainsKey(AClass.ClassName) then Exit(FOrderByMapping[AClass.ClassName]); LRttiType := TRttiSingleton.GetInstance.GetRttiType(AClass); Result := FPopularMapping.PopularOrderBy(LRttiType); /// Add List if Result <> nil then FOrderByMapping.Add(AClass.ClassName, Result); end; function TMappingExplorer.GetMappingAssociation(const AClass: TClass): TAssociationMappingList; var LRttiType: TRttiType; begin if FAssociationMapping.ContainsKey(AClass.ClassName) then Exit(FAssociationMapping[AClass.ClassName]); LRttiType := TRttiSingleton.GetInstance.GetRttiType(AClass); Result := FPopularMapping.PopularAssociation(LRttiType); /// Add List if Result <> nil then FAssociationMapping.Add(AClass.ClassName, Result); end; function TMappingExplorer.GetMappingTable(const AClass: TClass): TTableMapping; var LRttiType: TRttiType; begin if FTableMapping.ContainsKey(AClass.ClassName) then Exit(FTableMapping[AClass.ClassName]); LRttiType := TRttiSingleton.GetInstance.GetRttiType(AClass); Result := FPopularMapping.PopularTable(LRttiType); /// Add List if Result <> nil then FTableMapping.Add(AClass.ClassName, Result); end; function TMappingExplorer.GetMappingTrigger(const AClass: TClass): TTriggerMappingList; var LRttiType: TRttiType; begin if FTriggerMapping.ContainsKey(AClass.ClassName) then Exit(FTriggerMapping[AClass.ClassName]); LRttiType := TRttiSingleton.GetInstance.GetRttiType(AClass); Result := FPopularMapping.PopularTrigger(LRttiType); /// Add List if Result <> nil then FTriggerMapping.Add(AClass.ClassName, Result); end; function TMappingExplorer.GetMappingView(const AClass: TClass): TViewMapping; var LRttiType: TRttiType; begin if FViewMapping.ContainsKey(AClass.ClassName) then Exit(FViewMapping[AClass.ClassName]); LRttiType := TRttiSingleton.GetInstance.GetRttiType(AClass); Result := FPopularMapping.PopularView(LRttiType); /// Add List if Result <> nil then FViewMapping.Add(AClass.ClassName, Result); end; function TMappingExplorer.GetRepositoryMapping: TMappingRepository; begin Result := FRepositoryMapping; end; end.
unit Aurelius.Engine.ObjectMap; {$I Aurelius.inc} interface uses Generics.Defaults, Generics.Collections, SysUtils, Aurelius.Mapping.Metadata, Aurelius.Mapping.Optimization, Aurelius.Mapping.Explorer; type TObjectIdList = class private FIdKeys: TList<string>; FIdValues: TList<Variant>; FExplorer: TMappingExplorer; function GenerateIdKey(Id: Variant): string; function GetIdValue(Entity: TObject): Variant; public constructor Create(AExplorer: TMappingExplorer); destructor Destroy; override; procedure Add(Entity: TObject); function ContainsValue(Id: Variant): boolean; function ContainsValueOf(Entity: TObject): boolean; function IdValues: TEnumerable<Variant>; end; TCollectionState = class private FItemIds: TObjectIdList; public constructor Create(AExplorer: TMappingExplorer); destructor Destroy; override; property ItemIds: TObjectIdList read FItemIds; end; TObjectState = class private // Contains a map of ColumnName -> ColumnValue (db values, not member values) FValues: TDictionary<string, Variant>; procedure SetValues(const Value: TDictionary<string, Variant>); public destructor Destroy; override; property Values: TDictionary<string, Variant> read FValues write SetValues; end; TMapEntry = class strict private FEntity: TObject; FOldState: TObjectState; private FOldCollections: TDictionary<string, TCollectionState>; property OldState: TObjectState read FOldState write FOldState; public constructor Create; destructor Destroy; override; property Entity: TObject read FEntity write FEntity; end; TObjectMap = class private type TObjectMapKey = string; private FExplorer: TMappingExplorer; FMap: TDictionary<TObjectMapKey, TMapEntry>; FList: TList<TObject>; function GetIdValue(Entity: TObject): Variant; function GenerateKey(Entity: TObject): TObjectMapKey; overload; function GenerateKey(Clazz: TClass; Id: Variant): TObjectMapKey; overload; function BuildEntry(Entity: TObject): TMapEntry; procedure UpdateObjectState(Entity: TObject; State: TObjectState); public constructor Create(AExplorer: TMappingExplorer); virtual; destructor Destroy; override; function IsMapped(Entity: TObject): Boolean; function IsIdMapped(Entity: TObject): Boolean; procedure Add(Entity: TObject); function GetOldState(Entity: TObject): TObjectState; function GetOldCollectionState(Entity: TObject; MemberInfo: TRttiOptimization): TCollectionState; procedure Remove(Entity: TObject); function GetEntry(Entity: TObject): TMapEntry; function Get(Entity: TObject): TObject; function GetById(Clazz: TClass; Id: Variant): TObject; procedure Clear(DestroyObjects: Boolean); function GetList: TList<TObject>; function HasIdValue(Entity: TObject): Boolean; procedure UpdateOldState(Entity: TObject); procedure UpdateCollectionOldState(Entity: TObject; MemberInfo: TRttiOptimization; AListObj: TObject); overload; procedure UpdateCollectionOldState(Entity: TObject; MemberName: string; AListObj: TObject); overload; end; implementation uses Variants, Rtti, Aurelius.Engine.Exceptions, Aurelius.Global.Utils; { TObjectMap } procedure TObjectMap.Add(Entity: TObject); begin if not HasIdValue(Entity) then raise EIdNotSetException.Create(Entity.ClassType); if IsIdMapped(Entity) then raise EEngineInternalError.Create('Cannot add in object map - id already exists'); FMap.Add(GenerateKey(Entity), BuildEntry(Entity)); end; function TObjectMap.BuildEntry(Entity: TObject): TMapEntry; begin Result := TMapEntry.Create; Result.Entity := Entity; end; procedure TObjectMap.UpdateCollectionOldState(Entity: TObject; MemberName: string; AListObj: TObject); var Optimization: TRttiOptimization; begin Optimization := FExplorer.GetOptimization(Entity.ClassType, MemberName); try UpdateCollectionOldState(Entity, Optimization, AListObj); finally Optimization.Free; end; end; // AListObj is used when we want to pass the collection object itself, instead of letting this function to // load it from the member name. This is used in the TObjectManager.LoadProxyValue, because at the time // UpdateCollectionOldState is called, the proxy is not set yet - but we already have the collection object // Code could be later improved for a more generic and clean approach. procedure TObjectMap.UpdateCollectionOldState(Entity: TObject; MemberInfo: TRttiOptimization; AListObj: TObject); var Key: string; Entry: TMapEntry; List: IObjectList; ColState: TCollectionState; I: Integer; begin if not IsMapped(Entity) then Exit; Entry := GetEntry(Entity); Assert(Entry <> nil, 'Cannot update collection. Entity is mapped but Entry not found.'); // Delete old collection state if any Key := MemberInfo.MemberName; if Entry.FOldCollections.ContainsKey(Key) then Entry.FOldCollections.Remove(Key); // get current list if AListObj = nil then AListObj := FExplorer.GetMemberValue(Entity, MemberInfo).AsObject; if (AListObj <> nil) and (FExplorer.IsList(AListObj.ClassType)) then List := FExplorer.AsList(AListObj) else List := nil; // if list is nil (or lazy) avoid saving state if List = nil then Exit; // Add the collection state ColState := TCollectionState.Create(FExplorer); Entry.FOldCollections.Add(Key, ColState); // Update the collection state - list of current id's for I := 0 to List.Count - 1 do if HasIdValue(List.Item(I)) then ColState.ItemIds.Add(List.Item(I)); end; procedure TObjectMap.UpdateObjectState(Entity: TObject; State: TObjectState); begin // Get the current state of column fields. Use Values instead of FValues State.Values := FExplorer.GetColumnValues(Entity); end; procedure TObjectMap.Clear(DestroyObjects: Boolean); var V: TMapEntry; begin for V in FMap.Values do begin if DestroyObjects then V.Entity.Free; end; FMap.Clear; end; constructor TObjectMap.Create(AExplorer: TMappingExplorer); begin FExplorer := AExplorer; FMap := TObjectDictionary<TObjectMapKey, TMapEntry>.Create([doOwnsValues]); FList := TList<TObject>.Create; end; destructor TObjectMap.Destroy; begin Clear(false); FMap.Free; FList.Free; inherited; end; function TObjectMap.GenerateKey(Entity: TObject): TObjectMapKey; begin Result := GenerateKey(Entity.ClassType, GetIdValue(Entity)); end; function TObjectMap.Get(Entity: TObject): TObject; var Entry: TMapEntry; begin Entry := GetEntry(Entity); if Entry <> nil then Result := Entry.Entity else Result := nil; end; function TObjectMap.GenerateKey(Clazz: TClass; Id: Variant): TObjectMapKey; begin Result := Clazz.ClassName; Result := Result + '_' + TUtils.VariantToString(Id); // If you change this, revise TObjectManager.TEngineCursor class end; function TObjectMap.GetById(Clazz: TClass; Id: Variant): TObject; var Key: TObjectMapKey; SubClass: TClass; begin Key := GenerateKey(Clazz, Id); if FMap.ContainsKey(Key) then Result := FMap.Items[Key].Entity else Result := nil; // If class is not mapped, maybe there is a descendant mapped. For example, we're looking for // TAnimal (Id = 1) but maybe there is a TDog (Id=1) which is a valid TAnimal with id=1 if Result = nil then for SubClass in FExplorer.Hierarchy.GetAllSubClasses(Clazz) do begin Result := GetById(SubClass, Id); if Result <> nil then Exit; end; end; function TObjectMap.GetEntry(Entity: TObject): TMapEntry; var Key: TObjectMapKey; begin Key := GenerateKey(Entity); if FMap.ContainsKey(Key) then Result := FMap.Items[Key] else Result := nil; end; function TObjectMap.GetIdValue(Entity: TObject): Variant; begin Result := FExplorer.GetIdValue(Entity); end; function TObjectMap.GetList: TList<TObject>; var V: TMapEntry; begin FList.Clear; for V in FMap.Values do FList.Add(V.Entity); Result := FList; end; function TObjectMap.GetOldCollectionState(Entity: TObject; MemberInfo: TRttiOptimization): TCollectionState; var Entry: TMapEntry; Key: string; begin Entry := GetEntry(Entity); if Entry = nil then Exit(nil); Key := MemberInfo.MemberName; if Entry.FOldCollections.ContainsKey(Key) then Result := Entry.FOldCollections[Key] else Result := nil; end; function TObjectMap.GetOldState(Entity: TObject): TObjectState; begin Result := FMap.Items[GenerateKey(Entity)].OldState; end; function TObjectMap.HasIdValue(Entity: TObject): Boolean; begin Result := FExplorer.HasIdValue(Entity); end; function TObjectMap.IsIdMapped(Entity: TObject): Boolean; begin Result := FMap.ContainsKey(GenerateKey(Entity)); end; function TObjectMap.IsMapped(Entity: TObject): Boolean; begin if not IsIdMapped(Entity) then Exit(False); Result := Get(Entity) = Entity; end; procedure TObjectMap.Remove(Entity: TObject); begin FMap.Remove(GenerateKey(Entity)); end; procedure TObjectMap.UpdateOldState(Entity: TObject); var Entry: TMapEntry; begin Assert(IsMapped(Entity)); Entry := FMap[GenerateKey(Entity)]; if Entry.OldState = nil then Entry.OldState := TObjectState.Create; UpdateObjectState(Entity, Entry.OldState); end; { TObjectState } destructor TObjectState.Destroy; begin SetValues(nil); inherited; end; procedure TObjectState.SetValues(const Value: TDictionary<string, Variant>); begin if FValues <> nil then FValues.Free; FValues := Value; end; { TCollectionState } constructor TCollectionState.Create(AExplorer: TMappingExplorer); begin FItemIds := TObjectIdList.Create(AExplorer); end; destructor TCollectionState.Destroy; begin FItemIds.Free; inherited; end; { TMapEntry } constructor TMapEntry.Create; begin FOldCollections := TObjectDictionary<string, TCollectionState>.Create([doOwnsValues]); FOldState := nil; end; destructor TMapEntry.Destroy; begin FOldCollections.Free; FOldState.Free; inherited; end; { TObjectIdList } procedure TObjectIdList.Add(Entity: TObject); begin FIdKeys.Add(GenerateIdKey(GetIdValue(Entity))); FIdValues.Add(GetIdValue(Entity)); end; function TObjectIdList.ContainsValue(Id: Variant): boolean; begin Result := FIdKeys.Contains(GenerateIdKey(Id)); end; function TObjectIdList.ContainsValueOf(Entity: TObject): boolean; begin Result := ContainsValue(GetIdValue(Entity)); end; constructor TObjectIdList.Create(AExplorer: TMappingExplorer); begin FExplorer := AExplorer; FIdKeys := TList<string>.Create; FIdValues := TList<Variant>.Create; end; destructor TObjectIdList.Destroy; begin FIdKeys.Free; FIdValues.Free; inherited; end; function TObjectIdList.GenerateIdKey(Id: Variant): string; begin Result := TUtils.VariantToString(Id); end; function TObjectIdList.GetIdValue(Entity: TObject): Variant; begin Result := FExplorer.GetIdValue(Entity); end; function TObjectIdList.IdValues: TEnumerable<Variant>; begin Result := FIdValues; end; end.
// Copyright 2018 by John Kouraklis and Contributors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. unit Casbin.Core.Logger.Default; interface uses Casbin.Core.Logger.Base, Casbin.Core.Logger.Types, System.Generics.Collections; type TDefaultLogger = class (TBaseLogger) public procedure log(const aMessage: string); override; end; TDefaultLoggerPool = class (TInterfacedObject, ILoggerPool) private fLoggers: TList<ILogger>; function GetLoggers: TList<ILogger>; procedure SetLoggers(const Value: TList<ILogger>); procedure log(const aMessage: string); public constructor Create; overload; constructor Create(const aLogger: ILogger); overload; destructor Destroy; override; property Loggers: TList<ILogger> read GetLoggers write SetLoggers; end; implementation uses {$IFDEF MSWINDOWS} Winapi.Windows {$ENDIF} ; { TDefaultLogger } procedure TDefaultLogger.log(const aMessage: string); begin inherited; // The default logger does not log anything. // Any descentent classes can use aMessage // if Enabled then // ...log the message... if fEnableConsole then {$IFDEF MSWINDOWS} OutputDebugString(PChar(aMessage)) {$ELSE} raise Exception.Create('Not implemented yet'); {$ENDIF} end; constructor TDefaultLoggerPool.Create; begin inherited; fLoggers:=TList<ILogger>.Create; fLoggers.Add(TDefaultLogger.Create); end; constructor TDefaultLoggerPool.Create(const aLogger: ILogger); begin self.Create; // PALOFF if assigned(aLogger) then fLoggers.Add(aLogger); end; destructor TDefaultLoggerPool.Destroy; begin fLoggers.Free; inherited; end; function TDefaultLoggerPool.GetLoggers: TList<ILogger>; begin result:=fLoggers; end; procedure TDefaultLoggerPool.log(const aMessage: string); var logger: ILogger; begin for logger in fLoggers do if logger.Enabled then logger.log(aMessage); end; procedure TDefaultLoggerPool.SetLoggers(const Value: TList<ILogger>); begin if assigned(Value) then fLoggers:=Value; end; end.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.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.Win32.GameInput; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} {$m+} interface {$if defined(Windows)} uses {$if defined(Windows)} Windows, {$elseif defined(Unix)} BaseUnix,UnixType,dl, {$ifend} SysUtils, Classes, PasMP, PasVulkan.Types; const FACILITY_GAMEINPUT=906; GAMEINPUT_E_DEVICE_DISCONNECTED=TpvUInt32($838a0001); GAMEINPUT_E_DEVICE_NOT_FOUND=TpvUInt32($838a0002); GAMEINPUT_E_READING_NOT_FOUND=TpvUInt32($838a0003); GAMEINPUT_E_REFERENCE_READING_TOO_OLD=TpvUInt32($838a0004); GAMEINPUT_E_TIMESTAMP_OUT_OF_RANGE=TpvUInt32($838a0005); GAMEINPUT_E_INSUFFICIENT_FORCE_FEEDBACK_RESOURCES=TpvUInt32($838a0006); type TGameInputKind=TpvUInt32; const GameInputKindUnknown=$00000000; GameInputKindRawDeviceReport=$00000001; GameInputKindControllerAxis=$00000002; GameInputKindControllerButton=$00000004; GameInputKindControllerSwitch=$00000008; GameInputKindController=$0000000E; GameInputKindKeyboard=$00000010; GameInputKindMouse=$00000020; GameInputKindTouch=$00000100; GameInputKindMotion=$00001000; GameInputKindArcadeStick=$00010000; GameInputKindFlightStick=$00020000; GameInputKindGamepad=$00040000; GameInputKindRacingWheel=$00080000; GameInputKindUiNavigation=$01000000; type TGameInputEnumerationKind=TpvUInt32; const GameInputNoEnumeration=0; GameInputAsyncEnumeration=1; GameInputBlockingEnumeration=2; type TGameInputFocusPolicy=TpvUInt32; const GameInputDefaultFocusPolicy=$00000000; GameInputDisableBackgroundInput=$00000001; GameInputExclusiveForegroundInput=$00000002; type TGameInputSwitchKind=TpvInt32; const GameInputUnknownSwitchKind=-1; GameInput2WaySwitch=0; GameInput4WaySwitch=1; GameInput8WaySwitch=2; type TGameInputSwitchPosition=TpvUInt32; PGameInputSwitchPosition=^TGameInputSwitchPosition; const GameInputSwitchCenter=0; GameInputSwitchUp=1; GameInputSwitchUpRight=2; GameInputSwitchRight=3; GameInputSwitchDownRight=4; GameInputSwitchDown=5; GameInputSwitchDownLeft=6; GameInputSwitchLeft=7; GameInputSwitchUpLeft=8; type TGameInputKeyboardKind=TpvInt32; const GameInputUnknownKeyboard=-1; GameInputAnsiKeyboard=0; GameInputIsoKeyboard=1; GameInputKsKeyboard=2; GameInputAbntKeyboard=3; GameInputJisKeyboard=4; type TGameInputMouseButtons=TpvUInt32; const GameInputMouseNone=$00000000; GameInputMouseLeftButton=$00000001; GameInputMouseRightButton=$00000002; GameInputMouseMiddleButton=$00000004; GameInputMouseButton4=$00000008; GameInputMouseButton5=$00000010; GameInputMouseWheelTiltLeft=$00000020; GameInputMouseWheelTiltRight=$00000040; type TGameInputTouchShape=TpvInt32; const GameInputTouchShapeUnknown=-1; GameInputTouchShapePoint=0; GameInputTouchShape1DLinear=1; GameInputTouchShape1DRadial=2; GameInputTouchShape1DIrregular=3; GameInputTouchShape2DRectangular=4; GameInputTouchShape2DElliptical=5; GameInputTouchShape2DIrregular=6; type TGameInputMotionAccuracy=TpvUInt32; const GameInputMotionAccuracyUnknown=-1; GameInputMotionUnavailable=0; GameInputMotionUnreliable=1; GameInputMotionApproximate=2; GameInputMotionAccurate=3; type TGameInputArcadeStickButtons=TpvUInt32; const GameInputArcadeStickNone=$00000000; GameInputArcadeStickMenu=$00000001; GameInputArcadeStickView=$00000002; GameInputArcadeStickUp=$00000004; GameInputArcadeStickDown=$00000008; GameInputArcadeStickLeft=$00000010; GameInputArcadeStickRight=$00000020; GameInputArcadeStickAction1=$00000040; GameInputArcadeStickAction2=$00000080; GameInputArcadeStickAction3=$00000100; GameInputArcadeStickAction4=$00000200; GameInputArcadeStickAction5=$00000400; GameInputArcadeStickAction6=$00000800; GameInputArcadeStickSpecial1=$00001000; GameInputArcadeStickSpecial2=$00002000; type TGameInputFlightStickButtons=TpvUInt32; const GameInputFlightStickNone=$00000000; GameInputFlightStickMenu=$00000001; GameInputFlightStickView=$00000002; GameInputFlightStickFirePrimary=$00000004; GameInputFlightStickFireSecondary=$00000008; type TGameInputGamepadButtons=TpvUInt32; const GameInputGamepadNone=$00000000; GameInputGamepadMenu=$00000001; GameInputGamepadView=$00000002; GameInputGamepadA=$00000004; GameInputGamepadB=$00000008; GameInputGamepadX=$00000010; GameInputGamepadY=$00000020; GameInputGamepadDPadUp=$00000040; GameInputGamepadDPadDown=$00000080; GameInputGamepadDPadLeft=$00000100; GameInputGamepadDPadRight=$00000200; GameInputGamepadLeftShoulder=$00000400; GameInputGamepadRightShoulder=$00000800; GameInputGamepadLeftThumbstick=$00001000; GameInputGamepadRightThumbstick=$00002000; type TGameInputRacingWheelButtons=TpvUInt32; const GameInputRacingWheelNone=$00000000; GameInputRacingWheelMenu=$00000001; GameInputRacingWheelView=$00000002; GameInputRacingWheelPreviousGear=$00000004; GameInputRacingWheelNextGear=$00000008; GameInputRacingWheelDpadUp=$00000010; GameInputRacingWheelDpadDown=$00000020; GameInputRacingWheelDpadLeft=$00000040; GameInputRacingWheelDpadRight=$00000080; type TGameInputUiNavigationButtons=TpvUInt32; const GameInputUiNavigationNone=$00000000; GameInputUiNavigationMenu=$00000001; GameInputUiNavigationView=$00000002; GameInputUiNavigationAccept=$00000004; GameInputUiNavigationCancel=$00000008; GameInputUiNavigationUp=$00000010; GameInputUiNavigationDown=$00000020; GameInputUiNavigationLeft=$00000040; GameInputUiNavigationRight=$00000080; GameInputUiNavigationContext1=$00000100; GameInputUiNavigationContext2=$00000200; GameInputUiNavigationContext3=$00000400; GameInputUiNavigationContext4=$00000800; GameInputUiNavigationPageUp=$00001000; GameInputUiNavigationPageDown=$00002000; GameInputUiNavigationPageLeft=$00004000; GameInputUiNavigationPageRight=$00008000; GameInputUiNavigationScrollUp=$00010000; GameInputUiNavigationScrollDown=$00020000; GameInputUiNavigationScrollLeft=$00040000; GameInputUiNavigationScrollRight=$00080000; type TGameInputDeviceStatus=TpvUInt32; const GameInputDeviceNoStatus=$00000000; GameInputDeviceConnected=$00000001; GameInputDeviceInputEnabled=$00000002; GameInputDeviceOutputEnabled=$00000004; GameInputDeviceRawIoEnabled=$00000008; GameInputDeviceAudioCapture=$00000010; GameInputDeviceAudioRender=$00000020; GameInputDeviceSynchronized=$00000040; GameInputDeviceWireless=$00000080; GameInputDeviceUserIdle=$00100000; GameInputDeviceAnyStatus=$00FFFFFF; type TGameInputBatteryStatus=TpvInt32; const GameInputBatteryUnknown=-1; GameInputBatteryNotPresent=0; GameInputBatteryDischarging=1; GameInputBatteryIdle=2; GameInputBatteryCharging=3; type TGameInputDeviceFamily=TpvInt32; const GameInputFamilyVirtual=-1; GameInputFamilyAggregate=0; GameInputFamilyXboxOne=1; GameInputFamilyXbox360=2; GameInputFamilyHid=3; GameInputFamilyI8042=4; type TGameInputDeviceCapabilities=TpvUInt32; const GameInputDeviceCapabilityNone=$00000000; GameInputDeviceCapabilityAudio=$00000001; GameInputDeviceCapabilityPluginModule=$00000002; GameInputDeviceCapabilityPowerOff=$00000004; GameInputDeviceCapabilitySynchronization=$00000008; GameInputDeviceCapabilityWireless=$00000010; type TGameInputRawDeviceReportKind=TpvUInt32; const GameInputRawInputReport=0; GameInputRawOutputReport=1; GameInputRawFeatureReport=2; type TGameInputRawDeviceReportItemFlags=TpvUInt32; const GameInputDefaultItem=$00000000; GameInputConstantItem=$00000001; GameInputArrayItem=$00000002; GameInputRelativeItem=$00000004; GameInputWraparoundItem=$00000008; GameInputNonlinearItem=$00000010; GameInputStableItem=$00000020; GameInputNullableItem=$00000040; GameInputVolatileItem=$00000080; GameInputBufferedItem=$00000100; type TGameInputRawDeviceItemCollectionKind=TpvInt32; const GameInputUnknownItemCollection=-1; GameInputPhysicalItemCollection=0; GameInputApplicationItemCollection=1; GameInputLogicalItemCollection=2; GameInputReportItemCollection=3; GameInputNamedArrayItemCollection=4; GameInputUsageSwitchItemCollection=5; GameInputUsageModifierItemCollection=6; type TGameInputRawDevicePhysicalUnitKind=TpvInt32; const GameInputPhysicalUnitUnknown=-1; GameInputPhysicalUnitNone=0; GameInputPhysicalUnitTime=1; GameInputPhysicalUnitFrequency=2; GameInputPhysicalUnitLength=3; GameInputPhysicalUnitVelocity=4; GameInputPhysicalUnitAcceleration=5; GameInputPhysicalUnitMass=6; GameInputPhysicalUnitMomentum=7; GameInputPhysicalUnitForce=8; GameInputPhysicalUnitPressure=9; GameInputPhysicalUnitAngle=10; GameInputPhysicalUnitAngularVelocity=11; GameInputPhysicalUnitAngularAcceleration=12; GameInputPhysicalUnitAngularMass=13; GameInputPhysicalUnitAngularMomentum=14; GameInputPhysicalUnitAngularTorque=15; GameInputPhysicalUnitElectricCurrent=16; GameInputPhysicalUnitElectricCharge=17; GameInputPhysicalUnitElectricPotential=18; GameInputPhysicalUnitEnergy=19; GameInputPhysicalUnitPower=20; GameInputPhysicalUnitTemperature=21; GameInputPhysicalUnitLuminousIntensity=22; GameInputPhysicalUnitLuminousFlux=23; GameInputPhysicalUnitIlluminance=24; type TGameInputLabel=TpvInt32; const GameInputLabelUnknown=-1; GameInputLabelNone=0; GameInputLabelXboxGuide=1; GameInputLabelXboxBack=2; GameInputLabelXboxStart=3; GameInputLabelXboxMenu=4; GameInputLabelXboxView=5; GameInputLabelXboxA=7; GameInputLabelXboxB=8; GameInputLabelXboxX=9; GameInputLabelXboxY=10; GameInputLabelXboxDPadUp=11; GameInputLabelXboxDPadDown=12; GameInputLabelXboxDPadLeft=13; GameInputLabelXboxDPadRight=14; GameInputLabelXboxLeftShoulder=15; GameInputLabelXboxLeftTrigger=16; GameInputLabelXboxLeftStickButton=17; GameInputLabelXboxRightShoulder=18; GameInputLabelXboxRightTrigger=19; GameInputLabelXboxRightStickButton=20; GameInputLabelXboxPaddle1=21; GameInputLabelXboxPaddle2=22; GameInputLabelXboxPaddle3=23; GameInputLabelXboxPaddle4=24; GameInputLabelLetterA=25; GameInputLabelLetterB=26; GameInputLabelLetterC=27; GameInputLabelLetterD=28; GameInputLabelLetterE=29; GameInputLabelLetterF=30; GameInputLabelLetterG=31; GameInputLabelLetterH=32; GameInputLabelLetterI=33; GameInputLabelLetterJ=34; GameInputLabelLetterK=35; GameInputLabelLetterL=36; GameInputLabelLetterM=37; GameInputLabelLetterN=38; GameInputLabelLetterO=39; GameInputLabelLetterP=40; GameInputLabelLetterQ=41; GameInputLabelLetterR=42; GameInputLabelLetterS=43; GameInputLabelLetterT=44; GameInputLabelLetterU=45; GameInputLabelLetterV=46; GameInputLabelLetterW=47; GameInputLabelLetterX=48; GameInputLabelLetterY=49; GameInputLabelLetterZ=50; GameInputLabelNumber0=51; GameInputLabelNumber1=52; GameInputLabelNumber2=53; GameInputLabelNumber3=54; GameInputLabelNumber4=55; GameInputLabelNumber5=56; GameInputLabelNumber6=57; GameInputLabelNumber7=58; GameInputLabelNumber8=59; GameInputLabelNumber9=60; GameInputLabelArrowUp=61; GameInputLabelArrowUpRight=62; GameInputLabelArrowRight=63; GameInputLabelArrowDownRight=64; GameInputLabelArrowDown=65; GameInputLabelArrowDownLLeft=66; GameInputLabelArrowLeft=67; GameInputLabelArrowUpLeft=68; GameInputLabelArrowUpDown=69; GameInputLabelArrowLeftRight=70; GameInputLabelArrowUpDownLeftRight=71; GameInputLabelArrowClockwise=72; GameInputLabelArrowCounterClockwise=73; GameInputLabelArrowReturn=74; GameInputLabelIconBranding=75; GameInputLabelIconHome=76; GameInputLabelIconMenu=77; GameInputLabelIconCross=78; GameInputLabelIconCircle=79; GameInputLabelIconSquare=80; GameInputLabelIconTriangle=81; GameInputLabelIconStar=82; GameInputLabelIconDPadUp=83; GameInputLabelIconDPadDown=84; GameInputLabelIconDPadLeft=85; GameInputLabelIconDPadRight=86; GameInputLabelIconDialClockwise=87; GameInputLabelIconDialCounterClockwise=88; GameInputLabelIconSliderLeftRight=89; GameInputLabelIconSliderUpDown=90; GameInputLabelIconWheelUpDown=91; GameInputLabelIconPlus=92; GameInputLabelIconMinus=93; GameInputLabelIconSuspension=94; GameInputLabelHome=95; GameInputLabelGuide=96; GameInputLabelMode=97; GameInputLabelSelect=98; GameInputLabelMenu=99; GameInputLabelView=100; GameInputLabelBack=101; GameInputLabelStart=102; GameInputLabelOptions=103; GameInputLabelShare=104; GameInputLabelUp=105; GameInputLabelDown=106; GameInputLabelLeft=107; GameInputLabelRight=108; GameInputLabelLB=109; GameInputLabelLT=110; GameInputLabelLSB=111; GameInputLabelL1=112; GameInputLabelL2=113; GameInputLabelL3=114; GameInputLabelRB=115; GameInputLabelRT=116; GameInputLabelRSB=117; GameInputLabelR1=118; GameInputLabelR2=119; GameInputLabelR3=120; GameInputLabelP1=121; GameInputLabelP2=122; GameInputLabelP3=123; GameInputLabelP4=124; type TGameInputLocation=TpvInt32; const GameInputLocationUnknown=-1; GameInputLocationChassis=0; GameInputLocationDisplay=1; GameInputLocationAxis=2; GameInputLocationButton=3; GameInputLocationSwitch=4; GameInputLocationKey=5; GameInputLocationTouchPad=6; type TGameInputFeedbackAxes=TpvUInt32; const GameInputFeedbackAxisNone=$00000000; GameInputFeedbackAxisLinearX=$00000001; GameInputFeedbackAxisLinearY=$00000002; GameInputFeedbackAxisLinearZ=$00000004; GameInputFeedbackAxisAngularX=$00000008; GameInputFeedbackAxisAngularY=$00000010; GameInputFeedbackAxisAngularZ=$00000020; GameInputFeedbackAxisNormal=$00000040; type TGameInputFeedbackEffectState=TpvUInt32; const GameInputFeedbackStopped=0; GameInputFeedbackRunning=1; GameInputFeedbackPaused=2; type TGameInputForceFeedbackEffectKind=TpvUInt32; const GameInputForceFeedbackConstant=0; GameInputForceFeedbackRamp=1; GameInputForceFeedbackSineWave=2; GameInputForceFeedbackSquareWave=3; GameInputForceFeedbackTriangleWave=4; GameInputForceFeedbackSawtoothUpWave=5; GameInputForceFeedbackSawtoothDownWave=6; GameInputForceFeedbackSpring=7; GameInputForceFeedbackFriction=8; GameInputForceFeedbackDamper=9; GameInputForceFeedbackInertia=10; type TGameInputRumbleMotors=TpvUInt32; const GameInputRumbleNone=$00000000; GameInputRumbleLowFrequency=$00000001; GameInputRumbleHighFrequency=$00000002; GameInputRumbleLeftTrigger=$00000004; GameInputRumbleRightTrigger=$00000008; type TGameInputCallbackToken=TpvUInt64; PGameInputCallbackToken=^TGameInputCallbackToken; const GAMEINPUT_CURRENT_CALLBACK_TOKEN_VALUE=TpvUInt64($ffffffffffffffff); GAMEINPUT_INVALID_CALLBACK_TOKEN_VALUE=TpvUInt64($0000000000000000); type TAPP_LOCAL_DEVICE_ID=record value:array[0..31] of TpvUInt8; end; PAPP_LOCAL_DEVICE_ID=^TAPP_LOCAL_DEVICE_ID; IGameInput=interface; PIGameInput=^IGameInput; IGameInputDevice=interface; PIGameInputDevice=^IGameInputDevice; IGameInputReading=interface; PIGameInputReading=^IGameInputReading; IGameInputDispatcher=interface; PIGameInputDispatcher=^IGameInputDispatcher; IGameInputForceFeedbackEffect=interface; PIGameInputForceFeedbackEffect=^IGameInputForceFeedbackEffect; IGameInputRawDeviceReport=interface; PIGameInputRawDeviceReport=^IGameInputRawDeviceReport; TGameInputReadingCallback=procedure(callbackToken:TGameInputCallbackToken;context:TpvPointer;reading:IGameInputReading;HasOverrunOccurred:BOOL); {$ifdef cpu386}stdcall;{$endif} TGameInputDeviceCallback=procedure(callbackToken:TGameInputCallbackToken;context:TpvPointer;device:IGameInputDevice;timestamp:TpvUInt64;currentStatus,previousStatus:TGameInputDeviceStatus); {$ifdef cpu386}stdcall;{$endif} TGameInputGuideButtonCallback=procedure(callbackToken:TGameInputCallbackToken;context:TpvPointer;device:IGameInputDevice;timestamp:TpvUInt64;isPressed:BOOL); {$ifdef cpu386}stdcall;{$endif} TGameInputKeyboardLayoutCallback=procedure(callbackToken:TGameInputCallbackToken;context:TpvPointer;device:IGameInputDevice;timestamp:TpvUInt64;currentLayout,previousLayout:TpvUInt32); {$ifdef cpu386}stdcall;{$endif} TGameInputKeyState=record scanCode:TpvUInt32; codePoint:TpvUInt32; virtualKey:TpvUInt8; isDeadKey:BOOL; end; PGameInputKeyState=^TGameInputKeyState; TGameInputMouseState=record buttons:TGameInputMouseButtons; positionX:TpvInt64; positionY:TpvInt64; wheelX:TpvInt64; wheelY:TpvInt64; end; PGameInputMouseState=^TGameInputMouseState; TGameInputTouchState=record touchId:TpvUInt64; sensorIndex:TpvUInt32; positionX:TpvFloat; positionY:TpvFloat; pressure:TpvFloat; proximity:TpvFloat; contactRectTop:TpvFloat; contactRectLeft:TpvFloat; contactRectRight:TpvFloat; contactRectBottom:TpvFloat; end; PGameInputTouchState=^TGameInputTouchState; TGameInputMotionState=record accelerationX:TpvFloat; accelerationY:TpvFloat; accelerationZ:TpvFloat; angularVelocityX:TpvFloat; angularVelocityY:TpvFloat; angularVelocityZ:TpvFloat; magneticFieldX:TpvFloat; magneticFieldY:TpvFloat; magneticFieldZ:TpvFloat; orientationW:TpvFloat; orientationX:TpvFloat; orientationY:TpvFloat; orientationZ:TpvFloat; accelerometerAccuracy:TGameInputMotionAccuracy; gyroscopeAccuracy:TGameInputMotionAccuracy; magnetometerAccuracy:TGameInputMotionAccuracy; orientationAccuracy:TGameInputMotionAccuracy; end; PGameInputMotionState=^TGameInputMotionState; TGameInputArcadeStickState=record buttons:TGameInputArcadeStickButtons; end; PGameInputArcadeStickState=^TGameInputArcadeStickState; TGameInputFlightStickState=record buttons:TGameInputFlightStickButtons; hatSwitch:TGameInputSwitchPosition; roll:TpvFloat; pitch:TpvFloat; yaw:TpvFloat; throttle:TpvFloat; end; PGameInputFlightStickState=^TGameInputFlightStickState; TGameInputGamepadState=record buttons:TGameInputGamepadButtons; leftTrigger:TpvFloat; rightTrigger:TpvFloat; leftThumbstickX:TpvFloat; leftThumbstickY:TpvFloat; rightThumbstickX:TpvFloat; rightThumbstickY:TpvFloat; end; PGameInputGamepadState=^TGameInputGamepadState; TGameInputRacingWheelState=record buttons:TGameInputRacingWheelButtons; patternShifterGear:TpvInt32; wheel:TpvFloat; throttle:TpvFloat; brake:TpvFloat; clutch:TpvFloat; handbrake:TpvFloat; end; PGameInputRacingWheelState=^TGameInputRacingWheelState; TGameInputUiNavigationState=record buttons:TGameInputUiNavigationButtons; end; PGameInputUiNavigationState=^TGameInputUiNavigationState; TGameInputBatteryState=record chargeRate:TpvFloat; maxChargeRate:TpvFloat; remainingCapacity:TpvFloat; fullChargeCapacity:TpvFloat; status:TGameInputBatteryStatus; end; PGameInputBatteryState=^TGameInputBatteryState; TGameInputString=record sizeInBytes:TpvUInt32; codePointCount:TpvUInt32; data:PAnsiChar; end; PGameInputString=^TGameInputString; TGameInputUsage=record page:TpvUInt16; id:TpvUInt16; end; PGameInputUsage=^TGameInputUsage; TGameInputVersion=record major:TpvUInt16; minor:TpvUInt16; build:TpvUInt16; revision:TpvUInt16; end; PGameInputVersion=^TGameInputVersion; PGameInputRawDeviceItemCollectionInfo=^TGameInputRawDeviceItemCollectionInfo; TGameInputRawDeviceItemCollectionInfo=record kind:TGameInputRawDeviceItemCollectionKind; childCount:TpvUInt32; siblingCount:TpvUInt32; usageCount:TpvUInt32; usages:PGameInputUsage; parent:PGameInputRawDeviceItemCollectionInfo; firstSibling:PGameInputRawDeviceItemCollectionInfo; previousSibling:PGameInputRawDeviceItemCollectionInfo; nextSibling:PGameInputRawDeviceItemCollectionInfo; lastSibling:PGameInputRawDeviceItemCollectionInfo; firstChild:PGameInputRawDeviceItemCollectionInfo; lastChild:PGameInputRawDeviceItemCollectionInfo; end; TGameInputRawDeviceReportItemInfo=record bitOffset:TpvUInt32; bitSize:TpvUInt32; logicalMin:TpvInt64; logicalMax:TpvInt64; physicalMin:TpvDouble; physicalMax:TpvDouble; physicalUnits:TGameInputRawDevicePhysicalUnitKind; rawPhysicalUnits:TpvUInt32; rawPhysicalUnitsExponent:TpvInt32; flags:TGameInputRawDeviceReportItemFlags; usageCount:TpvUInt32; usages:PGameInputUsage; collection:PGameInputRawDeviceItemCollectionInfo; itemString:PGameInputString; end; PGameInputRawDeviceReportItemInfo=^TGameInputRawDeviceReportItemInfo; TGameInputRawDeviceReportInfo=record kind:TGameInputRawDeviceReportKind; id:TpvUInt32; size:TpvUInt32; itemCount:TpvUInt32; items:PGameInputRawDeviceReportItemInfo; end; PGameInputRawDeviceReportInfo=^TGameInputRawDeviceReportInfo; TGameInputControllerAxisInfo=record mappedInputKinds:TGameInputKind; label_:TGameInputLabel; isContinuous:bool; isNonlinear:bool; isQuantized:bool; hasRestValue:bool; restValue:TpvFloat; resolution:TpvUInt64; legacyDInputIndex:TpvUInt16; legacyHidIndex:TpvUInt16; rawReportIndex:TpvUInt32; inputReport:PGameInputRawDeviceReportInfo; inputReportItem:PGameInputRawDeviceReportItemInfo; end; PGameInputControllerAxisInfo=^TGameInputControllerAxisInfo; TGameInputControllerButtonInfo=record mappedInputKinds:TGameInputKind; label_:TGameInputLabel; legacyDInputIndex:TpvUInt16; legacyHidIndex:TpvUInt16; rawReportIndex:TpvUInt32; inputReport:PGameInputRawDeviceReportInfo; inputReportItem:PGameInputRawDeviceReportItemInfo; end; PGameInputControllerButtonInfo=^TGameInputControllerButtonInfo; TGameInputControllerSwitchInfo=record mappedInputKinds:TGameInputKind; label_:TGameInputLabel; positionLabels:array[0..8] of TGameInputLabel; kind:TGameInputSwitchKind; legacyDInputIndex:TpvUInt16; legacyHidIndex:TpvUInt16; rawReportIndex:TpvUInt32; inputReport:PGameInputRawDeviceReportInfo; inputReportItem:PGameInputRawDeviceReportItemInfo; end; PGameInputControllerSwitchInfo=^TGameInputControllerSwitchInfo; TGameInputKeyboardInfo=record kind:TGameInputKeyboardKind; layout:TpvUInt32; keyCount:TpvUInt32; functionKeyCount:TpvUInt32; maxSimultaneousKeys:TpvUInt32; platformType:TpvUInt32; platformSubtype:TpvUInt32; nativeLanguage:PGameInputString; end; PGameInputKeyboardInfo=^TGameInputKeyboardInfo; TGameInputMouseInfo=record supportedButtons:TGameInputMouseButtons; sampleRate:TpvUInt32; sensorDpi:TpvUInt32; hasWheelX:bool; hasWheelY:bool; end; PGameInputMouseInfo=^TGameInputMouseInfo; TGameInputTouchSensorInfo=record mappedInputKinds:TGameInputKind; label_:TGameInputLabel; location:TGameInputLocation; locationId:TpvUInt32; resolutionX:TpvUInt64; resolutionY:TpvUInt64; shape:TGameInputTouchShape; aspectRatio:TpvFloat; orientation:TpvFloat; physicalWidth:TpvFloat; physicalHeight:TpvFloat; maxPressure:TpvFloat; maxProximity:TpvFloat; maxTouchPoints:TpvUInt32; end; PGameInputTouchSensorInfo=^TGameInputTouchSensorInfo; TGameInputMotionInfo=record maxAcceleration:TpvFloat; maxAngularVelocity:TpvFloat; maxMagneticFieldStrength:TpvFloat; end; PGameInputMotionInfo=^TGameInputMotionInfo; TGameInputArcadeStickInfo=record menuButtonLabel:TGameInputLabel; viewButtonLabel:TGameInputLabel; stickUpLabel:TGameInputLabel; stickDownLabel:TGameInputLabel; stickLeftLabel:TGameInputLabel; stickRightLabel:TGameInputLabel; actionButton1Label:TGameInputLabel; actionButton2Label:TGameInputLabel; actionButton3Label:TGameInputLabel; actionButton4Label:TGameInputLabel; actionButton5Label:TGameInputLabel; actionButton6Label:TGameInputLabel; specialButton1Label:TGameInputLabel; specialButton2Label:TGameInputLabel; end; PGameInputArcadeStickInfo=^TGameInputArcadeStickInfo; TGameInputFlightStickInfo=record menuButtonLabel:TGameInputLabel; viewButtonLabel:TGameInputLabel; firePrimaryButtonLabel:TGameInputLabel; fireSecondaryButtonLabel:TGameInputLabel; hatSwitchKind:TGameInputSwitchKind; end; PGameInputFlightStickInfo=^TGameInputFlightStickInfo; TGameInputGamepadInfo=record menuButtonLabel:TGameInputLabel; viewButtonLabel:TGameInputLabel; aButtonLabel:TGameInputLabel; bButtonLabel:TGameInputLabel; xButtonLabel:TGameInputLabel; yButtonLabel:TGameInputLabel; dpadUpLabel:TGameInputLabel; dpadDownLabel:TGameInputLabel; dpadLeftLabel:TGameInputLabel; dpadRightLabel:TGameInputLabel; leftShoulderButtonLabel:TGameInputLabel; rightShoulderButtonLabel:TGameInputLabel; leftThumbstickButtonLabel:TGameInputLabel; rightThumbstickButtonLabel:TGameInputLabel; end; PGameInputGamepadInfo=^TGameInputGamepadInfo; TGameInputRacingWheelInfo=record menuButtonLabel:TGameInputLabel; viewButtonLabel:TGameInputLabel; previousGearButtonLabel:TGameInputLabel; nextGearButtonLabel:TGameInputLabel; dpadUpLabel:TGameInputLabel; dpadDownLabel:TGameInputLabel; dpadLeftLabel:TGameInputLabel; dpadRightLabel:TGameInputLabel; hasClutch:bool; hasHandbrake:bool; hasPatternShifter:bool; minPatternShifterGear:TpvInt32; maxPatternShifterGear:TpvInt32; maxWheelAngle:TpvFloat; end; PGameInputRacingWheelInfo=^TGameInputRacingWheelInfo; TGameInputUiNavigationInfo=record menuButtonLabel:TGameInputLabel; viewButtonLabel:TGameInputLabel; acceptButtonLabel:TGameInputLabel; cancelButtonLabel:TGameInputLabel; upButtonLabel:TGameInputLabel; downButtonLabel:TGameInputLabel; leftButtonLabel:TGameInputLabel; rightButtonLabel:TGameInputLabel; contextButton1Label:TGameInputLabel; contextButton2Label:TGameInputLabel; contextButton3Label:TGameInputLabel; contextButton4Label:TGameInputLabel; pageUpButtonLabel:TGameInputLabel; pageDownButtonLabel:TGameInputLabel; pageLeftButtonLabel:TGameInputLabel; pageRightButtonLabel:TGameInputLabel; scrollUpButtonLabel:TGameInputLabel; scrollDownButtonLabel:TGameInputLabel; scrollLeftButtonLabel:TGameInputLabel; scrollRightButtonLabel:TGameInputLabel; guideButtonLabel:TGameInputLabel; end; PGameInputUiNavigationInfo=^TGameInputUiNavigationInfo; TGameInputForceFeedbackMotorInfo=record supportedAxes:TGameInputFeedbackAxes; location:TGameInputLocation; locationId:TpvUInt32; maxSimultaneousEffects:TpvUInt32; isConstantEffectSupported:bool; isRampEffectSupported:bool; isSineWaveEffectSupported:bool; isSquareWaveEffectSupported:bool; isTriangleWaveEffectSupported:bool; isSawtoothUpWaveEffectSupported:bool; isSawtoothDownWaveEffectSupported:bool; isSpringEffectSupported:bool; isFrictionEffectSupported:bool; isDamperEffectSupported:bool; isInertiaEffectSupported:bool; end; PGameInputForceFeedbackMotorInfo=^TGameInputForceFeedbackMotorInfo; TGameInputHapticWaveformInfo=record usage:TGameInputUsage; isDurationSupported:bool; isIntensitySupported:bool; isRepeatSupported:bool; isRepeatDelaySupported:bool; defaultDuration:TpvUInt64; end; PGameInputHapticWaveformInfo=^TGameInputHapticWaveformInfo; TGameInputHapticFeedbackMotorInfo=record mappedRumbleMotors:TGameInputRumbleMotors; location:TGameInputLocation; locationId:TpvUInt32; waveformCount:TpvUInt32; waveformInfo:PGameInputHapticWaveformInfo; end; PGameInputHapticFeedbackMotorInfo=^TGameInputHapticFeedbackMotorInfo; TGameInputDeviceInfo=record infoSize:TpvUInt32; vendorId:TpvUInt16; productId:TpvUInt16; revisionNumber:TpvUInt16; interfaceNumber:TpvUInt8; collectionNumber:TpvUInt8; usage:TGameInputUsage; hardwareVersion:TGameInputVersion; firmwareVersion:TGameInputVersion; deviceId:TAPP_LOCAL_DEVICE_ID; deviceRootId:TAPP_LOCAL_DEVICE_ID; deviceFamily:TGameInputDeviceFamily; capabilities:TGameInputDeviceCapabilities; supportedInput:TGameInputKind; supportedRumbleMotors:TGameInputRumbleMotors; inputReportCount:TpvUInt32; outputReportCount:TpvUInt32; featureReportCount:TpvUInt32; controllerAxisCount:TpvUInt32; controllerButtonCount:TpvUInt32; controllerSwitchCount:TpvUInt32; touchPointCount:TpvUInt32; touchSensorCount:TpvUInt32; forceFeedbackMotorCount:TpvUInt32; hapticFeedbackMotorCount:TpvUInt32; deviceStringCount:TpvUInt32; deviceDescriptorSize:TpvUInt32; inputReportInfo:PGameInputRawDeviceReportInfo; outputReportInfo:PGameInputRawDeviceReportInfo; featureReportInfo:PGameInputRawDeviceReportInfo; controllerAxisInfo:PGameInputControllerAxisInfo; controllerButtonInfo:PGameInputControllerButtonInfo; controllerSwitchInfo:PGameInputControllerSwitchInfo; keyboardInfo:PGameInputKeyboardInfo; mouseInfo:PGameInputMouseInfo; touchSensorInfo:PGameInputTouchSensorInfo; motionInfo:PGameInputMotionInfo; arcadeStickInfo:PGameInputArcadeStickInfo; flightStickInfo:PGameInputFlightStickInfo; gamepadInfo:PGameInputGamepadInfo; racingWheelInfo:PGameInputRacingWheelInfo; uiNavigationInfo:PGameInputUiNavigationInfo; forceFeedbackMotorInfo:PGameInputForceFeedbackMotorInfo; hapticFeedbackMotorInfo:PGameInputHapticFeedbackMotorInfo; displayName:PGameInputString; deviceStrings:PGameInputString; deviceDescriptorData:TpvPointer; end; PGameInputDeviceInfo=^TGameInputDeviceInfo; TGameInputForceFeedbackEnvelope=record attackDuration:TpvUInt64; sustainDuration:TpvUInt64; releaseDuration:TpvUInt64; attackGain:TpvFloat; sustainGain:TpvFloat; releaseGain:TpvFloat; playCount:TpvUInt32; repeatDelay:TpvUInt64; end; PGameInputForceFeedbackEnvelope=^TGameInputForceFeedbackEnvelope; TGameInputForceFeedbackMagnitude=record linearX:TpvFloat; linearY:TpvFloat; linearZ:TpvFloat; angularX:TpvFloat; angularY:TpvFloat; angularZ:TpvFloat; normal:TpvFloat; end; PGameInputForceFeedbackMagnitude=^TGameInputForceFeedbackMagnitude; TGameInputForceFeedbackConditionParams=record magnitude:PGameInputForceFeedbackMagnitude; positiveCoefficient:TpvFloat; negativeCoefficient:TpvFloat; maxPositiveMagnitude:TpvFloat; maxNegativeMagnitude:TpvFloat; deadZone:TpvFloat; bias:TpvFloat; end; PGameInputForceFeedbackConditionParams=^TGameInputForceFeedbackConditionParams; TGameInputForceFeedbackConstantParams=record envelope:TGameInputForceFeedbackEnvelope; magnitude:TGameInputForceFeedbackMagnitude; end; PGameInputForceFeedbackConstantParams=^TGameInputForceFeedbackConstantParams; TGameInputForceFeedbackPeriodicParams=record envelope:TGameInputForceFeedbackEnvelope; magnitude:TGameInputForceFeedbackMagnitude; frequency:TpvFloat; phase:TpvFloat; bias:TpvFloat; end; PGameInputForceFeedbackPeriodicParams=^TGameInputForceFeedbackPeriodicParams; TGameInputForceFeedbackRampParams=record envelope:TGameInputForceFeedbackEnvelope; startMagnitude:TGameInputForceFeedbackMagnitude; endMagnitude:TGameInputForceFeedbackMagnitude; end; PGameInputForceFeedbackRampParams=^TGameInputForceFeedbackRampParams; TGameInputForceFeedbackParams=record kind:TGameInputForceFeedbackEffectKind; data:record case TGameInputForceFeedbackEffectKind of GameInputForceFeedbackConstant:( constant:TGameInputForceFeedbackConstantParams; ); GameInputForceFeedbackRamp:( ramp:TGameInputForceFeedbackRampParams; ); GameInputForceFeedbackSineWave:( sineWave:TGameInputForceFeedbackPeriodicParams; ); GameInputForceFeedbackSquareWave:( squareWave:TGameInputForceFeedbackPeriodicParams; ); GameInputForceFeedbackTriangleWave:( triangleWave:TGameInputForceFeedbackPeriodicParams; ); GameInputForceFeedbackSawtoothUpWave:( sawtoothUpWave:TGameInputForceFeedbackPeriodicParams; ); GameInputForceFeedbackSawtoothDownWave:( sawtoothDownWave:TGameInputForceFeedbackPeriodicParams; ); GameInputForceFeedbackSpring:( spring:TGameInputForceFeedbackConditionParams; ); GameInputForceFeedbackFriction:( friction:TGameInputForceFeedbackConditionParams; ); GameInputForceFeedbackDamper:( damper:TGameInputForceFeedbackConditionParams; ); GameInputForceFeedbackInertia:( inertia:TGameInputForceFeedbackConditionParams; ); end; end; PGameInputForceFeedbackParams=^TGameInputForceFeedbackParams; TGameInputHapticFeedbackParams=record waveformIndex:TpvUInt32; duration:TpvUInt64; intensity:TpvFloat; playCount:TpvUInt32; repeatDelay:TpvUInt64; end; PGameInputHapticFeedbackParams=^TGameInputHapticFeedbackParams; TGameInputRumbleParams=record lowFrequency:TpvFloat; highFrequency:TpvFloat; leftTrigger:TpvFloat; rightTrigger:TpvFloat; end; PGameInputRumbleParams=^TGameInputRumbleParams; IGameInput=interface(IUnknown)['{11BE2A7E-4254-445A-9C09-FFC40F006918}'] function GetCurrentTimestamp:TpvUInt64; {$ifdef cpu386}stdcall;{$endif} function GetCurrentReading(inputKind:TGameInputKind;device:IGameInputDevice;out reading:IGameInputReading):HRESULT; {$ifdef cpu386}stdcall;{$endif} function GetNextReading(referenceReading:IGameInputReading;inputKind:TGameInputKind;device:IGameInputDevice;out reading:IGameInputReading):HRESULT; {$ifdef cpu386}stdcall;{$endif} function GetPreviousReading(referenceReading:IGameInputReading;inputKind:TGameInputKind;device:IGameInputDevice;out reading:IGameInputReading):HRESULT; {$ifdef cpu386}stdcall;{$endif} function GetTemporalReading(timeStamp:TpvUInt64;device:IGameInputDevice;out reading:IGameInputReading):HRESULT; {$ifdef cpu386}stdcall;{$endif} function RegisterReadingCallback(device:IGameInputDevice;inputKind:TGameInputKind;analogThreshold:TpvFloat;context:TpvPointer;callbackFunc:TGameInputReadingCallback;callbackToken:PGameInputCallbackToken):HRESULT; {$ifdef cpu386}stdcall;{$endif} function RegisterDeviceCallback(device:IGameInputDevice;inputKind:TGameInputKind;statusFilter:TGameInputDeviceStatus;enumerationKind:TGameInputEnumerationKind;context:TpvPointer;callbackFunc:TGameInputDeviceCallback;callbackToken:PGameInputCallbackToken):HRESULT; {$ifdef cpu386}stdcall;{$endif} function RegisterGuideButtonCallback(device:IGameInputDevice;context:TpvPointer;callbackFunc:TGameInputGuideButtonCallback;callbackToken:PGameInputCallbackToken):HRESULT; {$ifdef cpu386}stdcall;{$endif} function RegisterKeyboardLayoutCallback(device:IGameInputDevice;context:TpvPointer;callbackFunc:TGameInputKeyboardLayoutCallback;callbackToken:PGameInputCallbackToken):HRESULT; {$ifdef cpu386}stdcall;{$endif} procedure StopCallback(callbackToken:TGameInputCallbackToken); {$ifdef cpu386}stdcall;{$endif} function UnregisterCallback(callbackToken:TGameInputCallbackToken;timeoutInMicroseconds:TpvUInt64):BOOL; {$ifdef cpu386}stdcall;{$endif} function CreateDispatcher(out dispatcher:IGameInputDispatcher):HRESULT; {$ifdef cpu386}stdcall;{$endif} function CreateAggregateDevice(inputKind:TGameInputKind;out device:IGameInputDevice):HRESULT; {$ifdef cpu386}stdcall;{$endif} function FindDeviceFromId(value:PAPP_LOCAL_DEVICE_ID;out device:IGameInputDevice):HRESULT; {$ifdef cpu386}stdcall;{$endif} function FindDeviceFromObject(value:IUnknown;out device:IGameInputDevice):HRESULT; {$ifdef cpu386}stdcall;{$endif} function FindDeviceFromPlatformHandle(value:THANDLE;out device:IGameInputDevice):HRESULT; {$ifdef cpu386}stdcall;{$endif} function FindDeviceFromPlatformString(value:LPCWSTR;out device:IGameInputDevice):HRESULT; {$ifdef cpu386}stdcall;{$endif} function EnableOemDeviceSupport(vendorId,productId:TpvUInt16;interfaceNumber,collectionNumber:TpvUInt8):HRESULT; {$ifdef cpu386}stdcall;{$endif} procedure SetFocusPolicy(policy:TGameInputFocusPolicy); {$ifdef cpu386}stdcall;{$endif} end; IGameInputReading=interface(IUnknown)['{2156947A-E1FA-4DE0-A30B-D812931DBD8D}'] function GetInputKind:TGameInputKind; {$ifdef cpu386}stdcall;{$endif} function GetSequenceNumber(inputKind:TGameInputKind):TpvUInt64; {$ifdef cpu386}stdcall;{$endif} function GetTimeStamp:TpvUInt64; {$ifdef cpu386}stdcall;{$endif} procedure GetDevice(out device:IGameInputDevice); {$ifdef cpu386}stdcall;{$endif} function GetRawReport(out report:IGameInputRawDeviceReport):bool; {$ifdef cpu386}stdcall;{$endif} function GetControllerAxisCount:TpvUInt32; {$ifdef cpu386}stdcall;{$endif} function GetControllerAxisState(stateArrayCount:TpvUInt32;stateArray:PpvFloat):TpvUInt32; {$ifdef cpu386}stdcall;{$endif} function GetControllerButtonCount:TpvUInt32; {$ifdef cpu386}stdcall;{$endif} function GetControllerButtonState(stateArrayCount:TpvUInt32;stateArray:PBool):TpvUInt32; {$ifdef cpu386}stdcall;{$endif} function GetControllerSwitchCount:TpvUInt32; {$ifdef cpu386}stdcall;{$endif} function GetControllerSwitchState(stateArrayCount:TpvUInt32;stateArray:PGameInputSwitchPosition):TpvUInt32; {$ifdef cpu386}stdcall;{$endif} function GetKeyCount:TpvUInt32; {$ifdef cpu386}stdcall;{$endif} function GetKeyState(stateArrayCount:TpvUInt32;stateArray:PGameInputKeyState):TpvUInt32; {$ifdef cpu386}stdcall;{$endif} function GetMouseState(state:PGameInputMouseState):Bool; {$ifdef cpu386}stdcall;{$endif} function GetTouchCount:TpvUInt32; {$ifdef cpu386}stdcall;{$endif} function GetTouchState(stateArrayCount:TpvUInt32;stateArray:PGameInputTouchState):TpvUInt32; {$ifdef cpu386}stdcall;{$endif} function GetMotionState(state:PGameInputMotionState):Bool; {$ifdef cpu386}stdcall;{$endif} function GetArcadeStickState(state:PGameInputArcadeStickState):Bool; {$ifdef cpu386}stdcall;{$endif} function GetFlightStickState(state:PGameInputFlightStickState):Bool; {$ifdef cpu386}stdcall;{$endif} function GetGamepadState(state:PGameInputGamepadState):Bool; {$ifdef cpu386}stdcall;{$endif} function GetRacingWheelState(state:PGameInputRacingWheelState):Bool; {$ifdef cpu386}stdcall;{$endif} function GetUiNavigationState(state:PGameInputUiNavigationState):Bool; {$ifdef cpu386}stdcall;{$endif} end; IGameInputDevice=interface(IUnknown)['{31DD86FB-4C1B-408A-868F-439B3CD47125}'] function GetDeviceInfo:PGameInputDeviceInfo; {$ifdef cpu386}stdcall;{$endif} function GetDeviceStatus:TGameInputDeviceStatus; {$ifdef cpu386}stdcall;{$endif} procedure GetBatteryState(state:PGameInputBatteryState); {$ifdef cpu386}stdcall;{$endif} function CreateForceFeedbackEffect(motorIndex:TpvUInt32;params:PGameInputForceFeedbackParams;out effect:IGameInputForceFeedbackEffect):HRESULT; {$ifdef cpu386}stdcall;{$endif} function IsForceFeedbackMotorPoweredOn(motorIndex:TpvUInt32):Bool; {$ifdef cpu386}stdcall;{$endif} procedure SetForceFeedbackMotorGain(motorIndex:TpvUInt32;masterGain:TpvFloat); {$ifdef cpu386}stdcall;{$endif} procedure SetHapticMotorState(motorIndex:TpvUInt32;params:PGameInputHapticFeedbackParams); {$ifdef cpu386}stdcall;{$endif} procedure SetRumbleState(params:PGameInputRumbleParams); {$ifdef cpu386}stdcall;{$endif} procedure SetInputSynchronizationState(enabled:Bool); {$ifdef cpu386}stdcall;{$endif} procedure SendInputSynchronizationHint; {$ifdef cpu386}stdcall;{$endif} procedure PowerOff; {$ifdef cpu386}stdcall;{$endif} function CreateRawDeviceReport(reportId:TpvUInt32;reportKind:TGameInputRawDeviceReportKind;out report:IGameInputRawDeviceReport):HRESULT; {$ifdef cpu386}stdcall;{$endif} function GetRawDeviceFeature(reportId:TpvUInt32;out report:IGameInputRawDeviceReport):HRESULT; {$ifdef cpu386}stdcall;{$endif} function SetRawDeviceFeature(report:IGameInputRawDeviceReport):HRESULT; {$ifdef cpu386}stdcall;{$endif} function SendRawDeviceOutput(report:IGameInputRawDeviceReport):HRESULT; {$ifdef cpu386}stdcall;{$endif} function SendRawDeviceOutputWithResponse(requestReport:IGameInputRawDeviceReport;out responseReport:IGameInputRawDeviceReport):HRESULT; {$ifdef cpu386}stdcall;{$endif} function ExecuteRawDeviceIoControl(controlCode:TpvUInt32;inputBufferSize:TpvSizeUInt;inputBuffer:TpvPointer;outputBufferSize:TpvSizeUInt;outputBuffer:TpvPointer;outputSize:TpvSizeUInt):HRESULT; {$ifdef cpu386}stdcall;{$endif} function AcquireExclusiveRawDeviceAccess(timeoutInMicroseconds:TpvUInt64):Bool; {$ifdef cpu386}stdcall;{$endif} procedure ReleaseExclusiveRawDeviceAccess; {$ifdef cpu386}stdcall;{$endif} end; IGameInputDispatcher=interface(IUnknown)['{415EED2E-98CB-42C2-8F28-B94601074E31}'] function Dispatch(quotaInMicroseconds:TpvUInt64):Bool; {$ifdef cpu386}stdcall;{$endif} function OpenWaitHandle(waitHandle:PHandle):HRESULT; {$ifdef cpu386}stdcall;{$endif} end; IGameInputForceFeedbackEffect=interface(IUnknown)['{51BDA05E-F742-45D9-B085-9444AE48381D}'] procedure GetDevice(out device:IGameInputDevice); {$ifdef cpu386}stdcall;{$endif} function GetMotorIndex:TpvUInt32; {$ifdef cpu386}stdcall;{$endif} function GetGain:TpvFloat; {$ifdef cpu386}stdcall;{$endif} procedure SetGain(gain:TpvFloat); {$ifdef cpu386}stdcall;{$endif} procedure GetParams(params:PGameInputForceFeedbackParams); {$ifdef cpu386}stdcall;{$endif} function SetParams(params:PGameInputForceFeedbackParams):Bool; {$ifdef cpu386}stdcall;{$endif} function GetState:TGameInputFeedbackEffectState; {$ifdef cpu386}stdcall;{$endif} procedure SetState(state:TGameInputFeedbackEffectState); {$ifdef cpu386}stdcall;{$endif} end; IGameInputRawDeviceReport=interface(IUnknown)['{61F08CF1-1FFC-40CA-A2B8-E1AB8BC5B6DC}'] procedure GetDevice(out device:IGameInputDevice); {$ifdef cpu386}stdcall;{$endif} function GetReportInfo:PGameInputRawDeviceReportInfo; {$ifdef cpu386}stdcall;{$endif} function GetRawDataSize:TpvSizeUInt; {$ifdef cpu386}stdcall;{$endif} function GetRawData(bufferSize:TpvSizeUInt;buffer:Pointer):TpvSizeUInt; {$ifdef cpu386}stdcall;{$endif} function SetRawData(bufferSize:TpvSizeUInt;buffer:Pointer):Bool; {$ifdef cpu386}stdcall;{$endif} function GetItemValue(itemIndex:TpvUInt32;value:PpvInt64):Bool; {$ifdef cpu386}stdcall;{$endif} function SetItemValue(itemIndex:TpvUInt32;value:TpvInt64):Bool; {$ifdef cpu386}stdcall;{$endif} function ResetItemValue(itemIndex:TpvUInt32):Bool; {$ifdef cpu386}stdcall;{$endif} function ResetAllItems:Bool; {$ifdef cpu386}stdcall;{$endif} end; TGameInputCreate=function(out gameInput:IGameInput):HRESULT; {$ifdef cpu386}stdcall;{$endif} var GameInputCreate:TGameInputCreate=nil; GameInputLibrary:THandle=THandle(0); {$ifend} implementation {$if defined(Windows)} procedure InitializeGameInput; begin GameInputLibrary:=LoadLibrary('gameinput.dll'); if GameInputLibrary<>THandle(0) then begin @GameInputCreate:=GetProcAddress(GameInputLibrary,'GameInputCreate'); end; end; procedure FinalizeGameInput; begin if GameInputLibrary<>THandle(0) then begin try FreeLibrary(GameInputLibrary); finally GameInputLibrary:=THandle(0); end; end; end; initialization InitializeGameInput; finalization FinalizeGameInput; {$ifend} end.
(* GAME MESSAGES *) function TFormGaple.PlayerNameError: integer; begin result := Application.MessageBox ('Player name must be unique.'#13'Please correct the players name. '#13, 'Name Conflict',MB_OK or MB_ICONERROR); end; function TFormGaple.NoNetPlayerError: integer; begin result := Application.MessageBox ('No network player involved.'#13'Cannot start game server.'#13, 'No Player',MB_OK or MB_ICONERROR); end; function TFormGaple.NoServerError: integer; var s: string; begin s := 'You haven''t enter the server IP address.'#13+ 'Please enter IP address of game server.'; result := Application.MessageBox (PChar(s),'Error',MB_OK or MB_ICONERROR); end; function TFormGaple.WrongCardWarning: integer; var s: string; begin s := 'Your card does not match with any deck cards.'#13+ 'Please select another card that mathes.'#13#13+ 'The deck is expecting value '+IntToStr(DeckGaple.TopValue)+' or '+IntToStr(DeckGaple.BottomValue)+'.'#13; result := Application.MessageBox (PChar(s),'Wrong card', MB_OK or MB_ICONWARNING); end; function TFormGaple.WrongTurnWarning: integer; begin result := Application.MessageBox ('This card belongs to player who is not on the turn.'#13+ 'Please select card of player currently playing.'#13, 'Wrong turn', MB_OK or MB_ICONWARNING); end; function TFormGaple.PassCardQuestion: integer; begin result := Application.MessageBox ('There is no card on your hand that matches with any deck cards.'#13+ 'Are you sure make this card as passing card?'#13, 'Pass card', MB_YESNO or MB_ICONQUESTION); end; function TFormGaple.SelectCardQuestion: integer; begin result := Application.MessageBox ('Your card matches with both sides of the deck cards.'#13+ 'Will you place your card on the top side of the deck?'#13#13+ 'Click Yes, if you want to place your card on the top side. '#13+ 'Click No, if you want to place your card on the bottom side. '#13+ 'Click Cancel, if you want to change or select another card. '#13, 'Select card', MB_YESNOCANCEL or MB_ICONQUESTION); end; function TFormGaple.ApplyChangesInformation: integer; begin result := Application.MessageBox ('The changes will apply after you restart the game or '#13+ 'maximum game scores has reached by the players.', 'Information',MB_OK or MB_ICONINFORMATION); end; function TFormGaple.NoCardInformation: integer; begin result := Application.MessageBox ('There is no card available on your hand.'#13+ 'The game is by passing your turn.'#13, 'No card', MB_OK or MB_ICONINFORMATION); end; function TFormGaple.GameOverInformation: integer; var i: integer; begin for i := 1 to 7 do with TDominoCard(FindComponent('DominoCard'+IntToStr(i))) do if Visible then Scores[GamePlayed].Player1 := Scores[GamePlayed].Player1 + TopValue + BottomValue; for i := 8 to 14 do with TDominoCard(FindComponent('DominoCard'+IntToStr(i))) do if Visible then Scores[GamePlayed].Player2 := Scores[GamePlayed].Player2 + TopValue + BottomValue; for i := 15 to 21 do with TDominoCard(FindComponent('DominoCard'+IntToStr(i))) do if Visible then Scores[GamePlayed].Player3 := Scores[GamePlayed].Player3 + TopValue + BottomValue; for i := 22 to 28 do with TDominoCard(FindComponent('DominoCard'+IntToStr(i))) do if Visible then Scores[GamePlayed].Player4 := Scores[GamePlayed].Player4 + TopValue + BottomValue; FormScore := TFormScore.Create(self); result := FormScore.ShowModal; FormScore.Free; end; function TFormGaple.QuitGameQuestion: integer; begin result := Application.MessageBox ('Current game is still running.'#13+ 'Are you sure want to quit the game?'#13, 'Confirm',MB_YESNO or MB_ICONQUESTION); end;
unit JoyShockLibrary; interface const JS_TYPE_JOYCON_LEFT = 1; JS_TYPE_JOYCON_RIGHT = 2; JS_TYPE_PRO_CONTROLLER = 3; JS_TYPE_DS4 = 4; JS_TYPE_DS = 5; JS_SPLIT_TYPE_LEFT = 1; JS_SPLIT_TYPE_RIGHT = 2; JS_SPLIT_TYPE_FULL = 3; JSMASK_UP = $00001; JSMASK_DOWN = $00002; JSMASK_LEFT = $00004; JSMASK_RIGHT = $00008; JSMASK_PLUS = $00010; JSMASK_OPTIONS = $00010; JSMASK_MINUS = $00020; JSMASK_SHARE = $00020; JSMASK_LCLICK = $00040; JSMASK_RCLICK = $00080; JSMASK_L = $00100; JSMASK_R = $00200; JSMASK_ZL = $00400; JSMASK_ZR = $00800; JSMASK_S = $01000; JSMASK_E = $02000; JSMASK_W = $04000; JSMASK_N = $08000; JSMASK_HOME = $10000; JSMASK_PS = $10000; JSMASK_CAPTURE = $20000; JSMASK_TOUCHPAD_CLICK = $20000; JSMASK_MIC = $40000; JSMASK_SL = $40000; JSMASK_SR = $80000; JSOFFSET_UP = 0; JSOFFSET_DOWN = 1; JSOFFSET_LEFT = 2; JSOFFSET_RIGHT = 3; JSOFFSET_PLUS = 4; JSOFFSET_OPTIONS = 4; JSOFFSET_MINUS = 5; JSOFFSET_SHARE = 5; JSOFFSET_LCLICK = 6; JSOFFSET_RCLICK = 7; JSOFFSET_L = 8; JSOFFSET_R = 9; JSOFFSET_ZL = 10; JSOFFSET_ZR = 11; JSOFFSET_S = 12; JSOFFSET_E = 13; JSOFFSET_W = 14; JSOFFSET_N = 15; JSOFFSET_HOME = 16; JSOFFSET_PS = 16; JSOFFSET_CAPTURE = 17; JSOFFSET_TOUCHPAD_CLICK = 17; JSOFFSET_MIC = 18; JSOFFSET_SL = 18; JSOFFSET_SR = 19; // PS5 Player maps for the DS Player Lightbar; DS5_PLAYER_1 = 4; DS5_PLAYER_2 = 10; DS5_PLAYER_3 = 21; DS5_PLAYER_4 = 27; DS5_PLAYER_5 = 31; type JOY_SHOCK_STATE = record buttons:integer; lTrigger:single; rTrigger:single; stickLX:single; stickLY:single; stickRX:single; stickRY:single; end; IMU_STATE = record accelX:single; accelY:single; accelZ:single; gyroX:single; gyroY:single; gyroZ:single; end; MOTION_STATE = record quatW:single; quatX:single; quatY:single; quatZ:single; accelX:single; accelY:single; accelZ:single; gravX:single; gravY:single; gravZ:single; end; TOUCH_STATE = record t0Id:integer; t1Id:integer; t0Down:boolean; t1Down:boolean; t0X:single; t0Y:single; t1X:single; t1Y:single; end; const jsldll = 'JoyShockLibrary.dll'; type TJslCallback = procedure(deviceId:integer; PrevShockState,CurrentShockState:JOY_SHOCK_STATE; PrevIMUState,CurrentIMUSTate:IMU_STATE; DeltaTime:single); cdecl; TJslTouchCallback = procedure(deviceId:integer; PrevTouchState,CurrentTouchState:TOUCH_STATE; DeltaTime:single); cdecl; PJslCallback = ^TJslCallback; PJslTouchCallback = ^TJslTouchCallback; function JslConnectDevices():integer; cdecl; external jsldll; function JslGetConnectedDeviceHandles(deviceHandleArray:PInteger;size:integer):integer; cdecl; external jsldll; procedure JslDisconnectAndDisposeAll(); cdecl; external jsldll; // get buttons as bits in the following order, using North South East West to name face buttons to avoid ambiguity between Xbox and Nintendo layouts: // $00001: up // $00002: down // $00004: left // $00008: right // $00010: plus // $00020: minus // $00040: left stick click // $00080: right stick click // $00100: L // $00200: R // ZL and ZR are reported as analogue inputs (GetLeftTrigger, GetRightTrigger), because DS4 and XBox controllers use analogue triggers, but we also have them as raw buttons // $00400: ZL // $00800: ZR // $01000: S // $02000: E // $04000: W // $08000: N // $10000: home / PS // $20000: capture / touchpad-click // $40000: SL // $80000: SR // These are the best way to get all the buttons/triggers/sticks, gyro/accelerometer (IMU), orientation/acceleration/gravity (Motion), or touchpad function JslGetSimpleState(deviceId:integer):JOY_SHOCK_STATE; cdecl; external jsldll ; function JslGetIMUState(deviceId:integer):IMU_STATE; cdecl; external jsldll; function JslGetMotionState(deviceId:integer):MOTION_STATE; cdecl; external jsldll; function JslGetTouchState(deviceId:integer):TOUCH_STATE; cdecl; external jsldll; function JslGetButtons(deviceId:integer):integer; cdecl; external jsldll; // get thumbsticks function JslGetLeftX(deviceId:integer):single; cdecl; external jsldll; function JslGetLeftY(deviceId:integer):single; cdecl; external jsldll; function JslGetRightX(deviceId:integer):single; cdecl; external jsldll; function JslGetRightY(deviceId:integer):single; cdecl; external jsldll; // get triggers. Switch controllers don't have analogue triggers, but will report 0.0 or 1.0 so they can be used in the same way as others function JslGetLeftTrigger(deviceId:integer):single; cdecl; external jsldll; function JslGetRightTrigger(deviceId:integer):single; cdecl; external jsldll; // get gyro function JslGetGyroX(deviceId:integer):single; cdecl; external jsldll; function JslGetGyroY(deviceId:integer):single; cdecl; external jsldll; function JslGetGyroZ(deviceId:integer):single; cdecl; external jsldll; // get accelerometor function JslGetAccelX(deviceId:integer):single; cdecl; external jsldll; function JslGetAccelY(deviceId:integer):single; cdecl; external jsldll; function JslGetAccelZ(deviceId:integer):single; cdecl; external jsldll; // get touchpad function JslGetTouchId(deviceId:integer; secondTouch:boolean = false):integer; cdecl; external jsldll; function JslGetTouchDown(deviceId:integer; secondTouch:boolean = false):boolean; cdecl; external jsldll; function JslGetTouchX(deviceId:integer; secondTouch:boolean = false):single; cdecl; external jsldll; function JslGetTouchY(deviceId:integer; secondTouch:boolean = false):single; cdecl; external jsldll; // analog parameters have different resolutions depending on device function JslGetStickStep(deviceId:integer):single; cdecl; external jsldll; function JslGetTriggerStep(deviceId:integer):single; cdecl; external jsldll; function JslGetPollRate(deviceId:integer):single; cdecl; external jsldll; // calibration procedure JslResetContinuousCalibration(deviceId:integer); cdecl; external jsldll; procedure JslStartContinuousCalibration(deviceId:integer); cdecl; external jsldll; procedure JslPauseContinuousCalibration(deviceId:integer); cdecl; external jsldll; procedure JslGetCalibrationOffset(deviceId:integer; var xOffset, yOffset, zOffset: single); cdecl; external jsldll; procedure JslSetCalibrationOffset(deviceId:integer; xOffset, yOffset, zOffset: single);cdecl; external jsldll; // this function will get called for each input event from each controller callback(int, JOY_SHOCK_STATE, JOY_SHOCK_STATE, IMU_STATE, IMU_STATE, float) procedure JslSetCallback(callback:PJslCallback); cdecl; external jsldll; // this function will get called for each input event, even if touch data didn't update callback(int, TOUCH_STATE, TOUCH_STATE, float) procedure JslSetTouchCallback(callback:PJslTouchCallback); cdecl; external jsldll; // what kind of controller is this? function JslGetControllerType(deviceId:integer):integer; cdecl; external jsldll; // is this a left, right, or full controller? function JslGetControllerSplitType(deviceId:integer):integer; cdecl; external jsldll; // what colour is the controller (not all controllers support this; those that don't will report white) function JslGetControllerColour(deviceId:integer):integer; cdecl; external jsldll; // set controller light colour (not all controllers have a light whose colour can be set, but that just means nothing will be done when this is called -- no harm) procedure JslSetLightColour(deviceId:integer; colour:integer); cdecl; external jsldll; // set controller rumble procedure JslSetRumble(deviceId:integer; smallRumble,bigRumble:integer); cdecl; external jsldll; // set controller player number indicator (not all controllers have a number indicator which can be set, but that just means nothing will be done when this is called -- no harm) procedure JslSetPlayerNumber(deviceId:integer; number:integer); cdecl; external jsldll; implementation end.
unit VkApi.Photo; interface // https://vk.com/dev/photo type TVkPhoto = record Id: Cardinal; AlbumId: Integer; OwnerId: Integer; UserId: Cardinal; Photo75: string; Photo130: string; Photo604: string; Photo807: string; Photo1280: string; Photo2560: string; Width: Cardinal; Height: Cardinal; Text: string; Date: TDateTime; end; implementation end.
{$include kode.inc} unit kode_filter_rc2; // http://musicdsp.org/showArchiveComment.php?ArchiveID=185 //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- type KFilter_RC2 = class private v0,v1 : single; c,r : single; public public constructor create; destructor destroy; override; procedure setCutoff(ACutoff:Single); // 0..1 procedure setResonance(AResonance:Single); // 0..1 procedure setFreq(AFreq,ARate:single); procedure setQ(AQ:single); function process(AInput:Single) : Single; end; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- uses math, // power kode_const; //---------- constructor KFilter_RC2.create; begin v0 := 0; v1 := 0; end; //---------- destructor KFilter_RC2.destroy; begin end; //---------- procedure KFilter_RC2.setCutoff(ACutoff:Single); // 0..1 var cutoff : single; begin cutoff := ACutoff * 127; c := power(0.5, (128-cutoff) / 16.0); end; //---------- procedure KFilter_RC2.setResonance(AResonance:Single); // 0..4 var resonance : single; begin resonance := AResonance * 127; r := power(0.5, (resonance+24) / 16.0); end; //---------- procedure KFilter_RC2.setFreq(AFreq,ARate:single); begin c := 2 * Sin ( Pi * AFreq / ARate ); //You can approximate this (tuning error towards nyquist): //c := KODE_PI2*freq/samplerate; end; //---------- procedure KFilter_RC2.setQ(AQ:single); begin r := 1 / AQ; end; //---------- function KFilter_RC2.process(AInput:Single) : Single; var tmp : single; begin {v0 := (1-r*c)*v0 - (c)*v1 + (c)*AInput; v1 := (1-r*c)*v1 + (c)*v0; result := v1;} // This filter has stability issues for high r values. State variable filter // stability limits seem to work fine here. It can also be oversampled for // better stability and wider frequency range (use 0.5*original frequency): v0 := (1-r*c)*v0 - c*v1 + c*AInput; v1 := (1-r*c)*v1 + c*v0; tmp := v1; v0 := (1-r*c)*v0 - c*v1 + c*AInput; v1 := (1-r*c)*v1 + c*v0; result := (tmp+v1)*0.5; end; //---------------------------------------------------------------------- end.
unit InterceptBaseClass_MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, RTTI; type TPerson = class private FBirthDate: TDate; FName: string; procedure SetBirthDate(const Value: TDate); procedure SetName(const Value: string); public property Name: string read FName write SetName; property BirthDate: TDate read FBirthDate write SetBirthDate; function Age: Integer; virtual; function ToString: string; override; end; TFormIntercept = class(TForm) BtnUse: TButton; BtnIntercept: TButton; BtnDisconnect: TButton; Memo1: TMemo; procedure BtnUseClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure BtnInterceptClick(Sender: TObject); procedure BtnDisconnectClick(Sender: TObject); private Person1: TPerson; Vmi: TVirtualMethodInterceptor; public procedure Log (const StrMsg: string); end; var FormIntercept: TFormIntercept; implementation uses System.DateUtils; {$R *.dfm} procedure TFormIntercept.BtnDisconnectClick(Sender: TObject); begin // PPointer(Person1)^ := vmi.OriginalClass; Vmi.Unproxify(Person1); // xe2 only end; procedure TFormIntercept.BtnInterceptClick(Sender: TObject); begin Vmi := TVirtualMethodInterceptor.Create(TPerson); Vmi.OnBefore := procedure(Instance: TObject; Method: TRttiMethod; const Args: TArray<TValue>; out DoInvoke: Boolean; out Result: TValue) begin Log('Before calling ' + Method.Name); if Method.Name = 'Age' then begin Result := 33; DoInvoke := False; end; end; Vmi.OnAfter := procedure(Instance: TObject; Method: TRttiMethod; const Args: TArray<TValue>; var Result: TValue) begin Log('After calling ' + Method.Name); end; Vmi.Proxify(Person1); end; procedure TFormIntercept.BtnUseClick(Sender: TObject); begin // use object Log ('Age: ' + IntToStr (Person1.Age)); Log ('Person: ' + Person1.ToString); Log ('Class: ' + Person1.ClassName); Log ('Base Class: ' + Person1.ClassParent.ClassName); end; { TPerson } function TPerson.Age: Integer; begin Result := YearsBetween (Date, FBirthDate); end; procedure TPerson.SetBirthDate(const Value: TDate); begin FBirthDate := Value; end; procedure TPerson.SetName(const Value: string); begin FName := Value; end; function TPerson.ToString: string; begin Result := FName + ' is ' + IntToStr (Age) + ' years old'; end; procedure TFormIntercept.FormCreate(Sender: TObject); begin Person1 := TPerson.Create; Person1.Name := 'Mark'; Person1.BirthDate := EncodeDate (1984, 5, 14); end; procedure TFormIntercept.Log(const StrMsg: string); begin Memo1.Lines.Add (StrMsg); end; end.
unit AddingUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, StdCtrls, Buttons; type TDlgAddFiles = class(TForm) FileList: TListView; BtnOk: TBitBtn; BtnCancel: TBitBtn; BtnAdd: TBitBtn; BtnDelete: TBitBtn; BtnClear: TBitBtn; Bevel1: TBevel; DlgAddingFiles: TOpenDialog; cbUsePassword: TCheckBox; PasswordEdit: TEdit; cbCompression: TComboBox; Label1: TLabel; BtnComment: TBitBtn; procedure BtnAddClick(Sender: TObject); procedure cbUsePasswordClick(Sender: TObject); procedure BtnDeleteClick(Sender: TObject); procedure BtnClearClick(Sender: TObject); procedure BtnOkClick(Sender: TObject); procedure BtnCommentClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var DlgAddFiles: TDlgAddFiles; implementation uses EditCommentUnit,MainUnit; {$R *.dfm} procedure TDlgAddFiles.BtnAddClick(Sender: TObject); var index:integer; SizeMeter:TFileStream; Size:LongInt; fName:string; ItemIndex:LongInt; begin if not DlgAddingFiles.Execute then Exit; ItemIndex:=FileList.Items.Count; for index:=0 to DlgAddingFiles.Files.Count-1 do begin SizeMeter:=TFileStream.Create(DlgAddingFiles.Files.Strings[Index],fmOpenRead); Size:=SizeMeter.Size; SizeMeter.Free; fName:=DlgAddingFiles.Files.Strings[Index]; FileList.Items.Add.Caption:=ExtractFileName(fName); FileList.Items.Item[ItemIndex].SubItems.Add(IntToStr(size)); FileList.Items.Item[ItemIndex].SubItems.Add(ExtractFileDir(fName)); inc(ItemIndex); end; end; procedure TDlgAddFiles.cbUsePasswordClick(Sender: TObject); begin PasswordEdit.Enabled:=cbUsePassword.Checked; PasswordEdit.Clear; end; procedure TDlgAddFiles.BtnDeleteClick(Sender: TObject); begin FileList.DeleteSelected; end; procedure TDlgAddFiles.BtnClearClick(Sender: TObject); begin FileList.Clear; end; procedure TDlgAddFiles.BtnOkClick(Sender: TObject); begin if (PasswordEdit.Text='') and (cbUsePassword.Checked) then begin MessageBox(Handle,'Password is empty, please insert password or disable!!!', nil,mb_ok+mb_iconstop); exit; end else modalresult:=mrOk; end; procedure TDlgAddFiles.BtnCommentClick(Sender: TObject); begin Application.CreateForm(TDlgEditComment, DlgEditComment); DlgEditComment.Comment.Text:=MainUnit.Comment; if DlgEditComment.ShowModal= mrOk then begin Comment:=DlgEditComment.Comment.Text; end; DlgEditComment.Free; end; end.
{*****************************************************************} { This is a component for placing icons in the notification area } { of the Windows taskbar (aka. the traybar). } { } { It is an expanded version of my CoolTrayIcon component, which } { you will need to make this work. The expanded features allow } { you to easily draw text in the tray icon. } { } { The component is freeware. Feel free to use and improve it. } { I would be pleased to hear what you think. } { } { Troels Jakobsen - delphiuser@get2net.dk } { Copyright (c) 2001 } {*****************************************************************} unit TextTrayIcon; interface uses CoolTrayIcon, Graphics, Classes, Controls; type TOffsetOptions = class(TPersistent) private FOffsetX, FOffsetY, FLineDistance: Integer; FOnChange: TNotifyEvent; // Procedure var. procedure SetOffsetX(Value: Integer); procedure SetOffsetY(Value: Integer); procedure SetLineDistance(Value: Integer); protected procedure Changed; dynamic; published property OffsetX: Integer read FOffsetX write SetOffsetX; property OffsetY: Integer read FOffsetY write SetOffsetY; property LineDistance: Integer read FLineDistance write SetLineDistance; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; TTextTrayIcon = class(TCoolTrayIcon) private FFont: TFont; FColor: TColor; FBorder: Boolean; FBorderColor: TColor; FText: String; FTextBitmap: TBitmap; FOffsetOptions: TOffsetOptions; FShowTextIcon: Boolean; procedure FontChanged(Sender: TObject); procedure SplitText(const Strings: TList); procedure OffsetOptionsChanged(OffsetOptions: TObject); protected procedure Paint; virtual; procedure SetShowTextIcon(Value: Boolean); procedure SetText(Value: String); procedure SetTextBitmap(Value: TBitmap); procedure SetFont(Value: TFont); procedure SetColor(Value: TColor); procedure SetBorder(Value: Boolean); procedure SetBorderColor(Value: TColor); procedure SetOffsetOptions(Value: TOffsetOptions); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Draw; published property ShowTextIcon: Boolean read FShowTextIcon write SetShowTextIcon default true; property Text: String read FText write SetText; property Font: TFont read FFont write SetFont; property Color: TColor read FColor write SetColor default clBtnFace; property Border: Boolean read FBorder write SetBorder; property BorderColor: TColor read FBorderColor write SetBorderColor default clBlack; property Options: TOffsetOptions read FOffsetOptions write SetOffsetOptions; end; procedure Register; implementation uses SysUtils; {------------------- TTextTrayIcon --------------------} procedure TOffsetOptions.Changed; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TOffsetOptions.SetOffsetX(Value: Integer); begin if Value <> FOffsetX then begin FOffsetX := Value; Changed; end; end; procedure TOffsetOptions.SetOffsetY(Value: Integer); begin if Value <> FOffsetY then begin FOffsetY := Value; Changed; end; end; procedure TOffsetOptions.SetLineDistance(Value: Integer); begin if Value <> FLineDistance then begin FLineDistance := Value; Changed; end; end; {------------------- TTextTrayIcon --------------------} constructor TTextTrayIcon.Create(AOwner: TComponent); begin inherited Create(AOwner); FShowTextIcon := true; FTextBitmap := TBitmap.Create; FFont := TFont.Create; FFont.OnChange := FontChanged; FColor := clBtnFace; FBorderColor := clBlack; FOffsetOptions := TOffsetOptions.Create; FOffsetOptions.OnChange := OffsetOptionsChanged; end; destructor TTextTrayIcon.Destroy; begin FFont.Free; FTextBitmap.Free; FOffsetOptions.Free; inherited Destroy; end; procedure TTextTrayIcon.FontChanged(Sender: TObject); { This method is invoked when user assigns to Font (but not when Font is set directly to another TFont var.) } begin Draw; end; procedure TTextTrayIcon.SetShowTextIcon(Value: Boolean); begin FShowTextIcon := Value; Draw; end; procedure TTextTrayIcon.SetText(Value: String); begin FText := Value; Draw; end; procedure TTextTrayIcon.SetTextBitmap(Value: TBitmap); begin FTextBitmap := Value; // Assign? Draw; end; procedure TTextTrayIcon.SetFont(Value: TFont); begin FFont.Assign(Value); Draw; end; procedure TTextTrayIcon.SetColor(Value: TColor); begin FColor := Value; Draw; end; procedure TTextTrayIcon.SetBorder(Value: Boolean); begin FBorder := Value; Draw; end; procedure TTextTrayIcon.SetBorderColor(Value: TColor); begin FBorderColor := Value; Draw; end; procedure TTextTrayIcon.SetOffsetOptions(Value: TOffsetOptions); { This method will only be invoked if the user creates a new TOffsetOptions object. User will probably just set the values of the existing TOffsetOptions object. } begin FOffsetOptions.Assign(Value); Draw; end; procedure TTextTrayIcon.OffsetOptionsChanged(OffsetOptions: TObject); { This method will be invoked when the user changes the values of the existing TOffsetOptions object. } begin Draw; end; procedure TTextTrayIcon.Draw; var Ico: TIcon; begin if FShowTextIcon then // Only redraw if in text mode! begin CycleIcons := False; // We cannot cycle and draw at the same time Paint; // Render FTextBitmap Ico := TIcon.Create; if BitmapToIcon(FTextBitmap, Ico, clNone) then begin Icon.Assign(Ico); Refresh; Ico.Free; end; end; end; procedure TTextTrayIcon.Paint; var Bitmap: TBitmap; Left, Top, LinesTop, LineHeight: Integer; Substr: PChar; Strings: TList; I: Integer; begin Bitmap := Graphics.TBitmap.Create; try Bitmap.Width := 16; Bitmap.Height := 16; // Bitmap.Canvas.TextFlags := 2; // ETO_OPAQUE // Render background rectangle Bitmap.Canvas.Brush.Color := FColor; Bitmap.Canvas.FillRect(Rect(0, 0, 16, 16)); // Render text; check for line breaks Bitmap.Canvas.Font.Assign(FFont); Substr := StrPos(PChar(FText), #13); if Substr = nil then begin // No line breaks Left := (15 - Bitmap.Canvas.TextWidth(FText)) div 2; if FOffsetOptions <> nil then Left := Left + FOffsetOptions.OffsetX; Top := (15 - Bitmap.Canvas.TextHeight(FText)) div 2; if FOffsetOptions <> nil then Top := Top + FOffsetOptions.OffsetY; Bitmap.Canvas.TextOut(Left, Top, FText); end else begin // Line breaks Strings := TList.Create; SplitText(Strings); LineHeight := Bitmap.Canvas.TextHeight(Substr); if FOffsetOptions <> nil then LineHeight := LineHeight + FOffsetOptions.LineDistance; LinesTop := (15 - (LineHeight * Strings.Count)) div 2; if FOffsetOptions <> nil then LinesTop := LinesTop + FOffsetOptions.OffsetY; for I := 0 to Strings.Count -1 do begin Substr := Strings[I]; Left := (15 - Bitmap.Canvas.TextWidth(Substr)) div 2; if FOffsetOptions <> nil then Left := Left + FOffsetOptions.OffsetX; Top := LinesTop + (LineHeight * I); Bitmap.Canvas.TextOut(Left, Top, Substr); end; for I := 0 to Strings.Count -1 do StrDispose(Strings[I]); Strings.Free; end; // Render border if FBorder then begin Bitmap.Canvas.Brush.Color := FBorderColor; Bitmap.Canvas.FrameRect(Rect(0, 0, 16, 16)); end; // Assign the final bitmap FTextBitmap.Assign(Bitmap); finally Bitmap.Free; end; end; procedure TTextTrayIcon.SplitText(const Strings: TList); function PeekedString(S: String): String; var P: Integer; begin P := Pos(#13, S); if P = 0 then Result := S else Result := Copy(S, 1, P-1); end; var Substr: String; P: Integer; S: PChar; begin Strings.Clear; Substr := FText; repeat P := Pos(#13, Substr); if P = 0 then begin S := StrNew(PChar(Substr)); Strings.Add(S); end else begin S := StrNew(PChar(PeekedString(Substr))); Strings.Add(S); Delete(Substr, 1, P); end; until P = 0; end; procedure Register; begin RegisterComponents('Custom', [TTextTrayIcon]); end; end.
unit Aurelius.Sql.MSSQL2000; interface uses Aurelius.Sql.Register, Aurelius.Sql.AnsiSqlGenerator, Aurelius.Sql.Metadata, Aurelius.Sql.Interfaces, Aurelius.Sql.Commands, Aurelius.Sql.BaseTypes, Aurelius.Sql.MSSQL; type TMSSQL2000SQLGenerator = class(TMSSQLSQLGenerator) protected function GenerateInsert(Command: TInsertCommand): string; override; function GenerateGetLastInsertId(SQLField: TSQLField): string; override; function GetSupportedFeatures: TDBFeatures; override; end; implementation uses Variants, SysUtils; function TMSSQL2000SQLGenerator.GenerateGetLastInsertId(SQLField: TSQLField): string; begin Result := 'SELECT CAST(IDENT_CURRENT('+QuotedStr(SQLField.Table.Name)+') AS INT)'; end; function TMSSQL2000SQLGenerator.GenerateInsert(Command: TInsertCommand): string; begin Result := inherited GenerateInsert(Command); { -- eliminato if Command.OutputColumn <> '' then Insert( Format('OUTPUT INSERTED.%s ' + sqlLineBreak, [Command.OutputColumn]), Result, Pos('VALUES (', Result) ); } end; function TMSSQL2000SQLGenerator.GetSupportedFeatures: TDBFeatures; begin Result := AllDBFeatures - [TDBFeature.Sequences,TDBFeature.RetrieveIdOnInsert]; end; initialization TSQLGeneratorRegister.GetInstance.RegisterGenerator(TMSSQL2000SQLGenerator.Create); end.
{AUTEUR : FRANCKY23012301 - 2008 ------- Gratuit pour une utilisation non commerciale} {DEEFAZE - 2009 ------- Codage du tempo} unit MidiWriter; interface uses Forms,SysUtils, Classes, StrUtils, DateUtils, Dialogs; type TFormatMidi = (single_track, multiple_tracks_synchronous, multiple_tracks_asynchronous); TChannel = 0..15; THalfByte = 0..127; THour = 0..23; TMinSec = 0..59; TFr =0..30; TSubFr=0..99; TKey=-7..7; TScale = 0..1; TControllerType =(CtBankSelect=0, CtModulationWheel=1, CtBreathControl=2, CtContinuouscontrollerSharp3=3, CtFootController=4, CtPortamentoTime=5, CtDataEntrySlider=6, CtMainVolume=7, CtStereoBalance=8, CtContinuouscontrollerSharp9=9, CtPan=10, CtExpression=11, CtEffectControl1=12, CtEffectControl2=13, CtContinuouscontrollerSharp14=14, CtContinuouscontrollerSharp15=15, CtGeneralPurposeSlider1=16, CtGeneralPurposeSlider2=17, CtGeneralPurposeSlider3=18, CtGeneralPurposeSlider4=19, CtContinuouscontrollerSharp20=20, CtContinuouscontrollerSharp21=21, CtContinuouscontrollerSharp22=22, CtContinuouscontrollerSharp23=23, CtContinuouscontrollerSharp24=24, CtContinuouscontrollerSharp25=25, CtContinuouscontrollerSharp26=26, CtContinuouscontrollerSharp27=27, CtContinuouscontrollerSharp28=28, CtContinuouscontrollerSharp29=29, CtContinuouscontrollerSharp30=30, CtContinuouscontrollerSharp31=31, CtBankSelectFine=32, CtModulationWheelFine=33, CtBreathControlFine=34, CtContinuouscontrollerSharp3Fine=35, CtFootControllerFine=36, CtPortamentoTimeFine=37, CtDataEntrySliderFineFine=38, CtMainVolumeFine=39, CtStereoBalanceFine=40, CtContinuouscontrollerSharp9Fine=41, CtPanFine=42, CtExpressionFine=43, CtEffectControl1Fine=44, CtEffectControl2Fine=45, CtContinuouscontrollerSharp14Fine=46, CtContinuouscontrollerSharp15Fine=47, CtContinuouscontrollerSharp16=48, CtContinuouscontrollerSharp17=49, CtContinuouscontrollerSharp18=50, CtContinuouscontrollerSharp19=51, CtContinuouscontrollerSharp20Fine=52, CtContinuouscontrollerSharp21Fine=53, CtContinuouscontrollerSharp22Fine=54, CtContinuouscontrollerSharp23Fine=55, CtContinuouscontrollerSharp24Fine=56, CtContinuouscontrollerSharp25Fine=57, CtContinuouscontrollerSharp26Fine=58, CtContinuouscontrollerSharp27Fine=59, CtContinuouscontrollerSharp28Fine=60, CtContinuouscontrollerSharp29Fine=61, CtContinuouscontrollerSharp30Fine=62, CtContinuouscontrollerSharp31Fine=63, CtHoldpedalSwitch=64, CtPortamentoSwitch=65, CtSustenutoPedalSwitch=66, CtSoftPedalSwitch=67, CtLegatoPedalSwitch=68, CtHoldPedal2Switch=69, CtSoundVariation=70, CtSoundTimbre=71, CtSoundReleaseTime=72, CtSoundAttackTime=73, CtSoundBrighness=74, CtSoundControl6=75, CtSoundControl7=76, CtSoundControl8=77, CtSoundControl9=78, CtSoundControl10=79, CtGeneralPurposeButton1=80, CtGeneralPurposeButton2=81, CtGeneralPurposeButton3=82, CtGeneralPurposeButton4=83, CtPortamentoNote=84, CtUndefinedSwitch2=85, CtUndefinedSwitch3=86, CtUndefinedSwitch4=87, CtUndefinedSwitch5=88, CtUndefinedSwitch6=89, CtUndefinedSwitch7=90, CtEffectsLevel=91, CtTremuloLevel=92, CtChorusLevel=93, CtCelesteLevel=94, CtPhaserLevel=95, CtDataentryAd1=96, CtDataentryDel1=97, CtNonRegisteredParameterNumber1=98, CtNonRegisteredParameterNumber2=99, CtRegisteredParameterNumber1=100, CtRegisteredParameterNumber2=101, CtUndefined1=102, CtUndefined2=103, CtUndefined3=104, CtUndefined4=105, CtUndefined5=106, CtUndefined6=107, CtUndefined7=108, CtUndefined8=109, CtUndefined9=110, CtUndefined10=111, CtUndefined11=112, CtUndefined12=113, CtUndefined13=114, CtUndefined14=115, CtUndefined15=116, CtUndefined16=117, CtUndefined17=118, CtUndefined18=119, CtAllSoundOff=120, CtAllControllersOff=121, CtLocalKeyboardSwitch=122, CtAllNotesOff=123, CtOmniModeOff=124, CtOmniModeOn=125, CtMonophonicModeOn=126, CtPolyphonicModeOn=127); TMidiWriter = class(TComponent) private fFormatMidi: TFormatMidi; fNbTracks: Byte; fDivision: word; EventsStream: TMemoryStream; TrackStream: TMemoryStream; Tempo:Integer; protected Function DeltaTimeToTicks(Value:Integer):Integer; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Initialize_Track; procedure Finalize_Track; procedure Create_MidiFile(AFile: string); procedure Add_NoteOn_Event(Const DeltaTime : Integer; Const Channel : TChannel; Const Note, Velocity: THalfByte); procedure Add_NoteOff_Event(Const DeltaTime : Integer; Const Channel : TChannel; Const Note, Velocity: THalfByte); procedure Add_Controller_Event(Const DeltaTime : Integer; Const Channel : TChannel; Const ControllerType: TControllerType; Const Value: THalfByte); procedure Add_ProgramChange_Event(Const DeltaTime : Integer; Const Channel : TChannel; Const Program_Number: THalfByte); procedure Add_ChannelAfterTouch_Event(Const DeltaTime : Integer; Const Channel : TChannel; Const Amount: THalfByte); procedure Add_NoteAftertouch_Event(Const DeltaTime : Integer; Const Channel : TChannel; Const Note, Amount: THalfByte); procedure Add_PitchBend_Event(Const DeltaTime : Integer; Const Channel : TChannel; Const Value:Word); procedure Add_SequenceNumber_Event(Const SeqNmber: Word); procedure Add_Event_String(Const DeltaTime : Integer; Const Event_Type:Byte;Const AText: string); procedure Add_Text_Event(Const DeltaTime : Integer; Const AText: string); procedure Add_CopyrightNotice_Event(Const DeltaTime : Integer; Const AText: string); procedure Add_TrackName_Event(Const DeltaTime : Integer; Const AText: string); procedure Add_InstrumentName_Event(Const DeltaTime : Integer; Const AText: string); procedure Add_Lyrics_Event(Const DeltaTime : Integer; Const AText: string); procedure Add_Marker_Event(Const DeltaTime : Integer; Const AText: string); procedure Add_CuePoint_Event(Const DeltaTime : Integer; Const AText: string); procedure Add_ChannelPrefix_Event(Const DeltaTime : Integer; Const Channel: TChannel); procedure Add_EndOfTrack_Event; procedure Add_SetTempo_Event(Const DeltaTime : Integer; Const BPM: Integer); procedure Add_SMPTEOffset_Event(Const DeltaTime : Integer; Const Hours : THour; Const Mins, Secs : TMinSec; Const Fr:TFr; Const SubFr: TSubFr); procedure Add_TimeSignature_Event(Const DeltaTime : Integer; Const Numer, Denom, Metro, TtNds: byte); procedure Add_KeySignature_Event(Const DeltaTime : Integer; Const Key : TKey; Const Scale: TScale); procedure Add_SequencerSpecific_Event(Const DeltaTime : Integer; Information :Variant); published property NbTracks: Byte Read fNbTracks Write fNbTracks; property FormatMidi: TFormatMidi Read fFormatMidi Write fFormatMidi; property Division: word Read fDivision Write fDivision; end; procedure Register; implementation procedure Register; begin RegisterComponents('MUSIC_PRO', [TMidiWriter]); end; Procedure SwapBytes(Const Data; Count: byte); var B: PByte; E: PByte; T: byte; begin B := PByte(@Data); E := PByte(integer(B) + Count - 1); while integer(B) < integer(E) do begin T := E^; E^ := B^; B^ := T; Inc(B); Dec(E); end; end; function ByteCount(del : Longint) : byte; var d : Longint; b : byte; begin d := del; b := 1; while d >= 128 do begin d := (d shr 7); b := b + 1; end; ByteCount := b; end; procedure VLQ(del : Integer ;AStream:TStream); var d : Longint; w:array of LongInt; tel,k: byte; begin If Not Assigned(AStream) Then Exit; d := del; tel := ByteCount(d); SetLength(W,tel); w[0]:=byte(d and $0000007F); if tel<>1 then for k := 1 to tel-1 do begin d := d shr 7; w[k]:=byte((d and $0000007F) or $80); end; for k:=High(W) DownTo Low(W) Do AStream.Write(w[k],1); end; Procedure WordToLSB_MSB(Value:WORD;AStream:TStream); var MSB,LSB:Byte; begin If Not Assigned(AStream) Then Exit; LSB:=Value and $7f; MSB:=(Value and $3f80) * 2; AStream.Write(LSB,1); AStream.Write(MSB,1); end; Procedure Write_Tempo(Const MPQN: Longword; AStream:TStream); var vMPQN : array[0..2] of Byte; k:Integer; begin If Not Assigned(AStream) Then Exit; vMPQN[0] := Byte($FF And MPQN); vMPQN[1] := Byte($FF And (MPQN shr 8)); vMPQN[2] := Byte($FF And (MPQN shr 16)); for k:=2 DownTo 0 Do AStream.Write(vMPQN[k],1); end; constructor TMidiWriter.Create(AOwner: TComponent); begin inherited Create(AOwner); fFormatMidi := single_track; fNbTracks := 1; fDivision:=96; Tempo:=120; EventsStream := TMemoryStream.Create; end; destructor TMidiWriter.Destroy; begin If Assigned(EventsStream) Then EventsStream.Free; inherited; end; Function TMidiWriter.DeltaTimeToTicks(Value:Integer):Integer; Begin Result :=Value*fDivision*Tempo Div 60000 ; End; procedure TMidiWriter.Initialize_Track; begin EventsStream.Position:=0; end; procedure TMidiWriter.Finalize_Track; Type TTrackHeader=Record ID : Array[0..3] Of Char; Size:LongWord; End; Var TrackHeader:TTrackHeader; begin if not Assigned(EventsStream) then Exit; if not Assigned(TrackStream) then TrackStream := TMemoryStream.Create; with TrackStream do try Add_EndOfTrack_Event; TrackHeader.ID:='MTrk'; TrackHeader.Size:=EventsStream.size; SwapBytes(TrackHeader.Size, SizeOf(TrackHeader.Size)); Write(TrackHeader,8); EventsStream.Position:=0; CopyFrom(EventsStream, EventsStream.Size); While EventsStream.Position<EventsStream.Size Do Application.ProcessMessages; Except Showmessage('Une erreur a eu lieu'); TrackStream.Free; end; end; procedure TMidiWriter.Create_MidiFile(AFile: string); Type TChunkHeader=Record ID : Array[0..3] Of Char; Size:LongWord; Format:Word; NbTracks:Word; Division:Word; End; var MidiStream: TFileStream; ChunkHeader:TChunkHeader; begin if not Assigned(TrackStream) then Exit; MidiStream := TFileStream.Create(AFile, fmCreate); with MidiStream do try ChunkHeader.ID := 'MThd'; ChunkHeader.Size :=6; SwapBytes(ChunkHeader.Size,4); ChunkHeader.Format := 0; case fFormatMidi of single_track: ChunkHeader.Format := 0; multiple_tracks_synchronous: ChunkHeader.Format := 1; multiple_tracks_asynchronous: ChunkHeader.Format := 2; end; SwapBytes(ChunkHeader.Format,2); ChunkHeader.NbTracks :=Self.fNbTracks; SwapBytes(ChunkHeader.NbTracks,2); ChunkHeader.Division :=Self.fDivision; SwapBytes(ChunkHeader.Division,2); Write(ChunkHeader, 14); TrackStream.Position:=0; MidiStream.CopyFrom(TrackStream, 0); finally TrackStream.Free; MidiStream.Free; end; end; {>>MIDI Channel Events} procedure TMidiWriter.Add_NoteOn_Event(Const DeltaTime : Integer; Const Channel : TChannel; Const Note, Velocity: THalfByte); var NoteOn_Val: byte; begin If (not Assigned(EventsStream)) then Exit; With EventsStream Do Begin VLQ(DeltaTimeToTicks(DeltaTime),EventsStream); NoteOn_Val:=144 + Channel; Write(NoteOn_Val,1); Write(Note,1); Write(Velocity,1); End; end; procedure TMidiWriter.Add_NoteOff_Event(Const DeltaTime : Integer; Const Channel : TChannel; Const Note, Velocity: THalfByte); var NoteOff_Val: byte; begin If (not Assigned(EventsStream)) then Exit; With EventsStream Do Begin VLQ(DeltaTimeToTicks(DeltaTime),EventsStream); NoteOff_Val:=128 + Channel; Write(NoteOff_Val,1); Write(Note,1); Write(Velocity,1); End; end; procedure TMidiWriter.Add_Controller_Event(Const DeltaTime : Integer; Const Channel : TChannel; Const ControllerType: TControllerType; Const Value: THalfByte); var Control_Val,Type_Val: byte; begin if (not Assigned(EventsStream)) then Exit; Control_Val:= 176 + Channel; Type_Val:= Ord(ControllerType); With EventsStream Do Begin VLQ(DeltaTimeToTicks(DeltaTime),EventsStream); Write(Control_Val,1); Write(Type_Val,1); Write(Value,1); End; end; procedure TMidiWriter.Add_ProgramChange_Event(Const DeltaTime : Integer; Const Channel : TChannel; Const Program_Number: THalfByte); var PrgrChg_Val:Byte; begin if (not Assigned(EventsStream)) then Exit; With EventsStream Do Begin VLQ(DeltaTimeToTicks(DeltaTime),EventsStream); PrgrChg_Val:=192 + Channel; Write(PrgrChg_Val,1); Write(Program_Number,1); End; end; procedure TMidiWriter.Add_ChannelAfterTouch_Event(Const DeltaTime : Integer; Const Channel : TChannel; Const Amount: THalfByte); var AfterTouch_Val:Byte; begin if (not Assigned(EventsStream)) then Exit; With EventsStream Do Begin VLQ(DeltaTimeToTicks(DeltaTime),EventsStream); AfterTouch_Val:=208 + Channel; Write(AfterTouch_Val,1); Write(Amount,1); End; end; procedure TMidiWriter.Add_NoteAftertouch_Event(Const DeltaTime : Integer; Const Channel : TChannel; Const Note, Amount: THalfByte); var AfterTouch_Val:Byte; begin if (not Assigned(EventsStream)) then Exit; With EventsStream Do Begin VLQ(DeltaTimeToTicks(DeltaTime),EventsStream); AfterTouch_Val:=160 + Channel; Write(AfterTouch_Val,1); Write(Note,1); Write(Amount,1); End; end; procedure TMidiWriter.Add_PitchBend_Event(Const DeltaTime : Integer; Const Channel : TChannel; Const Value:Word); var PitchBend_Val: byte; begin if (not Assigned(TrackStream)) then Exit; With EventsStream Do Begin VLQ(DeltaTimeToTicks(DeltaTime),EventsStream); PitchBend_Val:=224 + Channel; Write(PitchBend_Val,1); WordToLSB_MSB(Value,EventsStream); End; end; procedure TMidiWriter.Add_SequenceNumber_Event(Const SeqNmber: Word); var Meta_Val,Event_Type: byte; begin if (not Assigned(EventsStream)) then Exit; With EventsStream Do Begin VLQ(0,EventsStream); Meta_Val:=255; Write(Meta_Val,1); Event_Type:= 0; Write(Event_Type,1); VLQ(SizeOf(SeqNmber),EventsStream); WordToLSB_MSB(SeqNmber,EventsStream ); End; end; procedure TMidiWriter.Add_Event_String(Const DeltaTime : Integer; Const Event_Type:Byte;Const AText: string); var Meta_Val: byte; begin if (not Assigned(EventsStream)) Or (AText='') then Exit; With EventsStream Do Begin VLQ(DeltaTimeToTicks(DeltaTime),EventsStream); Meta_Val:=255; Write(Meta_Val,1); Write(Event_Type,1); VLQ(Length(AText),EventsStream); Write(AText,Length(AText)); End; end; procedure TMidiWriter.Add_Text_Event(Const DeltaTime : Integer; Const AText: string); Begin Add_Event_String(DeltaTime,1,AText); end; procedure TMidiWriter.Add_CopyrightNotice_Event(Const DeltaTime : Integer; Const AText: string); Begin Add_Event_String(DeltaTime,2,AText); end; procedure TMidiWriter.Add_TrackName_Event(Const DeltaTime : Integer; Const AText: string); Begin Add_Event_String(DeltaTime,3,AText); end; procedure TMidiWriter.Add_InstrumentName_Event(Const DeltaTime : Integer; Const AText: string); Begin Add_Event_String(DeltaTime,4,AText); end; procedure TMidiWriter.Add_Lyrics_Event(Const DeltaTime : Integer; Const AText: string); Begin Add_Event_String(DeltaTime,5,AText); end; procedure TMidiWriter.Add_Marker_Event(Const DeltaTime : Integer; Const AText: string); Begin Add_Event_String(DeltaTime,6,AText); end; procedure TMidiWriter.Add_CuePoint_Event(Const DeltaTime : Integer; Const AText: string); Begin Add_Event_String(DeltaTime,7,AText); end; procedure TMidiWriter.Add_ChannelPrefix_Event(Const DeltaTime : Integer; Const Channel: TChannel); var Meta_Val,Event_Type,Size_Event: byte; begin if (not Assigned(EventsStream)) or (Channel > 15) then Exit; With EventsStream Do Begin VLQ(0,EventsStream); Meta_Val:=255; Write(Meta_Val,1); Event_Type:= 32; Write(Event_Type,1); Size_Event:=1; Write(Size_Event,1); Write(Channel,1); End; end; procedure TMidiWriter.Add_EndOfTrack_Event; var SwPrefEnd, SwEndOfTrack_HexVal, SwType, SwSize: byte; begin If (Not Assigned(EventsStream)) Then Exit; With EventsStream Do Begin SwPrefEnd := 0; Write(SwPrefEnd,1); SwEndOfTrack_HexVal:=255; Write(SwEndOfTrack_HexVal,1); SwType:=47; Write(SwType,1); SwSize:=0; Write(SwSize,1); End; end; procedure TMidiWriter.Add_SetTempo_Event(Const DeltaTime : Integer; Const BPM: Integer); var Meta_Val,Event_Type,SwSize: byte; begin if (not Assigned(EventsStream)) then Exit; With EventsStream Do Begin Tempo:=BPM; VLQ(DeltaTimeToTicks(DeltaTime),EventsStream); Meta_Val:=255; Write(Meta_Val,1); Event_Type:=81; Write(Event_Type,1); SwSize:=3; Write(SwSize,1); Write_Tempo(60000000 Div BPM,EventsStream); End; end; procedure TMidiWriter.Add_SMPTEOffset_Event(Const DeltaTime : Integer; Const Hours : THour; Const Mins, Secs : TMinSec; Const Fr:TFr; Const SubFr: TSubFr); var Meta_Val,Event_Type,Size_Event: byte; begin if (not Assigned(EventsStream)) then Exit; With EventsStream Do Begin VLQ(DeltaTimeToTicks(DeltaTime),EventsStream); Meta_Val:=255; Write(Meta_Val,1); Event_Type:=84; Write(Event_Type,1); Size_Event:=5; Write(Size_Event,1); Write(Hours,1); Write(Mins,1); Write(Secs,1); Write(Fr,1); Write(SubFr,1); End; end; procedure TMidiWriter.Add_TimeSignature_Event(Const DeltaTime : Integer; Const Numer, Denom, Metro, TtNds: byte); var Meta_Val,Event_Type,Size_Event: byte; begin if (not Assigned(EventsStream)) then Exit; With EventsStream Do Begin VLQ(DeltaTimeToTicks(DeltaTime),EventsStream); Meta_Val:=255; Write(Meta_Val,1); Event_Type:=88; Write(Event_Type,1); Size_Event:=4; Write(Size_Event,1); Write(Numer,1); Write(Denom,1); Write(Metro,1); Write(TtNds,1); End; end; procedure TMidiWriter.Add_KeySignature_Event(Const DeltaTime : Integer; Const Key : TKey; Const Scale: TScale); var Meta_Val,Event_Type,Size_Event: byte; begin if (not Assigned(EventsStream)) then Exit; With EventsStream Do Begin VLQ(DeltaTimeToTicks(DeltaTime),EventsStream); Meta_Val:=255; Write(Meta_Val,1); Event_Type:=89; Write(Event_Type,1); Size_Event:=2; Write(Size_Event,1); Write(Key,1); Write(Scale ,1); End; end; procedure TMidiWriter.Add_SequencerSpecific_Event(Const DeltaTime : Integer; Information :Variant); var Meta_Val,Event_Type: byte; begin if (not Assigned(EventsStream))then Exit; With EventsStream Do Begin VLQ(DeltaTimeToTicks(DeltaTime),EventsStream); Meta_Val:=255; Write(Meta_Val,1); Event_Type:=127; Write(Event_Type,1); VLQ(SizeOf(Information),EventsStream ); SwapBytes(Information,SizeOf(Information)); Write(Information,SizeOf(Information)); End; end; end.
//------------------------------------------------------------------------------ // // Voxelizer // Copyright (C) 2021 by Jim Valavanis // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, inc., 59 Temple Place - Suite 330, Boston, MA // 02111-1307, USA. // //------------------------------------------------------------------------------ // Site : https://sourceforge.net/projects/voxelizer/ //------------------------------------------------------------------------------ unit vxl_filemenuhistory; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus; type TOnOpenEvent = procedure (Sender: TObject; const FileName: string) of object; TFileMenuHistory = class(TComponent) private { Private declarations } fMenuItems: array[0..9] of TMenuItem; fOnOpen: TOnOpenEvent; fPaths: TStringList; protected { Protected declarations } procedure DoFileOpen(Sender: TObject); procedure SetMenuItems0(Value: TMenuItem); virtual; procedure SetMenuItems1(Value: TMenuItem); virtual; procedure SetMenuItems2(Value: TMenuItem); virtual; procedure SetMenuItems3(Value: TMenuItem); virtual; procedure SetMenuItems4(Value: TMenuItem); virtual; procedure SetMenuItems5(Value: TMenuItem); virtual; procedure SetMenuItems6(Value: TMenuItem); virtual; procedure SetMenuItems7(Value: TMenuItem); virtual; procedure SetMenuItems8(Value: TMenuItem); virtual; procedure SetMenuItems9(Value: TMenuItem); virtual; procedure SetMenuItems(index: integer; Value: TMenuItem); virtual; procedure SetPaths(Value: TStringList); virtual; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; function MenuItem(index: integer): TMenuItem; procedure AddPath(const FileName: string); virtual; procedure RefreshMenuItems; virtual; function PathStringIdx(const idx: Integer): string; published { Published declarations } property MenuItem0: TMenuItem read fMenuItems[0] write SetMenuItems0; property MenuItem1: TMenuItem read fMenuItems[1] write SetMenuItems1; property MenuItem2: TMenuItem read fMenuItems[2] write SetMenuItems2; property MenuItem3: TMenuItem read fMenuItems[3] write SetMenuItems3; property MenuItem4: TMenuItem read fMenuItems[4] write SetMenuItems4; property MenuItem5: TMenuItem read fMenuItems[5] write SetMenuItems5; property MenuItem6: TMenuItem read fMenuItems[6] write SetMenuItems6; property MenuItem7: TMenuItem read fMenuItems[7] write SetMenuItems7; property MenuItem8: TMenuItem read fMenuItems[8] write SetMenuItems8; property MenuItem9: TMenuItem read fMenuItems[9] write SetMenuItems9; property Paths: TStringList read fPaths write SetPaths; property OnOpen:TOnOpenEvent read fOnOpen write fOnOpen; end; implementation uses vxl_utils; resourceString rsRangeCheckError = 'Index out of range.'; rsFmtMenuCaption = '&%d. %s'; procedure TFileMenuHistory.SetMenuItems0(Value: TMenuItem); begin SetMenuItems(0, Value); end; procedure TFileMenuHistory.SetMenuItems1(Value: TMenuItem); begin SetMenuItems(1, Value); end; procedure TFileMenuHistory.SetMenuItems2(Value: TMenuItem); begin SetMenuItems(2, Value); end; procedure TFileMenuHistory.SetMenuItems3(Value: TMenuItem); begin SetMenuItems(3, Value); end; procedure TFileMenuHistory.SetMenuItems4(Value: TMenuItem); begin SetMenuItems(4, Value); end; procedure TFileMenuHistory.SetMenuItems5(Value: TMenuItem); begin SetMenuItems(5, Value); end; procedure TFileMenuHistory.SetMenuItems6(Value: TMenuItem); begin SetMenuItems(6, Value); end; procedure TFileMenuHistory.SetMenuItems7(Value: TMenuItem); begin SetMenuItems(7, Value); end; procedure TFileMenuHistory.SetMenuItems8(Value: TMenuItem); begin SetMenuItems(8, Value); end; procedure TFileMenuHistory.SetMenuItems9(Value: TMenuItem); begin SetMenuItems(9, Value); end; procedure TFileMenuHistory.SetMenuItems(index: integer; Value: TMenuItem); begin if (index >= low(fMenuItems)) and (index <= high(fMenuItems)) then begin fMenuItems[index] := Value; fMenuItems[index].OnClick := DoFileOpen; end else raise Exception.Create(rsRangeCheckError); end; function TFileMenuHistory.MenuItem(index: integer): TMenuItem; begin if (index >= low(fMenuItems)) and (index <= high(fMenuItems)) then result := fMenuItems[index] else result := nil; end; constructor TFileMenuHistory.Create(AOwner: TComponent); var i: integer; begin Inherited; for i := low(fMenuItems) to high(fMenuItems) do fMenuItems[i] := nil; fPaths := TStringList.Create; end; destructor TFileMenuHistory.Destroy; begin fPaths.Free; Inherited; end; procedure TFileMenuHistory.DoFileOpen(Sender: TObject); var i: integer; begin if Sender <> nil then begin for i := low(fMenuItems) to high(fMenuItems) do begin if Sender = fMenuItems[i] then begin if fPaths.Count > i then if Assigned(fOnOpen) then fOnOpen(Sender, fPaths[i]); Exit; end; end; end; end; procedure TFileMenuHistory.SetPaths(Value: TStringList); var i, count: integer; begin if Value.Text <> Paths.Text then begin fPaths.Clear; for i := 0 to Value.Count do if Trim(Value.Strings[i]) <> '' then fPaths.Add(Value.Strings[i]); end; for i := low(fMenuItems) to high(fMenuItems) do if Assigned(fMenuItems[i]) then fMenuItems[i].Visible := false; count := 0; for i := low(fMenuItems) to MinI(high(fMenuItems), fPaths.Count - 1) do if Assigned(fMenuItems[i]) then begin inc(count); fMenuItems[i].Visible := true; fMenuItems[i].Caption := Format(rsFmtMenuCaption, [count, MkShortName(fPaths.Strings[i])]); end; end; procedure TFileMenuHistory.AddPath(const FileName: string); var i: integer; idx: integer; fname: string; begin fname := Trim(FileName); if fname = '' then Exit; idx := fPaths.IndexOf(fname); if idx = -1 then begin fPaths.Insert(0, fname); if fPaths.Count > high(fMenuItems) then for i := fPaths.Count - 1 downto high(fMenuItems) do fPaths.Delete(i); end else begin fPaths.Delete(idx); AddPath(fname); end; SetPaths(fPaths); end; procedure TFileMenuHistory.RefreshMenuItems; begin SetPaths(fPaths); end; function TFileMenuHistory.PathStringIdx(const idx: Integer): string; begin if idx < 0 then begin Result := ''; Exit; end; if idx >= fPaths.Count then begin Result := ''; Exit; end; Result := Trim(fPaths.Strings[idx]) end; end.
{*************************************************} { Базовая форма списка *} {*************************************************} unit ItemListUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, MaximizedUnit, StdCtrls, DBCtrls, ComCtrls, ToolWin, ExtCtrls, ImgList, ExtraUnit, DbGridUnit, DB, ItemEditUnit, GFunctions; type TItemListForm = class(TMaximizedForm) ToolPanel: TPanel; ToolBar: TToolBar; AddBtn: TToolButton; Panel: TPanel; ToolImages: TImageList; OpenBtn: TToolButton; DelBtn: TToolButton; GridFrame: TDbGridFrame; StatusBar: TStatusBar; procedure AddBtnClick(Sender: TObject); procedure OpenBtnClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure DelBtnClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure GridFrameDataSourceDataChange(Sender: TObject; Field: TField); procedure GridFrameGridDblClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure GridFrameGridKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); protected FEditFormClass: TItemEditFormClass; FIDFieldName: string; FFirstShow: boolean; procedure CommonOpen; virtual; procedure CommonRefresh; virtual; procedure RefreshAfterEdit; virtual; procedure DoDelete; virtual; procedure FontChanged; override; end; var ItemListForm: TItemListForm; implementation {$R *.dfm} procedure TItemListForm.FormCreate(Sender: TObject); begin inherited; FFirstShow := true; end; procedure TItemListForm.FormActivate(Sender: TObject); begin inherited; if FFirstShow then begin FFirstShow := false; CommonOpen; end else CommonRefresh; end; procedure TItemListForm.CommonRefresh; begin GridFrame.RefreshGridByID(GridFrame.DataSource.DataSet.FindField(FIDFieldName)); end; procedure TItemListForm.CommonOpen; begin GridFrame.DataSource.DataSet.Open; end; procedure TItemListForm.AddBtnClick(Sender: TObject); var Form: TItemEditForm; begin Form := FEditFormClass.Create(Application); try Form.StartAdd; Form.ShowModal; if (Form.ID > 0) then begin try GridFrame.DataSource.DataSet.DisableControls; CommonRefresh; GLocate(GridFrame.DataSource.DataSet, FIDFieldName, Form.ID); finally GridFrame.DataSource.DataSet.EnableControls; end; end; finally Form.Free; end; end; procedure TItemListForm.OpenBtnClick(Sender: TObject); var Form: TItemEditForm; begin Form := FEditFormClass.Create(Application); try Form.StartEdit(GridFrame.DataSource.DataSet.FindField(FIDFieldName).AsInteger); Form.ShowModal; if Form.Modified and Assigned(GridFrame.DataSource.DataSet) then GridFrame.DataSource.DataSet.Refresh; RefreshAfterEdit; finally Form.Free; end; end; procedure TItemListForm.RefreshAfterEdit; begin end; procedure TItemListForm.DelBtnClick(Sender: TObject); begin DoDelete; end; procedure TItemListForm.DoDelete; begin end; procedure TItemListForm.FontChanged; begin ToolPanel.Height := 41 + FontHeight(Font); end; procedure TItemListForm.GridFrameDataSourceDataChange(Sender: TObject; Field: TField); var XE: boolean; begin XE := GridFrame.DataSource.DataSet.EOF and GridFrame.DataSource.DataSet.BOF; OpenBtn.Enabled := not XE; DelBtn.Enabled := not XE; end; procedure TItemListForm.GridFrameGridDblClick(Sender: TObject); begin inherited; if OpenBtn.Enabled then OpenBtn.Click; end; procedure TItemListForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (Shift=[]) and (Key=VK_F5) then begin CommonRefresh; Key := 0; end; end; procedure TItemListForm.GridFrameGridKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_RETURN) and (Shift = [ssCtrl]) then begin if OpenBtn.Enabled then OpenBtn.Click; Key := 0; end else GridFrame.FrameKeyDown(Sender, Key, Shift); end; end.
unit UfrmBrowseFTP; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.ComCtrls, USourceInfo, Vcl.StdCtrls, Vcl.AppEvnts; type TfrmBrowseFTP = class(TForm) tvDirs: TTreeView; lvFiles: TListView; Panel1: TPanel; Panel2: TPanel; Splitter1: TSplitter; Panel3: TPanel; pnlFolder: TPanel; lblFolder: TLabel; btnOK: TButton; btnCancel: TButton; ApplicationEvents1: TApplicationEvents; procedure tvDirsChange(Sender: TObject; nodeSelected: TTreeNode); procedure ApplicationEvents1Idle(Sender: TObject; var Done: Boolean); procedure lvFilesDblClick(Sender: TObject); procedure FormCreate(Sender: TObject); private FAutoOpen: string; procedure AddToTree(parent: TStringTree; parentNode: TTreeNode); function GetSelectedFTPFileName: string; procedure SetAutoOpen(const Value: string); { Private declarations } public property SelectedFTPFileName: string read GetSelectedFTPFileName; property AutoOpen: string read FAutoOpen write SetAutoOpen; { Public declarations } end; function SelectFTPFile(var strFileName: string; strExtensions: string; strAutoOpen: string): boolean; function CopyExternalFileToLocal(strFileName: string): string; procedure OpenInternetSource(strAutoOpen: string); implementation uses ShellApi, GNUGetText, UBrowseFTP, USettings, UUtilsStrings, UTempActions; {$R *.dfm} var gl_frmBrowseFTP: TfrmBrowseFTP; function SelectFTPFile(var strFileName: string; strExtensions: string; strAutoOpen: string): boolean; begin if not Assigned(gl_frmBrowseFTP) then begin gl_frmBrowseFTP := TfrmBrowseFTP.Create(Application.MainForm); end; try GetBrowseFTP.Extensions.Clear; GetBrowseFTP.Extensions.Delimiter := '|'; GetBrowseFTP.Extensions.DelimitedText := strExtensions; gl_frmBrowseFTP.AutoOpen := strAutoOpen; Result := gl_frmBrowseFTP.ShowModal = mrOK; if Result then begin strFileName := gl_frmBrowseFTP.SelectedFTPFileName; end; finally //gl_frmBrowseFTP.Free; end; end; function CopyExternalFileToLocal(strFileName: string): string; var strLocalFile, strLocalFileOld: string; begin Result := ''; strLocalFile := '<ftp>' + StringReplace(strFileName, '/', '\', [rfReplaceAll]); strLocalFile := GetSettings.DirExplode(strLocalFile); if FileExists(strLocalFile) then begin strLocalFileOld := strLocalFile + '.old'; if FileExists(strLocalFileOld) then begin DeleteFile(strLocalFileOld); end; // just use the already downloaded file when in use if not RenameFile(strLocalFile, strLocalFileOld) then begin Result := strLocalFile; Exit; end; end; ForceDirectories(ExtractFilePath(strLocalFile)); if GetBrowseFTP.Download(strFileName, strLocalFile) then begin Result := strLocalFile; end; end; procedure OpenInternetSource(strAutoOpen: string); var strFileName: string; begin strFileName := ''; if SelectFTPFile(strFileName, '.ppt|.pptx|.doc|.docx|.xls|.xlsx|.rtf|.txt|.pdf', strAutoOpen) then begin strFileName := CopyExternalFileToLocal(strFileName); ShellExecute(0, '', PChar(strFileName), '', '', SW_SHOWNORMAL); end; end; procedure TfrmBrowseFTP.AddToTree(parent: TStringTree; parentNode: TTreeNode); var i: Integer; treeNode: TTreeNode; begin for i := 0 to parent.Count -1 do begin treeNode := tvDirs.Items.AddChild(parentNode, parent.Item[i].Data); AddToTree(parent.Item[i], treeNode); end; end; procedure TfrmBrowseFTP.ApplicationEvents1Idle(Sender: TObject; var Done: Boolean); var aFolders: TArrayOfString; index: integer; node: TTreeNode; begin btnOK.Enabled := lvFiles.ItemIndex <> -1; if FAutoOpen <> '' then begin SetWaitCursor; aFolders := Split(FAutoOpen, '/'); FAutoOpen := ''; node := tvDirs.Items.GetFirstNode; for index := 0 to Length(aFolders) -1 do begin while Assigned(node) do begin if node.Text = aFolders[index] then begin tvDirsChange(nil, node); node.Selected := true; node := node.getFirstChild; break; end; node := node.getNextSibling; end; end; end; end; procedure TfrmBrowseFTP.FormCreate(Sender: TObject); begin TranslateComponent(self); // todo GKVKandelaar tvDirs.Items.AddChildObject(nil, 'BeamTeam', pointer(-1)); tvDirs.FullExpand; end; function TfrmBrowseFTP.GetSelectedFTPFileName: string; begin Result := lblFolder.Caption; if lvFiles.ItemIndex <> -1 then Result := Result + '/' + lvFiles.Items[lvFiles.ItemIndex].Caption; end; procedure TfrmBrowseFTP.lvFilesDblClick(Sender: TObject); begin if lvFiles.ItemIndex <> -1 then ModalResult := mrOk; end; procedure TfrmBrowseFTP.SetAutoOpen(const Value: string); begin FAutoOpen := Value; end; procedure TfrmBrowseFTP.tvDirsChange(Sender: TObject; nodeSelected: TTreeNode); var node: TTreeNode; strPath: string; slDirs, slFiles: TStringList; i: integer; item: TListItem; begin if Assigned(nodeSelected) then begin slDirs := nil; slFiles := TStringList.Create; try slFiles.CaseSensitive := false; if integer(nodeSelected.Data) = -1 then begin slDirs := TStringList.Create; slDirs.CaseSensitive := false; end; // create path strPath := ''; node := nodeSelected; while Assigned(node) do begin if strPath = '' then strPath := node.Text else strPath := node.Text + '/' + strPath; node := node.Parent; end; strPath := '/' + strPath; if (strPath <> lblFolder.Caption) or Assigned(slDirs) then begin lvFiles.Items.Clear; lblFolder.Caption := ''; if GetBrowseFTP.GetFilesAndDirs(strPath, slFiles, slDirs) then begin if Assigned(slDirs) then begin // delete children nodeSelected.DeleteChildren; for i := 0 to slDirs.Count -1 do begin tvDirs.Items.AddChildObject(nodeSelected, slDirs[i], pointer(-1)); end; nodeSelected.Data := nil; nodeSelected.Expand(true); end; // fill list for i := 0 to slFiles.Count -1 do begin item := lvFiles.Items.Add; item.Caption := slFiles[i]; end; lblFolder.Caption := strPath; end else begin tvDirs.ClearSelection(); end; end; finally slFiles.Free; slDirs.Free; end; end; end; end.
(* PNG Library www.sibvrv.com Last Update : 14 agust 2008 Vereshagin Roman Vladimirovich *) unit acPNG; {$I sDefs.inc} interface Uses Windows, Graphics, SysUtils, Classes, acZLibEx, Math, sConst; const DefaultDisplayGamma = 2.2; gesInvalidImage = 'Cannot load image. Invalid or unexpected %s image format.'; gesInvalidColorFormat = 'Invalid color format in %s file.'; gesUnsupportedFeature = 'Cannot load image. %s not supported for %s files.'; gesInvalidCRC = 'Cannot load image. CRC error found in %s file.'; gesCompression = 'Cannot load image. Compression error found in %s file.'; gesExtraCompressedData = 'Cannot load image. Extra compressed data found in %s file.'; gesInvalidPalette = 'Cannot load image. Palette in %s file is invalid.'; gesUnknownCriticalChunk = 'Cannot load PNG image. Unexpected but critical chunk detected.'; gesIndexedNotSupported = 'Conversion between indexed and non-indexed pixel formats is not supported.'; gesConversionUnsupported = 'Color conversion failed. Could not find a proper method.'; gesInvalidSampleDepth = 'Color depth is invalid. Bits per sample must be 1, 2, 4, 8 or 16.'; gesInvalidPixelDepth = 'Sample count per pixel does not correspond to the given color scheme.'; gesInvalidSubSampling = 'Subsampling value is invalid. Allowed are 1, 2 and 4.'; gesVerticalSubSamplingError = 'Vertical subsampling value must be <= horizontal subsampling value.'; gesPreparing = 'Preparing...'; gesLoadingData = 'Loading data...'; gesUpsampling = 'Upsampling...'; gesTransfering = 'Transfering...'; type TColorScheme = (csUnknown, csIndexed, csG, csGA, csRGB, csRGBA, csBGR, csBGRA, csCMY, csCMYK, csCIELab, csYCbCr, csPhotoYCC ); TConvertOptions = set of ( coAlpha, coApplyGamma, coNeedByteSwap, coLabByteRange, coLabChromaOffset ); TRawPaletteFormat = ( pfInterlaced8Triple, pfInterlaced8Quad, pfPlane8Triple, pfPlane8Quad, pfInterlaced16Triple, pfInterlaced16Quad, pfPlane16Triple, pfPlane16Quad ); TConversionMethod = procedure(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte) of object; TColorManager = class private FChanged: Boolean; FSourceBPS, FTargetBPS, FSourceSPP, FTargetSPP: Byte; FMainGamma, FDisplayGamma: Single; FGammaTable: array[Byte] of Byte; FYCbCrCoefficients: array[0..2] of Single; FHSubsampling, FVSubSampling: Byte; FCrToRedTable, FCbToBlueTable, FCrToGreenTable, FCbToGreenTable: array of Integer; FSourceScheme, FTargetScheme: TColorScheme; FRowConversion: TConversionMethod; FSourceOptions, FTargetOptions: TConvertOptions; protected function ComponentGammaConvert(Value: Byte): Byte; function ComponentNoConvert16(Value: Word): Word; function ComponentNoConvert8(Value: Byte): Byte; function ComponentScaleConvert(Value: Word): Byte; function ComponentScaleGammaConvert(Value: Word): Byte; function ComponentSwapScaleGammaConvert(Value: Word): Byte; function ComponentSwapScaleConvert(Value: Word): Byte; function ComponentSwapConvert(Value: Word): Word; procedure RowConvertBGR2BGR(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); procedure RowConvertBGR2RGB(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); procedure RowConvertCIELAB2BGR(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); procedure RowConvertCIELAB2RGB(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); procedure RowConvertCMYK2BGR(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); procedure RowConvertCMYK2RGB(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); procedure RowConvertGray(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); procedure RowConvertIndexed8(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); procedure RowConvertIndexedBoth16(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); procedure RowConvertIndexedSource16(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); procedure RowConvertIndexedTarget16(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); procedure RowConvertRGB2BGR(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); procedure RowConvertRGB2RGB(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); procedure RowConvertPhotoYCC2BGR(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); procedure RowConvertPhotoYCC2RGB(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); procedure RowConvertYCbCr2BGR(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); procedure RowConvertYCbCr2RGB(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); procedure CreateYCbCrLookup; function GetPixelFormat(Index: Integer): TPixelFormat; procedure PrepareConversion; procedure SetSourceBitsPerSample(const Value: Byte); procedure SetSourceColorScheme(const Value: TColorScheme); procedure SetSourceSamplesPerPixel(const Value: Byte); procedure SetTargetBitsPerSample(const Value: Byte); procedure SetTargetColorScheme(const Value: TColorScheme); procedure SetTargetSamplesPerPixel(const Value: Byte); public constructor Create; procedure ConvertRow(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); function CreateColorPalette(Data: array of Pointer; DataFormat: TRawPaletteFormat; ColorCount: Cardinal; RGB: Boolean): HPALETTE; function CreateGrayscalePalette(MinimumIsWhite: Boolean): HPALETTE; procedure Error(const Msg: String); procedure SetGamma(MainGamma: Single; DisplayGamma: Single = DefaultDisplayGamma); property SourceBitsPerSample: Byte read FSourceBPS write SetSourceBitsPerSample; property SourceColorScheme: TColorScheme read FSourceScheme write SetSourceColorScheme; property SourceOptions: TConvertOptions read FSourceOptions write FSourceOptions; property SourcePixelFormat: TPixelFormat index 0 read GetPixelFormat; property SourceSamplesPerPixel: Byte read FSourceSPP write SetSourceSamplesPerPixel; property TargetBitsPerSample: Byte read FTargetBPS write SetTargetBitsPerSample; property TargetColorScheme: TColorScheme read FTargetScheme write SetTargetColorScheme; property TargetOptions: TConvertOptions read FTargetOptions write FTargetOptions; property TargetPixelFormat: TPixelFormat index 1 read GetPixelFormat; property TargetSamplesPerPixel: Byte read FTargetSPP write SetTargetSamplesPerPixel; end; type TByteArray = array of byte; TCardinalArray = array of Cardinal; TFloatArray = array of Single; TLZ77Decoder = class private FStream: TZStreamRec; FZLibResult, FFlushMode: Integer; FAutoReset: Boolean; function GetAvailableInput: Integer; function GetAvailableOutput: Integer; public constructor Create(FlushMode: Integer; AutoReset: Boolean); procedure Decode(var Source, Dest: Pointer; PackedSize, UnpackedSize: Integer); procedure DecodeEnd; procedure DecodeInit; procedure Encode(Source, Dest: Pointer; Count: Cardinal; var BytesStored: Cardinal); property AvailableInput: Integer read GetAvailableInput; property AvailableOutput: Integer read GetAvailableOutput; property ZLibResult: Integer read FZLibResult; end; TImageOptions = set of ( ioBigEndian, ioUseGamma ); TCompressionType = ( ctUnknown, ctNone, ctLZ77 ); PImageProperties = ^TImageProperties; TImageProperties = record Options : TImageOptions; Width : Cardinal; Height : Cardinal; ColorScheme : TColorScheme; BitsPerSample : Byte; SamplesPerPixel : Byte; BitsPerPixel : Byte; Compression : TCompressionType; FileGamma : Single; Interlaced : Boolean; HasAlpha : Boolean; FilterMode : Byte; end; TChunkType = array[0..3] of AnsiChar; TPNGChunkHeader = packed record Length: Cardinal; ChunkType: TChunkType; end; TPNGGraphic = class(TBitmap) private FColorManager : TColorManager; FProgressRect : TRect; FBasePosition : Cardinal; FStream : TStream; FImageProperties : TImageProperties; FDecoder : TLZ77Decoder; FIDATSize : Integer; FRawBuffer : Pointer; FCurrentSource : Pointer; FHeader : TPNGChunkHeader; FCurrentCRC : Cardinal; FSourceBPP : Integer; FPalette : HPALETTE; FTransparency : TByteArray; FTransparentColor : TColor; FBackgroundColor : TColor; procedure ApplyFilter(Filter: Byte; Line, PrevLine, Target: PByte; BPP, BytesPerRow: Integer); function IsChunk(ChunkType: TChunkType): Boolean; function LoadAndSwapHeader: Cardinal; procedure LoadBackgroundColor(const Description); procedure LoadIDAT(const Description); procedure LoadTransparency(const Description); procedure ReadDataAndCheckCRC; procedure ReadRow(RowBuffer: Pointer; BytesPerRow: Integer); function SetupColorDepth(ColorType, BitDepth: Integer): Integer; public Reflected : boolean; constructor Create; override; destructor Destroy; override; procedure Draw(ACanvas: TCanvas; const Rect: TRect); override; procedure Assign(Source: TPersistent); override; class function CanLoad(const FileName: String): Boolean; overload; class function CanLoad(Stream: TStream): Boolean; overload; procedure LoadFromStream(Stream: TStream); override; function ReadImageProperties(Stream: TStream; ImageIndex: Cardinal): Boolean; property BackgroundColor: TColor read FBackgroundColor; property Transparency: TByteArray read FTransparency; property ColorManager: TColorManager read FColorManager; property ImageProperties: TImageProperties read FImageProperties write FImageProperties; end; function ClampByte(Value: Integer): Byte; function MulDiv16(Number, Numerator, Denominator: Word): Word; procedure SwapLong(P: PInteger; Count: Cardinal); overload; function SwapLong(Value: Cardinal): Cardinal; overload; function MakeIcon32(Img: TBitmap; UpdateAlphaChannell : boolean = False): HICON; function MakeCompIcon(Img: TPNGGraphic; BGColor : TColor = clNone): HICON; procedure UpdateTransPixels(Img: TBitmap); const PNGMagic: array[0..7] of Byte = (137, 80, 78, 71, 13, 10, 26, 10); var UseACPng : boolean = True; implementation uses sGraphUtils, acntUtils, sAlphaGraph; var // used to calculate the running CRC of a bunch of bytes, // this table is dynamically created in order to save space if never needed CRCTable: array of Cardinal; procedure MakeCRCTable; // creates the CRC table when it is needed the first time var C: Cardinal; N, K : Integer; Poly: Cardinal; // polynomial exclusive-or pattern const // terms of polynomial defining this CRC (except x^32) P: array [0..13] of Byte = (0, 1, 2, 4, 5, 7, 8, 10, 11, 12, 16, 22, 23, 26); begin // make exclusive-or pattern from polynomial ($EDB88320) SetLength(CRCTable, 256); Poly := 0; for N := 0 to SizeOf(P) - 1 do Poly := Poly or (1 shl (31 - P[N])); for N := 0 to 255 do begin C := N; for K := 0 to 7 do begin if (C and 1) <> 0 then C := Poly xor (C shr 1) else C := C shr 1; end; CRCTable[N] := C; end; end; function CRC32(CRC: Cardinal; Buffer: PByte; Len: Cardinal): Cardinal; begin if Buffer = nil then Result := 0 else begin if CRCTable = nil then MakeCRCTable; CRC := CRC xor $FFFFFFFF; while Len >= 8 do begin CRC := CRCTable[Byte(CRC) xor Buffer^] xor (CRC shr 8); Inc(Buffer); CRC := CRCTable[Byte(CRC) xor Buffer^] xor (CRC shr 8); Inc(Buffer); CRC := CRCTable[Byte(CRC) xor Buffer^] xor (CRC shr 8); Inc(Buffer); CRC := CRCTable[Byte(CRC) xor Buffer^] xor (CRC shr 8); Inc(Buffer); CRC := CRCTable[Byte(CRC) xor Buffer^] xor (CRC shr 8); Inc(Buffer); CRC := CRCTable[Byte(CRC) xor Buffer^] xor (CRC shr 8); Inc(Buffer); CRC := CRCTable[Byte(CRC) xor Buffer^] xor (CRC shr 8); Inc(Buffer); CRC := CRCTable[Byte(CRC) xor Buffer^] xor (CRC shr 8); Inc(Buffer); Dec(Len, 8); end; while Len > 0 do begin CRC := CRCTable[(CRC xor Buffer^) and $FF] xor (CRC shr 8); Inc(Buffer); Dec(Len); end; Result := CRC xor $FFFFFFFF; end; end; procedure SwapLong(P: PInteger; Count: Cardinal); overload; asm @@Loop: MOV ECX, [EAX] BSWAP ECX MOV [EAX], ECX ADD EAX, 4 DEC EDX JNZ @@Loop end; function SwapLong(Value: Cardinal): Cardinal; overload; asm BSWAP EAX end; type EGraphicCompression = class(Exception); procedure GraphicExError(ErrorString: String); overload; begin raise EInvalidGraphic.Create(ErrorString); end; procedure GraphicExError(ErrorString: String; Args: array of const); overload; begin raise EInvalidGraphic.CreateFmt(ErrorString, Args); end; procedure CompressionError(ErrorString: String); overload; begin raise EGraphicCompression.Create(ErrorString); end; { TLZ77Decoder } constructor TLZ77Decoder.Create(FlushMode: Integer; AutoReset: Boolean); begin FillChar(FStream, SizeOf(FStream), 0); FFlushMode := FlushMode; FAutoReset := AutoReset; end; procedure TLZ77Decoder.Decode(var Source, Dest: Pointer; PackedSize, UnpackedSize: Integer); begin FStream.next_in := Source; FStream.avail_in := PackedSize; if FAutoReset then FZLibResult := acZLibEX.InflateReset(FStream); if FZLibResult = Z_OK then begin FStream.next_out := Dest; FStream.avail_out := UnpackedSize; FZLibResult := Inflate(FStream, FFlushMode); Source := FStream.next_in; Dest := FStream.next_out; end; end; procedure TLZ77Decoder.DecodeEnd; begin if InflateEnd(FStream) < 0 then CompressionError('LZ77 decompression error.'); end; procedure TLZ77Decoder.DecodeInit; begin if InflateInit(FStream) < 0 then CompressionError('LZ77 decompression error.'); end; procedure TLZ77Decoder.Encode(Source, Dest: Pointer; Count: Cardinal; var BytesStored: Cardinal); begin end; function TLZ77Decoder.GetAvailableInput: Integer; begin Result := FStream.avail_in; end; function TLZ77Decoder.GetAvailableOutput: Integer; begin Result := FStream.avail_out; end; const IHDR = 'IHDR'; IDAT = 'IDAT'; IEND = 'IEND'; PLTE = 'PLTE'; gAMA = 'gAMA'; tRNS = 'tRNS'; bKGD = 'bKGD'; CHUNKMASK = $20; type PIHDRChunk = ^TIHDRChunk; TIHDRChunk = packed record Width, Height: Cardinal; BitDepth, ColorType, Compression, Filter, Interlaced: Byte; end; class function TPNGGraphic.CanLoad(const FileName: String): Boolean; var Stream: TFileStream; begin if UseACPng then begin Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try Result := CanLoad(Stream); finally FreeAndNil(Stream); end; end else Result := False; end; class function TPNGGraphic.CanLoad(Stream: TStream): Boolean; var Magic: array[0..7] of Byte; LastPosition: Cardinal; begin if UseACPng then with Stream do begin LastPosition := Position; Result := (Size - Position) > SizeOf(Magic); if Result then begin ReadBuffer(Magic, SizeOf(Magic)); Result := CompareMem(@Magic, @PNGMagic, 8); end; Position := LastPosition; end else Result := False; end; function TPNGGraphic.IsChunk(ChunkType: TChunkType): Boolean; const Mask = not $20202020; begin Result := (Cardinal((@FHeader.ChunkType)^) and Mask) = (Cardinal((@ChunkType)^) and Mask); end; function TPNGGraphic.LoadAndSwapHeader: Cardinal; begin FStream.ReadBuffer(FHeader, SizeOf(FHeader)); Result := CRC32(0, PByte(@FHeader.ChunkType), 4); FHeader.Length := SwapLong(FHeader.Length); end; function PaethPredictor(a, b, c: Byte): Byte; var p, pa, pb, pc: Integer; begin p := a + b - c; pa := Abs(p - a); pb := Abs(p - b); pc := Abs(p - c); if (pa <= pb) and (pa <= pc) then Result := a else if pb <= pc then Result := b else Result := c; end; procedure TPNGGraphic.ApplyFilter(Filter: Byte; Line, PrevLine, Target: PByte; BPP, BytesPerRow: Integer); var I: Integer; Raw, Decoded, Prior, PriorDecoded, TargetRun: PByte; begin case Filter of 0: Move(Line^, Target^, BytesPerRow); 1: begin Raw := Line; TargetRun := Target; Move(Raw^, TargetRun^, BPP); 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: begin Raw := Line; Prior := PrevLine; TargetRun := Target; while BytesPerRow > 0 do begin TargetRun^ := Byte(Raw^ + Prior^); Inc(Raw); Inc(Prior); Inc(TargetRun); Dec(BytesPerRow); end; end; 3: begin Raw := Line; Decoded := Line; Prior := PrevLine; 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); 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: begin Raw := Line; Decoded := Target; Prior := PrevLine; PriorDecoded := PrevLine; 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); while BytesPerRow > 0 do begin TargetRun^ := Byte(Raw^ + PaethPredictor(Decoded^, Prior^, PriorDecoded^)); Inc(Raw); Inc(Decoded); Inc(Prior); Inc(PriorDecoded); Inc(TargetRun); Dec(BytesPerRow); end; end; end; end; {$IFNDEF DELPHI6UP} type PCardinal = ^Cardinal; {$ENDIF} procedure TPNGGraphic.LoadFromStream(Stream: TStream); var Description: TIHDRChunk; begin Handle := 0; FBasePosition := Stream.Position; FDecoder := nil; FStream := Stream; if ReadImageProperties(Stream, 0) then begin with Stream, FImageProperties do begin Position := FBasePosition + 8; FProgressRect := Rect(0, 0, Width, 1); Progress(Self, psStarting, 0, False, FProgressRect, gesPreparing); FPalette := 0; FTransparency := nil; FBackgroundColor := clWhite; FTransparentColor := clNone; FCurrentCRC := LoadAndSwapHeader; FRawBuffer := nil; ColorManager.SourceOptions := [coNeedByteSwap]; try ReadDataAndCheckCRC; Move(FRawBuffer^, Description, SizeOf(Description)); SwapLong(PInteger(@Description), 2); if Compression = ctLZ77 then begin FDecoder := TLZ77Decoder.Create(Z_PARTIAL_FLUSH, False); FDecoder.DecodeInit; end else GraphicExError(gesUnsupportedFeature, ['The compression scheme is', 'PNG']); repeat FCurrentCRC := LoadAndSwapHeader; if IsChunk(IDAT) then begin Progress(Self, psEnding, 0, False, FProgressRect, ''); LoadIDAT(Description); end else if IsChunk(PLTE) then begin if (FHeader.Length mod 3) <> 0 then GraphicExError(gesInvalidPalette, ['PNG']); ReadDataAndCheckCRC; if Description.ColorType = 3 then begin FSourceBPP := SetupColorDepth(Description.ColorType, Description.BitDepth); FPalette := ColorManager.CreateColorPalette([FRawBuffer], pfInterlaced8Triple, FHeader.Length div 3, False); end; Continue; end else if IsChunk(gAMA) then begin ReadDataAndCheckCRC; ColorManager.SetGamma(SwapLong(PCardinal(FRawBuffer)^) / 100000); ColorManager.TargetOptions := ColorManager.TargetOptions + [coApplyGamma]; Include(Options, ioUseGamma); Continue; end else if IsChunk(bKGD) then begin LoadBackgroundColor(Description); Continue; end else if IsChunk(tRNS) then begin LoadTransparency(Description); Continue; end; Seek(FHeader.Length + 4, soFromCurrent); if IsChunk(IEND) then Break; if (Byte(FHeader.ChunkType[0]) and CHUNKMASK) = 0 then GraphicExError(gesUnknownCriticalChunk); until False; finally if Assigned(FDecoder) then begin FDecoder.DecodeEnd; FreeAndNil(FDecoder); end; if Assigned(FRawBuffer) then FreeMem(FRawBuffer); Progress(Self, psEnding, 0, False, FProgressRect, ''); end; end; end else GraphicExError(gesInvalidImage, ['PNG']); end; function TPNGGraphic.ReadImageProperties(Stream: TStream; ImageIndex: Cardinal): Boolean; var Magic: array[0..7] of Byte; Description: TIHDRChunk; begin ZeroMemory(@FImageProperties, SizeOf(FImageProperties)); FImageProperties.FileGamma := 1; Result := False; FStream := Stream; with Stream, FImageProperties do begin ReadBuffer(Magic, 8); if CompareMem(@Magic, @PNGMagic, 8) then begin FCurrentCRC := LoadAndSwapHeader; if IsChunk(IHDR) then begin Include(Options, ioBigEndian); ReadDataAndCheckCRC; Move(FRawBuffer^, Description, SizeOf(Description)); SwapLong(PInteger(@Description), 2); if (Description.Width = 0) or (Description.Height = 0) then Exit; Width := Description.Width; Height := Description.Height; if Description.Compression = 0 then Compression := ctLZ77 else Compression := ctUnknown; BitsPerSample := Description.BitDepth; SamplesPerPixel := 1; case Description.ColorType of 0: ColorScheme := csG; 2: begin ColorScheme := csRGB; SamplesPerPixel := 3; end; 3: ColorScheme := csIndexed; 4: ColorScheme := csGA; 6: begin ColorScheme := csRGBA; SamplesPerPixel := 4; end; else ColorScheme := csUnknown; end; BitsPerPixel := SamplesPerPixel * BitsPerSample; FilterMode := Description.Filter; Interlaced := Description.Interlaced <> 0; HasAlpha := ColorScheme in [csGA, csRGBA, csBGRA]; repeat FCurrentCRC := LoadAndSwapHeader; if IsChunk(gAMA) then begin ReadDataAndCheckCRC; FileGamma := SwapLong(PCardinal(FRawBuffer)^) / 100000; Break; end; Seek(FHeader.Length + 4, soFromCurrent); if IsChunk(IEND) then Break; until False; FreeMem(FRawBuffer); Result := True; end; end; end; end; procedure TPNGGraphic.LoadBackgroundColor(const Description); var Run: PWord; R, G, B: Byte; begin ReadDataAndCheckCRC; with TIHDRChunk(Description) do begin case ColorType of 0, 4: begin case BitDepth of 2: FBackgroundColor := MulDiv16(Swap(PWord(FRawBuffer)^), 15, 3); 16:FBackgroundColor := MulDiv16(Swap(PWord(FRawBuffer)^), 255, 65535); else FBackgroundColor := Byte(Swap(PWord(FRawBuffer)^)); end; end; 2, 6: begin Run := FRawBuffer; if BitDepth = 16 then begin R := MulDiv16(Swap(Run^), 255, 65535); Inc(Run); G := MulDiv16(Swap(Run^), 255, 65535); Inc(Run); B := MulDiv16(Swap(Run^), 255, 65535); end else begin R := Byte(Swap(Run^)); Inc(Run); G := Byte(Swap(Run^)); Inc(Run); B := Byte(Swap(Run^)); end; FBackgroundColor := RGB(R, G, B); end; else FBackgroundColor := PByte(FRawBuffer)^; end; end; end; procedure TPNGGraphic.LoadIDAT(const Description); const RowStart: array[0..6] of Integer = (0, 0, 4, 0, 2, 0, 1); ColumnStart: array[0..6] of Integer = (0, 4, 0, 2, 0, 1, 0); RowIncrement: array[0..6] of Integer = (8, 8, 8, 4, 4, 2, 2); ColumnIncrement: array[0..6] of Integer = (8, 8, 4, 4, 2, 2, 1); PassMask: array[0..6] of Byte = ($80, $08, $88, $22, $AA, $55, $FF); var Row: Integer; TargetBPP: Integer; RowBuffer: array[Boolean] of PAnsiChar; // Serge EvenRow: Boolean; Pass: Integer; BytesPerRow, InterlaceRowBytes, InterlaceWidth: Integer; begin Progress(Self, psStarting, 0, False, FProgressRect, gesTransfering); RowBuffer[False] := nil; RowBuffer[True] := nil; try if PixelFormat = pfDevice then FSourceBPP := SetupColorDepth(TIHDRChunk(Description).ColorType, TIHDRChunk(Description).BitDepth); if TIHDRChunk(Description).BitDepth = 16 then TargetBPP := FSourceBPP div 2 else TargetBPP := FSourceBPP; if FPalette <> 0 then Palette := FPalette; Width := TIHDRChunk(Description).Width; Height := TIHDRChunk(Description).Height; Canvas.Lock; try Canvas.Brush.Color := FBackgroundColor; Canvas.FillRect(Rect(0, 0, Width, Height)); finally Canvas.Unlock; end; if FTransparentColor <> clNone then begin TransparentColor := FTransparentColor; Transparent := True; end; BytesPerRow := TargetBPP * ((Width * TIHDRChunk(Description).BitDepth + 7) div 8) + 1; RowBuffer[True] := AllocMem(BytesPerRow); RowBuffer[False] := AllocMem(BytesPerRow); EvenRow := True; if TIHDRChunk(Description).Interlaced = 1 then begin for Pass := 0 to 6 do begin if Width <= ColumnStart[Pass] then Continue; InterlaceWidth := (Width + ColumnIncrement[Pass] - 1 - ColumnStart[Pass]) div ColumnIncrement[Pass]; InterlaceRowBytes := TargetBPP * ((InterlaceWidth * TIHDRChunk(Description).BitDepth + 7) div 8) + 1; Row := RowStart[Pass]; while Row < Height do begin ReadRow(RowBuffer[EvenRow], InterlaceRowBytes); ApplyFilter(Byte(RowBuffer[EvenRow]^), Pointer(RowBuffer[EvenRow] + 1), Pointer(RowBuffer[not EvenRow] + 1), Pointer(RowBuffer[EvenRow] + 1), FSourceBPP, InterlaceRowBytes - 1); ColorManager.ConvertRow([Pointer(RowBuffer[EvenRow] + 1)], ScanLine[Row], Width, PassMask[Pass]); EvenRow := not EvenRow; Inc(Row, RowIncrement[Pass]); if Pass = 6 then begin // 7.22 Progress(Self, psRunning, MulDiv(Row, 100, Height), True, FProgressRect, ''); OffsetRect(FProgressRect, 0, 1); end; end; end; end else begin for Row := 0 to Height - 1 do begin ReadRow(RowBuffer[EvenRow], BytesPerRow); ApplyFilter(Byte(RowBuffer[EvenRow]^), Pointer(RowBuffer[EvenRow] + 1), Pointer(RowBuffer[not EvenRow] + 1), Pointer(RowBuffer[EvenRow] + 1), FSourceBPP, BytesPerRow - 1); ColorManager.ConvertRow([Pointer(RowBuffer[EvenRow] + 1)], ScanLine[Row], Width, $FF); EvenRow := not EvenRow; // 7.22 Progress(Self, psRunning, MulDiv(Row, 100, Height), True, FProgressRect, ''); OffsetRect(FProgressRect, 0, 1); end; end; while IsChunk(IDAT) do begin ReadDataAndCheckCRC; FCurrentCRC := LoadAndSwapHeader; end; finally if Assigned(RowBuffer[True]) then FreeMem(RowBuffer[True]); if Assigned(RowBuffer[False]) then FreeMem(RowBuffer[False]); end; end; procedure TPNGGraphic.LoadTransparency(const Description); var Run: PWord; R, G, B: Byte; begin ReadDataAndCheckCRC; with TIHDRChunk(Description) do begin case ColorType of 0: begin case BitDepth of 2: R := MulDiv16(Swap(PWord(FRawBuffer)^), 15, 3); 16: R := MulDiv16(Swap(PWord(FRawBuffer)^), 255, 65535); else R := Byte(Swap(PWord(FRawBuffer)^)); end; FTransparentColor := RGB(R, R, R); end; 2: begin Run := FRawBuffer; if BitDepth = 16 then begin R := MulDiv16(Swap(Run^), 255, 65535); Inc(Run); G := MulDiv16(Swap(Run^), 255, 65535); Inc(Run); B := MulDiv16(Swap(Run^), 255, 65535); end else begin R := Byte(Swap(Run^)); Inc(Run); G := Byte(Swap(Run^)); Inc(Run); B := Byte(Swap(Run^)); end; FTransparentColor := RGB(R, G, B); end; 4, 6: else SetLength(FTransparency, 256); Move(FRawBuffer^, FTransparency[0], Max(FHeader.Length, 256)); if FHeader.Length < 256 then FillChar(FTransparency[FHeader.Length], 256 - FHeader.Length, $FF); end; end; end; procedure TPNGGraphic.ReadDataAndCheckCRC; var FileCRC: Cardinal; begin ReallocMem(FRawBuffer, FHeader.Length); FStream.ReadBuffer(FRawBuffer^, FHeader.Length); FStream.ReadBuffer(FileCRC, SizeOf(FileCRC)); FileCRC := SwapLong(FileCRC); FCurrentCRC := CRC32(FCurrentCRC, FRawBuffer, FHeader.Length); if FCurrentCRC <> FileCRC then GraphicExError(gesInvalidCRC, ['PNG']); end; procedure TPNGGraphic.ReadRow(RowBuffer: Pointer; BytesPerRow: Integer); var LocalBuffer: Pointer; PendingOutput: Integer; begin LocalBuffer := RowBuffer; PendingOutput := BytesPerRow; repeat if FDecoder.AvailableInput = 0 then begin FIDATSize := 0; while FIDATSize = 0 do begin if not IsChunk(IDAT) then Exit; ReadDataAndCheckCRC; FCurrentSource := FRawBuffer; FIDATSize := FHeader.Length; FCurrentCRC := LoadAndSwapHeader; end; end; FDecoder.Decode(FCurrentSource, LocalBuffer, FIDATSize - (Integer(FCurrentSource) - Integer(FRawBuffer)), PendingOutput); if FDecoder.ZLibResult = Z_STREAM_END then begin if (FDecoder.AvailableOutput <> 0) or (FDecoder.AvailableInput <> 0) then GraphicExError(gesExtraCompressedData, ['PNG']); Break; end; if FDecoder.ZLibResult <> Z_OK then GraphicExError(gesCompression, ['PNG']); PendingOutput := BytesPerRow - (Integer(LocalBuffer) - Integer(RowBuffer)); until PendingOutput = 0; end; function TPNGGraphic.SetupColorDepth(ColorType, BitDepth: Integer): Integer; begin Result := 0; case ColorType of 0: if BitDepth in [1, 2, 4, 8, 16] then with ColorManager do begin SourceColorScheme := csG; TargetColorScheme := csG; SourceSamplesPerPixel := 1; TargetSamplesPerPixel := 1; SourceBitsPerSample := BitDepth; case BitDepth of 2: TargetBitsPerSample := 4; 16: TargetBitsPerSample := 8; else TargetBitsPerSample := BitDepth; end; PixelFormat := TargetPixelFormat; FPalette := CreateGrayscalePalette(False); Result := (BitDepth + 7) div 8; end else GraphicExError(gesInvalidColorFormat, ['PNG']); 2: if BitDepth in [8, 16] then with ColorManager do begin SourceSamplesPerPixel := 3; TargetSamplesPerPixel := 3; SourceColorScheme := csRGB; TargetColorScheme := csBGR; SourceBitsPerSample := BitDepth; TargetBitsPerSample := 8; PixelFormat := pf24Bit; Result := BitDepth * 3 div 8; end else GraphicExError(gesInvalidColorFormat, ['PNG']); 3: if BitDepth in [1, 2, 4, 8] then with ColorManager do begin SourceColorScheme := csIndexed; TargetColorScheme := csIndexed; SourceSamplesPerPixel := 1; TargetSamplesPerPixel := 1; SourceBitsPerSample := BitDepth; if BitDepth = 2 then TargetBitsPerSample := 4 else TargetBitsPerSample := BitDepth; PixelFormat := TargetPixelFormat; Result := 1; end else GraphicExError(gesInvalidColorFormat, ['PNG']); 4: if BitDepth in [8, 16] then with ColorManager do begin SourceSamplesPerPixel := 1; TargetSamplesPerPixel := 1; SourceBitsPerSample := BitDepth; TargetBitsPerSample := 8; SourceColorScheme := csGA; TargetColorScheme := csIndexed; PixelFormat := pf8Bit; FPalette := CreateGrayScalePalette(False); Result := 2 * BitDepth div 8; end else GraphicExError(gesInvalidColorFormat, ['PNG']); 6: if BitDepth in [8, 16] then with ColorManager do begin SourceSamplesPerPixel := 4; TargetSamplesPerPixel := 4; SourceColorScheme := csRGBA; TargetColorScheme := csBGRA; SourceBitsPerSample := BitDepth; TargetBitsPerSample := 8; PixelFormat := pf32Bit; Result := BitDepth * 4 div 8; end else GraphicExError(gesInvalidColorFormat, ['PNG']); else GraphicExError(gesInvalidColorFormat, ['PNG']); end; end; constructor TPNGGraphic.Create; begin inherited; FColorManager := TColorManager.Create; Reflected := False; end; destructor TPNGGraphic.Destroy; begin FreeAndNil(FColorManager); inherited; end; procedure TPNGGraphic.Assign(Source: TPersistent); begin if Source is TPNGGraphic then FImageProperties := TPNGGraphic(Source).FImageProperties; inherited; end; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// type EColorConversionError = class(Exception); PCMYK = ^TCMYK; TCMYK = packed record C, M, Y, K: Byte; end; PCMYK16 = ^TCMYK16; TCMYK16 = packed record C, M, Y, K: Word; end; PCMY = ^TCMY; TCMY = packed record C, M, Y: Byte; end; PCMY16 = ^TCMY16; TCMY16 = packed record C, M, Y: Word; end; PRGB = ^TRGB; TRGB = packed record R, G, B: Byte; end; PRGB16 = ^TRGB16; TRGB16 = packed record R, G, B: Word; end; PRGBA = ^TRGBA; TRGBA = packed record R, G, B, A: Byte; end; PRGBA16 = ^TRGBA16; TRGBA16 = packed record R, G, B, A: Word; end; PBGR = ^TBGR; TBGR = packed record B, G, R: Byte; end; PBGR16 = ^TBGR16; TBGR16 = packed record B, G, R: Word; end; PBGRA = ^TBGRA; TBGRA = packed record B, G, R, A: Byte; end; PBGRA16 = ^TBGRA16; TBGRA16 = packed record B, G, R, A: Word; end; function ClampByte(Value: Integer): Byte; asm OR EAX, EAX JNS @@positive XOR EAX, EAX RET @@positive: CMP EAX, 255 JBE @@OK MOV EAX, 255 @@OK: end; function MulDiv16(Number, Numerator, Denominator: Word): Word; asm MUL DX DIV CX end; constructor TColorManager.Create; begin FSourceBPS := 8; FTargetBPS := 8; FSourceSPP := 3; FTargetSPP := 3; SetGamma(1, DefaultDisplayGamma); FSourceScheme := csRGB; FTargetScheme := csBGR; FYCbCrCoefficients[0] := 0.299; FYCbCrCoefficients[1] := 0.587; FYCbCrCoefficients[2] := 0.114; FHSubSampling := 1; FVSubSampling := 1; FChanged := True; end; function TColorManager.ComponentNoConvert8(Value: Byte): Byte; begin Result := Value; end; function TColorManager.ComponentNoConvert16(Value: Word): Word; begin Result := Value; end; function TColorManager.ComponentGammaConvert(Value: Byte): Byte; begin Result := FGammaTable[Value]; end; function TColorManager.ComponentScaleConvert(Value: Word): Byte; begin Result := MulDiv16(Value, 255, 65535); end; function TColorManager.ComponentScaleGammaConvert(Value: Word): Byte; begin Result := FGammaTable[MulDiv16(Value, 255, 65535)]; end; function TColorManager.ComponentSwapScaleGammaConvert(Value: Word): Byte; begin Result := FGammaTable[MulDiv16(Swap(Value), 255, 65535)]; end; function TColorManager.ComponentSwapScaleConvert(Value: Word): Byte; begin Result := MulDiv16(Swap(Value), 255, 65535); end; function TColorManager.ComponentSwapConvert(Value: Word): Word; begin Result := Swap(Value); end; procedure TColorManager.RowConvertBGR2BGR(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); var SourceR16, SourceG16, SourceB16, SourceA16: PWord; SourceR8, SourceG8, SourceB8, SourceA8: PByte; TargetRun16: PBGR16; TargetRunA16: PBGRA16; TargetRun8: PBGR; TargetRunA8: PBGRA; BitRun: Byte; Convert8_8: function(Value: Byte): Byte of object; Convert16_8: function(Value: Word): Byte of object; Convert16_8Alpha: function(Value: Word): Byte of object; Convert16_16: function(Value: Word): Word of object; SourceIncrement, TargetIncrement: Cardinal; CopyAlpha: Boolean; begin BitRun := $80; CopyAlpha := False; if coAlpha in FSourceOptions then begin SourceIncrement := SizeOf(TRGBA); TargetIncrement := SizeOf(TRGB); if coAlpha in FTargetOptions then CopyAlpha := True; end else begin SourceIncrement := SizeOf(TRGB); if coAlpha in FTargetOptions then TargetIncrement := SizeOf(TRGBA) else TargetIncrement := SizeOf(TRGB); end; if Length(Source) > 1 then SourceIncrement := 1; case FSourceBPS of 8: begin if Length(Source) = 1 then begin SourceB8 := Source[0]; SourceG8 := SourceB8; Inc(SourceG8); SourceR8 := SourceG8; Inc(SourceR8); SourceA8 := SourceR8; Inc(SourceA8); end else begin SourceB8 := Source[0]; SourceG8 := Source[1]; SourceR8 := Source[2]; if coAlpha in FSourceOptions then SourceA8 := Source[3] else SourceA8 := nil; end; case FTargetBPS of 8: begin if coApplyGamma in FTargetOptions then Convert8_8 := ComponentGammaConvert else Convert8_8 := ComponentNoConvert8; if CopyAlpha then begin TargetRunA8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRunA8.R := Convert8_8(SourceR8^); TargetRunA8.G := Convert8_8(SourceG8^); TargetRunA8.B := Convert8_8(SourceB8^); TargetRunA8.A := SourceA8^; Inc(SourceB8, SourceIncrement); Inc(SourceG8, SourceIncrement); Inc(SourceR8, SourceIncrement); Inc(SourceA8, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(TargetRunA8); end; end else begin TargetRun8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRun8.R := Convert8_8(SourceR8^); TargetRun8.G := Convert8_8(SourceG8^); TargetRun8.B := Convert8_8(SourceB8^); Inc(SourceB8, SourceIncrement); Inc(SourceG8, SourceIncrement); Inc(SourceR8, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(PByte(TargetRun8), TargetIncrement); end; end; end; 16: begin if coApplyGamma in FTargetOptions then Convert8_8 := ComponentGammaConvert else Convert8_8 := ComponentNoConvert8; if coNeedByteSwap in FSourceOptions then Convert16_16 := ComponentSwapConvert else Convert16_16 := ComponentNoConvert16; if Length(Source) = 1 then begin SourceB8 := Source[0]; SourceG8 := SourceB8; Inc(SourceG8); SourceR8 := SourceG8; Inc(SourceR8); SourceA8 := SourceR8; Inc(SourceA8); end else begin SourceB8 := Source[0]; SourceG8 := Source[1]; SourceR8 := Source[2]; if coAlpha in FSourceOptions then SourceA8 := Source[3] else SourceA8 := nil; end; if CopyAlpha then begin TargetRunA16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRunA16.R := Convert16_16(MulDiv16(Convert8_8(SourceR8^), 65535, 255)); TargetRunA16.G := Convert16_16(MulDiv16(Convert8_8(SourceG8^), 65535, 255)); TargetRunA16.B := Convert16_16(MulDiv16(Convert8_8(SourceB8^), 65535, 255)); TargetRunA16.A := Convert16_16(MulDiv16(SourceA8^, 65535, 255)); Inc(SourceB8, SourceIncrement); Inc(SourceG8, SourceIncrement); Inc(SourceR8, SourceIncrement); Inc(SourceA8, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(TargetRunA16); end; end else begin TargetRun16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRun16.R := Convert16_16(MulDiv16(Convert8_8(SourceR8^), 65535, 255)); TargetRun16.G := Convert16_16(MulDiv16(Convert8_8(SourceG8^), 65535, 255)); TargetRun16.B := Convert16_16(MulDiv16(Convert8_8(SourceB8^), 65535, 255)); Inc(SourceB8, SourceIncrement); Inc(SourceG8, SourceIncrement); Inc(SourceR8, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(PWord(TargetRun16), TargetIncrement); end; end; end; end; end; 16: begin if Length(Source) = 1 then begin SourceB16 := Source[0]; SourceG16 := SourceB16; Inc(SourceG16); SourceR16 := SourceG16; Inc(SourceR16); SourceA16 := SourceR16; Inc(SourceA16); end else begin SourceB16 := Source[0]; SourceG16 := Source[1]; SourceR16 := Source[2]; if coAlpha in FSourceOptions then SourceA16 := Source[3] else SourceA16 := nil; end; case FTargetBPS of 8: begin if coApplyGamma in FTargetOptions then begin if coNeedByteSwap in FSourceOptions then Convert16_8 := ComponentSwapScaleGammaConvert else Convert16_8 := ComponentScaleGammaConvert; end else begin if coNeedByteSwap in FSourceOptions then Convert16_8 := ComponentSwapScaleConvert else Convert16_8 := ComponentScaleConvert; end; if coNeedByteSwap in FSourceOptions then Convert16_8Alpha := ComponentSwapScaleConvert else Convert16_8Alpha := ComponentScaleConvert; if CopyAlpha then begin TargetRunA8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRunA8.R := Convert16_8(SourceR16^); TargetRunA8.G := Convert16_8(SourceG16^); TargetRunA8.B := Convert16_8(SourceB16^); TargetRunA8.A := Convert16_8Alpha(SourceA16^); Inc(SourceB16, SourceIncrement); Inc(SourceG16, SourceIncrement); Inc(SourceR16, SourceIncrement); Inc(SourceA16, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(TargetRunA8); end; end else begin TargetRun8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRun8.R := Convert16_8(SourceR16^); TargetRun8.G := Convert16_8(SourceG16^); TargetRun8.B := Convert16_8(SourceB16^); Inc(SourceB16, SourceIncrement); Inc(SourceG16, SourceIncrement); Inc(SourceR16, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(PByte(TargetRun8), TargetIncrement); end; end; end; 16: begin if coNeedByteSwap in FSourceOptions then Convert16_16 := ComponentSwapConvert else Convert16_16 := ComponentNoConvert16; if Length(Source) = 1 then begin SourceB16 := Source[0]; SourceG16 := SourceB16; Inc(SourceG16); SourceR16 := SourceG16; Inc(SourceR16); SourceA16 := SourceR16; Inc(SourceA16); end else begin SourceB16 := Source[0]; SourceG16 := Source[1]; SourceR16 := Source[2]; if coAlpha in FSourceOptions then SourceA16 := Source[3] else SourceA16 := nil; end; if CopyAlpha then begin TargetRunA16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRunA16.R := Convert16_16(SourceR16^); TargetRunA16.G := Convert16_16(SourceG16^); TargetRunA16.B := Convert16_16(SourceB16^); TargetRunA16.A := Convert16_16(SourceA16^); Inc(SourceB16, SourceIncrement); Inc(SourceG16, SourceIncrement); Inc(SourceR16, SourceIncrement); Inc(SourceA16, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(TargetRunA16); end; end else begin TargetRun16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRun16.R := Convert16_16(SourceR16^); TargetRun16.G := Convert16_16(SourceG16^); TargetRun16.B := Convert16_16(SourceB16^); Inc(SourceB16, SourceIncrement); Inc(SourceG16, SourceIncrement); Inc(SourceR16, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(PWord(TargetRun16), TargetIncrement); end; end; end; end; end; end; end; procedure TColorManager.RowConvertBGR2RGB(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); var SourceR16, SourceG16, SourceB16, SourceA16: PWord; SourceR8, SourceG8, SourceB8, SourceA8: PByte; TargetRun16: PRGB16; TargetRunA16: PRGBA16; TargetRun8: PRGB; TargetRunA8: PRGBA; BitRun: Byte; Convert8_8: function(Value: Byte): Byte of object; Convert16_8: function(Value: Word): Byte of object; Convert16_8Alpha: function(Value: Word): Byte of object; Convert16_16: function(Value: Word): Word of object; SourceIncrement, TargetIncrement: Cardinal; CopyAlpha: Boolean; begin BitRun := $80; CopyAlpha := False; if coAlpha in FSourceOptions then begin SourceIncrement := SizeOf(TRGBA); TargetIncrement := SizeOf(TRGB); if coAlpha in FTargetOptions then CopyAlpha := True; end else begin SourceIncrement := SizeOf(TRGB); if coAlpha in FTargetOptions then TargetIncrement := SizeOf(TRGBA) else TargetIncrement := SizeOf(TRGB); end; if Length(Source) > 1 then SourceIncrement := 1; case FSourceBPS of 8: begin if Length(Source) = 1 then begin SourceB8 := Source[0]; SourceG8 := SourceB8; Inc(SourceG8); SourceR8 := SourceG8; Inc(SourceR8); SourceA8 := SourceR8; Inc(SourceA8); end else begin SourceB8 := Source[0]; SourceG8 := Source[1]; SourceR8 := Source[2]; if coAlpha in FSourceOptions then SourceA8 := Source[3] else SourceA8 := nil; end; case FTargetBPS of 8: begin if coApplyGamma in FTargetOptions then Convert8_8 := ComponentGammaConvert else Convert8_8 := ComponentNoConvert8; if CopyAlpha then begin TargetRunA8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRunA8.R := Convert8_8(SourceR8^); TargetRunA8.G := Convert8_8(SourceG8^); TargetRunA8.B := Convert8_8(SourceB8^); TargetRunA8.A := SourceA8^; Inc(SourceB8, SourceIncrement); Inc(SourceG8, SourceIncrement); Inc(SourceR8, SourceIncrement); Inc(SourceA8, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(TargetRunA8); end; end else begin TargetRun8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRun8.R := Convert8_8(SourceR8^); TargetRun8.G := Convert8_8(SourceG8^); TargetRun8.B := Convert8_8(SourceB8^); Inc(SourceB8, SourceIncrement); Inc(SourceG8, SourceIncrement); Inc(SourceR8, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(PByte(TargetRun8), TargetIncrement); end; end; end; 16: begin if coApplyGamma in FTargetOptions then Convert8_8 := ComponentGammaConvert else Convert8_8 := ComponentNoConvert8; if coNeedByteSwap in FSourceOptions then Convert16_16 := ComponentSwapConvert else Convert16_16 := ComponentNoConvert16; if Length(Source) = 1 then begin SourceB8 := Source[0]; SourceG8 := SourceB8; Inc(SourceG8); SourceR8 := SourceG8; Inc(SourceR8); SourceA8 := SourceR8; Inc(SourceA8); end else begin SourceB8 := Source[0]; SourceG8 := Source[1]; SourceR8 := Source[2]; if coAlpha in FSourceOptions then SourceA8 := Source[3] else SourceA8 := nil; end; if CopyAlpha then begin TargetRunA16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRunA16.R := Convert16_16(MulDiv16(Convert8_8(SourceR8^), 65535, 255)); TargetRunA16.G := Convert16_16(MulDiv16(Convert8_8(SourceG8^), 65535, 255)); TargetRunA16.B := Convert16_16(MulDiv16(Convert8_8(SourceB8^), 65535, 255)); TargetRunA16.A := Convert16_16(MulDiv16(SourceA8^, 65535, 255)); Inc(SourceB8, SourceIncrement); Inc(SourceG8, SourceIncrement); Inc(SourceR8, SourceIncrement); Inc(SourceA8, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(TargetRunA16); end; end else begin TargetRun16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRun16.R := Convert16_16(MulDiv16(Convert8_8(SourceR8^), 65535, 255)); TargetRun16.G := Convert16_16(MulDiv16(Convert8_8(SourceG8^), 65535, 255)); TargetRun16.B := Convert16_16(MulDiv16(Convert8_8(SourceB8^), 65535, 255)); Inc(SourceB8, SourceIncrement); Inc(SourceG8, SourceIncrement); Inc(SourceR8, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(PWord(TargetRun16), TargetIncrement); end; end; end; end; end; 16: begin if Length(Source) = 1 then begin SourceB16 := Source[0]; SourceG16 := SourceB16; Inc(SourceG16); SourceR16 := SourceG16; Inc(SourceR16); SourceA16 := SourceR16; Inc(SourceA16); end else begin SourceB16 := Source[0]; SourceG16 := Source[1]; SourceR16 := Source[2]; if coAlpha in FSourceOptions then SourceA16 := Source[3] else SourceA16 := nil; end; case FTargetBPS of 8: begin if coApplyGamma in FTargetOptions then begin if coNeedByteSwap in FSourceOptions then Convert16_8 := ComponentSwapScaleGammaConvert else Convert16_8 := ComponentScaleGammaConvert; end else begin if coNeedByteSwap in FSourceOptions then Convert16_8 := ComponentSwapScaleConvert else Convert16_8 := ComponentScaleConvert; end; if coNeedByteSwap in FSourceOptions then Convert16_8Alpha := ComponentSwapScaleConvert else Convert16_8Alpha := ComponentScaleConvert; if CopyAlpha then begin TargetRunA8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRunA8.R := Convert16_8(SourceR16^); TargetRunA8.G := Convert16_8(SourceG16^); TargetRunA8.B := Convert16_8(SourceB16^); TargetRunA8.A := Convert16_8Alpha(SourceA16^); Inc(SourceB16, SourceIncrement); Inc(SourceG16, SourceIncrement); Inc(SourceR16, SourceIncrement); Inc(SourceA16, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(TargetRunA8); end; end else begin TargetRun8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRun8.R := Convert16_8(SourceR16^); TargetRun8.G := Convert16_8(SourceG16^); TargetRun8.B := Convert16_8(SourceB16^); Inc(SourceB16, SourceIncrement); Inc(SourceG16, SourceIncrement); Inc(SourceR16, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(PByte(TargetRun8), TargetIncrement); end; end; end; 16: begin if coNeedByteSwap in FSourceOptions then Convert16_16 := ComponentSwapConvert else Convert16_16 := ComponentNoConvert16; if Length(Source) = 1 then begin SourceB16 := Source[0]; SourceG16 := SourceB16; Inc(SourceG16); SourceR16 := SourceG16; Inc(SourceR16); SourceA16 := SourceR16; Inc(SourceA16); end else begin SourceB16 := Source[0]; SourceG16 := Source[1]; SourceR16 := Source[2]; if coAlpha in FSourceOptions then SourceA16 := Source[3] else SourceA16 := nil; end; if CopyAlpha then begin TargetRunA16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRunA16.R := Convert16_16(SourceR16^); TargetRunA16.G := Convert16_16(SourceG16^); TargetRunA16.B := Convert16_16(SourceB16^); TargetRunA16.A := Convert16_16(SourceA16^); Inc(SourceB16, SourceIncrement); Inc(SourceG16, SourceIncrement); Inc(SourceR16, SourceIncrement); Inc(SourceA16, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(TargetRunA16); end; end else begin TargetRun16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRun16.R := Convert16_16(SourceR16^); TargetRun16.G := Convert16_16(SourceG16^); TargetRun16.B := Convert16_16(SourceB16^); Inc(SourceB16, SourceIncrement); Inc(SourceG16, SourceIncrement); Inc(SourceR16, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(PWord(TargetRun16), TargetIncrement); end; end; end; end; end; end; end; procedure TColorManager.RowConvertCIELAB2BGR(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); var LRun8, aRun8, bRun8: PByte; LRun16, aRun16, bRun16: PWord; L, a, b, X, Y, Z, T, YYn3: Extended; Target8: PByte; Target16: PWord; Increment: Integer; AlphaSkip: Integer; BitRun: Byte; begin BitRun := $80; AlphaSkip := Ord(coAlpha in FTargetOptions); case FSourceBPS of 8: begin if Length(Source) = 1 then begin LRun8 := Source[0]; aRun8 := LRun8; Inc(aRun8); bRun8 := aRun8; Inc(bRun8); Increment := 3; end else begin LRun8 := Source[0]; aRun8 := Source[1]; bRun8 := Source[2]; Increment := 1; end; case FTargetBPS of 8: begin Target8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin if coLabByteRange in FSourceOptions then L := LRun8^ / 2.55 else L := LRun8^; Inc(LRun8, Increment); if coLabChromaOffset in FSourceOptions then begin a := aRun8^ - 128; Inc(aRun8, Increment); b := bRun8^ - 128; Inc(bRun8, Increment); end else begin a := ShortInt(aRun8^); Inc(aRun8, Increment); b := ShortInt(bRun8^); Inc(bRun8, Increment); end; YYn3 := (L + 16) / 116; if L < 7.9996 then begin Y := L / 903.3; X := a / 3893.5 + Y; Z := Y - b / 1557.4; end else begin T := YYn3 + a / 500; X := T * T * T; Y := YYn3 * YYn3 * YYn3; T := YYn3 - b / 200; Z := T * T * T; end; Target8^ := ClampByte(Round(255 * ( 0.099 * X - 0.198 * Y + 1.099 * Z))); Inc(Target8); Target8^ := ClampByte(Round(255 * (-0.952 * X + 1.893 * Y + 0.059 * Z))); Inc(Target8); Target8^ := ClampByte(Round(255 * ( 2.998 * X - 1.458 * Y - 0.541 * Z))); Inc(Target8, 1 + AlphaSkip); end else Inc(Target8, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; 16: begin Target16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin if coLabByteRange in FSourceOptions then L := LRun8^ / 2.55 else L := LRun8^; Inc(LRun8, Increment); if coLabChromaOffset in FSourceOptions then begin a := aRun8^ - 128; Inc(aRun8, Increment); b := bRun8^ - 128; Inc(bRun8, Increment); end else begin a := ShortInt(aRun8^); Inc(aRun8, Increment); b := ShortInt(bRun8^); Inc(bRun8, Increment); end; YYn3 := (L + 16) / 116; if L < 7.9996 then begin Y := L / 903.3; X := a / 3893.5 + Y; Z := Y - b / 1557.4; end else begin T := YYn3 + a / 500; X := T * T * T; Y := YYn3 * YYn3 * YYn3; T := YYn3 - b / 200; Z := T * T * T; end; Target16^ := MulDiv16(ClampByte(Round(255 * ( 0.099 * X - 0.198 * Y + 1.099 * Z))), 65535, 255); Inc(Target16); Target16^ := MulDiv16(ClampByte(Round(255 * (-0.952 * X + 1.893 * Y + 0.059 * Z))), 65535, 255); Inc(Target16); Target16^ := MulDiv16(ClampByte(Round(255 * ( 2.998 * X - 1.458 * Y - 0.541 * Z))), 65535, 255); Inc(Target16, 1 + AlphaSkip); end else Inc(Target16, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end end; end; end; 16: begin if Length(Source) = 1 then begin LRun16 := Source[0]; aRun16 := LRun16; Inc(aRun16); bRun16 := aRun16; Inc(bRun16); Increment := 3; end else begin LRun16 := Source[0]; aRun16 := Source[1]; bRun16 := Source[2]; Increment := 1; end; case FTargetBPS of 8: begin Target8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin if coLabByteRange in FSourceOptions then L := LRun16^ / 2.55 else L := LRun16^; Inc(LRun16, Increment); if coLabChromaOffset in FSourceOptions then begin a := aRun16^ - 128; Inc(aRun16, Increment); b := bRun16^ - 128; Inc(bRun16, Increment); end else begin a := ShortInt(aRun16^); Inc(aRun16, Increment); b := ShortInt(bRun16^); Inc(bRun16, Increment); end; YYn3 := (L + 16) / 116; if L < 7.9996 then begin Y := L / 903.3; X := a / 3893.5 + Y; Z := Y - b / 1557.4; end else begin T := YYn3 + a / 500; X := T * T * T; Y := YYn3 * YYn3 * YYn3; T := YYn3 - b / 200; Z := T * T * T; end; Target8^ := ClampByte(Round(255 * ( 0.099 * X - 0.198 * Y + 1.099 * Z))); Inc(Target8); Target8^ := ClampByte(Round(255 * (-0.952 * X + 1.893 * Y + 0.059 * Z))); Inc(Target8); Target8^ := ClampByte(Round(255 * ( 2.998 * X - 1.458 * Y - 0.541 * Z))); Inc(Target8, 1 + AlphaSkip); end else Inc(Target8, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; 16: begin Target16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin if coLabByteRange in FSourceOptions then L := LRun16^ / 2.55 else L := LRun16^; Inc(LRun16, Increment); if coLabChromaOffset in FSourceOptions then begin a := aRun16^ - 128; Inc(aRun16, Increment); b := bRun16^ - 128; Inc(bRun16, Increment); end else begin a := ShortInt(aRun16^); Inc(aRun16, Increment); b := ShortInt(bRun16^); Inc(bRun16, Increment); end; YYn3 := (L + 16) / 116; if L < 7.9996 then begin Y := L / 903.3; X := a / 3893.5 + Y; Z := Y - b / 1557.4; end else begin T := YYn3 + a / 500; X := T * T * T; Y := YYn3 * YYn3 * YYn3; T := YYn3 - b / 200; Z := T * T * T; end; Target16^ := ClampByte(Round(255 * ( 0.099 * X - 0.198 * Y + 1.099 * Z))); Inc(Target16); Target16^ := ClampByte(Round(255 * (-0.952 * X + 1.893 * Y + 0.059 * Z))); Inc(Target16); Target16^ := ClampByte(Round(255 * ( 2.998 * X - 1.458 * Y - 0.541 * Z))); Inc(Target16, 1 + AlphaSkip); end else Inc(Target16, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; end; end; end; end; procedure TColorManager.RowConvertCIELAB2RGB(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); var LRun8, aRun8, bRun8: PByte; LRun16, aRun16, bRun16: PWord; L, a, b, X, Y, Z, T, YYn3: Extended; Target8: PByte; Target16: PWord; Increment: Integer; AlphaSkip: Integer; BitRun: Byte; begin BitRun := $80; AlphaSkip := Ord(coAlpha in FTargetOptions); case FSourceBPS of 8: begin if Length(Source) = 1 then begin LRun8 := Source[0]; aRun8 := LRun8; Inc(aRun8); bRun8 := aRun8; Inc(bRun8); Increment := 3; end else begin LRun8 := Source[0]; aRun8 := Source[1]; bRun8 := Source[2]; Increment := 1; end; case FTargetBPS of 8: begin Target8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin if coLabByteRange in FSourceOptions then L := LRun8^ / 2.55 else L := LRun8^; Inc(LRun8, Increment); if coLabChromaOffset in FSourceOptions then begin a := aRun8^ - 128; Inc(aRun8, Increment); b := bRun8^ - 128; Inc(bRun8, Increment); end else begin a := ShortInt(aRun8^); Inc(aRun8, Increment); b := ShortInt(bRun8^); Inc(bRun8, Increment); end; YYn3 := (L + 16) / 116; if L < 7.9996 then begin Y := L / 903.3; X := a / 3893.5 + Y; Z := Y - b / 1557.4; end else begin T := YYn3 + a / 500; X := T * T * T; Y := YYn3 * YYn3 * YYn3; T := YYn3 - b / 200; Z := T * T * T; end; Target8^ := ClampByte(Round(255 * ( 2.998 * X - 1.458 * Y - 0.541 * Z))); Inc(Target8); Target8^ := ClampByte(Round(255 * (-0.952 * X + 1.893 * Y + 0.059 * Z))); Inc(Target8); Target8^ := ClampByte(Round(255 * ( 0.099 * X - 0.198 * Y + 1.099 * Z))); Inc(Target8, 1 + AlphaSkip); end else Inc(Target8, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; 16: begin Target16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin if coLabByteRange in FSourceOptions then L := LRun8^ / 2.55 else L := LRun8^; Inc(LRun8, Increment); if coLabChromaOffset in FSourceOptions then begin a := aRun8^ - 128; Inc(aRun8, Increment); b := bRun8^ - 128; Inc(bRun8, Increment); end else begin a := ShortInt(aRun8^); Inc(aRun8, Increment); b := ShortInt(bRun8^); Inc(bRun8, Increment); end; YYn3 := (L + 16) / 116; if L < 7.9996 then begin Y := L / 903.3; X := a / 3893.5 + Y; Z := Y - b / 1557.4; end else begin T := YYn3 + a / 500; X := T * T * T; Y := YYn3 * YYn3 * YYn3; T := YYn3 - b / 200; Z := T * T * T; end; Target16^ := MulDiv16(ClampByte(Round(255 * ( 2.998 * X - 1.458 * Y - 0.541 * Z))), 65535, 255); Inc(Target16); Target16^ := MulDiv16(ClampByte(Round(255 * (-0.952 * X + 1.893 * Y + 0.059 * Z))), 65535, 255); Inc(Target16); Target16^ := MulDiv16(ClampByte(Round(255 * ( 0.099 * X - 0.198 * Y + 1.099 * Z))), 65535, 255); Inc(Target16, 1 + AlphaSkip); end else Inc(Target16, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end end; end; end; 16: begin if Length(Source) = 1 then begin LRun16 := Source[0]; aRun16 := LRun16; Inc(aRun16); bRun16 := aRun16; Inc(bRun16); Increment := 3; end else begin LRun16 := Source[0]; aRun16 := Source[1]; bRun16 := Source[2]; Increment := 1; end; case FTargetBPS of 8: begin Target8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin if coLabByteRange in FSourceOptions then L := LRun16^ / 2.55 else L := LRun16^; Inc(LRun16, Increment); if coLabChromaOffset in FSourceOptions then begin a := aRun16^ - 128; Inc(aRun16, Increment); b := bRun16^ - 128; Inc(bRun16, Increment); end else begin a := ShortInt(aRun16^); Inc(aRun16, Increment); b := ShortInt(bRun16^); Inc(bRun16, Increment); end; YYn3 := (L + 16) / 116; if L < 7.9996 then begin Y := L / 903.3; X := a / 3893.5 + Y; Z := Y - b / 1557.4; end else begin T := YYn3 + a / 500; X := T * T * T; Y := YYn3 * YYn3 * YYn3; T := YYn3 - b / 200; Z := T * T * T; end; Target8^ := ClampByte(Round(255 * ( 2.998 * X - 1.458 * Y - 0.541 * Z))); Inc(Target8); Target8^ := ClampByte(Round(255 * (-0.952 * X + 1.893 * Y + 0.059 * Z))); Inc(Target8); Target8^ := ClampByte(Round(255 * ( 0.099 * X - 0.198 * Y + 1.099 * Z))); Inc(Target8, 1 + AlphaSkip); end else Inc(Target8, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; 16: begin Target16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin if coLabByteRange in FSourceOptions then L := LRun16^ / 2.55 else L := LRun16^; Inc(LRun16, Increment); if coLabChromaOffset in FSourceOptions then begin a := aRun16^ - 128; Inc(aRun16, Increment); b := bRun16^ - 128; Inc(bRun16, Increment); end else begin a := ShortInt(aRun16^); Inc(aRun16, Increment); b := ShortInt(bRun16^); Inc(bRun16, Increment); end; YYn3 := (L + 16) / 116; if L < 7.9996 then begin Y := L / 903.3; X := a / 3893.5 + Y; Z := Y - b / 1557.4; end else begin T := YYn3 + a / 500; X := T * T * T; Y := YYn3 * YYn3 * YYn3; T := YYn3 - b / 200; Z := T * T * T; end; Target16^ := ClampByte(Round(255 * ( 2.998 * X - 1.458 * Y - 0.541 * Z))); Inc(Target16); Target16^ := ClampByte(Round(255 * (-0.952 * X + 1.893 * Y + 0.059 * Z))); Inc(Target16); Target16^ := ClampByte(Round(255 * ( 0.099 * X - 0.198 * Y + 1.099 * Z))); Inc(Target16, 1 + AlphaSkip); end else Inc(Target16, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; end; end; end; end; procedure TColorManager.RowConvertCMYK2BGR(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); var C8, M8, Y8, K8: PByte; C16, M16, Y16, K16: PWord; Target8: PByte; Target16: PWord; Increment: Integer; AlphaSkip: Integer; BitRun: Byte; begin BitRun := $80; AlphaSkip := Ord(coAlpha in FTargetOptions); case FSourceBPS of 8: begin if Length(Source) = 4 then begin C8 := Source[0]; M8 := Source[1]; Y8 := Source[2]; K8 := Source[3]; Increment := 1; end else begin C8 := Source[0]; M8 := C8; Inc(M8); Y8 := M8; Inc(Y8); K8 := Y8; Inc(K8); Increment := 4; end; case FTargetBPS of 8: begin Target8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin Target8^ := ClampByte(255 - (Y8^ - MulDiv16(Y8^, K8^, 255) + K8^)); Inc(Target8); Target8^ := ClampByte(255 - (M8^ - MulDiv16(M8^, K8^, 255) + K8^)); Inc(Target8); Target8^ := ClampByte(255 - (C8^ - MulDiv16(C8^, K8^, 255) + K8^)); Inc(Target8, 1 + AlphaSkip); Inc(C8, Increment); Inc(M8, Increment); Inc(Y8, Increment); Inc(K8, Increment); end else Inc(Target8, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; 16: begin Target16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin Target16^ := MulDiv16(ClampByte(255 - (Y8^ - MulDiv16(Y8^, K8^, 255) + K8^)), 65535, 255); Inc(Target16); Target16^ := MulDiv16(ClampByte(255 - (M8^ - MulDiv16(M8^, K8^, 255) + K8^)), 65535, 255); Inc(Target16); Target16^ := MulDiv16(ClampByte(255 - (C8^ - MulDiv16(C8^, K8^, 255) + K8^)), 65535, 255); Inc(Target16, 1 + AlphaSkip); Inc(C8, Increment); Inc(M8, Increment); Inc(Y8, Increment); Inc(K8, Increment); end else Inc(Target16, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; end; end; 16: begin if Length(Source) = 4 then begin C16 := Source[0]; M16 := Source[1]; Y16 := Source[2]; K16 := Source[3]; Increment := 1; end else begin C16 := Source[0]; M16 := C16; Inc(M16); Y16 := M16; Inc(Y16); K16 := Y16; Inc(K16); Increment := 4; end; case FTargetBPS of 8: // 161616 to 888 begin Target8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin // blue Target8^ := ClampByte(255 - MulDiv16((Y16^ - MulDiv16(Y16^, K16^, 65535) + K16^), 255, 65535)); Inc(Target8); // green Target8^ := ClampByte(255 - MulDiv16((M16^ - MulDiv16(M16^, K16^, 65535) + K16^), 255, 65535)); Inc(Target8); // blue Target8^ := ClampByte(255 - MulDiv16((C16^ - MulDiv16(C16^, K16^, 65535) + K16^), 255, 65535)); Inc(Target8, 1 + AlphaSkip); Inc(C16, Increment); Inc(M16, Increment); Inc(Y16, Increment); Inc(K16, Increment); end else Inc(Target8, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; 16: // 161616 to 161616 begin Target16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin // blue Target16^ := 65535 - (Y16^ - MulDiv16(Y16^, K16^, 65535) + K16^); Inc(Target16); // green Target16^ := 65535 - (M16^ - MulDiv16(M16^, K16^, 65535) + K16^); Inc(Target16); // blue Target16^ := 65535 - (C16^ - MulDiv16(C16^, K16^, 65535) + K16^); Inc(Target16, 1 + AlphaSkip); Inc(C16, Increment); Inc(M16, Increment); Inc(Y16, Increment); Inc(K16, Increment); end else Inc(Target16, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; end; end; end; end; procedure TColorManager.RowConvertCMYK2RGB(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); var C8, M8, Y8, K8: PByte; C16, M16, Y16, K16: PWord; Target8: PByte; Target16: PWord; Increment: Integer; AlphaSkip: Integer; BitRun: Byte; begin BitRun := $80; AlphaSkip := Ord(coAlpha in FTargetOptions); // 0 if no alpha must be skipped, otherwise 1 case FSourceBPS of 8: begin if Length(Source) = 4 then begin // plane mode C8 := Source[0]; M8 := Source[1]; Y8 := Source[2]; K8 := Source[3]; Increment := 1; end else begin // interleaved mode C8 := Source[0]; M8 := C8; Inc(M8); Y8 := M8; Inc(Y8); K8 := Y8; Inc(K8); Increment := 4; end; case FTargetBPS of 8: // 888 to 888 begin Target8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin // red Target8^ := ClampByte(255 - (C8^ - MulDiv16(C8^, K8^, 255) + K8^)); Inc(Target8); // green Target8^ := ClampByte(255 - (M8^ - MulDiv16(M8^, K8^, 255) + K8^)); Inc(Target8); // blue Target8^ := ClampByte(255 - (Y8^ - MulDiv16(Y8^, K8^, 255) + K8^)); Inc(Target8, 1 + AlphaSkip); Inc(C8, Increment); Inc(M8, Increment); Inc(Y8, Increment); Inc(K8, Increment); end else Inc(Target8, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; 16: // 888 to 161616 begin Target16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin // red Target16^ := MulDiv16(ClampByte(255 - (C8^ - MulDiv16(C8^, K8^, 255) + K8^)), 65535, 255); Inc(Target16); // green Target16^ := MulDiv16(ClampByte(255 - (M8^ - MulDiv16(M8^, K8^, 255) + K8^)), 65535, 255); Inc(Target16); // blue Target16^ := MulDiv16(ClampByte(255 - (Y8^ - MulDiv16(Y8^, K8^, 255) + K8^)), 65535, 255); Inc(Target16, 1 + AlphaSkip); Inc(C8, Increment); Inc(M8, Increment); Inc(Y8, Increment); Inc(K8, Increment); end else Inc(Target16, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; end; end; 16: begin if Length(Source) = 4 then begin // plane mode C16 := Source[0]; M16 := Source[1]; Y16 := Source[2]; K16 := Source[3]; Increment := 1; end else begin // interleaved mode C16 := Source[0]; M16 := C16; Inc(M16); Y16 := M16; Inc(Y16); K16 := Y16; Inc(K16); Increment := 4; end; case FTargetBPS of 8: // 161616 to 888 begin Target8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin // red Target8^ := ClampByte(255 - MulDiv16((C16^ - MulDiv16(C16^, K16^, 65535) + K16^), 255, 65535)); Inc(Target8); // green Target8^ := ClampByte(255 - MulDiv16((M16^ - MulDiv16(M16^, K16^, 65535) + K16^), 255, 65535)); Inc(Target8); // blue Target8^ := ClampByte(255 - MulDiv16((Y16^ - MulDiv16(Y16^, K16^, 65535) + K16^), 255, 65535)); Inc(Target8, 1 + AlphaSkip); Inc(C16, Increment); Inc(M16, Increment); Inc(Y16, Increment); Inc(K16, Increment); end else Inc(Target8, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; 16: // 161616 to 161616 begin Target16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin // red Target16^ := 65535 - (C16^ - MulDiv16(C16^, K16^, 65535) + K16^); Inc(Target16); // green Target16^ := 65535 - (M16^ - MulDiv16(M16^, K16^, 65535) + K16^); Inc(Target16); // blue Target16^ := 65535 - (Y16^ - MulDiv16(Y16^, K16^, 65535) + K16^); Inc(Target16, 1 + AlphaSkip); Inc(C16, Increment); Inc(M16, Increment); Inc(Y16, Increment); Inc(K16, Increment); end else Inc(Target16, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; end; end; end; end; procedure TColorManager.RowConvertGray(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); var Target8: PByte; Target16: PWord; Source8: PByte; Source16: PWord; BitRun: Byte; AlphaSkip: Integer; Convert16: function(Value: Word): Byte of object; begin BitRun := $80; AlphaSkip := Ord(coAlpha in FSourceOptions); // 0 if no alpha must be skipped, otherwise 1 case FSourceBPS of 8: case FTargetBPS of 8: // 888 to 888 begin Source8 := Source[0]; Target8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin Target8^ := Source8^; Inc(Source8, 1 + AlphaSkip); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(Target8); end; end; 16: // 888 to 161616 begin Source8 := Source[0]; Target16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin Target16^ := MulDiv16(Source8^, 65535, 255); Inc(Source8, 1 + AlphaSkip); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(Target16); end; end; end; 16: case FTargetBPS of 8: // 161616 to 888 begin Source16 := Source[0]; Target8 := Target; if coNeedByteSwap in FSourceOptions then Convert16 := ComponentSwapScaleConvert else Convert16 := ComponentScaleConvert; while Count > 0 do begin if Boolean(Mask and BitRun) then begin Target8^ := Convert16(Source16^); Inc(Source16, 1 + AlphaSkip); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(Target8); end; end; 16: // 161616 to 161616 begin Source16 := Source[0]; Target16 := Target; if coNeedByteSwap in FSourceOptions then begin while Count > 0 do begin if Boolean(Mask and BitRun) then begin Target16^ := Swap(Source16^); Inc(Source16, 1 + AlphaSkip); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(Target16); end; end else begin while Count > 0 do begin if Boolean(Mask and BitRun) then begin Target16^ := Source16^; Inc(Source16, 1 + AlphaSkip); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(Target16); end; end; end; end; end; end; procedure TColorManager.RowConvertIndexed8(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); var SourceRun, TargetRun: PByte; Value, BitRun, TargetMask, SourceMask, SourceShift, TargetShift, MaxInSample, MaxOutSample, SourceBPS, // local copies to ease assembler access TargetBPS: Byte; Done: Cardinal; begin SourceRun := Source[0]; TargetRun := Target; if (FSourceBPS = FTargetBPS) and (Mask = $FF) then Move(SourceRun^, TargetRun^, (Count * FSourceBPS + 7) div 8) else begin BitRun := $80; // make a copy of these both values from private variables to local variables // to ease access during assembler parts in the code SourceBPS := FSourceBPS; TargetBPS := FTargetBPS; SourceMask := Byte(not ((1 shl (8 - SourceBPS)) - 1)); MaxInSample := (1 shl SourceBPS) - 1; TargetMask := (1 shl (8 - TargetBPS)) - 1; MaxOutSample := (1 shl TargetBPS) - 1; SourceShift := 8; TargetShift := 8 - TargetBPS; Done := 0; while Done < Count do begin if Boolean(Mask and BitRun) then begin // adjust shift value by source bit depth Dec(SourceShift, SourceBPS); Value := (SourceRun^ and SourceMask) shr SourceShift; Value := MulDiv16(Value, MaxOutSample, MaxInSample); TargetRun^ := (TargetRun^ and TargetMask) or (Value shl TargetShift); if SourceShift = 0 then begin SourceShift := 8; Inc(SourceRun); end; asm MOV CL, [SourceBPS] ROR BYTE PTR [SourceMask], CL // roll source bit mask with source bit count end; end; asm ROR BYTE PTR [BitRun], 1 // adjust test bit mask MOV CL, [TargetBPS] ROR BYTE PTR [TargetMask], CL // roll target mask with target bit count end; if TargetShift = 0 then TargetShift := 8 - TargetBPS else Dec(TargetShift, TargetBPS); Inc(Done); // advance target pointer every (8 div target bit count) if (Done mod (8 div TargetBPS)) = 0 then Inc(TargetRun); end; end; end; procedure TColorManager.RowConvertIndexedBoth16(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); var TargetRun, SourceRun: PWord; BitRun: Byte; begin SourceRun := Source[0]; TargetRun := Target; BitRun := $80; if coNeedByteSwap in FSourceOptions then begin while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRun^ := Swap(SourceRun^); Inc(SourceRun); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(TargetRun); end; end else begin if Mask = $FF then Move(SourceRun^, TargetRun^, 2 * Count) else while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRun^ := SourceRun^; Inc(SourceRun); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(TargetRun); end; end; end; procedure TColorManager.RowConvertIndexedSource16(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); var TargetRun8: PByte; SourceRun16: PWord; Value, BitRun, TargetMask, TargetShift, MaxOutSample, TargetBPS: Byte; // local copies to ease assembler access begin SourceRun16 := Source[0]; TargetRun8 := Target; BitRun := $80; // make a copy of these both values from private variables to local variables // to ease access during assembler parts in the code TargetBPS := FTargetBPS; TargetMask := (1 shl (8 - TargetBPS)) - 1; MaxOutSample := (1 shl TargetBPS) - 1; TargetShift := 8 - TargetBPS; while Count > 0 do begin if Boolean(Mask and BitRun) then begin if coNeedByteSwap in FSourceOptions then Value := MulDiv16(Swap(SourceRun16^), MaxOutSample, 65535) else Value := MulDiv16(SourceRun16^, MaxOutSample, 65535); TargetRun8^ := (TargetRun8^ and TargetMask) or (Value shl TargetShift); Inc(SourceRun16); end; asm ROR BYTE PTR [BitRun], 1 // adjust test bit mask MOV CL, [TargetBPS] ROR BYTE PTR [TargetMask], CL // roll target mask with target bit count end; if TargetShift = 0 then TargetShift := 8 - TargetBPS else Dec(TargetShift, TargetBPS); Dec(Count); // advance target pointer every (8 div target bit count) if (Count mod (8 div TargetBPS)) = 0 then Inc(TargetRun8); end; end; procedure TColorManager.RowConvertIndexedTarget16(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); var SourceRun8: PByte; TargetRun16: PWord; Value: Word; BitRun, SourceMask, SourceShift, MaxInSample, SourceBPS: Byte; begin SourceRun8 := Source[0]; TargetRun16 := Target; BitRun := $80; SourceBPS := FSourceBPS; SourceMask := Byte(not ((1 shl (8 - SourceBPS)) - 1)); MaxInSample := (1 shl SourceBPS) - 1; SourceShift := 8; while Count > 0 do begin if Boolean(Mask and BitRun) then begin // adjust shift value by source bit depth Dec(SourceShift, SourceBPS); Value := (SourceRun8^ and SourceMask) shr SourceShift; Value := MulDiv16(Value, 65535, MaxInSample); if coNeedByteSwap in FSourceOptions then TargetRun16^ := Swap(Value) else TargetRun16^ := Value; if SourceShift = 0 then begin SourceShift := 8; Inc(SourceRun8); end; asm MOV CL, [SourceBPS] ROR BYTE PTR [SourceMask], CL // roll source bit mask with source bit count end; end; asm ROR BYTE PTR [BitRun], 1 // adjust test bit mask end; Dec(Count); // advance target pointer every (8 div target bit count) Inc(TargetRun16); end; end; procedure TColorManager.RowConvertRGB2BGR(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); var SourceR16, SourceG16, SourceB16, SourceA16: PWord; SourceR8, SourceG8, SourceB8, SourceA8: PByte; TargetRun16: PBGR16; TargetRunA16: PBGRA16; TargetRun8: PBGR; TargetRunA8: PBGRA; BitRun: Byte; Convert8_8: function(Value: Byte): Byte of object; Convert16_8: function(Value: Word): Byte of object; Convert16_8Alpha: function(Value: Word): Byte of object; Convert16_16: function(Value: Word): Word of object; SourceIncrement, TargetIncrement: Cardinal; CopyAlpha: Boolean; begin BitRun := $80; // determine alpha handling once CopyAlpha := False; if coAlpha in FSourceOptions then begin // byte size of components doesn't matter as the increments are applied to // pointers whose data types determine the final increment SourceIncrement := SizeOf(TRGBA); TargetIncrement := SizeOf(TRGB); if coAlpha in FTargetOptions then CopyAlpha := True; end else begin SourceIncrement := SizeOf(TRGB); if coAlpha in FTargetOptions then TargetIncrement := SizeOf(TRGBA) else TargetIncrement := SizeOf(TRGB); end; // in planar mode source increment is always 1 if Length(Source) > 1 then SourceIncrement := 1; case FSourceBPS of 8: begin if Length(Source) = 1 then begin // interleaved mode SourceR8 := Source[0]; SourceG8 := SourceR8; Inc(SourceG8); SourceB8 := SourceG8; Inc(SourceB8); SourceA8 := SourceB8; Inc(SourceA8); end else begin SourceR8 := Source[0]; SourceG8 := Source[1]; SourceB8 := Source[2]; if coAlpha in FSourceOptions then SourceA8 := Source[3] else SourceA8 := nil; end; case FTargetBPS of 8: // 888 to 888 begin if coApplyGamma in FTargetOptions then Convert8_8 := ComponentGammaConvert else Convert8_8 := ComponentNoConvert8; if CopyAlpha then begin TargetRunA8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRunA8.R := Convert8_8(SourceR8^); TargetRunA8.G := Convert8_8(SourceG8^); TargetRunA8.B := Convert8_8(SourceB8^); // alpha values are never gamma corrected TargetRunA8.A := SourceA8^; Inc(SourceB8, SourceIncrement); Inc(SourceG8, SourceIncrement); Inc(SourceR8, SourceIncrement); Inc(SourceA8, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(TargetRunA8); end; end else begin TargetRun8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRun8.R := Convert8_8(SourceR8^); TargetRun8.G := Convert8_8(SourceG8^); TargetRun8.B := Convert8_8(SourceB8^); Inc(SourceB8, SourceIncrement); Inc(SourceG8, SourceIncrement); Inc(SourceR8, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(PByte(TargetRun8), TargetIncrement); end; end; end; 16: // 888 to 161616 begin if coApplyGamma in FTargetOptions then Convert8_8 := ComponentGammaConvert else Convert8_8 := ComponentNoConvert8; if coNeedByteSwap in FSourceOptions then Convert16_16 := ComponentSwapConvert else Convert16_16 := ComponentNoConvert16; if Length(Source) = 1 then begin SourceB8 := Source[0]; SourceG8 := SourceB8; Inc(SourceG8); SourceR8 := SourceG8; Inc(SourceR8); SourceA8 := SourceR8; Inc(SourceA8); end else begin SourceB8 := Source[0]; SourceG8 := Source[1]; SourceR8 := Source[2]; if coAlpha in FSourceOptions then SourceA8 := Source[3] else SourceA8 := nil; end; if CopyAlpha then begin TargetRunA16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRunA16.R := Convert16_16(MulDiv16(Convert8_8(SourceR8^), 65535, 255)); TargetRunA16.G := Convert16_16(MulDiv16(Convert8_8(SourceG8^), 65535, 255)); TargetRunA16.B := Convert16_16(MulDiv16(Convert8_8(SourceB8^), 65535, 255)); TargetRunA16.A := Convert16_16(MulDiv16(SourceA8^, 65535, 255)); Inc(SourceB8, SourceIncrement); Inc(SourceG8, SourceIncrement); Inc(SourceR8, SourceIncrement); Inc(SourceA8, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(TargetRunA16); end; end else begin TargetRun16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRun16.R := Convert16_16(MulDiv16(Convert8_8(SourceR8^), 65535, 255)); TargetRun16.G := Convert16_16(MulDiv16(Convert8_8(SourceG8^), 65535, 255)); TargetRun16.B := Convert16_16(MulDiv16(Convert8_8(SourceB8^), 65535, 255)); Inc(SourceB8, SourceIncrement); Inc(SourceG8, SourceIncrement); Inc(SourceR8, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(PWord(TargetRun16), TargetIncrement); end; end; end; end; end; 16: begin if Length(Source) = 1 then begin SourceR16 := Source[0]; SourceG16 := SourceR16; Inc(SourceG16); SourceB16 := SourceG16; Inc(SourceB16); SourceA16 := SourceB16; Inc(SourceA16); end else begin SourceR16 := Source[0]; SourceG16 := Source[1]; SourceB16 := Source[2]; if coAlpha in FSourceOptions then SourceA16 := Source[3] else SourceA16 := nil; end; case FTargetBPS of 8: // 161616 to 888 begin if coApplyGamma in FTargetOptions then begin if coNeedByteSwap in FSourceOptions then Convert16_8 := ComponentSwapScaleGammaConvert else Convert16_8 := ComponentScaleGammaConvert; end else begin if coNeedByteSwap in FSourceOptions then Convert16_8 := ComponentSwapScaleConvert else Convert16_8 := ComponentScaleConvert; end; // since alpha channels are never gamma corrected we need a separate conversion routine if coNeedByteSwap in FSourceOptions then Convert16_8Alpha := ComponentSwapScaleConvert else Convert16_8Alpha := ComponentScaleConvert; if CopyAlpha then begin TargetRunA8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRunA8.R := Convert16_8(SourceR16^); TargetRunA8.G := Convert16_8(SourceG16^); TargetRunA8.B := Convert16_8(SourceB16^); TargetRunA8.A := Convert16_8Alpha(SourceA16^); Inc(SourceB16, SourceIncrement); Inc(SourceG16, SourceIncrement); Inc(SourceR16, SourceIncrement); Inc(SourceA16, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(TargetRunA8); end; end else begin TargetRun8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRun8.R := Convert16_8(SourceR16^); TargetRun8.G := Convert16_8(SourceG16^); TargetRun8.B := Convert16_8(SourceB16^); Inc(SourceB16, SourceIncrement); Inc(SourceG16, SourceIncrement); Inc(SourceR16, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(PByte(TargetRun8), TargetIncrement); end; end; end; 16: // 161616 to 161616 begin // no gamma correction for 16 bit samples yet if coNeedByteSwap in FSourceOptions then Convert16_16 := ComponentSwapConvert else Convert16_16 := ComponentNoConvert16; if Length(Source) = 1 then begin SourceB16 := Source[0]; SourceG16 := SourceB16; Inc(SourceG16); SourceR16 := SourceG16; Inc(SourceR16); SourceA16 := SourceR16; Inc(SourceA16); end else begin SourceB16 := Source[0]; SourceG16 := Source[1]; SourceR16 := Source[2]; if coAlpha in FSourceOptions then SourceA16 := Source[3] else SourceA16 := nil; end; if CopyAlpha then begin TargetRunA16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRunA16.R := Convert16_16(SourceR16^); TargetRunA16.G := Convert16_16(SourceG16^); TargetRunA16.B := Convert16_16(SourceB16^); TargetRunA16.A := Convert16_16(SourceA16^); Inc(SourceB16, SourceIncrement); Inc(SourceG16, SourceIncrement); Inc(SourceR16, SourceIncrement); Inc(SourceA16, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(TargetRunA16); end; end else begin TargetRun16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRun16.R := Convert16_16(SourceR16^); TargetRun16.G := Convert16_16(SourceG16^); TargetRun16.B := Convert16_16(SourceB16^); Inc(SourceB16, SourceIncrement); Inc(SourceG16, SourceIncrement); Inc(SourceR16, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(PWord(TargetRun16), TargetIncrement); end; end; end; end; end; end; end; procedure TColorManager.RowConvertRGB2RGB(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); var SourceR16, SourceG16, SourceB16, SourceA16: PWord; SourceR8, SourceG8, SourceB8, SourceA8: PByte; TargetRun16: PRGB16; TargetRunA16: PRGBA16; TargetRun8: PRGB; TargetRunA8: PRGBA; BitRun: Byte; Convert8_8: function(Value: Byte): Byte of object; Convert16_8: function(Value: Word): Byte of object; Convert16_8Alpha: function(Value: Word): Byte of object; Convert16_16: function(Value: Word): Word of object; SourceIncrement, TargetIncrement: Cardinal; CopyAlpha: Boolean; begin BitRun := $80; // determine alpha handling once CopyAlpha := False; if coAlpha in FSourceOptions then begin SourceIncrement := SizeOf(TRGBA); TargetIncrement := SizeOf(TRGB); if coAlpha in FTargetOptions then CopyAlpha := True; end else begin SourceIncrement := SizeOf(TRGB); if coAlpha in FTargetOptions then TargetIncrement := SizeOf(TRGBA) else TargetIncrement := SizeOf(TRGB); end; // in planar mode source increment is always 1 if Length(Source) > 1 then SourceIncrement := 1; case FSourceBPS of 8: begin if Length(Source) = 1 then begin // interleaved mode SourceR8 := Source[0]; SourceG8 := SourceR8; Inc(SourceG8); SourceB8 := SourceG8; Inc(SourceB8); SourceA8 := SourceB8; Inc(SourceA8); end else begin SourceR8 := Source[0]; SourceG8 := Source[1]; SourceB8 := Source[2]; if coAlpha in FSourceOptions then SourceA8 := Source[3] else SourceA8 := nil; end; case FTargetBPS of 8: // 888 to 888 begin if coApplyGamma in FTargetOptions then Convert8_8 := ComponentGammaConvert else Convert8_8 := ComponentNoConvert8; if CopyAlpha then begin TargetRunA8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRunA8.R := Convert8_8(SourceR8^); TargetRunA8.G := Convert8_8(SourceG8^); TargetRunA8.B := Convert8_8(SourceB8^); // alpha values are never gamma corrected TargetRunA8.A := SourceA8^; Inc(SourceB8, SourceIncrement); Inc(SourceG8, SourceIncrement); Inc(SourceR8, SourceIncrement); Inc(SourceA8, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(TargetRunA8); end; end else begin TargetRun8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRun8.R := Convert8_8(SourceR8^); TargetRun8.G := Convert8_8(SourceG8^); TargetRun8.B := Convert8_8(SourceB8^); Inc(SourceB8, SourceIncrement); Inc(SourceG8, SourceIncrement); Inc(SourceR8, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(PByte(TargetRun8), TargetIncrement); end; end; end; 16: // 888 to 161616 begin if coApplyGamma in FTargetOptions then Convert8_8 := ComponentGammaConvert else Convert8_8 := ComponentNoConvert8; if coNeedByteSwap in FSourceOptions then Convert16_16 := ComponentSwapConvert else Convert16_16 := ComponentNoConvert16; if Length(Source) = 1 then begin SourceB8 := Source[0]; SourceG8 := SourceB8; Inc(SourceG8); SourceR8 := SourceG8; Inc(SourceR8); SourceA8 := SourceR8; Inc(SourceA8); end else begin SourceB8 := Source[0]; SourceG8 := Source[1]; SourceR8 := Source[2]; if coAlpha in FSourceOptions then SourceA8 := Source[3] else SourceA8 := nil; end; if CopyAlpha then begin TargetRunA16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRunA16.R := Convert16_16(MulDiv16(Convert8_8(SourceR8^), 65535, 255)); TargetRunA16.G := Convert16_16(MulDiv16(Convert8_8(SourceG8^), 65535, 255)); TargetRunA16.B := Convert16_16(MulDiv16(Convert8_8(SourceB8^), 65535, 255)); TargetRunA16.A := Convert16_16(MulDiv16(SourceA8^, 65535, 255)); Inc(SourceB8, SourceIncrement); Inc(SourceG8, SourceIncrement); Inc(SourceR8, SourceIncrement); Inc(SourceA8, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(TargetRunA16); end; end else begin TargetRun16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRun16.R := Convert16_16(MulDiv16(Convert8_8(SourceR8^), 65535, 255)); TargetRun16.G := Convert16_16(MulDiv16(Convert8_8(SourceG8^), 65535, 255)); TargetRun16.B := Convert16_16(MulDiv16(Convert8_8(SourceB8^), 65535, 255)); Inc(SourceB8, SourceIncrement); Inc(SourceG8, SourceIncrement); Inc(SourceR8, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(PWord(TargetRun16), TargetIncrement); end; end; end; end; end; 16: begin if Length(Source) = 1 then begin SourceR16 := Source[0]; SourceG16 := SourceR16; Inc(SourceG16); SourceB16 := SourceG16; Inc(SourceB16); SourceA16 := SourceB16; Inc(SourceA16); end else begin SourceR16 := Source[0]; SourceG16 := Source[1]; SourceB16 := Source[2]; if coAlpha in FSourceOptions then SourceA16 := Source[3] else SourceA16 := nil; end; case FTargetBPS of 8: // 161616 to 888 begin if coApplyGamma in FTargetOptions then begin if coNeedByteSwap in FSourceOptions then Convert16_8 := ComponentSwapScaleGammaConvert else Convert16_8 := ComponentScaleGammaConvert; end else begin if coNeedByteSwap in FSourceOptions then Convert16_8 := ComponentSwapScaleConvert else Convert16_8 := ComponentScaleConvert; end; // since alpha channels are never gamma corrected we need a separate conversion routine if coNeedByteSwap in FSourceOptions then Convert16_8Alpha := ComponentSwapScaleConvert else Convert16_8Alpha := ComponentScaleConvert; if CopyAlpha then begin TargetRunA8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRunA8.R := Convert16_8(SourceR16^); TargetRunA8.G := Convert16_8(SourceG16^); TargetRunA8.B := Convert16_8(SourceB16^); TargetRunA8.A := Convert16_8Alpha(SourceA16^); Inc(SourceB16, SourceIncrement); Inc(SourceG16, SourceIncrement); Inc(SourceR16, SourceIncrement); Inc(SourceA16, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(TargetRunA8); end; end else begin TargetRun8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRun8.R := Convert16_8(SourceR16^); TargetRun8.G := Convert16_8(SourceG16^); TargetRun8.B := Convert16_8(SourceB16^); Inc(SourceB16, SourceIncrement); Inc(SourceG16, SourceIncrement); Inc(SourceR16, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(PByte(TargetRun8), TargetIncrement); end; end; end; 16: // 161616 to 161616 begin // no gamma correction for 16 bit samples yet if coNeedByteSwap in FSourceOptions then Convert16_16 := ComponentSwapConvert else Convert16_16 := ComponentNoConvert16; if Length(Source) = 1 then begin SourceB16 := Source[0]; SourceG16 := SourceB16; Inc(SourceG16); SourceR16 := SourceG16; Inc(SourceR16); SourceA16 := SourceR16; Inc(SourceA16); end else begin SourceB16 := Source[0]; SourceG16 := Source[1]; SourceR16 := Source[2]; if coAlpha in FSourceOptions then SourceA16 := Source[3] else SourceA16 := nil; end; if CopyAlpha then begin TargetRunA16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRunA16.R := Convert16_16(SourceR16^); TargetRunA16.G := Convert16_16(SourceG16^); TargetRunA16.B := Convert16_16(SourceB16^); TargetRunA16.A := Convert16_16(SourceA16^); Inc(SourceB16, SourceIncrement); Inc(SourceG16, SourceIncrement); Inc(SourceR16, SourceIncrement); Inc(SourceA16, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(TargetRunA16); end; end else begin TargetRun16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin TargetRun16.R := Convert16_16(SourceR16^); TargetRun16.G := Convert16_16(SourceG16^); TargetRun16.B := Convert16_16(SourceB16^); Inc(SourceB16, SourceIncrement); Inc(SourceG16, SourceIncrement); Inc(SourceR16, SourceIncrement); end; asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); Inc(PWord(TargetRun16), TargetIncrement); end; end; end; end; end; end; end; procedure TColorManager.RowConvertPhotoYCC2BGR(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); var Y, Cb, Cr: Integer; Yf, Cbf, Crf: Single; Y8Run, Cb8Run, Cr8Run: PByte; Y16Run, Cb16Run, Cr16Run: PWord; Target8: PByte; Target16: PWord; AlphaSkip: Integer; BitRun: Byte; Increment: Integer; begin BitRun := $80; AlphaSkip := Ord(coAlpha in FTargetOptions); // 0 if no alpha must be skipped, otherwise 1 case FSourceBPS of 8: begin if Length(Source) = 1 then begin Y8Run := Source[0]; Cb8Run := Y8Run; Inc(Cb8Run); Cr8Run := Cb8Run; Inc(Cr8Run); Increment := 3; end else begin Y8Run := Source[0]; Cb8Run := Source[1]; Cr8Run := Source[2]; Increment := 1; end; case FTargetBPS of 8: // 888 to 888 begin Target8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin Y := Y8Run^; Inc(Y8Run, Increment); Cb := Cb8Run^; Inc(Cb8Run, Increment); Cr := Cr8Run^; Inc(Cr8Run, Increment); // blue Target8^ := ClampByte(Y + FCbToBlueTable[Cb]); Inc(Target8); // green Target8^ := ClampByte(Y + FCbToGreenTable[Cb] + FCrToGreentable[Cr]); Inc(Target8); // red Target8^ := ClampByte(Y + FCrToRedTable[Cr]); Inc(Target8, 1 + AlphaSkip); end else Inc(Target8, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; 16: // 888 to 161616 begin Target16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin Y := Y8Run^; Inc(Y8Run, Increment); Cb := Cb8Run^; Inc(Cb8Run, Increment); Cr := Cr8Run^; Inc(Cr8Run, Increment); // blue Target16^ := MulDiv16(ClampByte(Y + FCbToBlueTable[Cb]), 65535, 255); Inc(Target16); // green Target16^ := MulDiv16(ClampByte(Y + FCbToGreenTable[Cb] + FCrToGreentable[Cr]), 65535, 255); Inc(Target16); // red Target16^ := MulDiv16(ClampByte(Y + FCrToRedTable[Cr]), 65535, 255); Inc(Target16, 1 + AlphaSkip); end else Inc(Target16, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; end; end; 16: begin if Length(Source) = 1 then begin Y16Run := Source[0]; Cb16Run := Y16Run; Inc(Cb16Run); Cr16Run := Cb16Run; Inc(Cr16Run); Increment := 3; end else begin Y16Run := Source[0]; Cb16Run := Source[1]; Cr16Run := Source[2]; Increment := 1; end; case FTargetBPS of 8: // 161616 to 888 begin Target8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin Y := MulDiv16(Y16Run^, 255, 65535); Inc(Y16Run, Increment); Cb := MulDiv16(Cb16Run^, 255, 65535); Inc(Cb16Run, Increment); Cr := MulDiv16(Cr16Run^, 255, 65535); Inc(Cr16Run, Increment); // blue Target8^ := ClampByte(Y + FCbToBlueTable[Cb]); Inc(Target8); // green Target8^ := ClampByte(Y + FCbToGreenTable[Cb] + FCrToGreentable[Cr]); Inc(Target8); // red Target8^ := ClampByte(Y + FCrToRedTable[Cr]); Inc(Target8, 1 + AlphaSkip); end else Inc(Target8, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; 16: // 161616 to 161616 begin Target16 := Target; // conversion from 16 to 16 is done with full precision, so there is no // loss of information, but the code is slower because the lookup tables // cannot be used while Count > 0 do begin if Boolean(Mask and BitRun) then begin Yf := 1.3584 * Y16Run^; Inc(Y16Run, Increment); Cbf := Cb16Run^ - 40092; // (156 * 65535) div 255 Inc(Cb16Run, Increment); Crf := Cr16Run^ - 35209; // (137 * 65535) div 255 Inc(Cr16Run, Increment); // blue Target16^ := Round(Yf + 2.2179 * Cbf); Inc(Target16); // green Target16^ := Round(Yf - 0.9271435 * Crf - 0.4302726 * Cbf); Inc(Target16); // red Target16^ := Round(Yf + 1.8215 * Crf); Inc(Target16, 1 + AlphaSkip); end else Inc(Target16, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; end; end; end; end; procedure TColorManager.RowConvertPhotoYCC2RGB(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); var Y, Cb, Cr: Integer; Yf, Cbf, Crf: Single; Y8Run, Cb8Run, Cr8Run: PByte; Y16Run, Cb16Run, Cr16Run: PWord; Target8: PByte; Target16: PWord; AlphaSkip: Integer; BitRun: Byte; Increment: Integer; begin BitRun := $80; AlphaSkip := Ord(coAlpha in FTargetOptions); // 0 if no alpha must be skipped, otherwise 1 case FSourceBPS of 8: begin if Length(Source) = 1 then begin Y8Run := Source[0]; Cb8Run := Y8Run; Inc(Cb8Run); Cr8Run := Cb8Run; Inc(Cr8Run); Increment := 3; end else begin Y8Run := Source[0]; Cb8Run := Source[1]; Cr8Run := Source[2]; Increment := 1; end; case FTargetBPS of 8: // 888 to 888 begin Target8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin Y := Y8Run^; Inc(Y8Run, Increment); Cb := Cb8Run^; Inc(Cb8Run, Increment); Cr := Cr8Run^; Inc(Cr8Run, Increment); // red Target8^ := ClampByte(Y + FCrToRedTable[Cr]); Inc(Target8, 1 + AlphaSkip); // green Target8^ := ClampByte(Y + FCbToGreenTable[Cb] + FCrToGreentable[Cr]); Inc(Target8); // blue Target8^ := ClampByte(Y + FCbToBlueTable[Cb]); Inc(Target8); end else Inc(Target8, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; 16: // 888 to 161616 begin Target16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin Y := Y8Run^; Inc(Y8Run, Increment); Cb := Cb8Run^; Inc(Cb8Run, Increment); Cr := Cr8Run^; Inc(Cr8Run, Increment); // red Target16^ := MulDiv16(ClampByte(Y + FCrToRedTable[Cr]), 65535, 255); Inc(Target16, 1 + AlphaSkip); // green Target16^ := MulDiv16(ClampByte(Y + FCbToGreenTable[Cb] + FCrToGreentable[Cr]), 65535, 255); Inc(Target16); // blue Target16^ := MulDiv16(ClampByte(Y + FCbToBlueTable[Cb]), 65535, 255); Inc(Target16); end else Inc(Target16, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; end; end; 16: begin if Length(Source) = 1 then begin Y16Run := Source[0]; Cb16Run := Y16Run; Inc(Cb16Run); Cr16Run := Cb16Run; Inc(Cr16Run); Increment := 3; end else begin Y16Run := Source[0]; Cb16Run := Source[1]; Cr16Run := Source[2]; Increment := 1; end; case FTargetBPS of 8: // 161616 to 888 begin Target8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin Y := MulDiv16(Y16Run^, 255, 65535); Inc(Y16Run, Increment); Cb := MulDiv16(Cb16Run^, 255, 65535); Inc(Cb16Run, Increment); Cr := MulDiv16(Cr16Run^, 255, 65535); Inc(Cr16Run, Increment); // red Target8^ := ClampByte(Y + FCrToRedTable[Cr]); Inc(Target8, 1 + AlphaSkip); // green Target8^ := ClampByte(Y + FCbToGreenTable[Cb] + FCrToGreentable[Cr]); Inc(Target8); // blue Target8^ := ClampByte(Y + FCbToBlueTable[Cb]); Inc(Target8); end else Inc(Target8, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; 16: // 161616 to 161616 begin Target16 := Target; // conversion from 16 to 16 is done with full precision, so there is no // loss of information, but the code is slower because the lookup tables // cannot be used while Count > 0 do begin if Boolean(Mask and BitRun) then begin Yf := 1.3584 * Y16Run^; Inc(Y16Run, Increment); Cbf := Cb16Run^ - 40092; // (156 * 65535) div 255 Inc(Cb16Run, Increment); Crf := Cr16Run^ - 35209; // (137 * 65535) div 255 Inc(Cr16Run, Increment); // red Target16^ := Round(Yf + 1.8215 * Crf); Inc(Target16, 1 + AlphaSkip); // green Target16^ := Round(Yf - 0.9271435 * Crf - 0.4302726 * Cbf); Inc(Target16); // blue Target16^ := Round(Yf + 2.2179 * Cbf); Inc(Target16); end else Inc(Target16, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; end; end; end; end; procedure TColorManager.RowConvertYCbCr2BGR(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); var Y, Cb, Cr: Integer; Yf, Cbf, Crf: Single; Y8Run, Cb8Run, Cr8Run: PByte; Y16Run, Cb16Run, Cr16Run: PWord; Target8: PByte; Target16: PWord; AlphaSkip: Integer; BitRun: Byte; Increment: Integer; begin BitRun := $80; AlphaSkip := Ord(coAlpha in FTargetOptions); // 0 if no alpha must be skipped, otherwise 1 case FSourceBPS of 8: begin if Length(Source) = 1 then begin Y8Run := Source[0]; Cb8Run := Y8Run; Inc(Cb8Run); Cr8Run := Cb8Run; Inc(Cr8Run); Increment := 3; end else begin Y8Run := Source[0]; Cb8Run := Source[1]; Cr8Run := Source[2]; Increment := 1; end; case FTargetBPS of 8: // 888 to 888 begin Target8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin Y := Y8Run^; Inc(Y8Run, Increment); Cb := Cb8Run^; Inc(Cb8Run, Increment); Cr := Cr8Run^; Inc(Cr8Run, Increment); // blue Target8^ := ClampByte(Y + FCbToBlueTable[Cb]); Inc(Target8); // green Target8^ := ClampByte(Y + FCbToGreenTable[Cb] + FCrToGreentable[Cr]); Inc(Target8); // red Target8^ := ClampByte(Y + FCrToRedTable[Cr]); Inc(Target8, 1 + AlphaSkip); end else Inc(Target8, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; 16: // 888 to 161616 begin Target16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin Y := Y8Run^; Inc(Y8Run, Increment); Cb := Cb8Run^; Inc(Cb8Run, Increment); Cr := Cr8Run^; Inc(Cr8Run, Increment); // blue Target16^ := MulDiv16(ClampByte(Y + FCbToBlueTable[Cb]), 65535, 255); Inc(Target16); // green Target16^ := MulDiv16(ClampByte(Y + FCbToGreenTable[Cb] + FCrToGreentable[Cr]), 65535, 255); Inc(Target16); // red Target16^ := MulDiv16(ClampByte(Y + FCrToRedTable[Cr]), 65535, 255); Inc(Target16, 1 + AlphaSkip); end else Inc(Target16, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; end; end; 16: begin if Length(Source) = 1 then begin Y16Run := Source[0]; Cb16Run := Y16Run; Inc(Cb16Run); Cr16Run := Cb16Run; Inc(Cr16Run); Increment := 3; end else begin Y16Run := Source[0]; Cb16Run := Source[1]; Cr16Run := Source[2]; Increment := 1; end; case FTargetBPS of 8: // 161616 to 888 begin Target8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin Y := MulDiv16(Y16Run^, 255, 65535); Inc(Y16Run, Increment); Cb := MulDiv16(Cb16Run^, 255, 65535); Inc(Cb16Run, Increment); Cr := MulDiv16(Cr16Run^, 255, 65535); Inc(Cr16Run, Increment); // blue Target8^ := ClampByte(Y + FCbToBlueTable[Cb]); Inc(Target8); // green Target8^ := ClampByte(Y + FCbToGreenTable[Cb] + FCrToGreentable[Cr]); Inc(Target8); // red Target8^ := ClampByte(Y + FCrToRedTable[Cr]); Inc(Target8, 1 + AlphaSkip); end else Inc(Target8, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; 16: // 161616 to 161616 begin Target16 := Target; // conversion from 16 to 16 is done with full precision, so there is no // loss of information, but the code is slower because the lookup tables // cannot be used while Count > 0 do begin if Boolean(Mask and BitRun) then begin Yf := 1.3584 * Y16Run^; Inc(Y16Run, Increment); Cbf := Cb16Run^ - 40092; // (156 * 65535) div 255 Inc(Cb16Run, Increment); Crf := Cr16Run^ - 35209; // (137 * 65535) div 255 Inc(Cr16Run, Increment); // blue Target16^ := Round(Yf + 2.2179 * Cbf); Inc(Target16); // green Target16^ := Round(Yf - 0.9271435 * Crf - 0.4302726 * Cbf); Inc(Target16); // red Target16^ := Round(Yf + 1.8215 * Crf); Inc(Target16, 1 + AlphaSkip); end else Inc(Target16, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; end; end; end; end; procedure TColorManager.RowConvertYCbCr2RGB(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); var Y, Cb, Cr: Integer; Yf, Cbf, Crf: Single; Y8Run, Cb8Run, Cr8Run: PByte; Y16Run, Cb16Run, Cr16Run: PWord; Target8: PByte; Target16: PWord; AlphaSkip: Integer; BitRun: Byte; Increment: Integer; begin BitRun := $80; AlphaSkip := Ord(coAlpha in FTargetOptions); // 0 if no alpha must be skipped, otherwise 1 case FSourceBPS of 8: begin if Length(Source) = 1 then begin Y8Run := Source[0]; Cb8Run := Y8Run; Inc(Cb8Run); Cr8Run := Cb8Run; Inc(Cr8Run); Increment := 3; end else begin Y8Run := Source[0]; Cb8Run := Source[1]; Cr8Run := Source[2]; Increment := 1; end; case FTargetBPS of 8: // 888 to 888 begin Target8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin Y := Y8Run^; Inc(Y8Run, Increment); Cb := Cb8Run^; Inc(Cb8Run, Increment); Cr := Cr8Run^; Inc(Cr8Run, Increment); // red Target8^ := ClampByte(Y + FCrToRedTable[Cr]); Inc(Target8, 1 + AlphaSkip); // green Target8^ := ClampByte(Y + FCbToGreenTable[Cb] + FCrToGreentable[Cr]); Inc(Target8); // blue Target8^ := ClampByte(Y + FCbToBlueTable[Cb]); Inc(Target8); end else Inc(Target8, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; 16: // 888 to 161616 begin Target16 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin Y := Y8Run^; Inc(Y8Run, Increment); Cb := Cb8Run^; Inc(Cb8Run, Increment); Cr := Cr8Run^; Inc(Cr8Run, Increment); // red Target16^ := MulDiv16(ClampByte(Y + FCrToRedTable[Cr]), 65535, 255); Inc(Target16, 1 + AlphaSkip); // green Target16^ := MulDiv16(ClampByte(Y + FCbToGreenTable[Cb] + FCrToGreentable[Cr]), 65535, 255); Inc(Target16); // blue Target16^ := MulDiv16(ClampByte(Y + FCbToBlueTable[Cb]), 65535, 255); Inc(Target16); end else Inc(Target16, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; end; end; 16: begin if Length(Source) = 1 then begin Y16Run := Source[0]; Cb16Run := Y16Run; Inc(Cb16Run); Cr16Run := Cb16Run; Inc(Cr16Run); Increment := 3; end else begin Y16Run := Source[0]; Cb16Run := Source[1]; Cr16Run := Source[2]; Increment := 1; end; case FTargetBPS of 8: // 161616 to 888 begin Target8 := Target; while Count > 0 do begin if Boolean(Mask and BitRun) then begin Y := MulDiv16(Y16Run^, 255, 65535); Inc(Y16Run, Increment); Cb := MulDiv16(Cb16Run^, 255, 65535); Inc(Cb16Run, Increment); Cr := MulDiv16(Cr16Run^, 255, 65535); Inc(Cr16Run, Increment); // red Target8^ := ClampByte(Y + FCrToRedTable[Cr]); Inc(Target8, 1 + AlphaSkip); // green Target8^ := ClampByte(Y + FCbToGreenTable[Cb] + FCrToGreentable[Cr]); Inc(Target8); // blue Target8^ := ClampByte(Y + FCbToBlueTable[Cb]); Inc(Target8); end else Inc(Target8, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; 16: // 161616 to 161616 begin Target16 := Target; // conversion from 16 to 16 is done with full precision, so there is no // loss of information, but the code is slower because the lookup tables // cannot be used while Count > 0 do begin if Boolean(Mask and BitRun) then begin Yf := 1.3584 * Y16Run^; Inc(Y16Run, Increment); Cbf := Cb16Run^ - 40092; // (156 * 65535) div 255 Inc(Cb16Run, Increment); Crf := Cr16Run^ - 35209; // (137 * 65535) div 255 Inc(Cr16Run, Increment); // red Target16^ := Round(Yf + 1.8215 * Crf); Inc(Target16, 1 + AlphaSkip); // green Target16^ := Round(Yf - 0.9271435 * Crf - 0.4302726 * Cbf); Inc(Target16); // blue Target16^ := Round(Yf + 2.2179 * Cbf); Inc(Target16); end else Inc(Target16, 3 + AlphaSkip); asm ROR BYTE PTR [BitRun], 1 end; Dec(Count); end; end; end; end; end; end; procedure TColorManager.CreateYCbCrLookup; var F1, F2, F3, F4: Single; LumaRed, LumaGreen, LumaBlue: Single; I: Integer; Offset1, Offset2: Integer; begin LumaRed := FYCbCrCoefficients[0]; LumaGreen := FYCbCrCoefficients[1]; LumaBlue := FYCbCrCoefficients[2]; F1 := 2 - 2 * LumaRed; F2 := LumaRed * F1 / LumaGreen; F3 := 2 - 2 * LumaBlue; F4 := LumaBlue * F3 / LumaGreen; SetLength(FCrToRedTable, 256); SetLength(FCbToBlueTable, 256); SetLength(FCrToGreenTable, 256); SetLength(FCbToGreenTable, 256); if FSourceScheme = csYCbCr then begin // I is the actual input pixel value in the range 0..255, Cb and Cr values are in the range -128..127. // (for TIFF files they are in a range defined by the ReferenceBlackWhite tag). Offset1 := -128; for I := 0 to 255 do begin FCrToRedTable[I] := Round(F1 * Offset1); FCbToBlueTable[I] := Round(F3 * Offset1); FCrToGreenTable[I] := -Round(F2 * Offset1); FCbToGreenTable[I] := -Round(F4 * Offset1); Inc(Offset1); end; end else begin // PhotoYCC // I is the actual input pixel value in the range 0..255, Cb values are in the range -156..99, // Cr values are in the range -137..118. // (for TIFF files they are in a range defined by the ReferenceBlackWhite tag). Offset1 := -156; Offset2 := -137; for I := 0 to 255 do begin FCrToRedTable[I] := Round(F1 * Offset2); FCbToBlueTable[I] := Round(F3 * Offset1); FCrToGreenTable[I] := -Round(F2 * Offset2); FCbToGreenTable[I] := -Round(F4 * Offset1); Inc(Offset1); Inc(Offset2); end; end; end; function TColorManager.GetPixelFormat(Index: Integer): TPixelFormat; var SamplesPerPixel, BitsPerSample: Byte; begin case Index of 0: begin SamplesPerPixel := FSourceSPP; BitsPerSample := FSourceBPS; end; else SamplesPerPixel := FTargetSPP; BitsPerSample := FTargetBPS; end; case SamplesPerPixel of 1: // one sample per pixel, this is usually a palette format case BitsPerSample of 1: Result := pf1Bit; 2..4: // values < 4 should be upscaled Result := pf4bit; 8..16: // values > 8 bits must be downscaled to 8 bits Result := pf8bit; else Result := pfCustom; end; 3: // Typical case is RGB or CIE L*a*b* (565 and 555 16 bit color formats would also be possible, but aren't handled // by the manager). case BitsPerSample of 1..5: // values < 5 should be upscaled Result := pf15Bit; else // values > 8 bits should be downscaled Result := pf24bit; end; 4: // Typical cases: RGBA and CMYK (with 8 bps, other formats like PCX's // 4 planes with 1 bit must be handled elsewhere) if BitsPerSample >= 8 then Result := pf32Bit else Result := pfCustom; else Result := pfCustom; end; end; procedure TColorManager.PrepareConversion; begin FRowConversion := nil; // Conversion between indexed and non-indexed formats is not supported as well as // between source BPS < 8 and target BPS > 8. // csGA and csG (grayscale w and w/o alpha) are considered being indexed modes if (FSourceScheme in [csIndexed, csG, csGA]) xor (FTargetScheme in [csIndexed, csG]) then Error(gesIndexedNotSupported); // set up special conversion options if FSourceScheme in [csGA, csRGBA, csBGRA] then Include(FSourceOptions, coAlpha) else Exclude(FSourceOptions, coAlpha); if FTargetScheme in [csGA, csRGBA, csBGRA] then Include(FTargetOptions, coAlpha) else Exclude(FTargetOptions, coAlpha); case FSourceScheme of csG: if (FSourceBPS = 16) or (FTargetBPS = 16) then begin if (FSourceBPS >= 8) and (FTargetBPS >= 8) then FRowConversion := RowConvertGray; end else FRowConversion := RowConvertIndexed8; csGA: if (FSourceBPS in [8, 16]) and (FTargetBPS in [8, 16]) then FRowConversion := RowConvertGray; csIndexed: begin // Grayscale is handled like indexed mode. // Generally use indexed conversions (with various possible bit operations), // assign special methods for source only, target only or source and target being 16 bits per sample if (FSourceBPS = 16) and (FTargetBPS = 16) then FRowConversion := RowConvertIndexedBoth16 else if FSourceBPS = 16 then FRowConversion := RowConvertIndexedSource16 else if FTargetBPS = 16 then FRowConversion := RowConvertIndexedTarget16 else FRowConversion := RowConvertIndexed8; end; csRGB, csRGBA: case FTargetScheme of csRGB: FRowConversion := RowConvertRGB2RGB; csRGBA: FRowConversion := RowConvertRGB2RGB; csBGR: FRowConversion := RowConvertRGB2BGR; csBGRA: FRowConversion := RowConvertRGB2BGR; csCMY: ; csCMYK: ; csCIELab: ; csYCbCr: ; end; csBGRA, csBGR: case FTargetScheme of csRGB, csRGBA: FRowConversion := RowConvertBGR2RGB; csBGR, csBGRA: FRowConversion := RowConvertBGR2BGR; csCMY: ; csCMYK: ; csCIELab: ; csYCbCr: ; end; csCMY: case FTargetScheme of csRGB: ; csRGBA: ; csBGR: ; csBGRA: ; csCMY: ; csCMYK: ; csCIELab: ; csYCbCr: ; end; csCMYK: case FTargetScheme of csRGB, csRGBA: FRowConversion := RowConvertCMYK2RGB; csBGR, csBGRA: FRowConversion := RowConvertCMYK2BGR; csCMY: ; csCMYK: ; csCIELab: ; csYCbCr: ; end; csCIELab: case FTargetScheme of csRGB, csRGBA: FRowConversion := RowConvertCIELab2RGB; csBGR, csBGRA: FRowConversion := RowConvertCIELab2BGR; csCMY: ; csCMYK: ; csCIELab: ; csYCbCr: ; end; csYCbCr: begin // create lookup tables to speed up conversion CreateYCbCrLookup; case FTargetScheme of csRGB, csRGBA: FRowConversion := RowConvertYCbCr2RGB; csBGR, csBGRA: FRowConversion := RowConvertYCbCr2BGR; csCMY: ; csCMYK: ; csCIELab: ; csYCbCr: ; end; end; csPhotoYCC: begin // create lookup tables to speed up conversion CreateYCbCrLookup; case FTargetScheme of csRGB, csRGBA: FRowConversion := RowConvertPhotoYCC2RGB; csBGR, csBGRA: FRowConversion := RowConvertPhotoYCC2BGR; csCMY: ; csCMYK: ; csCIELab: ; csYCbCr: ; end; end; end; FChanged := False; end; procedure TColorManager.SetSourceBitsPerSample(const Value: Byte); begin if not (Value in [1..16]) then Error(gesInvalidSampleDepth); if FSourceBPS <> Value then begin FSourceBPS := Value; FChanged := True; end; end; procedure TColorManager.SetSourceColorScheme(const Value: TColorScheme); begin if FSourceScheme <> Value then begin FSourceScheme := Value; FChanged := True; end; end; procedure TColorManager.SetSourceSamplesPerPixel(const Value: Byte); begin if not (Value in [1..4]) then Error(gesInvalidPixelDepth); if FSourceSPP <> Value then begin FSourceSPP := Value; FChanged := True; end; end; procedure TColorManager.SetTargetBitsPerSample(const Value: Byte); begin if not (Value in [1..16]) then Error(gesInvalidSampleDepth); if FTargetBPS <> Value then begin FTargetBPS := Value; FChanged := True; end; end; procedure TColorManager.SetTargetColorScheme(const Value: TColorScheme); begin if FTargetScheme <> Value then begin FTargetScheme := Value; FChanged := True; end; end; procedure TColorManager.SetTargetSamplesPerPixel(const Value: Byte); begin if not (Value in [1..4]) then Error(gesInvalidPixelDepth); if FTargetSPP <> Value then begin FTargetSPP := Value; FChanged := True; end; end; procedure TColorManager.ConvertRow(Source: array of Pointer; Target: Pointer; Count: Cardinal; Mask: Byte); begin // if there are pending changes then apply them if FChanged then PrepareConversion; // check if there's now a conversion method if @FRowConversion = nil then Error(gesConversionUnsupported) else FRowConversion(Source, Target, Count, Mask); end; function TColorManager.CreateColorPalette(Data: array of Pointer; DataFormat: TRawPaletteFormat; ColorCount: Cardinal; RGB: Boolean): HPALETTE; var I, MaxIn, MaxOut: Integer; LogPalette: TMaxLogPalette; RunR8, RunG8, RunB8: PByte; RunR16, RunG16, RunB16: PWord; Convert8: function(Value: Byte): Byte of object; Convert16: function(Value: Word): Byte of object; begin FillChar(LogPalette, SizeOf(LogPalette), 0); LogPalette.palVersion := $300; if ColorCount > 256 then LogPalette.palNumEntries := 256 else LogPalette.palNumEntries := ColorCount; case DataFormat of pfInterlaced8Triple, pfInterlaced8Quad: begin RunR8 := Data[0]; if coApplyGamma in FTargetOptions then Convert8 := ComponentGammaConvert else Convert8 := ComponentNoConvert8; if RGB then begin for I := 0 to LogPalette.palNumEntries - 1 do begin LogPalette.palPalEntry[I].peBlue := Convert8(RunR8^); Inc(RunR8); LogPalette.palPalEntry[I].peGreen := Convert8(RunR8^); Inc(RunR8); LogPalette.palPalEntry[I].peRed := Convert8(RunR8^); Inc(RunR8); if DataFormat = pfInterlaced8Quad then Inc(RunR8); end; end else begin for I := 0 to LogPalette.palNumEntries - 1 do begin LogPalette.palPalEntry[I].peRed := Convert8(RunR8^); Inc(RunR8); LogPalette.palPalEntry[I].peGreen := Convert8(RunR8^); Inc(RunR8); LogPalette.palPalEntry[I].peBlue := Convert8(RunR8^); Inc(RunR8); if DataFormat = pfInterlaced8Quad then Inc(RunR8); end; end; end; pfPlane8Triple, pfPlane8Quad: begin RunR8 := Data[0]; RunG8 := Data[1]; RunB8 := Data[2]; if coApplyGamma in FTargetOptions then Convert8 := ComponentGammaConvert else Convert8 := ComponentNoConvert8; for I := 0 to LogPalette.palNumEntries - 1 do begin LogPalette.palPalEntry[I].peRed := Convert8(RunR8^); Inc(RunR8); LogPalette.palPalEntry[I].peGreen := Convert8(RunG8^); Inc(RunG8); LogPalette.palPalEntry[I].peBlue := Convert8(RunB8^); Inc(RunB8); end; end; pfInterlaced16Triple, pfInterlaced16Quad: begin RunR16 := Data[0]; if coApplyGamma in FTargetOptions then begin if coNeedByteSwap in FSourceOptions then Convert16 := ComponentSwapScaleGammaConvert else Convert16 := ComponentScaleGammaConvert; end else begin if coNeedByteSwap in FSourceOptions then Convert16 := ComponentSwapScaleConvert else Convert16 := ComponentScaleConvert; end; if RGB then begin for I := 0 to LogPalette.palNumEntries - 1 do begin LogPalette.palPalEntry[I].peRed := Convert16(RunR16^); Inc(RunR16); LogPalette.palPalEntry[I].peGreen := Convert16(RunR16^); Inc(RunR16); LogPalette.palPalEntry[I].peBlue := Convert16(RunR16^); Inc(RunR16); if DataFormat = pfInterlaced16Quad then Inc(RunR16); end; end else begin for I := 0 to LogPalette.palNumEntries - 1 do begin LogPalette.palPalEntry[I].peBlue := Convert16(RunR16^); Inc(RunR16); LogPalette.palPalEntry[I].peGreen := Convert16(RunR16^); Inc(RunR16); LogPalette.palPalEntry[I].peRed := Convert16(RunR16^); Inc(RunR16); if DataFormat = pfInterlaced16Quad then Inc(RunR16); end; end; end; pfPlane16Triple, pfPlane16Quad: begin RunR16 := Data[0]; RunG16 := Data[1]; RunB16 := Data[2]; if coApplyGamma in FTargetOptions then begin if coNeedByteSwap in FSourceOptions then Convert16 := ComponentSwapScaleGammaConvert else Convert16 := ComponentScaleGammaConvert; end else begin if coNeedByteSwap in FSourceOptions then Convert16 := ComponentSwapScaleConvert else Convert16 := ComponentScaleConvert; end; for I := 0 to LogPalette.palNumEntries - 1 do begin LogPalette.palPalEntry[I].peRed := Convert16(RunR16^); Inc(RunR16); LogPalette.palPalEntry[I].peGreen := Convert16(RunG16^); Inc(RunG16); LogPalette.palPalEntry[I].peBlue := Convert16(RunB16^); Inc(RunB16); end; end; end; MaxIn := (1 shl FSourceBPS) - 1; MaxOut := (1 shl FTargetBPS) - 1; if (FTargetBPS <= 8) and (MaxIn <> MaxOut) then begin // If target resolution and given color depth differ then the palette needs to be adjusted. // Consider the case for 2 bit to 4 bit conversion. Only 4 colors will be given to create // the palette but after scaling all values will be up to 15 for which no color is in the palette. // This and the reverse case need to be accounted for. MaxIn := (1 shl FSourceBPS) - 1; MaxOut := (1 shl FTargetBPS) - 1; if MaxIn < MaxOut then begin // palette is too small, enhance it for I := MaxOut downto 0 do begin LogPalette.palPalEntry[I].peRed := LogPalette.palPalEntry[MulDiv16(I, MaxIn, MaxOut)].peRed; LogPalette.palPalEntry[I].peGreen := LogPalette.palPalEntry[MulDiv16(I, MaxIn, MaxOut)].peGreen; LogPalette.palPalEntry[I].peBlue := LogPalette.palPalEntry[MulDiv16(I, MaxIn, MaxOut)].peBlue; end; end else begin // palette contains too many entries, shorten it for I := 0 to MaxOut do begin LogPalette.palPalEntry[I].peRed := LogPalette.palPalEntry[MulDiv16(I, MaxIn, MaxOut)].peRed; LogPalette.palPalEntry[I].peGreen := LogPalette.palPalEntry[MulDiv16(I, MaxIn, MaxOut)].peGreen; LogPalette.palPalEntry[I].peBlue := LogPalette.palPalEntry[MulDiv16(I, MaxIn, MaxOut)].peBlue; end; end; LogPalette.palNumEntries := MaxOut + 1; end; // finally create palette Result := CreatePalette(PLogPalette(@LogPalette)^); end; function TColorManager.CreateGrayscalePalette(MinimumIsWhite: Boolean): HPALETTE; var LogPalette: TMaxLogPalette; I: Integer; BPS, Upper, Factor: Byte; begin FillChar(LogPalette, SizeOf(LogPalette), 0); LogPalette.palVersion := $300; // the product of BPS and SPP considers planar organizatons correctly // (e.g. PCX has a format 4 planes with 1 bit resulting to 16 color image) BPS := FTargetBPS * FTargetSPP; if BPS > 8 then BPS := 8; LogPalette.palNumEntries := 1 shl BPS; Upper := LogPalette.palNumEntries - 1; Factor := 255 div Upper; if MinimumIsWhite then begin if not (coApplyGamma in FTargetOptions) then begin for I := 0 to Upper do begin LogPalette.palPalEntry[Upper - I].peBlue := I * Factor; LogPalette.palPalEntry[Upper - I].peGreen := I * Factor; LogPalette.palPalEntry[Upper - I].peRed := I * Factor; end; end else begin for I := 0 to Upper do begin LogPalette.palPalEntry[Upper - I].peBlue := FGammaTable[I * Factor]; LogPalette.palPalEntry[Upper - I].peGreen := FGammaTable[I * Factor]; LogPalette.palPalEntry[Upper - I].peRed := FGammaTable[I * Factor]; end; end; end else begin if not (coApplyGamma in FTargetOptions) then begin for I := 0 to Upper do begin LogPalette.palPalEntry[I].peBlue := I * Factor; LogPalette.palPalEntry[I].peGreen := I * Factor; LogPalette.palPalEntry[I].peRed := I * Factor; end; end else begin for I := 0 to Upper do begin LogPalette.palPalEntry[I].peBlue := FGammaTable[I * Factor]; LogPalette.palPalEntry[I].peGreen := FGammaTable[I * Factor]; LogPalette.palPalEntry[I].peRed := FGammaTable[I * Factor]; end; end; end; // finally create palette Result := CreatePalette(PLogPalette(@LogPalette)^); end; procedure TColorManager.Error(const Msg: String); begin raise EColorConversionError.Create(Msg); end; procedure TColorManager.SetGamma(MainGamma, DisplayGamma: Single); var I, SourceHighBound, TargetHighBound: Integer; Gamma: Single; begin if MainGamma <= 0 then FMainGamma := 1 else FMainGamma := MainGamma; if DisplayGamma <= 0 then FDisplayGamma := 2.2 // default value for a usual CRT else FDisplayGamma := DisplayGamma; Gamma := 1 / (FMainGamma * FDisplayGamma); // source high bound is the maximum possible source value which can appear (0..255) if FSourceBPS >= 8 then SourceHighBound := 255 else SourceHighBound := (1 shl FTargetBPS) - 1; // target high bound is the target value which corresponds to a target sample value of 1 (0..255) if FTargetBPS >= 8 then TargetHighBound := 255 else TargetHighBound := (1 shl FTargetBPS) - 1; for I := 0 to SourceHighBound do FGammaTable[I] := Round(Power((I / SourceHighBound), Gamma) * TargetHighBound); end; function MakeIcon32(Img: TBitmap; UpdateAlphaChannell : boolean = False): HICON; var IconInfo: TIconInfo; MaskBitmap: TBitmap; X, Y : integer; C : TsColor; TransColor : TColor; S : PByteArray; Fast32Src : TacFast32; begin MaskBitmap := TBitmap.Create; MaskBitmap.PixelFormat := pf8bit; MaskBitmap.Width := Img.Width; MaskBitmap.Height := Img.Height; if (Img.PixelFormat <> pf32bit) or UpdateAlphaChannell then begin Img.PixelFormat := pf32bit; Fast32Src := TacFast32.Create; if Fast32Src.Attach(Img) then begin TransColor := Fast32Src[0, 0].C; for Y := 0 to Img.Height - 1 do begin S := MaskBitmap.ScanLine[Y]; for X := 0 to Img.Width - 1 do begin C := Fast32Src[x, y]; if C.C <> TransColor then begin C.A := 0; // Fast32Src[x, y] := C; v6.47 S[X] := C.A; end else S[X] := $FF; end; end; end; FreeAndNil(Fast32Src); MaskBitmap.PixelFormat := pf1bit; end else begin MaskBitmap.PixelFormat := pf1bit; MaskBitmap.Canvas.Brush.Color := clBlack; MaskBitmap.Canvas.FillRect(Rect(0, 0, MaskBitmap.Width, MaskBitmap.Height)); end; try IconInfo.fIcon := True; IconInfo.hbmColor := Img.Handle; IconInfo.hbmMask := MaskBitmap.Handle; Result := CreateIconIndirect(IconInfo); finally FreeAndNil(MaskBitmap); end; end; function MakeCompIcon(Img: TPNGGraphic; BGColor : TColor = clNone): HICON; var IconInfo: TIconInfo; MaskBitmap, ColorBitmap: TBitmap; X, Y : integer; C : TsColor; Fast32Src, Fast32Dst : TacFast32; begin MaskBitmap := TBitmap.Create; MaskBitmap.PixelFormat := pf1bit; MaskBitmap.Width := Img.Width; MaskBitmap.Height := Img.Height; ColorBitmap := CreateBmp32(Img.Width, Img.Height); FillDC(ColorBitmap.Canvas.Handle, Rect(0, 0, ColorBitmap.Width, ColorBitmap.Height), BGColor); Img.Draw(ColorBitmap.Canvas, Rect(0, 0, ColorBitmap.Width, ColorBitmap.Height)); Fast32Src := TacFast32.Create; Fast32Dst := TacFast32.Create; if Img.PixelFormat <> pf32bit then begin Img.PixelFormat := pf32bit; if Fast32Src.Attach(Img) then begin // Make Alpha mask for Y := 0 to Img.Height - 1 do begin for X := 0 to Img.Width - 1 do begin C := Fast32Src[x, y]; if C.C = clFuchsia then C.A := 0 else C.A := MaxByte; Fast32Src[x, y] := C; end; end; end; end; if Fast32Src.Attach(Img) and Fast32Dst.Attach(ColorBitmap) then begin for Y := 0 to Img.Height - 1 do begin for X := 0 to Img.Width - 1 do begin C := Fast32Src[x, y]; Fast32Dst[x, y] := C; if C.A = 0 then begin SetPixelV(MaskBitmap.Canvas.Handle, X, Y, clWhite) end else SetPixelV(MaskBitmap.Canvas.Handle, X, Y, clBlack) end; end; end; FreeAndNil(Fast32Src); FreeAndNil(Fast32Dst); try IconInfo.fIcon := True; IconInfo.hbmColor := ColorBitmap.Handle; IconInfo.hbmMask := MaskBitmap.Handle; Result := CreateIconIndirect(IconInfo); finally FreeAndNil(MaskBitmap); FreeAndNil(ColorBitmap); end; end; procedure UpdateTransPixels(Img: TBitmap); var x, y : integer; BlackColor : TsColor; Fast32 : TacFast32; C : TsColor; begin Fast32 := TacFast32.Create; if (Img.PixelFormat = pf32bit) and Fast32.Attach(Img) then begin BlackColor.I := 0; for x := 0 to Img.Width - 1 do for y := 0 to Img.Height - 1 do begin C := Fast32.Pixels[x, y]; if (C.R = $FF) and (C.G = $FF) and (C.B = $FF) and (C.A = 0) then Fast32.Pixels[x, y] := BlackColor; // if C. {and $FFFFFFFF} = $FFFFFFFF then Fast32.Pixels[x, y] := BlackColor; end; end; FreeAndNil(Fast32); end; procedure TPNGGraphic.Draw(ACanvas: TCanvas; const Rect: TRect); var DstBmp, SrcBmp, SrcBmp8, Mask : TBitmap; w, h : integer; begin if (PixelFormat = pf32bit) then begin w := WidthOf(Rect); h := HeightOf(Rect); DstBmp := CreateBmp32(w, h + Integer(Reflected) * (h div 2)); BitBlt(DstBmp.Canvas.Handle, 0, 0, w, DstBmp.Height, ACanvas.Handle, Rect.Left, Rect.Top, SRCCOPY); if (w = Width) and (h = Height) then begin CopyBmp32(Classes.Rect(0, 0, w, h), Classes.Rect(0, 0, w, h), DstBmp, Self, EmptyCI, False, clNone, 0, Reflected); end else begin // If stretched SrcBmp := TBitmap.Create; SrcBmp.PixelFormat := pfDevice; SrcBmp.Width := w; SrcBmp.Height := h; SetStretchBltMode(SrcBmp.Canvas.Handle, COLORONCOLOR); // Stretch(SrcBmp, Image, Image.Width, Image.Height, ftMitchell); StretchBlt(SrcBmp.Canvas.Handle, 0, 0, w, h, Canvas.Handle, 0, 0, Width, Height, SRCCOPY); SrcBmp.PixelFormat := pf32bit; Mask := CreateBmpLike(Self); Mask.PixelFormat := pf8bit; CopyChannel(Self, Mask, 3, True); Mask.PixelFormat := pfDevice; SrcBmp8 := TBitmap.Create; SrcBmp8.PixelFormat := pfDevice; SrcBmp8.Width := w; SrcBmp8.Height := h; SetStretchBltMode(SrcBmp8.Canvas.Handle, HALFTONE); StretchBlt(SrcBmp8.Canvas.Handle, 0, 0, w, h, Mask.Canvas.Handle, 0, 0, Width, Height, SRCCOPY); SrcBmp8.PixelFormat := pf8bit; CopyChannel(SrcBmp, SrcBmp8, 3, False); FreeAndNil(Mask); FreeAndNil(SrcBmp8); CopyBmp32(Classes.Rect(0, 0, w, h), Classes.Rect(0, 0, w, h), DstBmp, SrcBmp, EmptyCI, False, clNone, 0, False); FreeAndNil(SrcBmp); end; BitBlt(ACanvas.Handle, Rect.Left, Rect.Top, DstBmp.Width, DstBmp.Height, DstBmp.Canvas.Handle, 0, 0, SRCCOPY); FreeAndNil(DstBmp); end else inherited end; {$IFNDEF NOACPNG} initialization TPicture.RegisterFileFormat('png','Portable network graphics (AlphaControls)', TPNGGraphic); finalization TPicture.UnregisterGraphicClass(TPNGGraphic); {$ENDIF} end.
var b,p,m:int64; function power(b,p,m:int64):int64; var temp:int64; begin if (m=1) then exit(0) else if (p=0) then exit(1) else if (b<2) then exit(b); temp:=sqr(power(b,p div 2,m)) mod m; if p mod 2=1 then exit((temp*b) mod m) else exit(temp); end; begin while not eof do begin readln(b); readln(p); readln(m); readln; writeln(power(b,p,m)); end; end.
program truncamento; {truncar significa deixar somente a parte inteira do numero} var nI : integer; nR : real; begin read(nR); nI:= trunc(nR); writeln(nI); end.
unit GospelIDE; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, Menus, ComCtrls, ClipBrd, ToolWin, ActnList, ImgList, CodeEdit, Parser, GSystem, Compiler; type TCompilerIDE = class(TForm) MainMenu: TMainMenu; FileNewItem: TMenuItem; FileOpenItem: TMenuItem; FileSaveItem: TMenuItem; FileSaveAsItem: TMenuItem; FilePrintItem: TMenuItem; FileExitItem: TMenuItem; EditUndoItem: TMenuItem; EditCutItem: TMenuItem; EditCopyItem: TMenuItem; EditPasteItem: TMenuItem; HelpAboutItem: TMenuItem; OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; PrintDialog: TPrintDialog; StatusBar: TStatusBar; StandardToolBar: TToolBar; OpenButton: TToolButton; SaveButton: TToolButton; PrintButton: TToolButton; ToolButton5: TToolButton; UndoButton: TToolButton; CutButton: TToolButton; CopyButton: TToolButton; PasteButton: TToolButton; ToolbarImages: TImageList; ToolButton1: TToolButton; EditCutCmd: TAction; EditCopyCmd: TAction; EditPasteCmd: TAction; EditUndoCmd: TAction; EditFontCmd: TAction; Search1: TMenuItem; Find1: TMenuItem; Replace1: TMenuItem; SearchAgain1: TMenuItem; GotolineNumber1: TMenuItem; Options1: TMenuItem; Fonts1: TMenuItem; SelectAll1: TMenuItem; Redo1: TMenuItem; Reopen1: TMenuItem; Preferences1: TMenuItem; Content1: TMenuItem; Tools1: TMenuItem; ConfigureTools1: TMenuItem; ActionList1: TActionList; Run1: TMenuItem; Syntaxcheck1: TMenuItem; Compile1: TMenuItem; Run2: TMenuItem; StatusBar1: TStatusBar; Panel6: TPanel; Panel1: TPanel; Panel3: TPanel; GroupBox1: TGroupBox; Types: TListBox; GroupBox2: TGroupBox; Variables: TListBox; GroupBox3: TGroupBox; Constants: TListBox; GroupBox5: TGroupBox; Procedures: TListBox; GroupBox6: TGroupBox; Functions: TListBox; Panel4: TPanel; GroupBox4: TGroupBox; Tokens: TListBox; GroupBox7: TGroupBox; Blocks: TListBox; GroupBox8: TGroupBox; Console: TListBox; CodeContainer: TGroupBox; View1: TMenuItem; Symbols1: TMenuItem; procedure SelectionChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ShowHint(Sender: TObject); procedure FileNew(Sender: TObject); procedure FileOpen(Sender: TObject); procedure FileSave(Sender: TObject); procedure FileSaveAs(Sender: TObject); procedure FilePrint(Sender: TObject); procedure FileExit(Sender: TObject); procedure EditUndo(Sender: TObject); procedure EditCut(Sender: TObject); procedure EditCopy(Sender: TObject); procedure EditPaste(Sender: TObject); procedure HelpAbout(Sender: TObject); procedure SelectFont(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormPaint(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormShow(Sender: TObject); procedure RichEditChange(Sender: TObject); procedure ActionList1Update(Action: TBasicAction; var Handled: Boolean); procedure Find1Click(Sender: TObject); procedure Preferences1Click(Sender: TObject); procedure BlocksClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Syntaxcheck1Click(Sender: TObject); procedure Compile1Click(Sender: TObject); procedure Run2Click(Sender: TObject); procedure Symbols1Click(Sender: TObject); private CurrentBlock: TBlock; ReadyToRun: boolean; private FFileName: string; FUpdating: Boolean; function CurrText: TTextAttributes; procedure SetFileName(const FileName: String); procedure CheckFileSave; procedure SetEditRect; procedure WMDropFiles(var Msg: TWMDropFiles); message WM_DROPFILES; procedure PerformFileOpen(const AFileName: string); procedure SetModified(Value: Boolean); procedure EditorMoveCursor(Sender: TObject; const Col, Row: longint); public Editor: TCodeEdit; GospelCompiler: TGospelCompiler; function Compile: boolean; procedure ShowSymbols; procedure ShowBlocks; procedure Run; end; var CompilerIDE: TCompilerIDE; implementation uses REAbout, RichEdit, ShellAPI, ReInit, Fonts, FindText, PreferencesDlg; const GutterWid = 6; {$R *.DFM} procedure TCompilerIDE.SelectionChange(Sender: TObject); begin with Editor.Paragraph do try FUpdating := True; finally FUpdating := False; ShowCaret(Editor.Handle); end; end; procedure TCompilerIDE.SetFileName(const FileName: String); begin FFileName := FileName; Caption := Format('%s - %s', [ExtractFileName(FileName), Application.Title]); end; procedure TCompilerIDE.CheckFileSave; var SaveResp: Integer; begin if not Editor.Modified then Exit; SaveResp := MessageDlg(Format('Save changes to %s?', [FFileName]), mtConfirmation, mbYesNoCancel, 0); case SaveResp of idYes: FileSave(Self); idNo: {Nothing}; idCancel: Abort; end; end; procedure TCompilerIDE.SetEditRect; var R: TRect; begin with Editor do begin R := Rect(GutterWid, 0, ClientWidth-GutterWid, ClientHeight); SendMessage(Handle, EM_SETRECT, 0, Longint(@R)); end; end; function TCompilerIDE.CurrText: TTextAttributes; begin if Editor.SelLength > 0 then Result := Editor.SelAttributes else Result := Editor.DefAttributes; end; { Event Handlers } procedure TCompilerIDE.FormCreate(Sender: TObject); var ScreenLogPixels: Integer; DC: HDC; begin Editor := TCodeEdit.Create(Self); Editor.Parent := CodeContainer; Editor.Align := alClient; Editor.OnMoveCaret := EditorMoveCursor; Editor.OnChange := RichEditChange; GospelCompiler := TGospelCompiler.Create; GospelCompiler.Console := Console; Application.OnHint := ShowHint; OpenDialog.InitialDir := ExtractFilePath(ParamStr(0)); SaveDialog.InitialDir := OpenDialog.InitialDir; SetFileName('Untitled'); SelectionChange(Self); try CurrText.Name := 'Courier New'; CurrText.Size := 10; except CurrText.Name := FontsDlg.FontName.Items[0]; DC := GetDC(0); ScreenLogPixels := GetDeviceCaps(DC, LOGPIXELSY); CurrText.Size := -MulDiv(DefFontData.Height, 72, ScreenLogPixels); end; end; procedure TCompilerIDE.ShowHint(Sender: TObject); begin if Length(Application.Hint) > 0 then begin StatusBar.SimplePanel := True; StatusBar.SimpleText := Application.Hint; end else StatusBar.SimplePanel := False; end; procedure TCompilerIDE.FileNew(Sender: TObject); begin SetFileName('Untitled'); Editor.Lines.Clear; Editor.Modified := False; SetModified(False); end; procedure TCompilerIDE.PerformFileOpen(const AFileName: string); begin Editor.Lines.LoadFromFile(AFileName); SetFileName(AFileName); Editor.SetFocus; Editor.Modified := False; SetModified(False); end; procedure TCompilerIDE.FileOpen(Sender: TObject); begin CheckFileSave; if OpenDialog.Execute then begin PerformFileOpen(OpenDialog.FileName); Editor.ReadOnly := ofReadOnly in OpenDialog.Options; end; end; procedure TCompilerIDE.FileSave(Sender: TObject); begin if FFileName = 'Untitled' then FileSaveAs(Sender) else begin Editor.Lines.SaveToFile(FFileName); Editor.Modified := False; SetModified(False); end; end; procedure TCompilerIDE.FileSaveAs(Sender: TObject); begin if SaveDialog.Execute then begin if FileExists(SaveDialog.FileName) then if MessageDlg(Format('OK to overwrite %s', [SaveDialog.FileName]), mtConfirmation, mbYesNoCancel, 0) <> idYes then Exit; Editor.Lines.SaveToFile(SaveDialog.FileName); SetFileName(SaveDialog.FileName); Editor.Modified := False; SetModified(False); end; end; procedure TCompilerIDE.FilePrint(Sender: TObject); begin if PrintDialog.Execute then Editor.Print(FFileName); end; procedure TCompilerIDE.FileExit(Sender: TObject); begin Close; end; procedure TCompilerIDE.EditUndo(Sender: TObject); begin with Editor do if HandleAllocated then SendMessage(Handle, EM_UNDO, 0, 0); end; procedure TCompilerIDE.EditCut(Sender: TObject); begin Editor.CutToClipboard; end; procedure TCompilerIDE.EditCopy(Sender: TObject); begin Editor.CopyToClipboard; end; procedure TCompilerIDE.EditPaste(Sender: TObject); begin Editor.PasteFromClipboard; end; procedure TCompilerIDE.HelpAbout(Sender: TObject); begin with TAboutBox.Create(Self) do try ShowModal; finally Free; end; end; procedure TCompilerIDE.SelectFont(Sender: TObject); begin with FontsDlg do begin FontSize.Text := IntToStr(Editor.SelAttributes.Size); FontName.Text := Editor.SelAttributes.Name; if ShowModal = mrOk then begin CurrText.Size := StrToInt(FontSize.Text); CurrText.Name := FontName.Items[FontName.ItemIndex]; end; end; Editor.SetFocus; end; procedure TCompilerIDE.FormResize(Sender: TObject); begin SetEditRect; SelectionChange(Sender); end; procedure TCompilerIDE.FormPaint(Sender: TObject); begin SetEditRect; end; procedure TCompilerIDE.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin try CheckFileSave; except CanClose := False; end; end; procedure TCompilerIDE.FormShow(Sender: TObject); begin DragAcceptFiles(Handle, True); RichEditChange(nil); Editor.SetFocus; { Check if we should load a file from the command line } if (ParamCount > 0) and FileExists(ParamStr(1)) then PerformFileOpen(ParamStr(1)); end; procedure TCompilerIDE.WMDropFiles(var Msg: TWMDropFiles); var CFileName: array[0..MAX_PATH] of Char; begin try if DragQueryFile(Msg.Drop, 0, CFileName, MAX_PATH) > 0 then begin CheckFileSave; PerformFileOpen(CFileName); Msg.Result := 0; end; finally DragFinish(Msg.Drop); end; end; procedure TCompilerIDE.RichEditChange(Sender: TObject); begin SetModified(Editor.Modified); end; procedure TCompilerIDE.SetModified(Value: Boolean); begin if Value then begin StatusBar.Panels[1].Text := 'Modified'; ReadyToRun := false; end else StatusBar.Panels[1].Text := ''; end; procedure TCompilerIDE.ActionList1Update(Action: TBasicAction; var Handled: Boolean); begin { Update the status of the edit commands } EditCutCmd.Enabled := Editor.SelLength > 0; EditCopyCmd.Enabled := EditCutCmd.Enabled; if Editor.HandleAllocated then begin EditUndoCmd.Enabled := Editor.Perform(EM_CANUNDO, 0, 0) <> 0; EditPasteCmd.Enabled := Editor.Perform(EM_CANPASTE, 0, 0) <> 0; end; end; procedure TCompilerIDE.EditorMoveCursor(Sender: TObject; const Col, Row: Integer); begin StatusBar.Panels[0].Text := Format('Line: %3d Col: %3d', [Row, Col]); end; procedure TCompilerIDE.Find1Click(Sender: TObject); var FoundAt: LongInt; //Ver la UNit Commdlg.pas en Rtl\Win y Dialogos StartPos, ToEnd: integer; ST: TSearchTypes; begin if Find.ShowModal = mrOk then with Editor do begin if Find.Scope.ItemIndex = scSelected_Text then begin Startpos := SelStart; ToEnd := SelStart + SelLength; end else begin if Find.Origin.ItemIndex = orFrom_Cursor then StartPos := SelStart else StartPos := 0; ToEnd := Length(Text); end; ST := []; if Find.MatchCase.Checked then ST := ST + [stMatchCase]; if Find.WholeWords.Checked then ST := ST + [stWholeWord]; FoundAt := FindText(Find.Text.Text, StartPos, ToEnd, ST); if FoundAt <> -1 then begin SetFocus; SelStart := FoundAt; SelLength := Length(Find.Text.Text); end else begin MessageDlg(Format('Search string ''%s'' not found', [Find.Text.Text]), mtInformation, [mbOk], 0); if SelLength > 0 then SelLength := 0; end; end; end; procedure TCompilerIDE.Preferences1Click(Sender: TObject); begin if Preferences.ShowModal = mrOk then with Editor do begin if Preferences.AutoIndentMode.Checked then Options := Options + [eoAutoIdentMode] else Options := Options - [eoAutoIdentMode]; if Preferences.BackspaceUnindent.Checked then Options := Options + [eoBackspaceUnindents] else Options := Options - [eoBackspaceUnindents]; if Preferences.SmartTab.Checked then Options := Options + [eoSmartTab] else Options := Options - [eoSmartTab]; if Preferences.InsertMode.Checked then Options := Options + [eoInsertMode] else Options := Options - [eoInsertMode]; end; end; function TCompilerIDE.Compile: boolean; begin GospelCompiler.Source := Editor.Text; Result := GospelCompiler.Compile; Statusbar1.SimpleText := GospelCompiler.CompilerMessage; CurrentBlock := GospelCompiler.GlobalBlock; ShowBlocks; ShowSymbols; end; procedure TCompilerIDE.ShowSymbols; var i: integer; begin Types.Clear; Variables.Clear; Constants.Clear; Procedures.Clear; Functions.Clear; for i := 0 to pred(CurrentBlock.Types.Count) do Types.Items.Add(CurrentBlock.Types[i].Name); for i := 0 to pred(CurrentBlock.Variables.Count) do Variables.Items.Add(Format('%s : %s', [CurrentBlock.Variables[i].Name, TData(CurrentBlock.Variables[i]).DataType.Name])); for i := 0 to pred(CurrentBlock.Constants.Count) do Constants.Items.Add(Format('%s : %s', [CurrentBlock.Constants[i].Name, TData(CurrentBlock.Constants[i]).DataType.Name])); for i := 0 to pred(CurrentBlock.Procedures.Count) do Procedures.Items.Add(CurrentBlock.Procedures[i].Name); for i := 0 to pred(CurrentBlock.Functions.Count) do Functions.Items.Add(CurrentBlock.Functions[i].Name); end; procedure TCompilerIDE.ShowBlocks; var i: integer; begin Blocks.Clear; for i := 0 to pred(GospelCompiler.BlockList.Count) do Blocks.Items.Add(TBlock(GospelCompiler.BlockList.Items[i]).Name); end; procedure TCompilerIDE.BlocksClick(Sender: TObject); var Block: TBlock; begin if Blocks.ItemIndex >= 0 then begin Block := TBlock(GospelCompiler.BlockList.Items[Blocks.ItemIndex]); if Block <> CurrentBlock then begin CurrentBlock := Block; ShowSymbols; end; end; end; procedure TCompilerIDE.FormDestroy(Sender: TObject); begin GospelCompiler.free; end; procedure TCompilerIDE.Syntaxcheck1Click(Sender: TObject); begin Compile; end; procedure TCompilerIDE.Compile1Click(Sender: TObject); begin Compile; end; procedure TCompilerIDE.Run2Click(Sender: TObject); begin if ReadyToRun then Run else if Compile then Run; end; procedure TCompilerIDE.Run; begin GospelCompiler.Interpret; end; procedure TCompilerIDE.Symbols1Click(Sender: TObject); begin Symbols1.Checked := not Symbols1.Checked; Panel1.Visible := Symbols1.Checked; end; end.
unit WS.Common; interface uses System.Generics.Collections, MVCFramework, MVCFramework.Commons, MVCFramework.SysControllers,MVCFramework.Logger; type TMVCControllerClass = class of TMVCController; function RegisterWSController(const AClass: TMVCControllerClass): integer; procedure LoadWSControllers(FMVC: TMVCEngine); var WSConnectionString: string; implementation uses MVCAsyncMiddleware, MVCFramework.Middleware.CORS, MVCgzipMiddleware; var FList: TThreadList<TMVCControllerClass>; procedure LoadWSControllers(FMVC: TMVCEngine); var i: integer; begin with FList.LockList do try for i := 0 to Count - 1 do FMVC.AddController(Items[i]); finally FList.UnlockList; end; FMVC.AddMiddleware(TMVCgzipCallBackMiddleware.Create); FMVC.AddMiddleware(TMVCAsyncCallBackMiddleware.Create); FMVC.AddMiddleware(TCORSMiddleware.Create); end; function RegisterWSController(const AClass: TMVCControllerClass): integer; begin with FList.LockList do try Add(AClass); result := Count - 1; finally FList.UnlockList; end; end; initialization FList := TThreadList<TMVCControllerClass>.Create; finalization FList.Free; end.
unit OurCollection; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type TOurCollectionItem = class(TCollectionItem) private FSomeValue : String; protected function GetDisplayName : String; override; public procedure Assign(Source: TPersistent); override; published property SomeValue : String read FSomeValue write FSomeValue; end; TOurCollection = class(TCollection) private { Private declarations } FOwner : TComponent; protected { Protected declarations } function GetOwner : TPersistent; override; function GetItem(Index: Integer): TOurCollectionItem; procedure SetItem(Index: Integer; Value: TOurCollectionItem); procedure Update(Item: TOurCollectionItem); public { Public declarations } constructor Create(AOwner : TComponent); function Add : TOurCollectionItem; function Insert(Index: Integer): TOurCollectionItem; property Items[Index: Integer]: TOurCollectionItem read GetItem write SetItem; published { Published declarations } end; TCollectionComponent = class(TComponent) private FOurCollection : TOurCollection; procedure SetOurCollection(const Value: TOurCollection); protected public constructor Create(AOwner : TComponent); override; destructor Destroy; override; published property OurCollection : TOurCollection read FOurCollection write SetOurCollection; end; procedure Register; implementation procedure Register; begin RegisterComponents('Article', [TCollectionComponent]); end; { TOurCollectionItem } procedure TOurCollectionItem.Assign(Source: TPersistent); begin if Source is TOurCollectionItem then SomeValue := TOurCollectionItem(Source).SomeValue else inherited; //raises an exception end; function TOurCollectionItem.GetDisplayName: String; begin Result := Format('Item %d',[Index]); end; { TOurCollection } function TOurCollection.Add: TOurCollectionItem; begin Result := TOurCollectionItem(inherited Add); end; constructor TOurCollection.Create(AOwner: TComponent); begin inherited Create(TOurCollectionItem); FOwner := AOwner; end; function TOurCollection.GetItem(Index: Integer): TOurCollectionItem; begin Result := TOurCollectionItem(inherited GetItem(Index)); end; function TOurCollection.GetOwner: TPersistent; begin Result := FOwner; end; function TOurCollection.Insert(Index: Integer): TOurCollectionItem; begin Result := TOurCollectionItem(inherited Insert(Index)); end; procedure TOurCollection.SetItem(Index: Integer; Value: TOurCollectionItem); begin inherited SetItem(Index, Value); end; procedure TOurCollection.Update(Item: TOurCollectionItem); begin inherited Update(Item); end; { TCollectionComponent } constructor TCollectionComponent.Create(AOwner: TComponent); begin inherited; FOurCollection := TOurCollection.Create(Self); end; destructor TCollectionComponent.Destroy; begin FOurCollection.Free; inherited; end; procedure TCollectionComponent.SetOurCollection( const Value: TOurCollection); begin FOurCollection.Assign(Value); end; end.
Unit ZRegDlg; {################################} {# ZiLEM Z80 Emulator #} {# Register/Code Dialog #} {# Copyright (c) 1994 James Ots #} {# All rights reserved #} {################################} Interface Uses Objects, Views, Dialogs, Drivers, ZEngine, ZGlobals, ZConsts, ZInputs, MsgBox; Type PWord = ^Word; PByte = ^Byte; PRegisterInput = ^TRegisterInput; TRegisterInput = Object(TView) Register : PWord; Constructor Init(var Bounds : TRect; ARegister : PWord); Procedure Draw; virtual; Procedure HandleEvent(var Event : TEvent); virtual; Procedure MoveLeft; Procedure MoveRight; Procedure Enter(const AChar : Char); Function ChangedCursor(GlobalPos : TPoint) : Boolean; End; PFlagInput = ^TFlagInput; TFlagInput = Object(TView) Register : PByte; FlagMask : Byte; Constructor Init(var Bounds : TRect; ARegister : PByte; AFlagMask : Byte); Procedure Draw; virtual; Procedure HandleEvent(var Event : TEvent); virtual; Procedure Enter(const AChar : Char); End; PShowCode = ^TShowCode; TShowCode = Object(TView) PZMem : Pointer; PC : PWord; Constructor Init(var Bounds : TRect; APC : PWord; AZMem : Pointer); Procedure Draw; virtual; End; PRegistersDialog = ^TRegistersDialog; TRegistersDialog = Object(TDialog) Constructor Init(AZMem : Pointer; Engine : PEngine); Procedure HandleEvent(var Event : TEvent); virtual; Procedure Close; virtual; End; PEnterCodeDialog = ^TEnterCodeDialog; TEnterCodeDialog = Object(TDialog) PZMem : Pointer; TempMem : Pointer; CodeInputLine : PInputLine; AddressInputLine : PAddressInputLine; Constructor Init(APZMem : Pointer; AnAddress : Word); Procedure HandleEvent(var Event : TEvent); virtual; Destructor Done; virtual; End; PCodeViewer = ^TCodeViewer; TCodeViewer = Object(TScroller) PZMem : Pointer; Engine : PEngine; StartAt : Word; CursorAt : Word; Constructor Init(var Bounds : TRect; AVScroller : PScrollBar; CPZMem : Pointer; var AnEngine : PEngine); Procedure Draw; virtual; Procedure HandleEvent(var Event : TEvent); virtual; Procedure MoveDown; Procedure MoveUp; Procedure MoveToPC; Procedure ScrollDraw; virtual; Function ChangedCursor(GlobalPos : TPoint) : Boolean; Function ChangedPC(GlobalPos : TPoint) : Boolean; Procedure ChangePC; Procedure ReCalcCursor; End; PCodeWindow = ^TCodeWindow; TCodeWindow = Object(TWindow) Interior : PCodeViewer; PZMem : Pointer; Engine : PEngine; Constructor Init(var Bounds : TRect; CPZMem : Pointer; var AnEngine : PEngine); Procedure HandleEvent(var Event : TEvent); virtual; Procedure Close; virtual; End; Function OpCode(var AZMem : Pointer; Address : Word; var AString : String) : Byte; Implementation {#1=ld ,#2=jr ,#3=bit ,#4=res ,#5=set ,#6=call ,#7=jp , #8=inc ,#9=dec ,#10=add ,#11=adc ,#12=sub ,#13=sbc , #14=and ,#15=xor ,#16=or ,#17=cp ,#18=push ,#19=pop , #20=rlc ,#21=rrc ,#22=rl ,#23=rr ,#24=sla ,#25=sra , #26=sll ,#27=in ,#28=out ,#29=ret,#30=rst ,#31=hl, #128=h, #129=l} {%w=word, %d=index displacement, %b=byte, %e=relative jump offset} {dollarB=table as shown in Appendix A.B, dollarC= " " " " " A.C, dollarE= " " " " " A.E} {show blanks as DB opcode byte, i.e. EDH 01H would be DB $ED DB $01} Const Convert : Array[1..30] of string = ('ld ','jr ','bit ','res ','set ','call ','jp ', 'inc ','dec ','add ','adc ','sub ','sbc ', 'and ','xor ','or ','cp ','push ','pop ', 'rlc ','rrc ','rl ','rr ','sla ','sra ', 'sll ','in ','out ','ret','rst '); OpCodes : Array[1..3,0..255] of string[10] = (('nop',#1'bc,%w',#1'(bc),a',#8'bc',#8'b',#9'b', #1'b,%b','rlca','ex af,af''',#10#31',bc',#1'a,(bc)', #9'bc',#8'c',#9'c',#1'c,%b','rrca','djnz %e', #1'de,%w',#1'(de),a',#8'de',#8'd',#9'd',#1'd,%b', 'rla',#2'%e',#10#31',de',#1'a,(de)',#9'de',#8'e', #9'e',#1'e,%b','rra',#2'nz,%e',#1#31',%w',#1'(%w),'#31, #8#31,#8#128,#9#128,#1#128',%b','daa',#2'z,%e', #10#31','#31,#1#31',(%w)',#9#31,#8#129,#9#129,#1#129',%b', 'cpl',#2'nc,%e',#1'sp,%w',#1'(%w),a',#8'sp',#8'('#31'%d)', #9'('#31'%d)',#1'('#31'%d),%b','scf',#2'c,%e',#10#31',sp', #1'a,(%w)',#9'sp',#8'a',#9'a',#1'a,%b','ccf', #1'b,b',#1'b,c',#1'b,d',#1'b,e', #1'b,'#128,#1'b,'#129,#1'b,('#31'%d)',#1'b,a', #1'c,b',#1'c,c',#1'c,d',#1'c,e', #1'c,'#128,#1'c,'#129,#1'c,('#31'%d)',#1'c,a', #1'd,b',#1'd,c',#1'd,d',#1'd,e', #1'd,'#128,#1'd,'#129,#1'd,('#31'%d)',#1'd,a', #1'e,b',#1'e,c',#1'e,d',#1'e,e', #1'e,'#128,#1'e,'#129,#1'e,('#31'%d)',#1'e,a', #1#128',b',#1#128',c',#1#128',d',#1#128',e', #1#128','#128,#1#128','#129,#1'h,('#31'%d)',#1#128',a', #1#129',b',#1#129',c',#1#129',d',#1#129',e', #1#129','#128,#1#129','#129,#1'l,('#31'%d)',#1#129',a', #1'('#31'%d),b',#1'('#31'%d),c',#1'('#31'%d),d',#1'('#31'%d),e', #1'('#31'%d),'#128,#1'('#31'%d),'#129,'halt',#1'('#31'%d),a', #1'a,b',#1'a,c',#1'a,d',#1'a,e', #1'a,'#128,#1'a,'#129,#1'a,('#31'%d)',#1'a,a', #10'a,b',#10'a,c',#10'a,d',#10'a,e', #10'a,'#128,#10'a,'#129,#10'a,('#31'%d)',#10'a,a', #11'a,b',#11'a,c',#11'a,d',#11'a,e', #11'a,'#128,#11'a,'#129,#11'a,('#31'%d)',#11'a,a', #12'b',#12'c',#12'd',#12'e', #12#128,#12#129,#12'('#31'%d)',#12'a', #13'a,b',#13'a,c',#13'a,d',#13'a,e', #13'a,'#128,#13'a,'#129,#13'a,('#31'%d)',#13'a,a', #14'b',#14'c',#14'd',#14'e', #14#128,#14#129,#14'('#31'%d)',#14'a', #15'b',#15'c',#15'd',#15'e', #15#128,#15#129,#15'('#31'%d)',#15'a', #16'b',#16'c',#16'd',#16'e', #16#128,#16#129,#16'('#31'%d)',#16'a', #17'b',#17'c',#17'd',#17'e', #17#128,#17#129,#17'('#31'%d)',#17'a', #29' nz',#19'bc',#7'nz,%w',#7'%w',#6'nz,%w', #18'bc',#10'a,%b',#30'0',#29' z',#29, #7'z,%w','$B',#6'z,%w',#6'%w',#11'a,%b', #30'8',#29' nc',#19'de',#7'nc,%w',#28'(%b),a', #6'nc,%w',#18'de',#12'%b',#30'10',#29' c', 'exx',#7'c,%w',#27'a,(%b)',#6'c,%w','$C', #13'a,%b',#30'18',#29' po',#19#31,#7'po,%w', 'ex (sp),'#31,#6'po,%w',#18#31,#14'%b',#30'20', #29' pe',#7'('#31')',#7'pe,%w','ex de,'#31,#6'pe,%w', '$E',#15'%b',#30'28',#29' p',#19'af',#7'p,%w', 'di',#6'p,%w',#18'af',#16'%b',#30'30',#29' m', #1'sp,'#31,#7'm,%w','ei',#6'm,%w','$C', #17'%b',#30'38'), (#20'b',#20'c',#20'd',#20'e', #20#128,#20#129,#20'('#31'%d)',#20'a', #21'b',#21'c',#21'd',#21'e', #21#128,#21#129,#21'('#31'%d)',#21'a', #22'b',#22'c',#22'd',#22'e', #22#128,#22#129,#22'('#31'%d)',#22'a', #23'b',#23'c',#23'd',#23'e', #23#128,#23#129,#23'('#31'%d)',#23'a', #24'b',#24'c',#24'd',#24'e', #24#128,#24#129,#24'('#31'%d)',#24'a', #25'b',#25'c',#25'd',#25'e', #25#128,#25#129,#25'('#31'%d)',#25'a', #26'b',#26'c',#26'd',#26'e', #26#128,#26#129,#26'('#31'%d)',#26'a', 's'#22'b','s'#22'c','s'#22'd','s'#22'e', 's'#22#128,'s'#22#129,'s'#22'('#31'%d)','s'#22'a', #3'0,b',#3'0,c',#3'0,d',#3'0,e', #3'0,'#128,#3'0,'#129,#3'0,('#31'%d)',#3'0,a', #3'1,b',#3'1,c',#3'1,d',#3'1,e', #3'1,'#128,#3'1,'#129,#3'1,('#31'%d)',#3'1,a', #3'2,b',#3'2,c',#3'2,d',#3'2,e', #3'2,'#128,#3'2,'#129,#3'2,('#31'%d)',#3'2,a', #3'3,b',#3'3,c',#3'3,d',#3'3,e', #3'3,'#128,#3'3,'#129,#3'3,('#31'%d)',#3'3,a', #3'4,b',#3'4,c',#3'4,d',#3'4,e', #3'4,'#128,#3'4,'#129,#3'4,('#31'%d)',#3'4,a', #3'5,b',#3'5,c',#3'5,d',#3'5,e', #3'5,'#128,#3'5,'#129,#3'5,('#31'%d)',#3'5,a', #3'6,b',#3'6,c',#3'6,d',#3'6,e', #3'6,'#128,#3'6,'#129,#3'6,('#31'%d)',#3'6,a', #3'7,b',#3'7,c',#3'7,d',#3'7,e', #3'7,'#128,#3'7,'#129,#3'7,('#31'%d)',#3'7,a', #4'0,b',#4'0,c',#4'0,d',#4'0,e', #4'0,'#128,#4'0,'#129,#4'0,('#31'%d)',#4'0,a', #4'1,b',#4'1,c',#4'1,d',#4'1,e', #4'1,'#128,#4'1,'#129,#4'1,('#31'%d)',#4'1,a', #4'2,b',#4'2,c',#4'2,d',#4'2,e', #4'2,'#128,#4'2,'#129,#4'2,('#31'%d)',#4'2,a', #4'3,b',#4'3,c',#4'3,d',#4'3,e', #4'3,'#128,#4'3,'#129,#4'3,('#31'%d)',#4'3,a', #4'4,b',#4'4,c',#4'4,d',#4'4,e', #4'4,'#128,#4'4,'#129,#4'4,('#31'%d)',#4'4,a', #4'5,b',#4'5,c',#4'5,d',#4'5,e', #4'5,'#128,#4'5,'#129,#4'5,('#31'%d)',#4'5,a', #4'6,b',#4'6,c',#4'6,d',#4'6,e', #4'6,'#128,#4'6,'#129,#4'6,('#31'%d)',#4'6,a', #4'7,b',#4'7,c',#4'7,d',#4'7,e', #4'7,'#128,#4'7,'#129,#4'7,('#31'%d)',#4'7,a', #5'0,b',#5'0,c',#5'0,d',#5'0,e', #5'0,'#128,#5'0,'#129,#5'0,('#31'%d)',#5'0,a', #5'1,b',#5'1,c',#5'1,d',#5'1,e', #5'1,'#128,#5'1,'#129,#5'1,('#31'%d)',#5'1,a', #5'2,b',#5'2,c',#5'2,d',#5'2,e', #5'2,'#128,#5'2,'#129,#5'2,('#31'%d)',#5'2,a', #5'3,b',#5'3,c',#5'3,d',#5'3,e', #5'3,'#128,#5'3,'#129,#5'3,('#31'%d)',#5'3,a', #5'4,b',#5'4,c',#5'4,d',#5'4,e', #5'4,'#128,#5'4,'#129,#5'4,('#31'%d)',#5'4,a', #5'5,b',#5'5,c',#5'5,d',#5'5,e', #5'5,'#128,#5'5,'#129,#5'5,('#31'%d)',#5'5,a', #5'6,b',#5'6,c',#5'6,d',#5'6,e', #5'6,'#128,#5'6,'#129,#5'6,('#31'%d)',#5'6,a', #5'7,b',#5'7,c',#5'7,d',#5'7,e', #5'7,'#128,#5'7,'#129,#5'7,('#31'%d)',#5'7,a'), ('','','','','','','','','','','','','','','','', '','','','','','','','','','','','','','','','', '','','','','','','','','','','','','','','','', '','','','','','','','','','','','','','','','', #27'b,(c)',#28'(c),b',#13#31',bc',#1'(%w),bc', 'neg','retn','im 0',#1'i,a',#27'c,(c)',#28'(c),c', #11#31',bc',#1'bc,(%w)','','reti','',#1'r,a',#27'd,(c)', #28'(c),d',#13#31',de',#1'(%w),de','','','im 1',#1'a,i', #27'e,(c)',#28'(c),e',#11#31',de',#1'de,(%w),','','','im 2',#1'a,r', #27#128',(c)',#28'(c),'#128,#13#31','#31,'','','','','rrd', #27#129',(c)',#28'(c),'#129,#11#31','#31,'','','','','rld', '['#27'(c)]','',#13#31',sp',#1'(%w),sp','','','','', #27'a,(c)',#28'(c),a',#11#31',sp',#1'sp,(%w)', '','','','', '','','','','','','','','','','','','','','','', '','','','','','','','','','','','','','','','', 'ldi','cpi','ini','outi','','','','','ldd','cpd', 'ind','outd','','','','','ldir','cpir', 'inir','otir','','','','','lddr','cpdr', 'indr','otdr','','','','', '','','','','','','','','','','','','','','','', '','','','','','','','','','','','','','','','', '','','','','','','','','','','','','','','','', '','','','','','','','','','','','','','','','')); Function UpperCase(AString : String) : String; Var i : Integer; Begin If (Pref.Prefs and 4) = 4 then For i := 1 to length(AString) do AString[i] := UpCase(AString[i]); UpperCase := AString; End; {of UpperCase} Function DownCase(AChar : Char) : Char; Begin If (AChar>='A') and (AChar<='Z') then AChar := Char(Byte(AChar)+(Byte('a')-Byte('A'))); DownCase := AChar; End; {of DownCase} Function OpCode(var AZMem : Pointer; Address : Word; var AString : String) : Byte; Label ReadNextByte; Var AByte : Byte; Count : Integer; hlStr, hStr, lStr : String; i : Integer; Procedure Section(Num : Integer); Var i : Integer; FStr : String; Param : Longint; Sign : Char; Begin i := 1; If length(OpCodes[Num,AByte]) = 0 then AString := '? Unknown ?' else While i <= length(OpCodes[Num,AByte]) do Begin If (OpCodes[Num,AByte,i]>#0) and (OpCodes[Num,AByte,i]<#31) then AString := AString + Convert[ord(OpCodes[Num,AByte,i])] else Case OpCodes[Num,AByte,i] of #31 : AString := AString+hlStr; #128 : AString := AString+hStr; #129 : AString := AString+lStr; '%' : begin inc(i); Case OpCodes[Num,AByte,i] of 'b' : begin Param := Byte((Ptr(Seg(AZMem^),Ofs(AZmem^)+ Address))^); Inc(Address); Inc(Count); If Pref.Base = 0 then Begin FormatStr(FStr,'%02x',Param); AString := AString+'$'+FStr; End else Begin Str(Byte(Param),FStr); AString := AString+FStr; End; end; 'd' : if hlStr <> 'hl' then begin Param := Byte((Ptr(Seg(AZMem^),Ofs(AZmem^)+ Address))^); Inc(Address); Inc(Count); If Pref.Base = 0 then Begin FormatStr(FStr,'%02x',Param); AString := AString+'+$'+FStr; End else Begin Str(Byte(Param),FStr); AString := AString+'+'+FStr; End; end; 'w' : begin Param := LongInt(Byte((Ptr(Seg(AZMem^),Ofs(AZMem^)+ Address))^) + 256*Byte((Ptr(Seg(AZMem^),Ofs(AZMem^)+ Succ(Address)))^)); Inc(Address,2); Inc(Count,2); If Pref.Base = 0 then Begin FormatStr(FStr,'%04x',Param); AString := AString+'$'+FStr; End else Begin Str(Word(Param),FStr); AString := AString+FStr; End; end; 'e' : begin Param := Word(ShortInt((Ptr(Seg(AZMem^),Ofs(AZMem^)+ Address))^) + Succ(Address)); Inc(Address); Inc(Count); If Pref.Base = 0 then Begin FormatStr(FStr,'%04x',Param); AString := AString+'$'+FStr; End else Begin Str(Word(Param),FStr); AString := AString+FStr; End; end; end; end; else AString := AString+OpCodes[Num,AByte,i]; end; Inc(i); End; End; {of OpCode|Section} Var OrigAdd : Word; Unknown : Boolean; Begin OrigAdd := Address; Unknown := False; hlStr := 'hl'; hStr := 'h'; lStr := 'l'; AString := ''; Count := 0; ReadNextByte: {This is the only way to do this bit sensibly - using a goto} AByte := Byte((Ptr(Seg(AZMem^),Ofs(AZmem^)+Address))^); Inc(Address); Inc(Count); If AByte = $DD then begin hlStr := 'ix'; hStr := 'ixh'; lStr := 'ixl'; If Address<(OrigAdd+256) then goto ReadNextByte else Unknown := True; end; If AByte = $FD then begin hlStr := 'iy'; hStr := 'iyh'; lStr := 'iyl'; If Address<(OrigAdd+256) then goto ReadNextByte else Unknown := True; end; If AByte = $cb then Begin AByte := Byte((Ptr(Seg(AZMem^),Ofs(AZmem^)+Address))^); Inc(Address); Inc(Count); Section(2) End else If AByte = $ed then Begin AByte := Byte((Ptr(Seg(AZMem^),Ofs(AZmem^)+Address))^); Inc(Address); Inc(Count); Section(3) End else Section(1); If Unknown then Begin AString := '? Unknown ?'; Count := 1; End; AString := UpperCase(AString); OpCode := Count; End; {of OpCode} Function UnCode(var AZMem : Pointer; Address : Word; AString : String) : Byte; Var i : Integer; NumberStr : String; Number : Array[1..2] of Word; LastNum : Integer; NumberType : Array[1..2] of Char; LastNumType : Integer; Numbers : Set of '0'..'z'; XY : Char; Code : Integer; {Error code and opcode!} Table : Integer; Found : Boolean; WrongNum : Boolean; AStr : String; ANum : Word; ErrorCode : Integer; hStr,lStr,hlStr : String; Begin LastNum := 0; XY := ' '; i := 1; AString := AString+' '; {make sure it doesn't try looking at a non-existent character} While i <= Length(AString) do Begin If (AString[i] = #$27) {apostrophe} and {read character bytes} (length(AString) >= (i+2)) and (AString[i+2] = #$27) then Begin Inc(LastNum); Number[LastNum] := Word(Ord(AString[succ(i)])); AString := Copy(AString,1,Pred(i)) + '%%' + Copy(AString,i+3, length(AString)-i-2); Inc(i,3); End; If AString[i] = ' ' then {remove spaces} If i = 1 then Begin AString := Copy(AString,2,length(AString)-1); Dec(i); End else If i = length(AString) then AString := Copy(AString,1,Pred(i)) else If (AString[Succ(i)] = ',') or (AString[succ(i)] = ')') or (AString[succ(i)] = ' ') then Begin AString := Copy(AString,1,Pred(i)) + Copy(AString,succ(i), length(AString)-i); Dec(i); End else If (AString[Pred(i)] = ',') or (AString[Pred(i)] = '(') or (AString[Pred(i)] = ' ') then AString := Copy(AString,1,Pred(i)) + Copy(AString,succ(i), length(AString)-i); AString[i] := DownCase(AString[i]); {convert to lower case} If AString[i] in ['0'..'9','$'] then Begin {read numbers} AString[i] := UpCase(AString[i]); If AString[i]='$' then Numbers := ['0'..'9','A'..'F','a'..'f'] else Numbers := ['0'..'9']; NumberStr := AString[i]; AString[i] := '%'; Inc(i); AString[i] := UpCase(AString[i]); While AString[i] in Numbers do Begin NumberStr := NumberStr + AString[i]; Inc(i); End; AString := Copy(AString,1,i-length(NumberStr)) + '%' + Copy(AString,i,length(AString)-pred(i)); Inc(LastNum); Val(NumberStr,Number[LastNum],code); i := i - length(NumberStr) + 2; End; If (AString[i] = 'i') and ((AString[Succ(i)]='x') or (AString[Succ(i)]='y')) then {check indexes} Begin Inc(i); xy := AString[i]; If AString[Succ(i)]='+' then AString := Copy(AString,1,i)+ Copy(AString,i+2,length(AString)-succ(i)); End; Inc(i); End; If AString[length(AString)]=' ' then {remove the final space} Dec(AString[0]); Table := 1; Code := 0; Found := False; Repeat {search for OpCode} WrongNum := False; NumberStr := ''; If xy=' ' then Begin hStr := 'h'; lStr := 'l'; hlStr := 'hl'; End else If xy='x' then Begin hStr := 'ixh'; lStr := 'ixl'; hlStr := 'ix'; End else If xy='y' then Begin hStr := 'iyh'; lStr := 'iyl'; hlStr := 'iy'; End; LastNumType := 0; For i := 1 to length(OpCodes[table,code]) do Begin If (OpCodes[table,code,i] > #0) and (OpCodes[table,code,i] < #31) then NumberStr := NumberStr + Convert[Ord(OpCodes[table,code,i])] else Case OpCodes[table,code,i] of #31 : NumberStr := NumberStr+hlStr; #128 : NumberStr := NumberStr+hStr; #129 : NumberStr := NumberStr+lStr; '%' : begin inc(i); If not ((OpCodes[table,code,i] = 'd') and (xy=' ')) then Begin NumberStr := NumberStr+'%%'; Inc(LastNumType); NumberType[LastNumType] := OpCodes[table,code,i]; End; End; Else If OpCodes[table,code,i] in ['0'..'9'] then Begin AStr := OpCodes[table,code,i]; If OpCodes[table,code,succ(i)] in ['0'..'9'] then AStr := AString + OpCodes[table,code,succ(i)]; Val(AStr,ANum,ErrorCode); If ANum <> Number[1] then WrongNum := True; NumberStr := NumberStr + '%%'; Inc(LastNumType); NumberType[LastNumType] := 'n'; {a number!!} If OpCodes[table,code,succ(i)] in ['0'..'9'] then Inc(i); End else NumberStr := NumberStr + OpCodes[table,code,i]; End; End; If (NumberStr = AString) and (LastNumType=LastNum) and not(length(AString)=0) and not WrongNum then Found := True else Begin Inc(code); If Code > 255 then Begin Code := 0; Inc(Table); End; End; Until Found or (Table=4); If Found then Begin i := 1; {Encode into memory} If xy='x' then Begin Byte((Ptr(Seg(AZMem^),Ofs(AZmem^)+Address))^) := $DD; Inc(Address); Inc(i); End else If xy='y' then Begin Byte((Ptr(Seg(AZMem^),Ofs(AZmem^)+Address))^) := $FD; Inc(Address); Inc(i); End; If Table = 2 then Begin Byte((Ptr(Seg(AZMem^),Ofs(AZmem^)+Address))^) := $CB; Inc(Address); Inc(i); End else If Table = 3 then Begin Byte((Ptr(Seg(AZMem^),Ofs(AZmem^)+Address))^) := $ED; Inc(Address); Inc(i); End; Byte((Ptr(Seg(AZMem^),Ofs(AZmem^)+Address))^) := Code; Inc(Address); Inc(i); For Code := 1 to LastNum do Begin Case NumberType[Code] of 'e' : Begin ShortInt((Ptr(Seg(AZMem^),Ofs(AZMem^)+Address))^) := ShortInt(Word(Number[Code])-succ(Address)); Inc(Address); Inc(i); End; 'b' : Begin Byte((Ptr(Seg(AZMem^),Ofs(AZMem^)+Address))^) := Byte(Number[Code]); Inc(Address); Inc(i); End; 'w' : Begin Byte((Ptr(Seg(AZMem^),Ofs(AZMem^)+Address))^) := Lo(Number[Code]); Inc(Address); Byte((Ptr(Seg(AZMem^),Ofs(AZMem^)+Address))^) := Hi(Number[Code]); Inc(Address); Inc(i,2); End; 'd' : Begin ShortInt((Ptr(Seg(AZMem^),Ofs(AZMem^)+Address))^) := ShortInt(Number[Code]); Inc(Address); Inc(i,2); End; End End; UnCode := Pred(i); End else UnCode := 0; End; {of Uncode} {************************************************************************} {************************************************************************} Procedure TEnterCodeDialog.HandleEvent(var Event : TEvent); Var ANum : Longint; AString : String[18]; ALength : Byte; ACount : Word; Begin Inherited HandleEvent(Event); If (Event.What = evCommand) and (Event.Command = cmEnterCode) and AddressInputLine^.Valid(cmOk) then Begin AddressInputLine^.GetData(ANum); CodeInputLine^.GetData(AString); ALength := UnCode(TempMem,0,AString); If ALength = 0 then Begin MessageBox(#3'Error in mnemonic,'#13#13+ #3'try again.',nil,mfError or mfOkButton); CodeInputLine^.SelectAll(True); End else Begin Inc(ANum,UnCode(PZMem,Word(ANum),AString)); If ANum>$FFFF then ANum := 0; OpCode(PZMem,ANum,AString); CodeInputLine^.SetData(AString); End; AddressInputLine^.SetData(ANum); ClearEvent(Event); Message(Owner^.Owner,evCommand,cmRedrawCode,@Self); End; End; {of TEnterCodeDialog.HandleEvent} Destructor TEnterCodeDialog.Done; Begin Inherited Done; FreeMem(TempMem,10); End; Constructor TEnterCodeDialog.Init(APZMem : Pointer; AnAddress : Word); Var R : TRect; CodeButton : PButton; ANum : Longint; AString : String; Begin R.Assign(0,0,28,12); Inherited Init(R,'Enter Code'); Options := Options or ofCentered; PZMem := APZMem; GetMem(TempMem,10); R.Assign(3,3,23,4); CodeInputLine := New(PInputLine,Init(R,18)); Insert(CodeInputLine); CodeInputLine^.HelpCtx := hcCodeInputLine; OpCode(PZMem,AnAddress,AString); CodeInputLine^.SetData(AString); R.Assign(23,3,26,4); Insert(New(PHistory,Init(R,CodeInputLine,hsCodeInputLine))); R.Assign(2,2,11,3); Insert(New(PLabel,Init(R,'~Z~80 Code',CodeInputLine))); R.Assign(3,6,13,7); AddressInputLine := New(PAddressInputLine,Init(R,hcCodeAddress)); Insert(AddressInputLine); R.Assign(2,5,6,6); Insert(New(PLabel,Init(R,'~a~t',AddressInputLine))); ANum := Longint(AnAddress); AddressInputLine^.SetData(ANum); R.Assign(2,8,12,10); CodeButton := New(PButton,Init(R,'~E~nter',cmEnterCode,bfDefault)); CodeButton^.HelpCtx := hcEnterButton; Insert(CodeButton); R.Assign(14,8,24,10); CodeButton := New(PButton,Init(R,'~F~inish',cmCancel,bfNormal)); CodeButton^.HelpCtx := hcFinishButton; Insert(CodeButton); SelectNext(False); End; {of TEnterCodeDialog.Init} {************************************************************************} {************************************************************************} Procedure TCodeWindow.Close; Begin If Valid(cmClose) then Hide; End; Procedure TCodeWindow.HandleEvent(var Event : TEvent); Begin Inherited HandleEvent(Event); If Event.What = evCommand then case Event.Command of cmRedrawCode : Begin ReDraw; ClearEvent(Event); End; cmAssemble : Begin Owner^.ExecView(New(PEnterCodeDialog,Init(PZMem,Interior^. CursorAt))); Interior^.ReCalcCursor; ClearEvent(Event); End; End; End; {of TCodeWindow.HandleEvent} Constructor TCodeWindow.Init(var Bounds : TRect; CPZMem : Pointer; var AnEngine : PEngine); Var R : TRect; ScrollBar : PScrollBar; Begin Inherited Init(Bounds,'Z80 Code',3); HelpCtx := hcCodeWindow; PZMem := CPZMem; Engine := AnEngine; ScrollBar := StandardScrollBar(sbVertical); Insert(ScrollBar); GetExtent(R); R.Grow(-1,-1); Interior := New(PCodeViewer, Init(R,ScrollBar,PZMem,AnEngine)); Insert(Interior); End; {of TCodeWindow.Init} {************************************************************************} {************************************************************************} Procedure TCodeViewer.MoveToPC; Begin If (Pref.Prefs and 8) = 8 then Begin StartAt := Engine^.IRegs.PC; CursorAt := StartAt; Cursor.Y := 0; SetCursor(0,Cursor.Y); Delta.Y := Integer(StartAt div 2); VScrollBar^.SetValue(Integer(CursorAt div 2)); End; DrawView; End; {of TCodeViewer.MoveToPC} Procedure TCodeViewer.ReCalcCursor; Var i : Integer; AString : String; Begin CursorAt := StartAt; For i := 1 to Cursor.Y do CursorAt := CursorAt + OpCode(PZMem,CursorAt,AString); End; Constructor TCodeViewer.Init(var Bounds : TRect; AVScroller : PScrollBar; CPZMem : Pointer; var AnEngine : PEngine); Begin Inherited Init(Bounds,nil,AVScroller); Engine := AnEngine; GrowMode := gfGrowHiX + gfGrowHiY; Options := Options or ofTileable; PZMem := CPZMem; Cursor.X := 0; Cursor.Y := 0; StartAt := 0; CursorAt := 0; SetLimit(-$8000,$7FFF); VScrollBar^.SetRange($0,$7FFF); VScrollBar^.SetValue($0); Delta.Y := -$8000; ShowCursor; End; {of TCodeViewer.Init} Procedure TCodeViewer.Draw; Var DrawBuf : TDrawBuffer; Colour : Word; X,Y : Word; I : Word; S,T : String; Begin I := StartAt; For Y := 0 to Pred(Size.Y) do Begin Begin If I = Engine^.IRegs.PC then Colour := GetColor(2) else Colour := GetColor(1); FormatStr(S,'%04x',I); S := ' '+S+' '; I := I + OpCode(PZMem,I,T); S := S+T; While length(S)<Size.X do S := S+' '; End; MoveStr(DrawBuf,S,Colour); WriteLine(0,Y,Size.X,1,DrawBuf); End; End; {of TCodeViewer.Draw} Procedure TCodeViewer.MoveDown; Var AString : String; Begin Inc(Cursor.Y); CursorAt := CursorAt + OpCode(PZMem,CursorAt,AString); If Cursor.Y > Pred(Size.Y) then Begin Dec(Cursor.Y); StartAt := StartAt+OpCode(PZMem,StartAt,AString); DrawView; End; SetCursor(0,Cursor.Y); Delta.Y := Integer(StartAt div 2); VScrollBar^.SetValue(Integer(CursorAt div 2)); End; {of TCodeViewer.MoveDown} Procedure TCodeViewer.ScrollDraw; Begin If CursorAt div 2 <> VScrollBar^.Value then Begin CursorAt := VScrollBar^.Value * 2; StartAt := CursorAt; Cursor.Y := 0; Delta.Y := VScrollBar^.Value; DrawView; End; End; Procedure TCodeViewer.MoveUp; var AString : String; OldAdd : Word; i : Integer; Begin Dec(Cursor.Y); OldAdd := CursorAt; Dec(CursorAt,6); Repeat Inc(CursorAt); Until ((OpCode(PZMem,CursorAt,AString)+CursorAt)=OldAdd) or (CursorAt=Pred(OldAdd)); If Cursor.Y<0 then Begin Inc(Cursor.Y); StartAt := CursorAt; DrawView; End; SetCursor(0,Cursor.Y); VScrollBar^.SetValue(Integer(CursorAt div 2)); Delta.Y := Integer(StartAt div 2); End; {of TCodeViewer.MoveUp} Procedure TCodeViewer.HandleEvent(var Event : TEvent); Begin Inherited HandleEvent(Event); If Event.What = evKeyDown then Case Event.KeyCode of kbDown : Begin MoveDown; ClearEvent(Event); End; kbUp : Begin MoveUp; ClearEvent(Event); End; kbCtrlPgUp : Begin Cursor.Y := 0; StartAt := 0; CursorAt := 0; SetCursor(0,Cursor.Y); VScrollBar^.SetValue(0); DrawView; ClearEvent(Event); End; kbCtrlPgDn : Begin Cursor.Y := 0; StartAt := 0; CursorAt := 0; SetCursor(0,Cursor.Y); VScrollBar^.SetValue(0); DrawView; ClearEvent(Event); End; kbPgUp : Begin Cursor.Y := 0; StartAt := CursorAt-$20; CursorAt := StartAt; SetCursor(0,Cursor.Y); VScrollBar^.SetValue(Integer(StartAt div 2)); DrawView; ClearEvent(Event); End; kbPgDn : Begin Cursor.Y := 0; StartAt := CursorAt + $20; CursorAt := StartAt; SetCursor(0,Cursor.Y); VScrollBar^.SetValue(Integer(StartAt div 2)); DrawView; ClearEvent(Event); End; End; If Event.What = evCommand then Case Event.Command of cmChangedPC : Begin MoveToPC; ClearEvent(Event); End; End; If (Event.What = evMouseDown) and not (Event.Double) then If ChangedCursor(Event.Where) then ClearEvent(Event); If (Event.What = evMouseDown) and (Event.Double) then If ChangedPC(Event.Where) then ClearEvent(Event); End; {of TCodeViewer.HandleEvent} Function TCodeViewer.ChangedPC(GlobalPos : TPoint) : Boolean; Var Pos : TPoint; i : Integer; AString : String; Begin MakeLocal(GlobalPos,Pos); If MouseInView(GlobalPos) then Begin Cursor.Y := Pos.Y; CursorAt := StartAt; For i := 1 to Pos.Y do CursorAt := CursorAt + OpCode(PZMem,CursorAt,AString); SetCursor(0,Cursor.Y); VScrollBar^.SetValue(Integer(CursorAt div 2)); Delta.Y := Integer(StartAt div 2); Engine^.IRegs.PC := CursorAt; Message(Owner^.Owner^.Owner,evCommand,cmRedrawAll,@Self); End; End; {of TCodeViewer.MoveToPC} Procedure TCodeViewer.ChangePC; Begin Engine^.IRegs.PC := CursorAt; Message(Owner^.Owner^.Owner,evCommand,cmRedrawAll,@Self); End; {of TCodeViewer.MoveToPC} Function TCodeViewer.ChangedCursor(GlobalPos : TPoint) : Boolean; Var Pos : TPoint; AString : String; i : Integer; Begin MakeLocal(GlobalPos,Pos); If MouseInView(GlobalPos) then Begin Cursor.Y := Pos.Y; CursorAt := StartAt; For i := 1 to Pos.Y do CursorAt := CursorAt + OpCode(PZMem,CursorAt,AString); SetCursor(0,Cursor.Y); VScrollBar^.SetValue(Integer(CursorAt div 2)); Delta.Y := Integer(StartAt div 2); DrawView; End; End; {of TRegisterInput.ChangedCursor} {************************************************************************} {************************************************************************} Constructor TRegisterInput.Init(var Bounds : TRect; ARegister : PWord); Begin Inherited Init(Bounds); ShowCursor; Options := Options or ofFirstClick or ofSelectable; Register := ARegister; End; {of TRegisterInput.Init} Procedure TRegisterInput.Draw; Var AString : String; Begin FormatStr(AString,'%04x',Register^); WriteStr(0,0,AString,GetColor(19)); End; {of TRegisterInput.Draw} Procedure TRegisterInput.MoveLeft; Begin Dec(Cursor.X); If Cursor.X < 0 then Cursor.X := 0; SetCursor(Cursor.X,Cursor.Y); End; {of TRegisterInput.MoveLeft} Procedure TRegisterInput.MoveRight; Begin Inc(Cursor.X); If Cursor.X >3 then Cursor.X := 3; SetCursor(Cursor.X,Cursor.Y); End; {of TRegisterInput.MoveRight} Procedure TRegisterInput.Enter(const AChar : Char); Var Add, i : Word; Begin Add := 1; For i := 1 to (3-Cursor.X) do Add := Add*16; Register^ := (Register^ and not (Add * $F)) + (Pos(AChar,HexDigits) - 1) * Add; MoveRight; DrawView; Message(Owner^.Owner^.Owner,evCommand,cmRedrawMemory,nil); End; {of TRegisterInput.Enter} Function TRegisterInput.ChangedCursor(GlobalPos : TPoint) : Boolean; Var Pos : TPoint; Begin MakeLocal(GlobalPos,Pos); If (Pos.X >=0 ) and (Pos.X < 4) and (Pos.Y=0) then Begin Cursor.X := Pos.X; DrawView; End; End; {of TRegisterInput.ChangedCursor} Procedure TRegisterInput.HandleEvent(var Event : TEvent); Begin Inherited HandleEvent(Event); If Event.What = evKeyDown then Case Event.KeyCode of kbLeft,kbDel : Begin MoveLeft; ClearEvent(Event); End; kbRight : Begin MoveRight; ClearEvent(Event); End; End; If Event.What = evMouseDown then If ChangedCursor(Event.Where) then ClearEvent(Event); If (Event.What = evKeyDown) and (Upcase(Event.CharCode) in ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']) then Begin Enter(Upcase(Event.CharCode)); Message(Owner^.Owner^.Owner, evCommand, cmRedrawAll, nil); ClearEvent(Event); End; End; {of TRegisterInput.HandleEvent} Constructor TFlagInput.Init(var Bounds : TRect; ARegister : PByte; AFlagMask : Byte); Begin Inherited Init(Bounds); ShowCursor; Options := Options or ofFirstClick or ofSelectable; Register := ARegister; FlagMask := AFlagMask; End; {of TFlagInput.Init} Procedure TFlagInput.Draw; Begin If (Register^ and FlagMask) = 0 then WriteStr(0,0,'0',GetColor(19)) else WriteStr(0,0,'1',GetColor(19)); End; {of TFlagInput.Draw} Procedure TFlagInput.Enter(const AChar : Char); Begin If AChar = '0' then Register^ := (Register^ and not FlagMask) else Register^ := (Register^ and not FlagMask) + FlagMask; DrawView; End; {of TFlagInput.Enter} Procedure TFlagInput.HandleEvent(var Event : TEvent); Begin Inherited HandleEvent(Event); If Event.What = evKeyDown then Case Event.CharCode of '0','1' : Begin Enter(Event.CharCode); Message(Owner, evCommand, cmRedrawCode, nil); ClearEvent(Event); End; End; If (Event.What = evMouseDown) and (Event.Double) then Begin If (Register^ and FlagMask) = 0 then Enter('1') else Enter('0'); Message(Owner, evCommand, cmRedrawCode, nil); ClearEvent(Event); End; End;{of TFlagInput.HandleEvent} Constructor TShowCode.Init(var Bounds : TRect; APC : PWord; AZMem : Pointer); Begin Inherited Init(Bounds); PC := APC; PZMem := AZMem; End; {of TShowCode.Init} Procedure TShowCode.Draw; Var Buf : TDrawBuffer; AString : String; Begin AString := ''; OpCode(PZMem,PC^,AString); AString := ' '+AString; While Length(AString)<17 do AString := AString+' '; MoveStr(Buf,AString,GetColor(19)); WriteBuf(0,0,17,1,Buf); End; {of TShowCode.Draw} Procedure TRegistersDialog.Close; Begin If Valid(cmClose) then Hide; End; Constructor TRegistersDialog.Init(AZMem : Pointer; Engine : PEngine); Var PRegInput : PRegisterInput; PFlag : PFlagInput; R : TRect; Begin R.Assign(0,0,19,12); Inherited Init(R,'Z80 CPU'); Number := 2; R.Assign(5,1,9,2); PRegInput := New(PRegisterInput,Init(R,@Engine^.ZRegs.AF)); Insert(PRegInput); R.Assign(1,1,5,2); Insert(New(PLabel,Init(R,'af ',PRegInput))); R.Assign(13,1,17,2); PRegInput := New(PRegisterInput,Init(R,@Engine^.ARegs.AF)); Insert(PRegInput); R.Assign(9,1,13,2); Insert(New(PLabel,Init(R,'af''',PRegInput))); R.Assign(5,2,9,3); PRegInput := New(PRegisterInput,Init(R,@Engine^.ZRegs.BC)); Insert(PRegInput); R.Assign(1,2,5,3); Insert(New(PLabel,Init(R,'bc ',PRegInput))); R.Assign(13,2,17,3); PRegInput := New(PRegisterInput,Init(R,@Engine^.ARegs.BC)); Insert(PRegInput); R.Assign(9,2,13,3); Insert(New(PLabel,Init(R,'bc''',PRegInput))); R.Assign(5,3,9,4); PRegInput := New(PRegisterInput,Init(R,@Engine^.ZRegs.DE)); Insert(PRegInput); R.Assign(1,3,5,4); Insert(New(PLabel,Init(R,'de ',PRegInput))); R.Assign(13,3,17,4); PRegInput := New(PRegisterInput,Init(R,@Engine^.ARegs.DE)); Insert(PRegInput); R.Assign(9,3,13,4); Insert(New(PLabel,Init(R,'de''',PRegInput))); R.Assign(5,4,9,5); PRegInput := New(PRegisterInput,Init(R,@Engine^.ZRegs.HL)); Insert(PRegInput); R.Assign(1,4,5,5); Insert(New(PLabel,Init(R,'hl ',PRegInput))); R.Assign(13,4,17,5); PRegInput := New(PRegisterInput,Init(R,@Engine^.ARegs.HL)); Insert(PRegInput); R.Assign(9,4,13,5); Insert(New(PLabel,Init(R,'hl''',PRegInput))); R.Assign(5,5,9,6); PRegInput := New(PRegisterInput,Init(R,@Engine^.IRegs.IX)); Insert(PRegInput); R.Assign(1,5,5,6); Insert(New(PLabel,Init(R,'ix ',PRegInput))); R.Assign(13,5,17,6); PRegInput := New(PRegisterInput,Init(R,@Engine^.IRegs.IY)); Insert(PRegInput); R.Assign(9,5,13,6); Insert(New(PLabel,Init(R,'iy ',PRegInput))); R.Assign(5,6,9,7); PRegInput := New(PRegisterInput,Init(R,@Engine^.IRegs.PC)); Insert(PRegInput); R.Assign(1,6,5,7); Insert(New(PLabel,Init(R,'pc ',PRegInput))); R.Assign(13,6,17,7); PRegInput := New(PRegisterInput,Init(R,@Engine^.IRegs.SP)); Insert(PRegInput); R.Assign(9,6,13,7); Insert(New(PLabel,Init(R,'sp ',PRegInput))); R.Assign(4,7,5,8); PFlag := New(PFlagInput,Init(R,@Engine^.ZRegs.Flags,fSign)); Insert(PFlag); R.Assign(1,7,4,8); Insert(New(PLabel,Init(R,'s ',PFlag))); R.Assign(8,7,9,8); PFlag := New(PFlagInput,Init(R,@Engine^.ZRegs.Flags,fZero)); Insert(PFlag); R.Assign(5,7,8,8); Insert(New(PLabel,Init(R,'z ',PFlag))); R.Assign(12,7,13,8); PFlag := New(PFlagInput,Init(R,@Engine^.ZRegs.Flags,fHalf)); Insert(PFlag); R.Assign(9,7,12,8); Insert(New(PLabel,Init(R,'h ',PFlag))); R.Assign(16,7,17,8); PFlag := New(PFlagInput,Init(R,@Engine^.ZRegs.Flags,fParity)); Insert(PFlag); R.Assign(13,7,16,8); Insert(New(PLabel,Init(R,'v ',PFlag))); R.Assign(4,8,5,9); PFlag := New(PFlagInput,Init(R,@Engine^.ZRegs.Flags,fSub)); Insert(PFlag); R.Assign(1,8,4,9); Insert(New(PLabel,Init(R,'n ',PFlag))); R.Assign(8,8,9,9); PFlag := New(PFlagInput,Init(R,@Engine^.ZRegs.Flags,fCarry)); Insert(PFlag); R.Assign(5,8,8,9); Insert(New(PLabel,Init(R,'c ',PFlag))); R.Assign(13,8,17,9); PRegInput := New(PRegisterInput,Init(R,@Engine^.ORegs.R)); Insert(PRegInput); R.Assign(9,8,13,9); Insert(New(PLabel,Init(R,'ir ',PRegInput))); R.Assign(7,9,8,10); PFlag := New(PFlagInput,Init(R,@Engine^.ORegs.IFF1,255)); Insert(PFlag); R.Assign(1,9,7,10); Insert(New(PLabel,Init(R,'iff1 ',PFlag))); R.Assign(16,9,17,10); PFlag := New(PFlagInput,Init(R,@Engine^.ORegs.IFF2,255)); Insert(PFlag); R.Assign(10,9,16,10); Insert(New(PLabel,Init(R,'iff2 ',PFlag))); R.Assign(1,10,18,11); Insert(New(PShowCode,Init(R,@Engine^.IRegs.PC,Engine^.PZMem))); SelectNext(False); End; {of TRegistersDialog.Init} Procedure TRegistersDialog.HandleEvent(var Event : TEvent); Begin Inherited HandleEvent(Event); If (Event.What = evCommand) and (Event.Command = cmRedrawCode) then Begin ReDraw; ClearEvent(Event); End; End; {of TRegistersDialog.HandleEvent} End. {of Unit ZRegDlg}
unit TNT_File; // Gestion des fichiers // -------------------- // TFile: fichier // Read, ReadByte, ReadInt, ReadChar, ReadFloat, ReadStr interface type TFile = class private Data: File; public constructor Open(FileName: String); overload; procedure Read(var Buf; Size: Integer); function ReadByte: Byte; function ReadInt: Integer; function ReadChar: Char; function ReadFloat: Single; function ReadStr: String; function Eof: Boolean; destructor Close; end; implementation uses TNT_3D, SysUtils; constructor TFile.Open(FileName: String); begin inherited Create; FileName := LowerCase(FileName); AssignFile(Data, 'data/data.pak'); Reset(Data, 1); if ReadStr <> 'TNT-PAK' then Console.Log('ERROR reading ' + FileName + ': invalid TNT-PAK!'); while ReadStr <> FileName do Seek(Data, ReadInt+FilePos(Data)); ReadInt; end; procedure TFile.Read(var Buf; Size: Integer); begin BlockRead(Data, Buf, Size); end; function TFile.ReadByte: Byte; begin BlockRead(Data, Result, SizeOf(Byte)); end; function TFile.ReadInt: Integer; begin BlockRead(Data, Result, SizeOf(Integer)); end; function TFile.ReadChar: Char; begin BlockRead(Data, Result, SizeOf(Char)); end; function TFile.ReadFloat: Single; begin BlockRead(Data, Result, SizeOf(Single)); end; function TFile.ReadStr: String; var C: Char; begin Result := ''; repeat C := ReadChar; if C <> #0 then Result := Result + C; until C = #0; end; function TFile.Eof: Boolean; begin Result := System.Eof(Data); end; destructor TFile.Close; begin CloseFile(Data); inherited Destroy; end; end.
unit keyesdemomain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.StdCtrls, UsbRelay; type TfrmMain = class(TForm) btnFindDevices: TButton; btnOpenDevice: TButton; btnCloseDevice: TButton; cbRelay1: TCheckBox; cbRelay2: TCheckBox; cbRelay3: TCheckBox; cbRelay4: TCheckBox; cbRelay5: TCheckBox; cbRelay6: TCheckBox; cbRelay7: TCheckBox; cbRelay8: TCheckBox; pnlDeviceOpen: TPanel; tcUsbRelayDevices: TTabControl; procedure btnFindDevicesClick(Sender: TObject); procedure btnOpenDeviceClick(Sender: TObject); procedure btnCloseDeviceClick(Sender: TObject); procedure cbRelayClick(Sender: TObject); procedure tcUsbRelayDevicesChange(Sender: TObject); private FDeviceState: boolean; CurrentRelay : TUsbRelay; procedure SetDeviceState(const Value: boolean); procedure ShowRelays; procedure SetCheckbox(cb:TCheckBox); property DeviceState:boolean read FDeviceState write SetDeviceState; public { Public declarations } end; var frmMain: TfrmMain; implementation {$R *.dfm} procedure TfrmMain.btnCloseDeviceClick(Sender: TObject); begin CurrentRelay.open:=False; DeviceState:=CurrentRelay.open; end; procedure TfrmMain.btnFindDevicesClick(Sender: TObject); begin CurrentRelay:=nil; tcUsbRelayDevices.Tabs.Clear; FindUsbRelays; if UsbRelays.Count>0 then begin tcUsbRelayDevices.Visible:=true; tcUsbRelayDevices.Tabs.Addstrings(UsbRelays); tcUsbRelayDevicesChange(self); end else begin tcUsbRelayDevices.Visible:=false; end; end; procedure TfrmMain.btnOpenDeviceClick(Sender: TObject); begin CurrentRelay.open:=True; DeviceState:=CurrentRelay.open; end; procedure TfrmMain.cbRelayClick(Sender: TObject); begin CurrentRelay.state[TCheckbox(Sender).Tag]:=TCheckbox(Sender).Checked; end; procedure TfrmMain.SetCheckbox(cb: TCheckBox); begin if (cb.Tag>CurrentRelay.devicetype) or (not CurrentRelay.open) then begin cb.Checked:=false; cb.Enabled:=false; end else begin cb.Checked:=CurrentRelay.state[cb.Tag]; cb.Enabled:=True; end; end; procedure TfrmMain.SetDeviceState(const Value: boolean); begin if Value then pnlDeviceOpen.Color:=clGreen else pnlDeviceOpen.Color:=clRed; FDeviceState := Value; ShowRelays; end; procedure TfrmMain.ShowRelays; begin SetCheckBox(cbRelay1); SetCheckBox(cbRelay2); SetCheckBox(cbRelay3); SetCheckBox(cbRelay4); SetCheckBox(cbRelay5); SetCheckBox(cbRelay6); SetCheckBox(cbRelay7); SetCheckBox(cbRelay8); end; procedure TfrmMain.tcUsbRelayDevicesChange(Sender: TObject); begin CurrentRelay:=TUsbRelay(UsbRelays.Objects[tcUsbRelayDevices.TabIndex]); DeviceState:=CurrentRelay.open; 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. * * Contributor(s): * Jody Dawkins <jdawkins@delphixtreme.com> *) unit FailureMessages; interface const SpecNotApplicable = 'Not applicable to this specification'; SpecIntegerShouldEqual = '<%d> should equal <%d> but didn''t'; SpecIntegerShouldNotEqual = '<%d> should not equal <%d> but did'; SpecIntegerShouldBeGreaterThan = '<%d> should be greater than <%d> but wasn''t'; SpecIntegerShouldBeLessThan = '<%d> should be less than <%d> but wasn''t'; SpecIntegerShouldBeAtLeast = '<%d> should be at least <%d> but wasn''t'; SpecIntegerShouldBeAtMost = '<%d> should be at most <%d> but wasn''t'; SpecIntegerShouldBeOdd = '<%d> should be odd but wasn''t'; SpecIntegerShouldBeEven = '<%d> should be even but wasn''t'; SpecIntegerShouldBePositive = '<%d> should be positive but wasn''t'; SpecIntegerShouldBeNegative = '<%d> should be negative but wasn''t'; SpecIntegerShouldBePrime = '<%d> should be prime but wasn''t'; SpecIntegerShouldBeComposite = '<%d> should be composite but wasn''t'; SpecIntegerShouldBeZero = '<%d> should be zero but wasn''t'; SpecIntegerShouldBeNonZero = '<%d> should be non-zero but wasn''t'; SpecStringShouldEqual = '<%s> should equal <%s> but didn''t'; SpecStringShouldNotEqual = '<%s> should not equal <%s> but did'; SpecStringShouldMatch = '<%s> should match <%s> but didn''t'; SpecStringShouldBeNumeric = '<%s> should be numeric but wasn''t'; SpecStringShouldBeAlpha = '<%s> should be alpha but wasn''t'; SpecStringShouldBeAlphaNumeric = '<%s> should be alpha-numeric but wasn''t'; SpecStringShouldStartWith = '<%s> should start with <%s> but didn''t'; SpecStringShouldContain = '<%s> should contain <%s> but didn''t'; SpecStringShouldEndWith = '<%s> should end with <%s> but didn''t'; SpecStringShouldBeEmpty = '<%s> should be empty but wasn''t'; SpecFloatShouldEqual = '<%g> should equal <%g> but didn''t'; SpecFloatShouldNotEqual = '<%g> should not equal <%g> but did'; SpecFloatShouldBeGreaterThan = '<%g> should be greater than <%g> but wasn''t'; SpecFloatShouldBeLessThan = '<%g> should be less than <%g> but wasn''t'; SpecFloatShouldBeAtLeast = '<%g> should be at least <%g> but wasn''t'; SpecFloatShouldBeAtMost = '<%g> should be at most <%g> but wasn''t'; SpecFloatShouldBePositive = '<%g> should be positive but wasn''t'; SpecFloatShouldBeNegative = '<%g> should be negative but wasn''t'; SpecFloatShouldBeZero = '<%g> should be zero but wasn''t'; SpecDateTimeShouldBeGreaterThan = '<%s> should be greater than <%s> but wasn''t'; SpecDateTimeShouldBeLessThan = '<%s> should be less than <%s> but wasn''t'; SpecDateTimeShouldBeAtLeast = '<%s> should be at least <%s> but wasn''t'; SpecDateTimeShouldBeAtMost = '<%s> should be at most <%s> but wasn''t'; SpecPointerShouldBeNil = 'Pointer should be <nil> but wasn''t'; SpecPointerShouldNotBeNil = 'Pointer should be <assigned> but wasn''t'; SpecPointerShouldBeAssigned = 'Pointer should be <assigned> but wasn''t'; SpecObjectShouldBeOfType = '<%s> should be of type <%s> but wasn''t'; SpecObjectShouldNotBeOfType = '<%s> should not be of type <%s> but was'; SpecObjectShouldDescendFrom = '<%s> should descend from <%s> but didn''t'; SpecObjectShouldNotDescendFrom = '<%s> should not descend from <%s> but did'; SpecObjectShouldBeAssigned = 'Object should be <assigned> but wasn''t'; SpecObjectShouldImplement = '<%s> should implement interface <%s> but didn''t'; SpecObjectShouldSupport = '<%s> should support interface <%s> but didn''t'; SpecInterfaceShouldSupport = 'Interface should support <%s> but didn''t'; SpecInterfaceShouldBeAssigned = 'Interface should be <assigned> but wasn''t'; SpecInterfaceShouldBeNil = 'Interface should be nil but wasn''t'; SpecInterfaceImplementingObjectNotFound = 'No implementing object could be found'; SpecInterfaceShouldBeImplementedBy = 'Interface should be implemented by <%s> but wasn''t'; ModNotApplicable = 'Not applicable to this modification'; ModToleranceExceeded = '%s - exceeded tolerance of %g'; ModCaseInsenstiveMatch = '%s - even ignoring case'; ModPercentFailure = '%s - while evaluating percentage'; implementation end.
unit uUserMgr; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uBaseForm, AuthoritySvrIntf, Grids, DBGrids, ComCtrls, ToolWin, ImgList, DB, DBClient, DBIntf, SysSvc, _Sys; type TfrmUserMgr = class(TBaseForm) imgList: TImageList; ToolBar1: TToolBar; btn_New: TToolButton; Btn_Edit: TToolButton; btn_Delete: TToolButton; ToolButton7: TToolButton; btn_Save: TToolButton; Grid_User: TDBGrid; cds: TClientDataSet; ds: TDataSource; btn_Refresh: TToolButton; ToolButton2: TToolButton; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btn_NewClick(Sender: TObject); procedure Btn_EditClick(Sender: TObject); procedure btn_RefreshClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btn_SaveClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure Grid_UserDblClick(Sender: TObject); procedure btn_DeleteClick(Sender: TObject); private DBAC: IDBAccess; procedure LoadData; procedure SaveData; protected class procedure RegAuthority(aIntf: IAuthorityRegistrar); override; procedure HandleAuthority(const Key: String; aEnable: Boolean); override; public { Public declarations } end; var frmUserMgr: TfrmUserMgr; implementation uses uEdtUser; {$R *.dfm} const Key1 = '{0DA9CD26-BAC5-4417-B989-8D39581289B8}'; procedure TfrmUserMgr.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; if cds.ChangeCount > 0 then begin if sys.Dialogs.Ask('用户管理', '数据已改变,是否保存?') then self.SaveData; end; Action := caFree; end; class procedure TfrmUserMgr.RegAuthority(aIntf: IAuthorityRegistrar); begin aIntf.RegAuthorityItem(Key1, '系统管理\权限', '用户管理', True); end; procedure TfrmUserMgr.HandleAuthority(const Key: String; aEnable: Boolean); begin if Key = Key1 then begin if not aEnable then raise Exception.Create('对不起,你没有权限!'); end; end; procedure TfrmUserMgr.btn_NewClick(Sender: TObject); begin inherited; frmEdtUser := TfrmEdtUser.Create(nil); try frmEdtUser.Caption := '新增用户'; if frmEdtUser.ShowModal = mrOK then begin cds.Append; cds.FieldByName('UserName').AsString := frmEdtUser.UserName; cds.FieldByName('Psw').AsString := frmEdtUser.Psw; cds.FieldByName('RoleID').AsInteger := frmEdtUser.RoleID; cds.FieldByName('RoleName').AsString := frmEdtUser.RoleName; cds.Post; end; finally frmEdtUser.Free; end; end; procedure TfrmUserMgr.Btn_EditClick(Sender: TObject); begin inherited; if cds.IsEmpty then exit; frmEdtUser := TfrmEdtUser.Create(nil); try frmEdtUser.Caption := '编辑用户'; frmEdtUser.UserName := cds.FieldByName('UserName').AsString; frmEdtUser.Psw := cds.FieldByName('Psw').AsString; frmEdtUser.RoleID := cds.FieldByName('RoleID').AsInteger; if frmEdtUser.ShowModal = mrOK then begin cds.Edit; cds.FieldByName('UserName').AsString := frmEdtUser.UserName; cds.FieldByName('Psw').AsString := frmEdtUser.Psw; cds.FieldByName('RoleID').AsInteger := frmEdtUser.RoleID; cds.FieldByName('RoleName').AsString := frmEdtUser.RoleName; cds.Post; end; finally frmEdtUser.Free; end; end; procedure TfrmUserMgr.LoadData; const sql = 'select * from [User]'; begin DBAC.QuerySQL(cds, sql); end; procedure TfrmUserMgr.btn_RefreshClick(Sender: TObject); begin inherited; self.LoadData; end; procedure TfrmUserMgr.FormCreate(Sender: TObject); begin inherited; DBAC := SysService as IDBAccess; end; procedure TfrmUserMgr.SaveData; begin if cds.ChangeCount = 0 then exit; DBAC.BeginTrans; try DBAC.ApplyUpdate('[User]', cds); DBAC.CommitTrans; except on E: Exception do begin DBAC.RollbackTrans; sys.Dialogs.ShowError(E); end; end; end; procedure TfrmUserMgr.btn_SaveClick(Sender: TObject); begin inherited; self.SaveData; end; procedure TfrmUserMgr.FormShow(Sender: TObject); begin inherited; self.LoadData; end; procedure TfrmUserMgr.Grid_UserDblClick(Sender: TObject); begin inherited; Btn_Edit.Click; end; procedure TfrmUserMgr.btn_DeleteClick(Sender: TObject); begin inherited; if cds.IsEmpty then exit; if sys.Dialogs.Confirm('用户管理', '是否要删除当前用户?') then cds.Delete; end; end.
unit UDbfIndex; interface uses sysutils,classes, db, UDbfPagedFile,UDbfCursor,UDbfIndexFile,UDbfCommon; type //==================================================================== //=== Index support //==================================================================== TIndexCursor = class(TVirtualCursor) public constructor Create(dbfIndexFile:TIndexFile); function Next:boolean; override; function Prev:boolean; override; procedure First; override; procedure Last; override; function GetPhysicalRecno:integer; override; procedure SetPhysicalRecno(Recno:integer); override; function GetSequentialRecordCount:integer; override; function GetSequentialRecno:integer; override; procedure SetSequentialRecno(Recno:integer); override; procedure GotoBookmark(Bookmark:rBookmarkData); override; function GetBookMark:rBookmarkData; override; procedure Insert(Recno:integer; Buffer:PChar); override; procedure Update(Recno: integer; PrevBuffer,NewBuffer: PChar); override; public IndexBookmark:rBookmarkData; destructor Destroy; override; end; //==================================================================== // TIndexCursor = class; //==================================================================== PIndexPosInfo = ^TIndexPage; //==================================================================== implementation //========================================================== //============ TIndexCursor //========================================================== constructor TIndexCursor.Create(dbfIndexFile:TIndexFile); begin inherited Create(dbfIndexFile); //IndexBookmark.BookmarkFlag:=TBookmarkFlag(-1); IndexBookmark.IndexBookmark:=-1; IndexBookmark.RecNo:=-1; end; destructor TIndexCursor.Destroy; {override;} begin inherited Destroy; end; procedure TIndexCursor.Insert(Recno:integer; Buffer:PChar); begin // Insert doesn't need checkpos. TIndexFile(PagedFile).Insert(Recno,Buffer); // TODO SET RecNo and Key end; procedure TIndexCursor.Update(Recno: integer; PrevBuffer,NewBuffer: PChar); begin with TIndexFile(PagedFile) do begin CheckPos(IndexBookmark); Update(Recno,PrevBuffer,NewBuffer); end; end; procedure TIndexCursor.First; begin with TIndexFile(PagedFile) do begin // CheckPos(IndexBookmark); not needed First; IndexBookmark:=GetBookmark; end; end; procedure TIndexCursor.Last; begin with TIndexFile(PagedFile) do begin // CheckPos(IndexBookmark); not needed Last; IndexBookmark:=GetBookmark; end; end; function TIndexCursor.Prev:boolean; begin with TIndexFile(PagedFile) do begin CheckPos(IndexBookmark); if Prev then begin Result:=true; IndexBookmark:=GetBookmark; end else begin Result:=false; //IndexBookmark.BookmarkFlag:=TBookmarkFlag(-1); IndexBookmark.IndexBookmark:=-1; IndexBookmark.RecNo:=-1; end; end; end; function TIndexCursor.Next:boolean; begin with TIndexFile(PagedFile) do begin CheckPos(IndexBookmark); if Next then begin Result:=true; IndexBookmark:=GetBookmark; end else begin Result:=false; //IndexBookmark.BookmarkFlag:=TBookmarkFlag(-1); IndexBookmark.IndexBookmark:=-1; IndexBookmark.RecNo:=-1; end; end; end; function TIndexCursor.GetPhysicalRecno:integer; begin TIndexFile(PagedFile).CheckPos(IndexBookmark); Result:=TIndexFile(PagedFile).PhysicalRecno; end; procedure TIndexCursor.SetPhysicalRecno(Recno:integer); begin with TIndexFile(PagedFile) do begin GotoRecno(Recno); IndexBookmark:=GetBookMark; end; end; function TIndexCursor.GetSequentialRecordCount:integer; begin with TIndexFile(PagedFile) do begin result:=GetSequentialRecordCount; end; end; function TIndexCursor.GetSequentialRecno:integer; begin with TIndexFile(PagedFile) do begin CheckPos(IndexBookmark); result:=GetSequentialRecno; end; end; procedure TIndexCursor.SetSequentialRecNo(Recno:integer); begin TIndexFile(PagedFile).SetSequentialRecno(Recno); end; procedure TIndexCursor.GotoBookmark(Bookmark:rBookmarkData); begin with TIndexFile(PagedFile) do begin GotoBookMark(Bookmark); IndexBookmark:=GetBookmark; end; if (IndexBookmark.RecNo<>Bookmark.RecNo) then begin Bookmark.RecNo:=IndexBookmark.RecNo; end; end; function TIndexCursor.GetBookMark:rBookmarkData; begin Result:=IndexBookmark; end; end.
unit ChannelTests; interface uses Windows, SysUtils, Classes, eiTypes, eiConstants, eiExceptions, eiProtocol, eiHelpers, eiChannel, TestFramework, TestExtensions, WinSock; type TChannelTest = class(TTestCase) private FBufferChannel: IUdpChannel; FPacketChannel: IEasyIpChannel; FSendPacket: EasyIpPacket; FSendBuffer: DynamicByteArray; protected procedure SetUp; override; procedure TearDown; override; public published procedure TestChangeHost; procedure TestExecuteBuffer; procedure TestExecuteRecord; end; implementation uses TestConstants; { TChannelTest } procedure TChannelTest.SetUp; begin inherited; // FChannel := TMockChannel.Create('127.0.0.1', EASYIP_PORT); FBufferChannel := TEasyIpChannel.Create(TEST_PLC_HOST); FPacketChannel := TEasyIpChannel.Create(TEST_PLC_HOST); FSendPacket := TPacketFactory.GetReadPacket(TEST_OFFSET, dtFlag, 20); FSendBuffer := TPacketAdapter.ToByteArray(FSendPacket); end; procedure TChannelTest.TearDown; begin inherited; end; procedure TChannelTest.TestChangeHost; begin FBufferChannel.Host := TEST_SECOND_HOST; FPacketChannel.Host := TEST_SECOND_HOST; TestExecuteBuffer; TestExecuteRecord; end; procedure TChannelTest.TestExecuteBuffer; var receiveBuffer: DynamicByteArray; receivePacket: EasyIpPacket; begin receiveBuffer := FBufferChannel.Execute(FSendBuffer); Check(receiveBuffer <> nil); Check(Length(FSendBuffer) = Length(receiveBuffer)); receivePacket := TPacketAdapter.ToEasyIpPacket(receiveBuffer); Check(receivePacket.Error = 0); Check(receivePacket.Flags and EASYIP_FLAG_RESPONSE <> 0); end; procedure TChannelTest.TestExecuteRecord; var receivePacket: EasyIpPacket; begin receivePacket := FPacketChannel.Execute(FSendPacket); Check(SizeOf(receivePacket) = SizeOf(FSendPacket)); Check(receivePacket.Error = 0); Check(receivePacket.Flags and EASYIP_FLAG_RESPONSE <> 0); FSendPacket := TPacketFactory.GetWritePacket(TEST_OFFSET, dtFlag, 2); FSendPacket.Data[1] := 1; FSendPacket.Data[2] := 2; receivePacket := FPacketChannel.Execute(FSendPacket); Check(SizeOf(receivePacket) = SizeOf(FSendPacket)); Check(receivePacket.Error = 0); Check(receivePacket.Flags and EASYIP_FLAG_RESPONSE <> 0); end; initialization //TestFramework.RegisterTest(TChannelTest.Suite); TestFramework.RegisterTest(TRepeatedTest.Create(TChannelTest.Suite, 1)); end.
unit Lib.Classes; interface uses System.SysUtils, System.Types, System.UITypes, System.UIConsts, System.Classes, System.IOUtils, System.Generics.Collections, System.Permissions, FMX.Types, FMX.Ani, FMX.Graphics, FMX.Objects; type TPicture = class(TRectangle) private State: (StateEmpty,StateLoading,StateLoaded); protected FOnRead: TNotifyEvent; procedure AfterPaint; override; public BitmapSize: TPointF; PageBounds: TRectF; PictureFileName: string; PictureIndex: Integer; constructor Create(AOwner: TComponent); override; procedure SetBitmap(B: TBitmap); procedure ReleaseBitmap; function Empty: Boolean; function Loaded: Boolean; procedure Loading; function ToString: string; override; property OnRead: TNotifyEvent read FOnRead write FOnRead; end; TPictureQueue = TThreadedQueue<TPicture>; TPictureList = TList<TPicture>; TPictureReader = class(TThread) private Queue: TPictureQueue; protected procedure Execute; override; public constructor Create; destructor Destroy; override; procedure DoShutDown; procedure Push(Picture: TPicture); end; procedure RequestPermissionsExternalStorage(Proc: TProc<Boolean>); implementation {$IFDEF ANDROID} uses Androidapi.Helpers, Androidapi.JNI.Os; {$ENDIF} { TPicture } constructor TPicture.Create(AOwner: TComponent); begin inherited; Fill.Bitmap.WrapMode:=TWrapMode.TileStretch; Fill.Kind:=TBrushKind.None; Fill.Color:=claSilver; Stroke.Kind:=TBrushKind.None; Stroke.Thickness:=0; HitTest:=False; Opacity:=0.8; end; procedure TPicture.AfterPaint; begin inherited; if Empty and Assigned(FOnRead) then FOnRead(Self); end; function TPicture.ToString: string; begin Result:=PictureFilename+' ('+ Fill.Bitmap.Bitmap.Width.ToString+' x '+ Fill.Bitmap.Bitmap.Height.ToString+')'; end; function TPicture.Empty: Boolean; begin Result:=State=StateEmpty; end; function TPicture.Loaded: Boolean; begin Result:=State=StateLoaded; end; procedure TPicture.Loading; begin State:=StateLoading; end; procedure TPicture.SetBitmap(B: TBitmap); begin BeginUpdate; Opacity:=0; Fill.Bitmap.Bitmap:=B; Fill.Kind:=TBrushKind.Bitmap; State:=StateLoaded; EndUpdate; TAnimator.AnimateFloat(Self,'Opacity',0.8); end; procedure TPicture.ReleaseBitmap; begin BeginUpdate; Fill.Kind:=TBrushKind.None; Fill.Bitmap.Bitmap:=nil; State:=StateEmpty; EndUpdate; end; { TPictureReader } constructor TPictureReader.Create; begin Queue:=TPictureQueue.Create; inherited Create(True); FreeOnTerminate:=True; end; destructor TPictureReader.Destroy; begin Queue.Free; end; procedure TPictureReader.DoShutDown; begin Queue.DoShutDown; end; procedure TPictureReader.Push(Picture: TPicture); begin if Assigned(Picture) and Picture.Empty then begin Picture.Loading; Queue.PushItem(Picture); end; end; procedure TPictureReader.Execute; begin while not Terminated do begin var Picture:=Queue.PopItem; if Queue.ShutDown then Break; var B:=TBitmap.CreateFromFile(Picture.PictureFileName); Synchronize(procedure begin Picture.SetBitmap(B); end); B.Free; end; end; procedure RequestPermissionsExternalStorage(Proc: TProc<Boolean>); begin {$IFDEF ANDROID} var WRITE_EXTERNAL_STORAGE:=JStringToString(TJManifest_permission.JavaClass.WRITE_EXTERNAL_STORAGE); {$ELSE} var WRITE_EXTERNAL_STORAGE:=''; {$ENDIF} PermissionsService.DefaultService.RequestPermissions([WRITE_EXTERNAL_STORAGE], procedure(const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>) begin Proc((Length(AGrantResults)=1) and (AGrantResults[0]=TPermissionStatus.Granted)); end); end; end.
unit CalculatorUnitTests; interface uses System.SysUtils, DUnitX.TestFramework, Calculator.Core.SimpleCalc; type [TestFixture] TCalculatorUnitTests = class private FCalc: TSimpleCalc; public [Setup] procedure Setup; [TearDown] procedure TearDown; [Test] procedure Execute_NoOperations_DefaultsToZero; [Test] procedure Execute_AddOne_ReturnOne; [Test] procedure Execute_AddSome_ReturnCorrectSum; [Test] procedure Execute_AddSome_ReturnCorrectSumAndReset; [Test] procedure Execute_AddSome_ReturnValue; [Test] procedure Execute_AddRandomValues_ReturnSum; [Test] procedure Execute_DivideByZero_RaiseException; [Test] [Category('A test apart')] [Ignore('This test must be implemented')] procedure Execute_ToDo; [TestCase('A', '1')] [TestCase('A', '2')] [TestCase('A', '3')] procedure Execute_AddParam_ReturnCorrectSum(AValue: Integer); end; implementation procedure TCalculatorUnitTests.Execute_AddOne_ReturnOne; // GOOD begin FCalc.Add(1); Assert.AreEqual(1, FCalc.Execute); end; procedure TCalculatorUnitTests.Execute_AddParam_ReturnCorrectSum( AValue: Integer); begin FCalc.Add(AValue); Assert.AreEqual(AValue, FCalc.Execute); end; procedure TCalculatorUnitTests.Execute_AddRandomValues_ReturnSum; // BAD! var LValue: Integer; LSum: Integer; LIndex: Integer; begin Randomize; LSum := 0; for LIndex := 1 to 10 do begin LValue := Random(100); Inc(LSum, LValue); FCalc.Add(LValue); end; Assert.AreEqual(LSum, FCalc.Execute); end; procedure TCalculatorUnitTests.Execute_AddSome_ReturnCorrectSum; // GOOD begin FCalc.Add(1); FCalc.Add(2); FCalc.Add(3); Assert.AreEqual(6, FCalc.Execute); end; procedure TCalculatorUnitTests.Execute_AddSome_ReturnCorrectSumAndReset; // BAD begin FCalc.Add(1); Assert.AreEqual(1, FCalc.Execute); Assert.AreEqual(0, FCalc.Execute); end; procedure TCalculatorUnitTests.Execute_AddSome_ReturnValue; // GOOD (almost) begin FCalc.Add(2876); Assert.AreEqual(2876, FCalc.Execute); end; procedure TCalculatorUnitTests.Execute_DivideByZero_RaiseException; // GOOD begin Assert.WillRaise( procedure begin FCalc.Add(1); FCalc.Divide(0); end, EDivByZero); end; procedure TCalculatorUnitTests.Execute_NoOperations_DefaultsToZero; // GOOD begin Assert.AreEqual(0, FCalc.Execute); end; procedure TCalculatorUnitTests.Execute_ToDo; begin end; procedure TCalculatorUnitTests.Setup; begin FCalc := TSimpleCalc.Create; end; procedure TCalculatorUnitTests.TearDown; begin FreeAndNil(FCalc); end; initialization TDUnitX.RegisterTestFixture(TCalculatorUnitTests); end.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.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.Image.QOI; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} interface uses SysUtils, Classes, Math, PasVulkan.Types, PasVulkan.Compression.Deflate; type EpvLoadOOIImage=class(Exception); TpvQOIMagic=array[0..3] of AnsiChar; PpvQOIMagic=^TpvQOIMagic; const pvQOIMagic:TpvQOIMagic=('q','o','i','f'); function LoadQOIImage(aDataPointer:TpvPointer;aDataSize:TpvUInt32;var aImageData:TpvPointer;var aImageWidth,aImageHeight:TpvInt32;const aHeaderOnly:boolean;out aSRGB:boolean):boolean; function SaveQOIImage(const aImageData:TpvPointer;const aImageWidth,aImageHeight:TpvUInt32;out aDestData:TpvPointer;out aDestDataSize:TpvUInt32;const aSRGB:boolean=true):boolean; function SaveQOIImageAsStream(const aImageData:TpvPointer;const aImageWidth,aImageHeight:TpvUInt32;const aStream:TStream;const aSRGB:boolean=true):boolean; function SaveQOIImageAsFile(const aImageData:TpvPointer;const aImageWidth,aImageHeight:TpvUInt32;const aFileName:string;const aSRGB:boolean=true):boolean; implementation const QOI_MAGIC=TpvUInt32((TpvUInt32(TpvUInt8(AnsiChar('q'))) shl 24) or (TpvUInt32(TpvUInt8(AnsiChar('o'))) shl 16) or (TpvUInt32(TpvUInt8(AnsiChar('i'))) shl 8) or (TpvUInt32(TpvUInt8(AnsiChar('f'))) shl 0)); QOI_OP_INDEX=$00; // 00xxxxxx QOI_OP_DIFF=$40; // 01xxxxxx QOI_OP_LUMA=$80; // 10xxxxxx QOI_OP_RUN=$c0; // 11xxxxxx QOI_OP_RGB=$fe; // 11111110 QOI_OP_RGBA=$ff; // 11111111 QOI_MASK_2=$c0; // 11000000 QOI_SRGB=0; QOI_LINEAR=1; QOI_HEADER_SIZE=14; QOI_PIXELS_MAX=TpvUInt32(400000000); type TQOIDesc=record Width:TpvUInt32; Height:TpvUInt32; Channels:TpvUInt8; ColorSpace:TpvUInt8; end; PQOIDesc=^TQOIDesc; TQOIRGBA=packed record case boolean of false:( r:TpvUInt8; g:TpvUInt8; b:TpvUInt8; a:TpvUInt8; ); true:( v:TpvUInt32; ); end; PQOIRGBA=^TQOIRGBA; const QOIPadding:array[0..7] of TpvUInt8=(0,0,0,0,0,0,0,1); function QOIColorHash(const aColor:TQOIRGBA):TpvUInt32; inline; begin result:=(aColor.r*3)+(aColor.g*5)+(aColor.b*7)++(aColor.a*11); end; function QOIRead8(const aBytes:PpvUInt8Array;var aPosition:TpvUInt32):TpvUInt32; inline; begin result:=TpvUInt32(aBytes^[aPosition]); inc(aPosition); end; function QOIRead32(const aBytes:PpvUInt8Array;var aPosition:TpvUInt32):TpvUInt32; inline; begin result:=(TpvUInt32(aBytes^[aPosition]) shl 24) or (TpvUInt32(aBytes^[aPosition+1]) shl 16) or (TpvUInt32(aBytes^[aPosition+2]) shl 8) or (TpvUInt32(aBytes^[aPosition+3]) shl 0); inc(aPosition,4); end; procedure QOIWrite8(const aBytes:PpvUInt8Array;var aPosition:TpvUInt32;const aValue:TpvUInt32); inline; begin aBytes^[aPosition]:=aValue and $ff; inc(aPosition); end; procedure QOIWrite32(const aBytes:PpvUInt8Array;var aPosition:TpvUInt32;const aValue:TpvUInt32); inline; begin aBytes^[aPosition+0]:=(aValue shr 24) and $ff; aBytes^[aPosition+1]:=(aValue shr 16) and $ff; aBytes^[aPosition+2]:=(aValue shr 8) and $ff; aBytes^[aPosition+3]:=(aValue shr 0) and $ff; inc(aPosition,4); end; function LoadQOIImage(aDataPointer:TpvPointer;aDataSize:TpvUInt32;var aImageData:TpvPointer;var aImageWidth,aImageHeight:TpvInt32;const aHeaderOnly:boolean;out aSRGB:boolean):boolean; var DataPosition,HeaderMagic,PixelSize,PixelPosition,Run,ChunksLen, b1,b2:TpvUInt32; vg:TpvInt32; DataPointer:PpvUInt8Array; Desc:TQOIDesc; Pixel:TQOIRGBA; IndexPixels:array[0..63] of TQOIRGBA; begin if aDataSize>=(QOI_HEADER_SIZE+SizeOf(QOIPadding)) then begin DataPointer:=aDataPointer; DataPosition:=0; HeaderMagic:=QOIRead32(DataPointer,DataPosition); Desc.Width:=QOIRead32(DataPointer,DataPosition); Desc.Height:=QOIRead32(DataPointer,DataPosition); Desc.Channels:=QOIRead8(DataPointer,DataPosition); Desc.ColorSpace:=QOIRead8(DataPointer,DataPosition); if (HeaderMagic=QOI_MAGIC) and (Desc.Width>0) and (Desc.Height>0) and (Desc.Channels in [3,4]) and (Desc.ColorSpace in [0,1]) and ((TpvUInt64(Desc.Width)*Desc.Height)<=QOI_PIXELS_MAX) then begin aImageWidth:=Desc.Width; aImageHeight:=Desc.Height; aSRGB:=Desc.ColorSpace=QOI_SRGB; if aHeaderOnly then begin result:=true; exit; end; PixelSize:=aImageWidth*aImageHeight*4; GetMem(aImageData,PixelSize); FillChar(aImageData^,PixelSize,#0); FillChar(IndexPixels,SizeOf(IndexPixels),#0); Pixel.r:=0; Pixel.g:=0; Pixel.b:=0; Pixel.a:=255; ChunksLen:=aDataSize-SizeOf(QOIPadding); Run:=0; PixelPosition:=0; while PixelPosition<PixelSize do begin if Run>0 then begin dec(Run); end else if DataPosition<ChunksLen then begin b1:=QOIRead8(DataPointer,DataPosition); case b1 of QOI_OP_RGB:begin Pixel.r:=QOIRead8(DataPointer,DataPosition); Pixel.g:=QOIRead8(DataPointer,DataPosition); Pixel.b:=QOIRead8(DataPointer,DataPosition); end; QOI_OP_RGBA:begin Pixel.r:=QOIRead8(DataPointer,DataPosition); Pixel.g:=QOIRead8(DataPointer,DataPosition); Pixel.b:=QOIRead8(DataPointer,DataPosition); Pixel.a:=QOIRead8(DataPointer,DataPosition); end; else begin case b1 and QOI_MASK_2 of QOI_OP_INDEX:begin Pixel:=IndexPixels[b1 and 63]; end; QOI_OP_DIFF:begin Pixel.r:=Pixel.r+(((b1 shr 4) and 3)-2); Pixel.g:=Pixel.g+(((b1 shr 2) and 3)-2); Pixel.b:=Pixel.b+(((b1 shr 0) and 3)-2); end; QOI_OP_LUMA:begin b2:=QOIRead8(DataPointer,DataPosition); vg:=(b1 and 63)-32; Pixel.r:=Pixel.r+((vg-8)+((b2 shr 4) and 15)); Pixel.g:=Pixel.g+vg; Pixel.b:=Pixel.b+((vg-8)+((b2 shr 0) and 15)); end; else {QOI_OP_RUN:}begin Run:=b1 and 63; end; end; end; end; IndexPixels[QOIColorHash(Pixel) and 63]:=Pixel; end; PQOIRGBA(Pointer(@PpvUInt8Array(aImageData)^[PixelPosition]))^:=Pixel; inc(PixelPosition,4); end; result:=true; exit; end; result:=false; end; end; function SaveQOIImage(const aImageData:TpvPointer;const aImageWidth,aImageHeight:TpvUInt32;out aDestData:TpvPointer;out aDestDataSize:TpvUInt32;const aSRGB:boolean=true):boolean; var DataPosition,HeaderMagic,PixelSize,PixelPosition,LastPixelPosition, IndexPosition,Run,ChunksLen,Size,b1,b2:TpvUInt32; vr,vg,vb,vgr,vgb:TpvInt32; DataPointer:PpvUInt8Array; Desc:TQOIDesc; PreviousPixel,Pixel:TQOIRGBA; IndexPixels:array[0..63] of TQOIRGBA; begin Desc.Width:=aImageWidth; Desc.Height:=aImageHeight; Desc.Channels:=4; Desc.ColorSpace:=IfThen(aSRGB,QOI_SRGB,QOI_LINEAR); if (Desc.Width>0) and (Desc.Height>0) and (Desc.Channels in [3,4]) and (Desc.ColorSpace in [0,1]) and ((TpvUInt64(Desc.Width)*Desc.Height)<=QOI_PIXELS_MAX) then begin Size:=(QOI_HEADER_SIZE+SizeOf(QOIPadding))+(aImageWidth*aImageHeight*6); GetMem(aDestData,Size); try DataPointer:=aDestData; DataPosition:=0; QOIWrite32(DataPointer,DataPosition,QOI_MAGIC); QOIWrite32(DataPointer,DataPosition,Desc.Width); QOIWrite32(DataPointer,DataPosition,Desc.Height); QOIWrite8(DataPointer,DataPosition,Desc.Channels); QOIWrite8(DataPointer,DataPosition,Desc.ColorSpace); FillChar(IndexPixels,SizeOf(IndexPixels),#0); Pixel.r:=0; Pixel.g:=0; Pixel.b:=0; Pixel.a:=255; PreviousPixel:=Pixel; Run:=0; PixelSize:=aImageWidth*aImageHeight*4; PixelPosition:=0; LastPixelPosition:=PixelSize-4; while PixelPosition<PixelSize do begin Pixel:=PQOIRGBA(Pointer(@PpvUInt8Array(aImageData)^[PixelPosition]))^; inc(PixelPosition,4); if Pixel.v=PreviousPixel.v then begin inc(Run); if (Run=62) or (PixelPosition=LastPixelPosition) then begin QOIWrite8(DataPointer,DataPosition,QOI_OP_RUN or (Run-1)); Run:=0; end; end else begin if Run>0 then begin QOIWrite8(DataPointer,DataPosition,QOI_OP_RUN or (Run-1)); Run:=0; end; IndexPosition:=QOIColorHash(Pixel) and 63; if IndexPixels[IndexPosition].v=Pixel.v then begin QOIWrite8(DataPointer,DataPosition,QOI_OP_INDEX or IndexPosition); end else begin IndexPixels[IndexPosition]:=Pixel; if Pixel.a=PreviousPixel.a then begin vr:=TpvInt32(Pixel.r)-TpvInt32(PreviousPixel.r); vg:=TpvInt32(Pixel.g)-TpvInt32(PreviousPixel.g); vb:=TpvInt32(Pixel.b)-TpvInt32(PreviousPixel.b); if ((vr>-3) and (vr<2)) and ((vg>-3) and (vg<2)) and ((vb>-3) and (vb<2)) then begin QOIWrite8(DataPointer,DataPosition,QOI_OP_DIFF or (((vr+2) shl 4) or ((vg+2) shl 2) or ((vb+2) shl 0))); end else begin vgr:=vr-vg; vgb:=vb-vg; if ((vgr>-9) and (vgr<8)) and ((vg>-33) and (vg<2)) and ((vgb>-9) and (vgb<8)) then begin QOIWrite8(DataPointer,DataPosition,QOI_OP_LUMA or (vg+32)); QOIWrite8(DataPointer,DataPosition,(((vgr+8) and $f) shl 4) or ((vgb+8) and $f)); end else begin QOIWrite8(DataPointer,DataPosition,QOI_OP_RGB); QOIWrite8(DataPointer,DataPosition,Pixel.r); QOIWrite8(DataPointer,DataPosition,Pixel.g); QOIWrite8(DataPointer,DataPosition,Pixel.b); end; end; end else begin QOIWrite8(DataPointer,DataPosition,QOI_OP_RGBA); QOIWrite8(DataPointer,DataPosition,Pixel.r); QOIWrite8(DataPointer,DataPosition,Pixel.g); QOIWrite8(DataPointer,DataPosition,Pixel.b); QOIWrite8(DataPointer,DataPosition,Pixel.a); end; end; end; PreviousPixel:=Pixel; end; for vr:=0 to length(QOIPadding)-1 do begin QOIWrite8(DataPointer,DataPosition,QOIPadding[vr]); end; finally ReallocMem(aDestData,DataPosition); end; aDestDataSize:=DataPosition; result:=true; exit; end; result:=false; end; function SaveQOIImageAsStream(const aImageData:TpvPointer;const aImageWidth,aImageHeight:TpvUInt32;const aStream:TStream;const aSRGB:boolean=true):boolean; var Data:TpvPointer; DataSize:TpvUInt32; begin result:=SaveQOIImage(aImageData,aImageWidth,aImageHeight,Data,DataSize,aSRGB); if assigned(Data) then begin try aStream.Write(Data^,DataSize); finally FreeMem(Data); end; end; end; function SaveQOIImageAsFile(const aImageData:TpvPointer;const aImageWidth,aImageHeight:TpvUInt32;const aFileName:string;const aSRGB:boolean=true):boolean; var FileStream:TFileStream; begin FileStream:=TFileStream.Create(aFileName,fmCreate); try result:=SaveQOIImageAsStream(aImageData,aImageWidth,aImageHeight,FileStream,aSRGB); finally FileStream.Free; end; end; end.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.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.Scene3D.Renderer.MipmappedArray2DImage; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} {$m+} interface uses SysUtils, Classes, Math, Vulkan, PasVulkan.Types, PasVulkan.Math, PasVulkan.Framework, PasVulkan.Application; type { TpvScene3DRendererMipmappedArray2DImage } TpvScene3DRendererMipmappedArray2DImage=class private fVulkanImage:TpvVulkanImage; fVulkanSampler:TpvVulkanSampler; fVulkanMipMapSampler:TpvVulkanSampler; fVulkanImageView:TpvVulkanImageView; fVulkanArrayImageView:TpvVulkanImageView; fMemoryBlock:TpvVulkanDeviceMemoryBlock; fDescriptorImageInfo:TVkDescriptorImageInfo; fArrayDescriptorImageInfo:TVkDescriptorImageInfo; fWidth:TpvInt32; fHeight:TpvInt32; fMipMapLevels:TpvInt32; public VulkanImageViews:array of TpvVulkanImageView; DescriptorImageInfos:array of TVkDescriptorImageInfo; constructor Create(const aWidth,aHeight,aLayers:TpvInt32;const aFormat:TVkFormat;const aBilinear:boolean;const aSampleBits:TVkSampleCountFlagBits=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT);const aImageLayout:TVkImageLayout=TVkImageLayout(VK_IMAGE_LAYOUT_GENERAL)); destructor Destroy; override; published property VulkanImage:TpvVulkanImage read fVulkanImage; property VulkanSampler:TpvVulkanSampler read fVulkanSampler; property VulkanMipMapSampler:TpvVulkanSampler read fVulkanMipMapSampler; property VulkanArrayImageView:TpvVulkanImageView read fVulkanArrayImageView; property VulkanImageView:TpvVulkanImageView read fVulkanImageView; public property DescriptorImageInfo:TVkDescriptorImageInfo read fDescriptorImageInfo; property ArrayDescriptorImageInfo:TVkDescriptorImageInfo read fArrayDescriptorImageInfo; property Width:TpvInt32 read fWidth; property Height:TpvInt32 read fHeight; property MipMapLevels:TpvInt32 read fMipMapLevels; end; implementation { TpvScene3DRendererMipmappedArray2DImage } constructor TpvScene3DRendererMipmappedArray2DImage.Create(const aWidth,aHeight,aLayers:TpvInt32;const aFormat:TVkFormat;const aBilinear:boolean;const aSampleBits:TVkSampleCountFlagBits;const aImageLayout:TVkImageLayout); var MipMapLevelIndex:TpvInt32; MemoryRequirements:TVkMemoryRequirements; RequiresDedicatedAllocation, PrefersDedicatedAllocation, StorageBit:boolean; MemoryBlockFlags:TpvVulkanDeviceMemoryBlockFlags; ImageSubresourceRange:TVkImageSubresourceRange; Queue:TpvVulkanQueue; CommandPool:TpvVulkanCommandPool; CommandBuffer:TpvVulkanCommandBuffer; Fence:TpvVulkanFence; ImageViewType:TVkImageViewType; begin inherited Create; VulkanImageViews:=nil; DescriptorImageInfos:=nil; fWidth:=aWidth; fHeight:=aHeight; fMipMapLevels:=Max(1,IntLog2(Max(aWidth,aHeight)+1)); if aLayers>1 then begin ImageViewType:=TVkImageViewType(VK_IMAGE_VIEW_TYPE_2D_ARRAY); end else begin ImageViewType:=TVkImageViewType(VK_IMAGE_VIEW_TYPE_2D); end; StorageBit:=(aFormat<>VK_FORMAT_R8G8B8A8_SRGB) and (aFormat<>VK_FORMAT_R8G8B8_SRGB) and (aFormat<>VK_FORMAT_R8G8_SRGB) and (aFormat<>VK_FORMAT_R8_SRGB) and (aFormat<>VK_FORMAT_B8G8R8A8_SRGB); fVulkanImage:=TpvVulkanImage.Create(pvApplication.VulkanDevice, 0, //TVkImageCreateFlags(VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT), VK_IMAGE_TYPE_2D, aFormat, aWidth, aHeight, 1, MipMapLevels, aLayers, aSampleBits, VK_IMAGE_TILING_OPTIMAL, TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT) or //TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or IfThen(StorageBit,TVkImageUsageFlags(VK_IMAGE_USAGE_STORAGE_BIT),0) or TVkImageUsageFlags(VK_IMAGE_USAGE_TRANSFER_SRC_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_TRANSFER_DST_BIT), VK_SHARING_MODE_EXCLUSIVE, 0, nil, VK_IMAGE_LAYOUT_UNDEFINED ); MemoryRequirements:=pvApplication.VulkanDevice.MemoryManager.GetImageMemoryRequirements(fVulkanImage.Handle, RequiresDedicatedAllocation, PrefersDedicatedAllocation); MemoryBlockFlags:=[]; if RequiresDedicatedAllocation or PrefersDedicatedAllocation then begin Include(MemoryBlockFlags,TpvVulkanDeviceMemoryBlockFlag.DedicatedAllocation); end; fMemoryBlock:=pvApplication.VulkanDevice.MemoryManager.AllocateMemoryBlock(MemoryBlockFlags, MemoryRequirements.size, MemoryRequirements.alignment, MemoryRequirements.memoryTypeBits, TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT), 0, 0, 0, 0, 0, 0, 0, TpvVulkanDeviceMemoryAllocationType.ImageOptimal, @fVulkanImage.Handle); if not assigned(fMemoryBlock) then begin raise EpvVulkanMemoryAllocationException.Create('Memory for texture couldn''t be allocated!'); end; fMemoryBlock.AssociatedObject:=self; VulkanCheckResult(pvApplication.VulkanDevice.Commands.BindImageMemory(pvApplication.VulkanDevice.Handle, fVulkanImage.Handle, fMemoryBlock.MemoryChunk.Handle, fMemoryBlock.Offset)); Queue:=pvApplication.VulkanDevice.GraphicsQueue; CommandPool:=TpvVulkanCommandPool.Create(pvApplication.VulkanDevice, pvApplication.VulkanDevice.GraphicsQueueFamilyIndex, TVkCommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT)); try CommandBuffer:=TpvVulkanCommandBuffer.Create(CommandPool,VK_COMMAND_BUFFER_LEVEL_PRIMARY); try Fence:=TpvVulkanFence.Create(pvApplication.VulkanDevice); try FillChar(ImageSubresourceRange,SizeOf(TVkImageSubresourceRange),#0); ImageSubresourceRange.aspectMask:=TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT); ImageSubresourceRange.baseMipLevel:=0; ImageSubresourceRange.levelCount:=fMipMapLevels; ImageSubresourceRange.baseArrayLayer:=0; ImageSubresourceRange.layerCount:=aLayers; fVulkanImage.SetLayout(TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT), TVkImageLayout(VK_IMAGE_LAYOUT_UNDEFINED), aImageLayout, @ImageSubresourceRange, CommandBuffer, Queue, Fence, true); fVulkanSampler:=TpvVulkanSampler.Create(pvApplication.VulkanDevice, TVkFilter(VK_FILTER_LINEAR), TVkFilter(VK_FILTER_LINEAR), TVkSamplerMipmapMode(VK_SAMPLER_MIPMAP_MODE_LINEAR), TVkSamplerAddressMode(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE), TVkSamplerAddressMode(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE), TVkSamplerAddressMode(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE), 0.0, false, 1.0, false, TVkCompareOp(VK_COMPARE_OP_NEVER), 0.0, fMipMapLevels, TVkBorderColor(VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK), false); if aBilinear then begin fVulkanMipMapSampler:=TpvVulkanSampler.Create(pvApplication.VulkanDevice, TVkFilter(VK_FILTER_LINEAR), TVkFilter(VK_FILTER_LINEAR), TVkSamplerMipmapMode(VK_SAMPLER_MIPMAP_MODE_NEAREST), TVkSamplerAddressMode(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE), TVkSamplerAddressMode(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE), TVkSamplerAddressMode(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE), 0.0, false, 1.0, false, TVkCompareOp(VK_COMPARE_OP_NEVER), 0.0, 1, TVkBorderColor(VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK), false); end else begin fVulkanMipMapSampler:=TpvVulkanSampler.Create(pvApplication.VulkanDevice, TVkFilter(VK_FILTER_NEAREST), TVkFilter(VK_FILTER_NEAREST), TVkSamplerMipmapMode(VK_SAMPLER_MIPMAP_MODE_NEAREST), TVkSamplerAddressMode(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE), TVkSamplerAddressMode(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE), TVkSamplerAddressMode(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE), 0.0, false, 1.0, false, TVkCompareOp(VK_COMPARE_OP_NEVER), 0.0, 1, TVkBorderColor(VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK), false); end; fVulkanImageView:=TpvVulkanImageView.Create(pvApplication.VulkanDevice, fVulkanImage, ImageViewType, aFormat, TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT), 0, fMipMapLevels, 0, aLayers); fVulkanArrayImageView:=TpvVulkanImageView.Create(pvApplication.VulkanDevice, fVulkanImage, TVkImageViewType(VK_IMAGE_VIEW_TYPE_2D_ARRAY), aFormat, TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT), 0, fMipMapLevels, 0, aLayers); fDescriptorImageInfo:=TVkDescriptorImageInfo.Create(fVulkanSampler.Handle, fVulkanImageView.Handle, aImageLayout); fArrayDescriptorImageInfo:=TVkDescriptorImageInfo.Create(fVulkanSampler.Handle, fVulkanArrayImageView.Handle, aImageLayout); SetLength(VulkanImageViews,fMipMapLevels); SetLength(DescriptorImageInfos,fMipMapLevels); for MipMapLevelIndex:=0 to fMipMapLevels-1 do begin VulkanImageViews[MipMapLevelIndex]:=TpvVulkanImageView.Create(pvApplication.VulkanDevice, fVulkanImage, ImageViewType, aFormat, TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT), MipMapLevelIndex, 1, 0, aLayers); DescriptorImageInfos[MipMapLevelIndex]:=TVkDescriptorImageInfo.Create(fVulkanMipMapSampler.Handle, VulkanImageViews[MipMapLevelIndex].Handle, aImageLayout); end; finally FreeAndNil(Fence); end; finally FreeAndNil(CommandBuffer); end; finally FreeAndNil(CommandPool); end; end; destructor TpvScene3DRendererMipmappedArray2DImage.Destroy; var MipMapLevelIndex:TpvInt32; begin FreeAndNil(fMemoryBlock); for MipMapLevelIndex:=0 to fMipMapLevels-1 do begin FreeAndNil(VulkanImageViews[MipMapLevelIndex]); end; VulkanImageViews:=nil; DescriptorImageInfos:=nil; FreeAndNil(fVulkanArrayImageView); FreeAndNil(fVulkanImageView); FreeAndNil(fVulkanSampler); FreeAndNil(fVulkanMipMapSampler); FreeAndNil(fVulkanImage); inherited Destroy; end; end.
unit Row; interface uses LinkedList, LinkedListItem, Inf; type TRow = class private _cells: TLinkedList; _isSorted: boolean; private function ReadFirstCellRow(): TLinkedListItem; function ReadLastCellRow(): TLinkedListItem; procedure SortCells(isSorted: boolean); public constructor Create(); destructor Destroy(); override; public function ReadCell(rowIndex, colIndex: integer): integer; procedure WriteCell(value: integer; rowIndex, colIndex: integer); function SearchCell(rowIndex, colIndex: integer): TLinkedListItem; function ToString(): string; public property Head: TLinkedListItem read ReadFirstCellRow; property Tail: TLinkedListItem read ReadLastCellRow; property IsSorted: boolean read _isSorted write SortCells; end; implementation constructor TRow.Create(); begin inherited Create; _cells := TLinkedList.Create(); _isSorted := True; end; destructor TRow.Destroy(); begin _cells.Destroy(); inherited; end; function TRow.ReadFirstCellRow(): TlinkedListItem; begin Result := _cells.Head; end; function TRow.ReadLastCellRow(): TLinkedListItem; begin Result := _cells.Tail; end; procedure TRow.SortCells(sort: boolean); begin if sort then begin if (not _isSorted) then begin _cells.SortBubble(SortDown); _isSorted := True; end; end; end; function TRow.ReadCell(rowIndex, colIndex: integer): integer; var item: TLinkedListItem; begin item := _cells.SearchItem(rowIndex, colIndex); if (item = nil) then Result := 0 else Result := item.Inf.Value; end; procedure TRow.WriteCell(value: integer; rowIndex, colIndex: integer); var item: TLinkedListItem; inf: TInf; begin item := _cells.SearchItem(rowIndex, colIndex); if (value <> 0) then begin if (item = nil) then begin inf := TInf.Create(value, rowIndex, colIndex); _cells.AddFirstItem(inf); _isSorted := False; end else item.Inf.Value := Value; end else _cells.DeleteItem(item); end; function TRow.SearchCell(rowIndex, colIndex: integer): TLinkedListItem; begin Result := _cells.SearchItem(rowIndex, colIndex); end; function TRow.Tostring(): string; begin Result := _cells.ToString(); end; end.
program AutoMapperObjects; uses SysUtils, Quick.Commons, Quick.Console, Quick.JSONRecord, Quick.AutoMapper; type TJob = class private fName : string; fDateFrom : TDateTime; fDateTo : TDateTime; published property Name : string read fName write fName; property DateFrom : TDateTime read fDateFrom write fDateFrom; property DateTo : TDateTime read fDateTo write fDateTo; end; TCarType = (ctOil, ctDiesel); TCar = class private fModel : string; fCarType : TCarType; published property Model : string read fModel write fModel; property CarType : TCarType read fCarType write fCarType; end; TArrayOfInteger = array of Integer; TUserBase = class(TJsonRecord) private fName : string; fAge : Integer; fCreationDate : TDateTime; fNumbers : TArrayOfInteger; published property Name : string read fName write fName; property Age : Integer read fAge write fAge; property CreationDate : TDateTime read fCreationDate write fCreationDate; property Numbers : TArrayOfInteger read fNumbers write fNumbers; end; TUser = class(TUserBase) private fId : Int64; fCash : Integer; fJob : TJob; fCar : TCar; public constructor Create; destructor Destroy; override; published property Id : Int64 read fId write fId; property Cash : Integer read fCash write fCash; property Job : TJob read fJob write fJob; property Car : TCar read fCar write fCar; end; TUser2 = class(TUserBase) private fIdUser : Int64; fJob : TJob; fMoney : Integer; fCar : TCar; public constructor Create; destructor Destroy; override; published property IdUser : Int64 read fIdUser write fIdUser; property Money : Integer read fMoney write fMoney; property Job : TJob read fJob write fJob; property Car : TCar read fCar write fCar; end; var User : TUser; User2 : TUser2; AutoMapper : specialize TAutoMapper<TUser,TUser2>; { TUser } constructor TUser.Create; begin fCar := TCar.Create; fJob := TJob.Create; end; destructor TUser.Destroy; begin fCar.Free; fJob.Free; inherited; end; { TUser2 } constructor TUser2.Create; begin fCar := TCar.Create; fJob := TJob.Create; end; destructor TUser2.Destroy; begin fCar.Free; fJob.Free; inherited; end; begin try User := TUser.Create; User.Id := 17; User.CreationDate := Now(); User.Name := 'John Miller'; User.Age := 30; User.Numbers := [1,2,3,4,5]; User.Cash := 3500; User.Job.Name := 'Designer'; User.Job.DateFrom := IncMonth(Now(),-12); User.Job.DateTo := Now(); User.Car.Model := 'Ferrari'; User.Car.CarType := ctOil; //User2 := TMapper<TUser2>.Map(User); AutoMapper := specialize TAutoMapper<TUser,TUser2>.Create; try AutoMapper.CustomMapping.AddMap('Cash','Money'); AutoMapper.CustomMapping.AddMap('Id','IdUser'); User2 := AutoMapper.Map(User); //User2 := TUser2.Create; //User.MapTo(User2); //User2.MapFrom(User); //User2 := User.Map<TUser2>; //User2 := TUser2(User.Clone); //User2 := TMapper<TUserBase>.Clone(User) as TUser2; cout('COMPARE USER VS USER2',etTrace); cout('User.Id = %d / User2.IdUser = %d',[User.Id,User2.IdUser],etInfo); cout('User.CreationDate = %s / User2.CreationDate = %s',[DateTimeToStr(User.CreationDate),DateTimetoStr(User2.CreationDate)],etInfo); cout('User.Name = %s / User2.Name = %s',[User.Name,User2.Name],etInfo); cout('User.Age = %d / User2.Age = %d',[User.Age,User2.Age],etInfo); //cout('User.Numbers = %d / User2.Numbers = %d',[User.Numbers[1],User2.Numbers[1]],etInfo); cout('User.Cash = %d / User2.Money = %d',[User.Cash,User2.Money],etInfo); cout('User.Job.Name = %s / User2.Job.Name = %s',[User.Job.Name,User2.Job.Name],etInfo); cout('User.Job.DateFrom = %s / User2.Job.DateFrom = %s',[DateTimeToStr(User.Job.DateFrom),DateTimeToStr(User2.Job.DateFrom)],etInfo); cout('User.Car.Model = %s / User2.Car.Model = %s',[User.Car.Model,User2.Car.Model],etInfo); cout(' ',etInfo); cout('USER AS JSON RESULT',etTrace); cout('%s',[User.ToJson],etInfo); cout(' ',etInfo); cout('USER2 AS JSON RESULT',etTrace); cout('%s',[User2.ToJson],etInfo); finally AutoMapper.Free; User.Free; User2.Free; end; ConsoleWaitForEnterKey; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.
unit FHIR.Tx.Iso4217; { 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 SysUtils, Classes, FHIR.Support.Utilities, FHIR.Support.Base, FHIR.Support.Stream, FHIR.Base.Common, FHIR.Tx.Service; type TIso4217Concept = class (TCodeSystemProviderContext) private FDisplay: String; FCode: String; FDecimals: integer; public function link : TIso4217Concept; overload; property code : String read FCode write FCode; property display : String read FDisplay write FDisplay; property decimals : integer read FDecimals write FDecimals; end; TIso4217ConceptFilter = class (TCodeSystemProviderFilterContext) private FList : TFslList<TIso4217Concept>; FCursor : integer; public constructor Create; override; destructor Destroy; override; function link : TIso4217ConceptFilter; overload; end; TIso4217Services = class (TCodeSystemProvider) private FCodes : TFslList<TIso4217Concept>; FMap : TFslMap<TIso4217Concept>; procedure load; public Constructor Create; Override; Destructor Destroy; Override; Function Link : TIso4217Services; overload; function TotalCount : integer; override; function ChildCount(context : TCodeSystemProviderContext) : integer; override; function getcontext(context : TCodeSystemProviderContext; ndx : integer) : TCodeSystemProviderContext; override; function system(context : TCodeSystemProviderContext) : String; override; function getDisplay(code : String; lang : String):String; override; function getDefinition(code : String):String; override; function locate(code : String; var message : String) : TCodeSystemProviderContext; override; function locateIsA(code, parent : String) : TCodeSystemProviderContext; override; function IsAbstract(context : TCodeSystemProviderContext) : boolean; override; function Code(context : TCodeSystemProviderContext) : string; override; function Display(context : TCodeSystemProviderContext; lang : String) : string; override; procedure Displays(code : String; list : TStringList; lang : String); override; procedure Displays(context : TCodeSystemProviderContext; list : TStringList; lang : String); override; function Definition(context : TCodeSystemProviderContext) : string; override; function getPrepContext : TCodeSystemProviderFilterPreparationContext; override; function prepare(prep : TCodeSystemProviderFilterPreparationContext) : boolean; override; function searchFilter(filter : TSearchFilterText; prep : TCodeSystemProviderFilterPreparationContext; sort : boolean) : TCodeSystemProviderFilterContext; override; function filter(prop : String; op : TFhirFilterOperator; value : String; prep : TCodeSystemProviderFilterPreparationContext) : TCodeSystemProviderFilterContext; override; function filterLocate(ctxt : TCodeSystemProviderFilterContext; code : String; var message : String) : TCodeSystemProviderContext; override; function FilterMore(ctxt : TCodeSystemProviderFilterContext) : boolean; override; function FilterConcept(ctxt : TCodeSystemProviderFilterContext): TCodeSystemProviderContext; override; function InFilter(ctxt : TCodeSystemProviderFilterContext; concept : TCodeSystemProviderContext) : Boolean; override; function isNotClosed(textFilter : TSearchFilterText; propFilter : TCodeSystemProviderFilterContext = nil) : boolean; override; function subsumesTest(codeA, codeB : String) : String; override; procedure Close(ctxt : TCodeSystemProviderFilterPreparationContext); override; procedure Close(ctxt : TCodeSystemProviderContext); override; procedure Close(ctxt : TCodeSystemProviderFilterContext); override; end; implementation { TIso4217Services } Constructor TIso4217Services.create(); begin inherited Create; FCodes := TFslList<TIso4217Concept>.create; FMap := TFslMap<TIso4217Concept>.create; Load; end; function TIso4217Services.TotalCount : integer; begin result := FCodes.Count; end; function TIso4217Services.system(context : TCodeSystemProviderContext) : String; begin result := 'urn:iso:std:iso:4217'; end; function TIso4217Services.getDefinition(code: String): String; begin result := ''; end; function TIso4217Services.getDisplay(code : String; lang : String):String; begin result := FMap[code].display; end; function TIso4217Services.getPrepContext: TCodeSystemProviderFilterPreparationContext; begin result := nil; end; procedure TIso4217Services.Displays(code : String; list : TStringList; lang : String); begin list.Add(getDisplay(code, lang)); end; procedure TIso4217Services.load; procedure doLoad(code : string; decimals : integer; display, countries : String); var c : TIso4217Concept; begin c := TIso4217Concept.Create; try c.code := code; c.display := display; c.decimals := decimals; FCodes.Add(c.Link); FMap.Add(code, c.Link); finally c.Free; end; end; begin doLoad('AED', 2, 'United Arab Emirates dirham', 'United Arab Emirates'); doLoad('AFN', 2, 'Afghan afghani', 'Afghanistan'); doLoad('ALL', 2, 'Albanian lek', 'Albania'); doLoad('AMD', 2, 'Armenian dram', 'Armenia'); doLoad('ANG', 2, 'Netherlands Antillean guilder', 'Curaçao (CW), Sint Maarten (SX)'); doLoad('AOA', 2, 'Angolan kwanza', 'Angola'); doLoad('ARS', 2, 'Argentine peso', 'Argentina'); doLoad('AUD', 2, 'Australian dollar', 'Australia, Christmas Island (CX), Cocos (Keeling) Islands (CC), Heard Island and McDonald Islands (HM), Kiribati (KI), Nauru (NR), Norfolk Island (NF), Tuvalu (TV)'); doLoad('AWG', 2, 'Aruban florin', 'Aruba'); doLoad('AZN', 2, 'Azerbaijani manat', 'Azerbaijan'); doLoad('BAM', 2, 'Bosnia and Herzegovina convertible mark', 'Bosnia and Herzegovina'); doLoad('BBD', 2, 'Barbados dollar', 'Barbados'); doLoad('BDT', 2, 'Bangladeshi taka', 'Bangladesh'); doLoad('BGN', 2, 'Bulgarian lev', 'Bulgaria'); doLoad('BHD', 3, 'Bahraini dinar', 'Bahrain'); doLoad('BIF', 0, 'Burundian franc', 'Burundi'); doLoad('BMD', 2, 'Bermudian dollar', 'Bermuda'); doLoad('BND', 2, 'Brunei dollar', 'Brunei'); doLoad('BOB', 2, 'Boliviano', 'Bolivia'); doLoad('BOV', 2, 'Bolivian Mvdol (funds code)', 'Bolivia'); doLoad('BRL', 2, 'Brazilian real', 'Brazil'); doLoad('BSD', 2, 'Bahamian dollar', 'Bahamas'); doLoad('BTN', 2, 'Bhutanese ngultrum', 'Bhutan'); doLoad('BWP', 2, 'Botswana pula', 'Botswana'); doLoad('BYN', 2, 'Belarusian ruble', 'Belarus'); doLoad('BZD', 2, 'Belize dollar', 'Belize'); doLoad('CAD', 2, 'Canadian dollar', 'Canada'); doLoad('CDF', 2, 'Congolese franc', 'Democratic Republic of the Congo'); doLoad('CHE', 2, 'WIR Euro (complementary currency)', 'Switzerland'); doLoad('CHF', 2, 'Swiss franc', 'Switzerland, Liechtenstein (LI)'); doLoad('CHW', 2, 'WIR Franc (complementary currency)', 'Switzerland'); doLoad('CLF', 4, 'Unidad de Fomento (funds code)', 'Chile'); doLoad('CLP', 0, 'Chilean peso', 'Chile'); doLoad('CNY', 2, 'Renminbi (Chinese) yuan[8]', 'China'); doLoad('COP', 2, 'Colombian peso', 'Colombia'); doLoad('COU', 2, 'Unidad de Valor Real (UVR) (funds code)[9]', 'Colombia'); doLoad('CRC', 2, 'Costa Rican colon', 'Costa Rica'); doLoad('CUC', 2, 'Cuban convertible peso', 'Cuba'); doLoad('CUP', 2, 'Cuban peso', 'Cuba'); doLoad('CVE', 0, 'Cape Verde escudo', 'Cape Verde'); doLoad('CZK', 2, 'Czech koruna', 'Czechia [10]'); doLoad('DJF', 0, 'Djiboutian franc', 'Djibouti'); doLoad('DKK', 2, 'Danish krone', 'Denmark, Faroe Islands (FO), Greenland (GL)'); doLoad('DOP', 2, 'Dominican peso', 'Dominican Republic'); doLoad('DZD', 2, 'Algerian dinar', 'Algeria'); doLoad('EGP', 2, 'Egyptian pound', 'Egypt'); doLoad('ERN', 2, 'Eritrean nakfa', 'Eritrea'); doLoad('ETB', 2, 'Ethiopian birr', 'Ethiopia'); doLoad('EUR', 2, 'Euro', 'Andorra (AD), Austria (AT), Belgium (BE), Cyprus (CY), Estonia (EE), Finland (FI), France (FR), Germany (DE), Greece (GR), Guadeloupe (GP), Ireland (IE), Italy (IT), '+'Latvia (LV), Lithuania (LT), Luxembourg (LU), Malta (MT), Martinique (MQ), Mayotte (YT), Monaco (MC), '+'Montenegro (ME), Netherlands (NL), Portugal (PT), Réunion (RE), Saint Barthélemy (BL), Saint Pierre and Miquelon (PM), San Marino (SM), Slovakia (SK), Slovenia (SI), Spain (ES)'); doLoad('FJD', 2, 'Fiji dollar', 'Fiji'); doLoad('FKP', 2, 'Falkland Islands pound', 'Falkland Islands (pegged to GBP 1:1)'); doLoad('GBP', 2, 'Pound sterling', 'United Kingdom, the Isle of Man (IM, see Manx pound), Jersey (JE, see Jersey pound), and Guernsey (GG, see Guernsey pound)'); doLoad('GEL', 2, 'Georgian lari', 'Georgia'); doLoad('GHS', 2, 'Ghanaian cedi', 'Ghana'); doLoad('GIP', 2, 'Gibraltar pound', 'Gibraltar (pegged to GBP 1:1)'); doLoad('GMD', 2, 'Gambian dalasi', 'Gambia'); doLoad('GNF', 0, 'Guinean franc', 'Guinea'); doLoad('GTQ', 2, 'Guatemalan quetzal', 'Guatemala'); doLoad('GYD', 2, 'Guyanese dollar', 'Guyana'); doLoad('HKD', 2, 'Hong Kong dollar', 'Hong Kong'); doLoad('HNL', 2, 'Honduran lempira', 'Honduras'); doLoad('HRK', 2, 'Croatian kuna', 'Croatia'); doLoad('HTG', 2, 'Haitian gourde', 'Haiti'); doLoad('HUF', 2, 'Hungarian forint', 'Hungary'); doLoad('IDR', 2, 'Indonesian rupiah', 'Indonesia'); doLoad('ILS', 2, 'Israeli new shekel', 'Israel'); doLoad('INR', 2, 'Indian rupee', 'India, Bhutan'); doLoad('IQD', 3, 'Iraqi dinar', 'Iraq'); doLoad('IRR', 2, 'Iranian rial', 'Iran'); doLoad('ISK', 0, 'Icelandic króna', 'Iceland'); doLoad('JMD', 2, 'Jamaican dollar', 'Jamaica'); doLoad('JOD', 3, 'Jordanian dinar', 'Jordan'); doLoad('JPY', 0, 'Japanese yen', 'Japan'); doLoad('KES', 2, 'Kenyan shilling', 'Kenya'); doLoad('KGS', 2, 'Kyrgyzstani som', 'Kyrgyzstan'); doLoad('KHR', 2, 'Cambodian riel', 'Cambodia'); doLoad('KMF', 0, 'Comoro franc', 'Comoros'); doLoad('KPW', 2, 'North Korean won', 'North Korea'); doLoad('KRW', 0, 'South Korean won', 'South Korea'); doLoad('KWD', 3, 'Kuwaiti dinar', 'Kuwait'); doLoad('KYD', 2, 'Cayman Islands dollar', 'Cayman Islands'); doLoad('KZT', 2, 'Kazakhstani tenge', 'Kazakhstan'); doLoad('LAK', 2, 'Lao kip', 'Laos'); doLoad('LBP', 2, 'Lebanese pound', 'Lebanon'); doLoad('LKR', 2, 'Sri Lankan rupee', 'Sri Lanka'); doLoad('LRD', 2, 'Liberian dollar', 'Liberia'); doLoad('LSL', 2, 'Lesotho loti', 'Lesotho'); doLoad('LYD', 3, 'Libyan dinar', 'Libya'); doLoad('MAD', 2, 'Moroccan dirham', 'Morocco'); doLoad('MDL', 2, 'Moldovan leu', 'Moldova'); doLoad('MGA', 1, 'Malagasy ariary', 'Madagascar'); doLoad('MKD', 2, 'Macedonian denar', 'Macedonia'); doLoad('MMK', 2, 'Myanmar kyat', 'Myanmar'); doLoad('MNT', 2, 'Mongolian tögrög', 'Mongolia'); doLoad('MOP', 2, 'Macanese pataca', 'Macao'); doLoad('MRU', 1, 'Mauritanian ouguiya', 'Mauritania'); doLoad('MUR', 2, 'Mauritian rupee', 'Mauritius'); doLoad('MVR', 2, 'Maldivian rufiyaa', 'Maldives'); doLoad('MWK', 2, 'Malawian kwacha', 'Malawi'); doLoad('MXN', 2, 'Mexican peso', 'Mexico'); doLoad('MXV', 2, 'Mexican Unidad de Inversion (UDI) (funds code)', 'Mexico'); doLoad('MYR', 2, 'Malaysian ringgit', 'Malaysia'); doLoad('MZN', 2, 'Mozambican metical', 'Mozambique'); doLoad('NAD', 2, 'Namibian dollar', 'Namibia'); doLoad('NGN', 2, 'Nigerian naira', 'Nigeria'); doLoad('NIO', 2, 'Nicaraguan córdoba', 'Nicaragua'); doLoad('NOK', 2, 'Norwegian krone', 'Norway, Svalbard and Jan Mayen (SJ), Bouvet Island (BV)'); doLoad('NPR', 2, 'Nepalese rupee', 'Nepal'); doLoad('NZD', 2, 'New Zealand dollar', 'New Zealand, Cook Islands (CK), Niue (NU), Pitcairn Islands (PN); see also Pitcairn Islands dollar), Tokelau (TK)'); doLoad('OMR', 3, 'Omani rial', 'Oman'); doLoad('PAB', 2, 'Panamanian balboa', 'Panama'); doLoad('PEN', 2, 'Peruvian Sol', 'Peru'); doLoad('PGK', 2, 'Papua New Guinean kina', 'Papua New Guinea'); doLoad('PHP', 2, 'Philippine piso[13]', 'Philippines'); doLoad('PKR', 2, 'Pakistani rupee', 'Pakistan'); doLoad('PLN', 2, 'Polish złoty', 'Poland'); doLoad('PYG', 0, 'Paraguayan guaraní', 'Paraguay'); doLoad('QAR', 2, 'Qatari riyal', 'Qatar'); doLoad('RON', 2, 'Romanian leu', 'Romania'); doLoad('RSD', 2, 'Serbian dinar', 'Serbia'); doLoad('RUB', 2, 'Russian ruble', 'Russia'); doLoad('RWF', 0, 'Rwandan franc', 'Rwanda'); doLoad('SAR', 2, 'Saudi riyal', 'Saudi Arabia'); doLoad('SBD', 2, 'Solomon Islands dollar', 'Solomon Islands'); doLoad('SCR', 2, 'Seychelles rupee', 'Seychelles'); doLoad('SDG', 2, 'Sudanese pound', 'Sudan'); doLoad('SEK', 2, 'Swedish krona/kronor', 'Sweden'); doLoad('SGD', 2, 'Singapore dollar', 'Singapore'); doLoad('SHP', 2, 'Saint Helena pound', 'Saint Helena (SH-SH), Ascension Island (SH-AC), Tristan da Cunha'); doLoad('SLL', 2, 'Sierra Leonean leone', 'Sierra Leone'); doLoad('SOS', 2, 'Somali shilling', 'Somalia'); doLoad('SRD', 2, 'Surinamese dollar', 'Suriname'); doLoad('SSP', 2, 'South Sudanese pound', 'South Sudan'); doLoad('STN', 2, 'São Tomé and Príncipe dobra', 'São Tomé and Príncipe'); doLoad('SVC', 2, 'Salvadoran colón', 'El Salvador'); doLoad('SYP', 2, 'Syrian pound', 'Syria'); doLoad('SZL', 2, 'Swazi lilangeni', 'Swaziland'); doLoad('THB', 2, 'Thai baht', 'Thailand'); doLoad('TJS', 2, 'Tajikistani somoni', 'Tajikistan'); doLoad('TMT', 2, 'Turkmenistan manat', 'Turkmenistan'); doLoad('TND', 3, 'Tunisian dinar', 'Tunisia'); doLoad('TOP', 2, 'Tongan paʻanga', 'Tonga'); doLoad('TRY', 2, 'Turkish lira', 'Turkey'); doLoad('TTD', 2, 'Trinidad and Tobago dollar', 'Trinidad and Tobago'); doLoad('TWD', 2, 'New Taiwan dollar', 'Taiwan'); doLoad('TZS', 2, 'Tanzanian shilling', 'Tanzania'); doLoad('UAH', 2, 'Ukrainian hryvnia', 'Ukraine'); doLoad('UGX', 0, 'Ugandan shilling', 'Uganda'); doLoad('USD', 2, 'United States dollar', 'United States, American Samoa (AS), Barbados (BB) (as well as Barbados Dollar), Bermuda (BM) (as well as Bermudian Dollar), British Indian Ocean Territory (IO) (also uses GBP), British Virgin Islands (VG), '+'Caribbean Netherlands (BQ - Bonaire, Sint Eustatius and Saba), Ecuador (EC), El Salvador (SV), Guam (GU), Haiti (HT), Marshall Islands (MH), Federated States of Micronesia (FM), '+'Northern Mariana Islands (MP), Palau (PW), Panama (PA) (as well as Panamanian Balboa), Puerto Rico (PR), Timor-Leste (TL), Turks and Caicos Islands (TC), U.S. Virgin Islands (VI), United States Minor Outlying Islands'); doLoad('USN', 2, 'United States dollar (next day) (funds code)', 'United States'); doLoad('UYI', 0, 'Uruguay Peso en Unidades Indexadas (URUIURUI) (funds code)', 'Uruguay'); doLoad('UYU', 2, 'Uruguayan peso', 'Uruguay'); doLoad('UZS', 2, 'Uzbekistan som', 'Uzbekistan'); doLoad('VEF', 2, 'Venezuelan bolívar', 'Venezuela'); doLoad('VND', 0, 'Vietnamese đồng', 'Vietnam'); doLoad('VUV', 0, 'Vanuatu vatu', 'Vanuatu'); doLoad('WST', 2, 'Samoan tala', 'Samoa'); doLoad('XAF', 0, 'CFA franc BEAC', 'Cameroon (CM), Central African Republic (CF), Republic of the Congo (CG), Chad (TD), Equatorial Guinea (GQ), Gabon (GA)'); doLoad('XAG', -1, 'Silver (one troy ounce)', ''); doLoad('XAU', -1, 'Gold (one troy ounce)', ''); doLoad('XBA', -1, 'European Composite Unit (EURCO) (bond market unit)', ''); doLoad('XBB', -1, 'European Monetary Unit (E.M.U.-6) (bond market unit)', ''); doLoad('XBC', -1, 'European Unit of Account 9 (E.U.A.-9) (bond market unit)', ''); doLoad('XBD', -1, 'European Unit of Account 17 (E.U.A.-17) (bond market unit)', ''); doLoad('XCD', 2, 'East Caribbean dollar', 'Anguilla (AI), Antigua and Barbuda (AG), Dominica (DM), Grenada (GD), Montserrat (MS), Saint Kitts and Nevis (KN), Saint Lucia (LC), Saint Vincent and the Grenadines (VC)'); doLoad('XDR', -1, 'Special drawing rights', 'International Monetary Fund'); doLoad('XOF', 0, 'CFA franc BCEAO', 'Benin (BJ), Burkina Faso (BF), Côte d''Ivoire (CI), Guinea-Bissau (GW), Mali (ML), Niger (NE), Senegal (SN), Togo (TG)'); doLoad('XPD', -1, 'Palladium (one troy ounce)', ''); doLoad('XPF', 0, 'CFP franc (franc Pacifique)', 'French territories of the Pacific Ocean: French Polynesia (PF), New Caledonia (NC), Wallis and Futuna (WF)'); doLoad('XPT', -1, 'Platinum (one troy ounce)', ''); doLoad('XSU', -1, 'SUCRE', 'Unified System for Regional Compensation (SUCRE)[15]'); doLoad('XTS', -1, 'Code reserved for testing purposes', ''); doLoad('XUA', -1, 'ADB Unit of Account', 'African Development Bank[16]'); doLoad('XXX', -1, 'No currency', ''); doLoad('YER', 2, 'Yemeni rial', 'Yemen'); doLoad('ZAR', 2, 'South African rand', 'South Africa'); doLoad('ZMW', 2, 'Zambian kwacha', 'Zambia'); doLoad('ZWL', 2, 'Zimbabwean dollar A/10', 'Zimbabwe'); end; function TIso4217Services.locate(code : String; var message : String) : TCodeSystemProviderContext; begin result := FMap[code]; end; function TIso4217Services.Code(context : TCodeSystemProviderContext) : string; begin result := TIso4217Concept(context).code; end; function TIso4217Services.Definition(context: TCodeSystemProviderContext): string; begin result := ''; end; destructor TIso4217Services.Destroy; begin FMap.free; FCodes.Free; inherited; end; function TIso4217Services.Display(context : TCodeSystemProviderContext; lang : String) : string; begin result := TIso4217Concept(context).display; end; procedure TIso4217Services.Displays(context: TCodeSystemProviderContext; list: TStringList; lang : String); begin list.Add(Display(context, lang)); end; function TIso4217Services.IsAbstract(context : TCodeSystemProviderContext) : boolean; begin result := false; // 4217 doesn't do abstract end; function TIso4217Services.isNotClosed(textFilter: TSearchFilterText; propFilter: TCodeSystemProviderFilterContext): boolean; begin result := false; end; function TIso4217Services.Link: TIso4217Services; begin result := TIso4217Services(Inherited Link); end; function TIso4217Services.ChildCount(context : TCodeSystemProviderContext) : integer; begin if (context = nil) then result := TotalCount else result := 0; // no children end; function TIso4217Services.getcontext(context : TCodeSystemProviderContext; ndx : integer) : TCodeSystemProviderContext; begin result := FCodes[ndx]; end; function TIso4217Services.locateIsA(code, parent : String) : TCodeSystemProviderContext; begin raise ETerminologyError.create('locateIsA not supported by Iso4217'); // Iso4217 doesn't have formal subsumption property, so this is not used end; function TIso4217Services.prepare(prep : TCodeSystemProviderFilterPreparationContext) : boolean; begin // nothing result := true; end; function TIso4217Services.searchFilter(filter : TSearchFilterText; prep : TCodeSystemProviderFilterPreparationContext; sort : boolean) : TCodeSystemProviderFilterContext; begin raise ETerminologyError.create('not done yet'); end; function TIso4217Services.subsumesTest(codeA, codeB: String): String; begin result := 'not-subsumed'; end; function TIso4217Services.filter(prop : String; op : TFhirFilterOperator; value : String; prep : TCodeSystemProviderFilterPreparationContext) : TCodeSystemProviderFilterContext; var res : TIso4217ConceptFilter; c : TIso4217Concept; begin if (prop = 'decimals') and (op = foEqual) then begin res := TIso4217ConceptFilter.create; try for c in FCodes do if inttostr(c.decimals) = value then res.flist.Add(c.link); result := res.link; finally res.Free; end; end else raise ETerminologyError.create('the filter '+prop+' '+CODES_TFhirFilterOperator[op]+' = '+value+' is not support for '+system(nil)); end; function TIso4217Services.filterLocate(ctxt : TCodeSystemProviderFilterContext; code : String; var message : String) : TCodeSystemProviderContext; begin raise ETerminologyError.create('not done yet'); end; function TIso4217Services.FilterMore(ctxt : TCodeSystemProviderFilterContext) : boolean; begin TIso4217ConceptFilter(ctxt).FCursor := TIso4217ConceptFilter(ctxt).FCursor + 1; result := TIso4217ConceptFilter(ctxt).FCursor < TIso4217ConceptFilter(ctxt).FList.Count; end; function TIso4217Services.FilterConcept(ctxt : TCodeSystemProviderFilterContext): TCodeSystemProviderContext; begin result := TIso4217ConceptFilter(ctxt).FList[TIso4217ConceptFilter(ctxt).FCursor]; end; function TIso4217Services.InFilter(ctxt : TCodeSystemProviderFilterContext; concept : TCodeSystemProviderContext) : Boolean; begin raise ETerminologyError.create('not done yet'); end; procedure TIso4217Services.Close(ctxt: TCodeSystemProviderContext); begin // ctxt.free; end; procedure TIso4217Services.Close(ctxt : TCodeSystemProviderFilterContext); begin ctxt.free; end; procedure TIso4217Services.Close(ctxt: TCodeSystemProviderFilterPreparationContext); begin raise ETerminologyError.create('not done yet'); end; { TIso4217Concept } function TIso4217Concept.link: TIso4217Concept; begin result := TIso4217Concept(inherited Link); end; { TIso4217ConceptFilter } constructor TIso4217ConceptFilter.Create; begin inherited; FList := TFslList<TIso4217Concept>.Create; FCursor := -1; end; destructor TIso4217ConceptFilter.Destroy; begin FList.Free; inherited; end; function TIso4217ConceptFilter.link: TIso4217ConceptFilter; begin result := TIso4217ConceptFilter(inherited Link); end; end.
UNIT Queue; INTERFACE PROCEDURE EmptyQ; PROCEDURE AddQ(VAR Elt: CHAR); PROCEDURE DelQ; PROCEDURE HeadQ(VAR Elt: CHAR); PROCEDURE WriteQ; IMPLEMENTATION VAR Q, Temp: TEXT; PROCEDURE CopyOpen (VAR F1, F2: TEXT); {копириует строку из F1 в F2 без RESET или REWRITE; таким образом F1 должен быть готов для чтения,а F2 для записи, но прошлые строки у этих файлов могут быть не пусты } VAR Ch: CHAR; BEGIN {CopyOpen} WHILE NOT EOLN(F1) DO BEGIN READ(F1, Ch); WRITE(F2, Ch) END END;{CopyOpen} PROCEDURE EmptyQ; {Q := <, /, R>} BEGIN {EmptyQ} REWRITE(Q); WRITELN(Q); RESET(Q) END; {EmptyQ} PROCEDURE HeadQ(VAR Elt: CHAR); {(Q = <,/,R> --> Elt := '#')| (Q = <,ax/,R>,где a символ и x строка --> Elt:= 'a' } BEGIN {HeadQ} IF NOT EOLN(Q) THEN READ(Q, Elt) ELSE Elt := '#'; RESET(Q) END;{HeadQ} PROCEDURE WriteQ; { (Q = <,x/,R> и OUTPUT =<y,,W>,где y и x строка --> OUTPUT := <y&x/,,W> } BEGIN {WriteQ} CopyOpen(Q, OUTPUT); WRITELN(OUTPUT); RESET(Q) END;{WriteQ} PROCEDURE AddQ (VAR Elt: CHAR); {Q = <,x/,R>,где x строка И Elt = a --> Q = <,xa/,R> } VAR Temp: TEXT; BEGIN {AddQ} REWRITE(Temp); CopyOpen(Q, Temp); WRITELN(Temp, Elt); {копируем Temp в Elt} RESET(Temp); REWRITE(Q); CopyOpen(Temp, Q); WRITELN(Q); RESET(Q) END {AddQ}; PROCEDURE DelQ; {(Q = <,/,R> -->)| (Q = <,ax/,R>,где a символ и x строка --> Q:= <,x/,R> } VAR Ch: CHAR; BEGIN {DelQ} {удаляем первый элемент из Q}; READ(Q, Ch); IF NOT EOF(Q) THEN {не пустой} BEGIN REWRITE(Temp); CopyOpen(Q, Temp); WRITELN(Temp); {копируем Temp в Q} RESET(Temp); REWRITE(Q); CopyOpen(Temp, Q); WRITELN(Q); END; RESET(Q) END {DelQ}; BEGIN END.
unit all_owners; interface uses vcl.dbgrids, Classes, Graphics, Dialogs, Main, SysUtils; function AllOwnersOpen: Boolean; function AllOwnersColumnSetup(Setup: boolean): Boolean; implementation { ----------------------------------------------------------------------+ DBGrid2CellClick(): This procedure finds the houseAcct value of the current record in the All_Owners grid and copies it to the "Acct Search" TEdit box. It then calls the eCurrentAcctSearchChange event. +----------------------------------------------------------------------- } procedure AllOwnersCellClick(Column: TColumn); begin MainForm.eCurrentAcctSearch.Text := MainForm.adoTableOwners.FieldValues['houseAcct']; MainForm.eCurrentAcctSearchChange(Column); end; function AllOwnersOpen: Boolean; begin AllOwnersOpen := False; try MainForm.adoTableOwners.Active := True; AllOwnersOpen := True; except MainForm.adoTableOwners.Active := False; AllOwnersOpen := False; end; end; {-----------------------------------------------------------------------------+ AllOwnersColumnSetup(Setup: boolean): This function deletes any existing columns in the dbgridAllOwners. If the argument is TRUE then it creates the columns using a hardcoded methodology. This is done to reduce the file size of the executable. +----------------------------------------------------------------------------} function AllOwnersColumnSetup(Setup: boolean): Boolean; var i: Integer; begin AllOwnersColumnSetup := False; with MainForm.dbgridAllOwners do begin if Columns.Count > 0 then try for I := (Columns.Count - 1) downto 0 do begin Columns.Delete(i); end; except // do something here end; if Not(Setup) then exit; for i := 0 to 16 do begin Columns.Add; Columns.Items[i].Visible := True; Columns.Items[i].Title.Color := $00F0B4DC; Columns.Items[i].Title.Font.Style := [fsBold]; Columns.Items[i].Alignment := taLeftJustify; Columns.Items[i].Width := 80; end; Columns.Items[0].FieldName := 'ownerID'; Columns.Items[0].Title.Caption := 'ID #'; Columns.Items[0].Alignment := taRightJustify; Columns.Items[1].FieldName := 'houseAcct'; Columns.Items[1].Title.Caption := 'Acct'; Columns.Items[1].Alignment := taRightJustify; Columns.Items[2].FieldName := 'Owner'; Columns.Items[2].Title.Caption := Columns.Items[2].FieldName; Columns.Items[2].Width := 200; Columns.Items[3].FieldName := 'Offsite'; Columns.Items[3].Title.Caption := Columns.Items[3].FieldName; Columns.Items[3].Width := 100; Columns.Items[4].FieldName := 'Phone'; Columns.Items[4].Title.Caption := Columns.Items[4].FieldName; Columns.Items[5].FieldName := 'Alt Phone'; Columns.Items[5].Title.Caption := Columns.Items[5].FieldName; Columns.Items[6].FieldName := 'Mobile 1'; Columns.Items[6].Title.Caption := Columns.Items[6].FieldName; Columns.Items[7].FieldName := 'Mobile 2'; Columns.Items[7].Title.Caption := Columns.Items[7].FieldName; Columns.Items[8].FieldName := 'closeDate'; Columns.Items[8].Title.Caption := 'Close Date'; Columns.Items[8].Width := 70; Columns.Items[9].FieldName := 'sellDate'; Columns.Items[9].Title.Caption := 'Sell Date'; Columns.Items[9].Width := 70; Columns.Items[10].FieldName := 'greeting'; Columns.Items[10].Title.Caption := 'Greeting'; Columns.Items[10].Width := 120; Columns.Items[11].FieldName := 'mailName'; Columns.Items[11].Title.Caption := 'Mail Name'; Columns.Items[11].Width := 150; Columns.Items[12].FieldName := 'Address'; Columns.Items[12].Title.Caption := 'Offsite Address'; Columns.Items[12].Width := 120; Columns.Items[13].FieldName := 'city'; Columns.Items[13].Title.Caption := 'Offsite City'; Columns.Items[13].Width := 70; Columns.Items[14].FieldName := 'state'; Columns.Items[14].Title.Caption := 'Offsite State'; Columns.Items[15].FieldName := 'Zip'; Columns.Items[15].Title.Caption := 'Offsite Zip'; Columns.Items[15].Alignment := taRightJustify; Columns.Items[16].FieldName := 'cityStateZip'; Columns.Items[16].Visible := False; 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. } {$INCLUDE ..\ormbr.inc} unit ormbr.form.monitor; interface uses DB, Forms, Classes, Controls, SysUtils, Variants, StdCtrls, {$IFDEF MONITORRESTFULCLIENT} ormbr.client.interfaces, {$ELSE} dbebr.factory.interfaces, {$ENDIF} TypInfo, ComCtrls; type TCommandMonitor = class(TForm, ICommandMonitor) Button1: TButton; MemoSQL: TRichEdit; procedure Button1Click(Sender: TObject); private { Private declarations } class var FInstance: TCommandMonitor; procedure Command(const ASQL: string; AParams: TParams); public { Public declarations } class destructor Destroy; class function GetInstance: ICommandMonitor; end; implementation {$R *.dfm} { TFSQLMonitor } procedure TCommandMonitor.Button1Click(Sender: TObject); begin MemoSQL.Lines.Clear; end; procedure TCommandMonitor.Command(const ASQL: string; AParams: TParams); var LFor: Integer; LAsValue: string; begin MemoSQL.Lines.Add(''); MemoSQL.Lines.Add(ASQL); if AParams <> nil then begin for LFor := 0 to AParams.Count -1 do begin if AParams.Items[LFor].Value = Variants.Null then LAsValue := 'NULL' else if AParams.Items[LFor].DataType = ftDateTime then LAsValue := '"' + DateTimeToStr(AParams.Items[LFor].Value) + '"' else if AParams.Items[LFor].DataType = ftDate then LAsValue := '"' + DateToStr(AParams.Items[LFor].Value) + '"' else LAsValue := '"' + VarToStr(AParams.Items[LFor].Value) + '"'; MemoSQL.Lines.Add(AParams.Items[LFor].Name + ' = ' + LAsValue + ' (' + GetEnumName(TypeInfo(TFieldType), Ord(AParams.Items[LFor].DataType)) + ')'); end; end; end; class destructor TCommandMonitor.Destroy; begin if Assigned(FInstance) then FreeAndNil(FInstance); end; class function TCommandMonitor.GetInstance: ICommandMonitor; begin if FInstance = nil then FInstance := TCommandMonitor.Create(nil); Result := FInstance; end; end.
unit uEditBatch; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, Grids, StdCtrls, Menus, uCustomTypes, uStrUtils, math, uEditBatchElement; type { TfBatchEdit } TfBatchEdit = class(TForm) bCancel: TButton; bOK: TButton; eBatchName: TEdit; Label1: TLabel; pmiCopyBatchCommand: TMenuItem; miCopyBatchElement: TMenuItem; pmiDelBatchCommand: TMenuItem; pmiEditBatchCommand: TMenuItem; pmiAddBatchCommand: TMenuItem; miDelBatchCommand: TMenuItem; miEditBatchCommand: TMenuItem; miAddBatchElement: TMenuItem; miActions: TMenuItem; mmEditBatchMenu: TMainMenu; pmEditBatchMenu: TPopupMenu; sgBchEdit: TStringGrid; procedure bCancelClick(Sender: TObject); procedure bOKClick(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure miAddBatchElementClick(Sender: TObject); procedure miCopyBatchElementClick(Sender: TObject); procedure miDelBatchCommandClick(Sender: TObject); procedure miEditBatchCommandClick(Sender: TObject); procedure pmiAddBatchCommandClick(Sender: TObject); procedure pmiCopyBatchCommandClick(Sender: TObject); procedure pmiDelBatchCommandClick(Sender: TObject); procedure pmiEditBatchCommandClick(Sender: TObject); procedure sgBchEditDblClick(Sender: TObject); procedure sgBchEditResize(Sender: TObject); private { private declarations } public { public declarations } end; var fBatchEdit: TfBatchEdit; DecodedBatch: TDecodedBatch; res: TBatchResult; initBatchName:string; function EditBatch(in_bch:tBatch;name_read_only:boolean):TBatchResult; function DecodeBatch(batch:tBatch):TDecodedBatch; function EncodeBatch(b_name:string;dbatch:TDecodedBatch):TBatch; procedure RefreshList; procedure EditBatchEl; procedure CopyBatchEl; procedure AddBatchEl; procedure DelBatchEl; implementation {$R *.lfm} uses uBchEditor; { TfBatchEdit } function EditBatch(in_bch:tBatch;name_read_only:boolean):TBatchResult; begin Application.CreateForm(TfBatchEdit, fBatchEdit); DecodedBatch:=DecodeBatch(in_bch); if length(DecodedBatch)=1 then begin if DecodedBatch[0].be_param='err' then begin showmessage('Error decoding batch!'); Setlength(DecodedBatch,0); end; end; fBatchEdit.eBatchName.Text:=in_bch.batch_name; if name_read_only then begin fBatchEdit.eBatchName.Enabled:=false; end; RefreshList; res.res:=false; initBatchName:=in_bch.batch_name; fBatchEdit.ShowModal; result:=res; end; function DecodeBatch(batch:TBatch):TDecodedBatch; var count:integer; x:integer; tmp:string; begin setlength(result,0); try count:=strtoint(uStrUtils.GetFieldFromString(batch.batch_str, ParamLimiter, 1)); setlength(result,count); for x:=1 to count do begin result[x-1].be_param:=uStrUtils.GetFieldFromString(batch.batch_params, ParamLimiter, x); // wait or not tmp:=uStrUtils.GetFieldFromString(batch.batch_str, ParamLimiter, (x-1)*3+2); if trim(tmp)='1' then begin result[x-1].be_wait:=true; end else begin result[x-1].be_wait:=false; end; // write log or not tmp:=uStrUtils.GetFieldFromString(batch.batch_str, ParamLimiter, (x-1)*3+3); if trim(tmp)='1' then begin result[x-1].be_write_log:=true; end else begin result[x-1].be_write_log:=false; end; // timeout tmp:=uStrUtils.GetFieldFromString(batch.batch_str, ParamLimiter, (x-1)*3+4); result[x-1].be_timeout:=strtoint(tmp); end; except setlength(result,1); Result[0].be_param:='err'; end; end; function EncodeBatch(b_name:string;dbatch:TDecodedBatch):TBatch; var x,l:integer; begin l:=Length(dbatch); Result.batch_name:=b_name; Result.batch_str:=inttostr(l)+ParamLimiter; Result.batch_params:=''; for x:=1 to l do begin if dbatch[x-1].be_wait then begin Result.batch_str:=Result.batch_str+'1'+ParamLimiter; end else begin Result.batch_str:=Result.batch_str+'0'+ParamLimiter; end; if dbatch[x-1].be_write_log then begin Result.batch_str:=Result.batch_str+'1'+ParamLimiter; end else begin Result.batch_str:=Result.batch_str+'0'+ParamLimiter; end; Result.batch_str:=Result.batch_str+inttostr(dbatch[x-1].be_timeout)+ParamLimiter; Result.batch_params:=Result.batch_params+dbatch[x-1].be_param+ParamLimiter; end; end; procedure RefreshList; var x,l:integer; begin l:=length(DecodedBatch); fBatchEdit.sgBchEdit.RowCount:=max(l+1,2); if l=0 then begin fBatchEdit.sgBchEdit.Cells[0,1]:=''; fBatchEdit.sgBchEdit.Cells[1,1]:=''; fBatchEdit.sgBchEdit.Cells[2,1]:=''; fBatchEdit.sgBchEdit.Cells[3,1]:=''; end; for x:=1 to l do begin fBatchEdit.sgBchEdit.Cells[0,x]:=DecodedBatch[x-1].be_param; if DecodedBatch[x-1].be_wait then begin fBatchEdit.sgBchEdit.Cells[1,x]:='Yes'; end else begin fBatchEdit.sgBchEdit.Cells[1,x]:=''; end; if DecodedBatch[x-1].be_write_log then begin fBatchEdit.sgBchEdit.Cells[2,x]:='Yes'; end else begin fBatchEdit.sgBchEdit.Cells[2,x]:=''; end; fBatchEdit.sgBchEdit.Cells[3,x]:=inttostr(DecodedBatch[x-1].be_timeout); end; end; procedure TfBatchEdit.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin CloseAction:=caFree; end; procedure TfBatchEdit.miAddBatchElementClick(Sender: TObject); begin AddBatchEl; end; procedure TfBatchEdit.miCopyBatchElementClick(Sender: TObject); begin CopyBatchEl; end; procedure TfBatchEdit.miDelBatchCommandClick(Sender: TObject); begin DelBatchEl; end; procedure TfBatchEdit.miEditBatchCommandClick(Sender: TObject); begin EditBatchEl; end; procedure TfBatchEdit.pmiAddBatchCommandClick(Sender: TObject); begin AddBatchEl; end; procedure TfBatchEdit.pmiCopyBatchCommandClick(Sender: TObject); begin CopyBatchEl; end; procedure TfBatchEdit.pmiDelBatchCommandClick(Sender: TObject); begin DelBatchEl; end; procedure TfBatchEdit.pmiEditBatchCommandClick(Sender: TObject); begin EditBatchEl; end; procedure TfBatchEdit.sgBchEditDblClick(Sender: TObject); begin EditBatchEl; end; procedure TfBatchEdit.sgBchEditResize(Sender: TObject); begin sgBchEdit.Columns.Items[0].Width:=sgBchEdit.Width-(561-300); end; procedure TfBatchEdit.bCancelClick(Sender: TObject); begin Close; end; procedure TfBatchEdit.bOKClick(Sender: TObject); begin if length(DecodedBatch)=0 then begin ShowMessage('Empty batch!'); Exit; end; if trim(eBatchName.Text)='' then begin ShowMessage('Empty batch name!'); Exit; end; if not ValidName(eBatchName.Text) then begin ShowMessage('Batch name contains invalid symbols!'); Exit; end; if uBchEditor.BatchNameUsed(trim(eBatchName.Text),initBatchName) then begin ShowMessage('Batch name "'+trim(eBatchName.Text)+'" already used!'); Exit; end; res.br_batch:=EncodeBatch(trim(eBatchName.Text),DecodedBatch); res.res:=true; Close; end; procedure EditBatchEl; var r:integer; ber:TDecodedBatchElementResult; begin r:=fBatchEdit.sgBchEdit.Row; if r<1 then begin ShowMessage('Select batch element first!'); exit; end; if r>Length(DecodedBatch) then begin ShowMessage('Select batch element first!'); exit; end; ber:=uEditBatchElement.EditBatchElement(DecodedBatch[r-1]); if ber.res then begin DecodedBatch[r-1]:=ber.dber_batch_element; RefreshList; end; end; procedure CopyBatchEl; var r:integer; ber:TDecodedBatchElementResult; begin r:=fBatchEdit.sgBchEdit.Row; if r<1 then begin ShowMessage('Select batch element first!'); exit; end; if r>Length(DecodedBatch) then begin ShowMessage('Select batch element first!'); exit; end; ber:=uEditBatchElement.EditBatchElement(DecodedBatch[r-1]); if ber.res then begin SetLength(DecodedBatch,length(DecodedBatch)+1); DecodedBatch[length(DecodedBatch)-1]:=ber.dber_batch_element; RefreshList; end; end; procedure AddBatchEl; var ber:TDecodedBatchElementResult; in_b:TDecodedBatchElement; begin in_b.be_param:=''; in_b.be_timeout:=0; in_b.be_wait:=true; in_b.be_write_log:=true; ber:=uEditBatchElement.EditBatchElement(in_b); if ber.res then begin SetLength(DecodedBatch,length(DecodedBatch)+1); DecodedBatch[length(DecodedBatch)-1]:=ber.dber_batch_element; RefreshList; end; end; procedure DelBatchEl; var r,x:integer; begin r:=fBatchEdit.sgBchEdit.Row; if r<1 then begin ShowMessage('Select batch element first!'); exit; end; if r>Length(DecodedBatch) then begin ShowMessage('Select batch element first!'); exit; end; if MessageDlg('Are you sure?','Delete batch element?',mtConfirmation,[mbYes, mbNo],0)=mrYes then begin for x:=r to Length(DecodedBatch)-1 do begin DecodedBatch[x-1]:=DecodedBatch[x]; end; SetLength(DecodedBatch,Length(DecodedBatch)-1); RefreshList; end; end; end.
unit Unit1; { https://stackoverflow.com/questions/923350/delphi-prompt-for-uac-elevation-when-needed https://pastebin.com/w4X4pHpC } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Button1: TButton; Button2: TButton; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private procedure StartWait; procedure EndWait; public { Public declarations } end; var Form1: TForm1; implementation uses RunElevatedSupport; {$R *.dfm} const ArgInstallUpdate = '/install_update'; ArgRegisterExtension = '/register_global_file_associations'; procedure TForm1.FormCreate(Sender: TObject); begin Label1.Caption := Format('IsAdministrator: %s', [BoolToStr(IsAdministrator, True)]); Label2.Caption := Format('IsAdministratorAccount: %s', [BoolToStr(IsAdministratorAccount, True)]); Label3.Caption := Format('IsUACEnabled: %s', [BoolToStr(IsUACEnabled, True)]); Label4.Caption := Format('IsElevated: %s', [BoolToStr(IsElevated, True)]); Button1.Caption := 'Install updates'; SetButtonElevated(Button1.Handle); Button2.Caption := 'Register file associations for all users'; SetButtonElevated(Button2.Handle); end; procedure TForm1.Button1Click(Sender: TObject); begin StartWait; try SetLastError(RunElevated(ArgInstallUpdate, Handle, Application.ProcessMessages)); if GetLastError <> ERROR_SUCCESS then RaiseLastOSError; finally EndWait; end; end; procedure TForm1.Button2Click(Sender: TObject); begin StartWait; try SetLastError(RunElevated(ArgRegisterExtension, Handle, Application.ProcessMessages)); if GetLastError <> ERROR_SUCCESS then RaiseLastOSError; finally EndWait; end; end; function DoElevatedTask(const AParameters: String): Cardinal; procedure InstallUpdate; var Msg: String; begin Msg := 'Hello from InstallUpdate!' + sLineBreak + sLineBreak + 'This function is running elevated under full administrator rights.' + sLineBreak + 'This means that you have write-access to Program Files folder and you''re able to overwrite files (e.g. install updates).' + sLineBreak + 'However, note that your executable is still running.' + sLineBreak + sLineBreak + 'IsAdministrator: ' + BoolToStr(IsAdministrator, True) + sLineBreak + 'IsAdministratorAccount: ' + BoolToStr(IsAdministratorAccount, True) + sLineBreak + 'IsUACEnabled: ' + BoolToStr(IsUACEnabled, True) + sLineBreak + 'IsElevated: ' + BoolToStr(IsElevated, True); MessageBox(0, PChar(Msg), 'Hello from InstallUpdate!', MB_OK or MB_ICONINFORMATION); end; procedure RegisterExtension; var Msg: String; begin Msg := 'Hello from RegisterExtension!' + sLineBreak + sLineBreak + 'This function is running elevated under full administrator rights.' + sLineBreak + 'This means that you have write-access to HKEY_LOCAL_MACHINE key and you''re able to write keys and values (e.g. register file extensions globally/for all users).' + sLineBreak + 'However, note that this is usually not a good idea. It is better to register your file extensions under HKEY_CURRENT_USER\Software\Classes.' + sLineBreak + sLineBreak + 'IsAdministrator: ' + BoolToStr(IsAdministrator, True) + sLineBreak + 'IsAdministratorAccount: ' + BoolToStr(IsAdministratorAccount, True) + sLineBreak + 'IsUACEnabled: ' + BoolToStr(IsUACEnabled, True) + sLineBreak + 'IsElevated: ' + BoolToStr(IsElevated, True); MessageBox(0, PChar(Msg), 'Hello from RegisterExtension!', MB_OK or MB_ICONINFORMATION); end; begin Result := ERROR_SUCCESS; if AParameters = ArgInstallUpdate then InstallUpdate else if AParameters = ArgRegisterExtension then RegisterExtension else Result := ERROR_GEN_FAILURE; end; procedure TForm1.StartWait; begin Cursor := crHourglass; Screen.Cursor := crHourglass; Button1.Enabled := False; Button2.Enabled := False; Application.ProcessMessages; end; procedure TForm1.EndWait; begin Cursor := crDefault; Screen.Cursor := crDefault; Button1.Enabled := True; Button2.Enabled := True; Application.ProcessMessages; end; initialization OnElevateProc := DoElevatedTask; CheckForElevatedTask; end.
unit uRealSubject; interface uses uSubject; type { Real Subject } TCalculadorReal = class(TInterfacedObject, ICalculador) public // Método da Interface function CalcularDistancia(const Origem, Destino: string): string; end; implementation uses SysUtils, IdURI, IdHTTP, System.JSON; const // Endereço da API do Google Maps GOOGLE_MAPS_API = 'http://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=%s&destinations=%s'; { TCalculadorReal } function TCalculadorReal.CalcularDistancia(const Origem, Destino: string): string; var IdHTTP: TIdHTTP; Endereco: string; Resposta: string; Status: string; // Classe para trabalhar com JSON JSON: TJSONObject; begin // Cria o componente IdHTTP para executar a consulta na API IdHTTP := TIdHTTP.Create(nil); try // Configura o endereço de envio de dados para a API Endereco := Format(GOOGLE_MAPS_API, [Origem, Destino]); // "Codifica" a URL no formato correto (por exemplo, tratando acentos) Endereco := TIdURI.URLEncode(Endereco); // Recebe a resposta Resposta := IdHTTP.Get(Endereco); // Interpreta a resposta da API como JSON JSON := TJSONObject.ParseJSONValue(Resposta) as TJSONObject; // Faz a leitura do valor do rótulo "status" do JSON Status := TJSONObject( TJSONArray( TJSONObject( TJSONArray( JSON.GetValue('rows') ).Items[0] ).GetValue('elements') ).Items[0] ).GetValue('status') .Value; // Valida o status do retorno, // apresentando uma exceção caso as cidades não sejam encontradas if (Status = '"NOT_FOUND"') or (Status = '"ZERO_RESULTS"') then raise Exception.Create('A cidade de origem ou destino não foi encontrada.'); // Obtém o valor do rótulo "distance" result := TJSONObject( TJSONObject( TJSONArray( TJSONObject( TJSONArray( JSON.GetValue('rows') ).Items[0] ).GetValue('elements') ).Items[0] ).GetValue('distance') ).GetValue('text') .Value; finally // Libera o componente IdHTTP da memória FreeAndNil(IdHTTP); end; end; end.
{ "name": "Wadiya", "creator": "AndreasG", "version": "1.0", "date": "2016/06/13", "description": "Lhe legendary country of the one and only, beautifull, amazing, outstanding general admiral aladeen<3", "planets": [ { "name": "Nostalgica", "mass": 5000, "position_x": 37500, "position_y": -6200, "velocity_x": 18.708784103393555, "velocity_y": 113.15800476074219, "required_thrust_to_move": 3, "starting_planet": true, "respawn": false, "start_destroyed": false, "min_spawn_delay": 0, "max_spawn_delay": 0, "planet": { "seed": 356356192, "radius": 550, "heightRange": 0, "waterHeight": 0, "waterDepth": 100, "temperature": 0, "metalDensity": 100, "metalClusters": 92, "metalSpotLimit": -1, "biomeScale": 50, "biome": "moon", "symmetryType": "none", "symmetricalMetal": false, "symmetricalStarts": false, "numArmies": 2, "landingZonesPerArmy": 0, "landingZoneSize": 0 } } ] }
unit model.Notificacao; interface uses UConstantes, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants; type TNotificacao = class(TObject) private aID : TGUID; aCodigo : Currency; aData : TDateTime; aTitulo , aMensagem : String; aLida , aDestacar : Boolean; procedure SetTitulo(Value : String); procedure SetMensagem(Value : String); public constructor Create; overload; property ID : TGUID read aID write aID; property Codigo : Currency read aCodigo write aCodigo; property Data : TDateTime read aData write aData; property Titulo : String read aTitulo write SetTitulo; property Mensagem : String read aMensagem write SetMensagem; property Lida : Boolean read aLida write aLida; property Destacar : Boolean read aDestacar write aDestacar; procedure NewID; function ToString : String; override; end; TNotificacoes = Array of TNotificacao; implementation { TNotificacao } constructor TNotificacao.Create; begin inherited Create; aId := GUID_NULL; aCodigo := 0; aData := StrToDate(EMPTY_DATE); aTitulo := EmptyStr; aMensagem := EmptyStr; aLida := False; aDestacar := False; end; procedure TNotificacao.NewID; var aGuid : TGUID; begin CreateGUID(aGuid); aId := aGuid; end; procedure TNotificacao.SetMensagem(Value: String); begin aMensagem := Trim(Value); end; procedure TNotificacao.SetTitulo(Value: String); begin aTitulo := Trim(Value); end; function TNotificacao.ToString: String; begin Result := 'Notigicação #' + FormatFloat('##000', aCodigo) + ' - ' + aTitulo; end; end.
{******************************************************************************} {* TestOovcIintl.pas 4.07 *} {******************************************************************************} {* ***** BEGIN LICENSE BLOCK ***** *} {* 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 TurboPower Orpheus *} {* *} {* The Initial Developer of the Original Code is Roman Kassebaum *} {* *} {* *} {* Contributor(s): *} {* Roman Kassebaum *} {* *} {* ***** END LICENSE BLOCK ***** *} unit TestOVCIntl; interface uses TestFramework; type TTestOVCIntl = class(TTestCase) published procedure TestInternationalTime; end; implementation uses OvcIntl; type TProtectedIntlSub = class(TOvcIntlSup); { TTestOVCIntl } procedure TTestOVCIntl.TestInternationalTime; var pIntlSup: TOvcIntlSup; begin pIntlSup := TOvcIntlSup.Create; try //This test should also work on a German OS, that's why I'm doing //some tricks to simulate an English OS. TProtectedIntlSub(pIntlSup).w12Hour := True; TProtectedIntlSub(pIntlSup).w1159 := 'AM'; TProtectedIntlSub(pIntlSup).w2359 := 'PM'; CheckEquals(pIntlSup.InternationalTime(True), 'hh:mm:ss tt'); CheckEquals(pIntlSup.InternationalTime(False), 'hh:mm tt'); finally pIntlSup.Free; end; end; initialization RegisterTest(TTestOVCIntl.Suite); end.
unit Controle.CadastroBomba; interface uses Controle.Padrao, Modelo.Bomba, Dao.Bomba, Bd.Gerenciador, uTipos; type TControleBomba = class(TControlePadrao) public Bomba: TBomba; Constructor Create; Destructor Destroy; override; function CarregaBomba(ACodigoBomba: string): Boolean; function ObtemNumeroVago: Integer; override; procedure SalvarBomba(AEvento: TEvento); end; var Bd : TBdGerenciador; BombaDao : TBombaDao; implementation uses System.SysUtils; { TControleBomba } function TControleBomba.CarregaBomba(ACodigoBomba: string): Boolean; begin Result := BombaDao.RetornaBomba(StrToIntDef(ACodigoBomba, 0), Bomba); end; constructor TControleBomba.Create; begin if not Assigned(Bomba) then Bomba := TBomba.Create; if not Assigned(BombaDao) then BombaDao := TBombaDao.Create; Bd := TBdGerenciador.ObterInstancia; end; destructor TControleBomba.Destroy; begin if Assigned(Bomba) then FreeAndNil(Bomba); if Assigned(BombaDao) then FreeAndNil(BombaDao); inherited Destroy; end; function TControleBomba.ObtemNumeroVago: Integer; begin Result := Bd.RetornaMaxCodigo('Bomba', 'Codigo'); end; procedure TControleBomba.SalvarBomba(AEvento: TEvento); begin case AEvento of teInclusao: BombaDao.Inserir(Bomba); teEdicao: BombaDao.Atualizar(Bomba); end; end; end.
{$include kode.inc} unit kode_widget_tabs; //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- uses kode_flags, kode_rect, kode_widget, kode_widget_buttonrow, kode_widget_pages; //---------- type KWidget_Tabs = class(KWidget) protected FHeader : KWidget_ButtonRow; FPages : KWidget_Pages; FNumPages : LongInt; public property _header : KWidget_ButtonRow read FHeader; property _pages : KWidget_Pages read FPages; property _numpages : LongInt read FNumPages; public constructor create(ARect:KRect; AAlignment:LongWord=kwa_none); function appendPage(AWidget:KWidget; ATitle:PChar) : LongInt; //override; procedure selectTab(AIndex:LongInt); procedure do_Update(AWidget:KWidget); override; end; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- //uses // kode_debug; //---------- constructor KWidget_Tabs.create(ARect:KRect; AAlignment:LongWord=kwa_none); begin inherited; FName := 'KWidget_Tabs'; FHeader := KWidget_ButtonRow.create(rect(20),kwa_fillTop); FPages := KWidget_Pages.create( rect0, kwa_fillClient); FNumPages := 0; FHeader._width := 0; {KWidget.}_appendWidget(FHeader); {KWidget.}_appendWidget(FPages); end; //------------------------------ // //------------------------------ function KWidget_Tabs.appendPage(AWidget:KWidget; ATitle:PChar) : LongInt; begin result := FPages.appendPage(AWidget); FHeader.setName(FNumPages,ATitle); FNumPages += 1; FHeader._width := FNumPages; end; //---------- procedure KWidget_Tabs.selectTab(AIndex:LongInt); begin if AIndex < FNumPages then FPages.setPage(AIndex); end; //------------------------------ // do_ // from child to parent //------------------------------ procedure KWidget_Tabs.do_Update(AWidget:KWidget); var sel : longint; begin if AWidget = FHeader then begin sel := FHeader._selected; //KTrace(['sel: ',sel]); FPages.setPage(sel); do_Redraw(FPages,FPages._rect); end; inherited; end; //---------------------------------------------------------------------- end.
{******************************************************************************* Title: T2Ti ERP 3.0 Description: Model relacionado à tabela [CONTAS_PAGAR] 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 ContasPagar; interface uses MVCFramework.Serializer.Commons, ModelBase; type [MVCNameCase(ncLowerCase)] TContasPagar = class(TModelBase) private FId: Integer; FIdFornecedor: Integer; FIdCompraPedidoCabecalho: Integer; FDataLancamento: Integer; FDataVencimento: Integer; FDataPagamento: Integer; FValorAPagar: Extended; FTaxaJuro: Extended; FTaxaMulta: Extended; FTaxaDesconto: Extended; FValorJuro: Extended; FValorMulta: Extended; FValorDesconto: Extended; FValorPago: Extended; FNumeroDocumento: string; FHistorico: string; FStatusPagamento: string; public // procedure ValidarInsercao; override; // procedure ValidarAlteracao; override; // procedure ValidarExclusao; override; [MVCColumnAttribute('ID', True)] [MVCNameAsAttribute('id')] property Id: Integer read FId write FId; [MVCColumnAttribute('ID_FORNECEDOR')] [MVCNameAsAttribute('idFornecedor')] property IdFornecedor: Integer read FIdFornecedor write FIdFornecedor; [MVCColumnAttribute('ID_COMPRA_PEDIDO_CABECALHO')] [MVCNameAsAttribute('idCompraPedidoCabecalho')] property IdCompraPedidoCabecalho: Integer read FIdCompraPedidoCabecalho write FIdCompraPedidoCabecalho; [MVCColumnAttribute('DATA_LANCAMENTO')] [MVCNameAsAttribute('dataLancamento')] property DataLancamento: Integer read FDataLancamento write FDataLancamento; [MVCColumnAttribute('DATA_VENCIMENTO')] [MVCNameAsAttribute('dataVencimento')] property DataVencimento: Integer read FDataVencimento write FDataVencimento; [MVCColumnAttribute('DATA_PAGAMENTO')] [MVCNameAsAttribute('dataPagamento')] property DataPagamento: Integer read FDataPagamento write FDataPagamento; [MVCColumnAttribute('VALOR_A_PAGAR')] [MVCNameAsAttribute('valorAPagar')] property ValorAPagar: Extended read FValorAPagar write FValorAPagar; [MVCColumnAttribute('TAXA_JURO')] [MVCNameAsAttribute('taxaJuro')] property TaxaJuro: Extended read FTaxaJuro write FTaxaJuro; [MVCColumnAttribute('TAXA_MULTA')] [MVCNameAsAttribute('taxaMulta')] property TaxaMulta: Extended read FTaxaMulta write FTaxaMulta; [MVCColumnAttribute('TAXA_DESCONTO')] [MVCNameAsAttribute('taxaDesconto')] property TaxaDesconto: Extended read FTaxaDesconto write FTaxaDesconto; [MVCColumnAttribute('VALOR_JURO')] [MVCNameAsAttribute('valorJuro')] property ValorJuro: Extended read FValorJuro write FValorJuro; [MVCColumnAttribute('VALOR_MULTA')] [MVCNameAsAttribute('valorMulta')] property ValorMulta: Extended read FValorMulta write FValorMulta; [MVCColumnAttribute('VALOR_DESCONTO')] [MVCNameAsAttribute('valorDesconto')] property ValorDesconto: Extended read FValorDesconto write FValorDesconto; [MVCColumnAttribute('VALOR_PAGO')] [MVCNameAsAttribute('valorPago')] property ValorPago: Extended read FValorPago write FValorPago; [MVCColumnAttribute('NUMERO_DOCUMENTO')] [MVCNameAsAttribute('numeroDocumento')] property NumeroDocumento: string read FNumeroDocumento write FNumeroDocumento; [MVCColumnAttribute('HISTORICO')] [MVCNameAsAttribute('historico')] property Historico: string read FHistorico write FHistorico; [MVCColumnAttribute('STATUS_PAGAMENTO')] [MVCNameAsAttribute('statusPagamento')] property StatusPagamento: string read FStatusPagamento write FStatusPagamento; end; implementation { TContasPagar } end.
unit DSE_Misc; interface uses Windows, Classes, vcl.Graphics, Sysutils, vcl.Controls, DSE_defs; type polygonSquare = array [0..4] of TPoint; Const DosDelimSet : set of AnsiChar = ['\', ':', #0]; Const stMaxFileLen = 260; function imax(v1, v2: Integer): Integer; function imin(v1, v2: Integer): Integer; function ilimit(vv, min, max: Integer): Integer; function TColor2TRGB(cl: TColor): TRGB; function TRGB2TColor(rgb: TRGB): TColor; function dmin(v1, v2: Double): Double; function dmax(v1, v2: Double): Double; function blimit(vv: Integer): Integer; function wlimit(vv: Integer): word; function RGB2TColor(r, g, b: Integer): TColor; function HasExtensionL(const Name : String; var DotPos : Cardinal) : Boolean; function JustFilenameL(const PathName : String) : String; function JustNameL(const PathName : String) : String; function CharExistsL(const S : String; C : Char) : Boolean; function WordPositionL(N : Cardinal; const S, WordDelims : String; var Pos : Cardinal) : Boolean; function ExtractWordL(N : Cardinal; const S, WordDelims : String) : String; function WordCountL(const S, WordDelims : String) : Cardinal; function getToken( var sString: String; const sDelim: String ): String; function GetNextToken (Const S: string; Separator: char; var StartPos: integer): String; procedure Split (const S: String; Separator: Char; MyStringList: TStringList) ; function AddToken (const aToken, S: String; Separator: Char; StringLimit: integer): String; implementation function imax(v1, v2: Integer): Integer; asm cmp edx,eax jng @1 mov eax,edx @1: end; function imin(v1, v2: Integer): Integer; asm cmp eax,edx jng @1 mov eax,edx @1: end; function ilimit(vv, min, max: Integer): Integer; asm cmp eax,edx jg @1 mov eax,edx ret @1: cmp eax,ecx jl @2 mov eax,ecx ret @2: end; function TColor2TRGB(cl: TColor): TRGB; var rgb: longint; begin rgb := colortorgb(cl); result.r := $FF and rgb; result.g := ($FF00 and rgb) shr 8; result.b := ($FF0000 and rgb) shr 16; end; function TRGB2TColor(rgb: TRGB): TColor; begin with rgb do result := r or (g shl 8) or (b shl 16); end; function dmin(v1, v2: Double): Double; begin if v1 < v2 then dmin := v1 else dmin := v2; end; function dmax(v1, v2: Double): Double; begin if v1 > v2 then dmax := v1 else dmax := v2; end; function blimit(vv: Integer): Integer; asm OR EAX, EAX JNS @@plus XOR EAX, EAX RET @@plus: CMP EAX, 255 JBE @@END MOV EAX, 255 @@END: end; function wlimit(vv: Integer): word; begin if vv < 0 then result := 0 else if vv>65535 then result := 65535 else result := vv; end; function RGB2TColor(r, g, b: Integer): TColor; begin result := r or (g shl 8) or (b shl 16); end; function PointInLineAsm(X, Y, x1, y1, x2, y2, d: Integer): Boolean; var sine, cosinus: Double; dx, dy, len: Integer; begin if d = 0 then d := 1; asm fild(y2) fisub(y1) fild(x2) fisub(x1) fpatan fsincos fstp cosinus fstp sine end; dx := Round(cosinus * (x - x1) + sine * (y - y1)); dy := Round(cosinus * (y - y1) - sine * (x - x1)); len := Round(cosinus * (x2 - x1) + sine * (y2 - y1)); // length of line Result:= (dy > -d) and (dy < d) and (dx > -d) and (dx < len + d); end; {function PontInLine(X, Y, x1, y1, x2, y2, d: Integer): Boolean; var Theta, sine, cosinus: Double; dx, dy, len: Integer; begin if d = 0 then d := 1; //calc the angle of the line Theta:=ArcTan2( (y2-y1),(x2-x1)); SinCos(Theta,sine, cosinus); dx := Round(cosinus * (x - x1) + sine * (y - y1)); dy := Round(cosinus * (y - y1) - sine * (x - x1)); len := Round(cosinus * (x2 - x1) + sine * (y2 - y1)); // length of line Result:= (dy > -d) and (dy < d) and (dx > -d) and (dx < len + d); end;} function GetNextToken (Const S: string; Separator: char; var StartPos: integer): String; var Index: integer; begin Result := ''; While (S[StartPos] = Separator) and (StartPos <= length(S))do StartPos := StartPos + 1; if StartPos > length(S) then Exit; Index := StartPos; While (S[Index] <> Separator) and (Index <= length(S))do Index := Index + 1; Result := Copy(S, StartPos, Index - StartPos) ; StartPos := Index + 1; end; procedure Split (const S: String; Separator: Char; MyStringList: TStringList) ; var Start: integer; begin Start := 1; While Start <= Length(S) do MyStringList.Add (GetNextToken(S, Separator, Start)) ; end; function AddToken (const aToken, S: String; Separator: Char; StringLimit: integer): String; begin if Length(aToken) + Length(S) < StringLimit then begin if S = '' then Result := '' else Result := S + Separator; Result := Result + aToken; end else Raise Exception.Create('Cannot add token') ; end; function getToken( var sString: String; const sDelim: String ): String; var nPos: integer; begin nPos := Pos( sDelim, sString ); if nPos > 0 then begin GetToken := Copy( sString, 1, nPos - 1 ); sString := Copy( sString, nPos + 1, Length( sString ) - nPos ); end else begin GetToken := sString; sString := ''; end; end; function ExtractWordL(N : Cardinal; const S, WordDelims : String) : String; var C : Cardinal; I, J : Longint; begin Result := ''; if WordPositionL(N, S, WordDelims, C) then begin I := C; J := I; while (I <= Length(S)) and not CharExistsL(WordDelims, S[I]) do Inc(I); SetLength(Result, I-J); Move(S[J], Result[1], (I-J) * SizeOf(Char)); end; end; function WordCountL(const S, WordDelims : String) : Cardinal; var I : Cardinal; SLen : Cardinal; begin Result := 0; I := 1; SLen := Length(S); while I <= SLen do begin {skip over delimiters} while (I <= SLen) and CharExistsL(WordDelims, S[I]) do Inc(I); if I <= SLen then Inc(Result); while (I <= SLen) and not CharExistsL(WordDelims, S[I]) do Inc(I); end; end; function WordPositionL(N : Cardinal; const S, WordDelims : String; var Pos : Cardinal) : Boolean; var Count : Longint; I : Longint; begin Count := 0; I := 1; Result := False; while (I <= Length(S)) and (Count <> LongInt(N)) do begin {skip over delimiters} while (I <= Length(S)) and CharExistsL(WordDelims, S[I]) do Inc(I); if I <= Length(S) then Inc(Count); if Count <> LongInt(N) then while (I <= Length(S)) and not CharExistsL(WordDelims, S[I]) do Inc(I) else begin Pos := I; Result := True; end; end; end; function CharExistsL(const S : String; C : Char) : Boolean; register; {-Count the number of a given character in a string. } {$IFDEF UNICODE} var I: Integer; begin Result := False; for I := 1 to Length(S) do begin if S[I] = C then begin Result := True; Break; end; end; end; {$ELSE} asm push ebx xor ecx, ecx or eax, eax jz @@Done mov ebx, [eax-StrOffset].LStrRec.Length or ebx, ebx jz @@Done jmp @@5 @@Loop: cmp dl, [eax+3] jne @@1 inc ecx jmp @@Done @@1: cmp dl, [eax+2] jne @@2 inc ecx jmp @@Done @@2: cmp dl, [eax+1] jne @@3 inc ecx jmp @@Done @@3: cmp dl, [eax+0] jne @@4 inc ecx jmp @@Done @@4: add eax, 4 sub ebx, 4 @@5: cmp ebx, 4 jge @@Loop cmp ebx, 3 je @@1 cmp ebx, 2 je @@2 cmp ebx, 1 je @@3 @@Done: mov eax, ecx pop ebx end; {$ENDIF} function JustNameL(const PathName : String) : String; var DotPos : Cardinal; S : AnsiString; begin S := JustFileNameL(PathName); if HasExtensionL(S, DotPos) then S := System.Copy(S, 1, DotPos-1); Result := S; end; function HasExtensionL(const Name : String; var DotPos : Cardinal) : Boolean; var I : Cardinal; begin DotPos := 0; for I := Length(Name) downto 1 do if (Name[I] = '.') and (DotPos = 0) then DotPos := I; Result := (DotPos > 0) and not CharExistsL(System.Copy(Name, Succ(DotPos), StMaxFileLen), '\'); end; function JustFilenameL(const PathName : String) : String; var I : Cardinal; begin Result := ''; if PathName = '' then Exit; I := Succ(Cardinal(Length(PathName))); repeat Dec(I); until (I = 0) or (PathName[I] in DosDelimSet); Result := System.Copy(PathName, Succ(I), StMaxFileLen); end; end.
unit SJ_OneInstance; interface uses Windows, SysUtils, Classes, Controls, Forms; type TOneInstance=class(TComponent) private FTerminate: boolean; FSwitchToPrevious: boolean; Mutex: hWnd; MutexCreated: boolean; FOnInstanceExists: TNotifyEvent; public procedure Loaded; override; constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property SwitchToPrevious: boolean read FSwitchToPrevious write FSwitchToPrevious; property Terminate: boolean read FTerminate write FTerminate; property OnInstanceExists: TNotifyEvent read FOnInstanceExists write FOnInstanceExists; end; implementation constructor TOneInstance.Create(AOwner: TComponent); begin inherited Create(AOwner); FTerminate:=True; FSwitchToPrevious:=True; end; destructor TOneInstance.Destroy; begin if MutexCreated then CloseHandle(Mutex); inherited Destroy; end; procedure TOneInstance.Loaded; var Title: array[0..$100] of char; PreviousHandle: THandle; begin inherited Loaded; StrPCopy(Title, Application.Title); MutexCreated:=False; Mutex:=CreateMutex(nil, False, Title); if (GetLastError=ERROR_ALREADY_EXISTS)or(Mutex=0) then begin if Assigned(FOnInstanceExists) then FOnInstanceExists(Self); if FSwitchToPrevious then begin PreviousHandle:=FindWindow(nil, Title); SetWindowText(PreviousHandle, ''); PreviousHandle:=FindWindow(nil, Title); if PreviousHandle<>0 then begin if IsIconic(PreviousHandle) then ShowWindow(PreviousHandle, SW_RESTORE) else BringWindowToTop(PreviousHandle); end; end; if FTerminate then Application.Terminate; end; MutexCreated:=True; end; end.
unit uMainForm; {$mode objfpc}{$H+} // ALIGNEMENT {$ifdef cpu64} {$ALIGN 16} {$CODEALIGN CONSTMIN=16} {$CODEALIGN LOCALMIN=16} {$CODEALIGN VARMIN=16} {$endif} {$DEFINE USE_FASTMATH} {=============================================================================== D'après le code source original en delphi : - http://codes-sources.commentcamarche.net/source/46214-boids-de-craig-reynoldsAuteur : cs_barbichetteDate : 03/08/2013 Description : ============= C'est une simulation de vol d'oiseau en groupe (ou de banc de poisson) Créer par Craig Reynolds, cette simulation se base sur un algo simple 3 forces agissent sur chaque individu (boids): - chaque boids aligne sa direction sur celle de ses voisins. - chaque boids est attiré au centre de ses voisins - mais chaque boids est repoussé par les autres pour éviter le surpeuplement Enfin, une dernière force, classique attire les boids vers la souris. Dans tous les cas, le boids ne réagis que par rapport aux voisins qu'il voie (distance max et angle de vu). Il ne voit pas les boids derrière lui ni s'ils sont trop loin. ================================================================================} interface uses LCLIntf, Classes, SysUtils, Forms, Controls, Graphics, Dialogs, BZColors, BZVectorMath, BZGraphic, BZBitmap, BZCadencer, BZStopWatch; { TMainForm } Const maxboidz = 499; Cursor_attract = 1/150; // 1/150 cohesion_attract = 1/25; // 1/25 Align_attract = 1/4; // 1/4 Separation_repuls = 1/25; // 1/25 Vitesse_Max = 30; Distance_Max = 50*50; Angle_Vision = 90; //soit 180° au total; type TMainForm = class(TForm) procedure FormCloseQuery(Sender : TObject; var CanClose : boolean); procedure FormCreate(Sender : TObject); procedure FormDestroy(Sender : TObject); procedure FormResize(Sender : TObject); procedure FormShow(Sender : TObject); private FBitmapBuffer : TBZBitmap; FCadencer : TBZCadencer; FStopWatch : TBZStopWatch; {$ifdef cpu64} {$CODEALIGN RECORDMIN=16} FBoidz : array[0..MaxBoidz] of TBZVector4f; {$CODEALIGN RECORDMIN=4} {$else} FBoidz : array[0..MaxBoidz] of TBZVector4f; {$endif} FrameCounter :Integer; aCounter : Byte; procedure CadencerProgress(Sender : TObject; const deltaTime, newTime : Double); public procedure AnimateScene; Procedure RenderScene; Procedure InitScene; Procedure InitColorMap; end; var MainForm : TMainForm; implementation {$R *.lfm} uses BZMath; // vérifie si b1 vois b2 function CheckAngleOfView(b1,b2:TBZVector4f):boolean; var angle:extended; l:Single; begin b1.UV :=b1.UV - b2.UV; angle:=abs(ArcTan2(b1.x,b1.y)*cPIDiv180); //180/cPI); l:=b1.UV.LengthSquare; result:=(l<Distance_Max) and (angle<=Angle_Vision); end; { TMainForm } procedure TMainForm.FormCloseQuery(Sender : TObject; var CanClose : boolean); begin FStopWatch.Stop; FCadencer.Enabled := False; FCadencer.OnProgress := nil; Sleep(100); // Pour permettre à la derniere frame de s'afficher correctement CanClose := True; end; procedure TMainForm.FormCreate(Sender : TObject); begin InitScene; end; procedure TMainForm.FormDestroy(Sender : TObject); begin FreeAndNil(FStopWatch); FreeAndNil(FCadencer); FreeAndNil(FBitmapBuffer); end; procedure TMainForm.FormResize(Sender : TObject); begin FStopWatch.Stop; FCadencer.Enabled := False; Sleep(100); FBitmapBuffer.SetSize(ClientWidth,ClientHeight); FrameCounter := 0; FStopWatch.Start(); FCadencer.Enabled := True; end; procedure TMainForm.FormShow(Sender : TObject); begin DoubleBuffered:=true; FStopWatch.Start(); FCadencer.Enabled := True; end; procedure TMainForm.CadencerProgress(Sender : TObject; const deltaTime, newTime : Double); begin AnimateScene; RenderScene; FBitmapBuffer.DrawToCanvas(Canvas, ClientRect); Caption:='BZScene - Demo - BoïdZ : '+Format('%.*f FPS', [3, FStopWatch.getFPS]); end; procedure TMainForm.AnimateScene; var {$ifdef cpu64} {$CODEALIGN VARMIN=16} cohesion,balign,separation,center: TBZVector2f; ct : TBZVector2f; ptc, ptcx : TBZVector2f; {$CODEALIGN VARMIN=4} {$else} cohesion,balign,separation,center: TBZVector2f; ct : TBZVector2f; ptc, ptcx : TBZVector2f; {$endif} i,j:integer; pt:tpoint; c,rc:Single; begin // position de la souris ptcx.Create(FBitmapBuffer.CenterX,FBitmapBuffer.CenterY); GetCursorPos(pt); pt := Mainform.ScreenToClient(pt); ptc.Create(pt.x,pt.y); //ptc.Create(pt.x+(-320+Random(320)),pt.y+(-240+Random(240))); //ptc.X := ptc.x - (Mainform.ClientWidth shr 1) ; //ptc.Y := ptc.Y - (Mainform.ClientHeight shr 1) ; ptc :=ptc - ptcx; // pour chaque boïde for i:=0 to maxBoidz do begin c:=0; cohesion.Create(0,0); bAlign.Create(0,0); separation.Create(0,0); // ils suivent le comportement des voisins // on parcours toute la liste for j:=0 to maxBoidz do begin // si le FBoidz J est dans le champs de vision de I // càd : pas trop loin et devant lui if (i<>j) and CheckAngleOfView(FBoidz[i],FBoidz[j]) then begin // alors on traite les 3 forces qui régissent de comportement du groupe c:=c+1; // il se rapproche du centre de masse de ses voisins Cohesion := Cohesion + FBoidz[j].UV; // il aligne sa direction sur celle des autres bAlign := bAlign + FBoidz[j].ST; // mais il s'éloigne si ils sont trop nombreux Separation := Separation - (FBoidz[j].UV - FBoidz[i].UV); end; end; // si il y a des voisins, on fini les calculs des moyennes if c<>0 then begin rc := 1/c; ct.Create(rc,rc); cohesion := ((cohesion * ct) - FBoidz[i].UV) * Cohesion_attract; bAlign := ((bAlign * ct) - FBoidz[i].ST) * Align_attract; separation := separation * Separation_Repuls; end; // la dernière force les poussent tous vers la souris Center := (ptc*10-FBoidz[i].UV) * Cursor_Attract; // on combine toutes les infos pour avoir la nouvelle vitesse FBoidz[i].ST := FBoidz[i].ST + cohesion + bAlign + separation + center; // attention, si il va trop vite, on le freine // c:=round(sqrt(boides[i].ST.x*boides[i].ST.x+boides[i].ST.y*boides[i].ST.y)); c:=FBoidz[i].ST.Length; if c>Vitesse_Max then begin //c:=(Vitesse_Max / c); FBoidz[i].ST := (FBoidz[i].ST * Vitesse_Max) / c//* c; end; // on le déplace en fonction de sa vitesse FBoidz[i].UV := FBoidz[i].UV + (FBoidz[i].ST); //rebond sur les bords //if FBoidz[i].UV.x>FBitmapBuffer.width then FBoidz[i].ST.x:=-(FBoidz[i].ST.x) //else if FBoidz[i].UV.x<0 then FBoidz[i].ST.x:=-(FBoidz[i].ST.x); //if FBoidz[i].UV.y>FBitmapBuffer.height then FBoidz[i].ST.y:=-(FBoidz[i].ST.y) //else if FBoidz[i].UV.y<0 then FBoidz[i].ST.y:=-(FBoidz[i].ST.y); // univers fermé if FBoidz[i].UV.x>FBitmapBuffer.width then FBoidz[i].UV.x:=FBoidz[i].UV.x-FBitmapBuffer.width; if FBoidz[i].UV.x<0 then FBoidz[i].UV.x:=FBoidz[i].UV.x+FBitmapBuffer.width; if FBoidz[i].UV.y>FBitmapBuffer.height then FBoidz[i].UV.y:=FBoidz[i].UV.y-FBitmapBuffer.height; if FBoidz[i].UV.y<0 then FBoidz[i].UV.y:=FBoidz[i].UV.y+FBitmapBuffer.height; end; end; procedure TMainForm.RenderScene; var {$CODEALIGN LOCALMIN=16} b : TBZVector4f; p : TBZVector4i; CurColor : TBZColor; {$CODEALIGN LOCALMIN=4} i,c : Integer; begin AnimateScene; // on efface le buffer et on affiche les boïdes //if aCounter = 15 then //begin // aCounter := 0; //end; //db.Create(10,10,10,10); FBitmapBuffer.ColorFilter.AdjustBrightness(-0.15); FBitmapBuffer.BlurFilter.FastBlur; //GaussianSplitBlur(2); // FBitmapBuffer.Clear(clrBlack); for i:=0 to maxboidz do begin b := FBoidz[i]; p := b.Round; //calcul de la direction de déplacement pour la couleur c:=round((ArcTan2(b.ST.X,b.ST.Y)*c180divPI)+180); //*cPIDiv180)+180); // CurColor := FBitmapBuffer.ColorManager.Palette.Colors[c].Value; with FBitmapBuffer.Canvas do begin Pen.Color := CurColor; // dessine un traits de la longueur de la vitesse // ShowMessage('Line : '+P.UV.x.ToString+' , '+P.UV.y.ToString+' --> '+(P.UV.x+P.ST.x).ToString+' , '+(P.UV.y+P.ST.y).ToString); Line(P.UV.x,P.UV.y,(P.UV.x+P.ST.x),(P.UV.y+P.ST.y)); //MoveTo(P.UV.x,P.UV.y); //LineTo((P.UV.x+P.ST.x),(P.UV.y+P.ST.y)); end; end; { With FBitmapBuffer.Canvas do begin Font.Quality:=fqAntialiased; Font.Size := 32; Font.Color := clrRed; TextOut(FBitmapBuffer.CenterX-154,20,'Craig Reynolds''s BoidZ'); DrawMode.PixelMode := dmSet; DrawMode.AlphaMode := amAlpha; Brush.Style := bsSolid; Brush.Color.Create(192,220,192,192); Pen.Color := clrBlack; Pen.Style := psSolid; Rectangle(FBitmapBuffer.CenterX-154,70,580,110); Font.Size := 16; Font.Color.Create(255,255,255,192); //Font.Color.Alpha := 192; TextOut(FBitmapBuffer.CenterX-124,80,'Move your mouse around the windows'); Font.Color := clrBlack; DrawMode.AlphaMode := amNone; TextOut(FBitmapBuffer.CenterX-122,82,'Move your mouse around the windows'); end; } end; procedure TMainForm.InitScene; Var i: Integer; begin FCadencer := TBZCadencer.Create(self); FCadencer.Enabled:= False; FCadencer.OnProgress := @CadencerProgress; FStopWatch := TBZStopWatch.Create(self); Randomize; FBitmapBuffer := TBZBitmap.Create; FBitmapBuffer.SetSize(Width,Height); FBitmapBuffer.Clear(clrBlack); FBitmapBuffer.UsePalette := True; // Create Color Map InitColorMap; FrameCounter:=0; // on initialise une vitesse et une place aléatoire pour le départ for i:=0 to maxboidz do with Fboidz[i] do begin ST.x:=10+random(FBitmapBuffer.Width-10); ST.y:=10+random(FBitmapBuffer.Height-10); UV.x:=10+random(Vitesse_Max-10); UV.y:=10+random(Vitesse_Max-10); end; aCounter :=0; end; procedure TMainForm.InitColorMap; Var i : Integer; nc : TBZColor; begin // on crée la palette de oculeur pour l'affichage for i:=0 to 360 do begin Case (i div 60) of 0,6 : nc.Create(255,(i Mod 60)*255 div 60,0); 1 : nc.Create(255-(i Mod 60)*255 div 60,255,0); 2 : nc.Create(0,255,(i Mod 60)*255 div 60); 3 : nc.Create(0,255-(i Mod 60)*255 div 60,255); 4 : nc.Create((i Mod 60)*255 div 60,0,255); 5 : nc.Create(255,0,255-(i Mod 60)*255 div 60); end; FBitmapBuffer.ColorManager.CreateColor(nc); end; end; end.
unit OleData; interface uses Windows, ActiveX, Classes, ShellAPI, ShlObj, SysUtils; type PFormatList = ^TFormatList; TFormatList = array[0..0] of TFormatEtc; TEnumFormatEtc = class(TInterfacedObject, IEnumFormatEtc) private FFormatList: PFormatList; FFormatCount: Integer; FIndex: Integer; public constructor Create(FormatList: PFormatList; FormatCount, Index: Integer); { IEnumFormatEtc で定義されているメソッド } function Next(celt: Longint; out elt; pceltFetched: PLongint): HResult; stdcall; function Skip(celt: Longint): HResult; stdcall; function Reset: HResult; stdcall; function Clone(out enum: IEnumFormatEtc): HResult; stdcall; end; TDataObject = class(TInterfacedObject, IDataObject) private FFormatList: PFormatList; FFormatCount: Integer; { IDataObject で定義されているメソッド } function GetData(const formatetcIn: TFormatEtc; out medium: TStgMedium): HResult; virtual; stdcall; function GetDataHere(const formatetc: TFormatEtc; out medium: TStgMedium): HResult; virtual; stdcall; function QueryGetData(const formatetc: TFormatEtc): HResult; virtual; stdcall; function GetCanonicalFormatEtc(const formatetc: TFormatEtc; out formatetcOut: TFormatEtc): HResult; virtual; stdcall; function SetData(const formatetc: TFormatEtc; var medium: TStgMedium; fRelease: BOOL): HResult; virtual; stdcall; function EnumFormatEtc(dwDirection: Longint; out enumFormatEtc: IEnumFormatEtc): HResult; virtual; stdcall; function DAdvise(const formatetc: TFormatEtc; advf: Longint; const advSink: IAdviseSink; out dwConnection: Longint): HResult; virtual; stdcall; function DUnadvise(dwConnection: Longint): HResult; virtual; stdcall; function EnumDAdvise(out enumAdvise: IEnumStatData): HResult; virtual; stdcall; protected function GetMedium(const FormatEtc: TFormatEtc; var Medium: TStgMedium; CreateMedium: Boolean): HResult; virtual; abstract; public constructor Create(AFormatList: PFormatList; AFormatCount: Integer); destructor Destroy; override; end; implementation // IEnumFormatEtc constructor TEnumFormatEtc.Create(FormatList: PFormatList; FormatCount, Index: Integer); begin inherited Create; FFormatList := FormatList; FFormatCount := FormatCount; FIndex := Index; end; // 現在のインデックスからスタートして指定された数の FORMATETC 構造体を返します function TEnumFormatEtc.Next(celt: Longint; out elt; pceltFetched: PLongint): HResult; var I: Integer; begin I := 0; // FORMATETC 構造体を celt 個列挙する while (I < celt) and (FIndex < FFormatCount) do begin TFormatList(elt)[I] := FFormatList[FIndex]; Inc(FIndex); Inc(I); end; // 列挙した数を返す if pceltFetched <> nil then pceltFetched^ := I; // 要求された FORMATETC 構造体の数と、列挙した数が同じなら S_OK if I = celt then Result := S_OK else Result := S_FALSE; end; // このメソッドは、指定された数だけFORMATETC 構造体のリストをスキップします。 function TEnumFormatEtc.Skip(celt: Longint): HResult; begin if celt <= FFormatCount - FIndex then begin FIndex := FIndex + celt; Result := S_OK; end else begin FIndex := FFormatCount; Result := S_FALSE; end; end; function TEnumFormatEtc.Reset: HResult; begin FIndex := 0; Result := S_OK; end; function TEnumFormatEtc.Clone(out enum: IEnumFormatEtc): HResult; begin enum := TEnumFormatEtc.Create(FFormatList, FFormatCount, FIndex); Result := S_OK; end; // IDataObject の実装例 } constructor TDataObject.Create(AFormatList: PFormatList; AFormatCount: Integer); var CopySize: Integer; begin inherited Create; { オブジェクト内部に TFormatEtc 構造体のリストのコピーを確保する。 } FFormatCount := AFormatCount; CopySize := SizeOf(TFormatList) * FFormatCount; GetMem(FFormatList, CopySize); CopyMemory(FFormatList, AFormatList, CopySize); end; destructor TDataObject.Destroy; begin { オブジェクト内部に確保した TFormatEtc 構造体のリストを解放する。 } FreeMem(FFormatList); inherited Destroy; end; { 指定記憶メディアを使って指定形式のデータを展開する。 } function TDataObject.GetData( const formatetcIn: TFormatEtc; { データを戻すために使う形式 } out medium: TStgMedium { 記憶メディアへのポインタ } ): HResult; stdcall; begin { 初期値:指定されたメディアはサポートできません } Result := DV_E_FORMATETC; { 構造体の初期化 } medium.tymed := 0; medium.hGlobal := 0; medium.UnkForRelease := nil; try { サポート可能な形式であるかを確認する } if (S_OK = QueryGetData(formatetcIn)) then { 転送メディアは TDataObject から派生したクラスが作成する。 } Result := GetMedium(formatetcIn, medium, TRUE); except { エラーが発生した場合。 } Result := E_UNEXPECTED; end; end; { 指定された確保済み記憶媒体にデータを展開する } function TDataObject.GetDataHere(const formatetc: TFormatEtc; out medium: TStgMedium): HResult; stdcall; begin { 初期値:指定されたメディアはサポートできません } Result := DV_E_FORMATETC; { = DATA_E_FORMATETC (Win16) } try { サポート可能な形式であるかを確認する } if (S_OK = QueryGetData(formatetc)) then { 転送メディアは TDataObject から派生したクラスが作成する。 } Result := GetMedium(formatetc, medium, FALSE); except { エラーが発生した場合。 } Result := E_UNEXPECTED; end; end; { formatetc を GetData に渡した場合、処理が成功するかを判断する。  } function TDataObject.QueryGetData( const formatetc: TFormatEtc { データを受け取るための形式 } ): HResult; stdcall; var i: integer; begin { 初期値:指定されたメディアはサポートできない } Result := DV_E_FORMATETC; { オブジェクト内部に確保した TFormatEtc 構造体のリストと比較する。 } for i := 0 to FFormatCount - 1 do if (formatetc.cfFormat = FFormatList^[i].cfFormat) and (formatetc.dwAspect = FFormatList^[i].dwAspect) and Bool(formatetc.tymed and FFormatList^[i].tymed) then begin Result := NOERROR; Break; end; end; { 表示デバイスに固有な展開処理を行なわない場合の実装例 } function TDataObject.GetCanonicalFormatEtc( const formatetc: TFormatEtc; out formatetcOut: TFormatEtc): HResult; stdcall; begin formatetcOut := formatetc; formatetcOut.ptd := nil; Result := DATA_S_SAMEFORMATETC; end; { この実装例においては、この関数はサポートしない } function TDataObject.SetData( const formatetc: TFormatEtc; var medium: TStgMedium; fRelease: BOOL): HResult; stdcall; begin Result := E_NOTIMPL; end; { GetData メソッドでデータを取得するために利用可能な形式を列挙する。 } function TDataObject.EnumFormatEtc( dwDirection: Longint; { データをやり取りする方向 } out enumFormatEtc: IEnumFormatEtc { 列挙オブジェクトのインタフェース } ): HResult; stdcall; begin Result := E_NOTIMPL; enumFormatEtc := nil; if dwDirection = DATADIR_GET then begin { TFormatEtc 構造体から IEnumFormatEtc インタフェースを持つ } { オブジェクトを作成する } enumFormatEtc := TEnumFormatEtc.Create(FFormatList, FFormatCount, 0); if Assigned(enumFormatEtc) then Result := S_OK; end end; { この関数はサポートしない } function TDataObject.DAdvise(const formatetc: TFormatEtc; advf: Longint; const advSink: IAdviseSink; out dwConnection: Longint): HResult; stdcall; begin Result := OLE_E_ADVISENOTSUPPORTED; end; { この関数はサポートしない } function TDataObject.DUnadvise(dwConnection: Longint): HResult; stdcall; begin Result := OLE_E_ADVISENOTSUPPORTED; end; { この関数はサポートしない } function TDataObject.EnumDAdvise(out enumAdvise: IEnumStatData): HResult; stdcall; begin Result := OLE_E_ADVISENOTSUPPORTED; end; initialization OleInitialize(nil); { OLE ライブラリの初期化を行う } finalization OleFlushClipboard; OleUninitialize; { OLE ライブラリの初期化を解除 } end.
{ this file is part of Ares Aresgalaxy ( http://aresgalaxy.sourceforge.net ) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. } { Description: supernode server communication } unit const_supernode_commands; interface const //bye packet codes ERROR_PAYLOADBIG = 1; ERROR_FLOWTIMEOUT = 2; ERROR_NETWORKISSUE = 3; ERROR_FLUSHQUEUE_OVERFLOW = 4; ERROR_DECOMPRESSION_ERROR = 5; ERROR_DECOMPRESSED_PACKETBIG = 6; ERROR_SYNCTIMEOUT = 7; ERROR_SYNC_OLDBUILDERROR = 8; ERROR_SYNC_NOBUILDERROR = 9; ERROR_FLUSH_OVERFLOW = 10; // end of search descriptions RSN_ENDOFSEARCH_ASREQUESTED = 1; RSN_ENDOFSEARCH_TOMANYSEARCHES= 2; RSN_ENDOFSEARCH_MISSINGFIELDS = 3; RSN_ENDOFSEARCH_ENOUGHRESULTS = 4; // handle not encrypted packets CHAR_MARKER_NOCRYPT = 6; CHAR_MARKER_NEWSTACK =5; MSG_SERVER_LOGIN_OK = 1; MSG_SERVER_YOUR_NICK = 5; MSG_SERVER_PUSH_REQ = 8; MSG_SERVER_SEARCH_RESULT = 18; MSG_SERVER_SEARCH_ENDOF = 19; MSG_SERVER_STATS = 30; MSG_LINKED_ENDOFSYNCH = 45; MSG_LINKED_ENDOFSYNCH_100 = 145; MSG_SERVER_YOUR_IP = 37; MSG_SERVER_HERE_KSERVS = 38; MSG_SERVER_PRELOGIN_OK = 51; MSG_SERVER_PRELOGIN_OK_NEWNET_LATEST = 52; MSG_SERVER_HERE_CACHEPATCH = 53; MSG_SERVER_HERE_CACHEPATCH2 = 54; MSG_SERVER_HERE_CACHEPATCH3 = 55; //2952 MSG_SERVER_PRELGNOK = 56; //2958+ 17-2-2005 MSG_SERVER_PRELGNOKNOCRYPT = 60; MSG_SERVER_HERE_CHATCACHEPATCH = 57; //2960+ MSG_SERVER_PRELOGFAILLOGSECURTYIP = 58; MSG_SERVER_PRELOGFAILLOGBUSY = 59; MSG_SERVER_LINK_FULL = 94; MSG_SERVER_PUSH_CHATREQ_NEW = 97; MSG_SERVER_COMPRESSED = 101; MSG_LINKED_PING = 3; MSG_LINKED_PING_100 = 103; MSG_LINKED_QUERY = 19; MSG_LINKED_QUERY_100 = 119; MSG_LINKED_QUERY_HIT = 11; MSG_LINKED_QUERY_HIT_100 = 111; MSG_LINKED_BYE_PACKET = 36; MSG_LINKED_BYE_PACKET_100 = 136; MSG_LINKED_QUERYHASH = 70; MSG_LINKED_QUERYHASH_100 = 170; MSG_LINKED_QUERYHASH_HIT = 75; MSG_LINKED_QUERYHASH_HIT_100 = 175; // udp protocol MSG_SERV_UDP_PRELOGIN_REQ = 31; MSG_SERV_UDP_HERE_MYKEY = 32; MSG_SERV_UDP_LOGINREQ = 33; MSG_SERV_UDP_LOGIN_OK = 34; MSG_SERV_UDP_QUERY = 26; MSG_SERV_UDP_QUERY_HIT = 27; MSG_SERV_UDP_QUERY_ACK = 28; MSG_SERV_UDP_PING = 30; MSG_SERV_UDP_PONG = 37; MSG_SERV_UDP_QUERYHASH = 35; MSG_CLNT_UDP_PUSH = 45; MSG_SRV_UDP_PUSH_ACK = 46; MSG_SRV_UDP_PUSH_FAIL = 47; MSG_CLNT_UDP_CHATPUSH = 41; MSG_SRV_UDP_CHATPUSH_ACK = 42; MSG_SRV_UDP_CHATPUSH_FAIL = 43; // deprecated stuff //MSG_LINKED_USERLOGIN = 33; //2964 //MSG_LINKED_USERsSYNC = 34; //2964 //MSG_LINKED_DUMMY = 35;//per bug cryptazione su supernodo in parse receive <size fino a vers 2935 compresa //MSG_LINKER_RESET_REMOTE_HASH_TABLE = 50; //MSG_LINKER_ADD_REMOTE_HASH = 51; //CMD_LINKER_REMOTE_REM_HASH_REQUEST = 71; //MSG_LINKED_PONG = 4; //MSG_LINKED_QUERY = 10; //MSG_LINKED_QUERY2 = 15; //MSG_LINKED_QUERY_UNICODE = 16; //MSG_SERVER_HEREPROXY_ADDR = 95; //MSG_SERVER_STATUS_LINK = 58;//sent to client to facilitate elections //MSG_SUPERNODE_FIRST_LOG = 93; <---in const_commands //MSG_SERVER_PRELOGIN_OK_NEWNET = 51; implementation end.
unit lkp_CurrencyExchange; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, DB, DBClient, SimpleDS, Mask, DBCtrls, Grids, DBGrids,LookUp, VrControls, VrButtons, Buttons, jpeg, ExtCtrls; type TfmCurrencyExchange = class(TForm) grp_Content: TGroupBox; SDS_Header: TSimpleDataSet; DS_Header: TDataSource; grpData: TGroupBox; Label2: TLabel; Label1: TLabel; DBGrid1: TDBGrid; Label3: TLabel; EdtPrice: TDBEdit; GroupBox2: TGroupBox; BtnOpen: TButton; btnAdd: TButton; btnEdit: TButton; btnDelete: TButton; btnSave: TButton; BtnCancel: TButton; BtnShow: TButton; SDS_HeaderCompanyCode: TStringField; SDS_HeaderCurrencyCode: TStringField; SDS_HeaderBaseCurrencyCode: TStringField; SDS_HeaderExchangeRate: TFMTBCDField; Co_Currency: TDBLookupComboBox; Co_BaseCurrency: TDBLookupComboBox; SDS_Currency2: TSimpleDataSet; StringField1: TStringField; SDS_HeaderCurrencyNameA: TStringField; SDS_HeaderCurrencyNameE: TStringField; StringField2: TStringField; DS_Currency2: TDataSource; SDS_Currency1: TSimpleDataSet; StringField3: TStringField; StringField4: TStringField; StringField5: TStringField; StringField6: TStringField; DS_Currency1: TDataSource; procedure BtnOpenClick(Sender: TObject); procedure btnEditClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure BtnCancelClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure btnAddClick(Sender: TObject); procedure SDS_HeaderBeforePost(DataSet: TDataSet); procedure BtnShowClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } EditMode : Boolean; public { Public declarations } end; var fmCurrencyExchange: TfmCurrencyExchange; implementation uses Main, GFunctions, GVariable; {$R *.dfm} procedure TfmCurrencyExchange.BtnOpenClick(Sender: TObject); begin SDS_Header.Close; SDS_Header.Open; btnEdit.Enabled := True; BtnOpen.Enabled := True; btnAdd.Enabled := True; btnSave.Enabled := False; BtnCancel.Enabled := False; btnDelete.Enabled := True; grpData.Enabled := False; BtnShow.Enabled := True; EditMode := False; end; procedure TfmCurrencyExchange.btnEditClick(Sender: TObject); begin SDS_Header.Edit; btnEdit.Enabled := False; BtnOpen.Enabled := False; btnAdd.Enabled := False; btnSave.Enabled := True; BtnCancel.Enabled := True; btnDelete.Enabled := False; grpData.Enabled := True; Co_Currency.Enabled := False; Co_BaseCurrency.Enabled := False; BtnShow.Enabled := False; Co_Currency.Enabled := True; Co_BaseCurrency.Enabled := True; end; procedure TfmCurrencyExchange.btnSaveClick(Sender: TObject); Var IsDuplicated : Boolean; begin if SDS_HeaderCurrencyCode.AsString = '' Then Begin ShowMessage('يجب إختيار العملة'); Co_Currency.SetFocus; Exit; end; if SDS_HeaderBaseCurrencyCode.AsString = '' Then Begin ShowMessage('يجب إختبار العمله الأساسية'); Co_BaseCurrency.SetFocus; Exit; end; If SDS_HeaderExchangeRate.AsString = '' Then Begin ShowMessage('يجب تحديد سعر التحويل'); EdtPrice.SetFocus; Exit; end; IsDuplicated := RepeatedKey('tbl_CurrencyExch', ' CurrencyCode = ''' + SDS_HeaderCurrencyCode.AsString + ''' and BaseCurrencyCode = ''' + SDS_HeaderBaseCurrencyCode.AsString + ''' '); If (IsDuplicated = True) And (EditMode = False) Then Begin ShowMessage('هذا الرمز موجود مسبقا'); Co_Currency.SetFocus; Exit; end; if SDS_Header.ApplyUpdates(0) = 0 then Begin ShowMessage('تم الحفــظ بنجاح'); BtnOpenClick(Sender); end else Begin ShowMessage('حدث خطأ أثناء الحفظ') ; end; end; procedure TfmCurrencyExchange.BtnCancelClick(Sender: TObject); Var buttonSelected : Integer; begin // Show a confirmation dialog buttonSelected := MessageDlg('هل تريد حقا الغاء التعديلات',mtInformation, mbOKCancel, 0); // Show the button type selected if buttonSelected = mrOK then Begin SDS_Header.CancelUpdates; BtnOpenClick(Sender); end; end; procedure TfmCurrencyExchange.btnDeleteClick(Sender: TObject); Var buttonSelected : Integer; begin try // Show a confirmation dialog buttonSelected := MessageDlg('هل تريد حقا حذف البيانات',mtError, mbOKCancel, 0); // Show the button type selected if buttonSelected = mrOK then Begin SDS_Header.Delete; if SDS_Header.ApplyUpdates(0) = 0 then Begin ShowMessage('تم الحذف بنجاح'); BtnOpenClick(Sender); end else Begin ShowMessage('حدث خطأ أثناء حذف البيانات') ; BtnOpenClick(Sender); end; end; except ShowMessage('حدث خطأ أثناء مسح البيانات , لا يمكن حذف بيانات مستخدمة'); BtnOpenClick(Sender); end; end; procedure TfmCurrencyExchange.FormCreate(Sender: TObject); Begin { Left := (Screen.Width - Width) div 2; Top := (Screen.Height - Height) div 2; } BtnOpenClick(Sender); BtnShow.Enabled := False; SDS_Currency1.Open; SDS_Currency2.Open; end; procedure TfmCurrencyExchange.FormKeyPress(Sender: TObject; var Key: Char); begin If Key = #13 Then Begin SendMessage( handle, WM_NEXTDLGCTL, 0, 0 ); end; end; procedure TfmCurrencyExchange.btnAddClick(Sender: TObject); begin SDS_Header.Append; btnEdit.Enabled := False; BtnOpen.Enabled := False; btnAdd.Enabled := False; btnSave.Enabled := True; BtnCancel.Enabled := True; btnDelete.Enabled := False; grpData.Enabled := True; Co_Currency.Enabled := TRue; Co_BaseCurrency.Enabled := True; BtnShow.Enabled := False; Co_Currency.SetFocus; EditMode := False; end; procedure TfmCurrencyExchange.SDS_HeaderBeforePost(DataSet: TDataSet); begin SDS_HeaderCompanyCode.Value := DCompany; end; procedure TfmCurrencyExchange.BtnShowClick(Sender: TObject); var lkp : Tlkp; begin lkp := Tlkp.Create(SDS_Header,nil); lkp.ShowModal; end; procedure TfmCurrencyExchange.FormClose(Sender: TObject; var Action: TCloseAction); begin SDS_Currency1.Open; SDS_Currency2.Open; end; end.
unit RtcService; interface uses System.SysUtils, System.Classes, rtcDataCli, rtcInfo, rtcConn, rtcHttpCli, System.SyncObjs; type TOnRtcServiceResponse = reference to procedure(const Data:String); PRtcServiceUser = ^TRtcServiceUser; TRtcServiceUser = record userName: String; password: String; end; TRtcService = class(TComponent) private FEvent :TEvent; FResponse: String; FRtcDataRequest: TRtcDataRequest; FOnResponse: TOnRtcServiceResponse; FUser: PRtcServiceUser; // FhttpClient: TRtcHttpClient; procedure prepareRequest(const user:TRtcServiceUser); procedure SethttpClient(const Value: TRtcDataClient); function getHttpClient: TRtcDataClient; procedure DefaultRtcDataRequestDataReceived(Sender: TRtcConnection); procedure RtcDataRequestDataReceived(Sender: TRtcConnection); procedure SetOnResponse(const Value: TOnRtcServiceResponse); procedure SetUser(const Value: TRtcServiceUser); public constructor Create(AOwner:TComponent);override; destructor Destroy;override; property User:TRtcServiceUser read FUser write FUser ; property httpClient: TRtcDataClient read getHttpClient write SetHttpClient ; // property OnResponse: TOnRtcServiceResponse read FOnResponse write SetOnResponse; function executeGet(const path, query:String; onResponse:TOnRtcServiceResponse ):String; function executePost(const path:String; const value:String; onResponse:TOnRtcServiceResponse ):String; end; implementation { TRtcService } constructor TRtcService.Create(AOwner: TComponent); begin inherited; FRtcDataRequest := TRtcDataRequest.Create(AOwner); FRtcDataRequest.OnDataReceived := DefaultRtcDataRequestDataReceived; if (AOwner is TRtcClient) then FRtcDataRequest.Client := TRtcClient(AOwner); FUser = new(PRtcSetviceUser); // FEvent := TEvent.create(nil, true, false, 'DoRequest'); end; procedure TRtcService.DefaultRtcDataRequestDataReceived(Sender: TRtcConnection); var r: String; begin with TRTCDataClient( Sender ) do begin r := UTF8Decode(Read); if Assigned(FOnResponse) then FOnResponse(r); end; end; destructor TRtcService.Destroy; begin inherited; FRtcDataRequest.Free; end; function TRtcService.executeGet(const path, query: String;onResponse:TOnRtcServiceResponse): String; begin FOnResponse := onResponse; FRtcDataRequest.Request.Method := 'GET'; prepareRequest(FUser); //RtcDataRequest1.Post; with FRtcDataRequest do begin Request.FileName := path+'?'+query; Write(); Post; end; end; function TRtcService.executePost(const path: String; const value: String;onResponse:TOnRtcServiceResponse): String; begin FOnResponse := onResponse; FRtcDataRequest.Request.Method := 'POST'; prepareRequest(FUser); //RtcDataRequest1.Post; with FRtcDataRequest do begin // client.Connect(); //if not client.isConnected then // raise Exception.Create('Connection Eror'); Request.FileName := path; Write(UTF8Encode(value)); Post; end; end; function TRtcService.getHttpClient: TRtcDataClient; begin Result := FRtcDataRequest.Client; end; procedure TRtcService.prepareRequest(const user: TRtcServiceUser); begin with FRtcDataRequest do begin Request.AutoLength := true; Request.HeaderText := ''; Request.HeaderText := Request.HeaderText +'Accept: application/json; charset=UTF-8'+#13#10; Request.HeaderText := Request.HeaderText +'Content-Type: text/xml'+#13#10; Request.HeaderText := Request.HeaderText +'Authorization: Basic '+ StringReplace(Mime_Encode(user.userName+':'+user.password),#13#10, '',[]); end; end; procedure TRtcService.RtcDataRequestDataReceived(Sender: TRtcConnection); begin end; procedure TRtcService.SetHttpClient(const Value: TRtcDataClient); begin FRtcDataRequest.Client := Value; end; procedure TRtcService.SetOnResponse(const Value: TOnRtcServiceResponse); begin FOnResponse := Value; end; procedure TRtcService.SetUser(const Value: TRtcServiceUser); begin FUser := Value; end; end.
{ Ultibo RTL Builder Tool. Copyright (C) 2016 - SoftOz Pty Ltd. Arch ==== <All> Boards ====== <All> Licence ======= LGPLv2.1 with static linking exception (See COPYING.modifiedLGPL.txt) Credits ======= Information for this unit was obtained from: References ========== RTL Builder =========== The RTL builder creates a Windows batch file which compiles the RTL and Packages for any of the supported architectures and displays the output in a window during the compile. While the tool is designed to determine the correct paths and locations without configuration it does support creating a BuildRTL.ini file in the same directory and setting a number of parameters to adjust the behavior. The format of the INI file is: [BuildRTL] PathPrefix= InstallPath= CompilerName= CompilerPath= CompilerVersion= SourcePath= ARMCompiler= AARCH64Compiler= BuildRTL= BuildPackages= PlatformARMv6= PlatformARMv7= PlatformARMv8= A brief explanation of each parameter along with the standard default value: PathPrefix - A text value to prepend to the path variable in the batch file (Default: <Blank>) InstallPath - The path where Ultibo core is installed (Default: C:\Ultibo\Core) (Detected from the application path) CompilerName - The name of the Free Pascal compiler (Default: fpc.exe) CompilerPath - The path where the Ultibo version of FPC is installed (Default: <InstallPath>\fpc\<CompilerVersion>) CompilerVersion - The version of the FPC compiler (Default: 3.1.1) SourcePath - The path to RTL and Packages source code (Default: <CompilerPath>\source) ARMCompiler - The name of the Free Pascal ARM Compiler or Cross Compiler (Default: <Blank>) AARCH64Compiler - The name of the Free Pascal AARCH64 Compiler or Cross Compiler (Default: <Blank>) BuildRTL - Enable or disable building the RTL (0=Disable / 1=Enable) (Default: 1) BuildPackages - Enable or disable building the Packages (0=Disable / 1=Enable) (Default: 1) PlatformARMv6 - Build the RTL and Packages for ARMv6 architecture (0=Disable / 1=Enable) (Default: 1) PlatformARMv7 - Build the RTL and Packages for ARMv7 architecture (0=Disable / 1=Enable) (Default: 1) PlatformARMv8 - Build the RTL and Packages for ARMv8 architecture (0=Disable / 1=Enable) (Default: 1) } unit Main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, IniFiles; const LineEnd = Chr(13) + Chr(10); {CR LF} MarkerEnd = '!!!EndOfBuild!!!'; type TfrmMain = class(TForm) mmoMain: TMemo; sbMain: TStatusBar; pnlMain: TPanel; cmdExit: TButton; lblCompiler: TLabel; lblPlatforms: TLabel; cmdBuild: TButton; chkARMv6: TCheckBox; chkARMv7: TCheckBox; chkARMv8: TCheckBox; lblMain: TLabel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormHide(Sender: TObject); procedure cmdExitClick(Sender: TObject); procedure cmdBuildClick(Sender: TObject); procedure chkARMv6Click(Sender: TObject); procedure chkARMv7Click(Sender: TObject); procedure chkARMv8Click(Sender: TObject); private { Private declarations } PathPrefix:String; InstallPath:String; SourcePath:String; CompilerName:String; CompilerPath:String; CompilerVersion:String; ARMCompiler:String; AARCH64Compiler:String; BuildRTL:Boolean; BuildPackages:Boolean; PlatformARMv6:Boolean; PlatformARMv7:Boolean; PlatformARMv8:Boolean; public { Public declarations } function LoadConfig:Boolean; function CreateBuildFile:Boolean; function ExecuteBuildFile:Boolean; end; var frmMain: TfrmMain; function GetDosOutput(CommandLine: string; Work: string = 'C:\'): string; procedure CaptureConsoleOutput(const ACommand, AParameters: String; AMemo: TMemo); function ExecuteConsoleProcess(const ACommand,AParameters,AWorking:String;AMemo:TMemo):Boolean; function ExecuteConsoleProcessEx(const ACommand,AParameters,AWorking,AMarker:String;AMemo:TMemo):Boolean; {For details on how to capture command prompt output see: http://www.delphidabbler.com/tips/61 http://stackoverflow.com/questions/9119999/getting-output-from-a-shell-dos-app-into-a-delphi-app See also JclSysUtils unit in the Jedi JCL } function AddTrailingSlash(const FilePath:String):String; function StripTrailingSlash(const FilePath:String):String; function IsWinNT6orAbove:Boolean; implementation {$R *.DFM} {==============================================================================} function GetDosOutput(CommandLine: string; Work: string = 'C:\'): string; {From: http://www.delphidabbler.com/tips/61} var SA: TSecurityAttributes; SI: TStartupInfo; PI: TProcessInformation; StdOutPipeRead, StdOutPipeWrite: THandle; WasOK: Boolean; Buffer: array[0..255] of AnsiChar; BytesRead: Cardinal; WorkDir: string; Handle: Boolean; begin Result := ''; with SA do begin nLength := SizeOf(SA); bInheritHandle := True; lpSecurityDescriptor := nil; end; CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SA, 0); try with SI do begin FillChar(SI, SizeOf(SI), 0); cb := SizeOf(SI); dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES; wShowWindow := SW_HIDE; hStdInput := GetStdHandle(STD_INPUT_HANDLE); // don't redirect stdin hStdOutput := StdOutPipeWrite; hStdError := StdOutPipeWrite; end; WorkDir := Work; Handle := CreateProcess(nil, PChar('cmd.exe /C ' + CommandLine), nil, nil, True, 0, nil, PChar(WorkDir), SI, PI); CloseHandle(StdOutPipeWrite); if Handle then try repeat WasOK := ReadFile(StdOutPipeRead, Buffer, 255, BytesRead, nil); if BytesRead > 0 then begin Buffer[BytesRead] := #0; Result := Result + Buffer; end; until not WasOK or (BytesRead = 0); WaitForSingleObject(PI.hProcess, INFINITE); finally CloseHandle(PI.hThread); CloseHandle(PI.hProcess); end; finally CloseHandle(StdOutPipeRead); end; end; {==============================================================================} procedure CaptureConsoleOutput(const ACommand, AParameters: String; AMemo: TMemo); {From: http://stackoverflow.com/questions/9119999/getting-output-from-a-shell-dos-app-into-a-delphi-app} const CReadBuffer = 2400; var saSecurity: TSecurityAttributes; hRead: THandle; hWrite: THandle; suiStartup: TStartupInfo; piProcess: TProcessInformation; pBuffer: array[0..CReadBuffer] of AnsiChar; //<----- update dRead: DWord; dRunning: DWord; begin saSecurity.nLength := SizeOf(TSecurityAttributes); saSecurity.bInheritHandle := True; saSecurity.lpSecurityDescriptor := nil; if CreatePipe(hRead, hWrite, @saSecurity, 0) then begin FillChar(suiStartup, SizeOf(TStartupInfo), #0); suiStartup.cb := SizeOf(TStartupInfo); suiStartup.hStdInput := hRead; suiStartup.hStdOutput := hWrite; suiStartup.hStdError := hWrite; suiStartup.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW; suiStartup.wShowWindow := SW_HIDE; if CreateProcess(nil, PChar(ACommand + ' ' + AParameters), @saSecurity, @saSecurity, True, NORMAL_PRIORITY_CLASS, nil, nil, suiStartup, piProcess) then begin repeat dRunning := WaitForSingleObject(piProcess.hProcess, 100); Application.ProcessMessages(); repeat dRead := 0; ReadFile(hRead, pBuffer[0], CReadBuffer, dRead, nil); pBuffer[dRead] := #0; OemToAnsi(pBuffer, pBuffer); AMemo.Lines.Add(String(pBuffer)); until (dRead < CReadBuffer); until (dRunning <> WAIT_TIMEOUT); CloseHandle(piProcess.hProcess); CloseHandle(piProcess.hThread); end; CloseHandle(hRead); CloseHandle(hWrite); end; end; {==============================================================================} function ExecuteConsoleProcess(const ACommand,AParameters,AWorking:String;AMemo:TMemo):Boolean; {Modified from: CaptureConsoleOutput} const READ_BUFFER_SIZE = 2400; var Status:DWORD; WorkDir:PChar; Command:String; BytesRead:DWORD; ReadData:String; ReadRemain:String; ReadResult:Boolean; ReadHandle:THandle; WriteHandle:THandle; StartupInfo:TStartupInfo; ProcessInformation:TProcessInformation; SecurityAttributes:TSecurityAttributes; ReadBuffer:array[0..READ_BUFFER_SIZE] of AnsiChar; begin {} Result:=False; {Check Parameters} if (Length(ACommand) = 0) and (Length(AParameters) = 0) then Exit; if AMemo = nil then Exit; {Setup Security Attributes} FillChar(SecurityAttributes,SizeOf(TSecurityAttributes),0); SecurityAttributes.nLength:=SizeOf(TSecurityAttributes); SecurityAttributes.bInheritHandle:=True; SecurityAttributes.lpSecurityDescriptor:=nil; {Create Pipe} if CreatePipe(ReadHandle,WriteHandle,@SecurityAttributes,0) then begin try {Setup Startup Info} FillChar(StartupInfo,SizeOf(TStartupInfo),0); StartupInfo.cb:=SizeOf(TStartupInfo); StartupInfo.hStdInput:=ReadHandle; StartupInfo.hStdOutput:=WriteHandle; StartupInfo.hStdError:=WriteHandle; StartupInfo.dwFlags:=STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW; StartupInfo.wShowWindow:=SW_HIDE; {Setup Process Information} FillChar(ProcessInformation,SizeOf(TProcessInformation),0); {Create Command} Command:=Trim(ACommand + ' ' + AParameters); {Check Working} WorkDir:=nil; if Length(AWorking) <> 0 then begin WorkDir:=PChar(AWorking); end; {Create Process} if CreateProcess(nil,PChar(Command),@SecurityAttributes,@SecurityAttributes,True,NORMAL_PRIORITY_CLASS,nil,WorkDir,StartupInfo,ProcessInformation) then begin try {Wait for Process} Status:=WaitForSingleObject(ProcessInformation.hProcess,100); if Status <> WAIT_TIMEOUT then Exit; ReadData:=''; ReadRemain:=''; repeat {Read from Pipe} BytesRead:=0; ReadResult:=ReadFile(ReadHandle,ReadBuffer[0],READ_BUFFER_SIZE,BytesRead,nil); {Check Bytes Read} if BytesRead > 0 then begin {Update Buffer} ReadBuffer[BytesRead]:=#0; {Convert Output} OemToAnsi(ReadBuffer,ReadBuffer); //To Do //ReadData/ReadRemain //See HTTPBuffer and ExecuteConsoleProcessEx etc {Add Output} AMemo.Lines.Add(String(ReadBuffer)); Application.ProcessMessages; end; {Check Bytes Read} if (not(ReadResult) or (BytesRead < READ_BUFFER_SIZE)) then begin {Wait for Process} Status:=WaitForSingleObject(ProcessInformation.hProcess,100); end; until (Status <> WAIT_TIMEOUT); Result:=True; finally CloseHandle(ProcessInformation.hProcess); CloseHandle(ProcessInformation.hThread); end; end; finally CloseHandle(ReadHandle); CloseHandle(WriteHandle); end; end; end; {==============================================================================} function ExecuteConsoleProcessEx(const ACommand,AParameters,AWorking,AMarker:String;AMemo:TMemo):Boolean; {Modified from: CaptureConsoleOutput} var WorkDir:PChar; Command:String; BytesRead:DWORD; ReadData:String; ReadChar:AnsiChar; ReadResult:Boolean; ReadHandle:THandle; WriteHandle:THandle; StartupInfo:TStartupInfo; ProcessInformation:TProcessInformation; SecurityAttributes:TSecurityAttributes; begin {} Result:=False; {Check Parameters} if (Length(ACommand) = 0) and (Length(AParameters) = 0) then Exit; if AMemo = nil then Exit; {Setup Security Attributes} FillChar(SecurityAttributes,SizeOf(TSecurityAttributes),0); SecurityAttributes.nLength:=SizeOf(TSecurityAttributes); SecurityAttributes.bInheritHandle:=True; SecurityAttributes.lpSecurityDescriptor:=nil; {Create Pipe} if CreatePipe(ReadHandle,WriteHandle,@SecurityAttributes,0) then begin try {Setup Startup Info} FillChar(StartupInfo,SizeOf(TStartupInfo),0); StartupInfo.cb:=SizeOf(TStartupInfo); StartupInfo.hStdInput:=ReadHandle; if not(IsWinNT6orAbove) then StartupInfo.hStdInput:=INVAlID_HANDLE_VALUE; {Don't pass StdInput handle if less the Vista} StartupInfo.hStdOutput:=WriteHandle; StartupInfo.hStdError:=WriteHandle; StartupInfo.dwFlags:=STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW; StartupInfo.wShowWindow:=SW_HIDE; {Setup Process Information} FillChar(ProcessInformation,SizeOf(TProcessInformation),0); {Create Command} Command:=Trim(ACommand + ' ' + AParameters); {Check Working} WorkDir:=nil; if Length(AWorking) <> 0 then begin WorkDir:=PChar(AWorking); end; {Create Process} if CreateProcess(nil,PChar(Command),@SecurityAttributes,@SecurityAttributes,True,NORMAL_PRIORITY_CLASS,nil,WorkDir,StartupInfo,ProcessInformation) then begin try ReadData:=''; repeat {Read from Pipe} BytesRead:=0; ReadResult:=ReadFile(ReadHandle,ReadChar,1,BytesRead,nil); {Check Bytes Read} if BytesRead > 0 then begin {Convert Output} OemToAnsiBuff(@ReadChar,@ReadChar,1); {Check for CR LF} if not(ReadChar in [#10,#13]) then begin ReadData:=ReadData + ReadChar; end else begin {Check for LF} if ReadChar = #10 then begin {Check Marker} if Length(AMarker) <> 0 then begin if ReadData = AMarker then Break; end; {Add Output} AMemo.Lines.Add(ReadData); Application.ProcessMessages; {Reset Data} ReadData:=''; end; end; end; until (not(ReadResult) or (BytesRead = 0)); Result:=True; finally CloseHandle(ProcessInformation.hProcess); CloseHandle(ProcessInformation.hThread); end; end; finally CloseHandle(ReadHandle); CloseHandle(WriteHandle); end; end; end; {==============================================================================} function AddTrailingSlash(const FilePath:String):String; var WorkBuffer:String; begin {} WorkBuffer:=Trim(FilePath); Result:=WorkBuffer; if Length(WorkBuffer) > 0 then begin if WorkBuffer[Length(WorkBuffer)] <> '\' then begin Result:=WorkBuffer + '\'; end; end; end; {==============================================================================} function StripTrailingSlash(const FilePath:String):String; var WorkBuffer:String; begin {} WorkBuffer:=Trim(FilePath); Result:=WorkBuffer; if Length(WorkBuffer) > 0 then begin if WorkBuffer[Length(WorkBuffer)] = '\' then begin Delete(WorkBuffer,Length(WorkBuffer),1); Result:=WorkBuffer; end; end; end; {==============================================================================} function IsWinNT6orAbove:Boolean; {Returns True for WindowsVista(6.0) or higher} var OsVersionInfo:TOSVersionInfo; begin {} Result:=False; FillChar(OsVersionInfo,SizeOf(OsVersionInfo),0); OsVersionInfo.dwOSVersionInfoSize:=SizeOf(OsVersionInfo); if not GetVersionEx(OsVersionInfo) then Exit; if OsVersionInfo.dwPlatformId <> VER_PLATFORM_WIN32_NT then Exit; Result:=(OsVersionInfo.dwMajorVersion >= 6); end; {==============================================================================} {==============================================================================} procedure TfrmMain.FormCreate(Sender: TObject); begin {} {A value to prefix on the path} PathPrefix:=''; {Assume that this is running from <InstallPath>\tools and that the InstallPath will be the folder above} InstallPath:=ExtractFileDir(ExtractFileDir(Application.ExeName)); {The current compiler version} CompilerVersion:='3.1.1'; {Assume the compiler name is fpc.exe} CompilerName:='fpc.exe'; {Assume that the compiler path will be \fpc\<CompilerVersion> under the InstallPath} CompilerPath:=InstallPath + '\fpc\' + CompilerVersion; {Assume that the source path will be \source under the CompilerPath} SourcePath:=CompilerPath + '\source'; {The names of the ARM compiler or cross compiler} ARMCompiler:=''; {The names of the AARCH64 compiler or cross compiler} AARCH64Compiler:=''; BuildRTL:=True; BuildPackages:=True; PlatformARMv6:=True; PlatformARMv7:=True; PlatformARMv8:=True; LoadConfig; end; {==============================================================================} procedure TfrmMain.FormDestroy(Sender: TObject); begin {} end; {==============================================================================} procedure TfrmMain.FormShow(Sender: TObject); var Scale:Double; begin {} chkARMv6.Checked:=PlatformARMv6; chkARMv7.Checked:=PlatformARMv7; chkARMv8.Checked:=PlatformARMv8; {Check PixelsPerInch} if PixelsPerInch > 96 then begin {Calculate Scale} Scale:=(PixelsPerInch / 96); {Disable Anchors} lblMain.Anchors:=[akLeft,akTop]; chkARMv6.Anchors:=[akLeft,akTop]; chkARMv7.Anchors:=[akLeft,akTop]; chkARMv8.Anchors:=[akLeft,akTop]; cmdBuild.Anchors:=[akLeft,akTop]; cmdExit.Anchors:=[akLeft,akTop]; {Resize Form} Width:=Trunc(Width * Scale); Height:=Trunc(Height * Scale); {Move Buttons} cmdBuild.Left:=pnlMain.Width - Trunc(100 * Scale); {907 - 807 = 100} cmdExit.Left:=pnlMain.Width - Trunc(100 * Scale); {907 - 807 = 100} {Enable Anchors} lblMain.Anchors:=[akLeft,akTop,akRight]; chkARMv6.Anchors:=[akLeft,akTop,akRight]; chkARMv7.Anchors:=[akLeft,akTop,akRight]; chkARMv8.Anchors:=[akLeft,akTop,akRight]; cmdBuild.Anchors:=[akTop,akRight]; cmdExit.Anchors:=[akTop,akRight]; end; end; {==============================================================================} procedure TfrmMain.FormHide(Sender: TObject); begin {} end; {==============================================================================} procedure TfrmMain.chkARMv6Click(Sender: TObject); begin {} PlatformARMv6:=chkARMv6.Checked; end; {==============================================================================} procedure TfrmMain.chkARMv7Click(Sender: TObject); begin {} PlatformARMv7:=chkARMv7.Checked; end; {==============================================================================} procedure TfrmMain.chkARMv8Click(Sender: TObject); begin {} PlatformARMv8:=chkARMv8.Checked; end; {==============================================================================} procedure TfrmMain.cmdExitClick(Sender: TObject); begin {} Application.Terminate; end; {==============================================================================} procedure TfrmMain.cmdBuildClick(Sender: TObject); begin {} lblMain.Enabled:=False; lblPlatforms.Enabled:=False; chkARMv6.Enabled:=False; chkARMv7.Enabled:=False; chkARMv8.Enabled:=False; cmdBuild.Enabled:=False; cmdExit.Enabled:=False; try {Clear Memo} mmoMain.Lines.Clear; {Add Banner} mmoMain.Lines.Add('Building Ultibo RTL'); mmoMain.Lines.Add(''); {Add Path Prefix} mmoMain.Lines.Add(' Path Prefix is ' + PathPrefix); mmoMain.Lines.Add(''); {Add Install Path} mmoMain.Lines.Add(' Install Path is ' + InstallPath); mmoMain.Lines.Add(''); {Add Compiler Name} mmoMain.Lines.Add(' Compiler Name is ' + CompilerName); mmoMain.Lines.Add(''); {Add Compiler Path} mmoMain.Lines.Add(' Compiler Path is ' + CompilerPath); mmoMain.Lines.Add(''); {Add Source Path} mmoMain.Lines.Add(' Source Path is ' + SourcePath); mmoMain.Lines.Add(''); {Add ARM Compiler} if Length(ARMCompiler) <> 0 then begin mmoMain.Lines.Add(' ARM Compiler is ' + ARMCompiler); mmoMain.Lines.Add(''); end; {Add AARCH64 Compiler} if Length(AARCH64Compiler) <> 0 then begin mmoMain.Lines.Add(' AARCH64 Compiler is ' + AARCH64Compiler); mmoMain.Lines.Add(''); end; {Create Build File} mmoMain.Lines.Add(' Creating Build Script'); mmoMain.Lines.Add(''); if not CreateBuildFile then begin mmoMain.Lines.Add(' Error: Failed to create build script'); Exit; end; {Execute Build File} mmoMain.Lines.Add(' Executing Build Script'); mmoMain.Lines.Add(''); if not ExecuteBuildFile then begin mmoMain.Lines.Add(' Error: Failed to execute build script'); Exit; end; {Add Footer} mmoMain.Lines.Add(''); mmoMain.Lines.Add('Completed Build'); mmoMain.Lines.Add(''); finally lblMain.Enabled:=True; lblPlatforms.Enabled:=True; chkARMv6.Enabled:=True; chkARMv7.Enabled:=True; chkARMv8.Enabled:=True; cmdBuild.Enabled:=True; cmdExit.Enabled:=True; end; end; {==============================================================================} function TfrmMain.LoadConfig:Boolean; var Section:String; Filename:String; IniFile:TIniFile; begin {} Result:=False; try {Get Filename} Filename:=ChangeFileExt(Application.ExeName,'.ini'); {Check File} if FileExists(Filename) then begin IniFile:=TIniFile.Create(Filename); try Section:='BuildRTL'; {Get PathPrefix} PathPrefix:=IniFile.ReadString(Section,'PathPrefix',PathPrefix); {Get InstallPath} InstallPath:=IniFile.ReadString(Section,'InstallPath',InstallPath); {Get CompilerName} CompilerName:=IniFile.ReadString(Section,'CompilerName',CompilerName); {Get CompilerPath} CompilerPath:=IniFile.ReadString(Section,'CompilerPath',CompilerPath); {Get CompilerVersion} CompilerVersion:=IniFile.ReadString(Section,'CompilerVersion',CompilerVersion); {Get SourcePath} SourcePath:=IniFile.ReadString(Section,'SourcePath',SourcePath); {Get ARMCompiler} ARMCompiler:=IniFile.ReadString(Section,'ARMCompiler',ARMCompiler); {Get AARCH64Compiler} AARCH64Compiler:=IniFile.ReadString(Section,'AARCH64Compiler',AARCH64Compiler); {Get BuildRTL} BuildRTL:=IniFile.ReadBool(Section,'BuildRTL',BuildRTL); {Get BuildPackages} BuildPackages:=IniFile.ReadBool(Section,'BuildPackages',BuildPackages); {Get PlatformARMv6} PlatformARMv6:=IniFile.ReadBool(Section,'PlatformARMv6',PlatformARMv6); {Get PlatformARMv7} PlatformARMv7:=IniFile.ReadBool(Section,'PlatformARMv7',PlatformARMv7); {Get PlatformARMv8} PlatformARMv8:=IniFile.ReadBool(Section,'PlatformARMv8',PlatformARMv8); finally IniFile.Free; end; end; Result:=True; except {} end; end; {==============================================================================} function TfrmMain.CreateBuildFile:Boolean; var Filename:String; WorkBuffer:String; FileStream:TFileStream; begin {} Result:=False; try if Length(SourcePath) = 0 then Exit; if Length(InstallPath) = 0 then Exit; if Length(CompilerName) = 0 then Exit; if Length(CompilerPath) = 0 then Exit; if Length(CompilerVersion) = 0 then Exit; if not(BuildRTL) and not(BuildPackages) then Exit; if not(PlatformARMv6) and not(PlatformARMv7) and not(PlatformARMv8) then Exit; {Get ARM Compiler} if Length(ARMCompiler) = 0 then ARMCompiler:=CompilerName; {Get AARCH64 Compiler} if Length(AARCH64Compiler) = 0 then AARCH64Compiler:=CompilerName; {Get Filename} Filename:=AddTrailingSlash(SourcePath) + '__buildrtl.bat'; mmoMain.Lines.Add(' Build Script is ' + Filename); mmoMain.Lines.Add(''); {Check File} if FileExists(Filename) then begin {Delete File} DeleteFile(Filename); if FileExists(Filename) then Exit; end; {Create File} FileStream:=TFileStream.Create(Filename,fmCreate); try {Add Header} WorkBuffer:=''; WorkBuffer:=WorkBuffer + '@echo off' + LineEnd; WorkBuffer:=WorkBuffer + 'set path=' + PathPrefix + StripTrailingSlash(CompilerPath) + '\bin\i386-win32' + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; {Add Start} WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; WorkBuffer:=WorkBuffer + 'echo ======================Start of Build Script======================' + LineEnd; {Check ARMv6} if PlatformARMv6 then begin {Check RTL} if BuildRTL then begin WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; WorkBuffer:=WorkBuffer + 'echo Building ARMv6 RTL' + LineEnd; WorkBuffer:=WorkBuffer + 'echo ==================' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; {RTL Clean} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'make rtl_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv6'; WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler; WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV6 -CfVFPV2 -CIARM -CaEABIHF -OoFASTMATH"'; WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; {RTL} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'make rtl OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv6'; WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler; WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV6 -CfVFPV2 -CIARM -CaEABIHF -OoFASTMATH"'; WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; {RTL Install} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'make rtl_install CROSSINSTALL=1'; WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler; WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV6 -CfVFPV2 -CIARM -CaEABIHF -OoFASTMATH" OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv6'; WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler; WorkBuffer:=WorkBuffer + ' INSTALL_BASEDIR=' + StripTrailingSlash(CompilerPath); WorkBuffer:=WorkBuffer + ' INSTALL_UNITDIR=' + StripTrailingSlash(CompilerPath) + '/units/armv6-ultibo/rtl' + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; end; {Check Packages} if BuildPackages then begin WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; WorkBuffer:=WorkBuffer + 'echo Building ARMv6 packages' + LineEnd; WorkBuffer:=WorkBuffer + 'echo =======================' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; {RTL Clean (To remove units from \rtl\units)} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'make rtl_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv6'; WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler; WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV6 -CfVFPV2 -CIARM -CaEABIHF -OoFASTMATH"'; WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; {Packages Clean} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'make packages_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv6'; WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler; WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV6 -CfVFPV2 -CIARM -CaEABIHF -OoFASTMATH"'; WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; {Packages} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'make packages OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv6'; WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler; WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV6 -CfVFPV2 -CIARM -CaEABIHF -OoFASTMATH -Fu' + StripTrailingSlash(CompilerPath) + '\units\armv6-ultibo\rtl"'; WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; {Packages Install} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'make packages_install CROSSINSTALL=1'; WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler; WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV6 -CfVFPV2 -CIARM -CaEABIHF -OoFASTMATH" OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv6'; WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler; WorkBuffer:=WorkBuffer + ' INSTALL_BASEDIR=' + StripTrailingSlash(CompilerPath); WorkBuffer:=WorkBuffer + ' INSTALL_UNITDIR=' + StripTrailingSlash(CompilerPath) + '/units/armv6-ultibo/packages' + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; end; end; {Check ARMv7} if PlatformARMv7 then begin {Check RTL} if BuildRTL then begin WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; WorkBuffer:=WorkBuffer + 'echo Building ARMv7 RTL' + LineEnd; WorkBuffer:=WorkBuffer + 'echo ==================' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; {RTL Clean} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'make rtl_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv7a'; WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler; WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV7A -CfVFPV3 -CIARM -CaEABIHF -OoFASTMATH"'; WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; {RTL} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'make rtl OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv7a'; WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler; WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV7A -CfVFPV3 -CIARM -CaEABIHF -OoFASTMATH"'; WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; {RTL Install} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'make rtl_install CROSSINSTALL=1'; WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler; WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV7A -CfVFPV3 -CIARM -CaEABIHF -OoFASTMATH" OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv7a'; WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler; WorkBuffer:=WorkBuffer + ' INSTALL_BASEDIR=' + StripTrailingSlash(CompilerPath); WorkBuffer:=WorkBuffer + ' INSTALL_UNITDIR=' + StripTrailingSlash(CompilerPath) + '/units/armv7-ultibo/rtl' + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; end; {Check Packages} if BuildPackages then begin WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; WorkBuffer:=WorkBuffer + 'echo Building ARMv7 Packages' + LineEnd; WorkBuffer:=WorkBuffer + 'echo =======================' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; {RTL Clean (To remove units from \rtl\units)} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'make rtl_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv7a'; WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler; WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV7A -CfVFPV3 -CIARM -CaEABIHF -OoFASTMATH"'; WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; {Packages Clean} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'make packages_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv7a'; WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler; WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV7A -CfVFPV3 -CIARM -CaEABIHF -OoFASTMATH"'; WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; {Packages} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'make packages OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv7a'; WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler; WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV7A -CfVFPV3 -CIARM -CaEABIHF -OoFASTMATH -Fu' + StripTrailingSlash(CompilerPath) + '\units\armv7-ultibo\rtl"'; WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; {Packages Install} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'make packages_install CROSSINSTALL=1'; WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler; WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV7A -CfVFPV3 -CIARM -CaEABIHF -OoFASTMATH" OS_TARGET=ultibo CPU_TARGET=arm SUBARCH=armv7a'; WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + ARMCompiler; WorkBuffer:=WorkBuffer + ' INSTALL_BASEDIR=' + StripTrailingSlash(CompilerPath); WorkBuffer:=WorkBuffer + ' INSTALL_UNITDIR=' + StripTrailingSlash(CompilerPath) + '/units/armv7-ultibo/packages' + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; end; end; {Check ARMv8} if PlatformARMv8 then begin {Check RTL} if BuildRTL then begin WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; WorkBuffer:=WorkBuffer + 'echo Building ARMv8 RTL' + LineEnd; WorkBuffer:=WorkBuffer + 'echo ==================' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; {RTL Clean} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'make rtl_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=aarch64 SUBARCH=armv8'; WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler; WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV8 -CfVFP -OoFASTMATH"'; WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; {RTL} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'make rtl OS_TARGET=ultibo CPU_TARGET=aarch64 SUBARCH=armv8'; WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler; WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV8 -CfVFP -OoFASTMATH"'; WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; {RTL Install} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'make rtl_install CROSSINSTALL=1'; WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler; WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV8 -CfVFP -OoFASTMATH" OS_TARGET=ultibo CPU_TARGET=aarch64 SUBARCH=armv8'; WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler; WorkBuffer:=WorkBuffer + ' INSTALL_BASEDIR=' + StripTrailingSlash(CompilerPath); WorkBuffer:=WorkBuffer + ' INSTALL_UNITDIR=' + StripTrailingSlash(CompilerPath) + '/units/armv8-ultibo/rtl' + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; end; {Check Packages} if BuildPackages then begin WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; WorkBuffer:=WorkBuffer + 'echo Building ARMv8 Packages' + LineEnd; WorkBuffer:=WorkBuffer + 'echo =======================' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; {RTL Clean (To remove units from \rtl\units)} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'make rtl_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=aarch64 SUBARCH=armv8'; WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler; WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV8 -CfVFP -OoFASTMATH"'; WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; {Packages Clean} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'make packages_clean CROSSINSTALL=1 OS_TARGET=ultibo CPU_TARGET=aarch64 SUBARCH=armv8'; WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler; WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV8 -CfVFP -OoFASTMATH"'; WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; {Packages} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'make packages OS_TARGET=ultibo CPU_TARGET=aarch64 SUBARCH=armv8'; WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler; WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV8 -CfVFP -OoFASTMATH -Fu' + StripTrailingSlash(CompilerPath) + '\units\armv8-ultibo\rtl"'; WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; {Packages Install} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'make packages_install CROSSINSTALL=1'; WorkBuffer:=WorkBuffer + ' FPCFPMAKE=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler; WorkBuffer:=WorkBuffer + ' CROSSOPT="-CpARMV8 -CfVFP -OoFASTMATH" OS_TARGET=ultibo CPU_TARGET=aarch64 SUBARCH=armv8'; WorkBuffer:=WorkBuffer + ' FPC=' + StripTrailingSlash(CompilerPath) + '/bin/i386-win32/' + AARCH64Compiler; WorkBuffer:=WorkBuffer + ' INSTALL_BASEDIR=' + StripTrailingSlash(CompilerPath); WorkBuffer:=WorkBuffer + ' INSTALL_UNITDIR=' + StripTrailingSlash(CompilerPath) + '/units/armv8-ultibo/packages' + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'IF %errorlevel% NEQ 0 GOTO Error' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; end; end; {Add Footer} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; WorkBuffer:=WorkBuffer + 'echo Build RTL completed successfully' + LineEnd; WorkBuffer:=WorkBuffer + 'GOTO End' + LineEnd; {Add Error} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + ':Error' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; WorkBuffer:=WorkBuffer + 'echo Build RTL failed, see above for errors' + LineEnd; {Add End} WorkBuffer:=WorkBuffer + '' + LineEnd; WorkBuffer:=WorkBuffer + ':End' + LineEnd; WorkBuffer:=WorkBuffer + 'echo .' + LineEnd; WorkBuffer:=WorkBuffer + 'echo =======================End of Build Script=======================' + LineEnd; WorkBuffer:=WorkBuffer + 'echo ' + MarkerEnd + LineEnd; WorkBuffer:=WorkBuffer + '' + LineEnd; {Set Size} FileStream.Size:=Length(WorkBuffer); {Write File} FileStream.Position:=0; FileStream.WriteBuffer(PChar(WorkBuffer)^,Length(WorkBuffer)); Result:=True; finally FileStream.Free; end; except on E: Exception do begin mmoMain.Lines.Add(' Error: Exception creating build script - Message: ' + E.Message); end; end; end; {==============================================================================} function TfrmMain.ExecuteBuildFile:Boolean; var Filename:String; begin {} Result:=False; try if Length(SourcePath) = 0 then Exit; if Length(InstallPath) = 0 then Exit; if Length(CompilerName) = 0 then Exit; if Length(CompilerPath) = 0 then Exit; if Length(CompilerVersion) = 0 then Exit; if not(BuildRTL) and not(BuildPackages) then Exit; if not(PlatformARMv6) and not(PlatformARMv7) and not(PlatformARMv8) then Exit; {Get Filename} Filename:=AddTrailingSlash(SourcePath) + '__buildrtl.bat'; mmoMain.Lines.Add(' Build Script is ' + Filename); mmoMain.Lines.Add(''); {Check File} if not FileExists(Filename) then Exit; {Execute Process} if not ExecuteConsoleProcessEx('cmd.exe /c',Filename,SourcePath,MarkerEnd,mmoMain) then Exit; Result:=True; except on E: Exception do begin mmoMain.Lines.Add(' Error: Exception executing build script - Message: ' + E.Message); end; end; end; {==============================================================================} {==============================================================================} end.
{ Updates tangents and bitangents in NIF files, optionally adding them if missing where appropriate. Supports all game NIF formats starting from Morrowind. } unit NifBatchUpdateTangents; //============================================================================ procedure UpdateTangents(aPath: string; aAddIfMissing: Boolean); var TDirectory: TDirectory; // to access member functions i: integer; Nif: TwbNifFile; files: TStringDynArray; f, ext: string; bChanged: Boolean; begin if aPath = '' then Exit; Nif := TwbNifFile.Create; try files := TDirectory.GetFiles(aPath, '*.nif', soAllDirectories); AddMessage('Processing NIF files in "' + aPath + '", press and hold ESC to abort...'); for i := 0 to Pred(Length(files)) do begin f := files[i]; ext := ExtractFileExt(f); // break the files processing loop if Escape is pressed if GetKeyState(VK_ESCAPE) and 128 = 128 then Break; Nif.LoadFromFile(f); if aAddIfMissing then bChanged := Nif.SpellAddUpdateTangents else bChanged := Nif.SpellUpdateTangents; if bChanged then begin Nif.SaveToFile(f); AddMessage('Updated: ' + f); end else AddMessage('Nothing to update: ' + f); end; finally Nif.Free; end; end; //============================================================================ procedure btnSrcClick(Sender: TObject); var edSrc: TLabeledEdit; s: string; begin edSrc := TLabeledEdit(TForm(Sender.Parent).FindComponent('edSrc')); s := SelectDirectory('Select a directory', '', edSrc.Text, nil); if s <> '' then edSrc.Text := s; end; //============================================================================ function Initialize: Integer; var frm: TForm; edSrc: TLabeledEdit; chkAdd: TCheckBox; btnOk, btnCancel, btnSrc: TButton; pnl: TPanel; begin frm := TForm.Create(nil); try frm.Caption := 'Batch Update Tangents'; frm.Width := 500; frm.Height := 170; frm.Position := poMainFormCenter; frm.BorderStyle := bsDialog; edSrc := TLabeledEdit.Create(frm); edSrc.Parent := frm; edSrc.Name := 'edSrc'; edSrc.Left := 12; edSrc.Top := 24; edSrc.Width := frm.Width - 70; edSrc.LabelPosition := lpAbove; edSrc.EditLabel.Caption := 'Folder with *.nif files to update'; edSrc.Text := wbDataPath; btnSrc := TButton.Create(frm); btnSrc.Parent := frm; btnSrc.Top := edSrc.Top - 1; btnSrc.Left := edSrc.Left + edSrc.Width + 6; btnSrc.Width := 32; btnSrc.Height := 22; btnSrc.Caption := '...'; btnSrc.OnClick := btnSrcClick; chkAdd := TCheckBox.Create(frm); chkAdd.Parent := frm; chkAdd.Left := edSrc.Left + 12; chkAdd.Top := edSrc.Top + 32; chkAdd.Width := frm.Width - 60; chkAdd.Caption := 'Add tangents if missing where appropriate'; chkAdd.Checked := True; btnOk := TButton.Create(frm); btnOk.Parent := frm; btnOk.Caption := 'OK'; btnOk.ModalResult := mrOk; btnOk.Left := frm.Width - 176; btnOk.Top := frm.Height - 62; btnCancel := TButton.Create(frm); btnCancel.Parent := frm; btnCancel.Caption := 'Cancel'; btnCancel.ModalResult := mrCancel; btnCancel.Left := btnOk.Left + btnOk.Width + 8; btnCancel.Top := btnOk.Top; pnl := TPanel.Create(frm); pnl.Parent := frm; pnl.Left := 8; pnl.Top := btnOk.Top - 12; pnl.Width := frm.Width - 20; pnl.Height := 2; if frm.ShowModal = mrOk then if edSrc.Text <> '' then UpdateTangents( edSrc.Text, chkAdd.Checked ); finally frm.Free; end; Result := 1; 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) @abstract(Website : http://www.ormbr.com.br) @abstract(Telagram : https://t.me/ormbr) } unit ormbr.dataset.adapter; interface uses DB, Rtti, TypInfo, Classes, SysUtils, StrUtils, Variants, Generics.Collections, /// orm ormbr.criteria, ormbr.bind, ormbr.session.dataset, ormbr.dataset.base.adapter, dbcbr.mapping.classes, dbcbr.types.mapping, dbebr.factory.interfaces; type TDataSetHack = class(TDataSet) end; // M - Object M TDataSetAdapter<M: class, constructor> = class(TDataSetBaseAdapter<M>) private procedure ExecuteCheckNotNull; protected FConnection: IDBConnection; procedure OpenDataSetChilds; override; procedure RefreshDataSetOneToOneChilds(AFieldName: string); override; procedure DoAfterScroll(DataSet: TDataSet); override; procedure DoBeforePost(DataSet: TDataSet); override; procedure DoBeforeDelete(DataSet: TDataSet); override; procedure DoNewRecord(DataSet: TDataSet); override; public constructor Create(AConnection: IDBConnection; ADataSet: TDataSet; APageSize: Integer; AMasterObject: TObject); overload; destructor Destroy; override; procedure NextPacket; override; procedure LoadLazy(const AOwner: M); override; end; implementation uses ormbr.dataset.fields, ormbr.objects.helper, ormbr.rtti.helper, dbcbr.mapping.explorer, dbcbr.mapping.exceptions; { TDataSetAdapter<M> } constructor TDataSetAdapter<M>.Create(AConnection: IDBConnection; ADataSet: TDataSet; APageSize: Integer; AMasterObject: TObject); begin FConnection := AConnection; inherited Create(ADataSet, APageSize, AMasterObject); // Session que será usado pelo Adapter FSession := TSessionDataSet<M>.Create(Self, AConnection, APageSize); end; destructor TDataSetAdapter<M>.Destroy; begin FSession.Free; inherited; end; procedure TDataSetAdapter<M>.DoAfterScroll(DataSet: TDataSet); begin if DataSet.State in [dsBrowse] then if not FOrmDataSet.Eof then OpenDataSetChilds; inherited; end; procedure TDataSetAdapter<M>.DoBeforeDelete(DataSet: TDataSet); var LDataSet: TDataSet; LFor: Integer; begin inherited DoBeforeDelete(DataSet); // Alimenta a lista com registros deletados FSession.DeleteList.Add(M.Create); TBind.Instance .SetFieldToProperty(FOrmDataSet, TObject(FSession.DeleteList.Last)); // Deleta registros de todos os DataSet filhos EmptyDataSetChilds; // Exclui os registros dos NestedDataSets linkados ao FOrmDataSet // Recurso usado em banco NoSQL for LFor := 0 to TDataSetHack(FOrmDataSet).NestedDataSets.Count - 1 do begin LDataSet := TDataSetHack(FOrmDataSet).NestedDataSets.Items[LFor]; LDataSet.DisableControls; LDataSet.First; try repeat LDataSet.Delete; until LDataSet.Eof; finally LDataSet.EnableControls; end; end; end; procedure TDataSetAdapter<M>.DoBeforePost(DataSet: TDataSet); begin inherited DoBeforePost(DataSet); // Rotina de validação se o campo foi deixado null ExecuteCheckNotNull; end; procedure TDataSetAdapter<M>.ExecuteCheckNotNull; var LColumn: TColumnMapping; LColumns: TColumnMappingList; begin LColumns := TMappingExplorer.GetMappingColumn(FCurrentInternal.ClassType); for LColumn in LColumns do begin if LColumn.IsNoInsert then Continue; if LColumn.IsNoUpdate then Continue; if LColumn.IsJoinColumn then Continue; if LColumn.IsNoValidate then Continue; if LColumn.IsNullable then Continue; if LColumn.FieldType in [ftDataSet, ftADT, ftBlob] then Continue; if LColumn.IsNotNull then if FOrmDataSet.FieldValues[LColumn.ColumnName] = Null then raise EFieldValidate.Create(FCurrentInternal.ClassName + '.' + LColumn.ColumnName, FOrmDataSet.FieldByName(LColumn.ColumnName).ConstraintErrorMessage); end; end; procedure TDataSetAdapter<M>.OpenDataSetChilds; var LDataSetChild: TDataSetBaseAdapter<M>; LSQL: String; LObject: TObject; begin inherited; if not FOrmDataSet.Active then Exit; if FOrmDataSet.RecordCount = 0 then Exit; // Se Count > 0, identifica-se que é o objeto é o Master if FMasterObject.Count = 0 then Exit; // Popula o objeto com o registro atual do dataset Master para filtar // os filhos com os valores das chaves. LObject := M.Create; try TBind.Instance.SetFieldToProperty(FOrmDataSet, LObject); for LDataSetChild in FMasterObject.Values do begin LSQL := LDataSetChild.FSession.SelectAssociation(LObject); // Monta o comando SQL para abrir registros filhos if Length(LSQL) > 0 then LDataSetChild.OpenSQLInternal(LSQL); end; finally LObject.Free; end; end; procedure TDataSetAdapter<M>.LoadLazy(const AOwner: M); var LOwnerObject: TDataSetBaseAdapter<M>; LSQL: String; begin inherited; if AOwner <> nil then begin if FOwnerMasterObject <> nil then Exit; if FOrmDataSet.Active then Exit; SetMasterObject(AOwner); LOwnerObject := TDataSetBaseAdapter<M>(FOwnerMasterObject); if LOwnerObject <> nil then begin // Popula o objeto com o registro atual do dataset Master para filtar // os filhos com os valores das chaves. TBind.Instance .SetFieldToProperty(LOwnerObject.FOrmDataSet, TObject(LOwnerObject.FCurrentInternal)); LSQL := FSession.SelectAssociation(LOwnerObject.FCurrentInternal); if Length(LSQL) > 0 then OpenSQLInternal(LSQL); end; end else begin if FOwnerMasterObject = nil then Exit; if not TDataSetBaseAdapter<M>(FOwnerMasterObject).FOrmDataSet.Active then Exit; SetMasterObject(nil); Close; end; end; procedure TDataSetAdapter<M>.NextPacket; var LBookMark: TBookmark; begin inherited; if FSession.FetchingRecords then Exit; FOrmDataSet.DisableControls; // Desabilita os eventos dos TDataSets DisableDataSetEvents; LBookMark := FOrmDataSet.Bookmark; try FSession.NextPacket; finally FOrmDataSet.GotoBookmark(LBookMark); FOrmDataSet.EnableControls; EnableDataSetEvents; end; end; procedure TDataSetAdapter<M>.RefreshDataSetOneToOneChilds(AFieldName: string); var LAssociations: TAssociationMappingList; LAssociation: TAssociationMapping; LDataSetChild: TDataSetBaseAdapter<M>; LSQL: String; LObject: TObject; begin inherited; if not FOrmDataSet.Active then Exit; LAssociations := TMappingExplorer.GetMappingAssociation(FCurrentInternal.ClassType); if LAssociations = nil then Exit; for LAssociation in LAssociations do begin if not (LAssociation.Multiplicity in [OneToOne, ManyToOne]) then Continue; // Checa se o campo que recebeu a alteração, é um campo de associação // Se for é feito um novo select para atualizar a propriedade associada. if LAssociation.ColumnsName.IndexOf(AFieldName) = -1 then Continue; if not FMasterObject.ContainsKey(LAssociation.ClassNameRef) then Continue; LDataSetChild := FMasterObject.Items[LAssociation.ClassNameRef]; if LDataSetChild = nil then Continue; // Popula o objeto com o registro atual do dataset Master para filtar // os filhos com os valores das chaves. LObject := M.Create; try TBind.Instance.SetFieldToProperty(FOrmDataSet, LObject); LSQL := LDataSetChild.FSession.SelectAssociation(LObject); if Length(LSQL) > 0 then LDataSetChild.OpenSQLInternal(LSQL); finally LObject.Free; end; end; end; procedure TDataSetAdapter<M>.DoNewRecord(DataSet: TDataSet); begin // Limpa registros do dataset em memória antes de receber os novos registros EmptyDataSetChilds; inherited DoNewRecord(DataSet); end; end.
Program Pilha_Dinamica; Uses Crt; Type Elem=Char; Pilha = ^Nodo; Nodo = Record Obj : Elem; Prox:Pilha; end; Var Cabeca: Pilha; Procedure Init; Begin Cabeca:=nil; End; Function IsEmpty(Var Cabeca:Pilha):Boolean; Begin If Cabeca=nil Then IsEmpty:=True Else IsEmpty:=False; End; Procedure Push (Var Cabeca:Pilha; X:elem); Var N:Pilha; Begin New (N); N^.Obj := x; N^.Prox := cabeca; Cabeca:=N; end; Function Pop (Var Cabeca:Pilha): Elem; Var Q:Pilha; Begin If not IsEmpty (Cabeca) Then Begin Pop:= Cabeca^.Obj; Q:=Cabeca; Cabeca:=Cabeca^.Prox; Dispose(Q); End Else Writeln ('Pilha Underflow!!'); End; Function Top (Var Cabeca:Pilha): Elem; Begin If not IsEmpty (Cabeca) Then Top:= Cabeca^.Obj Else Writeln ('Pilha Underflow!!'); End; Procedure Listar(Var Cabeca:Pilha); Var P:Pilha; i:integer; Begin Clrscr; Gotoxy(23,3); Writeln('Elementos inseridos na Pilha'); Writeln; P:= cabeca; i:=0; While (p<> nil) do Begin Write (P^.Obj, ' '); P:=P^.prox; i:=i+1; End; Writeln; Writeln; Writeln ('A pilha tem ', i, ' Elementos'); Gotoxy(24,25); Write ('Tecle <Enter> para voltar ao Programa Principal'); Readln; End; Procedure Insere; Var x:Elem; Begin Clrscr; Gotoxy(23,3); Writeln ('Inserir Elementos'); Writeln; Writeln ('Digite . Para encerrar'); Repeat Readln (x); If (x <> '.') then Push(Cabeca,x); Until (x='.') End; Procedure Elimina; Var Resp:char; K:elem; Begin Resp:='S'; While (Resp='S') or (Resp='s') do Begin Clrscr; Gotoxy(30,3); Writeln ('Eliminar Elementos'); k:= Pop(Cabeca); Gotoxy (20,15); Writeln ('Elemento ',k,' Foi Eliminado com Sucesso'); Gotoxy(24,25); Write ('Deseja Eliminar outro elemento?(S/N): '); Readln(Resp); End; End; Begin While True do Begin Clrscr; Writeln ('1. Inicializa Pilha'); Writeln ('2. Insere Elementos na Pilha'); Writeln ('3. Eliminar Elementos na Pilha'); Writeln ('4. Listar Elementos da Pilha'); Writeln ('5. Finalizar'); Writeln; Writeln ('Opcao: '); Case Readkey of '1':Begin Clrscr; Init; Gotoxy(20,10); Writeln ('Pilha Inicializada...'); Gotoxy(24,25); Write('Tecle <Enter> para voltar ao Menu Principal'); Readln; End; '2':Insere; '3':Elimina; '4':Listar(Cabeca); '5':Halt; End; End; End.
unit Search; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls; type TSearchDialog = class(TForm) CancelButton: TButton; CaseSensitiveCheckBox: TCheckBox; DirectionRadioGroup: TRadioGroup; OkButton: TButton; OptionsGroupBox: TGroupBox; SearchForComboBox: TComboBox; SearchForLabel: TLabel; WholeWordsCheckBox: TCheckBox; procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormDestroy(Sender: TObject); procedure SearchForComboBoxChange(Sender: TObject); private function GetSearchBackwards: Boolean; function GetSearchCaseSensitive: Boolean; function GetSearchText: string; function GetSearchWholeWords: Boolean; public property SearchBackwards: Boolean read GetSearchBackwards; property SearchCaseSensitive: Boolean read GetSearchCaseSensitive; property SearchText: string read GetSearchText; property SearchWholeWords: Boolean read GetSearchWholeWords; end; function SearchDialog(Sender: TComponent): TSearchDialog; implementation {$R *.DFM} uses Common; var FSearchDialog: TSearchDialog; function SearchDialog(Sender: TComponent): TSearchDialog; begin if FSearchDialog = nil then FSearchDialog := TSearchDialog.Create(Sender); Result := FSearchDialog; end; procedure TSearchDialog.FormDestroy(Sender: TObject); begin FSearchDialog := nil; end; function TSearchDialog.GetSearchBackwards: Boolean; begin Result := DirectionRadioGroup.ItemIndex = 1; end; function TSearchDialog.GetSearchCaseSensitive: Boolean; begin Result := CaseSensitiveCheckBox.Checked; end; function TSearchDialog.GetSearchText: string; begin Result := SearchForComboBox.Text; end; function TSearchDialog.GetSearchWholeWords: Boolean; begin Result := WholeWordsCheckBox.Checked; end; procedure TSearchDialog.SearchForComboBoxChange(Sender: TObject); begin OkButton.Enabled := Trim(SearchForComboBox.Text) <> ''; end; procedure TSearchDialog.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if ModalResult = mrOK then InsertTextToCombo(SearchForComboBox); end; end.
unit uCMDLineOptions; {***************************************************************************} { } { VSoft.CommandLine } { } { Copyright (C) 2014 Vincent Parrett } { } { vincent@finalbuilder.com } { http://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} interface type TCMDLineOptions = class public class var NomeDB : string; Server : string; User : string; // -- serve per connessione con client tradizionali Pswd : string; // -- serve per connessione con client tradizionali Porta : integer; Debug : boolean; Uri: string; UrlUpd: string; WSS: string; WSP: integer; Doc: integer; // UDP: boolean; // UrlUser : string; // UrlPswd : string; // DB1 : string; // DB2 : string; (* ToDo Host : string; Site : string; *) class function ReadCMDParameters: boolean; end; implementation uses VSoft.CommandLine.Options, FMX.Overbyte.IniFiles, VSoft.CommandLine.Parser, System.Classes, System.SysUtils, Vcl.Dialogs, uCMDLineConfig, System.ioutils; class function TCMDLineOptions.ReadCMDParameters: boolean; const nEscl = 4; pEscl: array[1..nEscl] of string = ( '/GUI', '/Install', '/Uninstall', '/Silent' ); var parseresult: ICommandLineParseResult; ErrText: string; parser : ICommandLineParser; sList : TStringList; i : integer; FIniFile: TIniFile; z: integer; escluso: boolean; LogFileName: string; function ValutaErrori: boolean; begin if parseresult.HasErrors then begin ErrText := parseresult.ErrorText + chr(10) + 'Usage :'; TOptionsRegistry.PrintUsage( procedure(value : string) begin ErrText := ErrText + value + chr(10); end); ShowMessage( ErrText ); result := false; end else result := True; end; begin try parser := TCommandLineParser.Create(TOptionsRegistry.NameValueSeparator); LogFileName := TPath.ChangeExtension(GetModuleName(HInstance),'.config'); FIniFile := TIniFile.Create(LogFileName); sList := TStringList.Create; try for i := 1 to ParamCount do begin // -- escludo i parametri che servono per l'installazione dei servizi z:=1; repeat escluso := (CompareText(ParamStr(i), pEscl[z])=0); z := z+1; until escluso or (z>nEscl); if not escluso then sList.Add(ParamStr(i)); end; (* if (sList.Count=0) and FileExists(FIniFile.FileName) then begin sList.Add('-options:'+FIniFile.FileName); end; parseresult := TOptionsRegistry.Parse(sList); *) result := True; if (sList.Count>0) then begin parseresult := TOptionsRegistry.Parse(sList); result := ValutaErrori; end; if result and FileExists(FIniFile.FileName) then begin sList.Clear; sList.Add('-options:'+FIniFile.FileName); parseresult := TOptionsRegistry.Parse(sList); result := ValutaErrori; end; finally sList.Free; FIniFile.Free; end; except on E: Exception do begin ShowMessage( E.ClassName + ': ' + E.Message ); result := false; end; end; end; end.
program testif01(output); begin if 3 < 5 then writeln('three is less than five'); if 7 > 2 then begin writeln('seven is greater than two'); writeln('that is what I said!'); end; if 42 >= 44 then writeln('oopsie this should not show') else writeln('forty-two is not greater than or equal to 44'); end.
{* 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 TurboPower Orpheus *} {* *} {* The Initial Developer of the Original Code is Roman Kassebaum *} {* *} {* *} {* Contributor(s): *} {* Roman Kassebaum *} {* *} {* ***** END LICENSE BLOCK ***** *} unit TestOVCPlb; interface uses TestFramework; type TTestOVCPlb = class(TTestCase) published procedure TestAsString; procedure TestClear; end; implementation uses OvcPlb; { TTestOVCPlb } procedure TTestOVCPlb.TestAsString; const cSomeString = 'blabla'; cMask = 'XXXXXX'; //Same Length as cSomeString var pLabel: TOvcPictureLabel; begin pLabel := TOvcPictureLabel.Create(nil); try pLabel.PictureMask := cMask; pLabel.AsString := cSomeString; CheckEquals(pLabel.Caption, cSomeString); finally pLabel.Free; end; end; procedure TTestOVCPlb.TestClear; const cSomeString = 'blabla'; var pLabel: TOvcPictureLabel; bExcept: Boolean; begin pLabel := TOvcPictureLabel.Create(nil); try pLabel.AsString := cSomeString; pLabel.Clear; try //This now raises an access violation bExcept := False; pLabel.AsBoolean := True; except bExcept := True; end; CheckFalse(bExcept); finally pLabel.Free; end; end; initialization RegisterTest(TTestOVCPlb.Suite); end.
program ejer1; const valorAlto= 999; type empleado = record codigo: integer; nombre: String; monto: real; end; arc_empleado = file of empleado; arc_maestro = file of empleado; {-------LEO LA INFORMACION DEL EMPLEADO SI NO ES END OF FILE-------} procedure leer (var arc_e: arc_empleado; var e: empleado); begin if (not eof(arc_e)) then read(arc_e, e) else e.codigo := valorAlto; end; {-------RECORRO EL ARCHIVO EMPLEADO Y CARGO EL ARCHIVO MAESTRO-------} procedure recorrido_carga(var arc_e: arc_empleado; var arc_m: arc_maestro); var e, e2: empleado; begin reset(arc_e); reset(arc_m); leer(arc_e, e); while(e.codigo <> valorAlto) do begin read(arc_m, e2); while(e.codigo = e2.codigo) do begin e2.monto := e2.monto + e.monto; leer(arc_e, e); end; seek(arc_m, filepos(arc_m)-1); write(arc_m, e2); end; close(arc_e); close(arc_m); writeln('Archivo maestro cargado'); writeln(); end; {-------------MOSTRAR EN PANTALLA EL ARCHIVO MAESTRO-----------------} procedure imprimir_arc_maestro(var arc_m: arc_maestro); var e: empleado; begin reset(arc_m); writeln('ARCHIVO MAESTRO'); while(not eof(arc_m)) do begin read(arc_m, e); writeln(); writeln('Codigo: ', e.codigo); writeln('Nombre: ', e.nombre); writeln('Monto: ', e.monto:2:2); writeln('-------------------------'); end; close(arc_m); end; {---------MOSTRAR EN PANTALLA EL ARCHIVO EMPLEADO----------} procedure imprimir_arc_empleado(var arc_e: arc_empleado); var e: empleado; begin reset(arc_e); writeln('ARCHIVO EMPLEADO'); while(not eof(arc_e)) do begin read(arc_e, e); writeln(); writeln('Codigo: ', e.codigo); writeln('Nombre: ', e.nombre); writeln('Monto: ', e.monto:2:2); writeln('-------------------------'); end; close(arc_e); end; {--------------- LEER EMPLEADOS ---------------} procedure leer_empleado(var e: empleado); begin write('Codigo: '); readln(e.codigo); if (e.codigo <> -1) then begin write('Nombre: '); readln(e.nombre); write('Monto: '); readln(e.monto); writeln('-------------'); end; end; {-------------------- CARGAR ARCHIVO MAESTRO --------------} procedure cargar_archivo_maestro(var arc: arc_maestro); var e: empleado; begin rewrite(arc); writeln('COMO PRECONDICION DEBEN ESTAR ORDENADOS POR CODIGO, Y TIENE QUE HABER UN CODIGO POR EMPLEADO'); writeln('COMO ES EL ARCHIVO MAESTRO DEBEN ESTAR UNA SOLA VEZ CADA EMPLEADO'); writeln(); leer_empleado(e); while(e.codigo <> -1) do begin write(arc, e); leer_empleado(e); end; close(arc); end; {------------------ CARGAR ARCHIVO EMPLEADO -----------------} procedure cargar_archivo_empleado(var arc: arc_empleado); var e: empleado; begin rewrite(arc); writeln('COMO PRECONDICION DEBEN ESTAR ORDENADOS POR CODIGO'); writeln('COMO PRECONDICION EL EMPLEADO DETALLE DEBE ESTAR EN EL ARCHIVO MAESTRO'); writeln(); leer_empleado(e); while(e.codigo <> -1) do begin write(arc, e); leer_empleado(e); end; close(arc); end; {-----------------PROGRAMA PRINCIPAL---------------------} var arc_e: arc_empleado; arc_m: arc_maestro; begin assign(arc_e, 'archivoEmpleadoEj1'); assign(arc_m, 'archivoMaestroEj1'); cargar_archivo_maestro(arc_m); cargar_archivo_empleado(arc_e); imprimir_arc_empleado(arc_e); recorrido_carga(arc_e, arc_m); imprimir_arc_maestro(arc_m); end.
unit Rice.MongoFramework.Connection; interface uses System.SysUtils, System.Classes, MongoWire.MongoWire; type TConnectionMongo = class(TPersistent) strict private class var FMongoWire: TMongoWire; class function GetInstance(const pDbName: string = 'teste'; pServer: string = 'localhost'; const pPort: Integer = 27017): TMongoWire; class function Exists(): Boolean; public class function GetConnection(): TMongoWire; class constructor Create(); class destructor Destroy(); end; implementation { TConnectionMongo } class constructor TConnectionMongo.Create; begin FMongoWire := GetInstance(); end; class destructor TConnectionMongo.Destroy; begin inherited; if (FMongoWire <> nil) then FreeAndNil(FMongoWire); end; class function TConnectionMongo.Exists: Boolean; begin Result := (GetConnection <> nil); end; class function TConnectionMongo.GetConnection: TMongoWire; begin Result := FMongoWire; end; class function TConnectionMongo.GetInstance(const pDbName: string; pServer: string; const pPort: Integer): TMongoWire; begin if (Exists()) then GetConnection().Close(); Result := TMongoWire.Create(pDbName); Result.Open(pServer, pPort); end; end.
{ ID: a_zaky01 PROG: latin LANG: PASCAL } var n,i:integer; ans:int64; row,col:array[1..8,1..8] of boolean; label closefile; function latin(r,c:integer):int64; var k:integer; temp:int64; begin if c>n then exit(latin(r+1,2)); if r=n then exit(1); latin:=0; for k:=1 to n do if not row[r,k] and not col[c,k] then begin row[r,k]:=true; col[c,k]:=true; temp:=latin(r,c+1); latin:=latin+temp; row[r,k]:=false; col[c,k]:=false; end; end; procedure generate(pos,factor:integer); var i:integer; begin if pos=n then begin for i:=1 to n do if not row[2][i] then break; if i=n then exit; row[2][i]:=true; col[n][i]:=true; ans:=ans+factor*latin(3,2); row[2][i]:=false; col[n][i]:=false; exit; end; for i:=1 to n do if not row[2][i] and not col[pos][i] then begin row[2][i]:=true; col[pos][i]:=true; if i>pos then factor:=factor*(n-pos); generate(pos+1,factor); row[2][i]:=false; col[pos][i]:=false; if i>pos then exit; end; end; begin assign(input,'latin.in'); assign(output,'latin.out'); reset(input); rewrite(output); readln(n); ans:=0; //first we exclude cases for n=1 and 2, as my code will not work for them if n<=2 then begin writeln(1); goto closefile; end; ans:=0; for i:=1 to n do row[1,i]:=true; for i:=1 to n do row[i,i]:=true; for i:=1 to n do col[i,i]:=true; generate(2,1); { writeln(count); for i:=1 to count do begin for j:=1 to n do write(tab[i][j]); writeln(' ',f[i]); end; ans:=0; for i:=1 to n do row[1,i]:=true; for i:=1 to n do row[i,i]:=true; for i:=1 to count do begin fillchar(row[2],sizeof(row[2]),false); fillchar(col,sizeof(col),false); for j:=1 to n do col[j,j]:=true; for j:=1 to n do begin row[2][tab[i][j]]:=true; col[j][tab[i][j]]:=true; end; ans:=ans+f[i]*latin(3,2); end; } for i:=1 to n-1 do ans:=ans*i; writeln(ans); closefile: close(input); close(output); end.
unit Rice.Example.Aluno.Domain; interface Uses Rice.MongoFramework.CustomAtributeEntity, Rice.MongoFramework.GenericEntity, Rice.Example.Nota.Domain, System.SysUtils; type // nome da classe de entidade [DocumentName('aluno')] TAluno = class(TGenericEntity) private FMatricula: string; FNotas: TNotas; FNome: string; FEndereco: string; FId: string; public [IdField('Id')] property Id:string read FId write FId; property Nome:string read FNome write FNome; property Endereco:string read FEndereco write FEndereco; property Matricula: string read FMatricula write FMatricula; property Notas: TNotas read FNotas write FNotas; constructor Create(); destructor Destroy; override; end; implementation { TAluno } constructor TAluno.Create; begin FNotas := TNotas.Create; end; destructor TAluno.Destroy; begin FreeAndNil(FNotas); inherited; end; end.
unit UFormConnPc; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, RzTabs, StdCtrls, ExtCtrls, siComp, UMainForm; type TfrmConnComputer = class(TForm) pcMain: TRzPageControl; tsConnToOther: TRzTabSheet; tsConnByOther: TRzTabSheet; Image1: TImage; Label1: TLabel; Label2: TLabel; edtIp: TEdit; Label3: TLabel; edtPort: TEdit; btnOK: TButton; btnCancel: TButton; Panel1: TPanel; GroupBox1: TGroupBox; edtLanIp: TEdit; Label4: TLabel; Label6: TLabel; edtLanPort: TEdit; Panel2: TPanel; GroupBox2: TGroupBox; Label5: TLabel; edtInternetIp: TEdit; Label7: TLabel; edtInternetPort: TEdit; siLang_frmConnComputer: TsiLang; procedure FormShow(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure edtIpKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edtPortKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public procedure ShowConnToPc; procedure ShowDnsError( Ip, Port : string ); end; var DefaultPort_ConnPc : string = '9595'; var frmConnComputer: TfrmConnComputer; implementation uses UFormSetting, UNetworkControl, UMyUtil; {$R *.dfm} procedure TfrmConnComputer.btnCancelClick(Sender: TObject); begin Close end; procedure TfrmConnComputer.btnOKClick(Sender: TObject); var Ip, Port : string; ErrorStr : string; AdvanceNetworkConnHandle : TAdvanceNetworkConnHandle; begin Ip := edtIp.Text; Port := edtPort.Text; // 输入信息 不能为空 ErrorStr := ''; if Ip = '' then ErrorStr := frmSetting.siLang_frmSetting.GetText( 'InputDomain' ) else if Port = '' then ErrorStr := frmSetting.siLang_frmSetting.GetText( 'InputPassword' ); // 出错 if ErrorStr <> '' then begin MyMessageBox.ShowError( Self.Handle, ErrorStr ); Exit; end; // 添加 并 选择 AdvanceNetworkConnHandle := TAdvanceNetworkConnHandle.Create( ip, Port ); AdvanceNetworkConnHandle.Update; AdvanceNetworkConnHandle.Free; Close; end; procedure TfrmConnComputer.ShowConnToPc; begin edtIp.Clear; edtPort.Text := DefaultPort_ConnPc; Show; end; procedure TfrmConnComputer.ShowDnsError( Ip, Port : string ); begin edtIp.Text := Ip; edtPort.Text := Port; Show; end; procedure TfrmConnComputer.edtIpKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_Return then selectnext(twincontrol(sender),true,true); end; procedure TfrmConnComputer.edtPortKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_Return then btnOK.Click; end; procedure TfrmConnComputer.FormShow(Sender: TObject); begin edtLanIp.Text := frmSetting.cbbIP.Text; edtLanPort.Text := frmSetting.edtPort.Text; edtInternetIp.Text := frmSetting.edtInternetIp.Text; edtInternetPort.Text := frmSetting.edtInternetPort.Text; pcMain.ActivePage := tsConnToOther; end; end.