text
stringlengths
14
6.51M
unit Exemplo7_1; interface uses System.Classes, System.SysUtils, Xml.XMLDoc, Xml.XMLIntf, System.Json, Data.DBXJSONReflect, Exemplo7; type TExportadorFichaUsuarioTxt = class(TInterfacedObject, IExportadorFichaUsuario) public procedure Exportar(pFichaUsuario: IFichaUsuario; pArquivo: string); end; TExportadorFichaUsuarioXML = class(TInterfacedObject, IExportadorFichaUsuario) public procedure Exportar(pFichaUsuario: IFichaUsuario; pArquivo: string); end; TExportadorFichaUsuarioJson = class(TInterfacedObject, IExportadorFichaUsuario) public procedure Exportar(pFichaUsuario: IFichaUsuario; pArquivo: string); end; implementation { TExportaFichaUsuarioTxt } procedure TExportadorFichaUsuarioTxt.Exportar(pFichaUsuario: IFichaUsuario; pArquivo: string); var lTexto : TStringList; begin lTexto := TStringList.Create; try lTexto.Add('Código: '+pFichaUsuario.GetCodigo.ToString); lTexto.Add('Nome: ' +pFichaUsuario.GetNome); lTexto.Add('Data: ' +FormatDateTime('DD/MM/YYYY',pFichaUsuario.GetData)); lTexto.Add('Cargo: ' +pFichaUsuario.GetCargo); lTexto.SaveToFile(pArquivo); finally lTexto.Free; end; end; { TExportaFichaUsuarioXML } procedure TExportadorFichaUsuarioXML.Exportar(pFichaUsuario: IFichaUsuario; pArquivo: string); var lXml: IXMLDocument; lNode: IXMLNode; begin lXml := TXmlDocument.Create(nil); lXml.Active := True; lXml.Version := '1.0'; lXml.Encoding:= 'UTF-8'; lNode := lXml.AddChild('Ficha'); lNode.AddChild('Codigo').NodeValue := pFichaUsuario.GetCodigo; lNode.AddChild('Nome').NodeValue := pFichaUsuario.GetNome; lNode.AddChild('Data').NodeValue := pFichaUsuario.GetData; lNode.AddChild('Cargo').NodeValue := pFichaUsuario.GetCargo; lXml.SaveToFile(pArquivo); end; { TExportaFichaUsuarioJson } procedure TExportadorFichaUsuarioJson.Exportar(pFichaUsuario: IFichaUsuario; pArquivo: string); var lJson : TJsonValue; lJSONMarshal: TJSONMarshal; lTexto : TStringList; begin lJSONMarshal := TJSONMarshal.Create(TJSONConverter.Create); try lJson := lJSONMarshal.Marshal(TObject(pFichaUsuario)); lTexto := TStringList.Create; try lTexto.Text := lJson.ToString; lTexto.SaveToFile(pArquivo); finally lTexto.Free; end; finally lJSONMarshal.Free; lJson.Free; end; end; end.
unit Dialog.QueryBuilder; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Actions, System.Types, Vcl.ActnList, Vcl.StdCtrls, Vcl.Controls, Vcl.ExtCtrls, Vcl.Graphics, Vcl.Forms, Vcl.Dialogs; type TDialogQueryBuilder = class(TForm) pnTables: TPanel; pnCommands: TPanel; Label1: TLabel; cbxMainTables: TComboBox; lbxJoinTables: TListBox; Label2: TLabel; mmSqlPreview: TMemo; // ------------------------------------------------------------------ // Actions ActionList1: TActionList; actUseSQL: TAction; actCancel: TAction; actDemoSelect: TAction; actMainTableSelected: TAction; actJoinTableSelected: TAction; // ------------------------------------------------------------------ Button1: TButton; Button2: TButton; Button3: TButton; tmrReady: TTimer; procedure FormCreate(Sender: TObject); procedure actCancelExecute(Sender: TObject); procedure actDemoSelectExecute(Sender: TObject); procedure actJoinTableSelectedExecute(Sender: TObject); procedure actMainTableSelectedExecute(Sender: TObject); procedure actUseSQLExecute(Sender: TObject); procedure actUseSQLUpdate(Sender: TObject); procedure cbxTablesMainChange(Sender: TObject); procedure tmrReadyTimer(Sender: TObject); private FTables: TArray<String>; procedure PaintBox1Paint(Sender: TObject); procedure DrawInfoListBoxNotImplemented(APaintBox: TPaintBox); public class function Execute: string; end; implementation {$R *.dfm} uses DataModule.Main, App.AppInfo, Helper.TFDConnection; class function TDialogQueryBuilder.Execute: string; var dlg: TDialogQueryBuilder; mr: Integer; begin dlg := TDialogQueryBuilder.Create(Application); Result := ''; try mr := dlg.ShowModal; if mr = mrOK then Result := dlg.mmSqlPreview.Text; finally dlg.Free; end; end; procedure TDialogQueryBuilder.FormCreate(Sender: TObject); var s: String; begin FTables := DataModule1.GetConnection.GetTableNamesAsArray; // ------------------------------------------------------------------- // Configure dialog controls // ------------------------------------------------------------------- mmSqlPreview.Align := alClient; mmSqlPreview.Text := ''; // ------------------------------------------------------------------- // Configure cbxMainTables // ------------------------------------------------------------------- cbxMainTables.OnChange := nil; cbxMainTables.Style := csDropDownList; cbxMainTables.AddItem('<select object>', nil); cbxMainTables.ItemIndex := 0; cbxMainTables.DropDownCount := 25; for s in FTables do cbxMainTables.Items.Add(s); cbxMainTables.OnChange := cbxTablesMainChange; // ------------------------------------------------------------------- // Not implemented join tables selection // ------------------------------------------------------------------- lbxJoinTables.Visible := False; with TPaintBox.Create(Self) do begin; AlignWithMargins := True; Align := alClient; OnPaint := PaintBox1Paint; Parent := pnTables; end; end; // ------------------------------------------------------------------------ // Actions // ------------------------------------------------------------------------ procedure TDialogQueryBuilder.actDemoSelectExecute(Sender: TObject); var sql: string; begin sql := 'SELECT Orders.OrderID, ' + sLineBreak + ' Orders.CustomerID, Customers.CompanyName, Orders.EmployeeID, ' + sLineBreak + ' Employees.FirstName||'' ''||Employees.LastName EmployeeName, ' + sLineBreak + ' Orders.OrderDate, Orders.RequiredDate, Orders.ShippedDate, ' + sLineBreak + ' Orders.ShipVia, Orders.Freight ' + sLineBreak + 'FROM {id Orders} Orders ' + sLineBreak + ' INNER JOIN {id Employees} Employees ' + sLineBreak + ' ON Orders.EmployeeID = Employees.EmployeeID ' + sLineBreak + ' INNER JOIN {id Customers} Customers ' + sLineBreak + ' ON Orders.CustomerID = Customers.CustomerID ' + sLineBreak + 'WHERE {year(OrderDate)} = 1997 and {month (OrderDate)} = 09' + sLineBreak + 'ORDER BY Orders.OrderID '; mmSqlPreview.Text := sql; ModalResult := mrOK; end; procedure TDialogQueryBuilder.actJoinTableSelectedExecute(Sender: TObject); begin // TODO: Implementation required end; procedure TDialogQueryBuilder.actMainTableSelectedExecute(Sender: TObject); var aTableName: String; aFields: TArray<String>; fldName: String; FieldCount: Integer; sFieldsList: string; begin if cbxMainTables.ItemIndex > 0 then begin aTableName := cbxMainTables.Text; aFields := DataModule1.GetConnection.GetFieldNamesAsArray(aTableName); FieldCount := Length(aFields); mmSqlPreview.Clear; if FieldCount > 0 then begin sFieldsList := ''; for fldName in aFields do begin if sFieldsList = '' then sFieldsList := fldName else sFieldsList := sFieldsList + ', ' + fldName; end; mmSqlPreview.Lines.Add('SELECT '); mmSqlPreview.Lines.Add(' ' + sFieldsList + ' '); mmSqlPreview.Lines.Add('FROM '); mmSqlPreview.Lines.Add(' ' + aTableName); end; end; // TODO: Add foreign keys analysis for table aTableName (comments below) // it looks that it requires additional list with objects // * list of TTableForeignKey (FKName, FKTableName, [ReferenceFields]) // * basic version: just foreign tables names end; procedure TDialogQueryBuilder.actUseSQLExecute(Sender: TObject); begin ModalResult := mrOK; end; procedure TDialogQueryBuilder.actUseSQLUpdate(Sender: TObject); begin actUseSQL.Enabled := Trim(mmSqlPreview.Text) <> ''; end; procedure TDialogQueryBuilder.actCancelExecute(Sender: TObject); begin // TODO: Add veryfication if something is build? ModalResult := mrCancel; end; // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ procedure TDialogQueryBuilder.cbxTablesMainChange(Sender: TObject); begin actMainTableSelected.Execute; end; procedure TDialogQueryBuilder.PaintBox1Paint(Sender: TObject); begin Self.DrawInfoListBoxNotImplemented(Sender as TPaintBox); end; procedure TDialogQueryBuilder.tmrReadyTimer(Sender: TObject); begin tmrReady.Enabled := False; if TAplicationAutomation.IsActive then begin TAplicationAutomation.SpeedSlowDown; actDemoSelect.Execute; TAplicationAutomation.SpeedSlowDown; actUseSQL.Execute; end; end; procedure TDialogQueryBuilder.DrawInfoListBoxNotImplemented (APaintBox: TPaintBox); var Canv: TCanvas; rectA: TRect; xc: Integer; yc: Integer; sLine: string; hgText: Integer; wdText: Integer; begin Canv := APaintBox.Canvas; rectA := Rect(1, 1, APaintBox.Width - 1, APaintBox.Height - 1); Canv.Pen.Color := $E0E0E0; Canv.Pen.Width := 3; Canv.MoveTo(rectA.Left, rectA.Top); Canv.LineTo(rectA.Right, rectA.Bottom); Canv.MoveTo(rectA.Right, rectA.Top); Canv.LineTo(rectA.Left, rectA.Bottom); Canv.Brush.Style := bsClear; Canv.Pen.Width := 2; Canv.Pen.Color := $707070; Canv.Rectangle(rectA); xc := rectA.Left + (rectA.Right - rectA.Left) div 2; yc := rectA.Top + (rectA.Bottom - rectA.Top) div 2; Canv.Font.Color := $505050; Canv.Font.Style := []; sLine := 'ListBox: ' + lbxJoinTables.Name; hgText := Canv.TextHeight(sLine); wdText := Canv.TextWidth(sLine); Canv.TextOut(xc - wdText div 2, yc - hgText - 2, sLine); sLine := 'Not implemented yet'; Canv.Font.Style := [fsItalic]; wdText := Canv.TextWidth(sLine); Canv.TextOut(xc - wdText div 2, yc + 2, sLine); end; end.
unit ExportTabularMISC; uses ExportCore, ExportTabularCore, ExportJson, ExportTabularLOC; var ExportTabularMISC_outputLines: TStringList; var ExportTabularMISC_LOC_outputLines: TStringList; function initialize(): Integer; begin ExportTabularMISC_outputLines := TStringList.create(); ExportTabularMISC_outputLines.add( '"File"' // Name of the originating ESM + ', "Form ID"' // Form ID + ', "Editor ID"' // Editor ID + ', "Name"' // Full name + ', "Weight"' // Item weight in pounds + ', "Value"' // Item value in bottlecaps + ', "Components"' // Sorted JSON array of the components needed to craft. Each component is represented by a // JSON object containing the component identifier and the count ); ExportTabularMISC_LOC_outputLines := initLocList(); end; function canProcess(el: IInterface): Boolean; begin result := signature(el) = 'MISC'; end; function process(misc: IInterface): Integer; begin if not canProcess(misc) then begin addWarning(name(misc) + ' is not a MISC. Entry was ignored.'); exit; end; ExportTabularMISC_outputLines.add( escapeCsvString(getFileName(getFile(misc))) + ', ' + escapeCsvString(stringFormID(misc)) + ', ' + escapeCsvString(evBySign(misc, 'EDID')) + ', ' + escapeCsvString(evBySign(misc, 'FULL')) + ', ' + escapeCsvString(evByPath(eBySign(misc, 'DATA'), 'Weight')) + ', ' + escapeCsvString(evByPath(eBySign(misc, 'DATA'), 'Value')) + ', ' + escapeCsvString(getJsonComponentArray(misc)) ); appendLocationData(ExportTabularMISC_LOC_outputLines, misc); end; function finalize(): Integer; begin createDir('dumps/'); ExportTabularMISC_outputLines.saveToFile('dumps/MISC.csv'); ExportTabularMISC_outputLines.free(); ExportTabularMISC_LOC_outputLines.saveToFile('dumps/MISC_LOC.csv'); ExportTabularMISC_LOC_outputLines.free(); end; (** * Returns the components of [el] as a comma-separated list of identifiers and counts. * * @param el the element to return the components of * @return the components of [el] as a comma-separated list of identifiers and counts *) function getJsonComponentArray(el: IInterface): String; var i: Integer; components: IInterface; entry: IInterface; component: IInterface; quantity: IInterface; resultList: TStringList; begin resultList := TStringList.create(); components := eBySign(el, 'MCQP'); for i := 0 to eCount(components) - 1 do begin entry := eByIndex(components, i); component := eByName(entry, 'Component'); quantity := eByName(entry, 'Component Count Keyword'); resultList.add( '{' + '"Component":"' + escapeJson(gev(component)) + '"' + ',"Component Count Keyword":"' + escapeJson(gev(quantity)) + '"' + ',"Count":"' + escapeJson(intToStr(quantityKeywordToValue(linksTo(component), linksTo(quantity)))) + '"' + '}' ); end; resultList.sort(); result := listToJsonArray(resultList); resultList.free(); end; (** * Returns the number of items the quantity keyword [quantity] signifies for [component]. * * @param component the component to look up the quantity in * @param quantity the quantity keyword to look up in [component] * @return the number of items the quantity keyword [quantity] signifies for [component] *) function quantityKeywordToValue(component: IInterface; quantity: IInterface): Integer; var i: Integer; quantityName: String; componentQuantities: IInterface; componentQuantity: IInterface; begin quantityName := evBySign(quantity, 'EDID'); componentQuantities := eBySign(component, 'CVPA'); for i := 0 to eCount(componentQuantities) - 1 do begin componentQuantity := eByIndex(componentQuantities, i); if strEquals( quantityName, evBySign(linkByName(componentQuantity, 'Scrap Count Keyword'), 'EDID') ) then begin result := evByName(componentQuantity, 'Scrap Component Count'); break; end; end; end; end.
(********************************************************************************) (* TExtenso *) (* *) (* Este é um componente visual para ser usado em qualquer versão de Delhi. *) (* *) (* Copyright © 1998 by Leonardo Augusto Rezende Santos *) (* e-mail: laug@ufu.br *) (* *) (* Este componente é freeware e pode ser livremente distribuído em aplicações *) (* comerciais ou particulares. *) (* O Código Fonte pode ser livremente usado, modificado ou distribuído. *) (* O autor não se responsabiliza por nenhum dano, direto ou indireto causado *) (* este componente. *) (* *) (* Comentários e sugestões serão muito bem vindas. *) (********************************************************************************) unit Extenso; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type TExtenso = class(TComponent) private { Private declarations } Unidade : array[0..9] of string[7]; Dezena : array[0..9] of string[10]; Centena : array[0..9] of string[13]; FMoeda, FPluralMoeda, FFracao, FPluralFracao, FNumero, FExtenso : string; procedure SetNumero(Value : string); procedure SetMoeda(Value : string); procedure SetPluralMoeda(Value : string); procedure SetFracao(Value : string); procedure SetPluralFracao(Value : string); function Ext1(S : string) : string; function ExtUnidade(S : string) : string; function ExtDezena(S : string) : string; function Ext2(S : string) : string; protected { Protected declarations } public { Public declarations } constructor Create(AOwner : TComponent); override; published { Published declarations } property Moeda : string read FMoeda write SetMoeda; property PluralMoeda : string read FPluralMoeda write SetPluralMoeda; property Fracao : string read FFracao write SetFracao; property PluralFracao : string read FPluralFracao write SetPluralFracao; property Numero : string read FNumero write SetNumero; property Extenso : string read FExtenso write FExtenso; end; procedure Register; implementation procedure Register; begin RegisterComponents('CGLSOFT', [TExtenso]); end; constructor TExtenso.Create(AOwner : TComponent); begin inherited Create(AOwner); {Unidades} Unidade[0] := ''; Unidade[1] := 'um '; Unidade[2] := 'dois '; Unidade[3] := 'três '; Unidade[4] := 'quatro '; Unidade[5] := 'cinco '; Unidade[6] := 'seis '; Unidade[7] := 'sete '; Unidade[8] := 'oito '; Unidade[9] := 'nove '; {Dezenas} Dezena[0] := ''; Dezena[1] := 'dez '; Dezena[2] := 'vinte '; Dezena[3] := 'trinta '; Dezena[4] := 'quarenta '; Dezena[5] := 'cinqüenta '; Dezena[6] := 'sessenta '; Dezena[7] := 'setenta '; Dezena[8] := 'oitenta '; Dezena[9] := 'noventa '; {Centenas} Centena[0] := ''; Centena[1] := 'cem '; Centena[2] := 'duzentos '; Centena[3] := 'trezentos '; Centena[4] := 'quatrocentos '; Centena[5] := 'quinhentos '; Centena[6] := 'seiscentos '; Centena[7] := 'setecentos '; Centena[8] := 'oitocentos '; Centena[9] := 'novecentos '; FNumero := '0,00'; FMoeda := 'Real'; FPluralMoeda := 'Reais'; FFracao := 'centavo'; FPluralFracao := 'centavos'; end; procedure TExtenso.SetNumero(Value : string); var Inteiro, Centavo : string; Len, n : Integer; {Nº de Digitos } begin Len := Length(Value); n := Pos(',', Value); {Formatando a Vírgula e os Centavos} if n = 0 then Value := Value + ',00' else if Len > n + 2 then Delete(Value, n+3, Len-n+2) else if Len < n + 2 then Insert(Copy('00', 1, n + 2 - Len) , Value, n + 1); if Value = '0.00' then begin FExtenso := ''; Exit; end; n := Pos(',', Value); Inteiro := Copy(Value, 1, n - 1); Centavo := Copy(Value, n + 1, 2); Len := Length(Inteiro); case Len of 1 : FExtenso := Ext1(Inteiro); 2 : FExtenso := Ext1(Inteiro); 3 : FExtenso := Ext1(Inteiro); 4 : FExtenso := Ext2(Inteiro); 5 : FExtenso := Ext2(Inteiro); 6 : FExtenso := Ext2(Inteiro); else FExtenso := Value; end; if (StrToInt(Inteiro) <> 1) and (StrToInt(Inteiro) <> 0) then FExtenso := FExtenso + FPluralMoeda + ' ' else FExtenso := FExtenso + FMoeda + ' '; if Centavo <> '00' then if StrToInt(Inteiro) <> 0 then begin if Centavo <> '01' then FExtenso := FExtenso + 'e ' + Ext1(Centavo) + FPluralFracao else FExtenso := FExtenso + 'e um ' + FFracao end else begin if Centavo <> '01' then FExtenso := Ext1(Centavo) + FPluralFracao else FExtenso := 'um ' + FFracao end; FNumero := Value; end; procedure TExtenso.SetMoeda(Value : string); begin FMoeda := Value; SetNumero(FNumero); end; procedure TExtenso.SetPluralMoeda(Value : string); begin FPluralMoeda := Value; SetNumero(FNumero); end; procedure TExtenso.SetFracao(Value : string); begin FFracao := Value; SetNumero(FNumero); end; procedure TExtenso.SetPluralFracao(Value : string); begin FPluralFracao := Value; SetNumero(FNumero); end; function TExtenso.Ext1(S : string) : string; begin case Length(S) of 1 : Result := ExtUnidade(S[1]); 2 : Result := ExtDezena(S[1] + S[2]); 3 : if S[2] + S[3] = '00' then Result := Centena[StrToInt(S[1])] else if S[1] = '1' then Result := 'cento e ' + ExtDezena(S[2] + S[3]) else Result := Centena[StrToInt(S[1])] + 'e ' + ExtDezena(S[2] + S[3]); end; end; function TExtenso.ExtUnidade(S : string) : string; begin Result := Unidade[StrToInt(S[1])]; end; function TExtenso.ExtDezena(S : string) : string; begin if S[1] <> '1' then {Dezena <> 1} if S[2] <> '0' then if S[1] <> '0' then Result := Dezena[StrToInt(S[1])] + 'e ' + Unidade[StrToInt(S[2])] else Result := Unidade[StrToInt(S[2])] else Result := Dezena[StrToInt(S[1])] else {Dezena = 1} case S[2] of '0' : Result := 'dez '; '1' : Result := 'onze '; '2' : Result := 'doze '; '3' : Result := 'treze '; '4' : Result := 'quatorze '; '5' : Result := 'quinze '; '6' : Result := 'dezesseis '; '7' : Result := 'dezessete '; '8' : Result := 'dezoito '; '9' : Result := 'dezenove '; end; end; function TExtenso.Ext2(S : string) : string; begin case Length(S) of 4 : if Copy(S,1,1) <> '0' then Result := Ext1(Copy(S,1,1)) + 'mil ' + Ext1(Copy(S,2,3)) else Result := Ext1(Copy(S,2,3)); 5 : if Copy(S,1,2) <> '00' then Result := Ext1(Copy(S,1,2)) + 'mil ' + Ext1(Copy(S,3,3)) else Result := Ext1(Copy(S,3,3)); 6 : if Copy(S,1,3) <> '000' then Result := Ext1(Copy(S,1,3)) + 'mil ' + Ext1(Copy(S,4,3)) else Result := Ext1(Copy(S,4,3)); end; end; end.
unit Scanner; interface uses CRT; const ALNG = 30; eof = #26; tab = #009; LineFeed = #010; space = #032; car_return = #013; type Alfa = string[ALNG]; tokens = ( t_int, t_add, t_sub, t_mul, t_rdiv, t_double_mul, t_assign { ':=' }, t_lbrack { '[' }, t_rbrack { ']' }, t_lparent { '(' }, t_rparent { ')' }, t_id, t_else, t_if, t_then ); const num_reserved_word = 3; KeyStr : array [1..num_reserved_word] of Alfa = ( 'else', 'if', 'then' ); KeySym : array [1..num_reserved_word] of tokens = ( t_else, t_if, t_then ); var FIn : string[12]; FInput : text; LookAhead : boolean; Enum : boolean; Ch : char; token : tokens; Id : Alfa; Inum : longint; LineNumber : integer; procedure initialize; procedure scan; procedure terminate; implementation procedure Initialize; begin if (ParamCount < 1) then repeat Write(' File Sumber (.pas) '); Readln(FIn); until (Length(FIn) <> 0 ) else FIn := ParamStr(1); if (Pos('.', FIn) = 0 ) then FIn := FIn + '.pas'; {$I-} Assign(FInput, FIn); Reset(FInput); {$I+} if (IOResult <> 0 ) then begin Writeln('Tidak bisa mengkases File : "', FIn, "''); Halt; end; FIn ;= Copy(FIn, 1, Pos('.',FIn) -1 ) + '.out'; LookAhead := FALSE; Enum := FALSE; Ch := ' '; Line Number := 1; end; procedure Terminate; begin close(FInput); end; procedure GetCh; begin read(FInput, Ch); end; procedure error_report(id: byte); begin case id of 1 : writeln(' Error -> unknown character "', Ch, ''' Line : ', LineNumber); 2 : writeln(' Error -> comment not limited Line', LineNumber); end; end; procedure Scan; var Idx : integer; e : integer; begin if (not LookAhead) then GetCh; LookAhead := FALSE; repeat case Ch of tab, LineFeed, space : GetCh; car_return : begin GetCh; inc (LineNumber); end; eof : Exit; 'A'..'Z','a'..'z' : begin Id := ''; repeat Id := Id + Ch; GetCh; until (not (Ch in['0'..'9', 'A'..'Z', 'a'..'z'])); LookAhead := TRUE; Idx := 0; repeat Idx := Idx + 1; until ((Idx = num_reserved_word) or (Id = KeyStr[Idx])); if (Id = KeyStr[Idx]) then token := KeySym[Idx] else token := t_id; Exit; end; '0'..'9' : begin Inum := 0; token := t_int; repeat Inum := Inum * 10 + (ord(Ch) - ord('0')); until (not (Ch in['0'..'9'])); LookAhead := TRUE; Exit; end; '+' : begin token := t_add; exit; end; '-' : begin token := t_sub; exit; end; '*' : begin getch; if(ch = '*') then token := t_double_mul else begin token := t_mul; lookahead := true; end; exit; '/' : begin token := t_rdiv; exit; end; ')' : begin token := t_rparent; exit; end; '[' : begin token := t_lbrack; exit; end; ']' : begin token := t_rbrack; exit; end; ':' : begin GetCh; if ( Ch = '=') then begin token :=t_assign; end else begin Writeln('Error -> Unknown character'':'' line : ', LineNumber); lookahead := true; end; exit; end; '(' : begin GetCh; if(Ch <> '*') then begin token := t_lparent; LookAhead :=TRUE; Exit; end else begin GetCh; if (Ch = eof) then begin error_report(2); Exit; end; repeat while (Ch <> '*') do begin GetCh; if (Ch = eof) then begin error_report(2); exit; end; end; Getch; if(Ch = eof) then begin error_report(2); exit; end; until(Ch = ')'); GetCh; end; end; else begin error_report(1); GetCh; end; end; until FALSE; end end.
{******************************************************************************} { } { Indy (Internet Direct) - Internet Protocols Simplified } { } { https://www.indyproject.org/ } { https://gitter.im/IndySockets/Indy } { } {******************************************************************************} { } { This file is part of the Indy (Internet Direct) project, and is offered } { under the dual-licensing agreement described on the Indy website. } { (https://www.indyproject.org/license/) } { } { Copyright: } { (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { } {******************************************************************************} { } { Originally written by: Fabian S. Biehn } { fbiehn@aagon.com (German & English) } { } { Contributers: } { Here could be your name } { } {******************************************************************************} // This File is auto generated! // Any change to this file should be made in the // corresponding unit in the folder "intermediate"! // Generation date: 28.10.2020 15:24:33 unit IdOpenSSLHeaders_ssl3; interface // Headers for OpenSSL 1.1.1 // ssl3.h {$i IdCompilerDefines.inc} uses IdGlobal; const (* * Signalling cipher suite value from RFC 5746 * (TLS_EMPTY_RENEGOTIATION_INFO_SCSV) *) SSL3_CK_SCSV = $030000FF; (* * Signalling cipher suite value from draft-ietf-tls-downgrade-scsv-00 * (TLS_FALLBACK_SCSV) *) SSL3_CK_FALLBACK_SCSV = $03005600; SSL3_CK_RSA_NULL_MD5 = $03000001; SSL3_CK_RSA_NULL_SHA = $03000002; SSL3_CK_RSA_RC4_40_MD5 = $03000003; SSL3_CK_RSA_RC4_128_MD5 = $03000004; SSL3_CK_RSA_RC4_128_SHA = $03000005; SSL3_CK_RSA_RC2_40_MD5 = $03000006; SSL3_CK_RSA_IDEA_128_SHA = $03000007; SSL3_CK_RSA_DES_40_CBC_SHA = $03000008; SSL3_CK_RSA_DES_64_CBC_SHA = $03000009; SSL3_CK_RSA_DES_192_CBC3_SHA = $0300000A; SSL3_CK_DH_DSS_DES_40_CBC_SHA = $0300000B; SSL3_CK_DH_DSS_DES_64_CBC_SHA = $0300000C; SSL3_CK_DH_DSS_DES_192_CBC3_SHA = $0300000D; SSL3_CK_DH_RSA_DES_40_CBC_SHA = $0300000E; SSL3_CK_DH_RSA_DES_64_CBC_SHA = $0300000F; SSL3_CK_DH_RSA_DES_192_CBC3_SHA = $03000010; SSL3_CK_DHE_DSS_DES_40_CBC_SHA = $03000011; SSL3_CK_EDH_DSS_DES_40_CBC_SHA = SSL3_CK_DHE_DSS_DES_40_CBC_SHA; SSL3_CK_DHE_DSS_DES_64_CBC_SHA = $03000012; SSL3_CK_EDH_DSS_DES_64_CBC_SHA = SSL3_CK_DHE_DSS_DES_64_CBC_SHA; SSL3_CK_DHE_DSS_DES_192_CBC3_SHA = $03000013; SSL3_CK_EDH_DSS_DES_192_CBC3_SHA = SSL3_CK_DHE_DSS_DES_192_CBC3_SHA; SSL3_CK_DHE_RSA_DES_40_CBC_SHA = $03000014; SSL3_CK_EDH_RSA_DES_40_CBC_SHA = SSL3_CK_DHE_RSA_DES_40_CBC_SHA; SSL3_CK_DHE_RSA_DES_64_CBC_SHA = $03000015; SSL3_CK_EDH_RSA_DES_64_CBC_SHA = SSL3_CK_DHE_RSA_DES_64_CBC_SHA; SSL3_CK_DHE_RSA_DES_192_CBC3_SHA = $03000016; SSL3_CK_EDH_RSA_DES_192_CBC3_SHA = SSL3_CK_DHE_RSA_DES_192_CBC3_SHA; SSL3_CK_ADH_RC4_40_MD5 = $03000017; SSL3_CK_ADH_RC4_128_MD5 = $03000018; SSL3_CK_ADH_DES_40_CBC_SHA = $03000019; SSL3_CK_ADH_DES_64_CBC_SHA = $0300001A; SSL3_CK_ADH_DES_192_CBC_SHA = $0300001B; (* a bundle of RFC standard cipher names, generated from ssl3_ciphers[] *) SSL3_RFC_RSA_NULL_MD5 = AnsiString('TLS_RSA_WITH_NULL_MD5'); SSL3_RFC_RSA_NULL_SHA = AnsiString('TLS_RSA_WITH_NULL_SHA'); SSL3_RFC_RSA_DES_192_CBC3_SHA = AnsiString('TLS_RSA_WITH_3DES_EDE_CBC_SHA'); SSL3_RFC_DHE_DSS_DES_192_CBC3_SHA = AnsiString('TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA'); SSL3_RFC_DHE_RSA_DES_192_CBC3_SHA = AnsiString('TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA'); SSL3_RFC_ADH_DES_192_CBC_SHA = AnsiString('TLS_DH_anon_WITH_3DES_EDE_CBC_SHA'); SSL3_RFC_RSA_IDEA_128_SHA = AnsiString('TLS_RSA_WITH_IDEA_CBC_SHA'); SSL3_RFC_RSA_RC4_128_MD5 = AnsiString('TLS_RSA_WITH_RC4_128_MD5'); SSL3_RFC_RSA_RC4_128_SHA = AnsiString('TLS_RSA_WITH_RC4_128_SHA'); SSL3_RFC_ADH_RC4_128_MD5 = AnsiString('TLS_DH_anon_WITH_RC4_128_MD5'); SSL3_TXT_RSA_NULL_MD5 = AnsiString('NULL-MD5'); SSL3_TXT_RSA_NULL_SHA = AnsiString('NULL-SHA'); SSL3_TXT_RSA_RC4_40_MD5 = AnsiString('EXP-RC4-MD5'); SSL3_TXT_RSA_RC4_128_MD5 = AnsiString('RC4-MD5'); SSL3_TXT_RSA_RC4_128_SHA = AnsiString('RC4-SHA'); SSL3_TXT_RSA_RC2_40_MD5 = AnsiString('EXP-RC2-CBC-MD5'); SSL3_TXT_RSA_IDEA_128_SHA = AnsiString('IDEA-CBC-SHA'); SSL3_TXT_RSA_DES_40_CBC_SHA = AnsiString('EXP-DES-CBC-SHA'); SSL3_TXT_RSA_DES_64_CBC_SHA = AnsiString('DES-CBC-SHA'); SSL3_TXT_RSA_DES_192_CBC3_SHA = AnsiString('DES-CBC3-SHA'); SSL3_TXT_DH_DSS_DES_40_CBC_SHA = AnsiString('EXP-DH-DSS-DES-CBC-SHA'); SSL3_TXT_DH_DSS_DES_64_CBC_SHA = AnsiString('DH-DSS-DES-CBC-SHA'); SSL3_TXT_DH_DSS_DES_192_CBC3_SHA = AnsiString('DH-DSS-DES-CBC3-SHA'); SSL3_TXT_DH_RSA_DES_40_CBC_SHA = AnsiString('EXP-DH-RSA-DES-CBC-SHA'); SSL3_TXT_DH_RSA_DES_64_CBC_SHA = AnsiString('DH-RSA-DES-CBC-SHA'); SSL3_TXT_DH_RSA_DES_192_CBC3_SHA = AnsiString('DH-RSA-DES-CBC3-SHA'); SSL3_TXT_DHE_DSS_DES_40_CBC_SHA = AnsiString('EXP-DHE-DSS-DES-CBC-SHA'); SSL3_TXT_DHE_DSS_DES_64_CBC_SHA = AnsiString('DHE-DSS-DES-CBC-SHA'); SSL3_TXT_DHE_DSS_DES_192_CBC3_SHA = AnsiString('DHE-DSS-DES-CBC3-SHA'); SSL3_TXT_DHE_RSA_DES_40_CBC_SHA = AnsiString('EXP-DHE-RSA-DES-CBC-SHA'); SSL3_TXT_DHE_RSA_DES_64_CBC_SHA = AnsiString('DHE-RSA-DES-CBC-SHA'); SSL3_TXT_DHE_RSA_DES_192_CBC3_SHA = AnsiString('DHE-RSA-DES-CBC3-SHA'); (* * This next block of six 'EDH' labels is for backward compatibility with * older versions of OpenSSL. New code should use the six 'DHE' labels above * instead: *) SSL3_TXT_EDH_DSS_DES_40_CBC_SHA = AnsiString('EXP-EDH-DSS-DES-CBC-SHA'); SSL3_TXT_EDH_DSS_DES_64_CBC_SHA = AnsiString('EDH-DSS-DES-CBC-SHA'); SSL3_TXT_EDH_DSS_DES_192_CBC3_SHA = AnsiString('EDH-DSS-DES-CBC3-SHA'); SSL3_TXT_EDH_RSA_DES_40_CBC_SHA = AnsiString('EXP-EDH-RSA-DES-CBC-SHA'); SSL3_TXT_EDH_RSA_DES_64_CBC_SHA = AnsiString('EDH-RSA-DES-CBC-SHA'); SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA = AnsiString('EDH-RSA-DES-CBC3-SHA'); SSL3_TXT_ADH_RC4_40_MD5 = AnsiString('EXP-ADH-RC4-MD5'); SSL3_TXT_ADH_RC4_128_MD5 = AnsiString('ADH-RC4-MD5'); SSL3_TXT_ADH_DES_40_CBC_SHA = AnsiString('EXP-ADH-DES-CBC-SHA'); SSL3_TXT_ADH_DES_64_CBC_SHA = AnsiString('ADH-DES-CBC-SHA'); SSL3_TXT_ADH_DES_192_CBC_SHA = AnsiString('ADH-DES-CBC3-SHA'); SSL3_SSL_SESSION_ID_LENGTH = 32; SSL3_MAX_SSL_SESSION_ID_LENGTH = 32; SSL3_MASTER_SECRET_SIZE = 48; SSL3_RANDOM_SIZE = 32; SSL3_SESSION_ID_SIZE = 32; SSL3_RT_HEADER_LENGTH = 5; SSL3_HM_HEADER_LENGTH = 4; (* * Some will argue that this increases memory footprint, but it's not * actually true. Point is that malloc has to return at least 64-bit aligned * pointers, meaning that allocating 5 bytes wastes 3 bytes in either case. * Suggested pre-gaping simply moves these wasted bytes from the end of * allocated region to its front, but makes data payload aligned, which * improves performance:-) *) SSL3_ALIGN_PAYLOAD = 8; (* * This is the maximum MAC (digest) size used by the SSL library. Currently * maximum of 20 is used by SHA1, but we reserve for future extension for * 512-bit hashes. *) SSL3_RT_MAX_MD_SIZE = 64; (* * Maximum block size used in all ciphersuites. Currently 16 for AES. *) SSL_RT_MAX_CIPHER_BLOCK_SIZE = 16; SSL3_RT_MAX_EXTRA = 16384; (* Maximum plaintext length: defined by SSL/TLS standards *) SSL3_RT_MAX_PLAIN_LENGTH = 16384; (* Maximum compression overhead: defined by SSL/TLS standards *) SSL3_RT_MAX_COMPRESSED_OVERHEAD = 1024; (* * The standards give a maximum encryption overhead of 1024 bytes. In * practice the value is lower than this. The overhead is the maximum number * of padding bytes (256) plus the mac size. *) SSL3_RT_MAX_ENCRYPTED_OVERHEAD = 256 + SSL3_RT_MAX_MD_SIZE; SSL3_RT_MAX_TLS13_ENCRYPTED_OVERHEAD = 256; (* * OpenSSL currently only uses a padding length of at most one block so the * send overhead is smaller. *) SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD = SSL_RT_MAX_CIPHER_BLOCK_SIZE + SSL3_RT_MAX_MD_SIZE; (* If compression isn't used don't include the compression overhead *) SSL3_RT_MAX_COMPRESSED_LENGTH = SSL3_RT_MAX_PLAIN_LENGTH; // SSL3_RT_MAX_COMPRESSED_LENGTH = (SSL3_RT_MAX_PLAIN_LENGTH + SSL3_RT_MAX_COMPRESSED_OVERHEAD); SSL3_RT_MAX_ENCRYPTED_LENGTH = SSL3_RT_MAX_ENCRYPTED_OVERHEAD + SSL3_RT_MAX_COMPRESSED_LENGTH; SSL3_RT_MAX_TLS13_ENCRYPTED_LENGTH = SSL3_RT_MAX_PLAIN_LENGTH + SSL3_RT_MAX_TLS13_ENCRYPTED_OVERHEAD; SSL3_RT_MAX_PACKET_SIZE = SSL3_RT_MAX_ENCRYPTED_LENGTH + SSL3_RT_HEADER_LENGTH; SSL3_MD_CLIENT_FINISHED_= TIdAnsiChar($43) + TIdAnsiChar($4C) + TIdAnsiChar($4E) + TIdAnsiChar($54); SSL3_MD_SERVER_FINISHED_= TIdAnsiChar($53) + TIdAnsiChar($52) + TIdAnsiChar($56) + TIdAnsiChar($52); SSL3_VERSION = $0300; SSL3_VERSION_MAJOR = $03; SSL3_VERSION_MINOR = $00; SSL3_RT_CHANGE_CIPHER_SPEC = 20; SSL3_RT_ALERT = 21; SSL3_RT_HANDSHAKE = 22; SSL3_RT_APPLICATION_DATA = 23; DTLS1_RT_HEARTBEAT = 24; (* Pseudo content types to indicate additional parameters *) TLS1_RT_CRYPTO = $1000; TLS1_RT_CRYPTO_PREMASTER = TLS1_RT_CRYPTO or $1; TLS1_RT_CRYPTO_CLIENT_RANDOM = TLS1_RT_CRYPTO or $2; TLS1_RT_CRYPTO_SERVER_RANDOM = TLS1_RT_CRYPTO or $3; TLS1_RT_CRYPTO_MASTER = TLS1_RT_CRYPTO or $4; TLS1_RT_CRYPTO_READ = $0000; TLS1_RT_CRYPTO_WRITE = $0100; TLS1_RT_CRYPTO_MAC = TLS1_RT_CRYPTO or $5; TLS1_RT_CRYPTO_KEY = TLS1_RT_CRYPTO or $6; TLS1_RT_CRYPTO_IV = TLS1_RT_CRYPTO or $7; TLS1_RT_CRYPTO_FIXED_IV = TLS1_RT_CRYPTO or $8; (* Pseudo content types for SSL/TLS header info *) SSL3_RT_HEADER = $100; SSL3_RT_INNER_CONTENT_TYPE = $101; SSL3_AL_WARNING = 1; SSL3_AL_FATAL = 2; SSL3_AD_CLOSE_NOTIFY = 0; SSL3_AD_UNEXPECTED_MESSAGE = 10; (* fatal *) SSL3_AD_BAD_RECORD_MAC = 20; (* fatal *) SSL3_AD_DECOMPRESSION_FAILURE = 30; (* fatal *) SSL3_AD_HANDSHAKE_FAILURE = 40; (* fatal *) SSL3_AD_NO_CERTIFICATE = 41; SSL3_AD_BAD_CERTIFICATE = 42; SSL3_AD_UNSUPPORTED_CERTIFICATE = 43; SSL3_AD_CERTIFICATE_REVOKED = 44; SSL3_AD_CERTIFICATE_EXPIRED = 45; SSL3_AD_CERTIFICATE_UNKNOWN = 46; SSL3_AD_ILLEGAL_PARAMETER = 47; (* fatal *) TLS1_HB_REQUEST = 1; TLS1_HB_RESPONSE = 2; SSL3_CT_RSA_SIGN = 1; SSL3_CT_DSS_SIGN = 2; SSL3_CT_RSA_FIXED_DH = 3; SSL3_CT_DSS_FIXED_DH = 4; SSL3_CT_RSA_EPHEMERAL_DH = 5; SSL3_CT_DSS_EPHEMERAL_DH = 6; SSL3_CT_FORTEZZA_DMS = 20; (* * SSL3_CT_NUMBER is used to size arrays and it must be large enough to * contain all of the cert types defined for *either* SSLv3 and TLSv1. *) SSL3_CT_NUMBER = 10; (* No longer used as of OpenSSL 1.1.1 *) SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS = $0001; (* Removed from OpenSSL 1.1.0 *) TLS1_FLAGS_TLS_PADDING_BUG = $0; TLS1_FLAGS_SKIP_CERT_VERIFY = $0010; (* Set if we encrypt then mac instead of usual mac then encrypt *) TLS1_FLAGS_ENCRYPT_THEN_MAC_READ = $0100; TLS1_FLAGS_ENCRYPT_THEN_MAC = TLS1_FLAGS_ENCRYPT_THEN_MAC_READ; (* Set if extended master secret extension received from peer *) TLS1_FLAGS_RECEIVED_EXTMS = $0200; TLS1_FLAGS_ENCRYPT_THEN_MAC_WRITE = $0400; TLS1_FLAGS_STATELESS = $0800; SSL3_MT_HELLO_REQUEST = 0; SSL3_MT_CLIENT_HELLO = 1; SSL3_MT_SERVER_HELLO = 2; SSL3_MT_NEWSESSION_TICKET = 4; SSL3_MT_END_OF_EARLY_DATA = 5; SSL3_MT_ENCRYPTED_EXTENSIONS = 8; SSL3_MT_CERTIFICATE = 11; SSL3_MT_SERVER_KEY_EXCHANGE = 12; SSL3_MT_CERTIFICATE_REQUEST = 13; SSL3_MT_SERVER_DONE = 14; SSL3_MT_CERTIFICATE_VERIFY = 15; SSL3_MT_CLIENT_KEY_EXCHANGE = 16; SSL3_MT_FINISHED = 20; SSL3_MT_CERTIFICATE_URL = 21; SSL3_MT_CERTIFICATE_STATUS = 22; SSL3_MT_SUPPLEMENTAL_DATA = 23; SSL3_MT_KEY_UPDATE = 24; SSL3_MT_NEXT_PROTO = 67; SSL3_MT_MESSAGE_HASH = 254; DTLS1_MT_HELLO_VERIFY_REQUEST = 3; (* Dummy message type for handling CCS like a normal handshake message *) SSL3_MT_CHANGE_CIPHER_SPEC = $0101; SSL3_MT_CCS = 1; (* These are used when changing over to a new cipher *) SSL3_CC_READ = $001; SSL3_CC_WRITE = $002; SSL3_CC_CLIENT = $010; SSL3_CC_SERVER = $020; SSL3_CC_EARLY = $040; SSL3_CC_HANDSHAKE = $080; SSL3_CC_APPLICATION = $100; SSL3_CHANGE_CIPHER_CLIENT_WRITE = SSL3_CC_CLIENT or SSL3_CC_WRITE; SSL3_CHANGE_CIPHER_SERVER_READ = SSL3_CC_SERVER or SSL3_CC_READ; SSL3_CHANGE_CIPHER_CLIENT_READ = SSL3_CC_CLIENT or SSL3_CC_READ; SSL3_CHANGE_CIPHER_SERVER_WRITE = SSL3_CC_SERVER or SSL3_CC_WRITE; implementation end.
unit Writers; interface uses System.SysUtils, System.Classes, System.JSON.Writers, System.JSON.Readers, System.JSON.Types; type TJsonStringWriter = class(TJsonTextWriter) private FStrinBuilder: TStringBuilder; FStringWriter: TStringWriter; public constructor Create; destructor Destroy; function ToString: string; end; TJsonStringReader = class(TJsonTextReader) private FStrinReader: TStringReader; public constructor Create(const AJson: string); destructor Destroy; end; TJsonCodeWriter = class(TJsonWriter) private FWriter: TStringWriter; FBuilder: TStringBuilder; FIndentation: Integer; FIndentationBase: Integer; FIndentChar: Char; public constructor Create; destructor Destroy; procedure Rewind; override; function ToString: string; property IndentationBase: Integer read FIndentationBase write FIndentationBase; property Indentation: Integer read FIndentation write FIndentation; property IndentChar: Char read FIndentChar write FIndentChar; end; TJsonBuilderGenerator = class(TJsonCodeWriter) private FPropertyName: string; FBuilderName: string; FPreviousState: TJsonWriter.TState; procedure WriteIndent; procedure WriteValueAsFunction(const AValue: string; AsString: Boolean = False); overload; procedure WriteKeywordAsFunction(const AKeyword: string); overload; procedure WriteFunctionCall(const AFunction: string); overload; procedure WriteSymbolAsFunction(const ASymbol: string); overload; protected procedure WriteEnd(const Token: TJsonToken); override; public constructor Create(const ABuilderName: string); procedure WriteStartObject; override; procedure WriteStartArray; override; procedure WriteStartConstructor(const Name: string); override; procedure WritePropertyName(const Name: string); override; procedure WriteNull; override; procedure WriteRaw(const Json: string); override; procedure WriteRawValue(const Json: string); override; procedure WriteUndefined; override; procedure WriteValue(const Value: string); override; procedure WriteValue(Value: Integer); override; procedure WriteValue(Value: UInt32); override; procedure WriteValue(Value: Int64); override; procedure WriteValue(Value: UInt64); override; procedure WriteValue(Value: Single); override; procedure WriteValue(Value: Double); override; procedure WriteValue(Value: Extended); override; procedure WriteValue(Value: Boolean); override; procedure WriteValue(Value: Char); override; procedure WriteValue(Value: Byte); override; procedure WriteValue(Value: TDateTime); override; procedure WriteValue(const Value: TGUID); override; procedure WriteValue(const Value: TBytes; BinaryType: TJsonBinaryType = TJsonBinaryType.Generic); override; procedure WriteValue(const Value: TJsonOid); override; procedure WriteValue(const Value: TJsonRegEx); override; procedure WriteValue(const Value: TJsonDBRef); override; procedure WriteValue(const Value: TJsonCodeWScope); override; procedure WriteMinKey; override; procedure WriteMaxKey; override; procedure OnBeforeWriteToken(TokenBeginWritten: TJsonToken); override; end; TJsonWriterGenerator = class(TJsonCodeWriter) private FWriterName: string; procedure WriteValueAsFunctionCall(const AValue: string; AsString: Boolean = False); procedure WriteTokenAsFunctionCall(const ATokenName: string); protected procedure WriteEnd(const Token: TJsonToken); override; public constructor Create(const AWriterName: string); procedure WriteStartObject; override; procedure WriteStartArray; override; procedure WriteStartConstructor(const Name: string); override; procedure WritePropertyName(const Name: string); override; procedure WriteNull; override; procedure WriteRaw(const Json: string); override; procedure WriteRawValue(const Json: string); override; procedure WriteUndefined; override; procedure WriteValue(const Value: string); override; procedure WriteValue(Value: Integer); override; procedure WriteValue(Value: UInt32); override; procedure WriteValue(Value: Int64); override; procedure WriteValue(Value: UInt64); override; procedure WriteValue(Value: Single); override; procedure WriteValue(Value: Double); override; procedure WriteValue(Value: Extended); override; procedure WriteValue(Value: Boolean); override; procedure WriteValue(Value: Char); override; procedure WriteValue(Value: Byte); override; procedure WriteValue(Value: TDateTime); override; procedure WriteValue(const Value: TGUID); override; procedure WriteValue(const Value: TBytes; BinaryType: TJsonBinaryType = TJsonBinaryType.Generic); override; procedure WriteValue(const Value: TJsonOid); override; procedure WriteValue(const Value: TJsonRegEx); override; procedure WriteValue(const Value: TJsonDBRef); override; procedure WriteValue(const Value: TJsonCodeWScope); override; procedure WriteMinKey; override; procedure WriteMaxKey; override; procedure OnBeforeWriteToken(TokenBeginWritten: TJsonToken); override; end; implementation uses System.Math; { TJsonStringWriter } constructor TJsonStringWriter.Create; begin FStrinBuilder := TStringBuilder.Create; FStringWriter := TStringWriter.Create(FStrinBuilder); inherited Create(FStringWriter); end; destructor TJsonStringWriter.Destroy; begin FStringWriter.Free; FStrinBuilder.Free; inherited Destroy; end; function TJsonStringWriter.ToString: string; begin Result := FStrinBuilder.ToString; end; { TJsonStringReader } constructor TJsonStringReader.Create(const AJson: string); begin FStrinReader := TStringReader.Create(AJson); inherited Create(FStrinReader); end; destructor TJsonStringReader.Destroy; begin FStrinReader.Free; end; { TJsonWriterGenerator } constructor TJsonBuilderGenerator.Create(const ABuilderName: string); begin inherited Create; FBuilderName := ABuilderName; end; procedure TJsonBuilderGenerator.OnBeforeWriteToken(TokenBeginWritten: TJsonToken); begin FPreviousState := FCurrentState; if FCurrentState = TState.Start then begin FWriter.Write(FBuilderName); WriteIndent; end; if TokenBeginWritten = TJsonToken.PropertyName then Exit; case FCurrentState of TState.Property, TState.Array, TState.ArrayStart, TState.ObjectStart, TState.Object, TState.Constructor, TState.ConstructorStart: WriteIndent; TState.Start: if TokenBeginWritten = TJsonToken.PropertyName then WriteIndent; end; end; procedure TJsonBuilderGenerator.WriteSymbolAsFunction(const ASymbol: string); begin WriteKeywordAsFunction('Add' + ASymbol); end; procedure TJsonBuilderGenerator.WriteValueAsFunction(const AValue: string; AsString: Boolean); var LValue: string; begin if AsString then LValue := '''' + AValue + '''' else LValue := LValue; if FPreviousState = TJsonWriter.TState.Property then WriteFunctionCall('Add(''' + FPropertyName + ''', ' + LValue + ')') else WriteFunctionCall('Add(' + LValue + ')') end; procedure TJsonBuilderGenerator.WriteEnd(const Token: TJsonToken); begin case Token of TJsonToken.EndObject: WriteFunctionCall('EndObject'); TJsonToken.EndArray: WriteFunctionCall('EndArray'); TJsonToken.EndConstructor: // not implemented in builders ; end; end; procedure TJsonBuilderGenerator.WriteFunctionCall(const AFunction: string); begin FWriter.Write('.' + AFunction); end; procedure TJsonBuilderGenerator.WriteIndent; var CurrentIndentCount, WriteCount: Integer; begin FWriter.WriteLine; CurrentIndentCount := Top * FIndentation + FIndentationBase; while CurrentIndentCount > 0 do begin WriteCount := Min(CurrentIndentCount, 10); FWriter.Write(string.Create(FIndentChar, WriteCount)); Dec(CurrentIndentCount, WriteCount); end; end; procedure TJsonBuilderGenerator.WriteKeywordAsFunction(const AKeyword: string); begin if FPreviousState = TJsonWriter.TState.Property then WriteFunctionCall(AKeyword + '(''' + FPropertyName + ''')') else WriteFunctionCall(AKeyword) end; procedure TJsonBuilderGenerator.WriteMaxKey; begin inherited; WriteSymbolAsFunction('MaxKey'); end; procedure TJsonBuilderGenerator.WriteMinKey; begin inherited; WriteSymbolAsFunction('MinKey'); end; procedure TJsonBuilderGenerator.WriteNull; begin inherited; WriteSymbolAsFunction('Null'); end; procedure TJsonBuilderGenerator.WritePropertyName(const Name: string); begin inherited; FPropertyName := Name; end; procedure TJsonBuilderGenerator.WriteRaw(const Json: string); begin inherited; // not implemented in builders end; procedure TJsonBuilderGenerator.WriteRawValue(const Json: string); begin inherited; // not implemented in builders end; procedure TJsonBuilderGenerator.WriteStartArray; begin inherited; WriteKeywordAsFunction('BeginArray'); end; procedure TJsonBuilderGenerator.WriteStartConstructor(const Name: string); begin inherited; // not implemented in builders end; procedure TJsonBuilderGenerator.WriteStartObject; begin inherited; WriteKeywordAsFunction('BeginObject'); end; procedure TJsonBuilderGenerator.WriteUndefined; begin inherited; WriteSymbolAsFunction('Undefined'); end; procedure TJsonBuilderGenerator.WriteValue(Value: Int64); begin inherited; WriteValueAsFunction(IntToStr(Value)); end; procedure TJsonBuilderGenerator.WriteValue(Value: UInt64); begin inherited; WriteValueAsFunction(UIntToStr(Value)); end; procedure TJsonBuilderGenerator.WriteValue(Value: Single); begin inherited; WriteValueAsFunction(FloatToStr(Value, JSONFormatSettings)); end; procedure TJsonBuilderGenerator.WriteValue(const Value: string); begin inherited; WriteValueAsFunction(Value, True); end; procedure TJsonBuilderGenerator.WriteValue(Value: Integer); begin inherited; WriteValueAsFunction(IntToStr(Value)); end; procedure TJsonBuilderGenerator.WriteValue(Value: UInt32); begin inherited; WriteValueAsFunction(UIntToStr(Value)); end; procedure TJsonBuilderGenerator.WriteValue(Value: Double); begin inherited; WriteValueAsFunction(FloatToStr(Value, JSONFormatSettings)); end; procedure TJsonBuilderGenerator.WriteValue(const Value: TJsonOid); begin raise ENotImplemented.Create('TJsonOid overload'); end; procedure TJsonBuilderGenerator.WriteValue(const Value: TBytes; BinaryType: TJsonBinaryType); begin raise ENotImplemented.Create('TJsonRegEx overload'); end; procedure TJsonBuilderGenerator.WriteValue(const Value: TJsonRegEx); begin raise ENotImplemented.Create('TJsonRegEx overload'); end; procedure TJsonBuilderGenerator.WriteValue(const Value: TJsonCodeWScope); begin raise ENotImplemented.Create('TJsonCodeWScope overload'); end; procedure TJsonBuilderGenerator.WriteValue(const Value: TJsonDBRef); begin raise ENotImplemented.Create('TJsonDBRef overload'); end; procedure TJsonBuilderGenerator.WriteValue(const Value: TGUID); begin //TODO end; procedure TJsonBuilderGenerator.WriteValue(Value: Boolean); begin inherited; WriteValueAsFunction(BoolToStr(Value, True)); end; procedure TJsonBuilderGenerator.WriteValue(Value: Extended); begin inherited; WriteValueAsFunction(FloatToStr(Value, JSONFormatSettings)); end; procedure TJsonBuilderGenerator.WriteValue(Value: Char); begin inherited; WriteValueAsFunction(Value, True); end; procedure TJsonBuilderGenerator.WriteValue(Value: TDateTime); begin //TODO end; procedure TJsonBuilderGenerator.WriteValue(Value: Byte); begin WriteValueAsFunction(Value.ToString); end; { TJsonWriterGenerator } constructor TJsonWriterGenerator.Create(const AWriterName: string); begin inherited Create; FWriterName := AWriterName; end; procedure TJsonWriterGenerator.OnBeforeWriteToken(TokenBeginWritten: TJsonToken); begin FWriter.WriteLine; end; procedure TJsonWriterGenerator.WriteEnd(const Token: TJsonToken); begin case Token of TJsonToken.EndObject: WriteTokenAsFunctionCall('WriteEndObject'); TJsonToken.EndArray: WriteTokenAsFunctionCall('WriteEndArray'); TJsonToken.EndConstructor: WriteTokenAsFunctionCall('WriteEndConstructor'); end; end; procedure TJsonWriterGenerator.WriteTokenAsFunctionCall(const ATokenName: string); begin FWriter.Write(FWriterName + '.' + ATokenName + ';'); end; procedure TJsonWriterGenerator.WriteMaxKey; begin inherited; end; procedure TJsonWriterGenerator.WriteMinKey; begin inherited; end; procedure TJsonWriterGenerator.WriteNull; begin inherited; WriteTokenAsFunctionCall('Null'); end; procedure TJsonWriterGenerator.WritePropertyName(const Name: string); begin inherited; FWriter.Write(FWriterName + '.PropertyName(''' + Name + ''');'); end; procedure TJsonWriterGenerator.WriteRaw(const Json: string); begin inherited; end; procedure TJsonWriterGenerator.WriteRawValue(const Json: string); begin inherited; end; procedure TJsonWriterGenerator.WriteStartArray; begin inherited; WriteTokenAsFunctionCall('StartArray'); end; procedure TJsonWriterGenerator.WriteStartConstructor(const Name: string); begin inherited; WriteValueAsFunctionCall(Name, True); end; procedure TJsonWriterGenerator.WriteStartObject; begin inherited; WriteTokenAsFunctionCall('StartObject'); end; procedure TJsonWriterGenerator.WriteUndefined; begin inherited; WriteTokenAsFunctionCall('Undefined'); end; procedure TJsonWriterGenerator.WriteValue(Value: UInt64); begin inherited; WriteValueAsFunctionCall(Value.ToString); end; procedure TJsonWriterGenerator.WriteValue(Value: Single); begin inherited; WriteValueAsFunctionCall(Value.ToString); end; procedure TJsonWriterGenerator.WriteValue(Value: Double); begin inherited; WriteValueAsFunctionCall(Value.ToString); end; procedure TJsonWriterGenerator.WriteValue(Value: Int64); begin inherited; WriteValueAsFunctionCall(Value.ToString); end; procedure TJsonWriterGenerator.WriteValue(const Value: string); begin inherited; WriteValueAsFunctionCall(Value, True); end; procedure TJsonWriterGenerator.WriteValue(Value: Integer); begin inherited; WriteValueAsFunctionCall(Value.ToString); end; procedure TJsonWriterGenerator.WriteValue(Value: UInt32); begin inherited; WriteValueAsFunctionCall(Value.ToString); end; procedure TJsonWriterGenerator.WriteValue(const Value: TJsonOid); begin raise ENotImplemented.Create('TJsonOid overload'); end; procedure TJsonWriterGenerator.WriteValue(const Value: TBytes; BinaryType: TJsonBinaryType); begin raise ENotImplemented.Create('TBytes overload'); end; procedure TJsonWriterGenerator.WriteValue(const Value: TJsonRegEx); begin raise ENotImplemented.Create('TJsonRegEx overload'); end; procedure TJsonWriterGenerator.WriteValue(const Value: TJsonCodeWScope); begin raise ENotImplemented.Create('TJsonCodeWScope overload'); end; procedure TJsonWriterGenerator.WriteValue(const Value: TJsonDBRef); begin raise ENotImplemented.Create('TJsonDBRef overload'); end; procedure TJsonWriterGenerator.WriteValue(const Value: TGUID); begin raise ENotImplemented.Create('TGUID overload'); end; procedure TJsonWriterGenerator.WriteValue(Value: Boolean); begin inherited; WriteValueAsFunctionCall(Value.ToString(True)); end; procedure TJsonWriterGenerator.WriteValue(Value: Extended); begin inherited; WriteValueAsFunctionCall(Value.ToString); end; procedure TJsonWriterGenerator.WriteValue(Value: Char); begin inherited; WriteValueAsFunctionCall(Value, True); end; procedure TJsonWriterGenerator.WriteValue(Value: TDateTime); begin end; procedure TJsonWriterGenerator.WriteValue(Value: Byte); begin inherited; WriteValueAsFunctionCall(Value.ToString); end; procedure TJsonWriterGenerator.WriteValueAsFunctionCall(const AValue: string; AsString: Boolean); var LValue: string; begin if AsString then LValue := '''' + AValue + '''' else LValue := AValue; FWriter.Write(FWriterName + '.WriteValue(' + LValue + ');'); end; { TJsonCodeWriter } constructor TJsonCodeWriter.Create; begin inherited Create; FIndentation := 2; FIndentChar := ' '; FBuilder := TStringBuilder.Create; FWriter := TStringWriter.Create(FBuilder); end; destructor TJsonCodeWriter.Destroy; begin FWriter.Free; FBuilder.Free; end; procedure TJsonCodeWriter.Rewind; begin inherited; FBuilder.Clear; end; function TJsonCodeWriter.ToString: string; begin Result := FBuilder.ToString; end; end.
(* Copyright (c) 2012-2014, Stefan Glienke 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 this library 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. *) unit DSharp.Interception.PolicyInjectionBehavior; interface uses DSharp.Interception, DSharp.Interception.HandlerPipeline, DSharp.Interception.PipelineManager, Rtti, SysUtils, TypInfo; type TPolicyInjectionBehavior = class(TInterfacedObject, IInterceptionBehavior) private FPipelineManager: IPipelineManager; function GetPipeline(Method: TRttiMethod): THandlerPipeline; public constructor Create(PipelineManager: IPipelineManager); overload; constructor Create(const InterceptionRequest: TCurrentInterceptionRequest; const Policies: array of IInjectionPolicy); overload; function Invoke(Input: IMethodInvocation; GetNext: TFunc<TInvokeInterceptionBehaviorDelegate>): IMethodReturn; function GetRequiredInterfaces: TArray<PTypeInfo>; function WillExecute: Boolean; end; implementation uses DSharp.Interception.MethodImplementationInfo, DSharp.Interception.PolicySet; { TPolicyInjectionBehavior } constructor TPolicyInjectionBehavior.Create(PipelineManager: IPipelineManager); begin FPipelineManager := PipelineManager; end; constructor TPolicyInjectionBehavior.Create( const InterceptionRequest: TCurrentInterceptionRequest; const Policies: array of IInjectionPolicy); var allPolicies: TPolicySet; hasHandlers: Boolean; manager: IPipelineManager; method: TMethodImplementationInfo; hasNewHandlers: Boolean; begin allPolicies := TPolicySet.Create(Policies); hasHandlers := False; manager := TPipelineManager.Create; for method in InterceptionRequest.Interceptor.GetInterceptableMethods( InterceptionRequest.TypeToIntercept, InterceptionRequest.ImplementationType) do begin hasNewHandlers := manager.InitializePipeline(method, allPolicies.GetHandlersFor(method)); hasHandlers := hasHandlers or hasNewHandlers; end; if hasHandlers then begin FPipelineManager := manager; end; allPolicies.Free; end; function TPolicyInjectionBehavior.GetPipeline( Method: TRttiMethod): THandlerPipeline; begin Result := FPipelineManager.GetPipeline(Method); end; function TPolicyInjectionBehavior.GetRequiredInterfaces: TArray<PTypeInfo>; begin Result := nil; end; function TPolicyInjectionBehavior.Invoke(Input: IMethodInvocation; GetNext: TFunc<TInvokeInterceptionBehaviorDelegate>): IMethodReturn; var pipeline: THandlerPipeline; begin pipeline := GetPipeline(Input.Method); Result := pipeline.Invoke(Input, function(PolicyInjectionInput: IMethodInvocation; PolicyInjectionInputGetNext: TFunc<TInvokeHandlerDelegate>): IMethodReturn begin try Result := GetNext()(PolicyInjectionInput, GetNext); except on E: Exception do begin Result := PolicyInjectionInput.CreateExceptionMethodReturn(E.InnerException); end; end; end); end; function TPolicyInjectionBehavior.WillExecute: Boolean; begin Result := Assigned(FPipelineManager); end; end.
unit UnitMain; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls, IdTCPServer, dom, zlibar, IdCustomTCPServer, IdContext, XmlRead, XmlWrite, Base64, Buttons, IniFiles, IdServerIOHandlerStack, IdSSLOpenSSL; type { TfrmMain } TfrmMain = class(TForm) btnCerrar: TBitBtn; IdTCPServer1: TIdTCPServer; Label1: TLabel; Label2: TLabel; edRecuperadas: TMemo; edAlmacenadas: TMemo; Label3: TLabel; edPuerto: TStaticText; procedure btnCerrarClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure IdTCPServer1Execute(AContext: TIdContext); private { private declarations } procedure Ejecutar(AContext:TIdContext); procedure pSaveImage(InputXml,OutputXml:TXmlDocument); procedure pLoadImage(InputXml,OutputXml:TXmlDocument); public { public declarations } end; var frmMain: TfrmMain; puerto:Integer; maxcon:Integer; implementation { TfrmMain } procedure TfrmMain.IdTCPServer1Execute(AContext: TIdContext); begin if AContext.Connection.IOHandler.RecvBufferSize > 0 then Ejecutar(AContext); end; procedure TfrmMain.btnCerrarClick(Sender: TObject); begin IdTCPServer1.Active := False; Close; end; procedure TfrmMain.FormCreate(Sender: TObject); var MiIni:TIniFile; begin MiIni := TIniFile.Create(ExtractFilePath(Application.ExeName)+'\serverimages.ini'); puerto := MiIni.ReadInteger('GENERAL','puerto',3080); maxcon := MiIni.ReadInteger('GENERAL','maxcon',20); edPuerto.Caption := IntToStr(puerto); IdTCPServer1.DefaultPort := puerto; IdTCPServer1.MaxConnections := maxcon; IdTCPServer1.Active := True; end; procedure TfrmMain.Ejecutar(AContext: TIdContext); var InputXml:TXmlDocument; OutputXml:TXmlDocument; InputStream, OutputStream:TStream; InputSize,OutputSize:Int64; Root:TDOMNode; begin InputXml := TXmlDocument.Create; OutputXml := TXmlDocument.Create; AContext.Connection.IOHandler.WriteLn('Esperando...'); InputStream := TMemoryStream.Create; OutputStream := TMemoryStream.Create; InputSize := AContext.Connection.IOHandler.ReadInt64; AContext.Connection.IOHandler.ReadStream(InputStream,InputSize,False); ReadXMLFile(InputXml,InputStream); Application.ProcessMessages; Root := InputXml.DocumentElement.ChildNodes.Item[0]; if TDOMElement(Root).GetAttribute('cmd') = 'write' then pSaveImage(InputXml,OutputXml) else if TDOMElement(Root).GetAttribute('cmd') = 'read' then pLoadImage(InputXml, OutputXml); WriteXMLFile(OutputXml,OutputStream); OutputStream.Seek(0,soFromBeginning); AContext.Connection.IOHandler.Write(OutputStream.Size); AContext.Connection.IOHandler.WriteBufferOpen; AContext.Connection.IOHandler.Write(OutputStream); AContext.Connection.IOHandler.WriteBufferClose; AContext.Connection.IOHandler.Close; end; procedure TfrmMain.pSaveImage(InputXml,OutputXml:TXmlDocument); var Root:TDOMNode; FotoStr:TStringStream; FirmaStr:TStringStream; HuellaStr:TStringStream; ISFoto:TStream; ISFirma:TStream; ISHuella:TStream; ISFotoC:TStream; ISFirmaC:TStream; ISHuellaC:TStream; id:integer; doc:string; NodoImg:TDOMNode; NodoTmp:TDOMNode; begin Root := InputXml.DocumentElement.ChildNodes.Item[0]; NodoImg := Root.ChildNodes.Item[0]; id := strtoint(TDOMElement(Root).GetAttribute('id')); doc := TDOMElement(Root).GetAttribute('doc'); NodoTmp := TDOMElement(NodoImg).ChildNodes.Item[0]; FotoStr := TStringStream.Create(NodoTmp.NodeValue); NodoTmp := TDOMElement(NodoImg).ChildNodes.Item[1]; FirmaStr := TStringStream.Create(NodoTmp.NodeValue); NodoTmp := TDOMElement(NodoImg).ChildNodes.Item[2]; HuellaStr := TStringStream.Create(NodoTmp.NodeValue); ISFoto := TBase64DecodingStream.Create(FotoStr); ISFirma := TBase64DecodingStream.Create(FirmaStr); ISHuella := TBase64DecodingStream.Create(HuellaStr); ISFotoC := TMemoryStream.Create; ISFirmaC := TMemoryStream.Create; ISHuellaC := TMemoryStream.Create; CompressStream(ISFoto,ISFotoC); CompressStream(ISFirma,ISFirmaC); CompressStream(ISHuella,ISHuellaC); end; procedure TfrmMain.pLoadImage(InputXml,OutputXml:TXmlDocument); begin end; initialization {$I unitmain.lrs} end.
unit PGoodsEdit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, stdctrls, dbtables, extctrls, RxCtrls, dbctrls, db, SelectDlg, PLabelPanel, LookupControls; type TDisplayLevel = (dlNone,dlGoods,dlStock,dlStockCode); TPGoodsEdit = class(TCustomControl) private { Private declarations } FCheck: Boolean; FDatabaseName: string; FDisplayLevel: TDisplayLevel; FEdit: TEdit; FFormatIsOk: Boolean; FGoods: string; FGoodsLen: integer; FIsInDataBase: Boolean; FLabel: TRxLabel; FLabelStyle: TLabelStyle; FLookField: string; FLookFieldCaption: string; FLookSubField: string; FLookSubFieldCaption: string; FParentFont: Boolean; FStock: string; FStockCode: string; FStockCodeLen: integer; FStockLen: integer; FSubFieldControl: TPLabelPanel; FTableName: string; FQuery: TQuery; protected { Protected declarations } function GetCaption:TCaption; function GetEditFont:TFont; function GetEditWidth:integer; function GetGoods:string; function GetLabelFont: TFont; function GetRdOnly:Boolean; function DefaultString(ALen:integer):string; function ExtendText:boolean; function FindCurrent(var LabelText: string):Boolean; function GetStock:string; function GetStockCode:string; function GetText: string; procedure ControlExit(Sender: TObject); procedure ControlDblClick(Sender: TObject); procedure SetDisplayLevel(Value: TDisplayLevel); procedure EditKeyPress(Sender: TObject; var Key: Char); procedure Paint;override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; procedure SetCaption(Value: TCaption); procedure SetDataBaseName(Value: string); procedure SetEditWidth(Value: integer); procedure SetEditFont(Value: TFont); procedure SetLabelFont(Value: TFont); procedure SetLabelStyle(Value: TLabelStyle); procedure SetRdOnly(Value: Boolean); procedure SetParentFont(Value: Boolean); procedure SetText(Value: string); procedure TextChange(Sendor: TObject); public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy;override; function CheckExist: Boolean; property FormatIsOk: Boolean read FFormatIsOk write FFormatIsOk; property Goods:string read GetGoods; property GoodsLen:integer read FGoodsLen; property IsInDataBase: Boolean read FIsInDataBase write FIsInDataBase; property StockLen:integer read FStockLen; property StockCodeLen:integer read FStockCodeLen; property Stock:string read GetStock; property StockCode:string read GetStockCode; published { Published declarations } property Caption:TCaption read GetCaption write SetCaption; property Check: Boolean read FCheck write FCheck; property DatabaseName: string read FDatabaseName write SetDatabaseName; property DisplayLevel:TDisplayLevel read FDisplayLevel write SetDisplayLevel; property EditFont:TFont read GetEditFont write SetEditFont; property EditWidth:integer read GetEditWidth write SetEditWidth; property LabelFont: TFont read GetLabelFont write SetLabelFont; property LabelStyle: TLabelStyle read FLabelStyle write SetLabelStyle default Normal; property LookFieldCaption:string read FLookFieldCaption write FLookFieldCaption; property LookSubFieldCaption:string read FLookSubFieldCaption write FLookSubFieldCaption; property ParentFont : Boolean read FParentFont write SetParentFont; property RdOnly: Boolean read GetRdOnly write SetRdOnly; property SubFieldControl: TPLabelPanel read FSubFieldControl write FSubFieldControl; property TabOrder; property Text: string read GetText write SetText; end; procedure Register; implementation constructor TPGoodsEdit.Create (AOwner: TComponent); begin inherited Create(AOwner); FLabel := TRxLabel.Create(Self); FLabel.Parent := Self; FLabel.ShadowSize := 0; FLabel.Layout := tlCenter; FLabel.AutoSize := False; FLabel.Visible := True; FLabel.ParentFont := False; FLabel.Font.Size := 11; FLabel.Font.Name := '宋体'; FEdit := TEdit.Create(Self); FEdit.Parent := Self; FEdit.Visible := True; FEdit.Font.Size := 9; FEdit.Font.Name := '宋体'; FEdit.OnExit := ControlExit; FEdit.OnDblClick := ControlDblClick; FEdit.OnKeyPress := EditKeyPress; FEdit.OnChange := TextChange; FLabel.FocusControl := FEdit; Height := 20; FLabel.Height := Height; FEdit.Height := Height; Width := 200; FEdit.Width := 140; FLabel.Width := Width-FEdit.Width; FEdit.Left := FLabel.Width; FQuery := TQuery.Create(Self); LabelStyle := Normal; FTableName := 'tbGoods'; FLookField := 'STOCKCODE'; FLookSubField := 'STK_NAME'; FGoodsLen := 4; FStockLen := 9; FStockCodeLen := 13; ParentFont := False; FIsInDataBase := False; FFormatIsOk := False; end; destructor TPGoodsEdit.Destroy; begin FEdit.Free; FQuery.Free; FLabel.Free; inherited Destroy; end; function TPGoodsEdit.GetLabelFont: TFont; begin Result := FLabel.Font; end; procedure TPGoodsEdit.SetLabelFont(Value: TFont); begin FLabel.Font := Value; end; function TPGoodsEdit.CheckExist: Boolean; var LabelText : string; begin Result := False; LabelText := ''; if Check then begin if not ExtendText then Result := True else if not FindCurrent(LabelText) then Result := False; end else begin if not ExtendText then Result := True; FindCurrent(LabelText); end; if LabelText <> '' then FIsInDataBase := True else FIsInDataBase := False; if FSubFieldControl <> nil then (FSubFieldControl as TPLabelPanel).Caption := LabelText; end; function TPGoodsEdit.ExtendText:boolean; var TextLen: integer; begin Result := True; FFormatIsOk := True; TextLen := Length(FEdit.Text); case FDisplayLevel of dlNone : if (TextLen<>0) and (TextLen <> FGoodsLen) and (TextLen <> FStockLen) and (TextLen <> FStockCodeLen) then begin Result := False; FFormatIsOk := False; Exit; end; dlGoods : if TextLen <> FGoodsLen then begin Result := False; FFormatIsOk := False; Exit; end; dlStock : if TextLen <> FStockLen then begin Result := False; FFormatIsOk := False; Exit; end; dlStockCode : if TextLen <> FStockCodeLen then begin Result := False; FFormatIsOk := False; Exit; end; end; if TextLen=0 then begin FGoods := ''; FStock := ''; FStockCode := ''; end else if TextLen=FGoodsLen then begin FGoods := FEdit.Text; FStock := FGoods+DefaultString(FStockLen-FGoodsLen); FStockCode := FStock+DefaultString(FStockCodeLen-FStockLen); end else if TextLen=FStockLen then begin FGoods := Copy(FEdit.Text,1,FGoodsLen); FStock := FEdit.Text; FStockCode := FStock+DefaultString(FStockCodeLen-FStockLen); end else if TextLen=FStockCodeLen then begin FGoods := Copy(FEdit.Text,1,FGoodsLen); FStock := Copy(FEdit.Text,1,FStockLen); FStockCode := FEdit.Text; end; end; function TPGoodsEdit.FindCurrent(var LabelText: string):Boolean; begin if (DisplayLevel = dlNone) and (FEdit.Text = '') then begin LabelText := ''; Result := True; Exit; end; FQuery.DatabaseName := FDatabaseName; FQuery.SQL.Clear; FQuery.SQL.Add('Select * from '+FTableName + ' where stockcode = ''' + FStockCode +''''); FQuery.Open; if not FQuery.Locate(FLookField, FStockCode,[]) then begin Result := False; LabelText := ''; end else begin Result := True; LabelText := FQuery.FieldByName(FLookSubField).AsString; end; FQuery.Close; end; function TPGoodsEdit.GetCaption:TCaption; begin Result := FLabel.Caption; end; function TPGoodsEdit.DefaultString(ALen:integer):string; var i: integer; begin if ALen<1 then Result := '' else begin Result := ''; for i := 1 to ALen-1 do Result := Result + '0'; Result := Result + '1'; end; end; function TPGoodsEdit.GetEditFont:TFont; begin Result := FEdit.Font; end; function TPGoodsEdit.GetEditWidth:integer; begin Result := FEdit.Width; end; function TPGoodsEdit.GetGoods:string; var LabelText: string; begin if ExtendText then begin Result := FGoods; end else begin FGoods := Copy(FEdit.Text,1,FGoodsLen); FStock := Copy(FEdit.Text,1,FStockLen); FStockCode := Copy(FEdit.Text,1,FStockcodeLen); Result := FGoods; end; end; function TPGoodsEdit.GetRdOnly:Boolean; begin Result := FEdit.ReadOnly; end; function TPGoodsEdit.GetStock:string; var LabelText: string; begin if ExtendText then begin Result := FStock; end else begin FGoods := Copy(FEdit.Text,1,FGoodsLen); FStock := Copy(FEdit.Text,1,FStockLen); FStockCode := Copy(FEdit.Text,1,FStockcodeLen); Result := FStock; end; end; function TPGoodsEdit.GetStockCode:string; var LabelText : string; begin if ExtendText then begin Result := FStockCode; end else begin FGoods := Copy(FEdit.Text,1,FGoodsLen); FStock := Copy(FEdit.Text,1,FStockLen); FStockCode := Copy(FEdit.Text,1,FStockcodeLen); Result := FStockCode; end; end; function TPGoodsEdit.GetText: string; begin Result := FEdit.Text ; end; procedure TPGoodsEdit.ControlDblClick(Sender: TObject); var SltDlg: TfrmSelectDlg; begin FQuery.DatabaseName := FDatabaseName; FQuery.SQL.Clear; FQuery.SQL.Add('Select * from '+FTableName); FQuery.Open; if (not RdOnly) and (not FQuery.IsEmpty) then begin SltDlg := TfrmSelectDlg.Create(Self); with SltDlg do begin SelectDataSource.DataSet := FQuery; grdSelect.Columns.Clear; grdSelect.Columns.Add; grdSelect.Columns.Items[0].FieldName := FLookField; grdSelect.Columns.Items[0].Title.Caption := FLookFieldCaption; grdSelect.Columns.Items[0].Title.Font.Size := 10; grdSelect.Columns.Add; grdSelect.Columns.Items[1].FieldName := FLookSubField; grdSelect.Columns.Items[1].Title.Caption := FLookSubFieldCaption; grdSelect.Columns.Items[1].Title.Font.Size := 10; end; if SltDlg.ShowModal=mrOK then begin FEdit.Text := FQuery.FieldByName(FLookField).AsString; if FSubFieldControl<>nil then (FSubFieldControl as TPLabelPanel).Caption := FQuery.FieldByName(FLookSubField).AsString; end; SltDlg.Free; end; FQuery.Close; end; procedure TPGoodsEdit.ControlExit; begin end; procedure TPGoodsEdit.EditKeyPress(Sender: TObject; var Key: Char); var LabelText : string; fgError : Boolean; begin if Key = #13 then begin fgError := False; LabelText := ''; if Check then begin if not ExtendText then fgError := True else if not FindCurrent(LabelText) then fgError := True; end else begin if not ExtendText then fgError := True; FindCurrent(LabelText); end; if fgError then Application.MessageBox('输入不合法!','错误',MB_OK); if FSubFieldControl <> nil then (FSubFieldControl as TPLabelPanel).Caption := LabelText; end; end; procedure TPGoodsEdit.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); begin if AHeight < 20 then AHeight := 20; if AHeight >50 then AHeight := 50; inherited; FEdit.Height := AHeight; FLabel.Height := AHeight; end; procedure TPGoodsEdit.SetCaption(Value: TCaption); begin FLabel.Caption := Value; end; procedure TPGoodsEdit.SetDataBaseName(Value: string); begin FDataBaseName := Value; if Value = '' then begin Check := False; end; end; procedure TPGoodsEdit.SetDisplayLevel(Value : TDisplayLevel); begin FEdit.Text := ''; FDisplayLevel := Value; Case Value of dlNone : FEdit.MaxLength := FStockCodeLen; dlGoods : FEdit.MaxLength := FGoodsLen; dlStock : FEdit.MaxLength := FStockLen; dlStockCode : FEdit.MaxLength := FStockCodeLen; end; end; procedure TPGoodsEdit.SetEditFont(Value: TFont); begin FEdit.Font.Assign(Value); FLabel.Height := FEdit.Height; Height := FEdit.Height; end; procedure TPGoodsEdit.SetEditWidth(Value: integer); begin FEdit.Width := Value; FEdit.Left := Width-Value; FLabel.Width := FEdit.Left; end; procedure TPGoodsEdit.SetLabelStyle (Value: TLabelStyle); begin FLabelStyle := Value; case Value of Conditional: begin FLabel.Font.Color := clBlack; FLabel.Font.Style := [fsUnderline]; end; Normal: begin FLabel.Font.Color := clBlack; FLabel.Font.Style := []; end; NotnilAndConditional: begin FLabel.Font.Color := clTeal; FLabel.Font.Style := [fsUnderline]; end; Notnil: begin FLabel.Font.Color := clTeal; FLabel.Font.Style := []; end; end; end; procedure TPGoodsEdit.SetParentFont(Value: Boolean); begin inherited; FEdit.ParentFont := Value; Flabel.ParentFont := Value; FParentFont := Value; end; procedure TPGoodsEdit.SetRdOnly(Value: Boolean); begin FEdit.ReadOnly := Value; if Value then FEdit.Color := clSilver else FEdit.Color := clWhite; end; procedure TPGoodsEdit.SetText(Value: string); begin FEdit.Text := Value; end; procedure TPGoodsEdit.Paint; begin FLabel.Height := Height; FEdit.Height := Height; FLabel.Width := Width-FEdit.Width; FEdit.Left := FLabel.Width; SetLabelStyle(LabelStyle); inherited Paint; end; procedure TPGoodsEdit.TextChange(Sendor: TObject); begin FFormatIsOk := ExtendText; end; procedure Register; begin RegisterComponents('PosControl2', [TPGoodsEdit]); end; end.
unit frm_main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VclTee.TeeGDIPlus, VCLTee.TeEngine, VCLTee.TeeProcs, VCLTee.Chart, System.ImageList, Vcl.ImgList, RzPanel, Vcl.Menus, ActnCtrls, System.Actions, Vcl.ActnList, Vcl.ActnMan, Vcl.ExtCtrls, VCLTee.Series, RzStatus, RzButton, unit_messages; type TfrmMain = class(TForm) StatusBar: TRzStatusBar; MainMenu: TMainMenu; File1: TMenuItem; Open1: TMenuItem; Save1: TMenuItem; N1: TMenuItem; Print1: TMenuItem; N2: TMenuItem; Exit1: TMenuItem; Data1: TMenuItem; Fit1: TMenuItem; Help1: TMenuItem; Edit1: TMenuItem; Preferences1: TMenuItem; MainToolBar: TRzToolbar; ImageList32: TImageList; Chart: TChart; Actions: TActionList; actFileExit: TAction; MainSeries: TLineSeries; actDataImport: TAction; dlgImportData: TOpenDialog; Importformfile1: TMenuItem; actFitGauss: TAction; Gauss1: TMenuItem; SumSeries: TLineSeries; pnlChi: TRzStatusPane; Window1: TMenuItem; actWinShowLog: TAction; ShowLog1: TMenuItem; actWinFunctions: TAction; Params1: TMenuItem; Background: TLineSeries; btnBtnOpen: TRzToolButton; btnBtnSave: TRzToolButton; btnImport: TRzToolButton; btnFit: TRzToolButton; btnFunctionsWindow: TRzToolButton; actFileSave: TAction; actFileOpen: TAction; dlgSave: TSaveDialog; dlgOpen: TOpenDialog; StatusX: TRzStatusPane; StatusY: TRzStatusPane; actResultExportClpbrd: TAction; BtnCopyAll: TRzToolButton; oolk1: TMenuItem; actToolsShift: TAction; Shift1: TMenuItem; actFileSaveAs: TAction; Saveas1: TMenuItem; actFileNew: TAction; BtnNew: TRzToolButton; actFileLoadFunctions: TAction; N3: TMenuItem; N4: TMenuItem; Loadfunctions1: TMenuItem; procedure actFileExitExecute(Sender: TObject); procedure actDataImportExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure actFitGaussExecute(Sender: TObject); procedure actWinShowLogExecute(Sender: TObject); procedure actWinFunctionsExecute(Sender: TObject); procedure actFileSaveExecute(Sender: TObject); procedure actFileOpenExecute(Sender: TObject); procedure ChartDblClick(Sender: TObject); procedure ChartMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure ChartClickSeries(Sender: TCustomChart; Series: TChartSeries; ValueIndex: Integer; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure ChartMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure actResultExportClpbrdExecute(Sender: TObject); procedure actToolsShiftExecute(Sender: TObject); procedure actFileSaveAsExecute(Sender: TObject); procedure actFileNewExecute(Sender: TObject); procedure actFileLoadFunctionsExecute(Sender: TObject); private { Private declarations } FFileName: string; FLastX: single; ResultSeries: array of TLineSeries; FLastY: Single; FSeriesSelected: Boolean; FSeriesIndex: Integer; SeriesDragStartX: Integer; SeriesDragStartY: Integer; FPeakSelected: Boolean; procedure ClearSeries; procedure OnCalcMessage(var Msg: TMessage); message WM_RECALC; procedure PlotGraphs; procedure UpdateGraphs; procedure SetCaption; public { Public declarations } end; var frmMain: TfrmMain; implementation uses unit_utils, unit_GaussFit, unit_const, frm_log, frm_EditorTest, ClipBrd; {$R *.dfm} procedure TfrmMain.actDataImportExecute(Sender: TObject); begin if dlgImportData.Execute then begin SeriesFromFile(MainSeries, Background, dlgImportData.FileName); end; end; procedure TfrmMain.actFileExitExecute(Sender: TObject); begin Close; end; procedure TfrmMain.actFileLoadFunctionsExecute(Sender: TObject); var Data, BG: TDataArray; begin if dlgOpen.Execute then begin ClearSeries; Fit.Zero; Data := SeriesToData(MainSeries); BG := SeriesToData(Background); LoadProject(MainSeries, Background, dlgOpen.FileName, True); Fit.NMax := 0; Fit.Process(Data, BG); PlotGraphs; Fit.NMax := 5000; SetCaption; end;end; procedure TfrmMain.actFileNewExecute(Sender: TObject); begin MainSeries.Clear; Background.Clear; ClearSeries; Fit.Zero; FFileName := 'NONAME'; SetCaption; end; procedure TfrmMain.actFileOpenExecute(Sender: TObject); var Data, BG: TDataArray; begin if dlgOpen.Execute then begin FFileName := dlgOpen.FileName; LoadProject(MainSeries, Background, FFileName); ClearSeries; Data := SeriesToData(MainSeries); BG := SeriesToData(Background); Fit.NMax := 0; Fit.Process(Data, BG); PlotGraphs; Fit.NMax := 5000; SetCaption; end; end; procedure TfrmMain.actFileSaveAsExecute(Sender: TObject); begin if dlgSave.Execute then begin FFileName := dlgSave.FileName; SaveProject(MainSeries, Background, FFileName); SetCaption; end; end; procedure TfrmMain.actFileSaveExecute(Sender: TObject); begin if FFileName = 'NONAME' then actFileSaveExecute(Sender) else SaveProject(MainSeries, Background, FFileName); SetCaption; end; procedure TfrmMain.PlotGraphs; var i: Integer; begin SetLength(ResultSeries, High(Fit.Functions) + 1); for I := 0 to High(ResultSeries) do begin ResultSeries[i] := TLineSeries.Create(Chart); ResultSeries[i].Tag := 100 + i; Chart.AddSeries(ResultSeries[i]); ResultSeries[i].LinePen.Width := 2; end; for i := 0 to High(Fit.Result) do begin DataToSeries(Fit.Result[i], ResultSeries[i]); frmLog.Memo.Lines.Add('Peak ' + IntToStr(i + 1) + ' ' + Fit.Functions[i].ToString); end; DataToSeries(Fit.Sum, SumSeries); pnlChi.Caption := FloatToStrF(Fit.LastChiSqr, ffFixed, 6, 3); end; procedure TfrmMain.SetCaption; begin Caption := 'XPS Peak Fit: ' + ExtractFileName(FFileName); end; procedure TfrmMain.actFitGaussExecute(Sender: TObject); var Data, BG: TDataArray; begin try Screen.Cursor := crHourGlass; ClearSeries; Data := SeriesToData(MainSeries); BG := SeriesToData(Background); Fit.Process(Data, BG); PlotGraphs; finally Screen.Cursor := crDefault; end; end; procedure TfrmMain.actResultExportClpbrdExecute(Sender: TObject); var i, j: Integer; SL: TStringList; S: string; procedure AddToLine(Val: single; var S: string); begin if S = '' then S := FloatToStrF(Val, ffFixed, 5, 2 ) else S := S + chr(9) + FloatToStrF(Val, ffFixed, 5, 2); end; begin SL := TStringList.Create; try S := 'Binding energy' + chr(9) + 'Intensity' + chr(9) + 'Sum' + chr(9) + 'Background'; for j := 0 to High(ResultSeries) do S := S + chr(9) + 'Peak ' + IntToStr(j+1); SL.Add(S); S := 'eV'; for j := 0 to High(ResultSeries) + 3 do S := S + chr(9) + 'cps'; SL.Add(S); S := ' '+ chr(9) + ' ' + chr(9) + ' '+ chr(9) + ' '; for j := 0 to High(ResultSeries) do S := S + chr(9) + FloatToStrF(Fit.Functions[j].xc.Last, ffFixed, 5, 2); SL.Add(S); for I := 0 to MainSeries.XValues.Count - 2 do begin S := ''; AddToLine(MainSeries.XValue[i], S); AddToLine(MainSeries.YValue[i], S); AddToLine(SumSeries.YValue[i], S); AddToLine(Background.YValue[i], S); for j := 0 to High(ResultSeries) do AddToLine(ResultSeries[j].YValue[i], S); SL.Add(S); end; Clipboard.AsText := SL.Text; finally FreeAndNil(SL); end; end; procedure TfrmMain.actToolsShiftExecute(Sender: TObject); var DX : single; i: integer; S : string; begin S := InputBox('Fit shift','Input hte shifting value',''); if S = '' then Exit; DX := StrToFloat(S); for I := 0 to MainSeries.XValues.Count - 2 do begin MainSeries.XValue[i] := MainSeries.XValue[i] + DX; Background.XValue[i] := Background.XValue[i] + DX; end; end; procedure TfrmMain.actWinFunctionsExecute(Sender: TObject); begin frmEditorTest.WriteData(Fit.Functions); frmEditorTest.MainForm := Self.Handle; frmEditorTest.Show; end; procedure TfrmMain.actWinShowLogExecute(Sender: TObject); begin frmLog.Show; end; procedure TfrmMain.ChartClickSeries(Sender: TCustomChart; Series: TChartSeries; ValueIndex: Integer; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var yv: single; MaxY: single; begin FSeriesSelected := True; if Series.Tag >= 100 then FSeriesIndex := Series.Tag - 100; SeriesDragStartX := X; SeriesDragStartY := Y; yv := Series.YScreenToValue(Y); MaxY := Series.MaxYValue; if (MaxY > (0.7 * yv)) and (MaxY < (1.1 * yv)) then FPeakSelected := True else FPeakSelected := False; end; procedure TfrmMain.UpdateGraphs; var Data, BG: TDataArray; begin ClearSeries; Data := SeriesToData(MainSeries); BG := SeriesToData(Background); Fit.NMax := 0; Fit.Process(Data, BG); PlotGraphs; Fit.NMax := 5000; end; procedure TfrmMain.ChartDblClick(Sender: TObject); begin if frmEditorTest.Visible then begin frmEditorTest.AddFunction(FLastX, FLastY); Fit.Functions := frmEditorTest.GetData; UpdateGraphs; end; end; procedure TfrmMain.ChartMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var xv, yv: single; R: TRect; DX, DY: single; begin xv := MainSeries.XScreenToValue(X); yv := MainSeries.YScreenToValue(Y); StatusX.Caption := FloatToStrF(xv, ffFixed, 6, 2); StatusY.Caption := FloatToStrF(yv, ffFixed, 6, 2); R := Chart.Legend.RectLegend; if (X > R.Left) and (X < R.Right) and (Y > R.Top) and (Y < R.Bottom) then Chart.Cursor := crArrow else Chart.Cursor := crCross; FLastX := xv; FLastY := yv; if FSeriesSelected then begin DX := MainSeries.XScreenToValue(X) - MainSeries.XScreenToValue(SeriesDragStartX); DY := MainSeries.YScreenToValue(Y) - MainSeries.YScreenToValue(SeriesDragStartY); if FPeakSelected then begin if Abs(DX) > abs(DY) then Fit.Functions[FSeriesIndex].xc.Last := Fit.Functions[FSeriesIndex].xc.Last + DX else Fit.Functions[FSeriesIndex].A.Last := Fit.Functions[FSeriesIndex].A.Last + DY end else Fit.Functions[FSeriesIndex].W.Last := Fit.Functions[FSeriesIndex].W.Last + DX; UpdateGraphs; SeriesDragStartX := X; SeriesDragStartY := Y; end; end; procedure TfrmMain.ChartMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if FSeriesSelected then begin FSeriesSelected := False; frmEditorTest.WriteData(Fit.Functions); end; end; procedure TfrmMain.ClearSeries; var i: Integer; begin SumSeries.Clear; for I := 0 to High(ResultSeries) do ResultSeries[i].Free; SetLength(ResultSeries, 0); end; procedure TfrmMain.FormCreate(Sender: TObject); begin FFileName := 'NONAME'; Fit := TFit.Create; // {$IFDEF DEBUG} // if ParamCount = 1 then // SeriesFromFile(MainSeries, Background, ParamStr(1)); // {$ENDIF} SetCaption; end; procedure TfrmMain.FormDestroy(Sender: TObject); begin FreeAndNil(Fit); end; procedure TfrmMain.OnCalcMessage(var Msg: TMessage); begin Fit.Functions := frmEditorTest.GetData; actFitGaussExecute(Self); frmEditorTest.WriteData(Fit.Functions); end; end.
unit JuridicalSettingsTest; interface uses dbTest, dbObjectTest, ObjectTest; type TJuridicalSettingsTest = class (TdbObjectTestNew) published procedure ProcedureLoad; override; procedure Test; override; end; TJuridicalSettingsObjectTest = class(TObjectTest) function InsertDefault: integer; override; public function InsertUpdateJuridicalSettings(const Id, JuridicalId: integer; Bonus: real): integer; constructor Create; override; end; implementation uses DB, UtilConst, TestFramework, SysUtils, JuridicalTest; { TdbUnitTest } procedure TJuridicalSettingsTest.ProcedureLoad; begin ScriptDirectory := LocalProcedurePath + 'OBJECTS\JuridicalSettings\'; inherited; end; procedure TJuridicalSettingsTest.Test; var Id: integer; RecordCount: Integer; ObjectTest: TJuridicalSettingsObjectTest; begin ObjectTest := TJuridicalSettingsObjectTest.Create; // Получим список RecordCount := ObjectTest.GetDataSet.RecordCount; // Вставка Типа импорта Id := ObjectTest.InsertDefault; try // Получение данных о роли with ObjectTest.GetRecord(Id) do begin Check((FieldByName('Bonus').AsFloat = 10), 'Не сходятся данные Id = ' + IntToStr(id)); end; finally ObjectTest.Delete(Id); end; end; { TJuridicalSettingsTest } constructor TJuridicalSettingsObjectTest.Create; begin inherited Create; spInsertUpdate := 'gpInsertUpdate_Object_JuridicalSettings'; spSelect := 'gpSelect_Object_JuridicalSettings'; spGet := 'gpGet_Object_JuridicalSettings'; end; function TJuridicalSettingsObjectTest.InsertDefault: integer; var JuridicalId: Integer; begin JuridicalId := TJuridical.Create.GetDefault; result := InsertUpdateJuridicalSettings(0, JuridicalId, 10); inherited; end; function TJuridicalSettingsObjectTest.InsertUpdateJuridicalSettings (const Id, JuridicalId: integer; Bonus: real): integer; begin FParams.Clear; FParams.AddParam('ioId', ftInteger, ptInputOutput, Id); FParams.AddParam('inJuridicalId', ftInteger, ptInput, JuridicalId); FParams.AddParam('inBonus', ftFloat, ptInput, Bonus); result := InsertUpdate(FParams); end; initialization TestFramework.RegisterTest('Объекты', TJuridicalSettingsTest.Suite); end.
unit Unit1; { Requiriments: Project-Options-Entitlement List-Secure File Sharing = True For Delphi 10.4+ there is no need to exchange the provider_paths.xml, while checking TRUE "Secure File Sharing" Delphi will create its own provider_paths.xml, doesn't matter if you exchange it or not Tests on: Delphi 11 + 2 Patchs: Android 10, 12 } interface uses System.Permissions, uPdfPrint, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts; type TForm1 = class(TForm) btnPreview: TButton; Layout1: TLayout; btnShare: TButton; procedure btnPreviewTap(Sender: TObject; const Point: TPointF); private FIsToShare: Boolean; procedure PdfFunction; { This sample is not about Permissions, please, take a look at some other sample to learn more regarding this subject } procedure DisplayRationale( Sender: TObject; const APermissions: {$IF CompilerVersion >= 35.0}TClassicStringDynArray{$ELSE}TArray<string>{$ENDIF}; const APostRationaleProc: TProc ); procedure GetPermissionRequestResult( Sender: TObject; const APermissions: {$IF CompilerVersion >= 35.0}TClassicStringDynArray{$ELSE}TArray<string>{$ENDIF}; const AGrantResults: {$IF CompilerVersion >= 35.0}TClassicPermissionStatusDynArray{$ELSE}TArray<TPermissionStatus>{$ENDIF} ); { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation uses {$IFDEF ANDROID} Androidapi.Helpers, Androidapi.JNI.JavaTypes, Androidapi.JNI.Os, {$ENDIF} FMX.DialogService; {$R *.fmx} procedure TForm1.btnPreviewTap(Sender: TObject; const Point: TPointF); var FPermissionReadExternalStorage, FPermissionWriteExternalStorage: string; begin { Since Android10* (newer) the Android file manager was changed, so we are using now System.IOUtils.TPath.GetPublicPath instead the old version the path on your Cellphone is on /storage/emulated/0/Android/data/<Project PackageName>/files It is a public path which can be reached through APP File Manager OR your own PC } FIsToShare := Sender = btnShare; { This sample is not about Permissions, please, take a look at some other sample to learn more regarding this subject } FPermissionReadExternalStorage := JStringToString(TJManifest_permission.JavaClass.READ_EXTERNAL_STORAGE); FPermissionWriteExternalStorage := JStringToString(TJManifest_permission.JavaClass.WRITE_EXTERNAL_STORAGE); PermissionsService.RequestPermissions([ FPermissionReadExternalStorage, FPermissionWriteExternalStorage], GetPermissionRequestResult, DisplayRationale); end; procedure TForm1.PdfFunction; var lPdf: TPDFPrint; vSizeFont, vFormFont: Integer; pFase: String; I, Conta: Integer; begin Conta := 0; vSizeFont := 10; vFormFont := 8; lPdf := TPDFPrint.Create('SoretoPdfPrint'); try lPdf.Open; lPdf.FonteName := 'Arial'; lPdf.BordaSupInf := 6; lPdf.BordaLefRig := 25; lPdf.ImpC(1, 1, 'Something here', Normal, TAlphaColors.Black, vSizeFont); lPdf.ImpLinhaH(Conta, 1, 52, TAlphaColors.Gray); lPdf.Close; if FIsToShare then lPdf.Share else lPdf.Preview; finally lPdf.Free; end; end; procedure TForm1.DisplayRationale(Sender: TObject; const APermissions: {$IF CompilerVersion >= 35.0}TClassicStringDynArray{$ELSE}TArray<string>{$ENDIF}; const APostRationaleProc: TProc); begin TDialogService.ShowMessage('The permissions are needed', procedure(const AResult: TModalResult) begin APostRationaleProc; end) end; procedure TForm1.GetPermissionRequestResult(Sender: TObject; const APermissions: {$IF CompilerVersion >= 35.0}TClassicStringDynArray{$ELSE}TArray<string>{$ENDIF}; const AGrantResults: {$IF CompilerVersion >= 35.0}TClassicPermissionStatusDynArray{$ELSE}TArray<TPermissionStatus>{$ENDIF} ); begin // 2 permissions involved: CAMERA, READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE if (Length(AGrantResults) = 2) and (AGrantResults[0] = TPermissionStatus.Granted) and (AGrantResults[1] = TPermissionStatus.Granted) then PdfFunction else TDialogService.ShowMessage('Rquired permissions are not granted'); end; end.
// ************************************************************************ // // The types declared in this file were generated from data read from the // WSDL File described below: // WSDL : http://192.168.0.131:8080/SERVERPEDIDO.apw?WSDL // >Import : http://192.168.0.131:8080/SERVERPEDIDO.apw?WSDL>0 // Encoding : utf-8 // Version : 1.0 // (07/04/2017 10:31:11 - - $Rev: 24171 $) // ************************************************************************ // unit SERVERPEDIDO; interface uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns; const IS_OPTN = $0001; IS_UNBD = $0002; IS_REF = $0080; type // ************************************************************************ // // The following types, referred to in the WSDL document are not being represented // in this file. They are either aliases[@] of other types represented or were referred // to but never[!] declared in the document. The types from the latter category // typically map to predefined/known XML or Embarcadero types; however, they could also // indicate incorrect WSDL documents that failed to declare or import a schema type. // ************************************************************************ // // !:string - "http://www.w3.org/2001/XMLSchema"[Gbl] // !:float - "http://www.w3.org/2001/XMLSchema"[Gbl] // !:date - "http://www.w3.org/2001/XMLSchema"[Gbl] AITENSPED = class; { "http://192.168.0.131:8080/"[GblCplx] } C5PEDIDO = class; { "http://192.168.0.131:8080/"[GblCplx] } VRETORNO = class; { "http://192.168.0.131:8080/"[GblCplx] } C6ITEMPEDIDO = class; { "http://192.168.0.131:8080/"[GblCplx] } ARRAYOFC6ITEMPEDIDO = array of C6ITEMPEDIDO; { "http://192.168.0.131:8080/"[GblCplx] } // ************************************************************************ // // XML : AITENSPED, global, <complexType> // Namespace : http://192.168.0.131:8080/ // ************************************************************************ // AITENSPED = class(TRemotable) private FC6ITENS: ARRAYOFC6ITEMPEDIDO; public destructor Destroy; override; published property C6ITENS: ARRAYOFC6ITEMPEDIDO read FC6ITENS write FC6ITENS; end; // ************************************************************************ // // XML : C5PEDIDO, global, <complexType> // Namespace : http://192.168.0.131:8080/ // ************************************************************************ // C5PEDIDO = class(TRemotable) private FPC5_AGENCIA: string; FPC5_CLIENTE: string; FPC5_COMIS1: Single; FPC5_COMIS2: Single; FPC5_COMIS3: Single; FPC5_CONDPAG: string; FPC5_CONTA: string; FPC5_EMISSAO: TXSDate; FPC5_EMPRESA: string; FPC5_FILIAL: string; FPC5_FORMA: string; FPC5_GERENTE: string; FPC5_GRPREP: string; FPC5_LOJACLI: string; FPC5_MENNOTA: string; FPC5_PARCELA: string; FPC5_PORTADOR: string; FPC5_SUPERVISOR: string; FPC5_TIPO: string; FPC5_TPCLI: string; FPC5_TPFRETE: string; FPC5_TRANSP: string; FPC5_TROCA: string; FPC5_VENCIMENTO: TXSDate; FPC5_VEND1: string; FPC5_VEND2: string; FPC5_VEND3: string; FPC5_X_NRMOB: string; FPC5_TABELA: string; public destructor Destroy; override; published property PC5_AGENCIA: string read FPC5_AGENCIA write FPC5_AGENCIA; property PC5_CLIENTE: string read FPC5_CLIENTE write FPC5_CLIENTE; property PC5_COMIS1: Single read FPC5_COMIS1 write FPC5_COMIS1; property PC5_COMIS2: Single read FPC5_COMIS2 write FPC5_COMIS2; property PC5_COMIS3: Single read FPC5_COMIS3 write FPC5_COMIS3; property PC5_CONDPAG: string read FPC5_CONDPAG write FPC5_CONDPAG; property PC5_CONTA: string read FPC5_CONTA write FPC5_CONTA; property PC5_EMISSAO: TXSDate read FPC5_EMISSAO write FPC5_EMISSAO; property PC5_EMPRESA: string read FPC5_EMPRESA write FPC5_EMPRESA; property PC5_FILIAL: string read FPC5_FILIAL write FPC5_FILIAL; property PC5_FORMA: string read FPC5_FORMA write FPC5_FORMA; property PC5_GERENTE: string read FPC5_GERENTE write FPC5_GERENTE; property PC5_GRPREP: string read FPC5_GRPREP write FPC5_GRPREP; property PC5_LOJACLI: string read FPC5_LOJACLI write FPC5_LOJACLI; property PC5_MENNOTA: string read FPC5_MENNOTA write FPC5_MENNOTA; property PC5_PARCELA: string read FPC5_PARCELA write FPC5_PARCELA; property PC5_PORTADOR: string read FPC5_PORTADOR write FPC5_PORTADOR; property PC5_SUPERVISOR: string read FPC5_SUPERVISOR write FPC5_SUPERVISOR; property PC5_TIPO: string read FPC5_TIPO write FPC5_TIPO; property PC5_TPCLI: string read FPC5_TPCLI write FPC5_TPCLI; property PC5_TPFRETE: string read FPC5_TPFRETE write FPC5_TPFRETE; property PC5_TRANSP: string read FPC5_TRANSP write FPC5_TRANSP; property PC5_TROCA: string read FPC5_TROCA write FPC5_TROCA; property PC5_VENCIMENTO: TXSDate read FPC5_VENCIMENTO write FPC5_VENCIMENTO; property PC5_VEND1: string read FPC5_VEND1 write FPC5_VEND1; property PC5_VEND2: string read FPC5_VEND2 write FPC5_VEND2; property PC5_VEND3: string read FPC5_VEND3 write FPC5_VEND3; property PC5_X_NRMOB: string read FPC5_X_NRMOB write FPC5_X_NRMOB; property PC5_TABELA: string read FPC5_TABELA write FPC5_TABELA; end; // ************************************************************************ // // XML : VRETORNO, global, <complexType> // Namespace : http://192.168.0.131:8080/ // ************************************************************************ // VRETORNO = class(TRemotable) private FVERRO: string; FVPEDIDO: string; FVMENSAGEM: string; published property VERRO: string read FVERRO write FVERRO; property VPEDIDO: string read FVPEDIDO write FVPEDIDO; property VMENSAGEM: string read FVMENSAGEM write FVMENSAGEM; end; // ************************************************************************ // // XML : C6ITEMPEDIDO, global, <complexType> // Namespace : http://192.168.0.131:8080/ // ************************************************************************ // C6ITEMPEDIDO = class(TRemotable) private FPC6_CF: string; FPC6_CLASFIS: string; FPC6_COMIS1: Single; FPC6_COMIS2: Single; FPC6_DESCRI: string; FPC6_DTVALID: TXSDate; FPC6_ITEM: string; FPC6_LOCAL: string; FPC6_LOTECTL: string; FPC6_PEDCLI: string; FPC6_PRCVEN: Single; FPC6_PRODUTO: string; FPC6_PRUNIT: Single; FPC6_QTDLIB: Single; FPC6_QTDVEN: Single; FPC6_SEGUM: string; FPC6_TES: string; FPC6_UM: string; FPC6_VALDESC: Single; FPC6_VALOR: Single; FPC6_X_NRMOB: string; FPC6_X_PRCTB: Single; public destructor Destroy; override; published property PC6_CF: string read FPC6_CF write FPC6_CF; property PC6_CLASFIS: string read FPC6_CLASFIS write FPC6_CLASFIS; property PC6_COMIS1: Single read FPC6_COMIS1 write FPC6_COMIS1; property PC6_COMIS2: Single read FPC6_COMIS2 write FPC6_COMIS2; property PC6_DESCRI: string read FPC6_DESCRI write FPC6_DESCRI; property PC6_DTVALID: TXSDate read FPC6_DTVALID write FPC6_DTVALID; property PC6_ITEM: string read FPC6_ITEM write FPC6_ITEM; property PC6_LOCAL: string read FPC6_LOCAL write FPC6_LOCAL; property PC6_LOTECTL: string read FPC6_LOTECTL write FPC6_LOTECTL; property PC6_PEDCLI: string read FPC6_PEDCLI write FPC6_PEDCLI; property PC6_PRCVEN: Single read FPC6_PRCVEN write FPC6_PRCVEN; property PC6_PRODUTO: string read FPC6_PRODUTO write FPC6_PRODUTO; property PC6_PRUNIT: Single read FPC6_PRUNIT write FPC6_PRUNIT; property PC6_QTDLIB: Single read FPC6_QTDLIB write FPC6_QTDLIB; property PC6_QTDVEN: Single read FPC6_QTDVEN write FPC6_QTDVEN; property PC6_SEGUM: string read FPC6_SEGUM write FPC6_SEGUM; property PC6_TES: string read FPC6_TES write FPC6_TES; property PC6_UM: string read FPC6_UM write FPC6_UM; property PC6_VALDESC: Single read FPC6_VALDESC write FPC6_VALDESC; property PC6_VALOR: Single read FPC6_VALOR write FPC6_VALOR; property PC6_X_NRMOB: string read FPC6_X_NRMOB write FPC6_X_NRMOB; property PC6_X_PRCTB: Single read FPC6_X_PRCTB write FPC6_X_PRCTB; end; // ************************************************************************ // // Namespace : http://192.168.0.131:8080/ // soapAction: http://192.168.0.131:8080/LANCAPEDIDO // transport : http://schemas.xmlsoap.org/soap/http // style : document // binding : SERVERPEDIDOSOAP // service : SERVERPEDIDO // port : SERVERPEDIDOSOAP // URL : http://192.168.0.131:8080/SERVERPEDIDO.apw // ************************************************************************ // SERVERPEDIDOSOAP = interface(IInvokable) ['{70B5C6A9-14AF-38A1-2A6C-E70CA3D247DF}'] function LANCAPEDIDO(const IPEDIDO: C5PEDIDO; const IITENS: AITENSPED): VRETORNO; stdcall; end; function GetSERVERPEDIDOSOAP(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): SERVERPEDIDOSOAP; implementation uses SysUtils; function GetSERVERPEDIDOSOAP(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): SERVERPEDIDOSOAP; const defWSDL = 'http://192.168.0.131:8080/SERVERPEDIDO.apw?WSDL'; defURL = 'http://192.168.0.131:8080/SERVERPEDIDO.apw'; defSvc = 'SERVERPEDIDO'; defPrt = 'SERVERPEDIDOSOAP'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; try Result := (RIO as SERVERPEDIDOSOAP); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; destructor AITENSPED.Destroy; var I: Integer; begin for I := 0 to System.Length(FC6ITENS)-1 do SysUtils.FreeAndNil(FC6ITENS[I]); System.SetLength(FC6ITENS, 0); inherited Destroy; end; destructor C5PEDIDO.Destroy; begin SysUtils.FreeAndNil(FPC5_EMISSAO); SysUtils.FreeAndNil(FPC5_VENCIMENTO); inherited Destroy; end; destructor C6ITEMPEDIDO.Destroy; begin SysUtils.FreeAndNil(FPC6_DTVALID); inherited Destroy; end; initialization InvRegistry.RegisterInterface(TypeInfo(SERVERPEDIDOSOAP), 'http://192.168.0.131:8080/', 'utf-8'); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(SERVERPEDIDOSOAP), 'http://192.168.0.131:8080/LANCAPEDIDO'); InvRegistry.RegisterInvokeOptions(TypeInfo(SERVERPEDIDOSOAP), ioDocument); RemClassRegistry.RegisterXSInfo(TypeInfo(ARRAYOFC6ITEMPEDIDO), 'http://192.168.0.131:8080/', 'ARRAYOFC6ITEMPEDIDO'); RemClassRegistry.RegisterXSClass(AITENSPED, 'http://192.168.0.131:8080/', 'AITENSPED'); RemClassRegistry.RegisterXSClass(C5PEDIDO, 'http://192.168.0.131:8080/', 'C5PEDIDO'); RemClassRegistry.RegisterXSClass(VRETORNO, 'http://192.168.0.131:8080/', 'VRETORNO'); RemClassRegistry.RegisterXSClass(C6ITEMPEDIDO, 'http://192.168.0.131:8080/', 'C6ITEMPEDIDO'); end.
// ************************************************************************ // // The types declared in this file were generated from data read from the // WSDL File described below: // WSDL : http://localhost:8888/wsdl/IDRX_Configuration_WS // Version : 1.0 // (5/6/2011 11:20:47 PM - 1.33.2.5) // ************************************************************************ // unit DRX_Configuration_WS; interface uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns; type // ************************************************************************ // // The following types, referred to in the WSDL document are not being represented // in this file. They are either aliases[@] of other types represented or were referred // to but never[!] declared in the document. The types from the latter category // typically map to predefined/known XML or Borland types; however, they could also // indicate incorrect WSDL documents that failed to declare or import a schema type. // ************************************************************************ // // !:int - "http://www.w3.org/2001/XMLSchema" // !:double - "http://www.w3.org/2001/XMLSchema" Settings = class; { "urn:Site" } TBoundArray = array of Integer; { "urn:Site" } // ************************************************************************ // // Namespace : urn:Site // ************************************************************************ // Settings = class(TRemotable) private FScan_step: Integer; FScan_delay: Integer; FScan_width: Integer; FStaloPort: Integer; FPower_factor_tx: Double; FStart_sample_lp: Integer; FStop_sample_lp: Integer; FStart_sample_sp: Integer; FStop_sample_sp: Integer; FThresholdSQI: Double; FC1: Double; FC2: Double; FSP_TX_PulsePosition: Integer; FLP_TX_PulsePosition: Integer; FNoise_power: Double; FNoise_source: Integer; FPower_shot: Integer; FSensibility: Integer; FDinamic_range: Integer; FRadar_constant_lp: Double; FRadar_constant_sp: Double; FMet_pot_lp: Double; FMet_pot_sp: Double; FConv_table: TBoundArray; FWS_Port: Integer; published property Scan_step: Integer read FScan_step write FScan_step; property Scan_delay: Integer read FScan_delay write FScan_delay; property Scan_width: Integer read FScan_width write FScan_width; property StaloPort: Integer read FStaloPort write FStaloPort; property Power_factor_tx: Double read FPower_factor_tx write FPower_factor_tx; property Start_sample_lp: Integer read FStart_sample_lp write FStart_sample_lp; property Stop_sample_lp: Integer read FStop_sample_lp write FStop_sample_lp; property Start_sample_sp: Integer read FStart_sample_sp write FStart_sample_sp; property Stop_sample_sp: Integer read FStop_sample_sp write FStop_sample_sp; property ThresholdSQI: Double read FThresholdSQI write FThresholdSQI; property C1: Double read FC1 write FC1; property C2: Double read FC2 write FC2; property SP_TX_PulsePosition: Integer read FSP_TX_PulsePosition write FSP_TX_PulsePosition; property LP_TX_PulsePosition: Integer read FLP_TX_PulsePosition write FLP_TX_PulsePosition; property Noise_power: Double read FNoise_power write FNoise_power; property Noise_source: Integer read FNoise_source write FNoise_source; property Power_shot: Integer read FPower_shot write FPower_shot; property Sensibility: Integer read FSensibility write FSensibility; property Dinamic_range: Integer read FDinamic_range write FDinamic_range; property Radar_constant_lp: Double read FRadar_constant_lp write FRadar_constant_lp; property Radar_constant_sp: Double read FRadar_constant_sp write FRadar_constant_sp; property Met_pot_lp: Double read FMet_pot_lp write FMet_pot_lp; property Met_pot_sp: Double read FMet_pot_sp write FMet_pot_sp; property Conv_table: TBoundArray read FConv_table write FConv_table; property WS_Port: Integer read FWS_Port write FWS_Port; end; // ************************************************************************ // // Namespace : urn:DRX_Configuration_WS-IDRX_Configuration_WS // soapAction: urn:DRX_Configuration_WS-IDRX_Configuration_WS#%operationName% // transport : http://schemas.xmlsoap.org/soap/http // style : rpc // binding : IDRX_Configuration_WSbinding // service : IDRX_Configuration_WSservice // port : IDRX_Configuration_WSPort // URL : http://localhost:8888/soap/IDRX_Configuration_WS // ************************************************************************ // IDRX_Configuration_WS = interface(IInvokable) ['{3F38E698-F6FF-D865-B8EF-51DC7DEAD009}'] function Get_Configuration: Settings; stdcall; procedure Set_Configuration(const config: Settings); stdcall; end; function GetIDRX_Configuration_WS(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): IDRX_Configuration_WS; implementation function GetIDRX_Configuration_WS(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): IDRX_Configuration_WS; const defWSDL = 'http://localhost:8888/wsdl/IDRX_Configuration_WS'; defURL = 'http://localhost:8888/soap/IDRX_Configuration_WS'; defSvc = 'IDRX_Configuration_WSservice'; defPrt = 'IDRX_Configuration_WSPort'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; try Result := (RIO as IDRX_Configuration_WS); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; initialization InvRegistry.RegisterInterface(TypeInfo(IDRX_Configuration_WS), 'urn:DRX_Configuration_WS-IDRX_Configuration_WS', ''); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(IDRX_Configuration_WS), 'urn:DRX_Configuration_WS-IDRX_Configuration_WS#%operationName%'); RemClassRegistry.RegisterXSInfo(TypeInfo(TBoundArray), 'urn:Site', 'TBoundArray'); RemClassRegistry.RegisterXSClass(Settings, 'urn:Site', 'Settings'); end.
unit AdminForm_Unit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Front_DataBase_Unit, BaseFrontForm_Unit, FrontData_Unit, ExtCtrls, AdvPanel, AdvSmoothButton, ActnList, AddUserForm_unit, EditReportForm_Unit, frmEditUsers_unit; type TCrackControl = class(TControl); TAdminForm = class(TBaseFrontForm) pnlMain: TAdvPanel; alMain: TActionList; actAddUser: TAction; btnExit: TAdvSmoothButton; btnEditReport: TAdvSmoothButton; actEditReport: TAction; btnHallsEdit: TAdvSmoothButton; btnEditUser: TAdvSmoothButton; actEditUser: TAction; actExit: TAction; procedure actAddUserExecute(Sender: TObject); procedure actEditReportExecute(Sender: TObject); procedure actEditUserExecute(Sender: TObject); procedure actExitExecute(Sender: TObject); procedure alMainExecute(Action: TBasicAction; var Handled: Boolean); private FFrontBase: TFrontBase; public property FrontBase: TFrontBase read FFrontBase write FFrontBase; end; var AdminForm: TAdminForm; implementation {$R *.dfm} procedure TAdminForm.actAddUserExecute(Sender: TObject); var FForm: TAddUserForm; begin Assert(Assigned(FFrontBase), 'FrontBase not assigned'); FForm := TAddUserForm.Create(Self); try FForm.FrontBase := FFrontBase; FForm.ShowModal; finally FForm.Free; end; end; procedure TAdminForm.actEditReportExecute(Sender: TObject); var Form: TEditReport; begin Assert(Assigned(FFrontBase), 'FrontBase not assigned'); Form := TEditReport.Create(nil); try Form.FrontBase := FFrontBase; Form.ShowModal; finally Form.Free; end; end; procedure TAdminForm.actEditUserExecute(Sender: TObject); var Form: TEditUsers; begin Assert(Assigned(FFrontBase), 'FrontBase not assigned'); Form := TEditUsers.Create(nil); try Form.FrontBase := FFrontBase; Form.ShowModal; finally Form.Free; end; end; procedure TAdminForm.actExitExecute(Sender: TObject); begin ModalResult := mrCancel; end; procedure TAdminForm.alMainExecute(Action: TBasicAction; var Handled: Boolean); var FComponent: TControl; begin inherited; if Action.ActionComponent is TControl then begin FComponent := TControl(Action.ActionComponent); if Assigned(FLogManager) then begin FLogManager.DoActionLog(FLogManager.GetCurrentUserInfo, Format('Форма %s (%s), событие %s (%s)', [Self.Caption, Self.Name, TCrackControl(FComponent).Caption, FComponent.Name])); end; end; end; end.
unit Unit3; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdUDPServer, IdGlobal, IdSocketHandle, IdBaseComponent, IdComponent, IdUDPBase, Vcl.StdCtrls, IdContext, IdCustomTCPServer, IdTCPServer, IdTCPConnection, IdTCPClient, Vcl.ExtCtrls; type TMode = (cmServer, cmFindingServer, cmClient); TForm3 = class(TForm) IdUDPServer1: TIdUDPServer; IdTCPServer1: TIdTCPServer; IdTCPClient1: TIdTCPClient; Timer1: TTimer; ListBox1: TListBox; Panel1: TPanel; Panel2: TPanel; Edit1: TEdit; Button1: TButton; Label1: TLabel; Button2: TButton; procedure IdUDPServer1UDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle); procedure Button1Click(Sender: TObject); procedure IdTCPServer1Execute(AContext: TIdContext); procedure FormDestroy(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private 宣言 } public { Public 宣言 } mode: TMode; procedure broadcastMessage(str: string); end; var Form3: TForm3; implementation {$R *.dfm} procedure TForm3.broadcastMessage(str: string); var i: integer; s: TIdContext; begin with IdTCPServer1.Contexts.LockList do for i := 0 to Count-1 do begin s:=Items[i]; s.Connection.IOHandler.Write(str); end; IdTCPServer1.Contexts.UnlockList; end; procedure TForm3.Button1Click(Sender: TObject); begin if mode = TMode.cmClient then IdTCPClient1.IOHandler.Write(Edit1.Text) else broadcastMessage(Edit1.Text); // ListBox1.Items.Insert(0, Edit1.Text); end; procedure TForm3.Button2Click(Sender: TObject); begin IdUDPServer1.Broadcast('サーバーある?', IdUDPServer1.DefaultPort); mode := TMode.cmFindingServer; end; procedure TForm3.FormDestroy(Sender: TObject); begin IdUDPServer1.Active := false; IdTCPServer1.Active := false; end; procedure TForm3.IdTCPServer1Execute(AContext: TIdContext); var s: string; begin s := AContext.Connection.IOHandler.ReadLn(#13#10); ListBox1.Items.Insert(0, s); broadcastMessage(s); end; procedure TForm3.IdUDPServer1UDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle); var s: string; ip: string; begin s := string(AData); ip := ABinding.PeerIP; if s = 'サーバーある?' then begin mode := TMode.cmServer; s := '私はサーバー'; IdUDPServer1.Send(ip, IdUDPServer1.DefaultPort, s); end else if s = '私はサーバー' then begin mode := TMode.cmClient; IdTCPClient1.Host := ip; IdTCPClient1.Connect; end; end; procedure TForm3.Timer1Timer(Sender: TObject); begin Timer1.Enabled := false; if mode <> TMode.cmFindingServer then begin Label1.Caption := '接続'; Exit; end else Label1.Caption := '接続していません'; mode := TMode.cmServer; IdTCPServer1.Active := true; end; end.
unit ufrmSameColumnsSet; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Math, System.Types, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls; type TfrmSameColumnsSet = class(TForm) btnOk: TButton; Panel1: TPanel; Label1: TLabel; edtEachPageRowCount: TEdit; pnlContainer: TPanel; procedure FormCreate(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure edtKeyPress(Sender: TObject; var Key: Char); procedure FormDestroy(Sender: TObject); procedure FormResize(Sender: TObject); private fDataMode: Byte; fMaxValue: Word; fIntervalValues: TWordDynArray; fCheckedList: TList; fEachRowValueCount: TByteDynArray; fValues: TWordDynArray; fValueChanged: Boolean; fEachPageRowCount: Word; procedure CheckBoxClick(Sender: TObject); procedure CheckBoxGroupClick(Sender: TObject); procedure BuildCheckBox(aEachRowValueCount: TByteDynArray; Offset: Byte = 0); procedure RenameCheckBox(aIntervalValues: TWordDynArray); procedure SetIntervalValues(aIntervalValues: TWordDynArray); public property DataMode: Byte read fDataMode write fDataMode; property IntervalValues: TWordDynArray read fIntervalValues write SetIntervalValues; property Values: TWordDynArray read fValues; property ValueChanged: Boolean read fValueChanged; property EachPageRowCount: Word read fEachPageRowCount; end; var frmSameColumnsSet: TfrmSameColumnsSet; const CheckBoxGroupName = 'chkGroup%d'; CheckBoxName = 'chk%d'; EachRowValueCount: TByteDynArray = [19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 17]; EachRowValueCount2: TByteDynArray = [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6]; procedure SameColumnsSet(aIntervalValues: TWordDynArray; aDataMode: Byte = 0); implementation {$R *.dfm} procedure SameColumnsSet(aIntervalValues: TWordDynArray; aDataMode: Byte); begin if not Assigned(frmSameColumnsSet) then frmSameColumnsSet := TfrmSameColumnsSet.Create(Application); frmSameColumnsSet.DataMode := aDataMode; frmSameColumnsSet.IntervalValues := aIntervalValues; frmSameColumnsSet.ShowModal; end; procedure TfrmSameColumnsSet.SetIntervalValues(aIntervalValues: TWordDynArray); var IsEqual: Boolean; i: Integer; begin IsEqual := Length(aIntervalValues) = Length(fIntervalValues); if IsEqual then begin for i := Low(fIntervalValues) to High(fIntervalValues) do begin IsEqual := fIntervalValues[i] = aIntervalValues[i]; if not IsEqual then Break; end; end; if not IsEqual then begin fIntervalValues := aIntervalValues; fMaxValue := 0; for i := Low(fIntervalValues) to High(fIntervalValues) do fMaxValue := fMaxValue + fIntervalValues[i]; case fDataMode of 1: BuildCheckBox(EachRowValueCount2); else BuildCheckBox(EachRowValueCount, 1); end; RenameCheckBox(aIntervalValues); end; end; procedure TfrmSameColumnsSet.FormCreate(Sender: TObject); begin fDataMode := 0; fValues := []; fCheckedList := TList.Create; end; procedure TfrmSameColumnsSet.FormDestroy(Sender: TObject); begin fCheckedList.Free; end; procedure TfrmSameColumnsSet.FormResize(Sender: TObject); var iLeft, iTop: Integer; begin iLeft := (ClientWidth - pnlContainer.Width) div 2; if iLeft < 0 then iLeft := 0; iTop := (ClientHeight - pnlContainer.Height - Panel1.Height) div 2; if iTop < 0 then iTop := 0; pnlContainer.Left := iLeft; pnlContainer.Top := iTop; end; procedure TfrmSameColumnsSet.FormShow(Sender: TObject); begin FValueChanged := False; end; procedure TfrmSameColumnsSet.btnOkClick(Sender: TObject); var i: Integer; begin if FValueChanged then begin SetLength(fValues, 0); for i := 0 to FCheckedList.Count - 1 do begin with TCheckBox(FCheckedList[i]) do begin if Checked then begin SetLength(fValues, Length(fValues) + 1); fValues[High(fValues)] := Tag; end; end; end; FValueChanged := False; end; if not (TryStrToInt(edtEachPageRowCount.Text, i) and (i > 0)) then raise Exception.Create('请输入有效每页行数'); fEachPageRowCount := i; ModalResult := mrOk; end; procedure TfrmSameColumnsSet.CheckBoxClick(Sender: TObject); begin with TCheckBox(Sender) do begin if Checked then fCheckedList.Add(Sender) else fCheckedList.Remove(Sender); end; FValueChanged := True; end; procedure TfrmSameColumnsSet.CheckBoxGroupClick(Sender: TObject); var CheckBox: TControl; i, v: Integer; begin with TCheckBox(Sender) do begin v := 0; for i := 0 to Tag - 1 do v := v + fEachRowValueCount[i]; for i := v + 1 to v + fEachRowValueCount[Tag] do begin CheckBox := pnlContainer.FindChildControl(Format(CheckBoxName, [i])); if not Assigned(CheckBox) then Continue; TCheckBox(CheckBox).Checked := Checked; end; end; end; procedure TfrmSameColumnsSet.BuildCheckBox(aEachRowValueCount: TByteDynArray; Offset: Byte); const CheckBoxWidth = 52; CheckBoxHeight = 24; var i, j, v, iLeft, iTop, iMaxLeft: Integer; begin for i := pnlContainer.ControlCount - 1 downto 0 do pnlContainer.Controls[i].Free; iMaxLeft := 0; v := 0; for i := Low(aEachRowValueCount) to High(aEachRowValueCount) do begin iLeft := 0; if i = 0 then iLeft := Offset * CheckBoxWidth; iTop := i * CheckBoxHeight; for j := 1 to aEachRowValueCount[i] do begin Inc(v); if v > fMaxValue then Break; with TCheckBox.Create(Self) do begin Name := Format(CheckBoxName, [v]); Parent := pnlContainer; Tag := v; OnClick := CheckBoxClick; Left := iLeft; Top := iTop; iLeft := iLeft + CheckBoxWidth; if iLeft > iMaxLeft then iMaxLeft := iLeft; end; end; with TCheckBox.Create(Self) do begin Name := Format(CheckBoxGroupName, [i + 1]); Parent := pnlContainer; Font.Style := [fsBold]; Caption := Format('第%d行全选口√', [i + 1]); Tag := i; OnClick := CheckBoxGroupClick; Left := iMaxLeft + 10; Top := iTop; Width := 180; end; if v >= fMaxValue then Break; end; pnlContainer.Width := iMaxLeft + 180; pnlContainer.Height := iTop + 24; Panel1.BringToFront; FormResize(Self); fEachRowValueCount := aEachRowValueCount; end; procedure TfrmSameColumnsSet.RenameCheckBox(aIntervalValues: TWordDynArray); var i, v, IntervalValue, IntervalIndex: Integer; CheckBox: TControl; begin if Length(aIntervalValues) = 0 then Exit; IntervalIndex := 0; IntervalValue := 0; for i := 1 to 256 do begin CheckBox := pnlContainer.FindChildControl(Format(CheckBoxName, [i])); if not Assigned(CheckBox) then Continue; with TCheckBox(CheckBox) do begin v := i; if (IntervalIndex <= High(aIntervalValues)) and (v > IntervalValue + aIntervalValues[IntervalIndex]) then begin repeat if IntervalIndex <= High(aIntervalValues) then begin IntervalValue := IntervalValue + aIntervalValues[IntervalIndex]; Inc(IntervalIndex); end; until (v <= IntervalValue + aIntervalValues[IntervalIndex]) or (IntervalIndex > High(aIntervalValues)); end; v := v - IntervalValue; case fDataMode of 1: if IntervalIndex = 0 then v := (v - 1) mod 10; end; Caption := v.ToString; end; end; end; procedure TfrmSameColumnsSet.edtKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then btnOkClick(nil); end; end.
{//************************************************************//} {// //} {// Código gerado pelo assistente //} {// //} {// Projeto MVCBr //} {// tireideletra.com.br / amarildo lacerda //} {//************************************************************//} {// Data: 13/06/2017 23:41:39 //} {//************************************************************//} /// <summary> /// O ViewModel esta conectado diretamente com a VIEW /// e possui um Controller ao qual esta associado /// </summary> unit EConference2017.ViewModel.Interf; interface uses MVCBr.Interf, MVCBr.ViewModel; Type /// Interaface para o ViewModel IEConference2017ViewModel = interface(IViewModel) ['{784C3946-032F-427C-9E10-A3B70EA7E56C}'] // incluir especializações aqui end; Implementation end.
unit SimThyrLog; { SimThyr Project } { A numerical simulator of thyrotropic feedback control } { Version 3.3.3 (Gaia) } { (c) J. W. Dietrich, 1994 - 2014 } { (c) Ludwig Maximilian University of Munich 1995 - 2002 } { (c) Ruhr University of Bochum 2005 - 2014 } { This unit draws a spreadsheet-like grid with simulation results } { Source code released under the BSD License } { See http://simthyr.sourceforge.net for details } {$mode objfpc}{$R+} interface uses Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs, Grids, clipbrd, ComCtrls, ExtCtrls, Menus, SimThyrTypes, SimThyrResources, SimThyrServices, DIFSupport; type { TSimThyrLogWindow } TSimThyrLogWindow = class(TForm) CopyItem: TMenuItem; CutItem: TMenuItem; DeleteItem: TMenuItem; Divider1: TMenuItem; PasteItem: TMenuItem; PopupMenu1: TPopupMenu; ProgressBar1: TProgressBar; StatusBar1: TStatusBar; UndoItem: TMenuItem; ValuesGrid: TStringGrid; procedure CopyCells; procedure CopyItemClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure InitGrid; procedure PopupMenu1Popup(Sender: TObject); procedure SaveGrid(theFileName: String; theDelimiter: Char); procedure ValuesGridGetCellHint(Sender: TObject; ACol, ARow: Integer; var HintText: String); private { private declarations } public { public declarations } end; var SimThyrLogWindow: TSimThyrLogWindow; implementation uses SimThyrMain; procedure CutorCopyfromGrid(theGrid: TStringGrid; cut: Boolean = False); {supports cutting or copying cells from the grid} var theSelection: TGridRect; r, c: integer; textfromSelection: AnsiString; begin theSelection := theGrid.Selection; textfromSelection := ''; for r := theSelection.Top to theSelection.Bottom do begin for c := theSelection.Left to theSelection.Right do begin textfromSelection := textfromSelection + theGrid.Cells[c,r]; if cut then begin theGrid.Cells[c,r] := ''; end; if c < theSelection.Right then textfromSelection := textfromSelection + kTAB; end; if r < theSelection.Bottom then textfromSelection := textfromSelection + kCRLF; end; ClipBoard.AsText := textfromSelection; end; procedure TSimThyrLogWindow.CopyCells; begin CutorCopyfromGrid(valuesGrid, false); end; procedure TSimThyrLogWindow.CopyItemClick(Sender: TObject); begin CopyCells; end; procedure TSimThyrLogWindow.FormActivate(Sender: TObject); begin if Screen.Width < SimThyrLogWindow.Left + SimThyrLogWindow.Width then SimThyrLogWindow.Width := Screen.Width - SimThyrLogWindow.Left - 13; SimThyrToolbar.SelectAllMenuItem.Enabled := true; gLastActiveCustomForm := SimThyrLogWindow; {stores window as last active form} end; procedure TSimThyrLogWindow.InitGrid; {initializes empty table} begin ValuesGrid.RowCount := 1; GridRows := RES_BLANK_ROWS; ValuesGrid.RowCount := GridRows; ValuesGrid.Tag := 0; end; procedure TSimThyrLogWindow.PopupMenu1Popup(Sender: TObject); begin end; procedure TSimThyrLogWindow.SaveGrid(theFileName: String; theDelimiter: Char); {saves the contents of the log window} {file type and, where applicable, delimiter are defined by variable theDelimiter} var theString: String; r, c: integer; theContents: TStringList; doc: TDIFDocument; theCode: integer; begin if theDelimiter = 'd' then begin {DIF file handling} theCode := 0; SetFileName(SimThyrLogWindow, theFileName); try doc := TDIFDocument.Create; doc.SetHead('SimThyr'); doc.NewTuple; theString := ''; for c := 1 to SimThyrLogWindow.ValuesGrid.ColCount - 1 do begin theString := SimThyrLogWindow.ValuesGrid.Cells[c, 0]; Doc.AppendCell(theString); end; for r := 1 to SimThyrLogWindow.ValuesGrid.RowCount - 1 do begin doc.NewTuple; theString := ''; for c := 1 to SimThyrLogWindow.ValuesGrid.ColCount - 1 do begin theString := SimThyrLogWindow.ValuesGrid.Cells[c, r]; Doc.AppendCell(theString); end; end; WriteDIFFile(doc, theFileName, theCode); if theCode <> 0 then ShowSaveError; finally doc.Free; end; end else if theDelimiter <> ' ' then {tab delimited and CSV files} begin theContents := TStringList.Create; SetFileName(SimThyrLogWindow, theFileName); theString := ''; for c := 1 to SimThyrLogWindow.ValuesGrid.ColCount - 1 do theString := theString + SimThyrLogWindow.ValuesGrid.Cells[c, 0] + theDelimiter; theContents.Add(theString); for r := 1 to SimThyrLogWindow.ValuesGrid.RowCount - 1 do begin theString := ''; for c := 1 to SimThyrLogWindow.ValuesGrid.ColCount - 1 do theString := theString + SimThyrLogWindow.ValuesGrid.Cells[c, r] + theDelimiter; theContents.Add(theString); end; try try theContents.SaveToFile(theFileName); except on Ex: EFCreateError do ShowMessage(SAVE_ERROR_MESSAGE); end; finally theContents.Free; end; end else ShowSaveError; end; procedure TSimThyrLogWindow.ValuesGridGetCellHint(Sender: TObject; ACol, ARow: Integer; var HintText: String); { TODO 9 -oJ. W. Dietrich -cbugs : This bug is to be fixed. } var theText: String; begin { Raises a SIGSEGV exception theText := 'Simulated behavioural parameters of thyroid homeostasis'; if ACol > 1 then theText := gParameterLabel[ACol - 1]; HintText := theText; } end; initialization {$I simthyrlog.lrs} end.
unit DIOTA.IotaAPIClasses; interface uses REST.Client, System.JSON.Builders; type TIotaAPIResponse = class public constructor Create; virtual; end; TIotaAPIRequest = class private FRequest: TRESTRequest; FResponse: TRESTResponse; protected function GetCommand: String; virtual; abstract; function BuildRequestBody(JsonBuilder: TJSONCollectionBuilder.TPairs): TJSONCollectionBuilder.TPairs; virtual; public constructor Create(ARESTClient: TCustomRESTClient; ATimeout: Integer); virtual; destructor Destroy; override; function Execute<TResult: TIotaAPIResponse, constructor>: TResult; end; implementation uses REST.Types, REST.Json.Types, REST.Json; { TIotaAPIRequest } constructor TIotaAPIRequest.Create(ARESTClient: TCustomRESTClient; ATimeout: Integer); begin FRequest := TRESTRequest.Create(nil); FRequest.SynchronizedEvents:= False; FRequest.Timeout := ATimeout; FRequest.Method := rmPOST; FRequest.Params.AddHeader('X-IOTA-API-Version', '1.6.1'); FRequest.Params.AddHeader('Content-Type', 'application/json'); FRequest.Params.AddHeader('User-Agent', 'DIOTA-API wrapper'); FRequest.Client := ARESTClient; FResponse:= TRESTResponse.Create(nil); FRequest.Response := FResponse; end; destructor TIotaAPIRequest.Destroy; begin FResponse.Free; FRequest.Free; inherited; end; function TIotaAPIRequest.Execute<TResult>: TResult; var JsonBuilder: TJSONObjectBuilder; begin JsonBuilder := TJSONObjectBuilder.Create(FRequest.Body.JSONWriter); try BuildRequestBody(JsonBuilder.BeginObject.Add('command', GetCommand)).EndObject; finally JsonBuilder.Free; end; FRequest.Execute; if Assigned(FResponse.JSONValue) then Result := TJson.JsonToObject<TResult>(FResponse.JSONValue.ToJSON) else Result := nil; end; function TIotaAPIRequest.BuildRequestBody(JsonBuilder: TJSONCollectionBuilder.TPairs): TJSONCollectionBuilder.TPairs; begin Result := JsonBuilder; end; { TIotaAPIResponse } constructor TIotaAPIResponse.Create; begin // end; end.
unit VariantTypeUnit; interface uses Variants; type TVariant = class sealed (TObject) strict private FValue: Variant; public constructor Create; overload; constructor Create(const AValue: Variant); overload; property Value: Variant read FValue write FValue; end; implementation { TVariant } constructor TVariant.Create(const AValue: Variant); begin inherited Create; FValue := AValue; end; constructor TVariant.Create; begin inherited; end; end.
unit Clothes.DataModule; interface uses System.SysUtils, System.Classes, Connection.Model, Database.Types, Database.Datamodule, Database.Model, Database.Utils, Clothes.Classes, Clothes.Model, Data.FMTBcd, Datasnap.DBClient, Datasnap.Provider, Data.DB, Data.SqlExpr; type TdmClothes = class(TDataModule) sqldsClothesTypes: TSQLDataSet; prvClothesTypes: TDataSetProvider; cdsClothesTypes: TClientDataSet; sqldsClothes: TSQLDataSet; prvClothes: TDataSetProvider; cdsClothes: TClientDataSet; cdsClothesTypesID: TLargeintField; cdsClothesTypesTITLE: TWideStringField; cdsClothesTypesORDER_NO: TSmallintField; procedure DataModuleCreate(Sender: TObject); procedure cdsClothesTypesBeforePost(DataSet: TDataSet); procedure cdsClothesBeforePost(DataSet: TDataSet); procedure cdsClothesTypesAfterPost(DataSet: TDataSet); procedure DataModuleDestroy(Sender: TObject); procedure cdsClothesAfterPost(DataSet: TDataSet); private FClothesModel: TClothesModel; procedure SetClothesModel(const Value: TClothesModel); { Private declarations } public FDatabaseModel: TDatabaseModel; property ClothesModel: TClothesModel read FClothesModel write SetClothesModel; procedure CancelClothesDataset; procedure CancelClothesTypesDataset; procedure SaveClothes(AClothes: TClothes; AnOperation: TOperation = opInsert); procedure SaveClothesTypes(AClothesType: TClothesType; AnOperation: TOperation = opInsert); { Public declarations } end; var dmClothes: TdmClothes; implementation {%CLASSGROUP 'FMX.Controls.TControl'} {$R *.dfm} procedure TdmClothes.CancelClothesDataset; begin CancelDataset(cdsClothes); end; procedure TdmClothes.CancelClothesTypesDataset; begin CancelDataset(cdsClothesTypes); end; procedure TdmClothes.cdsClothesAfterPost(DataSet: TDataSet); begin SaveCdsData(cdsClothes); end; procedure TdmClothes.cdsClothesBeforePost(DataSet: TDataSet); begin // if cdsClothes.State = dsInsert then // begin // cdsClothes.FieldByName('ID').AsInteger := FClothesModel.GetClothesNextId; // end; end; procedure TdmClothes.cdsClothesTypesAfterPost(DataSet: TDataSet); begin SaveCdsData(cdsClothesTypes); end; procedure TdmClothes.cdsClothesTypesBeforePost(DataSet: TDataSet); begin // if cdsClothesTypes.State = dsInsert then // begin // cdsClothesTypes.FieldByName('ID').AsInteger := FClothesModel.GetClothesTypeNextId; // end; end; procedure TdmClothes.DataModuleCreate(Sender: TObject); begin FDatabaseModel := TDatabaseModel.GetInstance; FClothesModel := TClothesModel.GetInstance; cdsClothesTypes.Open; cdsClothes.Open; end; procedure TdmClothes.DataModuleDestroy(Sender: TObject); begin SaveCdsData(cdsClothes); SaveCdsData(cdsClothesTypes); end; procedure TdmClothes.SaveClothes(AClothes: TClothes; AnOperation: TOperation); var ACds: TClientDataSet; begin ACds := cdsClothes; if ACds.Locate('SN', AClothes.SN, []) then begin Exit; end; if AnOperation = opInsert then begin AClothes.ID := FClothesModel.GetClothesNextId; ACds.Insert; ACds.FieldByName('ID').AsInteger := AClothes.ID; ACds.FieldByName('REGTM').AsDateTime := Now; end else begin cdsClothesTypes.Edit; end; ACds.FieldByName('SN').AsString := AClothes.SN; ACds.FieldByName('TYPE_ID').AsInteger := AClothes.ClothesType.ID; ACds.FieldByName('UPDTM').AsDateTime := Now; ACds.Post; end; procedure TdmClothes.SaveClothesTypes(AClothesType: TClothesType; AnOperation: TOperation); begin if cdsClothesTypes.Locate('TITLE', AClothesType.Name, []) then begin Exit; end; if AnOperation = opInsert then begin AClothesType.ID := FClothesModel.GetClothesTypeNextId; cdsClothesTypes.Insert; cdsClothesTypes.FieldByName('ID').AsInteger := AClothesType.ID; end else begin cdsClothesTypes.Edit; end; cdsClothesTypes.FieldByName('TITLE').AsString := AClothesType.Name; cdsClothesTypes.FieldByName('ORDER_NO').AsInteger := AClothesType.OrderNo; cdsClothesTypes.Post; end; procedure TdmClothes.SetClothesModel(const Value: TClothesModel); begin FClothesModel := Value; end; end.
{! Tick Tack Toe } {! Written By Alex Cummaudo 2013-12-12 } program TickTackToe; { Define the Blip Type } type BlipType = (Blank, Naught, Cross); GridType = record size : Integer; grid : Array [0..9, 0..9] of BlipType; end; GameData = record board : GridType; quit : Boolean; turn : BlipType; win : Boolean; end; { Basic Exponentional (equivalent to 10^x) } function Exponent(x : Integer) : Integer; var i : Integer; result : Integer; begin result := 1; if ((x < 0) or (x > 4)) then begin WriteLn('ERROR: Invalid or overexcessive exponent!'); Exponent := -1; exit; end; for i := x downto 1 do begin result := result * 10; end; Exponent := result; end; { Prompt } function Prompt(promptText : String) : String; var input : String; begin Write(' >> ', promptText, ': '); ReadLn(input); Prompt := input; end; { Alert } procedure Alert(alertText : String); begin WriteLn(' > ', alertText); end; { Converts singular char to it's numerical equivalent } function CharToInt(input : Char) : Integer; begin CharToInt := -1; case input of '0': CharToInt := 0; '1': CharToInt := 1; '2': CharToInt := 2; '3': CharToInt := 3; '4': CharToInt := 4; '5': CharToInt := 5; '6': CharToInt := 6; '7': CharToInt := 7; '8': CharToInt := 8; '9': CharToInt := 9; end; end; { Reads in any, positive, whole integer with prompt } function ReadInteger(promptStr : String) : Integer; var strInput : String; { Raw string input } numDigit : Integer; { The length of input (or # digits) } ithDigit : Integer; { The integer of the i'th digit } i , j : Integer; { Iterators for for loop } iDigExp : Integer; { The exponent of this digit } result : Integer; { The actual result } begin strInput := Prompt(promptStr); numDigit := Length(strInput); result := 0; if (numDigit > 4) then begin Alert('ERROR: ' + strInput + ' is too high to convert!'); ReadInteger := -1; exit; end; { Go down from MSD to LSD (in char terms that means we want to go from the start of the string to EOS) } for i := 1 to numDigit do begin ithDigit := CharToInt(strInput[i]); { Exponent means the total worth of the ith digit subtracted from the total number of digits } iDigExp := Exponent(numDigit-i); { Unsuccessful char to int conversion } { Unsuccessful exp raise (too high) } if ((ithDigit = -1) or (iDigExp = -1)) then begin Alert('ERROR: Conversion to Integer failed!'); ReadInteger := -1; exit; end; { Otherwise, a succesful conversion } result := result + (ithDigit * iDigExp); end; ReadInteger := result; end; { Sets up the game passed with given params } procedure SetupGame(var theGame : GameData); var boardSize, row, col : Integer; begin Alert('Starting a new game'); { Quit to false } theGame.quit := false; { Win to false } theGame.win := false; { Cross goes first } theGame.turn := cross; { Read in the board's new size } repeat boardSize := ReadInteger('Enter a board size between 2 and 10'); until ((boardSize > 2) and (boardSize < 10)); theGame.board.size := boardSize; { Set up the blanks in each row/col } for row := 0 to boardSize do for col := 0 to boardSize do theGame.board.grid[row][col] := blank; end; { Converts a specific blip to textual equivalent } function BlipToString(var blip : BlipType) : String; begin case blip of Blank : BlipToString := '_'; Naught : BlipToString := 'o'; Cross : BlipToString := 'x'; end; end; { Draws the grid to the screen } procedure DrawGrid(var board : GridType); var row, col : Integer; begin Alert('Drawing the game board: '); WriteLn(''); { COLS HEADERS } Write(' '); for col := 1 to board.size do begin Write(col,' '); end; WriteLn(''); { ROWS } for row := 1 to board.size do begin { Each row starts with a new blank space } Write(row, ' '); { COL } for col := 1 to board.size do begin { Draw the row's column's blip with a space } Write(' ', BlipToString(board.grid[col][row])); end; { End of the line? Write new line. } WriteLn(' '); end; { End of the board? Write new line. } WriteLn(' '); end; { Draws the menu options } procedure DrawMenu(var game : GameData); begin Alert('It''s ' + BlipToString(game.turn) + '''s turn'); Alert('[1] -> Enter Selection'); Alert('[2] -> New Game'); Alert('[0] -> Quit'); WriteLn(''); end; { Draws some simple separators around the board } procedure DrawSeparator(size : Integer); var i : Integer; begin WriteLn(''); WriteLn(''); for i:= 0 to size do Write('='); WriteLn(''); WriteLn(''); end; { Draws the grid as well as prompts for further stuff to the screen } procedure DrawGame(var game : GameData); var i : Integer; begin DrawGrid(game.board); DrawMenu(game); end; { Swaps the current player to the opposite of whoever is currently playing } procedure NextPlayer(var game : GameData); begin if (game.turn = Naught) then game.turn := Cross else if (game.turn = Cross) then game.turn := Naught; end; { Prompts a confirm } function Confirm : Boolean; var input : String; begin Confirm := false; input := Prompt('Are you sure? [y/n]'); if (input[1] = 'y') then begin Confirm := true; end; end; { Confirms the player's selection } function ConfirmSelection(col, row : Integer; var game : GameData) : Boolean; var coords : String; begin ConfirmSelection := false; { Confirm that the col/row is in boundaries } if (((col > game.board.size) or (row > game.board.size)) or ((col < 1 ) or (row < 1 ))) then Alert('ALERT: The row or column is out of the range of the board!') { The col/row is okay, but is anything there? } else if (game.board.grid[col][row] <> blank) then begin Alert('ALERT: That position has been taken by ' + BlipToString(game.board.grid[col][row])); end { ELSE Everything is OKAY! } else begin { Place the current turn (player) at that position) } game.board.grid[col][row] := game.turn; ConfirmSelection := true; end; end; { Checks a singular column that all match -- col static while row changes } function CheckCol(var board : GridType; col : Integer) : Boolean; var row : Integer; begin { Given the first blip isn't blank } if (board.grid[col][1] <> blank) then begin { Start iterating through each row in this col up until the second last row } for row := 1 to (board.size-1) do begin { This blip doesn't match the blip underneath it } if (board.grid[col][row] <> board.grid[col][row+1]) then begin CheckCol := false; exit; end; end; { Out of loop---must have passed! } CheckCol := true; exit; end { Otherwise, this is a blank blip } else begin CheckCol := false; exit; end; end; { Checks all cols for any match } function CheckAllCols(var board : GridType) : Boolean; var col : Integer; valid : Boolean; begin CheckAllCols := false; { Check every single col for row match } for col := 1 to board.size do begin valid := CheckCol(board, col); if (valid) then begin CheckAllCols := true; exit; end; end; end; { Checks a singular row that all match -- row static while col changes } function CheckRow(var board : GridType; row : Integer) : Boolean; var col : Integer; begin { Given the first blip isn't blank } if (board.grid[1][row] <> blank) then begin { Start iterating through each column in this row up until the second last column } for col := 1 to (board.size-1) do begin { This blip doesn't match the blip next to it } if (board.grid[col][row] <> board.grid[col+1][row]) then begin CheckRow := false; exit; end; end; { Out of loop---must have passed! } CheckRow := true; exit; end { Otherwise, this is a blank blip } else begin CheckRow := false; exit; end; end; { Checks all rows for any match } function CheckAllRows(var board : GridType) : Boolean; var row : Integer; valid : Boolean; begin CheckAllRows := false; { Check every single row for column match } for row := 1 to board.size do begin valid := CheckRow(board, row); if (valid) then begin CheckAllRows := true; exit; end; end; end; { Checks diagonals top left to bottom right } function CheckDiagTopBottom(var board : GridType) : Boolean; var i : Integer; begin { Given the first left top isn't blank } if (board.grid[1][1] <> blank) then begin { Start iterating through every diag tile up until the second last col/row } for i := 1 to (board.size-1) do begin { This blip doesn't match the blip south-east to it } if (board.grid[i][i] <> board.grid[i+1][i+1]) then begin CheckDiagTopBottom := false; exit; end; end; { Out of loop---must have passed! } CheckDiagTopBottom := true; exit; end { Otherwise, this is a blank blip } else begin CheckDiagTopBottom := false; exit; end; end; { Checks diagonals bottom left to top right } function CheckDiagBottomUp(var board : GridType) : Boolean; var i : Integer; begin { Given the bottom left top isn't blank } if (board.grid[1][board.size] <> blank) then begin { Start iterating through every diag tile down back up until second last col/row } for i := board.size downto 2 do begin { This blip doesn't match the blip north-east to it } { board.size - i + 1 == say 6 - 6 + 1 = 1st col 6 - 5 + 1 = 2nd col 6 - 4 + 1 = 3rd col etc. } if (board.grid[board.size-i+1][i] <> board.grid[board.size-i+2][i-1]) then begin CheckDiagBottomUp := false; exit; end; end; { Out of loop---must have passed! } CheckDiagBottomUp := true; exit; end { Otherwise, this is a blank blip } else begin CheckDiagBottomUp := false; exit; end; end; { Checks if a winner has won } procedure CheckWinner(var game : GameData); begin if (CheckAllRows(game.board) or CheckAllCols(game.board) or CheckDiagTopBottom(game.board) or CheckDiagBottomUp (game.board)) then begin game.win := true; Alert('We have a winner: '+BlipToString(game.turn)) end else Alert('No winner yet'); end; { Prompts the user to enter in a selection } procedure EnterSelection(var game : GameData); var colSelection : Integer; rowSelection : Integer; begin colSelection := ReadInteger('Enter column number'); rowSelection := ReadInteger('Enter row number'); { If confirmed selection } if (ConfirmSelection(colSelection, rowSelection, game)) then begin { Check for winner } CheckWinner(game); { Move onto next player! } NextPlayer(game); end; end; procedure RecieveInput(var game : GameData); var input : Integer; begin input := ReadInteger('[?] ->'); case input of 0: game.quit := Confirm; 1: EnterSelection(game); 2: begin if (Confirm) then begin DrawSeparator(60); SetupGame(game); end; end; 111: begin Alert('Force swap player'); NextPlayer(game); DrawMenu(game); end; end; end; procedure Main; var game : GameData; begin WriteLn(' -- TICK TACK TOE v1.0 -- '); WriteLn(' Written By Alex Cummaudo '); WriteLn(''); SetupGame(game); while not (game.quit) do begin DrawGame(game); RecieveInput(game); if (game.win) then begin DrawGrid(game.board); DrawSeparator(60); SetupGame(game); end; end; Alert('Goodbye!'); end; begin Main; end.
program Whatever; uses Graph, Crt, GrafBits; const North: array[1..3] of Byte = (1, 2, 8); NorthEast: array[1..3] of Byte = (1, 2, 3); East: array[1..3] of Byte = (2, 3, 4); SouthEast: array[1..3] of Byte = (3, 4, 5); South: array[1..3] of Byte = (4, 5, 6); SouthWest: array[1..3] of Byte = (5, 6, 7); West: array[1..3] of Byte = (6, 7, 8); NorthWest: array[1..3] of Byte = (7, 8, 1); MoveDist = 2; type TBall = Object X, Y, XSize, YSize, XMov, YMov: integer; GenDirection, Direction: Byte; procedure MoveBall; procedure TestForEdges; procedure StartBall(XP, YP, XM, YM: integer); end; var I, XPos, YPos, Dela, NumBalls, XSize, YSize: integer; Size: integer; MM, M, P: pointer; Balls: array[1..100] of TBall; procedure TBall.TestForEdges; begin if X >= MaxX - 40 then if GenDirection in [2, 3, 4] then GenDirection:= West[Random(3) + 1]; if Y >= MaxY - 40 then if GenDirection in [4, 5, 6] then GenDirection:= North[Random(3) + 1]; if X <= 10 then if GenDirection in [6, 7, 8] then GenDirection:= East[Random(3) + 1]; if Y <= 10 then if GenDirection in [1, 2, 8] then GenDirection:= South[Random(3) + 1]; end; function Direct(Dir: Byte): Byte; begin Case Dir of 1: Direct:= North[Random(3) + 1]; 2: Direct:= NorthEast[Random(3) + 1]; 3: Direct:= East[Random(3) + 1]; 4: Direct:= SouthEast[Random(3) + 1]; 5: Direct:= South[Random(3) + 1]; 6: Direct:= SouthWest[Random(3) + 1]; 7: Direct:= West[Random(3) + 1]; 8: Direct:= NorthWest[Random(3) + 1]; end; end; procedure TBall.MoveBall; begin TestForEdges; Direction:= Direct(GenDirection); Case Direction of 1: Repeat Dec(Y, MoveDist); { North } Until Y < MaxX - 40; 2: Repeat Inc(X, MoveDist); { North - East } Dec(Y, MoveDist); Until (X > 10) and (Y < MaxY - 40); 3: Repeat Inc(X, MoveDist); { East } Until X > 10; 4: Repeat Inc(X, MoveDist); { South - East } Inc(Y, MoveDist); Until (X > 10) and (Y > 10); 5: Repeat Inc(Y, MoveDist); { South } Until Y > 10; 6: Repeat Dec(X, MoveDist); { South West } Inc(Y, MoveDist); Until (X < MaxX - 40) and (Y > 10); 7: Repeat Dec(X, MoveDist); { West } Until X < MaxX - 40; 8: Repeat Dec(X, MoveDist); { North - West } Dec(Y, MoveDist); Until (X < MaxX - 40) and (Y < MaxY - 40); end; PutImage(X, Y, P^, NormalPut); { if X = MaxX - 34 then PutImage(X, Y, P^, NormalPut);} end; procedure DrawBall; begin XPos:= 18; YPos:= 18; XSize:= 36; YSize:= XSize; For I:= 0 to 15 do begin SetPalette(I, I); SetRGBPalette(I, I * 3, I * 3, I * 3); SetColor(I); SetFillStyle(1, I); FillEllipse(XPos, YPos, 15 - I, 15 - I); end; Size:= ImageSize(0, 0, XSize, YSize); GetMem(P, Size); GetImage(0, 0, XSize, YSize, P^); SetFillStyle(1, White); Bar(100, 100, 100 + XSize, 100 + YSize); PutImage(100, 100, P^, xorput); GetMem(M, Size); GetImage(100, 100, 100 + XSize, 100 + YSize, M^); end; procedure TBall.StartBall; begin X:= XP; Y:= YP; GenDirection:= Random(8) + 1; end; function RandX: integer; begin RandX:= Random(MaxX - 34); end; function RandY: integer; begin RandY:= Random(MaxY - 34); end; function RndXM: integer; begin RndXM:= Random(2) + 1; end; function RndYM: integer; begin RndYM:= Random(4) + 1; end; procedure RunEm; begin ClearDevice; For I:= 1 to NumBalls do begin Balls[I].StartBall(RandX, RandY, RndXM, RndYM); end; While not KEyPressed do begin For I:= 1 to NumBalls do begin Balls[I].MoveBall; Delay(Dela); end; end; end; procedure Starter; var Code: integer; begin if ParamCount = 0 then begin NumBalls:= 2; Dela:= 0; end; if ParamCount > 0 then begin Val(ParamStr(1), NumBalls, Code); Dela:= 0; end; if ParamCount > 1 then Val(ParamStr(2), Dela, Code); if NumBalls > 100 then NumBalls:= 100; if Dela > 1000 then Dela:= 1000; if Dela < 0 then Dela:= 0; if NumBalls < 1 then NumBalls:= 1; end; begin Randomize; GraphicsScreen; Starter; DrawBall; RunEm; ReadKey; CloseGraph; end.
unit MUIClass.Menu; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fgl, Math, Exec, Utility, AmigaDOS, Intuition, icon, mui, muihelper, tagsparamshelper, MUIClass.Base; {$M+} type // Usually it should look like this: // TMUIApplication.MenuStrip -> TMUIMenuStrip -> TMUIMenu -> TMenuItem // or // TMUIWindow.MenuStrip -> TMUIMenuStrip -> TMUIMenu -> TMenuItem TMUIMenustrip = class(TMUIFamily) private FEnabled: Boolean; procedure SetEnabled(AValue: Boolean); protected procedure GetCreateTags(var ATagList: TATagList); override; public constructor Create; override; procedure CreateObject; override; published property Enabled: Boolean read FEnabled write SetEnabled default True; // Enable/Disable Menu end; TMUIMenu = class(TMUIFamily) private FEnabled: Boolean; FTitle: string; procedure SetEnabled(AValue: Boolean); procedure SetTitle(AValue: string); protected procedure GetCreateTags(var ATagList: TATagList); override; public constructor Create; override; procedure CreateObject; override; published property Enabled: Boolean read FEnabled write SetEnabled default True; // Disable/Enable the full Menu property Title: string read FTitle write SetTitle; // Title for the Menu end; TMUIMenuItem = class(TMUIFamily) private FEnabled: Boolean; FTitle: string; FChecked: Boolean; FCheckIt: Boolean; FCommandString: Boolean; FExclude: LongWord; FShortCut: string; FToggle: Boolean; FOnTrigger: TNotifyEvent; function GetChecked: Boolean; procedure SetChecked(AValue: Boolean); procedure SetCheckit(AValue: Boolean); procedure SetCommandString(AValue: Boolean); procedure SetEnabled(AValue: Boolean); procedure SetExclude(AValue: LongWord); procedure SetShortCut(AValue: string); procedure SetTitle(AValue: string); procedure SetToggle(AValue: Boolean); protected procedure GetCreateTags(var ATagList: TATagList); override; public constructor Create; override; procedure CreateObject; override; procedure AfterCreateObject; override; published property Checked: Boolean read GetChecked write SetChecked default False; // Check a Checkable Menu Entry (if CheckIt is True) property CheckIt: Boolean read FCheckIt write SetCheckIt default False; // If True the Item is Checkable property CommandString: Boolean read FCommandString write SetCommandString default False; // if True SortCut points to a full Short Cut, else only the first Char + Amiga is used property Enabled: Boolean read FEnabled write SetEnabled default True; // Enable/Disable this Menu Entry property Exclude: LongWord read FExclude write SetExclude default 0; // BitField to uncheck other menu entries when this one is checked (Radio) property ShortCut: string read FShortCut write SetShortCut; // ShortCut (just the name on the menu, the actual check you have to do yourself) property Title: string read FTitle write SetTitle; // Title for menu Entry or '-' for a Line property Toggle: Boolean read FToggle write SetToggle default False; // Automatically toggle Checkable Entries when selected by user property OnTrigger: TNotifyEvent read FOnTrigger write FOnTrigger; // Event when an Entry is selected end; implementation const NM_BarLabel = -1; { TMUIMenuStrip } constructor TMUIMenustrip.Create; begin inherited; FEnabled := True; end; procedure TMUIMenustrip.GetCreateTags(var ATagList: TATagList); begin inherited; if not FEnabled then ATagList.AddTag(MUIA_Menustrip_Enabled, AsTag(FEnabled)); end; procedure TMUIMenustrip.CreateObject; var TagList: TATagList; begin if not Assigned(FMUIObj) then begin BeforeCreateObject; GetCreateTags(TagList); FMUIObj := MUI_NewObjectA(MUIC_MenuStrip, TagList.GetTagPointer); AfterCreateObject end; end; procedure TMUIMenustrip.SetEnabled(AValue: Boolean); begin if AValue <> FEnabled then begin FEnabled := AValue; if Assigned(FMUIObj) then SetValue(MUIA_Menustrip_Enabled, FEnabled); end; end; { TMUIMenu } constructor TMUIMenu.Create; begin inherited; FEnabled := True; FTitle := ''; end; procedure TMUIMenu.GetCreateTags(var ATagList: TATagList); begin inherited; if not FEnabled then ATagList.AddTag(MUIA_Menu_Enabled, AsTag(FEnabled)); ATagList.AddTag(MUIA_Menu_Title, AsTag(PChar(FTitle))); end; procedure TMUIMenu.CreateObject; var TagList: TATagList; begin if not Assigned(FMUIObj) then begin BeforeCreateObject; GetCreateTags(TagList); FMUIObj := MUI_NewObjectA(MUIC_Menu, TagList.GetTagPointer); AfterCreateObject end; end; procedure TMUIMenu.SetEnabled(AValue: Boolean); begin if AValue <> FEnabled then begin FEnabled := AValue; if Assigned(FMUIObj) then SetValue(MUIA_Menu_Enabled, FEnabled); end; end; procedure TMUIMenu.SetTitle(AValue: string); begin if AValue <> FTitle then begin FTitle := AValue; if Assigned(FMUIObj) then SetValue(MUIA_Menu_Title, PChar(FTitle)); end; end; { TMUIMenuItem } constructor TMUIMenuItem.Create; begin inherited; FEnabled := True; FTitle := ''; FChecked := False; FCheckIt := False; FCommandString := False; FExclude := 0; FShortCut := ''; FToggle := False; end; procedure TMUIMenuItem.GetCreateTags(var ATagList: TATagList); begin inherited; if not FEnabled then ATagList.AddTag(MUIA_MenuItem_Enabled, AsTag(FEnabled)); if FTitle = '-' then ATagList.AddTag(MUIA_MenuItem_Title, AsTag(NM_BarLabel)) else ATagList.AddTag(MUIA_MenuItem_Title, AsTag(PChar(FTitle))); if FCheckIt then ATagList.AddTag(MUIA_MenuItem_CheckIt, AsTag(FCheckIt)); if FChecked then ATagList.AddTag(MUIA_MenuItem_Checked, AsTag(FChecked)); if FCommandString then ATagList.AddTag(MUIA_MenuItem_CommandString, AsTag(FCommandString)); if FExclude > 0 then ATagList.AddTag(MUIA_MenuItem_Exclude, AsTag(FExclude)); if FShortCut <> '' then ATagList.AddTag(MUIA_MenuItem_ShortCut, AsTag(PChar(FShortCut))); if FToggle then ATagList.AddTag(MUIA_MenuItem_Toggle, AsTag(FToggle)); end; procedure TMUIMenuItem.CreateObject; var TagList: TATagList; begin if not Assigned(FMUIObj) then begin BeforeCreateObject; GetCreateTags(TagList); FMUIObj := MUI_NewObjectA(MUIC_MenuItem, TagList.GetTagPointer); AfterCreateObject end; end; function TriggerFunc(Hook: PHook; Obj: PObject_; Msg: Pointer): PtrInt; var PasObj: TMUIMenuItem; begin try Result := 0; PasObj := TMUIMenuItem(Hook^.h_Data); if Assigned(PasObj.OnTrigger) then PasObj.OnTrigger(PasObj); except on E: Exception do MUIApp.DoException(E); end; end; procedure TMUIMenuItem.AfterCreateObject; begin inherited; // Connect Events ConnectHook(MUIA_Menuitem_Trigger, MUIV_EveryTime, @TriggerFunc); end; function TMUIMenuItem.GetChecked: Boolean; begin if HasObj then FChecked := GetBoolValue(MUIA_MenuItem_Checked); Result := FChecked; end; procedure TMUIMenuItem.SetChecked(AValue: Boolean); begin if AValue <> Checked then begin FChecked := AValue; if Assigned(FMUIObj) then SetValue(MUIA_MenuItem_Checked, FChecked); end; end; procedure TMUIMenuItem.SetCheckit(AValue: Boolean); begin if AValue <> FCheckIt then begin FCheckIt := AValue; if Assigned(FMUIObj) then SetValue(MUIA_MenuItem_CheckIt, FCheckIt); end; end; procedure TMUIMenuItem.SetCommandString(AValue: Boolean); begin if AValue <> FCommandString then begin FCommandString := AValue; if Assigned(FMUIObj) then SetValue(MUIA_MenuItem_CommandString, FCommandString); end; end; procedure TMUIMenuItem.SetEnabled(AValue: Boolean); begin if AValue <> FEnabled then begin FEnabled := AValue; if Assigned(FMUIObj) then SetValue(MUIA_MenuItem_Enabled, FEnabled); end; end; procedure TMUIMenuItem.SetExclude(AValue: LongWord); begin if AValue <> FExclude then begin FExclude := AValue; if Assigned(FMUIObj) then SetValue(MUIA_MenuItem_Exclude, FExclude); end; end; procedure TMUIMenuItem.SetShortCut(AValue: string); begin if AValue <> FShortCut then begin FShortCut := AValue; if Assigned(FMUIObj) then SetValue(MUIA_MenuItem_ShortCut, PChar(FShortCut)); end; end; procedure TMUIMenuItem.SetTitle(AValue: string); begin if AValue <> FTitle then begin FTitle := AValue; if Assigned(FMUIObj) then begin if FTitle = '-' then SetValue(MUIA_MenuItem_Title, NM_BarLabel) else SetValue(MUIA_MenuItem_Title, PChar(FTitle)); end; end; end; procedure TMUIMenuItem.SetToggle(AValue: Boolean); begin if AValue <> FToggle then begin FToggle := AValue; if Assigned(FMUIObj) then SetValue(MUIA_MenuItem_Toggle, FToggle); end; end; end.
unit UKCJZone; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Grids, StdCtrls, ExtCtrls, UzLogConst, UzLogGlobal, UzLogQSO; type TKCJZone = class(TForm) Panel1: TPanel; Button1: TButton; cbStayOnTop: TCheckBox; Grid1: TStringGrid; Grid3: TStringGrid; Grid2: TStringGrid; procedure cbStayOnTopClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure GridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); private { Private declarations } function BandToCol(B: TBand): Integer; function ColToBand(col: Integer): TBand; public { Public declarations } MultiForm: TForm; procedure UpdateData; end; implementation uses UKCJMulti; {$R *.DFM} function TKCJZone.BandToCol(B: TBand): integer; begin case B of b19: Result := 1; b35: Result := 2; b7: Result := 3; b14: Result := 4; b21: Result := 5; b28: Result := 6; b50: Result := 7; else Result := 1; end; end; function TKCJZone.ColToBand(col: Integer): TBand; begin case col of 1: Result := b19; 2: Result := b35; 3: Result := b7; 4: Result := b14; 5: Result := b21; 6: Result := b28; 7: Result := b50; else Result := b19; end; end; procedure TKCJZone.UpdateData; var i: integer; B: TBand; begin for i := 0 to 23 do begin for B := b19 to b50 do begin if NotWARC(B) then begin if TKCJMulti(MultiForm).MultiArray[B, i] then begin Grid1.Cells[BandToCol(B), i] := '*'; end else begin Grid1.Cells[BandToCol(B), i] := '.'; end; end; end; end; for i := 24 to 47 do begin for B := b19 to b50 do begin if NotWARC(B) then begin if TKCJMulti(MultiForm).MultiArray[B, i] then begin Grid2.Cells[BandToCol(B), i - 24] := '*'; end else begin Grid2.Cells[BandToCol(B), i - 24] := '.'; end; end; end; end; for i := 48 to maxindex do begin for B := b19 to b50 do begin if NotWARC(B) then begin if TKCJMulti(MultiForm).MultiArray[B, i] then begin Grid3.Cells[BandToCol(B), i - 48] := '*'; end else begin Grid3.Cells[BandToCol(B), i - 48] := '.'; end; end; end; end; end; procedure TKCJZone.cbStayOnTopClick(Sender: TObject); begin if cbStayOnTop.Checked then begin FormStyle := fsStayOnTop; end else begin FormStyle := fsNormal; end; end; procedure TKCJZone.Button1Click(Sender: TObject); begin Close; end; procedure TKCJZone.FormShow(Sender: TObject); var R: Integer; B: TBand; begin for R := 0 to 23 do begin for B := b19 to b50 do begin Grid1.Cells[0, R] := Copy(KenNames[R], 1, 2) end; end; for R := 24 to 47 do begin for B := b19 to b50 do begin Grid2.Cells[0, R - 24] := Copy(KenNames[R], 1, 2); end; end; for R := 48 to maxindex do begin for B := b19 to b50 do begin Grid3.Cells[0, R - 48] := Copy(KenNames[R], 1, 2); end; end; UpdateData; end; procedure TKCJZone.GridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); var strText: string; i: Integer; CL: TColor; tf: TTextFormat; begin if ACol = 0 then begin // KCJCODE CL := clBlack; strText := TStringGrid(Sender).Cells[ACol, ARow]; tf := [tfLeft, tfVerticalCenter, tfSingleLine]; end else begin i := ARow + TStringGrid(Sender).Tag; if (i >= 0) and (i <= maxindex) then begin if TKCJMulti(MultiForm).MultiArray[ColToBand(ACol), i] = True then begin CL := clRed; strText := '*'; end else begin CL := clBlack; strText := '.'; end; end else begin CL := clBlack; strText := ''; end; tf := [tfCenter, tfVerticalCenter, tfSingleLine]; end; with TStringGrid(Sender).Canvas do begin Brush.Color := TStringGrid(Sender).Color; Brush.Style := bsSolid; FillRect(Rect); Font.Name := '‚l‚r ƒSƒVƒbƒN'; Font.Size := 11; Font.Color := CL; TextRect(Rect, strText, tf); end; end; end.
unit RelayControl; interface uses Classes, CommBase, TextMessage; type IRelayControl = interface function CloseRelays(const relays: string): boolean; function OpenRelays(const relays: string): boolean; function OpenAllRelays(): boolean; function SwitchRelaysOnOff(const relays: string; const tdelay: cardinal = 50): boolean; function SwitchRelaysOffOn(const relays: string; const tdelay: cardinal = 50): boolean; function QueryRelays(var closednrs, openednrs: string): boolean; function GetClosedRelays(): string; function GetOpenedRelays(): string; function GetAllRelays(): string; function VerifyClosedRelays(const refrelnrs: string): boolean; end; TRelayControl = class(TInterfacedObject, IRelayControl, ITextMessengerImpl) protected i_rcount: integer; t_curconn: TConnBase; t_msgrimpl:TTextMessengerImpl; protected procedure SetConnection(const conn: TConnBase); virtual; public constructor Create(); destructor Destroy; override; function CloseRelays(const relays: string): boolean; virtual; function OpenRelays(const relays: string): boolean; virtual; function OpenAllRelays(): boolean; virtual; function SwitchRelaysOnOff(const relays: string; const tdelay: cardinal): boolean; virtual; function SwitchRelaysOffOn(const relays: string; const tdelay: cardinal): boolean; virtual; function QueryRelays(var closednrs, openednrs: string): boolean; virtual; function GetClosedRelays(): string; virtual; function GetOpenedRelays(): string; virtual; function GetAllRelays(): string; virtual; function VerifyClosedRelays(const refrelnrs: string): boolean; virtual; property CurConnect: TConnBase read t_curconn write SetConnection; property MessengerService: TTextMessengerImpl read t_msgrimpl implements ITextMessengerImpl; property RelayCount: integer read i_rcount; end; TRelayHygrosenUsb = class(TRelayControl) public //constructor Create(); //destructor Destroy; override; property CurConnect: TConnBase read t_curconn; end; //Every Keithley Pseudocard 7705 has 40 channels and they are nummerized : //101, 102, ..., 140 for the first pseudo card //201, 202, ..., 240 for the second pseudo card, and so on //301-340 for third, 401-440 for forth and 501-540 for fifth card //here a channel set (index of channel) is defined for all channels which are being mapped from 0 to 199, //together are 200 channels for 5 cards. Die mapping: //101, 102, ..., 140, 201, 202, ..., 240, ......, 501, 502, ..., 540 //0, 1, ..., 39, 40, 41, ..., 79, ......, 160, 161, ..., 199 //using channel set it's easy to compare two groups of relays, see in VerifyClosedRelays TKeithleyChannelIndex = 0..199; TKeithleyChannelSet = set of TKeithleyChannelIndex; //a class to control Keithley Pseudocard 7705 TRelayKeithley = class(TRelayControl) protected t_slots: TStrings; set_all: TKeithleyChannelSet; protected procedure UpdateCardInfo(); procedure SetConnection(const conn: TConnBase); override; function GetCardSlots(): integer; function GetCardName(idx: integer): string; function GetClosedRelayNrs(var closednrs: string): boolean; function ChannelIndexSet(const chnr: string): TKeithleyChannelSet; function ChannelNumbers(const chset: TKeithleyChannelSet): string; function ChannelIndexToNumber(const idx: integer): string; function ChannelNumberToIndex(const chnr: string): integer; public constructor Create(); destructor Destroy; override; function CloseRelays(const relays: string): boolean; override; function OpenRelays(const relays: string): boolean; override; function OpenAllRelays(): boolean; override; function QueryRelays(var closednrs, openednrs: string): boolean; override; function GetClosedRelays(): string; override; function GetOpenedRelays(): string; override; function GetAllRelays(): string; override; function VerifyClosedRelays(const refrelnrs: string): boolean; override; property CardSlots: integer read GetCardSlots; property CardName[idx: integer]: string read GetCardName; end; implementation uses SysUtils, GenUtils, StrUtils; const C_MULTIMETER_OPT = '*OPT?'; //query which typ of pseudo card and how many cards are installed C_MULTIMETER_OPEN_ALL = 'ROUT:OPEN:ALL'; //open all relays C_MULTIMETER_OPEN = 'ROUT:MULT:OPEN (@%s)'; //n relays to open. %s: relay numbers with separator ',' C_MULTIMETER_CLOSE = 'ROUT:MULT:CLOS (@%s)'; //n relays to clase. %s: relay numbers with separator ',' C_MULTIMETER_CLOSE_ASK = 'ROUT:CLOS?'; // geschlossene Relais abfragen C_PCARD_CHANNEL_MAX = 40; //channels of one Pseudocard 7705 C_PCARD_SLOT_MAX = 5; //maximal slots for Pseudocard 7705 procedure TRelayControl.SetConnection(const conn: TConnBase); begin t_curconn := conn; end; constructor TRelayControl.Create(); begin inherited Create(); i_rcount := 0; t_msgrimpl := TTextMessengerImpl.Create(ClassName()); end; destructor TRelayControl.Destroy; begin t_msgrimpl.Free(); inherited Destroy(); end; function TRelayControl.CloseRelays(const relays: string): boolean; begin result := false; if assigned(t_curconn) then begin result := t_curconn.SendStr(relays); end; end; function TRelayControl.OpenRelays(const relays: string): boolean; begin result := false; if assigned(t_curconn) then begin result := t_curconn.SendStr(relays); end; end; function TRelayControl.OpenAllRelays(): boolean; begin result := false; end; function TRelayControl.SwitchRelaysOnOff(const relays: string; const tdelay: cardinal): boolean; begin result := CloseRelays(relays); if result then begin TGenUtils.Delay(tdelay); result := OpenRelays(relays); end; end; function TRelayControl.SwitchRelaysOffOn(const relays: string; const tdelay: cardinal): boolean; begin result := OpenRelays(relays); if result then begin TGenUtils.Delay(tdelay); result := CloseRelays(relays); end; end; function TRelayControl.QueryRelays(var closednrs, openednrs: string): boolean; begin closednrs := ''; openednrs := ''; result := false; end; function TRelayControl.GetClosedRelays(): string; begin result := ''; end; function TRelayControl.GetOpenedRelays(): string; begin result := ''; end; function TRelayControl.GetAllRelays(): string; begin result := ''; end; function TRelayControl.VerifyClosedRelays(const refrelnrs: string): boolean; begin result := false; end; procedure TRelayKeithley.UpdateCardInfo(); var i, i_start, i_end, i_cards: integer; s_recv: string; begin t_slots.Clear(); i_cards := 0; set_all := []; if assigned(t_curconn) then begin if t_curconn.SendStr(C_MULTIMETER_OPT + Char(13)) then begin t_curconn.ExpectStr(s_recv, AnsiChar(13), false); s_recv := trim(s_recv); if (ExtractStrings([','], [' '], PChar(s_recv), t_slots) > 0) then begin for i := 0 to t_slots.Count - 1 do if SameText(t_slots[i], '7705') then begin inc(i_cards); i_start := C_PCARD_CHANNEL_MAX * i; i_end := C_PCARD_CHANNEL_MAX * i + 39; set_all := set_all + [i_start..i_end]; end; i_rcount := i_cards * C_PCARD_CHANNEL_MAX; end; if (i_cards > 0) then t_msgrimpl.AddMessage(format('%d available relay cards(%s) are found.', [i_cards, s_recv])) else t_msgrimpl.AddMessage('No available relay card is found.', ML_WARNING); end; end; end; procedure TRelayKeithley.SetConnection(const conn: TConnBase); begin inherited SetConnection(conn); UpdateCardInfo(); end; function TRelayKeithley.GetCardSlots(): integer; begin result := t_slots.Count; end; function TRelayKeithley.GetCardName(idx: integer): string; begin if ((idx >= 0) and (idx < t_slots.Count)) then result := t_slots[idx] else result := ''; end; function TRelayKeithley.GetClosedRelayNrs(var closednrs: string): boolean; var s_recv: string; begin result := false; closednrs := ''; if assigned(t_curconn) then begin if t_curconn.SendStr(C_MULTIMETER_CLOSE_ASK + Char(13)) then begin if t_curconn.ExpectStr(s_recv, ')', false) then begin result := true; s_recv := trim(s_recv); if (StartsText('(@', s_recv) and EndsText(')', s_recv)) then closednrs := MidStr(s_recv, 3, length(s_recv) - 3) end; end; end; end; function TRelayKeithley.ChannelIndexSet(const chnr: string): TKeithleyChannelSet; var t_chnrs: TStrings; i, i_idx: integer; begin t_chnrs := TStringList.Create(); result := []; if (ExtractStrings([','], [' '], PChar(chnr), t_chnrs) > 0) then begin for i := 0 to t_chnrs.Count - 1 do begin i_idx := ChannelNumberToIndex(t_chnrs[i]); if (i_idx >= Low(TKeithleyChannelIndex)) then Include(result, i_idx); end; end; t_chnrs.Free(); end; function TRelayKeithley.ChannelNumbers(const chset: TKeithleyChannelSet): string; var i: integer; s_chnr: string; begin result := ''; for i := Low(TKeithleyChannelIndex) to High(TKeithleyChannelIndex) do begin if (i in chset) then begin s_chnr := ChannelIndexToNumber(i); if (s_chnr <> '') then result := result + s_chnr + ','; end; end; if EndsText(',', result) then result := LeftStr(result, length(result) - 1); end; function TRelayKeithley.ChannelIndexToNumber(const idx: integer): string; var i_nr: integer; begin if ((idx >= Low(TKeithleyChannelIndex)) and (idx <= High(TKeithleyChannelIndex))) then begin i_nr := ((idx div C_PCARD_CHANNEL_MAX) + 1) * 100 + (idx mod C_PCARD_CHANNEL_MAX) + 1; result := IntToStr(i_nr); end else result := ''; end; function TRelayKeithley.ChannelNumberToIndex(const chnr: string): integer; var i_chnr, i_cardnr: integer; begin result := -1; if TryStrToInt(chnr, i_chnr) then begin i_cardnr := trunc(i_chnr / 100); i_chnr := (i_chnr mod 100); if ((i_cardnr > 0) and (i_cardnr <= t_slots.Count) and (i_chnr <= C_PCARD_CHANNEL_MAX)) then result := (i_cardnr - 1) * C_PCARD_CHANNEL_MAX + i_chnr - 1; end; end; constructor TRelayKeithley.Create(); begin inherited Create(); t_slots := TStringList.Create(); end; destructor TRelayKeithley.Destroy; begin t_slots.Free(); inherited Destroy(); end; function TRelayKeithley.CloseRelays(const relays: string): boolean; begin result := false; if assigned(t_curconn) then begin result := t_curconn.SendStr(Format(C_MULTIMETER_CLOSE + AnsiChar(13), [relays])); if result then result := VerifyClosedRelays(relays); end; end; function TRelayKeithley.OpenRelays(const relays: string): boolean; var set_relopen, set_relclose: TKeithleyChannelSet; s_relclose: string; begin result := false; if assigned(t_curconn) then begin result := t_curconn.SendStr(format(C_MULTIMETER_OPEN + AnsiChar(13), [relays])); if result then begin s_relclose := GetClosedRelays(); if (s_relclose <> '') then begin set_relclose := ChannelIndexSet(s_relclose); set_relopen := ChannelIndexSet(relays); result := ((set_relopen * set_relclose) = []); end; end; end; end; function TRelayKeithley.OpenAllRelays(): boolean; begin result := false; if assigned(t_curconn) then begin result := t_curconn.SendStr(C_MULTIMETER_OPEN_ALL + Char(13)); if result then result := VerifyClosedRelays(''); end; end; function TRelayKeithley.QueryRelays(var closednrs, openednrs: string): boolean; var set_closed, set_opened: TKeithleyChannelSet; begin result := false; closednrs := ''; openednrs := ''; if GetClosedRelayNrs(closednrs) then begin set_closed := ChannelIndexSet(closednrs); set_opened := (set_all - set_closed); openednrs := ChannelNumbers(set_opened); end; end; function TRelayKeithley.GetClosedRelays(): string; begin GetClosedRelayNrs(result); end; function TRelayKeithley.GetOpenedRelays(): string; var s_closed: string; begin QueryRelays(s_closed, result); end; function TRelayKeithley.GetAllRelays(): string; begin result := ChannelNumbers(set_all); end; function TRelayKeithley.VerifyClosedRelays(const refrelnrs: string): boolean; var set_refrel, set_isrel: TKeithleyChannelSet; s_isrel: string; begin result := GetClosedRelayNrs(s_isrel); if result then begin set_refrel := ChannelIndexSet(refrelnrs); set_isrel := ChannelIndexSet(s_isrel); result := (set_refrel <= set_isrel) and (set_refrel <> []); end; end; end.
{ **** UBPFD *********** by delphibase.endimus.com **** >> Поместить/получить строку из буфера обмена (Заплатка к стандартным) Под Win2k попытка вставить русскую строку в Clipboard ClipBoard.AsText:='Проба' с последующей вставкой в Word'е показывает кракозябрики.. Расследование показало, что виноваты мелкомягкие (как обычно :) ) С целью нивелирования различий между всеми Win-платформами были написаны эти 2 ф-ции.. Принимают на вход/возвращают строку в Unicode - WideString.. но не надо беспокоиться, Дельфи сам вставит при необходимости конвертацию в/из AnsiString. Если платформа поддерживает уникод (NT), то используется этот формат, иначе вызываются стандартные процедуры/ф-ции. Удачи! Зависимости: ClipBrd Автор: Shaman_Naydak, shanturov@pisem.net Copyright: Shaman_Naydak Дата: 26 июня 2002 г. ***************************************************** } unit RClipBrd; interface procedure PutStringIntoClipBoard(const Str: WideString); function GetStringFromClipboard: WideString; implementation uses Windows, Messages, Classes, Graphics, ClipBrd; procedure PutStringIntoClipBoard(const Str: WideString); var Size: Integer; Data: THandle; DataPtr: Pointer; begin Size := Length(Str); if Size = 0 then exit; if not IsClipboardFormatAvailable(CF_UNICODETEXT) then Clipboard.AsText := Str else begin Size := Size shl 1 + 2; Data := GlobalAlloc(GMEM_MOVEABLE + GMEM_DDESHARE, Size); try DataPtr := GlobalLock(Data); try Move(Pointer(Str)^, DataPtr^, Size); Clipboard.SetAsHandle(CF_UNICODETEXT, Data); finally GlobalUnlock(Data); end; except GlobalFree(Data); raise; end; end; end; function GetStringFromClipboard: WideString; var Data: THandle; begin if not IsClipboardFormatAvailable(CF_UNICODETEXT) then Result := Clipboard.AsText else begin Clipboard.Open; Data := GetClipboardData(CF_UNICODETEXT); try if Data <> 0 then Result := PWideChar(GlobalLock(Data)) else Result := ''; finally if Data <> 0 then GlobalUnlock(Data); Clipboard.Close; end; end; end; end.
unit UWinUtils; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 2007 by Bradford Technologies, Inc. } interface uses Controls, Classes, UCraftClass; {Directory Handling Utilities} function GetWindowsDirectory : string; function GetWindowsSystemDirectory : string; function GetWindowsTempDirectory : string; function GetCurrentDirectory : string; {Cursor Handling Utilities} function SetMouseCursor(ACursor: TCursor): TCursor; procedure PushMouseCursor(ACursor: TCursor = crHourglass); procedure PopMouseCursor; {Generic File Handing Utilities} function RecycleFile(AFileName: string; const ProgressCaption: string = EMPTY_STRING) : Boolean; function MoveFile(SourceFileName, TargetFileName : string; Overwrite: Boolean = False) : Boolean; function CopyFile(SourceFileName, TargetFileName : string; Overwrite: Boolean = True) : Boolean; procedure WriteFile(const AFileName, AText: string); overload; procedure WriteFile(const AFileName: string; AStream : TStream); overload; procedure AppendLineToFile(const AFileName: string; ALine : string); procedure AppendToFile(const AFileName, AText: string); function FileSize(const AFileName : string): Int64; function WinExecAndWait32(const FileName: String; const Visibility: Integer): LongWord; implementation Uses Windows, SysUtils, Forms, ShellAPI; var GlobalMouseCursorStack: TList = nil; GDisabledTaskWindows: Pointer = nil; {Directory Handling Utilities} function GetWindowsDirectory : string; begin SetLength(Result, MAX_PATH); SetLength(Result, Windows.GetWindowsDirectory(PChar(Result), MAX_PATH)); end; function GetWindowsSystemDirectory: string; begin SetLength(Result, MAX_PATH); SetLength(Result, Windows.GetSystemDirectory(PChar(Result), MAX_PATH)); end; function GetWindowsTempDirectory : string; begin SetLength(Result, MAX_PATH); SetLength(Result, Windows.GetTempPath(MAX_PATH, PChar(Result))); if Copy(Result, Length(Result), 1) = '\' then Delete(Result, Length(Result), 1); end; function GetCurrentDirectory : string; begin SetLength(Result, MAX_PATH); SetLength(Result, Windows.GetCurrentDirectory(MAX_PATH, PChar(Result))); if Copy(Result, Length(Result), 1) = '\' then Delete(Result, Length(Result), 1); end; {Cursor Handling Utilities} function SetMouseCursor(ACursor : TCursor) : TCursor; begin Result := Screen.Cursor; Screen.Cursor := ACursor; end; procedure PushMouseCursor(ACursor : TCursor); begin if GlobalMouseCursorStack = nil then GlobalMouseCursorStack := TList.Create; GlobalMouseCursorStack.Add(Pointer(SetMouseCursor(ACursor))); // prevent clicking if (GlobalMouseCursorStack.Count = 0) and (ACursor = crHourglass) then GDisabledTaskWindows := DisableTaskWindows(0); end; procedure PopMouseCursor; begin if (GlobalMouseCursorStack <> nil) and (GlobalMouseCursorStack.Count > 0) then begin // enable clicking if (GlobalMouseCursorStack.Count = 0) and Assigned(GDisabledTaskWindows) then begin EnableTaskWindows(GDisabledTaskWindows); GDisabledTaskWindows := nil; end; SetMouseCursor(TCursor(GlobalMouseCursorStack.Last)); GlobalMouseCursorStack.Delete(GlobalMouseCursorStack.Count - 1); end; end; function BaseShellFunction(SourceFileName : string; AFunction : Integer; TargetFileName : string = EMPTY_STRING; const ProgressCaption : string = EMPTY_STRING) : Boolean; var ThisFileInfo : TSHFileOpStruct; WasAborted : Boolean; begin SourceFileName := ExpandFileName(SourceFileName); if (TargetFileName <> EMPTY_STRING) and (ExtractFileDir(TargetFileName) = EMPTY_STRING) then TargetFileName := IncludeTrailingPathDelimiter(GetCurrentDirectory) + TargetFileName; FillChar(ThisFileInfo, SizeOf(ThisFileInfo), 0); with ThisFileInfo do begin Wnd := 0; wFunc := AFunction; pFrom := PChar(SourceFileName + #0); pTo := PChar(TargetFileName + #0); if ProgressCaption <> EMPTY_STRING then fFlags := FOF_ALLOWUNDO and FOF_SIMPLEPROGRESS + FOF_NOCONFIRMATION + FOF_NOCONFIRMMKDIR + FOF_NOERRORUI else fFlags := FOF_ALLOWUNDO and FOF_SILENT + FOF_NOCONFIRMATION + FOF_NOCONFIRMMKDIR + FOF_NOERRORUI; WasAborted := False; fAnyOperationsAborted := WasAborted; hNameMappings := nil; if ProgressCaption <> EMPTY_STRING then lpszProgressTitle := PChar(ProgressCaption) else lpszProgressTitle := nil; Result := (ShellAPI.SHFileOperation(ThisFileInfo) = 0) and (not WasAborted); end; end; function RecycleFile(AFileName : string; const ProgressCaption : string = EMPTY_STRING) : Boolean; begin Result := FileExists(AFileName) or DirectoryExists(AFileName) or DirectoryExists(ExtractFileDir(AFileName)); if Result then Result := BaseShellFunction(AFileName, FO_DELETE, ProgressCaption); end; function MoveFile(SourceFileName, TargetFileName : string; Overwrite : Boolean) : Boolean; begin Result := FileExists(SourceFileName); if Result then begin if FileExists(TargetFileName) then begin if Overwrite then RecycleFile(TargetFileName) else begin Result := False; Exit; end; end; Result := BaseShellFunction(SourceFileName, FO_MOVE, TargetFileName); end; end; function CopyFile(SourceFileName, TargetFileName : string; Overwrite : Boolean) : Boolean; begin Result := FileExists(SourceFileName); if Result then begin if FileExists(TargetFileName) then begin if Overwrite then RecycleFile(TargetFileName) else begin Result := False; Exit; end; end; Result := BaseShellFunction(SourceFileName, FO_COPY, TargetFileName); end; end; procedure WriteFile(const AFileName : string; AStream : TStream); var ThisStringStream : TStringStream; begin ThisStringStream := TStringStream.Create(''); try ThisStringStream.CopyFrom(AStream, 0); WriteFile(AFileName, ThisStringStream.DataString); finally ThisStringStream.Free; end; end; procedure WriteFile(const AFileName, AText : string); begin if SameText(AFileName, 'stdout') then SysUtils.FileWrite(Windows.GetStdHandle(STD_OUTPUT_HANDLE), PChar(AText)^, Length(AText)) else begin with TFileStream.Create(AFileName, fmCreate) do try Write(PChar(AText)^, Length(AText)); finally Free; end; end; end; procedure AppendToFile(const AFileName, AText : string); begin if FileExists(AFileName) then begin with TFileStream.Create(AFileName, fmOpenReadWrite) do try Position := Size; Write(PChar(AText)^, Length(AText)); finally Free; end; end else WriteFile(AFileName, AText); end; procedure AppendLineToFile(const AFileName : string; ALine : string); begin if FileExists(AFileName) then begin with TFileStream.Create(AFileName, fmOpenReadWrite) do try if Size > 0 then ALine := #13#10 + TrimLeft(ALine); Position := Size; Write(PChar(ALine)^, Length(ALine)); finally Free; end; end else WriteFile(AFileName, ALine); end; function FileSize(const AFileName : string) : Int64; begin try with TCraftingFileStream.ReadOnly(AFileName, fmShareDenyNone) do try Result := Size; finally Free; end; except Result := -1; end; end; function WinExecAndWait32(const FileName: String; const Visibility: Integer): LongWord; var zAppName: array[0..512] of Char; zCurDir: array[0..255] of Char; WorkDir: string; StartupInfo: TStartupInfo; ProcessInfo: TProcessInformation; begin StrPCopy(zAppName, FileName); GetDir(0, WorkDir); StrPCopy(zCurDir, WorkDir); FillChar(StartupInfo, Sizeof(StartupInfo), #0); StartupInfo.cb := Sizeof(StartupInfo); StartupInfo.dwFlags := STARTF_USESHOWWINDOW; StartupInfo.wShowWindow := Visibility; if not CreateProcess(nil, zAppName, nil, nil, false, CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInfo) then Result := $ffffffff else begin WaitforSingleObject(ProcessInfo.hProcess, INFINITE); GetExitCodeProcess(ProcessInfo.hProcess, Result); CloseHandle(ProcessInfo.hProcess); CloseHandle(ProcessInfo.hThread); end; end; end.
unit StratTypes; interface uses FrogObj, Strategy, Classes; const MAX_STRATS = 20; DEFAULT_SWITCH_AFTER = 9; MAX_ITERS = 20; type // TStrategyType = (stBasic, stExpo, stIntenGate, stProjections, stOverstep, // stFRMin, stPRMin, stXFrogProj, stModErrProj); TStrategyCals = class(TFrogObject) private mAppPath: string; function GetName(i: integer): string; procedure SetName(i: integer; pName: string); function GetSwitch(i: integer): integer; procedure SetSwitch(i, pSwitch: integer); function GetNewField(i: integer): double; procedure SetNewField(i: integer; pNewField: double); function GetSpecial(i: integer): integer; procedure SetSpecial(i: integer; pSpecial: integer); procedure CheckIntenIters(pI: integer); function StratFileName: string; protected mAvailableStrategies: TStringList; mNames: array[1..MAX_STRATS] of string; mSwitchAfter: array[1..MAX_STRATS] of integer; mNewField: array[1..MAX_STRATS] of double; mSpecial: array[1..MAX_STRATS] of integer; mNumStrats: integer; procedure CreateDefaultSchedule; virtual; procedure ReadFromFile; virtual; procedure SaveToFile; virtual; function AllowSpecial(pStrat: string): boolean; virtual; public function NameOfStrategy(i: integer): string; function TotalNumStrategies: integer; function ClassRef(pStratType: string): TStrategyClass; procedure InsertStrategy(pI: integer); procedure DeleteStrategy(pI: integer); property NumStrategies: integer read mNumStrats; property Name[i: integer]: string read GetName write SetName; property SwitchAfter[i: integer]: integer read GetSwitch write SetSwitch; property Special[i: integer]: integer read GetSpecial write SetSpecial; property NewField[i: integer]: double read GetNewField write SetNewField; constructor Create; destructor Destroy; override; end; TStratClassHolder = class private mClassRef: TStrategyClass; public property MyClassRef: TStrategyClass read mClassRef write mClassRef; constructor Create(pClassRef: TStrategyClass); end; const FILE_NAME = 'strat.txt'; stBasic = 'Basic'; stExpo = 'Expo'; stIntenGate = 'IntenGate'; stProjections = 'Projections'; stOverstep = 'Proj. - Overstep'; stFRMin = 'Minimization - FR'; stPRMin = 'Minimization - PR'; implementation // In order to add a new Strategy Class to this class, do // 1. Add the unit to the implementation uses clause // 2. Add its name to the string and type lists in the constructor // 3. Add its Class Type to the ClassRef function. uses SysUtils, BasicFrog, Expo, IntenGate, Projection, Overstep, FRMin, PRMin; constructor TStrategyCals.Create; begin inherited Create; // This object gets instantiated at program startup, so it should have the // app path as the starting path mAppPath := GetCurrentDir; mAvailableStrategies := TStringList.Create; mAvailableStrategies.AddObject(stBasic, TStratClassHolder.Create(TBasicStrategy)); mAvailableStrategies.AddObject(stExpo, TStratClassHolder.Create(TExpoStrategy)); mAvailableStrategies.AddObject(stIntenGate, TStratClassHolder.Create(TIntenGateStrategy)); mAvailableStrategies.AddObject(stProjections, TStratClassHolder.Create(TProjection)); mAvailableStrategies.AddObject(stOverstep, TStratClassHolder.Create(TOverstep)); mAvailableStrategies.AddObject(stFRMin, TStratClassHolder.Create(TFRMin)); mAvailableStrategies.AddObject(stPRMin, TStratClassHolder.Create(TPRMin)); // Qualify the file name try ReadFromFile; except DeleteFile(StratFileName); CreateDefaultSchedule; end; end; function TStrategyCals.ClassRef(pStratType: string): TStrategyClass; var i: integer; begin i := mAvailableStrategies.IndexOf(pStratType); if i = (-1) then begin ClassRef := nil; raise Exception.Create('Strategy name not in list: ' + pStratType); end else ClassRef := TStratClassHolder(mAvailableStrategies.Objects[i]).MyClassRef; end; procedure TStrategyCals.CreateDefaultSchedule; begin mNames[1] := stBasic; mSwitchAfter[1] := DEFAULT_SWITCH_AFTER; mNewField[1] := 0; mSpecial[1] := 0; mNames[2] := stProjections; mSwitchAfter[2] := DEFAULT_SWITCH_AFTER; mNewField[2] := 0; mSpecial[2] := 5; mNames[3] := stOverstep; mSwitchAfter[3] := DEFAULT_SWITCH_AFTER; mNewField[3] := 0; mSpecial[3] := 0; mNames[4] := stIntenGate; mSwitchAfter[4] := DEFAULT_SWITCH_AFTER; mNewField[4] := 0; mSpecial[4] := 0; mNames[5] := stExpo; mSwitchAfter[5] := DEFAULT_SWITCH_AFTER; mNewField[5] := 0; mSpecial[5] := 0; mNames[6] := stProjections; mSwitchAfter[6] := DEFAULT_SWITCH_AFTER; mNewField[6] := -1; mSpecial[6] := 0; mNames[7] := stProjections; mSwitchAfter[7] := DEFAULT_SWITCH_AFTER; mNewField[7] := 0.05; mSpecial[7] := 0; mNumStrats := 7; end; function TStrategyCals.TotalNumStrategies: integer; begin TotalNumStrategies := mAvailableStrategies.Count; end; function TStrategyCals.NameOfStrategy(i: integer): string; begin NameOfStrategy := mAvailableStrategies[i]; end; // List manipulation function TStrategyCals.GetName(i: integer): string; begin GetName := mNames[i]; end; procedure TStrategyCals.SetName(i: integer; pName: string); begin mNames[i] := pName; CheckIntenIters(i); end; function TStrategyCals.GetSwitch(i: integer): integer; begin GetSwitch := mSwitchAfter[i]; end; procedure TStrategyCals.SetSwitch(i, pSwitch: integer); begin mSwitchAfter[i] := pSwitch; if mSwitchAfter[i] > MAX_ITERS then mSwitchAfter[i] := MAX_ITERS; CheckIntenIters(i); end; function TStrategyCals.GetNewField(i: integer): double; begin GetNewField := mNewField[i]; end; procedure TStrategyCals.SetNewField(i: integer; pNewField: double); begin mNewField[i] := pNewField; end; function TStrategyCals.GetSpecial(i: integer): integer; begin GetSpecial := mSpecial[i]; end; procedure TStrategyCals.SetSpecial(i: integer; pSpecial: integer); begin // This is now used for shortcuts if (pSpecial < 0) then pSpecial := 0; if (pSpecial = 1) or (pSpecial = 2) then pSpecial := 3; if AllowSpecial(mNames[i]) then mSpecial[i] := pSpecial else mSpecial[i] := 0; end; function TStrategyCals.AllowSpecial(pStrat: string): boolean; begin if (pStrat = stProjections) or (pStrat = stOverstep) then AllowSpecial := True else AllowSpecial := False; end; procedure TStrategyCals.CheckIntenIters(pI: integer); begin if (mNames[pI] = stIntenGate) and (mSwitchAfter[pI] < 3) then mSwitchAfter[pI] := 3; end; procedure TStrategyCals.InsertStrategy(pI: integer); var j: integer; begin Inc(mNumStrats); for j := mNumStrats downto pI + 2 do begin mNames[j] := mNames[j - 1]; mSwitchAfter[j] := mSwitchAfter[j - 1]; mNewField[j] := mNewField[j - 1]; mSpecial[j] := mSpecial[j - 1]; end; end; procedure TStrategyCals.DeleteStrategy(pI: integer); var j: integer; begin // These arrays are 1-based. But when you delete the first row on the form, // it comes in as zero based. So without this next line you are overwriting // memory somewhere (I thought Object Pascal didn't let you do that? Are we // writing C again?) pI := pI + 1; for j := pI to mNumStrats - 1 do begin mNames[j] := mNames[j + 1]; mSwitchAfter[j] := mSwitchAfter[j + 1]; mNewField[j] := mNewField[j + 1]; mSpecial[j] := mSpecial[j + 1]; end; Dec(mNumStrats); end; destructor TStrategyCals.Destroy; var i, count: integer; begin SaveToFile; count := mAvailableStrategies.Count; for i := 0 to count - 1 do mAvailableStrategies.Objects[i].Free; mAvailableStrategies.Free; mAvailableStrategies := nil; inherited Destroy; end; procedure TStrategyCals.SaveToFile; var sList: TStringList; i: integer; begin sList := TStringList.Create; try sList.Add(IntToStr(mNumStrats)); for i := 1 to mNumStrats do begin sList.Add(mNames[i]); sList.Add(IntToStr(mSwitchAfter[i])); sList.Add(FloatToStr(mNewField[i])); sList.Add(FloatToStr(mSpecial[i])); end; sList.SaveToFile(StratFileName); finally sList.Free; end; end; procedure TStrategyCals.ReadFromFile; var sList: TStringList; i, cursor: integer; begin sList := TStringList.Create; cursor := 0; try sList.LoadFromFile(StratFileName); mNumStrats := StrToInt(sList[cursor]); if (mNumStrats < 1) or (mNumStrats > MAX_STRATS) then raise Exception.Create('Error'); Inc(cursor); for i := 1 to mNumStrats do begin mNames[i] := sList[cursor]; if mAvailableStrategies.IndexOf(mNames[i]) = -1 then raise Exception.Create('Error'); Inc(cursor); mSwitchAfter[i] := StrToInt(sList[cursor]); if (mSwitchAfter[i] < 0) or (mSwitchAfter[i] > MAX_ITERS) then raise Exception.Create('Error'); if (mSwitchAfter[i] = 0) then mSwitchAfter[i] := DEFAULT_SWITCH_AFTER; Inc(cursor); mNewField[i] := StrToFloat(sList[cursor]); Inc(cursor); mSpecial[i] := StrToInt(sList[cursor]); Inc(cursor); end; finally sList.Free; end; end; function TStrategyCals.StratFileName: string; begin Result := mAppPath + '\' + FILE_NAME; end; constructor TStratClassHolder.Create(pClassRef: TStrategyClass); begin mClassRef := pClassRef; end; end.
unit RttiPatch; interface {$I DSharp.inc} // Thanks to Andreas Hausladen implementation {$IF CompilerVersion > 20} uses Generics.Collections, PatchUtils, RTLConsts, Rtti, SysConst, SysUtils, TypInfo, Windows; var IsPatched: Boolean = False; {--------------------------------------------------------------------------------------------------} type PInterceptFrame = Pointer; PParamLoc = ^TParamLoc; TParamLoc = record FTypeInfo: PTypeInfo; FByRefParam: Boolean; FOffset: Integer; procedure SetArg(AFrame: PInterceptFrame; const Value: TValue); end; const SetArgCallBytes: array[0..18] of SmallInt = ( $8D, $04, $5B, // lea eax,[ebx+ebx*2] // 0 $8B, $55, $F0, // mov edx,[ebp-$10] // 3 $8D, $0C, $C2, // lea ecx,[edx+eax*8] // 6 $8B, $55, $FC, // mov edx,[ebp-$04] // 9 $8D, $04, $82, // lea eax,[edx+eax*4] // 12 $8B, $55, $F4, // mov edx,[ebp-$0c] // 15 $E8 // call TMethodImplementation.TParamLoc.SetArg // 18 ); var TParamLoc_SetArg: procedure(var Self: TParamLoc; AFrame: PInterceptFrame; const Value: TValue); procedure TParamLoc.SetArg(AFrame: PInterceptFrame; const Value: TValue); begin // Fix from XE2 if FByRefParam then TParamLoc_SetArg(Self, AFrame, Value); end; {--------------------------------------------------------------------------------------------------} type {$M+} {$RTTI EXPLICIT METHODS([vcPublic, vcPublished])} IIntfMethodHelper = interface procedure IntfMethod; end; {$RTTI EXPLICIT METHODS([vcPublic, vcPublished])} TInstanceMethodHelper = class(TObject) public procedure InstanceMethod; end; {$M-} TRttiMethodFix = class(TRttiMethod) public function IntfDispatchInvoke(Instance: TValue; const Args: array of TValue): TValue; function InstanceDispatchInvoke(Instance: TValue; const Args: array of TValue): TValue; end; PPVtable = ^PVtable; PVtable = ^TVtable; TVtable = array[0..MaxInt div SizeOf(Pointer) - 1] of Pointer; TValueHelper = record helper for TValue {$IF CompilerVersion = 21} function Cast(ATypeInfo: PTypeInfo): TValue; function TryCastFix(ATypeInfo: PTypeInfo; out AResult: TValue): Boolean; {$IFEND} function TryAsOrdinalFix(out AResult: Int64): Boolean; end; {$IF CompilerVersion = 21} const GUID_NULL: TGUID = '{00000000-0000-0000-0000-000000000000}'; function ConvClass2Intf(const ASource: TValue; ATarget: PTypeInfo; out AResult: TValue): Boolean; var iid: TGUID; obj: Pointer; begin iid := GetTypeData(ATarget)^.Guid; if IsEqualGUID(iid, GUID_NULL) then Exit(False); Result := ASource.AsObject.GetInterface(iid, obj); if Result then TValue.MakeWithoutCopy(@obj, ATarget, AResult); end; function TValueHelper.Cast(ATypeInfo: PTypeInfo): TValue; begin if not TryCastFix(ATypeInfo, Result) then raise EInvalidCast.CreateRes(@SInvalidCast); end; function TValueHelper.TryCastFix(ATypeInfo: PTypeInfo; out AResult: TValue): Boolean; begin if Self.FData.FTypeInfo = ATypeInfo then begin AResult := Self; Exit(True); end; if (Self.FData.FTypeInfo^.Kind = tkClass) and (ATypeInfo^.Kind = tkInterface) then begin if IsEmpty then begin // nil converts to reference types AResult := TValue.Empty; Result := (ATypeInfo <> nil) and (ATypeInfo^.Kind in [tkInterface, tkClass, tkClassRef]); if Result then AResult.FData.FTypeInfo := ATypeInfo; Exit; end; if ATypeInfo = nil then Exit(False); Result := ConvClass2Intf(Self, ATypeInfo, AResult); end else Result := TryCast(ATypeInfo, AResult); end; {$IFEND} function GetInlineSize(TypeInfo: PTypeInfo): Integer; begin if TypeInfo = nil then Exit(0); case TypeInfo^.Kind of tkInteger, tkEnumeration, tkChar, tkWChar, tkSet: case GetTypeData(TypeInfo)^.OrdType of otSByte, otUByte: Exit(1); otSWord, otUWord: Exit(2); otSLong, otULong: Exit(4); else Exit(0); end; tkFloat: case GetTypeData(TypeInfo)^.FloatType of ftSingle: Exit(4); ftDouble: Exit(8); ftExtended: Exit(SizeOf(Extended)); ftComp: Exit(8); ftCurr: Exit(8); else Exit(0); end; tkClass, tkClassRef: Exit(SizeOf(Pointer)); tkMethod: Exit(SizeOf(TMethod)); tkInt64: Exit(8); tkDynArray, tkUString, tkLString, tkWString, tkInterface: Exit(-SizeOf(Pointer)); tkString: Exit(-GetTypeData(TypeInfo)^.MaxLength + 1); tkPointer: Exit(SizeOf(Pointer)); tkProcedure: Exit(SizeOf(Pointer)); tkRecord: Exit(-GetTypeData(TypeInfo)^.RecSize); tkArray: Exit(-GetTypeData(TypeInfo)^.ArrayData.Size); tkVariant: Exit(-SizeOf(Variant)); else Exit(0); end; end; function TValueHelper.TryAsOrdinalFix(out AResult: Int64): Boolean; begin Result := not Assigned(TypeInfo) or IsOrdinal; if Result then begin case GetInlineSize(TypeInfo) of 1: AResult := TValueData(Self).FAsSByte; 2: AResult := TValueData(Self).FAsSWord; 4: AResult := TValueData(Self).FAsSLong; else AResult := TValueData(Self).FAsSInt64; end; end; end; procedure TInstanceMethodHelper.InstanceMethod; begin end; procedure CheckCodeAddress(code: Pointer); begin if (code = nil) or (PPointer(code)^ = nil) then raise EInsufficientRtti.CreateRes(@SInsufficientRtti); end; function PassByRef(TypeInfo: PTypeInfo; CC: TCallConv; IsConst: Boolean = False): Boolean; begin if TypeInfo = nil then Exit(False); case TypeInfo^.Kind of {$IF Defined(CPUX86)} tkVariant: Result := IsConst or not (CC in [ccCdecl, ccStdCall, ccSafeCall]); tkRecord: if (CC in [ccCdecl, ccStdCall, ccSafeCall]) and not IsConst then Result := False else Result := GetTypeData(TypeInfo)^.RecSize > SizeOf(Pointer); {$ELSEIF Defined(CPUX64)} tkVariant: Result := True; tkRecord: Result := not (GetTypeData(TypeInfo)^.RecSize in [1,2,4,8]); tkMethod: Result := True; {$IFEND} tkArray: Result := GetTypeData(TypeInfo)^.ArrayData.Size > SizeOf(Pointer); tkString: Result := GetTypeData(TypeInfo)^.MaxLength > SizeOf(Pointer); else Result := False; end; end; procedure PassArg(Par: TRttiParameter; const ArgSrc: TValue; var ArgDest: TValue; CC: TCallConv); begin if Par.ParamType = nil then ArgDest := TValue.From<Pointer>(ArgSrc.GetReferenceToRawData) else if Par.Flags * [TParamFlag.pfVar, TParamFlag.pfOut] <> [] then begin if Par.ParamType.Handle <> ArgSrc.TypeInfo then raise EInvalidCast.CreateRes(@SByRefArgMismatch); ArgDest := TValue.From<Pointer>(ArgSrc.GetReferenceToRawData); end else if (TParamFlag.pfConst in Par.Flags) and PassByRef(Par.ParamType.Handle, CC, True) then begin if Par.ParamType.Handle <> ArgSrc.TypeInfo then raise EInvalidCast.CreateRes(@SByRefArgMismatch); ArgDest := TValue.From(ArgSrc.GetReferenceToRawData); end else ArgDest := ArgSrc.Cast(Par.ParamType.Handle); end; procedure PushSelfFirst(CC: TCallConv; var argList: TArray<TValue>; var Index: Integer; const Value: TValue); inline; begin if CC <> TCallConv.ccPascal then begin argList[Index] := Value; Inc(Index); end; end; procedure PushSelfLast(CC: TCallConv; var argList: TArray<TValue>; var Index: Integer; const Value: TValue); inline; begin if CC = TCallConv.ccPascal then argList[Index] := Value; end; function TRttiMethodFix.IntfDispatchInvoke(Instance: TValue; const Args: array of TValue): TValue; var Code: Pointer; ArgCount: Integer; ArgList: TArray<TValue>; ParList: TArray<TRttiParameter>; I, CurrArg: Integer; Inst: PPVtable; begin ParList := GetParameters; if Length(Args) <> Length(ParList) then raise EInvocationError.CreateRes(@SParameterCountMismatch); ArgCount := Length(Args); SetLength(ArgList, ArgCount + 1); CurrArg := 0; Inst := PPVtable(Instance.AsInterface); PushSelfFirst(CallingConvention, ArgList, CurrArg, Instance); for I := 0 to Length(Args) - 1 do begin PassArg(ParList[I], Args[I], ArgList[CurrArg], CallingConvention); Inc(CurrArg); end; Assert(DispatchKind = dkInterface); Code := Inst^^[VirtualIndex]; CheckCodeAddress(Code); PushSelfLast(CallingConvention, ArgList, CurrArg, Instance); if ReturnType <> nil then Result := Rtti.Invoke(Code, ArgList, CallingConvention, ReturnType.Handle) else Result := Rtti.Invoke(Code, ArgList, CallingConvention, nil); end; function TRttiMethodFix.InstanceDispatchInvoke(Instance: TValue; const Args: array of TValue): TValue; var Code: Pointer; ArgCount: Integer; ArgList: TArray<TValue>; ParList: TArray<TRttiParameter>; I, CurrArg: Integer; Cls: TClass; Obj: TObject; Alloc: Boolean; begin ParList := GetParameters; if Length(Args) <> Length(ParList) then raise EInvocationError.CreateRes(@SParameterCountMismatch); ArgCount := Length(Args); if IsConstructor or IsDestructor then Inc(ArgCount); if not IsStatic then Inc(ArgCount); SetLength(ArgList, ArgCount); CurrArg := 0; Cls := nil; Alloc := True; Obj := nil; if not IsStatic then begin if IsConstructor then begin Alloc := Instance.TryAsType<TClass>(Cls); if Alloc then Obj := nil else begin Obj := Instance.AsObject; if Obj <> nil then Cls := Obj.ClassType else Cls := nil; end; if Alloc then PushSelfFirst(CallingConvention, ArgList, CurrArg, Cls) else PushSelfFirst(CallingConvention, ArgList, CurrArg, Obj); ArgList[CurrArg] := Alloc; Inc(CurrArg); end else if IsDestructor then begin Cls := Instance.AsObject.ClassType; PushSelfFirst(CallingConvention, ArgList, CurrArg, Instance); ArgList[CurrArg] := True; Inc(CurrArg); end else if IsClassMethod then begin Cls := Instance.AsClass; PushSelfFirst(CallingConvention, ArgList, CurrArg, Instance); end else begin Cls := Instance.AsObject.ClassType; PushSelfFirst(CallingConvention, ArgList, CurrArg, Instance); end; if (Cls <> nil) and not Cls.InheritsFrom(TRttiInstanceType(Parent).MetaclassType) then raise EInvalidCast.CreateRes(@SInvalidCast); end; for I := 0 to Length(Args) - 1 do begin PassArg(ParList[I], Args[I], ArgList[CurrArg], CallingConvention); Inc(CurrArg); end; if IsStatic then Code := CodeAddress else case DispatchKind of dkVtable: Code := PVtable(Cls)^[VirtualIndex]; dkDynamic: Code := GetDynaMethod(Cls, VirtualIndex); else Code := CodeAddress; end; CheckCodeAddress(Code); if not IsStatic then begin if IsConstructor then begin if Alloc then PushSelfLast(CallingConvention, ArgList, CurrArg, Cls) else PushSelfLast(CallingConvention, ArgList, CurrArg, Obj); end else PushSelfLast(CallingConvention, ArgList, CurrArg, Instance); end; if ReturnType <> nil then Result := Rtti.Invoke(Code, ArgList, CallingConvention, ReturnType.Handle{$IF CompilerVersion > 22}, IsStatic{$IFEND}) else if IsConstructor then Result := Rtti.Invoke(Code, ArgList, CallingConvention, Cls.ClassInfo{$IF CompilerVersion > 22}, True{$IFEND}) else Result := Rtti.Invoke(Code, ArgList, CallingConvention, nil); end; {--------------------------------------------------------------------------------------------------} {$IF CompilerVersion = 22} const TRttiMethod_CreateImplementationBytesCmp: array[0..11] of Byte = ( $53, // push ebx // 0 $56, // push esi // 1 $57, // push edi // 2 $8B, $F9, // mov edi,ecx // 3 $8B, $F2, // mov esi,edx // 5 $8B, $D8, // mov ebx,eax // 7 $8B, $C3, // mov eax,ebx // 9 $E8 // call TRttiMethod.GetInvokeInfo // 11 ); TRttiMethod_GetInvokeInfoBytes: array[0..25] of SmallInt = ( $B0, $01, // mov al,$01 // 0 $50, // push eax // 2 $8B, $C6, // mov eax,esi // 3 $8B, $10, // mov edx,[eax] // 5 $FF, $52, $10, // call dword ptr [edx+$10] // 7 $E8, -1, -1, -1, -1, // call Generics + $4C9D7C // 10 $8B, $D0, // mov edx,eax // 15 $8B, $45, $F8, // mov eax,[ebp-$08] // 17 $59, // pop ecx // 20 $E8, -1, -1, -1, -1 // call TMethodImplementation.TInvokeInfo.AddParameter // 21 ); var OrgInvokeInfoAddParameter: procedure(AInvokeInfo: TObject; AType: PTypeInfo; ByRef: Boolean); procedure FixInvokeInfoAddParameter(AInvokeInfo: TObject; AType: PTypeInfo; ByRef: Boolean; p: TRttiParameter; Method: TRttiMethod); begin OrgInvokeInfoAddParameter(AInvokeInfo, p.ParamType.Handle, ([pfVar, pfOut] * p.Flags <> []) or PassByRef(p.ParamType.Handle, Method.CallingConvention, pfConst in p.Flags)); end; procedure FixInvokeInfoAddParameterEnter(AInvokeInfo: TObject; AType: PTypeInfo; ByRef: Boolean); asm push esi // p is kept in ESI push edi // TMethodRtti is kept in EDI call FixInvokeInfoAddParameter end; {$IFEND} {--------------------------------------------------------------------------------------------------} {$IF CompilerVersion = 21} type TRttiPackageFix = class helper for TRttiPackage class function GetMakeTypeLookupTableAddress: Pointer; procedure MakeTypeLookupTableFix; end; procedure PeekData(var P: PByte; var Data; Len: Integer); begin Move(P^, Data, Len); end; procedure ReadData(var P: PByte; var Data; Len: Integer); begin PeekData(P, Data, Len); Inc(P, Len); end; function ReadU8(var P: PByte): Byte; begin ReadData(P, Result, SizeOf(Result)); end; function ReadShortString(var P: PByte): string; var len: Integer; begin Result := UTF8ToString(PShortString(P)^); len := ReadU8(P); Inc(P, len); end; class function TRttiPackageFix.GetMakeTypeLookupTableAddress: Pointer; asm lea eax, [TRttiPackage.MakeTypeLookupTable] end; procedure TRttiPackageFix.MakeTypeLookupTableFix; function GetUnits: TArray<string>; var p: PByte; i: Integer; begin SetLength(Result, Self.FTypeInfo^.UnitCount); p := Pointer(Self.FTypeInfo^.UnitNames); for i := 0 to Self.FTypeInfo^.UnitCount - 1 do Result[i] := ReadShortString(p); end; procedure DoMake; var units: TArray<string>; typeIter: PPTypeInfo; currUnit: Integer; typeName: string; i: Integer; begin Self.FLock.Acquire; try if Self.FNameToType <> nil then // presumes double-checked locking ok Exit; units := GetUnits; currUnit := 0; Self.FNameToType := TDictionary<string,PTypeInfo>.Create; Self.FTypeToName := TDictionary<PTypeInfo,string>.Create; for i := 0 to Self.FTypeInfo^.TypeCount - 1 do begin typeIter := Self.FTypeInfo^.TypeTable^[i]; if typeIter = nil then Continue; if Integer(typeIter) = 1 then begin // inter-unit boundary Inc(currUnit); Continue; end; if typeIter^ = nil then // linker broke or fixup eliminated. Continue; typeName := units[currUnit] + '.' + UTF8ToString(typeIter^^.Name); if not Self.FNameToType.ContainsKey(typeName) then Self.FNameToType.Add(typeName, typeIter^); if not Self.FTypeToName.ContainsKey(typeIter^) then Self.FTypeToName.Add(typeIter^, typeName); end; finally Self.FLock.Release; end; end; begin if Self.FNameToType <> nil then Exit; DoMake; end; {$IFEND} {--------------------------------------------------------------------------------------------------} function IsManaged(TypeInfo: PTypeInfo): Boolean; var elTypePtr: PPTypeInfo; begin if TypeInfo = nil then Exit(False); case TypeInfo^.Kind of tkDynArray, tkUString, tkWString, tkLString, tkInterface, tkVariant, tkMethod: Result := True; tkRecord: Result := GetTypeData(TypeInfo)^.ManagedFldCount > 0; tkArray: begin elTypePtr := GetTypeData(TypeInfo)^.ArrayData.ElType; Result := (elTypePtr <> nil) and IsManaged(elTypePtr^); end; else Result := False; end; end; {--------------------------------------------------------------------------------------------------} const PassByRefBytes: array[0..47] of SmallInt = ( // begin $48, $83, $EC, $28, // if TypeInfo = nil then $48, $85, $C9, $75, $05, // Exit(False); $48, $33, $C0, $EB, $79, // case TypeInfo^.Kind of $48, $0F, $B6, $01, $80, $E8, $05, $84, $C0, $74, $5A, $80, $E8, $07, $84, $C0, $74, $4F, $80, $E8, $01, $84, $C0, $74, $09, $80, $E8, $01, $84, $C0, $75, $56, $EB, $0D ); {$IF CompilerVersion = 21} GetInlineSizeBytes: array[0..29] of SmallInt = ( // begin $53, $8B, $D8, // if TypeInfo = nil then $85, $DB, $75, $04, // Exit(0); $33, $C0, $5B, $C3, // case TypeInfo^.Kind of $0F, $B6, $03, $83, $F8, $14, $0F, $87, $37, $01, $00, $00, $FF, $24, $85, -1, -1, -1, -1 ); {$ELSEIF CompilerVersion = 22} GetInlineSizeBytes: array[0..29] of SmallInt = ( // begin $53, $8B, $D8, // if TypeInfo = nil then $85, $DB, $75, $04, // Exit(0); $33, $C0, $5B, $C3, // case TypeInfo^.Kind of $0F, $B6, $03, $83, $F8, $14, $0F, $87, $30, $01, $00, $00, $FF, $24, $85, -1, -1, -1, -1 ); {$IFEND} procedure PatchRtti; {$HINTS OFF} var Ctx: TRttiContext; Meth: TRttiMethod; P: PByte; Offset: Integer; n: UINT_PTR; begin {$IF CompilerVersion = 22} // Get the code pointer of the TMethodImplementation.TInvokeInfo.GetParamLocs method for which // extended RTTI is available to find the private type private method SaveArguments. P := Ctx.GetType(TMethodImplementation).GetField('FInvokeInfo').FieldType.GetMethod('GetParamLocs').CodeAddress; // Find for the "locs[i].SetArg(AFrame, Args[i]);" call and replace it with a call to our function. P := FindMethodBytes(P - 128 - SizeOf(SetArgCallBytes), SetArgCallBytes, 128 - SizeOf(SetArgCallBytes)); if P <> nil then begin // Replace the call to SetArg with our method. @TParamLoc_SetArg := (P + 19 + 4) + PInteger(@P[19])^; Offset := PByte(@TParamLoc.SetArg) - (P + 19 + 4); if not WriteProcessMemory(GetCurrentProcess, P + 19, @Offset, SizeOf(Offset), n) then RaiseLastOSError; end else raise Exception.Create('Patching TMethodImplementation.TInvokeInfo.SaveArguments failed. Do you have set a breakpoint in the method?'); RedirectFunction(GetActualAddr(@Rtti.IsManaged), @IsManaged); {$IFEND} {$IF CompilerVersion < 23} // Fix TRttiIntfMethod.DispatchInvoke Meth := ctx.GetType(TypeInfo(IIntfMethodHelper)).GetMethod('IntfMethod'); RedirectFunction(GetVirtualMethod(Meth.ClassType, 13), @TRttiMethodFix.IntfDispatchInvoke); // Fix TRttiInstanceMethodEx.DispatchInvoke Meth := ctx.GetType(TInstanceMethodHelper).GetMethod('InstanceMethod'); RedirectFunction(GetVirtualMethod(Meth.ClassType, 13), @TRttiMethodFix.InstanceDispatchInvoke); {$IFEND} {$IF Defined(CPUX64)} // Fix PassByRef P := FindMethodBytes(GetActualAddr(@Rtti.IsManaged), PassByRefBytes, 1000); if P <> nil then RedirectFunction(P, @PassByRef) else raise Exception.Create('Patching PassByRef failed. Do you have set a breakpoint in the method?'); {$IFEND} {$IF CompilerVersion <= 22} // Fix GetInlineSize P := FindMethodBytes(GetActualAddr(@Rtti.IsManaged), GetInlineSizeBytes, 1000); if P <> nil then RedirectFunction(P, @GetInlineSize) else raise Exception.Create('Patching GetInlineSize failed. Do you have set a breakpoint in the method?'); {$IFEND} {$IF CompilerVersion = 21} // Fix TRttiPackage.MakeTypeLookupTable RedirectFunction(TRttiPackage.GetMakeTypeLookupTableAddress, @TRttiPackage.MakeTypeLookupTableFix); {$IFEND} {$IF CompilerVersion < 23} // Fix TValue.TryAsOrdinal RedirectFunction(@TValue.TryAsOrdinal, @TValue.TryAsOrdinalFix); {$IFEND} {$IF CompilerVersion = 22} // Fix TRttiMethod.GetInvokeInfo // Find the private TRttiMethod.GetInvokeInfo method P := GetActualAddr(@TRttiMethod.CreateImplementation); if CompareMem(P, @TRttiMethod_CreateImplementationBytesCmp[0], SizeOf(TRttiMethod_CreateImplementationBytesCmp)) then begin P := PByte(P + 11 + 5) + PInteger(@P[11 + 1])^; // relative call => absolute address P := FindMethodBytes(P, TRttiMethod_GetInvokeInfoBytes, 400); if P <> nil then begin @OrgInvokeInfoAddParameter := PByte(P + 21 + 5) + PInteger(@P[21 + 1])^; // relative call => absolute address Offset := PByte(@FixInvokeInfoAddParameterEnter) - (P + 21 + 5); if not WriteProcessMemory(GetCurrentProcess, P + 21 + 1, @Offset, SizeOf(Offset), n) then RaiseLastOSError; end else raise Exception.Create('Patching TRttiMethod.GetInvokeInfoBytes failed. Do you have set a breakpoint in the method?'); end else raise Exception.Create('TRttiMethod.CreateImplementation does not match the search pattern. Do you have set a breakpoint in the method?'); {$IFEND} end; initialization if not IsPatched and (ExtractFileName(ParamStr(0)) <> 'bds.exe') then try PatchRtti; IsPatched := True; except on e: Exception do if not (e is EAbort) and IsDebuggerPresent then MessageBox(0, PChar(e.ClassName + ': ' + e.Message), PChar(ExtractFileName(ParamStr(0))), MB_OK or MB_ICONERROR); end; {$IFEND} end.
{******************************************************************************} { } { WiRL: RESTful Library for Delphi } { } { Copyright (c) 2015-2019 WiRL Team } { } { https://github.com/delphi-blocks/WiRL } { } {******************************************************************************} unit WiRL.http.Core; interface {$SCOPEDENUMS ON} uses System.SysUtils, System.Classes; type TWiRLHttpMethod = (GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE, CONNECT); TWiRLHttpMethodHelper = record helper for TWiRLHttpMethod public class function ConvertFromString(const AMethod: string): TWiRLHttpMethod; static; public function ToString: string; procedure FromString(const AMethod: string); end; TWiRLHttpStatus = class public const // 1xx Informational CONTINUE_REQUEST = 100; SWITCHING_PROTOCOLS = 101; PROCESSING = 102; CHECKPOINT = 103; // 2xx Success OK = 200; CREATED = 201; ACCEPTED = 202; NON_AUTHORITATIVE_INFORMATION = 203; NO_CONTENT = 204; RESET_CONTENT = 205; PARTIAL_CONTENT = 206; MULTI_STATUS = 207; ALREADY_REPORTED = 208; IM_USED = 226; // 3xx Redirection MULTIPLE_CHOICES = 300; MOVED_PERMANENTLY = 301; MOVED_TEMPORARILY = 302; // Deprecated FOUND = 302; SEE_OTHER = 303; NOT_MODIFIED = 304; USE_PROXY = 305; TEMPORARY_REDIRECT = 307; PERMANENT_REDIRECT = 308; // --- 4xx Client Error --- BAD_REQUEST = 400; UNAUTHORIZED = 401; PAYMENT_REQUIRED = 402; FORBIDDEN = 403; NOT_FOUND = 404; METHOD_NOT_ALLOWED = 405; NOT_ACCEPTABLE = 406; PROXY_AUTHENTICATION_REQUIRED = 407; REQUEST_TIMEOUT = 408; CONFLICT = 409; GONE = 410; LENGTH_REQUIRED = 411; PRECONDITION_FAILED = 412; PAYLOAD_TOO_LARGE = 413; REQUEST_ENTITY_TOO_LARGE = 413; URI_TOO_LONG = 414; REQUEST_URI_TOO_LONG = 414; UNSUPPORTED_MEDIA_TYPE = 415; REQUESTED_RANGE_NOT_SATISFIABLE = 416; EXPECTATION_FAILED = 417; I_AM_A_TEAPOT = 418; INSUFFICIENT_SPACE_ON_RESOURCE = 419; METHOD_FAILURE = 420; DESTINATION_LOCKED = 421; UNPROCESSABLE_ENTITY = 422; LOCKED = 423; FAILED_DEPENDENCY = 424; UPGRADE_REQUIRED = 426; PRECONDITION_REQUIRED = 428; TOO_MANY_REQUESTS = 429; REQUEST_HEADER_FIELDS_TOO_LARGE = 431; UNAVAILABLE_FOR_LEGAL_REASONS = 451; // --- 5xx Server Error --- INTERNAL_SERVER_ERROR = 500; NOT_IMPLEMENTED = 501; BAD_GATEWAY = 502; SERVICE_UNAVAILABLE = 503; GATEWAY_TIMEOUT = 504; HTTP_VERSION_NOT_SUPPORTED = 505; VARIANT_ALSO_NEGOTIATES = 506; INSUFFICIENT_STORAGE = 507; LOOP_DETECTED = 508; BANDWIDTH_LIMIT_EXCEEDED = 509; NOT_EXTENDED = 510; NETWORK_AUTHENTICATION_REQUIRED = 511; private FCode: Integer; FLocation: string; FReason: string; public constructor Create; overload; constructor Create(ACode: Integer); overload; constructor Create(ACode: Integer; const AReason: string); overload; constructor Create(ACode: Integer; const AReason, ALocation: string); overload; property Code: Integer read FCode write FCode; property Reason: string read FReason write FReason; property Location: string read FLocation write FLocation; end; TWiRLHeaderList = class(TStringList) private function GetName(AIndex: Integer): string; function GetValue(const AName: string): string; procedure SetValue(const AName, AValue: string); function GetValueFromLine(AIndex: Integer): string; public constructor Create; function IndexOfName(const AName: string): Integer; reintroduce; property Names[Index: Integer]: string read GetName; property Values[const Name: string]: string read GetValue write SetValue; default; property ValueFromIndex[Index: Integer]: string read GetValueFromLine; end; TWiRLParam = class(TStringList) private function GetValue(const Name: string): string; procedure SetValue(const Name, Value: string); public property Values[const Name: string]: string read GetValue write SetValue; default; end; TWiRLStreamWrapper = class(TStream) private FOwnsStream: Boolean; FStream: TStream; protected function GetSize: Int64; override; procedure SetSize(const NewSize: Int64); overload; override; public function Read(var Buffer; Count: Longint): Longint; overload; override; function Write(const Buffer; Count: Longint): Longint; overload; override; function Seek(Offset: Longint; Origin: Word): Longint; overload; override; constructor Create(AStream: TStream; AOwnsStream: Boolean = False); destructor Destroy; override; property Stream: TStream read FStream; end; var GetDefaultCharSetEncoding: TEncoding = nil; function EncodingFromCharSet(const ACharset: string): TEncoding; function ContentStreamToString(const ACharset: string; AContentStream: TStream): string; implementation uses System.TypInfo; function DefaultCharSetEncoding: TEncoding; begin Result := nil; if Assigned(GetDefaultCharSetEncoding) then Result := GetDefaultCharSetEncoding; if Result = nil then Result := TEncoding.UTF8; end; function ContentStreamToString(const ACharset: string; AContentStream: TStream): string; var LEncoding: TEncoding; LBuffer: TBytes; LPos :Int64; begin Result := ''; if Assigned(AContentStream) and (AContentStream.Size > 0) then begin LPos := AContentStream.Position; try LEncoding := EncodingFromCharSet(ACharset); AContentStream.Position := 0; SetLength(LBuffer, AContentStream.Size); AContentStream.Read(LBuffer[0], AContentStream.Size); Result := LEncoding.GetString(LBuffer); finally AContentStream.Position := LPos; end; end; end; function EncodingFromCharSet(const ACharset: string): TEncoding; begin if CompareText('utf-8', ACharset) = 0 then Result := TEncoding.UTF8 else if CompareText('ISO-8859-1', ACharset) = 0 then Result := TEncoding.ANSI else if CompareText('ANSI', ACharset) = 0 then Result := TEncoding.ANSI else if CompareText('ASCII', ACharset) = 0 then Result := TEncoding.ASCII else Result := DefaultCharSetEncoding; end; { TWiRLHeaderList } const HeaderNameValueSeparator = ': '; constructor TWiRLHeaderList.Create; begin inherited Create; NameValueSeparator := ':'; end; function TWiRLHeaderList.GetName(AIndex: Integer): string; var LLine: string; LTrimmedSeparator: string; LSepIndex: Integer; begin if (AIndex >= 0) and (AIndex < Count) then begin LLine := Get(AIndex); LTrimmedSeparator := Trim(HeaderNameValueSeparator); // Sometimes the space is not present LSepIndex := LLine.IndexOf(LTrimmedSeparator); Result := LLine.Substring(0, LSepIndex).Trim; end else begin Result := ''; end; end; function TWiRLHeaderList.GetValueFromLine(AIndex: Integer): string; var LLine: string; LTrimmedSeparator: string; LSepIndex: Integer; begin if (AIndex >= 0) and (AIndex < Count) then begin LLine := Get(AIndex); LTrimmedSeparator := Trim(HeaderNameValueSeparator); // Sometimes the space is not present LSepIndex := LLine.IndexOf(LTrimmedSeparator); Result := LLine.Substring(LSepIndex + 1).Trim; end else begin Result := ''; end; end; function TWiRLHeaderList.GetValue(const AName: string): string; var LIndex: Integer; begin LIndex := IndexOfName(AName); Result := GetValueFromLine(LIndex); end; function TWiRLHeaderList.IndexOfName(const AName: string): Integer; var LIndex: Integer; begin Result := -1; for LIndex := 0 to Count - 1 do begin if CompareText(GetName(LIndex), AName) = 0 then begin Exit(LIndex); end; end; end; procedure TWiRLHeaderList.SetValue(const AName, AValue: string); var LIndex: Integer; begin LIndex := IndexOfName(AName); if AValue <> '' then begin if LIndex < 0 then LIndex := Add(''); Put(LIndex, AName + HeaderNameValueSeparator + AValue); end else if LIndex >= 0 then Delete(LIndex); end; { TWiRLParam } function TWiRLParam.GetValue(const Name: string): string; begin Result := inherited Values[Name]; end; procedure TWiRLParam.SetValue(const Name, Value: string); begin inherited Values[Name] := Value; end; { TWiRLHttpMethodHelper } procedure TWiRLHttpMethodHelper.FromString(const AMethod: string); begin Self := ConvertFromString(AMethod); end; class function TWiRLHttpMethodHelper.ConvertFromString(const AMethod: string): TWiRLHttpMethod; var LRes: Integer; begin LRes := GetEnumValue(TypeInfo(TWiRLHttpMethod), AMethod); if LRes >= 0 then Result := TWiRLHttpMethod(LRes) else raise Exception.Create('Error converting string type'); end; function TWiRLHttpMethodHelper.ToString: string; begin case Self of TWiRLHttpMethod.GET: Result := 'GET'; TWiRLHttpMethod.HEAD: Result := 'HEAD'; TWiRLHttpMethod.POST: Result := 'POST'; TWiRLHttpMethod.PUT: Result := 'PUT'; TWiRLHttpMethod.PATCH: Result := 'PATCH'; TWiRLHttpMethod.DELETE: Result := 'DELETE'; TWiRLHttpMethod.OPTIONS: Result := 'OPTIONS'; TWiRLHttpMethod.TRACE: Result := 'TRACE'; TWiRLHttpMethod.CONNECT: Result := 'CONNECT'; end; end; { TWiRLHttpStatus } constructor TWiRLHttpStatus.Create(ACode: Integer); begin Create(ACode, '', ''); end; constructor TWiRLHttpStatus.Create(ACode: Integer; const AReason: string); begin Create(ACode, AReason, ''); end; constructor TWiRLHttpStatus.Create(ACode: Integer; const AReason, ALocation: string); begin FCode := ACode; FReason := AReason; FLocation := ALocation; end; constructor TWiRLHttpStatus.Create; begin Create(200, '', ''); end; { TWiRLStreamWrapper } constructor TWiRLStreamWrapper.Create(AStream: TStream; AOwnsStream: Boolean); begin inherited Create; FStream := AStream; FOwnsStream := AOwnsStream; end; destructor TWiRLStreamWrapper.Destroy; begin if FOwnsStream then FStream.Free; inherited; end; function TWiRLStreamWrapper.GetSize: Int64; begin Result := FStream.Size; end; function TWiRLStreamWrapper.Read(var Buffer; Count: Longint): Longint; begin Result := FStream.Read(Buffer, Count); end; function TWiRLStreamWrapper.Seek(Offset: Longint; Origin: Word): Longint; begin Result := FStream.Seek(Offset, Origin); end; procedure TWiRLStreamWrapper.SetSize(const NewSize: Int64); begin FStream.Size := NewSize; end; function TWiRLStreamWrapper.Write(const Buffer; Count: Longint): Longint; begin Result := FStream.Write(Buffer, Count); end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, unit2; type { TForm1 } TForm1 = class(TForm) Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; Memo1: TMemo; Memo2: TMemo; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); private public end; var Form1: TForm1; // Делаем матрицу и её размерность глобальными переменными // чтобы они были видны во всех функциях - // обработчиков нажатия кнопок a: Ar; n : integer; b: Ar; // Вспомогательная матрица - эталонная(исходная) implementation {$R *.lfm} { TForm1 } // удобно будет создать процедуру вывода матрицы в объект типа TMemo // 'var output:TMemo' так как мы будем изменять объект Memo - записывать в него // Хотя это не обязательно, работает и без, тупо для приличия делаем так procedure printAr(a: Ar; n: integer; var output: TMemo); var // строковое представление одного числа s_x: string; // вспомогательная строка, чтобы добавить элементы матрицы // то есть это сумма строковых представлений каждого элемента(s_x) матрциы s: string; // переменные для циклов обхода матрицы i,j: integer; begin // перед записью чего-то в Memo очищаем его // В Memo могла остаться старая матрица output.Clear; // сначала мы будем собирать строку из элементов матрицы, // лежащих на i-ой строчке // Потом добавляем эту строку в Memo через Append for i:=1 to n do begin // присваиваем пустую строку про обработке каждой строки матрицы // То есть обработали одну строку, очистили переменную, обработать другую // иначе элементы с другой (предыдущей) строки будут выводиться и в новой строке s := ''; for j:=1 to n do begin // преобразуем елемент матрицы в строку // число 5 - так же как и в writeln - ширина поля под число // чтобы не замарачиваться с пробелами при выводе str(a[i,j]:5, s_x); // по одному элементы i-ой строки собираем в одну строку s := s + s_x; end; // собрали одну строку, теперь добавляем её в Memo output.Append(s); end; end; {Нажали 'Новая матрица'} procedure TForm1.Button1Click(Sender: TObject); begin // Получаем размерность матрицы от пользователя // InputBox возвращает строку, но ГЛОБАЛЬНАЯ переменная 'n' типа integer // поэтому преобразуем возвращаем значение в целое число при помощи StrToInt n := StrToInt(InputBox('Размерность матрицы', 'Введите целое число', '5')); // Теперь так как УЖЕ ЕСТЬ число строк и столбцов // Заполняем ЭТАЛОННУЮ матрицу NewAr(b, n); // выводим матрицу в Memo1 - исходная матрица PrintAr(b, n, Memo1); end; {Нажали 'ПО ЧС'} procedure TForm1.Button2Click(Sender: TObject); var i, k: integer; begin // копируем матрицу из ЭТАЛОНА a := b; // получаем сколько поворотов нужно сделать k := StrToInt(InputBox('Количество Поворотов', 'Введите целое число', '1')); // K раз вращаем по очасовой for i:=1 to k do ByHourHand(a, n); // выводим изменённую матрицу в Memo2 printAr(a,n, Memo2); end; {Нажали 'ПРОТИВ ЧС'} procedure TForm1.Button3Click(Sender: TObject); var i, k: integer; begin // копируем матрицу из ЭТАЛОНА a := b; // получаем сколько поворотов нужно сделать k := StrToInt(InputBox('Количество Поворотов', 'Введите целое число', '1')); // K раз вращаем против очасовой for i:=1 to k do AginHourHand(a, n); // выводим изменённую матрицу в Memo2 printAr(a,n, Memo2); end; {Нажали 'Закрыть'} procedure TForm1.Button4Click(Sender: TObject); begin close; end; end.
{******************************************************************************* * * * TksControlBadge - iOS style badge used by other controls * * * * https://github.com/gmurt/KernowSoftwareFMX * * * * Copyright 2015 Graham Murt * * * * email: graham@kernow-software.co.uk * * * * 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 ksControlBadge; interface {$I ksComponents.inc} uses FMX.Controls, Classes, FMX.StdCtrls, FMX.Objects, FMX.Effects, ksTypes; type TksControlBadge = class; TksBadgeProperties = class(TPersistent) private FOwner: TksControlBadge; FValue: Integer; FShadow: Boolean; procedure Changed; procedure SetValue(const Value: integer); procedure SetShadow(const Value: Boolean); public constructor Create(AOwner: TksControlBadge); virtual; procedure Assign(Source: TPersistent); override; published property Value: integer read FValue write SetValue default 0; property Shadow: Boolean read FShadow write SetShadow default True; end; TksControlBadge = class(TksRoundRect) private FLabel: TLabel; FProperties: TksBadgeProperties; FShadowEffect: TShadowEffect; procedure DoChanged; procedure SetProperties(const Value: TksBadgeProperties); protected procedure Resize; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; published property Properties: TksBadgeProperties read FProperties write SetProperties; end; implementation uses FMX.Types, System.UIConsts, FMX.Graphics, SysUtils, Math; { TksBadgeProperties } procedure TksBadgeProperties.Assign(Source: TPersistent); begin inherited; FValue := (Source as TksBadgeProperties).Value; FShadow := (Source as TksBadgeProperties).Shadow; end; procedure TksBadgeProperties.Changed; begin FOwner.DoChanged; end; constructor TksBadgeProperties.Create(AOwner: TksControlBadge); begin inherited Create; FOwner := AOwner; FValue := 0; FShadow := True; end; procedure TksBadgeProperties.SetShadow(const Value: Boolean); begin FShadow := Value; Changed; end; procedure TksBadgeProperties.SetValue(const Value: integer); begin FValue := Value; Changed; end; { TksControlBadge } constructor TksControlBadge.Create(AOwner: TComponent); begin inherited Create(AOwner); FProperties := TksBadgeProperties.Create(Self); FLabel := TLabel.Create(Self); FShadowEffect := TShadowEffect.Create(Self); HitTest := False; Locked := True; FLabel.TextSettings.Font.Size := 10; FLabel.TextSettings.FontColor := claWhite; FLabel.StyledSettings := []; FLabel.VertTextAlign := TTextAlign.Center; FLabel.TextAlign := TTextAlign.Center; Stroke.Kind := TBrushKind.None; Fill.Color := claRed; Height := 16; Stored := False; Width := 16; Position.Y := -8; Visible := False; FShadowEffect.Distance := 0.8; FShadowEffect.Softness := 0.08; AddObject(FLabel); AddObject(FShadowEffect); FLabel.Locked := True; FLabel.HitTest := False; end; destructor TksControlBadge.Destroy; begin FreeAndNil(FProperties); {$IFDEF NEXTGEN} FLabel.DisposeOf; FShadowEffect.DisposeOf; {$ELSE} FLabel.Free; FShadowEffect.Free; {$ENDIF} inherited; end; procedure TksControlBadge.Assign(Source: TPersistent); begin inherited; end; procedure TksControlBadge.DoChanged; begin Visible := FProperties.Value > 0; Resize; FLabel.Text := IntToStr(FProperties.Value); FShadowEffect.Enabled := FProperties.Shadow; (Owner as TControl).RecalcSize; end; procedure TksControlBadge.Resize; begin inherited; if Canvas <> nil then Width := Max(16,(Canvas.TextWidth(IntToStr(FProperties.Value)))+4); FLabel.Position.X := 0; FLabel.Position.Y := 0; FLabel.Size.Width := Width; FLabel.Size.Height := Height-1; Repaint; end; procedure TksControlBadge.SetProperties(const Value: TksBadgeProperties); begin FProperties.Assign(Value); end; initialization Classes.RegisterClass(TksBadgeProperties); Classes.RegisterClass(TksControlBadge); end.
unit Unit1; interface {$WARN UNIT_PLATFORM OFF} uses Windows, SysUtils, dialogs, Forms, StdCtrls, ComCtrls, Controls, Classes, Alcinoe.StringList, Alcinoe.HTTP.Client, Alcinoe.HTTP.Client.WinHTTP, Alcinoe.WebSpider, Alcinoe.AVLBinaryTree, ExtCtrls, Shellapi; type {-------------------} TForm1 = class(TForm) StatusBar1: TStatusBar; Label1: TLabel; editURL2Crawl: TEdit; ButtonStart: TButton; EditSaveDirectory: TEdit; Label2: TLabel; EditMaxDeepLevel: TEdit; UpDownMaxDeepLevel: TUpDown; Label3: TLabel; CheckBoxDownloadImage: TCheckBox; CheckBoxUpdateHref: TCheckBox; CheckBoxStayInStartSite: TCheckBox; StatusBar2: TStatusBar; BtnChooseSaveDirectory: TButton; MemoErrorMsg: TMemo; ButtonStop: TButton; EditIncludeLink: TEdit; Label4: TLabel; EditExcludeLink: TEdit; Label6: TLabel; procedure ButtonStartClick(Sender: TObject); procedure BtnChooseSaveDirectoryClick(Sender: TObject); procedure MainWebSpiderCrawlDownloadError(Sender: TObject; const URL, ErrorMessage: {$IFDEF UNICODE}AnsiString{$ELSE}String{$ENDIF}; HTTPResponseHeader: TALHTTPResponseHeader; var StopCrawling: Boolean); procedure MainWebSpiderCrawlDownloadRedirect(Sender: TObject; const Url, RedirectedTo: {$IFDEF UNICODE}AnsiString{$ELSE}String{$ENDIF}; HTTPResponseHeader: TALHTTPResponseHeader; var StopCrawling: Boolean); procedure MainWebSpiderCrawlDownloadSuccess(Sender: TObject; const Url: {$IFDEF UNICODE}AnsiString{$ELSE}String{$ENDIF}; HTTPResponseHeader: TALHTTPResponseHeader; HttpResponseContent: TStream; var StopCrawling: Boolean); procedure MainWebSpiderCrawlFindLink(Sender: TObject; const HtmlTagString: {$IFDEF UNICODE}AnsiString{$ELSE}String{$ENDIF}; HtmlTagParams: TALStringsA; const URL: {$IFDEF UNICODE}AnsiString{$ELSE}String{$ENDIF}); procedure MainWebSpiderCrawlGetNextLink(Sender: TObject; var Url: {$IFDEF UNICODE}AnsiString{$ELSE}String{$ENDIF}); procedure MainWebSpiderUpdateLinkToLocalPathFindLink(Sender: TObject; const HtmlTagString: {$IFDEF UNICODE}AnsiString{$ELSE}String{$ENDIF}; HtmlTagParams: TALStringsA; const URL: {$IFDEF UNICODE}AnsiString{$ELSE}String{$ENDIF}; var LocalPath: {$IFDEF UNICODE}AnsiString{$ELSE}String{$ENDIF}); procedure MainWebSpiderUpdateLinkToLocalPathGetNextFile(Sender: TObject; var FileName, BaseHref: {$IFDEF UNICODE}AnsiString{$ELSE}String{$ENDIF}); procedure ButtonStopClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); private FPageDownloadedBinTree: TAlStringKeyAVLBinaryTree; FPageNotYetDownloadedBinTree: TAlStringKeyAVLBinaryTree; FCurrentDeepLevel: Integer; FCurrentLocalFileNameIndex: integer; fMainWebSpider: TAlWebSpider; fMainHttpClient: TALWinHttpClient; function GetNextLocalFileName(const aContentType: AnsiString): AnsiString; public end; {---------------------------------------------------------------} TPageDownloadedBinTreeNode = Class(TALStringKeyAVLBinaryTreeNode) Private Protected Public Data: AnsiString; end; {---------------------------------------------------------------------} TPageNotYetDownloadedBinTreeNode = Class(TALStringKeyAVLBinaryTreeNode) Private Protected Public DeepLevel: Integer; end; var Form1: TForm1; implementation {$R *.dfm} uses System.AnsiStrings, FileCtrl, Masks, UrlMon, Alcinoe.Files, Alcinoe.Mime, Alcinoe.StringUtils; Const SplitDirectoryAmount = 5000; {*************************************************} procedure TForm1.ButtonStartClick(Sender: TObject); {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} Procedure InternalEnableControl; Begin ButtonStop.Enabled := False; buttonStart.Enabled := True; editURL2Crawl.Enabled := True; EditIncludeLink.Enabled := True; EditExcludeLink.Enabled := True; EditSaveDirectory.Enabled := True; EditMaxDeepLevel.Enabled := True; UpDownMaxDeepLevel.Enabled := True; CheckBoxDownloadImage.Enabled := True; CheckBoxUpdateHref.Enabled := True; CheckBoxStayInStartSite.Enabled := True; BtnChooseSaveDirectory.Enabled := True; end; {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} Procedure InternalDisableControl; Begin ButtonStop.Enabled := True; buttonStart.Enabled := False; editURL2Crawl.Enabled := False; EditIncludeLink.Enabled := False; EditExcludeLink.Enabled := False; EditSaveDirectory.Enabled := False; EditMaxDeepLevel.Enabled := False; UpDownMaxDeepLevel.Enabled := False; CheckBoxDownloadImage.Enabled := False; CheckBoxUpdateHref.Enabled := False; CheckBoxStayInStartSite.Enabled := False; BtnChooseSaveDirectory.Enabled := False; end; Var aNode: TPageNotYetDownloadedBinTreeNode; Begin {check the save directory} If ALTrim(AnsiString(EditSaveDirectory.Text)) = '' then raise Exception.Create('Please select a directory to save the downloaded files!'); {Handle if we ask to start or stop} InternalDisableControl; Try {clear the label control} StatusBar1.Panels[0].Text := ''; StatusBar1.Panels[1].Text := ''; StatusBar2.Panels[0].Text := ''; MemoErrorMsg.Lines.Clear; {init private var} FCurrentDeepLevel := 0; FCurrentLocalFileNameIndex := 0; FPageDownloadedBinTree:= TAlStringKeyAVLBinaryTree.Create; FPageNotYetDownloadedBinTree:= TAlStringKeyAVLBinaryTree.Create; Try {add editURL2Crawl.text to the fPageNotYetDownloadedBinTree} aNode:= TPageNotYetDownloadedBinTreeNode.Create; aNode.ID := ALTrim(AnsiString(editURL2Crawl.text)); aNode.DeepLevel := 0; FPageNotYetDownloadedBinTree.AddNode(aNode); {start the crawl} fMainWebSpider.Crawl; {exit if the user click on the stop button} If not ButtonStop.Enabled then exit; {update the link on downloaded page to local path} if CheckBoxUpdateHref.Checked then fMainWebSpider.UpdateLinkToLocalPath; finally FPageDownloadedBinTree.Free; FPageNotYetDownloadedBinTree.Free; end; finally InternalEnableControl; StatusBar2.Panels[0].Text := ''; end; end; {************************************************} procedure TForm1.ButtonStopClick(Sender: TObject); begin ButtonStop.Enabled := False; end; {************************************************************} procedure TForm1.BtnChooseSaveDirectoryClick(Sender: TObject); Var aDir: String; Begin aDir := ''; if SelectDirectory(aDir, [sdAllowCreate, sdPerformCreate, sdPrompt],0) then EditSaveDirectory.Text := IncludeTrailingPathDelimiter(aDir); end; {*******************************************************************************} function TForm1.GetNextLocalFileName(const aContentType: AnsiString): AnsiString; Var aExt: AnsiString; {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} Function SplitPathMakeFilename: AnsiString; begin Result := AnsiString(EditSaveDirectory.Text) + ALIntToStrA((FCurrentLocalFileNameIndex div SplitDirectoryAmount) * SplitDirectoryAmount + SplitDirectoryAmount) + '\'; If (not SysUtils.DirectoryExists(String(Result))) and (not createDir(String(Result))) then raise exception.Create('cannot create dir: ' + String(Result)); Result := Result + ALIntToStrA(FCurrentLocalFileNameIndex) + aExt; inc(FCurrentLocalFileNameIndex); end; Begin aExt := ALlowercase(ALGetDefaultFileExtFromMimeContentType(aContentType)); // '.htm' If FCurrentLocalFileNameIndex = 0 then Begin result := AnsiString(EditSaveDirectory.Text) + 'Start' + aExt; inc(FCurrentLocalFileNameIndex); end else result := SplitPathMakeFilename; end; {***********************************************} procedure TForm1.MainWebSpiderCrawlDownloadError( Sender: TObject; const URL, ErrorMessage: AnsiString; HTTPResponseHeader: TALHTTPResponseHeader; var StopCrawling: Boolean); Var aNode: TPageDownloadedBinTreeNode; begin {add the url to downloaded list} aNode:= TPageDownloadedBinTreeNode.Create; aNode.ID := Url; aNode.data := '!'; If not FPageDownloadedBinTree.AddNode(aNode) then aNode.Free; {delete the url from the not yet downloaded list} FPageNotYetDownloadedBinTree.DeleteNode(url); {update label} MemoErrorMsg.Lines.Add('Error: ' + String(ErrorMessage)); StatusBar1.Panels[0].Text := 'Url Downloaded: ' + IntToStr((FPageDownloadedBinTree.nodeCount)); StatusBar1.Panels[1].Text := 'Url to Download: ' + IntToStr((FPageNotYetDownloadedBinTree.nodeCount)); application.ProcessMessages; StopCrawling := not ButtonStop.Enabled; end; {**************************************************} procedure TForm1.MainWebSpiderCrawlDownloadRedirect( Sender: TObject; const Url, RedirectedTo: AnsiString; HTTPResponseHeader: TALHTTPResponseHeader; var StopCrawling: Boolean); Var aNode: TALStringKeyAVLBinaryTreeNode; RedirectedToWithoutAnchor: ansiString; begin {add the url to downloaded list} aNode:= TPageDownloadedBinTreeNode.Create; aNode.ID := Url; TPageDownloadedBinTreeNode(aNode).data := '=>'+RedirectedTo; If not FPageDownloadedBinTree.AddNode(aNode) then aNode.Free; {delete the url from the not yet downloaded list} FPageNotYetDownloadedBinTree.DeleteNode(url); {Stay in start site} If not CheckBoxStayInStartSite.Checked or (ALlowercase(AlExtractHostNameFromUrl(ALTrim(AnsiString(editURL2Crawl.Text)))) = ALlowercase(AlExtractHostNameFromUrl(RedirectedTo))) then begin {remove the anchor} RedirectedToWithoutAnchor := AlRemoveAnchorFromUrl(RedirectedTo); {add the redirectTo url to the not yet downloaded list} If FPageDownloadedBinTree.FindNode(RedirectedToWithoutAnchor) = nil then begin aNode:= TPageNotYetDownloadedBinTreeNode.Create; aNode.ID := RedirectedToWithoutAnchor; TPageNotYetDownloadedBinTreeNode(aNode).DeepLevel := FCurrentDeepLevel; If not FPageNotYetDownloadedBinTree.AddNode(aNode) then aNode.Free; end; end; {update label} StatusBar1.Panels[0].Text := 'Url Downloaded: ' + IntToStr((FPageDownloadedBinTree.nodeCount)); StatusBar1.Panels[1].Text := 'Url to Download: ' + IntToStr((FPageNotYetDownloadedBinTree.nodeCount)); application.ProcessMessages; StopCrawling := not ButtonStop.Enabled; end; {*************************************************} procedure TForm1.MainWebSpiderCrawlDownloadSuccess( Sender: TObject; const Url: AnsiString; HTTPResponseHeader: TALHTTPResponseHeader; HttpResponseContent: TStream; var StopCrawling: Boolean); Var aNode: TPageDownloadedBinTreeNode; Str: AnsiString; AFileName: AnsiString; pMimeTypeFromData: LPWSTR; begin {put the content in str} HttpResponseContent.Position := 0; SetLength(Str, HttpResponseContent.size); HttpResponseContent.ReadBuffer(Str[1],HttpResponseContent.Size); {we add a check here to be sure that the file is an http file (text file} {Some server send image with text/htm content type} IF (FindMimeFromData( nil, // bind context - can be nil nil, // url - can be nil PAnsiChar(str), // buffer with data to sniff - can be nil (pwzUrl must be valid) length(str), // size of buffer PWidechar(WideString(HTTPResponseHeader.ContentType)), // proposed mime if - can be nil 0, // will be defined pMimeTypeFromData, // the suggested mime 0 // must be 0 ) <> NOERROR) then pMimeTypeFromData := PWidechar(WideString(HTTPResponseHeader.ContentType)); {Get the FileName where to save the responseContent} aFileName := GetNextLocalFileName(AnsiString(pMimeTypeFromData)); {If html then add <!-- saved from '+ URL +' -->' at the top of the file} If ALSameTextA(AnsiString(pMimeTypeFromData),'text/html') then begin Str := '<!-- saved from '+ URL+' -->' +#13#10 + Str; AlSaveStringToFile(str,aFileName); end {Else Save the file without any change} else TmemoryStream(HttpResponseContent).SaveToFile(String(aFileName)); {delete the Url from the PageNotYetDownloadedBinTree} FPageNotYetDownloadedBinTree.DeleteNode(Url); {add the url to the PageDownloadedBinTree} aNode:= TPageDownloadedBinTreeNode.Create; aNode.ID := Url; aNode.data := AlCopyStr(AFileName,length(EditSaveDirectory.Text) + 1,maxint); If not FPageDownloadedBinTree.AddNode(aNode) then aNode.Free; {update label} StatusBar1.Panels[0].Text := 'Url Downloaded: ' + IntToStr((FPageDownloadedBinTree.nodeCount)); StatusBar1.Panels[1].Text := 'Url to Download: ' + IntToStr((FPageNotYetDownloadedBinTree.nodeCount)); application.ProcessMessages; StopCrawling := not ButtonStop.Enabled; end; {******************************************} procedure TForm1.MainWebSpiderCrawlFindLink( Sender: TObject; const HtmlTagString: AnsiString; HtmlTagParams: TALStringsA; const URL: AnsiString); Var aNode: TPageNotYetDownloadedBinTreeNode; aURLWithoutAnchor: AnsiString; Lst: TALStringListA; I: integer; Flag1 : Boolean; S1: AnsiString; begin {If Check BoxDownload Image} IF not CheckBoxDownloadImage.Checked and ( ALSameTextA(HtmlTagString,'img') or ( ALSameTextA(HtmlTagString,'input') and ALSameTextA(ALTrim(HtmlTagParams.Values['type']),'image') ) ) then Exit; {Stay in start site} If CheckBoxStayInStartSite.Checked and (ALlowercase(AlExtractHostNameFromUrl(ALTrim(AnsiString(editURL2Crawl.Text)))) <> ALlowercase(AlExtractHostNameFromUrl(Url))) then exit; {DeepLevel} If (UpDownMaxDeepLevel.Position >= 0) and (FCurrentDeepLevel + 1 > UpDownMaxDeepLevel.Position) then exit; {include link(s)} If EditIncludeLink.Text <> '' then begin Lst := TALStringListA.Create; Try Lst.Text := ALTrim(ALStringReplaceA(AnsiString(EditIncludeLink.Text),';',#13#10,[RfReplaceall])); Flag1 := True; For i := 0 to Lst.Count - 1 do begin S1 := ALTrim(Lst[i]); If S1 <> '' then begin Flag1 := ALMatchesMaskA(URL, S1); If Flag1 then Break; end; end; If not flag1 then Exit; Finally Lst.Free; end; end; {Exclude link(s)} If EditExcludeLink.Text <> '' then begin Lst := TALStringListA.Create; Try Lst.Text := ALTrim(ALStringReplaceA(AnsiString(EditExcludeLink.Text),';',#13#10,[RfReplaceall])); Flag1 := False; For i := 0 to Lst.Count - 1 do begin S1 := ALTrim(Lst[i]); If S1 <> '' then begin Flag1 := ALMatchesMaskA(URL, S1); If Flag1 then Break; end; end; If flag1 then Exit; Finally Lst.Free; end; end; {remove the anchor} aURLWithoutAnchor := AlRemoveAnchorFromUrl(URL); {If the link not already downloaded then add it to the FPageNotYetDownloadedBinTree} If FPageDownloadedBinTree.FindNode(aURLWithoutAnchor) = nil then begin aNode:= TPageNotYetDownloadedBinTreeNode.Create; aNode.ID := aURLWithoutAnchor; aNode.DeepLevel := FCurrentDeepLevel + 1; If not FPageNotYetDownloadedBinTree.AddNode(aNode) then aNode.Free else begin StatusBar1.Panels[1].Text := 'Url to Download: ' + IntToStr((FPageNotYetDownloadedBinTree.nodeCount)); application.ProcessMessages; end; end; end; {*********************************************} procedure TForm1.MainWebSpiderCrawlGetNextLink( Sender: TObject; var Url: AnsiString); {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} function InternalfindNextUrlToDownload( aNode: TPageNotYetDownloadedBinTreeNode; alowDeepLevel: Integer): TPageNotYetDownloadedBinTreeNode; Var aTmpNode1, aTmpNode2: TPageNotYetDownloadedBinTreeNode; Begin If (not assigned(Anode)) or (aNode.DeepLevel <= alowDeepLevel) then result := aNode else begin if aNode.ChildNodes[true] <> nil then begin aTmpNode1 := InternalfindNextUrlToDownload(TPageNotYetDownloadedBinTreeNode(aNode.ChildNodes[true]), alowDeepLevel); If (assigned(aTmpNode1)) and (aTmpNode1.DeepLevel <= alowDeepLevel) then begin result := aTmpNode1; exit; end; end else aTmpNode1 := nil; if aNode.ChildNodes[false] <> nil then begin aTmpNode2 := InternalfindNextUrlToDownload(TPageNotYetDownloadedBinTreeNode(aNode.ChildNodes[false]), alowDeepLevel); If (assigned(aTmpNode2)) and (aTmpNode2.DeepLevel <= alowDeepLevel) then begin result := aTmpNode2; exit; end; end else aTmpNode2 := nil; result := aNode; If assigned(aTmpNode1) and (result.deepLevel > aTmpNode1.deeplevel) then result := aTmpNode1; If assigned(aTmpNode2) and (result.deepLevel > aTmpNode2.deeplevel) then result := aTmpNode2; end; end; Var aNode: TPageNotYetDownloadedBinTreeNode; begin {If theire is more url to download} IF FPageNotYetDownloadedBinTree.NodeCount > 0 then begin {Find next url with deeplevel closer to FCurrentDeepLevel} If UpDownMaxDeepLevel.Position >= 0 then aNode := InternalfindNextUrlToDownload( TPageNotYetDownloadedBinTreeNode(FPageNotYetDownloadedBinTree.head), FCurrentDeepLevel ) {Find next url without take care of FCurrentDeepLevel} else aNode := TPageNotYetDownloadedBinTreeNode(FPageNotYetDownloadedBinTree.head); Url := aNode.ID; FCurrentDeepLevel := TPageNotYetDownloadedBinTreeNode(aNode).DeepLevel; end {If their is no more url to download then exit} else begin Url := ''; FCurrentDeepLevel := -1; end; StatusBar2.Panels[0].Text := 'Downloading Url: ' + String(Url); Application.ProcessMessages; if not ButtonStop.Enabled then url := ''; end; {**********************************************************} procedure TForm1.MainWebSpiderUpdateLinkToLocalPathFindLink( Sender: TObject; const HtmlTagString: AnsiString; HtmlTagParams: TALStringsA; const URL: AnsiString; var LocalPath: AnsiString); Var aNode: TALStringKeyAVLBinaryTreeNode; aTmpUrl: ansiString; aAnchorValue: AnsiString; begin LocalPath := ''; If Url <> '' then begin aTmpUrl := Url; While True Do begin aTmpUrl := AlRemoveAnchorFromUrl(aTmpUrl, aAnchorValue); aNode := FPageDownloadedBinTree.FindNode(aTmpUrl); If (aNode <> nil) then begin LocalPath := TPageDownloadedBinTreeNode(aNode).Data; If ALPosA('=>',LocalPath) = 1 then Begin aTmpUrl := AlCopyStr(LocalPath,3,MaxInt); LocalPath := ''; end else Break; end else Break; end; If LocalPath = '!' then localpath := '' else If LocalPath <> '' then begin LocalPath := ALStringReplaceA( LocalPath, '\', '/', [RfReplaceall] ) + aAnchorValue; If (FCurrentLocalFileNameIndex >= 0) then LocalPath := '../' + LocalPath; end; end; end; {*************************************************************} procedure TForm1.MainWebSpiderUpdateLinkToLocalPathGetNextFile( Sender: TObject; var FileName, BaseHref: AnsiString); {~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} Function SplitPathMakeFilename: AnsiString; begin If FCurrentLocalFileNameIndex < 0 then result := '' else If FCurrentLocalFileNameIndex = 0 then result := AnsiString(EditSaveDirectory.Text + 'Start.htm') else Result := AnsiString(EditSaveDirectory.Text + IntToStr((FCurrentLocalFileNameIndex div SplitDirectoryAmount) * SplitDirectoryAmount + SplitDirectoryAmount) + '\' + IntToStr(FCurrentLocalFileNameIndex) + '.htm'); dec(FCurrentLocalFileNameIndex); end; Begin {Find FileName} FileName := SplitPathMakeFilename; While (FileName <> '') and not fileExists(String(FileName)) do Filename := SplitPathMakeFilename; {if filename found} If FileName <> '' then Begin {Extract the Base Href} BaseHref := AlGetStringFromFile(FileName); BaseHref := ALTrim( AlCopyStr( BaseHref, 17, // '<!-- saved from ' + URL ALPosA(#13,BaseHref) - 21 // URL + ' -->' +#13#10 ) ); end else BaseHref := ''; {update label} StatusBar2.Panels[0].Text := 'Update Href to Local path for file: ' + String(FileName); application.ProcessMessages; if not ButtonStop.Enabled then begin FileName := ''; BaseHref := ''; end end; {*******************************************} procedure TForm1.FormCreate(Sender: TObject); begin fMainHttpClient := TALWinHttpClient.Create; fMainHttpClient.InternetOptions := [wHttpIo_REFRESH, wHttpIo_Keep_connection]; fMainWebSpider := TAlWebSpider.Create; fMainWebSpider.OnCrawlDownloadSuccess := MainWebSpiderCrawlDownloadSuccess; fMainWebSpider.OnCrawlDownloadRedirect := MainWebSpiderCrawlDownloadRedirect; fMainWebSpider.OnCrawlDownloadError := MainWebSpiderCrawlDownloadError; fMainWebSpider.OnCrawlGetNextLink := MainWebSpiderCrawlGetNextLink; fMainWebSpider.OnCrawlFindLink := MainWebSpiderCrawlFindLink; fMainWebSpider.OnUpdateLinkToLocalPathGetNextFile := MainWebSpiderUpdateLinkToLocalPathGetNextFile; fMainWebSpider.OnUpdateLinkToLocalPathFindLink := MainWebSpiderUpdateLinkToLocalPathFindLink; fMainWebSpider.HttpClient := fMainHttpClient; end; {********************************************************************} procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin fMainHttpClient.Free; fMainWebSpider.Free; end; initialization {$IFDEF DEBUG} ReportMemoryleaksOnSHutdown := True; {$ENDIF} SetMultiByteConversionCodePage(CP_UTF8); end.
{***************************************************************************} { } { DelphiUIAutomation } { } { Copyright 2015 JHC Systems Limited } { } {***************************************************************************} { } { 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 DelphiUIAutomation.PatternIDs; interface const // Automation Pattern Identifiers // See - https://msdn.microsoft.com/en-us/library/windows/desktop/ee671195%28v=vs.85%29.aspx UIA_InvokePatternId = 10000; UIA_SelectionPatternId = 10001; UIA_ValuePatternId = 10002; UIA_RangeValuePatternId = 10003; UIA_ScrollPatternId = 10004; UIA_ExpandCollapsePatternId = 10005; UIA_GridPatternId = 10006; UIA_GridItemPatternId = 10007; UIA_MultipleViewPatternId = 10008; UIA_WindowPatternId = 10009; UIA_SelectionItemPatternId = 10010; UIA_DockPatternId = 10011; UIA_TablePatternId = 10012; UIA_TableItemPatternId = 10013; UIA_TextPatternId = 10014; UIA_TogglePatternId = 10015; UIA_TransformPatternId = 10016; UIA_ScrollItemPatternId = 10017; UIA_LegacyIAccessiblePatternId = 10018; UIA_ItemContainerPatternId = 10019; UIA_VirtualizedItemPatternId = 10020; UIA_SynchronizedInputPatternId = 10021; UIA_ObjectModelPatternId = 10022; UIA_AnnotationPatternId = 10023; UIA_TextPattern2Id = 10024; UIA_StylesPatternId = 10025; UIA_SpreadsheetPatternId = 10026; UIA_SpreadsheetItemPatternId = 10027; UIA_TransformPattern2Id = 10028; UIA_TextChildPatternId = 10029; UIA_DragPatternId = 10030; UIA_DropTargetPatternId = 10031; UIA_TextEditPatternId = 10032; UIA_CustomNavigationPatternId = 10033; implementation end.
unit FitTransform; interface uses OApproxNew; type TTransformFunction=(tfDeriv,tfMedian,tfSmooth); const TransformFunctionNames:array[TTransformFunction]of string= ('Derivative','Median filter','Smoothing'); TransformFunctionDescriptions:array[TTransformFunction]of string= ('Derivative, which is calculated as derivative of 3-poin Lagrange polynomial', '3-point median filtering', '3-point averaging, the weighting coefficient are determined by Gaussian distribution with 60% dispersion'); type TFitTransform=class (TFitFunctionNew) {базовий для операцій простих перетворень вихідної функції} private fTTF:TTransformFunction; protected procedure RealFitting;override; procedure NamesDefine;override; public Constructor Create(FunctionName:string); end; //TFitTransform=class (TFitFunctionNew) implementation { TFitTransform } constructor TFitTransform.Create(FunctionName: string); var i:TTransformFunction; begin for I := Low(TTransformFunction) to High(TTransformFunction) do if FunctionName=TransformFunctionNames[i] then begin fTTF:=i; Break; end; inherited Create; if fTTF=tfMedian then fPictureName:='MedianFig'; fHasPicture:=True; end; procedure TFitTransform.NamesDefine; begin SetNameCaption(TransformFunctionNames[fTTF], TransformFunctionDescriptions[fTTF]); end; procedure TFitTransform.RealFitting; begin case fTTF of tfSmooth:fDataToFit.Smoothing(FittingData); tfDeriv:fDataToFit.Derivate(FittingData); tfMedian:fDataToFit.Median(FittingData); end; end; end.
unit BDE32; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Registry; type TBDE32 = class(TComponent) private FLocalShare: Boolean; FPdxNetDir: String; FMaxBufSize, FMaxFileHandles, FMemSize, FSharedMemSize: integer; function GetRegistryDir(RegKey, DefaultDir: string): String ; procedure TestBDEDir(TestDir: string; var CF: string; var DLLP: string); function GetPaths(var CF: string; var DLLP: string): boolean; procedure writeToCFG(Item: string; Val: string); function ReadFromCFG(Item: string; DefStr: string): string; protected { Protected declarations } public constructor Create(AOwner:TComponent); override; published property LocalShare: boolean read FLocalShare write FLocalShare; property PdxNetDir: String read FPdxNetDir write FPdxNetDir; property MaxBufSize: integer read FMaxBufSize write FMaxBufSize; property MaxFileHandles: integer read FMaxFileHandles write FMaxFileHandles; property MemSize: integer read FMemSize write FMemSize; property SharedMemSize: integer read FSharedMemSize write FSharedMemSize; procedure WriteSettings; procedure ReadSettings; end; function FilePos(FileName, What: string; startFrom: integer):integer; procedure Register; implementation {thanks to Andrea Sessa (asessa@nest.it) for the leading '\' on all registry paths... and to Remy Vincent (remyvincent@hotmail.com) for the GetCommonFilesDir function and for providing key dirs to look for BDE files... anyone else who improves BDE32 will get a mention - email paul@kestrelsoftware.co.uk with your improvements} {########################### Check for BDE installation ###########################} constructor TBDE32.Create(AOwner:TComponent); var ConfigFile, DLLPath: string; begin {Create: 1. Discover if BDE is installed by checing registry 2. If not then look for BDE files and write loctations to Registry 3. If unable to find BDE files then ask for them 4. Finally read key settings from CFG file (if available)} inherited Create(AOwner); with TRegistry.create do begin Rootkey := HKEY_LOCAL_MACHINE; if not (OpenKey('\SOFTWARE\BORLAND\DATABASE ENGINE', false) and FileExists(ReadString('DLLPATH') + '\idapi32.dll')) then begin if GetPaths(ConfigFile, DLLPath) then begin Rootkey := HKEY_LOCAL_MACHINE; OpenKey('\SOFTWARE\BORLAND\DATABASE ENGINE', True); WriteString('CONFIGFILE01', ConfigFile); WriteString('DLLPATH', DLLPath); WriteString('RESOURCE', '0009'); WriteString('SAVECONFIG', 'WIN31'); WriteString('UseCount', '1'); end else begin ShowMessage('Please put BDE files in ' + ExtractFilePath(application.ExeName) + 'BDE'); halt; end; end; Free; end; ReadSettings; end; {########################### Read/Write to CFG file ###########################} procedure TBDE32.ReadSettings; begin FPdxNetDir := ReadFromCFG('NET DIR', 'F:\'); FLocalShare := ReadFromCFG('LOCAL SHARE', 'FALSE') = 'TRUE'; FMaxBufSize := StrToInt(ReadFromCFG('MAXBUFSIZE', '2048')); FMaxFileHandles := StrToInt(ReadFromCFG('MAXFILEHANDLES', '48')); FMemSize := StrToInt(ReadFromCFG('MEMSIZE', '16')); FSharedMemSize := StrToInt(ReadFromCFG('SHAREDMEMSIZE', '2048')); end; procedure TBDE32.WriteSettings; begin if FLocalShare then writeToCFG('LOCAL SHARE', 'TRUE') else writeToCFG('LOCAL SHARE', 'FALSE'); writeToCFG('NET DIR', FPdxNetDir); writeToCFG('MAXBUFSIZE', IntToStr(FMaxBufSize)); writeToCFG('MAXFILEHANDLES', IntToStr(FMaxFileHandles)); writeToCFG('MEMSIZE', IntToStr(FMemSize)); writeToCFG('SHAREDMEMSIZE', IntToStr(FSharedMemSize)); end; procedure TBDE32.writeToCFG(Item: string; Val: string); Var CFGFile, TempFile: string; CFGStream, TempStream: TFileStream; FoundPos1, FoundPos2: integer; myBuf: array[0..255] of char; begin with TRegistry.create do begin Rootkey := HKEY_LOCAL_MACHINE; OpenKey('\SOFTWARE\BORLAND\DATABASE ENGINE', false); CFGFile := ReadString('CONFIGFILE01'); Free; end; TempFile := CFGFile + '2'; FoundPos1 := FilePos(CFGFile, Item, 0); if FoundPos1 > 0 then begin FoundPos2 := FilePos(CFGFile, #0, FoundPos1 + Length(Item) + 3); CFGStream := TFileStream.Create(CFGFile, fmOpenRead); TempStream := TFileStream.Create(TempFile, fmOpenWrite or fmCreate); TempStream.CopyFrom(CFGStream, FoundPos1 + Length(Item) + 2); StrPCopy(MyBuf, Val); TempStream.Write(MyBuf, length(Val)); CFGStream.Seek(FoundPos2 - 1, soFromBeginning); TempStream.CopyFrom(CFGStream, CFGStream.Size - FoundPos2 + 1); TempStream.Free; CFGStream.Free; end; DeleteFile(CFGFile); RenameFile(TempFile, CFGFile); end; function TBDE32.ReadFromCFG(Item: string; DefStr: string): string; Var CFGFile: string; FoundPos1, FoundPos2: integer; MyFile: TextFile; MyStr: string; begin with TRegistry.create do begin Rootkey := HKEY_LOCAL_MACHINE; OpenKey('\SOFTWARE\BORLAND\DATABASE ENGINE', false); CFGFile := ReadString('CONFIGFILE01'); Free; end; if FileExists(CFGFile) then begin AssignFile(MyFile, CFGFile); Reset(MyFile); ReadLn(MyFile, MyStr); CloseFile(MyFile); FoundPos1 := Pos(Item, MyStr); if FoundPos1 > 0 then begin Delete(MyStr, 1, FoundPos1 + Length(Item) + 2); foundPos2 := Pos(#0, MyStr); Result := Copy(MyStr, 0, FoundPos2 + 1); end else result := DefStr; end else result := DefStr; end; function FilePos(FileName, What: string; startFrom: integer): integer; var MyStr: string; MyFile: TextFile; begin if FileExists(FileName) then begin AssignFile(MyFile, FileName); Reset(MyFile); ReadLn(MyFile, MyStr); Delete(MyStr, 1, StartFrom); Result := StartFrom + Pos(What, MyStr); CloseFile(MyFile); end else result := 0; end; {########################### Find a previous BDE ###########################} function TBDE32.GetPaths(var CF: string; var DLLP: string): boolean; var AppDir, CommonDir, ProgDir: string; begin {GetPaths: looks for the BDE, assumed to be found if a ConfigFile (CF) and DLL Path (DLLP) are found. You can add your own search paths to these ones, remember that they are checked in order, so if 2 BDE's are found then the second one will be used} AppDir := ExtractFilePath(Application.ExeName); AppDir := Copy(AppDir, 1, length(AppDir) - 1); {get rid of the last '\'} CommonDir := GetRegistryDir('CommonFilesDir', 'C:\Program Files\Common Files'); ProgDir := GetRegistryDir('ProgramFilesDir', 'C:\Program Files'); TestBDEDir(AppDir, CF, DLLP); TestBDEDir(AppDir + '\BDE', CF, DLLP); TestBDEDir(ProgDir + '\borland\common files\BDE', CF, DLLP); TestBDEDir(CommonDir + '\BDE', CF, DLLP); TestBDEDir(CommonDir + '\Borland\BDE', CF, DLLP); TestBDEDir(CommonDir + '\Borland Shared\BDE', CF, DLLP); Result := FileExists(CF) and FileExists(DLLP + '\idapi32.dll'); end; procedure TBDE32.TestBDEDir(TestDir: string; var CF: string; var DLLP: string); begin if FileExists(TestDir + '\idapi.cfg') then CF := TestDir + '\idapi.cfg'; if FileExists(TestDir + '\idapi32.cfg') then CF := TestDir + '\idapi32.cfg'; if FileExists(TestDir + '\idapi32.dll') then DLLP := TestDir; end; function TBDE32.GetRegistryDir(RegKey, DefaultDir: string): String; begin with TRegistry.create do begin Rootkey := HKEY_LOCAL_MACHINE; OpenKey('\SOFTWARE\Microsoft\Windows\CurrentVersion', false); Result := ReadString(RegKey); Free; end; if Result = '' then Result := DefaultDir; end; {########################### Register Component ###########################} procedure Register; begin RegisterComponents('Data Access', [TBDE32]); end; end.
{ **************************************************************************** } { Project: ConnectFour3D { Module: SearchUtil.pas { Author: Josef Schuetzenberger { E-Mail: schutzenberger@hotmail.com { WWW: http://members.fortunecity.com/schutzenberger { This unit is based on work by J.T. Deuter { **************************************************************************** } { Copyright ©2006 Josef Schuetzenberger { This programme 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 any later version. { { This programme is distributed for educational purposes in the hope that it { will be useful, but WITHOUT ANY WARRANTY. See the GNU General Public License { for more details at http://www.gnu.org/licenses/gpl.html { **************************************************************************** } unit SearchUtil; interface const // Connect four game parameters N_COL = 7; N_ROW = 6; N_NUM = 4; N_SQR = 42; N_WL = 69; // Player types PT_PLR1 = 1; PT_PLR2 = 2; // Extreme limits of evaluated score of a position INFINITY = High(smallint); SCR_WIN = 1000; SCR_DRAW = 0; SCR_LOSS = -1000; // Board constants BRD_FULL = $000003FFFFFFFFFF; FRST_ROW = $000000000000007F; LAST_ROW = $000003F800000000; BRD_COL = $0000000810204081; //0000 0000 1000 0001 0000 0010 0000 0100 0000 1000 0001 BRD_EVENSQRS = $000003F80FE03F80; //0011 1111 1000 0000 1111 1110 0000 0011 1111 1000 0000 // Sort constants FIRST = 0; LAST = 1; NONE = 2; // There are 69 unique winning lines of 4 in a row in connect 4 WIN_LINES: array[0..(N_WL - 1)] of Int64 = ( $000000000000000F, $000000000000001E, $000000000000003C, $0000000000000078, $0000000000000780, $0000000000000F00, $0000000000001E00, $0000000000003C00, $000000000003C000, $0000000000078000, $00000000000F0000, $00000000001E0000, $0000000001E00000, $0000000003C00000, $0000000007800000, $000000000F000000, $00000000F0000000, $00000001E0000000, $00000003C0000000, $0000000780000000, $0000007800000000, $000000F000000000, $000001E000000000, $000003C000000000, $0000000000204081, $0000000010204080, $0000000810204000, $0000000000408102, $0000000020408100, $0000001020408000, $0000000000810204, $0000000040810200, $0000002040810000, $0000000001020408, $0000000081020400, $0000004081020000, $0000000002040810, $0000000102040800, $0000008102040000, $0000000004081020, $0000000204081000, $0000010204080000, $0000000008102040, $0000000408102000, $0000020408100000, $0000000001010101, $0000000080808080, $0000004040404000, $0000000002020202, $0000000101010100, $0000008080808000, $0000000004040404, $0000000202020200, $0000010101010000, $0000000008080808, $0000000404040400, $0000020202020000, $0000000000208208, $0000000010410400, $0000000820820000, $0000000000410410, $0000000020820800, $0000001041040000, $0000000000820820, $0000000041041000, $0000002082080000, $0000000001041040, $0000000082082000, $0000004104100000); // 69 sorted winning lines of 4 in a row in connect 4 WIN_LINES1: array[0..(N_WL - 1)] of Int64 = ( $000000000000000F, $000000000000001E, $000000000000003C, $0000000000000078, $0000000000000780, $0000000000000F00, $0000000000001E00, $0000000000003C00, $000000000003C000, $0000000000078000, $00000000000F0000, $00000000001E0000, $0000000001E00000, $0000000003C00000, $0000000007800000, $000000000F000000, $00000000F0000000, $0000000000204081, $0000000010204080, $0000000000408102, $0000000020408100, $0000000000810204, $0000000040810200, $0000000001020408, $0000000081020400, $0000000002040810, $0000000004081020, $0000000008102040, $0000000001010101, $0000000080808080, $0000000002020202, $0000000004040404, $0000000008080808, $0000000000208208, $0000000010410400, $0000000000410410, $0000000020820800, $0000000000820820, $0000000041041000, $0000000001041040, $0000000082082000, $0000004040404000, $0000001020408000, $0000000820820000, $0000000404040400, $0000000101010100, $0000008080808000, $0000004081020000, $0000000408102000, $0000000102040800, $0000001041040000, $0000002082080000, $0000000202020200, $0000000810204000, $0000008102040000, $00000001E0000000, $00000003C0000000, $0000000780000000, $000000F000000000, $0000007800000000, $0000002040810000, $0000000204081000, $0000004104100000, $0000010204080000, $0000020408100000, $000003C000000000, $000001E000000000, $0000020202020000, $0000010101010000 ); // Winning Lines Mask for each game cell - Use logical OR to set the appropriate Winning Lines WLINE_MASK: array[0..(N_SQR - 1)] of Int64 = ( $000000000121418F, $000000000242831F, $000000000485063F, $00000000092A8E7F, $0000000002450C7E, $00000000048A187C, $0000000009143078, $0000000090A0C781, $0000000121418F83, $0000000242A39F8E, $0000000495473F9C, $000000012A8E3F38, $00000002450C3E60, $000000048A183C40, $000000485063C081, $00000090A0E7C38A, $0000012151CFC715, $0000024AA39FCE2A, $00000095471F9C54, $000001228E1F3828, $000002450C1E2040, $0000000811E0C289, $0000005073E1C512, $000000A8E7E38AA4, $00000151CFE71549, $000002A38FCE2A12, $000001470F9C1424, $000002040F182848, $00000008F0614480, $00000019F0C28900, $00000073F1C55200, $000000E7F38AA480, $000001C7E7150900, $00000307C60A1200, $000002078C142400, $0000007830A24000, $000000F861448000, $000001F8C2890000, $000003F9C5524000, $000003F182848000, $000003E305090000, $000003C60A120000); // Set Mask for each game cell - Use logical OR to set the appropriate cell SET_MASK: array[0..(N_SQR - 1)] of Int64 = ( $0000000000000001, $0000000000000002, $0000000000000004, $0000000000000008, $0000000000000010, $0000000000000020, $0000000000000040, $0000000000000080, $0000000000000100, $0000000000000200, $0000000000000400, $0000000000000800, $0000000000001000, $0000000000002000, $0000000000004000, $0000000000008000, $0000000000010000, $0000000000020000, $0000000000040000, $0000000000080000, $0000000000100000, $0000000000200000, $0000000000400000, $0000000000800000, $0000000001000000, $0000000002000000, $0000000004000000, $0000000008000000, $0000000010000000, $0000000020000000, $0000000040000000, $0000000080000000, $0000000100000000, $0000000200000000, $0000000400000000, $0000000800000000, $0000001000000000, $0000002000000000, $0000004000000000, $0000008000000000, $0000010000000000, $0000020000000000); // Reset Mask for each game cell - Use logical AND to set the appropriate cell RESET_MASK: array[0..(N_SQR - 1)] of Int64 = ( $FFFFFFFFFFFFFFFE, $FFFFFFFFFFFFFFFD, $FFFFFFFFFFFFFFFB, $FFFFFFFFFFFFFFF7, $FFFFFFFFFFFFFFEF, $FFFFFFFFFFFFFFDF, $FFFFFFFFFFFFFFBF, $FFFFFFFFFFFFFF7F, $FFFFFFFFFFFFFEFF, $FFFFFFFFFFFFFDFF, $FFFFFFFFFFFFFBFF, $FFFFFFFFFFFFF7FF, $FFFFFFFFFFFFEFFF, $FFFFFFFFFFFFDFFF, $FFFFFFFFFFFFBFFF, $FFFFFFFFFFFF7FFF, $FFFFFFFFFFFEFFFF, $FFFFFFFFFFFDFFFF, $FFFFFFFFFFFBFFFF, $FFFFFFFFFFF7FFFF, $FFFFFFFFFFEFFFFF, $FFFFFFFFFFDFFFFF, $FFFFFFFFFFBFFFFF, $FFFFFFFFFF7FFFFF, $FFFFFFFFFEFFFFFF, $FFFFFFFFFDFFFFFF, $FFFFFFFFFBFFFFFF, $FFFFFFFFF7FFFFFF, $FFFFFFFFEFFFFFFF, $FFFFFFFFDFFFFFFF, $FFFFFFFFBFFFFFFF, $FFFFFFFF7FFFFFFF, $FFFFFFFEFFFFFFFF, $FFFFFFFDFFFFFFFF, $FFFFFFFBFFFFFFFF, $FFFFFFF7FFFFFFFF, $FFFFFFEFFFFFFFFF, $FFFFFFDFFFFFFFFF, $FFFFFFBFFFFFFFFF, $FFFFFF7FFFFFFFFF, $FFFFFEFFFFFFFFFF, $FFFFFDFFFFFFFFFF); CENT_COL = $7EFDFBF7; // 0111 1110 1111 1101 1111 1011 1111 0111 MID_COL = $3C78F1E3; // 0011 1100 0111 1000 1111 0001 1110 0011 COL_06 = $183060C1; // 0001 1000 0011 0000 0110 0000 1100 0001 COL_01 = $183060C183; // 0001 1000 0011 0000 0110 0000 1100 0001 1000 0011 COL_56 = $3060C183060;// 0011 0000 0110 0000 1100 0001 1000 0011 0000 0110 0000 WLineDepth =17; // depth at which win-lines are recalculated type TBtBrd= array[0..PT_PLR2] of Int64; TMove = record Move:integer; {last Move} nBV:integer; {Minmax-SearchValue} end; TMoves = array [0..6]of TMove; var // BitBoards of current game position 0=WinLine, 1=Player 1, 2=Player 2 BtBrd: TbtBrd = (0,0, 0); function Sign(const AValue: integer): integer; function BitCount(const aBoard: Int64): Integer; function BitScanForward(const aBoard: Int64): Integer; procedure DoMove(const Pos,aPlayer:integer); procedure UndoMove(const Pos,aPlayer:integer); function CheckMovesBelow(const Pos,aPlayer:integer):boolean; implementation function Sign(const AValue: integer): integer; begin Result := 0; if AValue < 0 then Result := -1 else if AValue > 0 then Result := 1; end; // check whether the 2 stones under the current position are occupied by the Player function CheckMovesBelow(const Pos,aPlayer:integer):boolean; asm sub eax,7 //calc Pos below cmc //complement carry jl @@e //exit if bottom reached cmp eax,$20 //Pos in low or high word jnl @@n bt dword ptr [BtBrd+edx*8],eax //Player in edx ? jmp @@k @@n: sub eax,$20 bt dword ptr [BtBrd+edx*8+4],eax @@k: jnc @@e //exit if there is no move sub eax,7 //calc pos below cmc //complement carry jl @@e //exit if bottom reached cmp eax,$20 //Pos in low or high word jnl @@m bt dword ptr [BtBrd+edx*8],eax //Player in edx ? jmp @@e @@m: sub eax,$20 bt dword ptr [BtBrd+edx*8+4],eax @@e: rcl eax,1 //transfer carry-flag in result and al,$1 end; procedure DoMove(const Pos,aPlayer:integer); asm cmp eax,$20 //Pos in eax jnl @@n bts dword ptr [BtBrd+edx*8],eax //Player in edx jmp @@e @@n: sub eax,$20 bts dword ptr [BtBrd+edx*8+4],eax @@e: end; procedure UndoMove(const Pos,aPlayer:integer); asm // mov eax,Pos // mov edx,aPlayer // lea ecx,BtBrd cmp eax,$20 jnl @@n btr dword ptr [BtBrd+edx*8],eax jmp @@e @@n: sub eax,$20 btr dword ptr [BtBrd+edx*8+4],eax @@e: end; function BitCount(const aBoard: Int64): Integer; asm mov ecx, dword ptr aBoard xor eax, eax test ecx, ecx jz @@1 @@0: lea edx, [ecx-1] inc eax and ecx, edx jnz @@0 @@1: mov ecx, dword ptr aBoard+04h test ecx, ecx jz @@3 @@2: lea edx, [ecx-1] inc eax and ecx, edx jnz @@2 @@3: end; function BitScanForward(const aBoard: Int64): Integer; asm bsf eax, dword ptr aBoard jz @@0 jnz @@2 @@0: bsf eax, dword ptr aBoard+04h jz @@1 add eax, 20h jnz @@2 @@1: mov eax, -1 @@2: end; end.
unit mnMathTestCase; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework; type TmnMathTestCase = class(TTestCase) strict private public procedure SetUp; override; procedure TearDown; override; published procedure testFloatCompareSeries; procedure testCompareValue2D; procedure testChineseRound; procedure testSingleDigit; procedure testAlignInt; procedure testReverseIntSeries; procedure testCount1InBinary; procedure testBitIsInBinarySeries; procedure testSetBitInBinarySeries; procedure testLocateInSections; procedure testPC; procedure testProbability; procedure testCombination; end; implementation uses mnMath, Types, mnSystem, mnDebug, SysUtils, mnResStrsU; { TmnMathTestCase } procedure TmnMathTestCase.SetUp; begin end; procedure TmnMathTestCase.TearDown; begin end; procedure TmnMathTestCase.testFloatCompareSeries; begin Check(mnFloatEQ(1.234, 1.234)); CheckFalse(mnFloatEQ(1.234, 1.2340001)); Check(mnFloatNE(1.234, 1.2340001)); CheckFalse(mnFloatNE(1.234, 1.234)); Check(mnFloatLT(1.234, 1.2340001)); CheckFalse(mnFloatLT(1.234, 1.234)); CheckFalse(mnFloatLT(1.234, 1.2339999)); Check(mnFloatLE(1.234, 1.2340001)); Check(mnFloatLE(1.234, 1.234)); CheckFalse(mnFloatLE(1.234, 1.2339999)); Check(mnFloatGT(1.234, 1.2339999)); CheckFalse(mnFloatGT(1.234, 1.234)); CheckFalse(mnFloatGT(1.234, 1.2340001)); Check(mnFloatGE(1.234, 1.2339999)); Check(mnFloatGE(1.234, 1.234)); CheckFalse(mnFloatGE(1.234, 1.2340001)); end; procedure TmnMathTestCase.testCompareValue2D; begin Check(mnCompareValue2D(1, 2, 3, 4) = LessThanValue); Check(mnCompareValue2D(3, 4, 1, 2) = GreaterThanValue); Check(mnCompareValue2D(1, 2, 1, 4) = LessThanValue); Check(mnCompareValue2D(1, 4, 1, 2) = GreaterThanValue); Check(mnCompareValue2D(1, 2, 1, 2) = EqualsValue); end; procedure TmnMathTestCase.testChineseRound; begin CheckEquals(mnChineseRound(4041.5), 4042); CheckEquals(mnChineseRound(4042.5), 4043); CheckEquals(mnChineseRound(4043.5), 4044); CheckEquals(mnChineseRound(4041.4999), 4041); CheckEquals(mnChineseRound(4042.4999), 4042); CheckEquals(mnChineseRound(4043.4999), 4043); CheckEquals(mnChineseRound(4041.5001), 4042); CheckEquals(mnChineseRound(4042.5001), 4043); CheckEquals(mnChineseRound(4043.5001), 4044); CheckEquals(mnChineseRound(40.415, -2), 40.42, mnParticle); CheckEquals(mnChineseRound(40.425, -2), 40.43, mnParticle); CheckEquals(mnChineseRound(40.435, -2), 40.44, mnParticle); CheckEquals(mnChineseRound(40.414999, -2), 40.41, mnParticle); CheckEquals(mnChineseRound(40.424999, -2), 40.42, mnParticle); CheckEquals(mnChineseRound(40.434999, -2), 40.43, mnParticle); CheckEquals(mnChineseRound(40.415001, -2), 40.42, mnParticle); CheckEquals(mnChineseRound(40.425001, -2), 40.43, mnParticle); CheckEquals(mnChineseRound(40.435001, -2), 40.44, mnParticle); CheckEquals(mnChineseRound(40415, 1), 40420); CheckEquals(mnChineseRound(40425, 1), 40430); CheckEquals(mnChineseRound(40435, 1), 40440); CheckEquals(mnChineseRound(40414.999, 1), 40410); CheckEquals(mnChineseRound(40424.999, 1), 40420); CheckEquals(mnChineseRound(40434.999, 1), 40430); CheckEquals(mnChineseRound(40415.001, 1), 40420); CheckEquals(mnChineseRound(40425.001, 1), 40430); CheckEquals(mnChineseRound(40435.001, 1), 40440); CheckEquals(mnChineseRound(-4041.5), -4042); CheckEquals(mnChineseRound(-4042.5), -4043); CheckEquals(mnChineseRound(-4043.5), -4044); CheckEquals(mnChineseRound(-4041.4999), -4041); CheckEquals(mnChineseRound(-4042.4999), -4042); CheckEquals(mnChineseRound(-4043.4999), -4043); CheckEquals(mnChineseRound(-4041.5001), -4042); CheckEquals(mnChineseRound(-4042.5001), -4043); CheckEquals(mnChineseRound(-4043.5001), -4044); CheckEquals(mnChineseRound(-40.415, -2), -40.42, mnParticle); CheckEquals(mnChineseRound(-40.425, -2), -40.43, mnParticle); CheckEquals(mnChineseRound(-40.435, -2), -40.44, mnParticle); CheckEquals(mnChineseRound(-40.414999, -2), -40.41, mnParticle); CheckEquals(mnChineseRound(-40.424999, -2), -40.42, mnParticle); CheckEquals(mnChineseRound(-40.434999, -2), -40.43, mnParticle); CheckEquals(mnChineseRound(-40.415001, -2), -40.42, mnParticle); CheckEquals(mnChineseRound(-40.425001, -2), -40.43, mnParticle); CheckEquals(mnChineseRound(-40.435001, -2), -40.44, mnParticle); CheckEquals(mnChineseRound(-40415, 1), -40420); CheckEquals(mnChineseRound(-40425, 1), -40430); CheckEquals(mnChineseRound(-40435, 1), -40440); CheckEquals(mnChineseRound(-40414.999, 1), -40410); CheckEquals(mnChineseRound(-40424.999, 1), -40420); CheckEquals(mnChineseRound(-40434.999, 1), -40430); CheckEquals(mnChineseRound(-40415.001, 1), -40420); CheckEquals(mnChineseRound(-40425.001, 1), -40430); CheckEquals(mnChineseRound(-40435.001, 1), -40440); end; procedure TmnMathTestCase.testSingleDigit; begin CheckEquals(mnSingleDigit(0), 0); CheckEquals(mnSingleDigit(9), 9); CheckEquals(mnSingleDigit(1234567890), 9); CheckEquals(mnSingleDigit(1234567891), 1); CheckEquals(mnSingleDigit(1234567892), 2); end; procedure TmnMathTestCase.testAlignInt; begin CheckEquals(mnAlignInt(25, 0), 25); CheckEquals(mnAlignInt(25, 1), 25); CheckEquals(mnAlignInt(25, 2), 26); CheckEquals(mnAlignInt(25, 3), 27); CheckEquals(mnAlignInt(25, 4), 28); CheckEquals(mnAlignInt(25, 5), 25); CheckEquals(mnAlignInt(25, 6), 30); CheckEquals(mnAlignInt(25, -1), 25); CheckEquals(mnAlignInt(25, -2), 26); CheckEquals(mnAlignInt(-25, 1), -25); CheckEquals(mnAlignInt(-25, 2), -26); CheckEquals(mnAlignInt(-25, -1), -25); CheckEquals(mnAlignInt(-25, -2), -26); end; procedure TmnMathTestCase.testReverseIntSeries; begin // mnReverseInt16 Check(mnReverseInt16($1234) = $3412); Check(mnReverseInt16(High(Int16)) = Int16($FF7F)); Check(mnReverseInt16(Low(Int16)) = Int16($0080)); // mnReverseInt32 Check(mnReverseInt32($12345678) = $78563412); Check(mnReverseInt32(High(Int32)) = Int32($FFFFFF7F)); Check(mnReverseInt32(Low(Int32)) = Int32($00000080)); // mnReverseInt64 Check(mnReverseInt64($1234567890ABCDEF) = $EFCDAB9078563412); Check(mnReverseInt64(High(Int64)) = Int64($FFFFFFFFFFFFFF7F)); Check(mnReverseInt64(Low(Int64)) = Int64($0000000000000080)); // mnReverseUInt16 Check(mnReverseUInt16($1234) = $3412); Check(mnReverseUInt16(High(UInt16)) = UInt16($FFFF)); Check(mnReverseUInt16(Low(UInt16)) = UInt16($0000)); // mnReverseUInt32 Check(mnReverseUInt32($12345678) = $78563412); Check(mnReverseUInt32(High(UInt32)) = UInt32($FFFFFFFF)); Check(mnReverseUInt32(Low(UInt32)) = UInt32($00000000)); end; procedure TmnMathTestCase.testCount1InBinary; begin CheckEquals(mnCount1InBinary($00000001), 1); CheckEquals(mnCount1InBinary($00F00030), 6); CheckEquals(mnCount1InBinary($F0000000), 4); CheckEquals(mnCount1InBinary(High(UInt32)), 32); CheckEquals(mnCount1InBinary(Low(UInt32)), 0); end; procedure TmnMathTestCase.testBitIsInBinarySeries; begin // mnBitIs1InBinary Check(mnBitIs1InBinary($00000002, 1)); Check(mnBitIs1InBinary($F0000000, 31)); // mnBitIs0InBinary Check(mnBitIs0InBinary($00000002, 0)); Check(mnBitIs0InBinary($00000002, 31)); end; procedure TmnMathTestCase.testSetBitInBinarySeries; begin // mnSetBit1InBinary CheckEquals(mnSetBit1InBinary($00000002, 0), $00000003); CheckEquals(mnSetBit1InBinary($00000002, 1), $00000002); CheckEquals(mnSetBit1InBinary($00000002, 31), $80000002); // mnSetBit0InBinary CheckEquals(mnSetBit0InBinary($00000002, 0), $00000002); CheckEquals(mnSetBit0InBinary($00000002, 1), $00000000); CheckEquals(mnSetBit0InBinary($80000002, 31), $00000002); // mnSetBitInBinary CheckEquals(mnSetBitInBinary($00000002, 0, True), $00000003); CheckEquals(mnSetBitInBinary($00000002, 1, True), $00000002); CheckEquals(mnSetBitInBinary($00000002, 31, True), $80000002); CheckEquals(mnSetBitInBinary($00000002, 0, False), $00000002); CheckEquals(mnSetBitInBinary($00000002, 1, False), $00000000); CheckEquals(mnSetBitInBinary($80000002, 31, False), $00000002); end; procedure TmnMathTestCase.testLocateInSections; var SectionIndex, ItemIndex: Integer; IntList: mnTIntList; begin // overload form 1 try mnLocateInSections(0, [], SectionIndex, ItemIndex); mnNeverGoesHere; except on E: Exception do CheckEquals(E.Message, SSectionsTooShort); end; try mnLocateInSections(10, [1, 2, 3, 4], SectionIndex, ItemIndex); mnNeverGoesHere; except on E: Exception do CheckEquals(E.Message, SSectionsTooShort); end; mnLocateInSections(9, [1, 2, 3, 4], SectionIndex, ItemIndex); CheckEquals(SectionIndex, 3); CheckEquals(ItemIndex, 3); mnLocateInSections(6, [1, 2, 3, 4], SectionIndex, ItemIndex); CheckEquals(SectionIndex, 3); CheckEquals(ItemIndex, 0); mnLocateInSections(5, [1, 2, 3, 4], SectionIndex, ItemIndex); CheckEquals(SectionIndex, 2); CheckEquals(ItemIndex, 2); mnLocateInSections(3, [1, 2, 3, 4], SectionIndex, ItemIndex); CheckEquals(SectionIndex, 2); CheckEquals(ItemIndex, 0); mnLocateInSections(2, [1, 2, 3, 4], SectionIndex, ItemIndex); CheckEquals(SectionIndex, 1); CheckEquals(ItemIndex, 1); mnLocateInSections(1, [1, 2, 3, 4], SectionIndex, ItemIndex); CheckEquals(SectionIndex, 1); CheckEquals(ItemIndex, 0); mnLocateInSections(0, [1, 2, 3, 4], SectionIndex, ItemIndex); CheckEquals(SectionIndex, 0); CheckEquals(ItemIndex, 0); mnLocateInSections(-1, [1, 2, 3, 4], SectionIndex, ItemIndex); CheckEquals(SectionIndex, 0); CheckEquals(ItemIndex, -1); // overload form 2 IntList := mnTIntList.Create; try IntList.Clear; try mnLocateInSections(0, IntList, SectionIndex, ItemIndex); mnNeverGoesHere; except on E: Exception do CheckEquals(E.Message, SSectionsTooShort); end; IntList.LoadFromArray([1, 2, 3, 4]); try mnLocateInSections(10, IntList, SectionIndex, ItemIndex); mnNeverGoesHere; except on E: Exception do CheckEquals(E.Message, SSectionsTooShort); end; mnLocateInSections(9, IntList, SectionIndex, ItemIndex); CheckEquals(SectionIndex, 3); CheckEquals(ItemIndex, 3); mnLocateInSections(6, IntList, SectionIndex, ItemIndex); CheckEquals(SectionIndex, 3); CheckEquals(ItemIndex, 0); mnLocateInSections(5, IntList, SectionIndex, ItemIndex); CheckEquals(SectionIndex, 2); CheckEquals(ItemIndex, 2); mnLocateInSections(3, IntList, SectionIndex, ItemIndex); CheckEquals(SectionIndex, 2); CheckEquals(ItemIndex, 0); mnLocateInSections(2, IntList, SectionIndex, ItemIndex); CheckEquals(SectionIndex, 1); CheckEquals(ItemIndex, 1); mnLocateInSections(1, IntList, SectionIndex, ItemIndex); CheckEquals(SectionIndex, 1); CheckEquals(ItemIndex, 0); mnLocateInSections(0, IntList, SectionIndex, ItemIndex); CheckEquals(SectionIndex, 0); CheckEquals(ItemIndex, 0); mnLocateInSections(-1, IntList, SectionIndex, ItemIndex); CheckEquals(SectionIndex, 0); CheckEquals(ItemIndex, -1); finally IntList.Free; end; end; procedure TmnMathTestCase.testPC; begin // mnP CheckEquals(mnP(5, 1), 5); CheckEquals(mnP(5, 2), 20); CheckEquals(mnP(5, 3), 60); CheckEquals(mnP(5, 4), 120); CheckEquals(mnP(5, 5), 120); CheckEquals(mnP(10, 7), 604800); CheckEquals(mnP(20, 5), 1860480); // mnC CheckEquals(mnC(5, 1), 5); CheckEquals(mnC(5, 2), 10); CheckEquals(mnC(5, 3), 10); CheckEquals(mnC(5, 4), 5); CheckEquals(mnC(5, 5), 1); CheckEquals(mnC(10, 7), 120); CheckEquals(mnC(20, 5), 15504); end; procedure TmnMathTestCase.testProbability; var FullProb: mnTIntArrayDim2; begin mnProbability(5, 2, FullProb); CheckEquals(Low(FullProb), 0); CheckEquals(High(FullProb), mnP(5, 2)-1); CheckEquals(Low(FullProb[0]), 0); CheckEquals(High(FullProb[0]), 2-1); CheckEquals(FullProb[ 0, 0], 0); CheckEquals(FullProb[ 0, 1], 1); CheckEquals(FullProb[ 1, 0], 0); CheckEquals(FullProb[ 1, 1], 2); CheckEquals(FullProb[ 2, 0], 0); CheckEquals(FullProb[ 2, 1], 3); CheckEquals(FullProb[ 3, 0], 0); CheckEquals(FullProb[ 3, 1], 4); CheckEquals(FullProb[ 4, 0], 1); CheckEquals(FullProb[ 4, 1], 0); CheckEquals(FullProb[ 5, 0], 1); CheckEquals(FullProb[ 5, 1], 2); CheckEquals(FullProb[ 6, 0], 1); CheckEquals(FullProb[ 6, 1], 3); CheckEquals(FullProb[ 7, 0], 1); CheckEquals(FullProb[ 7, 1], 4); CheckEquals(FullProb[ 8, 0], 2); CheckEquals(FullProb[ 8, 1], 0); CheckEquals(FullProb[ 9, 0], 2); CheckEquals(FullProb[ 9, 1], 1); CheckEquals(FullProb[10, 0], 2); CheckEquals(FullProb[10, 1], 3); CheckEquals(FullProb[11, 0], 2); CheckEquals(FullProb[11, 1], 4); CheckEquals(FullProb[12, 0], 3); CheckEquals(FullProb[12, 1], 0); CheckEquals(FullProb[13, 0], 3); CheckEquals(FullProb[13, 1], 1); CheckEquals(FullProb[14, 0], 3); CheckEquals(FullProb[14, 1], 2); CheckEquals(FullProb[15, 0], 3); CheckEquals(FullProb[15, 1], 4); CheckEquals(FullProb[16, 0], 4); CheckEquals(FullProb[16, 1], 0); CheckEquals(FullProb[17, 0], 4); CheckEquals(FullProb[17, 1], 1); CheckEquals(FullProb[18, 0], 4); CheckEquals(FullProb[18, 1], 2); CheckEquals(FullProb[19, 0], 4); CheckEquals(FullProb[19, 1], 3); end; procedure TmnMathTestCase.testCombination; var FullComb: mnTIntArrayDim2; begin mnCombination(5, 2, FullComb); CheckEquals(Low(FullComb), 0); CheckEquals(High(FullComb), mnC(5, 2)-1); CheckEquals(Low(FullComb[0]), 0); CheckEquals(High(FullComb[0]), 2-1); CheckEquals(FullComb[0, 0], 0); CheckEquals(FullComb[0, 1], 1); CheckEquals(FullComb[1, 0], 0); CheckEquals(FullComb[1, 1], 2); CheckEquals(FullComb[2, 0], 0); CheckEquals(FullComb[2, 1], 3); CheckEquals(FullComb[3, 0], 0); CheckEquals(FullComb[3, 1], 4); CheckEquals(FullComb[4, 0], 1); CheckEquals(FullComb[4, 1], 2); CheckEquals(FullComb[5, 0], 1); CheckEquals(FullComb[5, 1], 3); CheckEquals(FullComb[6, 0], 1); CheckEquals(FullComb[6, 1], 4); CheckEquals(FullComb[7, 0], 2); CheckEquals(FullComb[7, 1], 3); CheckEquals(FullComb[8, 0], 2); CheckEquals(FullComb[8, 1], 4); CheckEquals(FullComb[9, 0], 3); CheckEquals(FullComb[9, 1], 4); mnCombination(7, 3, FullComb); CheckEquals(Low(FullComb), 0); CheckEquals(High(FullComb), mnC(7, 3)-1); CheckEquals(Low(FullComb[0]), 0); CheckEquals(High(FullComb[0]), 3-1); CheckEquals(FullComb[ 0, 0], 0); CheckEquals(FullComb[ 0, 1], 1); CheckEquals(FullComb[ 0, 2], 2); CheckEquals(FullComb[ 1, 0], 0); CheckEquals(FullComb[ 1, 1], 1); CheckEquals(FullComb[ 1, 2], 3); CheckEquals(FullComb[ 2, 0], 0); CheckEquals(FullComb[ 2, 1], 1); CheckEquals(FullComb[ 2, 2], 4); CheckEquals(FullComb[ 3, 0], 0); CheckEquals(FullComb[ 3, 1], 1); CheckEquals(FullComb[ 3, 2], 5); CheckEquals(FullComb[ 4, 0], 0); CheckEquals(FullComb[ 4, 1], 1); CheckEquals(FullComb[ 4, 2], 6); CheckEquals(FullComb[ 5, 0], 0); CheckEquals(FullComb[ 5, 1], 2); CheckEquals(FullComb[ 5, 2], 3); CheckEquals(FullComb[ 6, 0], 0); CheckEquals(FullComb[ 6, 1], 2); CheckEquals(FullComb[ 6, 2], 4); CheckEquals(FullComb[ 7, 0], 0); CheckEquals(FullComb[ 7, 1], 2); CheckEquals(FullComb[ 7, 2], 5); CheckEquals(FullComb[ 8, 0], 0); CheckEquals(FullComb[ 8, 1], 2); CheckEquals(FullComb[ 8, 2], 6); CheckEquals(FullComb[ 9, 0], 0); CheckEquals(FullComb[ 9, 1], 3); CheckEquals(FullComb[ 9, 2], 4); CheckEquals(FullComb[10, 0], 0); CheckEquals(FullComb[10, 1], 3); CheckEquals(FullComb[10, 2], 5); CheckEquals(FullComb[11, 0], 0); CheckEquals(FullComb[11, 1], 3); CheckEquals(FullComb[11, 2], 6); CheckEquals(FullComb[12, 0], 0); CheckEquals(FullComb[12, 1], 4); CheckEquals(FullComb[12, 2], 5); CheckEquals(FullComb[13, 0], 0); CheckEquals(FullComb[13, 1], 4); CheckEquals(FullComb[13, 2], 6); CheckEquals(FullComb[14, 0], 0); CheckEquals(FullComb[14, 1], 5); CheckEquals(FullComb[14, 2], 6); CheckEquals(FullComb[15, 0], 1); CheckEquals(FullComb[15, 1], 2); CheckEquals(FullComb[15, 2], 3); CheckEquals(FullComb[16, 0], 1); CheckEquals(FullComb[16, 1], 2); CheckEquals(FullComb[16, 2], 4); CheckEquals(FullComb[17, 0], 1); CheckEquals(FullComb[17, 1], 2); CheckEquals(FullComb[17, 2], 5); CheckEquals(FullComb[18, 0], 1); CheckEquals(FullComb[18, 1], 2); CheckEquals(FullComb[18, 2], 6); CheckEquals(FullComb[19, 0], 1); CheckEquals(FullComb[19, 1], 3); CheckEquals(FullComb[19, 2], 4); CheckEquals(FullComb[20, 0], 1); CheckEquals(FullComb[20, 1], 3); CheckEquals(FullComb[20, 2], 5); CheckEquals(FullComb[21, 0], 1); CheckEquals(FullComb[21, 1], 3); CheckEquals(FullComb[21, 2], 6); CheckEquals(FullComb[22, 0], 1); CheckEquals(FullComb[22, 1], 4); CheckEquals(FullComb[22, 2], 5); CheckEquals(FullComb[23, 0], 1); CheckEquals(FullComb[23, 1], 4); CheckEquals(FullComb[23, 2], 6); CheckEquals(FullComb[24, 0], 1); CheckEquals(FullComb[24, 1], 5); CheckEquals(FullComb[24, 2], 6); CheckEquals(FullComb[25, 0], 2); CheckEquals(FullComb[25, 1], 3); CheckEquals(FullComb[25, 2], 4); CheckEquals(FullComb[26, 0], 2); CheckEquals(FullComb[26, 1], 3); CheckEquals(FullComb[26, 2], 5); CheckEquals(FullComb[27, 0], 2); CheckEquals(FullComb[27, 1], 3); CheckEquals(FullComb[27, 2], 6); CheckEquals(FullComb[28, 0], 2); CheckEquals(FullComb[28, 1], 4); CheckEquals(FullComb[28, 2], 5); CheckEquals(FullComb[29, 0], 2); CheckEquals(FullComb[29, 1], 4); CheckEquals(FullComb[29, 2], 6); CheckEquals(FullComb[30, 0], 2); CheckEquals(FullComb[30, 1], 5); CheckEquals(FullComb[30, 2], 6); CheckEquals(FullComb[31, 0], 3); CheckEquals(FullComb[31, 1], 4); CheckEquals(FullComb[31, 2], 5); CheckEquals(FullComb[32, 0], 3); CheckEquals(FullComb[32, 1], 4); CheckEquals(FullComb[32, 2], 6); CheckEquals(FullComb[33, 0], 3); CheckEquals(FullComb[33, 1], 5); CheckEquals(FullComb[33, 2], 6); CheckEquals(FullComb[34, 0], 4); CheckEquals(FullComb[34, 1], 5); CheckEquals(FullComb[34, 2], 6); end; initialization // Register any test cases with the test runner RegisterTest(TmnMathTestCase.Suite); end.
unit u_qip_plugin; interface uses u_plugin_info, u_plugin_msg, u_common, u_BasePlugin, Classes,SysUtils, unitMessage,Dynamic_Bass; const PLUGIN_VER_MAJOR = 1; PLUGIN_VER_MINOR = 0; PLUGIN_NAME : WideString = 'Говорун'; PLUGIN_HINT : WideString = 'Птица-говорун для QIP'; PLUGIN_AUTHOR : WideString = 'CkEsc'; PLUGIN_DESC : WideString = 'Проговаривает всё происходящее в QIP'; DOWNLOAD_ATTEMPTS = 5; DOWNLOAD_ATTEMPTS_DELAY = 500; TTS_URL: WideString ='http://translate.google.com/translate_tts?tl=ru&q='; type TQipPlugin = class(TBaseQipPlugin) private phraseCounter:Integer; public procedure GetPluginInformation(var VersionMajor: Word; var VersionMinor: Word; var PluginName: PWideChar; var Creator: PWideChar; var Description: PWideChar; var Hint: PWideChar); override; procedure InitPlugin;override; procedure FinalPlugin;override; function MessageReceived(const AMessage: TQipMsgPlugin; var ChangeMessageText: WideString): Boolean;override; procedure Say(Text: WideString); end; implementation procedure TQipPlugin.InitPlugin; var BassInfo: BASS_INFO; begin inherited; //инициализация звука Load_BASSDLL('bass.dll'); BASS_Init(1, 44100, BASS_DEVICE_3D, 0, nil); BASS_Start; BASS_GetInfo(BassInfo); end; procedure TQipPlugin.FinalPlugin; begin inherited; BASS_Stop; BASS_Free; Unload_BASSDLL; end; procedure TQipPlugin.GetPluginInformation(var VersionMajor, VersionMinor: Word; var PluginName, Creator, Description, Hint: PWideChar); begin inherited; VersionMajor := PLUGIN_VER_MAJOR; VersionMinor := PLUGIN_VER_MINOR; Creator := PWideChar(PLUGIN_AUTHOR); PluginName := PWideChar(PLUGIN_NAME); Hint := PWideChar(PLUGIN_HINT); Description := PWideChar(PLUGIN_DESC); end; function TQipPlugin.MessageReceived(const AMessage: TQipMsgPlugin; var ChangeMessageText: WideString): Boolean; begin Say(ChangeMessageText); result:=True; end; procedure TQipPlugin.Say(Text: WideString); var phrase:TPhrase; thread:TPhraseThread; id:string; begin id:= IntToStr(phraseCounter); inc(phraseCounter); phrase:=TPhrase.Create(Text); thread:=TPhraseThread.Create(id,phrase); thread.Priority:=tpLower; thread.FreeOnTerminate:=true; thread.Resume; end; end.
unit LaunchPatch; {$mode objfpc}{$H+} interface uses Classes, SysUtils, BaseModel; type IBaseLaunchPatch = interface(IBaseModel) ['{7DC64C34-50AB-48E2-927D-E6206AA28A45}'] function GetLarge: string; function GetSmall: string; procedure SetLarge(AValue: string); procedure SetSmall(AValue: string); end; ILaunchPatch = interface(IBaseLaunchPatch) ['{27E37272-FB24-488B-BF7F-FD9BF63F5E12}'] property Large: string read GetLarge write SetLarge; property Small: string read GetSmall write SetSmall; end; function NewLaunchPatch: ILaunchPatch; implementation uses Variants; type { TLaunchPatch } TLaunchPatch = class(TBaseModel, ILaunchPatch) private FLarge: string; FSmall: string; function GetLarge: string; function GetSmall: string; procedure SetLarge(AValue: string); procedure SetLarge(AValue: Variant); procedure SetSmall(AValue: string); procedure SetSmall(AValue: Variant); public function ToString: string; override; published property large: Variant write SetLarge; property small: Variant write SetSmall; end; function NewLaunchPatch: ILaunchPatch; begin Result := TLaunchPatch.Create; end; { TLaunchPatch } function TLaunchPatch.GetLarge: string; begin Result := FLarge; end; function TLaunchPatch.GetSmall: string; begin Result := FSmall; end; procedure TLaunchPatch.SetLarge(AValue: string); begin FLarge := AValue; end; procedure TLaunchPatch.SetLarge(AValue: Variant); begin if VarIsNull(AValue) then begin FLarge := ''; end else if VarIsStr(AValue) then FLarge := AValue; end; procedure TLaunchPatch.SetSmall(AValue: string); begin FSmall := AValue; end; procedure TLaunchPatch.SetSmall(AValue: Variant); begin if VarIsNull(AValue) then begin FSmall := ''; end else if VarIsStr(AValue) then FSmall := AValue; end; function TLaunchPatch.ToString: string; begin Result := Format('' + 'Large: %s' + LineEnding + 'Small: %s' , [ GetLarge, GetSmall ]); end; end.
Unit Defines; Interface Uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ImgList, Vcl.Menus, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.OleCtrls, SHDocVw, Vcl.ComCtrls, Vcl.Buttons; Const FAILD_INITIALIZE = 'Failed to initialize.'; FAILD_OPEN = 'Failed to open the file.'; FAILED_FOUND_FLASH = 'Error occurs, please contact us.'; UPDATE_NOW = 'New version detected, do you want to update?'; NO_IMAGE_FILE = 'Does not support the file or the file is not a valid image file.'; ORI_SIZE = 'Use the original video size:<a id="original">%d x %d</a>'#13'Click <a id="crop">here to crop video.</a>'; ABORT_EXPORT = 'Are you sure to abort the recording?'; FOLDER_HINT = 'Output Folder(Click link to open folder):'#13#10'<a>%s</a>'; Const DevelopAddress = 'http://www.vmeisoft.com/develop/'; SuggestAddress = 'http://www.vmeisoft.com/suggest/'; RegisterAddress = 'http://www.vmeisoft.com/register/thanks.php'; Var APP_TITLE: String = 'VMeisoft Video Converter and Video Editor'; Const WATR_HINT = 'Video output size:%d*%d, Watermark image size:%d*%d'; AD_HINT = 'Video output size:%d*%d, Advertisement image size:%d*%d'; Var g_IsRegistered: Integer; // 0-Trail; 1-Registered; 2-Free Const SELECT_WATERMARK = 'Select Watermark Picture'; SELECT_AD = 'Select Advertisement Picture'; Const PICTURE_FILTERS = 'All|*.gif;*.png;*.jpg;*.jpeg;*.bmp;*.tif;*.tiff;*.ico;*.emf;*.wmf|' + 'JPEG Image File|*.jpg;*.jpeg|' + 'Bitmaps|*.bmp|' + 'Portable Network Graphics|*.png|' + 'GIF Image|*.gif|' + 'TIFF Images|*.tif;*.tiff|' + 'Icons|*.ico|' + 'Enhanced Metafiles|*.emf|' + 'Metafiles|*.wmf' + 'All Files|*.*'; PICTURE_ENCODER_FILTERS = 'Bitmap|*.bmp|' + 'JPEG Image File |*.jpg|' + 'Portable Network Graphics|*.png|' + 'TIFF Images|*.tif|' + 'GIF Image|*.gif'; AUDIO_FILTERS = '*.3ga;*.669;' + '*.a52;*.aac;*.ac3;*.adt;*.adts;*.aif;*.aifc;*.aiff;*.amr;*.aob;*.ape;*.asf;*.au;*.awb;' + '*.caf;*.cda;' + '*.dts;' + '*.eac3;' + '*.flac;' + '*.it;' + '*.m2a;*.m3u;*.m4a;*.m4p;*.mid;*.midi;*.mka;*.mlp;*.mod;*.mp1;*.mp2;*.mp3;*.mpc;' + '*.oga;*.ogg;*.oma;' + '*.qcp;' + '*.rmi;' + '*.s3m;*.snd;*.spx;' + '*.thd;*.tta;' + '*.voc;*.vqf;' + '*.w64;*.wav;*.wax;*.wma;*.wma;*.wv;' + '*.xa;*.xm'; VIDEO_FILE_FILTER = '*.3g2;*.3gp;*.3gp2;*.3gpp;' + '*.amv;*.asf;*.asx;*.avi;' + '*.bin;' + '*.dat;*.divx;*.drc;*.dv;*.dvr-ms;' + '*.f4v;*.f4v;*.flv;*.flv;' + '*.gxf;' + '*.h264;*.hdmov;' + '*.iso;*.ivf;' + '*.m1v;*.m2t;*.m2ts;*.m2v;*.m4v;*.mjp;*.mjpg;*.mkv;*.mod;*.mov;*.movie;*.mp2;*.mp2v;*.mp4;*.mp4v;*.mpa;*.mpe;*.mpeg;*.mpeg1;*.mpeg2;*.mpeg4;*.mpg;*.mpv2;*.mpv4;*.mts;*.mtv;*.mxf;*.mxg;' + '*.nsv;*.nuv;' + '*.ogg;*.ogm;*.ogv;*.ogx;' + '*.ps;' + '*.ram;*.rec;*.rm;*.rmm;*.rmvb;*.rpm;' + '*.swf;' + '*.tod;*.ts;*.tts;' + '*.vob;*.vro;' + '*.webm;*.wm;*.wmd;*.wmp;*.wmv;*.wmv;*.wmx;*.wmz;*.wpl;*.wv;' + '*.yuv'; MOVIE_FILE_FILTER = 'Video Files|' + VIDEO_FILE_FILTER + '|' + 'AVI Video|*.avi|' + 'DVD file|*.vob|' + 'Flash Video File|*.flv;*.f4v|' + 'MPEG Video|*.mpg;*.mpe;*.mpeg;*.m1v;*.m2v;*.dat;*.vob;*.mod;*.h264|' + 'MPEG-4 Video|*.mp4;*.m4v|' + 'MPEG-TS Files|*.m2ts;*.m2t;*.mts;*.ts;*.tod|' + 'Windows Media Video|*.wmv;*.asf|' + 'Real Media Files|*.rm;*.rmvb|' + 'QuickTime Movie|*.mov;*.qt;*.mp4;*.m4v;*.dv;*.3gp;*.3g2|' + '3GP Video|*.3gp;*.3g2;*.3gpp;*.3gp2|' + 'Digital Video|*.dv|' + 'All Files|*.*' ; SUBTITLE_FILE_FILTER = 'Subtitle Files|' + '*.utf;*.utf8;*.utf-8;*.sub;*.srt;*.smi;*.rt;*.txt;*.ssa;*.aqt;*.jss;*.js;*.ass;' + '*.vtt;' + '|' + 'All Files|*.*' ; Const FRAME_START_FMT = 'From Frame:%d'; FRAME_STOP_FMT = 'End Frame:%d'; TOTAL_FRAME_FRAME = 'Total Frame:%d'; Const {$IFNDEF DEBUG} DLL_NAME = 'VideoConverter.dll'; {$ELSE} {$IFDEF WIN64} DLL_NAME = 'E:\VideoConverter\src\x64\Release\VideoConverter.dll'; {$ELSE} DLL_NAME = 'E:\VideoConverter\src\Debug\VideoConverter.dll'; {$ENDIF} {$ENDIF} Implementation End.
unit UFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ToolWin, StdCtrls, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, ULEDFont, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxLabel, cxMaskEdit, cxDropDownEdit, UMgrdOPCTunnels, ExtCtrls, IdTCPServer, IdContext, IdGlobal, UBusinessConst, ULibFun, Menus, cxButtons, UMgrSendCardNo, USysLoger, cxCurrencyEdit, dxSkinsCore, dxSkinsDefaultPainters, cxSpinEdit, DateUtils, dOPCIntf, dOPCComn, dOPCDA, dOPC, Activex, StrUtils, USysConst; type TFrame1 = class(TFrame) ToolBar1: TToolBar; ToolButton2: TToolButton; btnPause: TToolButton; ToolButton6: TToolButton; ToolButton9: TToolButton; ToolButton10: TToolButton; ToolButton1: TToolButton; GroupBox1: TGroupBox; GroupBox2: TGroupBox; EditValue: TLEDFontNum; GroupBox3: TGroupBox; cxLabel4: TcxLabel; EditBill: TcxComboBox; cxLabel5: TcxLabel; EditTruck: TcxComboBox; cxLabel7: TcxLabel; EditCusID: TcxComboBox; cxLabel8: TcxLabel; EditStockID: TcxComboBox; cxLabel6: TcxLabel; EditMaxValue: TcxTextEdit; cxLabel1: TcxLabel; editPValue: TcxTextEdit; cxLabel2: TcxLabel; editZValue: TcxTextEdit; editNetValue: TLEDFontNum; editBiLi: TLEDFontNum; cxLabel3: TcxLabel; cxLabel9: TcxLabel; BtnStop: TButton; BtnStart: TButton; dOPCServer: TdOPCServer; StateTimer: TTimer; MemoLog: TMemo; cxLabel10: TcxLabel; EditUseTime: TcxTextEdit; DelayTimer: TTimer; procedure BtnStopClick(Sender: TObject); procedure BtnStartClick(Sender: TObject); procedure StateTimerTimer(Sender: TObject); procedure DelayTimerTimer(Sender: TObject); private { Private declarations } FCardUsed: string; //卡片类型 FUIData: TLadingBillItem; //界面数据 FOPCTunnel: PPTOPCItem; //OPC通道 FHasDone, FSetValue, FUseTime: Double; FDataLarge: Double;//放大倍数 procedure SetUIData(const nReset: Boolean; const nOnlyData: Boolean = False); //设置界面数据 procedure SetTunnel(const Value: PPTOPCItem); procedure WriteLog(const nEvent: string); procedure OnDatachange(Sender: TObject; ItemList: TdOPCItemList); procedure SyncReadValues(const FromCache: boolean); procedure Get_Card_Message(var Message: TMessage); message WM_HAVE_CARD ; public FrameId:Integer; //PLC通道 FIsBusy: Boolean; //占用标识 FSysLoger : TSysLoger; FCard: string; FLastValue,FControl : Double; property OPCTunnel: PPTOPCItem read FOPCTunnel write SetTunnel; procedure LoadBillItems(const nCard: string); //读取交货单 procedure StopPound; end; implementation {$R *.dfm} uses USysBusiness, USysDB, UDataModule, UFormInputbox, UFormCtrl, main; procedure TFrame1.Get_Card_Message(var Message: TMessage); Begin EditBill.Text := FCard; LoadBillItems(EditBill.Text); End ; //Parm: 磁卡或交货单号 //Desc: 读取nCard对应的交货单 procedure TFrame1.LoadBillItems(const nCard: string); var nStr,nTruck: string; nBills: TLadingBillItems; nRet,nHisMValueControl: Boolean; nIdx,nSendValue: Integer; nVal, nPreKD: Double; nEvent,nEID:string; nItem : TdOPCItem; begin if Assigned(FOPCTunnel.FOptions) And (UpperCase(FOPCTunnel.FOptions.Values['SendToPlc']) = sFlag_Yes) then begin WriteLog('非OPC启动,退出操作'); Exit; end; if DelayTimer.Enabled then begin nStr := '请勿频繁刷卡'; WriteLog(nStr); LineClose(FOPCTunnel.FID, sFlag_Yes); ShowLedText(FOPCTunnel.FID, nStr); SetUIData(True); Exit; end; FDataLarge := 1; if Assigned(FOPCTunnel.FOptions) And (IsNumber(FOPCTunnel.FOptions.Values['DataLarge'], True)) then begin FDataLarge := StrToFloat(FOPCTunnel.FOptions.Values['DataLarge']); end; if Assigned(FOPCTunnel.FOptions) And (UpperCase(FOPCTunnel.FOptions.Values['ClearLj']) = sFlag_Yes) then begin if StrToFloatDef(EditValue.Text, 0) > 0.1 then begin nStr := '请清除累计量'; WriteLog(nStr); LineClose(FOPCTunnel.FID, sFlag_Yes); ShowLedText(FOPCTunnel.FID, nStr); SetUIData(True); Exit; end; end; WriteLog('接收到卡号:' + nCard); FCard := nCard; nRet := GetLadingBills(nCard, sFlag_TruckBFP, nBills); if (not nRet) or (Length(nBills) < 1) then begin nStr := '读取磁卡信息失败,请联系管理员'; WriteLog(nStr); SetUIData(True); Exit; end; //获取最大限载值 //nBills[0].FMData.FValue := StrToFloatDef(GetLimitValue(nBills[0].FTruck),0); FUIData := nBills[0]; if Assigned(FOPCTunnel.FOptions) And (UpperCase(FOPCTunnel.FOptions.Values['NoHasDone']) = sFlag_Yes) then FHasDone := 0 else FHasDone := ReadDoneValue(FUIData.FID, FUseTime); FSetValue := FUIData.FValue; nHisMValueControl := False; if Assigned(FOPCTunnel.FOptions) And (UpperCase(FOPCTunnel.FOptions.Values['TruckHzValueControl']) = sFlag_Yes) then nHisMValueControl := True; if nHisMValueControl then begin nVal := GetTruckSanMaxLadeValue(FUIData.FTruck); if (nVal > 0) and (FUIData.FValue > nVal) then//开单量大于系统设定最大量 begin EditMaxValue.Text := Format('%.2f', [nVal]); FSetValue := nVal; nEvent := '车辆[ %s ]交货单[ %s ],' + '开单量[ %.2f ]大于核载量[ %.2f ],调整后开单量[ %.2f ].'; nEvent := Format(nEvent, [FUIData.FTruck, FUIData.FID, FUIData.FValue, nVal, nVal]); WriteLog(nEvent); end; end; nVal := GetSanMaxLadeValue; if (nVal > 0) and (FUIData.FValue > nVal) then//开单量大于系统设定最大量 begin EditMaxValue.Text := Format('%.2f', [nVal]); FSetValue := nVal; nEvent := '车辆[ %s ]交货单[ %s ],' + '开单量[ %.2f ]大于系统设定最大量[ %.2f ],调整后开单量[ %.2f ].'; nEvent := Format(nEvent, [FUIData.FTruck, FUIData.FID, FUIData.FValue, nVal, nVal]); WriteLog(nEvent); end; nVal := ReadTruckHisMValueMax(FUIData.FTruck); nPreKD := GetSanPreKD; nHisMValueControl := False; if Assigned(FOPCTunnel.FOptions) And (UpperCase(FOPCTunnel.FOptions.Values['HisMValueControl']) = sFlag_Yes) then nHisMValueControl := True; if nHisMValueControl and (nVal > 0) and ((FUIData.FPData.FValue + FUIData.FValue) > nVal) then begin FSetValue := nVal - FUIData.FPData.FValue - nPreKD; //生成事件 if Assigned(FOPCTunnel.FOptions) And (UpperCase(FOPCTunnel.FOptions.Values['SendMsg']) = sFlag_Yes) then begin try nEID := FUIData.FID + 'H'; nStr := 'Delete From %s Where E_ID=''%s'''; nStr := Format(nStr, [sTable_ManualEvent, nEID]); FDM.ExecuteSQL(nStr); nEvent := '车辆[ %s ]交货单[ %s ]装车量已调整,历史最大毛重[ %.2f ],' + '当前皮重[ %.2f ],开单量[ %.2f ],预扣量[ %.2f ],调整后装车量[ %.2f ].'; nEvent := Format(nEvent, [FUIData.FTruck, FUIData.FID, nVal, FUIData.FPData.FValue, FUIData.FValue, nPreKD, FSetValue]); WriteLog(nEvent); nStr := MakeSQLByStr([ SF('E_ID', nEID), SF('E_Key', ''), SF('E_From', sFlag_DepJianZhuang), SF('E_Event', nEvent), SF('E_Solution', sFlag_Solution_OK), SF('E_Departmen', sFlag_DepDaTing), SF('E_Date', sField_SQLServer_Now, sfVal) ], sTable_ManualEvent, '', True); FDM.ExecuteSQL(nStr); except on E: Exception do begin WriteLog('保存事件失败:' + e.message); end; end; end; end else begin if (FUIData.FValue - nPreKD) > 0 then begin FSetValue := FSetValue - nPreKD; nEvent := '车辆[ %s ]交货单[ %s ],' + '开单量[ %.2f ],预扣量[ %.2f ],调整后装车量[ %.2f ].'; nEvent := Format(nEvent, [FUIData.FTruck, FUIData.FID, FUIData.FValue, nPreKD, FSetValue]); WriteLog(nEvent); end; end; if FHasDone >= FSetValue then begin nStr := '交货单[ %s ]设置量[ %.2f ],已装量[ %.2f ],无法继续装车'; nStr := Format(nStr, [FUIData.FID, FSetValue, FHasDone]); WriteLog(nStr); LineClose(FOPCTunnel.FID, sFlag_Yes); ShowLedText(FOPCTunnel.FID, '装车量已达到设置量'); SetUIData(True); Exit; end; EditValue.Text := Format('%.2f', [FHasDone]); SetUIData(False); try if FDataLarge > 0 then begin nSendValue := Round((FSetValue - FHasDone)/ FDataLarge); FormMain.gOPCServer.OPCGroups[FrameId].OPCItems[0].WriteSync(nSendValue); WriteLog(FOPCTunnel.FID +'发送提货量:'+ IntToStr(nSendValue)); end else begin FormMain.gOPCServer.OPCGroups[FrameId].OPCItems[0].WriteSync(FSetValue - FHasDone); WriteLog(FOPCTunnel.FID +'发送提货量:'+ FloatToStr(FUIData.FValue - FHasDone)); end; if Trim(FOPCTunnel.FTruckTag) <> '' then begin nItem := FormMain.gOPCServer.OPCGroups[FrameId].OPCItems.FindOPCItem(FOPCTunnel.FTruckTag); if nItem <> nil then begin nTruck := ''; nStr := FUIData.FTruck; for nIdx := 1 to Length(nStr) do begin if IsNumber(nStr[nIdx], False) then nTruck := nTruck + nStr[nIdx]; end; if nTruck <> '' then begin nItem.WriteSync(nTruck); WriteLog(FOPCTunnel.FID +'发送车牌号:'+ FUIData.FTruck + '格式化后:' + nTruck); end; end; end; if Trim(FOPCTunnel.FStartTag) <> '' then begin for nIdx := 1 to 30 do begin Sleep(100); Application.ProcessMessages; end; FormMain.gOPCServer.OPCGroups[FrameId].OPCItems[2].WriteSync(FOPCTunnel.FStartOrder); for nIdx := 1 to 30 do begin Sleep(100); Application.ProcessMessages; end; FormMain.gOPCServer.OPCGroups[FrameId].OPCItems[2].WriteSync(FOPCTunnel.FStopOrder); end; LineClose(FOPCTunnel.FID, sFlag_No); WriteLog(FOPCTunnel.FID +'发送启动命令成功'); StateTimer.Tag := 0; except on E: Exception do begin StopPound; WriteLog(FOPCTunnel.FID +'启动失败,原因为:' + e.Message); ShowLedText(FOPCTunnel.FID, '启动失败,请重新刷卡'); end; end; end; procedure TFrame1.SetUIData(const nReset: Boolean; const nOnlyData: Boolean = False); var nItem: TLadingBillItem; begin if nReset then begin FillChar(nItem, SizeOf(nItem), #0); nItem.FFactory := gSysParam.FFactNum; FUIData := nItem; if nOnlyData then Exit; EditValue.Text := '0.00'; editNetValue.Text := '0.00'; editBiLi.Text := '0'; EditUseTime.Text := '0'; EditBill.Properties.Items.Clear; end; with FUIData do begin EditBill.Text := FID; EditTruck.Text := FTruck; EditStockID.Text := FStockName; EditCusID.Text := FCusName; //EditMaxValue.Text := Format('%.2f', [FMData.FValue]); EditPValue.Text := Format('%.2f', [FPData.FValue]); EditZValue.Text := Format('%.2f', [FValue]); end; end; procedure TFrame1.WriteLog(const nEvent: string); begin if MemoLog.Lines.Count > 100 then MemoLog.Clear; MemoLog.Lines.Add(nEvent); FSysLoger.AddLog(TFrame, '定置装车OPC主单元', nEvent); end; procedure TFrame1.SetTunnel(const Value: PPTOPCItem); begin FOPCTunnel := Value; SetUIData(true); end; procedure TFrame1.StopPound; var nItemList: TdOPCItemList; nOPCServer: TdOPCServer; nGroup: TdOPCGroup; nIdx: Integer; begin if Assigned(FOPCTunnel.FOptions) And (UpperCase(FOPCTunnel.FOptions.Values['SendToPlc']) = sFlag_Yes) then begin WriteLog('非OPC启动,退出操作'); Exit; end; if DelayTimer.Enabled then begin Exit; end; if Assigned(FOPCTunnel.FOptions) And (UpperCase(FOPCTunnel.FOptions.Values['NoHasDone']) <> sFlag_Yes) then begin DelayTimer.Tag := 0; DelayTimer.Enabled := True; end; FHasDone := 0; FUseTime := 0; LineClose(FOPCTunnel.FID, sFlag_Yes); SetUIData(true); if Trim(FOPCTunnel.FStopTag) <> '' then begin FormMain.gOPCServer.OPCGroups[FrameId].OPCItems[3].WriteSync(FOPCTunnel.FStartOrder); for nIdx := 1 to 30 do begin Sleep(100); Application.ProcessMessages; end; FormMain.gOPCServer.OPCGroups[FrameId].OPCItems[3].WriteSync(FOPCTunnel.FStopOrder); WriteLog(FOPCTunnel.FID +'发送停止命令成功'); end; end; procedure TFrame1.BtnStopClick(Sender: TObject); begin try StopPound; except on E: Exception do begin WriteLog('通道' + FOPCTunnel.FID + '停止称重失败,原因:' + e.Message); end; end; end; procedure TFrame1.BtnStartClick(Sender: TObject); var nStr: string; begin nStr := FCard; if not ShowInputBox('请输入磁卡号:', '提示', nStr) then Exit; try LoadBillItems(nStr); except on E: Exception do begin WriteLog('通道' + FOPCTunnel.FID + '启动称重失败,原因:' + e.Message); end; end; end; procedure TFrame1.SyncReadValues(const FromCache: boolean); var nItemList: TdOPCItemList; begin nItemList := TdOPCItemList.create(FormMain.gOPCServer.OPCGroups[FrameId].OPCItems); try FormMain.gOPCServer.OPCGroups[FrameId].SyncRead(nil,FromCache); //nGroup.ASyncRead(nil); Application.ProcessMessages; try OnDatachange(self,nItemList); except end; finally if Assigned(nItemList) then nItemList.Free; // !!!!!!!!!!!!! end; end; procedure TFrame1.OnDatachange(Sender: TObject; ItemList: TdOPCItemList); var nIdx: Integer; nValue: Double; nZValue, nBiLi : Double; begin for nIdx := 0 to Itemlist.Count-1 do begin if Itemlist[nIdx].ItemId = FOPCTunnel.FImpDataTag then begin WriteLog(FOPCTunnel.FImpDataTag+':'+Itemlist[nIdx].ValueStr); if IsNumber(Itemlist[nIdx].ValueStr, True) then begin WriteLog('当前已装量' + Itemlist[nIdx].ValueStr + '上次已装量' + FloatToStr(FLastValue)); if FLastValue <= 0 then FLastValue := StrToFloat(Itemlist[nIdx].ValueStr) else begin if Abs(StrToFloat(Itemlist[nIdx].ValueStr) - FLastValue) < FControl then begin WriteLog('累计量变化小于' + FloatToStr(FControl) + ',不做处理'); Continue; end; FLastValue := StrToFloat(Itemlist[nIdx].ValueStr); end; nValue := (StrToFloat(Itemlist[nIdx].ValueStr) + FHasDone) * FDataLarge; EditValue.Text := Format('%.2f', [nValue]); if (Length(Trim(EditBill.Text)) > 0) and (nValue > 0) then begin SaveDoneValue(FUIData.FID, StrToFloatDef(EditValue.Text, 0) ,StrToFloatDef(EditUseTime.Text, 0)); ShowLedText(FOPCTunnel.FID, '当前累计重量:'+ EditValue.Text); end; nZValue := StrToFloatDef(editZValue.Text,0); //票重 nBiLi := 0; if nZValue > 0 then nBiLi := nValue/nZValue *100; //完成比例 editNetValue.Text := EditValue.Text; editBiLi.Text := Format('%.2f',[nBiLi]); end; end else if Itemlist[nIdx].ItemId = FOPCTunnel.FUseTimeTag then begin if IsNumber(Itemlist[nIdx].ValueStr, True) then begin nValue := StrToFloat(Itemlist[nIdx].ValueStr) + FUseTime; EditUseTime.Text := Format('%.2f', [nValue]); end; end; end; end; procedure TFrame1.StateTimerTimer(Sender: TObject); var nInfo: string; nList: TStrings; nItem : TdOPCItem; begin StateTimer.Enabled := False; StateTimer.Tag := StateTimer.Tag + 1; if Assigned(FOPCTunnel.FOptions) And (UpperCase(FOPCTunnel.FOptions.Values['SendToPlc']) = sFlag_Yes) then begin try WriteLog('读取库底计量'); if not ReadBaseWeight(FOPCTunnel.FID, nInfo) then begin StateTimer.Enabled := True; Exit; end; WriteLog('库底计量:' + nInfo); nList := TStringList.Create; try nList.Text := nInfo; EditBill.Text := nList.Values['Bill']; editPValue.Text := nList.Values['PValue']; EditValue.Text := nList.Values['ValueMax']; editZValue.Text := nList.Values['Value']; if EditBill.Text <> '' then begin FormMain.gOPCServer.OPCGroups[FrameId].OPCItems[0].WriteSync(editZValue.Text); WriteLog(FOPCTunnel.FID +'发送提货量:'+ editZValue.Text); FormMain.gOPCServer.OPCGroups[FrameId].OPCItems[1].WriteSync(EditValue.Text); WriteLog(FOPCTunnel.FID +'发送地磅重量:'+ EditValue.Text); if Trim(FOPCTunnel.FTruckTag) <> '' then begin nItem := FormMain.gOPCServer.OPCGroups[FrameId].OPCItems.FindOPCItem(FOPCTunnel.FTruckTag); if nItem <> nil then begin nItem.WriteSync(editPValue.Text); WriteLog(FOPCTunnel.FID +'发送皮重:'+ editPValue.Text); end; end; end; finally nList.Free; end; except on E: Exception do begin WriteLog(e.Message); end; end; end else begin try SyncReadValues(False); except on E: Exception do begin WriteLog('通道' + fOPCTunnel.FID + '读取累计数据失败,原因:' + e.Message); end; end; end; StateTimer.Enabled := True; end; procedure TFrame1.DelayTimerTimer(Sender: TObject); begin DelayTimer.Tag := DelayTimer.Tag + 1; if DelayTimer.Tag >= 10 then begin DelayTimer.Enabled := False; end; end; end.
unit Polynomial; interface uses MathUtils, Procs, SysUtils, Config; type TPolynom = class private items: array of array[0..1] of TTerm; tmpItems: array of array[0..1] of TTerm; procedure AddTermToTmp( t: TTerm ); //function markRemove(index: integer): Term; procedure Pack; procedure Sort; procedure Simplyfy; function StrSign( v: extended ): string; public procedure AddTerm( t: TTerm ); function GetTerm( index: integer ): TTerm; function RemoveTerm( index: integer ): TTerm; procedure Mul( expr: TMathExpr ); overload; procedure Mul( pol: TPolynom ); overload; procedure AddPolynom( expr: TMathExpr ); overload; procedure AddPolynom( pol: TPolynom ); overload; function Calc( x: extended ): extended; function Count: integer; function ToString: string; end; function Lagrange( xyData: array of TXYPoint ): TPolynom; implementation function TPolynom.Count: integer; begin result := Length( items ); end; function TPolynom.StrSign( v: extended ): string; begin if v < 0 then result := '-' else result := '+'; end; procedure TPolynom.AddTerm( t: TTerm ); begin SetLength( items, Length( items ) + 1 ); items[High( items ), 0] := t; items[High( items ), 1].coeff := 0; end; procedure TPolynom.AddTermToTmp( t: TTerm ); begin SetLength( tmpItems, Length( tmpItems ) + 1 ); tmpItems[High( tmpItems ), 0] := t; tmpItems[High( tmpItems ), 1].coeff := 0; end; function TPolynom.getTerm( index: integer ): TTerm; begin result := items[index, 0]; end; function TPolynom.RemoveTerm( index: integer ): TTerm; var i, counter: integer; begin if index = 0 then begin result := items[0, 0]; items := Copy( items, 1, High( items ) ); end else if index = High( items ) then begin result := items[High( items ), 0]; items := Copy( items, 0, High( items ) - 1 ); end else begin SetLength( tmpItems, Length( items ) - 1 ); counter := 0; for i := 0 to High( items ) do if ( i <> index ) then begin tmpItems[counter, 0] := items[i, 0]; inc( counter ); end else result := items[i, 0]; SetLength( items, Length( items ) - 1 ); for i := 0 to High( tmpItems ) do items[i, 0] := tmpItems[i, 0]; end; end; {function TPolynom.markRemove(index: integer): Term; begin items[index, 1].coeff := 1; end;} procedure TPolynom.Pack; var i, newLen: integer; tmpArr: array of TTerm; begin for i := 0 to High( items ) do begin if ( items[i, 1].coeff = 0 ) and ( items[i, 0].coeff <> 0 ) then begin newLen := Length( tmpArr ) + 1; SetLength( tmpArr, newLen ); tmpArr[newLen - 1] := items[i, 0]; end; end; SetLength( items, Length( tmpArr ) ); for i := 0 to High( tmpArr ) do items[i, 0] := tmpArr[i]; end; procedure TPolynom.Simplyfy; var i, newLen: integer; tmpArr: array of TTerm; currTerm: TTerm; begin pack; while true do begin if count > 0 then begin currTerm := removeTerm( 0 ); for i := 0 to High( items ) do begin if items[i, 0].power = currTerm.power then begin items[i, 1].coeff := 1; //mark for delete currTerm.coeff := currTerm.coeff + items[i, 0].coeff; pack; end; end; end else break; newLen := Length( tmpArr ) + 1; SetLength( tmpArr, newLen ); tmpArr[newLen - 1] := currTerm; end; SetLength( items, Length( tmpArr ) ); for i := 0 to High( tmpArr ) do items[i, 0] := tmpArr[i]; pack; end; procedure TPolynom.Sort; var i, j: integer; t: TTerm; begin for i := 0 to High( items ) - 1 do for j := High( items ) downto i + 1 do if items[i, 0].power > items[j, 0].power then begin t.coeff := items[i, 0].coeff; t.power := items[i, 0].power; items[i, 0] := items[j, 0]; items[j, 0] := t; end; end; function TPolynom.ToString: string; var i: integer; s, s1, s2: string; begin //sort; result := ''; for i := High( items ) downto 0 do begin if ( Abs( items[i, 0].coeff ) = 1 ) and ( items[i, 0].power <> 0 ) then s1 := '' else s1 := FloatToStr( Abs( items[i, 0].coeff ) ); if items[i, 0].power = 0 then s2 := '' else if items[i, 0].power = 1 then s2 := 'x' else s2 := 'x' + IntToStr( items[i, 0].power ) + ''; s := s1 + s2; if ( i = High( items ) ) and ( strSign( items[i, 0].coeff ) = '-' ) then s := '-' + s else if i < High( items ) then s := ' ' + strSign( items[i, 0].coeff ) + ' ' + s; result := result + s; end; end; procedure TPolynom.Mul( pol: TPolynom ); var i, j: integer; resultTerm: TTerm; begin if Length( items ) = 0 then exit; if pol.count = 0 then begin SetLength( items, 0 ); exit; end; //SetLength(tmpItems, Length(items) * pol.count); for i := 0 to High( items ) do for j := 0 to pol.count - 1 do begin resultTerm.coeff := items[i, 0].coeff * pol.getTerm( j ).coeff; resultTerm.power := items[i, 0].power + pol.getTerm( j ).power; addTermToTmp( resultTerm ); end; SetLength( items, 0 ); //SetLength(items, Length(tmpItems)); for i := 0 to High( tmpItems ) do addTerm( tmpItems[i, 0] ); tmpItems := nil; simplyfy; end; procedure TPolynom.Mul( expr: TMathExpr ); var i: integer; pol: TPolynom; begin pol := TPolynom.Create; for i := 0 to High( expr ) do pol.addTerm( expr[i] ); mul( pol ); pol.Free; end; procedure TPolynom.AddPolynom( expr: TMathExpr ); var i: integer; begin for i := 0 to High( expr ) do addTerm( expr[i] ); end; procedure TPolynom.AddPolynom( pol: TPolynom ); var i: integer; begin for i := 0 to pol.count - 1 do addTerm( pol.getTerm( i ) ); simplyfy; end; function TPolynom.Calc( x: extended ): extended; var i: integer; begin result := 0; for i := 0 to High( items ) do result := result + items[i, 0].coeff * Stepen( x, items[i, 0].power ); end; function Lagrange( xyData: array of TXYPoint ): TPolynom; var i, j: integer; numerator: TPolynom; denominator: extended; resultPoly: TPolynom; expr: TMathExpr; t: TTerm; s: string; begin resultPoly := TPolynom.Create; if Length( xyData ) = 0 then begin result := nil; exit; end; for i := 0 to High( xyData ) do begin SetLength( expr, 2 ); //numerator := 1; denominator := 1; numerator := TPolynom.Create; t.coeff := 1; t.power := 0; numerator.addTerm( t ); for j := 0 to High( xyData ) do begin if ( j <> i ) then begin expr[0].coeff := 1; expr[0].power := 1; expr[1].coeff := 0 - xyData[j].x; expr[1].power := 0; numerator.mul( expr ); s := numerator.toString; //msgbox(s); //numerator := numerator * (x - xyData[j].x); denominator := denominator * ( xyData[i].x - xyData[j].x ); end; end; if denominator <> 0 then begin SetLength( expr, 1 ); expr[0].coeff := xyData[i].y / denominator; expr[0].power := 0; numerator.mul( expr ); end else msgbox( '0' ); resultPoly.addPolynom( numerator ); end; //msgbox(resultPoly.toString); result := resultPoly; end; end.
/////////////////////////////////////////////////////////////////////////// // Project: CW // Program: cwu.pas // Language: Object Pascal - Delphi ver 3.0 // Support: David Fahey // Date: 01Oct97 // Purpose: Displays a dialog that allows the user to learn the // International Morse code. // History: 01Oct97 Initial coding DAF // 02Oct97 Modified code to work with Windows95 and NT DAF // 13Oct98 Rebuilt using Delphi Ver 4 DAF // 13Oct98 Rebuilt using Delphi 2006 DAF // Notes: None /////////////////////////////////////////////////////////////////////////// unit cwu; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, Tabnotbk, beeperu, codedspu, codesndu, helpu, copycdeu, sendtxtu, aboutu, lightplu, ExtCtrls ; const NCodes = 128 ; {number of codes} dit = 1 ; {duration of dit} dah = 3 ; {duration of dah} AvgWdLen = 5 ; {average word length (characters) } AvgCodeLen = 8 ; {average code length (dits) } type TForm1 = class(TForm) TabbedNotebook1: TTabbedNotebook; MsgText: TEdit; SendButton: TButton; Code: TLabel; CurPos: TLabel; ExitButton: TButton; Label1: TLabel; CpmBox: TComboBox; Label2: TLabel; IcsBox: TComboBox; Label3: TLabel; IwsBox: TComboBox; Label4: TLabel; Label5: TLabel; MorseKeyButton: TButton; GroupBox1: TGroupBox; DispChar: TLabel; ViewCodes: TMemo; CodeGroupBox: TComboBox; Label6: TLabel; SendCharButton: TButton; DisplayCodeCheckBox: TCheckBox; DisplayCode: TLabel; GroupBox2: TGroupBox; Answer: TLabel; Choice1Button: TButton; Choice2Button: TButton; Choice3Button: TButton; Choice4Button: TButton; Choice5Button: TButton; Label7: TLabel; FreqBox: TComboBox; Label8: TLabel; RepeatButton: TButton; Shape1: TShape; HelpButton: TButton; Label9: TLabel; Label10: TLabel; Label11: TLabel; Label12: TLabel; DcCheckBox: TCheckBox; BeginSendingButton: TButton; LetterSent: TLabel; StopSendingButton: TButton; SendTwiceCheckBox: TCheckBox; Shape2: TShape; Label13: TLabel; Label14: TLabel; Label15: TLabel; CopySendButton: TButton; CopyEdit: TEdit; Label16: TLabel; Label17: TLabel; ActualEdit: TEdit; Label18: TLabel; CorrectLabel: TLabel; CopyStopButton: TButton; Button1: TButton; Button2: TButton; Light: TShape; SendWithLight: TCheckBox; SendWithSound: TCheckBox; Msg: TLabel; procedure DCode(sel: string; n: integer) ; function RCode(sel: string; n: integer):string ; procedure SendButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure SendText(s: string) ; procedure ExitButtonClick(Sender: TObject); procedure CpmBoxChange(Sender: TObject); procedure IcsBoxChange(Sender: TObject); procedure IwsBoxChange(Sender: TObject); procedure MorseKeyButtonMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure MorseKeyButtonMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FreqBoxChange(Sender: TObject); procedure SendCharButtonClick(Sender: TObject); procedure Choice1ButtonClick(Sender: TObject); procedure Choice2ButtonClick(Sender: TObject); procedure Choice3ButtonClick(Sender: TObject); procedure Choice4ButtonClick(Sender: TObject); procedure Choice5ButtonClick(Sender: TObject); procedure RepeatButtonClick(Sender: TObject); procedure HelpButtonClick(Sender: TObject); procedure CodeGroupBoxChange(Sender: TObject); procedure DisplayCodeCheckBoxClick(Sender: TObject); procedure BeginSendingButtonClick(Sender: TObject); procedure StopSendingButtonClick(Sender: TObject); procedure SendTwiceCheckBoxClick(Sender: TObject); procedure CopySendButtonClick(Sender: TObject); procedure CopyStopButtonClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure TabbedNotebook1Change(Sender: TObject; NewTab: Integer; var AllowChange: Boolean); procedure SendWithSoundClick(Sender: TObject); procedure SendWithLightClick(Sender: TObject); private { Private declarations } public { Public declarations } end; TCodes = array[1..128] of string ; TSpecNames = array[1..5] of string ; function RepStr(i:integer; c: char): string ; function NTBeep(dwFreq, dwDuration: DWORD): BOOL; stdcall; procedure MyBeep(dwFreq, dwDuration: DWORD) ; procedure SendChar(c: char) ; var Form1: TForm1; Codes: TCodes ; {morse code sequence for characters} freq: integer ; {frequency of sound} cpm: integer ; {characters per minute duration (m/s) } ics: integer ; {duration of inter character space} iws: integer ; {duration of inter word space} st: integer ; {morse key start time} et: integer ; {morse key end time} {Global Variables} CodeStr: string ; {current code string from morse key} CCode: string ; {character code sent in code recognition} Letter: string ; {character sent in random codes} Twice: boolean ; {random codes sent twice} Actual: string ; {copy code actual phrase} DspText: string ; {text to send for send text} DspChar: char ; {sent char for send text} DspPos: integer ; {current char pos for send text} LightOn: boolean ; {status of the light} SendSound: boolean ; {send with sound} SpecNames: TSpecNames ; {names of special characters} CodeDspStarted: boolean ; {code display thread started flag} BeepThread: Beeper ; CodeDspThread: TCodeDsp ; CodeSendThread: TCodeSend ; CopyCodeThread: TCopyCode ; SendTextThread: TSendText ; LightPolThread: TLightPol ; Win32Platform: Integer = 0; Win32MajorVersion: Integer = 0; Win32MinorVersion: Integer = 0; Win32BuildNumber: Integer = 0; implementation function NTBeep; external kernel32 name 'Beep'; {$R *.DFM} function RepStr(i:integer; c: char): string ; var j: integer ; s: string ; begin s := '' ; for j := 1 to i do s := s + c ; result := s ; end ; procedure InitPlatformId ; var OSVersionInfo: TOSVersionInfo ; begin OSVersionInfo.dwOSVersionInfoSize := SizeOf(OSVersionInfo) ; if GetVersionEx(OSVersionInfo) then with OSVersionInfo do begin Win32Platform := dwPlatformId ; Win32MajorVersion := dwMajorVersion ; Win32MinorVersion := dwMinorVersion ; Win32BuildNumber := dwBuildNumber ; end ; end ; procedure StartSound(dwFreq: DWORD) ; const FOscillator = 1193180 ; var freq: integer ; freqh,freql: byte ; begin if SendSound then begin freq := dwFreq ; { massage the frequency for the 8254 chip } freq := FOscillator div freq ; freqh := freq div 256 ; freql := freq mod 256 ; { Start a tone on the 8254 timer chip } asm { set the frequency in the 8254 } mov al,10110110b { counter 2, low-order and high-order counter byte } { mode 3, binary counnting } out 43h,al { write control register } mov al,freql { transfer low-order counter byte to al } out 42h,al { output low-order counter byte } mov al,freqh { transfer high-order counter byte to al } out 42h,al { output high-order counter byte } { turn on the speaker } in al,61h { read old value of port B } or al,00000011b { set bits 0 and 1, bits 2-7 unchanged } out 61h,al { output byte with set bits 0 and 1 to port B } end ; end ; end ; procedure EndSound ; begin asm { turn off the speaker } in al,61h { read old value of port B } and al,11111100b { turn bits 0 and 1 off, bits 2-7 unchanged } out 61h,al { output byte with cleared bits 0 and 1 to port B } end ; end ; procedure MyBeep(dwFreq, dwDuration: DWORD) ; begin LightOn := True ; if Win32Platform = VER_PLATFORM_WIN32_NT then { on windows NT } begin if SendSound then NTBeep(dwFreq,dwDuration) { let winNT make a noise } else Sleep(dwDuration) ; { do a system wait } end else { on windows95... or win3.1 - we have to make the noise ourselves } begin { ENTERING THE TWILIGHT ZONE } StartSound(dwFreq) ; Sleep(dwDuration) ; { do a system wait } EndSound ; end ; LightOn := False ; end ; procedure SendChar(c: char) ; var j: integer ; mc: string ; begin mc := Codes[ord(c)] ; {look up code for character} for j := 1 to length(mc) do begin if mc[j] = '-' then begin MyBeep(freq,dah*cpm) ; Sleep(dit*cpm) ; {sleep after tone} end else if mc[j] = '.' then begin MyBeep(freq,dit*cpm) ; Sleep(dit*cpm) ; {sleep after tone} end else Sleep(iws*cpm) ; {sleep during inter word space} end ; Sleep(ics*cpm) ; {sleep during inter character space} end ; procedure SendStr(s: string) ; var i: integer ; begin for i := 1 to length(s) do SendChar(s[i]) ; end ; procedure TForm1.FormCreate(Sender: TObject); var i: integer ; begin freq := 1000 ; {initial frequency of sound} cpm := 60000 div (6*((AvgWdLen*AvgCodeLen)+1)) ; {chars/min duration (m/s) } ics := 3 ; {duration of inter character space} iws := 5 ; {duration of inter word space} CodeStr := '' ; CodeDspStarted := False ; Twice := False ; SendSound := True ; {send with sound} Codes[ord('a')] := '.-' ; Codes[ord('A')] := '.-' ; Codes[ord('b')] := '-...' ; Codes[ord('B')] := '-...' ; Codes[ord('c')] := '-.-.' ; Codes[ord('C')] := '-.-.' ; Codes[ord('d')] := '-..' ; Codes[ord('D')] := '-..' ; Codes[ord('e')] := '.' ; Codes[ord('E')] := '.' ; Codes[ord('f')] := '..-.' ; Codes[ord('F')] := '..-.' ; Codes[ord('g')] := '--.' ; Codes[ord('G')] := '--.' ; Codes[ord('h')] := '....' ; Codes[ord('H')] := '....' ; Codes[ord('i')] := '..' ; Codes[ord('I')] := '..' ; Codes[ord('j')] := '.---' ; Codes[ord('J')] := '.---' ; Codes[ord('k')] := '-.-' ; Codes[ord('K')] := '-.-' ; Codes[ord('l')] := '.-..' ; Codes[ord('L')] := '.-..' ; Codes[ord('m')] := '--' ; Codes[ord('M')] := '--' ; Codes[ord('n')] := '-.' ; Codes[ord('N')] := '-.' ; Codes[ord('o')] := '---' ; Codes[ord('O')] := '---' ; Codes[ord('p')] := '.--.' ; Codes[ord('P')] := '.--.' ; Codes[ord('q')] := '--.-' ; Codes[ord('Q')] := '--.-' ; Codes[ord('r')] := '.-.' ; Codes[ord('R')] := '.-.' ; Codes[ord('s')] := '...' ; Codes[ord('S')] := '...' ; Codes[ord('t')] := '-' ; Codes[ord('T')] := '-' ; Codes[ord('u')] := '..-' ; Codes[ord('U')] := '..-' ; Codes[ord('v')] := '...-' ; Codes[ord('V')] := '...-' ; Codes[ord('w')] := '.--' ; Codes[ord('W')] := '.--' ; Codes[ord('x')] := '-..-' ; Codes[ord('X')] := '-..-' ; Codes[ord('y')] := '-.--' ; Codes[ord('Y')] := '-.--' ; Codes[ord('z')] := '--..' ; Codes[ord('Z')] := '--..' ; Codes[ord('1')] := '.----' ; Codes[ord('2')] := '..---' ; Codes[ord('3')] := '...--' ; Codes[ord('4')] := '....-' ; Codes[ord('5')] := '.....' ; Codes[ord('6')] := '-....' ; Codes[ord('7')] := '--...' ; Codes[ord('8')] := '---..' ; Codes[ord('9')] := '----.' ; Codes[ord('0')] := '-----' ; Codes[ord('.')] := '.-.-.-' ; Codes[ord(',')] := '--..--' ; Codes[ord('?')] := '..--..' ; Codes[ord('/')] := '-..-.' ; {special codes are userping these characters} Codes[ord('[')] := '.-...' ; {wait AS} Codes[ord('\')] := '-...-' ; {pause BT} Codes[ord(']')] := '.-.-.' ; {end of message AR} Codes[ord('^')] := '...-.-' ; {end of work VA} Codes[ord('_')] := '-.-' ; {invitation to transmit K} SpecNames[1] := 'Wait-AS' ; SpecNames[2] := 'Pause-BT' ; SpecNames[3] := 'End message-AR' ; SpecNames[4] := 'End of work-VA' ; SpecNames[5] := 'Transmit-K' ; {blank character indicates inter word gap} Codes[ord(' ')] := ' ' ; {set up view codes memo area} for i := 1 to NCodes do begin if (Codes[i] <> '') and (Codes[i] <> ' ') and (i < ord('[')) then ViewCodes.Lines.Add(chr(i)+' = '+Codes[i]) ; end ; ViewCodes.Lines.Add('Wait (AS) = '+Codes[ord('[')]) ; ViewCodes.Lines.Add('Pause (BT) = '+Codes[ord('\')]) ; ViewCodes.Lines.Add('End of message (AR) = '+Codes[ord(']')]) ; ViewCodes.Lines.Add('End of work (VA) = '+Codes[ord('^')]) ; ViewCodes.Lines.Add('Invitation to transmit (K) = '+Codes[ord('_')]) ; InitPlatformId ; DCode('SEHI ',4) ; Randomize ; end; procedure TForm1.SendText(s: string) ; var i: integer ; k: integer ; mc: string ; begin k := length(s) ; for i := 1 to k do begin mc := Codes[ord(s[i])] ; {look up code for character} if DcCheckBox.State = cbChecked then Code.Caption := s[i]+' = '+mc ; CurPOs.Caption := RepStr(i-1,'-')+s[i]+RepStr(k-i,'-') ; Form1.Update ; SendChar(s[i]) ; end ; end ; procedure TForm1.SendButtonClick(Sender: TObject); begin Code.Caption := '' ; CurPOs.Caption := '' ; {start a thread to send the text} DspText := MsgText.Text ; SendTextThread := TSendText.Create(False) ; end; procedure TForm1.ExitButtonClick(Sender: TObject); begin Form1.Close ; end; procedure TForm1.CpmBoxChange(Sender: TObject); begin cpm := 60000 div (StrToInt(CpmBox.Text)*((AvgWdLen * AvgCodeLen)+1) ) ; end; procedure TForm1.IcsBoxChange(Sender: TObject); begin ics := StrToInt(IcsBox.Text) ; end; procedure TForm1.IwsBoxChange(Sender: TObject); begin iws := StrToInt(IwsBox.Text) ; end; procedure TForm1.MorseKeyButtonMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Hour, Min, Sec, MSec: word ; begin DecodeTime(Time,Hour,Min,Sec,MSec) ; st := (Sec*1000)+MSec ; if Win32Platform = VER_PLATFORM_WIN32_NT then { on windows NT ?} BeepThread := Beeper.Create(False) {WinNT} else begin if SendWithLight.State = cbChecked then LightOn := True ; StartSound(freq) ; {Win95} end ; if not(CodeDspStarted) then begin CodeDspStarted := True ; CodeStr := '' ; CodeDspThread := TCodeDsp.Create(False) ; end ; end; procedure TForm1.MorseKeyButtonMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Hour, Min, Sec, MSec: word ; ft: integer ; begin DecodeTime(Time,Hour,Min,Sec,MSec) ; et := (Sec*1000)+MSec ; if Win32Platform = VER_PLATFORM_WIN32_NT then { on windows NT ?} BeepThread.Terminate {WinNT} else begin if SendWithLight.State = cbChecked then LightOn := False ; EndSound ; {Win95} end ; if st <= et then ft := et - st else ft := et + (60000 - st) ; if ft > (2*cpm) then {dah} CodeStr := CodeStr + '-' else {dit} CodeStr := CodeStr + '.' ; DispChar.Caption := CodeStr ; end; procedure TForm1.FreqBoxChange(Sender: TObject); begin freq := StrToInt(FreqBox.Text) ; end; procedure TForm1.DCode(sel: string; n: integer) ; var i: integer ; p: integer ; begin Choice1Button.Caption := '' ; Choice2Button.Caption := '' ; Choice3Button.Caption := '' ; Choice4Button.Caption := '' ; Choice5Button.Caption := '' ; for i := 1 to n do begin p := ord(sel[i]) - ord('[') + 1 ; if (p >= 1) and (p <= 5) then {its a special character} begin case i of 1: Choice1Button.Caption := SpecNames[p] ; 2: Choice2Button.Caption := SpecNames[p] ; 3: Choice3Button.Caption := SpecNames[p] ; 4: Choice4Button.Caption := SpecNames[p] ; 5: Choice5Button.Caption := SpecNames[p] ; end ; end else begin case i of 1: Choice1Button.Caption := copy(sel,1,1) ; 2: Choice2Button.Caption := copy(sel,2,1) ; 3: Choice3Button.Caption := copy(sel,3,1) ; 4: Choice4Button.Caption := copy(sel,4,1) ; 5: Choice5Button.Caption := copy(sel,5,1) ; end ; end ; end ; end ; function TForm1.RCode(sel: string; n: integer):string ; var cc: string ; i: integer ; begin i := Trunc(Random(n+1)) ; cc := copy(sel,i,1) ; {start a thread to send the randomly selected character} DspText := cc ; SendTextThread := TSendText.Create(False) ; {return randomly selected character} result := cc ; end ; procedure TForm1.SendCharButtonClick(Sender: TObject); begin Choice1Button.Enabled := True ; Choice2Button.Enabled := True ; Choice3Button.Enabled := True ; Choice4Button.Enabled := True ; Choice5Button.Enabled := True ; Answer.Caption := '' ; Randomize ; if CodeGroupBox.Text[1] = 'E' then CCode := RCode('SEHI ',4) else if CodeGroupBox.Text[1] = 'T' then CCode := RCode('TMOR ',4) else if CodeGroupBox.Text[1] = 'A' then CCode := RCode('AWJK ',4) else if CodeGroupBox.Text[1] = 'U' then CCode := RCode('UVFL ',4) else if CodeGroupBox.Text[1] = 'N' then CCode := RCode('NDBG ',4) else if CodeGroupBox.Text[1] = 'C' then CCode := RCode('CYQX ',4) else if CodeGroupBox.Text[1] = 'Z' then CCode := RCode('ZP ',2) else if CodeGroupBox.Text[1] = '1' then CCode := RCode('12345',5) else if CodeGroupBox.Text[1] = '6' then CCode := RCode('67890',5) else if CodeGroupBox.Text[1] = 'P' then {punctuation} CCode := RCode('.,?/ ',4) else if CodeGroupBox.Text[1] = 'S' then {special codes} CCode := RCode('[\]^_',5) ; if cbChecked = DisplayCodeCheckBox.State then DisplayCode.Caption := 'Code: '+Codes[ord(CCode[1])] else DisplayCode.Caption := '' ; end; function Ans(cb,cc: string): string ; var p: integer ; begin p := ord(cc[1]) - ord('[') + 1 ; if (p >= 1) and (p <= 5) then {last char was a special character} begin if cb = SpecNames[p] then result := 'Correct' else result := 'Wrong, code was '+SpecNames[p]+', try another.' end else {last char was an ascii char} begin if cb = cc then result := 'Correct' else result := 'Wrong, code was '+cc+', try another.' ; end ; end ; procedure TForm1.Choice1ButtonClick(Sender: TObject); begin Answer.Caption := Ans(Choice1Button.Caption,CCode) ; end; procedure TForm1.Choice2ButtonClick(Sender: TObject); begin Answer.Caption := Ans(Choice2Button.Caption,CCode) ; end; procedure TForm1.Choice3ButtonClick(Sender: TObject); begin Answer.Caption := Ans(Choice3Button.Caption,CCode) ; end; procedure TForm1.Choice4ButtonClick(Sender: TObject); begin Answer.Caption := Ans(Choice4Button.Caption,CCode) ; end; procedure TForm1.Choice5ButtonClick(Sender: TObject); begin Answer.Caption := Ans(Choice5Button.Caption,CCode) ; end; procedure TForm1.RepeatButtonClick(Sender: TObject); begin SendStr(CCode) ; end; procedure TForm1.HelpButtonClick(Sender: TObject); begin Help.ShowModal ; end; procedure TForm1.CodeGroupBoxChange(Sender: TObject); begin if CodeGroupBox.Text[1] = 'E' then DCode('SEHI ',4) else if CodeGroupBox.Text[1] = 'T' then DCode('TMOR ',4) else if CodeGroupBox.Text[1] = 'A' then DCode('AWJK ',4) else if CodeGroupBox.Text[1] = 'U' then DCode('UVFL ',4) else if CodeGroupBox.Text[1] = 'N' then DCode('NDBG ',4) else if CodeGroupBox.Text[1] = 'C' then DCode('CYQX ',4) else if CodeGroupBox.Text[1] = 'Z' then DCode('ZP ',2) else if CodeGroupBox.Text[1] = '1' then DCode('12345',5) else if CodeGroupBox.Text[1] = '6' then DCode('67890',5) else if CodeGroupBox.Text[1] = 'P' then {punctuation} DCode('.,?/ ',4) else if CodeGroupBox.Text[1] = 'S' then {special codes} DCode('[\]^_',5) ; DisplayCode.Caption := '' ; Answer.Caption := '' ; end; procedure TForm1.DisplayCodeCheckBoxClick(Sender: TObject); begin if cbChecked = DisplayCodeCheckBox.State then DisplayCode.Caption := 'Code: '+Codes[ord(CCode[1])] else DisplayCode.Caption := '' ; end; procedure TForm1.BeginSendingButtonClick(Sender: TObject); begin CodeSendThread := TCodeSend.Create(False) ; end; procedure TForm1.StopSendingButtonClick(Sender: TObject); begin CodeSendThread.Terminate ; end; procedure TForm1.SendTwiceCheckBoxClick(Sender: TObject); begin if SendTwiceCheckBox.State = cbChecked then Twice := True else Twice := False ; end; procedure TForm1.CopySendButtonClick(Sender: TObject); begin CopyEdit.Text := '' ; ActualEdit.Text := '' ; CorrectLabel.Caption := '' ; CopyCodeThread := TCopyCode.Create(False) ; end; procedure TForm1.CopyStopButtonClick(Sender: TObject); begin CopyCodeThread.Terminate ; end; procedure TForm1.Button1Click(Sender: TObject); begin SendTextThread.Terminate ; end; procedure TForm1.Button2Click(Sender: TObject); begin About.ShowModal ; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin if Win32Platform <> VER_PLATFORM_WIN32_NT then { Not windows NT ?} EndSound ; {On Win95, do just in case} end; procedure TForm1.TabbedNotebook1Change(Sender: TObject; NewTab: Integer; var AllowChange: Boolean); begin Choice1Button.Enabled := False ; Choice2Button.Enabled := False ; Choice3Button.Enabled := False ; Choice4Button.Enabled := False ; Choice5Button.Enabled := False ; end; procedure TForm1.SendWithSoundClick(Sender: TObject); begin if SendWithSound.State = cbChecked then SendSound := True else SendSound := False ; end; procedure TForm1.SendWithLightClick(Sender: TObject); begin if SendWithLight.State = cbChecked then LightPolThread := TLightPol.Create(False) else LightPolThread.Terminate ; end; end.
unit UMISMOEnvelope; interface uses Classes, uCraftXML, uCraftClass, UMismoOrderObjects; const REQUEST_ROOT_ELEMENT_NAME = 'REQUEST_GROUP'; REQUEST_PARENT_ELEMENT_XPATH = REQUEST_ROOT_ELEMENT_NAME + '/REQUEST/REQUEST/DATA'; RESPONSE_ROOT_ELEMENT_NAME = 'RESPONSE_GROUP'; RESPONSE_PARENT_ELEMENT_XPATH = RESPONSE_ROOT_ELEMENT_NAME + '/RESPONSE/RESPONSE_DATA'; APPRAISAL_REPORT_FILE_EXTENSION = 'AppraisalReport'; APPRAISAL_ORDER_FILE_EXTENSION = 'AppraisalOrder'; APPRAISAL_STATUS_FILE_EXTENSION = 'AppraisalStatus'; APPRAISAL_RESPONSE_ELEMENT = 'APPRAISAL_RESPONSE'; APPRAISAL_REQUEST_ELEMENT = 'APPRAISAL_REQUEST'; DEFAULT_MISMO_VERSION = '2.3.1'; type TContactPointRole = (cprUnknown, cprHome, cprWork, cprMobile); TContactPointType = (cptUnknown, cptEMail, cptFax, cptPhone, cptPager, cptAutomationEMail, cptOther); TAppraisalPurposeType = (aptUnknown, aptPurchase, aptRefinance, aptEquity, aptEstate, aptDivorce, aptTaxAppeal, aptInspection, aptConstruction, aptSecondMortgage, aptOther); const CONTACT_POINT_ROLE_NAMES : array[TContactPointRole] of string = ('Unknown', 'Home', 'Work', 'Mobile'); CONTACT_POINT_TYPE_NAMES : array[TContactPointType] of string = ('Unknown', 'EMail', 'Fax', 'Phone', 'Pager', 'Automation EMail', 'Other'); APPRAISAL_PURPOSE_TYPE_NAMES : array[TAppraisalPurposeType] of string = ('Unknown', 'Purchase', 'Refinance', 'Equity', 'Estate', 'Divorce', 'TaxAppeal', 'Inspection', 'Construction', 'SecondMortgage', 'Other'); function ContactPointRoleToStr(ARole : TContactPointRole) : string; function StrToContactPointRole(const AString : string) : TContactPointRole; function ContactPointTypeToStr(AType : TContactPointType) : string; function StrToContactPointType(const AString : string) : TContactPointType; type TContactDetail = class; TContactPoint = class(TCollectionItem) private FRole : TContactPointRole; FContactType : TContactPointType; FDescription : string; FValue : string; public procedure Clear; property Role : TContactPointRole read FRole write FRole; property ContactType : TContactPointType read FContactType write FContactType; property Description : string read FDescription write FDescription; property Value : string read FValue write FValue; procedure Parse(AnElement : TXMLElement; ADetail : TContactDetail = nil); procedure Compose(AnElement : TXMLElement; ADetail : TContactDetail = nil); function GetDescription(const LinePrefix : string = EMPTY_STRING) : string; virtual; end; TContactDetail = class(TCollectionItem) private FName : string; FContactPoints : TCraftingCollection; FPreferredContactPoint : TContactPoint; function GetContactPoints : TCraftingCollection; function GetContactPoint(Index : Integer) : TContactPoint; protected property ContactPoints : TCraftingCollection read GetContactPoints; public destructor Destroy; override; procedure Clear; property Name : string read FName write FName; // person name property PreferredContactPoint : TContactPoint read FPreferredContactPoint write FPreferredContactPoint; property ContactPoint[Index : Integer] : TContactPoint read GetContactPoint; function AddContactPoint : TContactPoint; function ContactPointCount : Integer; procedure Parse(AnElement : TXMLElement); procedure Compose(AnElement : TXMLElement); function GetDescription(const LinePrefix : string = EMPTY_STRING) : string; virtual; end; TContact = class(TCraftingCollectionItem) private FDetails : TCraftingCollection; FName : string; FStreetAddress : string; FStreetAddress2 : string; FCity : string; FState : string; FPostalCode : string; FCountry : string; FIdentifier : string; function GetContactDetail(Index : Integer) : TContactDetail; public constructor Create; reintroduce; overload; virtual; destructor Destroy; override; procedure Clear; override; function QuickName : string; property CompanyName : string read FName write FName; property StreetAddress : string read FStreetAddress write FStreetAddress; property StreetAddress2 : string read FStreetAddress2 write FStreetAddress2; property City : string read FCity write FCity; property State : string read FState write FState; property PostalCode : string read FPostalCode write FPostalCode; property Country : string read FCountry write FCountry; property Identifier : string read FIdentifier write FIdentifier; property Details[Index : Integer] : TContactDetail read GetContactDetail; function AddDetail : TContactDetail; function DetailCount : Integer; procedure Parse(AnElement : TXMLElement); virtual; procedure Compose(AnElement : TXMLElement); virtual; function GetDescription(const LinePrefix : string = EMPTY_STRING) : string; virtual; end; TContacts = class(TCraftingCollection) public constructor Create; reintroduce; overload; function GetDescription(const LinePrefix : string = EMPTY_STRING) : string; virtual; function First(var AContact : TContact) : Boolean; reintroduce; overload; function Next(var AContact : TContact) : Boolean; reintroduce; overload; end; TPreferredFormat = (pfUnknown, pfXML, pfText, pfPDF, pfPCL, pfOther); TDeliveryMethod = (dmUnknown, dmSMTP, dmHTTP, dmHTTPS, dmVAN, dmMessageQueue, dmMail, dmFax, dmFile, dmFTP, dmOther); TInspectionType = (itUnknown, itNone, itExteriorOnly, itExteriorAndInterior); TGraphicFormat = (gfUnknown, gfGIF, gfJPEG, gfBitmap, gfPNG); TComparable = (cUnknown, cSubject, cComp1, cComp2, cComp3, cComp4, cComp5, cComp6, cComp7, cComp8, cComp9, cCompOther); TComparableType = (ctSales, ctRentals, ctListings); TImageType = (imtUnknown, imtSketch, imtMap, imtPhoto, imtExhibit); const GRAPHIC_FORMAT_NAMES : array[TGraphicFormat] of string = ('Unknown', 'GIF', 'JPG', 'BMP', 'PNG'); GRAPHIC_FORMAT_MIME_TYPES : array[TGraphicFormat] of string = ('Unknown', 'image/gif', 'image/jpeg', 'Unknown', 'image/png'); PREFERRED_FORMAT_NAMES : array[TPreferredFormat] of string = ('Unknown', 'XML', 'Text', 'PDF', 'PCL', 'Other'); PREFERRED_DELIVERY_NAMES : array[TDeliveryMethod] of string = ('Unknown', 'SMTP', 'HTTP', 'HTTPS', 'VAN', 'MessageQueue', 'Mail', 'Fax', 'File', 'FTP', 'Other'); INSPECTION_TYPE_NAMES : array[TInspectionType] of string = ('Unknown', 'None', 'Exterior Only', 'Exterior And Interior'); COMPARABLE_NAMES : array[TComparable] of string = ('Unknown', 'Subject', 'ComparableOne', 'ComparableTwo', 'ComparableThree', 'ComparableFour', 'ComparableFive', 'ComparableSix', 'ComparableSeven', 'ComparableEight', 'ComparableNine', 'Other'); COMPARABLE_INDEX_NAMES : array[0..11] of string = ('Unknown', 'Subject', 'ComparableOne', 'ComparableTwo', 'ComparableThree', 'ComparableFour', 'ComparableFive', 'ComparableSix', 'ComparableSeven', 'ComparableEight', 'ComparableNine', 'Other'); COMPARABLE_TITLES : array[TComparableType, TComparable] of string = (('Unknown', 'Subject', 'Comparable Sale 1', 'Comparable Sale 2', 'Comparable Sale 3', 'Comparable Sale 4', 'Comparable Sale 5', 'Comparable Sale 6', 'Comparable Sale 7', 'Comparable Sale 8', 'Comparable Sale 9', 'Other'), ('Unknown', 'Subject', 'Comparable Rental 1', 'Comparable Rental 2', 'Comparable Rental 3', 'Comparable Rental 4', 'Comparable Rental 5', 'Comparable Rental 6', 'Comparable Rental 7', 'Comparable Rental 8', 'Comparable Rental 9', 'Other'), ('Unknown', 'Subject', 'Comparable Listing 1', 'Comparable Listing 2', 'Comparable Listing 3', 'Comparable Listing 4', 'Comparable Listing 5', 'Comparable Listing 6', 'Comparable Listing 7', 'Comparable Listing 8', 'Comparable Listing 9', 'Other')); COMPARABLE_TYPE_NAMES : array[TComparableType] of string = ('Sales', 'Rentals', 'Listings'); COMPARABLE_TYPE_INDEX : array[TComparableType] of Integer = (1, 2, 3); IMAGE_TYPE_NAMES : array[TImageType] of string = ('Unknown', 'Sketch', 'Map', 'Photo', 'Exhibit'); BASE64_ENCODING_TAG = 'base64'; function PreferredFormatToStr(AFormat : TPreferredFormat) : string; function PreferredDeliveryMethodToStr(ADeliveryMethod : TDeliveryMethod) : string; type TPreferredResponse = class(TObject) private FFormat : TPreferredFormat; FMethod : TDeliveryMethod; FFormatOther : string; FMethodOther : string; FDestination : string; public property Format : TPreferredFormat read FFormat write FFormat; property FormatOther : string read FFormatOther write FFormatOther; property Method : TDeliveryMethod read FMethod write FMethod; property MethodOther : string read FMethodOther write FMethodOther; property Destination : string read FDestination write FDestination; procedure Clear; procedure Parse(AnElement : TXMLElement); procedure Compose(AnElement : TXMLElement); function GetDescription(const LinePrefix : string = EMPTY_STRING) : string; virtual; end; TRequestingParty = class(TContact) private FPreferredResponse : TPreferredResponse; public constructor Create; override; destructor Destroy; override; procedure Clear; override; property PreferredResponse : TPreferredResponse read FPreferredResponse; procedure Parse(AnElement : TXMLElement); override; procedure Compose(AnElement : TXMLElement); override; function GetDescription(const LinePrefix : string = EMPTY_STRING) : string; override; end; TSubmittingParty = class(TRequestingParty) private FLoginAccountIdentifier : string; FLoginAccountPassword : string; FSequenceIdentifier : string; public procedure Clear; override; procedure Parse(AnElement : TXMLElement); override; procedure Compose(AnElement : TXMLElement); override; property LoginAccountIdentifier : string read FLoginAccountIdentifier write FLoginAccountIdentifier; property LoginAccountPassword : string read FLoginAccountPassword write FLoginAccountPassword; function GetDescription(const LinePrefix : string = EMPTY_STRING) : string; override; property SequenceIdentifier : string read FSequenceIdentifier write FSequenceIdentifier; end; TMISMOEnvelope = class; TPayload = class(TCraftingCollectionItem) private FXML : TXMLCollection; FKeyData : TCraftingStringList; FInternalAccount : string; FLoginAccountName : string; FLoginAccountPassword : string; FEnvelope : TMISMOEnvelope; function GetKeyData : TStrings; function GetData : TXMLElement; procedure SetData(AnElement : TXMLElement); function GetXML : TXMLCollection; protected property Envelope : TMISMOEnvelope read FEnvelope; property XML : TXMLCollection read GetXML; public constructor Create(ACollection : TCollection); override; destructor Destroy; override; procedure Clear; override; property Keys : TStrings read GetKeyData; property InternalAccount : string read FInternalAccount write FInternalAccount; property LoginAccountName : string read FLoginAccountName write FLoginAccountName; property LoginAccountPassword : string read FLoginAccountPassword write FLoginAccountPassword; property Data : TXMLElement read GetData write SetData; // this is the root of the payload XML procedure Compose(AnElement : TXMLElement); virtual; procedure Parse(AnElement : TXMLElement); virtual; function GetDescription(const LinePrefix : string = EMPTY_STRING) : string; virtual; end; TPayloads = class(TCraftingCollection) public function GetDescription(const LinePrefix : string = EMPTY_STRING) : string; virtual; function First(var APayload : TPayload) : Boolean; reintroduce; overload; function Next(var APayload : TPayload) : Boolean; reintroduce; overload; end; TValuation = class(TCraftingCollectionItem) public ValuationType : TAppraisalType; ValuationForm : string; FeeAmount : Currency; IsTaxable : Boolean; end; TValuations = class(TCraftingCollection) private function GetValuation(Index : Integer) : TValuation; public constructor Create; reintroduce; overload; function Add : TValuation; function First(var AValuation : TValuation) : Boolean; reintroduce; overload; function Next(var AValuation : TValuation) : Boolean; reintroduce; overload; property Valuations[Index : Integer] : TValuation read GetValuation; default; end; TOrder = class(TCraftingCollectionItem) private FDueDate : TDateTime; FAcceptanceDueDate : TDateTime; FInformalDueDate : TDateTime; FIsInformalRequested : Boolean; FValuations : TValuations; FOrderID : string; FPleaseConfirmBeforeAssignment : Boolean; FSpecialInstructions : string; FFormName : string; FInspectionType : TInspectionType; FAppraisalPurposeType : TAppraisalPurposeType; public constructor Create(ACollection : TCollection); override; destructor Destroy; override; function GetDescription(const LinePrefix : string) : string; property DueDate : TDateTime read FDueDate write FDueDate; property AcceptanceDueDate : TDateTime read FAcceptanceDueDate write FAcceptanceDueDate; property IsInformalRequested : Boolean read FIsInformalRequested write FIsInformalRequested; property InformalDueDate : TDateTime read FInformalDueDate write FInformalDueDate; property Valuations : TValuations read FValuations; property OrderID : string read FOrderID write FOrderID; property PleaseConfirmBeforeAssignment : Boolean read FPleaseConfirmBeforeAssignment write FPleaseConfirmBeforeAssignment; property SpecialInstructions : string read FSpecialInstructions write FSpecialInstructions; property FormName : string read FFormName write FFormName; property InspectionType : TInspectionType read FInspectionType write FInspectionType; property AppraisalPurposeType : TAppraisalPurposeType read FAppraisalPurposeType write FAppraisalPurposeType; procedure Parse(AnElement : TXMLElement); virtual; procedure Compose(AnElement : TXMLElement); virtual; end; TOrders = class(TCraftingCollection) private function GetOrder(Index : Integer) : TOrder; public constructor Create; reintroduce; overload; function Add : TOrder; function First(var AOrder : TOrder) : Boolean; reintroduce; overload; function Next(var AOrder : TOrder) : Boolean; reintroduce; overload; property Orders[Index : Integer] : TOrder read GetOrder; default; end; TRequest = class(TPayload) private FRequestDate : TDateTime; FPriority : string; FOrders : TOrders; FInternalAccountIdentifier : string; FLoginAccountIdentifier : string; FLoginAccountPassword : string; FRequestingPartyBranchIdentifier : string; function GetClientName : string; function GetAppraiserName : string; public constructor Create(ACollection : TCollection); override; destructor Destroy; override; procedure Compose(AnElement : TXMLElement); override; procedure Parse(AnElement : TXMLElement); override; property ClientName : string read GetClientName; property AppraiserName : string read GetAppraiserName; property Priority : string read FPriority write FPriority; function GetDescription(const LinePrefix : string = EMPTY_STRING) : string; override; property RequestDate : TDateTime read FRequestDate write FRequestDate; property InternalAccountIdentifier : string read FInternalAccountIdentifier write FInternalAccountIdentifier; property LoginAccountIdentifier : string read FLoginAccountIdentifier write FLoginAccountIdentifier; property LoginAccountPassword : string read FLoginAccountPassword write FLoginAccountPassword; property RequestingPartyBranchIdentifier : string read FRequestingPartyBranchIdentifier write FRequestingPartyBranchIdentifier; property Orders : TOrders read FOrders; end; TMISMOEnvelope = class(TPersistent) private FMismoVersion : string; function GetAsXML : string; procedure SetAsXML(Value : string); protected procedure AssignTo(Target : TPersistent); override; function GetOrderID : string; virtual; procedure SetOrderID(Value : string); virtual; public procedure AfterConstruction; override; procedure Clear; virtual; property MismoVersion : string read FMismoVersion write FMismoVersion; procedure Assign(Source : TPersistent); override; property AsXML : string read GetAsXML write SetAsXML; function GetDescription(const LinePrefix : string = EMPTY_STRING) : string; virtual; procedure Compose(AnXML : TXMLCollection); overload; procedure Compose(AnXMLElement : TXMLElement); overload; virtual; abstract; function Compose : string; overload; procedure Parse(const AText : string); overload; procedure Parse(AnXML : TXMLCollection); overload; procedure Parse(AnXMLElement : TXMLElement); overload; virtual; abstract; property OrderID : string read GetOrderID write SetOrderID; end; TMISMORequestEnvelope = class(TMISMOEnvelope) private FReceivingParty : TContact; FSubmittingParty : TSubmittingParty; FRequestingParties : TContacts; FRequests : TPayloads; function GetRequestingParty(Index : Integer) : TRequestingParty; function GetRequest(Index : Integer) : TRequest; protected function GetOrderID : string; override; public constructor Create; destructor Destroy; override; procedure Clear; override; property ReceivingParty : TContact read FReceivingParty write FReceivingParty; property SubmittingParty : TSubmittingParty read FSubmittingParty write FSubmittingParty; property RequestingParties[Index : Integer] : TRequestingParty read GetRequestingParty; function AddRequestingParty : TRequestingParty; function RequestingPartyCount : Integer; property Requests[Index : Integer] : TRequest read GetRequest; default; function AddRequest : TRequest; function RequestCount : Integer; procedure Parse(AnXMLElement : TXMLElement); override; procedure Compose(AnXMLElement : TXMLElement); override; function GetDescription(const LinePrefix : string = EMPTY_STRING) : string; override; end; TResponseStatus = class(TCraftingCollectionItem) private FCondition : string; FCode : Integer; FName : string; FDescription : string; function GetStatus : TeTracStatus; procedure SetStatus(Value : TeTracStatus); procedure SetCode(const Value : Integer); procedure SetName(const Value : string); public procedure Clear; override; property Name : string read FName write SetName; property Code : Integer read FCode write SetCode; property Condition : string read FCondition write FCondition; property Description : string read FDescription write FDescription; property Status : TeTracStatus read GetStatus write SetStatus; procedure Compose(AnElement : TXMLElement); overload; function Compose : string; overload; procedure Parse(AnElement : TXMLElement); overload; procedure Parse(const AText : string); overload; function GetDescription(const LinePrefix : string = EMPTY_STRING) : string; virtual; end; TStatuses = class(TCraftingCollection) public constructor Create; reintroduce; overload; function GetDescription(const LinePrefix : string = EMPTY_STRING) : string; virtual; function First(var AStatus : TResponseStatus) : Boolean; reintroduce; overload; function Next(var AStatus : TResponseStatus) : Boolean; reintroduce; overload; end; TResponse = class(TPayload) private FOrderID : string; FClientID : string; FStatuses : TStatuses; FReports : TStringList; FResponseDate : TDateTime; function GetStatus(Index : Integer) : TResponseStatus; function GetReport(Index : Integer) : string; public constructor Create(ACollection : TCollection); override; destructor Destroy; override; procedure Compose(AnElement : TXMLElement); override; procedure Parse(AnElement : TXMLElement); override; property Statuses[Index : Integer] : TResponseStatus read GetStatus; function AddStatus : TResponseStatus; function StatusCount : Integer; property Reports[Index : Integer] : string read GetReport; procedure AddReport(const AText : string); function ReportCount : Integer; property ClientID : string read FClientID write FClientID; property OrderID : string read FOrderID write FOrderID; property ResponseDate : TDateTime read FResponseDate write FResponseDate; function GetDescription(const LinePrefix : string = EMPTY_STRING) : string; override; end; TResponses = class(TCraftingCollection) public constructor Create; reintroduce; overload; function GetDescription(const LinePrefix : string = EMPTY_STRING) : string; virtual; function First(var AResponse : TResponse) : Boolean; reintroduce; overload; function Next(var AResponse : TResponse) : Boolean; reintroduce; overload; function Add : TResponse; end; type TMISMOResponseEnvelope = class(TMISMOEnvelope) private FRespondingParty : TContact; FRespondToParty : TContact; FResponses : TResponses; function GetResponse(Index : Integer) : TResponse; protected function GetOrderID : string; override; public constructor Create; virtual; destructor Destroy; override; procedure Clear; override; property RespondingParty : TContact read FRespondingParty; property RespondToParty : TContact read FRespondToParty; property Responses[Index : Integer] : TResponse read GetResponse; default; function AddResponse : TResponse; function ResponseCount : Integer; procedure Parse(AnXMLElement : TXMLElement); override; procedure Compose(AnXMLElement : TXMLElement); override; function GetDescription(const LinePrefix : string = EMPTY_STRING) : string; override; end; TMessageEnvelope = class(TMISMOResponseEnvelope) private FReplyRequested : Boolean; FOrderID : string; FPriority : string; FMessage : string; FDate : TDateTime; protected function GetOrderID : string; override; procedure SetOrderID(Value : string); override; public property Date : TDateTime read FDate write FDate; property OrderID : string read FOrderID write FOrderID; property ReplyRequested : Boolean read FReplyRequested write FReplyRequested; property Priority : string read FPriority write FPriority; property Message : string read FMessage write FMessage; procedure Compose(AnXMLElement : TXMLElement); override; procedure Parse(AnXMLElement : TXMLElement); override; end; TStatusEnvelope = class(TMISMOResponseEnvelope) private FMessage : string; FOrderID : string; FStatus : TAppraisalOrderStatus; FDate : TDateTime; FInspectionDate : TDateTime; protected function GetOrderID : string; override; procedure SetOrderID(Value : string); override; public property Status : TAppraisalOrderStatus read FStatus write FStatus; property Date : TDateTime read FDate write FDate; property Message : string read FMessage write FMessage; property InspectionDate : TDateTime read FInspectionDate write FInspectionDate; property OrderID : string read FOrderID write FOrderID; procedure Compose(AnXMLElement : TXMLElement); override; procedure Parse(AnXMLElement : TXMLElement); override; end; function ComposeStatusEnvelope(FromID, ToID, AnOrderID : string; NewStatus : TeTracStatus; AComment : string = ''; ADate : TDateTime = 0.0) : string; implementation uses SysUtils, uInternetUtils, UWindowsInfo, uMISMOImportExport; function MISMOBoolToStr(AnExpression : Boolean) : string; begin if AnExpression then Result := 'Y' else Result := 'N'; end; function ContactPointRoleToStr(ARole : TContactPointRole) : string; begin Result := CONTACT_POINT_ROLE_NAMES[ARole]; end; function StrToContactPointRole(const AString : string) : TContactPointRole; begin Result := High(TContactPointRole); repeat if CONTACT_POINT_ROLE_NAMES[Result] = AString then Exit; Dec(Result); until Result = Low(TContactPointRole); // cprUnknown end; function ContactPointTypeToStr(AType : TContactPointType) : string; begin Result := CONTACT_POINT_TYPE_NAMES[AType]; end; function StrToContactPointType(const AString : string) : TContactPointType; begin Result := High(TContactPointType); repeat if CONTACT_POINT_TYPE_NAMES[Result] = AString then Exit; Dec(Result); until Result = Low(TContactPointType); // cptUnknown end; function StrToResponseFormat(const AString : string) : TPreferredFormat; begin Result := High(TPreferredFormat); repeat if PREFERRED_FORMAT_NAMES[Result] = AString then Exit; Dec(Result); until Result = Low(TPreferredFormat); //pfUnknown end; function StrToResponseMethod(const AString : string) : TDeliveryMethod; begin Result := High(TDeliveryMethod); repeat if PREFERRED_DELIVERY_NAMES[Result] = AString then Exit; Dec(Result); until Result = Low(TDeliveryMethod); // dmUnknown end; function PreferredFormatToStr(AFormat : TPreferredFormat) : string; begin Result := PREFERRED_FORMAT_NAMES[AFormat]; end; function PreferredDeliveryMethodToStr(ADeliveryMethod : TDeliveryMethod) : string; begin Result := PREFERRED_DELIVERY_NAMES[ADeliveryMethod]; end; { TMISMOEnvelope } procedure TMISMOEnvelope.AfterConstruction; begin inherited; Clear; end; procedure TMISMOEnvelope.Clear; begin inherited; FMISMOVersion := DEFAULT_MISMO_VERSION; end; procedure TMISMOEnvelope.AssignTo(Target : TPersistent); begin if Target is TXMLCollection then Compose(TXMLCollection(Target)) else if Target is TStrings then TStrings(Target).Text := Self.AsXML else inherited AssignTo(Target); end; function TMISMOEnvelope.GetDescription(const LinePrefix : string) : string; begin Result := #13#10 + LinePrefix + 'MISMOVersion=' + Self.MismoVersion; end; procedure TMISMOEnvelope.Compose(AnXML : TXMLCollection); begin Compose(AnXML.RootElement); end; procedure TMISMOEnvelope.Parse(const AText : string); begin with TXMLCollection.Create do try AsString := AText; // load the collection Self.Parse(RootElement); // load the envelope from the collection finally Free; end; end; procedure TMISMOEnvelope.Parse(AnXML : TXMLCollection); begin Parse(AnXML.RootElement); end; procedure TMISMOEnvelope.Assign(Source : TPersistent); begin if Source is TXMLCollection then Parse(TXMLCollection(Source)) else if Source is TStrings then Self.AsXML := TStrings(Source).Text else inherited Assign(Source); end; function TMISMOEnvelope.GetAsXML : string; var ThisXML : TXMLCollection; begin ThisXML := TXMLCollection.Create; try Compose(ThisXML); Result := ThisXML.AsString; finally ThisXML.Free; end; end; procedure TMISMOEnvelope.SetAsXML(Value : string); var ThisXML : TXMLCollection; begin ThisXML := TXMLCollection.Create; try ThisXML.AsString := Value; Parse(ThisXML); finally ThisXML.Free; end; end; function TMISMOEnvelope.Compose : string; var ThisXML : TXMLCollection; begin ThisXML := TXMLCollection.Create; try Compose(ThisXML); Result := ThisXML.AsString; finally ThisXML.Free; end; end; function TMISMOEnvelope.GetOrderID : string; begin raise Exception.Create('No OrderID available'); end; procedure TMISMOEnvelope.SetOrderID(Value : string); begin raise Exception.Create('No OrderID available'); end; { TMISMORequestEnvelope } constructor TMISMORequestEnvelope.Create; begin inherited; FReceivingParty := TContact.Create; FSubmittingParty := TSubmittingParty.Create; FRequestingParties := TContacts.Create(TRequestingParty); FRequests := TPayloads.Create(TRequest); end; destructor TMISMORequestEnvelope.Destroy; begin FRequestingParties.Free; FRequests.Free; inherited; end; procedure TMISMORequestEnvelope.Clear; begin inherited; FReceivingParty.Clear; FSubmittingParty.Clear; FRequestingParties.Clear; FRequests.Clear; end; function TMISMORequestEnvelope.GetDescription(const LinePrefix : string) : string; begin Result := inherited GetDescription(LinePrefix); Result := TrimRight(Result + #13#10 + FReceivingParty.GetDescription(LinePrefix + 'ReceivingParty') + FSubmittingParty.GetDescription(LinePrefix + 'SubmittingParty') + FRequestingParties.GetDescription(LinePrefix + 'RequestingParties') + FRequests.GetDescription(LinePrefix + 'Requests')); end; function TMISMORequestEnvelope.AddRequestingParty : TRequestingParty; begin Result := FRequestingParties.Add as TRequestingParty; Assert(Result.PreferredResponse <> nil); end; function TMISMORequestEnvelope.GetRequestingParty(Index : Integer) : TRequestingParty; begin Result := FRequestingParties.Items[Index] as TRequestingParty; end; function TMISMORequestEnvelope.RequestingPartyCount : Integer; begin Result := FRequestingParties.Count; end; function TMISMORequestEnvelope.GetRequest(Index : Integer) : TRequest; begin Result := FRequests.Items[Index] as TRequest; end; function TMISMORequestEnvelope.AddRequest : TRequest; begin Result := FRequests.Add as TRequest; Result.FEnvelope := Self; end; function TMISMORequestEnvelope.RequestCount : Integer; begin Result := FRequests.Count; end; procedure TMISMORequestEnvelope.Parse(AnXMLElement : TXMLElement); var ThisElement : TXMLElement; begin Self.Clear; if AnXMLElement.Name <> REQUEST_ROOT_ELEMENT_NAME then AnXMLElement := AnXMLElement.FindElement(REQUEST_ROOT_ELEMENT_NAME); with AnXMLElement do begin if AttributeExists('MISMOVersionID') then Self.MismoVersion := AttributeValues['MISMOVersionID']; SubmittingParty.Parse(FindElement('REQUESTING_PARTY')); ReceivingParty.Parse(FindElement('RECEIVING_PARTY')); if FirstElement('REQUESTING_PARTY', ThisElement) then begin repeat AddRequestingParty.Parse(ThisElement); until not NextElement('REQUESTING_PARTY', ThisElement); end; if FirstElement('REQUEST', ThisElement) then begin repeat AddRequest.Parse(ThisElement); until not NextElement('REQUEST', ThisElement); end; end; end; procedure TMISMORequestEnvelope.Compose(AnXMLElement : TXMLElement); var Counter : Integer; begin AnXMLElement.Name := REQUEST_ROOT_ELEMENT_NAME; AnXMLElement.AttributeValues['MISMOVersionID'] := Self.MismoVersion; with AnXMLElement do begin for Counter := 0 to RequestingPartyCount - 1 do RequestingParties[Counter].Compose(AddElement('REQUESTING_PARTY')); SubmittingParty.Compose(AddElement('SUBMITTING_PARTY')); ReceivingParty.Compose(AddElement('RECEIVING_PARTY')); for Counter := 0 to RequestCount - 1 do Requests[Counter].Compose(AddElement('REQUEST')); end; end; function ComposeResponse(FromID, ToID, OrderID : string; NewStatus : TeTracStatus) : string; begin with TMISMOResponseEnvelope.Create do try RespondingParty.Identifier := FromID; RespondToParty.Identifier := ToID; FResponses.Add.AddStatus.Status := NewStatus; Result := Compose; finally Free; end; end; function TMISMORequestEnvelope.GetOrderID : string; begin case RequestCount of 0 : raise Exception.Create('No requests in this envelope'); 1 : begin case Requests[0].Orders.Count of 0 : raise Exception.Create('No orders in this envelope'); 1 : Result := Requests[0].Orders[0].OrderID; else raise Exception.Create('More than one order in this envelope'); end; end; else raise Exception.Create('More than one request in this envelope'); end; end; { TMISMOResponseEnvelope } constructor TMISMOResponseEnvelope.Create; begin inherited; FRespondingParty := TContact.Create; FRespondToParty := TContact.Create; FResponses := TResponses.Create; end; destructor TMISMOResponseEnvelope.Destroy; begin FRespondingParty.Free; FRespondToParty.Free; FResponses.Free; inherited; end; procedure TMISMOResponseEnvelope.Clear; begin inherited; FRespondingParty.Clear; FRespondToParty.Clear; FResponses.Clear; end; function TMISMOResponseEnvelope.GetDescription(const LinePrefix : string) : string; begin Result := inherited GetDescription(LinePrefix); Result := TrimRight(Result + #13#10 + RespondingParty.GetDescription(LinePrefix + 'RespondingParty') + RespondToParty.GetDescription(LinePrefix + 'RespondToParty') + FResponses.GetDescription(LinePrefix + 'Responses')); end; function TMISMOResponseEnvelope.GetResponse(Index : Integer) : TResponse; begin Result := FResponses.Items[Index] as TResponse; end; function TMISMOResponseEnvelope.AddResponse : TResponse; begin Result := FResponses.Add as TResponse; Result.FEnvelope := Self; end; function TMISMOResponseEnvelope.ResponseCount : Integer; begin Result := FResponses.Count; end; procedure TMISMOResponseEnvelope.Parse(AnXMLElement : TXMLElement); var ThisElement, RootElement : TXMLElement; begin Self.Clear; if AnXMLElement.Name = RESPONSE_ROOT_ELEMENT_NAME then RootElement := AnXMLElement else RootElement := AnXMLElement.FindElement(RESPONSE_ROOT_ELEMENT_NAME); if RootElement <> nil then begin with RootElement do begin if AttributeExists('MISMOVersionID') then MismoVersion := AttributeValues['MISMOVersionID']; RespondingParty.Parse(FindElement('RESPONDING_PARTY')); RespondToParty.Parse(FindElement('RESPOND_TO_PARTY')); if FirstElement('RESPONSE', ThisElement) then begin repeat AddResponse.Parse(ThisElement); until not NextElement('RESPONSE', ThisElement); end; end; end else end; procedure TMISMOResponseEnvelope.Compose(AnXMLElement : TXMLElement); var Counter : Integer; begin AnXMLElement.Name := RESPONSE_ROOT_ELEMENT_NAME; AnXMLElement.AttributeValues['MISMOVersionID'] := Self.MismoVersion; with AnXMLElement do begin RespondingParty.Compose(AddElement('RESPONDING_PARTY')); RespondToParty.Compose(AddElement('RESPOND_TO_PARTY')); for Counter := 0 to ResponseCount - 1 do Responses[Counter].Compose(AddElement('RESPONSE')); end; end; function TMISMOResponseEnvelope.GetOrderID : string; begin case ResponseCount of 0 : raise Exception.Create('No Responses in this envelope'); 1 : Result := Responses[0].OrderID; else raise Exception.Create('More than one Response in this envelope'); end; end; { TResponseStatus } procedure TResponseStatus.Clear; begin FCondition := EMPTY_STRING; FCode := -1; FName := EMPTY_STRING; FDescription := EMPTY_STRING; end; function TResponseStatus.GetDescription(const LinePrefix : string) : string; begin Result := #13#10 + LinePrefix + 'Name=' + Name + #13#10 + LinePrefix + 'Code=' + IntToStr(Code) + #13#10 + LinePrefix + 'Condition=' + Condition + #13#10 + LinePrefix + 'Description=' + Description; end; function TResponseStatus.Compose : string; begin with TXMLCollection.Create do try RootElement.Name := 'STATUS'; Self.Compose(RootElement); Result := AsString; finally Free; end; end; procedure TResponseStatus.Compose(AnElement : TXMLElement); begin with AnElement do begin AttributeValues['_Name'] := Self.Name; // e.g. Accepted AttributeValues['_Code'] := IntToStr(Self.Code); // e.g. etsAccepted AttributeValues['_Condition'] := Self.Condition; // e.g. <date> AttributeValues['_Description'] := Self.Description; end; end; procedure TResponseStatus.Parse(const AText : string); begin with TXMLCollection.Create do try try AsString := AText; except on EXMLUnsupportedByteOrderError do AsString := ComposeHeader + AText; // add an XML header to the string end; finally Free; end; end; procedure TResponseStatus.Parse(AnElement : TXMLElement); begin if AnElement <> nil then begin Self.FCode := StrToIntDef(AnElement.AttributeValues['_Code'], -1); Self.FName := AnElement.AttributeValues['_Name']; Self.FCondition := AnElement.AttributeValues['_Condition']; Self.FDescription := AnElement.AttributeValues['_Description']; end; end; function TResponseStatus.GetStatus : TeTracStatus; begin Result := CodeToStatus(Self.Code); if Result = etsUnknown then Result := UMismoOrderObjects.StrToStatus(Self.Name); end; procedure TResponseStatus.SetStatus(Value : TeTracStatus); begin FName := UMismoOrderObjects.StatusToStr(Value); FCode := UMismoOrderObjects.StatusToCode(Value); end; procedure TResponseStatus.SetCode(const Value : Integer); begin if FCode <> Value then Status := UMismoOrderObjects.CodeToStatus(Value); end; procedure TResponseStatus.SetName(const Value : string); begin if FName <> Value then Status := UMismoOrderObjects.StrToStatus(Value); end; { TPayloads } function TPayloads.GetDescription(const LinePrefix : string) : string; var ThisPayload : TPayload; begin Result := EMPTY_STRING; if First(ThisPayload) then repeat Result := Result + #13#10 + ThisPayload.GetDescription(LinePrefix); until not Next(ThisPayload); end; function TPayloads.First(var APayload : TPayload) : Boolean; begin Result := inherited First(TCollectionItem(APayload)); end; function TPayloads.Next(var APayload : TPayload) : Boolean; begin Result := inherited Next(TCollectionItem(APayload)); end; { TPayload } constructor TPayload.Create(ACollection : TCollection); begin inherited; FKeyData := nil; // create on demand FXML := nil; end; destructor TPayload.Destroy; begin FKeyData.Free; FXML.Free; inherited; end; procedure TPayload.Clear; begin FInternalAccount := EMPTY_STRING; if FKeyData <> nil then FKeyData.Clear; if FXML <> nil then FXML.Clear; end; function TPayload.GetDescription(const LinePrefix : string) : string; var Counter : Integer; begin Result := EMPTY_STRING; if InternalAccount <> EMPTY_STRING then Result := Result + #13#10 + LinePrefix + 'InternalAccount=' + InternalAccount; if LoginAccountName <> EMPTY_STRING then Result := Result + #13#10 + LinePrefix + 'LoginAccountName=' + LoginAccountName; if LoginAccountPassword <> EMPTY_STRING then Result := Result + #13#10 + LinePrefix + 'LoginAccountPassword=' + LoginAccountPassword; if FKeyData <> nil then begin for Counter := 0 to FKeyData.Count - 1 do begin Result := Result + #13#10 + LinePrefix + 'Key' + FKeyData.Names[Counter] + '=' + FKeyData.ValueStrings[Counter]; end; end; end; function TPayload.GetKeyData : TStrings; begin if FKeyData = nil then FKeyData := TCraftingStringList.Create; Result := FKeyData; end; function TPayload.GetData : TXMLElement; begin Result := XML.RootElement; // creates FXML if necessary end; procedure TPayload.SetData(AnElement : TXMLElement); begin if (Self.Data <> AnElement) then XML.Assign(AnElement); end; procedure TPayload.Compose(AnElement : TXMLElement); var Counter : Integer; begin with AnElement do begin AttributeValues['InternalAccountIdentifier'] := Self.InternalAccount; AttributeValues['LoginAccountIdentifier'] := Self.LoginAccountName; AttributeValues['LoginAccountPassword'] := Self.LoginAccountPassword; for Counter := 0 to Keys.Count - 1 do AddElement('KEY', ['_Name', Keys.Names[Counter], '_Value', Keys.Values[Keys.Names[Counter]]]); end; end; procedure TPayload.Parse(AnElement : TXMLElement); var KeyElement : TXMLElement; begin Self.Clear; if AnElement <> nil then begin with AnElement do begin Self.InternalAccount := AttributeValues['InternalAccountIdentifier']; Self.LoginAccountName := AttributeValues['LoginAccountIdentifier']; Self.LoginAccountPassword := AttributeValues['LoginAccountpassword']; if FirstElement('KEY', KeyElement) then begin repeat Keys.Add(KeyElement.AttributeValues['_Name'] + '=' + KeyElement.AttributeValues['_Value']); until not NextElement('KEY', KeyElement); end; end; end; end; function TPayload.GetXML : TXMLCollection; begin if FXML = nil then FXML := TXMLCollection.Create; Result := FXML; end; { TValuations } constructor TValuations.Create; begin Create(TValuation); end; function TValuations.Add : TValuation; begin Result := inherited Add as TValuation; end; function TValuations.First(var AValuation : TValuation) : Boolean; begin Result := First(TCollectionItem(AValuation)); end; function TValuations.Next(var AValuation : TValuation) : Boolean; begin Result := Next(TCollectionItem(AValuation)); end; function TValuations.GetValuation(Index : Integer) : TValuation; begin Result := Items[Index] as TValuation; end; { TOrder } constructor TOrder.Create(ACollection : TCollection); begin inherited; FValuations := TValuations.Create; end; destructor TOrder.Destroy; begin FValuations.Free; inherited; end; function TOrder.GetDescription(const LinePrefix : string) : string; begin Result := ''; if AcceptanceDueDate <> EMPTY_DATE then begin Result := Result + #13#10 + LinePrefix + 'AcceptanceDueDate=' + uInternetUtils.DateTimeToISO8601(AcceptanceDueDate); end; if DueDate <> EMPTY_DATE then Result := Result + #13#10 + LinePrefix + 'RequestDate=' + uInternetUtils.DateTimeToISO8601(DueDate); if IsInformalRequested then Result := Result + #13#10 + LinePrefix + 'InformalReportRequested=True'; if InformalDueDate <> EMPTY_DATE then Result := Result + #13#10 + LinePrefix + 'InformalDueDate=' + uInternetUtils.DateTimeToISO8601(InformalDueDate); Result := Result + #13#10 + LinePrefix + 'PleaseConfirmBeforeAssignment=' + uCraftClass.BoolToStr(PleaseConfirmBeforeAssignment); end; procedure TOrder.Parse(AnElement : TXMLElement); // The VALUATION_REQUEST element var ThisElement : TXMLElement; begin PleaseConfirmBeforeAssignment := uCraftClass.StrToBool(AnElement.AttributeValues['ConfirmAppraiserBeforeAssignmentIndicator']); SpecialInstructions := AnElement.AttributeValues['SpecialInstructionsDescription']; IsInformalRequested := uCraftClass.StrToBool(AnElement.AttributeValues['AppraisalEstimateVarianceAdvisoryIndicator']); OrderID := AnElement.AttributeValues['RequestorOrderReferenceIdentifier']; if AnElement.FindElement('_PRODUCT', ThisElement) then begin DueDate := uInternetUtils.ISO8601ToDateTime(ThisElement.AttributeValues['RequestedCompletionDueDate']); AcceptanceDueDate := uInternetUtils.ISO8601ToDateTime(ThisElement.AttributeValues['RequestedAcceptaceDueDate']); end; end; procedure TOrder.Compose(AnElement : TXMLElement); begin if AnElement <> nil then begin AnElement.AttributeValues['RequestorOrderReferenceIdentifier'] := OrderID; AnElement.AttributeValues['AppraisalEstimateVarianceAdvisoryIndicator'] := uCraftClass.BoolToStr(IsInformalRequested); AnElement.AttributeValues['InformalReportDueDate'] := uInternetUtils.DateTimeToISO8601(InformalDueDate); AnElement.AttributeValues['ConfirmOrderProviderBeforeAssignmentIndicator'] := uCraftClass.BoolToStr(PleaseConfirmBeforeAssignment); AnElement.AttributeValues['SpecialInstructionsDescription'] := SpecialInstructions; with AnElement.OpenElement('_PRODUCT') do begin AttributeValues['RequestedCompletionDueDate'] := uInternetUtils.DateTimeToISO8601(DueDate); AttributeValues['RequestedAcceptaceDueDate'] := uInternetUtils.DateTimeToISO8601(AcceptanceDueDate); end; end; end; { TOrders } constructor TOrders.Create; begin Create(TOrder); end; function TOrders.First(var AOrder : TOrder) : Boolean; begin Result := First(TCollectionItem(AOrder)); end; function TOrders.Next(var AOrder : TOrder) : Boolean; begin Result := Next(TCollectionItem(AOrder)); end; function TOrders.GetOrder(Index : Integer) : TOrder; begin Result := Items[Index] as TOrder; end; function TOrders.Add : TOrder; begin Result := inherited Add as TOrder; end; { TRequest } constructor TRequest.Create(ACollection : TCollection); begin inherited; FOrders := TOrders.Create; end; destructor TRequest.Destroy; begin FOrders.Free; inherited; end; function TRequest.GetClientName : string; begin Result := (Envelope as TMISMORequestEnvelope).SubmittingParty.CompanyName; end; function TRequest.GetAppraiserName : string; begin Result := (Envelope as TMISMORequestEnvelope).ReceivingParty.CompanyName; end; function TRequest.GetDescription(const LinePrefix : string) : string; var ThisOrder : TOrder; begin Result := inherited GetDescription(LinePrefix); if RequestDate <> EMPTY_DATE then Result := Result + #13#10 + LinePrefix + 'RequestDate=' + uInternetUtils.DateTimeToISO8601(RequestDate); if Priority <> EMPTY_STRING then Result := Result + #13#10 + LinePrefix + 'RequestDate=' + Priority; if FOrders.First(ThisOrder) then begin repeat Result := Result + ThisOrder.GetDescription(LinePrefix); until not FOrders.Next(ThisOrder); end; end; procedure TRequest.Parse(AnElement : TXMLElement); var DataElement, RequestElement : TXMLElement; begin inherited Parse(AnElement); if AnElement <> nil then begin RequestDate := uInternetUtils.ISO8601ToDateTime(AnElement.AttributeValues['RequestDatetime']); InternalAccountIdentifier := AnElement.AttributeValues['InternalAccountIdentifier']; LoginAccountIdentifier := AnElement.AttributeValues['LoginAccountIdentifier']; LoginAccountPassword := AnElement.AttributeValues['LoginAccountPassword']; RequestingPartyBranchIdentifier := AnElement.AttributeValues['RequestingPartyBranchIdentifier']; if AnElement.FindElement('REQUEST_DATA', DataElement) then begin if DataElement.FindElement('VALUATION_REQUEST', RequestElement) then begin Priority := RequestElement.AttributeValues['PriorityDescription']; FOrders.Add.Parse(RequestElement); end; Self.XML.Assign(DataElement); // the root of the nested FXML will be VALUATION_REQUEST end; end; end; procedure TRequest.Compose(AnElement : TXMLElement); begin inherited Compose(AnElement); AnElement.AttributeValues['RequestDatetime'] := uInternetUtils.DateTimeToISO8601(Self.RequestDate); AnElement.AttributeValues['InternalAccountIdentifier'] := InternalAccountIdentifier; AnElement.AttributeValues['LoginAccountIdentifier'] := LoginAccountIdentifier; AnElement.AttributeValues['LoginAccountPassword'] := LoginAccountPassword; AnElement.AttributeValues['RequestingPartyBranchIdentifier'] := RequestingPartyBranchIdentifier; if Self.FXML <> nil then begin AnElement.OpenElement('REQUEST_DATA'). OpenElement(uMISMOImportExport.APPRAISAL_RESPONSE_ELEMENT_NAME).Assign(Self.Data); end; end; { TResponses } constructor TResponses.Create; begin Create(TResponse); end; function TResponses.GetDescription(const LinePrefix : string) : string; var ThisResponse : TResponse; begin Result := EMPTY_STRING; if First(ThisResponse) then repeat Result := Result + ThisResponse.GetDescription(LinePrefix + 'Response'); until not Next(ThisResponse); end; function TResponses.First(var AResponse : TResponse) : Boolean; begin Result := inherited First(TCollectionItem(AResponse)); end; function TResponses.Next(var AResponse : TResponse) : Boolean; begin Result := inherited Next(TCollectionItem(AResponse)); end; function TResponses.Add : TResponse; begin Result := inherited Add as TResponse; end; { TStatuses } constructor TStatuses.Create; begin Create(TResponseStatus); end; function TStatuses.GetDescription(const LinePrefix : string) : string; var ThisStatus : TResponseStatus; begin Result := EMPTY_STRING; if First(ThisStatus) then repeat Result := Result + ThisStatus.GetDescription(LinePrefix + 'Status'); until not Next(ThisStatus); end; function TStatuses.First(var AStatus : TResponseStatus) : Boolean; begin Result := inherited First(TCollectionItem(AStatus)); end; function TStatuses.Next(var AStatus : TResponseStatus) : Boolean; begin Result := inherited Next(TCollectionItem(AStatus)); end; { TResponse } constructor TResponse.Create(ACollection : TCollection); begin inherited; FStatuses := TStatuses.Create; FReports := TCraftingStringList.Create; FResponseDate := SysUtils.Now; end; destructor TResponse.Destroy; begin FStatuses.Free; FReports.Free; inherited; end; function TResponse.GetDescription(const LinePrefix : string) : string; begin Result := inherited GetDescription(LinePrefix) + FStatuses.GetDescription(LinePrefix + 'Status'); if ResponseDate <> EMPTY_DATE then Result := Result + #13#10 + LinePrefix + 'ResponseDate=' + uInternetUtils.DateTimeToISO8601(Self.ResponseDate); end; procedure TResponse.Parse(AnElement : TXMLElement); var ThisElement : TXMLElement; begin inherited Parse(AnElement); OrderID := Keys.Values['OrderID']; ClientID := Keys.Values['ClientID']; if AnElement <> nil then begin if AnElement.FirstElement('STATUS', ThisElement) then begin repeat AddStatus.Parse(ThisElement); until not AnElement.NextElement('STATUS', ThisElement); end; if AnElement.AttributeValues['ResponseDateTime'] <> EMPTY_STRING then Self.ResponseDate := uInternetUtils.ISO8601ToDateTime(AnElement.AttributeValues['ResponseDateTime']); if AnElement.FirstElement('RESPONSE_DATA', ThisElement) then begin Self.Data.Assign(ThisElement); repeat if ThisElement.ElementCount > 0 then FReports.Add(ThisElement.Elements[0].Compose); until not AnElement.NextElement('RESPONSE_DATA', ThisElement); end; end; end; procedure TResponse.Compose(AnElement : TXMLElement); var Counter : Integer; begin inherited Compose(AnElement); with AnElement do begin AttributeValues['ResponseDateTime'] := uInternetUtils.DateTimeToISO8601(Self.ResponseDate); if Self.FXML <> nil then begin if not Self.Data.IsEmpty then AddElement('RESPONSE_DATA').Assign(Self.Data); end; for Counter := 0 to StatusCount - 1 do Statuses[Counter].Compose(AddElement('STATUS')); end; end; function TResponse.GetStatus(Index : Integer) : TResponseStatus; begin Result := FStatuses.Items[Index] as TResponseStatus; end; function TResponse.AddStatus : TResponseStatus; begin Result := FStatuses.Add as TResponseStatus; end; function TResponse.StatusCount : Integer; begin Result := FStatuses.Count; end; function TResponse.GetReport(Index : Integer) : string; begin Result := FReports.Strings[Index]; end; procedure TResponse.AddReport(const AText : string); begin FReports.Add(AText); end; function TResponse.ReportCount : Integer; begin Result := FReports.Count; end; { TContacts } constructor TContacts.Create; begin Create(TContact); end; function TContacts.GetDescription(const LinePrefix : string) : string; var ThisContact : TContact; begin Result := EMPTY_STRING; if First(ThisContact) then begin repeat Result := Result + ThisContact.GetDescription(LinePrefix + 'Contact'); until not Next(ThisContact); end; end; function TContacts.First(var AContact : TContact) : Boolean; begin Result := inherited First(TCollectionItem(AContact)); end; function TContacts.Next(var AContact : TContact) : Boolean; begin Result := inherited Next(TCollectionItem(AContact)); end; { TContact } constructor TContact.Create; begin FDetails := TCraftingCollection.Create(TContactDetail); end; destructor TContact.Destroy; begin FDetails.Free; inherited; end; procedure TContact.Clear; begin FDetails.Clear; FName := EMPTY_STRING; FStreetAddress := EMPTY_STRING; FStreetAddress2 := EMPTY_STRING; FCity := EMPTY_STRING; FState := EMPTY_STRING; FPostalCode := EMPTY_STRING; FCountry := EMPTY_STRING; end; function TContact.QuickName : string; begin if DetailCount > 0 then Result := Details[0].Name + ' (' + Self.CompanyName + ')' else Result := Self.CompanyName; end; function TContact.GetDescription(const LinePrefix : string) : string; var DetailCounter : Integer; begin Result := ''; if CompanyName <> EMPTY_STRING then Result := Result + #13#10 + LinePrefix + 'CompanyName=' + CompanyName; if StreetAddress <> EMPTY_STRING then Result := Result + #13#10 + LinePrefix + 'StreetAddress=' + StreetAddress; if StreetAddress2 <> EMPTY_STRING then Result := Result + #13#10 + LinePrefix + 'StreetAddress2=' + StreetAddress2; if City <> EMPTY_STRING then Result := Result + #13#10 + LinePrefix + 'City=' + City; if State <> EMPTY_STRING then Result := Result + #13#10 + LinePrefix + 'State=' + State; if PostalCode <> EMPTY_STRING then Result := Result + #13#10 + LinePrefix + 'PostalCode=' + PostalCode; if Country <> EMPTY_STRING then Result := Result + #13#10 + LinePrefix + 'Country=' + Country; if Identifier <> EMPTY_STRING then Result := Result + #13#10 + LinePrefix + 'Identifier=' + Identifier; for DetailCounter := 0 to DetailCount - 1 do begin Result := TrimLeft(Result + #13#10) + Details[DetailCounter].GetDescription(LinePrefix + 'Detail' + IntToStr(DetailCounter)); end; end; function TContact.AddDetail : TContactDetail; begin Result := FDetails.Add as TContactDetail; end; function TContact.GetContactDetail(Index : Integer) : TContactDetail; begin Result := FDetails.Items[Index] as TContactDetail; end; function TContact.DetailCount : Integer; begin Result := FDetails.Count; end; procedure TContact.Parse(AnElement : TXMLElement); var ThisElement : TXMLElement; begin if AnElement <> nil then begin with AnElement do begin Self.CompanyName := AttributeValues['_Name']; Self.StreetAddress := AttributeValues['_StreetAddress']; Self.StreetAddress2 := AttributeValues['_StreetAddress2']; Self.City := AttributeValues['_City']; Self.State := AttributeValues['_State']; Self.PostalCode := AttributeValues['_PostalCode']; Self.Country := AttributeValues['_Country']; Self.Identifier := AttributeValues['_Identifier']; if FirstElement('CONTACT_DETAIL', ThisElement) then begin repeat AddDetail.Parse(ThisElement); until not NextElement('CONTACT_DETAIL', ThisElement); end; end; end; end; procedure TContact.Compose(AnElement : TXMLElement); var Counter : Integer; begin with AnElement do begin AttributeValues['_Name'] := Self.CompanyName; AttributeValues['_StreetAddress'] := StreetAddress; AttributeValues['_StreetAddress2'] := StreetAddress2; AttributeValues['_City'] := City; AttributeValues['_State'] := State; AttributeValues['_PostalCode'] := PostalCode; AttributeValues['_Country'] := Country; AttributeValues['_Identifier'] := Self.Identifier; for Counter := 0 to DetailCount - 1 do Details[Counter].Compose(AddElement('CONTACT_DETAIL')); end; end; { TContactDetail } destructor TContactDetail.Destroy; begin FContactPoints.Free; inherited; end; procedure TContactDetail.Clear; begin FName := EMPTY_STRING; if FContactPoints <> nil then FContactPoints.Clear; end; function TContactDetail.GetDescription(const LinePrefix : string) : string; var Counter : Integer; begin if Name <> EMPTY_STRING then Result := #13#10 + LinePrefix + 'Name=' + Self.Name else Result := EMPTY_STRING; for Counter := 0 to ContactPointCount - 1 do begin Result := TrimLeft(Result + #13#10) + ContactPoint[Counter].GetDescription(LinePrefix + 'Point' + IntToStr(Counter)); end; end; function TContactDetail.GetContactPoints : TCraftingCollection; begin if FContactPoints = nil then FContactPoints := TCraftingCollection.Create(TContactPoint); Result := FContactPoints; end; function TContactDetail.AddContactPoint : TContactPoint; begin Result := ContactPoints.Add as TContactPoint; end; function TContactDetail.GetContactPoint(Index : Integer) : TContactPoint; begin Result := ContactPoints.Items[Index] as TContactPoint; end; function TContactDetail.ContactPointCount : Integer; begin if FContactPoints = nil then Result := 0 else Result := FContactPoints.Count; end; procedure TContactDetail.Parse(AnElement : TXMLElement); var ThisElement : TXMLElement; begin Clear; if AnElement <> nil then begin Self.Name := AnElement.AttributeValues['_Name']; if AnElement.FirstElement('CONTACT_POINT', ThisElement) then begin repeat AddContactPoint.Parse(ThisElement); until not AnElement.NextElement('CONTACT_POINT', ThisElement); end; end; end; procedure TContactDetail.Compose(AnElement : TXMLElement); var Counter : Integer; begin AnElement.AttributeValues['_Name'] := Self.Name; for Counter := 0 to ContactPointCount - 1 do ContactPoint[Counter].Compose(AnElement.AddElement('CONTACT_POINT'), Self); end; { TRequestingParty } constructor TRequestingParty.Create; begin inherited; FPreferredResponse := TPreferredResponse.Create; end; destructor TRequestingParty.Destroy; begin FPreferredResponse.Free; inherited; end; procedure TRequestingParty.Clear; begin inherited; FPreferredResponse.Clear; end; function TRequestingParty.GetDescription(const LinePrefix : string) : string; begin Result := inherited GetDescription(LinePrefix) + TrimRight(#13#10 + FPreferredResponse.GetDescription(LinePrefix + 'PreferredResponse')); end; procedure TRequestingParty.Parse(AnElement : TXMLElement); begin inherited Parse(AnElement); if AnElement <> nil then PreferredResponse.Parse(AnElement); end; procedure TRequestingParty.Compose(AnElement : TXMLElement); begin inherited Compose(AnElement); PreferredResponse.Compose(AnElement); end; { TSubmittingParty } procedure TSubmittingParty.Clear; begin inherited; FLoginAccountIdentifier := EMPTY_STRING; FLoginAccountPassword := EMPTY_STRING; end; function TSubmittingParty.GetDescription(const LinePrefix : string) : string; begin Result := inherited GetDescription(LinePrefix); if LoginAccountIdentifier <> EMPTY_STRING then Result := Result + #13#10 + LinePrefix + 'LoginAccountIdentifier=' + LoginAccountIdentifier; if LoginAccountPassword <> EMPTY_STRING then Result := Result + #13#10 + LinePrefix + 'LoginAccountPassword=' + LoginAccountPassword; if SequenceIdentifier <> EMPTY_STRING then Result := Result + #13#10 + LinePrefix + 'SequenceIdentifier=' + SequenceIdentifier; end; procedure TSubmittingParty.Parse(AnElement : TXMLElement); begin inherited Parse(AnElement); if AnElement <> nil then begin LoginAccountIdentifier := AnElement.AttributeValues['LoginAccountIdentifier']; LoginAccountPassword := AnElement.AttributeValues['LoginAccountPassword']; SequenceIdentifier := AnElement.AttributeValues['SequenceIdentifier']; end; end; procedure TSubmittingParty.Compose(AnElement : TXMLElement); begin inherited Compose(AnElement); AnElement.AttributeValues['LoginAccountIdentifier'] := LoginAccountIdentifier; AnElement.AttributeValues['LoginAccountPassword'] := LoginAccountPassword; AnElement.AttributeValues['SequenceIdentifier'] := SequenceIdentifier; end; { TPreferredResponse } procedure TPreferredResponse.Clear; begin FFormat := pfUnknown; FMethod := dmUnknown; FFormatOther := EMPTY_STRING; FMethodOther := EMPTY_STRING; FDestination := EMPTY_STRING; end; function TPreferredResponse.GetDescription(const LinePrefix : string) : string; begin Result := EMPTY_STRING; if FFormat <> pfUnknown then Result := Result + #13#10 + LinePrefix + 'Format=' + PreferredFormatToStr(FFormat); if FMethod <> dmUnknown then Result := Result + #13#10 + LinePrefix + 'Method=' + PreferredDeliveryMethodToStr(FMethod); if FFormatOther <> EMPTY_STRING then Result := Result + #13#10 + LinePrefix + 'FormatOther=' + FFormatOther; if FMethodOther <> EMPTY_STRING then Result := Result + #13#10 + LinePrefix + 'MethodOther=' + FMethodOther; if FDestination <> EMPTY_STRING then Result := Result + #13#10 + LinePrefix + 'Destination=' + FDestination; end; procedure TPreferredResponse.Parse(AnElement : TXMLElement); begin if AnElement <> nil then begin Self.Format := StrToResponseFormat(AnElement.AttributeValues['_Format']); Self.Method := StrToResponseMethod(AnElement.AttributeValues['_Method']); Self.FormatOther := AnElement.AttributeValues['_FormatOtherDescription']; Self.MethodOther := AnElement.AttributeValues['_MethodOther']; Self.Destination := AnElement.AttributeValues['_Destination']; end; end; procedure TPreferredResponse.Compose(AnElement : TXMLElement); begin with AnElement do begin AttributeValues['_Format'] := PREFERRED_FORMAT_NAMES[Self.Format]; AttributeValues['_Method'] := PREFERRED_DELIVERY_NAMES[Self.Method]; AttributeValues['_FormatOtherDescription'] := Self.FormatOther; AttributeValues['_MethodOther'] := Self.MethodOther; AttributeValues['_Destination'] := Self.Destination; end; end; { TContactPoint } procedure TContactPoint.Clear; begin FRole := cprUnknown; FContactType := cptUnknown; FDescription := EMPTY_STRING; FValue := EMPTY_STRING; end; function TContactPoint.GetDescription(const LinePrefix : string) : string; begin Result := EMPTY_STRING; if Value <> EMPTY_STRING then Result := Result + #13#10 + LinePrefix + 'Value=' + Value; if Role <> cprUnknown then Result := Result + #13#10 + LinePrefix + 'Role=' + ContactPointRoleToStr(Role); if ContactType <> cptUnknown then Result := Result + #13#10 + LinePrefix + 'Type=' + ContactPointTypeToStr(ContactType); if Description <> EMPTY_STRING then Result := Result + #13#10 + LinePrefix + 'Description=' + Description; end; procedure TContactPoint.Parse(AnElement : TXMLElement; ADetail : TContactDetail = nil); begin if AnElement <> nil then begin with AnElement do begin Self.Role := StrToContactPointRole(AttributeValues['_RoleType']); Self.ContactType := StrToContactPointType(AttributeValues['_Type']); Self.Description := AttributeValues['_TypeOtherDescription']; Self.Value := AttributeValues['_Value']; if (ADetail <> nil) and uCraftClass.StrToBool(AttributeValues['_PreferenceIndicator']) then ADetail.PreferredContactPoint := Self end; end; end; procedure TContactPoint.Compose(AnElement : TXMLElement; ADetail : TContactDetail = nil); begin with AnElement do begin AttributeValues['_RoleType'] := CONTACT_POINT_ROLE_NAMES[Self.Role]; AttributeValues['_Type'] := CONTACT_POINT_TYPE_NAMES[Self.ContactType]; AttributeValues['_TypeOtherDescription'] := Self.Description; AttributeValues['_Value'] := Self.Value; if ADetail <> nil then AttributeValues['_PreferenceIndicator'] := MISMOBoolToStr(ADetail.PreferredContactPoint = Self); end; end; { TStatusEnvelope } function ComposeStatusEnvelope(FromID, ToID, AnOrderID : string; NewStatus : TeTracStatus; AComment : string; ADate : TDateTime) : string; var ThisEnvelope : TStatusEnvelope; begin ThisEnvelope := TStatusEnvelope.Create; with ThisEnvelope do try RespondingParty.Identifier := FromID; RespondToParty.Identifier := ToID; OrderID := AnOrderID; InspectionDate := ADate; Date := SysUtils.Now; Status := NewStatus; Message := AComment; Result := Compose; finally Free; end; end; function TStatusEnvelope.GetOrderID : string; begin Result := FOrderID; end; procedure TStatusEnvelope.SetOrderID(Value : string); begin inherited; FOrderID := Value; end; procedure TStatusEnvelope.Parse(AnXMLElement : TXMLElement); var ThisElement : TXMLElement; begin inherited; if AnXMLElement.FindElement('/RESPONSE_GROUP/RESPONSE/APPRAISAL_STATUS', ThisElement) then begin Self.Status := CodeToStatus(StrToIntDef(ThisElement.AttributeValues['_Code'], -1)); if Self.Status = etsUnknown then Self.Status := StrToStatus(ThisElement.AttributeValues['_Name']); Self.Date := uInternetUtils.ISO8601ToDateTime(ThisElement.AttributeValues['_Date']); Self.Message := ThisElement.AttributeValues['_Message']; Self.InspectionDate := uInternetUtils.ISO8601ToDateTime(ThisElement.AttributeValues['InspectionDate']); Self.OrderID := ThisElement.AttributeValues['VenderOrderIdentifier']; end; end; procedure TStatusEnvelope.Compose(AnXMLElement : TXMLElement); begin if Self.Status = etsUnknown then raise Exception.Create('This status envelope does not have any status set'); inherited Compose(AnXMLElement); with AnXMLElement.OpenElement('/RESPONSE_GROUP/RESPONSE/APPRAISAL_STATUS') do begin AttributeValues['_Code'] := IntToStr(StatusToCode(Self.Status)); AttributeValues['_Name'] := StatusToStr(Self.Status); AttributeValues['_Date'] := uInternetUtils.DateTimeToISO8601(Self.Date); AttributeValues['_Message'] := Self.Message; AttributeValues['InspectionDate'] := uInternetUtils.DateTimeToISO8601(Self.InspectionDate); AttributeValues['VenderOrderIdentifier'] := Self.OrderID; end; end; { TMessageEnvelope } function TMessageEnvelope.GetOrderID : string; begin Result := FOrderID; end; procedure TMessageEnvelope.SetOrderID(Value : string); begin FOrderID := Value; end; procedure TMessageEnvelope.Compose(AnXMLElement: TXMLElement); begin inherited Compose(AnXMLElement); with AnXMLElement.OpenElement('/RESPONSE_GROUP/RESPONSE/APPRAISAL_MESSAGE') do begin AttributeValues['_Date'] := uInternetUtils.DateTimeToISO8601(Self.Date); AttributeValues['_Message'] := Self.Message; AttributeValues['_ReplyRequestedIndicator'] := MISMOBoolToStr(Self.ReplyRequested); AttributeValues['_PriorityDescription'] := Self.Priority; AttributeValues['_VenderOrderIdentifier'] := Self.OrderID; end; end; procedure TMessageEnvelope.Parse(AnXMLElement: TXMLElement); var ThisElement : TXMLElement; begin inherited; if AnXMLElement.FindElement('/RESPONSE_GROUP/RESPONSE/APPRAISAL_MESSAGE', ThisElement) then begin Self.Date := uInternetUtils.ISO8601ToDateTime(ThisElement.AttributeValues['_Date']); Self.Message := ThisElement.AttributeValues['_Message']; Self.ReplyRequested := StrToBool(ThisElement.AttributeValues['_ReplyRequestedIndicator']); Self.Priority := ThisElement.AttributeValues['_PriorityDescription']; Self.OrderID := ThisElement.AttributeValues['_VenderOrderIdentifier']; end; end; end.
{******************************************************************************} { } { Delphi FireMonkey Platform } { } { Flip View Control for Metropolis UI } { } { Copyright(c) 2012 Embarcadero Technologies, Inc. } { } { } { This unit containes abstract interface for access and navigate } { to slider data item } { } {******************************************************************************} unit FMX.FlipView.Data; interface uses System.Generics.Collections, System.Rtti, FMX.Types; type { TAbstractDataSource } /// <summary> /// It is collection of abstract data items with access methods. /// </summary> TAbstractDataSource = class abstract protected function GetCurrent: TObject; virtual; abstract; function GetNext: TObject; virtual; abstract; function GetPrevious: TObject; virtual; abstract; public { Items Navigation } procedure GoFirst; virtual; abstract; procedure Forward; virtual; abstract; procedure Backward; virtual; abstract; procedure GoLast; virtual; abstract; function IsFirst: Boolean; virtual; abstract; function IsLast: Boolean; virtual; abstract; function HasItems: Boolean; virtual; abstract; { Data Access} procedure Load; virtual; abstract; procedure Clear; virtual; abstract; property Current: TObject read GetCurrent; property Next: TObject read GetNext; property Previous: TObject read GetPrevious; end; /// <summary> /// It is collection of images (TBitmap) /// </summary> TImageDataSource = class (TAbstractDataSource) strict private FImages: array of TBitmap; FCurrentIndex: Integer; protected function GetCurrent: TObject; override; function GetNext: TObject; override; function GetPrevious: TObject; override; public constructor Create; destructor Destroy; override; { Items Navigation } function IsFirst: Boolean; override; function IsLast: Boolean; override; function HasItems: Boolean; override; procedure GoFirst; override; procedure Forward; override; procedure Backward; override; procedure GoLast; override; { Data Access} procedure Clear; override; procedure Load; override; end; implementation uses System.SysUtils; { TImageIterator } procedure TImageDataSource.Clear; var I: Integer; begin for I := Low(FImages) to High(FImages) do FImages[I].Free; SetLength(FImages, 0); end; constructor TImageDataSource.Create; begin FCurrentIndex := -1; end; function TImageDataSource.GetCurrent: TObject; begin Result := FImages[FCurrentIndex]; end; destructor TImageDataSource.Destroy; begin Clear; inherited Destroy; end; function TImageDataSource.IsFirst: Boolean; begin Result := (FCurrentIndex <> -1) and (FCurrentIndex = Low(FImages)); end; function TImageDataSource.IsLast: Boolean; begin Result := (FCurrentIndex <> -1) and (FCurrentIndex = High(FImages)); end; procedure TImageDataSource.Load; const ImagesPath = './images/'; var SR: TSearchRec; Res: Integer; I: Integer; ImagesFilter: string; begin I := 0; // Find all images ImagesFilter := ImagesPath + '*.jpg'; Res := FindFirst(ImagesFilter, faAnyFile, SR); while Res = 0 do begin SetLength(FImages, I + 1); FImages[I] := TBitmap.CreateFromFile(ImagesPath + SR.Name); Res := FindNext(SR); Inc(I); end; if Length(FImages) > 0 then FCurrentIndex := 0 else FCurrentIndex := -1; end; procedure TImageDataSource.Forward; begin if not IsLast then Inc(FCurrentIndex); end; procedure TImageDataSource.Backward; begin if not IsFirst then Inc(FCurrentIndex, -1); end; procedure TImageDataSource.GoFirst; begin if Length(FImages) > 0 then FCurrentIndex := 0 else FCurrentIndex := -1; end; procedure TImageDataSource.GoLast; begin if Length(FImages) > 0 then FCurrentIndex := High(FImages) else FCurrentIndex := -1; end; function TImageDataSource.GetNext: TObject; begin if not IsLast then Result := FImages[FCurrentIndex + 1]; end; function TImageDataSource.GetPrevious: TObject; begin if not IsFirst then Result := FImages[FCurrentIndex - 1]; end; function TImageDataSource.HasItems: Boolean; begin Result := Length(FImages) > 0; end; end.
unit uClasseCalculadora; interface uses uInterfaceObjeto, uClasseSoma, System.Classes, System.Generics.Collections, uCalculadoraEventos; type TCalculadora = class(TInterfacedObject, iCalculadora, iCalculadoraDisplay) private FEventoDisplay : TEventoDisplay; FLista : TList<Double>; 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: TEventoDisplay): iCalculadoraDisplay; function EndDisplay: iCalculadora; end; implementation uses System.SysUtils, uClasseMetodosUteis, uClasseDividir, uClasseMultiplicar, uClasseSubtrair; { TCalculadora } function TCalculadora.Add(Value: String): iCalculadora; begin Result:= Self; FLista.Add(Value.ToNumerico); end; function TCalculadora.Add(Value: Integer): iCalculadora; begin Result:= Self; FLista.Add(Value.ToDouble) end; function TCalculadora.Add(Value: Currency): iCalculadora; begin Result:= Self; FLista.Add(Value); 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(FEventoDisplay).EndDisplay; end; function TCalculadora.EndDisplay: iCalculadora; begin Result:= Self; end; function TCalculadora.Multiplicar: iOperacoes; begin Result := TMultiplicar.New(FLista).Display.Resultado(FEventoDisplay).EndDisplay; end; class function TCalculadora.New: iCalculadora; begin Result := Self.Create; end; function TCalculadora.Resultado(Value: TEventoDisplay): iCalculadoraDisplay; begin Result:= Self; FEventoDisplay:= Value; end; function TCalculadora.Somar: iOperacoes; begin Result := TSoma.New(FLista).Display.Resultado(FEventoDisplay).EndDisplay; end; function TCalculadora.Subtrair: iOperacoes; begin Result := TSubtrair.New(FLista).Display.Resultado(FEventoDisplay).EndDisplay; end; end.
unit main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, wclBluetooth, wclWeDoWatcher, wclWeDoHub; type TfmMain = class(TForm) btConnect: TButton; btDisconnect: TButton; laStatus: TLabel; laIoState: TLabel; laNote: TLabel; cbNote: TComboBox; laOctave: TLabel; cbOctave: TComboBox; laDuration: TLabel; edDuration: TEdit; btPlay: TButton; btStop: TButton; procedure FormCreate(Sender: TObject); procedure btDisconnectClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btConnectClick(Sender: TObject); procedure btStopClick(Sender: TObject); procedure btPlayClick(Sender: TObject); private FManager: TwclBluetoothManager; FWatcher: TwclWeDoWatcher; FHub: TwclWeDoHub; FPiezo: TwclWeDoPiezo; procedure EnablePlay(Attached: Boolean); procedure EnableConnect(Connected: Boolean); procedure FHub_OnDeviceDetached(Sender: TObject; Device: TwclWeDoIo); procedure FHub_OnDeviceAttached(Sender: TObject; Device: TwclWeDoIo); procedure FHub_OnDisconnected(Sender: TObject; Reason: Integer); procedure FHub_OnConnected(Sender: TObject; Error: Integer); procedure FWatcher_OnHubFound(Sender: TObject; Address: Int64; Name: string); procedure Disconnect; end; var fmMain: TfmMain; implementation uses wclErrors; {$R *.dfm} procedure TfmMain.btConnectClick(Sender: TObject); var Res: Integer; Radio: TwclBluetoothRadio; begin // The very first thing we have to do is to open Bluetooth Manager. // That initializes the underlying drivers and allows us to work with // Bluetooth. // Always check result! Res := FManager.Open; if Res <> WCL_E_SUCCESS then // It should never happen but if it does notify user. ShowMessage('Unable to open Bluetooth Manager: 0x' + IntToHex(Res, 8)) else begin // Assume that no one Bluetooth Radio available. Radio := nil; Res := FManager.GetLeRadio(Radio); if Res <> WCL_E_SUCCESS then // If not, let user know that he has no Bluetooth. ShowMessage('No available Bluetooth Radio found') else begin // If found, try to start discovering. Res := FWatcher.Start(Radio); if Res <> WCL_E_SUCCESS then // It is something wrong with discovering starting. Notify user about // the error. ShowMessage('Unable to start discovering: 0x' + IntToHex(Res, 8)) else begin btConnect.Enabled := False; btDisconnect.Enabled := True; laStatus.Caption := 'Searching...'; end; end; // Again, check the found Radio. if Res <> WCL_E_SUCCESS then begin // And if it is null (not found or discovering was not started // close the Bluetooth Manager to release all the allocated resources. FManager.Close; // Also clean up found Radio variable so we can check it later. Radio := nil; end; end; end; procedure TfmMain.btDisconnectClick(Sender: TObject); begin Disconnect; end; procedure TfmMain.btPlayClick(Sender: TObject); const Notes: array of TwclWeDoPiezoNote = [ pnA, pnAis, pnB, pnC, pnCis, pnD, pnDis, pnE, pnF, pnFis, pnG, pnGis ]; var Note: TwclWeDoPiezoNote; Res: Integer; begin if FPiezo = nil then ShowMessage('"Device is not attached') else begin Note := Notes[cbNote.ItemIndex]; Res := FPiezo.PlayNote(Note, cbOctave.ItemIndex + 1, StrToInt(edDuration.Text)); if Res <> WCL_E_SUCCESS then ShowMessage('Play failed: 0x' + IntToHex(Res, 8)); end; end; procedure TfmMain.btStopClick(Sender: TObject); var Res: Integer; begin if FPiezo = nil then ShowMessage('Device is not attached') else begin Res := FPiezo.StopPlaying; if Res <> WCL_E_SUCCESS then ShowMessage('Stop failed: 0x' + IntToHex(Res, 8)); end; end; procedure TfmMain.Disconnect; begin FWatcher.Stop; FHub.Disconnect; FManager.Close; btConnect.Enabled := True; btDisconnect.Enabled := False; end; procedure TfmMain.EnableConnect(Connected: Boolean); begin if Connected then begin btConnect.Enabled := False; btDisconnect.Enabled := True; laStatus.Caption := 'Connected'; end else begin btConnect.Enabled := True; btDisconnect.Enabled := False; laStatus.Caption := 'Disconnected'; end; end; procedure TfmMain.EnablePlay(Attached: Boolean); begin if Attached then laIoState.Caption := 'Attached' else laIoState.Caption := 'Dectahed'; btPlay.Enabled := Attached; btStop.Enabled := Attached; cbNote.Enabled := Attached; cbOctave.Enabled := Attached; edDuration.Enabled := Attached; end; procedure TfmMain.FHub_OnConnected(Sender: TObject; Error: Integer); begin if Error <> WCL_E_SUCCESS then begin ShowMessage('Connect failed: 0x' + IntToHex(Error, 8)); EnableConnect(False); FManager.Close; end else EnableConnect(True); end; procedure TfmMain.FHub_OnDeviceAttached(Sender: TObject; Device: TwclWeDoIo); begin if Device.DeviceType = iodPiezo then begin FPiezo := TwclWeDoPiezo(Device); EnablePlay(True); end; end; procedure TfmMain.FHub_OnDeviceDetached(Sender: TObject; Device: TwclWeDoIo); begin if Device.DeviceType = iodPiezo then begin FPiezo := nil; EnablePlay(False); end; end; procedure TfmMain.FHub_OnDisconnected(Sender: TObject; Reason: Integer); begin EnableConnect(False); FManager.Close; end; procedure TfmMain.FormCreate(Sender: TObject); begin cbNote.ItemIndex := 0; cbOctave.ItemIndex := 0; FManager := TwclBluetoothManager.Create(nil); FWatcher := TwclWeDoWatcher.Create(nil); FWatcher.OnHubFound := FWatcher_OnHubFound; FHub := TwclWeDoHub.Create(nil); FHub.OnConnected := FHub_OnConnected; FHub.OnDisconnected := FHub_OnDisconnected; FHub.OnDeviceAttached := FHub_OnDeviceAttached; FHub.OnDeviceDetached := FHub_OnDeviceDetached; FPiezo := nil; end; procedure TfmMain.FormDestroy(Sender: TObject); begin Disconnect; FManager.Free; FWatcher.Free; FHub.Free; end; procedure TfmMain.FWatcher_OnHubFound(Sender: TObject; Address: Int64; Name: string); var Radio: TwclBluetoothRadio; Res: Integer; begin Radio := FWatcher.Radio; FWatcher.Stop; Res := FHub.Connect(Radio, Address); if Res <> WCL_E_SUCCESS then begin ShowMessage('Connect failed: 0x' + IntToHex(Res, 8)); EnableConnect(False); end else laStatus.Caption := 'Connecting'; end; end.
unit DeviceListUnit; //------------------------------------------------------------------------------ // Модуль, отвечающий за выполнение команд на подключенных ККТ //------------------------------------------------------------------------------ {$mode objfpc}{$H+} interface uses Classes, SysUtils, TypesUnit, AtolKKTUnit, LoggerUnit, ResponseUnit, RequestUnit, SegmentArrayUnit, base64; type { TDeviceList } TDeviceList = class(TObject) private class var devices: AtolDeviceArrayType; class var atol_do_comand: boolean; public class procedure addDevice(device: AtolDeviceType); class procedure clearDeviceList; class procedure DisconnectFromDevices; class function getDeviceByDeviceNumber( const num: integer): TAtolKKT; class function runComand(const cmd: RequestType): ResponseType; class function runDeviceComand(const cmd: RequestType): ResponseType; class procedure setAtolDoCommand(fDo: boolean); class function doDeviceComandPrintLastCheckCopy(var device: TAtolKKT; const cmd: RequestType): ResponseType; class function doDeviceComandCashRegisterInf(var device: TAtolKKT; const cmd: RequestType): ResponseType; class function doDeviceComandPrintTStringList(var device: TAtolKKT; const cmd: RequestType): ResponseType; class function doDeviceComandPrintStringList(var device: TAtolKKT; const cmd: RequestType): ResponseType; class function doDeviceComandChequePartialCut(var device: TAtolKKT; const cmd: RequestType): ResponseType; class function doDeviceComandChequeFullCut(var device: TAtolKKT; const cmd: RequestType): ResponseType; class function doDeviceComandResetSummary(var device: TAtolKKT; const cmd: RequestType): ResponseType; class function doDeviceComandTechReset(var device: TAtolKKT; const cmd: RequestType): ResponseType; class function doDeviceComandIncome(var device: TAtolKKT; const cmd: RequestType): ResponseType; class function doDeviceComandReturn(var device: TAtolKKT; const cmd: RequestType): ResponseType; class function doDeviceComandXReport(var device: TAtolKKT; const cmd: RequestType): ResponseType; class function doDeviceComandZReport(var device: TAtolKKT; const cmd: RequestType): ResponseType; class function doDeviceComandCashIncome(var device: TAtolKKT; const cmd: RequestType): ResponseType; class function doDeviceComandCashOutcome(var device: TAtolKKT; const cmd: RequestType): ResponseType; class function doDeviceComandOpenSession(var device: TAtolKKT; const cmd: RequestType): ResponseType; class function doDeviceComand(var device: TAtolKKT; const cmd: RequestType): ResponseType; class function doDeviceComandSegment(var device: TAtolKKT; const cmd: RequestType): ResponseType; class function getDeviceCashRegisterInf(var device: TAtolKKT): CashRegisterInfType; class function getSuccessResult(): ResponseType; end; implementation { TDeviceList } class procedure TDeviceList.addDevice(device: AtolDeviceType); begin SetLength(devices, Length(devices)+1); devices[Length(devices)-1] := device; end; class procedure TDeviceList.clearDeviceList; begin SetLength(devices, 0); end; class procedure TDeviceList.DisconnectFromDevices; var i: integer; begin for i := 0 to Length(devices)-1 do if devices[i].atol_cash_register then if Assigned(devices[i].atol) then begin devices[i].atol.free; devices[i].atol := nil; end; end; class function TDeviceList.getDeviceByDeviceNumber(const num: integer): TAtolKKT; var i: integer; begin result := nil; MyLogger.LogText('Searching device #'+IntToStr(num)+'...'); for i:=0 to Length(devices)-1 do if devices[i].atol_device_number=num then begin MyLogger.LogText('Device #'+IntToStr(num)+' found: index='+IntToStr(i)); if Assigned(devices[i].atol) then MyLogger.LogText('Assigned') else MyLogger.LogText('NOT assigned!!!'); result := devices[i].atol; break; end; end; class function TDeviceList.runComand(const cmd: RequestType): ResponseType; begin if cmd.comand = rctUnknown then begin result.response := '""'; result.error_code := -1; result.error := 'Неизвестная команда'; end else begin result := runDeviceComand(cmd); end; end; class function TDeviceList.runDeviceComand(const cmd: RequestType): ResponseType; var device: TAtolKKT; err_code: integer; begin device := getDeviceByDeviceNumber(cmd.atol_device_data.atol_device_number); if Assigned(device) or (cmd.comand = rctSegment) then begin try //raise EATOLException.create('Тестовое сообщение об окончании бумаги!', -3807); //result := device.printStringList(TEST_CHEQUE, true, true); if Assigned(device) then device.OperatorPassword := cmd.atol_device_data.atol_operator_password; result := doDeviceComand(device, cmd); except on e: exception do begin if (e is EATOLException) then err_code := (e as EATOLException).ErrorCode else err_code := -1; MyLogger.LogError(err_code, e.Message); result.error := e.Message; result.response := '""'; result.error_code := err_code; exit; end; end; end else begin Result.error := 'Устройство с номером '+IntToStr(cmd.atol_device_data.atol_device_number)+' не найдено'; Result.response := '""'; Result.error_code := -1; end; end; class procedure TDeviceList.setAtolDoCommand(fDo: boolean); begin atol_do_comand := fDo; end; class function TDeviceList.doDeviceComandPrintLastCheckCopy(var device: TAtolKKT; const cmd: RequestType): ResponseType; begin if atol_do_comand then device.PrintLastCheckCopy; result := getSuccessResult(); end; class function TDeviceList.doDeviceComandCashRegisterInf(var device: TAtolKKT; const cmd: RequestType): ResponseType; var inf: CashRegisterInfType; begin if atol_do_comand then begin inf := getDeviceCashRegisterInf(device); result.response := TResponse.getDeviceCashRegisterInfResponseString(inf); end else result.response := TResponse.getDeviceCashRegisterInfResponseStringDefault(); result.error_code := 0; result.error := ''; end; class function TDeviceList.doDeviceComandPrintTStringList(var device: TAtolKKT; const cmd: RequestType): ResponseType; var lst: TStringList; setmode_one: boolean; use_print_string: boolean; begin lst := TStringList.create; TRequest.getPrintTStringListRequestData(lst, setmode_one, use_print_string, cmd.data); try if atol_do_comand then device.printTStringList(lst, setmode_one, use_print_string); finally lst.Free; end; result := getSuccessResult(); end; class function TDeviceList.doDeviceComandPrintStringList(var device: TAtolKKT; const cmd: RequestType): ResponseType; var text: string; setmode_one: boolean; use_print_string: boolean; begin text := ''; TRequest.getPrintStringListRequestData(text, setmode_one, use_print_string, cmd.data); if atol_do_comand then device.printStringList(text, setmode_one, use_print_string); result := getSuccessResult(); end; class function TDeviceList.doDeviceComandChequePartialCut(var device: TAtolKKT; const cmd: RequestType): ResponseType; begin if atol_do_comand then device.PartialCut; result := getSuccessResult(); end; class function TDeviceList.doDeviceComandChequeFullCut(var device: TAtolKKT; const cmd: RequestType): ResponseType; begin if atol_do_comand then device.FullCut; result := getSuccessResult(); end; class function TDeviceList.doDeviceComandResetSummary(var device: TAtolKKT; const cmd: RequestType): ResponseType; begin if atol_do_comand then device.resetSummary; result := getSuccessResult(); end; class function TDeviceList.doDeviceComandTechReset(var device: TAtolKKT; const cmd: RequestType): ResponseType; begin if atol_do_comand then device.techReset; result := getSuccessResult(); end; class function TDeviceList.doDeviceComandIncome(var device: TAtolKKT; const cmd: RequestType): ResponseType; var h_lst, f_lst: TStringList; cheque_data: ChequeDataType; i: integer; begin h_lst := TStringList.create; f_lst := TStringList.create; TRequest.getIncomeRequestData(h_lst, f_lst, cheque_data, cmd.data); try if atol_do_comand then begin // печать заголовка if h_lst.count>0 then device.printTStringList(h_lst, true, false); device.openIncomeCheck(cheque_data.tr_id); for i:=0 to Length(cheque_data.goods)-1 do begin device.addProductToIncomeCheck(cheque_data.goods[i].name, cheque_data.goods[i].price, cheque_data.goods[i].kol, cheque_data.goods[i].nds, cheque_data.goods[i].barcode, cheque_data.goods[i].dep, cheque_data.goods[i].discount); end; // печать подвала if f_lst.count>0 then device.printTStringList(f_lst, false, false); if cheque_data.check_sm>0 then device.closeIncomeCheck(cheque_data.check_sm, cheque_data.check_discount_sm, cheque_data.type_close, cheque_data.cash_sm); end; finally h_lst.Free; f_lst.Free; end; result := getSuccessResult(); end; class function TDeviceList.doDeviceComandReturn(var device: TAtolKKT; const cmd: RequestType): ResponseType; var h_lst, f_lst: TStringList; cheque_data: ChequeDataType; i: integer; begin h_lst := TStringList.create; f_lst := TStringList.create; TRequest.getIncomeRequestData(h_lst, f_lst, cheque_data, cmd.data); try if atol_do_comand then begin // печать заголовка if h_lst.count>0 then device.printTStringList(h_lst, true, false); device.openReturnCheck(cheque_data.tr_id); for i:=0 to Length(cheque_data.goods)-1 do begin device.addProductToReturnCheck(cheque_data.goods[i].name, cheque_data.goods[i].price, cheque_data.goods[i].kol, cheque_data.goods[i].nds, cheque_data.goods[i].barcode, cheque_data.goods[i].dep, cheque_data.goods[i].discount); end; // печать подвала if f_lst.count>0 then device.printTStringList(f_lst, false, false); device.closeReturnCheck(cheque_data.type_close, cheque_data.check_discount_sm); end; finally h_lst.Free; f_lst.Free; end; result := getSuccessResult(); end; class function TDeviceList.doDeviceComandXReport(var device: TAtolKKT; const cmd: RequestType): ResponseType; begin if atol_do_comand then device.getXReport; result := getSuccessResult(); end; class function TDeviceList.doDeviceComandZReport(var device: TAtolKKT; const cmd: RequestType): ResponseType; begin if atol_do_comand then device.getZReport; result := getSuccessResult(); end; class function TDeviceList.doDeviceComandCashIncome(var device: TAtolKKT; const cmd: RequestType): ResponseType; begin if atol_do_comand then device.CashIncome(TRequest.getCashIncomeOutcomeRequestData(cmd.data)); result := getSuccessResult(); end; class function TDeviceList.doDeviceComandCashOutcome(var device: TAtolKKT; const cmd: RequestType): ResponseType; begin if atol_do_comand then device.cashOutcome(TRequest.getCashIncomeOutcomeRequestData(cmd.data)); result := getSuccessResult(); end; class function TDeviceList.doDeviceComandOpenSession(var device: TAtolKKT; const cmd: RequestType): ResponseType; begin if atol_do_comand then device.openSession; result := getSuccessResult(); end; class function TDeviceList.doDeviceComand(var device: TAtolKKT; const cmd: RequestType): ResponseType; begin case cmd.comand of rctPrintTestCheque: begin if atol_do_comand then device.printStringList(TEST_CHEQUE, true, true); result.response := '"готово"'; result.error_code := 0; result.error := ''; end; rctPrintLastCheckCopy: begin result := doDeviceComandPrintLastCheckCopy(device, cmd); end; rctCashRegisterInf: begin result := doDeviceComandCashRegisterInf(device, cmd); end; rctPrintTStringList: begin result := doDeviceComandPrintTStringList(device, cmd); end; rctPrintStringList: begin result := doDeviceComandPrintStringList(device, cmd); end; rctChequePartialCut: begin result := doDeviceComandChequePartialCut(device, cmd); end; rctChequeFullCut: begin result := doDeviceComandChequeFullCut(device, cmd); end; rctResetSummary: begin result := doDeviceComandResetSummary(device, cmd); end; rctTechReset: begin result := doDeviceComandTechReset(device, cmd); end; rctIncome: begin result := doDeviceComandIncome(device, cmd); end; rctReturn: begin result := doDeviceComandReturn(device, cmd); end; rctXReport: begin result := doDeviceComandXReport(device, cmd); end; rctZReport: begin result := doDeviceComandZReport(device, cmd); end; rctCashIncome: begin result := doDeviceComandCashIncome(device, cmd); end; rctCashOutcome: begin result := doDeviceComandCashOutcome(device, cmd); end; rctOpenSession: begin result := doDeviceComandOpenSession(device, cmd); end; rctSegment: begin result := doDeviceComandSegment(device, cmd); end; end; end; class function TDeviceList.doDeviceComandSegment(var device: TAtolKKT; const cmd: RequestType): ResponseType; var data: RequestSegmentType; full_data: string; req: RequestType; request_string: string; begin MyLogger.LogText('doDeviceComandSegment'); data := TRequest.getSegmentRequestData(cmd.data); MyLogger.LogText('doDeviceComandSegment: before addSegment()'); // накапливаем сегменты segments_arr.addSegment(data.guid, data.text, data.count); full_data := segments_arr.getGuidFullData(data.guid, true); if Trim(full_data)<>'' then begin // все сегменты пришли // декодируем данные-реальную-команду request_string := DecodeStringBase64(full_data); MyLogger.LogText('decoded request: '+request_string); // разберем команду req := TRequest.getRequestTypeByRequest(request_string); // и выполним, наконец result := runComand(req); end else // ждем следующий сегмент begin result := getSuccessResult(); end; end; class function TDeviceList.getDeviceCashRegisterInf(var device: TAtolKKT ): CashRegisterInfType; begin device.getStatus; result.KKMDateTime := formatdatetime('dd.mm.yyyy hh:nn:ss', device.getKKMDateTime); result.KKMEarnings := device.getKKMEarnings; result.KKMEarningSession := device.getKKMEarningSession; result.KKMSum := device.getKKMSum; result.Mode := device.getMode; result.SerialNumber := device.getSerialNumber; result.CheckFontSizeString := device.getCheckFontSizeString; result.CheckLineSpacing := device.getCheckLineSpacing; result.SessionNumber := device.getSessionNumber; result.isFiskal := device.isFiskal(); result.isSessionExceedLimit24 := device.isSessionExceedLimit24(); result.isSessionOpened := device.isSessionOpened; result.CashRegisterNum := device.CashRegisterNum; end; class function TDeviceList.getSuccessResult(): ResponseType; begin result.response := '"готово"'; result.error_code := 0; result.error := ''; end; end.
unit PriceList; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, LikeList, cxGridCustomPopupMenu, cxGridPopupMenu, DB, dxBar, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase, cxSplitter, cxContainer, cxEdit, cxTextEdit, cxMemo, cxDBEdit, StdCtrls, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, ExtCtrls, cxInplaceContainer, cxTL, cxDBTL, cxTLData, cxGraphics, cxCalendar, pFIBQuery, frxClass; type TfrmPriceList = class(TfrmLikeList) tlGroups: TcxDBTreeList; tlGroupsNAME: TcxDBTreeListColumn; tlGroupsID: TcxDBTreeListColumn; tlGroupsPARENT_ID: TcxDBTreeListColumn; tlGroupsCHILD_COUNT: TcxDBTreeListColumn; cxSplitter2: TcxSplitter; fibdsGoodsServices: TpFIBDataSet; fibdsGoodsServicesID: TFIBIntegerField; fibdsGoodsServicesPARENT_ID: TFIBIntegerField; fibdsGoodsServicesCHILD_COUNT: TFIBIntegerField; fibdsGoodsServicesNAME: TFIBStringField; dsGoodsServices: TDataSource; fibdsMainListID: TFIBIntegerField; fibdsMainListGOOD_SERVICE_ID: TFIBIntegerField; fibdsMainListDEPARTMENT_ID: TFIBIntegerField; fibdsMainListSTART_DATE: TFIBDateField; fibdsMainListPRICE: TFIBFloatField; fibdsMainListCOMMENTS: TFIBStringField; fibdsGoodsServicesITEM_TYPE: TFIBIntegerField; tvMainListDEPARTMENT_ID: TcxGridDBColumn; tvMainListSTART_DATE: TcxGridDBColumn; tvMainListPRICE: TcxGridDBColumn; tvMainListCOMMENTS: TcxGridDBColumn; cxSplitter3: TcxSplitter; grdSearch: TcxGrid; tvSearch: TcxGridDBTableView; tvSearchID: TcxGridDBColumn; tvSearchITEM_TYPE: TcxGridDBColumn; tvSearchNAME: TcxGridDBColumn; lvSearch: TcxGridLevel; fibdsSearch: TpFIBDataSet; fibdsSearchID: TFIBIntegerField; fibdsSearchITEM_TYPE: TFIBIntegerField; fibdsSearchNAME: TFIBStringField; dsSearch: TDataSource; tlGroupsITEM_TYPE: TcxDBTreeListColumn; fibdsMainListCAN_EDIT_PRICE: TFIBIntegerField; tvMainListCAN_EDIT_PRICE: TcxGridDBColumn; sbPrint: TdxBarButton; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure tlGroupsCustomDrawCell(Sender: TObject; ACanvas: TcxCanvas; AViewInfo: TcxTreeListEditCellViewInfo; var ADone: Boolean); procedure sbFilterClick(Sender: TObject); procedure tvSearchCustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); procedure tvSearchFocusedRecordChanged(Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); procedure sbApplyClick(Sender: TObject); procedure cxSplitter3AfterClose(Sender: TObject); procedure fibdsGoodsServicesBeforeScroll(DataSet: TDataSet); procedure sbCancelClick(Sender: TObject); procedure fibdsMainListAfterOpen(DataSet: TDataSet); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure fibdsMainListBeforeInsert(DataSet: TDataSet); procedure fibdsMainListBeforeOpen(DataSet: TDataSet); procedure fibdsMainListNewRecord(DataSet: TDataSet); procedure tvMainListCustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); procedure tvMainListEditing(Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem; var AAllow: Boolean); procedure tvMainListFocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); procedure tvMainListSTART_DATEPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); procedure fibdsMainListBeforeDelete(DataSet: TDataSet); procedure OpenAll; override; procedure Run(ID : Integer); override; procedure sbPrintClick(Sender: TObject); private { Private declarations } CurDate: Tdate; procedure DoSearch(ID : Integer); procedure GetValue(const VarName: String; var Value: Variant); public { Public declarations } procedure Search(S : String); end; var frmPriceList: TfrmPriceList; implementation uses DM, GoodsAndServices, Main, Departments, Misk; {$R *.dfm} var DepartmentID: Integer = 0; DMTagIncreased: Boolean = False; BkMrkGoodsServices: String = ''; BkMrkIDMainList: Integer = 0; procedure TfrmPriceList.FormCreate(Sender: TObject); begin FName := 'Прайс-лист'; inherited; cxSplitter3.CloseSplitter end; procedure TfrmPriceList.Run(ID : Integer); begin OpenAll; If (ID<>0) then DoSearch(ID); Show end; procedure TfrmPriceList.OpenAll; begin inherited; If Not(frmDM.trMain.InTransaction) then frmDM.trMain.StartTransaction; frmDM.fibdsDepartments.Open; If Not(DMTagIncreased) then Begin DMTagIncreased := True; frmDM.fibdsDepartments.Tag := Succ(frmDM.fibdsDepartments.Tag) End; If (fibdsGoodsServices.Active) then fibdsGoodsServices.ReopenLocate('ID') else Begin fibdsGoodsServices.FullRefresh; If (BkMrkGoodsServices<>'') then fibdsGoodsServices.Bookmark := BkMrkGoodsServices End; If (fibdsMainList.Active) then fibdsMainList.ReopenLocate('ID') else Begin fibdsMainList.FullRefresh; If (BkMrkIDMainList<>0) then fibdsMainList.Locate('ID',BkMrkIDMainList,[]) End; tlGroups.FullExpand end; procedure TfrmPriceList.FormClose(Sender: TObject; var Action: TCloseAction); begin If (frmDM.fibdsDepartments.Tag=1) then frmDM.fibdsDepartments.Close else frmDM.fibdsDepartments.Tag := Pred(frmDM.fibdsDepartments.Tag); inherited end; procedure TfrmPriceList.tlGroupsCustomDrawCell(Sender: TObject; ACanvas: TcxCanvas; AViewInfo: TcxTreeListEditCellViewInfo; var ADone: Boolean); begin If (AViewInfo.Node.Values[tlGroupsITEM_TYPE.ItemIndex]=0) then ACanvas.Font.Color := clWindowText else ACanvas.Font.Color := clrServices end; procedure TfrmPriceList.sbFilterClick(Sender: TObject); var S: string; begin If (InputQuery('Поиск','Наименование содержит:', S)) then Search(S) end; procedure TfrmPriceList.Search(S : String); begin fibdsSearch.Close; fibdsSearch.ParamByName('NAME').AsString := '%'+AnsiUpperCase(S)+'%'; fibdsSearch.Open; If (fibdsSearch.RecordCount=0) then MessageDlg('Записей, удовлетворяющих условию не найдено.', mtInformation, [mbOK], 0) else If (fibdsSearch.RecordCount>1) then Begin cxSplitter3.Visible := True; cxSplitter3.OpenSplitter; grdSearch.SetFocus End end; procedure TfrmPriceList.DoSearch(ID : Integer); begin tlGroups.FullExpand; tlGroups.FocusedNode := tlGroups.FindNodeByKeyValue(ID,tlGroupsID,nil,False) end; procedure TfrmPriceList.tvSearchCustomDrawCell( Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); begin If NOT(AviewInfo.Selected) then If (VarAsType(AViewInfo.GridRecord.Values[Sender.FindItemByName(Sender.Name+'ITEM_TYPE').Index],varInteger)=0) then ACanvas.Brush.Color := clrGroups else ACanvas.Brush.Color := clWindow end; procedure TfrmPriceList.tvSearchFocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); begin DoSearch(fibdsSearchID.AsInteger) end; procedure TfrmPriceList.sbApplyClick(Sender: TObject); begin If (MessageDlg('Сохранить все сделанные изменения?',mtInformation,[mbCancel,mbOK],0)=mrOK) then Begin fibdsMainList.ApplyUpdates; BkMrkGoodsServices := fibdsGoodsServices.Bookmark; BkMrkIDMainList := fibdsMainListID.Value; fibdsGoodsServices.DisableScrollEvents; trMain.Commit; OpenAll; fibdsGoodsServices.EnableScrollEvents; SetACButtons(False) End end; procedure TfrmPriceList.cxSplitter3AfterClose(Sender: TObject); begin cxSplitter3.Visible := False; fibdsSearch.Close end; procedure TfrmPriceList.fibdsGoodsServicesBeforeScroll(DataSet: TDataSet); begin If (sbApply.Enabled) then sbApply.Click end; procedure TfrmPriceList.sbCancelClick(Sender: TObject); begin If (MessageDlg('Отменить все сделанные изменения?',mtInformation,[mbCancel,mbOK],0)=mrOK) then Begin fibdsMainList.CancelUpdates; SetACButtons(False) End end; procedure TfrmPriceList.fibdsMainListAfterOpen(DataSet: TDataSet); begin If (fibdsGoodsServicesITEM_TYPE.AsInteger=1) then fibdsMainList.AllowedUpdateKinds := [ukModify, ukInsert, ukDelete] else fibdsMainList.AllowedUpdateKinds := []; SetACButtons(False) end; procedure TfrmPriceList.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; If (Key=vk_F6) then If (tlGroups.Focused) then Begin If (frmMain.FindComponent('frmGoodsAndServices')=nil) then frmGoodsAndServices := TfrmGoodsAndServices.Create(frmMain); frmGoodsAndServices.Run(tlGroups.FocusedNode.Values[tlGroupsID.ItemIndex]) End else If (tvMainList.Focused) then Begin If (frmMain.FindComponent('frmDepartments')=nil) then frmDepartments := TfrmDepartments.Create(frmMain); frmDepartments.Run(fibdsMainListDEPARTMENT_ID.AsInteger) End end; procedure TfrmPriceList.fibdsMainListBeforeInsert(DataSet: TDataSet); begin DataSet.DisableControls; DataSet.First; DepartmentID := fibdsMainListDEPARTMENT_ID.AsInteger; DataSet.EnableControls end; procedure TfrmPriceList.fibdsMainListBeforeOpen(DataSet: TDataSet); var fibqLocalAux : TpFIBQuery; begin fibqLocalAux := TpFIBQuery.Create(Nil); fibqLocalAux.Database := fibdsMainList.Database; fibqLocalAux.Transaction := fibdsMainList.Transaction; fibqLocalAux.SQL.Clear; fibqLocalAux.SQL.Add('select current_date from rdb$database'); fibqLocalAux.ExecQuery; CurDate := fibqLocalAux.Fields[0].AsDate; fibqLocalAux.Close; fibqLocalAux.Free end; procedure TfrmPriceList.fibdsMainListNewRecord(DataSet: TDataSet); begin If (DepartmentID<>0) then fibdsMainListDEPARTMENT_ID.Value := DepartmentID; fibdsMainListSTART_DATE.Value := CurDate+1 end; procedure TfrmPriceList.tvMainListCustomDrawCell( Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); begin If NOT(AviewInfo.Selected) then If (AViewInfo.GridRecord.Values[tvMainListSTART_DATE.Index]>CurDate) then ACanvas.Brush.Color := clWindow else ACanvas.Brush.Color := clrReadOnly end; procedure TfrmPriceList.tvMainListEditing(Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem; var AAllow: Boolean); begin AAllow := (tvMainList.DataController.Values[tvMainList.DataController.FocusedRecordIndex,tvMainListSTART_DATE.Index]>CurDate) end; procedure TfrmPriceList.tvMainListFocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); begin inherited; sbDelete.Enabled := (tvMainList.DataController.Values[tvMainList.DataController.FocusedRecordIndex,tvMainListSTART_DATE.Index]>CurDate) end; procedure TfrmPriceList.tvMainListSTART_DATEPropertiesValidate( Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); begin ErrorText := 'Начало действия цены не может быть ранее следующего дня.'; Error := Not(VarAsType(DisplayValue,varDate)>CurDate) end; procedure TfrmPriceList.fibdsMainListBeforeDelete(DataSet: TDataSet); begin If Not(tvMainList.DataController.Values[tvMainList.DataController.FocusedRecordIndex,tvMainListSTART_DATE.Index]>CurDate) then Begin MessageDlg('Нельзя удалять вступившие в силу позиции прайс-листа',mtError,[mbOk],0); Abort End end; procedure TfrmPriceList.sbPrintClick(Sender: TObject); begin frmDM.frxReport.DataSet := nil; frmDM.frxReport.DataSetName := ''; frmDM.frxReport.PreviewOptions.Buttons := [pbPrint,pbExport,pbZoom,pbFind,pbPageSetup,pbTools,pbNavigator]; frmDM.frxReport.OnGetValue := GetValue; PrintClick(Sender) end; procedure TfrmPriceList.GetValue(const VarName: String; var Value: Variant); begin If (VarName='Наименование организации') then Value := Institution.Name end; end.
unit dwsSystemInfoLibModule; interface uses Windows, SysUtils, Classes, Registry, dwsComp, dwsExprs, dwsUtils, dwsCPUUsage; type TOSNameVersion = record Name : String; Version : String; end; TdwsSystemInfoLibModule = class(TDataModule) dwsSystemInfo: TdwsUnit; procedure dwsSystemInfoClassesMemoryStatusConstructorsCreateEval( Info: TProgramInfo; var ExtObject: TObject); procedure dwsSystemInfoClassesOSVersionInfoMethodsNameEval( Info: TProgramInfo; ExtObject: TObject); procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); procedure dwsSystemInfoClassesOSVersionInfoMethodsVersionEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsSystemInfoClassesCPUInfoMethodsSystemUsageEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsSystemInfoClassesCPUInfoMethodsCountEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsSystemInfoClassesCPUInfoMethodsKernelUsageEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsSystemInfoClassesCPUInfoMethodsFrequencyMHzEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsSystemInfoClassesCPUInfoMethodsNameEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsSystemInfoClassesCPUInfoMethodsProcessUsageEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsSystemInfoClassesApplicationInfoMethodsVersionEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsSystemInfoClassesApplicationInfoMethodsExeNameEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsSystemInfoClassesApplicationInfoMethodsRunningAsServiceEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsSystemInfoClassesHostInfoMethodsNameEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsSystemInfoClassesHostInfoMethodsDNSDomainEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsSystemInfoClassesHostInfoMethodsDNSFullyQualifiedEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsSystemInfoClassesHostInfoMethodsDNSNameEval(Info: TProgramInfo; ExtObject: TObject); procedure dwsSystemInfoClassesApplicationInfoMethodsGetEnvironmentVariableEval( Info: TProgramInfo; ExtObject: TObject); procedure dwsSystemInfoClassesApplicationInfoMethodsSetEnvironmentVariableEval( Info: TProgramInfo; ExtObject: TObject); private { Private declarations } FOSNameVersion : TOSNameVersion; FGlobalMemory : TThreadCached<TMemoryStatusEx>; class var FRunningAsService : Boolean; public { Public declarations } class property RunningAsService : Boolean read FRunningAsService write FRunningAsService; end; implementation {$R *.dfm} procedure GetWin32_OSNameVersion(var osnv : TOSNameVersion); var reg : TRegistry; begin osnv.Name:='?'; osnv.Version:=Format('%d.%d.%d', [Win32MajorVersion, Win32MinorVersion, Win32BuildNumber]); reg:=TRegistry.Create; try reg.RootKey:=HKEY_LOCAL_MACHINE; reg.OpenKeyReadOnly('\Software\Microsoft\Windows NT\CurrentVersion\'); if reg.ValueExists('ProductName') then begin osnv.Name:=reg.ReadString('ProductName'); if Win32CSDVersion<>'' then osnv.Name:=osnv.Name+' '+Win32CSDVersion; end; finally reg.Free; end; end; function GetGlobalMemory(var ms : TMemoryStatusEx) : TSimpleCallbackStatus; begin ms.dwLength:=SizeOf(ms); GlobalMemoryStatusEx(ms); Result:=csContinue; end; // Adapted from Ian Boyd code published in // http://stackoverflow.com/questions/10854958/how-to-get-version-of-running-executable function GetModuleVersion(instance : THandle; var major, minor, release, build : Integer) : Boolean; var fileInformation : PVSFIXEDFILEINFO; verlen : Cardinal; rs : TResourceStream; m : TMemoryStream; resource : HRSRC; begin Result:=False; // Workaround bug in Delphi if resource doesn't exist resource:=FindResource(instance, PChar(1), RT_VERSION); if resource=0 then Exit; m:=TMemoryStream.Create; try rs:=TResourceStream.CreateFromID(instance, 1, RT_VERSION); try m.CopyFrom(rs, rs.Size); finally rs.Free; end; m.Position:=0; if VerQueryValue(m.Memory, '\', Pointer(fileInformation), verlen) then begin major := fileInformation.dwFileVersionMS shr 16; minor := fileInformation.dwFileVersionMS and $FFFF; release := fileInformation.dwFileVersionLS shr 16; build := fileInformation.dwFileVersionLS and $FFFF; Result:=True; end; finally m.Free; end; end; // GetHostName // function GetHostName(nameFormat : TComputerNameFormat) : UnicodeString; var n : Cardinal; begin n:=0; GetComputerNameExW(nameFormat, nil, n); SetLength(Result, n-1); GetComputerNameExW(nameFormat, PWideChar(Pointer(Result)), n); end; procedure TdwsSystemInfoLibModule.DataModuleCreate(Sender: TObject); begin // limit query rate to 10 Hz FGlobalMemory:=TThreadCached<TMemoryStatusEx>.Create(GetGlobalMemory, 100); GetWin32_OSNameVersion(FOSNameVersion); SystemCPU.Track; end; procedure TdwsSystemInfoLibModule.DataModuleDestroy(Sender: TObject); begin FGlobalMemory.Free; end; procedure TdwsSystemInfoLibModule.dwsSystemInfoClassesApplicationInfoMethodsExeNameEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=ParamStr(0); end; procedure TdwsSystemInfoLibModule.dwsSystemInfoClassesApplicationInfoMethodsGetEnvironmentVariableEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=GetEnvironmentVariable(Info.ParamAsString[0]); end; procedure TdwsSystemInfoLibModule.dwsSystemInfoClassesApplicationInfoMethodsRunningAsServiceEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsBoolean:=RunningAsService; end; procedure TdwsSystemInfoLibModule.dwsSystemInfoClassesApplicationInfoMethodsSetEnvironmentVariableEval( Info: TProgramInfo; ExtObject: TObject); begin SetEnvironmentVariableW(PWideChar(Info.ParamAsString[0]), PWideChar(Info.ParamAsString[1])); end; procedure TdwsSystemInfoLibModule.dwsSystemInfoClassesApplicationInfoMethodsVersionEval( Info: TProgramInfo; ExtObject: TObject); var major, minor, release, build : Integer; begin if GetModuleVersion(HInstance, major, minor, release, build) then Info.ResultAsString:=Format('%d.%d.%d.%d', [major, minor, release, build]) else Info.ResultAsString:='?.?.?.?'; end; procedure TdwsSystemInfoLibModule.dwsSystemInfoClassesCPUInfoMethodsCountEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsInteger:=SystemCPU.Count; end; procedure TdwsSystemInfoLibModule.dwsSystemInfoClassesCPUInfoMethodsFrequencyMHzEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsInteger:=SystemCPU.Frequency; end; procedure TdwsSystemInfoLibModule.dwsSystemInfoClassesCPUInfoMethodsKernelUsageEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsFloat:=SystemCPU.Kernel; end; procedure TdwsSystemInfoLibModule.dwsSystemInfoClassesCPUInfoMethodsNameEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=SystemCPU.Name; end; procedure TdwsSystemInfoLibModule.dwsSystemInfoClassesCPUInfoMethodsProcessUsageEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsFloat:=SystemCPU.ProcessUser+SystemCPU.ProcessKernel; end; procedure TdwsSystemInfoLibModule.dwsSystemInfoClassesCPUInfoMethodsSystemUsageEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsFloat:=SystemCPU.Usage; end; procedure TdwsSystemInfoLibModule.dwsSystemInfoClassesHostInfoMethodsDNSDomainEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=GetHostName(ComputerNameDnsDomain); end; procedure TdwsSystemInfoLibModule.dwsSystemInfoClassesHostInfoMethodsDNSFullyQualifiedEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=GetHostName(ComputerNameDnsFullyQualified); end; procedure TdwsSystemInfoLibModule.dwsSystemInfoClassesHostInfoMethodsDNSNameEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=GetHostName(ComputerNameDnsHostname); end; procedure TdwsSystemInfoLibModule.dwsSystemInfoClassesHostInfoMethodsNameEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=GetHostName(ComputerNameNetBIOS); end; procedure TdwsSystemInfoLibModule.dwsSystemInfoClassesMemoryStatusConstructorsCreateEval( Info: TProgramInfo; var ExtObject: TObject); procedure SetDetail(const detailName : String; total, avail : Int64); var detail : IInfo; begin detail:=Info.Vars[detailName]; detail.Member['Total'].ValueAsInteger:=total; detail.Member['Available'].ValueAsInteger:=avail; end; var ms : TMemoryStatusEx; begin ms:=FGlobalMemory.Value; SetDetail('Physical', ms.ullTotalPhys, ms.ullAvailPhys); SetDetail('Virtual', ms.ullTotalVirtual, ms.ullAvailVirtual); SetDetail('PageFile', ms.ullTotalPageFile, ms.ullAvailPageFile); end; procedure TdwsSystemInfoLibModule.dwsSystemInfoClassesOSVersionInfoMethodsNameEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=FOSNameVersion.Name; end; procedure TdwsSystemInfoLibModule.dwsSystemInfoClassesOSVersionInfoMethodsVersionEval( Info: TProgramInfo; ExtObject: TObject); begin Info.ResultAsString:=FOSNameVersion.Version; end; end.
unit UBoard; interface uses Classes,Windows,Graphics,Controls,Contnrs,ExtCtrls, Messages,Forms,SysUtils,Dialogs,UBrick,UShape,TetrixConst,Math, UMsg; type TBoardLastEmptyRec = record EndPoint:TPoint; Res:Boolean; Distance:Integer; end; type TBoard = class(TGraphicControl) private Board:TBitmap; OptionsWidth:Integer; Msg:TMsg; ShapeList:TObjectList; BrickList:TObjectList; GameTimer:TTimer; Positions:array[0..BoardYLines-1] of String; GameLines:Integer; GameLevel:Integer; GameScore:Integer; DrawShapeEndPoint:Boolean; TipShapeDistance:Integer; ShowMessageFlag:Boolean; procedure OnMyTimer(Sender:TObject); function GetShapes(index: Integer): TShape; procedure SetShapes(index: Integer; const Value: TShape); function GetBoardShapes(x, y: Integer): TBrick; procedure SetBoardShapes(x, y: Integer; const Value: TBrick); function GetBricks(index: Integer): TBrick; procedure SetBricks(index: Integer; const Value: TBrick); protected procedure Paint; override; function ActiveShape:TShape; function WaitingShape:TShape; function ShapeCanMoveDown:Boolean; function ShapeCanMoveLeft:Boolean; function ShapeCanMoveRight:Boolean; function BoardGetLastEmpty():TBoardLastEmptyRec; procedure PlaceShapeAtBoard; procedure SwitchNewShape; procedure AddRandomShape; procedure FindLinesAndDelete; procedure PlaceinBottom; procedure InitOptions; procedure DrawWaitingShape; procedure DrawOptions; procedure BoardShowMessage(Str:String); function CalcShapeEndPoint:Boolean; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure MyKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure StartGame; procedure RestartGame; property Shapes[index:Integer]:TShape read GetShapes write SetShapes; property Bricks[index:Integer]:TBrick read GetBricks write SetBricks; property BoardShapes[x,y:Integer]:TBrick read GetBoardShapes write SetBoardShapes; published end; implementation uses UMain; { TBoard } function TBoard.ActiveShape: TShape; begin Result:= Shapes[0]; end; procedure TBoard.AddRandomShape; var ShapeRandom:Integer; begin ShapeRandom:= Random(ShapesCount); ShapeList.Add( TShape.Create(TShapeType(ShapeRandom)) ); end; function TBoard.BoardGetLastEmpty(): TBoardLastEmptyRec; var I,Cnt:Integer; yBrick,xBrick:Integer; begin Result.Res:=False; Cnt:=1; repeat for i:= 0 to ActiveShape.BricksCount-1 do begin yBrick:= (ActiveShape.Bricks[i].BrickPoint.Y-1) + (ActiveShape.BoardPoint.Y); XBrick:= (ActiveShape.Bricks[i].BrickPoint.X-1) + (ActiveShape.BoardPoint.X); if (BoardShapes[xBrick,yBrick+Cnt] <> nil) then begin Result.EndPoint:= Point(ActiveShape.BoardPoint.X, yBrick+Cnt- ActiveShape.Bricks[i].BrickPoint.Y) ; if Result.EndPoint.Y + ActiveShape.FindBricksMax(ftYMax) > BoardYLines-1 then Result.EndPoint := Point(Result.EndPoint.X, Result.EndPoint.Y - (ActiveShape.FindBricksMax(ftYMax) + Result.EndPoint.Y-BoardYLines)); Result.Distance:= yBrick+Cnt; Result.Res:=True; Exit; end; end;//end for Inc(Cnt); until (Cnt + yBrick > BoardYLines -1); if (yBrick+Cnt = BoardYLines) then begin Result.EndPoint := Point(ActiveShape.BoardPoint.X, (yBrick+Cnt) - ActiveShape.FindBricksMax(ftYMax) ); Result.Distance:= yBrick + Cnt; Result.Res:=True; Exit; end; end; procedure TBoard.BoardShowMessage(Str: String); begin Msg.Show(Str); ShowMessageFlag:=True; end; function TBoard.CalcShapeEndPoint:Boolean; var Rec:TBoardLastEmptyRec; begin Rec:= BoardGetLastEmpty; // Flag to show or hide the Shape Tips... // When ditance between current y, and minimum // empty point is less, hide. Result:= (Rec.Distance - ActiveShape.BoardPoint.Y) > BoardShapeTipMax; ActiveShape.BoardPointInEnd:= Rec.EndPoint; TipShapeDistance:= Rec.Distance - ActiveShape.BoardPoint.Y; // formmain.Memo1.Lines.Add(inttostr( TipShapeDistance )) end; constructor TBoard.Create(AOwner: TComponent); begin inherited Create(AOwner); Randomize; ControlStyle:= ControlStyle + [csOpaque]; ShapeList:= TObjectList.Create; BrickList:= TObjectList.Create; Msg:= TMsg.Create(self,''); Parent:= TWinControl(AOwner); Width:= BoardXLines*BrickSize + 1; Height:=BoardYLines*BrickSize + 1; OptionsWidth := Width div 2 + Width div 8; Width:= Width + OptionsWidth; Board:= TBitmap.Create; Board.Width:= Width; Board.Height:= Height; GameTimer:= TTimer.Create(nil); GameTimer.Interval:= 1000; GameTimer.Enabled:= False; GameTimer.OnTimer:= OnMyTimer; GameTimer.Tag:=1000; InitOptions; ShowMessageFlag:=True; // Msg.Show('Starting Game'); end; destructor TBoard.Destroy; begin inherited; while ShapeList.Count > 0 do ShapeList.Remove(ShapeList.Items[0]); ShapeList.Free; end; procedure TBoard.DrawOptions; begin with Board.Canvas do begin Font.Name:= 'David'; Font.Size:= 20; Font.Color:= ClBlue; TextOut(BoardXLines*BrickSize + 120,220,inttostr(GameLines)); TextOut(BoardXLines*BrickSize + 120,268,inttostr(GameLevel)); TextOut(BoardXLines*BrickSize + 120,319,inttostr(GameScore)); end; end; procedure TBoard.DrawWaitingShape; var T:TRect; i:integer; ActiveDiv:Integer; begin InitOptions; ActiveDiv:= ((4 * BrickSize) - (WaitingShape.FindBricksMax(ftXMax)*BrickSize)) div 2; for i:= 0 to WaitingShape.BricksCount-1 do begin T:= Rect ( ActiveDiv + BoardXLines * BrickSize + 2 + WaitingShape.Bricks[i].BrickPoint.X*BrickSize, 60 + WaitingShape.Bricks[i].BrickPoint.Y*BrickSize, ActiveDiv + BoardXLines * BrickSize + 2 + WaitingShape.Bricks[i].BrickPoint.X*BrickSize + BrickSize + 1, 60+ WaitingShape.Bricks[i].BrickPoint.Y*BrickSize + BrickSize + 1); WaitingShape.Bricks[i].DrawBrick(Board.Canvas,T); end; DrawOptions; end; procedure TBoard.FindLinesAndDelete; var i,j:Integer; begin for i:= 0 to BoardYLines-1 do if Pos('0',Positions[i]) = 0 then begin //remove line i for j:= 0 to BoardXLines -1 do //remove line BrickList.Remove(BoardShapes[j,i]); for j:= 0 to BrickList.Count-1 do if Bricks[j].BrickPoint.Y < i then Bricks[j].BrickPoint:= Point(Bricks[j].BrickPoint.X, Bricks[j].BrickPoint.Y+1); for j:= i downto 1 do // update strings Positions[j]:= Positions[j-1]; inc(GameLines); inc(GameScore,GameLevel*GameLines); GameLevel:= 1 + (GameLines div 5); GameTimer.Interval:= 1000 - (GameLevel mod 10)*100; end; end; function TBoard.GetBoardShapes(x, y: Integer): TBrick; var i:Integer; begin Result:= nil; for i:= 0 to BrickList.Count -1 do begin if (Bricks[i].BrickPoint.X = X) and (Bricks[i].BrickPoint.Y = Y) then begin Result:= Bricks[i]; Exit; end; end; end; function TBoard.GetBricks(index: Integer): TBrick; begin Result:= TBrick(BrickList.Items[index]); end; function TBoard.GetShapes(index: Integer): TShape; begin Result:= TShape( ShapeList.Items[index] ); end; procedure TBoard.InitOptions; begin FormMain.Cursor:= CrNone; with Board.Canvas do begin Brush.Style:= bsSolid; Brush.Color:= ClSilver; FillRect(ClientRect); end; Board.Canvas.Draw(BoardXLines*BrickSize + 2,0,FormMain.OptionsImage.Picture.Graphic); end; procedure TBoard.MyKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key in [49..51] then begin Repaint; DrawWaitingShape; end; if GameTimer.Enabled then begin case key of VK_RIGHT: if ShapeCanMoveRight then ActiveShape.IncreaseBoardX(1); VK_LEFT: if ShapeCanMoveLeft then ActiveShape.IncreaseBoardX(-1); end; if (ShapeCanMoveDown) then begin case key of VK_UP: if ActiveShape.BoardPoint.X + ActiveShape.FindBricksMax(ftYMax) <= BoardXLines then ActiveShape.Rotate(1); VK_DOWN: ActiveShape.IncreaseBoardY(1); VK_SPACE: PlaceinBottom; VK_ESCAPE,VK_KeyQ: begin GameTimer.Tag:= Key; BoardShowMessage('Game Over'); GameTimer.Enabled:=False; end; VK_KeyP: begin GameTimer.Tag:= Key; BoardShowMessage('Poused.'); GameTimer.Enabled:=False; end; end; DrawShapeEndPoint:= CalcShapeEndPoint; end else PlaceShapeAtBoard; end else begin case key of VK_RETURN: begin case GameTimer.Tag of VK_KeyP: begin ShowMessageFlag:=False; GameTimer.Enabled:=True; end; B_EndGame,VK_KeyQ,VK_ESCAPE: begin GameTimer.Tag:=B_InitStart; Msg.Show('Game Start'); end; B_ReStart: begin GameTimer.Enabled:=True; ShowMessageFlag:=False; ReStartGame; end; B_InitStart: begin GameTimer.Enabled:=True; ShowMessageFlag:=False; StartGame; end; end; end; VK_ESCAPE,VK_KeyQ: FormMain.Close; end; end; Repaint; end; procedure TBoard.OnMyTimer(Sender: TObject); begin case ShapeCanMoveDown of False: PlaceShapeAtBoard; True: ActiveShape.IncreaseBoardY(1); end; //Form1.Caption:= Format('x=%d,y=%d',[ActiveShape.BoardPoint.X,ActiveShape.BoardPoint.Y]); DrawShapeEndPoint:= CalcShapeEndPoint; Repaint; end; procedure TBoard.Paint; var i,j:Integer; T:TRect; begin inherited; if ActiveShape = nil then Exit; with Board.Canvas do begin Pen.Color:= RGB(100,100,100); Pen.Style:= psClear; Brush.Color:= RGB(105,105,105); for i:= 0 to BoardYLines - 1 do for j:= 0 to BoardXLines -1 do begin Rectangle(j*BrickSize,i*BrickSize,(j+1)*BrickSize+1,(i+1)*BrickSize+1); end; // Painting the curretn moving shape; for i:= 0 to ActiveShape.BricksCount - 1 do begin T:= Rect( ActiveShape.BoardPoint.X*BrickSize + (ActiveShape.Bricks[i].BrickPoint.X-1)*BrickSize, ActiveShape.BoardPoint.Y*BrickSize + (ActiveShape.Bricks[i].BrickPoint.Y-1)*BrickSize, ActiveShape.BoardPoint.X*BrickSize + (ActiveShape.Bricks[i].BrickPoint.X-1)*BrickSize+BrickSize+1, ActiveShape.BoardPoint.Y*BrickSize + (ActiveShape.Bricks[i].BrickPoint.Y-1)*BrickSize+BrickSize+1); ActiveShape.Bricks[i].DrawBrick(Board.Canvas,T); if DrawShapeEndPoint then begin T:= Rect( ActiveShape.BoardPointInEnd.X*BrickSize + (ActiveShape.Bricks[i].BrickPoint.X-1)*BrickSize, ActiveShape.BoardPointInEnd.Y*BrickSize + (ActiveShape.Bricks[i].BrickPoint.Y-1)*BrickSize, ActiveShape.BoardPointInEnd.X*BrickSize + (ActiveShape.Bricks[i].BrickPoint.X-1)*BrickSize+BrickSize+1, ActiveShape.BoardPointInEnd.Y*BrickSize + (ActiveShape.Bricks[i].BrickPoint.Y-1)*BrickSize+BrickSize+1); ActiveShape.Bricks[i].DrawBrickEx(Board.Canvas,T,TipShapeDistance-BoardShapeTipMax); end; end; for i:= 0 to BrickList.Count -1 do begin T:= Rect ( Bricks[i].BrickPoint.X*BrickSize, Bricks[i].BrickPoint.Y*BrickSize, Bricks[i].BrickPoint.X*BrickSize + BrickSize + 1, Bricks[i].BrickPoint.Y*BrickSize + BrickSize + 1); Bricks[i].DrawBrick(Board.Canvas,T); end; end; // end with if ShowMessageFlag then BitBlt(Board.Canvas.Handle,10,160,Msg.GetWidth,Msg.GetHeight,Msg.Canvas.Handle,0,0,SrcCopy); BitBlt(Canvas.Handle,0,0,Width,Height,Board.Canvas.Handle,0,0,SRCCOPY); end; procedure TBoard.PlaceinBottom; begin while ShapeCanMoveDown do begin ActiveShape.BoardPoint:= Point(ActiveShape.BoardPoint.X,ActiveShape.BoardPoint.Y+1); //FormMain.Memo1.Lines.Add(Format('x=%d,y=%d',[ActiveShape.BoardPoint.X,ActiveShape.BoardPoint.Y])); end; PlaceShapeAtBoard; end; procedure TBoard.PlaceShapeAtBoard; var i:Integer; P:TPoint; begin if ActiveShape.BoardPoint.Y - ActiveShape.FindBricksMax(ftYMax) < 0 then begin GameTimer.Tag:=B_EndGame; BoardShowMessage('Game Over'); GameTimer.Enabled:=False; Exit; end; for i:= 0 to ActiveShape.BricksCount-1 do begin P:= Point((ActiveShape.BoardPoint.X + ActiveShape.Bricks[i].BrickPoint.X-1), (ActiveShape.BoardPoint.Y + ActiveShape.Bricks[i].BrickPoint.Y-1)); BrickList.Add(TBrick.Create(self,P,Ord( ActiveShape.ShapeType ))); Positions[P.Y][P.X+1]:='1'; end; FindLinesAndDelete; SwitchNewShape; end; procedure TBoard.RestartGame; var j:Integer; begin BrickList.Clear; GameLines:=0; GameLevel:=1; GameScore:=0; for j:= 0 to BoardYLines -1 do Positions[j]:=StringOfChar('0',BoardXLines); DrawWaitingShape; DrawOptions; DrawShapeEndPoint:= CalcShapeEndPoint; GameTimer.Tag:=100; GameTimer.Interval:=1000; Msg.Show('Restart Game'); end; procedure TBoard.SetBoardShapes(x, y: Integer; const Value: TBrick); begin end; procedure TBoard.SetBricks(index: Integer; const Value: TBrick); begin BrickList.Items[index]:= Value; end; procedure TBoard.SetShapes(index: Integer; const Value: TShape); begin ShapeList.Items[index]:= Value; end; function TBoard.ShapeCanMoveDown: Boolean; var i,xBrick,yBrick:Integer; begin Result:= True; if (ActiveShape.FindBricksMax(ftYMax)-1 + ActiveShape.BoardPoint.Y >= BoardYLines-1) then begin Result := False; Exit; end; for i:= 0 to ActiveShape.BricksCount-1 do begin yBrick:= (ActiveShape.Bricks[i].BrickPoint.Y-1) + (ActiveShape.BoardPoint.Y); XBrick:= (ActiveShape.Bricks[i].BrickPoint.X-1) + (ActiveShape.BoardPoint.X); if BoardShapes[xBrick,yBrick+1] <> nil then begin Result:= False; Exit; end; end; end; function TBoard.ShapeCanMoveLeft: Boolean; var i:Integer; yBrick,xBrick:Integer; begin Result:= True; if ActiveShape.BoardPoint.X = 0 then begin Result:= False; Exit; end; for i:= 0 to ActiveShape.BricksCount -1 do begin yBrick:= (ActiveShape.Bricks[i].BrickPoint.Y-1) + (ActiveShape.BoardPoint.Y); XBrick:= (ActiveShape.Bricks[i].BrickPoint.X-1) + (ActiveShape.BoardPoint.X); if BoardShapes[xBrick-1,yBrick] <> nil then begin Result:= False; Exit; end; end; end; function TBoard.ShapeCanMoveRight: Boolean; var i:Integer; yBrick,xBrick:Integer; begin Result:= True; if ActiveShape.BoardPoint.X + ActiveShape.FindBricksMax(ftXMax)-1 = BoardXLines -1 then begin Result:= False; Exit; end; for i:= 0 to ActiveShape.BricksCount-1 do begin yBrick:= (ActiveShape.Bricks[i].BrickPoint.Y-1) + (ActiveShape.BoardPoint.Y); XBrick:= (ActiveShape.Bricks[i].BrickPoint.X-1) + (ActiveShape.BoardPoint.X); if BoardShapes[xBrick+1,yBrick] <> nil then begin Result:= False; Exit; end; end; end; procedure TBoard.StartGame; var j:Integer; begin BrickList.Clear; ShapeList.Clear; AddRandomShape; AddRandomShape; GameLines:=0; GameLevel:=1; GameScore:=0; //formmain.Memo1.Lines.Add(inttostr(GameTimer.Tag)); //ShapeList.Add( TShape.Create( stDot ) ) ; //ShapeList.Add( TShape.Create( stZed2 ) ); for j:= 0 to BoardYLines -1 do Positions[j]:=StringOfChar('0',BoardXLines); DrawWaitingShape; DrawOptions; DrawShapeEndPoint:= CalcShapeEndPoint; GameTimer.Tag:=B_ReStart; GameTimer.Interval:=1000; Msg.Show('Start Game'); end; procedure TBoard.SwitchNewShape; begin AddRandomShape; ShapeList.Delete(0); DrawWaitingShape; DrawOptions; end; function TBoard.WaitingShape: TShape; begin Result:= Shapes[1]; end; end.
program bar-div-calc; const info='This is a simple bar division calculator with a remainder, used for integral numbers.'; var a,b:Extended; answer:char; //..................... {CALCULATING FUNCTIONS} //..................... //the quotient function c_div(a,b:Extended):Extended; begin c_div:=a/b; end; //the remainder function e_substr:Extended; function d_mult:Extended; begin d_mult:=b*c_div(a,b); end; begin e_substr:=a-d_mult; end; //.............. {INSERT NUMBERS} //.............. procedure insert_a; begin writeln('Enter the dividend:'); readln(a); end; procedure insert_b; begin writeln('Enter the divider:'); readln(b); end; //........................ {SANITY PARSING PROCEDURE} //........................ //too large numbers` amount exception handling to be added procedure div_ratio_check; begin while a<b do begin repeat writeln('The dividend should be more than the divider (or equal to it).'); writeln('Enter a valid divivend:'); readln(a); until a>b; end; end; procedure div_remainder_notice; begin if ((trunc(e_substr))<1) then writeln('It looks like the remainder is less than 1.'); end; //........................... {USER INTERACTION PROCEDURES} //........................... procedure result_msg; begin writeln('Result:'); writeln('Quotient - ',(trunc(c_div(a,b))),','); writeln('Remainder - ',(trunc(e_substr)),'.'); end; procedure try_q; begin writeln('Try again?'); writeln('(y - yes, n - no)'); readln(answer); end; procedure answer_check; begin while not (answer in ['y','Y','n','N']) do begin writeln('(y - yes, n - no)'); writeln('Try again?'); readln(answer); end end; procedure quit; begin writeln('Press enter to quit'); readln(); end; //.............. {PROGRAM STARTS} //.............. begin writeln(info); writeln(); repeat insert_a; insert_b; writeln(); div_ratio_check; writeln(); div_remainder_notice; writeln(); result_msg; writeln(); try_q; writeln(); answer_check; until (answer in ['n','N']); quit; end.
unit View.Configuracao; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, View.Frame.Cabecalho, FMX.Objects, FMX.Effects, FMX.Filter.Effects, FMX.Edit, FMX.Controls.Presentation, FMX.Layouts; type TFrameConfiguracao = class(TFrame) Layout4: TLayout; GboxPadraoArquivo: TGroupBox; Layout2: TLayout; RadioArquivoFilizola: TRadioButton; RadioArquivoToleto: TRadioButton; RadioOutros: TRadioButton; GBoxLocalArquivo: TGroupBox; Layout1: TLayout; EdtLocalArquivo: TEdit; imgPasta: TImage; FillRGBEffect1: TFillRGBEffect; Layout3: TLayout; BtnAlter: TRectangle; Label1: TLabel; BtnCancelar: TRectangle; Label2: TLabel; BtnGravar: TRectangle; Label3: TLabel; Rectangle1: TRectangle; FrameCabecalho1: TFrameCabecalho; procedure FrameCabecalho1Image1Click(Sender: TObject); procedure imgPastaClick(Sender: TObject); procedure BtnAlterClick(Sender: TObject); procedure BtnGravarClick(Sender: TObject); procedure BtnCancelarClick(Sender: TObject); private function OpenDialogDir: String; procedure EnabledBtn(pBtnAlterar, pBtnGrava, pBtnCancelar: Boolean); procedure EnabledCampo(pParams: Boolean); procedure CarregaConfiguracaoNaTela; { Private declarations } public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure CloseConfiguracao; end; var FrameConfiguracao: TFrameConfiguracao; implementation {$R *.fmx} uses Vcl.Dialogs, uDm, System.StrUtils, uSmartPro99; procedure TFrameConfiguracao.BtnAlterClick(Sender: TObject); begin EnabledBtn(False, True, True); EnabledCampo(True); end; procedure TFrameConfiguracao.BtnCancelarClick(Sender: TObject); begin EnabledBtn(True, False, False); EnabledCampo(False); CarregaConfiguracaoNaTela; end; procedure TFrameConfiguracao.CarregaConfiguracaoNaTela; begin Dm.LerConfiguracao; case SmartPro.Config.TipoIntegracao of tsToledo: RadioArquivoToleto.IsChecked := True; tsFilizola: RadioArquivoFilizola.IsChecked := True; tsOutros: RadioOutros.IsChecked := True; end; EdtLocalArquivo.Text := SmartPro.Config.LocalArquivo; EnabledCampo(False); EnabledBtn(True, False, False); end; procedure TFrameConfiguracao.CloseConfiguracao; begin if Assigned(FrameConfiguracao) then begin FrameConfiguracao.Visible := False; FrameConfiguracao.DisposeOf; FrameConfiguracao := Nil; end; end; constructor TFrameConfiguracao.Create(AOwner: TComponent); begin inherited; FrameCabecalho1.LblNomeDaTela.Text := 'Configurações'; CarregaConfiguracaoNaTela; end; destructor TFrameConfiguracao.Destroy; begin inherited; end; procedure TFrameConfiguracao.BtnGravarClick(Sender: TObject); begin SmartPro.Config.LocalArquivo := EdtLocalArquivo.Text; if RadioArquivoToleto.IsChecked then SmartPro.Config.TipoIntegracao := tsToledo; if RadioArquivoFilizola.IsChecked then SmartPro.Config.TipoIntegracao := tsFilizola; if RadioOutros.IsChecked then SmartPro.Config.TipoIntegracao := tsOutros; Dm.GravarConfiguracao; EnabledBtn(True, False, False); EnabledCampo(False); end; procedure TFrameConfiguracao.EnabledBtn(pBtnAlterar, pBtnGrava, pBtnCancelar: Boolean); begin BtnAlter.Enabled := pBtnAlterar; BtnGravar.Enabled := pBtnGrava; BtnCancelar.Enabled := pBtnCancelar; end; procedure TFrameConfiguracao.EnabledCampo(pParams: Boolean); begin RadioArquivoToleto.Enabled := pParams; RadioArquivoFilizola.Enabled := pParams; RadioOutros.Enabled := pParams; EdtLocalArquivo.Enabled := pParams; imgPasta.Enabled := pParams; end; procedure TFrameConfiguracao.FrameCabecalho1Image1Click(Sender: TObject); begin CloseConfiguracao; end; procedure TFrameConfiguracao.imgPastaClick(Sender: TObject); begin EdtLocalArquivo.Text := OpenDialogDir; end; function TFrameConfiguracao.OpenDialogDir: String; begin with TOpenDialog.Create(nil) do try InitialDir := 'C:'; Options := [ofFileMustExist]; Filter := '*.txt'; if Execute then Result := FileName; finally Free; end; end; end.
// ****************************************************************** // // Program Name : AT Library // Program Version: // Platform(s) : Win32, Win64, OSX, Android, IOS // Framework : None // // Filename : AT.EncDec.Hash.MD.pas // File Version : 2.00 // Date Created : 26-APR-2016 // Author : Matthew S. Vesperman // // Description: // // MD Hashing functions... // // Revision History: // // v1.00 : Initial version // // ****************************************************************** // // COPYRIGHT © 2015 - PRESENT Angelic Technology // ALL RIGHTS RESERVED WORLDWIDE // // ****************************************************************** unit AT.EncDec.Hash.MD; interface function HashMD2ofFile(AFileName: String): String; inline; function HashMD4ofFile(AFileName: String): String; inline; function HashMD5ofFile(AFileName: String): String; inline; function StringHashMD2(Value: String): String; inline; function StringHashMD4(Value: String): String; inline; function StringHashMD5(Value: String): String; inline; implementation uses IdHash, IdHashMessageDigest, System.SysUtils, System.Classes, AT.GarbageCollector; function _HashMDofFile(const AFileName: String; AHash: TIdHashMessageDigest): String; inline; var AFile: TFileStream; AGC: IATGarbageCollector; begin if (NOT FileExists(AFileName)) then Exit(EmptyStr); if (NOT Assigned(AHash)) then Exit(EmptyStr); AFile := TATGC.Collect(TFileStream.Create(AFileName, fmOpenRead), AGC); Result := AHash.HashStreamAsHex(AFile); end; function HashMD2ofFile(AFileName: String): String; inline; var AHash: TIdHashMessageDigest2; AGC: IATGarbageCollector; begin AHash := TATGC.Collect(TIdHashMessageDigest2.Create, AGC); Result := _HashMDofFile(AFileName, AHash) end; function HashMD4ofFile(AFileName: String): String; inline; var AHash: TIdHashMessageDigest4; AGC: IATGarbageCollector; begin AHash := TATGC.Collect(TIdHashMessageDigest4.Create, AGC); Result := _HashMDofFile(AFileName, AHash) end; function HashMD5ofFile(AFileName: String): String; inline; var AHash: TIdHashMessageDigest5; AGC: IATGarbageCollector; begin AHash := TATGC.Collect(TIdHashMessageDigest5.Create, AGC); Result := _HashMDofFile(AFileName, AHash) end; function StringHashMD2(Value: String): String; inline; var AHash: TIdHashMessageDigest2; AGC: IATGarbageCollector; begin AHash := TATGC.Collect(TIdHashMessageDigest2.Create, AGC); Result := AHash.HashStringAsHex(Value); end; function StringHashMD4(Value: String): String; inline; var AHash: TIdHashMessageDigest4; AGC: IATGarbageCollector; begin AHash := TATGC.Collect(TIdHashMessageDigest4.Create, AGC); Result := AHash.HashStringAsHex(Value); end; function StringHashMD5(Value: String): String; inline; var AHash: TIdHashMessageDigest5; AGC: IATGarbageCollector; begin AHash := TATGC.Collect(TIdHashMessageDigest5.Create, AGC); Result := AHash.HashStringAsHex(Value); end; end.
object EdPartsForm: TEdPartsForm Left = 274 Top = 90 HelpContext = 6 ActiveControl = DBEdit2 BorderIcons = [biSystemMenu, biMinimize] BorderStyle = bsSingle Caption = 'Edit Parts' ClientHeight = 264 ClientWidth = 313 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = True Position = poScreenCenter OnCloseQuery = FormCloseQuery PixelsPerInch = 96 TextHeight = 13 object Panel1: TPanel Left = 0 Top = 0 Width = 313 Height = 36 Align = alTop BevelOuter = bvNone TabOrder = 0 object PrintBtn: TSpeedButton Left = 270 Top = 5 Width = 25 Height = 25 Hint = 'Print form image' Glyph.Data = { 2A010000424D2A010000000000007600000028000000130000000F0000000100 040000000000B400000000000000000000001000000000000000000000000000 8000008000000080800080000000800080008080000080808000C0C0C0000000 FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00333333333333 3333333F0EFF3300000000000003333F00FF37877777777777703330000030F8 8888888888870333003330F9988888888887703F11EE37FFFFFFFFFFFFF77039 0910330888888888888F703865F03330870000000078F03765F03333000FFFFF F000033865F03333330F44448033333765F033333330FFFFFF03333865F03333 3330F4444803333765F0333333330FFFFFF0333865F033333333000000003336 66C0333333333333333333300000} OnClick = PrintBtnClick end object Bevel1: TBevel Left = 0 Top = 34 Width = 313 Height = 2 Align = alBottom Shape = bsTopLine end object Navigator: TDBNavigator Left = 16 Top = 5 Width = 240 Height = 25 HelpContext = 6 DataSource = PartsSource1 ParentShowHint = False ShowHint = True TabOrder = 0 end end object Panel2: TPanel Left = 0 Top = 36 Width = 313 Height = 193 Align = alTop BevelOuter = bvNone TabOrder = 1 object Label1: TLabel Left = 8 Top = 11 Width = 33 Height = 13 Caption = 'PartNo' end object Label2: TLabel Left = 8 Top = 33 Width = 53 Height = 13 Caption = 'Description' end object Label3: TLabel Left = 8 Top = 55 Width = 34 Height = 13 Caption = 'Vendor' end object Label4: TLabel Left = 8 Top = 77 Width = 40 Height = 13 Caption = 'OnHand' end object Label5: TLabel Left = 8 Top = 100 Width = 40 Height = 13 Caption = 'OnOrder' end object Label7: TLabel Left = 8 Top = 144 Width = 21 Height = 13 Caption = 'Cost' end object Label8: TLabel Left = 8 Top = 166 Width = 40 Height = 13 Caption = 'ListPrice' end object Label6: TLabel Left = 8 Top = 122 Width = 61 Height = 13 Caption = 'Backordered' end object DBEdit2: TDBEdit Left = 80 Top = 29 Width = 225 Height = 21 HelpContext = 6 DataField = 'Description' DataSource = PartsSource1 TabOrder = 1 end object DBEdit4: TDBEdit Left = 80 Top = 74 Width = 82 Height = 21 HelpContext = 6 DataField = 'OnHand' DataSource = PartsSource1 TabOrder = 3 end object DBEdit5: TDBEdit Left = 80 Top = 97 Width = 82 Height = 21 HelpContext = 6 DataField = 'OnOrder' DataSource = PartsSource1 TabOrder = 4 end object DBEdit7: TDBEdit Left = 80 Top = 141 Width = 102 Height = 21 HelpContext = 6 DataField = 'Cost' DataSource = PartsSource1 TabOrder = 6 end object DBEdit8: TDBEdit Left = 80 Top = 163 Width = 102 Height = 21 HelpContext = 6 DataField = 'ListPrice' DataSource = PartsSource1 TabOrder = 7 end object DBEdPartNo: TDBEdit Left = 80 Top = 6 Width = 102 Height = 21 HelpContext = 6 DataField = 'PartNo' DataSource = PartsSource1 TabOrder = 0 end object DBEdit3: TDBEdit Left = 80 Top = 119 Width = 45 Height = 21 HelpContext = 6 DataField = 'BackOrd' DataSource = PartsSource1 TabOrder = 5 end object DataComboBox1: TDBLookupComboBox Left = 80 Top = 51 Width = 225 Height = 21 DataField = 'VendorNo' DataSource = PartsSource1 KeyField = 'VendorNo' ListField = 'VendorName' ListSource = MastData.VendorSource TabOrder = 2 end end object OKButton: TButton Left = 147 Top = 235 Width = 75 Height = 25 Caption = 'OK' Default = True ModalResult = 1 TabOrder = 2 end object CancelButton: TButton Left = 232 Top = 235 Width = 75 Height = 25 Cancel = True Caption = 'Cancel' ModalResult = 2 TabOrder = 3 end object PartsSource1: TDataSource DataSet = MastData.Parts Left = 24 Top = 232 end end
unit pins; interface uses sc32442b_gpio, sc32442b_irq, sc32442b_clock; const BASE_CS0 = $00000000; BASE_CS1 = $08000000; BASE_CS2 = $10000000; BASE_CS3 = $18000000; BASE_CS4 = $20000000; BASE_CS5 = $28000000; BASE_CS6 = $30000000; BASE_CS7 = $38000000; GTA02_CS_FLASHROM = BASE_CS0; GTA02_CS_3D = BASE_CS1; GTA02_GPIO_n3DL_GSM = GPA13; (* v1 + v2 + v3 only *) GTA02_GPIO_PWR_LED1 = GPB0; GTA02_GPIO_PWR_LED2 = GPB1; GTA02_GPIO_AUX_LED = GPB2; GTA02_GPIO_VIBRATOR_ON = GPB3; GTA02_GPIO_MODEM_RST = GPB5; GTA02_GPIO_BT_EN = GPB6; GTA02_GPIO_MODEM_ON = GPB7; GTA02_GPIO_EXTINT8 = GPB8; GTA02_GPIO_USB_PULLUP = GPB9; GTA02_GPIO_PIO5 = GPC5; (* v3 + v4 only *) GTA02v3_GPIO_nG1_CS = GPD12; (* v3 + v4 only *) GTA02v3_GPIO_nG2_CS = GPD13; (* v3 + v4 only *) GTA02v5_GPIO_HDQ = GPD14; (* v5 + *) GTA02_GPIO_nG1_INT = GPF0; GTA02_GPIO_IO1 = GPF1; GTA02_GPIO_PIO_2 = GPF2; (* v2 + v3 + v4 only *) GTA02_GPIO_JACK_INSERT = GPF4; GTA02_GPIO_WLAN_GPIO1 = GPF5; (* v2 + v3 + v4 only *) GTA02_GPIO_AUX_KEY = GPF6; GTA02_GPIO_HOLD_KEY = GPF7; GTA02_GPIO_3D_IRQ = GPG4; GTA02v2_GPIO_nG2_INT = GPG8; (* v2 + v3 + v4 only *) GTA02v3_GPIO_nUSB_OC = GPG9; (* v3 + v4 only *) GTA02v3_GPIO_nUSB_FLT = GPG10; (* v3 + v4 only *) GTA02v3_GPIO_nGSM_OC = GPG11; (* v3 + v4 only *) GTA02_GPIO_AMP_SHUT = GPJ1; (* v2 + v3 + v4 only *) GTA02v1_GPIO_WLAN_GPIO10 = GPJ2; GTA02_GPIO_HP_IN = GPJ2; (* v2 + v3 + v4 only *) GTA02_GPIO_INT0 = GPJ3; (* v2 + v3 + v4 only *) GTA02_GPIO_nGSM_EN = GPJ4; GTA02_GPIO_3D_RESET = GPJ5; GTA02_GPIO_nDL_GSM = GPJ6; (* v4 + v5 only *) GTA02_GPIO_WLAN_GPIO0 = GPJ7; GTA02v1_GPIO_BAT_ID = GPJ8; GTA02_GPIO_KEEPACT = GPJ8; GTA02v1_GPIO_HP_IN = GPJ10; GTA02_CHIP_PWD = GPJ11; (* v2 + v3 + v4 only *) GTA02_GPIO_nWLAN_RESET = GPJ12; (* v2 + v3 + v4 only *) GTA02_IRQ_GSENSOR_1 = IRQ_EINT0; GTA02_IRQ_MODEM = IRQ_EINT1; GTA02_IRQ_PIO_2 = IRQ_EINT2; (* v2 + v3 + v4 only *) GTA02_IRQ_nJACK_INSERT = IRQ_EINT4; GTA02_IRQ_WLAN_GPIO1 = IRQ_EINT5; GTA02_IRQ_AUX = IRQ_EINT6; GTA02_IRQ_nHOLD = IRQ_EINT7; GTA02_IRQ_PCF50633 = IRQ_EINT9; GTA02_IRQ_3D = IRQ_EINT12; GTA02_IRQ_GSENSOR_2 = IRQ_EINT16; (* v2 + v3 + v4 only *) GTA02v3_IRQ_nUSB_OC = IRQ_EINT17; (* v3 + v4 only *) GTA02v3_IRQ_nUSB_FLT = IRQ_EINT18; (* v3 + v4 only *) GTA02v3_IRQ_nGSM_OC = IRQ_EINT19; (* v3 + v4 only *) (* returns 00 000 on GTA02 A5 and earlier, A6 returns 01 001 *) GTA02_PCB_ID1_0 = GPC13; GTA02_PCB_ID1_1 = GPC15; GTA02_PCB_ID1_2 = GPD0; GTA02_PCB_ID2_0 = GPD3; GTA02_PCB_ID2_1 = GPD4; function DetectVersion: longword; implementation function DetectVersion: longword; const pinlist: array[0..4] of longword = (GTA02_PCB_ID1_0, GTA02_PCB_ID1_1, GTA02_PCB_ID1_2, GTA02_PCB_ID2_0, GTA02_PCB_ID2_1); pin_offset: array[0..4] of longint = (0,1,2,8,9); var i, res: longint; begin res := 0; for i := 0 to high(pinlist) do begin GPIOSetConfig(pinlist[i], GPIO_Output); GPIOSetOutput(pinlist[i], false); { misnomer: it is a pullDOWN in 2442 } GPIOSetPulldown(pinlist[i], true); GPIOSetConfig(pinlist[i], GPIO_Input); //udelay(10); if GPIOGetValue(pinlist[i]) then res := res or (1 shl pin_offset[i]); { when not being interrogated, all of the revision GPIO are set to output HIGH without pulldown so no current flows if they are NC or pulled up. } GPIOSetOutput(pinlist[i], true); GPIOSetConfig(pinlist[i], GPIO_Output); GPIOSetPulldown(pinlist[i], false); end; DetectVersion := res; end; end
// ************************************************************************ // // The types declared in this file were generated from data read from the // WSDL File described below: // WSDL : http://localhost/iaf/IAFServer.dll/wsdl/IExtraMethods // Version : 1.0 // (03/12/2011 16:13:39 - - $Rev: 34800 $) // ************************************************************************ // unit UExtraMethods; interface uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns; type // ************************************************************************ // // The following types, referred to in the WSDL document are not being represented // in this file. They are either aliases[@] of other types represented or were referred // to but never[!] declared in the document. The types from the latter category // typically map to predefined/known XML or Embarcadero types; however, they could also // indicate incorrect WSDL documents that failed to declare or import a schema type. // ************************************************************************ // // !:string - "http://www.w3.org/2001/XMLSchema"[] // ************************************************************************ // // Namespace : urn:UExtraMethodsIntf-IExtraMethods // soapAction: urn:UExtraMethodsIntf-IExtraMethods#GetConstraintsFor // transport : http://schemas.xmlsoap.org/soap/http // style : rpc // use : encoded // binding : IExtraMethodsbinding // service : IExtraMethodsservice // port : IExtraMethodsPort // URL : http://localhost/iaf/IAFServer.dll/soap/IExtraMethods // ************************************************************************ // IExtraMethods = interface(IInvokable) ['{C6037FCA-3DC8-4F09-EC59-87ADF44E2873}'] function GetConstraintsFor(const aProviderName: String; aDataSetName: String; const aSessionID: String): String; stdcall; function GetPermissions(const aSessionID: String): OleVariant; stdcall; end; function GetConstraintsFor(const aProviderName: String; aDataSetName: String; const aSessionID: String): String; function GetPermissions(const aSessionID: String): OleVariant; implementation uses SysUtils , UConfiguracoes; function GetIExtraMethods(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): IExtraMethods; const defSvc = 'IExtraMethodsservice'; defPrt = 'IExtraMethodsPort'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := Configuracoes.ServicoWeb + '/wsdl/IExtraMethods' else Addr := Configuracoes.ServicoWeb + '/soap/IExtraMethods'; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; { Autenticação proxy } if Configuracoes.EnderecoProxy <> '' then begin RIO.HTTPWebNode.Proxy := Configuracoes.EnderecoProxy; RIO.HTTPWebNode.UserName := Configuracoes.UsuarioProxy; RIO.HTTPWebNode.Password := Configuracoes.SenhaProxy; end; try Result := (RIO as IExtraMethods); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; function GetConstraintsFor(const aProviderName: String; aDataSetName: String; const aSessionID: String): String; begin Result := GetIExtraMethods.GetConstraintsFor(aProviderName,aDataSetName,aSessionID); end; function GetPermissions(const aSessionID: String): OleVariant; begin Result := GetIExtraMethods.GetPermissions(aSessionID); end; initialization { IExtraMethods } InvRegistry.RegisterInterface(TypeInfo(IExtraMethods), 'urn:UExtraMethodsIntf-IExtraMethods', ''); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(IExtraMethods), 'urn:UExtraMethodsIntf-IExtraMethods#GetConstraintsFor'); end.
unit AT.Vcl.DX.NativePrintPane.Reg; interface uses Vcl.ImgList, cxPropEditors; type TATdxNativePrintPaneImageIndexProperty = class(TImageIndexProperty) public function GetImages: TCustomImageList; override; end; procedure Register; implementation uses System.Classes, System.UITypes, ComponentDesigner, DesignIntf, AT.Vcl.DX.NativePrintPane; procedure Register; begin RegisterComponents('AT DevExpress', [TATdxNativePrintPane]); RegisterPropertyEditor(TypeInfo(TImageIndex), TATdxNativePrintPane, '', TATdxNativePrintPaneImageIndexProperty); end; { TATdxNativePrintPaneImageIndexProperty } function TATdxNativePrintPaneImageIndexProperty.GetImages: TCustomImageList; begin Result := TATdxNativePrintPane(GetComponent(0)).Images; end; end.
unit QGame.SceneManager; interface uses Generics.Collections, QCore.Types, QCore.Input, QGame.Scene, Strope.Math; type TSceneManager = class sealed (TComponent) strict private FScenes: TDictionary<string, TScene>; FCurrentScene: TScene; function GetScene(const ASceneName: string): TScene; public constructor Create; destructor Destroy; override; procedure AddScene(AScene: TScene); procedure MakeCurrent(const ASceneName: string); procedure DeleteScene(const ASceneName: string); ///<summary>Метод вызывается для инициализации текущей сцены.</summary> ///<param name="AParameter">Объект-параметр для инициализации.</param> procedure OnInitialize(AParameter: TObject = nil); override; ///<summary>Метод служит для активации или деактивации текущей сцены.</summary> ///<param name="AIsActivate">Значение True служит для активации, ///значение False - для деактивации.</param> procedure OnActivate(AIsActivate: Boolean); override; ///<summary>Метод вызывается для отрисовки текущей сцены.</summary> ///<param name="ALayer">Слой сцены для отрисовки.</param> procedure OnDraw(const ALayer: Integer); override; ///<summary>Метод вызывается для обновления состояния текущей сцены.</summary> ///<param name="ADelta">Промежуток времены в секундах, ///прошедший с предыдущего обновления состояния.</param> procedure OnUpdate(const ADelta: Double); override; ///<summary>Метод должен вызываться (вручную или в деструкторе) для или перед удалением текущей сцены. /// Служит для очистки занятых сценой ресурсов.</summary> procedure OnDestroy; override; ///<summary>Метод вызывается для реакции на событие "движение мышки"</summary> ///<param name="AMousePosition">Текущие координаты мыши, ///относительно левого верхнего края рабочего окна.</param> ///<returns>Возвращенное логическое значение сигнализирует о том, ///было ли событие обработано объектом.</returns> function OnMouseMove(const AMousePosition: TVectorF): Boolean; override; ///<summary>Метод вызывается для реакции на событие <b><i>нажатие кнопки мыши</i></b></summary> ///<param name="AButton">Нажатая кнопка мыши.</param> ///<param name="AMousePosition">Координаты мыши в момент нажатие кнопки, ///относительно левого верхнего края рабочего окна.</param> ///<returns>Возвращенное логическое значение сигнализирует о том, ///было ли событие обработано объектом.</returns> ///<remarks>Значения перечисления <see creg="QCore.Input|TMouseButton" /> /// можно узать в модуле QCore.Input.</remarks> function OnMouseButtonDown( AButton: TMouseButton; const AMousePosition: TVectorF): Boolean; override; ///<summary>Метод вызывается для реакции на событие <b><i>отпускание кнопки мыши</i></b></summary> ///<param name="AButton">Отпущенная кнопка мыши.</param> ///<param name="AMousePosition">Координаты мыши в момент отпускания кнопки, /// относительно левого верхнего края рабочего окна.</param> ///<returns>Возвращенное логическое значение сигнализирует о том, ///было ли событие обработано объектом.</returns> ///<remarks>Значения перечисления <see creg="QCore.Input|TMouseButton" /> /// можно узать в модуле QCore.Input.</remarks> function OnMouseButtonUp( AButton: TMouseButton; const AMousePosition: TVectorF): Boolean; override; ///<summary>Метод вызывается для реакции на событие <b><i>прокрутка колеса мыши вниз</i></b></summary> ///<param name="ADirection">Напревление прокрутки колеса. /// Значение +1 соответствует прокрутке вверх, -1 - вниз.</param> ///<returns>Возвращенное логическое значение сигнализирует о том, ///было ли событие обработано объектом.</returns> function OnMouseWheel(ADirection: Integer): Boolean; override; ///<summary>Метод вызывается для рекции на событие <b><i>нажатие кнопки на клавиатуре</i></b></summary> ///<param name="AKey">Нажатая кнопка на клавиатуре.</param> ///<returns>Возвращенное логическое значение сигнализирует о том, ///было ли событие обработано объектом.</returns> ///<remarks>Значения констант TKeyButton можно узать в модуле uInput.</remarks> function OnKeyDown(AKey: TKeyButton): Boolean; override; ///<summary>Метод вызывается для рекции на событие <b><i>отпускание кнопки на клавиатуре</i></b></summary> ///<param name="AKey">Отпущенная кнопка на клавиатуре.</param> ///<returns>Возвращенное логическое значение сигнализирует о том, ///было ли событие обработано объектом.</returns> ///<remarks>Значения констант TKeyButton можно узать в модуле uInput.</remarks> function OnKeyUp(AKey: TKeyButton): Boolean; override; public end; implementation uses SysUtils; {$REGION ' TSceneManager '} constructor TSceneManager.Create; begin FScenes := TDictionary<string, TScene>.Create; FCurrentScene := nil; end; destructor TSceneManager.Destroy; var AScene: TScene; begin for AScene in FScenes.Values do begin AScene.OnDestroy; AScene.Free; end; FScenes.Free; inherited; end; function TSceneManager.GetScene(const ASceneName: string): TScene; begin Result := nil; FScenes.TryGetValue(AnsiUpperCase(ASceneName), Result); end; procedure TSceneManager.AddScene(AScene: TScene); begin if Assigned(AScene) then begin if Assigned(GetScene(AScene.Name)) then raise EArgumentException.Create( 'Сцена с таким именем уже существует. ' + '{0CAED87C-8402-47EA-A245-4BAA77905A23}'); FScenes.Add(AScene.Name, AScene); end; end; procedure TSceneManager.MakeCurrent(const ASceneName: string); begin FCurrentScene := GetScene(ASceneName); end; procedure TSceneManager.DeleteScene(const ASceneName: string); var AScene: TScene; begin AScene := GetScene(ASceneName); if Assigned(AScene) then begin if FCurrentScene = AScene then FCurrentScene := nil; FScenes.Remove(AScene.Name); AScene.OnDestroy; FreeAndNil(AScene); end; end; procedure TSceneManager.OnActivate(AIsActivate: Boolean); begin if Assigned(FCurrentScene) then FCurrentScene.OnActivate(AIsActivate); end; procedure TSceneManager.OnDestroy; begin if Assigned(FCurrentScene) then FCurrentScene.OnDestroy; end; procedure TSceneManager.OnDraw(const ALayer: Integer); begin if Assigned(FCurrentScene) then FCurrentScene.OnDraw(ALayer); end; procedure TSceneManager.OnInitialize(AParameter: TObject); begin if Assigned(FCurrentScene) then FCurrentScene.OnInitialize(AParameter); end; function TSceneManager.OnKeyDown(AKey: TKeyButton): Boolean; begin Result := True; if Assigned(FCurrentScene) then Result := FCurrentScene.OnKeyDown(AKey); end; function TSceneManager.OnKeyUp(AKey: TKeyButton): Boolean; begin Result := True; if Assigned(FCurrentScene) then Result := FCurrentScene.OnKeyUp(AKey); end; function TSceneManager.OnMouseButtonDown(AButton: TMouseButton; const AMousePosition: TVectorF): Boolean; begin Result := True; if Assigned(FCurrentScene) then Result := FCurrentScene.OnMouseButtonDown(AButton, AMousePosition); end; function TSceneManager.OnMouseButtonUp(AButton: TMouseButton; const AMousePosition: TVectorF): Boolean; begin Result := True; if Assigned(FCurrentScene) then Result := FCurrentScene.OnMouseButtonUp(AButton, AMousePosition); end; function TSceneManager.OnMouseMove(const AMousePosition: TVectorF): Boolean; begin Result := True; if Assigned(FCurrentScene) then Result := FCurrentScene.OnMouseMove(AMousePosition); end; function TSceneManager.OnMouseWheel(ADirection: Integer): Boolean; begin Result := True; if Assigned(FCurrentScene) then Result := FCurrentScene.OnMouseWheel(ADirection) end; procedure TSceneManager.OnUpdate(const ADelta: Double); begin if Assigned(FCurrentScene) then FCurrentScene.OnUpdate(ADelta); end; end.
unit AES_INTV; {$ifdef VirtualPascal} {$stdcall+} {$else} Error('Interface unit for VirtualPascal'); {$endif} (************************************************************************* DESCRIPTION : Interface unit for AES_DLL REQUIREMENTS : VirtualPascal EXTERNAL DATA : --- MEMORY USAGE : --- DISPLAY MODE : --- Version Date Author Modification ------- -------- ------- ------------------------------------------ 0.10 02.07.04 W.Ehrhardt Initial version from AES_Intf 0.20 03.07.04 we VirtualPascal syntax 0.21 30.11.04 we AES_XorBlock, AESBLKSIZE 0.22 01.12.04 we AES_Err_Data_After_Short_Block 0.23 01.12.04 we AES_ prefix for CTR increment routines 0.24 24.12.04 we AES_Get/SetFastInit 0.25 09.07.06 we CMAC, updated OMAC 0.26 14.06.07 we Type TAES_EAXContext 0.27 16.06.07 we AES_CPRF128 0.28 29.09.07 we AES_XTS 0.29 25.12.07 we AES_CFB8 **************************************************************************) (*------------------------------------------------------------------------- (C) Copyright 2002-2007 Wolfgang Ehrhardt This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ----------------------------------------------------------------------------*) interface const AES_Err_Invalid_Key_Size = -1; {Key size <> 128, 192, or 256 Bits} AES_Err_Invalid_Mode = -2; {Encr/Decr with Init for Decr/Encr} AES_Err_Invalid_Length = -3; {No full block for cipher stealing} AES_Err_Data_After_Short_Block = -4; {Short block must be last} AES_Err_MultipleIncProcs = -5; {More than one IncProc Setting } AES_Err_NIL_Pointer = -6; {nil pointer to block with nonzero length} const AESMaxRounds = 14; type TAESBlock = packed array[0..15] of byte; PAESBlock = ^TAESBlock; TKeyArray = packed array[0..AESMaxRounds] of TAESBlock; TIncProc = procedure(var CTR: TAESBlock); {user supplied IncCTR proc} TAESContext = packed record RK : TKeyArray; {Key (encr. or decr.) } IV : TAESBlock; {IV or CTR } buf : TAESBlock; {Work buffer } bLen : word; {Bytes used in buf } Rounds : word; {Number of rounds } KeyBits : word; {Number of bits in key } Decrypt : byte; {<>0 if decrypting key } Flag : byte; {Bit 1: Short block } IncProc : TIncProc; {Increment proc CTR-Mode} end; type TAES_EAXContext = packed record HdrOMAC : TAESContext; {Hdr OMAC1 context} MsgOMAC : TAESContext; {Msg OMAC1 context} ctr_ctx : TAESContext; {Msg AESCTR context} NonceTag: TAESBlock; {nonce tag } tagsize : word; {tag size (unused) } flags : word; {ctx flags (unused)} end; const AESBLKSIZE = sizeof(TAESBlock); type TAES_XTSContext = packed record main : TAESContext; {Main context} tweak: TAESContext; {Tweak context} end; function AES_DLL_Version: PChar; {-Return DLL version as PChar} procedure AES_XorBlock(const B1, B2: TAESBlock; var B3: TAESBlock); {-xor two blocks, result in third} function AES_Init(const Key; KeyBits: word; var ctx: TAESContext): integer; {-AES key expansion, error if invalid key size} function AES_Init_Encr(const Key; KeyBits: word; var ctx: TAESContext): integer; {-AES key expansion, error if invalid key size} procedure AES_Encrypt(var ctx: TAESContext; const BI: TAESBlock; var BO: TAESBlock); {-encrypt one block, not checked: key must be encryption key} function AES_Init_Decr(const Key; KeyBits: word; var ctx: TAESContext): integer; {-AES key expansion, InvMixColumn(Key) for Decypt, error if invalid key size} procedure AES_Decrypt(var ctx: TAESContext; const BI: TAESBlock; var BO: TAESBlock); {-decrypt one block (in ECB mode)} procedure AES_SetFastInit(value: boolean); {-set FastInit variable} function AES_GetFastInit: boolean; {-Returns FastInit variable} function AES_ECB_Init_Encr(const Key; KeyBits: word; var ctx: TAESContext): integer; {-AES key expansion, error if invalid key size, encrypt IV} function AES_ECB_Init_Decr(const Key; KeyBits: word; var ctx: TAESContext): integer; {-AES key expansion, error if invalid key size, encrypt IV} function AES_ECB_Encrypt(ptp, ctp: Pointer; ILen: word; var ctx: TAESContext): integer; {-Encrypt ILen bytes from ptp^ to ctp^ in ECB mode} function AES_ECB_Decrypt(ctp, ptp: Pointer; ILen: word; var ctx: TAESContext): integer; {-Decrypt ILen bytes from ctp^ to ptp^ in ECB mode} function AES_CBC_Init_Encr(const Key; KeyBits: word; const IV: TAESBlock; var ctx: TAESContext): integer; {-AES key expansion, error if invalid key size, encrypt IV} function AES_CBC_Init_Decr(const Key; KeyBits: word; const IV: TAESBlock; var ctx: TAESContext): integer; {-AES key expansion, error if invalid key size, encrypt IV} function AES_CBC_Encrypt(ptp, ctp: Pointer; ILen: word; var ctx: TAESContext): integer; {-Encrypt ILen bytes from ptp^ to ctp^ in CBC mode} function AES_CBC_Decrypt(ctp, ptp: Pointer; ILen: word; var ctx: TAESContext): integer; {-Decrypt ILen bytes from ctp^ to ptp^ in CBC mode} function AES_CFB_Init(const Key; KeyBits: word; const IV: TAESBlock; var ctx: TAESContext): integer; {-AES key expansion, error if invalid key size, encrypt IV} function AES_CFB_Encrypt(ptp, ctp: Pointer; ILen: word; var ctx: TAESContext): integer; {-Encrypt ILen bytes from ptp^ to ctp^ in CFB128 mode} function AES_CFB_Decrypt(ctp, ptp: Pointer; ILen: word; var ctx: TAESContext): integer; {-Decrypt ILen bytes from ctp^ to ptp^ in CFB128 mode} function AES_CFB8_Init(const Key; KeyBits: word; const IV: TAESBlock; var ctx: TAESContext): integer; {-AES key expansion, error if invalid key size, store IV} function AES_CFB8_Encrypt(ptp, ctp: Pointer; ILen: word; var ctx: TAESContext): integer; {-Encrypt ILen bytes from ptp^ to ctp^ in CFB8 mode} function AES_CFB8_Decrypt(ctp, ptp: Pointer; ILen: word; var ctx: TAESContext): integer; {-Decrypt ILen bytes from ctp^ to ptp^ in CFB8 mode} function AES_OFB_Init(const Key; KeyBits: word; const IV: TAESBlock; var ctx: TAESContext): integer; {-AES key expansion, error if invalid key size, encrypt IV} function AES_OFB_Encrypt(ptp, ctp: Pointer; ILen: word; var ctx: TAESContext): integer; {-Encrypt ILen bytes from ptp^ to ctp^ in OFB mode} function AES_OFB_Decrypt(ctp, ptp: Pointer; ILen: word; var ctx: TAESContext): integer; {-Decrypt ILen bytes from ctp^ to ptp^ in OFB mode} function AES_CTR_Init(const Key; KeyBits: word; const CTR: TAESBlock; var ctx: TAESContext): integer; {-AES key expansion, error if inv. key size, encrypt CTR} function AES_CTR_Encrypt(ptp, ctp: Pointer; ILen: word; var ctx: TAESContext): integer; {-Encrypt ILen bytes from ptp^ to ctp^ in CTR mode} function AES_CTR_Decrypt(ctp, ptp: Pointer; ILen: word; var ctx: TAESContext): integer; {-Decrypt ILen bytes from ctp^ to ptp^ in CTR mode} function AES_SetIncProc(IncP: TIncProc; var ctx: TAESContext): integer; {-Set user supplied IncCTR proc} procedure AES_IncMSBFull(var CTR: TAESBlock); {-Increment CTR[15]..CTR[0]} procedure AES_IncLSBFull(var CTR: TAESBlock); {-Increment CTR[0]..CTR[15]} procedure AES_IncMSBPart(var CTR: TAESBlock); {-Increment CTR[15]..CTR[8]} procedure AES_IncLSBPart(var CTR: TAESBlock); {-Increment CTR[0]..CTR[7]} function AES_OMAC_Init(const Key; KeyBits: word; var ctx: TAESContext): integer; {-OMAC init: AES key expansion, error if inv. key size} function AES_OMAC_Update(data: pointer; ILen: word; var ctx: TAESContext): integer; {-OMAC data input, may be called more than once} procedure AES_OMAC_Final(var tag: TAESBlock; var ctx: TAESContext); {-end data input, calculate OMAC=OMAC1 tag} procedure AES_OMAC1_Final(var tag: TAESBlock; var ctx: TAESContext); {-end data input, calculate OMAC1 tag} procedure AES_OMAC2_Final(var tag: TAESBlock; var ctx: TAESContext); {-end data input, calculate OMAC2 tag} function AES_OMAC_UpdateXL(data: pointer; ILen: longint; var ctx: TAESContext): integer; {-OMAC data input, may be called more than once} procedure AES_OMACx_Final(OMAC2: boolean; var tag: TAESBlock; var ctx: TAESContext); {-end data input, calculate OMAC tag} function AES_CMAC_Init(const Key; KeyBits: word; var ctx: TAESContext): integer; {-CMAC init: AES key expansion, error if inv. key size} function AES_CMAC_Update(data: pointer; ILen: word; var ctx: TAESContext): integer; {-CMAC data input, may be called more than once} procedure AES_CMAC_Final(var tag: TAESBlock; var ctx: TAESContext); {-end data input, calculate CMAC=OMAC1 tag} function AES_CMAC_UpdateXL(data: pointer; ILen: longint; var ctx: TAESContext): integer; {-CMAC data input, may be called more than once} function AES_EAX_Init(const Key; KBits: word; const nonce; nLen: word; var ctx: TAES_EAXContext): integer; {-Init hdr and msg OMACs, setp AESCTR with nonce tag} function AES_EAX_Provide_Header(Hdr: pointer; hLen: word; var ctx: TAES_EAXContext): integer; {-Supply a message header. The header "grows" with each call} function AES_EAX_Encrypt(ptp, ctp: Pointer; ILen: word; var ctx: TAES_EAXContext): integer; {-Encrypt ILen bytes from ptp^ to ctp^ in CTR mode, update OMACs} function AES_EAX_Decrypt(ctp, ptp: Pointer; ILen: word; var ctx: TAES_EAXContext): integer; {-Encrypt ILen bytes from ptp^ to ctp^ in CTR mode, update OMACs} procedure AES_EAX_Final(var tag: TAESBlock; var ctx: TAES_EAXContext); {-Compute EAX tag from context} function AES_CPRF128(const Key; KeyBytes: word; msg: pointer; msglen: longint; var PRV: TAESBlock): integer; {Calculate variable-length key AES CMAC Pseudo-Random Function-128 for msg} {returns AES_OMAC error and 128-bit pseudo-random value PRV} function AES_CPRF128_selftest: boolean; {-Seftest with RFC 4615 test vectors} function AES_XTS_Init_Encr({$ifdef CONST}const{$else}var{$endif} K1,K2; KBits: word; var ctx: TAES_XTSContext): integer; {-Init XTS encrypt context (key expansion), error if invalid key size} function AES_XTS_Encrypt(ptp, ctp: Pointer; ILen: longint; {$ifdef CONST}const{$else}var{$endif} twk: TAESBlock; var ctx: TAES_XTSContext): integer; {-Encrypt data unit of ILen bytes from ptp^ to ctp^ in XTS mode, twk: tweak of data unit} function AES_XTS_Init_Decr({$ifdef CONST}const{$else}var{$endif} K1,K2; KBits: word; var ctx: TAES_XTSContext): integer; {-Init XTS decrypt context (key expansion), error if invalid key size} function AES_XTS_Decrypt(ctp, ptp: Pointer; ILen: longint; {$ifdef CONST}const{$else}var{$endif} twk: TAESBlock; var ctx: TAES_XTSContext): integer; {-Decrypt data unit of ILen bytes from ptp^ to ctp^ in XTS mode, twk: tweak of data unit} implementation function AES_DLL_Version; external 'AES_DLL' name 'AES_DLL_Version'; procedure AES_XorBlock; external 'AES_DLL' name 'AES_XorBlock'; function AES_Init; external 'AES_DLL' name 'AES_Init'; function AES_Init_Decr; external 'AES_DLL' name 'AES_Init_Decr'; function AES_Init_Encr; external 'AES_DLL' name 'AES_Init_Encr'; procedure AES_Decrypt; external 'AES_DLL' name 'AES_Decrypt'; procedure AES_Encrypt; external 'AES_DLL' name 'AES_Encrypt'; procedure AES_SetFastInit; external 'AES_DLL' name 'AES_SetFastInit'; function AES_GetFastInit; external 'AES_DLL' name 'AES_GetFastInit'; function AES_ECB_Init_Encr; external 'AES_DLL' name 'AES_ECB_Init_Encr'; function AES_ECB_Init_Decr; external 'AES_DLL' name 'AES_ECB_Init_Decr'; function AES_ECB_Encrypt; external 'AES_DLL' name 'AES_ECB_Encrypt'; function AES_ECB_Decrypt; external 'AES_DLL' name 'AES_ECB_Decrypt'; function AES_CBC_Init_Encr; external 'AES_DLL' name 'AES_CBC_Init_Encr'; function AES_CBC_Init_Decr; external 'AES_DLL' name 'AES_CBC_Init_Decr'; function AES_CBC_Encrypt; external 'AES_DLL' name 'AES_CBC_Encrypt'; function AES_CBC_Decrypt; external 'AES_DLL' name 'AES_CBC_Decrypt'; function AES_CFB_Init; external 'AES_DLL' name 'AES_CFB_Init'; function AES_CFB_Encrypt; external 'AES_DLL' name 'AES_CFB_Encrypt'; function AES_CFB_Decrypt; external 'AES_DLL' name 'AES_CFB_Decrypt'; function AES_CFB8_Init; external 'AES_DLL' name 'AES_CFB8_Init'; function AES_CFB8_Encrypt; external 'AES_DLL' name 'AES_CFB8_Encrypt'; function AES_CFB8_Decrypt; external 'AES_DLL' name 'AES_CFB8_Decrypt'; function AES_CTR_Init; external 'AES_DLL' name 'AES_CTR_Init'; function AES_CTR_Encrypt; external 'AES_DLL' name 'AES_CTR_Encrypt'; function AES_CTR_Decrypt; external 'AES_DLL' name 'AES_CTR_Decrypt'; function AES_SetIncProc; external 'AES_DLL' name 'AES_SetIncProc'; procedure AES_IncLSBFull; external 'AES_DLL' name 'AES_IncLSBFull'; procedure AES_IncLSBPart; external 'AES_DLL' name 'AES_IncLSBPart'; procedure AES_IncMSBFull; external 'AES_DLL' name 'AES_IncMSBFull'; procedure AES_IncMSBPart; external 'AES_DLL' name 'AES_IncMSBPart'; function AES_OFB_Init; external 'AES_DLL' name 'AES_OFB_Init'; function AES_OFB_Encrypt; external 'AES_DLL' name 'AES_OFB_Encrypt'; function AES_OFB_Decrypt; external 'AES_DLL' name 'AES_OFB_Decrypt'; function AES_OMAC_Init; external 'AES_DLL' name 'AES_OMAC_Init'; function AES_OMAC_Update; external 'AES_DLL' name 'AES_OMAC_Update'; function AES_OMAC_UpdateXL; external 'AES_DLL' name 'AES_OMAC_UpdateXL'; procedure AES_OMAC_Final; external 'AES_DLL' name 'AES_OMAC_Final'; procedure AES_OMAC1_Final; external 'AES_DLL' name 'AES_OMAC1_Final'; procedure AES_OMAC2_Final; external 'AES_DLL' name 'AES_OMAC2_Final'; procedure AES_OMACx_Final; external 'AES_DLL' name 'AES_OMACx_Final'; function AES_CMAC_Init; external 'AES_DLL' name 'AES_CMAC_Init'; function AES_CMAC_Update; external 'AES_DLL' name 'AES_CMAC_Update'; function AES_CMAC_UpdateXL; external 'AES_DLL' name 'AES_CMAC_UpdateXL'; procedure AES_CMAC_Final; external 'AES_DLL' name 'AES_CMAC_Final'; function AES_EAX_Init; external 'AES_DLL' name 'AES_EAX_Init'; function AES_EAX_Encrypt; external 'AES_DLL' name 'AES_EAX_Encrypt'; function AES_EAX_Decrypt; external 'AES_DLL' name 'AES_EAX_Decrypt'; procedure AES_EAX_Final; external 'AES_DLL' name 'AES_EAX_Final'; function AES_EAX_Provide_Header; external 'AES_DLL' name 'AES_EAX_Provide_Header'; function AES_CPRF128; external 'AES_DLL' name 'AES_CPRF128'; function AES_CPRF128_selftest; external 'AES_DLL' name 'AES_CPRF128_selftest'; function AES_XTS_Init_Encr; external 'AES_DLL' name 'AES_XTS_Init_Encr'; function AES_XTS_Encrypt; external 'AES_DLL' name 'AES_XTS_Encrypt'; function AES_XTS_Init_Decr; external 'AES_DLL' name 'AES_XTS_Init_Decr'; function AES_XTS_Decrypt; external 'AES_DLL' name 'AES_XTS_Decrypt'; end.
unit ExportTabularGMST; uses ExportCore, ExportTabularCore; var ExportTabularGMST_outputLines: TStringList; function initialize(): Integer; begin ExportTabularGMST_outputLines := TStringList.create(); ExportTabularGMST_outputLines.add( '"File"' // Name of the originating ESM + ', "Form ID"' // Form ID + ', "Editor ID"' // Editor ID + ', "Type"' // Type of value, such as `string` or `float` + ', "Value"' // Value of the settings ); end; function canProcess(el: IInterface): Boolean; begin result := signature(el) = 'GMST'; end; function process(gmst: IInterface): Integer; begin if not canProcess(gmst) then begin addWarning(name(gmst) + ' is not a GMST. Entry was ignored.'); exit; end; ExportTabularGMST_outputLines.add( escapeCsvString(getFileName(getFile(gmst))) + ', ' + escapeCsvString(stringFormID(gmst)) + ', ' + escapeCsvString(evBySign(gmst, 'EDID')) + ', ' + escapeCsvString(letterToType(copy(evBySign(gmst, 'EDID'), 1, 1))) + ', ' + escapeCsvString(gev(lastElement(eBySign(gmst, 'DATA')))) ); end; function finalize(): Integer; begin createDir('dumps/'); ExportTabularGMST_outputLines.saveToFile('dumps/GMST.csv'); ExportTabularGMST_outputLines.free(); end; function letterToType(letter: String): String; begin if letter = 'b' then begin result := 'boolean'; end else if letter = 'f' then begin result := 'float'; end else if letter = 'i' then begin result := 'integer'; end else if letter = 's' then begin result := 'string'; end else if letter = 'u' then begin result := 'unsigned integer'; end else begin result := addError('Unknown type `' + letter + '`'); end; end; end.
unit ETL.Form.Edit.Load.Script; interface uses ETL.Form.Edit, Vcl.StdCtrls, Vcl.Samples.Spin, Vcl.Controls, Vcl.ExtCtrls, System.Classes, System.Actions, Vcl.ActnList, Vcl.ComCtrls, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxEdit, cxDropDownEdit, cxVGrid, cxInplaceContainer, cxTextEdit; const SEPARATE_SCRIPT_CHAR = '|'; SEPARATE_SCRIPT_FIELDS_CHAR = ','; type TFoEditLoadScript = class(TFoEdit) PageControl1: TPageControl; TsSettings: TTabSheet; Label2: TLabel; CbCommit: TCheckBox; CbDisableFK: TCheckBox; CbUse: TCheckBox; RgCommand: TRadioGroup; EdBlock: TSpinEdit; TsNames: TTabSheet; EdSchema: TEdit; Label1: TLabel; Gr: TcxVerticalGrid; GrEditorRow1: TcxEditorRow; strict private public procedure AddField(const AField: string); function ToString: string; override; procedure SetValue(const ARow: Integer; const AValue: string); function getValue(const ARow: Integer): Variant; class function New(const AOwner: TComponent): TFoEditLoadScript; end; implementation {$R *.dfm} uses SysUtils, Variants; { TFoEditLoadScript } function TFoEditLoadScript.getValue(const ARow: Integer): Variant; begin Result := TcxEditorRow(Gr.Rows.Items[ARow]).Properties.Value; end; class function TFoEditLoadScript.New(const AOwner: TComponent): TFoEditLoadScript; begin Result := TFoEditLoadScript.Create(AOwner); end; procedure TFoEditLoadScript.SetValue(const ARow: Integer; const AValue: string); begin TcxEditorRow(Gr.Rows.Items[ARow]).Properties.Value := AValue; end; procedure TFoEditLoadScript.AddField(const AField: string); begin with Gr.Add(TcxEditorRow) as TcxEditorRow do begin Properties.EditPropertiesClass := TcxTextEditProperties; Properties.Caption := AField; Properties.Value := AField; end; end; function TFoEditLoadScript.ToString: string; var i: Integer; begin Result := IntToStr(RgCommand.ItemIndex) + SEPARATE_SCRIPT_CHAR; if CbDisableFK.Checked then Result := Result + '1'; Result := Result + SEPARATE_SCRIPT_CHAR; if CbUse.Checked then Result := Result + '1'; Result := Result + SEPARATE_SCRIPT_CHAR; Result := Result + EdSchema.Text + SEPARATE_SCRIPT_CHAR; if CbCommit.Checked then Result := Result + '1'; Result := Result + SEPARATE_SCRIPT_CHAR; Result := Result + EdBlock.Text + SEPARATE_SCRIPT_CHAR; for i := 0 to Gr.Rows.Count - 1 do Result := Result + VarToStr(TcxEditorRow(Gr.Rows.Items[i]).Properties.Value) + SEPARATE_SCRIPT_FIELDS_CHAR; end; end.
unit zoomableimageview; {$mode delphi} interface uses Classes, SysUtils, And_jni, {And_jni_Bridge,} AndroidWidget, systryparent; type {Draft Component code by "LAMW: Lazarus Android Module Wizard" [11/12/2019 21:55:59]} {https://github.com/jmpessoa/lazandroidmodulewizard} {jVisualControl template} jZoomableImageView = class(jVisualControl) private FimageIdentifier: string; FMaxZoom: single; procedure SetVisible(Value: Boolean); procedure SetColor(Value: TARGBColorBridge); //background public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Init; override; procedure Refresh; procedure UpdateLayout; override; procedure ClearLayout; procedure GenEvent_OnClick(Obj: TObject); function jCreate(): jObject; procedure jFree(); procedure SetViewParent(_viewgroup: jObject); override; function GetParent(): jObject; procedure RemoveFromViewParent(); override; function GetView(): jObject; override; procedure SetLParamWidth(_w: integer); procedure SetLParamHeight(_h: integer); function GetLParamWidth(): integer; function GetLParamHeight(): integer; procedure SetLGravity(_g: integer); procedure SetLWeight(_w: single); procedure SetLeftTopRightBottomWidthHeight(_left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer); procedure AddLParamsAnchorRule(_rule: integer); procedure AddLParamsParentRule(_rule: integer); procedure SetLayoutAll(_idAnchor: integer); procedure ClearLayoutAll(); procedure SetImageByResIdentifier(_imageResIdentifier: string); // ../res/drawable procedure SetImage(_bitmap: jObject); procedure SetMaxZoom(_maxZoom: single); function GetMaxZoom(): single; published property BackgroundColor: TARGBColorBridge read FColor write SetColor; property ImageIdentifier : string read FimageIdentifier write SetImageByResIdentifier; property MaxZoom: single read GetMaxZoom write SetMaxZoom; //property OnClick: TOnNotify read FOnClick write FOnClick; end; function jZoomableImageView_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject; procedure jZoomableImageView_jFree(env: PJNIEnv; _jzoomableimageview: JObject); procedure jZoomableImageView_SetViewParent(env: PJNIEnv; _jzoomableimageview: JObject; _viewgroup: jObject); procedure jZoomableImageView_SetId(env:PJNIEnv; _jzoomableimageview : jObject; id: DWord); function jZoomableImageView_GetParent(env: PJNIEnv; _jzoomableimageview: JObject): jObject; procedure jZoomableImageView_RemoveFromViewParent(env: PJNIEnv; _jzoomableimageview: JObject); function jZoomableImageView_GetView(env: PJNIEnv; _jzoomableimageview: JObject): jObject; procedure jZoomableImageView_SetLParamWidth(env: PJNIEnv; _jzoomableimageview: JObject; _w: integer); procedure jZoomableImageView_SetLParamHeight(env: PJNIEnv; _jzoomableimageview: JObject; _h: integer); function jZoomableImageView_GetLParamWidth(env: PJNIEnv; _jzoomableimageview: JObject): integer; function jZoomableImageView_GetLParamHeight(env: PJNIEnv; _jzoomableimageview: JObject): integer; procedure jZoomableImageView_SetLGravity(env: PJNIEnv; _jzoomableimageview: JObject; _g: integer); procedure jZoomableImageView_SetLWeight(env: PJNIEnv; _jzoomableimageview: JObject; _w: single); procedure jZoomableImageView_SetLeftTopRightBottomWidthHeight(env: PJNIEnv; _jzoomableimageview: JObject; _left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer); procedure jZoomableImageView_AddLParamsAnchorRule(env: PJNIEnv; _jzoomableimageview: JObject; _rule: integer); procedure jZoomableImageView_AddLParamsParentRule(env: PJNIEnv; _jzoomableimageview: JObject; _rule: integer); procedure jZoomableImageView_SetLayoutAll(env: PJNIEnv; _jzoomableimageview: JObject; _idAnchor: integer); procedure jZoomableImageView_ClearLayoutAll(env: PJNIEnv; _jzoomableimageview: JObject); procedure jZoomableImageView_SetImage(env: PJNIEnv; _jzoomableimageview: JObject; _bitmap: jObject); procedure jZoomableImageView_SetMaxZoom(env: PJNIEnv; _jzoomableimageview: JObject; _maxZoom: single); function jZoomableImageView_GetMaxZoom(env: PJNIEnv; _jzoomableimageview: JObject): single; Procedure jZoomableImageView_SetImageByResIdentifier(env:PJNIEnv; _jzoomableimageview : jObject; _imageResIdentifier: string); implementation {--------- jZoomableImageView --------------} constructor jZoomableImageView.Create(AOwner: TComponent); begin inherited Create(AOwner); if gapp <> nil then FId := gapp.GetNewId(); FMarginLeft := 10; FMarginTop := 10; FMarginBottom := 10; FMarginRight := 10; FHeight := 96; //?? FWidth := 96; //?? FLParamWidth := lpMatchParent; //lpWrapContent FLParamHeight := lpWrapContent; //lpMatchParent FAcceptChildrenAtDesignTime:= False; //your code here.... FMaxZoom:= 4; end; destructor jZoomableImageView.Destroy; begin if not (csDesigning in ComponentState) then begin if FjObject <> nil then begin jFree(); FjObject:= nil; end; end; //you others free code here...' inherited Destroy; end; procedure jZoomableImageView.Init; var rToP: TPositionRelativeToParent; rToA: TPositionRelativeToAnchorID; begin if not FInitialized then begin inherited Init; //set default ViewParent/FjPRLayout as jForm.View! //your code here: set/initialize create params.... FjObject := jCreate(); //jSelf ! if FjObject = nil then exit; if FParent <> nil then sysTryNewParent( FjPRLayout, FParent); FjPRLayoutHome:= FjPRLayout; jZoomableImageView_SetViewParent(gApp.jni.jEnv, FjObject, FjPRLayout); jZoomableImageView_SetId(gApp.jni.jEnv, FjObject, Self.Id); jZoomableImageView_SetMaxZoom(gApp.jni.jEnv, FjObject, FMaxZoom); end; jZoomableImageView_SetLeftTopRightBottomWidthHeight(gApp.jni.jEnv, FjObject, FMarginLeft,FMarginTop,FMarginRight,FMarginBottom, sysGetLayoutParams( FWidth, FLParamWidth, Self.Parent, sdW, fmarginLeft + fmarginRight ), sysGetLayoutParams( FHeight, FLParamHeight, Self.Parent, sdH, fMargintop + fMarginbottom )); for rToA := raAbove to raAlignRight do begin if rToA in FPositionRelativeToAnchor then begin jZoomableImageView_AddLParamsAnchorRule(gApp.jni.jEnv, FjObject, GetPositionRelativeToAnchor(rToA)); end; end; for rToP := rpBottom to rpCenterVertical do begin if rToP in FPositionRelativeToParent then begin jZoomableImageView_AddLParamsParentRule(gApp.jni.jEnv, FjObject, GetPositionRelativeToParent(rToP)); end; end; if Self.Anchor <> nil then Self.AnchorId:= Self.Anchor.Id else Self.AnchorId:= -1; //dummy jZoomableImageView_SetLayoutAll(gApp.jni.jEnv, FjObject, Self.AnchorId); if not FInitialized then begin FInitialized := true; if FColor <> colbrDefault then View_SetBackGroundColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FColor)); View_SetVisible(gApp.jni.jEnv, FjObject, FVisible); end; end; procedure jZoomableImageView.SetColor(Value: TARGBColorBridge); begin FColor:= Value; if (FInitialized = True) and (FColor <> colbrDefault) then View_SetBackGroundColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FColor)); end; procedure jZoomableImageView.SetVisible(Value : Boolean); begin FVisible:= Value; if FInitialized then View_SetVisible(gApp.jni.jEnv, FjObject, FVisible); end; procedure jZoomableImageView.UpdateLayout; begin if not FInitialized then exit; ClearLayout(); inherited UpdateLayout; init; end; procedure jZoomableImageView.Refresh; begin if FInitialized then View_Invalidate(gApp.jni.jEnv, FjObject); end; procedure jZoomableImageView.ClearLayout; var rToP: TPositionRelativeToParent; rToA: TPositionRelativeToAnchorID; begin if not FInitialized then Exit; jZoomableImageView_ClearLayoutAll(gApp.jni.jEnv, FjObject ); for rToP := rpBottom to rpCenterVertical do if rToP in FPositionRelativeToParent then jZoomableImageView_AddLParamsParentRule(gApp.jni.jEnv, FjObject , GetPositionRelativeToParent(rToP)); for rToA := raAbove to raAlignRight do if rToA in FPositionRelativeToAnchor then jZoomableImageView_AddLParamsAnchorRule(gApp.jni.jEnv, FjObject , GetPositionRelativeToAnchor(rToA)); end; //Event : Java -> Pascal procedure jZoomableImageView.GenEvent_OnClick(Obj: TObject); begin if Assigned(FOnClick) then FOnClick(Obj); end; function jZoomableImageView.jCreate(): jObject; begin Result:= jZoomableImageView_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis); end; procedure jZoomableImageView.jFree(); begin //in designing component state: set value here... if FInitialized then jZoomableImageView_jFree(gApp.jni.jEnv, FjObject); end; procedure jZoomableImageView.SetViewParent(_viewgroup: jObject); begin //in designing component state: set value here... if FInitialized then jZoomableImageView_SetViewParent(gApp.jni.jEnv, FjObject, _viewgroup); end; function jZoomableImageView.GetParent(): jObject; begin //in designing component state: result value here... if FInitialized then Result:= jZoomableImageView_GetParent(gApp.jni.jEnv, FjObject); end; procedure jZoomableImageView.RemoveFromViewParent(); begin //in designing component state: set value here... if FInitialized then jZoomableImageView_RemoveFromViewParent(gApp.jni.jEnv, FjObject); end; function jZoomableImageView.GetView(): jObject; begin //in designing component state: result value here... if FInitialized then Result:= jZoomableImageView_GetView(gApp.jni.jEnv, FjObject); end; procedure jZoomableImageView.SetLParamWidth(_w: integer); begin //in designing component state: set value here... if FInitialized then jZoomableImageView_SetLParamWidth(gApp.jni.jEnv, FjObject, _w); end; procedure jZoomableImageView.SetLParamHeight(_h: integer); begin //in designing component state: set value here... if FInitialized then jZoomableImageView_SetLParamHeight(gApp.jni.jEnv, FjObject, _h); end; function jZoomableImageView.GetLParamWidth(): integer; begin //in designing component state: result value here... if FInitialized then Result:= jZoomableImageView_GetLParamWidth(gApp.jni.jEnv, FjObject); end; function jZoomableImageView.GetLParamHeight(): integer; begin //in designing component state: result value here... if FInitialized then Result:= jZoomableImageView_GetLParamHeight(gApp.jni.jEnv, FjObject); end; procedure jZoomableImageView.SetLGravity(_g: integer); begin //in designing component state: set value here... if FInitialized then jZoomableImageView_SetLGravity(gApp.jni.jEnv, FjObject, _g); end; procedure jZoomableImageView.SetLWeight(_w: single); begin //in designing component state: set value here... if FInitialized then jZoomableImageView_SetLWeight(gApp.jni.jEnv, FjObject, _w); end; procedure jZoomableImageView.SetLeftTopRightBottomWidthHeight(_left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer); begin //in designing component state: set value here... if FInitialized then jZoomableImageView_SetLeftTopRightBottomWidthHeight(gApp.jni.jEnv, FjObject, _left ,_top ,_right ,_bottom ,_w ,_h); end; procedure jZoomableImageView.AddLParamsAnchorRule(_rule: integer); begin //in designing component state: set value here... if FInitialized then jZoomableImageView_AddLParamsAnchorRule(gApp.jni.jEnv, FjObject, _rule); end; procedure jZoomableImageView.AddLParamsParentRule(_rule: integer); begin //in designing component state: set value here... if FInitialized then jZoomableImageView_AddLParamsParentRule(gApp.jni.jEnv, FjObject, _rule); end; procedure jZoomableImageView.SetLayoutAll(_idAnchor: integer); begin //in designing component state: set value here... if FInitialized then jZoomableImageView_SetLayoutAll(gApp.jni.jEnv, FjObject, _idAnchor); end; procedure jZoomableImageView.ClearLayoutAll(); begin //in designing component state: set value here... if FInitialized then jZoomableImageView_ClearLayoutAll(gApp.jni.jEnv, FjObject); end; procedure jZoomableImageView.SetImage(_bitmap: jObject); begin //in designing component state: set value here... if FInitialized then jZoomableImageView_SetImage(gApp.jni.jEnv, FjObject, _bitmap); end; procedure jZoomableImageView.SetMaxZoom(_maxZoom: single); begin //in designing component state: set value here... if _maxZoom <= 0 then Exit; FMaxZoom:= _maxZoom; if FInitialized then jZoomableImageView_SetMaxZoom(gApp.jni.jEnv, FjObject, _maxZoom); end; function jZoomableImageView.GetMaxZoom(): single; begin //in designing component state: result value here... Result:= FMaxZoom; if FInitialized then Result:= jZoomableImageView_GetMaxZoom(gApp.jni.jEnv, FjObject); end; procedure jZoomableImageView.SetImageByResIdentifier(_imageResIdentifier: string); begin FimageIdentifier:= _imageResIdentifier; if FInitialized then jZoomableImageView_SetImageByResIdentifier(gApp.jni.jEnv, FjObject , _imageResIdentifier); end; {-------- jZoomableImageView_JNI_Bridge ----------} function jZoomableImageView_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject; var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].j:= _Self; jCls:= Get_gjClass(env); jMethod:= env^.GetMethodID(env, jCls, 'jZoomableImageView_jCreate', '(J)Ljava/lang/Object;'); Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams); Result:= env^.NewGlobalRef(env, Result); end; procedure jZoomableImageView_jFree(env: PJNIEnv; _jzoomableimageview: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jzoomableimageview); jMethod:= env^.GetMethodID(env, jCls, 'jFree', '()V'); env^.CallVoidMethod(env, _jzoomableimageview, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jZoomableImageView_SetViewParent(env: PJNIEnv; _jzoomableimageview: JObject; _viewgroup: jObject); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= _viewgroup; jCls:= env^.GetObjectClass(env, _jzoomableimageview); jMethod:= env^.GetMethodID(env, jCls, 'SetViewParent', '(Landroid/view/ViewGroup;)V'); env^.CallVoidMethodA(env, _jzoomableimageview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jZoomableImageView_SetId(env:PJNIEnv; _jzoomableimageview : jObject; id: DWord); var _jMethod : jMethodID = nil; _jParams : array[0..0] of jValue; cls: jClass; begin _jParams[0].i:= id; cls := env^.GetObjectClass(env, _jzoomableimageview); _jMethod:= env^.GetMethodID(env, cls, 'SetId', '(I)V'); env^.CallVoidMethodA(env,_jzoomableimageview,_jMethod,@_jParams); env^.DeleteLocalRef(env, cls); end; function jZoomableImageView_GetParent(env: PJNIEnv; _jzoomableimageview: JObject): jObject; var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jzoomableimageview); jMethod:= env^.GetMethodID(env, jCls, 'GetParent', '()Landroid/view/ViewGroup;'); Result:= env^.CallObjectMethod(env, _jzoomableimageview, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jZoomableImageView_RemoveFromViewParent(env: PJNIEnv; _jzoomableimageview: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jzoomableimageview); jMethod:= env^.GetMethodID(env, jCls, 'RemoveFromViewParent', '()V'); env^.CallVoidMethod(env, _jzoomableimageview, jMethod); env^.DeleteLocalRef(env, jCls); end; function jZoomableImageView_GetView(env: PJNIEnv; _jzoomableimageview: JObject): jObject; var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jzoomableimageview); jMethod:= env^.GetMethodID(env, jCls, 'GetView', '()Landroid/view/View;'); Result:= env^.CallObjectMethod(env, _jzoomableimageview, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jZoomableImageView_SetLParamWidth(env: PJNIEnv; _jzoomableimageview: JObject; _w: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _w; jCls:= env^.GetObjectClass(env, _jzoomableimageview); jMethod:= env^.GetMethodID(env, jCls, 'SetLParamWidth', '(I)V'); env^.CallVoidMethodA(env, _jzoomableimageview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jZoomableImageView_SetLParamHeight(env: PJNIEnv; _jzoomableimageview: JObject; _h: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _h; jCls:= env^.GetObjectClass(env, _jzoomableimageview); jMethod:= env^.GetMethodID(env, jCls, 'SetLParamHeight', '(I)V'); env^.CallVoidMethodA(env, _jzoomableimageview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; function jZoomableImageView_GetLParamWidth(env: PJNIEnv; _jzoomableimageview: JObject): integer; var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jzoomableimageview); jMethod:= env^.GetMethodID(env, jCls, 'GetLParamWidth', '()I'); Result:= env^.CallIntMethod(env, _jzoomableimageview, jMethod); env^.DeleteLocalRef(env, jCls); end; function jZoomableImageView_GetLParamHeight(env: PJNIEnv; _jzoomableimageview: JObject): integer; var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jzoomableimageview); jMethod:= env^.GetMethodID(env, jCls, 'GetLParamHeight', '()I'); Result:= env^.CallIntMethod(env, _jzoomableimageview, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jZoomableImageView_SetLGravity(env: PJNIEnv; _jzoomableimageview: JObject; _g: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _g; jCls:= env^.GetObjectClass(env, _jzoomableimageview); jMethod:= env^.GetMethodID(env, jCls, 'SetLGravity', '(I)V'); env^.CallVoidMethodA(env, _jzoomableimageview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jZoomableImageView_SetLWeight(env: PJNIEnv; _jzoomableimageview: JObject; _w: single); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].f:= _w; jCls:= env^.GetObjectClass(env, _jzoomableimageview); jMethod:= env^.GetMethodID(env, jCls, 'SetLWeight', '(F)V'); env^.CallVoidMethodA(env, _jzoomableimageview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jZoomableImageView_SetLeftTopRightBottomWidthHeight(env: PJNIEnv; _jzoomableimageview: JObject; _left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer); var jParams: array[0..5] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _left; jParams[1].i:= _top; jParams[2].i:= _right; jParams[3].i:= _bottom; jParams[4].i:= _w; jParams[5].i:= _h; jCls:= env^.GetObjectClass(env, _jzoomableimageview); jMethod:= env^.GetMethodID(env, jCls, 'SetLeftTopRightBottomWidthHeight', '(IIIIII)V'); env^.CallVoidMethodA(env, _jzoomableimageview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jZoomableImageView_AddLParamsAnchorRule(env: PJNIEnv; _jzoomableimageview: JObject; _rule: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _rule; jCls:= env^.GetObjectClass(env, _jzoomableimageview); jMethod:= env^.GetMethodID(env, jCls, 'AddLParamsAnchorRule', '(I)V'); env^.CallVoidMethodA(env, _jzoomableimageview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jZoomableImageView_AddLParamsParentRule(env: PJNIEnv; _jzoomableimageview: JObject; _rule: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _rule; jCls:= env^.GetObjectClass(env, _jzoomableimageview); jMethod:= env^.GetMethodID(env, jCls, 'AddLParamsParentRule', '(I)V'); env^.CallVoidMethodA(env, _jzoomableimageview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jZoomableImageView_SetLayoutAll(env: PJNIEnv; _jzoomableimageview: JObject; _idAnchor: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _idAnchor; jCls:= env^.GetObjectClass(env, _jzoomableimageview); jMethod:= env^.GetMethodID(env, jCls, 'SetLayoutAll', '(I)V'); env^.CallVoidMethodA(env, _jzoomableimageview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jZoomableImageView_ClearLayoutAll(env: PJNIEnv; _jzoomableimageview: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jzoomableimageview); jMethod:= env^.GetMethodID(env, jCls, 'ClearLayoutAll', '()V'); env^.CallVoidMethod(env, _jzoomableimageview, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jZoomableImageView_SetImage(env: PJNIEnv; _jzoomableimageview: JObject; _bitmap: jObject); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= _bitmap; jCls:= env^.GetObjectClass(env, _jzoomableimageview); jMethod:= env^.GetMethodID(env, jCls, 'SetImage', '(Landroid/graphics/Bitmap;)V'); env^.CallVoidMethodA(env, _jzoomableimageview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jZoomableImageView_SetMaxZoom(env: PJNIEnv; _jzoomableimageview: JObject; _maxZoom: single); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].f:= _maxZoom; jCls:= env^.GetObjectClass(env, _jzoomableimageview); jMethod:= env^.GetMethodID(env, jCls, 'SetMaxZoom', '(F)V'); env^.CallVoidMethodA(env, _jzoomableimageview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; function jZoomableImageView_GetMaxZoom(env: PJNIEnv; _jzoomableimageview: JObject): single; var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jzoomableimageview); jMethod:= env^.GetMethodID(env, jCls, 'GetMaxZoom', '()F'); Result:= env^.CallFloatMethod(env, _jzoomableimageview, jMethod); env^.DeleteLocalRef(env, jCls); end; Procedure jZoomableImageView_SetImageByResIdentifier(env:PJNIEnv; _jzoomableimageview : jObject; _imageResIdentifier: string); var _jMethod : jMethodID = nil; _jParams : array[0..0] of jValue; cls: jClass; begin _jParams[0].l := env^.NewStringUTF(env, PChar(_imageResIdentifier) ); cls := env^.GetObjectClass(env, _jzoomableimageview); _jMethod:= env^.GetMethodID(env, cls, 'SetImageByResIdentifier', '(Ljava/lang/String;)V'); env^.CallVoidMethodA(env,_jzoomableimageview,_jMethod,@_jParams); env^.DeleteLocalRef(env,_jParams[0].l); env^.DeleteLocalRef(env, cls); end; end.
{ NIM/Nama : 16518332/Dhafin Rayhan Ahmad } { Tanggal : 22 Maret 2019 } Program ProsesLingkaran; { Input: 2 buah Lingkaran } { Output: luas, keliling, dan hubungan lingkaran A dan B } { KAMUS } const PI : real = 3.1415; type { Definisi Type Koordinat } Koordinat = record x : real; y : real; end; { Definisi Type Lingkaran } Lingkaran = record c : Koordinat; { titik pusat lingkaran } r : real; { jari-jari, > 0 } end; var A, B : Lingkaran; { variabel untuk lingkaran A dan B } { FUNGSI DAN PROSEDUR } function IsRValid (var r : real) : boolean; { Menghasilkan validasi r > 0 } { ALGORITMA FUNGSI IsRValid } begin if (r > 0) then begin IsRValid := true; end else { rx <= 0 } begin IsRValid := false; end; end; procedure InputLingkaran (var A : Lingkaran); { I.S.: A sembarang } { F.S.: A terdefinisi sesuai dengan masukan pengguna. Pemasukan jari-jari diulangi sampai didapatkan jari-jari yang benar yaitu r > 0. Pemeriksaan apakah jari- jari valid menggunakan fungsi IsRValid. Jika jari-jari tidak valid, dikeluarkan pesan kesalahan “Jari-jari harus > 0”. } { KAMUS LOKAL } var r : real; { ALGORITMA PROSEDUR InputLingkaran } begin readln(A.c.x, A.c.y); readln(r); while (IsRValid(r) = false) do begin writeln('Jari-jari harus > 0'); readln(r); end; A.r := r; end; function KelilingLingkaran (var A : Lingkaran) : real; { Menghasilkan keliling lingkaran A = 2 * PI * A.r } { ALGORITMA FUNGSI KelilingLingkaran } begin KelilingLingkaran := 2 * PI * A.r; end; function LuasLingkaran (var A : Lingkaran) : real; { Menghasilkan luas lingkaran A = PI * A.r * A.r } { ALGORITMA FUNGSI LuasLingkaran } begin LuasLingkaran := PI * A.r * A.r; end; function Jarak (var P1, P2 : Koordinat) : real; { Menghasilkan jarak antara P1 dan P2 } { ALGORITMA FUNGSI Jarak } begin Jarak := sqrt((P2.x-P1.x)*(P2.x-P1.x)+(P2.y-P1.y)*(P2.y-P1.y)); end; function HubunganLingkaran (var A, B : Lingkaran) : integer; { Menghasilkan integer yang menyatakan hubungan lingkaran A dan B, yaitu: 1 = A dan B sama; 2 = A dan B berimpit; 3 = A dan B beririsan; 4 = A dan B bersentuhan; 5 = A dan B saling lepas } { ALGORITMA FUNGSI HubunganLingkaran } begin if (Jarak(A.c, B.c) = 0) and (A.r = B.r) then begin HubunganLingkaran := 1; end else if (Jarak(A.c, B.c) = 0) and (A.r <> B.r) then begin HubunganLingkaran := 2; end else if (Jarak(A.c, B.c) <> 0) and (Jarak(A.c, B.c) < (A.r + B.r)) then begin HubunganLingkaran := 3; end else if (Jarak(A.c, B.c) = (A.r + B.r)) then begin HubunganLingkaran := 4; end else { Jarak(A.c, B.c) > (A.r + B.r) } begin HubunganLingkaran := 5; end; end; { ALGORITMA PROGRAM UTAMA } begin writeln('Masukkan lingkaran A:'); InputLingkaran(A); writeln('Masukkan lingkaran B:'); InputLingkaran(B); writeln('Keliling lingkaran A = ', KelilingLingkaran(A):0:2); writeln('Luas lingkaran A = ', LuasLingkaran(A):0:2); writeln('Keliling lingkaran B = ', KelilingLingkaran(B):0:2); writeln('Luas lingkaran B = ', LuasLingkaran(B):0:2); write('A dan B adalah '); case HubunganLingkaran(A, B) of 1 : begin writeln('sama'); end; 2 : begin writeln('berimpit'); end; 3 : begin writeln('beririsan'); end; 4 : begin writeln('bersentuhan'); end; else { 5 } begin writeln('saling lepas'); end; end; end.
unit EditExts; {********************************************** Kingstar Delphi Library Copyright (C) Kingstar Corporation <Unit>EditExts <What>扩充的输入控件 <Written By> Huang YanLai (黄燕来) <History> 1.1 对数字输入控件的按键消息处理进行了修改,原来不能让下层自动处理ESC/ALT+F4等等消息,现在可以了。 1.0 **********************************************} { TODO : Bug1:Text可以任意指定(非法字符串) Bug2:设置Value过大,Text变成科学计数法 ,产生出"E' } (***** Code Written By Huang YanLai *****) interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,StdCtrls,ExtCtrls; type { keys: '0'..'9','+','-','.' back,delete : 删除最后一个字符 shift+delete : 清空 deleteChar : 删除最后一个字符 ClearChar : 清空 } { Notes : 解决了关键的bug。 原来使用缺省的AutoSize属性(来自TControl)。 但是如果AutoSize=True的时候,因为各种原因(文字大小变化、对齐等等)多次更改控件的大小以后,控件的大小变为不正常,变为0。 修正的方法是: 1、设置继承的AutoSize=False。 2、增加一个新的AutoSize属性。 } TKSDigitalEdit = class(TCustomControl) private { Private declarations } FAllowPoint: boolean; FAllowNegative: boolean; FUserSeprator: boolean; FOnChange: TNotifyEvent; FReadOnly: boolean; FDeleteChar: char; FRedNegative: boolean; FNegativeColor: TColor; FMaxIntLen: integer; FPrecision: integer; FClearChar: char; FLeading: string; FBorderStyle: TBorderStyle; FErrorBeep: boolean; FAutoselect:boolean; //add FSelectedTextColor:TColor; //add FSelectedColor:TColor; //add FSelected : Boolean; FAutoSize: Boolean; procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN; procedure SetUserSeprator(const Value: boolean); procedure WMSetFocus(var Message:TWMSetFocus); message WM_SetFocus; procedure WMKillFocus(var Message:TWMKillFocus); message WM_KillFocus; procedure HandleDelete; procedure SetNegativeColor(const Value: TColor); procedure SetRedNegative(const Value: boolean); procedure SetSelectedTextColor(const Value: TColor); //add procedure SetSelectedColor(const Value: TColor); //add procedure SetLeading(const Value: string); procedure SetBorderStyle(const Value: TBorderStyle); procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED; procedure SetSelected(const Value: Boolean); function GetValue: Double; procedure SetValue(const Value: Double); procedure SetReadOnly(const Value: boolean); procedure SetAutoSize(const Value: Boolean); procedure UpdateHeight; procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE; procedure CMWANTSPECIALKEY(var Message:TMessage); message CM_WANTSPECIALKEY; protected { Protected declarations } procedure Paint; override; procedure PaintBorder(var R:TRect); dynamic; procedure PaintText(var R:TRect); dynamic; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyUp(var Key: Word; Shift: TShiftState); override; //procedure KeyUp(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; //modify function acceptKey(key:char):boolean; dynamic; procedure HandleKey(Key:char); dynamic; procedure Change; dynamic; function CanAddDigital(const AText:string): boolean; dynamic; procedure Loaded; override; procedure ReadOnlyChanged; dynamic; public { Public declarations } constructor Create(AOwner : TComponent); override; function GetDisplayText : string; dynamic; procedure Clear; property Selected : Boolean read FSelected write SetSelected; published { Published declarations } property AutoSize: Boolean read FAutoSize write SetAutoSize default False; property AllowPoint : boolean read FAllowPoint write FAllowPoint default false; property AllowNegative : boolean read FAllowNegative write FAllowNegative default false; property UserSeprator : boolean read FUserSeprator write SetUserSeprator default false; property ReadOnly : boolean read FReadOnly write SetReadOnly default false; property DeleteChar : char read FDeleteChar write FDeleteChar default #0; property ClearChar : char read FClearChar write FClearChar default #0; property RedNegative : boolean read FRedNegative write SetRedNegative default false; property NegativeColor : TColor read FNegativeColor write SetNegativeColor default clRed; property Precision : integer read FPrecision write FPrecision default -1; property MaxIntLen : integer read FMaxIntLen write FMaxIntLen default -1; property Leading : string read FLeading write SetLeading; property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle; property ErrorBeep : boolean read FErrorBeep write FErrorBeep default false; property OnChange : TNotifyEvent read FOnChange write FOnChange; property AutoSelect: boolean read FAutoselect write FAutoselect default True; //add property SelectedColor: TColor read FSelectedColor write SetSelectedColor default clNavy;//add property SelectedTextColor:TColor read FSelectedTextColor write SetSelectedTextColor default clwhite; //add property Value : Double read GetValue write SetValue; property Anchors; //property AutoSize default true; property BiDiMode; //property BorderStyle; property Color default clWhite; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Text; property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; end; procedure Register; implementation //uses LogFile; procedure Register; begin RegisterComponents('UserCtrls', [TKSDigitalEdit]); end; { TKSDigitalEdit } constructor TKSDigitalEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); Width := 121; Height := 25; TabStop := True; ParentColor := False; Text:='0'; inherited AutoSize := False; FAutoSize := False; FAllowPoint:=false; FAllowNegative:=false; FUserSeprator:=false; FReadOnly := false; FDeleteChar := #0; FClearChar := #0; FRedNegative := false; FNegativeColor := clRed; FPrecision:=-1; FMaxIntLen:=-1; FBorderStyle:=bsSingle; FErrorBeep := false; FSelectedTextColor:=clwhite; FSelectedColor:=clNavy; FAutoselect := True; end; function TKSDigitalEdit.acceptKey(key: char): boolean; begin result := not ReadOnly and ( (key in ['0'..'9',char(VK_Back),DeleteChar,ClearChar]) or ( (key in ['+','-']) and AllowNegative) or ( (key='.') and AllowPoint) ); end; procedure TKSDigitalEdit.HandleKey(Key: char); var l : integer; AText : string; begin if key=#0 then exit; AText := text; if Selected then begin FSelected := False; AText := '0'; end; l := length(AText); if (key=char(VK_Back)) or ((key=DeleteChar)) then begin //if l>0 then text:=Copy(AText,1,l-1); HandleDelete; end else if key=ClearChar then Clear else if key in ['0'..'9'] then begin if AText='0' then Text:=key else if CanAddDigital(AText) then begin text:=Atext+key; end; end else if (key in ['+','-']) and (l>0) then begin {if AText[1]='-' then delete(AText,1,1); if (key='-') and (AText<>'0') then AText:='-'+AText;} if AText[1]='-' then // no matter when key='+' or key='-' delete(AText,1,1) else if (key='-') and (AText<>'0') then // positive to negative AText:='-'+AText; Text:=AText; end else if (key='.') and (pos('.',AText)<=0) then Text:=AText+'.'; end; procedure TKSDigitalEdit.KeyPress(var Key: Char); begin inherited KeyPress(Key); if acceptKey(Key) then begin HandleKey(Key); Key := #0; end else if ErrorBeep then Beep; end; procedure TKSDigitalEdit.Paint; var r : TRect; begin HideCaret(Handle); r := GetClientRect; { if R.Right-R.Left=0 then begin WriteLog(Format('TKSDigitalEdit=(%d,%d)',[Width,Height])); end; } PaintBorder(r); InflateRect(r,-1,-1); PaintText(r); ShowCaret(Handle); end; procedure TKSDigitalEdit.PaintBorder(var R:TRect); begin Canvas.Brush.Color := Color; Canvas.FillRect(r); if BorderStyle=bsSingle then if Ctl3D then Frame3D(Canvas,r,clBlack,clBtnHighlight,2) else Frame3D(Canvas,r,clBlack,clBlack,1); end; procedure TKSDigitalEdit.PaintText(var R:TRect); var AText : string; begin Canvas.Font := Font; if RedNegative then begin AText := Text; if (length(AText)>0) and (AText[1]='-') then Canvas.Font.Color := NegativeColor; end; WINDOWS.DrawText(Canvas.handle,pchar(FLeading),-1,R, DT_Left or DT_SINGLELINE or DT_VCENTER ); if Selected then begin Canvas.Font.Color := SelectedTextColor; Canvas.Brush.Color := SelectedColor; end; AText := GetDisplayText; //OutputDebugString(PChar(AText)); WINDOWS.DrawText(Canvas.handle,pchar(AText),-1,R, DT_RIGHT or DT_SINGLELINE or DT_VCENTER ); end; function TKSDigitalEdit.GetDisplayText: string; var i,l : integer; AText : string; PositivePart,NegativePart : string; Negativechar : char; begin AText :=text; if (AText='') or not UserSeprator then result := Atext else begin if AText[1] in ['-','+'] then begin Negativechar:=AText[1]; delete(Atext,1,1); end else begin Negativechar:=#0; end; i:=pos('.',Atext); if i>0 then begin PositivePart := copy(AText,1,i-1); NegativePart := copy(AText,i,length(Atext)-i+1); end else begin PositivePart := AText; NegativePart := ''; end; result := NegativePart; l := length(PositivePart); for i:=0 to l-1 do begin result := PositivePart[l-i]+result; if ( ((i+1) mod 3)=0 ) and (i<>l-1) then result := ','+result; end; if Negativechar<>#0 then result := Negativechar+result; end; end; procedure TKSDigitalEdit.CMTextChanged(var Message: TMessage); begin inherited; Change; end; procedure TKSDigitalEdit.WMLButtonDown(var Message: TWMLButtonDown); begin inherited; if CanFocus then SetFocus; end; procedure TKSDigitalEdit.SetUserSeprator(const Value: boolean); begin if FUserSeprator <> Value then begin FUserSeprator := Value; Invalidate; end; end; procedure TKSDigitalEdit.Change; begin if assigned(FOnChange) then FOnChange(self); Invalidate; end; procedure TKSDigitalEdit.WMKillFocus(var Message: TWMKillFocus); begin inherited ; DestroyCaret; Selected := False; end; procedure TKSDigitalEdit.WMSetFocus(var Message: TWMSetFocus); begin inherited ; CreateCaret(Handle, 0, 2, abs(Font.Height)); SetCaretPos(width-4,(Height-abs(Font.Height))div 2); ShowCaret(handle); if AutoSelect then Selected := True; end; procedure TKSDigitalEdit.KeyDown(var Key: Word; Shift: TShiftState); begin inherited KeyDown(Key,Shift); if (key=VK_Delete) and not ReadOnly then begin if not (ssShift in Shift) then HandleDelete else Clear; Key := 0; end else if Key in [VK_LEFT,VK_RIGHT,VK_UP,VK_DOWN] then begin Selected := False; Key := 0; end; end; procedure TKSDigitalEdit.HandleDelete; var AText : string; l : integer; begin AText := text; l := length(AText); if l>0 then Atext:=Copy(AText,1,l-1); if (AText='') or (AText='-') or (AText='+') then AText:='0'; Text:=AText; end; procedure TKSDigitalEdit.SetNegativeColor(const Value: TColor); begin if FNegativeColor <> Value then begin FNegativeColor := Value; if RedNegative then Invalidate; end; end; procedure TKSDigitalEdit.SetRedNegative(const Value: boolean); begin if FRedNegative <> Value then begin FRedNegative := Value; Invalidate; end; end; //begin add procedure TKSDigitalEdit.SetSelectedTextColor(const Value: TColor); begin if FSelectedTextColor <> Value then begin FSelectedTextColor:= Value; Invalidate; end; end; procedure TKSDigitalEdit.SetSelectedColor(const Value: TColor); begin if FSelectedColor <> Value then begin FSelectedColor:= Value; Invalidate; end; end; //end add function TKSDigitalEdit.CanAddDigital(const AText: string): boolean; var i,l : integer; begin l:=length(AText); i:=pos('.',Atext); if i>0 then begin // after point result := (Precision<0) or (l-i<Precision); end else begin // before point result := (MaxIntLen<0) or (l=0) or (l<MaxIntLen) or ((Atext[1]='-') and (l-1<MaxIntLen)); end; end; procedure TKSDigitalEdit.Clear; begin Text:='0'; end; procedure TKSDigitalEdit.SetLeading(const Value: string); begin if FLeading <> Value then begin FLeading := Value; Invalidate; end; end; procedure TKSDigitalEdit.SetBorderStyle(const Value: TBorderStyle); begin if FBorderStyle <> Value then begin FBorderStyle := Value; if AutoSize then UpdateHeight else invalidate; end; end; const Margin = 1; procedure TKSDigitalEdit.CMFontChanged(var Message: TMessage); begin Inherited; UpdateHeight; end; procedure TKSDigitalEdit.CMCtl3DChanged(var Message: TMessage); begin inherited; UpdateHeight; end; procedure TKSDigitalEdit.Loaded; begin inherited Loaded; UpdateHeight; end; procedure TKSDigitalEdit.SetSelected(const Value: Boolean); begin if FSelected <> Value then begin FSelected := Value; Invalidate; end; end; function TKSDigitalEdit.GetValue: Double; begin Result := StrToFloat(Text); end; procedure TKSDigitalEdit.SetValue(const Value: Double); var aPrecision, aDigits: Integer; begin if AllowPoint then if Precision>=0 then aDigits := Precision else aDigits := 18 else aDigits := 0; aPrecision := 15; Text := FloatToStrF(Value,ffFixed,aPrecision,aDigits); end; procedure TKSDigitalEdit.SetReadOnly(const Value: boolean); begin if FReadOnly <> Value then begin FReadOnly := Value; ReadOnlyChanged; end; end; procedure TKSDigitalEdit.ReadOnlyChanged; begin end; procedure TKSDigitalEdit.SetAutoSize(const Value: Boolean); begin if FAutoSize <> Value then begin FAutoSize := Value; UpdateHeight; end; end; procedure TKSDigitalEdit.UpdateHeight; var Delta : integer; NewHeight : integer; begin //OutputDebugString(PChar(Format('Before UpdateHeight : %d,%d,%d,%d',[Left, Top, Width, Height]))); if AutoSize and HandleAllocated and not (csLoading in ComponentState) and not (csReading in ComponentState) then begin if BorderStyle=bsNone then Delta:=0 else if Ctl3D then Delta:=2*2 else Delta:=2*1; NewHeight := Abs(Font.Height)+Delta+2*Margin; SetBounds(Left, Top, Width, NewHeight); { // 下面注释的方法,解说不正确。关键在于不能使用缺省的AutoSize属性。 // 直接调用API,关键是SWP_NOSENDCHANGING标志,避免TWinControl错误的更新大小(否则,错误地更新为0) SetWindowPos(Handle, 0, Left, Top, Width, NewHeight, SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOZORDER or SWP_NOSENDCHANGING); } end; //OutputDebugString(PChar(Format('After UpdateHeight : %d,%d,%d,%d',[Left, Top, Width, Height]))); end; procedure TKSDigitalEdit.WMGetDlgCode(var Message: TWMGetDlgCode); begin inherited; Message.Result := Message.Result {or DLGC_WANTALLKEYS} or DLGC_WANTARROWS or DLGC_WANTCHARS; end; procedure TKSDigitalEdit.KeyUp(var Key: Word; Shift: TShiftState); begin inherited; if Key in [VK_LEFT,VK_RIGHT,VK_UP,VK_DOWN,VK_DELETE] then begin Key := 0; end; end; procedure TKSDigitalEdit.CMWANTSPECIALKEY(var Message: TMessage); begin inherited; if Message.WParam=VK_RETURN then Message.Result := 1; end; end.
unit dblistview; {$mode delphi} interface uses Classes, SysUtils, And_jni, And_jni_Bridge, AndroidWidget, Laz_And_Controls; type TOnClickDBListItem = procedure(Sender: TObject; itemIndex: integer; itemCaption: string) of object; {Draft Component code by "Lazarus Android Module Wizard" [01/02/2018 11:13:51]} {https://github.com/jmpessoa/lazandroidmodulewizard} {jVisualControl template} { jDBListView - thanks to Martin Lowry !!! } jDBListView = class(jVisualControl) // Anachronism, it's actually an Extended ListView private FOnClickDBListItem: TOnClickDBListItem; FOnLongClickDBListItem: TOnClickDBListItem; //FOnDrawItemTextColor: TOnDrawItemTextColor; //FOnDrawItemBitmap: TOnDrawItemBitmap; //FItemsLayout: TListItemLayout; FjSqliteCursor: jSqliteCursor; FColWeights: TStrings; procedure SetColor(Value: TARGBColorBridge); //background procedure SetColumnWeights(Value: TStrings); procedure SetCursor(Value: jSqliteCursor); procedure SetFontColor(_color: TARGBColorBridge); procedure SetFontSize(_size: DWord); procedure SetFontSizeUnit(_unit: TFontSizeUnit); procedure SetVisible(Value: boolean); protected FjPRLayoutHome: jObject; //Save parent origin procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Init; override; procedure Refresh; procedure UpdateLayout; override; procedure GenEvent_OnClickDBListItem(Obj: TObject; position: integer); procedure GenEvent_OnLongClickDBListItem(Obj: TObject; position: integer); function jCreate(): jObject; procedure jFree(); function GetParent(): jObject; function GetView(): jObject; override; procedure SetViewParent(_viewgroup: jObject); override; procedure RemoveFromViewParent(); override; procedure SetLParamWidth(_w: integer); procedure SetLParamHeight(_h: integer); procedure setLGravity(_g: integer); procedure setLWeight(_w: single); procedure SetLeftTopRightBottomWidthHeight(_left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer); procedure AddLParamsAnchorRule(_rule: integer); procedure AddLParamsParentRule(_rule: integer); procedure SetLayoutAll(_idAnchor: integer); procedure ClearLayout(); procedure UpdateView; //procedure SetItemsLayout(_value: integer); function GetItemIndex(): integer; function GetItemCaption(): string; procedure SetSelection(_index: integer); //procedure DispatchOnDrawItemTextColor(_value: boolean); //procedure DispatchOnDrawItemBitmap(_value: boolean); procedure ChangeCursor(NewCursor: jSqliteCursor); published property BackgroundColor: TARGBColorBridge read FColor write SetColor; property ColumnWeights: TStrings read FColWeights write SetColumnWeights; property DataSource: jSqliteCursor read FjSqliteCursor write SetCursor; property FontColor: TARGBColorBridge read FFontColor write SetFontColor; property FontSize: DWord read FFontSize write SetFontSize; property FontSizeUnit: TFontSizeUnit read FFontSizeUnit write SetFontSizeUnit; property OnClickItem: TOnClickDBListItem read FOnClickDBListItem write FOnClickDBListItem; property OnLongClickItem: TOnClickDBListItem read FOnLongClickDBListItem write FOnLongClickDBListItem; end; function jDBListView_jCreate(env: PJNIEnv; _Self: int64; this: JObject): jObject; procedure jDBListView_jFree(env: PJNIEnv; _jdblistview: JObject); function jDBListView_GetView(env: PJNIEnv; _jdblistview: JObject): jObject; procedure jDBListView_SetViewParent(env: PJNIEnv; _jdblistview: JObject; _viewgroup: jObject); procedure jDBListView_RemoveFromViewParent(env: PJNIEnv; _jdblistview: JObject); function jDBListView_GetParent(env: PJNIEnv; _jdblistview: JObject): jObject; procedure jDBListView_SetLParamWidth(env: PJNIEnv; _jdblistview: JObject; _w: integer); procedure jDBListView_SetLParamHeight(env: PJNIEnv; _jdblistview: JObject; _h: integer); procedure jDBListView_setLGravity(env: PJNIEnv; _jdblistview: JObject; _g: integer); procedure jDBListView_setLWeight(env: PJNIEnv; _jdblistview: JObject; _w: single); procedure jDBListView_SetLeftTopRightBottomWidthHeight(env: PJNIEnv; _jdblistview: JObject; _left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer); procedure jDBListView_AddLParamsAnchorRule(env: PJNIEnv; _jdblistview: JObject; _rule: integer); procedure jDBListView_AddLParamsParentRule(env: PJNIEnv; _jdblistview: JObject; _rule: integer); procedure jDBListView_SetLayoutAll(env: PJNIEnv; _jdblistview: JObject; _idAnchor: integer); procedure jDBListView_ClearLayoutAll(env: PJNIEnv; _jdblistview: JObject); procedure jDBListView_SetId(env: PJNIEnv; _jdblistview: JObject; _id: integer); procedure jDBListView_UpdateView(env: PJNIEnv; _jdblistview: JObject); procedure jDBListView_SetItemsLayout(env: PJNIEnv; _jdblistview: JObject; _value: integer); function jDBListView_GetItemIndex(env: PJNIEnv; _jdblistview: JObject): integer; function jDBListView_GetItemCaption(env: PJNIEnv; _jdblistview: JObject): string; procedure jDBListView_SetSelection(env: PJNIEnv; _jdblistview: JObject; _index: integer); procedure jDBListView_DispatchOnDrawItemTextColor(env: PJNIEnv; _jdblistview: JObject; _value: boolean); procedure jDBListView_DispatchOnDrawItemBitmap(env: PJNIEnv; _jdblistview: JObject; _value: boolean); procedure jDBListView_SetFontSize(env: PJNIEnv; _jdblistview: JObject; _size: integer); procedure jDBListView_SetFontColor(env: PJNIEnv; _jdblistview: JObject; _color: integer); procedure jDBListView_SetFontSizeUnit(env: PJNIEnv; _jdblistview: JObject; _unit: integer); procedure jDBListView_ChangeCursor(env: PJNIEnv; _jdblistview: JObject; Cursor: jObject); procedure jDBListView_SetColumnWeights(env:PJNIEnv; _jdblistview: jObject; _value: TDynArrayOfSingle); procedure DBListView_Log (msg: string); implementation //----------------------------------------------------------------------------- // For debug //----------------------------------------------------------------------------- procedure DBListView_Log (msg: string); begin //__android_log_write(ANDROID_LOG_INFO, 'jDBListView', Pchar(msg)); end; {--------- jDBListView --------------} constructor jDBListView.Create(AOwner: TComponent); begin inherited Create(AOwner); if gapp <> nil then FId := gapp.GetNewId(); FMarginLeft := 10; FMarginTop := 10; FMarginBottom := 10; FMarginRight := 10; FLParamWidth := lpMatchParent; FLParamHeight := lpMatchParent; FHeight := 160; //?? FWidth := 96; //?? FAcceptChildrenAtDesignTime := False; //your code here.... FColWeights:= TStringList.Create; FjSqliteCursor := nil; end; destructor jDBListView.Destroy; begin if not (csDesigning in ComponentState) then begin if FjObject <> nil then begin jFree(); FjObject := nil; end; end; //you others free code here...' if FjSqliteCursor <> nil then FjSqliteCursor.UnRegisterObserver(self); FColWeights.Free; inherited Destroy; end; procedure jDBListView.Init; var rToP: TPositionRelativeToParent; rToA: TPositionRelativeToAnchorID; i: integer; weights: TDynArrayOfSingle; begin if not FInitialized then begin inherited Init; //set default ViewParent/FjPRLayout as jForm.View! //your code here: set/initialize create params.... FjObject := jCreate(); //jSelf ! if FFontColor <> colbrDefault then jDBListView_setFontColor(gApp.jni.jEnv, FjObject , GetARGB(FCustomColor, FFontColor)); if FFontSizeUnit <> unitDefault then jDBListView_SetFontSizeUnit(gApp.jni.jEnv, FjObject, Ord(FFontSizeUnit)); if FFontSize > 0 then jDBListView_setFontSize(gApp.jni.jEnv, FjObject , FFontSize); if FColWeights.Count > 0 then begin SetLength(weights, FColWeights.Count); for i := 0 to FColWeights.Count-1 do weights[i] := StrToFloat(FColWeights[i]); jDBListView_SetColumnWeights(gApp.jni.jEnv, FjObject, weights); end; if FParent <> nil then sysTryNewParent( FjPRLayout, FParent); FjPRLayoutHome:= FjPRLayout; jDBListView_SetViewParent(gApp.jni.jEnv, FjObject, FjPRLayout); jDBListView_SetId(gApp.jni.jEnv, FjObject, Self.Id); end; jDBListView_setLeftTopRightBottomWidthHeight(gApp.jni.jEnv, FjObject , FMarginLeft,FMarginTop,FMarginRight,FMarginBottom, sysGetLayoutParams( FWidth, FLParamWidth, Self.Parent, sdW, fmarginLeft + fmarginRight ), sysGetLayoutParams( FHeight, FLParamHeight, Self.Parent, sdH, fMargintop + fMarginbottom )); for rToA := raAbove to raAlignRight do begin if rToA in FPositionRelativeToAnchor then begin jDBListView_AddLParamsAnchorRule(gApp.jni.jEnv, FjObject, GetPositionRelativeToAnchor(rToA)); end; end; for rToP := rpBottom to rpCenterVertical do begin if rToP in FPositionRelativeToParent then begin jDBListView_AddLParamsParentRule(gApp.jni.jEnv, FjObject, GetPositionRelativeToParent(rToP)); end; end; if Self.Anchor <> nil then Self.AnchorId := Self.Anchor.Id else Self.AnchorId := -1; //dummy jDBListView_SetLayoutAll(gApp.jni.jEnv, FjObject, Self.AnchorId); if not FInitialized then begin FInitialized:= True; if FColor <> colbrDefault then View_SetBackGroundColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FColor)); View_SetVisible(gApp.jni.jEnv, FjObject, FVisible); end; end; procedure jDBListView.SetColor(Value: TARGBColorBridge); begin FColor := Value; if (FInitialized = True) and (FColor <> colbrDefault) then View_SetBackGroundColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FColor)); end; procedure jDBListView.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if Operation = opRemove then begin if AComponent = FjSqliteCursor then begin FjSqliteCursor:= nil; end end; end; procedure jDBListView.SetColumnWeights(Value: TStrings); var i: integer; weights: TDynArrayOfSingle; begin FColWeights.Assign(Value); if FInitialized and (Value.Count <> 0) then begin SetLength(weights, Value.Count); for i := 0 to Value.Count-1 do weights[i] := StrToFloat(Value[i]); jDBListView_SetColumnWeights(gApp.jni.jEnv, FjObject, weights); end; end; procedure jDBListView.SetCursor(Value: jSqliteCursor); begin //DBListView_Log ('Entering SetCursor ...'); if Value <> FjSqliteCursor then begin if Assigned(FjSqliteCursor) then begin //DBListView_Log ('... phase 1 ...'); FjSqliteCursor.UnRegisterObserver(Self); FjSqliteCursor.RemoveFreeNotification(Self); //remove free notification... end; //DBListView_Log ('... phase 2 ...'); FjSqliteCursor:= Value; if Value <> nil then //re- add free notification... begin //DBListView_Log ('... phase 3 ...'); Value.RegisterObserver(self); Value.FreeNotification(self); ChangeCursor(Value); end; end; //DBListView_Log ('Exiting SetCursor'); end; procedure jDBListView.SetVisible(Value: boolean); begin FVisible := Value; if FInitialized then View_SetVisible(gApp.jni.jEnv, FjObject, FVisible); end; procedure jDBListView.UpdateLayout; begin if not FInitialized then exit; ClearLayout(); inherited UpdateLayout; init; end; procedure jDBListView.Refresh; begin if FInitialized then View_Invalidate(gApp.jni.jEnv, FjObject); end; //Event : Java -> Pascal procedure jDBListView.GenEvent_OnClickDBListItem(Obj: TObject; position: integer); begin if Assigned(FOnClickDBListItem) then FOnClickDBListItem(Obj, position, ''); end; procedure jDBListView.GenEvent_OnLongClickDBListItem(Obj: TObject; position: integer); begin if Assigned(FOnLongClickDBListItem) then FOnLongClickDBListItem(Obj, position, ''); end; function jDBListView.jCreate(): jObject; begin //in designing component state: result value here... Result := jDBListView_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis); end; procedure jDBListView.jFree(); begin //in designing component state: set value here... if FInitialized then jDBListView_jFree(gApp.jni.jEnv, FjObject); end; function jDBListView.GetView(): jObject; begin //in designing component state: result value here... if FInitialized then Result := jDBListView_GetView(gApp.jni.jEnv, FjObject); end; procedure jDBListView.SetViewParent(_viewgroup: jObject); begin //in designing component state: set value here... if FInitialized then jDBListView_SetViewParent(gApp.jni.jEnv, FjObject, _viewgroup); end; procedure jDBListView.RemoveFromViewParent(); begin //in designing component state: set value here... if FInitialized then jDBListView_RemoveFromViewParent(gApp.jni.jEnv, FjObject); end; function jDBListView.GetParent(): jObject; begin //in designing component state: result value here... if FInitialized then Result := jDBListView_GetParent(gApp.jni.jEnv, FjObject); end; procedure jDBListView.SetLParamWidth(_w: integer); begin //in designing component state: set value here... if FInitialized then jDBListView_SetLParamWidth(gApp.jni.jEnv, FjObject, _w); end; procedure jDBListView.SetLParamHeight(_h: integer); begin //in designing component state: set value here... if FInitialized then jDBListView_SetLParamHeight(gApp.jni.jEnv, FjObject, _h); end; procedure jDBListView.setLGravity(_g: integer); begin //in designing component state: set value here... if FInitialized then jDBListView_setLGravity(gApp.jni.jEnv, FjObject, _g); end; procedure jDBListView.setLWeight(_w: single); begin //in designing component state: set value here... if FInitialized then jDBListView_setLWeight(gApp.jni.jEnv, FjObject, _w); end; procedure jDBListView.SetLeftTopRightBottomWidthHeight(_left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer); begin //in designing component state: set value here... if FInitialized then jDBListView_SetLeftTopRightBottomWidthHeight(gApp.jni.jEnv, FjObject, _left, _top, _right, _bottom, _w, _h); end; procedure jDBListView.AddLParamsAnchorRule(_rule: integer); begin //in designing component state: set value here... if FInitialized then jDBListView_AddLParamsAnchorRule(gApp.jni.jEnv, FjObject, _rule); end; procedure jDBListView.AddLParamsParentRule(_rule: integer); begin //in designing component state: set value here... if FInitialized then jDBListView_AddLParamsParentRule(gApp.jni.jEnv, FjObject, _rule); end; procedure jDBListView.SetLayoutAll(_idAnchor: integer); begin //in designing component state: set value here... if FInitialized then jDBListView_SetLayoutAll(gApp.jni.jEnv, FjObject, _idAnchor); end; procedure jDBListView.ClearLayout(); var rToP: TPositionRelativeToParent; rToA: TPositionRelativeToAnchorID; begin //in designing component state: set value here... if FInitialized then begin jDBListView_clearLayoutAll(gApp.jni.jEnv, FjObject); for rToP := rpBottom to rpCenterVertical do if rToP in FPositionRelativeToParent then jDBListView_addlParamsParentRule(gApp.jni.jEnv, FjObject , GetPositionRelativeToParent(rToP)); for rToA := raAbove to raAlignRight do if rToA in FPositionRelativeToAnchor then jDBListView_addlParamsAnchorRule(gApp.jni.jEnv, FjObject , GetPositionRelativeToAnchor(rToA)); end; end; procedure jDBListView.UpdateView(); begin //in designing component state: set value here... if FInitialized then jDBListView_UpdateView(gApp.jni.jEnv, FjObject); end; (* procedure jDBListView.SetItemsLayout(_value: integer); begin //in designing component state: set value here... if FInitialized then jDBListView_SetItemsLayout(gApp.jni.jEnv, FjObject, _value); end; *) function jDBListView.GetItemIndex(): integer; begin //in designing component state: result value here... if FInitialized then Result := jDBListView_GetItemIndex(gApp.jni.jEnv, FjObject); end; function jDBListView.GetItemCaption(): string; begin //in designing component state: result value here... if FInitialized then Result := jDBListView_GetItemCaption(gApp.jni.jEnv, FjObject); end; procedure jDBListView.SetSelection(_index: integer); begin //in designing component state: set value here... if FInitialized then jDBListView_SetSelection(gApp.jni.jEnv, FjObject, _index); end; (* procedure jDBListView.DispatchOnDrawItemTextColor(_value: boolean); begin //in designing component state: set value here... if FInitialized then jDBListView_DispatchOnDrawItemTextColor(gApp.jni.jEnv, FjObject, _value); end; procedure jDBListView.DispatchOnDrawItemBitmap(_value: boolean); begin //in designing component state: set value here... if FInitialized then jDBListView_DispatchOnDrawItemBitmap(gApp.jni.jEnv, FjObject, _value); end; *) procedure jDBListView.SetFontSize(_size: DWord); begin //in designing component state: set value here... FFontSize := _size; if FInitialized then jDBListView_SetFontSize(gApp.jni.jEnv, FjObject, _size); end; procedure jDBListView.SetFontColor(_color: TARGBColorBridge); begin //in designing component state: set value here... FFontColor := _color; if FInitialized then jDBListView_SetFontColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, _color)); end; procedure jDBListView.SetFontSizeUnit(_unit: TFontSizeUnit); begin //in designing component state: set value here... FFontSizeUnit := _unit; if FInitialized then jDBListView_SetFontSizeUnit(gApp.jni.jEnv, FjObject, Ord(_unit)); end; procedure jDBListView.ChangeCursor(NewCursor: jSqliteCursor); begin //in designing component state: set value here... if FInitialized then jDBListView_ChangeCursor(gApp.jni.jEnv, FjObject, NewCursor.Cursor); end; {-------- jDBListView_JNI_Bridge ----------} function jDBListView_jCreate(env: PJNIEnv; _Self: int64; this: JObject): jObject; var jParams: array[0..0] of jValue; jMethod: jMethodID = nil; jCls: jClass = nil; begin jParams[0].j := _Self; jCls := Get_gjClass(env); jMethod := env^.GetMethodID(env, jCls, 'jDBListView_jCreate', '(J)Ljava/lang/Object;'); Result := env^.CallObjectMethodA(env, this, jMethod, @jParams); Result := env^.NewGlobalRef(env, Result); end; (* //Please, you need insert: public java.lang.Object jDBListView_jCreate(long _Self) { return (java.lang.Object)(new class(this,_Self)); } //to end of "public class Controls" in "Controls.java" *) procedure jDBListView_jFree(env: PJNIEnv; _jdblistview: JObject); var jMethod: jMethodID = nil; jCls: jClass = nil; begin jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'jFree', '()V'); env^.CallVoidMethod(env, _jdblistview, jMethod); env^.DeleteLocalRef(env, jCls); end; function jDBListView_GetView(env: PJNIEnv; _jdblistview: JObject): jObject; var jMethod: jMethodID = nil; jCls: jClass = nil; begin jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'GetView', '()Landroid/view/View;'); Result := env^.CallObjectMethod(env, _jdblistview, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_SetViewParent(env: PJNIEnv; _jdblistview: JObject; _viewgroup: jObject); var jParams: array[0..0] of jValue; jMethod: jMethodID = nil; jCls: jClass = nil; begin jParams[0].l := _viewgroup; jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'SetViewParent', '(Landroid/view/ViewGroup;)V'); env^.CallVoidMethodA(env, _jdblistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_RemoveFromViewParent(env: PJNIEnv; _jdblistview: JObject); var jMethod: jMethodID = nil; jCls: jClass = nil; begin jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'RemoveFromViewParent', '()V'); env^.CallVoidMethod(env, _jdblistview, jMethod); env^.DeleteLocalRef(env, jCls); end; function jDBListView_GetParent(env: PJNIEnv; _jdblistview: JObject): jObject; var jMethod: jMethodID = nil; jCls: jClass = nil; begin jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'GetParent', '()Landroid/view/ViewGroup;'); Result := env^.CallObjectMethod(env, _jdblistview, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_SetLParamWidth(env: PJNIEnv; _jdblistview: JObject; _w: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID = nil; jCls: jClass = nil; begin jParams[0].i := _w; jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'SetLParamWidth', '(I)V'); env^.CallVoidMethodA(env, _jdblistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_SetLParamHeight(env: PJNIEnv; _jdblistview: JObject; _h: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID = nil; jCls: jClass = nil; begin jParams[0].i := _h; jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'SetLParamHeight', '(I)V'); env^.CallVoidMethodA(env, _jdblistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_setLGravity(env: PJNIEnv; _jdblistview: JObject; _g: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID = nil; jCls: jClass = nil; begin jParams[0].i := _g; jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'setLGravity', '(I)V'); env^.CallVoidMethodA(env, _jdblistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_setLWeight(env: PJNIEnv; _jdblistview: JObject; _w: single); var jParams: array[0..0] of jValue; jMethod: jMethodID = nil; jCls: jClass = nil; begin jParams[0].f := _w; jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'setLWeight', '(F)V'); env^.CallVoidMethodA(env, _jdblistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_SetLeftTopRightBottomWidthHeight(env: PJNIEnv; _jdblistview: JObject; _left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer); var jParams: array[0..5] of jValue; jMethod: jMethodID = nil; jCls: jClass = nil; begin jParams[0].i := _left; jParams[1].i := _top; jParams[2].i := _right; jParams[3].i := _bottom; jParams[4].i := _w; jParams[5].i := _h; jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'SetLeftTopRightBottomWidthHeight', '(IIIIII)V'); env^.CallVoidMethodA(env, _jdblistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_AddLParamsAnchorRule(env: PJNIEnv; _jdblistview: JObject; _rule: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID = nil; jCls: jClass = nil; begin jParams[0].i := _rule; jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'AddLParamsAnchorRule', '(I)V'); env^.CallVoidMethodA(env, _jdblistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_AddLParamsParentRule(env: PJNIEnv; _jdblistview: JObject; _rule: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID = nil; jCls: jClass = nil; begin jParams[0].i := _rule; jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'AddLParamsParentRule', '(I)V'); env^.CallVoidMethodA(env, _jdblistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_SetLayoutAll(env: PJNIEnv; _jdblistview: JObject; _idAnchor: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID = nil; jCls: jClass = nil; begin jParams[0].i := _idAnchor; jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'SetLayoutAll', '(I)V'); env^.CallVoidMethodA(env, _jdblistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_ClearLayoutAll(env: PJNIEnv; _jdblistview: JObject); var jMethod: jMethodID = nil; jCls: jClass = nil; begin jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'ClearLayoutAll', '()V'); env^.CallVoidMethod(env, _jdblistview, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_SetId(env: PJNIEnv; _jdblistview: JObject; _id: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID = nil; jCls: jClass = nil; begin jParams[0].i := _id; jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'setId', '(I)V'); env^.CallVoidMethodA(env, _jdblistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_UpdateView(env: PJNIEnv; _jdblistview: JObject); var jMethod: jMethodID = nil; jCls: jClass = nil; begin jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'UpdateView', '()V'); env^.CallVoidMethod(env, _jdblistview, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_SetNumColumns(env: PJNIEnv; _jdblistview: JObject; _value: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID = nil; jCls: jClass = nil; begin jParams[0].i := _value; jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'SetNumColumns', '(I)V'); env^.CallVoidMethodA(env, _jdblistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_SetColumnWidth(env: PJNIEnv; _jdblistview: JObject; _value: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID = nil; jCls: jClass = nil; begin jParams[0].i := _value; jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'SetColumnWidth', '(I)V'); env^.CallVoidMethodA(env, _jdblistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_SetItemsLayout(env: PJNIEnv; _jdblistview: JObject; _value: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID = nil; jCls: jClass = nil; begin jParams[0].i := _value; jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'SetItemsLayout', '(I)V'); env^.CallVoidMethodA(env, _jdblistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; function jDBListView_GetItemIndex(env: PJNIEnv; _jdblistview: JObject): integer; var jMethod: jMethodID = nil; jCls: jClass = nil; begin jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'GetItemIndex', '()I'); Result := env^.CallIntMethod(env, _jdblistview, jMethod); env^.DeleteLocalRef(env, jCls); end; function jDBListView_GetItemCaption(env: PJNIEnv; _jdblistview: JObject): string; begin Result:= jni_func_out_t(env, _jdblistview, 'GetItemCaption'); end; procedure jDBListView_SetSelection(env: PJNIEnv; _jdblistview: JObject; _index: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID = nil; jCls: jClass = nil; begin jParams[0].i := _index; jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'SetSelection', '(I)V'); env^.CallVoidMethodA(env, _jdblistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_DispatchOnDrawItemTextColor(env: PJNIEnv; _jdblistview: JObject; _value: boolean); var jParams: array[0..0] of jValue; jMethod: jMethodID = nil; jCls: jClass = nil; begin jParams[0].z := JBool(_value); jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'DispatchOnDrawItemTextColor', '(Z)V'); env^.CallVoidMethodA(env, _jdblistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_DispatchOnDrawItemBitmap(env: PJNIEnv; _jdblistview: JObject; _value: boolean); var jParams: array[0..0] of jValue; jMethod: jMethodID = nil; jCls: jClass = nil; begin jParams[0].z := JBool(_value); jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'DispatchOnDrawItemBitmap', '(Z)V'); env^.CallVoidMethodA(env, _jdblistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_SetFontSize(env: PJNIEnv; _jdblistview: JObject; _size: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID = nil; jCls: jClass = nil; begin jParams[0].i := _size; jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'SetFontSize', '(I)V'); env^.CallVoidMethodA(env, _jdblistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_SetFontSizeUnit(env: PJNIEnv; _jdblistview: JObject; _unit: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID = nil; jCls: jClass = nil; begin jParams[0].i := _unit; jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'SetFontSizeUnit', '(I)V'); env^.CallVoidMethodA(env, _jdblistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_SetFontColor(env: PJNIEnv; _jdblistview: JObject; _color: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID = nil; jCls: jClass = nil; begin jParams[0].i := _color; jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'SetFontColor', '(I)V'); env^.CallVoidMethodA(env, _jdblistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_ChangeCursor(env:PJNIEnv; _jdblistview: jObject; Cursor: jObject); var jParams: array[0..0] of jValue; jMethod: jMethodID = nil; jCls: jClass = nil; begin jParams[0].l:= Cursor; jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'SetCursor', '(Landroid/database/Cursor;)V'); env^.CallVoidMethodA(env, _jdblistview, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jDBListView_SetColumnWeights(env:PJNIEnv; _jdblistview: jObject; _value: TDynArrayOfSingle); var jParams: array[0..0] of jValue; jMethod: jMethodID = nil; jCls: jClass = nil; newSize0: integer; jNewArray0: jObject=nil; begin newSize0:= Length(_value); jNewArray0:= env^.NewFloatArray(env, newSize0); // allocate env^.SetFloatArrayRegion(env, jNewArray0, 0, newSize0, @_value[0] {source}); jParams[0].l:= jNewArray0; //DBListView_Log('Calling SetColumnWeights ... (last=' + FloatToStr(_value[newSize0-1]) + ')'); jCls := env^.GetObjectClass(env, _jdblistview); jMethod := env^.GetMethodID(env, jCls, 'SetColumnWeights', '([F)V'); env^.CallVoidMethodA(env, _jdblistview, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env, jCls); end; end.
{***************************************************************************} { } { DUnitX } { } { Copyright (C) 2012 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. } { } {***************************************************************************} unit DUnitX.Examples.EqualityAsserts; interface uses DUnitX.TestFramework; type [TestFixture] TDUnitXExamplesEqualityAsserts = class public [Test] procedure Assert_AreNotEqual; end; implementation { TDUnitXExamplesEqualityAsserts } procedure TDUnitXExamplesEqualityAsserts.Assert_AreNotEqual; var valueToTest : boolean; begin //String Assert.AreNotEqual('Not', 'Equal'); //TClass Assert.AreNotEqual(TObject, TInterfacedObject); //Extended with tolerance Assert.AreNotEqual(1.81E10, 1.9E10, 0.1E9); //Generic valueToTest := false; Assert.IsFalse(valueToTest = true); end; initialization TDUnitX.RegisterTestFixture(TDUnitXExamplesEqualityAsserts); end.
unit UOperatorPowerDialog; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, System.StrUtils; type TOperatorPowerDialog = class(TForm) Panel1: TPanel; buttonOK: TButton; buttonCancel: TButton; comboPower19: TComboBox; Label1: TLabel; comboPower35: TComboBox; Label2: TLabel; comboPower7: TComboBox; Label3: TLabel; comboPower14: TComboBox; Label4: TLabel; comboPower21: TComboBox; Label5: TLabel; comboPower28: TComboBox; Label6: TLabel; comboPower50: TComboBox; Label7: TLabel; comboPower144: TComboBox; Label8: TLabel; comboPower430: TComboBox; Label9: TLabel; comboPower1200: TComboBox; Label10: TLabel; comboPower2400: TComboBox; Label11: TLabel; comboPower5600: TComboBox; Label12: TLabel; comboPower10g: TComboBox; Label13: TLabel; GroupBox1: TGroupBox; procedure FormCreate(Sender: TObject); procedure comboPowerChange(Sender: TObject); private { Private 宣言 } FComboArray: array[1..13] of TComboBox; function GetPower(): string; procedure SetPower(v: string); public { Public 宣言 } property Power: string read GetPower write SetPower; end; resourcestring // 以降のバンドも同じ設定に変更しますか? DoYouWantTheUpperBandsToHaveTheSameSettins = 'Do you want the higher bands to have the same settings?'; implementation {$R *.dfm} procedure TOperatorPowerDialog.FormCreate(Sender: TObject); begin FComboArray[1] := comboPower19; FComboArray[2] := comboPower35; FComboArray[3] := comboPower7; FComboArray[4] := comboPower14; FComboArray[5] := comboPower21; FComboArray[6] := comboPower28; FComboArray[7] := comboPower50; FComboArray[8] := comboPower144; FComboArray[9] := comboPower430; FComboArray[10] := comboPower1200; FComboArray[11] := comboPower2400; FComboArray[12] := comboPower5600; FComboArray[13] := comboPower10g; end; procedure TOperatorPowerDialog.comboPowerChange(Sender: TObject); var Index: Integer; i: Integer; begin if MessageBox(Handle, PChar(DoYouWantTheUpperBandsToHaveTheSameSettins), PChar(Application.Title), MB_YESNO or MB_DEFBUTTON2 or MB_ICONEXCLAMATION) = IDNO then begin Exit; end; Index := TComboBox(Sender).Tag; for i := Index + 1 to High(FComboArray) do begin FComboArray[i].ItemIndex := TComboBox(Sender).ItemIndex; end; end; function TOperatorPowerDialog.GetPower(): string; var i: Integer; S: string; begin S := ''; for i := Low(FComboArray) to High(FComboArray) do begin S := S + FComboArray[i].Text; end; Result := S; end; procedure TOperatorPowerDialog.SetPower(v: string); var i: Integer; S: string; Index: Integer; begin S := v + DupeString('-', 13); for i := Low(FComboArray) to High(FComboArray) do begin Index := FComboArray[i].Items.IndexOf(S[i]); if Index = -1 then begin FComboArray[i].ItemIndex := 0; // - end else begin FComboArray[i].ItemIndex := Index; end; end; end; end.
unit DBDemosMainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, RemoteDB.Client.Dataset, Vcl.StdCtrls, RemoteDB.Client.Database, Vcl.DBCtrls, Vcl.Grids, Vcl.DBGrids; type TfmMain = class(TForm) RemoteDBDatabase1: TRemoteDBDatabase; edServer: TEdit; Label1: TLabel; btConnect: TButton; DataSource1: TDataSource; XDataset1: TXDataset; DBGrid1: TDBGrid; DBImage1: TDBImage; DBMemo1: TDBMemo; procedure btConnectClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var fmMain: TfmMain; implementation {$R *.dfm} procedure TfmMain.btConnectClick(Sender: TObject); begin RemoteDBDatabase1.ServerUri := edServer.Text; RemoteDBDatabase1.Connected := true; XDataset1.Open; end; end.
unit dbMetaDataTest; interface uses TestFramework, ZConnection, ZDataset; type TdbMetaDataTest = class (TTestCase) private ZConnection: TZConnection; ZQuery: TZQuery; protected // подготавливаем данные для тестирования procedure SetUp; override; // возвращаем данные для тестирования procedure TearDown; override; published // Очередность важна - по алфавиту не ставить!!! procedure CreateObjectDescFunction; procedure CreateContainerDescFunction; procedure CreateObjectHistoryDescFunction; procedure CreateMovementDescFunction; procedure CreateMovementItemDescFunction; procedure CreateMovementItemContainerFunction; procedure CreateObjectCostFunction; end; var MetadataPath: string = '..\DATABASE\Boutique\METADATA\'; implementation uses zLibUtil; { TdbMetaDataTest } procedure TdbMetaDataTest.CreateContainerDescFunction; begin ExecFile(MetadataPath + 'Container\CreateContainerDescFunction.sql', ZQuery); ExecFile(MetadataPath + 'Container\CreateContainerLinkObjectDescFunction.sql', ZQuery); end; procedure TdbMetaDataTest.CreateMovementDescFunction; begin ExecFile(MetadataPath + 'Movement\CreateMovementDescFunction.sql', ZQuery); ExecFile(MetadataPath + 'Movement\CreateMovementLinkObjectDescFunction.sql', ZQuery); ExecFile(MetadataPath + 'Movement\CreateMovementFloatDescFunction.sql', ZQuery); ExecFile(MetadataPath + 'Movement\CreateMovementDateDescFunction.sql', ZQuery); ExecFile(MetadataPath + 'Movement\CreateMovementBooleanDescFunction.sql', ZQuery); ExecFile(MetadataPath + 'Movement\CreateMovementLinkMovementDescFunction.sql', ZQuery); ExecFile(MetadataPath + 'Movement\CreateMovementStringDescFunction.sql', ZQuery); ExecFile(MetadataPath + 'Movement\CreateMovementBLOBDescFunction.sql', ZQuery); end; procedure TdbMetaDataTest.CreateMovementItemDescFunction; begin ExecFile(MetadataPath + 'MovementItem\CreateMovementItemDescFunction.sql', ZQuery); ExecFile(MetadataPath + 'MovementItem\CreateMovementItemLinkObjectDescFunction.sql', ZQuery); ExecFile(MetadataPath + 'MovementItem\CreateMovementItemFloatDescFunction.sql', ZQuery); ExecFile(MetadataPath + 'MovementItem\CreateMovementItemBooleanDescFunction.sql', ZQuery); ExecFile(MetadataPath + 'MovementItem\CreateMovementItemStringDescFunction.sql', ZQuery); ExecFile(MetadataPath + 'MovementItem\CreateMovementItemDateDescFunction.sql', ZQuery); end; procedure TdbMetaDataTest.CreateMovementItemContainerFunction; begin ExecFile(MetadataPath + 'MovementItemContainer\CreateMovementItemContainerDescFunction.sql', ZQuery); end; procedure TdbMetaDataTest.CreateObjectCostFunction; begin // ExecFile(MetadataPath + 'ObjectCost\CreateObjectCostDescFunction.sql', ZQuery); // ExecFile(MetadataPath + 'ObjectCost\CreateObjectCostLinkDescFunction.sql', ZQuery); end; procedure TdbMetaDataTest.CreateObjectDescFunction; begin ExecFile(MetadataPath + 'Object\CreateObjectDescFunction.sql', ZQuery); ExecFile(MetadataPath + 'Object\CreateObjectStringDescFunction.sql', ZQuery); ExecFile(MetadataPath + 'Object\CreateObjectLinkDescFunction.sql', ZQuery); ExecFile(MetadataPath + 'Object\CreateObjectBLOBDescFunction.sql', ZQuery); ExecFile(MetadataPath + 'Object\CreateObjectFloatDescFunction.sql', ZQuery); ExecFile(MetadataPath + 'Object\CreateObjectBooleanDescFunction.sql', ZQuery); ExecFile(MetadataPath + 'Object\CreateObjectDateDescFunction.sql', ZQuery); end; procedure TdbMetaDataTest.CreateObjectHistoryDescFunction; begin ExecFile(MetadataPath + 'ObjectHistory\CreateObjectHistoryDescFunction.sql', ZQuery); ExecFile(MetadataPath + 'ObjectHistory\CreateObjectHistoryFloatDescFunction.sql', ZQuery); ExecFile(MetadataPath + 'ObjectHistory\CreateObjectHistoryStringDescFunction.sql', ZQuery); ExecFile(MetadataPath + 'ObjectHistory\CreateObjectHistoryLinkDescFunction.sql', ZQuery); end; procedure TdbMetaDataTest.SetUp; begin inherited; ZConnection := TConnectionFactory.GetConnection; ZQuery := TZQuery.Create(nil); ZQuery.Connection := ZConnection; end; procedure TdbMetaDataTest.TearDown; begin inherited; ZConnection.Free; ZQuery.Free; end; initialization // TestFramework.RegisterTest('Метаданные', TdbMetaDataTest.Suite); end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, TCaptureXLib_TLB, TSelectionLib_TLB, UIElementLib_TLB; type TForm1 = class(TForm) btnCapture: TButton; txtResult: TMemo; btnSelReg: TButton; btnSelWnd: TButton; Label1: TLabel; txtHandle: TEdit; Label2: TLabel; Label3: TLabel; txtX: TEdit; txtY: TEdit; Label4: TLabel; Label5: TLabel; txtW: TEdit; Label6: TLabel; txtH: TEdit; Label7: TLabel; radioNative: TRadioButton; radioFull: TRadioButton; radioOCR: TRadioButton; comboEngine: TComboBox; comboLang: TComboBox; checkLayout: TCheckBox; Label8: TLabel; checkID: TCheckBox; Button3: TButton; Button4: TButton; Button5: TButton; txtID: TMemo; procedure btnCaptureClick(Sender: TObject); procedure btnSelRegClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnSelWndClick(Sender: TObject); procedure Button3Click(Sender: TObject); procedure checkLayoutClick(Sender: TObject); procedure ManageError(exception : Exception); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); private { Private declarations } m_tCapture: TextCaptureX; m_tSelection: ITSelection; m_tAAText : GetAAText; m_tOCR : GetOCRText; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.ManageError(exception: Exception); var strWideCharErr : PWideChar; strWideCharTitle : PWideCHar; strTCXTitle : string; begin strTCXTitle := 'Text Capture X Delphi Sample'; GetMem(strWideCharErr, sizeof(WideChar) * (length(exception.Message) + 1)); GetMem(strWideCharTitle, sizeof(WideChar) * (length(strTCXTitle) + 1)); StringToWideChar(exception.Message, strWideCharErr, length(exception.message) + 1); StringToWideChar(strTCXTitle, strWideCharTitle, length(strTCXTitle) + 1); MessageBox(0, strWideCharErr, strWideCharTitle, 0); FreeMem(strWideCharErr); FreeMem(strWideCharTitle); end; procedure TForm1.btnCaptureClick(Sender: TObject); var strResult : string; hwnd, x, y, width, height : Integer; strLang : string; uiElem : IUIElem; left, top, w, h : integer; begin if (checkID.Checked = true) then begin uiElem := CoUIElem.Create; uiElem.InitializeFromID(txtID.Text, false); hwnd := uiElem.hwnd; end else hwnd := StrToInt(txtHandle.Text); x := StrToInt(txtX.Text); y := StrToInt(txtY.Text); width := StrToInt(txtW.Text); height := StrToInt(txtH.Text); try if radioNative.checked = true then strResult := m_tCapture.GetTextFromRect(hwnd, x, y, width, height) else if radioFull.Checked = true then strResult := m_tAAText.GetFullTextFromRectangle(hwnd, x, y, width, height) else if radioOCR.Checked = true then begin strLang := comboLang.Text; {translate the rectangle to client coordinates} uiElem := CoUIelem.Create; uiElem.hwnd := hwnd; uiElem.GetRectangle(left, top, w, h); x := x - left; y := y - top; strResult := m_tOCR.GetTextFromRect(hwnd, x, y, width, height, strLang, false); end; except On E: Exception do begin ManageError(E); exit; end; end; txtresult.Text := strResult; end; procedure TForm1.btnSelRegClick(Sender: TObject); var tSelInfo: IDispatch; tSelInfo2 : TSelectionInfo; uiElem: IUIElem; points : OleVariant; point1, point2, x1, y1, x2, y2: Integer; finalX, finalY, height, width: Integer; begin try tSelInfo := m_tSelection.Start(tsSelectionRectangle, tsSelFlagDefaultText); except On E: exception do begin ManageError(E); exit; end; end; tSelInfo.QueryInterface(IID_ITSelectionInfo, tSelInfo2) ; txtHandle.Text := IntToStr(tSelInfo2.WindowHandle); try uiElem := CoUIElem.Create; uiElem.hwnd := tSelInfo2.WindowHandle; txtID.Text := uiElem.GetID(TRUE); except on E: exception do begin ManageError(E); exit; end; end; points := tSelInfo2.Points; point1 := VarArrayGet(points, [0]); point2 := VarArrayGet(points, [1]); x1 := LoWord(point1); y1 := HiWord(point1); x2 := LoWord(point2); y2 := HiWord(point2); if (x1 > x2) then begin finalX := x2; width := x1 - x2; end else begin finalX := x1; width := x2 - x1; end; if (y1 > y2) then begin finalY := y2; height := y1 - y2; end else begin finalY := y1; height := y2 - y1; end; txtX.Text := IntToStr(finalX); txtY.Text := IntToStr(finalY); txtW.Text := IntToStr(width); txtH.Text := IntToStr(height); end; procedure TForm1.btnSelWndClick(Sender: TObject); var tSelInfo: IDispatch; tSelInfo2 : ITSelectionInfo; uiElem : IUIElem; begin Form1.Visible := false; try tSelInfo := m_tSelection.Start(tsSelectionUIelement, tsSelFlagDefaultText); tSelInfo.QueryInterface(IID_ITSelectionInfo, tSelInfo2); except on E: exception do begin ManageError(E); exit; end; end; Sleep(200); Form1.Visible := true; txtID.Text := tSelInfo2.UIElementID; txtHandle.Text := IntToStr(tSelInfo2.WindowHandle); if (tSelInfo2.UIElementID = '') then begin txtID.Text := 'A valid ID could not be generated'; end else begin try uiElem := CoUIElem.Create; uiElem.InitializeFromID(tSelInfo2.UIElementID, false); except on E: exception do begin ManageError(E); exit; end; end; end; txtX.Text := '0'; txtY.Text := '0'; txtW.Text := '0'; txtH.Text := '0'; end; procedure TForm1.Button3Click(Sender: TObject); var uiElem : IUIElem; strText, strLang : string; hwnd : Integer; begin uiElem := CoUIElem.Create; try uiElem := CoUIElem.Create; if (checkID.Checked = true) then begin uiElem.InitializeFromID(txtID.Text, false); end else begin hwnd := StrToInt(txtHandle.Text); uiElem.hwnd := hwnd; end; except on E: exception do begin ManageError(E); exit; end; end; try if radioNative.checked = true then strText := m_tCapture.GetTextFromUIElem(uiElem) else if radioFull.Checked = true then strText := m_tAAText.GetFullTextFromUIElem(uiElem) else if radioOCR.Checked = true then begin strLang := comboLang.Text; strText := m_tOCR.GetTextFromUIElem(uiElem, strLang, false); end; except on E: exception do begin strText := 'Capture Error!'; ManageError(E); exit; end; end; txtResult.Text := strtext; end; procedure TForm1.Button4Click(Sender: TObject); var hwnd : Integer; begin try Form1.Visible := false; Sleep (100); hwnd := m_tCapture.GetActiveWindowHwnd; txtResult.Text := m_tCapture.CaptureWindow(hwnd); Sleep (100); Form1.Visible := true; except on E: Exception do begin ManageError(E); exit; end; end; end; procedure TForm1.Button5Click(Sender: TObject); var x, y, hwnd : Integer; strResult : string; begin hwnd := StrToInt(txtHandle.Text); x := StrToInt(txtX.Text); y := StrToInt(txtY.Text); try strResult := m_tCapture.GetTextFromPoint(hwnd, x, y); txtResult.Text := strResult; except on E: Exception do begin ManageError(E); exit; end; end; end; procedure TForm1.checkLayoutClick(Sender: TObject); begin m_tCapture.FormattedText := checkLayout.Checked; end; procedure TForm1.FormCreate(Sender: TObject); begin try m_tSelection := CoTSelection.Create; m_tCapture := CoTextCaptureX.Create; m_tAAText := CoGetAAText.Create; m_tOCR := CoGetOCRText.Create; except on E: exception do begin ManageError(E); exit; end; end; comboEngine.Items.Add('Internal'); comboLang.Items.Add('eng'); comboLang.Items.Add('deu'); comboLang.Items.Add('spa'); comboLang.Items.Add('nld'); comboLang.SelText := ''; comboEngine.SelText := ''; radioNative.Checked := true; end; end.
unit uHoldingsData; {$mode objfpc}{$H+} interface uses Classes, SysUtils, uLibrary, uMap, uHoldings; type { THoldingsSaver } ITypeData = interface ['{F461FC21-75A7-4703-B387-01333D55F36C}'] function GetValue: DWord; function GetValueStr: String; property Value: DWord read GetValue; property ValueStr: String read GetValueStr; end; { TTypeData } TTypeData = class(TInterfacedObject, ITypeData) protected fVarDefine: IVarDefine; fMap: IMap; protected function GetValue: DWord; virtual; function GetValueStr: String; virtual; abstract; public constructor Create(const aVarDefine: IVarDefine; const aMap: IMap); reintroduce; end; { TIntegerData } TIntegerData = class(TTypeData) protected function GetValueStr: String; override; end; { TSingleData } TSingleData = class(TTypeData) protected function GetValueStr: String; override; end; { TDataFactory } TDataFactory = class public class function GetTypeData(const aVarDefine: IVarDefine; const aMap: IMap): ITypeData; end; { THoldingBuilder } THoldingBuilder = class public class procedure BuildHolding(const aHolding: IHolding; const aVarDefine: IVarDefine; const aMap: IMap); end; implementation resourcestring SIntegerFormat = '%d'; SBitmapFormat = '0x%.*x'; SSingleFormat = '%.*f'; { THoldingBuilder } class procedure THoldingBuilder.BuildHolding(const aHolding: IHolding; const aVarDefine: IVarDefine; const aMap: IMap); var TypeData: ITypeData; begin TypeData := TDataFactory.GetTypeData(aVarDefine, aMap); aHolding.Name := aVarDefine.Name; aHolding.Index := aVarDefine.Index; aHolding.VarType := aVarDefine.VarType; aHolding.ShortDescription := aVarDefine.ShortDescription; aHolding.Multipler := aVarDefine.Multipler; aHolding.Value := TypeData.Value; aHolding.ValueStr := TypeData.ValueStr; end; { TDataFactory } class function TDataFactory.GetTypeData(const aVarDefine: IVarDefine; const aMap: IMap): ITypeData; var IsSingle: Boolean; begin IsSingle := (aVarDefine.VarType = TVarType.vtFLOAT) or (aVarDefine.Multipler > 1); if IsSingle then Result := TSingleData.Create(aVarDefine, aMap) else Result := TIntegerData.Create(aVarDefine, aMap); end; { TTypeData } constructor TTypeData.Create(const aVarDefine: IVarDefine; const aMap: IMap); begin inherited Create; fVarDefine := aVarDefine; fMap := aMap; end; function TTypeData.GetValue: DWord; begin if fVarDefine.VarType in DWordTypes then Result := fMap.ReadUint32(TTypeTable.ttHolding, fVarDefine.Index) else Result := fMap.ReadUint16(TTypeTable.ttHolding, fVarDefine.Index); end; { TIntegerData } function TIntegerData.GetValueStr: String; begin Result := '0'; case fVarDefine.VarType of vtUINT8L: Result := Format(SIntegerFormat, [fMap.ReadUint8l(TTypeTable.ttHolding, fVarDefine.Index)]); vtUINT8H: Result := Format(SIntegerFormat, [fMap.ReadUint8h(TTypeTable.ttHolding, fVarDefine.Index)]); vtUINT16: Result := Format(SIntegerFormat, [fMap.ReadUint16(TTypeTable.ttHolding, fVarDefine.Index)]); vtSINT16: Result := Format(SIntegerFormat, [fMap.ReadSint16(TTypeTable.ttHolding, fVarDefine.Index)]); vtUINT32: Result := Format(SIntegerFormat, [fMap.ReadUint32(TTypeTable.ttHolding, fVarDefine.Index)]); vtSINT32: Result := Format(SIntegerFormat, [fMap.ReadSint32(TTypeTable.ttHolding, fVarDefine.Index)]); vtBITMAP16: Result := Format( SBitmapFormat, [4, fMap.ReadBitmap16(TTypeTable.ttHolding, fVarDefine.Index)]); vtBITMAP32: Result := Format( SBitmapFormat, [8, fMap.ReadBitmap32(TTypeTable.ttHolding, fVarDefine.Index)]); vtBOOL_EXT: Result := Format(SIntegerFormat, [fMap.ReadUint32(TTypeTable.ttHolding, fVarDefine.Index)]); vtBOOL: Result := BoolToStr(fMap.ReadBool(TTypeTable.ttHolding, fVarDefine.Index)); end; end; { TSingleData } function TSingleData.GetValueStr: String; var Precision: Byte; begin Result := '0.0'; Precision := NumberDecimals(fVarDefine.Multipler); case fVarDefine.VarType of vtUINT8l: Result := Format(SSingleFormat, [Precision, fMap.ReadUint8l(TTypeTable.ttHolding, fVarDefine.Index, fVarDefine.Multipler)]); vtUINT8H: Result := Format(SSingleFormat, [Precision, fMap.ReadUint8h(TTypeTable.ttHolding, fVarDefine.Index, fVarDefine.Multipler)]); vtUINT16: Result := Format(SSingleFormat, [Precision, fMap.ReadUint16(TTypeTable.ttHolding, fVarDefine.Index, fVarDefine.Multipler)]); vtSINT16: Result := Format(SSingleFormat, [Precision, fMap.ReadSint16(TTypeTable.ttHolding, fVarDefine.Index, fVarDefine.Multipler)]); vtUINT32: Result := Format(SSingleFormat, [Precision, fMap.ReadUint32(TTypeTable.ttHolding, fVarDefine.Index, fVarDefine.Multipler)]); vtSINT32: Result := Format(SSingleFormat, [Precision, fMap.ReadSint32(TTypeTable.ttHolding, fVarDefine.Index, fVarDefine.Multipler)]); vtFLOAT: Result := Format(SSingleFormat, [5, fMap.ReadFloat(TTypeTable.ttHolding, fVarDefine.Index)]); end; end; end.
unit u_EnumDoublePointByLineSet; interface uses t_GeoTypes, i_EnumDoublePoint, i_VectorItemLonLat, i_VectorItemProjected, i_VectorItemLocal; type TEnumDoublePointByLineSetBase = class(TInterfacedObject, IEnumDoublePoint) private FSourceLineSet: IInterface; FClosed: Boolean; FCurrentEnum: IEnumDoublePoint; FCount: Integer; FIndex: Integer; FNeedEmptyPoint: Boolean; FFinished: Boolean; FPreparedPointExists: Boolean; FPreparedPoint: TDoublePoint; function GetNextEnum: IEnumDoublePoint; virtual; abstract; private function Next(out APoint: TDoublePoint): Boolean; private constructor CreateInternal( const ALineSet: IInterface; ALineCount: Integer; AClosed: Boolean ); end; TEnumLonLatPointByPath = class(TEnumDoublePointByLineSetBase, IEnumLonLatPoint) private function GetNextEnum: IEnumDoublePoint; override; public constructor Create(const ALineSet: ILonLatPath); end; TEnumLonLatPointByPolygon = class(TEnumDoublePointByLineSetBase, IEnumLonLatPoint) private function GetNextEnum: IEnumDoublePoint; override; public constructor Create(const ALineSet: ILonLatPolygon); end; TEnumProjectedPointByPath = class(TEnumDoublePointByLineSetBase, IEnumProjectedPoint) private function GetNextEnum: IEnumDoublePoint; override; public constructor Create(const ALineSet: IProjectedPath); end; TEnumProjectedPointByPolygon = class(TEnumDoublePointByLineSetBase, IEnumProjectedPoint) private function GetNextEnum: IEnumDoublePoint; override; public constructor Create(const ALineSet: IProjectedPolygon); end; TEnumLocalPointByPath = class(TEnumDoublePointByLineSetBase, IEnumLocalPoint) private function GetNextEnum: IEnumDoublePoint; override; public constructor Create(const ALineSet: ILocalPath); end; TEnumLocalPointByPolygon = class(TEnumDoublePointByLineSetBase, IEnumLocalPoint) private function GetNextEnum: IEnumDoublePoint; override; public constructor Create(const ALineSet: ILocalPolygon); end; implementation uses u_GeoFun; { TEnumDoublePointByLineSetBase } constructor TEnumDoublePointByLineSetBase.CreateInternal( const ALineSet: IInterface; ALineCount: Integer; AClosed: Boolean ); begin inherited Create; FSourceLineSet := ALineSet; FClosed := AClosed; FCurrentEnum := nil; FCount := ALineCount; FIndex := -1; FNeedEmptyPoint := False; FFinished := False; FPreparedPointExists := False; end; function TEnumDoublePointByLineSetBase.Next(out APoint: TDoublePoint): Boolean; begin while not FFinished do begin if FCurrentEnum <> nil then begin if FPreparedPointExists then begin APoint := FPreparedPoint; FPreparedPointExists := False; FNeedEmptyPoint := True; Break; end; if FCurrentEnum.Next(APoint) then begin FNeedEmptyPoint := True; Break; end else begin FCurrentEnum := nil; end; end else begin Inc(FIndex); if FIndex < FCount then begin FCurrentEnum := GetNextEnum; if FCurrentEnum <> nil then begin if FNeedEmptyPoint then begin if FCurrentEnum.Next(FPreparedPoint) then begin FPreparedPointExists := True; FNeedEmptyPoint := False; APoint := CEmptyDoublePoint; Break; end; end; end; end else begin FFinished := True; FSourceLineSet := nil; end; end; end; Result := not FFinished; end; { TEnumLonLatPointByPath } constructor TEnumLonLatPointByPath.Create(const ALineSet: ILonLatPath); begin inherited CreateInternal(ALineSet, ALineSet.Count, False); end; function TEnumLonLatPointByPath.GetNextEnum: IEnumDoublePoint; begin Result := ILonLatPath(FSourceLineSet).Item[FIndex].GetEnum; end; { TEnumLonLatPointByPolygon } constructor TEnumLonLatPointByPolygon.Create(const ALineSet: ILonLatPolygon); begin inherited CreateInternal(ALineSet, ALineSet.Count, True); end; function TEnumLonLatPointByPolygon.GetNextEnum: IEnumDoublePoint; begin Result := ILonLatPolygon(FSourceLineSet).Item[FIndex].GetEnum; end; { TEnumProjectedPointByPath } constructor TEnumProjectedPointByPath.Create(const ALineSet: IProjectedPath); begin inherited CreateInternal(ALineSet, ALineSet.Count, False); end; function TEnumProjectedPointByPath.GetNextEnum: IEnumDoublePoint; begin Result := IProjectedPath(FSourceLineSet).Item[FIndex].GetEnum; end; { TEnumProjectedPointByPolygon } constructor TEnumProjectedPointByPolygon.Create(const ALineSet: IProjectedPolygon); begin inherited CreateInternal(ALineSet, ALineSet.Count, True); end; function TEnumProjectedPointByPolygon.GetNextEnum: IEnumDoublePoint; begin Result := IProjectedPolygon(FSourceLineSet).Item[FIndex].GetEnum; end; { TEnumLocalPointByPath } constructor TEnumLocalPointByPath.Create(const ALineSet: ILocalPath); begin inherited CreateInternal(ALineSet, ALineSet.Count, False); end; function TEnumLocalPointByPath.GetNextEnum: IEnumDoublePoint; begin Result := ILocalPath(FSourceLineSet).Item[FIndex].GetEnum; end; { TEnumLocalPointByPolygon } constructor TEnumLocalPointByPolygon.Create(const ALineSet: ILocalPolygon); begin inherited CreateInternal(ALineSet, ALineSet.Count, True); end; function TEnumLocalPointByPolygon.GetNextEnum: IEnumDoublePoint; begin Result := ILocalPolygon(FSourceLineSet).Item[FIndex].GetEnum; end; end.
program BookDatabase; {$APPTYPE CONSOLE} //main variables var db,choice:string; //print instructions procedure Instructions; begin WriteLn('To add book press A'); WriteLn('To write the database on screen press W'); WriteLn('To end press E'); end; //count lines in file and return integer value function CountLines(path : string): integer; var i:integer; myfile:textfile; begin i:=0; AssignFile(myfile, path); Reset(myfile); while not EoF(myfile) do begin i:= i+1; ReadLn(myfile); end; CloseFile(myfile); Result:=i; //Return lines end; //Add book to database procedure AddBook(author, title : string); var myfile: textfile; begin AssignFile(myfile, db); Append(myfile); WriteLn(myfile, author + ' - ' + title); //Author and title are stored in one line CloseFile(myfile); WriteLn('Book added to database.'); WriteLn('___________'); end; procedure Book; var author,title:string; begin WriteLn('___________'); WriteLn('Your choice: ' + UpCase(choice)); if CountLines(db) < 100 then //Check if database has 100 or more entries begin WriteLn('Adding to database:'); Write('Author: '); Readln(author); Write('Book title: '); Readln(title); AddBook(author, title); end else begin Writeln('Database full!'); Writeln('___________'); end; end; //Print all books in database procedure Show; var myfile: TextFile; line: string; begin AssignFile(myfile, db); Reset(myfile); while not EoF(myfile) do begin ReadLn(myfile, line); Writeln(line); end; CloseFile(myfile); end; //Main code begin db:='db.txt'; while true do begin Instructions; Readln(choice); Case choice of 'a','A':Book; 'w','W':Show; 'e','E':halt; else WriteLn('Invalid command.'); end; end; end.
unit uProduct; interface uses System.Classes; type TProductBase = class(TComponent) type TFilterProduct = class private FCodigo: integer; FDescricao: string; procedure SetCodigo(const Value: integer); procedure SetDescricao(const Value: string); published property Descricao : string read FDescricao write SetDescricao; property Codigo : integer read FCodigo write SetCodigo; public procedure Clear; end; private FFilter: TFilterProduct; procedure SetFilter(const Value: TFilterProduct); published property Filter : TFilterProduct read FFilter write SetFilter; end; TProduct = class(TProductBase) private Fcodigo: Integer; Fdescricao: String; Fpreco: Currency; public function SetCodigo(aCodigo: Integer): TProduct; function SetDescricao(aDescricao: String): TProduct; function SetPreco(aPreco: Currency): TProduct; function GetCodigo: Integer; function GetDescricao: String; function GetPreco: Currency; function Get: TList; end; implementation uses FireDAC.Comp.Client, FireDAC.Dapt, uDM, System.SysUtils; { TProduct } function TProduct.Get: TList; var lQuery: TFDQuery; lBegin: boolean; lList : TList; lProduct : TProduct; begin lBegin := True; lQuery := TFDQuery.Create(self); lQuery.Connection := DM.FDConnection; lQuery.Close; lQuery.SQL.add('SELECT codigo, descricao, preco FROM produtos'); //Identifica se é para trazer todos os registros if (Filter.Codigo <> 0) or (Filter.Descricao <> '') then begin lQuery.SQL.add('WHERE'); if Filter.Codigo <> 0 then begin lQuery.SQL.add('codigo = '+IntToStr(Filter.Codigo)); lBegin := False; end; if Filter.Descricao <> '' then begin {Junto com as condicionais não encadeadas, possibilitam utilizar vários filtros ao mesmo tempo, caso necessario} if NOT lBegin then lQuery.SQL.add('OR'); lQuery.SQL.add('UPPER(descricao) like '+QuotedStr('%'+UpperCase(Filter.Descricao)+'%')); end; end; lQuery.Open(); if lQuery.RecordCount > 0 then begin lList := TList.Create; while not lQuery.Eof do begin lProduct := TProduct.Create(self); lProduct.Fcodigo := lQuery.FieldByName('codigo').AsInteger; lProduct.Fdescricao := lQuery.FieldByName('descricao').AsString; lProduct.Fpreco := lQuery.FieldByName('preco').AsCurrency; lList.Add(lProduct); lQuery.Next; end; Result := lList; end else begin Result := nil; end; end; function TProduct.GetCodigo: Integer; begin result := Fcodigo; end; function TProduct.GetDescricao: String; begin result := Fdescricao; end; function TProduct.GetPreco: Currency; begin result := Fpreco; end; function TProduct.SetCodigo(aCodigo: Integer): TProduct; begin Result := Self; Fcodigo := aCodigo; end; function TProduct.SetDescricao(aDescricao: String): TProduct; begin Result := Self; Fdescricao := aDescricao; end; function TProduct.SetPreco(aPreco: Currency): TProduct; begin Result := Self; Fpreco := aPreco; end; { TProductBase } procedure TProductBase.SetFilter(const Value: TFilterProduct); begin FFilter := Value; end; { TProductBase.TFilterProduct } procedure TProductBase.TFilterProduct.Clear; begin FCodigo := 0; FDescricao := ''; end; procedure TProductBase.TFilterProduct.SetCodigo(const Value: integer); begin FCodigo := Value; end; procedure TProductBase.TFilterProduct.SetDescricao(const Value: string); begin FDescricao := Value; end; end.
unit TarFTP.MVC; interface uses Classes; type IController = interface; IModel = interface; IView = interface ['{A74830EF-5BA4-4F8A-B3F4-F3A49A4FD45D}'] procedure SetController(const Controller : IController); procedure SetModel(const Model : IModel); procedure Display; procedure Close; procedure ProcessErrors; end; IMainView = interface(IView) ['{29AE12AB-4B0B-4CA5-B986-F77EE1B5D40A}'] end; IFileCompressionView = interface(IView) ['{EA63896E-3089-48BB-987F-5DF0810A3DE4}'] end; IFileUploadView = interface(IView) ['{9A1C09EB-E341-48B1-B623-BC0C15F3C3A4}'] end; IController = interface ['{58B1B9F7-0A80-495C-889D-005722F618BF}'] procedure RegisterView(const Kind : TGUID; const View : IView); procedure CompressAndUpload; end; TWorkProgressEvent = procedure(CurrentItem, TotalItems : Integer; BytesProcessed, TotalBytes : Int64) of object; TTaskKind = ( tkUndefined, tkCompress, tkUpload ); TTaskState = ( tsBeforeStarted, tsAfterFinished ); TModelNotifyEvent = procedure(Task : TTaskKind; State : TTaskState) of object; IModel = interface ['{99B8DD6A-CF98-4760-9F7C-07A6D863F885}'] function GetOnFileCompress : TWorkProgressEvent; procedure SetOnFileCompress(Value : TWorkProgressEvent); property OnFileCompress : TWorkProgressEvent read GetOnFileCompress write SetOnFileCompress; function GetOnFileUpload : TWorkProgressEvent; procedure SetOnFileUpload(Value : TWorkProgressEvent); property OnFileUpload : TWorkProgressEvent read GetOnFileUpload write SetOnFileUpload; function GetOnTaskEvent : TModelNotifyEvent; procedure SetOnTaskEvent(Value : TModelNotifyEvent); property OnTaskEvent : TModelNotifyEvent read GetOnTaskEvent write SetOnTaskEvent; function GetTerminated : Boolean; property Terminated : Boolean read GetTerminated; function GetError : Boolean; property Error: Boolean read GetError; procedure Reset; procedure AddFile(const FileName : String); procedure SetOutputFile(const OutputFile : String); procedure SetFtpCredentials(const Host, Login, Password : String); procedure NeedError; procedure Compress; procedure Upload; procedure TerminateTask; procedure ForcedTerminateTask; end; implementation end.
// ============================================================================= // Module name : $RCSfile: CommBase.pas,v $ // description : This unit implements a basis methodes and properties of a class // for connection FlashRunner. The types of connection includes Jtag // RS232, USB, GPIB, CAN-bus and Profil-Bus. // Compiler : Delphi 2007 // Author : 2015-09-08 /bsu/ // History : //============================================================================== unit CommBase; interface uses Classes, TextMessage, IniFiles, Serial3, SyncObjs, SysUtils, DataBuffer; const C_BUFFER_SIZE_WRITE = 512; C_BUFFER_SIZE_READ = 2048; type //enumeration for all connection type EConnectType = (CT_UNKNOWN, //unknown connection CT_RS232, //rs232 CT_MTXUSB, //metronix usb (usbiocom) CT_TEKUSB, //usb interface to oscilloscope (Tektronix) CT_GPIB, //GPIB (IEEE 488) CT_ETHERNET,//ethernet CT_JTAG, //jtag CT_PCAN, //can-bus over pcan-adapter CT_PROFI //profi-bus ); ECommProtocol = ( CP_ORIGINAL,//'ABCDEFGH...' CP_HEXESTR, //'8F239542' CP_RIPSIP, //'RIP:041' CP_OROW, //'OR:00A1' CP_DXOROW, //'#OR:00A1:0001:01:XX' CP_CAN, //'587:00123456' CP_CANOPEN //'587:00123456' ); //enumeration of connection states EConnectState = ( CS_UNKNOWN, //unknown state CS_CONFIGURED,//connection is configurated CS_CONNECTED //connection is connected and in use ); // ICommHandle = interface // function Config(const sconfs: TStrings): boolean; // function Connect(): boolean; // function Disconnect: boolean; // function Send(const str: string): boolean; // function Recv(var str: string; const coder: ECommProtocol): boolean; // end; // // TCommHandle = class(TComponent, ICommHandle, ITextMessengerImpl) // // end; //definition of a interface for communication ICommInterf = interface function Config(const sconf: string): boolean; overload; function Config(const sconfs: TStrings): boolean; overload; function Connect(): boolean; function Disconnect: boolean; function SendPacket(const pbuf: PByteArray; const wlen: word): boolean; function SendStr(const str: string): boolean; function RecvPacket(var pbuf: PByteArray; var wlen: word; const bwait: boolean): boolean; function RecvStr(var str: string; const bwait: boolean): integer; function ExpectStr(var str: string; const swait: string; const bcase: boolean): boolean; end; //base class of connection TConnBase = class(TComponent, ICommInterf, ITextMessengerImpl) class function GetConnectTypeEnum(const conkey: string; var val: EConnectType): boolean; class function GetConnectTypeName(const etype: EConnectType): string; class function GetConnectState(const estate: EConnectState): string; protected e_type: EConnectType; //connection type e_state: EConnectState; //connection state c_timeout: cardinal; //timeout in milli seconds t_msgrimpl: TTextMessengerImpl; //for transfering messages t_rxwait: TEvent; //wait event for reading t_txwait: TEvent; //wait event for writing complete protected function GetTypeName(): string; virtual; function GetStateStr(): string; virtual; function PacketToStr(const pbytes: PByteArray; const wlen: Word; const bhex: Boolean = True): string; virtual; abstract; function WaitForReceiving(const tend: cardinal; const bfirst: boolean = true): boolean; virtual; function WaitForSending(const tend: cardinal): boolean; virtual; function WaitForConnecting(const tend: cardinal): boolean; virtual; function IsConnected(): boolean; virtual; function IsReadReady(): boolean; virtual; abstract; function IsWriteComplete(): boolean; virtual; abstract; function TryConnect(): boolean; virtual; abstract; function TryDisconnect(): boolean; virtual; abstract; function InitBuffer(): boolean; virtual; abstract; function WriteStrToBuffer(const txstr: string): boolean; virtual; abstract; function WritePacketToBuffer(const pbytes: PByteArray; const wlen: word): boolean; virtual; abstract; function SendFromBuffer(): boolean; virtual; abstract; function ReadStrFromBuffer(): string; virtual; abstract; function ReadPacketFromBuffer(var pbytes: PByteArray; var wlen: word): integer; virtual; abstract; function RecvToBuffer(): integer; virtual; abstract; procedure DeinitBuffer(); virtual; abstract; public //constructor and destructor constructor Create(owner: TComponent); override; destructor Destroy(); override; //delegate interface ITextMessengerImpl property MessengerService: TTextMessengerImpl read t_msgrimpl implements ITextMessengerImpl; //base properties property Connected: boolean read IsConnected; property ConnectType: EConnectType read e_type; property ConnectTypeName: string read GetTypeName; property ConnectState: EConnectState read e_state; property Timeout: cardinal read c_timeout write c_timeout; //implementation of ICommInterf function Config(const sconf: string): boolean; overload; virtual; function Config(const sconfs: TStrings): boolean; overload; virtual; abstract; function Connect(): boolean; virtual; function Disconnect(): boolean; virtual; function SendPacket(const pbuf: PByteArray; const wlen: word): boolean; virtual; function SendStr(const str: string): boolean; virtual; function RecvPacket(var pbuf: PByteArray; var wlen: word; const bwait: boolean = true): boolean; virtual; function RecvStr(var str: string; const bwait: boolean = true): integer; virtual; function ExpectStr(var str: string; const swait: string; const bcase: boolean = false): boolean; virtual; //additionnal functions function RecvStrTimeout(var str: string; const timeout: cardinal): integer; virtual; function RecvStrInterval(var str: string; const timeout: cardinal; const interv: cardinal = 3000): integer; virtual; function RecvStrExpected(var str: string; const exstr: string; timeout: cardinal; const bcase: boolean = false): boolean; virtual; function ClearBuffer(): integer; virtual; abstract; //sync methods procedure SetEventRx(); procedure ResetEventRx(); procedure SetEventTx(); procedure ResetEventTx(); end; PConnBase = ^TConnBase; const //define names of connection types CSTR_CONN_KEYS : array[EConnectType] of string = ( 'UNKNOWN', 'RS232', 'MTXUSB', 'TEKUSB', 'GPIB', 'ETHERNET', 'JTAG', 'PCAN', 'PROFI' ); //define connection state CSTR_CONN_STATES: array[EConnectState] of string = ( 'unknown', 'configured', 'connected' ); CINT_TIMEOUT_DEFAULT = 2000;//default timeout in milliseconds CINT_INTERVAL_DEFAULT = 300;//default interval by reading in milliseconds CINT_RECV_INTERVAL = 50; //milliseconds implementation uses Forms, StrUtils, Windows, Registry; // ============================================================================= // Description : a class function to get connection type using its name // Parameter : conkey, string to represent the name of a connection type // val, enum for output, see definition of EConnectType // Return : true, if the given conkey is found in the definiation of // connection type and the type value will be save in the // parameter val. Otherwise false. // Exceptions : -- // First author : 2016-07-15 /bsu/ // History : // ============================================================================= class function TConnBase.GetConnectTypeEnum(const conkey: string; var val: EConnectType): boolean; var i_idx: integer; begin i_idx := IndexText(conkey, CSTR_CONN_KEYS); if ((i_idx >= Ord(Low(EConnectType))) and (i_idx <= Ord(High(EConnectType)))) then begin val := EConnectType(i_idx); result := true; end else result := false; end; // ============================================================================= // Description : a class function to get the name of a connection type // Parameter : etype, enum, see definition of EConnectType // Return : string, name of connection type // Exceptions : -- // First author : 2016-07-15 /bsu/ // History : // ============================================================================= class function TConnBase.GetConnectTypeName(const etype: EConnectType): string; begin result := CSTR_CONN_KEYS[etype]; end; // ============================================================================= // Description : a class function to get string which represents the current // state of the connection // Parameter : estate, enum, see definition of EConnectState // Return : string of current state // Exceptions : -- // First author : 2016-07-15 /bsu/ // History : // ============================================================================= class function TConnBase.GetConnectState(const estate: EConnectState): string; begin result := CSTR_CONN_STATES[estate]; end; // ============================================================================= // Description : get name of the connection type of the object // Parameter : -- // Return : string of current state // Exceptions : -- // First author : 2016-07-15 /bsu/ // History : // ============================================================================= function TConnBase.GetTypeName(): string; begin result := TConnBase.GetConnectTypeName(e_type); end; // ============================================================================= // Description : get string which represents the current state // Parameter : -- // Return : string of current state // Exceptions : -- // First author : 2016-07-15 /bsu/ // History : // ============================================================================= function TConnBase.GetStateStr(): string; begin result := TConnBase.GetConnectState(e_state); end; // ============================================================================= // Description : wait until the first data arrives. // Parameter : tend, end time (current time + timeout) // Return : true, if the data arrives // false, otherwise // Exceptions : -- // First author : 2016-07-15 /bsu/ // History : // ============================================================================= function TConnBase.WaitForReceiving(const tend: cardinal; const bfirst: boolean): boolean; var s_lastmsg: string; c_tcur, c_count, c_secs: cardinal; b_wait, b_read: boolean; begin c_tcur := GetTickCount(); c_count := c_tcur; b_read := IsReadReady(); //save its return value in a local variable, because it can be other value for next calling, e.g. an event automatically signaled b_wait := ((not b_read) and (c_tcur < tend)); if b_wait then begin if bfirst then begin s_lastmsg := format('Waiting for reading: %d', [Round((tend - c_tcur) / 1000)]) + ' ... %ds'; t_msgrimpl.AddMessage(format(s_lastmsg, [Round((tend - c_tcur) / 1000)])); end; repeat Application.ProcessMessages(); c_tcur := GetTickCount(); if (c_tcur - c_count) > 500 then begin //update the message per 0.5 second to avoid flashing in gui if (tend > c_tcur) then c_secs := Round((tend - c_tcur) / 1000) else c_secs := 0; t_msgrimpl.UpdateMessage(format(s_lastmsg, [c_secs])); c_count := c_tcur; end; b_read := IsReadReady(); b_wait := ((not b_read) and (c_tcur < tend)); until (not b_wait); end; result := b_read; end; // ============================================================================= // Description : wait until the sending data is acturally sent. // Parameter : tend, end time (current time + timeout) // Return : true, if the data is sent // false, otherwise // Exceptions : -- // First author : 2016-07-15 /bsu/ // History : // ============================================================================= function TConnBase.WaitForSending(const tend: cardinal): boolean; var s_lastmsg: string; c_tcur, c_count, c_secs: cardinal; b_wait, b_write: boolean; begin c_tcur := GetTickCount(); c_count := c_tcur; b_write := IsWriteComplete(); //save its return value in a local variable, because it can be other value for next calling, e.g. an event automatically signaled b_wait := ((not b_write) and (c_tcur < tend)); if b_wait then begin s_lastmsg := format('Waiting for completing write: %d', [Round((tend - c_tcur) / 1000)]) + ' ... %ds'; t_msgrimpl.AddMessage(format(s_lastmsg, [Round((tend - c_tcur) / 1000)])); repeat Application.ProcessMessages(); c_tcur := GetTickCount(); if (c_tcur - c_count) > 500 then begin //update the message per 0.5 second to avoid flashing if (tend > c_tcur) then c_secs := Round((tend - c_tcur) / 1000) else c_secs := 0; t_msgrimpl.UpdateMessage(format(s_lastmsg, [c_secs])); c_count := c_tcur; end; b_write := IsWriteComplete(); b_wait := ((not b_write) and (c_tcur < tend)); until (not b_wait); end; result := b_write; end; // ============================================================================= // Description : try to connect more times till timeout or the connection is // established if it is not connected // Parameter : tend, end time (current time + timeout) // Return : true, if it is connected // false, otherwise // Exceptions : -- // First author : 2016-07-15 /bsu/ // History : // ============================================================================= function TConnBase.WaitForConnecting(const tend: cardinal): boolean; var s_lastmsg: string; c_tcur, c_count, c_secs: cardinal; b_wait: boolean; begin c_tcur := GetTickCount(); c_count := c_tcur; b_wait := ((not Connected) and (c_tcur < tend)); if b_wait then begin s_lastmsg := format('Waiting for connecting: %d', [Round((tend - c_tcur) / 1000)]) + ' ... %ds'; t_msgrimpl.AddMessage(format(s_lastmsg, [Round((tend - c_tcur) / 1000.0)])); repeat Application.ProcessMessages(); TryConnect(); c_tcur := GetTickCount(); if (c_tcur - c_count) > 500 then begin //update the message per 0.5 second to avoid flashing if (tend > c_tcur) then c_secs := Round((tend - c_tcur) / 1000) else c_secs := 0; t_msgrimpl.UpdateMessage(format(s_lastmsg, [c_secs])); c_count := c_tcur; end; b_wait := ((not IsConnected()) and (c_tcur < tend)); until (not b_wait); end; result := IsConnected(); end; // ============================================================================= // Description : query whether the object is connected // Parameter : -- // Return : true, if it is connected // false, otherwise // Exceptions : -- // First author : 2016-07-15 /bsu/ // History : // ============================================================================= function TConnBase.IsConnected(): boolean; begin result := (e_state = CS_CONNECTED); end; // ============================================================================= // Description : constuctor // Parameter : -- // Exceptions : -- // First author : 2016-06-15 /bsu/ // History : // ============================================================================= constructor TConnBase.Create(owner: TComponent); begin inherited Create(owner); t_msgrimpl := TTextMessengerImpl.Create(ClassName()); e_type := CT_UNKNOWN; e_state := CS_UNKNOWN; c_timeout := CINT_TIMEOUT_DEFAULT; InitBuffer(); t_rxwait := TEvent.Create(nil, false, false, 'TMtxConn.Rx'); t_txwait := TEvent.Create(nil, false, false, 'TMtxConn.Tx'); end; // ============================================================================= // Description : destuctor // Parameter : -- // Exceptions : -- // First author : 2016-06-15 /bsu/ // History : // ============================================================================= destructor TConnBase.Destroy; begin FreeAndNil(t_txwait); FreeAndNil(t_rxwait); DeinitBuffer(); t_msgrimpl.Free(); inherited Destroy(); end; // ============================================================================= // Description : config device using a string, which is formatted as // 'PropertyName1:value1|PropertyName2:value2' or // 'PropertyName1=value1|PropertyName2=value2' // Parameter : sconf, a formatted string. As empty parameter is not acceptable // Return : true, if the sconf is valid and accepted by the connection // First author : 2016-06-17 /bsu/ // History : // ============================================================================= function TConnBase.Config(const sconf: string): boolean; var t_confs: TStrings; s_conf: string; begin result := false; s_conf := ReplaceStr(sconf, ':', '='); t_confs := TStringList.Create(); if (ExtractStrings(['|'], [' ', #9], PChar(s_conf), t_confs) > 0) then result := Config(t_confs); t_confs.Free(); end; // ============================================================================= // Description : establisch connection // Note: This function will try to establish the connections // more times till timeout if the connection is not establisched // by the first one time // Parameter : -- // Return : true, if the connection is established // false, otherwise // Exceptions : -- // First author : 2016-07-12 /bsu/ // History : // ============================================================================= function TConnBase.Connect(): boolean; begin result := false; if (e_state in [CS_CONFIGURED, CS_CONNECTED]) then begin TryConnect(); result := WaitForConnecting(GetTickCount() + c_timeout); if result then begin e_state := CS_CONNECTED; t_msgrimpl.AddMessage(format('Successful to make a connection(%s).', [GetTypeName()])); end else t_msgrimpl.AddMessage(format('Failed to make a connection(%s)', [GetTypeName()]), ML_ERROR); end else t_msgrimpl.AddMessage(format('The current state (%s) is not suitable for making a connection.', [GetStateStr()]), ML_WARNING); end; // ============================================================================= // Description : disconnect from the device and release the resource // Parameter : -- // Return : true, if the device is disconnected // false, otherwise // Exceptions : -- // First author : 2016-11-28 /bsu/ // History : // ============================================================================= function TConnBase.Disconnect(): boolean; begin if Connected then begin result := TryDisconnect(); if result then begin if (e_state in [CS_CONFIGURED, CS_CONNECTED]) then e_state := CS_CONFIGURED; t_msgrimpl.AddMessage(format('Successful to disconnect from the device (type=%s).', [GetTypeName()])); end else t_msgrimpl.AddMessage(format('Failed to disconnect from the device (type=%s).', [GetTypeName()]), ML_ERROR); end else result := true; end; // ============================================================================= // Description : send data in an array of char // Parameter : buf, pointer of the array to send // len, length of the array // Return : true, if the string is sent successfully // false, otherwise // Exceptions : -- // First author : 2016-07-15 /bsu/ // History : // ============================================================================= function TConnBase.SendPacket(const pbuf: PByteArray; const wlen: word): boolean; var c_tend: cardinal; s_packet: string; begin result := false; if Connected then begin ClearBuffer(); c_tend := GetTickCount() + c_timeout; s_packet := PacketToStr(pbuf, wlen, true); result := WritePacketToBuffer(pbuf, wlen); if result then begin result := SendFromBuffer(); if result then result := WaitForSending(c_tend); if result then t_msgrimpl.AddMessage(format('Successful to send packet: data=%s (%d bytes)', [s_packet, wlen])) else t_msgrimpl.AddMessage(format('Failed to send packet: data=%s (%d bytes)', [s_packet, wlen]), ML_ERROR) end else t_msgrimpl.AddMessage(format('Failed to write packet into sending buffer: data=%s (%d bytes)', [s_packet, wlen]), ML_ERROR) end else t_msgrimpl.AddMessage(format('No data can be sent because the connection (%s) is not yet established.', [GetTypeName()]), ML_ERROR); end; // ============================================================================= // Description : send a string // Parameter : str, the string to send // Return : true, if the string is sent successfully // false, otherwise // Exceptions : -- // First author : 2016-07-15 /bsu/ // History : // ============================================================================= function TConnBase.SendStr(const str: string): boolean; var w_len: word; c_tend: cardinal; begin result := false; if Connected then begin ClearBuffer(); c_tend := GetTickCount() + c_timeout; w_len := length(str); result := WriteStrToBuffer(str); if result then begin result := SendFromBuffer(); if result then result := WaitForSending(c_tend); if result then t_msgrimpl.AddMessage(format('Successful to send string: string=%s; length=%d', [str, w_len])) else t_msgrimpl.AddMessage(format('Failed to send string into sending buffer: string=%s; length=%d', [str, w_len]), ML_ERROR); end else t_msgrimpl.AddMessage(format('Failed to write string into sending buffer: string=%s; length=%d', [str, w_len]), ML_ERROR); end else t_msgrimpl.AddMessage(format('No data can be sent because the connection (%s) is not yet established.', [GetTypeName()]), ML_ERROR); end; // ============================================================================= // Description : receive data and save it in an array of char // Parameter : buf, an array variable for output // len, length of the array // bwait, indicates whether it should wait if no data is not available recently // Note: The property Timeout will be used if bwait is equal true. // Return : integer, the length of the received data in byte // Exceptions : -- // First author : 2016-07-15 /bsu/ // History : // ============================================================================= function TConnBase.RecvPacket(var pbuf: PByteArray; var wlen: word; const bwait: boolean): boolean; var c_tend: cardinal; s_packet: string; begin result := false; if Connected then begin c_tend := GetTickCount() + c_timeout; if bwait then WaitForReceiving(c_tend); result := (RecvToBuffer() > 0); if result then begin result := (ReadPacketFromBuffer(pbuf, wlen) > 0); if result then begin s_packet := PacketToStr(pbuf, wlen, true); t_msgrimpl.AddMessage(format('Successful to get packet from receieving buffer: data=%s (%d bytes)', [s_packet, wlen])) end else t_msgrimpl.AddMessage('Failed to get packet from receieving buffer', ML_ERROR); end else t_msgrimpl.AddMessage('No packet is received', ML_ERROR); end else t_msgrimpl.AddMessage(format('No data can be received because the connection (%s) is not yet established.', [GetTypeName()]), ML_ERROR); end; // ============================================================================= // Description : receive a string // Parameter : str, output string which is received // bwait, indicates whether it should wait if no data is not available recently // Note: The property Timeout will be used if bwait is equal true. // Return : integer, the length of the received string // Exceptions : -- // First author : 2016-07-15 /bsu/ // History : // ============================================================================= function TConnBase.RecvStr(var str: string; const bwait: boolean): integer; var c_tend: cardinal; begin result := 0; if Connected then begin c_tend := GetTickCount() + c_timeout; if bwait then WaitForReceiving(c_tend); result := RecvToBuffer(); if (result > 0) then begin str := ReadStrFromBuffer(); if (str <> '') then t_msgrimpl.AddMessage(format('Successful to get string from receieving buffer: data=%s', [str])) else t_msgrimpl.AddMessage('Failed to get string from receieving buffer', ML_ERROR); end else t_msgrimpl.AddMessage('No string is received', ML_ERROR); end else t_msgrimpl.AddMessage(format('No data can be received because the connection (%s) is not yet established.', [GetTypeName()]), ML_ERROR); end; function TConnBase.ExpectStr(var str: string; const swait: string; const bcase: boolean): boolean; begin result := RecvStrExpected(str, swait, c_timeout, bcase); end; // ============================================================================= // Description : force to receive string until the timeout is over // Parameter : str, output string which is received // timeout, in millisecond // Return : integer, the length of the received string // Exceptions : -- // First author : 2016-07-15 /bsu/ // History : // ============================================================================= function TConnBase.RecvStrTimeout(var str: string; const timeout: cardinal): integer; var tend: cardinal; begin result := 0; str := ''; tend := GetTickCount() + timeout; if Connected then begin repeat result := RecvToBuffer(); if (result > 0) then str := str + ReadStrFromBuffer(); Application.ProcessMessages(); until (GetTickCount() >= tend); result := length(str); if (result > 0) then t_msgrimpl.AddMessage(format('Successful to receieve string: %s (length=%d)', [str, result])) else t_msgrimpl.AddMessage('Nothing is receieved.', ML_WARNING); end else t_msgrimpl.AddMessage(format('No data can be received because the connection (%s) is not yet established.', [GetTypeName()]), ML_ERROR); end; // ============================================================================= // Description : force to receive string until the time is over or the interval is over // An interval is allowed between the data blocks if they arrive in more times // Parameter : str, output string which is received // timeout, time in millisecond // interv, an interval in millisecond // Return : integer, the length of the received string // Exceptions : -- // First author : 2016-07-15 /bsu/ // History : // ============================================================================= function TConnBase.RecvStrInterval(var str: string; const timeout: cardinal; const interv: cardinal): integer; var c_time: cardinal; b_break, b_first: boolean; tend: cardinal; begin result := 0; str := ''; tend := GetTickCount() + timeout; if Connected then begin b_first := true; repeat result := RecvToBuffer(); if (result > 0) then str := str + ReadStrFromBuffer(); c_time := GetTickCount() + interv; if (c_time > tend) then c_time := tend; Application.ProcessMessages(); b_break := (not WaitForReceiving(c_time, b_first)); b_first := false; until (b_break or (GetTickCount() >= tend)); result := length(str); if (result > 0) then t_msgrimpl.AddMessage(format('Successful to receieve string: %s (length=%d)', [str, result])) else t_msgrimpl.AddMessage('Nothing is receieved.', ML_WARNING); end else t_msgrimpl.AddMessage(format('No data can be received because the connection (%s) is not yet established.', [GetTypeName()]), ML_ERROR); end; // ============================================================================= // Description : force to receive string until the time is over or the expected string arrives // Parameter : str, output string which is received // exstr, expected string // timeout, in millisecond // bcase, indicates if case sensitivity should be considered // Return : integer, the length of the received string // Exceptions : -- // First author : 2016-07-15 /bsu/ // History : // ============================================================================= function TConnBase.RecvStrExpected(var str: string; const exstr: string; timeout: cardinal; const bcase: boolean): boolean; var tend: cardinal; w_len: word; begin result := false; str := ''; tend := GetTickCount() + timeout; if Connected then begin repeat w_len := RecvToBuffer(); if (w_len > 0) then str := str + ReadStrFromBuffer(); if bcase then result := ContainsStr(str, exstr) else result := ContainsText(str, exstr); Application.ProcessMessages(); until (result or (GetTickCount() >= tend)); w_len := length(str); if (result) then t_msgrimpl.AddMessage(format('Successful to receieve string: %s (length=%d)', [str, w_len])) else t_msgrimpl.AddMessage('The expected string is not receieved.', ML_WARNING); end else t_msgrimpl.AddMessage(format('No data can be received because the connection (%s) is not yet established.', [GetTypeName()]), ML_ERROR); end; // ============================================================================= // Description : signal the read event // Parameter : -- // Return : -- // Exceptions : -- // First author : 2016-07-15 /bsu/ // History : // ============================================================================= procedure TConnBase.SetEventRx(); begin t_rxwait.SetEvent(); end; // ============================================================================= // Description : unsignal the event of read complete // Parameter : -- // Return : -- // Exceptions : -- // First author : 2016-07-15 /bsu/ // History : // ============================================================================= procedure TConnBase.ResetEventRx(); begin t_rxwait.ResetEvent(); end; // ============================================================================= // Description : signal the event of write complete // Parameter : -- // Return : -- // Exceptions : -- // First author : 2016-07-15 /bsu/ // History : // ============================================================================= procedure TConnBase.SetEventTx(); begin t_txwait.SetEvent(); end; // ============================================================================= // Description : unsignal the event of write complete // Parameter : -- // Return : -- // Exceptions : -- // First author : 2016-07-15 /bsu/ // History : // ============================================================================= procedure TConnBase.ResetEventTx(); begin t_txwait.ResetEvent(); end; end.
unit Internet; interface uses Windows, WinInet, AntiSniffModule, ImportsDoctor, MemStrTools, commonDefs; type InetOpenPROTO = function(lpszAgent: PAnsiChar; dwAccessType: DWORD; lpszProxy, lpszProxyBypass: PAnsiChar; dwFlags: DWORD): Pointer; stdcall; InetOpenUrlPROTO = function(hInet: Pointer; lpszUrl: PAnsiChar; lpszHeaders: PAnsiChar; dwHeadersLength: DWORD; dwFlags: DWORD; dwContext: DWORD): Pointer; stdcall; InetReadFilePROTO = function(hFile: Pointer; lpBuffer: Pointer; dwNumberOfBytesToRead: DWORD; var lpdwNumberOfBytesRead: DWORD): BOOL; stdcall; InetCloseHandlePROTO = function(hInet: Pointer): BOOL; stdcall; InetClass = class lpInternetOpen: InetOpenPROTO; lpInternetOpenUrlA: InetOpenUrlPROTO; lpInternetReadFile: InetReadFilePROTO; lpInternetCloseHandle: InetCloseHandlePROTO; internet, UrlHandle:Pointer; Buffer: array[0..1023] of byte; BytesRead: dWord; StrBuffer: UTF8String; Wininet: Cardinal; lock: Boolean; private function GETRequest(request: string):string; public constructor Create; function SendLog(request: PChar):string; end; var Inet: InetClass; implementation constructor InetClass.Create(); begin Wininet := GetModuleHandle(PChar(Tools.Crypt(COMDEF_LIBRARY_WININET, false))); if Wininet=0 then Wininet := LoadLibrary(PChar(Tools.Crypt(COMDEF_LIBRARY_WININET, false))); @lpInternetOpen := GetProcAddress(Wininet, PChar(Tools.Crypt(COMDEF_FUNCTION_INETOPEN, false))); @lpInternetOpenUrlA := GetProcAddress(Wininet, PChar(Tools.Crypt(COMDEF_FUNCTION_INETOPENURL, false))); @lpInternetReadFile := GetProcAddress(Wininet, PChar(Tools.Crypt(COMDEF_FUNCTION_INETREADFILE, false))); @lpInternetCloseHandle := GetProcAddress(Wininet, PChar(Tools.Crypt(COMDEF_FUNCTION_INETCLOSEHANDLE, false))); lock := false; end; {$O-} function InetClass.GETRequest(request: string): string; begin internet := lpInternetOpen(PChar(Tools.Crypt(COMDEF_INTERNET_AGENT, false)), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0); UrlHandle := lpInternetOpenUrlA(internet, PChar(request), nil, 0, INTERNET_FLAG_RELOAD, 0); if Assigned(UrlHandle) then try repeat lpInternetReadFile(UrlHandle, @Buffer, SizeOf(Buffer), BytesRead); SetString(StrBuffer, PAnsiChar(@Buffer[0]), BytesRead); Result := Result + StrBuffer; lock := false; until BytesRead = 0; finally lpInternetCloseHandle(internet); lpInternetCloseHandle(UrlHandle); lock := false; end; end; {$O+} function InetClass.SendLog(request: PChar):string; var tempbuf: array [0..1023] of char; tmp: string; begin Result := ''; lstrcpy(@tempbuf, request); if Traffic.FindBads=false then begin while self.lock do Sleep(50); lock := true; Result := GETRequest(tempbuf); end end; end.
unit DlgTestWaitDialog; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DlgTest, Menus, cxLookAndFeelPainters, StdCtrls, cxButtons, ExtCtrls, mnWaitDialog; type TTestWaitDialogDialog = class(TTestDialog) wdMain: mnTWaitDialog; cbCanCancel: TCheckBox; cbHasGauge: TCheckBox; cbCancelAfter5Secs: TCheckBox; btnShow: TButton; tmrCancel: TTimer; procedure tmrCancelTimer(Sender: TObject); procedure btnShowClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var TestWaitDialogDialog: TTestWaitDialogDialog; implementation uses mnDialog, mnSystem; {$R *.dfm} procedure TTestWaitDialogDialog.btnShowClick(Sender: TObject); var i: Integer; begin tmrCancel.Enabled := cbCancelAfter5Secs.Checked; try try wdMain.CanCancel := cbCanCancel.Checked; wdMain.HasGauge := cbHasGauge.Checked; wdMain.Workload := 2000; wdMain.Show; for i := 1 to wdMain.Workload do begin wdMain.Prompt := Format('Please wait... %d / %d', [i, wdMain.Workload]); Sleep(2); wdMain.AddProgress(1); wdMain.CheckCancelled; end; mnInfoBox('Mission accomplished'); except on E: Exception do begin mnCreateError(ExceptClass(E.ClassType), E.Message + mnNewLine + mnNewLine + 'Current prompt: ' + mnNewLine + wdMain.Prompt); end; end; finally wdMain.Close; end; end; procedure TTestWaitDialogDialog.tmrCancelTimer(Sender: TObject); begin wdMain.Cancel; end; end.
unit Crypt; interface uses Windows, SysUtils; const PASSWORD_EXPAND_ITERATIONS = 500000; // 500k - 5 per sec; 300k - 8 per sec; HARDCODED_SALT = 'sPz1x3u3vyU4yr'; CRYPT_ERR_SUCCESS = 0; CRYPT_ERR_UNKNOWN = 1; CRYPT_ERR_FILE_NOT_FOUND = 2; CRYPT_ERR_DELETE_OUTPUT_FILE_FAILED = 3; CRYPT_ERR_OPEN_INPUT_FILE_FAILED = 4; CRYPT_ERR_CREATE_OUTPUT_FILE_FAILED = 5; CRYPT_ERR_INPUT_FILE_IS_EMPTY = 6; CRYPT_ERR_READ_FILE_FAILED = 7; CRYPT_ERR_WRITE_FILE_FAILED = 8; CRYPT_ERR_FILE_MAPPING_FAILED = 9; CRYPT_ERR_FILE_MAP_VIEW_FAILED = 10; type TByteArray = Array [0..0] of Byte; PByteArray = ^TByteArray; T128bit = packed Array[0..3] of DWORD; // 128 bits P128bit = ^T128bit; function Crypt_GenerateSalt: WideString; procedure Crypt_GenRandom(const pData: Pointer; const dwSize: DWORD); procedure Crypt_GenerateRandom128bit(const pValue: P128bit); function Crypt_GenerateRndNameW(const Len: Integer): WideString; procedure Crypt_SetKey(const Password, Salt: WideString); procedure Crypt_CipherBlock(const pBlock: P128bit); procedure Crypt_Hash128(const pData: Pointer; const dwSize, dwIterationsCount: LongWord; const pHash: P128bit); procedure Crypt_CryptMemory_CTR(const pData: Pointer; const dwSize: DWORD; const pIV: P128bit); function Crypt_EncryptStringW(const SrcString: WideString): WideString; function Crypt_DecryptStringW(const SrcString: WideString): WideString; function Crypt_CryptAndCopyFile(const InFileName, OutFileName: WideString; const pIV, pInFileHash, pOutFileHash: P128bit): DWORD; function Crypt_ErrToStr(const dwErrorCode: DWORD): string; function CompareMem128(const pMem1, pMem2: P128Bit): Boolean; implementation uses RC6, Tiger, Utils; function RtlGenRandom(RandomBuffer: PBYTE; RandomBufferLength: ULONG): Boolean; stdcall; external advapi32 name 'SystemFunction036'; function Crypt_ErrToStr(const dwErrorCode: DWORD): string; begin case dwErrorCode of CRYPT_ERR_SUCCESS : result:='CRYPT_ERR_SUCCESS'; CRYPT_ERR_UNKNOWN : result:='CRYPT_ERR_UNKNOWN'; CRYPT_ERR_FILE_NOT_FOUND : result:='CRYPT_ERR_FILE_NOT_FOUND'; CRYPT_ERR_DELETE_OUTPUT_FILE_FAILED : result:='CRYPT_ERR_DELETE_OUTPUT_FILE_FAILED'; CRYPT_ERR_OPEN_INPUT_FILE_FAILED : result:='CRYPT_ERR_OPEN_INPUT_FILE_FAILED'; CRYPT_ERR_CREATE_OUTPUT_FILE_FAILED : result:='CRYPT_ERR_CREATE_OUTPUT_FILE_FAILED'; CRYPT_ERR_INPUT_FILE_IS_EMPTY : result:='CRYPT_ERR_INPUT_FILE_IS_EMPTY'; CRYPT_ERR_READ_FILE_FAILED : result:='CRYPT_ERR_READ_FILE_FAILED'; CRYPT_ERR_WRITE_FILE_FAILED : result:='CRYPT_ERR_WRITE_FILE_FAILED'; CRYPT_ERR_FILE_MAPPING_FAILED : result:='CRYPT_ERR_FILE_MAPPING_FAILED'; CRYPT_ERR_FILE_MAP_VIEW_FAILED : result:='CRYPT_ERR_FILE_MAP_VIEW_FAILED'; else result:='# ' + IntToStr(dwErrorCode); end; end; procedure Crypt_GenRandom(const pData: Pointer; const dwSize: DWORD); begin RtlGenRandom(pData, dwSize); end; procedure Crypt_GenerateRandom128bit(const pValue: P128bit); begin RtlGenRandom(Pointer(pValue), SizeOf(pValue^)); Hash_128(pValue, SizeOf(pValue^), 1, pValue); end; function Crypt_GenerateSalt: WideString; const CHARSET: Array[0..86] of WideChar = ('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', '1','2','3','4','5','6','7','8','9','0', '_',')','(','*','&','^','%','$','#','@','!','~','?','>','<',',','.','/','[',']','{','}',';','"',':'); var Len, i, j: DWORD; begin RtlGenRandom(@Len, SizeOf(Len)); Len:=(Len AND $00000007) + 5; // Len = 5..12 SetLength(result, Len); i:=1; while i <= Len do begin RtlGenRandom(@j, SizeOf(j)); j:=j AND $000000FF; if j <= High(CHARSET) then begin result[i]:=CHARSET[j]; inc(i); end; end; end; function Crypt_GenerateRndNameW(const Len: Integer): WideString; const CHARSET: Array[0..61] of WideChar = ('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', '1','2','3','4','5','6','7','8','9','0'); var i, j: Integer; begin SetLength(result, Len); i:=1; while i <= Len do begin RtlGenRandom(@j, SizeOf(j)); j:=j AND $000000FF; if j <= High(CHARSET) then begin result[i]:=CHARSET[j]; inc(i); end; end; end; procedure Crypt_SetKey(const Password, Salt: WideString); var _Password: WideString; Hash: T128bit; len: Integer; begin _Password:=Password + Salt + HARDCODED_SALT; len:=length(_Password); while len < 128 do begin _Password:=_Password + IntToStr(len) + WChar(len) + _Password; len:=length(_Password); end; Hash_128(PWideChar(_Password), length(_Password) shl 1, PASSWORD_EXPAND_ITERATIONS, @Hash); RC6_Init(@Hash); end; procedure Crypt_CryptMemory_CTR(const pData: Pointer; const dwSize: DWORD; const pIV: P128bit); const BLOCK_SIZE = 16; var pBlock: PByte; dwInSize, i: DWORD; Counter: T128bit; begin if (pData = nil) OR (dwSize = 0) then Exit; Counter[0]:=pIV^[0]; Counter[1]:=pIV^[1]; Counter[2]:=pIV^[2]; Counter[3]:=pIV^[3]; pBlock:=pData; dwInSize:=dwSize; i:=0; while dwInSize > 0 do begin if i mod BLOCK_SIZE = 0 then // generating new gamma block, every 128 bits input data begin Hash_128(@Counter, SizeOf(Counter), 1, @Counter); RC6_EncryptBlock(@Counter); end; pBlock^:=pBlock^ XOR PByte(Cardinal(@Counter) + (i mod 16))^; inc(i); inc(pBlock); dec(dwInSize); end; end; function Crypt_EncryptStringW(const SrcString: WideString): WideString; var IV: T128bit; begin RtlGenRandom(@IV, SizeOf(IV)); Hash_128(@IV, SizeOf(IV), 1, @IV); result:=#0#0#0#0#0#0#0#0 + SrcString; // 8 wide chars = 16 Bytes - IV Crypt_CryptMemory_CTR(@result[9], length(SrcString) shl 1, @IV); PDWORD(@result[1])^:=IV[0]; PDWORD(@result[3])^:=IV[1]; PDWORD(@result[5])^:=IV[2]; PDWORD(@result[7])^:=IV[3]; end; function Crypt_DecryptStringW(const SrcString: WideString): WideString; var IV: T128bit; begin result:=SrcString; if length(result) < 9 then Exit; IV[0]:=PDWORD(@result[1])^; IV[1]:=PDWORD(@result[3])^; IV[2]:=PDWORD(@result[5])^; IV[3]:=PDWORD(@result[7])^; delete(result, 1, 8); // remove IV Crypt_CryptMemory_CTR(PWideChar(result), length(result) shl 1, @IV); end; function Crypt_GetFileHandleHash(const hTargetFile: HFILE; const dwFileSize: DWORD; const pHash: P128bit): DWORD; var hMapping: THandle; pData: Pointer; begin hMapping:=CreateFileMapping(hTargetFile, nil, PAGE_READONLY, 0, 0, nil); if hMapping = 0 then begin result:=CRYPT_ERR_FILE_MAPPING_FAILED; Exit; end; pData:=MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0); if pData = nil then begin CloseHandle(hMapping); result:=CRYPT_ERR_FILE_MAP_VIEW_FAILED; Exit; end; Hash_128(pData, dwFileSize, 1, pHash); UnmapViewOfFile(pData); CloseHandle(hMapping); result:=CRYPT_ERR_SUCCESS; end; procedure Crypt_CipherBlock(const pBlock: P128bit); begin RC6_EncryptBlock(pBlock); end; procedure Crypt_Hash128(const pData: Pointer; const dwSize, dwIterationsCount: LongWord; const pHash: P128bit); begin Hash_128(pData, dwSize, dwIterationsCount, pHash); end; function Crypt_CryptAndCopyFile(const InFileName, OutFileName: WideString; const pIV, pInFileHash, pOutFileHash: P128bit): DWORD; var hInFile, hOutFile: HFILE; FileSize: Integer; dwSavedFileSize, dwReaded, dwWritten: DWORD; Block, Counter: T128bit; begin if NOT FileExistsW(InFileName) then begin result:=CRYPT_ERR_FILE_NOT_FOUND; Exit; end; if FileExistsW(OutFileName) then begin if NOT (DeleteFileW(PWideChar(OutFileName)) AND (NOT FileExistsW(OutFileName))) then begin result:=CRYPT_ERR_DELETE_OUTPUT_FILE_FAILED; Exit; end; end; hInFile:=CreateFileW(PWideChar(InFileName), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0); if hInFile = INVALID_HANDLE_VALUE then begin result:=CRYPT_ERR_OPEN_INPUT_FILE_FAILED; Exit; end; hOutFile:=CreateFileW(PWideChar(OutFileName), GENERIC_ALL, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if hOutFile = INVALID_HANDLE_VALUE then begin CloseHandle(hInFile); result:=CRYPT_ERR_CREATE_OUTPUT_FILE_FAILED; Exit; end; dwSavedFileSize:=GetFileSize(hInFile, nil); if dwSavedFileSize = 0 then begin CloseHandle(hInFile); CloseHandle(hOutFile); result:=CRYPT_ERR_INPUT_FILE_IS_EMPTY; Exit; end; FileSize:=dwSavedFileSize; Counter[0]:=pIV^[0]; Counter[1]:=pIV^[1]; Counter[2]:=pIV^[2]; Counter[3]:=pIV^[3]; while FileSize > 0 do begin if NOT ReadFile(hInFile, Block, SizeOf(Block), dwReaded, nil) then begin CloseHandle(hInFile); CloseHandle(hOutFile); result:=CRYPT_ERR_READ_FILE_FAILED; Exit; end; // Generate new CTR state Hash_128(@Counter, SizeOf(Counter), 1, @Counter); // Cipher CTR state RC6_EncryptBlock(@Counter); // Encrypt data block Block[0]:=Block[0] XOR Counter[0]; Block[1]:=Block[1] XOR Counter[1]; Block[2]:=Block[2] XOR Counter[2]; Block[3]:=Block[3] XOR Counter[3]; if ((NOT WriteFile(hOutFile, Block, dwReaded, dwWritten, nil)) OR (dwReaded <> dwWritten)) then begin CloseHandle(hInFile); CloseHandle(hOutFile); result:=CRYPT_ERR_WRITE_FILE_FAILED; Exit; end; dec(FileSize, dwReaded); end; if pInFileHash <> nil then begin result:=Crypt_GetFileHandleHash(hInFile, dwSavedFileSize, pInFileHash); if result <> CRYPT_ERR_SUCCESS then begin CloseHandle(hInFile); CloseHandle(hOutFile); Exit; end; end; if pOutFileHash <> nil then begin result:=Crypt_GetFileHandleHash(hOutFile, dwSavedFileSize, pOutFileHash); if result <> CRYPT_ERR_SUCCESS then begin CloseHandle(hInFile); CloseHandle(hOutFile); Exit; end; end; CloseHandle(hInFile); CloseHandle(hOutFile); result:=CRYPT_ERR_SUCCESS; end; function CompareMem128(const pMem1, pMem2: P128Bit): Boolean; begin result:=(PDWORD(pMem1)^ = PDWORD(pMem2)^) AND (PDWORD(Cardinal(pMem1) + 4)^ = PDWORD(Cardinal(pMem2) + 4)^) AND (PDWORD(Cardinal(pMem1) + 8)^ = PDWORD(Cardinal(pMem2) + 8)^) AND (PDWORD(Cardinal(pMem1) + 12)^ = PDWORD(Cardinal(pMem2) + 12)^); end; end.
unit View.TemplateList; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, FireDAC.Comp.Client, System.ImageList, Vcl.ImgList, Util.View, View.Template, Controller, Util.Enum, Model, Singleton.Connection, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, Vcl.Menus; type TTemplateListView = class(TForm) PanelHeader: TPanel; DBGrid: TDBGrid; StatusBar: TStatusBar; DataSource: TDataSource; PanelFilter: TPanel; BTNPesquisar: TButton; BTNIncluir: TButton; BTNAlterar: TButton; BTNExcluir: TButton; BTNLimpar: TButton; ImageList1: TImageList; FDQuery: TFDQuery; PPMList: TPopupMenu; MIAlterar: TMenuItem; MIExcluir: TMenuItem; MIVisualizar: TMenuItem; procedure DBGridTitleClick(Column: TColumn); procedure DBGridDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure BTNLimparClick(Sender: TObject); procedure BTNExcluirClick(Sender: TObject); procedure BTNIncluirClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure BTNAlterarClick(Sender: TObject); procedure DBGridKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormDestroy(Sender: TObject); procedure BTNPesquisarClick(Sender: TObject); procedure MIAlterarClick(Sender: TObject); procedure MIExcluirClick(Sender: TObject); procedure MIVisualizarClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DBGridDblClick(Sender: TObject); procedure FormShow(Sender: TObject); protected IDReturnSearch: Integer; private FViewTemplate: TTemplateView; FController: TController; FModoViewList: TModoViewList; procedure SetViewTemplate(const Value: TTemplateView); procedure SetController(const Value: TController); procedure SetModoViewList(const Value: TModoViewList); public procedure Visualizar; function CreateViewTemplate(AOperacao: TOperacao): TTemplateView; virtual; abstract; procedure CreateController; virtual; abstract; procedure ShowViewTemplate(AOperacao: TOperacao); virtual; function Search(const ACondition: string): TModel; virtual; property ModoViewList: TModoViewList read FModoViewList write SetModoViewList default mvlNormal; property ViewTemplate: TTemplateView read FViewTemplate write SetViewTemplate; property Controller: TController read FController write SetController; end; var TemplateListView: TTemplateListView; implementation {$R *.dfm} procedure TTemplateListView.BTNAlterarClick(Sender: TObject); begin if (Assigned(DataSource.DataSet)) and (DataSource.DataSet.Active) and (not DataSource.DataSet.IsEmpty) then begin ShowViewTemplate(oUpdate); end; end; procedure TTemplateListView.BTNExcluirClick(Sender: TObject); var LMensagem: string; begin if (Assigned(DataSource.DataSet)) and (DataSource.DataSet.Active) and (not DataSource.DataSet.IsEmpty) then begin if Application.MessageBox('Deseja realmente excluir esse registro?', 'Atenção', MB_YESNO + MB_ICONWARNING + ICON_SMALL) = mrYes then begin CreateController; Controller.Model.ID := DataSource.DataSet.FieldByName('ID').AsInteger; try if Controller.Transaction(oDelete, Controller.Model, LMensagem) then begin Application.MessageBox('Registro excluído com sucesso', 'Sucesso', MB_OK + MB_ICONINFORMATION); end else begin Application.MessageBox(PWideChar('Erro: ' + LMensagem), 'Erro', MB_OK + MB_ICONERROR); end; finally DataSource.DataSet.Refresh; end; end; end; end; procedure TTemplateListView.BTNIncluirClick(Sender: TObject); begin ShowViewTemplate(oCreate); end; procedure TTemplateListView.BTNLimparClick(Sender: TObject); begin LimparCampos(Self); end; procedure TTemplateListView.BTNPesquisarClick(Sender: TObject); begin CreateController; end; procedure TTemplateListView.DBGridDblClick(Sender: TObject); var Shift: TShiftState; LKey: Word; begin LKey := VK_Return; DBGrid.OnKeyDown(Sender, LKey, Shift); end; procedure TTemplateListView.DBGridDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if Odd(DataSource.DataSet.Recno) = False then begin DBGrid.Canvas.Brush.Color := ClBtnFace; DBGrid.Canvas.Font.Color := ClBlack; DBGrid.Canvas.FillRect(Rect); DBGrid.DefaultDrawDataCell(Rect, Column.Field, State); end; if GdSelected in State then begin DBGrid.Canvas.Brush.Color := ClHighlight; DbGrid.Canvas.Font.Color := ClWhite; DBGrid.Canvas.FillRect(Rect); DBGrid.DefaultDrawDataCell(Rect, Column.Field, State); end; end; procedure TTemplateListView.DBGridKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin with DBGrid do begin if DgRowSelect in Options then begin if Key in [VK_LEFT, VK_RIGHT] then begin case Key of VK_LEFT: if (SsCtrl in Shift) then Perform(WM_HSCROLL, SB_PAGELEFT, 0) else Perform(WM_HSCROLL, SB_LINELEFT, 0); VK_RIGHT: if (SsCtrl in Shift) then Perform(WM_HSCROLL, SB_PAGERIGHT, 0) else Perform(WM_HSCROLL, SB_LINERIGHT, 0); end; Key := 0; Exit; end; end; end; if Key = VK_RETURN then begin if ModoViewList = mvlNormal then Visualizar else begin IDReturnSearch := DataSource.DataSet.FieldByName('ID').AsInteger; Close; end; end; end; procedure TTemplateListView.DBGridTitleClick(Column: TColumn); begin if Assigned(DataSource.DataSet) then TFDQuery(DataSource.DataSet).IndexFieldNames := Column.FieldName; end; procedure TTemplateListView.FormCreate(Sender: TObject); begin BTNPesquisar.Click; end; procedure TTemplateListView.FormDestroy(Sender: TObject); begin if Assigned(Controller) then FreeAndNil(FController); end; procedure TTemplateListView.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_F9 then begin BTNPesquisar.OnClick(nil); end; end; procedure TTemplateListView.FormShow(Sender: TObject); begin if ModoViewList = mvlSearch then begin Width := 500; Height := 800; WindowState := wsNormal; BloquearRedimensionamento(Self); BorderIcons := BorderIcons + [biSystemMenu] + [biMinimize] - [biMaximize]; StatusBar.Panels.Items[0].Text := 'RETURN - Selecionar registro'; if DBGrid.CanFocus then DBGrid.SetFocus; end else begin StatusBar.Panels.Items[0].Text := 'RETURN - Tecle na tabela para visualizar os dados do registro'; WindowState := wsMaximized; end; end; function TTemplateListView.Search(const ACondition: string): TModel; begin Result := nil; end; procedure TTemplateListView.SetController(const Value: TController); begin FController := Value; end; procedure TTemplateListView.SetModoViewList(const Value: TModoViewList); begin FModoViewList := Value; end; procedure TTemplateListView.SetViewTemplate(const Value: TTemplateView); begin FViewTemplate := Value; end; procedure TTemplateListView.ShowViewTemplate(AOperacao: TOperacao); begin FViewTemplate := CreateViewTemplate(AOperacao); FViewTemplate.Operacao := AOperacao; CreateController; try FViewTemplate.PrepareView; if AOperacao in [oUpdate, oRead] then begin FViewTemplate.Model := Controller.DAO.Find(DataSource.DataSet.FieldByName('ID').AsInteger); FViewTemplate.SetViewByModel(FViewTemplate.Model); end; HabilitarCampos(FViewTemplate, not (AOperacao = oRead)); FViewTemplate.Operacao := AOperacao; FViewTemplate.ShowModal; finally if DataSource.DataSet.Active then DataSource.DataSet.Refresh; FreeAndNil(FViewTemplate); end; end; procedure TTemplateListView.Visualizar; begin if (Assigned(DataSource.DataSet)) and (DataSource.DataSet.Active) and (not DataSource.DataSet.IsEmpty) then begin ShowViewTemplate(oRead); end; end; procedure TTemplateListView.MIAlterarClick(Sender: TObject); begin BTNAlterar.Click; end; procedure TTemplateListView.MIExcluirClick(Sender: TObject); begin BTNExcluir.Click; end; procedure TTemplateListView.MIVisualizarClick(Sender: TObject); begin Visualizar; end; end.
unit changeEventCaller; { Trida TChangeEventCaller poskutuje pomocne funkce pro volani ChangeEvents (viz changeEvent.pas). } interface uses changeEvent; type TNPCallerData = record usekId:Integer; jcId:Integer; end; TChangeEventCaller = class procedure CopyUsekZaver(Sender:TObject; data:Integer); procedure NullZamekZaver(Sender:TObject; data:Integer); procedure NullPrejezdZaver(Sender:TObject; data:Integer); procedure NullTratZaver(Sender:TObject; data:Integer); procedure NullVyhybkaMenuReduction(Sender:TObject; data:Integer); procedure NullSComMenuReduction(Sender:TObject; data:Integer); procedure RemoveUsekNeprofil(Sender:TObject; data:Integer); end; var ceCaller: TChangeEventCaller; implementation uses TBloky, TBlok, TBlokUsek, TBlokVyhybka, TBlokZamek, TBlokSCom, TBlokPrejezd, TBlokTrat; //////////////////////////////////////////////////////////////////////////////// procedure TChangeEventCaller.CopyUsekZaver(Sender:TObject; data:Integer); var blk:TBlk; begin Blky.GetBlkByID(data, blk); if ((blk = nil) or ((blk.typ <> _BLK_USEK) and (blk.typ <> _BLK_TU))) then Exit(); TBlkUsek(Blk).Zaver := TBlkUsek(Sender).Zaver; end; procedure TChangeEventCaller.NullZamekZaver(Sender:TObject; data:Integer); var blk:TBlk; begin Blky.GetBlkByID(data, blk); if ((blk = nil) or (blk.typ <> _BLK_ZAMEK)) then Exit(); TBlkZamek(Blk).Zaver := false; end; procedure TChangeEventCaller.NullPrejezdZaver(Sender:TObject; data:Integer); var blk:TBlk; begin Blky.GetBlkByID(data, blk); if ((blk = nil) or (blk.typ <> _BLK_PREJEZD)) then Exit(); TBlkPrejezd(Blk).Zaver := false; end; procedure TChangeEventCaller.NullTratZaver(Sender:TObject; data:Integer); var blk:TBlk; begin Blky.GetBlkByID(data, blk); if ((blk = nil) or (blk.typ <> _BLK_TRAT)) then Exit(); TBlkTrat(Blk).Zaver := false; end; //////////////////////////////////////////////////////////////////////////////// procedure TChangeEventCaller.NullVyhybkaMenuReduction(Sender:TObject; data:Integer); var blk:TBlk; begin Blky.GetBlkByID(data, blk); if ((blk = nil) or (blk.typ <> _BLK_VYH)) then Exit(); TBlkVyhybka(Blk).ZrusRedukciMenu(); end; procedure TChangeEventCaller.NullSComMenuReduction(Sender:TObject; data:Integer); var blk:TBlk; begin Blky.GetBlkByID(data, blk); if ((blk = nil) or (blk.typ <> _BLK_SCOM)) then Exit(); TBlkSCom(Blk).ZrusRedukciMenu(); end; //////////////////////////////////////////////////////////////////////////////// procedure TChangeEventCaller.RemoveUsekNeprofil(Sender:TObject; data:Integer); var blk:TBlk; caller:^TNPCallerData; begin caller := Pointer(data); Blky.GetBlkByID(caller.usekId, blk); if ((blk = nil) or ((blk.typ <> _BLK_USEK) and (blk.typ <> _BLK_TU))) then Exit(); TBlkUsek(Blk).RemoveNeprofilJC(caller.jcId); FreeMem(caller); end; //////////////////////////////////////////////////////////////////////////////// initialization ceCaller := TChangeEventCaller.Create(); finalization ceCaller.Free(); end.
unit AncestorMain; interface uses DataModul, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, dsdAddOn, dsdDB, Data.DB, Datasnap.DBClient, frxExportXML, frxExportXLS, frxClass, frxExportRTF, Vcl.ActnList, dxBar, cxClasses, Vcl.StdActns, dxSkinsCore, dxSkinsDefaultPainters, dxSkinsdxBarPainter, cxPropertiesStore, Vcl.Menus, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxLabel, dsdAction, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnMan, Vcl.ToolWin, Vcl.ActnCtrls, Vcl.ActnMenus; type TAncestorMainForm = class(TForm) UserSettingsStorageAddOn: TdsdUserSettingsStorageAddOn; StoredProc: TdsdStoredProc; ClientDataSet: TClientDataSet; frxXMLExport: TfrxXMLExport; ActionList: TActionList; actAbout: TAction; actUpdateProgram: TAction; cxPropertiesStore: TcxPropertiesStore; actLookAndFeel: TAction; actImportExportLink: TdsdOpenForm; MainMenu: TMainMenu; miGuide: TMenuItem; miService: TMenuItem; miProtocol: TMenuItem; miExit: TMenuItem; miLine801: TMenuItem; miMovementProtocol: TMenuItem; miUserProtocol: TMenuItem; miLine802: TMenuItem; miLookAndFillSettings: TMenuItem; miAbout: TMenuItem; miUpdateProgramm: TMenuItem; frxXLSExport: TfrxXLSExport; actMovementDesc: TdsdOpenForm; miMovementDesc: TMenuItem; miProtocolAll: TMenuItem; miServiceGuide: TMenuItem; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure actUpdateProgramExecute(Sender: TObject); procedure actAboutExecute(Sender: TObject); procedure actLookAndFeelExecute(Sender: TObject); end; implementation {$R *.dfm} uses ParentForm, Storage, CommonData, MessagesUnit, UtilConst, Math, AboutBoxUnit, UtilConvert, LookAndFillSettings; { TfmBaseForm } procedure TAncestorMainForm.actAboutExecute(Sender: TObject); begin TAboutBox.Create(Self).ShowModal; end; procedure TAncestorMainForm.actLookAndFeelExecute(Sender: TObject); begin TLookAndFillSettingsForm.Create(Screen.ActiveForm).Show; end; procedure TAncestorMainForm.actUpdateProgramExecute(Sender: TObject); var Index: integer; AllParentFormFree: boolean; begin AllParentFormFree := false; while not AllParentFormFree do begin AllParentFormFree := true; for Index := 0 to Screen.FormCount - 1 do if Screen.Forms[Index] is TParentForm then begin AllParentFormFree := false; Screen.Forms[Index].Free; break; end; end; ShowMessage('Программа обновлена'); end; procedure TAncestorMainForm.FormCreate(Sender: TObject); begin UserSettingsStorageAddOn.LoadUserSettings; TranslateForm(Self); end; procedure TAncestorMainForm.FormShow(Sender: TObject); var i, j, k: integer; begin StoredProc.Execute; ClientDataSet.IndexFieldNames := 'ActionName'; for I := 0 to ActionList.ActionCount - 1 do // Проверяем только открытие формы if (ActionList.Actions[i].ClassName = 'TdsdOpenForm') or (ActionList.Actions[i].ClassName = 'TdsdOpenStaticForm') or (ActionList.Actions[i].Name = 'actReport_OLAPSold') then if not ClientDataSet.Locate('ActionName', ActionList.Actions[i].Name, []) then begin TCustomAction(ActionList.Actions[i]).Enabled := false; TCustomAction(ActionList.Actions[i]).Visible := false; end; ClientDataSet.EmptyDataSet; // Отображаем видимые пункты меню for i := 0 to MainMenu.Items.Count - 1 do if Assigned(MainMenu.Items[i].Action) then if not TCustomAction(MainMenu.Items[i].Action).Enabled then MainMenu.Items[i].Visible := false; for i := 0 to ComponentCount - 1 do //Items.Count if Components[i] is TMenuItem then if TMenuItem(Components[i]).Count > 0 then TMenuItem(Components[i]).Visible := false; for k := 1 to 3 do // А теперь бы пройтись по группам меню и отрубить те, у которых нет видимых чайлдов for i := 0 to ComponentCount - 1 do if Components[i] is TMenuItem then if TMenuItem(Components[i]).Count > 0 then for j := 0 to TMenuItem(Components[i]).Count - 1 do if (TMenuItem(Components[i]).Items[j].Visible) and not (TMenuItem(Components[i]).Items[j].IsLine) then begin TMenuItem(Components[i]).Visible := true; break; end; if not SameText(gc_User.Login, '') then // Caption := Caption + ' - Пользователь: ' + gc_User.Login; Caption := Caption + ' <' + gc_User.Login + '>'; end; end.
{* ***************************************************************************** PROYECTO FACTURACION ELECTRONICA Copyright (C) 2010-2014 - Bambú Code SA de CV - Ing. Luis Carrasco Esta clase representa la estructura de un PAC para basarse en ella y poder implementar a un nuevo PAC. Se deben de implementar los métodos definidos en esta clase. Este archivo pertenece al proyecto de codigo abierto de Bambú Code: http://bambucode.com/codigoabierto La licencia de este código fuente se encuentra en: http://github.com/bambucode/tfacturaelectronica/blob/master/LICENCIA ***************************************************************************** *} unit ProveedorAutorizadoCertificacion; interface uses Classes, SysUtils, FacturaTipos; type // Definimos el tipo nativo en Delphi para enviar el XML al PAC TTipoComprobanteXML = String; {$REGION 'Documentation'} /// <summary> /// Clase padre abstracta que representa a un proveedor autorizado de certificacion /// (PAC) y los métodos de timbrado y cancelación que todos deben de /// soportar. Todas las implementaciones de PAC deben heredar esta clase /// </summary> {$ENDREGION} TProveedorAutorizadoCertificacion = class protected function getNombre() : String; virtual; abstract; public property Nombre : String read getNombre; constructor Create(const aDominioWebService: string; const aDominioWebServiceSeguridad: String = ''; const aDominioWebServiceRespaldo: String = ''; const aDominioWebServiceCancelacion: string = ''); virtual; abstract; procedure AsignarCredenciales(const aCredenciales: TFEPACCredenciales); overload; virtual; abstract; procedure AsignarCredenciales(const aCredenciales, aCredencialesIntegrador: TFEPACCredenciales); overload; virtual; abstract; function ObtenerAcuseDeCancelacion(const aDocumento: TTipoComprobanteXML): string; virtual; abstract; function CancelarDocumento(const aDocumento: TTipoComprobanteXML): Boolean; virtual; abstract; function TimbrarDocumento(const aDocumento: TTipoComprobanteXML): TFETimbre; virtual; abstract; function AgregaCliente(const aNuevoEmisor: TFEContribuyente): String; virtual; abstract; function EditaCliente(const Activar: Boolean;const aRFC:String):String; virtual; abstract; function BorraCliente(const aRFC: String):String; virtual; abstract; function SaldoCliente(const aRFC: String) : Integer; virtual; abstract; end; implementation end.
{ FOR TESTING ONLY (Bukan bagian dari spesifikasi tugas) } unit uDEBUG; interface uses uType; { PROSEDUR } procedure ld ( var dBuku : bukuArr; var dUser : userArr; var dPeminjaman : peminjamanArr; var dPengembalian : pengembalianArr; var dKehilangan : kehilanganArr ); procedure sv ( dBuku : bukuArr; dUser : userArr; dPeminjaman : peminjamanArr; dPengembalian : pengembalianArr; dKehilangan : kehilanganArr ); implementation uses CSVtools; { PROSEDUR } procedure ld ( { Menggunakan array-array data sebagai parameter, pass by reference } var dBuku : bukuArr; var dUser : userArr; var dPeminjaman : peminjamanArr; var dPengembalian : pengembalianArr; var dKehilangan : kehilanganArr ); var { Filename masing-masing data } fBuku, fUser, fPeminjaman, fPengembalian, fKehilangan : string; begin { Meminta input dari pengguna } fBuku := 'buku.csv'; fUser := 'user.csv'; fPeminjaman := 'peminjaman.csv'; fPengembalian := 'pengembalian.csv'; fKehilangan := 'kehilangan.csv'; { Memasukkan data ke file CSV masing-masing } ctRead(dBuku, fBuku); ctRead(dUser, fUser); ctRead(dPeminjaman, fPeminjaman); ctRead(dPengembalian, fPengembalian); ctRead(dKehilangan, fKehilangan); writeln(); writeln('[TESTING MODE]'); writeln('File perpustakaan berhasil dimuat!'); end; procedure sv ( { Menggunakan array-array data sebagai parameter, pass by value } dBuku : bukuArr; dUser : userArr; dPeminjaman : peminjamanArr; dPengembalian : pengembalianArr; dKehilangan : kehilanganArr ); var { Filename masing-masing data } fBuku, fUser, fPeminjaman, fPengembalian, fKehilangan : string; begin { Meminta input dari pengguna } fBuku := 'buku.csv'; fUser := 'user.csv'; fPeminjaman := 'peminjaman.csv'; fPengembalian := 'pengembalian.csv'; fKehilangan := 'kehilangan.csv'; { Memasukkan data ke file CSV masing-masing } ctWrite(dBuku, fBuku); ctWrite(dUser, fUser); ctWrite(dPeminjaman, fPeminjaman); ctWrite(dPengembalian, fPengembalian); ctWrite(dKehilangan, fKehilangan); writeln(); writeln('[TESTING MODE]'); writeln('Data berhasil disimpan!'); end; end.
unit UFrameDriver; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VirtualTrees, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.Buttons, RzTabs, Vcl.Menus, ShellAPI, Vcl.ImgList, IOUtils, IniFiles, ActiveX, Vcl.StdCtrls, dirnotify, UMainForm, Generics.Collections; type TFrameDriver = class(TFrame) Splitter1: TSplitter; plRight: TPanel; vstLocal: TVirtualStringTree; vstNetwork: TVirtualStringTree; plLeft: TPanel; plLocalBottom: TPanel; plLocalComputer: TPanel; ilMyComputer: TImage; sbMyComputer: TSpeedButton; plLocalStatus: TPanel; plNetworkBottom: TPanel; plNetworkStatus: TPanel; plNetworkDriver: TPanel; ilNetworkDriver: TImage; sbNetwork: TSpeedButton; plCopy: TPanel; plCopyBottom: TPanel; plSplit: TPanel; tmrLeftEnter: TTimer; tmrRightEnter: TTimer; pmLocalFolder: TPopupMenu; miLocalRefresh: TMenuItem; miLocalNewFolder: TMenuItem; miLocalExplorer: TMenuItem; pmNetworkFolder: TPopupMenu; miNetworkNewFolder: TMenuItem; miNetworkRefresh: TMenuItem; miNetworkExplorer: TMenuItem; pmLocalFile: TPopupMenu; miLocalZip: TMenuItem; miLocalRename: TMenuItem; miLocalDelete: TMenuItem; pmNeworkFile: TPopupMenu; miNetworkZip: TMenuItem; miNetworkRename: TMenuItem; miNetworkDelete: TMenuItem; PcCopyUtil: TRzPageControl; tsCopy: TRzTabSheet; tsCopyAfter: TRzTabSheet; PcCopy: TRzPageControl; tsCopyLeft: TRzTabSheet; plCopyLeft: TPanel; sbCopyLeft: TSpeedButton; ilCopyLeft: TImage; tsCopyRight: TRzTabSheet; plRightCopy: TPanel; sbCopyRight: TSpeedButton; ilCopyRight: TImage; tsCopyLeftDisable: TRzTabSheet; ilCopyLeftDisable: TImage; tsCopyRightDisable: TRzTabSheet; ilCopyRightDisable: TImage; PcCopyAfter: TRzPageControl; tsCopyLeftAfter: TRzTabSheet; tsCopyRightAfter: TRzTabSheet; ilCopyLeftAfter: TImage; ilCopyRightAfter: TImage; plBottom: TPanel; vstFileJob: TVirtualStringTree; edtLocalSearch: TButtonedEdit; tmrLocalSearch: TTimer; edtNetworkSearch: TButtonedEdit; tmrNetworkSearch: TTimer; sbLocalStatus: TSpeedButton; sbNetworkStatus: TSpeedButton; plNetworkStatusCopy: TPanel; vstLocalHistory: TVirtualStringTree; plLocal: TPanel; slLocalHistory: TSplitter; pmLocalHistory: TPopupMenu; miHistoryRemove: TMenuItem; il16: TImageList; procedure vstLocalGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure vstLocalGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); procedure vstNetworkGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); procedure vstNetworkGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure vstLocalDblClick(Sender: TObject); procedure vstNetworkDblClick(Sender: TObject); procedure ilMyComputerMouseEnter(Sender: TObject); procedure sbMyComputerMouseLeave(Sender: TObject); procedure sbNetworkMouseLeave(Sender: TObject); procedure ilNetworkDriverMouseEnter(Sender: TObject); procedure sbNetworkClick(Sender: TObject); procedure ilCopyLeftMouseEnter(Sender: TObject); procedure sbCopyLeftMouseLeave(Sender: TObject); procedure ilCopyRightMouseEnter(Sender: TObject); procedure sbCopyRightMouseLeave(Sender: TObject); procedure vstLocalChange(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure vstNetworkChange(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure tmrLeftEnterTimer(Sender: TObject); procedure ilCopyLeftMouseLeave(Sender: TObject); procedure tmrRightEnterTimer(Sender: TObject); procedure ilCopyRightMouseLeave(Sender: TObject); procedure miLocalRefreshClick(Sender: TObject); procedure miNetworkRefreshClick(Sender: TObject); procedure sbCopyLeftClick(Sender: TObject); procedure sbCopyRightClick(Sender: TObject); procedure miLocalExplorerClick(Sender: TObject); procedure miNetworkExplorerClick(Sender: TObject); procedure miLocalNewFolderClick(Sender: TObject); procedure miNetworkNewFolderClick(Sender: TObject); procedure vstLocalMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure vstNetworkMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure miNetworkDeleteClick(Sender: TObject); procedure miLocalDeleteClick(Sender: TObject); procedure miLocalRenameClick(Sender: TObject); procedure miNetworkRenameClick(Sender: TObject); procedure miLocalZipClick(Sender: TObject); procedure miNetworkZipClick(Sender: TObject); procedure ilCopyLeftAfterMouseLeave(Sender: TObject); procedure ilCopyRightAfterMouseLeave(Sender: TObject); procedure vstLocalKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure vstNetworkKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure vstFileJobGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure vstFileJobGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); procedure sbMyComputerClick(Sender: TObject); procedure vstLocalCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); procedure vstLocalHeaderClick(Sender: TVTHeader; HitInfo: TVTHeaderHitInfo); procedure vstNetworkHeaderClick(Sender: TVTHeader; HitInfo: TVTHeaderHitInfo); procedure vstNetworkCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); procedure vstLocalDragOver(Sender: TBaseVirtualTree; Source: TObject; Shift: TShiftState; State: TDragState; Pt: TPoint; Mode: TDropMode; var Effect: Integer; var Accept: Boolean); procedure vstNetworkDragOver(Sender: TBaseVirtualTree; Source: TObject; Shift: TShiftState; State: TDragState; Pt: TPoint; Mode: TDropMode; var Effect: Integer; var Accept: Boolean); procedure vstLocalDragDrop(Sender: TBaseVirtualTree; Source: TObject; DataObject: IDataObject; Formats: TFormatArray; Shift: TShiftState; Pt: TPoint; var Effect: Integer; Mode: TDropMode); procedure vstNetworkDragDrop(Sender: TBaseVirtualTree; Source: TObject; DataObject: IDataObject; Formats: TFormatArray; Shift: TShiftState; Pt: TPoint; var Effect: Integer; Mode: TDropMode); procedure edtLocalSearchKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edtLocalSearchKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure tmrLocalSearchTimer(Sender: TObject); procedure edtNetworkSearchKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edtNetworkSearchKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure tmrNetworkSearchTimer(Sender: TObject); procedure edtLocalSearchRightButtonClick(Sender: TObject); procedure edtNetworkSearchRightButtonClick(Sender: TObject); procedure sbLocalStatusMouseLeave(Sender: TObject); procedure plLocalStatusMouseEnter(Sender: TObject); procedure sbLocalStatusClick(Sender: TObject); procedure plNetworkStatusMouseEnter(Sender: TObject); procedure sbNetworkStatusMouseLeave(Sender: TObject); procedure sbNetworkStatusClick(Sender: TObject); procedure plNetworkStatusCopyMouseLeave(Sender: TObject); procedure vstLocalHistoryGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); procedure vstLocalHistoryGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure vstLocalHistoryDblClick(Sender: TObject); procedure miHistoryRemoveClick(Sender: TObject); procedure vstLocalHistoryChange(Sender: TBaseVirtualTree; Node: PVirtualNode); private ControlPath, DriverPath : string; LocalPath, NetworkPath : string; public procedure IniFrame; procedure SetControlPath( _ControlPath, _DriverPath : string ); procedure SetLocalPath( _LocalPath : string ); procedure SetNetworkPath( _NetworkPath : string ); end; {$Region ' 界面 数据 ' } // 本地数据 TVstLocalData = record public FilePath : WideString; IsFile : Boolean; FileSize : Int64; FileTime : TDateTime; public ShowName, ShowSize, ShowTime : WideString; ShowIcon : Integer; public IsLocked : Boolean; end; PVstLocalData = ^TVstLocalData; // 网络数据 TVstNetworkData = record public FilePath : WideString; IsFile : Boolean; FileSize : Int64; FileTime : TDateTime; public ShowName, ShowSize, ShowTime : WideString; ShowIcon : Integer; public IsLocked : Boolean; end; PVstNetworkData = ^TVstNetworkData; // 文件任务数据 TVstFileJobData = record public FilePath, ActionType : WideString; public ShowName, ActionName : WideString; ShowIcon, ActionIcon : Integer; public ActionID : WideString; end; PVstFileJobData = ^TVstFileJobData; // 本地历史数据 TVstLocalHistoryData = record public FolderPath : WideString; public ShowName, ShowDir : WideString; ShowIcon : Integer; end; PVstLocalHistoryData = ^TVstLocalHistoryData; {$EndRegion} {$Region ' 界面 操作 ' } // Frame Api TFaceFrameDriverApi = class public FrameDriver : TFrameDriver; public procedure Activate( _FrameDriver : TFrameDriver ); public procedure SetLocalPath( LocalPath : string ); procedure SetNetworkPath( NetworkPath : string ); public function ReadLocalPath : string; function ReadNetworkPath : string; function ReadDriverPath : string; public procedure UnvisibleLocalSearch; procedure UnvisibleNetworkSearch; function ReadLocalSerach : string; function ReadNetworkSerach : string; end; // 添加参数 TFileAddParams = record public FilePath : string; IsFile : Boolean; FileSize : Int64; FileTime : TDateTime; end; // 本地文件 TFaceLocalDriverApi = class public vstLocal : TVirtualStringTree; public procedure Activate( _vstLocal : TVirtualStringTree ); public procedure Clear; function ReadIsExist( FilePath : string ): Boolean; procedure Add( Params : TFileAddParams ); procedure AddDriver( Params : TFileAddParams ); procedure AddParentFolder( ParentPath : string ); procedure Insert( Params : TFileAddParams ); procedure Select( FilePath : string ); procedure CancelSelect; procedure Search( FileName : string ); procedure Remove( FilePath : string ); public function ReadSelectList : TStringList; function ReadPathList : TStringList; function ReadFocusePath : string; private function ReadNode( FilePath : string ): PVirtualNode; function CreateInsertNode : PVirtualNode; end; // 网络文件 TFaceNetworkDriverApi = class public vstNetwork : TVirtualStringTree; public procedure Activate( _vstNetwork : TVirtualStringTree ); public procedure Clear; function ReadIsExist( FilePath : string ): Boolean; procedure Add( Params : TFileAddParams ); procedure AddParentFolder( ParentPath : string ); procedure Insert( Params : TFileAddParams ); procedure Select( FilePath : string ); procedure CancelSelect; procedure Search( FileName : string ); procedure Remove( FilePath : string ); public function ReadSelectList : TStringList; function ReadPathList : TStringList; function ReadFocusePath : string; private function ReadNode( FilePath : string ): PVirtualNode; function CreateInsertNode : PVirtualNode; end; // 本地磁盘状态 TFaceLocalStatusApi = class public plLocalStatus : TPanel; sbLocalStatus : TSpeedButton; public procedure Activate( _plLocalStatus : TPanel; _sbLocalStatus : TSpeedButton ); public procedure ShowPath( FolderPath : string ); end; // 网络磁盘状态 TFaceNetworkStatusApi = class public plNetworkStatus : TPanel; sbNetworkStatus : TSpeedButton; public procedure Activate( _plNetworkStatus : TPanel; _sbNetworkStatus : TSpeedButton ); public procedure ShowPath( FolderPath : string ); end; // 文件任务列表 TFaceFileJobApi = class public vstFileJob : TVirtualStringTree; PlFileJob : TPanel; public procedure Activate( _vstFileJob : TVirtualStringTree; _PlFileJob : TPanel ); public function AddFileJob( FilePath, ActionType : string ): string; procedure RemoveFileJob( ActionID : string ); private function ReadNode( ActionID : string ): PVirtualNode; end; // 本地访问历史 TFaceLocalHistoryApi = class public vstLocalHistory : TVirtualStringTree; slLocalHistory : TSplitter; public procedure Activate( _vstLocalHistory : TVirtualStringTree; _slLocalHistory : TSplitter ); public function ReadIsExist( FolderPath : string ): Boolean; procedure Add( FolderPath : string ); procedure Remove( FolderPath : string ); public function ReadHistoryCount : Integer; procedure MoveToTop( FolderPath : string ); procedure RemoveLastNode; function ReadList : TStringList; function ReadSelectList : TStringList; procedure SetVisible( Isvisible : Boolean ); private function ReadNode( FolderPath : string ): PVirtualNode; end; {$EndRegion} {$Region ' 用户 操作 ' } // 复制信息 TCopyPathInfo = class public SourcePath, DesPath : string; public constructor Create( _SourcePath, _DesPath : string ); end; TCopyPathList = class( TObjectList<TCopyPathInfo> )end; // 复制冲突处理 TFileCopyHandle = class public ControlPath : string; IsLocal : Boolean; public SourceList : TStringList; DesFolder : string; public CopyPathList : TCopyPathList; public constructor Create( _SourceFileList : TStringList; _DesFolder : string ); procedure SetControlPath( _ControlPath : string; _IsLocal : Boolean ); procedure Update; destructor Destroy; override; private function IsExistConflict : Boolean; function ConfirmConflict : Boolean; procedure CopyHandle; end; // 本地文件夹 UserLocalDriverApi = class public class procedure EnterFolder( FolderPath, ControlPath : string ); class procedure RefreshFolder( ControlPath : string ); class procedure CopyFile( ControlPath : string ); class procedure NewFolder( ControlPath : string ); class procedure DeleteFile( ControlPath : string ); class procedure RenameFile( ControlPath : string ); class procedure ZipFile( ControlPath : string ); class procedure SearchFile( ControlPath : string ); public class procedure AddFile( ControlPath, FilePath : string ); class procedure RemoveFile( ControlPath, FilePath : string ); class procedure CancelSelect( ControlPath : string ); class procedure Select( ControlPath, FilePath : string ); class function ReadFileList( ControlPath : string ): TStringList; public class procedure CopyNow( ControlPath: string; PathList : TStringList ); private class function ControlPage( ControlPath : string ): Boolean; end; // 网络文件夹 UserNetworkDriverApi = class public class procedure EnterFolder( FolderPath, ControlPath : string ); class procedure RefreshFolder( ControlPath : string ); class procedure CopyFile( ControlPath : string ); class procedure NewFolder( ControlPath : string ); class procedure DeleteFile( ControlPath : string ); class procedure RenameFile( ControlPath : string ); class procedure ZipFile( ControlPath : string ); class procedure SearchFile( ControlPath : string ); public class procedure AddFile( ControlPath, FilePath : string ); class procedure RemoveFile( ControlPath, FilePath : string ); class procedure CancelSelect( ControlPath : string ); class procedure Select( ControlPath, FilePath : string ); class function ReadFileList( ControlPath : string ): TStringList; private class function ControlPage( ControlPath : string ): Boolean; end; // Frame Api UserFrameDriverApi = class public class procedure LoadFromData( UsbFrameInfo : TUsbFrameInfo ); class procedure SaveToData( UsbFrameInfo : TUsbFrameInfo ); class procedure SaveIni( DriverID : string; IniFile : TIniFile; FrameIndex : Integer ); class procedure LoadIni( DriverID : string; IniFile : TIniFile; FrameIndex : Integer ); class procedure SelectFrame( ControlPath : string ); private class function ControlPage( ControlPath : string ): Boolean; end; // 本地历史 Api UserLocalHistoryApi = class public class procedure AddHistory( ControlPath, FolderPath : string ); class procedure RemoveHistory( ControlPath, FolderPath : string ); class function ReadSelectList( ControlPath : string ) : TStringList; private class function ControlPage( ControlPath : string ): Boolean; end; {$EndRegion} var FaceFrameDriverApi : TFaceFrameDriverApi; FaceLocalDriverApi : TFaceLocalDriverApi; FaceNetworkDriverApi : TFaceNetworkDriverApi; FaceLocalStatusApi : TFaceLocalStatusApi; FaceNetworkStatusApi : TFaceNetworkStatusApi; FaceFileJobApi : TFaceFileJobApi; FaceLocalHistoryApi : TFaceLocalHistoryApi; var FileJob_ActionID : Int64 = 0; const VstLocal_FileName = 0; VstLocal_FileSize = 1; VstLocal_FileTime = 2; const VstNetwork_FileName = 0; VstNetwork_FileSize = 1; VstNetwork_FileTime = 2; const VstHistory_FileName = 0; VstHistory_FileDir = 1; const Caption_ParentFolder = '返回上一层'; Caption_MyComputer = '我的电脑'; const NewFolder_DefaultName = '新建文件夹'; NewFolder_Title : string = '新建文件夹'; NewFolder_Name : string = '输入文件夹名'; Rename_Title : string = '重命名'; Rename_Name : string = '输入文件名'; Rename_Exist : string = '路径已存在'; DeleteFile_Comfirm : string = '确定要删除吗?'; const EnterFolder_Title = '打开文件夹'; EnterFolder_Name = '文件夹路径'; EnterFolder_NotExist = '路径不存在'; const Compressed_NewName : string = '压缩文件'; const ActionType_CopyLeft = 'CopyLeft'; ActionType_CopyRight = 'CopyRight'; ActionType_Delete = 'Delete'; ActionType_Zip = 'Zip'; AcionTypeShow_Copy = '等待复制'; AcionTypeShow_Delete = '等待删除'; AcionTypeShow_Zip = '等待压缩'; const Ini_FrameDriver = 'FrameDriver'; Ini_DriverID = 'DriverID'; Ini_LocalFolder = 'LocalFolder'; Ini_NetworkFolder = 'NetworkFolder'; Ini_LocalWidth = 'LocalWidth'; Ini_LocalHistoryCount = 'LocalHistoryCount'; Ini_LocalHistory = 'LocalHistory'; Ini_LocalHistoryHeigh = 'LocalHistoryHeigh'; implementation uses UMyUtils, UMyFaceThread, UFileThread, UFileWatchThread, UFormConflict, Clipbrd; {$R *.dfm} { TFaceLocalDriverApi } procedure TFaceLocalDriverApi.Activate(_vstLocal: TVirtualStringTree); begin vstLocal := _vstLocal; end; procedure TFaceLocalDriverApi.Add(Params: TFileAddParams); var FileNode : PVirtualNode; NodeData : PVstLocalData; begin FileNode := vstLocal.AddChild( vstLocal.RootNode ); NodeData := vstLocal.GetNodeData( FileNode ); NodeData.FilePath := Params.FilePath; NodeData.IsFile := Params.IsFile; NodeData.FileSize := Params.FileSize; NodeData.FileTime := Params.FileTime; NodeData.ShowName := MyFilePath.getName( Params.FilePath ); NodeData.ShowTime := DateTimeToStr( Params.FileTime ); if Params.IsFile then NodeData.ShowSize := MySizeUtil.getFileSizeStr( Params.FileSize ) else NodeData.ShowSize := ''; NodeData.ShowIcon := MyIcon.getPathIcon( Params.FilePath, Params.IsFile ); NodeData.IsLocked := False; end; procedure TFaceLocalDriverApi.AddDriver(Params: TFileAddParams); var FileNode : PVirtualNode; NodeData : PVstLocalData; begin FileNode := vstLocal.AddChild( vstLocal.RootNode ); NodeData := vstLocal.GetNodeData( FileNode ); NodeData.FilePath := Params.FilePath; NodeData.IsFile := Params.IsFile; NodeData.FileSize := Params.FileSize; NodeData.FileTime := Params.FileTime; NodeData.ShowName := MyFilePath.getDriverName( Params.FilePath ); NodeData.ShowTime := ''; NodeData.ShowSize := ''; NodeData.ShowIcon := MyIcon.getPathIcon( Params.FilePath, Params.IsFile ); NodeData.IsLocked := False; end; procedure TFaceLocalDriverApi.AddParentFolder(ParentPath: string); var FileNode : PVirtualNode; NodeData : PVstLocalData; begin FileNode := vstLocal.InsertNode( vstLocal.RootNode, amAddChildFirst ); NodeData := vstLocal.GetNodeData( FileNode ); NodeData.FilePath := ParentPath; NodeData.IsFile := False; NodeData.ShowName := Caption_ParentFolder; NodeData.ShowSize := ''; NodeData.ShowTime := ''; NodeData.ShowIcon := My16IconUtil.getBack; NodeData.IsLocked := True; end; procedure TFaceLocalDriverApi.CancelSelect; var SelectNode : PVirtualNode; begin SelectNode := vstLocal.RootNode.FirstChild; while Assigned( SelectNode ) do begin vstLocal.Selected[ SelectNode ] := False; SelectNode := SelectNode.NextSibling; end; end; procedure TFaceLocalDriverApi.Clear; begin vstLocal.Clear; end; function TFaceLocalDriverApi.CreateInsertNode: PVirtualNode; var FirstNode : PVirtualNode; NodeData : PVstLocalData; begin FirstNode := vstLocal.RootNode.FirstChild; if Assigned( FirstNode ) then begin NodeData := vstLocal.GetNodeData( FirstNode ); if NodeData.IsLocked then Result := vstLocal.InsertNode( FirstNode, amInsertAfter ) else Result := vstLocal.InsertNode( vstLocal.RootNode, amAddChildFirst ); end else Result := vstLocal.InsertNode( vstLocal.RootNode, amAddChildFirst ); end; procedure TFaceLocalDriverApi.Insert(Params: TFileAddParams); var FileNode : PVirtualNode; NodeData : PVstLocalData; begin FileNode := CreateInsertNode; NodeData := vstLocal.GetNodeData( FileNode ); NodeData.FilePath := Params.FilePath; NodeData.IsFile := Params.IsFile; NodeData.FileSize := Params.FileSize; NodeData.FileTime := Params.FileTime; NodeData.ShowName := MyFilePath.getName( Params.FilePath ); NodeData.ShowTime := DateTimeToStr( Params.FileTime ); if Params.IsFile then NodeData.ShowSize := MySizeUtil.getFileSizeStr( Params.FileSize ) else NodeData.ShowSize := ''; NodeData.ShowIcon := MyIcon.getPathIcon( Params.FilePath, Params.IsFile ); NodeData.IsLocked := False; end; function TFaceLocalDriverApi.ReadFocusePath: string; var NodeData : PVstLocalData; begin Result := ''; if not Assigned( vstLocal.FocusedNode ) then Exit; NodeData := vstLocal.GetNodeData( vstLocal.FocusedNode ); Result := NodeData.FilePath; end; function TFaceLocalDriverApi.ReadIsExist(FilePath: string): Boolean; begin Result := Assigned( ReadNode( FilePath ) ); end; function TFaceLocalDriverApi.ReadNode(FilePath: string): PVirtualNode; var SelectNode : PVirtualNode; NodeData : PVstLocalData; begin Result := nil; SelectNode := vstLocal.RootNode.FirstChild; while Assigned( SelectNode ) do begin NodeData := vstLocal.GetNodeData( SelectNode ); if NodeData.FilePath = FilePath then begin Result := SelectNode; Break; end; SelectNode := SelectNode.NextSibling; end; end; function TFaceLocalDriverApi.ReadPathList: TStringList; var SelectNode : PVirtualNode; NodeData : PVstLocalData; begin Result := TStringList.Create; SelectNode := vstLocal.RootNode.FirstChild; while Assigned( SelectNode ) do begin NodeData := vstLocal.GetNodeData( SelectNode ); if not NodeData.IsLocked then Result.Add( NodeData.FilePath ); SelectNode := SelectNode.NextSibling; end; end; function TFaceLocalDriverApi.ReadSelectList: TStringList; var SelectNode : PVirtualNode; NodeData : PVstLocalData; begin Result := TStringList.Create; SelectNode := vstLocal.GetFirstSelected; while Assigned( SelectNode ) do begin NodeData := vstLocal.GetNodeData( SelectNode ); if not NodeData.IsLocked then Result.Add( NodeData.FilePath ); SelectNode := vstLocal.GetNextSelected( SelectNode ); end; end; procedure TFaceLocalDriverApi.Remove(FilePath: string); var SelectNode : PVirtualNode; begin SelectNode := ReadNode( FilePath ); if not Assigned( SelectNode ) then Exit; vstLocal.DeleteNode( SelectNode ); end; procedure TFaceLocalDriverApi.Search(FileName: string); var SelectNode : PVirtualNode; NodeData : PVstLocalData; IsVisible, IsSearchAll : Boolean; begin FileName := LowerCase( FileName ); IsSearchAll := FileName = ''; // 过滤 SelectNode := vstLocal.RootNode.FirstChild; while Assigned( SelectNode ) do begin NodeData := vstLocal.GetNodeData( SelectNode ); IsVisible := IsSearchAll or NodeData.IsLocked or ( Pos( FileName, LowerCase( string( NodeData.ShowName ) ) ) > 0 ); vstLocal.IsVisible[ SelectNode ] := IsVisible; vstLocal.Selected[ SelectNode ] := False; SelectNode := SelectNode.NextSibling; end; // 全选 if IsSearchAll then Exit; // 默认选择第一个 SelectNode := vstLocal.GetFirstVisible; if not Assigned( SelectNode ) then Exit; NodeData := vstLocal.GetNodeData( SelectNode ); if NodeData.IsLocked then begin SelectNode := vstLocal.GetNextVisible( SelectNode ); if not Assigned( SelectNode ) then Exit; end; vstLocal.Selected[ SelectNode ] := True; vstLocal.FocusedNode := SelectNode; end; procedure TFaceLocalDriverApi.Select(FilePath: string); var SelectNode : PVirtualNode; begin SelectNode := ReadNode( FilePath ); if not Assigned( SelectNode ) then Exit; vstLocal.Selected[ SelectNode ] := True; vstLocal.FocusedNode := SelectNode; end; { TFrameDriver } procedure TFrameDriver.edtLocalSearchKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin // 回车 if Key = VK_RETURN then begin if Assigned( vstLocal.FocusedNode ) and vstLocal.IsVisible[ vstLocal.FocusedNode ] then begin vstLocalDblClick( Sender ); vstLocal.SetFocus; end; Exit; end; // 向上/向下 if ( Key = VK_UP ) or ( Key = VK_DOWN ) then begin vstLocal.SetFocus; Exit; end; // 启动定时器 if not tmrLocalSearch.Enabled then tmrLocalSearch.Enabled := True; end; procedure TFrameDriver.edtLocalSearchKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin // 有输入则显示关闭按钮 edtLocalSearch.RightButton.Visible := edtLocalSearch.Text <> ''; end; procedure TFrameDriver.edtLocalSearchRightButtonClick(Sender: TObject); begin edtLocalSearch.Text := ''; tmrLocalSearch.Enabled := True; edtLocalSearch.RightButton.Visible := False; end; procedure TFrameDriver.edtNetworkSearchKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var FirstVisibleNode : PVirtualNode; begin // 回车 if Key = VK_RETURN then begin if Assigned( vstNetwork.FocusedNode ) and vstNetwork.IsVisible[ vstNetwork.FocusedNode ] then begin vstNetworkDblClick( Sender ); vstNetwork.SetFocus; end; Exit; end; // 向上/向下 if ( Key = VK_UP ) or ( Key = VK_DOWN ) then begin vstNetwork.SetFocus; Exit; end; // 启动定时器 if not tmrNetworkSearch.Enabled then tmrNetworkSearch.Enabled := True; end; procedure TFrameDriver.edtNetworkSearchKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin // 有输入则显示关闭按钮 edtNetworkSearch.RightButton.Visible := edtNetworkSearch.Text <> ''; end; procedure TFrameDriver.edtNetworkSearchRightButtonClick(Sender: TObject); begin edtNetworkSearch.Text := ''; tmrNetworkSearch.Enabled := True; edtNetworkSearch.RightButton.Visible := False; end; procedure TFrameDriver.ilCopyLeftAfterMouseLeave(Sender: TObject); begin PcCopyUtil.ActivePage := tsCopy; end; procedure TFrameDriver.ilCopyLeftMouseEnter(Sender: TObject); begin tmrLeftEnter.Enabled := True; end; procedure TFrameDriver.ilCopyLeftMouseLeave(Sender: TObject); begin tmrLeftEnter.Enabled := False; end; procedure TFrameDriver.ilCopyRightAfterMouseLeave(Sender: TObject); begin PcCopyUtil.ActivePage := tsCopy; end; procedure TFrameDriver.ilCopyRightMouseEnter(Sender: TObject); begin tmrRightEnter.Enabled := True; end; procedure TFrameDriver.ilCopyRightMouseLeave(Sender: TObject); begin tmrRightEnter.Enabled := False; end; procedure TFrameDriver.ilMyComputerMouseEnter(Sender: TObject); begin ilMyComputer.Visible := False; sbMyComputer.Visible := True; end; procedure TFrameDriver.ilNetworkDriverMouseEnter(Sender: TObject); begin ilNetworkDriver.Visible := False; sbNetwork.Visible := True; end; procedure TFrameDriver.IniFrame; begin vstLocal.NodeDataSize := SizeOf( TVstLocalData ); vstLocal.Images := MyIcon.getSysIcon; vstNetwork.NodeDataSize := SizeOf( TVstNetworkData ); vstNetwork.Images := MyIcon.getSysIcon; vstFileJob.NodeDataSize := SizeOf( TVstFileJobData ); vstFileJob.Images := MyIcon.getSysIcon; vstLocalHistory.NodeDataSize := SizeOf( TVstLocalHistoryData ); vstLocalHistory.Images := MyIcon.getSysIcon; PcCopyUtil.ActivePage := tsCopy; PcCopy.ActivePage := tsCopyRight; plRight.Width := ( frmMain.Width - plCopy.Width ) div 2; end; procedure TFrameDriver.miHistoryRemoveClick(Sender: TObject); var SelectList : TStringList; i: Integer; begin SelectList := UserLocalHistoryApi.ReadSelectList( ControlPath ); for i := 0 to SelectList.Count - 1 do UserLocalHistoryApi.RemoveHistory( ControlPath, SelectList[i] ); SelectList.Free; end; procedure TFrameDriver.miLocalDeleteClick(Sender: TObject); begin UserLocalDriverApi.DeleteFile( ControlPath ); end; procedure TFrameDriver.miLocalExplorerClick(Sender: TObject); begin MyExplorer.ShowFolder( LocalPath ); end; procedure TFrameDriver.miLocalNewFolderClick(Sender: TObject); begin UserLocalDriverApi.NewFolder( ControlPath ); end; procedure TFrameDriver.miLocalRefreshClick(Sender: TObject); begin UserLocalDriverApi.RefreshFolder( ControlPath ); end; procedure TFrameDriver.miLocalRenameClick(Sender: TObject); begin UserLocalDriverApi.RenameFile( ControlPath ); end; procedure TFrameDriver.miLocalZipClick(Sender: TObject); begin UserLocalDriverApi.ZipFile( ControlPath ); end; procedure TFrameDriver.miNetworkDeleteClick(Sender: TObject); begin UserNetworkDriverApi.DeleteFile( ControlPath ); end; procedure TFrameDriver.miNetworkExplorerClick(Sender: TObject); begin MyExplorer.ShowFolder( NetworkPath ); end; procedure TFrameDriver.miNetworkNewFolderClick(Sender: TObject); begin UserNetworkDriverApi.NewFolder( ControlPath ); end; procedure TFrameDriver.miNetworkRefreshClick(Sender: TObject); begin UserNetworkDriverApi.RefreshFolder( ControlPath ); end; procedure TFrameDriver.miNetworkRenameClick(Sender: TObject); begin UserNetworkDriverApi.RenameFile( ControlPath ); end; procedure TFrameDriver.miNetworkZipClick(Sender: TObject); begin UserNetworkDriverApi.ZipFile( ControlPath ); end; procedure TFrameDriver.plLocalStatusMouseEnter(Sender: TObject); begin sbLocalStatus.Visible := True; end; procedure TFrameDriver.plNetworkStatusCopyMouseLeave(Sender: TObject); begin plNetworkStatusCopy.Visible := False; plNetworkStatus.Caption := sbNetworkStatus.Caption; end; procedure TFrameDriver.plNetworkStatusMouseEnter(Sender: TObject); begin sbNetworkStatus.Visible := True; end; procedure TFrameDriver.sbCopyLeftClick(Sender: TObject); begin // 开始复制 UserLocalDriverApi.CopyFile( ControlPath ); // 切换 Disable PcCopyUtil.ActivePage := tsCopyAfter; PcCopyAfter.ActivePage := tsCopyLeftAfter; end; procedure TFrameDriver.sbCopyLeftMouseLeave(Sender: TObject); begin sbCopyLeft.Visible := False; ilCopyLeft.Visible := True; end; procedure TFrameDriver.sbCopyRightClick(Sender: TObject); begin // 开始复制文件 UserNetworkDriverApi.CopyFile( ControlPath ); // 切换 Disable PcCopyUtil.ActivePage := tsCopyAfter; PcCopyAfter.ActivePage := tsCopyRightAfter; end; procedure TFrameDriver.sbCopyRightMouseLeave(Sender: TObject); begin sbCopyRight.Visible := False; ilCopyRight.Visible := True; end; procedure TFrameDriver.sbLocalStatusClick(Sender: TObject); var InputStr, OldInputStr : string; begin InputStr := sbLocalStatus.Caption; OldInputStr := InputStr; if not InputQuery( EnterFolder_Title, EnterFolder_Name, InputStr ) then Exit; if FileExists( InputStr ) then InputStr := ExtractFileDir( InputStr ); if not DirectoryExists( InputStr ) then MyMessageForm.ShowWarnning( EnterFolder_NotExist ) else if InputStr <> OldInputStr then UserLocalDriverApi.EnterFolder( InputStr, ControlPath ); end; procedure TFrameDriver.sbLocalStatusMouseLeave(Sender: TObject); begin sbLocalStatus.Visible := False; end; procedure TFrameDriver.sbMyComputerClick(Sender: TObject); begin UserLocalDriverApi.EnterFolder( '', ControlPath ); end; procedure TFrameDriver.sbMyComputerMouseLeave(Sender: TObject); begin sbMyComputer.Visible := False; ilMyComputer.Visible := True; end; procedure TFrameDriver.sbNetworkClick(Sender: TObject); begin UserNetworkDriverApi.EnterFolder( DriverPath, ControlPath ); end; procedure TFrameDriver.sbNetworkMouseLeave(Sender: TObject); begin sbNetwork.Visible := False; ilNetworkDriver.Visible := True; end; procedure TFrameDriver.sbNetworkStatusClick(Sender: TObject); begin Clipboard.AsText := sbNetworkStatus.Caption; plNetworkStatus.Caption := ''; plNetworkStatusCopy.Visible := True; sbNetworkStatus.Visible := False; end; procedure TFrameDriver.sbNetworkStatusMouseLeave(Sender: TObject); begin sbNetworkStatus.Visible := False; end; procedure TFrameDriver.SetControlPath(_ControlPath, _DriverPath: string); begin ControlPath := _ControlPath; DriverPath := _DriverPath; end; procedure TFrameDriver.SetLocalPath(_LocalPath: string); begin LocalPath := _LocalPath; end; procedure TFrameDriver.SetNetworkPath(_NetworkPath: string); begin NetworkPath := _NetworkPath; end; procedure TFrameDriver.tmrLeftEnterTimer(Sender: TObject); begin tmrLeftEnter.Enabled := False; ilCopyLeft.Visible := False; sbCopyLeft.Visible := True; end; procedure TFrameDriver.tmrLocalSearchTimer(Sender: TObject); begin tmrLocalSearch.Enabled := False; UserLocalDriverApi.SearchFile( ControlPath ); end; procedure TFrameDriver.tmrNetworkSearchTimer(Sender: TObject); begin tmrNetworkSearch.Enabled := False; UserNetworkDriverApi.SearchFile( ControlPath ); end; procedure TFrameDriver.tmrRightEnterTimer(Sender: TObject); begin tmrRightEnter.Enabled := False; ilCopyRight.Visible := False; sbCopyRight.Visible := True; end; procedure TFrameDriver.vstFileJobGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); var NodeData : PVstFileJobData; begin if (Kind = ikNormal) or (Kind = ikSelected) then begin NodeData := Sender.GetNodeData( Node ); if Column = 0 then ImageIndex := NodeData.ShowIcon else if Column = 1 then ImageIndex := NodeData.ActionIcon else ImageIndex := -1; end else ImageIndex := -1; end; procedure TFrameDriver.vstFileJobGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); var NodeData : PVstFileJobData; begin NodeData := Sender.GetNodeData( Node ); if Column = 0 then CellText := NodeData.ShowName else if Column = 1 then CellText := NodeData.ActionName else CellText := ''; end; procedure TFrameDriver.vstLocalChange(Sender: TBaseVirtualTree; Node: PVirtualNode); begin if ( Sender.SelectedCount > 0 ) and ( LocalPath <> '' ) then PcCopy.ActivePage := tsCopyLeft else PcCopy.ActivePage := tsCopyLeftDisable; end; procedure TFrameDriver.vstLocalCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); var NodeData1, NodeData2 : PVstLocalData; begin NodeData1 := Sender.GetNodeData( Node1 ); NodeData2 := Sender.GetNodeData( Node2 ); if NodeData1.IsLocked then Result := 0 else if NodeData2.IsLocked then Result := 0 else if NodeData1.IsFile <> NodeData2.IsFile then Result := 0 else if Column = VstLocal_FileName then Result := CompareText( NodeData1.ShowName, NodeData2.ShowName ) else if Column = VstLocal_FileSize then Result := NodeData1.FileSize - NodeData2.FileSize else if Column = VstLocal_FileTime then begin if NodeData1.FileTime > NodeData2.FileTime then Result := 1 else if NodeData1.FileTime < NodeData2.FileTime then Result := -1 else Result := 0; end else Result := 0; end; procedure TFrameDriver.vstLocalDblClick(Sender: TObject); var NodeData : PVstLocalData; MarkPath, MarkName : string; IsLocked : Boolean; RootCount : Integer; begin if not Assigned( vstLocal.FocusedNode ) then Exit; NodeData := vstLocal.GetNodeData( vstLocal.FocusedNode ); // 记录信息 RootCount := vstLocal.RootNode.ChildCount; MarkPath := LocalPath; MarkName := MyFilePath.getName( NodeData.FilePath ); IsLocked := NodeData.IsLocked; // 文件/目录 if NodeData.IsFile then MyExplorer.RunFile( NodeData.FilePath ) else UserLocalDriverApi.EnterFolder( NodeData.FilePath, ControlPath ); // 返回上一层 if IsLocked then MyFaceJobHandler.FileListSelect( ControlPath, MarkPath, True ); // 记录选择 if ( RootCount > 10 ) and not IsLocked then MyFaceJobHandler.FileListMarkSelect( MarkPath, MarkName ); end; procedure TFrameDriver.vstLocalDragDrop(Sender: TBaseVirtualTree; Source: TObject; DataObject: IDataObject; Formats: TFormatArray; Shift: TShiftState; Pt: TPoint; var Effect: Integer; Mode: TDropMode); begin if Source = vstNetwork then sbCopyRight.Click; end; procedure TFrameDriver.vstLocalDragOver(Sender: TBaseVirtualTree; Source: TObject; Shift: TShiftState; State: TDragState; Pt: TPoint; Mode: TDropMode; var Effect: Integer; var Accept: Boolean); begin Accept := ( Source = vstNetwork ) and ( LocalPath <> '' ); end; procedure TFrameDriver.vstLocalGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); var NodeData : PVstLocalData; begin if ( (Kind = ikNormal) or (Kind = ikSelected) ) and ( Column = 0 ) then begin NodeData := Sender.GetNodeData( Node ); ImageIndex := NodeData.ShowIcon; end else ImageIndex := -1; end; procedure TFrameDriver.vstLocalGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); var NodeData : PVstLocalData; begin NodeData := Sender.GetNodeData( Node ); if Column = VstLocal_FileName then CellText := NodeData.ShowName else if Column = VstLocal_FileSize then CellText := NodeData.ShowSize else if Column = VstLocal_FileTime then CellText := NodeData.ShowTime; end; procedure TFrameDriver.vstLocalHeaderClick(Sender: TVTHeader; HitInfo: TVTHeaderHitInfo); begin if vstLocal.Header.SortDirection = sdAscending then begin vstLocal.Header.SortDirection := sdDescending; vstLocal.SortTree( HitInfo.Column, sdDescending ) end else begin vstLocal.Header.SortDirection := sdAscending; vstLocal.SortTree( HitInfo.Column, sdAscending ); end; end; procedure TFrameDriver.vstLocalHistoryChange(Sender: TBaseVirtualTree; Node: PVirtualNode); begin miHistoryRemove.Visible := Sender.SelectedCount > 0; end; procedure TFrameDriver.vstLocalHistoryDblClick(Sender: TObject); var SelectNode : PVirtualNode; NodeData : PVstLocalHistoryData; begin SelectNode := vstLocalHistory.FocusedNode; if not Assigned( SelectNode ) then Exit; NodeData := vstLocalHistory.GetNodeData( SelectNode ); UserLocalDriverApi.EnterFolder( NodeData.FolderPath, ControlPath ); end; procedure TFrameDriver.vstLocalHistoryGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); var NodeData : PVstLocalHistoryData; begin if ( (Kind = ikNormal) or (Kind = ikSelected) ) and ( Column = 0 ) then begin NodeData := Sender.GetNodeData( Node ); ImageIndex := NodeData.ShowIcon; end else ImageIndex := -1; end; procedure TFrameDriver.vstLocalHistoryGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); var NodeData : PVstLocalHistoryData; begin NodeData := Sender.GetNodeData( Node ); if Column = VstHistory_FileName then CellText := NodeData.ShowName else if Column = VstHistory_FileDir then CellText := NodeData.ShowDir else CellText := ''; end; procedure TFrameDriver.vstLocalKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin // 文件搜索 if ( Key > 47 ) and ( Key < 91 ) and ( not ( ssCtrl in Shift ) ) then begin edtLocalSearch.Visible := True; edtLocalSearch.Text := LowerCase( Char( Key ) ); edtLocalSearch.SetFocus; edtLocalSearch.SelStart := 1; end else if Key = VK_F5 then UserLocalDriverApi.RefreshFolder( ControlPath ) else // 文件菜单 if vstLocal.SelectedCount > 0 then begin if Key = VK_DELETE then UserLocalDriverApi.DeleteFile( ControlPath ) else if Key = VK_F2 then UserLocalDriverApi.RenameFile( ControlPath ) else if Key = VK_RETURN then vstLocalDblClick( Sender ); end; end; procedure TFrameDriver.vstLocalMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var SelectNode : PVirtualNode; NodeData : PVstLocalData; IsSelectNode : Boolean; begin if Button <> mbRight then Exit; SelectNode := vstLocal.GetNodeAt( x, y ); IsSelectNode := False; if Assigned( SelectNode ) then IsSelectNode := vstLocal.Selected[ SelectNode ]; if LocalPath = '' then vstLocal.PopupMenu := nil else if IsSelectNode then vstLocal.PopupMenu := pmLocalFile else begin vstLocal.PopupMenu := pmLocalFolder; SelectNode := vstLocal.GetFirstSelected; while Assigned( SelectNode ) do begin vstLocal.Selected[ SelectNode ] := False; SelectNode := vstLocal.GetNextSelected( SelectNode ); end; end; end; procedure TFrameDriver.vstNetworkChange(Sender: TBaseVirtualTree; Node: PVirtualNode); begin if ( Sender.SelectedCount > 0 ) and ( LocalPath <> '' ) then PcCopy.ActivePage := tsCopyRight else PcCopy.ActivePage := tsCopyRightDisable; end; procedure TFrameDriver.vstNetworkCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); var NodeData1, NodeData2 : PVstNetworkData; begin NodeData1 := Sender.GetNodeData( Node1 ); NodeData2 := Sender.GetNodeData( Node2 ); if NodeData1.IsLocked then Result := 0 else if NodeData2.IsLocked then Result := 0 else if NodeData1.IsFile <> NodeData2.IsFile then Result := 0 else if Column = VstNetwork_FileName then Result := CompareText( NodeData1.ShowName, NodeData2.ShowName ) else if Column = VstNetwork_FileSize then Result := NodeData1.FileSize - NodeData2.FileSize else if Column = VstNetwork_FileTime then begin if NodeData1.FileTime > NodeData2.FileTime then Result := 1 else if NodeData1.FileTime < NodeData2.FileTime then Result := -1 else Result := 0; end else Result := 0; end; procedure TFrameDriver.vstNetworkDblClick(Sender: TObject); var NodeData : PVstNetworkData; MarkPath, MarkName : string; IsLocked : Boolean; RootCount : Integer; begin if not Assigned( vstNetwork.FocusedNode ) then Exit; NodeData := vstNetwork.GetNodeData( vstNetwork.FocusedNode ); // 记录信息 RootCount := vstNetwork.RootNode.ChildCount; MarkPath := NetworkPath; MarkName := MyFilePath.getName( NodeData.FilePath ); IsLocked := NodeData.IsLocked; // 文件/目录 if not NodeData.IsFile then UserNetworkDriverApi.EnterFolder( NodeData.FilePath, ControlPath ) else MyExplorer.RunFile( NodeData.FilePath ); // 返回上一层 if IsLocked then MyFaceJobHandler.FileListSelect( ControlPath, MarkPath, False ); // 记录选择 if ( RootCount > 10 ) and not IsLocked then MyFaceJobHandler.FileListMarkSelect( MarkPath, MarkName ); end; procedure TFrameDriver.vstNetworkDragDrop(Sender: TBaseVirtualTree; Source: TObject; DataObject: IDataObject; Formats: TFormatArray; Shift: TShiftState; Pt: TPoint; var Effect: Integer; Mode: TDropMode); begin if Source = vstLocal then sbCopyLeft.Click; end; procedure TFrameDriver.vstNetworkDragOver(Sender: TBaseVirtualTree; Source: TObject; Shift: TShiftState; State: TDragState; Pt: TPoint; Mode: TDropMode; var Effect: Integer; var Accept: Boolean); begin Accept := Source = vstLocal; end; procedure TFrameDriver.vstNetworkGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); var NodeData : PVstNetworkData; begin if ( (Kind = ikNormal) or (Kind = ikSelected) ) and ( Column = 0 ) then begin NodeData := Sender.GetNodeData( Node ); ImageIndex := NodeData.ShowIcon; end else ImageIndex := -1; end; procedure TFrameDriver.vstNetworkGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); var NodeData : PVstNetworkData; begin NodeData := Sender.GetNodeData( Node ); if Column = VstNetwork_FileName then CellText := NodeData.ShowName else if Column = VstNetwork_FileSize then CellText := NodeData.ShowSize else if Column = VstNetwork_FileTime then CellText := NodeData.ShowTime; end; procedure TFrameDriver.vstNetworkHeaderClick(Sender: TVTHeader; HitInfo: TVTHeaderHitInfo); begin if vstNetwork.Header.SortDirection = sdAscending then begin vstNetwork.Header.SortDirection := sdDescending; vstNetwork.SortTree( HitInfo.Column, sdDescending ) end else begin vstNetwork.Header.SortDirection := sdAscending; vstNetwork.SortTree( HitInfo.Column, sdAscending ); end; end; procedure TFrameDriver.vstNetworkKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin // 文件搜索 if ( Key > 47 ) and ( Key < 91 ) and ( not ( ssCtrl in Shift ) ) then begin edtNetworkSearch.Visible := True; edtNetworkSearch.Text := LowerCase( Char( Key ) ); edtNetworkSearch.SetFocus; edtNetworkSearch.SelStart := 1; end else if Key = VK_F5 then UserNetworkDriverApi.RefreshFolder( ControlPath ) else // 文件菜单 if vstNetwork.SelectedCount > 0 then begin if Key = VK_DELETE then UserNetworkDriverApi.DeleteFile( ControlPath ) else if Key = VK_F2 then UserNetworkDriverApi.RenameFile( ControlPath ) else if Key = VK_RETURN then vstNetworkDblClick( Sender ); end; end; procedure TFrameDriver.vstNetworkMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var SelectNode : PVirtualNode; NodeData : PVstNetworkData; IsSelectNode : Boolean; begin if Button <> mbRight then Exit; SelectNode := vstNetwork.GetNodeAt( x, y ); IsSelectNode := False; if Assigned( SelectNode ) then IsSelectNode := vstNetwork.Selected[ SelectNode ]; if IsSelectNode then vstNetwork.PopupMenu := pmNeworkFile else begin vstNetwork.PopupMenu := pmNetworkFolder; SelectNode := vstNetwork.GetFirstSelected; while Assigned( SelectNode ) do begin vstNetwork.Selected[ SelectNode ] := False; SelectNode := vstNetwork.GetNextSelected( SelectNode ); end; end; end; { TFaceNetworkDriverApi } procedure TFaceNetworkDriverApi.Activate(_vstNetwork: TVirtualStringTree); begin vstNetwork := _vstNetwork; end; procedure TFaceNetworkDriverApi.Add(Params: TFileAddParams); var FileNode : PVirtualNode; NodeData : PVstNetworkData; begin FileNode := vstNetwork.AddChild( vstNetwork.RootNode ); NodeData := vstNetwork.GetNodeData( FileNode ); NodeData.FilePath := Params.FilePath; NodeData.IsFile := Params.IsFile; NodeData.FileSize := Params.FileSize; NodeData.FileTime := Params.FileTime; NodeData.ShowName := MyFilePath.getName( Params.FilePath ); NodeData.ShowTime := DateTimeToStr( Params.FileTime ); if Params.IsFile then NodeData.ShowSize := MySizeUtil.getFileSizeStr( Params.FileSize ) else NodeData.ShowSize := ''; NodeData.ShowIcon := MyIcon.getPathIcon( Params.FilePath, Params.IsFile ); NodeData.IsLocked := False; end; procedure TFaceNetworkDriverApi.AddParentFolder(ParentPath: string); var FileNode : PVirtualNode; NodeData : PVstNetworkData; begin FileNode := vstNetwork.InsertNode( vstNetwork.RootNode, amAddChildFirst ); NodeData := vstNetwork.GetNodeData( FileNode ); NodeData.FilePath := ParentPath; NodeData.IsFile := False; NodeData.ShowName := Caption_ParentFolder; NodeData.ShowSize := ''; NodeData.ShowTime := ''; NodeData.ShowIcon := My16IconUtil.getBack; NodeData.IsLocked := True; end; procedure TFaceNetworkDriverApi.CancelSelect; var SelectNode : PVirtualNode; begin SelectNode := vstNetwork.RootNode.FirstChild; while Assigned( SelectNode ) do begin vstNetwork.Selected[ SelectNode ] := False; SelectNode := SelectNode.NextSibling; end; end; procedure TFaceNetworkDriverApi.Clear; begin vstNetwork.Clear; end; function TFaceNetworkDriverApi.CreateInsertNode: PVirtualNode; var FirstNode : PVirtualNode; NodeData : PVstNetworkData; begin FirstNode := vstNetwork.RootNode.FirstChild; if Assigned( FirstNode ) then begin NodeData := vstNetwork.GetNodeData( FirstNode ); if NodeData.IsLocked then Result := vstNetwork.InsertNode( FirstNode, amInsertAfter ) else Result := vstNetwork.InsertNode( vstNetwork.RootNode, amAddChildFirst ); end else Result := vstNetwork.InsertNode( vstNetwork.RootNode, amAddChildFirst ); end; procedure TFaceNetworkDriverApi.Insert(Params: TFileAddParams); var FileNode : PVirtualNode; NodeData : PVstNetworkData; begin FileNode := CreateInsertNode; NodeData := vstNetwork.GetNodeData( FileNode ); NodeData.FilePath := Params.FilePath; NodeData.IsFile := Params.IsFile; NodeData.FileSize := Params.FileSize; NodeData.FileTime := Params.FileTime; NodeData.ShowName := MyFilePath.getName( Params.FilePath ); NodeData.ShowTime := DateTimeToStr( Params.FileTime ); if Params.IsFile then NodeData.ShowSize := MySizeUtil.getFileSizeStr( Params.FileSize ) else NodeData.ShowSize := ''; NodeData.ShowIcon := MyIcon.getPathIcon( Params.FilePath, Params.IsFile ); NodeData.IsLocked := False; end; function TFaceNetworkDriverApi.ReadFocusePath: string; var NodeData : PVstNetworkData; begin Result := ''; if not Assigned( vstNetwork.FocusedNode ) then Exit; NodeData := vstNetwork.GetNodeData( vstNetwork.FocusedNode ); Result := NodeData.FilePath; end; function TFaceNetworkDriverApi.ReadIsExist(FilePath: string): Boolean; begin Result := Assigned( ReadNode( FilePath ) ); end; function TFaceNetworkDriverApi.ReadNode(FilePath: string): PVirtualNode; var SelectNode : PVirtualNode; NodeData : PVstNetworkData; begin Result := nil; SelectNode := vstNetwork.RootNode.FirstChild; while Assigned( SelectNode ) do begin NodeData := vstNetwork.GetNodeData( SelectNode ); if NodeData.FilePath = FilePath then begin Result := SelectNode; Break; end; SelectNode := SelectNode.NextSibling; end; end; function TFaceNetworkDriverApi.ReadPathList: TStringList; var SelectNode : PVirtualNode; NodeData : PVstNetworkData; begin Result := TStringList.Create; SelectNode := vstNetwork.RootNode.FirstChild; while Assigned( SelectNode ) do begin NodeData := vstNetwork.GetNodeData( SelectNode ); if not NodeData.IsLocked then Result.Add( NodeData.FilePath ); SelectNode := SelectNode.NextSibling; end; end; function TFaceNetworkDriverApi.ReadSelectList: TStringList; var SelectNode : PVirtualNode; NodeData : PVstNetworkData; begin Result := TStringList.Create; SelectNode := vstNetwork.GetFirstSelected; while Assigned( SelectNode ) do begin NodeData := vstNetwork.GetNodeData( SelectNode ); if not NodeData.IsLocked then Result.Add( NodeData.FilePath ); SelectNode := vstNetwork.GetNextSelected( SelectNode ); end; end; procedure TFaceNetworkDriverApi.Remove(FilePath: string); var SelectNode : PVirtualNode; begin SelectNode := ReadNode( FilePath ); if not Assigned( SelectNode ) then Exit; vstNetwork.DeleteNode( SelectNode ); end; procedure TFaceNetworkDriverApi.Search(FileName: string); var SelectNode : PVirtualNode; NodeData : PVstLocalData; IsVisible, IsSearchAll : Boolean; begin FileName := LowerCase( FileName ); IsSearchAll := FileName = ''; SelectNode := vstNetwork.RootNode.FirstChild; while Assigned( SelectNode ) do begin NodeData := vstNetwork.GetNodeData( SelectNode ); IsVisible := IsSearchAll or NodeData.IsLocked or ( Pos( FileName, LowerCase( string( NodeData.ShowName ) ) ) > 0 ); vstNetwork.IsVisible[ SelectNode ] := IsVisible; vstNetwork.Selected[ SelectNode ] := False; SelectNode := SelectNode.NextSibling; end; // 全选 if IsSearchAll then Exit; // 默认选择第一个 SelectNode := vstNetwork.GetFirstVisible; if not Assigned( SelectNode ) then Exit; NodeData := vstNetwork.GetNodeData( SelectNode ); if NodeData.IsLocked then begin SelectNode := vstNetwork.GetNextVisible( SelectNode ); if not Assigned( SelectNode ) then Exit; end; vstNetwork.Selected[ SelectNode ] := True; vstNetwork.FocusedNode := SelectNode; end; procedure TFaceNetworkDriverApi.Select(FilePath: string); var SelectNode : PVirtualNode; begin SelectNode := ReadNode( FilePath ); if not Assigned( SelectNode ) then Exit; vstNetwork.Selected[ SelectNode ] := True; vstNetwork.FocusedNode := SelectNode; end; { TFaceFrameDriverApi } procedure TFaceFrameDriverApi.Activate(_FrameDriver: TFrameDriver); begin FrameDriver := _FrameDriver; FaceLocalDriverApi.Activate( FrameDriver.vstLocal ); FaceNetworkDriverApi.Activate( FrameDriver.vstNetwork ); FaceLocalStatusApi.Activate( FrameDriver.plLocalStatus, FrameDriver.sbLocalStatus ); FaceNetworkStatusApi.Activate( FrameDriver.plNetworkStatus, FrameDriver.sbNetworkStatus ); FaceFileJobApi.Activate( FrameDriver.vstFileJob, FrameDriver.plBottom ); FaceLocalHistoryApi.Activate( FrameDriver.vstLocalHistory, FrameDriver.slLocalHistory ); end; function TFaceFrameDriverApi.ReadDriverPath: string; begin Result := FrameDriver.DriverPath; end; function TFaceFrameDriverApi.ReadLocalPath: string; begin Result := FrameDriver.LocalPath; end; function TFaceFrameDriverApi.ReadLocalSerach: string; begin Result := FrameDriver.edtLocalSearch.Text; end; function TFaceFrameDriverApi.ReadNetworkPath: string; begin Result := FrameDriver.NetworkPath; end; function TFaceFrameDriverApi.ReadNetworkSerach: string; begin Result := FrameDriver.edtNetworkSearch.Text; end; procedure TFaceFrameDriverApi.SetLocalPath(LocalPath: string); begin FrameDriver.SetLocalPath( LocalPath ); end; procedure TFaceFrameDriverApi.SetNetworkPath(NetworkPath: string); begin FrameDriver.SetNetworkPath( NetworkPath ); end; procedure TFaceFrameDriverApi.UnvisibleLocalSearch; begin FrameDriver.edtLocalSearch.Visible := False; end; procedure TFaceFrameDriverApi.UnvisibleNetworkSearch; begin FrameDriver.edtNetworkSearch.Visible := False; end; { UserLocalDriverApi } class procedure UserLocalDriverApi.AddFile(ControlPath, FilePath: string); var Params : TFileAddParams; begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 页面已变化 if FaceFrameDriverApi.ReadLocalPath <> ExtractFileDir( FilePath ) then Exit; // 已存在,则先删除 if FaceLocalDriverApi.ReadIsExist( FilePath ) then FaceLocalDriverApi.Remove( FilePath ); // 插入文件 Params.FilePath := FilePath; Params.IsFile := FileExists( FilePath ); Params.FileTime := MyFileInfo.getFileTime( FilePath ); if Params.IsFile then Params.FileSize := MyFileInfo.getFileSize( FilePath ); FaceLocalDriverApi.Insert( Params ); // 选中文件 FaceLocalDriverApi.Select( FilePath ); end; class procedure UserLocalDriverApi.CancelSelect(ControlPath: string); begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 取消选择 FaceLocalDriverApi.CancelSelect; end; class function UserLocalDriverApi.ControlPage(ControlPath: string): Boolean; begin Result := FacePageDriverApi.ControlPage( ControlPath ); end; class procedure UserLocalDriverApi.CopyFile(ControlPath: string); var PathList : TStringList; begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 复制文件 PathList := FaceLocalDriverApi.ReadSelectList; CopyNow( ControlPath, PathList ); PathList.Free; end; class procedure UserLocalDriverApi.CopyNow(ControlPath: string; PathList: TStringList); var DesFolder, LocalFolder : string; FileCopyHandle : TFileCopyHandle; begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 取消目标选择 FaceNetworkDriverApi.CancelSelect; // 网络目录路径 DesFolder := FaceFrameDriverApi.ReadNetworkPath; // 复制文件 FileCopyHandle := TFileCopyHandle.Create( PathList, DesFolder ); FileCopyHandle.SetControlPath( ControlPath, True ); FileCopyHandle.Update; FileCopyHandle.Free; // 本地目录 if PathList.Count > 0 then LocalFolder := ExtractFileDir( PathList[0] ) else LocalFolder := FaceFrameDriverApi.ReadLocalPath; if not MyFilePath.getIsRoot( LocalFolder ) and DirectoryExists( LocalFolder ) then UserLocalHistoryApi.AddHistory( ControlPath, LocalFolder ); end; class procedure UserLocalDriverApi.DeleteFile(ControlPath: string); var PathList : TStringList; i: Integer; Params : TJobDeleteParams; begin // 删除确认 if MessageDlg( DeleteFile_Comfirm, mtConfirmation, [mbYes, mbNo], 0 ) <> mrYes then Exit; // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 复制文件 Params.ControlPath := ControlPath; Params.IsLocal := True; PathList := FaceLocalDriverApi.ReadSelectList; for i := 0 to PathList.Count - 1 do begin Params.FilePath := PathList[i]; Params.ActionID := FaceFileJobApi.AddFileJob( PathList[i], ActionType_Delete ); MyFileJobHandler.AddFleDelete( Params ); end; PathList.Free; end; class procedure UserLocalDriverApi.EnterFolder(FolderPath, ControlPath: string); var IsHistoryShow : Boolean; begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 设置本地路径 FaceFrameDriverApi.SetLocalPath( FolderPath ); // 显示状态路径 FaceLocalStatusApi.ShowPath( FolderPath ); // 搜索文件 MyFaceJobHandler.RefreshLocalDriver( FolderPath, ControlPath ); // 隐藏本地搜索 FaceFrameDriverApi.UnvisibleLocalSearch; // 监听 MyFileWatch.SetLocalPath( FolderPath ); // 本地历史是否可视化 IsHistoryShow := ( FolderPath = '' ) and ( FaceLocalHistoryApi.ReadHistoryCount > 0 ); FaceLocalHistoryApi.SetVisible( IsHistoryShow ); end; class procedure UserLocalDriverApi.NewFolder(ControlPath: string); var LocalFolder, FolderName, NewFolderPath : string; begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; LocalFolder := FaceFrameDriverApi.ReadLocalPath; FolderName := NewFolder_DefaultName; FolderName := MyFilePath.getRenamePath( MyFilePath.getPath( LocalFolder ) + FolderName, False ); FolderName := ExtractFileName( FolderName ); // 输入新名字 if not InputQuery( NewFolder_Title, NewFolder_Name, FolderName ) then Exit; // 新路径 NewFolderPath := MyFilePath.getPath( LocalFolder ) + FolderName; // 已存在则取消 if MyFilePath.getIsExist( NewFolderPath, False ) then begin MyMessageForm.ShowWarnning( Rename_Exist ); NewFolder( ControlPath ); Exit; end; // 创建文件夹 ForceDirectories( NewFolderPath ); FaceLocalDriverApi.CancelSelect; AddFile( ControlPath, NewFolderPath ); end; class function UserLocalDriverApi.ReadFileList( ControlPath: string): TStringList; begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; Result := FaceLocalDriverApi.ReadPathList; end; class procedure UserLocalDriverApi.RefreshFolder(ControlPath: string); var LocalFolder : string; begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 刷新当前目录 LocalFolder := FaceFrameDriverApi.ReadLocalPath; EnterFolder( LocalFolder, ControlPath ); end; class procedure UserLocalDriverApi.RemoveFile(ControlPath, FilePath: string); var Params : TFileAddParams; begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 页面已变化 if FaceFrameDriverApi.ReadLocalPath <> ExtractFileDir( FilePath ) then Exit; // 存在,则删除 if FaceLocalDriverApi.ReadIsExist( FilePath ) then FaceLocalDriverApi.Remove( FilePath ); end; class procedure UserLocalDriverApi.RenameFile(ControlPath: string); var OldPath, NewName, NewPath : string; fo: TSHFILEOPSTRUCT; begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 读取选择的路径 OldPath := FaceLocalDriverApi.ReadFocusePath; NewName := ExtractFileName( OldPath ); // 输入新名字 if not InputQuery( Rename_Title, Rename_Name, NewName ) then Exit; // 没有后缀 if ExtractFileExt( NewName ) = '' then NewName := NewName + ExtractFileExt( OldPath ); // 新路径 NewPath := ExtractFilePath( OldPath ) + NewName; // 已存在则取消 if MyFilePath.getIsExist( NewPath, FileExists( OldPath ) ) then begin if NewPath <> OldPath then begin MyMessageForm.ShowWarnning( Rename_Exist ); RenameFile( ControlPath ); end; Exit; end; // 重命名 FillChar(fo, SizeOf(fo), 0); with fo do begin Wnd := 0; wFunc := FO_RENAME; pFrom := PChar( OldPath + #0); pTo := PChar( NewPath + #0); fFlags := FOF_NOCONFIRMATION + FOF_NOCONFIRMMKDIR; end; if SHFileOperation(fo)=0 then begin RemoveFile( ControlPath, OldPath ); AddFile( ControlPath, NewPath ); end; end; class procedure UserLocalDriverApi.SearchFile(ControlPath: string); begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 搜索 FaceLocalDriverApi.Search( FaceFrameDriverApi.ReadLocalSerach ); end; class procedure UserLocalDriverApi.Select(ControlPath, FilePath: string); begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; FaceLocalDriverApi.Select( FilePath ); end; class procedure UserLocalDriverApi.ZipFile(ControlPath: string); var SelectPathList : TStringList; LocalFolder, ZipPath : string; Params : TJobZipParams; begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 获取选择的文件路径 SelectPathList := FaceLocalDriverApi.ReadSelectList; // 目录路径 LocalFolder := FaceFrameDriverApi.ReadLocalPath; // 压缩的目标路径 if SelectPathList.Count = 1 then begin ZipPath := SelectPathList[0]; if FileExists( ZipPath ) then ZipPath := MyFilePath.getPath( LocalFolder ) + TPath.GetFileNameWithoutExtension( ZipPath ); end else ZipPath := MyFilePath.getPath( LocalFolder ) + Compressed_NewName; ZipPath := ZipPath + '.zip'; ZipPath := MyFilePath.getRenamePath( ZipPath, True ); // 压缩参数 Params.FileList := SelectPathList; Params.ZipPath := ZipPath; Params.ControlPath := ControlPath; Params.IsLocal := True; if SelectPathList.Count > 0 then Params.ActionID := FaceFileJobApi.AddFileJob( SelectPathList[0], ActionType_Zip ); // 启动压缩 MyFileJobHandler.AddFileZip( Params ); end; { UserNeworkDriverApi } class procedure UserNetworkDriverApi.AddFile(ControlPath, FilePath: string); var Params : TFileAddParams; begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 页面已变化 if FaceFrameDriverApi.ReadNetworkPath <> ExtractFileDir( FilePath ) then Exit; // 已存在,则先删除 if FaceNetworkDriverApi.ReadIsExist( FilePath ) then FaceNetworkDriverApi.Remove( FilePath ); // 插入文件 Params.FilePath := FilePath; Params.IsFile := FileExists( FilePath ); Params.FileTime := MyFileInfo.getFileTime( FilePath ); if Params.IsFile then Params.FileSize := MyFileInfo.getFileSize( FilePath ); FaceNetworkDriverApi.Insert( Params ); // 选中文件 FaceNetworkDriverApi.Select( FilePath ); end; class procedure UserNetworkDriverApi.CancelSelect(ControlPath: string); begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 取消选择 FaceNetworkDriverApi.CancelSelect; end; class function UserNetworkDriverApi.ControlPage(ControlPath: string): Boolean; begin Result := FacePageDriverApi.ControlPage( ControlPath ); end; class procedure UserNetworkDriverApi.CopyFile(ControlPath: string); var PathList : TStringList; i: Integer; DesFolder : string; FileCopyHandle : TFileCopyHandle; begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 取消目标选择 FaceLocalDriverApi.CancelSelect; // 本地目录路径 DesFolder := FaceFrameDriverApi.ReadLocalPath; // 复制文件 PathList := FaceNetworkDriverApi.ReadSelectList; FileCopyHandle := TFileCopyHandle.Create( PathList, DesFolder ); FileCopyHandle.SetControlPath( ControlPath, False ); FileCopyHandle.Update; FileCopyHandle.Free; PathList.Free; // 添加到历史 if DirectoryExists( DesFolder ) then UserLocalHistoryApi.AddHistory( ControlPath, DesFolder ); end; class procedure UserNetworkDriverApi.DeleteFile(ControlPath: string); var PathList : TStringList; i: Integer; Params : TJobDeleteParams; begin // 删除确认 if MessageDlg( DeleteFile_Comfirm, mtConfirmation, [mbYes, mbNo], 0 ) <> mrYes then Exit; // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 复制文件 Params.ControlPath := ControlPath; Params.IsLocal := False; PathList := FaceNetworkDriverApi.ReadSelectList; for i := 0 to PathList.Count - 1 do begin Params.FilePath := PathList[i]; Params.ActionID := FaceFileJobApi.AddFileJob( PathList[i], ActionType_Delete ); MyFileJobHandler.AddFleDelete( Params ); end; PathList.Free; end; class procedure UserNetworkDriverApi.EnterFolder(FolderPath, ControlPath: string); begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 设置网络路径 FaceFrameDriverApi.SetNetworkPath( FolderPath ); // 显示状态 FaceNetworkStatusApi.ShowPath( FolderPath ); // 搜索文件 MyFaceJobHandler.RefreshNetworkDriver( FolderPath, ControlPath ); // 隐藏网络搜索 FaceFrameDriverApi.UnvisibleNetworkSearch; // 监听 MyFileWatch.SetNetworkPath( FolderPath ); end; class procedure UserNetworkDriverApi.NewFolder(ControlPath: string); var NetworkFolder, FolderName, NewFolderPath : string; begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; NetworkFolder := FaceFrameDriverApi.ReadNetworkPath; FolderName := NewFolder_DefaultName; FolderName := MyFilePath.getRenamePath( MyFilePath.getPath( NetworkFolder ) + FolderName, False ); FolderName := ExtractFileName( FolderName ); // 输入新名字 if not InputQuery( NewFolder_Title, NewFolder_Name, FolderName ) then Exit; // 新路径 NewFolderPath := MyFilePath.getPath( NetworkFolder ) + FolderName; // 已存在则取消 if MyFilePath.getIsExist( NewFolderPath, False ) then begin MyMessageForm.ShowWarnning( Rename_Exist ); NewFolder( ControlPath ); Exit; end; // 创建文件夹 ForceDirectories( NewFolderPath ); FaceNetworkDriverApi.CancelSelect; AddFile( ControlPath, NewFolderPath ); end; class function UserNetworkDriverApi.ReadFileList( ControlPath: string): TStringList; begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; Result := FaceNetworkDriverApi.ReadPathList; end; class procedure UserNetworkDriverApi.RefreshFolder(ControlPath: string); var NetworkFolder : string; begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 刷新当前目录 NetworkFolder := FaceFrameDriverApi.ReadNetworkPath; EnterFolder( NetworkFolder, ControlPath ); end; class procedure UserNetworkDriverApi.RemoveFile(ControlPath, FilePath: string); var Params : TFileAddParams; begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 页面已变化 if FaceFrameDriverApi.ReadNetworkPath <> ExtractFileDir( FilePath ) then Exit; // 存在,则删除 if FaceNetworkDriverApi.ReadIsExist( FilePath ) then FaceNetworkDriverApi.Remove( FilePath ); end; class procedure UserNetworkDriverApi.RenameFile(ControlPath: string); var OldPath, NewName, NewPath : string; fo: TSHFILEOPSTRUCT; begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 读取选择的路径 OldPath := FaceNetworkDriverApi.ReadFocusePath; NewName := ExtractFileName( OldPath ); // 输入新名字 if not InputQuery( Rename_Title, Rename_Name, NewName ) then Exit; // 没有后缀 if ExtractFileExt( NewName ) = '' then NewName := NewName + ExtractFileExt( OldPath ); // 新路径 NewPath := ExtractFilePath( OldPath ) + NewName; // 已存在则取消 if MyFilePath.getIsExist( NewPath, FileExists( OldPath ) ) then begin if NewPath <> OldPath then begin MyMessageForm.ShowWarnning( Rename_Exist ); RenameFile( ControlPath ); end; Exit; end; // 重命名 FillChar(fo, SizeOf(fo), 0); with fo do begin Wnd := 0; wFunc := FO_RENAME; pFrom := PChar( OldPath + #0); pTo := PChar( NewPath + #0); fFlags := FOF_NOCONFIRMATION + FOF_NOCONFIRMMKDIR; end; if SHFileOperation(fo)=0 then begin RemoveFile( ControlPath, OldPath ); AddFile( ControlPath, NewPath ); end; end; class procedure UserNetworkDriverApi.SearchFile(ControlPath: string); begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; FaceNetworkDriverApi.Search( FaceFrameDriverApi.ReadNetworkSerach ); end; class procedure UserNetworkDriverApi.Select(ControlPath, FilePath: string); begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; FaceNetworkDriverApi.Select( FilePath ); end; class procedure UserNetworkDriverApi.ZipFile(ControlPath: string); var SelectPathList : TStringList; NetworkFolder, ZipPath : string; Params : TJobZipParams; begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 获取选择的文件路径 SelectPathList := FaceNetworkDriverApi.ReadSelectList; // 目录路径 NetworkFolder := FaceFrameDriverApi.ReadNetworkPath; // 压缩的目标路径 if SelectPathList.Count = 1 then begin ZipPath := SelectPathList[0]; if FileExists( ZipPath ) then ZipPath := MyFilePath.getPath( NetworkFolder ) + TPath.GetFileNameWithoutExtension( ZipPath ); end else ZipPath := MyFilePath.getPath( NetworkFolder ) + Compressed_NewName; ZipPath := ZipPath + '.zip'; ZipPath := MyFilePath.getRenamePath( ZipPath, True ); // 压缩参数 Params.FileList := SelectPathList; Params.ZipPath := ZipPath; Params.ControlPath := ControlPath; Params.IsLocal := False; if SelectPathList.Count > 0 then Params.ActionID := FaceFileJobApi.AddFileJob( SelectPathList[0], ActionType_Zip ); // 启动压缩 MyFileJobHandler.AddFileZip( Params ); end; { TFaceLocalStatusApi } procedure TFaceLocalStatusApi.Activate(_plLocalStatus : TPanel; _sbLocalStatus : TSpeedButton); begin plLocalStatus := _plLocalStatus; sbLocalStatus := _sbLocalStatus; end; procedure TFaceLocalStatusApi.ShowPath(FolderPath: string); var ShowStr : string; begin if FolderPath = '' then ShowStr := Caption_MyComputer else ShowStr := FolderPath; plLocalStatus.Caption := ShowStr; sbLocalStatus.Caption := ShowStr; end; { TFaceNetworkStatusApi } procedure TFaceNetworkStatusApi.Activate(_plNetworkStatus : TPanel; _sbNetworkStatus : TSpeedButton); begin plNetworkStatus := _plNetworkStatus; sbNetworkStatus := _sbNetworkStatus; end; procedure TFaceNetworkStatusApi.ShowPath(FolderPath: string); begin plNetworkStatus.Caption := FolderPath; sbNetworkStatus.Caption := FolderPath; end; { TFaceFileJobApi } procedure TFaceFileJobApi.Activate(_vstFileJob: TVirtualStringTree; _PlFileJob : TPanel); begin vstFileJob := _vstFileJob; PlFileJob := _PlFileJob; end; function TFaceFileJobApi.AddFileJob(FilePath, ActionType: string): string; var FileJobNode : PVirtualNode; NodeData : PVstFileJobData; ActionName : string; ActionIcon : Integer; begin Result := ''; if not MyFileJobHandler.ReadIsRunning then Exit; // 节点类型 if ActionType = ActionType_CopyLeft then begin ActionName := AcionTypeShow_Copy; ActionIcon := My16IconUtil.getLeft; end else if ActionType = ActionType_CopyRight then begin ActionName := AcionTypeShow_Copy; ActionIcon := My16IconUtil.getRight; end else if ActionType = ActionType_Delete then begin ActionName := AcionTypeShow_Delete; ActionIcon := My16IconUtil.getDelete; end else if ActionType = ActionType_Zip then begin ActionName := AcionTypeShow_Zip; ActionIcon := My16IconUtil.getZip; end; // 添加节点 FileJobNode := vstFileJob.InsertNode( vstFileJob.RootNode, amAddChildFirst ); NodeData := vstFileJob.GetNodeData( FileJobNode ); NodeData.FilePath := FilePath; NodeData.ActionType := ActionType; NodeData.ShowName := MyFilePath.getName( FilePath ); NodeData.ShowIcon := MyIcon.getPathIcon( FilePath ); NodeData.ActionName := ActionName; NodeData.ActionIcon := ActionIcon; NodeData.ActionID := IntToStr( FileJob_ActionID ); // ActionID Result := NodeData.ActionID; Inc( FileJob_ActionID ); // 显示 PlFileJob.Visible := True; end; function TFaceFileJobApi.ReadNode(ActionID: string): PVirtualNode; var SelectNode : PVirtualNode; NodeData : PVstFileJobData; begin Result := nil; SelectNode := vstFileJob.RootNode.FirstChild; while Assigned( SelectNode ) do begin NodeData := vstFileJob.GetNodeData( SelectNode ); if NodeData.ActionID = ActionID then begin Result := SelectNode; Break; end; SelectNode := SelectNode.NextSibling; end; end; procedure TFaceFileJobApi.RemoveFileJob(ActionID: string); var SelectNode : PVirtualNode; begin SelectNode := ReadNode( ActionID ); if not Assigned( SelectNode ) then Exit; vstFileJob.DeleteNode( SelectNode ); if vstFileJob.RootNode.ChildCount = 0 then PlFileJob.Visible := False; end; { UserFrameDriverApi } class function UserFrameDriverApi.ControlPage(ControlPath: string): Boolean; begin Result := FacePageDriverApi.ControlPage( ControlPath ); end; class procedure UserFrameDriverApi.LoadFromData(UsbFrameInfo: TUsbFrameInfo); var i: Integer; begin // 页面不存在 if not ControlPage( UsbFrameInfo.UsbID ) then Exit; // 读取 FaceFrameDriverApi.SetLocalPath( UsbFrameInfo.LocalPath ); FaceFrameDriverApi.SetNetworkPath( UsbFrameInfo.NetworkPath ); FaceFrameDriverApi.FrameDriver.plRight.Width := UsbFrameInfo.LocalWidth; FaceLocalHistoryApi.vstLocalHistory.Height := UsbFrameInfo.LocalHistoryHeigh; // 读取本地历史 for i := 0 to UsbFrameInfo.HistoryList.Count - 1 do FaceLocalHistoryApi.Add( UsbFrameInfo.HistoryList[i] ); end; class procedure UserFrameDriverApi.LoadIni(DriverID: string; IniFile : TIniFile; FrameIndex : Integer); var FrameCaption : string; LocalFolder, NetworkFolder : string; HistoryCount : Integer; i: Integer; LocalHistory : string; begin // 页面不存在 if not ControlPage( DriverID ) then Exit; // 读取 FrameCaption := Ini_FrameDriver + IntToStr( FrameIndex ); LocalFolder := IniFile.ReadString( FrameCaption, Ini_LocalFolder, FaceFrameDriverApi.ReadLocalPath ); NetworkFolder := IniFile.ReadString( FrameCaption, Ini_NetworkFolder, FaceFrameDriverApi.ReadNetworkPath ); FaceFrameDriverApi.FrameDriver.plRight.Width := IniFile.ReadInteger( FrameCaption, Ini_LocalWidth, FaceFrameDriverApi.FrameDriver.plRight.Width ); FaceLocalHistoryApi.vstLocalHistory.Height := IniFile.ReadInteger( FrameCaption, Ini_LocalHistoryHeigh, FaceLocalHistoryApi.vstLocalHistory.Height ); // 设置 FaceFrameDriverApi.SetLocalPath( LocalFolder ); FaceFrameDriverApi.SetNetworkPath( NetworkFolder ); // 读取本地历史 HistoryCount := IniFile.ReadInteger( FrameCaption, Ini_LocalHistoryCount, 0 ); for i := HistoryCount - 1 downto 0 do begin LocalHistory := IniFile.ReadString( FrameCaption, Ini_LocalHistory + IntToStr( i ), '' ); if LocalHistory <> '' then FaceLocalHistoryApi.Add( LocalHistory ); end; end; class procedure UserFrameDriverApi.SaveIni(DriverID: string; IniFile : TIniFile; FrameIndex : Integer); var FrameCaption : string; HistoryList : TStringList; i: Integer; begin // 页面不存在 if not ControlPage( DriverID ) then Exit; FrameCaption := Ini_FrameDriver + IntToStr( FrameIndex ); IniFile.WriteString( FrameCaption, Ini_LocalFolder, FaceFrameDriverApi.ReadLocalPath ); IniFile.WriteString( FrameCaption, Ini_NetworkFolder, FaceFrameDriverApi.ReadNetworkPath ); IniFile.WriteInteger( FrameCaption, Ini_LocalWidth, FaceFrameDriverApi.FrameDriver.plRight.Width ); IniFile.WriteInteger( FrameCaption, Ini_LocalHistoryHeigh, FaceLocalHistoryApi.vstLocalHistory.Height ); // 保存本地历史 HistoryList := FaceLocalHistoryApi.ReadList; IniFile.WriteInteger( FrameCaption, Ini_LocalHistoryCount, HistoryList.Count ); for i := 0 to HistoryList.Count - 1 do IniFile.WriteString( FrameCaption, Ini_LocalHistory + IntToStr( i ), HistoryList[i] ); HistoryList.Free; end; class procedure UserFrameDriverApi.SaveToData(UsbFrameInfo: TUsbFrameInfo); var HistoryList : TStringList; i: Integer; begin // 页面不存在 if not ControlPage( UsbFrameInfo.UsbID ) then Exit; UsbFrameInfo.UsbPath := FaceFrameDriverApi.ReadDriverPath; UsbFrameInfo.LocalPath := FaceFrameDriverApi.ReadLocalPath; UsbFrameInfo.NetworkPath := FaceFrameDriverApi.ReadNetworkPath; UsbFrameInfo.LocalWidth := FaceFrameDriverApi.FrameDriver.plRight.Width; UsbFrameInfo.LocalHistoryHeigh := FaceLocalHistoryApi.vstLocalHistory.Height; // 保存本地历史 UsbFrameInfo.HistoryList.Clear; HistoryList := FaceLocalHistoryApi.ReadList; for i := 0 to HistoryList.Count - 1 do UsbFrameInfo.HistoryList.Add( HistoryList[i] ); HistoryList.Free; end; class procedure UserFrameDriverApi.SelectFrame(ControlPath: string); var LocalPath, NetworkPath : string; begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 监听路径 LocalPath := FaceFrameDriverApi.ReadLocalPath; NetworkPath := FaceFrameDriverApi.ReadNetworkPath; MyFileWatch.SetPath( ControlPath, LocalPath, NetworkPath ); end; { TFileCopyHandle } function TFileCopyHandle.ConfirmConflict: Boolean; var i : Integer; TargetFolder : string; SourcePath, TargetPath : string; ActionType, DesPath : string; begin // 处理冲突路径 frmConflict.ClearConflictPaths; TargetFolder := MyFilePath.getPath( DesFolder ); for i := 0 to SourceList.Count - 1 do begin SourcePath := SourceList[i]; TargetPath := TargetFolder + ExtractFileName( SourcePath ); if FileExists( TargetPath ) or DirectoryExists( TargetPath ) then frmConflict.AddConflictPath( SourcePath ); end; Result := frmConflict.ReadConflict; // 取消复制 if not Result then Exit; // 生成目标路径 CopyPathList.Clear; for i := 0 to SourceList.Count - 1 do begin SourcePath := SourceList[i]; ActionType := frmConflict.ReadConflictAction( SourcePath ); if ( ActionType = ConflictAction_None ) or ( ActionType = ConflictAction_Replace ) then DesPath := TargetFolder + ExtractFileName( SourcePath ) else if ActionType = ConflictAction_Rename then begin DesPath := TargetFolder + ExtractFileName( SourcePath ); DesPath := MyFilePath.getRenamePath( DesPath, FileExists( SourcePath ) ); end else if ActionType = ConflictAction_Cancel then Continue; CopyPathList.Add( TCopyPathInfo.Create( SourcePath, DesPath ) ); end; end; procedure TFileCopyHandle.CopyHandle; var i: Integer; Params : TJobAddParams; ActionType : string; begin if IsLocal then ActionType := ActionType_CopyLeft else ActionType := ActionType_CopyRight; Params.ControlPath := ControlPath; Params.IsLocal := IsLocal; for i := 0 to CopyPathList.Count - 1 do begin Params.FilePath := CopyPathList[i].SourcePath; Params.DesFilePath := CopyPathList[i].DesPath; Params.ActionID := FaceFileJobApi.AddFileJob( Params.FilePath, ActionType ); MyFileJobHandler.AddFleCopy( Params ); end; end; constructor TFileCopyHandle.Create(_SourceFileList : TStringList; _DesFolder : string); begin SourceList := _SourceFileList; DesFolder := _DesFolder; CopyPathList := TCopyPathList.Create; end; destructor TFileCopyHandle.Destroy; begin CopyPathList.Free; inherited; end; function TFileCopyHandle.IsExistConflict: Boolean; var i : Integer; TargetFolder : string; SourcePath, TargetPath : string; begin Result := False; TargetFolder := MyFilePath.getPath( DesFolder ); for i := 0 to SourceList.Count - 1 do begin SourcePath := SourceList[i]; TargetPath := TargetFolder + ExtractFileName( SourcePath ); if FileExists( TargetPath ) or DirectoryExists( TargetPath ) then begin Result := True; Break; end; CopyPathList.Add( TCopyPathInfo.Create( SourcePath, TargetPath ) ); end; end; procedure TFileCopyHandle.SetControlPath(_ControlPath: string; _IsLocal : Boolean); begin ControlPath := _ControlPath; IsLocal := _IsLocal; end; procedure TFileCopyHandle.Update; begin // 因冲突取消复制 if IsExistConflict and not ConfirmConflict then Exit; // 文件处理 CopyHandle; end; { TCopyPathInfo } constructor TCopyPathInfo.Create(_SourcePath, _DesPath: string); begin SourcePath := _SourcePath; DesPath := _DesPath; end; { TFaceLocalHistoryApi } procedure TFaceLocalHistoryApi.Activate(_vstLocalHistory: TVirtualStringTree; _slLocalHistory : TSplitter); begin vstLocalHistory := _vstLocalHistory; slLocalHistory := _slLocalHistory; end; procedure TFaceLocalHistoryApi.Add(FolderPath: string); var NewNode : PVirtualNode; NodeData : PVstLocalHistoryData; begin NewNode := vstLocalHistory.InsertNode( vstLocalHistory.RootNode, amAddChildFirst ); NodeData := vstLocalHistory.GetNodeData( NewNode ); NodeData.FolderPath := FolderPath; NodeData.ShowName := ExtractFileName( FolderPath ); NodeData.ShowDir := ExtractFileDir( FolderPath ); NodeData.ShowIcon := MyIcon.getFolderIcon( FolderPath ); end; procedure TFaceLocalHistoryApi.MoveToTop(FolderPath: string); var SelectNode : PVirtualNode; begin SelectNode := ReadNode( FolderPath ); if not Assigned( SelectNode ) then Exit; vstLocalHistory.MoveTo( SelectNode, vstLocalHistory.RootNode, amAddChildFirst, False ); end; function TFaceLocalHistoryApi.ReadHistoryCount: Integer; begin Result := vstLocalHistory.RootNodeCount; end; function TFaceLocalHistoryApi.ReadIsExist(FolderPath: string): Boolean; begin Result := Assigned( ReadNode( FolderPath ) ); end; function TFaceLocalHistoryApi.ReadList: TStringList; var SelectNode : PVirtualNode; NodeData : PVstLocalHistoryData; begin Result := TStringList.Create; SelectNode := vstLocalHistory.RootNode.FirstChild; while Assigned( SelectNode ) do begin NodeData := vstLocalHistory.GetNodeData( SelectNode ); Result.Add( NodeData.FolderPath ); SelectNode := SelectNode.NextSibling; end; end; function TFaceLocalHistoryApi.ReadNode(FolderPath: string): PVirtualNode; var SelectNode : PVirtualNode; NodeData : PVstLocalHistoryData; begin Result := nil; SelectNode := vstLocalHistory.RootNode.FirstChild; while Assigned( SelectNode ) do begin NodeData := vstLocalHistory.GetNodeData( SelectNode ); if NodeData.FolderPath = FolderPath then begin Result := SelectNode; Break; end; SelectNode := SelectNode.NextSibling; end; end; function TFaceLocalHistoryApi.ReadSelectList: TStringList; var SelectNode : PVirtualNode; NodeData : PVstLocalHistoryData; begin Result := TStringList.Create; SelectNode := vstLocalHistory.GetFirstSelected; while Assigned( SelectNode ) do begin NodeData := vstLocalHistory.GetNodeData( SelectNode ); Result.Add( NodeData.FolderPath ); SelectNode := vstLocalHistory.GetNextSelected( SelectNode ); end; end; procedure TFaceLocalHistoryApi.Remove(FolderPath: string); var SelectNode : PVirtualNode; begin SelectNode := ReadNode( FolderPath ); if not Assigned( SelectNode ) then Exit; vstLocalHistory.DeleteNode( SelectNode ); end; procedure TFaceLocalHistoryApi.RemoveLastNode; var SelectNode : PVirtualNode; begin SelectNode := vstLocalHistory.RootNode.LastChild; if not Assigned( SelectNode ) then Exit; vstLocalHistory.DeleteNode( SelectNode ); end; procedure TFaceLocalHistoryApi.SetVisible(Isvisible: Boolean); begin vstLocalHistory.Visible := Isvisible; slLocalHistory.Visible := Isvisible; end; { UserLocalHistoryApi } class procedure UserLocalHistoryApi.AddHistory(ControlPath, FolderPath: string); begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 已存在,则置顶 if FaceLocalHistoryApi.ReadIsExist( FolderPath ) then begin FaceLocalHistoryApi.MoveToTop( FolderPath ); Exit; end; // 超过上限,则删除 if FaceLocalHistoryApi.ReadHistoryCount > 15 then FaceLocalHistoryApi.RemoveLastNode; // 添加 FaceLocalHistoryApi.Add( FolderPath ); end; class function UserLocalHistoryApi.ControlPage(ControlPath: string): Boolean; begin Result := FacePageDriverApi.ControlPage( ControlPath ); end; class function UserLocalHistoryApi.ReadSelectList( ControlPath: string): TStringList; begin // 页面不存在 if not ControlPage( ControlPath ) then begin Result := TStringList.Create; Exit; end; Result := FaceLocalHistoryApi.ReadSelectList; end; class procedure UserLocalHistoryApi.RemoveHistory(ControlPath, FolderPath: string); begin // 页面不存在 if not ControlPage( ControlPath ) then Exit; // 删除 FaceLocalHistoryApi.Remove( FolderPath ); end; end.
unit UAirGameCell; interface uses UGameCell, Graphics, Classes, UPerson, UGameTypes; TYPE TAirGameCell = class (TGameCell) // Наш класс унаследован от базового - Игровой Клеточки private protected public constructor Create(AOwner: TComponent); override; // переопределяем КОНСТРУКТОР //для ввода начальных значений end; //---------------------------------------------------------- TFriendAirGameCell = class (TAirGameCell) //Этот класс мы наследуем от НАШЕГО private //базового класса protected procedure SetPerson(const Value: TPerson); override; public constructor Create(AOwner: TComponent); override; // нам необходимо только загрузить //другую картинку end; //---------------------------------------------------------- TMyAirGameCell = class (TAirGameCell) //аналогично - см выше private protected procedure SetPerson(const Value: TPerson); override; public constructor Create(AOwner: TComponent); override; end; //######################################################## var bmpAir,bmpFriendAir,bmpMyAir : TBitMap; implementation constructor TAirGameCell.Create(AOwner: TComponent); begin inherited; MyElement := 'Air'; FriendElement := 'Air'; If bmpAir = nil then begin bmpAir := TBitmap.Create; //создаём объект "картинка" try bmpAir.LoadFromFile('Pictures\AirOneCloud.bmp'); //загружаем в него //картинку из файла finally end; end; FBitMap := bmpAir; //присваиваем ссылку на картинку в наше приватное поле end; //---------------------------------------------------------- { TFriendAirGameCell } constructor TFriendAirGameCell.Create(AOwner: TComponent); begin inherited; MyElement := 'Air'; FriendElement := 'Air'; If bmpFriendAir = nil then begin bmpFriendAir := TBitmap.Create; //создаём объект "картинка" try bmpFriendAir.LoadFromFile('Pictures\AirTwoClouds.bmp'); //загружаем в него //картинку из файла finally end; end; FBitMap := bmpFriendAir; //присваиваем ссылку на картинку в наше приватное поле end; //---------------------------------------------------------- procedure TFriendAirGameCell.SetPerson(const Value: TPerson); begin inherited; If Value = nil then exit; If (Pos(MyElement,Value.ClassName)>0) OR (Pos(FriendElement,Value.ClassName)>0) then Value.HealthPoint := Value.HealthPoint+5 else Value.HealthPoint := Value.HealthPoint-5; Paint; end; { TMyAirGameCell } constructor TMyAirGameCell.Create(AOwner: TComponent); begin inherited; MyElement := 'Air'; FriendElement := 'Space'; If bmpMyAir = nil then begin bmpMyAir := TBitmap.Create; //создаём объект "картинка" try bmpMyAir.LoadFromFile('Pictures\AirFiveClouds.bmp'); //загружаем в него //картинку из файла finally end; end; FBitMap := bmpMyAir; //присваиваем ссылку на картинку в наше приватное поле end; procedure TMyAirGameCell.SetPerson(const Value: TPerson); begin inherited; If Value = nil then exit; If Pos(MyElement,Value.ClassName)>0 then Value.HealthPoint := Value.HealthPoint+10 Else If Pos(FriendElement,Value.ClassName)=0 then Value.HealthPoint := Value.HealthPoint-10; Paint; end; //--------------------МАГИЯ ССЫЛОК НА КЛАССЫ -------------- // Данная сейкция выполняется самой первой при загрузке программы // ещё до выполнения основного кода // это позволяет нам заполнить массив ССЫЛОК НА КЛАССЫ (ячеек и тп) // При выполнении основного кода массив уже будет заполнен. // Данная секция может присутствовать в любом модуле, секции выполняются последовательно // от модуля к модулю INITIALIZATION ClassGC[MaxGC] := TAirGameCell; Inc(MaxGC); ClassGC[MaxGC] := TFriendAirGameCell; Inc(MaxGC); ClassGC[MaxGC] := TMyAirGameCell; Inc(MaxGC); end.
//MYC:2006/08/17 = Correction in TRARHeaderDataEx interface in order to handle stress Filenames in archive { see UNRARDLL.TXT for Informations about UnRar.dll - Functions and structures } unit untUnRar; interface uses Windows; const { // deutsche Meldungen MSG1 = 'Fehler beim Schließen'; MSG2 = 'Kein Passwort angegeben!'; MSG3 = 'Verwendetes Passwort: '; MSG4 = 'UnRar.Dll nicht geladen'; MSG5 = 'Fehlerhafte Daten'; MSG6 = 'Fehlerhaftes Archiv'; MSG7 = 'Unbekanntes Datenformat'; MSG8 = 'Volumn-Fehler'; MSG9 = 'Fehler beim Erstellen der Datei'; MSG10 = 'Fehler beim Schließen der Datei'; MSG11 = 'Lesefehler'; MSG12 = 'Schreibfehler'; MSG14 = 'Kein Speicher'; MSG16 = 'Buffer zu klein'; MSG17 = 'Datei-Header defekt'; VOLDLGCAPTION = 'Nächstes Archiv: ...'; PASSDLGCAPTION = 'Passwort: ...'; CANCELCAPTION = 'Abbrechen'; OKCAPTION = 'Ok'; COMPRESSMETHODSTORE = 'speichern'; COMPRESSMETHODFASTEST = 'sehr schnell'; COMPRESSMETHODFAST = 'schnell'; COMPRESSMETHODNORMAL = 'normal'; COMPRESSMETHODGOOD = 'gut'; COMPRESSMETHODBEST = 'sehr gut'; } { // delete comments for english text MSG1 = 'Error on close'; MSG2 = 'No Password!'; MSG3 = 'Used Pass is: '; MSG4 = 'UnRar.Dll not loaded'; MSG5 = 'corrupt data'; MSG6 = 'Fehlerhaftes Archiv'; MSG7 = 'unknown format'; MSG8 = 'Volumn-Error'; MSG9 = 'error on create file'; MSG10 = 'error on closing file'; MSG11 = 'read error'; MSG12 = 'write error'; MSG14 = 'no memory'; MSG16 = 'buffer to small'; MSG17 = 'File Haeder corrupt'; VOLDLGCAPTION = 'Next Archive: ...'; PASSDLGCAPTION = 'Password: ...'; CANCELCAPTION = 'Cancel'; OKCAPTION = 'Ok'; COMPRESSMETHODSTORE = 'store'; COMPRESSMETHODFASTEST = 'fastest'; COMPRESSMETHODFAST = 'fast'; COMPRESSMETHODNORMAL = 'normal'; COMPRESSMETHODGOOD = 'good'; COMPRESSMETHODBEST = 'best'; } // delete comments for french text MSG1 = 'Erreur lors de la fermeture'; MSG2 = 'Pas de mot de passe!'; MSG3 = 'Le mot de passe utilisé est : '; MSG4 = 'UnRar.Dll not loaded'; MSG5 = 'données corrompues'; MSG6 = 'Archive défectueuse'; MSG7 = 'format inconnu'; MSG8 = 'Volumn-Error'; MSG9 = 'Erreur à la création du fichier'; MSG10 = 'Erreur à la fermeture du fichier'; MSG11 = 'Erreur de lecture'; MSG12 = 'Erreur d''écriture'; MSG14 = 'Mémoire insuffisante'; MSG16 = 'buffer trop petit'; MSG17 = 'Entête de fichier corrompu'; VOLDLGCAPTION = 'Archive suivante : ...'; PASSDLGCAPTION = 'Mot de passe : ...'; CANCELCAPTION = 'Annuler'; OKCAPTION = 'Ok'; COMPRESSMETHODSTORE = 'pas de compression'; COMPRESSMETHODFASTEST = 'la plus rapide'; COMPRESSMETHODFAST = 'rapide'; COMPRESSMETHODNORMAL = 'normale'; COMPRESSMETHODGOOD = 'bonne'; COMPRESSMETHODBEST = 'la meilleure'; // Constants not from UnRar.h ! RAR_METHOD_STORE = 48; RAR_METHOD_FASTEST = 49; RAR_METHOD_FAST = 50; RAR_METHOD_NORMAL = 51; RAR_METHOD_GOOD = 52; RAR_METHOD_BEST = 53; RAR_SUCCESS = 0; ERAR_COMMENTS_EXISTS = 1; ERAR_NO_COMMENTS = 0; // Constants from UnRar.h ERAR_END_ARCHIVE = 10; ERAR_NO_MEMORY = 11; ERAR_BAD_DATA = 12; ERAR_BAD_ARCHIVE = 13; ERAR_UNKNOWN_FORMAT = 14; ERAR_EOPEN = 15; ERAR_ECREATE = 16; ERAR_ECLOSE = 17; ERAR_EREAD = 18; ERAR_EWRITE = 19; ERAR_SMALL_BUF = 20; ERAR_UNKNOWN = 21; RAR_OM_LIST = 0; RAR_OM_EXTRACT = 1; RAR_SKIP = 0; RAR_TEST = 1; RAR_EXTRACT = 2; RAR_VOL_ASK = 0; RAR_VOL_NOTIFY = 1; RAR_DLL_VERSION = 3; UCM_CHANGEVOLUME = 0; UCM_PROCESSDATA = 1; UCM_NEEDPASSWORD = 2; // Max. Comment Size MAXRARCOMMENTSIZE = 1024 * 64; // 64kB type // Callback functions, the first 2 are deprecated - use TUnRarCallBack instead TProcessDataProc = function(Addr: PByte; Size: integer): integer; stdcall; TChangeVolProc = function(ArcName: PChar; Mode: integer): integer; stdcall; TUnRarCallBack = function(msg: Cardinal; UserData, P1, P2: longint): integer; stdcall; // Header for every file in an archive TRARHeaderData = record ArcName : array[0..259] of char; FileName : array[0..259] of char; Flags : cardinal; PackSize : cardinal; UnpSize : cardinal; HostOS : cardinal; FileCRC : cardinal; FileTime : cardinal; UnpVer : cardinal; Method : cardinal; FileAttr : cardinal; CmtBuf : PChar; CmtBufSize : cardinal; CmtSize : cardinal; CmtState : cardinal; end; PRARHeaderData = ^TRARHeaderData; // extended Header - not used in this component TRARHeaderDataEx = record ArcName : array[0..1023] of char; ArcNameW : array[0..1023] of WideChar; FileName : array[0..1023] of char; FileNameW : array[0..1023] of WideChar; Flags : cardinal; PackSize : cardinal; PackSizeHigh : cardinal; UnpSize : cardinal; UnpSizeHigh : cardinal; HostOS : cardinal; FileCRC : cardinal; FileTime : cardinal; UnpVer : cardinal; Method : cardinal; FileAttr : cardinal; CmtBuf : PChar; CmtBufSize : cardinal; CmtSize : cardinal; CmtState : cardinal; Reserved : array[1..1024] of cardinal; end; //MYC:2006/08/17 //PRARHeaderDataEx = TRARHeaderDataEx; PRARHeaderDataEx = ^TRARHeaderDataEx; // Archive-Data for opening rar-archive TRAROpenArchiveData = record ArcName : PChar; OpenMode : cardinal; OpenResult : cardinal; CmtBuf : PChar; CmtBufSize : cardinal; CmtSize : cardinal; CmtState : cardinal; end; PRAROpenArchiveData = ^TRAROpenArchiveData; // extended Archive-Data - not used in this component TRAROpenArchiveDataEx = record ArcName : PChar; ArcNameW : PWideChar; OpenMode : cardinal; OpenResult : cardinal; CmtBuf : PChar; CmtBufSize : cardinal; CmtSize : cardinal; CmtState : cardinal; Flags : cardinal; Reserved : array[1..32] of cardinal; end; PRAROpenArchiveDataEx = ^TRAROpenArchiveDataEx; var // Flag for: Is Dll loaded... IsLoaded: boolean = false; // function Pointer - Dll is always dynamicly loaded RAROpenArchive : function(ArchiveData: PRAROpenArchiveData): THandle; stdcall; RAROpenArchiveEx : function(ArchiveData: PRAROpenArchiveDataEx): THandle; stdcall; RARCloseArchive : function(hArcData: THandle): integer; stdcall; RARReadHeader : function(hArcData: THandle; HeaderData: PRARHeaderData): Integer; stdcall; RARReadHeaderEx : function(hArcData: THandle; HeaderData: PRARHeaderDataEx): Integer; stdcall; RARProcessFile : function(hArcData: THandle; Operation: Integer; DestPath, DestName: PChar): Integer; stdcall; RARSetCallback : procedure(hArcData: THandle; Callback: TUnRarCallback; UserData: longint); stdcall; RARSetChangeVolProc : procedure(hArcData: THandle; ChangeVolProc: TChangeVolProc); stdcall; RARSetProcessDataProc : procedure(hArcData: THandle; ProcessDataProc: TProcessDataProc); stdcall; RARSetPassword : procedure(hArcData: THandle; Password: PChar); stdcall; RARGetDllVersion : function:Integer; stdcall; // helper functions for (un)loading the Dll and check for loaded procedure LoadRarLibrary; procedure UnLoadRarLibrary; function IsRarLoaded: boolean; implementation var // Dll-Handle h: THandle; // Loads the UnRar.dll procedure LoadRarLibrary; begin // UnRar.dll must exists in typically dll-paths // 1. Application-Directory // 2. Current Directory // 3. System-Directory // 4. Windows-Direcory // 5. Directories from PATH-Variable h := LoadLibrary('unrar.dll'); if h <> 0 then begin IsLoaded := true; @RAROpenArchive := GetProcAddress(h, 'RAROpenArchive'); @RAROpenArchiveEx := GetProcAddress(h, 'RAROpenArchiveEx'); @RARCloseArchive := GetProcAddress(h, 'RARCloseArchive'); @RARReadHeader := GetProcAddress(h, 'RARReadHeader'); @RARReadHeaderEx := GetProcAddress(h, 'RARReadHeaderEx'); @RARProcessFile := GetProcAddress(h, 'RARProcessFile'); @RARSetCallback := GetProcAddress(h, 'RARSetCallback'); @RARSetChangeVolProc := GetProcAddress(h, 'RARSetChangeVolProc'); @RARSetProcessDataProc := GetProcAddress(h, 'RARSetProcessDataProc'); @RARSetPassword := GetProcAddress(h, 'RARSetPassword'); @RARGetDllVersion := GetProcAddress(h, 'RARGetDllVersion'); end; end; // Unloading Library procedure UnLoadRarLibrary; begin if h <> 0 then begin FreeLibrary(h); IsLoaded := false; h := 0; RAROpenArchive := nil; RAROpenArchiveEx := nil; RARCloseArchive := nil; RARReadHeader := nil; RARReadHeaderEx := nil; RARProcessFile := nil; RARSetCallback := nil; RARSetChangeVolProc := nil; RARSetProcessDataProc := nil; RARSetPassword := nil; RARGetDllVersion := nil; end; end; // returns true if UnRar.Dll is loaded function IsRarLoaded: boolean; begin Result := IsLoaded; end; end.
unit Main; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ScrollBox, FMX.Memo, FMX.Controls.Presentation, FMX.StdCtrls , UIntBus ; type TForm4 = class(TForm) Label1: TLabel; Label2: TLabel; LblStatus: TLabel; Label4: TLabel; LblRegister: TLabel; Memo1: TMemo; Memo2: TMemo; Button1: TButton; LblCurrentOP: TLabel; DumpRAM: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Button1Click(Sender: TObject); procedure DumpRAMClick(Sender: TObject); private FBus: IBus; procedure RefreshView; public { Public declarations } end; var Form4: TForm4; implementation uses StrUtils , UImpl6502 , UBus ; const TEST_CODE = '$A2 $0A $8E $00 $00 $A2 $03 $8E $01 $00 $AC $00 $00 $A9 $00 $18 $6D $01 $00 $88 $D0 $FA $8D $02 $00 $EA $EA $EA'; BASE_CODE = $8000; {$R *.fmx} procedure TForm4.Button1Click(Sender: TObject); begin (FBus as TBus).CPU.Clock; RefreshView; end; procedure TForm4.DumpRAMClick(Sender: TObject); var LRamFile: File; i: Integer; begin AssignFile(LRamFile, 'RAMDump.bin'); Rewrite(LRamFile, 64); try BlockWrite(LRamFile, (FBus as TBus).FRAM[0], 1024); finally CloseFile(LRamFile); end; end; procedure TForm4.FormCreate(Sender: TObject); var i: Integer; LHexaNumber: string; LCodeIndex: Integer; begin FBus := TBus.Create; (FBus as TBus).FRAM[$FFFC] := $00; (FBus as TBus).FRAM[$FFFD] := $80; i := 1; LCodeIndex := BASE_CODE; while i < Length(TEST_CODE) do begin LHexaNumber := Copy(TEST_CODE, i, 3); (FBus as TBus).FRAM[LCodeIndex] := StrToInt(LHexaNumber); Inc(LCodeIndex); Inc(i, 4); end; (FBus as TBus).CPU.Reset; end; procedure TForm4.FormDestroy(Sender: TObject); begin FBus := nil; end; procedure TForm4.RefreshView; begin LblStatus.Text := ''; if ((FBus as TBus).CPU.GetStatus and Ord(cfNegative)) <> 0 then LblStatus.Text := LblStatus.Text + '1 ' else LblStatus.Text := LblStatus.Text + '0 '; if ((FBus as TBus).CPU.GetStatus and Ord(cfOverflow)) <> 0 then LblStatus.Text := LblStatus.Text + '1 ' else LblStatus.Text := LblStatus.Text + '0 '; if ((FBus as TBus).CPU.GetStatus and Ord(cfUnused)) <> 0 then LblStatus.Text := LblStatus.Text + '1 ' else LblStatus.Text := LblStatus.Text + '0 '; if ((FBus as TBus).CPU.GetStatus and Ord(cfBreak)) <> 0 then LblStatus.Text := LblStatus.Text + '1 ' else LblStatus.Text := LblStatus.Text + '0 '; if ((FBus as TBus).CPU.GetStatus and Ord(cfDecimalMode)) <> 0 then LblStatus.Text := LblStatus.Text + '1 ' else LblStatus.Text := LblStatus.Text + '0 '; if ((FBus as TBus).CPU.GetStatus and Ord(cfDisableInterrupts)) <> 0 then LblStatus.Text := LblStatus.Text + '1 ' else LblStatus.Text := LblStatus.Text + '0 '; if ((FBus as TBus).CPU.GetStatus and Ord(cfZero)) <> 0 then LblStatus.Text := LblStatus.Text + '1 ' else LblStatus.Text := LblStatus.Text + '0 '; if ((FBus as TBus).CPU.GetStatus and Ord(cfCarry)) <> 0 then LblStatus.Text := LblStatus.Text + '1' else LblStatus.Text := LblStatus.Text + '0'; LblRegister.Text := ''; LblRegister.Text := LblRegister.Text + Format('%.2x ', [(FBus as TBus).CPU.GetA]); LblRegister.Text := LblRegister.Text + Format('%.2x ', [(FBus as TBus).CPU.GetX]); LblRegister.Text := LblRegister.Text + Format('%.2x ', [(FBus as TBus).CPU.GetY]); LblRegister.Text := LblRegister.Text + Format('%.2x ', [(FBus as TBus).CPU.GetStackP]); LblRegister.Text := LblRegister.Text + Format('%.4x ', [(FBus as TBus).CPU.GetPC]); end; end.
{ /** * @package Delphi Lua * @copyright Copyright (c) 2009 Dennis D. Spreen (http://www.spreendigital.de/blog) * @license http://opensource.org/licenses/gpl-license.php GNU Public License * @author Dennis D. Spreen <dennis@spreendigital.de> * @version 1.3 * @revision $Id: Lua.pas 102 2009-09-30 11:39:41Z dennis.spreen $ */ History 1.3 DS Improved Callback, now uses pointer instead of object index Modified RegisterFunctions to allow methods from other class to be registered, moved object table into TLua class 1.2 DS Added example on how to extend lua with a delphi dll 1.1 DS Improved global object table, this optimizes the delphi function calls 1.0 DS Initial Release Copyright 2009 Dennis D. Spreen (email : dennis@spreendigital.de) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA } unit Lua; interface uses Classes, LuaLib; type TLuaState = Lua_State; TLua = class(TObject) private fAutoRegister: Boolean; CallbackList: TList; // internal callback list public LuaInstance: TLuaState; // Lua instance constructor Create(AutoRegister: Boolean = True); overload; virtual; destructor Destroy; override; function DoFile(Filename: String): Integer; virtual;// load file and execute procedure RegisterFunction(FuncName: AnsiString; MethodName: AnsiString = ''; Obj: TObject = NIL); virtual; //register function procedure AutoRegisterFunctions(Obj: TObject); // register all published functions procedure UnregisterFunctions(Obj: TObject); // unregister all object functions end; implementation type TProc = function(L: TLuaState): Integer of object; // Lua Function TCallback = class Routine: TMethod; // Code and Data for the method Exec: TProc; // Resulting execution function end; // // This function is called by Lua, it extracts the object by // pointer to the objects method by name, which is then called. // // @param Lua_State L Pointer to Lua instance // @return Integer Number of result arguments on stack // function LuaCallBack(L: Lua_State): Integer; cdecl; var CallBack: TCallBack; // The Object stored in the Object Table begin // Retrieve first Closure Value (=Object Pointer) CallBack := lua_topointer(L, lua_upvalueindex(1)); // Execute only if Object is valid if (assigned(CallBack) and assigned(CallBack.Exec)) then Result := CallBack.Exec(L) else Result := 0; end; { TLua } // // Create a new Lua instance and optionally create Lua functions // // @param Boolean AutoRegister (optional) // @return TLua Lua Instance // constructor TLua.Create(AutoRegister: Boolean = True); begin inherited Create; // Load Lua Lib if not already done if (not LuaLibLoaded) then LoadLuaLib; // Open Library LuaInstance := Lua_Open(); luaopen_base(LuaInstance); fAutoRegister := AutoRegister; // Create Object List on initialization CallBackList := TList.Create; // if set then register published functions if (AutoRegister) then AutoRegisterFunctions(self); end; // // Dispose Lua instance // destructor TLua.Destroy; begin // Unregister all functions if previously autoregistered if (fAutoRegister) then UnregisterFunctions(Self); // dispose Object List on finalization CallBackList.Free; // Close instance Lua_Close(LuaInstance); inherited; end; // // Wrapper for Lua File load and Execution // // @param String Filename Lua Script file name // @return Integer // function TLua.DoFile(Filename: String): Integer; begin Result := lual_dofile(LuaInstance, PAnsiChar(AnsiString(Filename))); end; // // Register a new Lua Function and map it to the Objects method name // // @param AnsiString FuncName Lua Function Name // @param AnsiString MethodName (optional) Objects Method name // procedure TLua.RegisterFunction(FuncName: AnsiString; MethodName: AnsiString = ''; Obj: TObject = NIL); var CallBack: TCallBack; // Callback Object begin // if method name not specified use Lua function name if (MethodName = '') then MethodName := FuncName; // if not object specified use this object if (Obj = NIL) then Obj := Self; // Add Callback Object to the Object Index CallBack := TCallBack.Create; CallBack.Routine.Data := Obj; CallBack.Routine.Code := Obj.MethodAddress(String(MethodName)); CallBack.Exec := TProc(CallBack.Routine); CallbackList.Add(CallBack); // prepare Closure value (Method Name) lua_pushstring(LuaInstance, PAnsiChar(FuncName)); // prepare Closure value (CallBack Object Pointer) lua_pushlightuserdata(LuaInstance, CallBack); // set new Lua function with Closure value lua_pushcclosure(LuaInstance, LuaCallBack, 1); lua_settable(LuaInstance, LUA_GLOBALSINDEX); end; // // UnRegister all new Lua Function // // @param TObject Object Object with prev registered lua functions // procedure TLua.UnregisterFunctions(Obj: TObject); var I: Integer; CallBack: TCallBack; begin // remove obj from object list for I := CallBackList.Count downto 1 do begin CallBack := CallBackList[I-1]; if (assigned(CallBack)) and (CallBack.Routine.Data = Obj) then begin CallBack.Free; CallBackList.Items[I-1] := NIL; CallBackList.Delete(I-1); end; end; end; // // Register all published methods as Lua Functions // procedure TLua.AutoRegisterFunctions(Obj: TObject); type PPointer = ^Pointer; PMethodRec = ^TMethodRec; TMethodRec = packed record wSize: Word; pCode: Pointer; sName: ShortString; end; var MethodTable: PAnsiChar; MethodRec: PMethodRec; wCount: Word; nMethod: Integer; begin // Get a pointer to the class's published method table MethodTable := PAnsiChar(Pointer(PAnsiChar(Obj.ClassType) + vmtMethodTable)^); if (MethodTable <> Nil) then begin // Get the count of the methods in the table Move(MethodTable^, wCount, 2); // Position the MethodRec pointer at the first method in the table // (skip over the 2-byte method count) MethodRec := PMethodRec(MethodTable + 2); // Iterate through all the published methods of this class for nMethod := 0 to wCount - 1 do begin // Add the method name to the lua functions RegisterFunction(MethodRec.sName, MethodRec.sName, Obj); // Skip to the next method MethodRec := PMethodRec(PAnsiChar(MethodRec) + MethodRec.wSize); end; end; end; end.
//******************************************************* // // Delphi DataSnap Framework // // Copyright(c) 1995-2012 Embarcadero Technologies, Inc. // //******************************************************* unit DBXJsonTools; {$IFDEF FPC} {$mode DELPHI} {$ENDIF} interface uses DBXFPCJSON, DBXFPCCommon, Classes, {$IFDEF FPC} DB, BufDataset, FMTBcd, {$ELSE} Data.DB, {$ENDIF} DSRestTypes, DBXValue; type { TDBXJsonTools } TDBXJsonTools = class public class procedure jsonToDBX(obj: TJSONValue; var value: TDBXValue; dbxTypeName: String); class procedure JSONToValueType(json: TJSONArray; var vt: TDBXValueType); class function DBXParametersToJSONObject(dbxParameters: TDSParams) : TJSONObject; class function DBXReaderToJSONObject(dbxReader: TDBXReader): TJSONObject; class function CreateTDataSetFromJSON(value: TJSONObject): TDataset; class function TDataSetToJSONObject(value: TDataset): TJSONObject; class function GetTFieldTypeByTDBXDataTypes(DBXDataTypes: TDBXDataTypes) : TFieldType; class function GetTDBXDataTypesByTFieldType(FieldType: TFieldType) : TDBXDataTypes; class function CreateTStreamFromJSONArray(value: TJSONArray): TStream; class function StreamToJSONArray(value: TStream): TJSONArray; class function JSONToTableType(value: TJSONValue; dbxTypeName: String): TObject; class function SerializeTableType(Objetc: TObject): TJSONObject; end; implementation uses SysUtils, DBXDefaultFormatter,FPCStrings; { TDBXJsonTools } class procedure TDBXJsonTools.jsonToDBX(obj: TJSONValue; var value: TDBXValue; dbxTypeName: String); begin if TypeIsDBXValue(dbxTypeName) and (obj is TJSONNull) then begin value.AsDBXValue.SetNull; end else begin if not((obj is TJSONNull) and (trim(dbxTypeName) = '')) then begin case value.DBXType of Int8Type: begin if TypeIsDBXValue(dbxTypeName) then value.AsDBXValue.AsInt8 := TJSONNumber(obj).GetIntValue else value.AsInt8 := TJSONNumber(obj).GetIntValue; end; Int16Type: begin if TypeIsDBXValue(dbxTypeName) then value.AsDBXValue.AsInt16 := TJSONNumber(obj).GetIntValue else value.AsInt16 := TJSONNumber(obj).GetIntValue; end; Int32Type: begin if TypeIsDBXValue(dbxTypeName) then value.AsDBXValue.ASInt32 := TJSONNumber(obj).GetIntValue else value.ASInt32 := TJSONNumber(obj).GetIntValue; end; Int64Type: begin if TypeIsDBXValue(dbxTypeName) then value.AsDBXValue.ASInt64 := TJSONNumber(obj).GetIntValue else value.ASInt64 := TJSONNumber(obj).GetIntValue; end; UInt8Type: begin if TypeIsDBXValue(dbxTypeName) then value.AsDBXValue.AsUInt8 := TJSONNumber(obj).GetIntValue else value.AsUInt8 := TJSONNumber(obj).GetIntValue; end; UInt16Type: begin if TypeIsDBXValue(dbxTypeName) then value.AsDBXValue.AsUInt16 := TJSONNumber(obj).GetIntValue else value.AsUInt16 := TJSONNumber(obj).GetIntValue; end; UInt32Type: begin if TypeIsDBXValue(dbxTypeName) then value.AsDBXValue.AsUInt32 := TJSONNumber(obj).GetIntValue else value.AsUInt32 := TJSONNumber(obj).GetIntValue; end; UInt64Type: begin if TypeIsDBXValue(dbxTypeName) then value.AsDBXValue.ASInt32 := TJSONNumber(obj).GetIntValue else value.ASInt32 := TJSONNumber(obj).GetIntValue; end; AnsiStringType: begin {$WARNINGS OFF} if TypeIsDBXValue(dbxTypeName) then value.AsDBXValue.AsAnsiString := TJSONString(obj).GetValue else value.AsAnsiString := TJSONString(obj).GetValue; {$WARNINGS ON} end; WideStringType: begin if TypeIsDBXValue(dbxTypeName) then value.AsDBXValue.AsString := TJSONString(obj).GetValue else value.AsString := TJSONString(obj).GetValue; end; DateType: begin if TypeIsDBXValue(dbxTypeName) then value.AsDBXValue.AsTDBXDate := TDBXDefaultFormatter.GetInstance.StringToDBXDate (TJSONString(obj).GetValue) else value.AsTDBXDate := TDBXDefaultFormatter.GetInstance. StringToDBXDate(TJSONString(obj).GetValue); end; DoubleType: begin if TypeIsDBXValue(dbxTypeName) then value.AsDBXValue.AsDouble := TJSONNumber(obj).GetValue else value.AsDouble := TJSONNumber(obj).GetValue; end; BcdType: begin if TypeIsDBXValue(dbxTypeName) then value.AsDBXValue.AsBcd := TJSONNumber(obj).GetValue else value.AsBcd := TJSONNumber(obj).GetValue; end; BooleanType: begin if TypeIsDBXValue(dbxTypeName) then value.AsDBXValue.AsBoolean := obj is TJSONTrue else value.AsBoolean := obj is TJSONTrue; end; TimeType: begin if TypeIsDBXValue(dbxTypeName) then value.AsDBXValue.AsTDBXTime := TDBXDefaultFormatter.GetInstance.StringToDBXTime (TJSONString(obj).GetValue) else value.AsTDBXTime := TDBXDefaultFormatter.GetInstance. StringToDBXTime(TJSONString(obj).GetValue); end; DateTimeType: value.AsDateTime := TDBXDefaultFormatter.GetInstance.StringToDateTime (TJSONString(obj).GetValue); TableType: begin if TypeIsDBXValue(dbxTypeName) then value.AsDBXValue.AsTable := TDBXJsonTools.JSONToTableType (obj.Clone, dbxTypeName) else value.AsTable := TDBXJsonTools.JSONToTableType(obj.Clone, dbxTypeName); end; TimeStampType: begin if TypeIsDBXValue(dbxTypeName) then value.AsDBXValue.AsTimeStamp := TDBXDefaultFormatter.GetInstance.StringToDateTime (TJSONString(obj).GetValue) else value.AsTimeStamp := TDBXDefaultFormatter.GetInstance. StringToDateTime(TJSONString(obj).GetValue); end; CurrencyType: begin if TypeIsDBXValue(dbxTypeName) then value.AsDBXValue.AsCurrency := TJSONNumber(obj).GetCurrencyValue else value.AsCurrency := TJSONNumber(obj).GetCurrencyValue; end; SingleType: begin if TypeIsDBXValue(dbxTypeName) then value.AsDBXValue.AsSingle := TJSONNumber(obj).GetValue else value.AsSingle := TJSONNumber(obj).GetValue; end; JsonValueType: value.AsJsonValue := obj.Clone; BinaryBlobType: begin if TypeIsDBXValue(dbxTypeName) then value.AsDBXValue.AsStream := TDBXJsonTools.CreateTStreamFromJSONArray(TJSONArray(obj)) else value.AsStream := TDBXJsonTools.CreateTStreamFromJSONArray (TJSONArray(obj)); end; BlobType: value.AsBlob := TDBXJsonTools.CreateTStreamFromJSONArray (TJSONArray(obj)); CallbackType: ; else raise DBXException.create('Cannot convert Json to DBX'); end; end else value.clear; end; end; class procedure TDBXJsonTools.JSONToValueType(json: TJSONArray; var vt: TDBXValueType); begin vt.Name := json.getString(0); vt.setDataType(TDBXDataTypes(json.getInt(1))); vt.Ordinal := json.getInt(2); vt.SubType := json.getInt(3); vt.Scale := json.getInt(4); vt.Size := json.getInt(5); vt.Precision := json.getInt(6); vt.ChildPosition := json.getInt(7); vt.Nullable := json.getBoolean(8); vt.Hidden := json.getBoolean(9); vt.ParameterDirection := json.getInt(10); vt.ValueParameter := json.getBoolean(11); vt.Literal := json.getBoolean(12); end; class function TDBXJsonTools.DBXParametersToJSONObject(dbxParameters: TDSParams) : TJSONObject; var json: TJSONObject; arrParameters, arrParam, arrParamsValue: TJSONArray; I: Integer; begin json := TJSONObject.create; arrParameters := TJSONArray.create; json.AddPairs('table', arrParameters); for I := 0 to dbxParameters.Size - 1 do begin arrParam := TJSONArray.create; arrParam.Add(dbxParameters.getParameter(I).Name); arrParam.Add(dbxParameters.getParameter(I).getDataType); arrParam.Add(dbxParameters.getParameter(I).Ordinal); arrParam.Add(dbxParameters.getParameter(I).SubType); arrParam.Add(dbxParameters.getParameter(I).Scale); arrParam.Add(dbxParameters.getParameter(I).Size); arrParam.Add(dbxParameters.getParameter(I).Precision); arrParam.Add(dbxParameters.getParameter(I).ChildPosition); arrParam.Add(dbxParameters.getParameter(I).Nullable); arrParam.Add(dbxParameters.getParameter(I).Hidden); arrParam.Add(dbxParameters.getParameter(I).ParameterDirection); arrParam.Add(dbxParameters.getParameter(I).ValueParameter); arrParam.Add(dbxParameters.getParameter(I).Literal); arrParameters.Add(arrParam); end; for I := 0 to dbxParameters.Size() - 1 do begin arrParamsValue := TJSONArray.create; arrParamsValue.Add(dbxParameters.getParameter(I).GetValue.toString); json.AddPairs(dbxParameters.getParameter(I).Name, arrParamsValue); end; Result := json; end; class function TDBXJsonTools.DBXReaderToJSONObject(dbxReader: TDBXReader) : TJSONObject; var json: TJSONObject; arrayParams: TJSONArray; columns: TDSParams; I, C: Integer; begin try json := TJSONObject.create; columns := dbxReader.columns; arrayParams := TJSONArray.create; for I := 0 to columns.Size - 1 do begin arrayParams.Add(columns.getParameter(I).ToJSON); // Create the empty JSONArray for the data. Will be filled after json.AddPairs(columns.getParameter(I).Name, TJSONArray.create); end; while (dbxReader.Next) do begin for C := 0 to columns.Size - 1 do begin dbxReader.columns.getParameter(C).GetValue.AppendTo (json.GetJSONArray(columns.getParameter(C).Name)); end; end; json.AddPairs('table', arrayParams); Result := json; except on e: exception do raise DBXException.create(e.Message); end; end; class function TDBXJsonTools.CreateTDataSetFromJSON(value: TJSONObject) : TDataset; {$IFDEF FPC} var json: TJSONArray; I: Integer; val: TDBXValue; FieldName, s: String; FieldSize: Integer; FieldType: TFieldType; rdr: TDBXReader; {$ENDIF} begin {$IFDEF FPC} Result := TBufDataset.create(nil); rdr := TDBXReader.CreateFrom(value); try for I := 0 to rdr.columns.Size - 1 do begin FieldName := rdr.columns.getParameter(I).Name; FieldType := GetTFieldTypeByTDBXDataTypes (TDBXDataTypes(rdr.columns.getParameter(I).getDataType)); if FieldType in [ftString, ftWideString] then FieldSize := rdr.columns.getParameter(I).Size else FieldSize := 0; Result.FieldDefs.Add(FieldName, FieldType, FieldSize); end; TBufDataset(Result).CreateDataset; Result.Active := True; I := 0; while rdr.Next do begin Result.Append; for I := 0 to rdr.columns.Size - 1 do begin case TDBXDataTypes(rdr.columns.getParameter(I).getDataType) of AnsiStringType, WideStringType: Result.Fields[I].AsString := rdr.GetValue(I).AsString; DateType: Result.Fields[I].AsDateTime := rdr.GetValue(I).AsTDBXDate; DateTimeType, TimeStampType: Result.Fields[I].AsDateTime := rdr.GetValue(I).AsDateTime; TimeType: Result.Fields[I].AsDateTime := rdr.GetValue(I).AsTDBXTime; BooleanType: Result.Fields[I].AsBoolean := rdr.GetValue(I).AsBoolean; Int16Type: Result.Fields[I].AsInteger := rdr.GetValue(I).AsInt16; Int32Type: Result.Fields[I].AsInteger := rdr.GetValue(I).ASInt32; UInt16Type: Result.Fields[I].AsInteger := rdr.GetValue(I).AsUInt16; UInt32Type: Result.Fields[I].AsInteger := rdr.GetValue(I).AsUInt32; Int8Type: Result.Fields[I].AsInteger := rdr.GetValue(I).AsInt8; UInt8Type: Result.Fields[I].AsInteger := rdr.GetValue(I).AsUInt8; DoubleType, BcdType: Result.Fields[I].AsFloat := rdr.GetValue(I).AsDouble; SingleType: Result.Fields[I].AsFloat := rdr.GetValue(I).AsSingle; Int64Type: Result.Fields[I].AsLargeInt := rdr.GetValue(I).ASInt64; UInt64Type: Result.Fields[I].AsLargeInt := rdr.GetValue(I).AsUInt64; CurrencyType: Result.Fields[I].AsCurrency := rdr.GetValue(I).AsCurrency; BinaryBlobType: TBlobField(Result.Fields[I]) .LoadFromStream(rdr.GetValue(I).AsStream); BlobType: TBlobField(Result.Fields[I]).LoadFromStream(rdr.GetValue(I).AsBlob); // TimeStampOffsetType, TimeStampType: // Result.Fields[i].AsLargeInt := rdr.GetValue(i).AsTimeStamp; end; end; Result.Post; end; Result.First; finally rdr.Free; end; {$ELSE} result:= nil; {$ENDIF} end; class function TDBXJsonTools.TDataSetToJSONObject(value: TDataset): TJSONObject; var json: TJSONObject; arr, arrayParams: TJSONArray; column: TDBXParameter; I, C: Integer; ms: TMemoryStream; begin try json := TJSONObject.create; arrayParams := TJSONArray.create; for I := 0 to value.FieldCount - 1 do begin column := TDBXParameter.create; column.Name := value.FieldDefs[I].Name; column.setDataType(TDBXJsonTools.GetTDBXDataTypesByTFieldType (value.FieldDefs[I].DataType)); column.Size := value.FieldDefs[I].Size; arrayParams.Add(column.ToJSON); // Create the empty JSONArray for the data. Will be filled after json.AddPairs(column.Name, TJSONArray.create); column.Free; end; value.First; while not value.EOF do begin for C := 0 to value.FieldCount - 1 do begin arr := json.GetJSONArray(value.FieldDefs[C].Name); case value.FieldDefs[C].DataType of ftString: arr.Add(value.Fields[C].AsString); ftDate, ftTime, ftDateTime, ftTimeStamp: arr.Add(TDBXDefaultFormatter.GetInstance.DateTimeToString (value.Fields[C].AsDateTime)); ftBoolean: arr.Add(value.Fields[C].AsBoolean); ftInteger, ftWord: arr.Add(value.Fields[C].AsInteger); ftFloat: arr.Add(value.Fields[C].AsFloat); {$IFDEF FPC} ftBCD: arr.Add(BCDToDouble(value.Fields[C].AsBcd)); {$ENDIF} ftLargeint: arr.Add(value.Fields[C].AsLargeInt); ftCurrency: arr.Add(double(value.Fields[C].AsCurrency)); ftWideString: arr.Add(value.Fields[C].AsWideString); ftBlob, ftMemo, ftGraphic, ftWideMemo: begin ms := TMemoryStream.create; try TBlobField(value.Fields[C]).SaveToStream(ms); ms.Position := 0; arr.Add(StreamToJSONArray(ms)); finally ms.Free; end; end; else raise DBXException.create('Fied type not supported'); end; // case end; // for value.Next; end; // while json.AddPairs('table', arrayParams); Result := json; except on e: exception do raise DBXException.create(e.Message); end; end; class function TDBXJsonTools.GetTFieldTypeByTDBXDataTypes (DBXDataTypes: TDBXDataTypes): TFieldType; begin case DBXDataTypes of AnsiStringType: Result := ftString; DateType: Result := ftDate; BlobType: Result := ftBlob; BooleanType: Result := ftBoolean; Int16Type, Int32Type, UInt16Type, UInt32Type, Int8Type, UInt8Type: Result := ftInteger; DoubleType: Result := ftFloat; BcdType: Result := ftBCD; TimeType: Result := ftTime; DateTimeType: Result := ftDateTime; Int64Type, UInt64Type: Result := ftLargeint; TimeStampType: Result := ftTimeStamp; CurrencyType: Result := ftCurrency; WideStringType: Result := ftWideString; SingleType: Result := ftFloat; BinaryBlobType: Result := ftBlob; TimeStampOffsetType: Result := ftTimeStamp; else raise DBXException.create('invalid data type'); end; end; class function TDBXJsonTools.GetTDBXDataTypesByTFieldType(FieldType: TFieldType) : TDBXDataTypes; begin case FieldType of ftString: Result := AnsiStringType; ftDate: Result := DateType; ftBoolean: Result := BooleanType; ftInteger, ftWord: Result := Int32Type; ftFloat: Result := DoubleType; ftBCD: Result := BcdType; ftTime: Result := TimeType; ftDateTime: Result := DateTimeType; ftLargeint: Result := Int64Type; ftTimeStamp: Result := TimeStampType; ftCurrency: Result := CurrencyType; ftWideString: Result := WideStringType; ftBlob: Result := BinaryBlobType; ftMemo: Result := BlobType; else raise DBXException.create('invalid field type'); end; end; class function TDBXJsonTools.CreateTStreamFromJSONArray (value: TJSONArray): TStream; {$IFDEF FPC} var I: Integer; b: byte; begin try Result := TMemoryStream.create; for I := 0 to value.Size - 1 do begin b := byte(value.getInt(I)); Result.WriteByte(b); end; Result.Position := 0; except on e: exception do raise DBXException.create(e.Message); end; {$ELSE} begin result:= nil; {$ENDIF} end; class function TDBXJsonTools.StreamToJSONArray(value: TStream): TJSONArray; {$IFDEF FPC} var b: byte; old_pos: Integer; {$ENDIF} begin Result := TJSONArray.create; {$IFDEF FPC} if assigned( value) then begin old_pos := value.Position; value.Position := 0; while value.Position < value.Size do begin b := value.ReadByte; Result.Add(b); end; value.Position := old_pos; end; {$ENDIF} end; class function TDBXJsonTools.JSONToTableType(value: TJSONValue; dbxTypeName: String): TObject; begin try if dbxTypeName = 'TDSParams' then begin exit(TDSParams.CreateFrom(TJSONObject(value))) end else if ((dbxTypeName = 'TDBXReader') or (dbxTypeName = 'TDBXReaderValue')) then begin exit(TDBXReader.CreateFrom(TJSONObject(value))); end else if dbxTypeName = 'TDataSet' then begin exit(TDBXJsonTools.CreateTDataSetFromJSON(TJSONObject(value))); end else raise DBXException.create(dbxTypeName + ' is not a table type'); except on e: exception do raise DBXException.create(e.Message); end; end; class function TDBXJsonTools.SerializeTableType(Objetc: TObject): TJSONObject; begin try if Objetc is TDSParams then begin Result := TDSParams(Objetc).asJSONObject; end else if Objetc is TDBXReader then begin Result := TDBXReader(Objetc).asJSONObject; end else if Objetc is TDataset then begin Result := TDBXJsonTools.TDataSetToJSONObject(TDataset(Objetc)); end else raise DBXException.create('Invalid table type to serialize'); except on e: exception do raise DBXException.create(e.Message); end; end; end.
unit unAplEditaTexto; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, AdvPanel, AdvGlassButton, Xml.XMLDoc, System.Contnrs, AdvAppStyler, AdvGlowButton; type TfmAplEditaTexto = class(TForm) PanelBotoes: TAdvPanel; PanelCentral: TAdvPanel; FormStyler: TAdvFormStyler; BitBtnFechar: TAdvGlowButton; BitBtnSalvar: TAdvGlowButton; BitBtnLimpar: TAdvGlowButton; BitBtnRestaurar: TAdvGlowButton; MemoEditor: TMemo; procedure BitBtnLimparClick(Sender: TObject); procedure BitBtnFecharClick(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormCreate(Sender: TObject); procedure BitBtnSalvarClick(Sender: TObject); procedure BitBtnRestaurarClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } pId: TGUID; pTexto: TStrings; pSomenteLeitura: boolean; procedure setaTexto(prmTexto: TStrings); procedure setaSomenteLeitura(prmSomenteLeitura: boolean); function obtemTexto: TStrings; function obtemSomenteLeitura: boolean; public { Public declarations } property Texto: TStrings read obtemTexto write setaTexto; property SomenteLeitura: boolean read obtemSomenteLeitura write setaSomenteLeitura; end; var fmAplEditaTexto: TfmAplEditaTexto; implementation {$R *.dfm} uses unPrincipal, undmEstilo; procedure TfmAplEditaTexto.BitBtnFecharClick(Sender: TObject); begin Close; end; procedure TfmAplEditaTexto.BitBtnLimparClick(Sender: TObject); begin MemoEditor.Lines.Clear; end; procedure TfmAplEditaTexto.BitBtnRestaurarClick(Sender: TObject); begin MemoEditor.Lines.Text := Texto.Text; end; procedure TfmAplEditaTexto.BitBtnSalvarClick(Sender: TObject); begin Texto := MemoEditor.Lines; Close; end; procedure TfmAplEditaTexto.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TfmAplEditaTexto.FormCreate(Sender: TObject); begin try CreateGUID(pId); Color := Self.Color; FormStyler.AutoThemeAdapt := false; pTexto := TStringList.Create; Texto.Clear; FormResize(Sender); except on E: Exception do begin fmPrincipal.manipulaExcecoes(Sender,E); Close; end; end; end; procedure TfmAplEditaTexto.FormResize(Sender: TObject); begin BitBtnFechar.Left := PanelBotoes.Width - BitBtnFechar.Width - fmPrincipal.EspacamentoFinalBotao; BitBtnRestaurar.Left := BitBtnFechar.Left - BitBtnRestaurar.Width - fmPrincipal.EspacamentoEntreBotoes; BitBtnLimpar.Left := BitBtnRestaurar.Left - BitBtnLimpar.Width - fmPrincipal.EspacamentoEntreBotoes; BitBtnSalvar.Left := BitBtnLimpar.Left - BitBtnSalvar.Width - fmPrincipal.EspacamentoEntreBotoes; end; procedure TfmAplEditaTexto.FormShow(Sender: TObject); begin MemoEditor.Lines.Text := Texto.Text; BitBtnSalvar.Enabled := not SomenteLeitura; BitBtnLimpar.Enabled := not SomenteLeitura; BitBtnRestaurar.Enabled := not SomenteLeitura; MemoEditor.Enabled := not SomenteLeitura; end; function TfmAplEditaTexto.obtemSomenteLeitura: boolean; begin Result := pSomenteLeitura; end; function TfmAplEditaTexto.obtemTexto: TStrings; begin Result := pTexto; end; procedure TfmAplEditaTexto.setaSomenteLeitura(prmSomenteLeitura: boolean); begin pSomenteLeitura := prmSomenteLeitura; end; procedure TfmAplEditaTexto.setaTexto(prmTexto: TStrings); begin pTexto := prmTexto; end; end.
{ $HDR$} {**********************************************************************} { Unit archived using Team Coherence } { Team Coherence is Copyright 2002 by Quality Software Components } { } { For further information / comments, visit our WEB site at } { http://www.TeamCoherence.com } {**********************************************************************} {} { $Log: 11257: HeaderListTest.pas { { Rev 1.0 11/12/2002 09:18:24 PM JPMugaas { Initial check in. Import from FTP VC. } unit HeaderListTest; interface uses IndyBox, IdHeaderList; type THeaderListProc = class(TIndyBox) public procedure Test; override; end; implementation { THeaderListProc } procedure THeaderListProc.Test; var h : TIdHeaderList; begin h := TIdHeaderList.Create; try h.Add('Subject: This is a'); h.Add(' folded line.'); Check(h.Values['Subject']='This is a folded line.' ,'Wrong value'); h.Values['Subject'] := ''; Check(h.Count = 0,'HeaderList count should have been zero'); h.Add('Subject: This is a'); h.Add(' folded line.'); h.Add('Subject2: This is a'); h.Add(' folded line.'); h.Values['Subject'] := ''; Check(h.Count = 2,'HeaderList count should have been two.'); Check(h.Values['Subject2']='This is a folded line.','Expected value not returned'); h.Values['Subject2'] := ''; h.Add('FirstValue: This is a'); h.Add(' folded line.'); h.Add('Dummy: This is a dummy line for a test'); Check(h.Values['FirstValue']='This is a folded line.','Expected value not returned'); finally h.Free; end; end; initialization TIndyBox.RegisterBox(THeaderListProc, 'HeaderList', 'Misc'); end.
unit Dash; interface uses W3C.DOM, W3C.HTML5; type JLogLevel = Integer; JLogLevelHelper = strict helper for JLogLevel const LOG_LEVEL_NONE = 0; const LOG_LEVEL_FATAL = 1; const LOG_LEVEL_ERROR = 2; const LOG_LEVEL_WARNING = 3; const LOG_LEVEL_INFO = 4; const LOG_LEVEL_DEBUG = 5; end; JMediaType = String; JMediaTypeHelper = strict helper for JMediaType const Video = 'video'; const Audio = 'audio'; const Text = 'text'; const FragmentedText = 'fragmentedText'; const EmbeddedText = 'embeddedText'; const Image = 'image'; end; JDashLogger = class external (* debug(...params: any[]): void; info(...params: any[]): void; warn(...params: any[]): void; error(...params: any[]): void; fatal(...params: any[]): void; *) end; Debug = class external function getLogger: JDashLogger; procedure setLogTimestampVisible(flag: boolean); procedure setCalleeNameVisible(flag: boolean); end; JVideoModel = Variant; JProtectionController = class external (* initializeForMedia(mediaInfo: ProtectionMediaInfo): void; createKeySession(initData: ArrayBuffer, cdmData: Uint8Array): void; removeKeySession(session: SessionToken): void; closeKeySession(session: SessionToken): void; setServerCertificate(serverCertificate: ArrayBuffer): void; setMediaElement(element: HTMLMediaElement): void; setSessionType(type: string): void; setRobustnessLevel(level: string): void; setProtectionData(protData: ProtectionData): void; getSupportedKeySystemsFromContentProtection(cps: any[]): SupportedKeySystem[]; getKeySystems(): KeySystem[]; procedure setKeySystems(keySystems: KeySystem[]); *) procedure stop; procedure reset; end; JBitrate = class external width: Integer; height: Integer; bandwidth: Float; scanType: String; end; JMediaInfo = class external id: String; index: Integer; &type: JMediaType; (* streamInfo: JStreamInfo; *) representationCount: Integer; labels: array of String; lang: string; viewpoint: Variant; accessibility: array of Variant; audioChannelConfiguration: array of Variant; roles: array of String; codec: String; mimeType: String; contentProtection: Variant; isText: Boolean; KID: Variant; (* bitrateList: array of JBitrate; *) end; JProtectionMediaInfo = class external codec: String; contentProtection: Variant; end; JMediaPlayerSettingDebugClass = class external logLevel: JLogLevel; end; JMediaPlayerSettingStreamingClass = class external metricsMaxListDepth: Integer; abandonLoadTimeout: Integer; liveDelayFragmentCount: Integer; (* liveDelay?: number; scheduleWhilePaused?: boolean; fastSwitchEnabled?: boolean; bufferPruningInterval?: number; bufferToKeep?: number; bufferAheadToKeep?: number; jumpGaps?: boolean; smallGapLimit?: number; stableBufferTime?: number; bufferTimeAtTopQuality?: number; bufferTimeAtTopQualityLongForm?: number; longFormContentDurationThreshold?: number; wallclockTimeUpdateInterval?: number; lowLatencyEnabled?: boolean; keepProtectionMediaKeys?: boolean; useManifestDateHeaderTimeSource?: boolean; useSuggestedPresentationDelay?: boolean; useAppendWindowEnd?: boolean, manifestUpdateRetryInterval?: number; liveCatchUpMinDrift?: number; liveCatchUpMaxDrift?: number; liveCatchUpPlaybackRate?: number; lastBitrateCachingInfo?: { enabled?: boolean; ttl?: number; }; lastMediaSettingsCachingInfo?: { enabled?: boolean; ttl?: number; }; cacheLoadThresholds?: { video?: number; audio?: number; }; retryIntervals?: { 'MPD'?: number; 'XLinkExpansion'?: number; 'MediaSegment'?: number; 'InitializationSegment'?: number; 'BitstreamSwitchingSegment'?: number; 'IndexSegment'?: number; 'other'?: number; }; retryAttempts?: { 'MPD'?: number; 'XLinkExpansion'?: number; 'MediaSegment'?: number; 'InitializationSegment'?: number; 'BitstreamSwitchingSegment'?: number; 'IndexSegment'?: number; 'other'?: number; }; abr?: { movingAverageMethod?: 'slidingWindow' | 'ewma'; ABRStrategy?: 'abrDynamic' | 'abrBola'; bandwidthSafetyFactor?: number; useDefaultABRRules?: boolean; useBufferOccupancyABR?: boolean; useDeadTimeLatency?: boolean; limitBitrateByPortal?: boolean; usePixelRatioInLimitBitrateByPortal?: boolean; maxBitrate?: { audio?: number; video?: number; }; minBitrate?: { audio?: number; video?: number; }; maxRepresentationRatio?: { audio?: number; video?: number; }; initialBitrate?: { audio?: number; video?: number; }; initialRepresentationRatio?: { audio?: number; video?: number; }; autoSwitchBitrate?: { audio?: boolean; video?: boolean; }; } } *) end; JMediaPlayerSettingClass = class external debug: JMediaPlayerSettingDebugClass; streaming: JMediaPlayerSettingStreamingClass; end; JMediaPlayer = class external 'dashjs.MediaPlayer' class function create: JMediaPlayer; procedure initialize(Element: JHTMLElement); overload; procedure initialize(Element: JHTMLElement; Source: String); overload; procedure initialize(Element: JHTMLElement; Source: String; AutoPlay: Boolean); overload; procedure extend(ParentNameString: String; ChildInstance: Variant; &Override: Boolean); procedure attachView(Element: JHTMLElement); procedure attachSource(UrlOrManifest: Variant); function isReady: Boolean; procedure play; function isPaused: Boolean; procedure pause; function isSeeking: Boolean; function isDynamic: Boolean; procedure seek(Value: Float); procedure setPlaybackRate(Value: Float); function getPlaybackRate: Integer; procedure setMute(Value: Boolean); function isMuted: Boolean; procedure setVolume(value: Float); function getVolume: Integer; function time: Integer; overload; function time(streamId: String): Integer; overload; function duration: Integer; function timeAsUTC: Integer; function durationAsUTC: Integer; function getActiveStream: Variant; function getDVRWindowSize: Integer; function getDVRSeekOffset(value: Integer): Integer; function convertToTimeCode(value: Integer): String; function formatUTC(Time: Integer; Locales: String; Hour12: Boolean): String; overload; function formatUTC(Time: Integer; Locales: String; Hour12: Boolean; WithDate: Boolean): String; overload; function getVersion: string; (* function getDebug: Debug; *) function getBufferLength(&type: JMediaType): Integer; function getVideoModel: JVideoModel; function getTTMLRenderingDiv: JHTMLDivElement; function getVideoElement: JHTMLVideoElement; function getSource: String; (* function getTopBitrateInfoFor(type: MediaType): BitrateInfo; *) procedure setAutoPlay(value: Boolean); function getAutoPlay: Boolean; (* function getDashMetrics: DashMetrics; function getDashAdapter: DashAdapter; *) function getQualityFor(&type: JMediaType): Integer; procedure setQualityFor(&type: JMediaType; Value: Integer); procedure updatePortalSize; procedure enableText(Enable: Boolean); procedure setTextTrack(Index: Integer); function getTextDefaultLanguage: string; procedure setTextDefaultLanguage(Lang: String); function getTextDefaultEnabled: Boolean; procedure setTextDefaultEnabled(Enable: Boolean); (* function getThumbnail(time: Float): Thumbnail; function getBitrateInfoListFor(type: MediaType): BitrateInfo[]; function getStreamsFromManifest(manifest: object): StreamInfo[]; function getTracksFor(&type: JMediaType): array of JMediaInfo; procedure getTracksForTypeFromManifest(&type: JMediaType; manifest: Variant; streamInfo: JStreamInfo): array of JMediaInfo; function getCurrentTrackFor(&type: JMediaType): JMediaInfo; procedure setInitialMediaSettingsFor(type: JMediaType, value: MediaSettings); function getInitialMediaSettingsFor(type: JMediaType): MediaSettings; *) procedure setCurrentTrack(track: JMediaInfo); (* procedure getTrackSwitchModeFor(type: JMediaType): TrackSwitchMode; procedure setTrackSwitchModeFor(type: JMediaType; mode: TrackSwitchMode); procedure setSelectionModeForInitialTrack(mode: TrackSelectionMode); procedure getSelectionModeForInitialTrack: TrackSelectionMode; procedure retrieveManifest(url: string, callback: (manifest: object | null, error: any) => void); *) procedure addUTCTimingSource(SchemeIdUri, Value: string); procedure removeUTCTimingSource(SchemeIdUri, Value: string); procedure clearDefaultUTCTimingSources; procedure restoreDefaultUTCTimingSources; (* procedure setXHRWithCredentialsForType(type: string, value: Boolean); procedure getXHRWithCredentialsForType(type: string): Boolean; procedure getProtectionController: ProtectionController; procedure attachProtectionController(value: ProtectionController); procedure setProtectionData(value: ProtectionData); *) procedure enableManifestDateHeaderTimeSource(Value: Boolean); procedure displayCaptionsOnTop(Value: Boolean); procedure attachTTMLRenderingDiv(&Div: JHTMLDivElement); function getCurrentTextTrackIndex: Integer; procedure preload; procedure reset; procedure addABRCustomRule(&Type, RuleName: String; Rule: Variant); procedure removeABRCustomRule(RuleName: String); procedure removeAllABRCustomRule; function getCurrentLiveLatency: Integer; procedure enableForcedTextStreaming(Value: Boolean); function isTextEnabled: Boolean; procedure getAverageThroughput(Value: Float); function getSettings: JMediaPlayerSettingClass; procedure updateSettings(settings: JMediaPlayerSettingClass); procedure resetSettings; end; JDashJS = class external 'dashjs' function MediaPlayer: JMediaPlayer; end; var DashJS external 'dashjs': JDashJS; function MediaPlayer: JMediaPlayer; external 'dashjs.MediaPlayer'; implementation end.
unit TrafficUnit; interface uses SysUtils, Windows, IPHelper, IPHLPAPI; type TTraffic = Class; TNewInstanceEvent = procedure(Sender :TTraffic) of object; TFreezeEvent = procedure(Sender :TTraffic) of object; TTraffic = Class private FIP: string; FMac: string; FInPerSec: Dword; FInTotal: Dword; FPeakInPerSec: Dword; FInterfaceIndex: DWord; FActiveCountIn: Dword; FSecondsActive: Cardinal; FPrevCountIn: DWord; FDescription: string; FOutTotal: Dword; FPeakOutPerSec: Dword; FOutPerSec: Dword; FPrevCountOut: DWord; FActiveCountOut: Dword; FAverageInPerSec: Dword; FAverageOutPerSec: Dword; FStartedAt: TDateTime; FRunning: boolean; FOnFreeze: TFreezeEvent; FOnUnFreeze: TFreezeEvent; FConnected: boolean; FFound: boolean; FSpeed: DWord; function GetIPFromIFIndex(InterfaceIndex: Cardinal): string; public property Found : boolean read FFound write FFound; property Connected : boolean read FConnected; property Running : boolean read FRunning; property InterfaceIndex : DWord read FInterfaceIndex; property IP : string read FIP; property Mac : string read FMac; property Description : string read FDescription; property StartedAt : TDateTime read FStartedAt; property SecondsActive : Cardinal read FSecondsActive; property Speed : DWord read FSpeed; property ActiveCountIn : Dword read FActiveCountIn; { count of samples where something was received } property PrevCountIn : DWord read FPrevCountIn; { previous byte count in } property InPerSec : Dword read FInPerSec; { byte count in of last sample period } property AverageInPerSec : Dword read FAverageInPerSec; { Average in } property InTotal : Dword read FInTotal; { total byte count in } property PeakInPerSec : Dword read FPeakInPerSec; { peak byte count in } property ActiveCountOut : Dword read FActiveCountOut; { count of samples where something was sent } property PrevCountOut : DWord read FPrevCountOut; { previous byte count out } property OutPerSec : Dword read FOutPerSec; { byte count out of last sample period } property AverageOutPerSec : Dword read FAverageOutPerSec; { Average Out } property OutTotal : Dword read FOutTotal; { total byte count out } property PeakOutPerSec : Dword read FPeakOutPerSec; { peak byte count out } procedure NewCycle(const InOctets, OutOctets, TrafficSpeed : Dword); procedure Reset; procedure Freeze; procedure UnFreeze; procedure MarkDisconnected; function GetStatus : string; function FriendlyRunningTime:string; constructor Create(const AMibIfRow : TMibIfRow; OnNewInstance : TNewInstanceEvent); published property OnFreeze :TFreezeEvent read FOnFreeze write FOnFreeze; property OnUnFreeze :TFreezeEvent read FOnUnFreeze write FOnUnFreeze; end; function BytesToFriendlyString(Value : DWord) : string; function BitsToFriendlyString(Value : DWord) : string; implementation function BytesToFriendlyString(Value : DWord) : string; const OneKB=1024; OneMB=OneKB*1024; OneGB=OneMB*1024; begin if Value<OneKB then Result:=FormatFloat('#,##0.00 B',Value) else if Value<OneMB then Result:=FormatFloat('#,##0.00 KB', Value/OneKB) else if Value<OneGB then Result:=FormatFloat('#,##0.00 MB', Value/OneMB) end; function BitsToFriendlyString(Value : DWord) : string; const OneKB=1000; OneMB=OneKB*1000; OneGB=OneMB*1000; begin if Value<OneKB then Result:=FormatFloat('#,##0.00 bps',Value) else if Value<OneMB then Result:=FormatFloat('#,##0.00 Kbps', Value/OneKB) else if Value<OneGB then Result:=FormatFloat('#,##0.00 Mbps', Value/OneMB) end; constructor TTraffic.Create(const AMibIfRow: TMibIfRow; OnNewInstance : TNewInstanceEvent); var Descr: string; begin inherited Create; FRunning:=true; FConnected:=true; self.FInterfaceIndex:=AMibIfRow.dwIndex; self.FIP:=GetIPFromIFIndex(self.InterfaceIndex); self.FMac:=MacAddr2Str(TMacAddress(AMibIfRow.bPhysAddr), AMibIfRow.dwPhysAddrLen); SetLength(Descr, Pred(AMibIfRow.dwDescrLen)); Move(AMibIfRow.bDescr, Descr[1], pred(AMibIfRow.dwDescrLen)); self.FDescription:=Trim(Descr); self.FPrevCountIn:=AMibIfRow.dwInOctets; self.FPrevCountOut:=AMibIfRow.dwOutOctets; self.FStartedAt:=Now; self.FSpeed:=AMibIfRow.dwSpeed; FActiveCountIn:=0; FActiveCountOut:=0; FInTotal:=0; FOutTotal:=0; FInPerSec:=0; FOutPerSec:=0; FPeakInPerSec:=0; FPeakOutPerSec:=0; //notify this instance if Assigned(OnNewInstance) then OnNewInstance(self); end; procedure TTraffic.NewCycle(const InOctets, OutOctets, TrafficSpeed: Dword); begin inc(self.FSecondsActive); if not Running then Exit; FSpeed:=TrafficSpeed; // in self.FInPerSec:=InOctets-self.PrevCountIn; Inc(self.FInTotal, self.InPerSec); if InPerSec>0 then Inc(FActiveCountIn); if InPerSec>PeakInPerSec then FPeakInPerSec:=InPerSec; try if ActiveCountIn<>0 then self.FAverageInPerSec:=InTotal div ActiveCountIn except self.FAverageInPerSec:=0; end; FPrevCountIn:=InOctets; // out self.FOutPerSec:=OutOctets-self.PrevCountOut; Inc(self.FOutTotal,self.OutPerSec); if OutPerSec>0 then Inc(FActiveCountOut); if OutPerSec>PeakOutPerSec then FPeakOutPerSec:=OutPerSec; try if ActiveCountIn<>0 then self.FAverageOutPerSec:=OutTotal div ActiveCountOut except self.FAverageOutPerSec:=0; end; FPrevCountOut:=OutOctets; end; function TTraffic.GetIPFromIFIndex(InterfaceIndex: Cardinal): string; var i: integer; IPArr: TMIBIPAddrArray; begin Result:='Not found!'; // shouldn't happen... Get_IPAddrTableMIB(IpArr); // get IP-address table if Length(IPArr)>0 then for i:=low(IPArr) to High(IPArr) do // look for matching index... if IPArr[i].dwIndex=InterfaceIndex then begin Result:=IPAddr2Str(IParr[i].dwAddr); Break; end; end; procedure TTraffic.Reset; begin self.FPrevCountIn:=InPerSec; self.FPrevCountOut:=OutPerSec; self.FStartedAt:=Now; FSecondsActive:=0; FActiveCountIn:=0; FActiveCountOut:=0; FInTotal:=0; FOutTotal:=0; FInPerSec:=0; FOutPerSec:=0; FPeakInPerSec:=0; FPeakOutPerSec:=0; end; procedure TTraffic.Freeze; begin FRunning:=false; if Assigned(FOnFreeze) then OnFreeze(Self); end; procedure TTraffic.UnFreeze; begin FRunning:=true; if Assigned(FOnUnFreeze) then OnUnFreeze(Self); end; procedure TTraffic.MarkDisconnected; begin self.FConnected:=false; self.FRunning:=false; end; function TTraffic.GetStatus: string; begin if self.Connected then Result:='Connected' else Result:='Not connected'; if self.Running then Result:=Result+', Running' else Result:=Result+', Not running'; end; function TTraffic.FriendlyRunningTime: string; var H,M,S: string; ZH,ZM,ZS: integer; begin ZH:=SecondsActive div 3600; ZM:=Integer(SecondsActive) div (60-ZH*60); ZS:=Integer(SecondsActive)-(ZH*3600+ZM*60); H:=Format('%.2d',[ZH]); M:=Format('%.2d',[ZM]); S:=Format('%.2d',[ZS]); Result:=H+':'+M+':'+S; end; end.
unit ClothesTypesReg.View; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, Common.Types, Common.Form, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Edit, Database.Types, Clothes.Classes, Clothes.ViewModel, Clothes.DataModule, Data.Bind.EngExt, Fmx.Bind.DBEngExt, System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.Components, Data.Bind.DBScope, FMX.EditBox, FMX.SpinBox; type TfrmClothesTypeReg = class(TCommonForm) lbl1: TLabel; edtTitle: TEdit; spnOrderNo: TSpinBox; procedure btnOkClick(Sender: TObject); private FViewModel: TClothesViewModel; FClothesType: TClothesType; FOperation: TOperation; procedure SetCtrlVal; procedure GetCtrlVal; procedure SetOperation(const Value: TOperation); function GetClothesType: TClothesType; { Private declarations } public constructor Create(AOwner: TComponent; AViewModel: TClothesViewModel; AnOperation: TOperation = opInsert); reintroduce; property Operation: TOperation read FOperation; // write SetOperation; property ClothesType: TClothesType read GetClothesType; { Public declarations } end; //var // frmClothesTypeReg: TfrmClothesTypeReg; implementation {$R *.fmx} {$R *.Windows.fmx MSWINDOWS} { TfrmClothesTypeReg } procedure TfrmClothesTypeReg.btnOkClick(Sender: TObject); var fr: TFunctionResult; begin // inherited; ModalResult := mrNone; GetCtrlVal; fr := FViewModel.SaveClothesTypesDataset; if fr.Successful then ModalResult := mrOk; end; constructor TfrmClothesTypeReg.Create(AOwner: TComponent; AViewModel: TClothesViewModel; AnOperation: TOperation); begin inherited Create(AOwner); FViewModel := AViewModel; FOperation := AnOperation; FClothesType := FViewModel.ClothesType; btnOk.ModalResult := mrOk; btnClose.ModalResult := mrCancel; end; function TfrmClothesTypeReg.GetClothesType: TClothesType; begin Result := FClothesType; end; procedure TfrmClothesTypeReg.GetCtrlVal; begin FClothesType.Name := edtTitle.Text; FClothesType.OrderNo := spnOrderNo.Text.ToInteger; end; procedure TfrmClothesTypeReg.SetCtrlVal; begin edtTitle.Text := FClothesType.Name; spnOrderNo.Text := FClothesType.OrderNo.ToString; end; procedure TfrmClothesTypeReg.SetOperation(const Value: TOperation); begin FOperation := Value; if FOperation <> opInsert then SetCtrlVal; end; end.