text
stringlengths
14
6.51M
unit ANovaTransferencia; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, Componentes1, ExtCtrls, PainelGradiente, Localizacao, StdCtrls, Buttons, ComCtrls, Mask, numericos, UnDadosCR, UnCaixa,SqlExpr; type TTipoTela = (ttTransferencia,ttAplicacao,ttResgate); TFNovaTransferencia = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor1: TPanelColor; PanelColor2: TPanelColor; Label1: TLabel; EDatTransferencia: TCalendario; BGravar: TBitBtn; BCancelar: TBitBtn; Localiza: TConsultaPadrao; EValor: Tnumerico; Label2: TLabel; Label3: TLabel; EObservacao: TEditColor; PContaCaixaDestino: TPanelColor; Label28: TLabel; EContaCorrente: TEditLocaliza; SpeedButton3: TSpeedButton; Label38: TLabel; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BCancelarClick(Sender: TObject); procedure BGravarClick(Sender: TObject); private { Private declarations } VprAcao : Boolean; VprCaixaOrigem : String; VprTipoTela : TTipoTela; FunCaixa : TRBFuncoesCaixa; function DadosValidos : String; function GravaCaixaOrigem : String; function GravaCaixaDestino : String; function GravaAplicacao : string; function GravaResgate : string; procedure ConfiguraTela; function GravaTransferencia: String; public { Public declarations } function TransferenciaCaixa(VpaCaixaOrigem : String):Boolean; function AplicarDinheiro(VpaCaixa : String):Boolean; function ResgataDinheiro(VpaCaixa : String):Boolean; end; var FNovaTransferencia: TFNovaTransferencia; implementation uses APrincipal, Constantes, constmsg; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFNovaTransferencia.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } VprAcao := false; FunCaixa := TRBFuncoesCaixa.cria(FPrincipal.BaseDados); EDatTransferencia.Date := date; end; { ******************* Quando o formulario e fechado ************************** } procedure TFNovaTransferencia.BGravarClick(Sender: TObject); var VpfResultado : String; VpfTransacao : TTransactionDesc; begin VpfResultado := ''; VpfTransacao.IsolationLevel :=xilDIRTYREAD; FPrincipal.BaseDados.StartTransaction(VpfTransacao); case VprTipoTela of ttTransferencia: VpfResultado := GravaTransferencia; ttAplicacao: VpfResultado := GravaAplicacao; ttResgate: VpfResultado := GravaResgate; end; if VpfResultado <> '' then begin if FPrincipal.BaseDados.inTransaction then FPrincipal.BaseDados.Rollback(VpfTransacao); aviso(VpfResultado) end else begin FPrincipal.BaseDados.Commit(VpfTransacao); VprAcao := true; close; end; end; {******************************************************************************} procedure TFNovaTransferencia.ConfiguraTela; begin case VprTipoTela of ttAplicacao: begin Self.Caption := 'Aplicação'; PainelGradiente1.Caption := ' Aplicação '; PContaCaixaDestino.Visible := false; self.Height := PainelGradiente1.Height+PanelColor1.Height+PanelColor2.Height; end; ttResgate: begin Self.Caption := 'Resgate'; PainelGradiente1.Caption := ' Resgate '; PContaCaixaDestino.Visible := false; self.Height := PainelGradiente1.Height+PanelColor1.Height+PanelColor2.Height; end; end; end; {******************************************************************************} procedure TFNovaTransferencia.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } FunCaixa.Free; Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************************************************************************} function TFNovaTransferencia.TransferenciaCaixa(VpaCaixaOrigem : String):Boolean; begin VprTipoTela := ttTransferencia; VprCaixaOrigem := VpaCaixaOrigem; showmodal; result := VprAcao; end; {******************************************************************************} function TFNovaTransferencia.DadosValidos : String; begin result := ''; if VprCaixaOrigem = EContaCorrente.Text then result := 'CONTA CAIXA DESTINO IGUAL A CONTA ORIGEM!!!'#13'A conta caixa destino não pode ser igual a conta caixa origem.'; if result = '' then begin if FunCaixa.RSeqCaixa(VprCaixaOrigem)= 0 then result := 'CAIXA ORIGEM NÃO ABERTO!!!'#13'É necessário abrir o caixa origem antes de fazer a transferência.'; if result = '' then begin if FunCaixa.RSeqCaixa(EContaCorrente.Text)= 0 then result := 'CAIXA DESTINO NÃO ABERTO!!!'#13'É necessário abrir o caixa destino antes de fazer a transferência.'; end; end; end; {******************************************************************************} function TFNovaTransferencia.GravaCaixaOrigem : String; var VpfDCaixa : TRBDCaixa; VpfDItemCaixa : TRBDCaixaItem; VpfSeqCaixaOrigem : Integer; begin VpfDCaixa := TRBDCaixa.cria; VpfSeqCaixaOrigem := FunCaixa.RSeqCaixa(VprCaixaOrigem); FunCaixa.CarDCaixa(VpfDCaixa,VpfSeqCaixaOrigem); VpfDItemCaixa := VpfDCaixa.AddCaixaItem; VpfDItemCaixa.CodUsuario := varia.codigoUsuario; VpfDItemCaixa.CodFormaPagamento := varia.FormaPagamentoDinheiro; VpfDItemCaixa.DesLancamento := 'Transferência entre caixa "'+EContaCorrente.Text+'" '+EObservacao.Text; VpfDItemCaixa.DesDebitoCredito := 'D'; VpfDItemCaixa.ValLancamento := EValor.AValor; VpfDItemCaixa.DatPagamento := EDatTransferencia.Date; VpfDItemCaixa.DatLancamento :=EDatTransferencia.Date; result := FunCaixa.GravaDCaixa(VpfDCaixa); end; {******************************************************************************} function TFNovaTransferencia.GravaResgate: string; var VpfDCaixa : TRBDCaixa; VpfDItemCaixa : TRBDCaixaItem; VpfSeqCaixaOrigem : Integer; begin VpfDCaixa := TRBDCaixa.cria; VpfSeqCaixaOrigem := FunCaixa.RSeqCaixa(VprCaixaOrigem); FunCaixa.CarDCaixa(VpfDCaixa,VpfSeqCaixaOrigem); VpfDItemCaixa := VpfDCaixa.AddCaixaItem; VpfDItemCaixa.CodUsuario := varia.codigoUsuario; VpfDItemCaixa.CodFormaPagamento := varia.FormaPagamentoDinheiro; VpfDItemCaixa.DesLancamento := 'Valor resgatado da aplicação na conta "'+EContaCorrente.Text+'" '+EObservacao.Text; VpfDItemCaixa.DesDebitoCredito := 'C'; VpfDItemCaixa.ValLancamento := EValor.AValor; VpfDItemCaixa.DatPagamento := EDatTransferencia.Date; VpfDItemCaixa.DatLancamento := EDatTransferencia.Date; result := FunCaixa.GravaDCaixa(VpfDCaixa); if result = '' then result := FunCaixa.ResgataValor(VpfDCaixa,VpfDItemCaixa); end; {******************************************************************************} function TFNovaTransferencia.GravaTransferencia: String; begin result := DadosValidos; if result = '' then begin result := GravaCaixaOrigem; if result = '' then result := GravaCaixaDestino; end; end; {******************************************************************************} function TFNovaTransferencia.ResgataDinheiro(VpaCaixa: String): Boolean; begin VprCaixaOrigem := VpaCaixa; VprTipoTela := ttResgate; ConfiguraTela; ShowModal; result := VprAcao; end; {******************************************************************************} function TFNovaTransferencia.GravaAplicacao: string; var VpfDCaixa : TRBDCaixa; VpfDItemCaixa : TRBDCaixaItem; VpfSeqCaixaOrigem : Integer; begin VpfDCaixa := TRBDCaixa.cria; VpfSeqCaixaOrigem := FunCaixa.RSeqCaixa(VprCaixaOrigem); FunCaixa.CarDCaixa(VpfDCaixa,VpfSeqCaixaOrigem); VpfDItemCaixa := VpfDCaixa.AddCaixaItem; VpfDItemCaixa.CodUsuario := varia.codigoUsuario; VpfDItemCaixa.CodFormaPagamento := varia.FormaPagamentoDinheiro; VpfDItemCaixa.DesLancamento := 'Valor aplicado na conta "'+EContaCorrente.Text+'" '+EObservacao.Text; VpfDItemCaixa.DesDebitoCredito := 'D'; VpfDItemCaixa.ValLancamento := EValor.AValor; VpfDItemCaixa.DatPagamento := Date; VpfDItemCaixa.DatLancamento := Date; result := FunCaixa.GravaDCaixa(VpfDCaixa); if result = '' then result := FunCaixa.AplicaValor(VpfDCaixa,VpfDItemCaixa); end; {******************************************************************************} function TFNovaTransferencia.GravaCaixaDestino : String; var VpfDCaixa : TRBDCaixa; VpfDItemCaixa : TRBDCaixaItem; VpfSeqCaixaDestino : Integer; begin VpfDCaixa := TRBDCaixa.cria; VpfSeqCaixaDestino := FunCaixa.RSeqCaixa(EContaCorrente.Text); FunCaixa.CarDCaixa(VpfDCaixa,VpfSeqCaixaDestino); VpfDItemCaixa := VpfDCaixa.AddCaixaItem; VpfDItemCaixa.CodUsuario := varia.codigoUsuario; VpfDItemCaixa.CodFormaPagamento := varia.FormaPagamentoDinheiro; VpfDItemCaixa.DesLancamento := 'Transferência entre caixa "'+VprCaixaOrigem+'" '+EObservacao.Text; VpfDItemCaixa.DesDebitoCredito := 'C'; VpfDItemCaixa.ValLancamento := EValor.AValor; VpfDItemCaixa.DatPagamento := Date; VpfDItemCaixa.DatLancamento := Date; result := FunCaixa.GravaDCaixa(VpfDCaixa); end; {******************************************************************************} function TFNovaTransferencia.AplicarDinheiro(VpaCaixa: String): Boolean; begin VprCaixaOrigem := VpaCaixa; VprTipoTela := ttAplicacao; ConfiguraTela; ShowModal; result := VprAcao; end; {******************************************************************************} procedure TFNovaTransferencia.BCancelarClick(Sender: TObject); begin close; end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFNovaTransferencia]); end.
unit Table; interface uses {$IFDEF FPC} LResources, {$ENDIF} {$IFNDEF LINUX} Windows, Messages, {$ENDIF} Classes, SysUtils, Menus, ImgList, StdCtrls, ComCtrls, Buttons, ExtCtrls, Graphics, Controls, Forms, Dialogs, DBCtrls, Grids, DBGrids, UniDacVcl, Variants, {$IFNDEF FPC} MemDS, {$ELSE} MemDataSet, {$ENDIF} DB, DBAccess, Uni, DemoFrame, UniDacDemoForm; type TTableFrame = class(TDemoFrame) DBGrid: TDBGrid; DataSource: TDataSource; btOpen: TSpeedButton; btClose: TSpeedButton; btPrepare: TSpeedButton; btUnPrepare: TSpeedButton; btExecute: TSpeedButton; DBNavigator: TDBNavigator; UniTable: TUniTable; Panel2: TPanel; Panel3: TPanel; Panel5: TPanel; Label1: TLabel; edTableName: TEdit; Panel6: TPanel; Label2: TLabel; edKeyFields: TEdit; Panel7: TPanel; Label3: TLabel; edOrderFields: TEdit; Panel8: TPanel; Label4: TLabel; edFilterSQL: TEdit; procedure btOpenClick(Sender: TObject); procedure btCloseClick(Sender: TObject); procedure btPrepareClick(Sender: TObject); procedure btUnPrepareClick(Sender: TObject); procedure btExecuteClick(Sender: TObject); procedure edTableNameExit(Sender: TObject); procedure edKeyFieldsExit(Sender: TObject); procedure edOrderFieldsExit(Sender: TObject); procedure edFilterSQLExit(Sender: TObject); private procedure ShowState; procedure SetTableProperties; public procedure Initialize; override; procedure SetDebug(Value: boolean); override; end; implementation {$IFNDEF FPC} {$IFDEF CLR} {$R *.nfm} {$ELSE} {$R *.dfm} {$ENDIF} {$ENDIF} procedure TTableFrame.ShowState; var St:string; procedure AddSt(S:string); begin if St <> '' then St:= St + ', '; St:= St + S; end; begin St:= ''; if UniTable.Prepared then begin AddSt('Prepared'); if UniTable.IsQuery then AddSt('IsQuery'); end; if UniTable.Active then AddSt('Active') else AddSt('Inactive'); UniDacForm.StatusBar.Panels[1].Text:= St; end; procedure TTableFrame.SetTableProperties; begin UniTable.TableName := edTableName.Text; UniTable.KeyFields := edKeyFields.Text; UniTable.FilterSQL := edFilterSQL.Text; UniTable.OrderFields := edOrderFields.Text; end; procedure TTableFrame.btOpenClick(Sender: TObject); begin try SetTableProperties; UniTable.Open; finally edKeyFields.Text:= UniTable.KeyFields; ShowState; end; end; procedure TTableFrame.btCloseClick(Sender: TObject); begin UniTable.Close; ShowState; end; procedure TTableFrame.btPrepareClick(Sender: TObject); begin try SetTableProperties; UniTable.Prepare; finally edKeyFields.Text:= UniTable.KeyFields; ShowState; end; end; procedure TTableFrame.btUnPrepareClick(Sender: TObject); begin UniTable.UnPrepare; ShowState; end; procedure TTableFrame.btExecuteClick(Sender: TObject); begin try SetTableProperties; UniTable.Execute; finally edKeyFields.Text:= UniTable.KeyFields; ShowState; end; end; procedure TTableFrame.edTableNameExit(Sender: TObject); begin UniTable.TableName:= edTableName.Text; edKeyFields.Text:= UniTable.KeyFields; ShowState; end; procedure TTableFrame.edKeyFieldsExit(Sender: TObject); begin UniTable.KeyFields:= edKeyFields.Text; ShowState; end; procedure TTableFrame.edOrderFieldsExit(Sender: TObject); begin UniTable.OrderFields:= edOrderFields.Text; edKeyFields.Text:= UniTable.KeyFields; ShowState; end; procedure TTableFrame.edFilterSQLExit(Sender: TObject); begin try UniTable.FilterSQL:= edFilterSQL.Text; finally edFilterSQL.Text:= UniTable.FilterSQL; ShowState; end; end; procedure TTableFrame.Initialize; begin UniTable.Connection := TUniConnection(Connection); edTableName.Text := UniTable.TableName; edKeyFields.Text := UniTable.KeyFields; edOrderFields.Text := UniTable.OrderFields; edFilterSQL.Text := UniTable.FilterSQL; ShowState; end; procedure TTableFrame.SetDebug(Value: boolean); begin UniTable.Debug := Value; end; {$IFDEF FPC} initialization {$i Table.lrs} {$ENDIF} end.
// ------------------------------------------------------------------------------- // Um programa em Pascal que lê um número não conhecido de valores,um de cada vez, // e conta quantos deles estão em cada um dos intervalos [0, 50], (50, 100], //(100,200]. O programa deve encerrar ou terminar, quando for lido um valor fora // dos intervalos acima dados // ------------------------------------------------------------------------------- //Cadeira : Introdução a Informática //Curso : Ciencias de Informação Geográfica - 2o Ano - Laboral //Docente : Doutor Orlando Zacarias //Discentes : Fernando Gomes; Lino Domingos; Samuel Ouana; Shelton Novela //Data de entrega : 16/07/2021 // ------------------------------------------------------------------------------- Program Contador_de_numeros_dentro_dos_Intervalos; // Secção de Declarações das variáveis Var A : Array [1..200] of real; i : Integer; B, C, D , tam: Integer; //As letras B, C, D representam os intervalos [0 - 50], ]50 - 100], ]100 - 200], respectivamente Begin //Inicialização dos contadores B:=0; C:=0; D:=0; Write ('Quantos numeros quer digitar? '); Readln(tam); Writeln(); if (tam > 200) then //O tamanho dos numeros que pretende inserir nao pode ser superior a 200 writeln('O tamanho não pode ser superior a 200') else For i:= 1 to tam do Begin Write ('Insira ', i,'° elemento = '); Read (A[i]); //Delimitando o intervalo If ((A[i] > 200) OR (A[i] < 0)) then Begin Writeln (' '); Writeln ('Não inserir valores abaixo de 0 ou acima de 200'); exit; end; end; For i:= 1 to tam do //Análise do número digitado, visando determinar o número de valores em cada intervalo If (A[i] <= 50) then Begin B := B+1; end else if ((A[i] >= 50) AND (A[i] <= 100)) then begin C:= C+1; end else D:= D+1; //Impressão dos resultados Writeln (' '); Writeln ('No intervalo de [0-50] são ',B,' Números'); Writeln ('No intervalo de ]50-100] são ',C,' Números'); Writeln ('No intervalo de ]100-200] são ',D,' Números'); End.
//ALGORITHME : CARRE_MAGIQUE //BUT : Creer un carre magique de 5x5 ou 7x7 //ENTREE : //SORTIE : Carre magique (* procedure matrice (var carre : Tableau, n : entier) var i, j : entier DEBUT pour i + 1 A 5 faire DEBUT pour j + 1 A 5 faire DEBUT ECRIRE Carre[i, j] FIN FIN FIN procedure remplir_matrice(var carre : tableau, n : entier) var : i, a, j: ENTIER DEBUT i <- n div 2 j <- (n div 2) +1 a <- 0 REPETER SI carre[i, j] = 0 ALORS DEBUT a <- a + 1 Carre[i, j] <- a i <- i - 1 j <- j + 1 SI Carre[i, j] <> 0 ALORS DEBUT i <- i - 1 j <- j -1 FINSI SI i <- 5 ALORS i <- 1 SI i <- 1 ALORS i <- 5 SI j <- 5 ALORS j <- 1 SI j < 1 ALORS i <- 5 FINSI JUSQU'A a = 25 ECRIRE carre[i,j] FIN var : Carre : Tableau[1..5,1..5] de ENTIER i, a, j, n: ENTIER DEBUT ECRIRE "taille de la matrice" LIRE n SI (n = 5) ou (n=7) ALORS remplir_matrice(carre, n) matrice(carre,n) SINON ECRIRE "Ce n'est pas 5 ou 7" FINSI FIN *) program carre_magique; uses crt; type mat = array [0..8, 0..8] of integer; procedure matrice (var carre : mat; n : integer); var i, j : integer; begin for i := 0 to n+1 do// il s'agit de l'affichage du tableau begin for j := 0 to n+1 do begin if (i = 0) or (i = n +1) or (j = 0) or (j = n+1) then// de 64 à 68 : c'est le cadre du carre magique begin carre[i,j] := -1; Textcolor(green); write('[ ]'); end else begin (*if carre[i,j] = -1 then write('[ ]') else*) (*if (i <> 0) or (i <> n +1) or (j <> 0) or (j <> n+1) then*) Textcolor(yellow); if carre[i,j] < 10 then// J'ai ajouté un espace en plus pour qu'il y ait le même espace entre les chiffres qu'ils soient inferieur ou superieur a 10 write(' ', carre[i,j]) else write (' ', carre[i,j]); end; end; writeln; end; end; procedure remplir_matrice (var carre : mat; n : integer); var i, j, a : integer; begin a := 0; i:= (n DIV 2); j:= (n DIV 2) +1; repeat begin if carre[i,j] = 0 then begin a := a+1; carre[i,j] := a; i := i -1;// déplacement dans la matrice j := j +1; if i < 1 then //faire retourner au debut de la matrice si elle dépasse le max ou le min i := n; if j > n then j := 1; end else begin if carre[i,j] <> 0 then begin while carre[i,j] <> 0 do begin i := i -1; j := j -1; if i < 1 then i := n; if j < 1 then j := n; end; end; end; end; until a = sqr(n); end; var carre : mat; i, j, a, n : integer; BEGIN clrscr; writeln('programme carre magique'); writeln('Voici un carre magique'); writeln('Entrez la dimension entre 5 et 7.'); readln(n); if (n = 7) or (n = 5) then begin remplir_matrice(carre,n); matrice(carre,n); readln; end else writeln('Ce n''est pas 5 ou 7'); readln; end. (*begin for i := 0 to 6 do begin for j := 0 to 6 do begin carre[i, j] := 0; end end; a:= 0; x := 2; y := 3; for i:=0 to 6 do Begin for j:=0 to 6 do Begin if (i = 0) or (i = 6) or (j = 0) or (j = 6) then begin carre[i, j] := 1; Textcolor(green); end else begin carre[i,j]:= -2; Textcolor(yellow); end; if carre[i,j] = 1 then write('[ ]') else begin a := a +1; if (carre[i,j] = -2) then begin carre[x,y] := a; x := x -1; y := y +1; if x < 1 then x := 5; if y > 5 then y := 1; carre[i,j] := carre[x, y]; if carre[x,y] < 10 then write(' ',carre[x,y]) else write(' ',carre[x,y]); end else begin if carre[i,j] <> -2 then begin x := x +1; end else begin if carre[i,j] = -2 then carre[x, y] := a; if x < 1 then x := 5; if y < 1 then y := 5; carre[i,j] := carre[x, y]; if carre[x,y] < 10 then write(' ',carre[x,y]) else write(' ', carre[x,y]); end; end; end; end; writeln; end; readln; end.*)
// ------------------------------------------------------------------------------- // Descrição: Um programa em Pascal que determina se um determinado número, // lido do teclado, é impar // ------------------------------------------------------------------------------- //Autor : Fernando Gomes //Data : 19/08/2021 // ------------------------------------------------------------------------------- Program num_impar ; //Seção de Declarações das variáveis var num: integer; Begin //Pede ao usuario que insira um numero Write('Digite um número: '); Readln(num); //A Funcao ODD verifica a paridade do argumento, //retornando true se o argumento é ímpar, false em caso //contrário if odd(num) then write('O número ',num, ' é impar') else write('O número ',num, ' não é impar') End.
{**********************************************************************} {* Иллюстрация к книге "OpenGL в проектах Delphi" *} {* Краснов М.В. softgl@chat.ru *} {**********************************************************************} unit frmMain; interface uses Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Menus, Controls, Dialogs, SysUtils, OpenGL; type Vector = record x, y, z : GLfloat; end; type TfrmGL = class(TForm) procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private DC: HDC; hrc: HGLRC; Model, Normals : TList; lastx, down : Integer; procedure Init; procedure CalcNormals; procedure SetDCPixelFormat; procedure LoadDXF (st : String); protected procedure WMPaint(var Msg: TWMPaint); message WM_PAINT; end; const SURFACE = 1; var frmGL: TfrmGL; Angle : GLfloat = 0; Step : GLfloat = 1; wrkStep : GLfloat = 1; wrkTime : longint; wrkX, wrkY : Integer; implementation {$R *.DFM} {$WARNINGS OFF} procedure TfrmGL.LoadDXF (st : String); var f : TextFile; wrkString : String; group, err : GLint; x1, x2, y1, y2, z1, z2, x3, y3, z3 : GLfloat; procedure AddToList (x, y, z : GLfloat); var wrkVector : Vector; pwrkVector : ^Vector; begin wrkVector.x := x; wrkVector.y := y; wrkVector.z := z; New (pwrkVector); pwrkVector^ := wrkVector; Model.Add (pwrkVector); end; begin AssignFile(f,st); Reset(f); repeat // пропускаем файл до секции объектов "ENTITIES" ReadLn(f, wrkString); until (wrkString = 'ENTITIES') or eof(f); While not eof (f) do begin ReadLn (f, group); // маркер ReadLn (f, wrkString); // идентификатор либо координата case group of 0: begin // начался следующий объект AddToList (x3, y3, z3); AddToList (x2, y2, z2); AddToList (x1, y1, z1); end; 10: val(wrkString, x1, err); 20: val(wrkString, y1, err); 30: val(wrkString, z1, err); 11: val(wrkString, x2, err); 21: val(wrkString, y2, err); 31: val(wrkString, z2, err); 12: val(wrkString, x3, err); 22: val(wrkString, y3, err); 32: val(wrkString, z3, err); end; end; CloseFile(f); end; {$WARNINGS ON} {$HINTS OFF} procedure TfrmGL.CalcNormals; var i : Integer; wrki, vx1, vy1, vz1, vx2, vy2, vz2 : GLfloat; nx, ny, nz : GLfloat; wrkVector : Vector; pwrkVector : ^Vector; wrkVector1, wrkVector2, wrkVector3 : Vector; pwrkVector1, pwrkVector2, pwrkVector3 : ^Vector; begin New (pwrkVector1); New (pwrkVector2); New (pwrkVector3); For i := 0 to round (Model.Count / 3) - 1 do begin pwrkVector1 := Model [i * 3]; wrkVector1 := pwrkVector1^; pwrkVector2 := Model [i * 3 + 1]; wrkVector2 := pwrkVector2^; pwrkVector3 := Model [i * 3 + 2]; wrkVector3 := pwrkVector3^; vx1 := wrkVector1.x - wrkVector2.x; vy1 := wrkVector1.y - wrkVector2.y; vz1 := wrkVector1.z - wrkVector2.z; vx2 := wrkVector2.x - wrkVector3.x; vy2 := wrkVector2.y - wrkVector3.y; vz2 := wrkVector2.z - wrkVector3.z; // вектор перпендикулярен центру треугольника nx := vy1 * vz2 - vz1 * vy2; ny := vz1 * vx2 - vx1 * vz2; nz := vx1 * vy2 - vy1 * vx2; // получаем унитарный вектор единичной длины wrki := sqrt (nx * nx + ny * ny + nz * nz); If wrki = 0 then wrki := 1; // для предотвращения деления на ноль wrkVector.x := nx / wrki; wrkVector.y := ny / wrki; wrkVector.z := nz / wrki; New (pwrkVector); pwrkVector^ := wrkVector; Normals.Add (pwrkVector); end; end; {$HINTS ON} {======================================================================= Инициализация} procedure TfrmGL.Init; begin glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable (GL_COLOR_MATERIAL); glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 1); glColor3f (0.4, 0.6, 0.6); end; {======================================================================= Перерисовка окна} procedure TfrmGL.WMPaint(var Msg: TWMPaint); var ps : TPaintStruct; begin BeginPaint (Handle, ps); glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); glPushMatrix; glRotatef (Angle, 1.0, 0.0, 1.0); glRotatef (2 * Angle, 0.0, 1.0, 0.0); glCallList (SURFACE); glPopMatrix; SwapBuffers (DC); EndPaint (Handle, ps); Angle := Angle + Step; If Angle >= 360.0 then Angle := 0.0; InvalidateRect(Handle, nil, False); end; {======================================================================= Создание окна} procedure TfrmGL.FormCreate(Sender: TObject); var i : Integer; begin DC := GetDC(Handle); SetDCPixelFormat; hrc := wglCreateContext(DC); wglMakeCurrent(DC, hrc); glClearColor (1.0, 1.0, 1.0, 1.0); down := 0; Init; Model := TList.Create; Normals := TList.Create; LoadDxf ('Dolphin.dxf'); CalcNormals; glNewList (SURFACE, GL_COMPILE); For i := 0 to round (Model.Count / 3) - 1 do begin glBegin(GL_TRIANGLES); glNormal3fv(Normals.Items [i]); glvertex3fv(Model.Items [i * 3]); glvertex3fv(Model.Items [i * 3 + 1]); glvertex3fv(Model.Items [i * 3 + 2]); glEnd; end; glEndList; Model.Free; Normals.Free; end; {======================================================================= Изменение размеров окна} procedure TfrmGL.FormResize(Sender: TObject); begin glViewPort (0, 0, ClientWidth, ClientHeight); glMatrixMode(GL_PROJECTION); glLoadIdentity; gluPerspective(40.0, ClientWidth / ClientHeight, 3.0, 13.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity; glTranslatef(0.0, 0.0, -9.0); InvalidateRect(Handle, nil, False); end; {======================================================================= Конец работы программы} procedure TfrmGL.FormDestroy(Sender: TObject); begin glDeleteLists (SURFACE, 1); wglMakeCurrent(0, 0); wglDeleteContext(hrc); ReleaseDC(Handle, DC); DeleteDC (DC); end; {======================================================================= Обработка нажатия клавиши} procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_ESCAPE then Close; If Key = VK_SPACE then begin If step = 0 then step := wrkStep else begin wrkStep := step; step := 0; end end; end; {======================================================================= Движение мыши} procedure TfrmGL.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin If down <> 0 then begin glRotatef (lastx - x, 1, 0, 1); lastx := x; step := sqrt (sqr(X - wrkX) + sqr (Y - wrkY)) / (GetTickCount - wrkTime + 1); InvalidateRect(Handle, nil, False); end; end; {======================================================================= Кнопка мыши отжата} procedure TfrmGL.FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin down := 0; end; {======================================================================= Кнопка мыши нажата} procedure TfrmGL.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin If button = mbLeft then begin lastx := X; wrkX := X; wrkY := Y; down := 1; wrkTime := GetTickCount; end; end; {======================================================================= Устанавливаем формат пикселей} procedure TfrmGL.SetDCPixelFormat; var nPixelFormat: Integer; pfd: TPixelFormatDescriptor; begin FillChar(pfd, SizeOf(pfd), 0); pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; nPixelFormat := ChoosePixelFormat(DC, @pfd); SetPixelFormat(DC, nPixelFormat, @pfd); end; end.
program VoltageProbeInfo; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, uSMBIOS { you can add units after this }; function ByteToBinStr(AValue:Byte):string; const Bits: array[1..8] of byte = (128,64,32,16,8,4,2,1); var i: integer; begin Result:='00000000'; if (AValue<>0) then for i:=1 to 8 do if (AValue and Bits[i])<>0 then Result[i]:='1'; end; procedure GetVoltageProbeInfo; Var SMBios: TSMBios; LVoltageProbeInfo: TVoltageProbeInformation; begin SMBios:=TSMBios.Create; try WriteLn('Voltage Probe Information'); WriteLn('-------------------------'); if SMBios.HasVoltageProbeInfo then for LVoltageProbeInfo in SMBios.VoltageProbeInformation do begin WriteLn(Format('Description %s',[LVoltageProbeInfo.GetDescriptionStr])); WriteLn(Format('Location and Status %s',[ByteToBinStr(LVoltageProbeInfo.RAWVoltageProbeInfo^.LocationandStatus)])); WriteLn(Format('Location %s',[LVoltageProbeInfo.GetLocation])); WriteLn(Format('Status %s',[LVoltageProbeInfo.GetStatus])); if LVoltageProbeInfo.RAWVoltageProbeInfo^.MaximumValue=$8000 then WriteLn(Format('Maximum Value %s',['Unknown'])) else WriteLn(Format('Maximum Value %d',[LVoltageProbeInfo.RAWVoltageProbeInfo^.MaximumValue])); if LVoltageProbeInfo.RAWVoltageProbeInfo^.MinimumValue=$8000 then WriteLn(Format('Minimum Value %s',['Unknown'])) else WriteLn(Format('Minimum Value %d',[LVoltageProbeInfo.RAWVoltageProbeInfo^.MinimumValue])); if LVoltageProbeInfo.RAWVoltageProbeInfo^.Resolution=$8000 then WriteLn(Format('Resolution %s',['Unknown'])) else WriteLn(Format('Resolution %d',[LVoltageProbeInfo.RAWVoltageProbeInfo^.Resolution])); if LVoltageProbeInfo.RAWVoltageProbeInfo^.Tolerance=$8000 then WriteLn(Format('Tolerance %s',['Unknown'])) else WriteLn(Format('Tolerance %d',[LVoltageProbeInfo.RAWVoltageProbeInfo^.Tolerance])); WriteLn(Format('OEM Specific %.8x',[LVoltageProbeInfo.RAWVoltageProbeInfo^.OEMdefined])); if LVoltageProbeInfo.RAWVoltageProbeInfo^.Header.Length>$14 then if LVoltageProbeInfo.RAWVoltageProbeInfo^.NominalValue=$8000 then WriteLn(Format('Nominal Value %s',['Unknown'])) else WriteLn(Format('Nominal Value %d',[LVoltageProbeInfo.RAWVoltageProbeInfo^.NominalValue])); WriteLn; end else Writeln('No Voltage Probe Info was found'); finally SMBios.Free; end; end; begin try GetVoltageProbeInfo; except on E:Exception do Writeln(E.Classname, ':', E.Message); end; Writeln('Press Enter to exit'); Readln; end.
unit fMenu; (* Projet : POC Notes de frais URL du projet : https://www.developpeur-pascal.fr/p/_6006-poc-notes-de-frais-une-application-multiplateforme-de-saisie-de-notes-de-frais-en-itinerance.html Auteur : Patrick Prémartin https://patrick.premartin.fr Editeur : Olf Software https://www.olfsoftware.fr Site web : https://www.developpeur-pascal.fr/ Ce fichier et ceux qui l'accompagnent sont fournis en l'état, sans garantie, à titre d'exemple d'utilisation de fonctionnalités de Delphi dans sa version Tokyo 10.2 Vous pouvez vous en inspirer dans vos projets mais n'êtes pas autorisé à rediffuser tout ou partie des fichiers de ce projet sans accord écrit préalable. *) interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, System.Actions, FMX.ActnList, FMX.StdActns, FMX.MediaLibrary.Actions, FMX.Objects; type TfrmMenu = class(TForm) btnCaptureNoteDeFrais: TButton; btnSynchroniserLaBase: TButton; btnConsulter: TButton; btnLogout: TButton; ActionList1: TActionList; TakePhotoFromCameraAction1: TTakePhotoFromCameraAction; AnimationAttente: TRectangle; AniIndicator1: TAniIndicator; procedure btnSynchroniserLaBaseClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure TakePhotoFromCameraAction1DidFinishTaking(Image: TBitmap); procedure btnConsulterClick(Sender: TObject); procedure btnLogoutClick(Sender: TObject); procedure btnCaptureNoteDeFraisClick(Sender: TObject); procedure FormCreate(Sender: TObject); private Fsynchroniserbase: boolean; procedure Setsynchroniserbase(const Value: boolean); function DateHeure: string; procedure AjaxOn; procedure AjaxOff; public { Déclarations publiques } property synchroniserbase: boolean read Fsynchroniserbase write Setsynchroniserbase; end; var frmMenu: TfrmMenu; implementation {$R *.fmx} uses fConsulter, dmBaseFMX, uNotesDeFrais, uParam, System.IOUtils, uAPI; { TfrmMenu } procedure TfrmMenu.AjaxOff; begin AnimationAttente.Visible := false; AniIndicator1.Enabled := false; end; procedure TfrmMenu.AjaxOn; begin AnimationAttente.Visible := true; AnimationAttente.BringToFront; AniIndicator1.Enabled := true; end; procedure TfrmMenu.btnCaptureNoteDeFraisClick(Sender: TObject); begin if (not TakePhotoFromCameraAction1.Execute) then showmessage('erreur'); end; procedure TfrmMenu.btnConsulterClick(Sender: TObject); begin if not assigned(frmConsulter) then frmConsulter := tfrmconsulter.Create(self); try {$IFDEF ANDROID} frmConsulter.Show; {$ELSE} frmConsulter.ShowModal; {$ENDIF} finally {$IFNDEF ANDROID} freeandnil(frmConsulter); {$ENDIF} end; end; procedure TfrmMenu.btnLogoutClick(Sender: TObject); begin usercode := 0; username := ''; UserPassword := ''; param_save; close; end; procedure TfrmMenu.btnSynchroniserLaBaseClick(Sender: TObject); begin APISynchronisation(AjaxOn, AjaxOff); end; function TfrmMenu.DateHeure: string; var i: integer; ch: string; c: char; begin result := ''; ch := DateTimeToStr(Now).ToLower; for i := 0 to ch.Length - 1 do begin c := ch.Chars[i]; if ((c >= '0') and (c <= '9')) or ((c >= 'a') and (c <= 'z')) then result := result + c; end; end; procedure TfrmMenu.FormCreate(Sender: TObject); begin randomize; AjaxOff; end; procedure TfrmMenu.FormShow(Sender: TObject); begin if synchroniserbase then btnSynchroniserLaBaseClick(Sender); end; procedure TfrmMenu.Setsynchroniserbase(const Value: boolean); begin Fsynchroniserbase := Value; end; procedure TfrmMenu.TakePhotoFromCameraAction1DidFinishTaking(Image: TBitmap); var nom_photo: string; begin nom_photo := 'ndf-' + usercode.ToString + '-' + DateHeure + '-' + random(MaxInt).ToString + '.png'; if not dm.qryNotesDeFrais.active then dm.qryNotesDeFrais.open('select * from notesdefrais'); dm.qryNotesDeFrais.Insert; try dm.qryNotesDeFrais.fieldbyname('utilisateur_code').AsInteger := usercode; dm.qryNotesDeFrais.fieldbyname('mobile_code').AsString := nom_photo; Image.SaveToFile(tpath.Combine(NotesDeFrais_PhotosPath_mobile, nom_photo)); dm.qryNotesDeFrais.post; except dm.qryNotesDeFrais.cancel; end; end; end.
unit NtUtils.Job; interface uses Winapi.WinNt, Ntapi.ntdef, Ntapi.ntpsapi, NtUtils.Exceptions, NtUtils.Objects; const PROCESS_ASSIGN_TO_JOB = PROCESS_SET_QUOTA or PROCESS_TERMINATE; // Create new job object function NtxCreateJob(out hxJob: IHandle; ObjectName: String = ''; RootDirectory: THandle = 0; HandleAttributes: Cardinal = 0): TNtxStatus; // Open job object by name function NtxOpenJob(out hxJob: IHandle; DesiredAccess: TAccessMask; ObjectName: String; RootDirectory: THandle = 0; HandleAttributes: Cardinal = 0): TNtxStatus; // Enumerate active processes in a job function NtxEnurateProcessesInJob(hJob: THandle; out ProcessIds: TArray<NativeUInt>): TNtxStatus; // Check whether a process is a part of a specific/any job function NtxIsProcessInJob(out ProcessInJob: Boolean; hProcess: THandle; hJob: THandle = 0): TNtxStatus; // Assign a process to a job function NtxAssignProcessToJob(hProcess: THandle; hJob: THandle): TNtxStatus; // Terminate all processes in a job function NtxTerminateJob(hJob: THandle; ExitStatus: NTSTATUS): TNtxStatus; type NtxJob = class // Query fixed-size information class function Query<T>(hJob: THandle; InfoClass: TJobObjectInfoClass; out Buffer: T): TNtxStatus; static; // Set fixed-size information class function SetInfo<T>(hJob: THandle; InfoClass: TJobObjectInfoClass; const Buffer: T): TNtxStatus; static; end; implementation uses Ntapi.ntstatus, Ntapi.ntseapi; function NtxCreateJob(out hxJob: IHandle; ObjectName: String; RootDirectory: THandle; HandleAttributes: Cardinal): TNtxStatus; var hJob: THandle; ObjAttr: TObjectAttributes; NameStr: UNICODE_STRING; begin if ObjectName <> '' then begin NameStr.FromString(ObjectName); InitializeObjectAttributes(ObjAttr, @NameStr, HandleAttributes, RootDirectory); end else InitializeObjectAttributes(ObjAttr, nil, HandleAttributes); Result.Location := 'NtCreateJobObject'; Result.Status := NtCreateJobObject(hJob, JOB_OBJECT_ALL_ACCESS, @ObjAttr); if Result.IsSuccess then hxJob := TAutoHandle.Capture(hJob); end; function NtxOpenJob(out hxJob: IHandle; DesiredAccess: TAccessMask; ObjectName: String; RootDirectory: THandle; HandleAttributes: Cardinal): TNtxStatus; var hJob: THandle; ObjAttr: TObjectAttributes; NameStr: UNICODE_STRING; begin NameStr.FromString(ObjectName); InitializeObjectAttributes(ObjAttr, @NameStr, HandleAttributes, RootDirectory); Result.Location := 'NtOpenJobObject'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @JobAccessType; Result.Status := NtOpenJobObject(hJob, DesiredAccess, ObjAttr); if Result.IsSuccess then hxJob := TAutoHandle.Capture(hJob); end; function NtxEnurateProcessesInJob(hJob: THandle; out ProcessIds: TArray<NativeUInt>): TNtxStatus; const INITIAL_CAPACITY = 8; var BufferSize, Required: Cardinal; Buffer: PJobBasicProcessIdList; i: Integer; begin Result.Location := 'NtQueryInformationJobObject'; Result.LastCall.CallType := lcQuerySetCall; Result.LastCall.InfoClass := Cardinal(JobObjectBasicProcessIdList); Result.LastCall.InfoClassType := TypeInfo(TJobObjectInfoClass); Result.LastCall.Expects(JOB_OBJECT_QUERY, @JobAccessType); // Initial buffer capacity should be enough for at least one item. BufferSize := SizeOf(Cardinal) * 2 + SizeOf(NativeUInt) * INITIAL_CAPACITY; repeat // Allocate a buffer for MaxCount items Buffer := AllocMem(BufferSize); Required := 0; Result.Status := NtQueryInformationJobObject(hJob, JobObjectBasicProcessIdList, Buffer, BufferSize, nil); // If not all processes fit into the list then calculate the required size if Result.Status = STATUS_BUFFER_OVERFLOW then Required := SizeOf(Cardinal) * 2 + SizeOf(NativeUInt) * Buffer.NumberOfAssignedProcesses; if not Result.IsSuccess then FreeMem(Buffer); until not NtxExpandBuffer(Result, BufferSize, Required, True); if not Result.IsSuccess then Exit; SetLength(ProcessIds, Buffer.NumberOfProcessIdsInList); for i := 0 to High(ProcessIds) do ProcessIds[i] := Buffer.ProcessIdList{$R-}[i]{$R+}; FreeMem(Buffer); end; function NtxIsProcessInJob(out ProcessInJob: Boolean; hProcess: THandle; hJob: THandle): TNtxStatus; begin Result.Location := 'NtIsProcessInJob'; Result.LastCall.Expects(PROCESS_QUERY_LIMITED_INFORMATION, @ProcessAccessType); if hJob <> 0 then Result.LastCall.Expects(JOB_OBJECT_QUERY, @JobAccessType); Result.Status := NtIsProcessInJob(hProcess, hJob); case Result.Status of STATUS_PROCESS_IN_JOB: ProcessInJob := True; STATUS_PROCESS_NOT_IN_JOB: ProcessInJob := False; end; end; function NtxAssignProcessToJob(hProcess: THandle; hJob: THandle): TNtxStatus; begin Result.Location := 'NtAssignProcessToJobObject'; Result.LastCall.Expects(PROCESS_ASSIGN_TO_JOB, @ProcessAccessType); Result.LastCall.Expects(JOB_OBJECT_ASSIGN_PROCESS, @JobAccessType); Result.Status := NtAssignProcessToJobObject(hJob, hProcess); end; function NtxTerminateJob(hJob: THandle; ExitStatus: NTSTATUS): TNtxStatus; begin Result.Location := 'NtTerminateJobObject'; Result.LastCall.Expects(JOB_OBJECT_TERMINATE, @JobAccessType); Result.Status := NtTerminateJobObject(hJob, ExitStatus); end; class function NtxJob.Query<T>(hJob: THandle; InfoClass: TJobObjectInfoClass; out Buffer: T): TNtxStatus; begin Result.Location := 'NtQueryInformationJobObject'; Result.LastCall.CallType := lcQuerySetCall; Result.LastCall.InfoClass := Cardinal(InfoClass); Result.LastCall.InfoClassType := TypeInfo(TJobObjectInfoClass); Result.LastCall.Expects(JOB_OBJECT_QUERY, @JobAccessType); Result.Status := NtQueryInformationJobObject(hJob, InfoClass, @Buffer, SizeOf(Buffer), nil); end; class function NtxJob.SetInfo<T>(hJob: THandle; InfoClass: TJobObjectInfoClass; const Buffer: T): TNtxStatus; begin Result.Location := 'NtSetInformationJobObject'; Result.LastCall.CallType := lcQuerySetCall; Result.LastCall.InfoClass := Cardinal(InfoClass); Result.LastCall.InfoClassType := TypeInfo(TJobObjectInfoClass); case InfoClass of JobObjectBasicLimitInformation, JobObjectExtendedLimitInformation: Result.LastCall.ExpectedPrivilege := SE_INCREASE_BASE_PRIORITY_PRIVILEGE; JobObjectSecurityLimitInformation: Result.LastCall.ExpectedPrivilege := SE_ASSIGN_PRIMARY_TOKEN_PRIVILEGE; end; case InfoClass of JobObjectSecurityLimitInformation: Result.LastCall.Expects(JOB_OBJECT_SET_SECURITY_ATTRIBUTES, @JobAccessType); else Result.LastCall.Expects(JOB_OBJECT_SET_ATTRIBUTES, @JobAccessType); end; Result.Status := NtSetInformationJobObject(hJob, InfoClass, @Buffer, SizeOf(Buffer)); end; end.
{**********************************************************************} {* Иллюстрация к книге "OpenGL в проектах Delphi" *} {* Краснов М.В. softgl@chat.ru *} {**********************************************************************} unit Main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, ComCtrls, StdCtrls, Menus, Buttons, OpenGL; const // цвет тумана fogColor : Array [0..3] of GLfloat = (0.5, 0.5, 0.5, 1.0); // цвет площадки glfSquareAmbient : Array[0..3] of GLfloat = (0.24725, 0.1995, 0.0745, 1.0); glfSquareDiffuse : Array[0..3] of GLfloat = (0.75164, 0.60648, 0.22648, 1.0); glfSquareSpecular : Array[0..3] of GLfloat = (0.628281, 0.555802, 0.366065, 1.0); const // источник света glfLightAmbient : Array[0..3] of GLfloat = (0.25, 0.25, 0.25, 1.0); glfLightDiffuse : Array[0..3] of GLfloat = (1.0, 1.0, 1.0, 1.0); glfLightSpecular: Array[0..3] of GLfloat = (1.0, 1.0, 1.0, 1.0); glfLightPosition: Array[0..3] of GLfloat = (0.0, 0.0, 20.0, 1.0); glfLightModelAmbient: Array[0..3] of GLfloat = (0.25, 0.25, 0.25, 1.0); // позиция первого источника света LightPosition : Array[0..3] of GLfloat = (0.0, 0.0, 15.0, 1.0); // позиция второго источника света glfLight1Position: Array[0..3] of GLfloat = (15.0, 15.0, -5.0, 1.0); type TfrmGL = class(TForm) procedure Init; procedure SetProjection(Sender: TObject); procedure FormCreate(Sender: TObject); procedure SetDCPixelFormat; procedure FormDestroy(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); public DC : HDC; hrc : HGLRC; cubeX, cubeY, cubeZ : GLfloat; cubeL, cubeH, cubeW : GLfloat; AddX, AddY, AddZ : GLfloat; // начальные сдвиги SquareLength : GLfloat; // сторона площадки procedure Square; procedure Shadow; protected procedure WMPaint(var Msg: TWMPaint); message WM_PAINT; end; var frmGL: TfrmGL; implementation uses DGLUT; {$R *.DFM} {======================================================================= Нажатие клавиши} procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_ESCAPE then Close; If Key = VK_LEFT then begin cubeX := cubeX + 0.1; InvalidateRect(Handle, nil, False); end; If Key = VK_RIGHT then begin cubeX := cubeX - 0.1; InvalidateRect(Handle, nil, False); end; If Key = VK_UP then begin cubeZ := cubeZ + 0.1; InvalidateRect(Handle, nil, False); end; If Key = VK_DOWN then begin cubeZ := cubeZ - 0.1; InvalidateRect(Handle, nil, False); end; end; {====================================================================== Рисование тени} procedure TfrmGL.Shadow; // подсчет точки тени для одной точки procedure OneShadow (x, y, z, h : GLfloat; var x1, y1 : GLfloat); begin x1 := x * LightPosition [2] / (LightPosition [2] - (z + h)); If LightPosition [0] < x then begin If x1 > 0 then x1 := LightPosition [0] + x1 end else begin If x1 > 0 then x1 := LightPosition [0] - x1 end; y1 := y * LightPosition [2] / (LightPosition [2] - (z + h)); If LightPosition [1] < y then begin If y1 > 0 then y1 := LightPosition [1] + y1 end else begin If y1 > 0 then y1 := LightPosition [1] - y1 end; If x1 < 0 then x1 := 0 else If x1 > SquareLength then x1 := SquareLength; If y1 < 0 then y1 := 0 else If y1 > SquareLength then y1 := SquareLength; end; var x1, y1, x2, y2, x3, y3, x4, y4 : GLfloat; wrkx1, wrky1, wrkx2, wrky2, wrkx3, wrky3, wrkx4, wrky4 : GLfloat; begin OneShadow (cubeX + cubeL, cubeY + cubeH, cubeZ, cubeW, x1, y1); OneShadow (cubeX, cubeY + cubeH, cubeZ, cubeW, x2, y2); OneShadow (cubeX, cubeY, cubeZ, cubeW, x3, y3); OneShadow (cubeX + cubeL, cubeY, cubeZ, cubeW, x4, y4); If cubeZ + cubeW >= 0 then begin glBegin (GL_QUADS); glVertex3f (x1, y1, -0.99); glVertex3f (x2, y2, -0.99); glVertex3f (x3, y3, -0.99); glVertex3f (x4, y4, -0.99); glEnd; end; If cubeZ >= 0 then begin wrkx1 := x1; wrky1 := y1; wrkx2 := x2; wrky2 := y2; wrkx3 := x3; wrky3 := y3; wrkx4 := x4; wrky4 := y4; OneShadow (cubeX + cubeL, cubeY + cubeH, cubeZ, 0, x1, y1); OneShadow (cubeX, cubeY + cubeH, cubeZ, 0, x2, y2); OneShadow (cubeX, cubeY, cubeZ, 0, x3, y3); OneShadow (cubeX + cubeL, cubeY, cubeZ, 0, x4, y4); glBegin (GL_QUADS); glVertex3f (x1, y1, -0.99); glVertex3f (x2, y2, -0.99); glVertex3f (x3, y3, -0.99); glVertex3f (x4, y4, -0.99); glVertex3f (wrkx2, wrky2, -0.99); glVertex3f (x2, y2, -0.99); glVertex3f (x3, y3, -0.99); glVertex3f (wrkx3, wrky3, -0.99); glVertex3f (wrkx1, wrky1, -0.99); glVertex3f (wrkx4, wrky4, -0.99); glVertex3f (x4, y4, -0.99); glVertex3f (x1, y1, -0.99); glVertex3f (wrkx1, wrky1, -0.99); glVertex3f (x1, y1, -0.99); glVertex3f (x2, y2, -0.99); glVertex3f (wrkx2, wrky2, -0.99); glVertex3f (wrkx3, wrky3, -0.99); glVertex3f (x3, y3, -0.99); glVertex3f (x4, y4, -0.99); glVertex3f (wrkx4, wrky4, -0.99); glEnd; end; end; {====================================================================== Рисование площадки} procedure TfrmGL.Square; begin glPushAttrib (GL_ALL_ATTRIB_BITS ); glMaterialfv(GL_FRONT, GL_AMBIENT, @glfSquareAmbient); glMaterialfv(GL_FRONT, GL_DIFFUSE, @glfSquareDiffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, @glfSquareSpecular); glMaterialf (GL_FRONT, GL_SHININESS, 90.2); glBegin(GL_QUADS); glNormal3f(squarelength / 2.0, squarelength / 2.0, -1.0); glVertex3f(squarelength, squarelength, -1.0); glVertex3f(0.0, squarelength, -1.0); glVertex3f(0.0, 0.0, -1.0); glVertex3f(squarelength, 0.0, -1.0); glEnd; glPopAttrib; end; {====================================================================== Инициализация} procedure TfrmGL.Init; begin glEnable (GL_FOG); glEnable(GL_NORMALIZE); glEnable(GL_DEPTH_TEST); glLightfv(GL_LIGHT0, GL_AMBIENT, @glfLightambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, @glfLightdiffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, @glfLightspecular); glLightfv(GL_LIGHT0, GL_POSITION, @glfLightposition); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, @glfLightmodelambient); // второй источник света glLightfv(GL_LIGHT1, GL_AMBIENT, @glfLightambient); glLightfv(GL_LIGHT1, GL_DIFFUSE, @glfLightdiffuse); glLightfv(GL_LIGHT1, GL_SPECULAR, @glfLightspecular); glLightfv(GL_LIGHT1, GL_POSITION, @glfLight1position); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_LIGHT1); end; {====================================================================== Изменение размеров окна} procedure TfrmGL.SetProjection(Sender: TObject); begin glViewport(0, 0, ClientWidth, ClientHeight); glMatrixMode(GL_PROJECTION); glLoadIdentity; glFrustum (-0.5, 0.5, -0.5, 0.5, 1.0, 100.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity; glTranslatef(0.0, 0.0, -32.0); glRotatef(120.0, 1.0, 0.0, 0.0); glRotatef(180.0, 0.0, 1.0, 0.0); glRotatef(40.0, 0.0, 0.0, 1.0); InvalidateRect(Handle, nil, False); end; {====================================================================== Начало работы приложения} procedure TfrmGL.FormCreate(Sender: TObject); begin DC := GetDC(Handle); SetDCPixelFormat; hrc := wglCreateContext(DC); wglMakeCurrent(DC, hrc); Init; // параметры тумана glFogi(GL_FOG_MODE, GL_EXP); glFogfv(GL_FOG_COLOR, @fogColor); glFogf(GL_FOG_DENSITY, 0.015); SquareLength := 50.0; AddX := 0; AddY := 0; AddZ := 0; cubeX := 1.0; cubeY := 2.0; cubeZ := 3.0; cubeL := 1.0; cubeH := 2.0; cubeW := 3.0; end; {====================================================================== Аналог события OnPaint} procedure TfrmGL.WMPaint(var Msg: TWMPaint); var ps : TPaintStruct; const CubeColor : Array [0..3] of GLfloat = (1.0, 0.0, 0.0, 0.0); begin BeginPaint(Handle, ps); glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); glPushMatrix; glTranslatef(AddX, AddY, AddZ); glEnable (GL_LIGHT1); Square; glDisable (GL_LIGHT1); glPushAttrib (GL_ALL_ATTRIB_BITS ); glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, @CubeColor); glPushMatrix; glTranslatef (cubeX, cubeY, cubeZ); glScalef (cubeL, cubeH, cubeW); glutSolidCube (1.0); glPopMatrix; glPopAttrib; Shadow; glPopMatrix; SwapBuffers(DC); EndPaint(Handle, ps); end; {====================================================================== Конец работы приложения} procedure TfrmGL.FormDestroy(Sender: TObject); begin wglMakeCurrent(0, 0); wglDeleteContext(hrc); ReleaseDC(Handle, DC); DeleteDC (DC); end; {====================================================================== Формат пикселей} procedure TfrmGL.SetDCPixelFormat; var nPixelFormat: Integer; pfd: TPixelFormatDescriptor; begin FillChar(pfd, SizeOf(pfd), 0); with pfd do begin nSize := sizeof(pfd); nVersion := 1; dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; iPixelType:= PFD_TYPE_RGBA; cColorBits:= 24; cDepthBits:= 32; iLayerType:= PFD_MAIN_PLANE; end; nPixelFormat := ChoosePixelFormat(DC, @pfd); SetPixelFormat(DC, nPixelFormat, @pfd); end; end.
unit nkTitleBar; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls; type { TnkTitleBar } TnkTitleBar = class(TPanel) private FImage:TImage; FTopForm:TForm; FMoving:boolean; FXPos:integer; FYPos:integer; function GetPicture: TPicture; procedure SetPicture(AValue: TPicture); protected procedure _onMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure _onMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure _onMouseUp(Sender: TObject; Button: TMouseButton;Shift: TShiftState; X, Y: Integer); procedure Loaded;override; public constructor Create(AOwner:TComponent);override; destructor Destroy;override; published property Picture:TPicture read GetPicture write SetPicture; end; procedure Register; implementation procedure Register; begin {$I nktitlebar_icon.ctrs} RegisterComponents('Additional',[TnkTitleBar]); end; { TnkTitleBar } function TnkTitleBar.GetPicture: TPicture; begin Result:=FImage.Picture; end; procedure TnkTitleBar.SetPicture(AValue: TPicture); begin FImage.Picture.Assign(AValue); end; procedure TnkTitleBar._onMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if FTopForm<>nil then begin if FTopForm.WindowState=wsNormal then begin if mbLeft = Button then begin FMoving:=True; FXPos:=X; FYPos:=Y; end; end; end; end; procedure TnkTitleBar._onMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if FTopForm<>nil then begin if FTopForm.WindowState=wsNormal then begin if (ssLeft in Shift) and (FMoving=True) then begin FTopForm.Top:=FTopForm.Top+Y-Self.FYPos; FTopForm.Left:=FTopForm.Left+X-Self.FXPos; if FTopForm.Top<0 then FTopForm.Top:=0; end; end; end; end; procedure TnkTitleBar._onMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Self.FMoving:=False; end; procedure TnkTitleBar.Loaded; begin inherited Loaded; if Self.GetTopParent is TForm then FTopForm:=(Self.GetTopParent as TForm) else FTopForm:=nil; end; constructor TnkTitleBar.Create(AOwner: TComponent); begin inherited Create(AOwner); Self.Align:=alTop; Self.Width:=100; Self.Height:=27; Self.BevelOuter:=bvNone; FImage:=TImage.Create(Self); FImage.Parent:=Self; FImage.Align:=alClient; FImage.OnMouseDown:=@_onMouseDown; FImage.OnMouseMove:=@_onMouseMove; FImage.OnMouseUp:=@_onMouseUp; end; destructor TnkTitleBar.Destroy; begin FImage.Free; inherited Destroy; end; end.
unit IdDateTimeStamp; interface uses Classes, IdBaseComponent, SysConst, SysUtils; const IdMilliSecondsInSecond = 1000; IdSecondsInMinute = 60; IdMinutesInHour = 60; IdHoursInDay = 24; IdDaysInWeek = 7; IdDaysInYear = 365; IdDaysInLeapYear = 366; IdYearsInShortLeapYearCycle = 4; IdDaysInShortLeapYearCycle = IdDaysInLeapYear + (IdDaysInYear * 3); IdDaysInShortNonLeapYearCycle = IdDaysInYear * IdYearsInShortLeapYearCycle; IdDaysInFourYears = IdDaysInShortLeapYearCycle; IdYearsInCentury = 100; IdDaysInCentury = (25 * IdDaysInFourYears) - 1; IdDaysInLeapCentury = IdDaysInCentury + 1; IdYearsInLeapYearCycle = 400; IdDaysInLeapYearCycle = IdDaysInCentury * 4 + 1; IdMonthsInYear = 12; IdBeatsInDay = 1000; IdHoursInHalfDay = IdHoursInDay div 2; IdSecondsInHour = IdSecondsInMinute * IdMinutesInHour; IdSecondsInDay = IdSecondsInHour * IdHoursInDay; IdSecondsInHalfDay = IdSecondsInHour * IdHoursInHalfDay; IdSecondsInWeek = IdDaysInWeek * IdSecondsInDay; IdSecondsInYear = IdSecondsInDay * IdDaysInYear; IdSecondsInLeapYear = IdSecondsInDay * IdDaysInLeapYear; IdMillisecondsInMinute = IdSecondsInMinute * IdMillisecondsInSecond; IdMillisecondsInHour = IdSecondsInHour * IdMillisecondsInSecond; IdMillisecondsInDay = IdSecondsInDay * IdMillisecondsInSecond; IdMillisecondsInWeek = IdSecondsInWeek * IdMillisecondsInSecond; IdDaysInMonth: array[1..IdMonthsInYear] of byte = ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ); IdMonthNames: array[0..IdMonthsInYear] of string = ('', SLongMonthNameJan, SLongMonthNameFeb, SLongMonthNameMar, SLongMonthNameApr, SLongMonthNameMay, SLongMonthNameJun, SLongMonthNameJul, SLongMonthNameAug, SLongMonthNameSep, SLongMonthNameOct, SLongMonthNameNov, SLongMonthNameDec); IdMonthShortNames: array[0..IdMonthsInYear] of string = ('', SShortMonthNameJan, SShortMonthNameFeb, SShortMonthNameMar, SShortMonthNameApr, SShortMonthNameMay, SShortMonthNameJun, SShortMonthNameJul, SShortMonthNameAug, SShortMonthNameSep, SShortMonthNameOct, SShortMonthNameNov, SShortMonthNameDec); IdDayNames: array[0..IdDaysInWeek] of string = ('', SLongDayNameSun, SLongDayNameMon, SLongDayNameTue, SLongDayNameWed, SLongDayNameThu, SLongDayNameFri, SLongDayNameSat); IdDayShortNames: array[0..IdDaysInWeek] of string = ('', SShortDayNameSun, SShortDayNameMon, SShortDayNameTue, SShortDayNameWed, SShortDayNameThu, SShortDayNameFri, SShortDayNameSat); // Area Time Zones TZ_NZDT = 13; // New Zealand Daylight Time TZ_IDLE = 12; // International Date Line East TZ_NZST = TZ_IDLE; // New Zealand Standard Time TZ_NZT = TZ_IDLE; // New Zealand Time TZ_EADT = 11; // Eastern Australian Daylight Time TZ_GST = 10; // Guam Standard Time / Russia Zone 9 TZ_JST = 9; // Japan Standard Time / Russia Zone 8 TZ_CCT = 8; // China Coast Time / Russia Zone 7 TZ_WADT = TZ_CCT; // West Australian Daylight Time TZ_WAST = 7; // West Australian Standard Time / Russia Zone 6 TZ_ZP6 = 6; // Chesapeake Bay / Russia Zone 5 TZ_ZP5 = 5; // Chesapeake Bay / Russia Zone 4 TZ_ZP4 = 4; // Russia Zone 3 TZ_BT = 3; // Baghdad Time / Russia Zone 2 TZ_EET = 2; // Eastern European Time / Russia Zone 1 TZ_MEST = TZ_EET; // Middle European Summer Time TZ_MESZ = TZ_EET; // Middle European Summer Zone TZ_SST = TZ_EET; // Swedish Summer Time TZ_FST = TZ_EET; // French Summer Time TZ_CET = 1; // Central European Time TZ_FWT = TZ_CET; // French Winter Time TZ_MET = TZ_CET; // Middle European Time TZ_MEWT = TZ_CET; // Middle European Winter Time TZ_SWT = TZ_CET; // Swedish Winter Time TZ_GMT = 0; // Greenwich Meanttime TZ_UT = TZ_GMT; // Universla Time TZ_UTC = TZ_GMT; // Universal Time Co-ordinated TZ_WET = TZ_GMT; // Western European Time TZ_WAT = -1; // West Africa Time TZ_BST = TZ_WAT; // British Summer Time TZ_AT = -2; // Azores Time TZ_ADT = -3; // Atlantic Daylight Time TZ_AST = -4; // Atlantic Standard Time TZ_EDT = TZ_AST; // Eastern Daylight Time TZ_EST = -5; // Eastern Standard Time TZ_CDT = TZ_EST; // Central Daylight Time TZ_CST = -6; // Central Standard Time TZ_MDT = TZ_CST; // Mountain Daylight Time TZ_MST = -7; // Mountain Standard Time TZ_PDT = TZ_MST; // Pacific Daylight Time TZ_PST = -8; // Pacific Standard Time TZ_YDT = TZ_PST; // Yukon Daylight Time TZ_YST = -9; // Yukon Standard Time TZ_HDT = TZ_YST; // Hawaii Daylight Time TZ_AHST = -10; // Alaska-Hawaii Standard Time TZ_CAT = TZ_AHST; // Central Alaska Time TZ_HST = TZ_AHST; // Hawaii Standard Time TZ_EAST = TZ_AHST; // East Australian Standard Time TZ_NT = -11; // -None- TZ_IDLW = -12; // International Date Line West // Military Time Zones TZM_A = TZ_WAT; TZM_Alpha = TZM_A; TZM_B = TZ_AT; TZM_Bravo = TZM_B; TZM_C = TZ_ADT; TZM_Charlie = TZM_C; TZM_D = TZ_AST; TZM_Delta = TZM_D; TZM_E = TZ_EST; TZM_Echo = TZM_E; TZM_F = TZ_CST; TZM_Foxtrot = TZM_F; TZM_G = TZ_MST; TZM_Golf = TZM_G; TZM_H = TZ_PST; TZM_Hotel = TZM_H; TZM_J = TZ_YST; TZM_Juliet = TZM_J; TZM_K = TZ_AHST; TZM_Kilo = TZM_K; TZM_L = TZ_NT; TZM_Lima = TZM_L; TZM_M = TZ_IDLW; TZM_Mike = TZM_M; TZM_N = TZ_CET; TZM_November = TZM_N; TZM_O = TZ_EET; TZM_Oscar = TZM_O; TZM_P = TZ_BT; TZM_Papa = TZM_P; TZM_Q = TZ_ZP4; TZM_Quebec = TZM_Q; TZM_R = TZ_ZP5; TZM_Romeo = TZM_R; TZM_S = TZ_ZP6; TZM_Sierra = TZM_S; TZM_T = TZ_WAST; TZM_Tango = TZM_T; TZM_U = TZ_CCT; TZM_Uniform = TZM_U; TZM_V = TZ_JST; TZM_Victor = TZM_V; TZM_W = TZ_GST; TZM_Whiskey = TZM_W; TZM_X = TZ_NT; TZM_XRay = TZM_X; TZM_Y = TZ_IDLE; TZM_Yankee = TZM_Y; TZM_Z = TZ_GMT; TZM_Zulu = TZM_Z; type TDays = (TDaySun, TDayMon, TDayTue, TDayWed, TDayThu, TDayFri, TDaySat); TMonths = (TMthJan, TMthFeb, TMthMar, TMthApr, TMthMay, TMthJun, TMthJul, TMthAug, TMthSep, TMthOct, TMthNov, TMthDec); TIdDateTimeStamp = class(TIdBaseComponent) protected FDay: Integer; FIsLeapYear: Boolean; FMillisecond: Integer; FRequestedTimeZone: Integer; FSecond: Integer; FTimeZone: Integer; FYear: Integer; procedure CheckLeapYear; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AddDays(ANumber: Cardinal); procedure AddHours(ANumber: Cardinal); procedure AddMilliseconds(ANumber: Cardinal); procedure AddMinutes(ANumber: Cardinal); procedure AddMonths(ANumber: Cardinal); procedure AddSeconds(ANumber: Cardinal); procedure AddTDateTime(ADateTime: TDateTime); procedure AddTIdDateTimeStamp(AIdDateTime: TIdDateTimeStamp); procedure AddTTimeStamp(ATimeStamp: TTimeStamp); procedure AddWeeks(ANumber: Cardinal); procedure AddYears(ANumber: Cardinal); function GetAsISO8601Calendar: string; function GetAsISO8601Ordinal: string; function GetAsISO8601Week: string; function GetAsRFC882: string; function GetAsTDateTime: TDateTime; function GetAsTTimeStamp: TTimeStamp; function GetAsTimeOFDay: string; // HH:MM:SS function GetBeatOFDay: Integer; function GetDaysInYear: Integer; function GetDayOfMonth: Integer; function GetDayOfWeek: Integer; function GetDayOfWeekName: string; function GetDayOfWeekShortName: string; function GetHourOf12Day: Integer; function GetHourOf24Day: Integer; function GetIsMorning: Boolean; function GetMinuteOFDay: Integer; function GetMinuteOfHour: Integer; function GetMonthOFYear: Integer; function GetMonthName: string; function GetMonthShortName: string; function GetSecondsInYear: Integer; function GetSecondOfMinute: Integer; function GetWeekOFYear: Integer; procedure SetFromTDateTime(ADateTime: TDateTime); procedure SetFromTTimeStamp(ATimeStamp: TTimeStamp); procedure SetDay(ANumber: Integer); procedure SetMillisecond(ANumber: Integer); procedure SetSecond(ANumber: Integer); procedure SetYear(ANumber: Integer); procedure SubtractDays(ANumber: Cardinal); procedure SubtractHours(ANumber: Cardinal); procedure SubtractMilliseconds(ANumber: Cardinal); procedure SubtractMinutes(ANumber: Cardinal); procedure SubtractMonths(ANumber: Cardinal); procedure SubtractSeconds(ANumber: Cardinal); procedure SubtractTDateTime(ADateTime: TDateTime); procedure SubtractTIdDateTimeStamp(AIdDateTime: TIdDateTimeStamp); procedure SubtractTTimeStamp(ATimeStamp: TTimeStamp); procedure SubtractWeeks(ANumber: Cardinal); procedure SubtractYears(ANumber: Cardinal); property AsISO8601Calendar: string read GetAsISO8601Calendar; property AsISO8601Ordinal: string read GetAsISO8601Ordinal; property AsISO8601Week: string read GetAsISO8601Week; property AsRFC822: string read GetAsRFC882; property AsTDateTime: TDateTime read GetAsTDateTime; property AsTTimeStamp: TTimeStamp read GetAsTTimeStamp; property AsTimeOFDay: string read GetAsTimeOFDay; property BeatOFDay: Integer read GetBeatOFDay; property Day: Integer read FDay write FDay; property DaysInYear: Integer read GetDaysInYear; property DayOfMonth: Integer read GetDayOfMonth; property DayOfWeek: Integer read GetDayOfWeek; property DayOfWeekName: string read GetDayOfWeekName; property DayOfWeekShortName: string read GetDayOfWeekShortName; property HourOf12Day: Integer read GetHourOf12Day; property HourOf24Day: Integer read GetHourOf24Day; property IsLeapYear: Boolean read FIsLeapYear; property IsMorning: Boolean read GetIsMorning; property Second: Integer read FSecond write FSecond; property SecondsInYear: Integer read GetSecondsInYear; property SecondOfMinute: Integer read GetSecondOfMinute; property MinuteOFDay: Integer read GetMinuteOFDay; property MinuteOfHour: Integer read GetMinuteOfHour; property MonthOFYear: Integer read GetMonthOFYear; property MonthName: string read GetMonthName; property MonthShortName: string read GetMonthShortName; property Millisecond: Integer read FMillisecond write FMillisecond; property TimeZone: Integer read FTimeZone write FTimeZone; property Year: Integer read FYear write SetYear; property WeekOFYear: Integer read GetWeekOFYear; end; implementation const MaxWeekAdd: Cardinal = $FFFFFFFF div IdDaysInWeek; MaxMinutesAdd: Cardinal = $FFFFFFFF div IdSecondsInMinute; constructor TIdDateTimeStamp.Create; begin inherited Create(AOwner); FYear := 1; FDay := 1; FSecond := 1; FMillisecond := 1; FTimeZone := 0; FRequestedTimeZone := 0; end; destructor TIdDateTimeStamp.Destroy; begin inherited; end; procedure TIdDateTimeStamp.AddDays; var i: Integer; begin if (ANumber > Cardinal(DaysInYear - FDay)) and (not (FDay = 1)) then begin ANumber := ANumber - Cardinal(DaysInYear - FDay); FDay := 1; AddYears(1); end else begin FDay := FDay + Integer(ANumber); Exit; end; if ANumber >= IdDaysInLeapYearCycle then begin i := ANumber div IdDaysInLeapYearCycle; AddYears(i * IdYearsInLeapYearCycle); ANumber := ANumber - Cardinal(i * IdDaysInLeapYearCycle); end; if ANumber >= IdDaysInLeapCentury then begin while ANumber >= IDDaysInLeapCentury do begin i := FYear div 100; if i mod 4 = 0 then begin AddYears(IdYearsInCentury); ANumber := ANumber - Cardinal(IdDaysInLeapCentury); end else begin AddYears(IdYearsInCentury); ANumber := ANumber - Cardinal(IdDaysInCentury); end; end; end; if ANumber >= IdDaysInShortLeapYearCycle then begin i := ANumber div IdDaysInShortLeapYearCycle; AddYears(i * IdYearsInShortLeapYearCycle); ANumber := ANumber - Cardinal(i * IdDaysInShortLeapYearCycle); end; i := GetDaysInYear; while Integer(ANumber) > i do begin AddYears(1); Dec(ANumber, i); i := GetDaysInYear; end; if FDay + Integer(ANumber) > i then begin AddYears(1); Dec(ANumber, i - FDay); FDay := ANumber; end else begin Inc(FDay, ANumber); end; end; procedure TIdDateTimeStamp.AddHours; var i: Cardinal; begin i := ANumber div IdHoursInDay; AddDays(i); Dec(ANumber, i * IdHoursInDay); AddSeconds(ANumber * IdSecondsInHour); end; procedure TIdDateTimeStamp.AddMilliseconds; var i: Cardinal; begin i := ANumber div IdMillisecondsInDay; if i > 0 then begin AddDays(i); Dec(ANumber, i * IdMillisecondsInDay); end; i := ANumber div IdMillisecondsInSecond; if i > 0 then begin AddSeconds(i); Dec(ANumber, i * IdMillisecondsInSecond); end; Inc(FMillisecond, ANumber); while FMillisecond > IdMillisecondsInSecond do begin AddSeconds(1); Dec(FMillisecond, IdMillisecondsInSecond); end; end; procedure TIdDateTimeStamp.AddMinutes; begin while ANumber > MaxMinutesAdd do begin AddSeconds(MaxMinutesAdd); Dec(ANumber, MaxMinutesAdd); end; AddSeconds(ANumber * IdSecondsInMinute); end; procedure TIdDateTimeStamp.AddMonths; var i: Integer; begin i := ANumber div IdMonthsInYear; AddYears(i); Dec(ANumber, i * IdMonthsInYear); while ANumber > 0 do begin i := MonthOFYear; if i = 12 then begin i := 1; end; if (i = 2) and (IsLeapYear) then begin AddDays(IdDaysInMonth[i] + 1); end else begin AddDays(IdDaysInMonth[i]); end; Dec(ANumber); end; end; procedure TIdDateTimeStamp.AddSeconds; var i: Cardinal; begin i := ANumber div IdSecondsInDay; if i > 0 then begin AddDays(i); ANumber := ANumber - (i * IdSecondsInDay); end; Inc(FSecond, ANumber); while FSecond > IdSecondsInDay do begin AddDays(1); Dec(FSecond, IdSecondsInDay); end; end; procedure TIdDateTimeStamp.AddTDateTime; begin AddTTimeStamp(DateTimeToTimeStamp(ADateTime)); end; procedure TIdDateTimeStamp.AddTIdDateTimeStamp; begin AddYears(AIdDateTime.Year); AddDays(AIdDateTime.Day); AddSeconds(AIdDateTime.Second); AddMilliseconds(AIdDateTime.Millisecond); end; procedure TIdDateTimeStamp.AddTTimeStamp; var TId: TIdDateTimeStamp; begin TId := TIdDateTimeStamp.Create(Self); try TId.SetFromTTimeStamp(ATimeStamp); Self.AddTIdDateTimeStamp(TId); finally TId.Free; end; end; procedure TIdDateTimeStamp.AddWeeks; begin while ANumber > MaxWeekAdd do begin AddDays(MaxWeekAdd); Dec(ANumber, MaxWeekAdd); end; AddDays(ANumber * IdDaysInWeek); end; procedure TIdDateTimeStamp.AddYears; begin if (FYear <= -1) and (Integer(ANumber) >= -FYear) then begin Inc(ANumber); end; Inc(FYear, ANumber); CheckLeapYear; end; procedure TIdDateTimeStamp.CheckLeapYear; begin if FYear mod 4 = 0 then begin if FYear mod 100 = 0 then begin if FYear mod 400 = 0 then begin FIsLeapYear := True; end else begin FIsLeapYear := False; end; end else begin FIsLeapYear := True; end; end else begin FIsLeapYear := False; end; end; function TIdDateTimeStamp.GetAsISO8601Calendar; begin result := IntToStr(FYear) + '-'; result := result + IntToStr(MonthOFYear) + '-'; result := result + IntToStr(DayOfMonth) + 'T'; result := result + AsTimeOFDay; end; function TIdDateTimeStamp.GetAsISO8601Ordinal: string; begin result := IntToStr(FYear) + '-'; result := result + IntToStr(FDay) + 'T'; result := result + AsTimeOFDay; end; function TIdDateTimeStamp.GetAsISO8601Week: string; begin result := IntToStr(FYear) + '-W'; result := result + IntToStr(WeekOFYear) + '-'; result := result + IntToStr(DayOfWeek) + 'T'; result := result + AsTimeOFDay; end; function TIdDateTimeStamp.GetAsRFC882; begin result := IdDayShortNames[DayOfWeek] + ', '; result := result + IntToStr(DayOfMonth) + ' '; result := result + IdMonthShortNames[MonthOFYear] + ' '; result := result + IntToStr(Year) + ' '; result := result + AsTimeOFDay + ' '; if FTimeZone < -9 then begin result := result + IntToStr(FTimeZone) + '00'; end else if FTimeZone > 9 then begin result := result + '+' + IntToStr(FTimeZone) + '00'; end else if FTimeZone >= 0 then begin result := result + '+0' + IntToStr(FTimeZone) + '00'; end else begin result := result + '-0' + IntToStr(0 - FTimeZone) + '00'; end; end; function TIdDateTimeStamp.GetAsTDateTime; begin result := TimeStampToDateTime(GetAsTTimeStamp); end; function TIdDateTimeStamp.GetAsTTimeStamp; var NonLeap, Leap: Integer; begin Leap := FYear div 400; NonLeap := (FYear div 100) - Leap; Leap := (FYear div 4) - NonLeap; result.Date := (Leap * IdDaysInLeapYear) + (NonLeap * IdDaysInYear) + Integer(FDay); result.Time := (FSecond * IdMillisecondsInSecond) + FMillisecond; end; function TIdDateTimeStamp.GetAsTimeOFDay; var i: Integer; begin i := HourOf24Day; if i < 10 then begin result := result + '0' + IntToStr(i) + ':'; end else begin result := result + IntToStr(i) + ':'; end; i := MinuteOfHour - 1; if i < 10 then begin result := result + '0' + IntToStr(i) + ':'; end else begin result := result + IntToStr(i) + ':'; end; i := SecondOfMinute - 1; if i < 10 then begin result := result + '0' + IntToStr(i) + ' '; end else begin result := result + IntToStr(i) + ' '; end; end; function TIdDateTimeStamp.GetBeatOFDay; var i64: Int64; begin i64 := (FSecond) * IdBeatsInDay; i64 := i64 div IdSecondsInDay; result := Integer(i64); end; function TIdDateTimeStamp.GetDaysInYear; begin if IsLeapYear then begin result := IdDaysInLeapYear; end else begin result := IdDaysInYear; end; end; function TIdDateTimeStamp.GetDayOfMonth; var count, mnth, days: Integer; begin mnth := MonthOFYear; if IsLeapYear and (mnth > 2) then begin days := 1; end else begin days := 0; end; for count := 1 to mnth - 1 do begin Inc(days, IdDaysInMonth[count]); end; days := Day - days; if days < 0 then begin result := 0; end else begin result := days; end; end; function TIdDateTimeStamp.GetDayOfWeek; var a, y, m, d, mnth: Integer; begin // Thanks to the "FAQ About Calendars" by Claus Tøndering for this algorithm // http://www.tondering.dk/claus/calendar.html mnth := MonthOFYear; a := (14 - mnth) div 12; y := Year - a; m := mnth + (12 * a) - 2; d := DayOfMonth + y + (y div 4) - (y div 100) + (y div 400) + ((31 * m) div 12); d := d mod 7; result := d + 1; end; function TIdDateTimeStamp.GetDayOfWeekName; begin result := IdDayNames[GetDayOfWeek]; end; function TIdDateTimeStamp.GetDayOfWeekShortName; begin result := IdDayShortNames[GetDayOfWeek]; end; function TIdDateTimeStamp.GetHourOf12Day; var hr: Integer; begin hr := GetHourOf24Day; if hr > 12 then begin Dec(hr, 12); end; result := hr; end; function TIdDateTimeStamp.GetHourOf24Day; begin result := (Second - 1) div IdSecondsInHour; end; function TIdDateTimeStamp.GetIsMorning; begin if Second <= (IdSecondsInHalFDay + 1) then begin result := True; end else begin result := False; end; end; function TIdDateTimeStamp.GetMinuteOFDay; begin result := Second div IdSecondsInMinute; end; function TIdDateTimeStamp.GetMinuteOfHour; begin result := GetMinuteOFDay - (IdMinutesInHour * (GetHourOf24Day)); end; function TIdDateTimeStamp.GetMonthOFYear; var AddOne, Count: Byte; Today: Integer; begin if IsLeapYear then begin AddOne := 1; end else begin AddOne := 0; end; Today := Day; Count := 1; result := 0; while Count <> 13 do begin if Count = 2 then begin if Today > IdDaysInMonth[Count] + AddOne then begin Dec(Today, IdDaysInMonth[Count] + AddOne); end else begin result := Count; break; end; end else begin if Today > IdDaysInMonth[Count] then begin Dec(Today, IdDaysInMonth[Count]); end else begin result := Count; break; end; end; Inc(Count); end; end; function TIdDateTimeStamp.GetMonthName; begin result := IdMonthNames[MonthOFYear]; end; function TIdDateTimeStamp.GetMonthShortName; begin result := IdMonthShortNames[MonthOFYear]; end; function TIdDateTimeStamp.GetSecondsInYear; begin if IsLeapYear then begin result := IdSecondsInLeapYear; end else begin result := IdSecondsInYear; end; end; function TIdDateTimeStamp.GetSecondOfMinute; begin result := FSecond - (GetMinuteOFDay * IdSecondsInMinute); end; function TIdDateTimeStamp.GetWeekOFYear; var w: Integer; DT: TIdDateTimeStamp; begin DT := TIdDateTimeStamp.Create(Self); try DT.SetYear(Year); w := DT.DayOfWeek; w := w + Day - 2; w := w div 7; result := w + 1; finally DT.Free; end; end; procedure TIdDateTimeStamp.SetFromTDateTime; begin SetFromTTimeStamp(DateTimeToTimeStamp(ADateTime)); end; procedure TIdDateTimeStamp.SetFromTTimeStamp; begin SetYear(1); SetDay(1); SetSecond(0); SetMillisecond(ATimeStamp.Time); SetDay(ATimeStamp.Date); end; procedure TIdDateTimeStamp.SetDay; begin FDay := 0; AddDays(ANumber); end; procedure TIdDateTimeStamp.SetMillisecond; begin FMillisecond := 0; AddMilliseconds(ANumber); end; procedure TIdDateTimeStamp.SetSecond; begin FSecond := 0; AddSeconds(ANumber); end; procedure TIdDateTimeStamp.SetYear; begin if ANumber = 0 then begin exit; end; FYear := ANumber; CheckLeapYear; end; procedure TIdDateTimeStamp.SubtractDays; var i: Integer; begin if ANumber >= Cardinal(FDay - 1) then begin ANumber := ANumber - Cardinal(FDay - 1); FDay := 1; end else begin FDay := FDay - Integer(ANumber); end; if ANumber >= IdDaysInLeapYearCycle then begin i := ANumber div IdDaysInLeapYearCycle; SubtractYears(i * IdYearsInLeapYearCycle); ANumber := ANumber - Cardinal(i * IdDaysInLeapYearCycle); end; if ANumber >= IdDaysInLeapCentury then begin while ANumber >= IdDaysInLeapCentury do begin i := FYear div 100; if i mod 4 = 0 then begin SubtractYears(IdYearsInCentury); ANumber := ANumber - Cardinal(IdDaysInLeapCentury); end else begin SubtractYears(IdYearsInCentury); ANumber := ANumber - Cardinal(IdDaysInCentury); end; end; end; if ANumber >= IdDaysInShortLeapYearCycle then begin while ANumber >= IdDaysInShortLeapYearCycle do begin i := (FYear shr 2) shl 2; if SysUtils.IsLeapYear(i) then begin SubtractYears(IdYearsInShortLeapYearCycle); ANumber := ANumber - Cardinal(IdDaysInShortLeapYearCycle); end else begin SubtractYears(IdYearsInShortLeapYearCycle); ANumber := ANumber - Cardinal(IdDaysInShortNonLeapYearCycle); end; end; end; while ANumber > Cardinal(DaysInYear) do begin SubtractYears(1); Dec(ANumber, DaysInYear); if Self.IsLeapYear then begin AddDays(1); end; end; if ANumber >= Cardinal(FDay) then begin SubtractYears(1); ANumber := ANumber - Cardinal(FDay); Day := DaysInYear - Integer(ANumber); end else begin Dec(FDay, ANumber); end; end; procedure TIdDateTimeStamp.SubtractHours; var i: Cardinal; begin i := ANumber div IdHoursInDay; SubtractDays(i); Dec(ANumber, i * IdHoursInDay); SubtractSeconds(ANumber * IdSecondsInHour); end; procedure TIdDateTimeStamp.SubtractMilliseconds; var i: Cardinal; begin i := ANumber div IdMillisecondsInDay; SubtractDays(i); Dec(ANumber, i * IdMillisecondsInDay); i := ANumber div IdMillisecondsInSecond; SubtractSeconds(i); Dec(ANumber, i * IdMillisecondsInSecond); Dec(FMillisecond, ANumber); while FMillisecond <= 0 do begin SubtractSeconds(1); FMillisecond := IdMillisecondsInSecond - FMillisecond; end; end; procedure TIdDateTimeStamp.SubtractMinutes(ANumber: Cardinal); begin while ANumber > MaxMinutesAdd do begin SubtractSeconds(MaxMinutesAdd * IdSecondsInMinute); Dec(ANumber, MaxMinutesAdd); end; SubtractSeconds(ANumber * IdSecondsInMinute); end; procedure TIdDateTimeStamp.SubtractMonths; var i: Integer; begin i := ANumber div IdMonthsInYear; SubtractYears(i); Dec(ANumber, i * IdMonthsInYear); while ANumber > 0 do begin i := MonthOFYear; if i = 1 then begin i := 13; end; if (i = 3) and (IsLeapYear) then begin SubtractDays(IdDaysInMonth[2] + 1); end else begin SubtractDays(IdDaysInMonth[i - 1]); end; Dec(ANumber); end; end; procedure TIdDateTimeStamp.SubtractSeconds(ANumber: Cardinal); var i: Cardinal; begin i := ANumber div IdSecondsInDay; SubtractDays(i); Dec(ANumber, i * IdSecondsInDay); Dec(FSecond, ANumber); if FSecond <= 0 then begin SubtractDays(1); FSecond := IdSecondsInDay + FSecond; end; end; procedure TIdDateTimeStamp.SubtractTDateTime; begin SubtractTTimeStamp(DateTimeToTimeStamp(ADateTime)); end; procedure TIdDateTimeStamp.SubtractTIdDateTimeStamp; begin SubtractYears(AIdDateTime.Year); SubtractDays(AIdDateTime.Day); SubtractSeconds(AIdDateTime.Second); SubtractMilliseconds(AIdDateTime.Millisecond); end; procedure TIdDateTimeStamp.SubtractTTimeStamp; var TId: TIdDateTimeStamp; begin TId := TIdDateTimeStamp.Create(Self); try TId.SetFromTTimeStamp(ATimeStamp); Self.SubtractTIdDateTimeStamp(TId); finally TId.Free; end; end; procedure TIdDateTimeStamp.SubtractWeeks(ANumber: Cardinal); begin while ANumber > MaxWeekAdd do begin SubtractDays(MaxWeekAdd * IdDaysInWeek); Dec(ANumber, MaxWeekAdd * IdDaysInWeek); end; SubtractDays(ANumber * IdDaysInWeek); end; procedure TIdDateTimeStamp.SubtractYears; begin if (FYear > 0) and (ANumber >= Cardinal(FYear)) then begin Inc(ANumber); end; FYear := FYear - Integer(ANumber); CheckLeapYear; end; end.
unit uPostagensControl; interface uses uPostagensModel, System.SysUtils, FireDAC.Comp.Client; type TPostagensControl = class private FPostagensModel: TpostagensModel; public constructor Create; destructor Destroy; override; function Exibir(): TFDQuery; function Excluir(pId: Integer): Boolean; function Alterar(pIdUsario, pId : Integer; pTituloPostagem, pPostagem : string): Boolean; function Inserir (pIdUsario, pId : Integer; pTituloPostagem, pPostagem : string) : Boolean; function CriarBanco(pBancoDados : string ): Boolean; function ExecutaScript(): Boolean; end; implementation function TPostagensControl.Alterar(pIdUsario, pId : Integer; pTituloPostagem, pPostagem : string): Boolean; var PostagensModel: TpostagensModel; begin try PostagensModel := TpostagensModel.Create; Result := PostagensModel.Alterar(pIdUsario, pId, pTituloPostagem, pPostagem); finally PostagensModel.Free; end; end; constructor TPostagensControl.Create; begin FPostagensModel := TpostagensModel.Create; end; function TPostagensControl.CriarBanco(pBancoDados: string): Boolean; var PostagensModel: TpostagensModel; begin try PostagensModel := TpostagensModel.Create; Result := PostagensModel.CriarBanco(pBancoDados); finally PostagensModel.Free; end; end; destructor TPostagensControl.Destroy; begin FPostagensModel.Free; inherited; end; function TPostagensControl.Excluir(pId: Integer): Boolean; var PostagensModel: TpostagensModel; begin try PostagensModel := TpostagensModel.Create; Result := PostagensModel.Excluir(pId); finally PostagensModel.Free; end; end; function TPostagensControl.ExecutaScript : Boolean; var PostagensModel: TpostagensModel; begin try PostagensModel := TpostagensModel.Create; Result := PostagensModel.ExecutaScript; finally PostagensModel.Free; end; end; function TPostagensControl.Exibir: TFDQuery; begin Result := FPostagensModel.Exibir; end; function TPostagensControl.Inserir(pIdUsario, pId: Integer; pTituloPostagem, pPostagem: string): Boolean; var PostagensModel: TpostagensModel; begin try PostagensModel := TpostagensModel.Create; Result := PostagensModel.Inserir(pIdUsario, pId, pTituloPostagem, pPostagem); finally PostagensModel.Free; end; end; end.
unit fAbout; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TAboutForm = class(TForm) Label1: TLabel; VersionLabel: TLabel; Label3: TLabel; Button1: TButton; UrlLabel: TLabel; procedure FormCreate(Sender: TObject); procedure UrlLabelClick(Sender: TObject); private { Private declarations } public { Public declarations } end; implementation uses ShellAPI; {$R *.dfm} function GetVersion(const ExePath: string; out Major, Minor, Release, Build: Word): Boolean; var Info: PVSFixedFileInfo; InfoSize: Cardinal; nHwnd: DWORD; BufferSize: DWORD; Buffer: Pointer; begin Major := 0; Minor := 0; Release := 0; Build := 0; BufferSize := GetFileVersionInfoSize(PChar(ExePath), nHWnd); {Get buffer size} Result := True; if BufferSize <> 0 then begin {if zero, there is no version info} GetMem(Buffer, BufferSize); {allocate buffer memory} try if GetFileVersionInfo(PChar(ExePath), nHWnd, BufferSize, Buffer) then begin {got version info} if VerQueryValue(Buffer, '\', Pointer(Info), InfoSize) then begin {got root block version information} Major := HiWord(Info^.dwFileVersionMS); {extract major version} Minor := LoWord(Info^.dwFileVersionMS); {extract minor version} Release := HiWord(Info^.dwFileVersionLS); {extract release version} Build := LoWord(Info^.dwFileVersionLS); {extract build version} end else begin Result := False; {no root block version info} end; end else begin Result := False; {couldn't extract version info} end; finally FreeMem(Buffer, BufferSize); {release buffer memory} end; end else begin Result := False; {no version info at all in the file} end; end; //returns -1 if ExePath1 is a lower version than ExePath2, 0 if they are of //equal version, 1 if ExePath1 is a higher version than ExePath2 function CompareVersions(ExePath1, ExePath2: string): Integer; var Major1, Major2, Minor1, Minor2, Release1, Release2, Build1, Build2: Word; begin Result := 0; if FileExists(ExePath1) and FileExists(ExePath2) then begin if GetVersion(ExePath1, Major1, Minor1, Release1, Build1) then begin if GetVersion(ExePath2, Major2, Minor2, Release2, Build2) then begin if (Major1 > Major2) or ((Major1 = Major2) and (Minor1 > Minor2)) or ((Major1 = Major2) and (Minor1 = Minor2) and (Release1 > Release2)) or ((Major1 = Major2) and (Minor1 = Minor2) and (Release1 = Release2) and (Build1 > Build2)) then Result := 1 else if (Major1 = Major2) and (Minor1 = Minor2) and (Release1 = Release2) and (Build1 = Build2) then Result := 0 else Result := -1; end; end; end; end; function GetVersionString(const ExePath: string): string; var Major, Minor, Release, Build: Word; begin Result := '1.0.0 (Build 0)'; if FileExists(ExePath) then begin if GetVersion(ExePath, Major, Minor, Release, Build) then Result := IntToStr(Major) + '.' + IntToStr(Minor) + '.' + IntToStr(Release) + ' (Build ' + IntToStr(Build) + ')'; end; end; procedure TAboutForm.FormCreate(Sender: TObject); begin VersionLabel.Caption := GetVersionString(Application.ExeName); end; procedure TAboutForm.UrlLabelClick(Sender: TObject); begin ShellExecute(Handle, 'OPEN', PChar(TLabel(Sender).Caption), nil, nil, SW_SHOWNORMAL); end; end.
unit llcltest_DfmCheck_Unit; interface implementation uses Unit1, SysUtils; procedure TestDfmFormConsistency; begin { Form1: TForm1 } with TForm1(nil) do { Unit1.pas } begin Label1.ClassName; { Label1: TLabel; } GroupBox1.ClassName; { GroupBox1: TGroupBox; } RadioButton1.ClassName; { RadioButton1: TRadioButton; } RadioButton2.ClassName; { RadioButton2: TRadioButton; } ComboBox1.ClassName; { ComboBox1: TComboBox; } Edit1.ClassName; { Edit1: TEdit; } Button1.ClassName; { Button1: TButton; } Button3.ClassName; { Button3: TButton; } ListBox1.ClassName; { ListBox1: TListBox; } Memo1.ClassName; { Memo1: TMemo; } Button2.ClassName; { Button2: TButton; } Button4.ClassName; { Button4: TButton; } CheckBox1.ClassName; { CheckBox1: TCheckBox; } Button6.ClassName; { Button6: TButton; } Button7.ClassName; { Button7: TButton; } Button8.ClassName; { Button8: TButton; } Button9.ClassName; { Button9: TButton; } Button10.ClassName; { Button10: TButton; } CheckBox2.ClassName; { CheckBox2: TCheckBox; } CheckBox3.ClassName; { CheckBox3: TCheckBox; } ComboBox2.ClassName; { ComboBox2: TComboBox; } StaticText1.ClassName; { StaticText1: TStaticText; } Button5.ClassName; { Button5: TButton; } Button11.ClassName; { Button11: TButton; } ProgressBar1.ClassName; { ProgressBar1: TProgressBar; } StaticText2.ClassName; { StaticText2: TStaticText; } Timer1.ClassName; { Timer1: TTimer; } MainMenu1.ClassName; { MainMenu1: TMainMenu; } MenuItem1.ClassName; { MenuItem1: TMenuItem; } MenuItem3.ClassName; { MenuItem3: TMenuItem; } MenuItem4.ClassName; { MenuItem4: TMenuItem; } MenuItem13.ClassName; { MenuItem13: TMenuItem; } MenuItem11.ClassName; { MenuItem11: TMenuItem; } MenuItem12.ClassName; { MenuItem12: TMenuItem; } MenuItem5.ClassName; { MenuItem5: TMenuItem; } MenuItem6.ClassName; { MenuItem6: TMenuItem; } MenuItem2.ClassName; { MenuItem2: TMenuItem; } MenuItem7.ClassName; { MenuItem7: TMenuItem; } MenuItem8.ClassName; { MenuItem8: TMenuItem; } PopupMenu1.ClassName; { PopupMenu1: TPopupMenu; } MenuItem9.ClassName; { MenuItem9: TMenuItem; } MenuItem10.ClassName; { MenuItem10: TMenuItem; } XPManifest1.ClassName; { XPManifest1: TXPManifest; } SaveDialog1.ClassName; { SaveDialog1: TSaveDialog; } OpenDialog1.ClassName; { OpenDialog1: TOpenDialog; } end; end; end.
unit Security.User; interface uses System.SysUtils, System.Classes, Vcl.ExtCtrls, System.UITypes, Vcl.StdCtrls, Vcl.Forms , Security.User.Interfaces , Security.User.View, System.StrUtils ; type TPermissionNotifyEvent = Security.User.Interfaces.TUserNotifyEvent; TResultNotifyEvent = Security.User.Interfaces.TResultNotifyEvent; TSecurityUserView = Security.User.View.TSecurityUserView; TSecurityUser = class(TComponent) constructor Create(AOwner: TComponent); override; destructor Destroy; override; strict private FView: TSecurityUserView; FOnUser: TUserNotifyEvent; FOnResult: TResultNotifyEvent; { Strict private declarations } procedure SetComputerIP(const Value: string); procedure SetServerIP(const Value: string); procedure SetSigla(const Value: string); procedure setUpdatedIn(const Value: string); procedure SetVersion(const Value: string); function getComputerIP: string; function getLogo: TImage; function getServerIP: string; function getSigla: string; function getUpdatedIn: string; function getVersion: string; private { Private declarations } procedure setID(Value: Int64); function getID: Int64; function getUpdatedAt: TDateTime; procedure setUpdatedAt(const Value: TDateTime); procedure setNameUser(Value: String); function getNameUser: String; procedure setEmail(Value: String); function getEmail: String; procedure setActive(Value: Boolean); function getActive: Boolean; procedure setPassword(Value: String); function getPassword: String; procedure setMatrixID(Value: Integer); function getMatrixID: Integer; procedure setIsMatrix(Value: Boolean); function getIsMatrix: Boolean; protected { Protected declarations } public { Public declarations } function View: iUserView; property Logo: TImage read getLogo; procedure Execute; public { Published hide declarations } property ServerIP : string read getServerIP write SetServerIP; property ComputerIP: string read getComputerIP write SetComputerIP; property Sigla : string read getSigla write SetSigla; property Version : string read getVersion write SetVersion; property UpdatedIn : string read getUpdatedIn write setUpdatedIn; published { Published declarations - Properties } property ID : Int64 read getID write setID; property UpdatedAt : TDateTime read getUpdatedAt write setUpdatedAt; property NameUser: String read getNameUser write setNameUser; property Email : String read getEmail write setEmail; property Active : Boolean read getActive write setActive; property Password : String read getPassword write setPassword; property MatrixID : Integer read getUserID write setMatrixID; property IsMatrix : Boolean read getIsUser write setIsMatrix; { Published declarations - Events } property OnUser: TUserNotifyEvent read FOnUser write FOnUser; property OnResult: TResultNotifyEvent read FOnResult write FOnResult; end; implementation uses Security.Internal; { TSecurityManage } constructor TSecurityUser.Create(AOwner: TComponent); begin FView := TSecurityUserView.Create(Screen.FocusedForm); inherited; end; destructor TSecurityUser.Destroy; begin FreeAndNil(FView); inherited; end; procedure TSecurityUser.SetComputerIP(const Value: string); begin FView.LabelIPComputerValue.Caption := Value; end; function TSecurityUser.getComputerIP: string; begin Result := FView.LabelIPComputerValue.Caption; end; procedure TSecurityUser.SetServerIP(const Value: string); begin FView.LabelIPServerValue.Caption := Value; end; function TSecurityUser.getServerIP: string; begin Result := FView.LabelIPServerValue.Caption; end; procedure TSecurityUser.SetSigla(const Value: string); begin FView.PanelTitleLabelSigla.Caption := Value; end; function TSecurityUser.getSigla: string; begin Result := FView.PanelTitleLabelSigla.Caption; end; procedure TSecurityUser.setUpdatedIn(const Value: string); begin FView.PanelTitleAppInfoUpdatedValue.Caption := Value; end; function TSecurityUser.getUpdatedIn: string; begin Result := FView.PanelTitleAppInfoUpdatedValue.Caption; end; procedure TSecurityUser.SetVersion(const Value: string); begin FView.PanelTitleAppInfoVersionValue.Caption := Value; end; function TSecurityUser.getVersion: string; begin Result := FView.PanelTitleAppInfoVersionValue.Caption; end; function TSecurityUser.getLogo: TImage; begin Result := FView.ImageLogo; end; function TSecurityUser.View: iUserView; begin Result := FView; end; procedure TSecurityUser.setID(Value: Int64); begin FView.ID := Value; end; function TSecurityUser.getID: Int64; begin Result := FView.ID; end; procedure TSecurityUser.setNameUser(Value: String); begin FView.NameUser := Value; end; function TSecurityUser.getNameUser: String; begin Result := FView.NameUser; end; procedure TSecurityUser.setEmail(Value: String); begin FView.Email := Value; end; function TSecurityUser.getEmail: String; begin Result := FView.Email; end; procedure TSecurityUser.setActive(Value: Boolean); begin FView.Active := Value; end; function TSecurityUser.getActive: Boolean; begin Result := FView.Active; end; procedure TSecurityUser.setPassword(Value: String); begin FView.Password := Value; end; function TSecurityUser.getPassword: String; begin Result := FView.Password; end; procedure TSecurityUser.setUpdatedAt(const Value: TDateTime); begin FView.UpdatedAt := Value; end; function TSecurityUser.getUpdatedAt: TDateTime; begin Result := FView.UpdatedAt; end; procedure TSecurityUser.setUserID(Value: Integer); begin FView.MatrixID := Value; end; function TSecurityUser.getMatrixID: Integer; begin Result := FView.MatrixID; end; procedure TSecurityUser.setIsMatrix(Value: Boolean); begin FView.IsMatrix := Value; end; function TSecurityUser.getIsMatrix: Boolean; begin Result := FView.IsMatrix; end; procedure TSecurityUser.Execute; begin Internal.Required(Self.FOnUser); FView.OnUser := Self.FOnUser; FView.OnResult := Self.FOnResult; FView.Show; end; end.
unit SemiAutoTrimmer; interface uses SysUtils, Classes, ClipBrd, Windows, Thread.Trim, TrimList, Device.PhysicalDrive.List, Device.PhysicalDrive, Getter.PhysicalDrive.PartitionList, Getter.PhysicalDrive.ListChange; type TSemiAutoTrimmer = class public procedure SemiAutoTrim(const Model, Serial: String); private function GetDeviceEntry(const Model, Serial: String): IPhysicalDrive; function GetTrimList(SSDEntry: IPhysicalDrive): TTrimList; procedure ExecuteTrim(TrimList: TTrimList); end; implementation procedure TSemiAutoTrimmer.SemiAutoTrim(const Model, Serial: String); var SSDEntry: IPhysicalDrive; PartToTrim: TTrimList; begin SSDEntry := GetDeviceEntry(Model, Serial); PartToTrim := GetTrimList(SSDEntry); ExecuteTrim(PartToTrim); FreeAndNil(PartToTrim); end; function TSemiAutoTrimmer.GetDeviceEntry(const Model, Serial: String): IPhysicalDrive; var SSDList: TPhysicalDriveList; ListChangeGetter: TListChangeGetter; begin SSDList := TPhysicalDriveList.Create; ListChangeGetter := TListChangeGetter.Create; ListChangeGetter.IsOnlyGetSupportedDrives := true; ListChangeGetter.RefreshListWithoutResultFrom(SSDList); result := SSDList[SSDList.IndexOf(Model, Serial)]; FreeAndNil(ListChangeGetter); FreeAndNil(SSDList); end; function TSemiAutoTrimmer.GetTrimList(SSDEntry: IPhysicalDrive): TTrimList; var PhysicalDrive: IPhysicalDrive; Drives: TPartitionList; CurrPartition: Integer; begin result := TTrimList.Create; PhysicalDrive := SSDEntry; Drives := PhysicalDrive.GetPartitionList; for CurrPartition := 0 to Drives.Count - 1 do result.Add(Drives[CurrPartition].Letter + ':'); FreeAndNil(Drives); end; procedure TSemiAutoTrimmer.ExecuteTrim(TrimList: TTrimList); var TrimThread: TTrimThread; begin if TrimThread <> Nil then FreeAndNil(TrimThread); TrimThread := TTrimThread.Create(true, false); TrimThread.SetPartitionList(TrimList); TrimThread.Priority := tpLower; TrimThread.Start; while TTrimThread.TrimStage < TTrimStage.Finished do Sleep(10); Sleep(10); end; end.
namespace WindowsApplication2; interface uses System.Windows.Forms, System.Drawing; type /// <summary> /// Summary description for MainForm. /// </summary> MainForm = partial class(System.Windows.Forms.Form) private protected method Dispose(aDisposing: boolean); override; public constructor; end; implementation {$REGION Construction and Disposition} constructor MainForm; begin // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // end; method MainForm.Dispose(aDisposing: boolean); begin if aDisposing then begin if assigned(components) then components.Dispose(); // // TODO: Add custom disposition code here // end; inherited Dispose(aDisposing); end; {$ENDREGION} end.
unit FTPClient; interface uses Windows, Messages, Variants,SysUtils, Classes, Wininet, Dialogs; type TFTPClient = class(TObject) private FInetHandle: HInternet; // 句柄 FFtpHandle: HInternet; // 句柄 FHost: string; // 主机IP地址 FUserName: string; // 用户名 FPassword: string; // 密码 FPort: integer; // 端口 FCurrentDir: string; // 当前目录 public constructor Create;virtual; destructor Destroy;override; function Connect: boolean; function Disconnect: boolean; function UploadFile(RemoteFile: PChar; NewFile: PChar): boolean; function DownloadFile(RemoteFile: PChar; NewFile: PChar): boolean; function CreateDirectory(Directory: PChar): boolean; function LayerNumber(dir: string): integer; function MakeDirectory(dir: string): boolean; function FTPMakeDirectory(dir: string): boolean; function IndexOfLayer(index: integer; dir: string): string; function GetFileName(FileName: string): string; function GetDirectory(dir: string): string; property InetHandle: HInternet read FInetHandle write FInetHandle; property FtpHandle: HInternet read FFtpHandle write FFtpHandle; property Host: string read FHost write FHost; property UserName: string read FUserName write FUserName; property Password: string read FPassword write FPassword; property Port: integer read FPort write FPort; property CurrentDir: string read FCurrentDir write FCurrentDir; end; implementation //------------------------------------------------------------------------- // 构造函数 constructor TFTPClient.Create; begin inherited Create; end; //------------------------------------------------------------------------- // 析构函数 destructor TFTPClient.Destroy; begin inherited Destroy; end; //------------------------------------------------------------------------- // 链接服务器 function TFTPClient.Connect: boolean; begin try Result := false; // 创建句柄 FInetHandle := InternetOpen(PChar('KOLFTP'), 0, nil, nil, 0); FtpHandle := InternetConnect(FInetHandle, PChar(Host), FPort, PChar(FUserName), PChar(FPassword), INTERNET_SERVICE_FTP, 0, 255); if Assigned(FtpHandle) then begin Result := true; end; except Result := false; end; end; //------------------------------------------------------------------------- // 断开链接 function TFTPClient.Disconnect: boolean; begin try InternetCloseHandle(FFtpHandle); InternetCloseHandle(FInetHandle); FtpHandle:=nil; inetHandle:=nil; Result := true; except Result := false; end; end; //------------------------------------------------------------------------- // 上传文件 function TFTPClient.UploadFile(RemoteFile: PChar; NewFile: PChar): boolean; begin try Result := true; FTPMakeDirectory(NewFile); if not FtpPutFile(FFtpHandle, RemoteFile, NewFile, FTP_TRANSFER_TYPE_BINARY, 255) then begin Result := false; end; except Result := false; end; end; //------------------------------------------------------------------------- // 下载文件 function TFTPClient.DownloadFile(RemoteFile: PChar; NewFile: PChar): boolean; begin try Result := true; MakeDirectory(NewFile); if not FtpGetFile(FFtpHandle, RemoteFile, NewFile, True, FILE_ATTRIBUTE_NORMAL, FTP_TRANSFER_TYPE_BINARY OR INTERNET_FLAG_RELOAD, 255) then begin Result := false; end; except on E:Exception do begin Result := false; showMessage(e.Message); end; end; end; //------------------------------------------------------------------------- // 创建目录 function TFTPClient.CreateDirectory(Directory: PChar): boolean; begin try Result := true; if FtpCreateDirectory(FFtpHandle, Directory)=false then begin Result := false; end; except Result := false; end; end; //------------------------------------------------------------------------- // 目录数 function TFTPClient.LayerNumber(dir: string): integer; var i: integer; flag: string; begin Result := 0; for i:=1 to Length(dir) do begin flag := Copy(dir,i,1); if (flag='\') or (flag='/') then begin Result := Result + 1; end; end; end; //------------------------------------------------------------------------- // 创建目录 function TFTPClient.FTPMakeDirectory(dir: string): boolean; var count, i: integer; SubPath: string; begin Result := true; count := LayerNumber(dir); for i:=1 to count do begin SubPath := IndexOfLayer(i, dir); if CreateDirectory(PChar(CurrentDir+SubPath))=false then begin Result := false; end; end; end; //------------------------------------------------------------------------- // 创建目录 function TFTPClient.MakeDirectory(dir: string): boolean; var count, i: integer; SubPath: string; str: string; begin Result := true; count := LayerNumber(dir); str := GetDirectory(dir); for i:=2 to count do begin SubPath := IndexOfLayer(i, str); if not DirectoryExists(SubPath) then begin if not CreateDir(SubPath) then begin Result := false; end; end; end; end; //------------------------------------------------------------------------- // 获取index层的目录 function TFTPClient.IndexOfLayer(index: integer; dir: string): string; var count, i: integer; ch: string; begin Result := ''; count := 0; for i:=1 to Length(dir) do begin ch := Copy(dir, i, 1); if (ch='\') or (ch='/') then begin count := count+1; end; if count=index then begin break; end; Result := Result + ch; end; end; //------------------------------------------------------------------------- // 获取文件名 function TFTPClient.GetFileName(FileName: string): string; begin Result := ''; while (Copy(FileName, Length(FileName), 1)<>'\') and (Length(FileName)>0) do begin Result := Copy(FileName, Length(FileName), 1)+Result; Delete(FileName, Length(FileName), 1); end; end; //------------------------------------------------------------------------- // 获取目录 function TFTPClient.GetDirectory(dir: string): string; begin Result := dir; while (Copy(Result, Length(Result), 1)<>'/') and (Length(Result)>0) do begin Delete(Result, Length(Result), 1); end; { if Copy(Result, Length), 1)='\' then begin Delete(Result, 1, 1); end;} end; //------------------------------------------------------------------------- end.
unit UI.CommandLineParser; interface uses System.Classes, System.TypInfo, System.SysUtils, System.Generics.Collections, App.Types, UI.Types; type TCommandLinePattern = class strict private FName: string; FParametrs: TParametrs; function TryParse(Args: strings;out Return: TCommandData): boolean; virtual; public property Name: string read FName write FName; property Parametrs: TParametrs read FParametrs write FParametrs; function HasParameter(const ANameParametr,AValue: string): TCommandLinePattern; function Parse(args: strings): TCommandData;virtual; constructor Create(const AName: string); destructor Destroy; override; end; TCommand = class public class function WithName(const AName: string): TCommandLinePattern; static; end; implementation {$Region 'TCommand'} class function TCommand.WithName(const AName: string): TCommandLinePattern; begin Result := TCommandLinePattern.Create(AName); end; {$ENDREGION} {$Region 'TCommandLinePattern'} constructor TCommandLinePattern.Create(const AName: string); begin FName := AName; FParametrs := []; end; destructor TCommandLinePattern.Destroy; begin FName := string.Empty; inherited; end; function TCommandLinePattern.HasParameter(const ANameParametr,AValue: string): TCommandLinePattern; var Parametr: TParametr; begin Parametr.Name := ANameParametr; Parametr.Value := AValue; FParametrs := FParametrs + [Parametr]; Result := Self; end; function TCommandLinePattern.Parse(args: strings): TCommandData; var Command: TCommandData; begin try if TryParse(args,Command) then Result:= Command; except raise Exception.Create('Exception: Incorrect format string!'); end; end; function TCommandLinePattern.TryParse(Args: strings; out Return: TCommandData): boolean; var Parametr: TParametr; Name: string; i: uint64; begin Result := True; if Args.IsEmpty then begin Result := False; exit; end; if not (Args[0] = FName) then begin Result := False; exit; end; Return.CommandName := TCommandsNames.AsCommand(FName); i := 1; Parametr.Name := ''; Parametr.Value := ''; Return.Parametrs := []; while i <= Args.Length - 1 do begin if Parametr.Name = '' then begin if Args[i].StartsWith('-') then Parametr.Name := args[i].Substring(1); end else begin if Args[i].StartsWith('-') then begin Return.Parametrs := Return.Parametrs + [Parametr]; Parametr.Name := args[i].Substring(1); end else begin Parametr.Value := args[i].Substring(0); Return.Parametrs := Return.Parametrs + [Parametr]; Parametr.Name := ''; Parametr.Value := ''; end; end; inc(i); end; end; {$ENDREGION} end.
unit VersionInfo; interface uses Windows, SysUtils; type TLangAndCP = record wLanguage: word; wCodePage: word; end; PLangAndCP = ^TLangAndCP; RAppInfo = record InfoStr: String; Value: String; end; rRAppInfo = array of RAppInfo; {$M+} TVersionInfo = class private { Private declarations } FDefaultValue: String; FLang: PLangAndCP; FBuf: PChar; FAppInfo: rRAppInfo; function QueryValue(pInfo: Integer): String; procedure ClearAll; public { Public declarations } constructor Create; destructor Destroy; override; published { Published declarations } property DefaultValue: String read FDefaultValue write FDefaultValue stored False; procedure GetInfo(FName: String); function GetInfoString(pInfo: Integer): String; function GetInfoValue(pInfo: Integer): String; end; const cVICompanyName = Integer(0); cVIFileDescription = Integer(1); cVIFileVersion = Integer(2); cVIInternalName = Integer(3); cVILegalCopyright = Integer(4); cVILegalTradeMarks = Integer(5); cVIOriginalFilename = Integer(6); cVIProductName = Integer(7); cVIProductVersion = Integer(8); cVIComments = Integer(9); cVIPrivateBuild = Integer(10); cVISpecialBuild = Integer(11); // cVIMajorVersion = Integer(12); cVIMinorVersion = Integer(13); cVIRelease = Integer(14); cVIBuild = Integer(15); implementation //-------------------------------------------------------------------------- constructor TVersionInfo.Create; begin FDefaultValue := '<info not available>'; SetLength(FAppInfo, 16); FAppInfo[cVICompanyName].InfoStr := 'CompanyName'; FAppInfo[cVIFileDescription].InfoStr := 'FileDescription'; FAppInfo[cVIFileVersion].InfoStr := 'FileVersion'; FAppInfo[cVIInternalName].InfoStr := 'InternalName'; FAppInfo[cVILegalCopyright].InfoStr := 'LegalCopyright'; FAppInfo[cVILegalTradeMarks].InfoStr := 'LegalTradeMarks'; FAppInfo[cVIOriginalFilename].InfoStr := 'OriginalFilename'; FAppInfo[cVIProductName].InfoStr := 'ProductName'; FAppInfo[cVIProductVersion].InfoStr := 'ProductVersion'; FAppInfo[cVIComments].InfoStr := 'Comments'; FAppInfo[cVIPrivateBuild].InfoStr := 'PrivateBuild'; FAppInfo[cVISpecialBuild].InfoStr := 'SpecialBuild'; FAppInfo[cVIMajorVersion].InfoStr := 'MajorVersion'; FAppInfo[cVIMinorVersion].InfoStr := 'MinorVersion'; FAppInfo[cVIRelease].InfoStr := 'Release'; FAppInfo[cVIBuild].InfoStr := 'Build'; ClearAll; end; //-------------------------------------------------------------------------- destructor TVersionInfo.Destroy; begin inherited Destroy; end; //-------------------------------------------------------------------------- function TVersionInfo.GetInfoString(pInfo: Integer): String; begin try Result := FAppInfo[pInfo].InfoStr; except Result := ''; end; end; //-------------------------------------------------------------------------- function TVersionInfo.GetInfoValue(pInfo: Integer): String; begin try Result := FAppInfo[pInfo].Value; except Result := ''; end; end; //-------------------------------------------------------------------------- function TVersionInfo.QueryValue(pInfo: Integer): String; var Value: PChar; SubBlock: String; Len: Cardinal; begin SubBlock := Format('\\StringFileInfo\\%.4x%.4x\\%s',[ FLang^.wLanguage,FLang^.wCodePage, FAppInfo[pInfo].InfoStr ]); VerQueryValue(FBuf,PChar(SubBlock),Pointer(Value),Len); if Len > 0 then Result := Trim(String(Value)) else Result := ''; end; //-------------------------------------------------------------------------- procedure TVersionInfo.ClearAll; var i: Integer; begin for i := 0 to Length(FAppInfo)-1 do FAppInfo[i].Value := FDefaultValue; end; //-------------------------------------------------------------------------- procedure TVersionInfo.GetInfo(FName: String); var pp, i, p: Integer; ZValue, LangLen: Cardinal; sSep, s: String; begin ClearAll; try i := GetFileVersionInfoSize(PChar(FName),ZValue); if i > 0 then begin FBuf := AllocMem(i); try GetFileVersionInfo(PChar(FName),0,i,FBuf); VerQueryValue(FBuf,PChar('\\VarFileInfo\\Translation'),Pointer(FLang),LangLen); for p := 0 to 11 do begin try FAppInfo[p].Value := QueryValue(p); except FAppInfo[p].Value := FDefaultValue; end; end; // Seperate FileVersion values sSep := ''; s := FAppInfo[cVIFileVersion].Value; if s <> '' then begin if Pos('.',s) <> 0 then sSep := '.' // Separator as '.' else if Pos(',',s) <> 0 then sSep := ','; // Separator as ',' end; if sSep <> '' then begin try // Version as major.minor.release.build or major,minor,release,build for p := cVIMajorVersion to cVIRelease do begin pp := Pos(sSep,s); FAppInfo[p].Value := Copy(s,1,pp-1); Delete(s,1,pp); end; FAppInfo[cVIBuild].Value := s; except FAppInfo[cVIMajorVersion].Value := FDefaultValue; FAppInfo[cVIMinorVersion].Value := FDefaultValue; FAppInfo[cVIRelease].Value := FDefaultValue; FAppInfo[cVIBuild].Value := FDefaultValue; end; end; except ClearAll; end; FreeMem(FBuf,i); end; except ClearAll; end; end; end.
unit Converts; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; function CheckHex(const hex:string):boolean; function CheckDec(const dec:string):boolean; function CheckUnsigned(const dec:string):boolean; function CheckBin(const bin:string):boolean; function BinToInt(const bin:string):integer; function IntToBin(Value:LongInt; Digits:cardinal):TCaption; function IntToHex(Value:LongInt; Digits:cardinal):TCaption; function HexToInt(const hex:string):integer; implementation { The following function returns true if the string parameter contains } { a legal representation of a 16-bit hexadecimal value. } { Keep in mind that "Result" is where Delphi functions return their } { function result. } function CheckHex(const hex:string):boolean; const HexVals = ['0'..'9', 'A'..'F', 'a'..'f']; var index:integer; len: integer; begin len := length(hex); Result := (len <> 0) and (len <= 4); for index := 1 to len do begin Result := Result and (hex[index] in HexVals); end; end; { The following function checks its parameter to see if it is a string } { that properly represents a signed decimal value. } function CheckDec(const dec:string):boolean; const DecVals = ['0'..'9']; var index:integer; len: integer; Start:integer; begin len := length(dec); { First, check for total bail-out conditions; this would be any value } { greater than +32767 or less than -32768; a string that is just too } { long, a zero length string, or a string containing only the '-'. } Result := false; Start := 1; if (len = 0) then exit; if (dec[1] = '-') then begin if (len = 1) then exit; if (len > 6) then exit; if (len = 6) and (dec > '-32768') then exit; Start := 2; { Skip over '-' when testing characters } end else begin if (len >= 6) then exit; if (len = 5) and (dec > '32767') then exit; end; { Okay, if the length is five or six, it is not a numeric value that } { is out of range. However, the string could still contain illegal } { characters. We'll check for that down here. } Result := true; for index := Start to len do Result := Result and (dec[index] in DecVals); end; { CheckUnsigned is the same operation as CheckDec except it does not have } { to worry about negative numbers. } function CheckUnsigned(const dec:string):boolean; const DecVals = ['0'..'9']; var index:integer; len: integer; begin len := length(dec); { Check for totally illegal values here } Result := false; if (len = 0) then exit; if (len >= 6) then exit; if (len = 5) and (dec > '65535') then exit; { If the tests above succeeded, check the individual characters here. } Result := true; for index := 1 to len do Result := Result and (dec[index] in DecVals); end; { CheckBin checks the "bin" string to see if it is a valid binary number. } { This particular function allows spaces in binary numbers; this lets the } { use separate nibbles in a long binary string for readability. Note that } { this function allows spaces to occur in arbitrary places in the string, } { it simply ignores the spaces. } function CheckBin(const bin:string):boolean; const BinVals = ['0','1',' ']; var index:integer; len: integer; Bits: integer; begin len := length(bin); { if the string's length is zero or greater than 19 (16 digits plus } { three spaces to separate the nibbles) then immediately return an } { error. } Result := (len <> 0) and (len <= 19); if (not Result) then exit; { If the length of the string is okay, then check each character in } { the string to make sure it is a zero, one, or a space. } Bits := 0; for index := 1 to len do begin Result := Result and (bin[index] in BinVals); Bits := Bits + ord((bin[index] = '0') or (bin[index] = '1')); end; Result := Result and (Bits <=16) and (Bits > 0); end; { IntToBin- } { } { This function converts an integer value to a string of zeros and } { ones -- the binary representation of that integer. The integer } { to convert is the first parameter passed to this function. The } { second parameter specifies the number of digits to place in the } { output string (maximum 16); If the Digits value is less than } { the number of bits actually present in the first parameter, this } { function outputs the L.O. 'Digits' bits. Note that this routine } { inserts space between each group of four digits in order to make } { the output more readable. } function IntToBin( Value:LongInt; Digits:cardinal ):TCaption; var Mask: cardinal; Count:integer; begin { Result will hold the string this function produces } Result := ''; { Create a mask value with a single bit in the H.O. bit position } { so we can use it to see if the current value contains a zero } { or one in its H.O. bit. } Mask := $8000; { Eliminate the bits we're not interested in outputting. This } { adjusts the value so the first bit we want to test is located } { in bit #15 of Value. } Value := Value shl (16-Digits); { For each of the bits we want in the output string, test the } { current value to see if it's H.O. bit is zero or one. Append } { the corresponding character to the end of the result string. } { If the bit position is an even multiple of four, append a } { a space as well, although this code will not append a space to } { the end of the string. } Count := 16-Digits; {# of bits we're going to test. } While (true) do begin {Really a loop..endloop construct. } if ((Value and Mask) <> 0) then AppendStr(Result, '1') else AppendStr(Result,'0'); inc(Count); if (Count > 15) then break; { After bits 3, 7, and 11, append a space to the string. } if (Count mod 4) = 0 then AppendStr(Result,' '); { Adjust the Mask for the next loop iteration. This moves } { the single one bit in Mask one position to the right so it } { tests the next lower bit in Value. } Mask := Mask shr 1; end; end; { IntToHex- } { } { This function converts an integer value to a string of hex } { characters. The integer to convert is the first parameter. } { The second parameter specifies the number of digits to place in } { the output string (maximum 4); If the Digits value is less than } { the number of bits actually present in the first parameter, this } { function outputs the L.O. digits. } function IntToHex(Value:LongInt; Digits:cardinal):TCaption; const HexChars:array [0..$f] of char = ('0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F'); var Count:integer; begin { Result will hold the string this function produces } Result := ''; { For each of the nibbles we want to output, append the corres- } { ponding hex digit. } for Count := Digits-1 downto 0 do begin AppendStr(Result, HexChars[ (Value shr (Count*4)) and $f]); end; end; { HexToInt- } { } { This routine converts a string of characters that represent a hexa- } { decimal value into the corresponding integer value. This routine } { assumes that the string is a valid representation of a hexadecimal } { value. One should call "CheckHex" prior to this routine if not } { absolutely sure that the string is valid. } function HexToInt(const hex:string):integer; var index:integer; begin Result := StrToInt('$'+hex); end; { BinToInt- } { } { The following routine converts a string containing a sequence of } { ones and zeros (i.e., a binary number representation) into an inte- } { ger value. Note that this routine ignores any spaces appearing in } { the binary string; this allows the user to place spaces in the } { binary number to make it more readable. } function BinToInt(const bin:string):integer; var index:integer; begin Result := 0; for index := 1 to length(bin) do if bin[index] <> ' ' then Result := (Result shl 1) + (ord(bin[index]) and $1); end; end.
{$G+} Unit FCache; { Cache work with files. (for better speed on accesing disk) by Maple Leaf, 1996 } Interface Const MaxCache = 4*1024; { 4K } CacheError : byte = 0; CacheEOF : Boolean = False; (* 'CacheError' values: 0 = No error 1 = Write error/Disk full 2 = Is End-Of-File *) Var OutBuffIndex,InBuffIndex : Word; MaxCacheRead : Word; OBuff, IBuff : Array [1..MaxCache] of byte; { Write cache } Procedure FlushBuffer(var f:file); Function WriteByte(var f:file; b:byte):Boolean; { Read cache } Procedure ResetBuffer; Function ReadByte(var f:file) : Byte; Implementation Procedure FlushBuffer(var f:file); var k:word; begin {$i-} CacheError:=0; CacheEOF:=False; if (OutBuffIndex>0) and (OutBuffIndex<=MaxCache) then begin BlockWrite(f,OBuff,OutBuffIndex,k); if k<>OutBuffIndex then CacheError:=1; end; OutBuffIndex:=0; end; Function WriteByte(var f:file; b:byte):Boolean; begin {$i-} CacheError:=0; CacheEOF:=False; Inc(OutBuffIndex); if OutBuffIndex>MaxCache then begin dec(OutBuffIndex); FlushBuffer(f); OutBuffIndex:=1; end; OBuff[OutBuffIndex]:=b; WriteByte:=CacheError=0; end; Procedure ResetBuffer; begin InBuffIndex:=MaxCache+1; MaxCacheRead:=0; end; Function ReadByte(var f:file):Byte; begin {$i-} CacheEOF:=False; CacheError:=0; Inc(InBuffIndex); if InBuffIndex>MaxCacheRead then begin InBuffIndex:=1; BlockRead(f,IBuff,MaxCache,MaxCacheRead); if MaxCacheRead=0 then begin CacheEOF:=True; CacheError:=2; InBuffIndex:=0; end; end; ReadByte:=IBuff [ InBuffIndex ] ; end; begin end.
{ "Windows Console Station (VCL)" - Copyright 2004-2017 (c) RealThinClient.com (http://www.realthinclient.com) @exclude } unit rtcVWinStationCLI; interface {$INCLUDE rtcDefs.inc} USES Windows, SysUtils, rtcLog; TYPE { winsta.dll } TWinStationConnect = FUNCTION(hServer: THANDLE; SessionID: ULONG; TargetSessionID: ULONG; pPassword: PWideChar; bWait: Boolean) : Boolean; stdcall; { kernel32.dll } TWTSGetActiveConsoleSessionId = FUNCTION: DWORD; stdcall; TProcessIdToSessionId = FUNCTION(dwProcessID: DWORD; VAR pSessionId: DWORD) : BOOL; stdcall; { user32.dll } TLockWorkStation = FUNCTION: BOOL; stdcall; VAR WinStationConnect: TWinStationConnect = NIL; WTSGetActiveConsoleSessionId: TWTSGetActiveConsoleSessionId = NIL; ProcessIdToSessionId: TProcessIdToSessionId = NIL; LockWorkStation: TLockWorkStation = NIL; LibsLoaded: Integer = 0; gWinSta: HMODULE; gKernel32: HMODULE; gUser32: HMODULE; FUNCTION inConsoleSession: Boolean; PROCEDURE SetConsoleSession(pSessionId: DWORD = $FFFFFFFF); IMPLEMENTATION FUNCTION GetProcedureAddress(VAR P: Pointer; CONST ModuleName, ProcName: String; VAR pModule: HMODULE): Boolean; VAR ModuleHandle: HMODULE; BEGIN IF NOT Assigned(P) THEN BEGIN ModuleHandle := GetModuleHandle(PChar(ModuleName)); IF ModuleHandle = 0 THEN ModuleHandle := LoadLibrary(PChar(ModuleName)); IF ModuleHandle <> 0 THEN P := Pointer(GetProcAddress(ModuleHandle, PChar(ProcName))); Result := Assigned(P); END ELSE Result := True; END; FUNCTION InitProcLibs: Boolean; BEGIN IF LibsLoaded > 0 THEN Result := True ELSE IF LibsLoaded < 0 THEN Result := False ELSE BEGIN LibsLoaded := -1; IF GetProcedureAddress(@WinStationConnect, 'winsta.dll', 'WinStationConnectW', gWinSta) AND GetProcedureAddress(@WTSGetActiveConsoleSessionId, 'kernel32.dll', 'WTSGetActiveConsoleSessionId', gKernel32) AND GetProcedureAddress(@ProcessIdToSessionId, 'kernel32.dll', 'ProcessIdToSessionId', gKernel32) AND GetProcedureAddress(@LockWorkStation, 'user32.dll', 'LockWorkStation', gUser32) THEN LibsLoaded := 1; Result := LibsLoaded = 1; END; // {$IFDEF ExtendLog}XLog(Format('rtcTSCli.InitProclibs = %s', [BoolToStr(Result, True)]), LogAddon); {$ENDIF} END; PROCEDURE DeInitProcLibs; BEGIN IF LibsLoaded = 1 THEN BEGIN FreeLibrary(gWinSta); FreeLibrary(gKernel32); FreeLibrary(gUser32); END; END; FUNCTION ProcessSessionId: DWORD; BEGIN Result := 0; IF (LibsLoaded = 1) THEN BEGIN IF NOT ProcessIdToSessionId(GetCurrentProcessId(), Result) THEN Result := $FFFFFFFF END; // {$ifdef ExtendLog}XLog(Format('ProcessSessionId = %d', [result]), LogAddon);{$endif} END; FUNCTION ConsoleSessionId: DWORD; BEGIN IF (LibsLoaded = 1) THEN Result := WTSGetActiveConsoleSessionId ELSE Result := 0; // {$ifdef ExtendLog}XLog(Format('ConsoleSessionId = %d', [result]), LogAddon);{$endif} END; FUNCTION inConsoleSession: Boolean; BEGIN Result := ConsoleSessionId = ProcessSessionId; // {$ifdef ExtendLog}XLog(Format('inConsoleSession = %s', [booltostr(result, true)]), LogAddon);{$endif} END; PROCEDURE SetConsoleSession(pSessionId: DWORD = $FFFFFFFF); BEGIN // {$IFDEF ExtendLog}XLog(Format('SetConsoleSession(%d)', [pSessionId]), LogAddon); {$ENDIF} IF (LibsLoaded = 1) THEN BEGIN IF (pSessionId = $FFFFFFFF) THEN pSessionId := ProcessSessionId; // {$IFDEF ExtendLog}XLog(Format('WinStationConnect(%d, %d)', [pSessionId, ConsoleSessionId]), LogAddon); {$ENDIF} IF WinStationConnect(0, pSessionId, ConsoleSessionId, '', False) THEN {$IFDEF FORCELOGOUT} LockWorkStation; {$ELSE FORCELOGOUT} ; {$ENDIF FORCELOGOUT} END; END; INITIALIZATION InitProcLibs; FINALIZATION DeInitProcLibs; END.
unit Localizer; interface uses Forms, Classes; type TLocalizer = class private fLanguage: String; procedure SetLanguage(const Value: String); public procedure Localize(pForm: TForm; pList: TStrings); procedure LoadStrings(pList: TStrings); property language: String read fLanguage write SetLanguage; end; implementation uses Inifiles, SysUtils, Controls, StdCtrls, ActnList, ComCtrls, ExtCtrls, cUnicodeCodecs, Dialogs; { TLocalizer } procedure TLocalizer.LoadStrings(pList: TStrings); var I: Integer; lFn, lCaption: String; lLF: TiniFile; lComp: TComponent; begin lFn := ExtractFilePath(Application.ExeName)+'\lang\'+fLanguage+'.lng'; if (not FileExists(lFn)) then Exit; lLF := TIniFile.Create(lFn); try for I := 0 to pList.Count - 1 do begin pList.Values[pList.Names[i]] := UTF8StringToWideString(lLF.ReadString('HidMacros', pList.Names[i], pList.Values[pList.Names[i]])); end; finally lLF.Free; end; end; procedure TLocalizer.Localize(pForm: TForm; pList: TStrings); var I: Integer; lFn: String; lRawCaption: String; lCaption: TCaption; lLF: TiniFile; lComp: TObject; begin lFn := ExtractFilePath(Application.ExeName)+'\lang\'+fLanguage+'.lng'; if (not FileExists(lFn)) then Exit; lLF := TIniFile.Create(lFn); try for I := 0 to pList.Count - 1 do begin lComp := pForm.FindComponent(pList.Names[i]); if lComp <> nil then begin lRawCaption := lLF.ReadString('HidMacros', pList.Values[pList.Names[i]], ''); if lRawCaption <> '' then begin lCaption := UTF8StringToWideString(lRawCaption); if lComp is TLabel then (lComp as TLabel).Caption:= lCaption else if lComp is TGroupBox then (lComp as TGroupBox).Caption:= lCaption else if lComp is TButton then (lComp as TButton).Caption:= lCaption else if lComp is TCheckBox then (lComp as TCheckBox).Caption:= lCaption else if lComp is TCustomAction then (lComp as TCustomAction).Caption:= lCaption else if lComp is TRadioButton then (lComp as TRadioButton).Caption:= lCaption else if lComp is TTabSheet then (lComp as TTabSheet).Caption:= lCaption else if lComp is TListColumn then (lComp as TListColumn).Caption:= lCaption else if lComp is TPanel then (lComp as TPanel).Caption:= lCaption; end; end else if pForm.Name = pList.Names[i] then begin lRawCaption := lLF.ReadString('HidMacros', pList.Values[pList.Names[i]], ''); if lRawCaption <> '' then begin lCaption := UTF8StringToWideString(lRawCaption); pForm.Caption := lCaption; end; end; end; finally lLF.Free; end; end; procedure TLocalizer.SetLanguage(const Value: String); begin fLanguage := Value; end; end.
//Настройки unit fOptions; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, Mask, DBCtrlsEh, ToolEdit, FileCtrl, LMDCustomFileEdit, LMDFileOpenEdit, LMDColorEdit, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDBaseEdit, LMDCustomEdit, LMDCustomBrowseEdit, LMDBrowseEdit, LMDEdit, LMDCustomButton, LMDButton, LMDCustomListBox, LMDExtListBox, LMDCustomComponent, LMDBrowseDlg, LMDCustomScrollBox, LMDScrollBox, LMDCustomImageListBox, LMDCustomCheckListBox, LMDCheckListBox, LMDListBox, Placemnt, PropFilerEh, PropStorageEh, ActnList, Menus, ImgList; type TfrmOptions = class(TForm) PageControl: TPageControl; btnOK: TButton; btnCancel: TButton; TabSheet1: TTabSheet; TabSheet2: TTabSheet; lblName: TLabel; lblPath: TLabel; edZipPath: TLMDBrowseEdit; edName: TLMDEdit; btnAddFile1: TButton; OpenDialog: TOpenDialog; BrowseDlg: TLMDBrowseDlg; btnAddDirectory: TButton; btnDeleteFile1: TButton; FilesList: TLMDExtListBox; lblFilePath1: TLabel; Storage: TFormStorage; lblFilesList1: TLabel; ExcludeList: TLMDExtListBox; lblExcludeList: TLabel; btnDeleteFile2: TButton; btnAddFile2: TButton; lblFilePath2: TLabel; ActionList: TActionList; AcAddFile1: TAction; AcAddFile2: TAction; AcAddDirectory: TAction; AcDeleteFile1: TAction; AcDeleteFile2: TAction; PopupMenu1: TPopupMenu; PopupMenu2: TPopupMenu; pmAddFile1: TMenuItem; pmAddDir1: TMenuItem; pmDeleteFile1: TMenuItem; pmAddFile2: TMenuItem; pmDeleteFile2: TMenuItem; ImageList: TImageList; edUnZipPath: TLMDFileOpenEdit; lblPath2: TLabel; edUnZipDestDir: TLMDBrowseEdit; lblUnZipDestDir: TLabel; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FilesListSelect(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure ExcludeListSelect(Sender: TObject); procedure AcAddFile1Execute(Sender: TObject); procedure AcAddFile2Execute(Sender: TObject); procedure AcAddDirectoryExecute(Sender: TObject); procedure AcDeleteFile1Execute(Sender: TObject); procedure AcDeleteFile2Execute(Sender: TObject); procedure edUnZipPathClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmOptions: TfrmOptions; implementation {$R *.dfm} procedure TfrmOptions.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TfrmOptions.FilesListSelect(Sender: TObject); const max_length = 77; var i: integer; path, format_path: string; begin if (FilesList.ItemIndex = -1) then exit; btnDeleteFile1.Enabled := true; pmDeleteFile1.Enabled := true; lblFilePath1.Visible := true; path := FilesList.Items.Strings[FilesList.ItemIndex]; for i:=0 to trunc(length(path)/max_length) do begin format_path := format_path + copy(path, 1, max_length)+ #10#13; delete(path, 1, max_length); end; lblFilePath1.Caption := format_path; end; procedure TfrmOptions.FormCreate(Sender: TObject); var i: integer; files, format_files: string; begin Storage.StoredValues.RestoreValues; edName.Text := 'BackUp - ' + DateToStr(now); edZipPath.Text := Storage.StoredValues.Values['ZipPath'].Value; //TODO: При использовании FilesList.Items.Text //отображается только первая запись в списке FilesList.Clear; files := Storage.StoredValues.Values['FilesList'].Value; format_files := ''; for i := 1 to length(files) do begin if (files[i] <> '|') then format_files := format_files + files[i] else begin FilesList.Items.Add(format_files); format_files := ''; end; end; ExcludeList.Clear; files := Storage.StoredValues.Values['ExcludeList'].Value; format_files := ''; for i := 1 to length(files) do begin if (files[i] <> '|') then format_files := format_files + files[i] else begin ExcludeList.Items.Add(format_files); format_files := ''; end; end; edUnZipPath.Text := Storage.StoredValues.Values['UnZipPath'].Value; edUnZipDestDir.Text := Storage.StoredValues.Values['UnZipDestDir'].Value; lblFilePath1.Caption := ''; lblFilePath2.Caption := ''; lblFilePath1.Visible := false; lblFilePath2.Visible := false; btnDeleteFile1.Enabled := false; btnDeleteFile2.Enabled := false; pmDeleteFile1.Enabled := false; pmDeleteFile2.Enabled := false; PageControl.ActivePage := TabSheet1; end; procedure TfrmOptions.btnCancelClick(Sender: TObject); begin Close; end; procedure TfrmOptions.btnOKClick(Sender: TObject); var i: integer; files: string; begin Storage.StoredValues.Values['Name'].Value := edName.Text; Storage.StoredValues.Values['ZipPath'].Value := edZipPath.Text; files := ''; for i := 0 to FilesList.Items.Count-1 do files := files + FilesList.Items.Strings[i] + '|'; Storage.StoredValues.Values['FilesList'].Value := files; files := ''; for i := 0 to ExcludeList.Items.Count-1 do files := files + ExcludeList.Items.Strings[i] + '|'; Storage.StoredValues.Values['ExcludeList'].Value := files; Storage.StoredValues.Values['UnZipPath'].Value:=edUnZipPath.Text; Storage.StoredValues.Values['UnZipDestDir'].Value:=edUnZipDestDir.Text; Storage.StoredValues.SaveValues; Close; end; procedure TfrmOptions.ExcludeListSelect(Sender: TObject); const max_length = 77; var i: integer; path, format_path: string; begin if (ExcludeList.ItemIndex = -1) then exit; btnDeleteFile2.Enabled := true; pmDeleteFile2.Enabled := true; lblFilePath2.Visible := true; path := ExcludeList.Items.Strings[ExcludeList.ItemIndex]; for i:=0 to trunc(length(path)/max_length) do begin format_path := format_path + copy(path, 1, max_length)+ #10#13; delete(path, 1, max_length); end; lblFilePath2.Caption := format_path; end; procedure TfrmOptions.AcAddFile1Execute(Sender: TObject); begin OpenDialog.Execute; if (OpenDialog.FileName <> '') then begin FilesList.Items.Add(OpenDialog.FileName); btnDeleteFile1.Enabled := true; pmDeleteFile1.Enabled := true; lblFilePath1.Visible := true; end; end; procedure TfrmOptions.AcAddFile2Execute(Sender: TObject); begin OpenDialog.Execute; if (OpenDialog.FileName <> '') then begin ExcludeList.Items.Add(OpenDialog.FileName); btnDeleteFile2.Enabled := true; pmDeleteFile2.Enabled := false; lblFilePath2.Visible := true; end; end; procedure TfrmOptions.AcAddDirectoryExecute(Sender: TObject); begin BrowseDlg.Execute; if (BrowseDlg.SelectedFolder <> '') then begin FilesList.Items.Add(BrowseDlg.SelectedFolder + '\*.*'); btnDeleteFile1.Enabled := true; pmDeleteFile1.Enabled := true; lblFilePath1.Visible := true; end; end; procedure TfrmOptions.AcDeleteFile1Execute(Sender: TObject); begin FilesList.DeleteSelected; if (FilesList.Items.Count = 0) then begin btnDeleteFile1.Enabled := false; pmDeleteFile1.Enabled := false; lblFilePath1.Visible := false; end; end; procedure TfrmOptions.AcDeleteFile2Execute(Sender: TObject); begin ExcludeList.DeleteSelected; if (ExcludeList.Items.Count = 0) then begin btnDeleteFile2.Enabled := false; pmDeleteFile2.Enabled := false; lblFilePath2.Visible := false; end; end; procedure TfrmOptions.edUnZipPathClick(Sender: TObject); begin edUnZipPath.Show; end; end.
unit Getter.TrimBasics.NTFS; interface uses Windows, OSFile.IoControl, Getter.TrimBasics; type TNTFSTrimBasicsGetter = class(TTrimBasicsGetter) public function IsPartitionMyResponsibility: Boolean; override; function GetTrimBasicsToInitialize: TTrimBasicsToInitialize; override; private type TNTFSVolumeDataBuffer = record VolumeSerialNumber: _LARGE_INTEGER; NumberSectors: _LARGE_INTEGER; TotalClusters: _LARGE_INTEGER; FreeClusters: _LARGE_INTEGER; TotalReserved: _LARGE_INTEGER; BytesPerSector: DWORD; BytesPerCluster: DWORD; BytesPerFileRecordSegment: DWORD; ClustersPerFileRecordSegment: DWORD; MftValidDataLength: _LARGE_INTEGER; MftStartLcn: _LARGE_INTEGER; Mft2StartLcn: _LARGE_INTEGER; MftZoneStart: _LARGE_INTEGER; MftZoneEnd: _LARGE_INTEGER; end; private InnerBuffer: TNTFSVolumeDataBuffer; function GetLBAPerCluster: Cardinal; function GetIOBuffer: TIoControlIOBuffer; end; implementation { TNTFSTrimBasicsGetter } function TNTFSTrimBasicsGetter.IsPartitionMyResponsibility: Boolean; begin result := GetFileSystemName = 'NTFS'; end; function TNTFSTrimBasicsGetter.GetTrimBasicsToInitialize: TTrimBasicsToInitialize; begin result := inherited; result.PaddingLBA := 0; result.LBAPerCluster := GetLBAPerCluster; end; function TNTFSTrimBasicsGetter.GetIOBuffer: TIoControlIOBuffer; begin result.InputBuffer.Buffer := nil; result.InputBuffer.Size := 0; result.OutputBuffer.Buffer := @InnerBuffer; result.OutputBuffer.Size := SizeOf(InnerBuffer); end; function TNTFSTrimBasicsGetter.GetLBAPerCluster: Cardinal; begin IoControl(TIoControlCode.GetNTFSVolumeData, GetIOBuffer); result := InnerBuffer.BytesPerCluster div InnerBuffer.BytesPerSector; end; end.
unit Codes; interface uses Values, Variables, Strings; const TYPE_CONTINUE = -3; TYPE_BREAK = -2; TYPE_EXIT = -1; OW_VALUE = 1; OW_ID = 2; OW_DEFINE = 3; LW_NONE = 0; LW_OPERAND = 1; LW_OPERATOR = 2; LW_FUNCTION = 3; LW_FUNCTIONEND = 4; LW_INSTRUCTION = 5; LW_FLOWCONTROL = 6; type TOperator = (opNone, opOpenBrack, opCloseBrack, opComma, opEqual, opAddEqual, opAdd, opPreInc, opPostInc, opSubtractEqual, opSubtract, opUnarSubtract, opPreDec, opPostDec, opIOrEqual, opIOr, opOr, opIXorEqual, opIXor, opXor, opMultiplyEqual, opMultiply, opDivideEqual, opDivide, opModEqual, opMod, opIAndEqual, opIAnd, opAnd, opINot, opNot, opRound, opRandom, opEqualEqual, opNotEqual, opMore, opMoreOrEqual, opLess, opLessOrEqual, opOffset, opID, opClassItem); TCommand = (cmdNone, cmdIf, cmdFor, cmdDo); TFlowControl = (fcNone, fcContinue, fcBreak, fcExit); const opPostfix = [opCloseBrack, opPostInc, opPostDec]; OP_COUNT = 41; STR_OPERATOR: array [1..OP_COUNT] of String = ( '(', // (x) ')', // (x) ',', // x, y '=', // @x = y '+=', // @x += y '+', // x + y '++', // ++ @x '++', // @x ++ '-=', // @x -= y '-', // x - y '-', // - x '--', // -- @x '--', // @x -- '|=', // @(int)x |= (int)y '|', // (int)x | (int)y '||', // (int)x || (int)y '^=', // @(int)x ^= (int)y '^', // (int)x ^ (int)y '!!', // (int)x !! (int)y '*=', // @x *= y '*', // x * y '/=', // @x /= y '/', // x / y '%=', // @(int)x %= (int)y '%', // (int)x % (int)y '&=', // @(int)x &= (int)y '&', // (int)x & (int)y '&&', // (int)x && (int)y '~', // ~ (int)x '!', // !! (int)x '%', // % (float)x '?', // ? (float/int)x '==', // x == y '!=', // x != y '>', // x > y '>=', // x >= y '<', // x < y '<=', // x <= y '[', // (str/array)x[(int/str)y] '=>', // (str)id => x '->' // (class)x->y ); ARN: array [1..OP_COUNT] of Byte = ( 0, // ( 0, // ) 0, // , 2, // = 2, // += 2, // + 1, // ++ 1, // ++ 2, // -= 2, // - 1, // - 1, // -- 1, // -- 2, // |= 2, // | 2, // || 2, // ^= 2, // ^ 2, // !! 2, // *= 2, // * 2, // /= 2, // / 2, // %= 2, // % 2, // &= 2, // & 2, // && 1, // ~ 1, // ! 1, // % 1, // ? 2, // == 2, // != 2, // > 2, // >= 2, // < 2, // <= 2, // [ 2, // => 2 // -> ); PR_NUL = 0; PR_EQL = 1; PR_REL = 2; PR_ADD = 3; PR_MUL = 4; PR_UNO = 5; PR_FUN = 6; PR_INS = 7; PRIORITY: array [1..OP_COUNT] of Byte = ( PR_NUL, // ( PR_NUL, // ) PR_NUL, // , PR_EQL, // = PR_EQL, // += PR_ADD, // + PR_UNO, // ++ PR_UNO, // ++ PR_EQL, // -= PR_ADD, // - PR_UNO, // - PR_UNO, // -- PR_UNO, // -- PR_EQL, // |= PR_ADD, // | PR_ADD, // || PR_EQL, // ^= PR_ADD, // ^ PR_ADD, // !! PR_EQL, // *= PR_MUL, // * PR_EQL, // /= PR_MUL, // / PR_EQL, // %= PR_MUL, // % PR_EQL, // &= PR_MUL, // & PR_MUL, // && PR_UNO, // ~ PR_UNO, // ! PR_UNO, // % PR_UNO, // ? PR_REL, // == PR_REL, // != PR_REL, // > PR_REL, // >= PR_REL, // < PR_REL, // <= PR_UNO, // [ PR_EQL, // => PR_EQL // -> ); STR_COMMAND: array [1..3] of String = ( 'if', 'for', 'do' ); STR_FLOWCONTROL: array [1..3] of String = ( 'continue', 'break', 'exit' ); type TIPR = class; TIPRArray = array of TIPR; TInstruction = class private FCommand: TCommand; FItems: TIPRArray; function GetItem(Index: Integer): TIPR; function GetCount(): Integer; public constructor Create(ACommand: TCommand); destructor Destroy; override; procedure AddItem(); property Command: TCommand read FCommand; property Items[Index: Integer]: TIPR read GetItem; default; property Count: Integer read GetCount; end; TOperand = record What: Byte; case Byte of 0: (Value: TValue); 1: (ID: TID; Type_: TType_; Exts: TType_Exts); end; TLexem = record What: Byte; case Byte of LW_OPERAND: (Operand: TOperand); LW_OPERATOR: (Operator: TOperator); LW_FUNCTION: (ID: TID); LW_INSTRUCTION: (Instruction: TInstruction); LW_FLOWCONTROL: (FlowControl: TFlowControl); end; PPIPRItem = ^PIPRItem; PIPRItem = ^TIPRItem; TIPRItem = record Lexem: TLexem; Next: PIPRItem; end; TIPR = class private FHead: PIPRItem; FCurrent: PPIPRItem; function GetCurrent(): PIPRItem; function GetLexem(): TLexem; function GetText(): String; public constructor Create(); destructor Destroy(); override; function Copy(): TIPR; procedure Reset(); procedure Scroll(); procedure Tail(); procedure EndOf(); procedure Add(ALexem: TLexem); procedure Delete(); procedure Clear(AFree: Boolean); function CurrentIsFunction(): Boolean; function CurrentIsVariable(): Boolean; property Head: PIPRItem read FHead; property Current: PIPRItem read GetCurrent; property Lexem: TLexem read GetLexem; property Text: String read GetText; end; TDefineProc = procedure(const AID: TID; AType_: TType_; AExts: TType_Exts = []) of object; TVariableFunc = function(const AID: TID): TValue of object; TFunctionFunc = function(const AID: TID; const AArguments: TValues; AClass: TValue = nil): TValue of object; TCode = class private FVariables: TVariables; FIPR: TIPR; FOnDefine: TDefineProc; FOnVariable: TVariableFunc; FOnFunction: TFunctionFunc; FOnMethod: TFunctionFunc; procedure DoDefine(const AID: TID; AType_: TType_; AExts: TType_Exts = []); function DoVariable(const AID: TID): TValue; function DoFunction(const AID: TID; const AArguments: TValues; AClass: TValue = nil): TValue; function DoMethod(const AID: TID; const AArguments: TValues; AClass: TValue = nil): TValue; function DoRun(AClass: TValue = nil): TValue; public constructor Create(); destructor Destroy(); override; function Compile(const AText: String): Boolean; function Run(AClass: TValue = nil): TValue; function RunAsBlock(AClass: TValue = nil): TValue; procedure Clear(); property Variables: TVariables read FVariables; property IPR: TIPR read FIPR; property OnDefine: TDefineProc read FOnDefine write FOnDefine; property OnVariable: TVariableFunc read FOnVariable write FOnVariable; property OnFunction: TFunctionFunc read FOnFunction write FOnFunction; property OnMethod: TFunctionFunc read FOnMethod write FOnMethod; end; procedure ClearDir(const APath: String); procedure EraseDir(const APath: String); function Operator(const S: String): TOperator; function Command(const S: String): TCommand; function FlowControl(const S: String): TFlowControl; function nonLexem: TLexem; function valLexem(AValue: TValue): TLexem; function idLexem(const AID: TID): TLexem; function defLexem(const AID: TID; AType_: TType_; AExts: TType_Exts): TLexem; function opLexem(AOperator: TOperator): TLexem; function funLexem(const AID: TID): TLexem; function endLexem: TLexem; function insLexem(AInstruction: TInstruction): TLexem; function fcLexem(AFlowControl: TFlowControl): TLexem; function IPRItem(ALexem: TLexem; ANext: PIPRItem): PIPRItem; function funEqual(AValue1, AValue2: TValue): TValue; function funAddEqual(AValue1, AValue2: TValue): TValue; function funAdd(AValue1, AValue2: TValue): TValue; function funPreInc(AValue1: TValue): TValue; function funPostInc(AValue1: TValue): TValue; function funSubtractEqual(AValue1, AValue2: TValue): TValue; function funSubtract(AValue1, AValue2: TValue): TValue; function funUnarSubtract(AValue1: TValue): TValue; function funPreDec(AValue1: TValue): TValue; function funPostDec(AValue1: TValue): TValue; function funIOrEqual(AValue1, AValue2: TValue): TValue; function funIOr(AValue1, AValue2: TValue): TValue; function funOr(AValue1, AValue2: TValue): TValue; function funIXorEqual(AValue1, AValue2: TValue): TValue; function funIXor(AValue1, AValue2: TValue): TValue; function funXor(AValue1, AValue2: TValue): TValue; function funMultiplyEqual(AValue1, AValue2: TValue): TValue; function funMultiply(AValue1, AValue2: TValue): TValue; function funDivideEqual(AValue1, AValue2: TValue): TValue; function funDivide(AValue1, AValue2: TValue): TValue; function funModEqual(AValue1, AValue2: TValue): TValue; function funMod(AValue1, AValue2: TValue): TValue; function funIAndEqual(AValue1, AValue2: TValue): TValue; function funIAnd(AValue1, AValue2: TValue): TValue; function funAnd(AValue1, AValue2: TValue): TValue; function funINot(AValue1: TValue): TValue; function funNot(AValue1: TValue): TValue; function funRound(AValue1: TValue): TValue; function funRandom(AValue1: TValue): TValue; function funEqualEqual(AValue1, AValue2: TValue): TValue; function funNotEqual(AValue1, AValue2: TValue): TValue; function funMore(AValue1, AValue2: TValue): TValue; function funMoreOrEqual(AValue1, AValue2: TValue): TValue; function funLess(AValue1, AValue2: TValue): TValue; function funLessOrEqual(AValue1, AValue2: TValue): TValue; function funOffset(AValue1, AValue2: TValue): TValue; function funID(AValue1, AValue2: TValue): TValue; implementation uses Windows, Dialogs, Classes, SysUtils, StrUtils; { Routines } procedure ClearDir(const APath: String); var lFindData: TSearchRec; lFindResult: Integer; lName: String; lFile: File; begin lFindResult := FindFirst(IncludeTrailingBackslash(APath) + '*', faAnyFile, lFindData); while lFindResult = 0 do begin if not ThisStr(lFindData.Name, ['.', '..']) then begin lName := IncludeTrailingBackslash(APath) + lFindData.Name; if DirectoryExists(lName) then EraseDir(lName) else begin FileSetAttr(lName, 0); AssignFile(lFile, lName); {$I-} Erase(lFile); {$I+} end; end; lFindResult := FindNext(lFindData); end; FindClose(lFindData); end; procedure EraseDir(const APath: String); begin ClearDir(APath); {$I-}RmDir(APath);{$I+} end; function WinExecAndWait(lpCmdLine: PChar; uCmdShow: DWORD): DWORD; var szAppName: array [0..512] of Char; szCurDir: array [0..255] of Char; WorkDir: String; StartupInfo: TStartupInfo; ProcessInfo: TProcessInformation; begin StrPCopy(szAppName, lpCmdLine); GetDir(0, WorkDir); StrPCopy(szCurDir, WorkDir); FillChar(StartupInfo, SizeOf(StartupInfo), #0); StartupInfo.cb := SizeOf(StartupInfo); StartupInfo.dwFlags := STARTF_USESHOWWINDOW; StartupInfo.wShowWindow := uCmdShow; if not CreateProcess(nil, szAppName, nil, nil, False, CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInfo) then Result := 0 else begin while WaitForSingleObject(ProcessInfo.hProcess, INFINITE) = WAIT_TIMEOUT do ; GetExitCodeProcess(ProcessInfo.hProcess, Result); end; end; function Operator(const S: String): TOperator; var I: Integer; begin Result := opNone; for I := Low(STR_OPERATOR) to High(STR_OPERATOR) do if S = STR_OPERATOR[I] then begin Result := TOperator(I); Break; end; end; function Command(const S: String): TCommand; var I: Integer; begin Result := cmdNone; for I := Low(STR_COMMAND) to High(STR_COMMAND) do if S = STR_COMMAND[I] then begin Result := TCommand(I); Break; end; end; function FlowControl(const S: String): TFlowControl; var I: Integer; begin Result := fcNone; for I := Low(STR_FLOWCONTROL) to High(STR_FLOWCONTROL) do if S = STR_FLOWCONTROL[I] then begin Result := TFlowControl(I); Break; end; end; function nonLexem: TLexem; begin ZeroMemory(@Result, SizeOf(TLexem)); end; function valLexem(AValue: TValue): TLexem; begin Result.What := LW_OPERAND; Result.Operand.What := OW_VALUE; Result.Operand.Value := AValue; end; function idLexem(const AID: TID): TLexem; begin Result.What := LW_OPERAND; Result.Operand.What := OW_ID; Result.Operand.ID := AID; end; function defLexem(const AID: TID; AType_: TType_; AExts: TType_Exts): TLexem; begin Result.What := LW_OPERAND; Result.Operand.What := OW_DEFINE; Result.Operand.ID := AID; Result.Operand.Type_ := AType_; Result.Operand.Exts := AExts; end; function opLexem(AOperator: TOperator): TLexem; begin Result.What := LW_OPERATOR; Result.Operator := AOperator; end; function funLexem(const AID: TID): TLexem; begin Result.What := LW_FUNCTION; Result.ID := AID; end; function endLexem: TLexem; begin Result.What := LW_FUNCTIONEND; end; function insLexem(AInstruction: TInstruction): TLexem; begin Result.What := LW_INSTRUCTION; Result.Instruction := AInstruction; end; function fcLexem(AFlowControl: TFlowControl): TLexem; begin Result.What := LW_FLOWCONTROL; Result.FlowControl := AFlowControl; end; function IPRItem(ALexem: TLexem; ANext: PIPRItem): PIPRItem; begin GetMem(Result, SizeOf(TIPRItem)); Result^.Lexem := ALexem; Result^.Next := ANext; end; function funEqual(AValue1, AValue2: TValue): TValue; begin AValue1.Equal(AValue2); Result := ValueAssign(AValue1); end; function funAddEqual(AValue1, AValue2: TValue): TValue; begin case AValue1.Type_ of TYPE_FLOAT: AValue1.F := AValue1.F + AValue2.F; TYPE_INT: AValue1.I := AValue1.I + AValue2.I; TYPE_BYTE: AValue1.B := AValue1.B + AValue2.B; TYPE_STR: AValue1.S := AValue1.S + AValue2.S; end; Result := ValueAssign(AValue1); end; function funAdd(AValue1, AValue2: TValue): TValue; begin Result := nil; case AValue1.Type_ of TYPE_FLOAT: case AValue2.Type_ of TYPE_FLOAT, TYPE_INT, TYPE_BYTE: Result := Value(AValue1.F + AValue2.F); TYPE_STR: Result := Value(AValue1.S + AValue2.S); end; TYPE_INT, TYPE_BYTE: case AValue2.Type_ of TYPE_FLOAT: Result := Value(AValue1.I + AValue2.F); TYPE_INT, TYPE_BYTE: Result := Value(AValue1.I + AValue2.I); TYPE_STR: Result := Value(AValue1.S + AValue2.S); end; TYPE_STR: Result := Value(AValue1.S + AValue2.S); end; if not Assigned(Result) then Result := TValue.Create; end; function funPreInc(AValue1: TValue): TValue; begin case AValue1.Type_ of TYPE_FLOAT: AValue1.F := AValue1.F + 1; TYPE_INT: AValue1.I := AValue1.I + 1; TYPE_BYTE: AValue1.B := AValue1.B + 1; end; Result := ValueCopy(AValue1); end; function funPostInc(AValue1: TValue): TValue; begin Result := ValueCopy(AValue1); case AValue1.Type_ of TYPE_FLOAT: AValue1.F := AValue1.F + 1; TYPE_INT: AValue1.I := AValue1.I + 1; TYPE_BYTE: AValue1.B := AValue1.B + 1; end; end; function funSubtractEqual(AValue1, AValue2: TValue): TValue; var S: String; begin case AValue1.Type_ of TYPE_FLOAT: AValue1.F := AValue1.F - AValue2.F; TYPE_INT: AValue1.I := AValue1.I - AValue2.I; TYPE_BYTE: AValue1.B := AValue1.B - AValue2.B; TYPE_STR: begin S := AValue1.S; Subtract(S, AValue2.S); AValue1.S := S; end; end; Result := ValueAssign(AValue1); end; function funSubtract(AValue1, AValue2: TValue): TValue; begin Result := nil; case AValue1.Type_ of TYPE_FLOAT: if AValue2.Type_ in [TYPE_FLOAT, TYPE_INT, TYPE_BYTE] then Result := Value(AValue1.F - AValue2.F); TYPE_INT, TYPE_BYTE: case AValue2.Type_ of TYPE_FLOAT: Result := Value(AValue1.I - AValue2.F); TYPE_INT, TYPE_BYTE: Result := Value(AValue1.I - AValue2.I); end; TYPE_STR: Result := Value(GetSubtract(AValue1.S, AValue2.S)); end; if not Assigned(Result) then Result := TValue.Create; end; function funUnarSubtract(AValue1: TValue): TValue; begin Result := nil; case AValue1.Type_ of TYPE_FLOAT: Result := Value(- AValue1.F); TYPE_INT, TYPE_BYTE: Result := Value(- AValue1.I); end; if not Assigned(Result) then Result := TValue.Create; end; function funPreDec(AValue1: TValue): TValue; var S: String; begin case AValue1.Type_ of TYPE_FLOAT: AValue1.F := AValue1.F - 1; TYPE_INT: AValue1.I := AValue1.I - 1; TYPE_BYTE: AValue1.B := AValue1.B - 1; TYPE_STR: begin S := AValue1.S; Delete(S, Length(S), 1); AValue1.S := S; end; end; Result := ValueCopy(AValue1); end; function funPostDec(AValue1: TValue): TValue; var S: String; begin Result := ValueCopy(AValue1); case AValue1.Type_ of TYPE_FLOAT: AValue1.F := AValue1.F - 1; TYPE_INT: AValue1.I := AValue1.I - 1; TYPE_BYTE: AValue1.B := AValue1.B - 1; TYPE_STR: begin S := AValue1.S; Delete(S, Length(S), 1); AValue1.S := S; end; end; end; function funIOrEqual(AValue1, AValue2: TValue): TValue; begin AValue1.I := AValue1.I or AValue2.I; Result := ValueAssign(AValue1); end; function funIOr(AValue1, AValue2: TValue): TValue; begin Result := Value(AValue1.I or AValue2.I); end; function funOr(AValue1, AValue2: TValue): TValue; begin Result := Value(AValue1.L or AValue2.L); end; function funIXorEqual(AValue1, AValue2: TValue): TValue; begin AValue1.I := AValue1.I xor AValue2.I; Result := ValueAssign(AValue1); end; function funIXor(AValue1, AValue2: TValue): TValue; begin Result := Value(AValue1.I xor AValue2.I); end; function funXor(AValue1, AValue2: TValue): TValue; begin Result := Value(AValue1.L xor AValue2.L); end; function funMultiplyEqual(AValue1, AValue2: TValue): TValue; begin case AValue1.Type_ of TYPE_FLOAT: AValue1.F := AValue1.F * AValue2.F; TYPE_INT: case AValue2.Type_ of TYPE_FLOAT: AValue1.I := Round(AValue1.I * AValue2.F); TYPE_INT, TYPE_BYTE: AValue1.I := AValue1.I * AValue2.I; end; TYPE_BYTE: case AValue2.Type_ of TYPE_FLOAT: AValue1.B := Round(AValue1.B * AValue2.F); TYPE_INT, TYPE_BYTE: AValue1.B := AValue1.B * AValue2.B; end; end; Result := ValueAssign(AValue1); end; function funMultiply(AValue1, AValue2: TValue): TValue; begin Result := nil; case AValue1.Type_ of TYPE_FLOAT: if AValue2.Type_ in [TYPE_FLOAT, TYPE_INT, TYPE_BYTE] then Result := Value(AValue1.F * AValue2.F); TYPE_INT, TYPE_BYTE: case AValue2.Type_ of TYPE_FLOAT: Result := Value(AValue1.I * AValue2.F); TYPE_INT, TYPE_BYTE: Result := Value(AValue1.I * AValue2.I); end; end; if not Assigned(Result) then Result := TValue.Create; end; function funDivideEqual(AValue1, AValue2: TValue): TValue; begin case AValue1.Type_ of TYPE_FLOAT: AValue1.F := AValue1.F / AValue2.F; TYPE_INT: case AValue2.Type_ of TYPE_FLOAT: AValue1.I := Round(AValue1.I / AValue2.F); TYPE_INT, TYPE_BYTE: AValue1.I := AValue1.I div AValue2.I; end; TYPE_BYTE: case AValue2.Type_ of TYPE_FLOAT: AValue1.B := Round(AValue1.B / AValue2.F); TYPE_INT, TYPE_BYTE: AValue1.B := AValue1.B div AValue2.B; end; end; Result := ValueAssign(AValue1); end; function funDivide(AValue1, AValue2: TValue): TValue; begin Result := nil; case AValue1.Type_ of TYPE_FLOAT: if AValue2.Type_ in [TYPE_FLOAT, TYPE_INT, TYPE_BYTE] then Result := Value(AValue1.F / AValue2.F); TYPE_INT, TYPE_BYTE: case AValue2.Type_ of TYPE_FLOAT: Result := Value(AValue1.I / AValue2.F); TYPE_INT, TYPE_BYTE: Result := Value(AValue1.I div AValue2.I); end; end; if not Assigned(Result) then Result := TValue.Create; end; function funModEqual(AValue1, AValue2: TValue): TValue; begin AValue1.I := AValue1.I mod AValue2.I; Result := ValueAssign(AValue1); end; function funMod(AValue1, AValue2: TValue): TValue; begin Result := Value(AValue1.I mod AValue2.I); end; function funIAndEqual(AValue1, AValue2: TValue): TValue; begin AValue1.I := AValue1.I and AValue2.I; Result := ValueAssign(AValue1); end; function funIAnd(AValue1, AValue2: TValue): TValue; begin Result := Value(AValue1.I and AValue2.I); end; function funAnd(AValue1, AValue2: TValue): TValue; begin Result := Value(AValue1.L and AValue2.L); end; function funINot(AValue1: TValue): TValue; begin Result := Value(not AValue1.I); end; function funNot(AValue1: TValue): TValue; begin Result := Value(not AValue1.L); end; function funRound(AValue1: TValue): TValue; begin Result := Value(Round(AValue1.F)); end; function funRandom(AValue1: TValue): TValue; var I: Integer; begin I := AValue1.I; if I = 0 then Result := Value(Random(MaxInt)) else if I = 1 then Result := Value(Random) else Result := Value(Random(I)); end; function funEqualEqual(AValue1, AValue2: TValue): TValue; begin Result := Value(AValue1.Compare(AValue2)); end; function funNotEqual(AValue1, AValue2: TValue): TValue; begin Result := Value(not AValue1.Compare(AValue2)); end; function funMore(AValue1, AValue2: TValue): TValue; begin Result := nil; case AValue1.Type_ of TYPE_FLOAT: Result := Value(AValue1.F > AValue2.F); TYPE_INT, TYPE_BYTE: case AValue2.Type_ of TYPE_FLOAT: Result := Value(AValue1.I > AValue2.F); TYPE_INT, TYPE_BYTE: Result := Value(AValue1.I > AValue2.I); TYPE_STR: Result := Value(AValue1.S > AValue2.S); end; TYPE_STR: Result := Value(AValue1.S > AValue2.S); end; if not Assigned(Result) then Result := TValue.Create; end; function funMoreOrEqual(AValue1, AValue2: TValue): TValue; begin Result := nil; case AValue1.Type_ of TYPE_FLOAT: Result := Value(AValue1.F >= AValue2.F); TYPE_INT, TYPE_BYTE: case AValue2.Type_ of TYPE_FLOAT: Result := Value(AValue1.I >= AValue2.F); TYPE_INT, TYPE_BYTE: Result := Value(AValue1.I >= AValue2.I); TYPE_STR: Result := Value(AValue1.S >= AValue2.S); end; TYPE_STR: Result := Value(AValue1.S >= AValue2.S); end; if not Assigned(Result) then Result := TValue.Create; end; function funLess(AValue1, AValue2: TValue): TValue; begin Result := nil; case AValue1.Type_ of TYPE_FLOAT: Result := Value(AValue1.F < AValue2.F); TYPE_INT, TYPE_BYTE: case AValue2.Type_ of TYPE_FLOAT: Result := Value(AValue1.I < AValue2.F); TYPE_INT, TYPE_BYTE: Result := Value(AValue1.I < AValue2.I); TYPE_STR: Result := Value(AValue1.S < AValue2.S); end; TYPE_STR: Result := Value(AValue1.S < AValue2.S); end; if not Assigned(Result) then Result := TValue.Create; end; function funLessOrEqual(AValue1, AValue2: TValue): TValue; begin Result := nil; case AValue1.Type_ of TYPE_FLOAT: Result := Value(AValue1.F <= AValue2.F); TYPE_INT, TYPE_BYTE: case AValue2.Type_ of TYPE_FLOAT: Result := Value(AValue1.I <= AValue2.F); TYPE_INT, TYPE_BYTE: Result := Value(AValue1.I <= AValue2.I); TYPE_STR: Result := Value(AValue1.S <= AValue2.S); end; TYPE_STR: Result := Value(AValue1.S <= AValue2.S); end; if not Assigned(Result) then Result := TValue.Create; end; function funOffset(AValue1, AValue2: TValue): TValue; begin Result := AValue1.Offset(AValue2); end; function funID(AValue1, AValue2: TValue): TValue; begin Result := ValueCopy(AValue2); Result.ID := AValue1.S; end; { TInstruction } { private } function TInstruction.GetItem(Index: Integer): TIPR; begin Result := FItems[Index]; end; function TInstruction.GetCount(): Integer; begin Result := High(FItems) + 1; end; { public } constructor TInstruction.Create(ACommand: TCommand); begin inherited Create; FCommand := ACommand; SetLength(FItems, 0); end; destructor TInstruction.Destroy; var I: Integer; begin for I := 0 to High(FItems) do begin FItems[I].Free; FItems[I] := nil; end; SetLength(FItems, 0); inherited; end; procedure TInstruction.AddItem(); begin SetLength(FItems, High(FItems) + 2); FItems[High(FItems)] := TIPR.Create(); FItems[High(FItems)].Reset(); end; { TIPR } { private } function TIPR.GetCurrent(): PIPRItem; begin Result := FCurrent^; end; function TIPR.GetLexem(): TLexem; var lIPRItem: PIPRItem; begin lIPRItem := FCurrent^; if Assigned(lIPRItem) then Result := lIPRItem^.Lexem else Result := nonLexem(); end; function TIPR.GetText(): String; procedure DoAdd(const AText: String); begin if Result <> '' then Result := Result + ' '; Result := Result + AText; end; var I: Integer; S: String; begin Result := ''; Reset(); while Assigned(FCurrent^) do begin case FCurrent^^.Lexem.What of LW_OPERAND: case FCurrent^^.Lexem.Operand.What of OW_VALUE: DoAdd(FCurrent^^.Lexem.Operand.Value.S); OW_ID: DoAdd(FCurrent^^.Lexem.Operand.ID); OW_DEFINE: DoAdd('(' + STR_TYPE[FCurrent^^.Lexem.Operand.Type_] + ')' + FCurrent^^.Lexem.Operand.ID); end; LW_OPERATOR: DoAdd(STR_OPERATOR[Integer(FCurrent^^.Lexem.Operator)]); LW_FUNCTION: DoAdd(FCurrent^^.Lexem.ID); LW_FUNCTIONEND: DoAdd('.'); LW_INSTRUCTION: begin S := STR_COMMAND[Integer(FCurrent^^.Lexem.Instruction.Command)] + '('; for I := 0 to FCurrent^^.Lexem.Instruction.Count - 1 do if Assigned(FCurrent^^.Lexem.Instruction[I]) then S := S + FCurrent^^.Lexem.Instruction[I].Text; S := S + ')'; DoAdd(S); end; LW_FLOWCONTROL: DoAdd(STR_FLOWCONTROL[Integer(FCurrent^^.Lexem.FlowControl)]); end; Scroll(); end; end; { public } constructor TIPR.Create(); begin inherited Create(); FHead := nil; FCurrent := @FHead; end; destructor TIPR.Destroy(); begin Clear(True); inherited; end; function TIPR.Copy(): TIPR; begin Result := TIPR.Create(); Reset(); while Assigned(FCurrent^) do begin Result.EndOf(); Result.Add(FCurrent^^.Lexem); Scroll(); end; Result.Reset(); end; procedure TIPR.Reset(); begin FCurrent := @FHead; end; procedure TIPR.Scroll(); begin if Assigned(FCurrent^) then FCurrent := @FCurrent^^.Next else FCurrent := @FHead; end; procedure TIPR.Tail(); begin if Assigned(FHead) then begin if not Assigned(FCurrent^) then Reset(); while Assigned(FCurrent^.Next) do Scroll(); end else FCurrent := @FHead end; procedure TIPR.EndOf(); begin while Assigned(FCurrent^) do Scroll(); end; procedure TIPR.Add(ALexem: TLexem); begin FCurrent^ := IPRItem(ALexem, FCurrent^); end; procedure TIPR.Delete(); var lIPRItem: PIPRItem; begin if Assigned(FCurrent^) then begin lIPRItem := FCurrent^^.Next; FreeMem(FCurrent^); FCurrent^ := lIPRItem; end; end; procedure TIPR.Clear(AFree: Boolean); begin Reset(); if AFree then while Assigned(FCurrent^) do begin if FCurrent^^.Lexem.What = LW_OPERAND then if FCurrent^^.Lexem.Operand.What = OW_VALUE then FCurrent^^.Lexem.Operand.Value.Free() else else if FCurrent^^.Lexem.What = LW_INSTRUCTION then FCurrent^^.Lexem.Instruction.Free(); Delete(); end else while Assigned(FCurrent^) do Delete(); end; function TIPR.CurrentIsFunction(): Boolean; begin Result := FCurrent^^.Lexem.What = LW_FUNCTION; end; function TIPR.CurrentIsVariable(): Boolean; begin Result := (FCurrent^^.Lexem.What = LW_OPERAND) and (FCurrent^^.Lexem.Operand.What = OW_ID); end; { TCode } { private } procedure TCode.DoDefine(const AID: TID; AType_: TType_; AExts: TType_Exts); begin if teGlobal in AExts then if Assigned(FOnDefine) then FOnDefine(AID, AType_, AExts) else else FVariables.Define(AID, AType_, AExts); end; function TCode.DoVariable(const AID: TID): TValue; var lVariable: TVariable; begin lVariable := FVariables.VariableByID(AID); if Assigned(lVariable) then Result := lVariable.Value else if Assigned(FOnVariable) then Result := FOnVariable(AID) else Result := nil; if not Assigned(Result) then Result := TValue.Create(); end; function TCode.DoFunction(const AID: TID; const AArguments: TValues; AClass: TValue): TValue; function DoFunction_System(var AResult: TValue): Boolean; var lFile: TStringList; lCode: TCode; lCmdShow: DWORD; lFlag: Boolean; begin Result := True; //void call(str AFileName) if AID = 'call' then begin lFile := TStringList.Create(); lFile.LoadFromFile(AArguments[0].S); lCode := TCode.Create(); lCode.Compile(lFile.Text); AResult := lCode.Run(); lCode.Free(); lFile.Free(); end // int exec(str ACommand, int AShowMode = SW_SHOWNORMAL, int AWait = 0) else if AID = 'exec' then begin if High(AArguments) > 0 then begin lCmdShow := AArguments[1].I; if High(AArguments) > 1 then lFlag := AArguments[2].L else lFlag := False; end else begin lCmdShow := SW_SHOWNORMAL; lFlag := False; end; AResult := TValue.Create(TYPE_INT); if lFlag then AResult.I := WinExecAndWait(PChar(AArguments[0].S), lCmdShow) else AResult.I := WinExec(PChar(AArguments[0].S), lCmdShow); end else begin AResult := nil; Result := False; end; end; { DoFunction_System } function DoFunction_Common(var AResult: TValue): Boolean; var S: String; begin Result := True; // void msg(str AMessage) if AID = 'msg' then ShowMessage(AArguments[0].S) // int input(str ACaption, str APrompt, @str AValue) else if AID = 'input' then begin S := AArguments[2].S; AResult := TValue.Create(TYPE_INT); if InputQuery(AArguments[0].S, AArguments[1].S, S) then begin AResult.I := 1; AArguments[2].S := S; end else AResult.I := 0; end else begin AResult := nil; Result := False; end; end; { DoFunction_Common } function DoFunction_Str(var AResult: TValue): Boolean; var I: Integer; S: String; begin Result := True; // str chr(int ACode1, ..., int ACodeN) if AID = 'chr' then begin S := ''; for I := 0 to High(AArguments) do S := S + Chr(AArguments[I].I); AResult := TValue.Create(TYPE_STR); AResult.S := S; end // int strlen(str AStr) else if AID = 'strlen' then begin AResult := TValue.Create(TYPE_INT); AResult.I := Length(AArguments[0].S); end // int strpos(str ASubStr, str AStr, int AOffset = 1) else if AID = 'strpos' then begin if High(AArguments) = 1 then I := 1 else I := AArguments[2].I + 1; AResult := TValue.Create(TYPE_INT); AResult.I := PosEx(AArguments[0].S, AArguments[1].S, I) - 1; end // str strdel(str AStr, int AIndex, int ACount = MAX_INT) else if AID = 'strdel' then begin if High(AArguments) = 1 then I := MaxInt else I := AArguments[2].I; S := AArguments[0].S; Delete(S, AArguments[1].I, I); AResult := TValue.Create(TYPE_STR); AResult.S := S; end // str strcpy(str AStr, int AIndex, int ACount = MAX_INT) else if AID = 'strcpy' then begin if High(AArguments) = 1 then I := MaxInt else I := AArguments[2].I; S := Copy(AArguments[0].S, AArguments[1].I, I); AResult := TValue.Create(TYPE_STR); AResult.S := S; end // str strrep(str AStr, str AOldPattern, str ANewPattern) else if AID = 'strrep' then begin S := StringReplace(AArguments[0].S, AArguments[1].S, AArguments[2].S, [rfReplaceAll]); AResult := TValue.Create(TYPE_STR); AResult.S := S; end // str strltrim(str AStr) else if AID = 'strltrim' then begin S := TrimLeft(AArguments[0].S); AResult := TValue.Create(TYPE_STR); AResult.S := S; end // str strrtrim(str AStr) else if AID = 'strrtrim' then begin S := TrimRight(AArguments[0].S); AResult := TValue.Create(TYPE_STR); AResult.S := S; end // str strtrim(str AStr) else if AID = 'strtrim' then begin S := Trim(AArguments[0].S); AResult := TValue.Create(TYPE_STR); AResult.S := S; end // str strucase(str AStr) else if AID = 'strucase' then begin S := AnsiUpperCase(AArguments[0].S); AResult := TValue.Create(TYPE_STR); AResult.S := S; end // str strlcase(str AStr) else if AID = 'strlcase' then begin S := AnsiLowerCase(AArguments[0].S); AResult := TValue.Create(TYPE_STR); AResult.S := S; end else begin AResult := nil; Result := False; end; end; { DoFunction_Str } function DoFunction_Array(var AResult: TValue): Boolean; var I: Integer; begin Result := True; // array array(mix AItem1, ..., mix AItemN) if AID = 'array' then begin AResult := TValue.Create(TYPE_ARRAY); for I := 0 to High(AArguments) do AResult.Add(AArguments[I]); end // int arrcnt(array AArray) else if AID = 'arrcnt' then begin AResult := TValue.Create(TYPE_INT); AResult.I := AArguments[0].Count; end // void arradd(@array AArray, mix AItem, int/str AIndex = -1) else if AID = 'arradd' then begin if High(AArguments) = 2 then I := AArguments[2].I else I := -1; AArguments[0].Add(AArguments[1], I); end // void arrset(@array AArray, mix AItem, int AIndex) else if AID = 'arrset' then AArguments[0].Set_(AArguments[1], AArguments[2].I) // void arrdel(@array AArray, int/str AIndex = -1) else if AID = 'arrdel' then AArguments[0].Delete(AArguments[1]) // void arrclr(@array AArray) else if AID = 'arrclr' then AArguments[0].Clear() // str arrid(array AArray, int/str AIndex) else if AID = 'arrid' then begin AResult := TValue.Create(TYPE_STR); AResult.S := AArguments[0].Offset(AArguments[1]).ID; end // int arridx(array AArray, str AID) else if AID = 'arridx' then begin AResult := TValue.Create(TYPE_INT); AResult.I := AArguments[0].IndexOf(AArguments[1].S); end else begin AResult := nil; Result := False; end; end; { DoFunArray } function DoFunction_File(var AResult: TValue): Boolean; var F: Float; I: Integer; B: Byte; S, lItem: String; lStr: PChar; lFindData: ^TSearchRec; begin Result := True; // int fexists(str AFileName) if AID = 'fexists' then begin AResult := TValue.Create(TYPE_INT); AResult.L := FileExists(AArguments[0].S); end // int fcreate(str AFileName) else if AID = 'fcreate' then begin AResult := TValue.Create(TYPE_INT); AResult.I := FileCreate(AArguments[0].S); end // int fdelete(str AFileName) else if AID = 'fdelete' then begin AResult := TValue.Create(TYPE_INT); AResult.L := DeleteFile(AArguments[0].S); end // int fopen(str AFileName, str AMode) else if AID = 'fopen' then begin S := AArguments[1].S; I := 0; while S <> '' do begin lItem := ReadItem(S, ','); if AnsiCompareText(lItem, 'c') = 0 then I := I or fmCreate else if AnsiCompareText(lItem, 'r') = 0 then I := I or fmOpenRead else if AnsiCompareText(lItem, 'w') = 0 then I := I or fmOpenWrite else if AnsiCompareText(lItem, 'rw') = 0 then I := I or fmOpenReadWrite else if AnsiCompareText(lItem, 'sc') = 0 then I := I or fmShareCompat else if AnsiCompareText(lItem, 'se') = 0 then I := I or fmShareExclusive else if AnsiCompareText(lItem, 'sdr') = 0 then I := I or fmShareDenyRead else if AnsiCompareText(lItem, 'sdw') = 0 then I := I or fmShareDenyWrite else if AnsiCompareText(lItem, 'sdn') = 0 then I := I or fmShareDenyNone; end; AResult := TValue.Create(TYPE_INT); AResult.I := FileOpen(AArguments[0].S, I); end // void fclose(int AFileHandle) else if AID = 'fclose' then FileClose(AArguments[0].I) // int fseek(int AFileHandle, int AOffset, int AOrigin) else if AID = 'fseek' then begin AResult := TValue.Create(TYPE_INT); AResult.I := FileSeek(AArguments[0].I, AArguments[1].I, AArguments[2].I); end // int fread(int AFileHandle, @mix AValue) // int fread(int AFileHandle, @str AValue, int ACount) else if AID = 'fread' then begin AResult := TValue.Create(TYPE_INT); case AArguments[1].Type_ of TYPE_FLOAT: begin AResult.I := FileRead(AArguments[0].I, F, SizeOf(Float)); AArguments[1].F := F; end; TYPE_INT: begin AResult.I := FileRead(AArguments[0].I, I, SizeOf(Integer)); AArguments[1].I := I; end; TYPE_BYTE: begin AResult.I := FileRead(AArguments[0].I, B, SizeOf(Byte)); AArguments[1].B := B; end; TYPE_STR: begin GetMem(lStr, AArguments[2].I); AResult.I := FileRead(AArguments[0].I, lStr^, AArguments[2].I); AArguments[1].S := lStr; FreeMem(lStr); end; else AResult.I := 0; end; end // int fwrite(int AFileHandle, mix AValue) else if AID = 'fwrite' then begin AResult := TValue.Create(TYPE_INT); case AArguments[1].Type_ of TYPE_FLOAT: begin F := AArguments[1].F; AResult.I := FileWrite(AArguments[0].I, F, SizeOf(Float)); end; TYPE_INT: begin I := AArguments[1].I; AResult.I := FileWrite(AArguments[0].I, I, SizeOf(Integer)); end; TYPE_BYTE: begin B := AArguments[1].B; AResult.I := FileWrite(AArguments[0].I, B, SizeOf(Byte)); end; TYPE_STR: begin S := AArguments[1].S; AResult.I := FileWrite(AArguments[0].I, PChar(S)^, Length(S)); end; else AResult.I := 0; end; end // int findfirst(str APath, str AAttrs, @int AFindHandle) else if AID = 'findfirst' then begin S := AArguments[1].S; I := 0; while S <> '' do begin lItem := ReadItem(S, ','); if AnsiCompareText(lItem, 'ro') = 0 then I := I or faReadOnly else if AnsiCompareText(lItem, 'h') = 0 then I := I or faHidden else if AnsiCompareText(lItem, 's') = 0 then I := I or faSysFile else if AnsiCompareText(lItem, 'vid') = 0 then I := I or faVolumeID else if AnsiCompareText(lItem, 'd') = 0 then I := I or faDirectory else if AnsiCompareText(lItem, 'a') = 0 then I := I or faArchive else if AnsiCompareText(lItem, 'f') = 0 then I := I or faAnyFile; end; GetMem(lFindData, SizeOf(TSearchRec)); AResult := TValue.Create(TYPE_INT); AResult.I := FindFirst(AArguments[0].S, I, lFindData^); AArguments[2].I := Integer(lFindData); end // int findnext(int AFindHandle) else if AID = 'findnext' then begin AResult := TValue.Create(TYPE_INT); AResult.I := FindNext(TSearchRec(Pointer(AArguments[0].I)^)); end // void findclose(@int AFindHandle) else if AID = 'findclose' then begin FindClose(TSearchRec(Pointer(AArguments[0].I)^)); AArguments[0].I := 0; end // str getfindname(int AFindHandle) else if AID = 'getfindname' then begin AResult := TValue.Create(TYPE_STR); AResult.S := TSearchRec(Pointer(AArguments[0].I)^).Name; end // int direxists(str ADirectoryName) else if AID = 'direxists' then begin AResult := TValue.Create(TYPE_INT); AResult.L := DirectoryExists(AArguments[0].S); end // int mkdir(str ADirectoryName) else if AID = 'mkdir' then begin {$I-} MkDir(AArguments[0].S); AResult := TValue.Create(TYPE_INT); AResult.L := IOResult = 0; {$I+} end // int rmdir(str ADirectoryName) else if AID = 'rmdir' then begin {$I-} RmDir(AArguments[0].S); AResult := TValue.Create(TYPE_INT); AResult.L := IOResult = 0; {$I+} end // void clrdir(str ADirectoryName) else if AID = 'clrdir' then ClearDir(AArguments[0].S) // void deldir(str ADirectoryName) else if AID = 'deldir' then EraseDir(AArguments[0].S) // int chdir(str ADirectoryName) else if AID = 'chdir' then begin {$I-} ChDir(AArguments[0].S); AResult := TValue.Create(TYPE_INT); AResult.L := IOResult = 0; {$I+} end // str curdir() else if AID = 'curdir' then begin AResult := TValue.Create(TYPE_STR); AResult.S := GetCurrentDir(); end else begin AResult := nil; Result := False; end; end; { DoFunction_File } begin if Assigned(FOnFunction) then Result := FOnFunction(AID, AArguments, AClass) else Result := nil; if not Assigned(Result) then begin if not DoFunction_System(Result) then if not DoFunction_Common(Result) then if not DoFunction_Str(Result) then if not DoFunction_Array(Result) then if not DoFunction_File(Result) then; if not Assigned(Result) then Result := TValue.Create(); end; end; function TCode.DoMethod(const AID: TID; const AArguments: TValues; AClass: TValue): TValue; begin if Assigned(FOnMethod) then Result := FOnMethod(AID, AArguments, AClass) else Result := nil; end; function TCode.DoRun(AClass: TValue): TValue; function DoFun(var AOperands: TValues; AOperator: TOperator): TValue; begin case AOperator of opEqual: Result := funEqual(AOperands[0], AOperands[1]); opAddEqual: Result := funAddEqual(AOperands[0], AOperands[1]); opAdd: Result := funAdd(AOperands[0], AOperands[1]); opPreInc: Result := funPreInc(AOperands[0]); opPostInc: Result := funPostInc(AOperands[0]); opSubtractEqual: Result := funSubtractEqual(AOperands[0], AOperands[1]); opSubtract: Result := funSubtract(AOperands[0], AOperands[1]); opUnarSubtract: Result := funUnarSubtract(AOperands[0]); opPreDec: Result := funPreDec(AOperands[0]); opPostDec: Result := funPostDec(AOperands[0]); opIOrEqual: Result := funIOrEqual(AOperands[0], AOperands[1]); opIOr: Result := funIOr(AOperands[0], AOperands[1]); opOr: Result := funOr(AOperands[0], AOperands[1]); opIXorEqual: Result := funIXorEqual(AOperands[0], AOperands[1]); opIXor: Result := funIXor(AOperands[0], AOperands[1]); opXor: Result := funXor(AOperands[0], AOperands[1]); opMultiplyEqual: Result := funMultiplyEqual(AOperands[0], AOperands[1]); opMultiply: Result := funMultiply(AOperands[0], AOperands[1]); opDivideEqual: Result := funDivideEqual(AOperands[0], AOperands[1]); opDivide: Result := funDivide(AOperands[0], AOperands[1]); opModEqual: Result := funModEqual(AOperands[0], AOperands[1]); opMod: Result := funMod(AOperands[0], AOperands[1]); opIAndEqual: Result := funIAndEqual(AOperands[0], AOperands[1]); opIAnd: Result := funIAnd(AOperands[0], AOperands[1]); opAnd: Result := funAnd(AOperands[0], AOperands[1]); opINot: Result := funINot(AOperands[0]); opNot: Result := funNot(AOperands[0]); opRound: Result := funRound(AOperands[0]); opRandom: Result := funRandom(AOperands[0]); opEqualEqual: Result := funEqualEqual(AOperands[0], AOperands[1]); opNotEqual: Result := funNotEqual(AOperands[0], AOperands[1]); opMore: Result := funMore(AOperands[0], AOperands[1]); opMoreOrEqual: Result := funMoreOrEqual(AOperands[0], AOperands[1]); opLess: Result := funLess(AOperands[0], AOperands[1]); opLessOrEqual: Result := funLessOrEqual(AOperands[0], AOperands[1]); opOffset: Result := funOffset(AOperands[0], AOperands[1]); opID: Result := funID(AOperands[0], AOperands[1]); else Result := TValue.Create; end; FreeValues(AOperands); end; { DoFun } var lClass: TValue; function DoGetVariable(const AID: TID): TValue; begin if Assigned(lClass) then Result := lClass.Field(AID) else Result := nil; if not Assigned(Result) then Result := DoVariable(AID); end; { DoGetVariable } var lFuncName: TID; lFuncArgs: TValues; function DoRunFunction(): TValue; begin if Assigned(lClass) then Result := DoMethod(lFuncName, lFuncArgs, lClass) else Result := nil; if not Assigned(Result) then Result := DoFunction(lFuncName, lFuncArgs, lClass); FreeValues(lFuncArgs); end; { DoRunFunction } function DoRunMethod(AClass: TValue): TValue; begin Result := DoMethod(lFuncName, lFuncArgs, AClass); if not Assigned(Result) then Result := TValue.Create(); FreeValues(lFuncArgs); end; { DoRunMethod } function DoCalculation(AIPR: TIPR): TValue; forward; function DoEval(AIPR: TIPR): TValue; forward; function DoRunInst(ACommand: TCommand; AItems: TIPRArray): TValue; var lValue: TValue; I: Integer; lType: TType_; begin Result := nil; case ACommand of cmdIf: begin lValue := DoEval(AItems[0]); if lValue.L then Result := DoEval(AItems[1]) else if High(AItems) = 2 then Result := DoEval(AItems[2]) else Result := TValue.Create(); lValue.Free(); end; cmdFor: begin Result := DoEval(AItems[0]); lType := Result.Type_; if lType < TYPE_EXIT then begin Result.Free(); Result := TValue.Create(); end else if lType >= TYPE_VOID then while DoEval(AItems[1]).L do begin Result.Free; Result := DoEval(AItems[2]); lType := Result.Type_; if lType < TYPE_EXIT then begin Result.Free(); Result := TValue.Create(); end; case lType of TYPE_CONTINUE: ; TYPE_BREAK: Break; TYPE_EXIT: Break; end; end; end; cmdDo: for I := 0 to High(AItems) do begin Result := DoEval(AItems[I]); case Result.Type_ of TYPE_CONTINUE: Break; TYPE_BREAK: Break; TYPE_EXIT: Break; end; end; end; if not Assigned(Result) then Result := TValue.Create(); end; { DoRunInst } function DoOperand(AIPR: TIPR): TValue; var lLastFuncName: TID; lLastFuncArgs: TValues; begin if AIPR.Lexem.What = LW_FUNCTION then begin lLastFuncName := lFuncName; CopyValues(lFuncArgs, lLastFuncArgs); DoCalculation(AIPR); Result := DoRunFunction(); lFuncName := lLastFuncName; CopyValues(lLastFuncArgs, lFuncArgs); SetLength(lLastFuncArgs, 0); end else Result := DoCalculation(AIPR); end; { DoOperand } function DoCalculation(AIPR: TIPR): TValue; var lOperands: TValues; lArn: Byte; lOperator: TOperator; lID: TID; lClass_: TValue; lItems: TIPRArray; I, C: Integer; begin case AIPR.Lexem.What of LW_OPERAND: case AIPR.Lexem.Operand.What of OW_VALUE: begin Result := ValueAssign(AIPR.Lexem.Operand.Value); AIPR.Scroll(); end; OW_ID, OW_DEFINE: begin with AIPR.Lexem.Operand do begin if What = OW_DEFINE then DoDefine(ID, Type_, Exts); Result := DoGetVariable(ID); end; AIPR.Scroll(); end; else Result := TValue.Create(); end; LW_OPERATOR: begin lOperator := AIPR.Lexem.Operator; AIPR.Scroll(); if lOperator = opClassItem then if AIPR.CurrentIsFunction() then begin DoCalculation(AIPR); if AIPR.CurrentIsVariable() then begin lID := AIPR.Lexem.Operand.ID; lClass_ := DoOperand(AIPR); if lClass_.Type_ = TYPE_CLASS then begin Result := DoRunMethod(lClass_); lClass_.Free(); end else // îáðàùàåìñÿ ê ôóíêöèè êëàññà ò.å. TClass->ClassFunction() Result := TValue.Create(); {I := FCode.Types.Find(ID); if I = -1 then Result := TValue.Create(FCode) else begin FuncName := ID + '.' + FuncName; Result := RunFunction; end} end else begin lClass_ := DoOperand(AIPR); Result := DoRunMethod(lClass_); lClass_.Free(); end; end else begin lID := AIPR.Lexem.Operand.ID; AIPR.Scroll(); lClass_ := DoOperand(AIPR); Result := lClass_.Field(lID); lClass_.Free(); end else begin lArn := ARN[Byte(lOperator)]; SetLength(lOperands, lArn); for I := lArn - 1 downto 0 do lOperands[I] := DoOperand(AIPR); Result := DoFun(lOperands, lOperator); end; end; LW_FUNCTION: begin lFuncName := AIPR.Lexem.ID; AIPR.Scroll(); SetLength(lFuncArgs, 0); if Assigned(AIPR.Current) then while AIPR.Lexem.What <> LW_FUNCTIONEND do begin SetLength(lFuncArgs, High(lFuncArgs) + 2); for I := High(lFuncArgs) downto 1 do lFuncArgs[I] := lFuncArgs[I - 1]; lFuncArgs[0] := DoOperand(AIPR); if not Assigned(AIPR.Current) then Break; end; if Assigned(AIPR.Current) then AIPR.Scroll(); Result := TValue.Create(); end; LW_INSTRUCTION: begin SetLength(lItems, AIPR.Lexem.Instruction.Count); C := 0; for I := 0 to AIPR.Lexem.Instruction.Count - 1 do if Assigned(AIPR.Lexem.Instruction.Items[I]) then begin lItems[I] := AIPR.Lexem.Instruction.Items[I]; C := C + 1; end else Break; SetLength(lItems, C); Result := DoRunInst(AIPR.Lexem.Instruction.Command, lItems); SetLength(lItems, 0); AIPR.Scroll(); end; LW_FLOWCONTROL: case AIPR.Lexem.FlowControl of fcContinue: Result := TValue.Create(TYPE_CONTINUE); fcBreak: Result := TValue.Create(TYPE_BREAK); fcExit: Result := TValue.Create(TYPE_EXIT); else Result := TValue.Create(); end; else Result := TValue.Create(); end; end; { DoCalculation } function DoEval(AIPR: TIPR): TValue; begin AIPR.Reset(); if Assigned(AIPR.Head) then Result := DoOperand(AIPR) else Result := TValue.Create(); end; { DoEval } var lValue: TValue; begin lClass := AClass; lValue := DoEval(FIPR); Result := ValueCopy(lValue); lValue.Free(); end; { public } constructor TCode.Create(); begin inherited Create(); FVariables := TVariables.Create(); FIPR := TIPR.Create(); FOnDefine := nil; FOnVariable := nil; FOnFunction := nil; FOnMethod := nil; end; destructor TCode.Destroy(); begin FIPR.Free(); FVariables.Free(); inherited; end; function TCode.Compile(const AText: String): Boolean; const cNumber = ['0'..'9', '.']; cLetter = ['0'..'9', 'A'..'Z', 'a'..'z', 'À'..'Ï', 'Ð'..'ß', 'à'..'ï', 'ð'..'ÿ', '¨', '¸', '_']; cOperation = [',', '=', '+', '-', '|', '^', '!', '*', '/', '&', '~', '>', '<', '%', '?', '[']; cZero = Ord('0'); var lCursor: Integer; lQueue, lStack: TIPR; lCode: String; procedure DoReadValue(); var lVal, I, K, lPoint: Integer; begin lVal := 0; lPoint := 0; while lCode[lCursor] in cNumber do begin if lCode[lCursor] = '.' then lPoint := lCursor else lVal := lVal * 10 + Ord(lCode[lCursor]) - cZero; lCursor := lCursor + 1; end; lQueue.EndOf(); if lPoint > 0 then begin K := 1; I := 0; while I < lCursor - lPoint - 1 do begin K := K * 10; I := I + 1; end; lQueue.Add(valLexem(Value(lVal / K))); end else lQueue.Add(valLexem(Value(lVal))); end; { DoReadValue } procedure DoReadChar(); begin lCursor := lCursor + 1; lQueue.EndOf(); lQueue.Add(valLexem(Value(Byte(Ord(lCode[lCursor]))))); lCursor := lCursor + 2; end; { DoReadChar } procedure DoReadString(); var lVal: String; begin lVal := ''; lCursor := lCursor + 1; while lCode[lCursor] <> '"' do begin lVal := lVal + lCode[lCursor]; lCursor := lCursor + 1; end; lCursor := lCursor + 1; lQueue.EndOf(); lQueue.Add(valLexem(Value(lVal))); end; { DoReadString } function DoPredValue(): Boolean; var lIPRItem: PIPRItem; begin lQueue.Tail(); lIPRItem := lQueue.Current; lQueue.EndOf(); if not Assigned(lIPRItem) then Result := False else if lIPRItem^.Lexem.What = LW_OPERAND then Result := True else if lIPRItem^.Lexem.What = LW_OPERATOR then if lIPRItem^.Lexem.Operator in opPostfix then Result := True else Result := False else Result := False; end; { DoPredValue } var lFunc: Boolean; procedure DoReadOperator(); var lID: TID; lOp: TOperator; lFlag: Boolean; begin if (lCode[lCursor] = ',') and lFunc then begin lQueue.EndOf(); lQueue.Add(opLexem(opComma)); lCursor := lCursor + 1; end else begin lID := ''; lFlag := False; while lCode[lCursor] in cOperation do begin lID := lID + lCode[lCursor]; lOp := Operator(lID); if lOp = opNone then if lFlag then begin Delete(lID, Length(lID), 1); Break; end else lCursor := lCursor + 1 else begin lFlag := True; lCursor := lCursor + 1; end; end; if lID = '++' then if DoPredValue() then lQueue.Add(opLexem(opPostInc)) else lQueue.Add(opLexem(opPreInc)) else if lID = '-' then if DoPredValue() then lQueue.Add(opLexem(opSubtract)) else lQueue.Add(opLexem(opUnarSubtract)) else if lID = '--' then if DoPredValue() then lQueue.Add(opLexem(opPostDec)) else lQueue.Add(opLexem(opPreDec)) else if lID = '%' then if DoPredValue() then lQueue.Add(opLexem(opMod)) else lQueue.Add(opLexem(opRound)) else begin lOp := Operator(lID); if lOp > opNone then begin if ARN[Byte(lOp)] = 2 then lFlag := DoPredValue() else if ARN[Byte(lOp)] = 1 then lFlag := not DoPredValue() else lFlag := True; if lFlag then begin lQueue.EndOf(); lQueue.Add(opLexem(lOp)); end; end; end; end; end; { DoReadOperator } procedure DoReadBrack(); forward; procedure DoReadID(); var lID, lTypeStr: String; lLastFunc: Boolean; lCmd: TCommand; lType_: TType_; lExts: TType_Exts; lFC: TFlowControl; begin lID := ''; while lCode[lCursor] in (cLetter + [' '] + Type_Exts) do begin lID := lID + lCode[lCursor]; lCursor := lCursor + 1; end; lID := Trim(lID); if lID = '' then Exit; lQueue.EndOf(); if lCode[lCursor] = '(' then begin lLastFunc := lFunc; lFunc := True; lCmd := Command(lID); if lCmd = cmdNone then lQueue.Add(funLexem(lID)) else lQueue.Add(insLexem(TInstruction.Create(lCmd))); DoReadBrack(); lFunc := lLastFunc; end else if Type_ID(lID, lTypeStr, lID) then if lTypeStr <> '' then begin lExts := []; while lTypeStr[1] in Type_Exts do begin if lTypeStr[1] = '$' then lExts := lExts + [teGlobal] else if lTypeStr[1] = '@' then lExts := lExts + [teRef]; Delete(lTypeStr, 1, 1); end; lType_ := Type_(lTypeStr); if lType_ > TYPE_VOID then lQueue.Add(defLexem(lID, lType_, lExts)); end else else begin lFC := FlowControl(lID); if lFC = fcNone then lQueue.Add(idLexem(lID)) else lQueue.Add(fcLexem(lFC)); end; end; { DoReadID } procedure DoReadItem(); forward; procedure DoReadBrack(); begin if lCode[lCursor] = '(' then begin lQueue.EndOf(); lQueue.Add(opLexem(opOpenBrack)); lCursor := lCursor + 1; while lCursor <= Length(lCode) do case lCode[lCursor] of ')': begin lQueue.EndOf(); lQueue.Add(opLexem(opCloseBrack)); lCursor := lCursor + 1; Break; end; else DoReadItem(); end; end; end; { DoReadBrack } procedure DoReadOffset(); begin if (lCode[lCursor] = '[') and DoPredValue() then begin lQueue.EndOf(); lQueue.Add(opLexem(opOffset)); lQueue.EndOf(); lQueue.Add(opLexem(opOpenBrack)); lCursor := lCursor + 1; while lCursor <= Length(lCode) do case lCode[lCursor] of ']': begin lQueue.EndOf(); lQueue.Add(opLexem(opCloseBrack)); lCursor := lCursor + 1; Break; end; else DoReadItem(); end; end else lCursor := lCursor + 1; end; { DoReadOffset } procedure DoReadItem(); begin case lCode[lCursor] of '0'..'9': DoReadValue; '''': DoReadChar; '"': DoReadString; ',', '=', '+', '-', '|', '^', '!', '*', '/', '&', '~', '>', '<', '%', '?': DOReadOperator; 'A'..'Z', 'a'..'z', 'À'..'Ï', 'Ð'..'ß', 'à'..'ï', 'ð'..'ÿ', '¨', '¸', '_', '.', '$', '@', '#': DOReadID; '(': DoReadBrack; '[': DoReadOffset; else lCursor := lCursor + 1; end; end; { DoReadItem } procedure DoBrackPull(AIPR: TIPR); begin lStack.Reset(); while Assigned(lStack.Head) and (lStack.Lexem.Operator <> opOpenBrack) do begin AIPR.Add(lStack.Lexem); lStack.Delete(); end; lStack.Delete(); end; { DoBrackPull } procedure DoNextPull(AIPR: TIPR); begin lStack.Reset(); while Assigned(lStack.Head) and (lStack.Lexem.Operator <> opOpenBrack) do begin AIPR.Add(lStack.Lexem); lStack.Delete(); end; end; { DoNextPull } procedure DoPull(AIPR: TIPR); begin lStack.Reset(); while Assigned(lStack.Head) do begin AIPR.Add(lStack.Lexem); lStack.Delete(); end; end; { DoPull } procedure DoOpPull(AIPR: TIPR); var P1, P2: Integer; begin lStack.Reset(); if lQueue.Lexem.What = LW_OPERATOR then P1 := PRIORITY[Byte(lQueue.Lexem.Operator)] else if lQueue.Lexem.What = LW_FUNCTION then P1 := PR_FUN else if lQueue.Lexem.What = LW_INSTRUCTION then P1 := PR_INS else P1 := -1; P2 := -1; repeat if P2 > -1 then begin AIPR.Add(lStack.Lexem); lStack.Delete(); end; if Assigned(lStack.Head) then if lStack.Lexem.What = LW_OPERATOR then P2 := PRIORITY[Byte(lStack.Lexem.Operator)] else if lStack.Lexem.What = LW_FUNCTION then P2 := PR_FUN else if lStack.Lexem.What = LW_INSTRUCTION then P2 := PR_INS else P2 := -1 else P2 := -1; until (P1 > P2) or ((P1 = PR_EQL) and (P1 = P2)); lStack.Add(lQueue.Lexem); end; { DoOpPull } procedure DoInstPull(AIPR: TIPR); forward; procedure DoFuncPull(AIPR: TIPR); var lBrackCount: Integer; begin DoOpPull(AIPR); AIPR.Add(endLexem); lQueue.Scroll(); lBrackCount := 0; while Assigned(lQueue.Current) do begin if lQueue.Lexem.What = LW_OPERATOR then case lQueue.Lexem.Operator of opOpenBrack: begin lStack.Add(opLexem(opOpenBrack)); lBrackCount := lBrackCount + 1; end; opCloseBrack: begin DoBrackPull(AIPR); lBrackCount := lBrackCount - 1; if lBrackCount = 0 then Break; end; opComma: DoNextPull(AIPR); else DoOpPull(AIPR); end else if lQueue.Lexem.What = LW_FUNCTION then DoFuncPull(AIPR) else if lQueue.Lexem.What = LW_INSTRUCTION then DoInstPull(AIPR) else AIPR.Add(lQueue.Lexem); lQueue.Scroll(); end; lStack.Reset(); AIPR.Add(lStack.Lexem); lStack.Delete(); end; { DoFuncPull } procedure DoInstPull(AIPR: TIPR); var I, lBrackCount: Integer; lIPRItem: PIPRItem; begin lIPRItem := lQueue.Current; DoOpPull(AIPR); lQueue.Scroll(); lBrackCount := 0; I := 0; lIPRItem^.Lexem.Instruction.AddItem(); while Assigned(lQueue.Current) do begin if lQueue.Lexem.What = LW_OPERATOR then case lQueue.Lexem.Operator of opOpenBrack: begin lStack.Add(opLexem(opOpenBrack)); lBrackCount := lBrackCount + 1; end; opCloseBrack: begin DoBrackPull(lIPRItem^.Lexem.Instruction.Items[I]); lBrackCount := lBrackCount - 1; if lBrackCount = 0 then Break; end; opComma: begin DoNextPull(lIPRItem^.Lexem.Instruction.Items[I]); I := I + 1; lIPRItem^.Lexem.Instruction.AddItem(); end; else DoOpPull(lIPRItem^.Lexem.Instruction.Items[I]); end else if lQueue.Lexem.What = LW_FUNCTION then DoFuncPull(lIPRItem^.Lexem.Instruction.Items[I]) else if lQueue.Lexem.What = LW_INSTRUCTION then DoInstPull(lIPRItem^.Lexem.Instruction.Items[I]) else lIPRItem^.Lexem.Instruction.Items[I].Add(lQueue.Lexem); lQueue.Scroll(); end; lStack.Reset(); AIPR.Add(lStack.Lexem); lStack.Delete(); end; { DoInstPull } begin FIPR.Clear(True); lCursor := 1; lCode := AText; Prepare(lCode); Result := True; lQueue := TIPR.Create(); lFunc := False; while lCursor <= Length(lCode) do DoReadItem(); lStack := TIPR.Create(); lQueue.Reset(); while Assigned(lQueue.Current) do begin if lQueue.Lexem.What = LW_OPERATOR then case lQueue.Lexem.Operator of opOpenBrack: lStack.Add(opLexem(opOpenBrack)); opCloseBrack: DoBrackPull(FIPR); else DoOpPull(FIPR); end else if lQueue.Lexem.What = LW_FUNCTION then DoFuncPull(FIPR) else if lQueue.Lexem.What = LW_INSTRUCTION then DoInstPull(FIPR) else FIPR.Add(lQueue.Lexem); lQueue.Scroll(); end; DoPull(FIPR); lQueue.Clear(False); lQueue.Free; lStack.Clear(False); lStack.Free; end; function TCode.Run(AClass: TValue): TValue; begin FVariables.Clear(); Result := DoRun(AClass); FVariables.Clear(); end; function TCode.RunAsBlock(AClass: TValue): TValue; begin Result := DoRun(AClass); end; procedure TCode.Clear(); begin FIPR.Clear(True); FVariables.Clear(); end; end.
unit TestWriteBufferSettingVerifier; { 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, OS.WriteBufferSettingVerifier; type // Test methods for class TWriteBufferSettingVerifier TestTWriteBufferSettingVerifier = class(TTestCase) strict private FWriteBufferSettingVerifier: TWriteBufferSettingVerifier; procedure TestSplittingModelAndFirmware( ModelAndFirmware, ExpectedModel, ExpectedFirmware: String); public procedure SetUp; override; procedure TearDown; override; published procedure TestSplittingHardDiskModelFirmware; end; implementation procedure TestTWriteBufferSettingVerifier.SetUp; begin FWriteBufferSettingVerifier := TWriteBufferSettingVerifier.Create; end; procedure TestTWriteBufferSettingVerifier.TearDown; begin FWriteBufferSettingVerifier.Free; FWriteBufferSettingVerifier := nil; end; procedure TestTWriteBufferSettingVerifier.TestSplittingHardDiskModelFirmware; begin TestSplittingModelAndFirmware( 'DiskWDC_WD10EZEX-00BN5A0____________________01.01A01', 'WDC WD10EZEX-00BN5A0', '01.01A01'); TestSplittingModelAndFirmware( 'DiskWDC_WD10EZEX-00RKKA0____________________80.00A80', 'WDC WD10EZEX-00RKKA0', '80.00A80'); TestSplittingModelAndFirmware( 'DiskWDC_WD10EZEX-00ZF5A0____________________80.00A80', 'WDC WD10EZEX-00ZF5A0', '80.00A80'); end; procedure TestTWriteBufferSettingVerifier.TestSplittingModelAndFirmware( ModelAndFirmware, ExpectedModel, ExpectedFirmware: String); var RealModel, RealFirmware: String; begin FWriteBufferSettingVerifier.SplitIntoModelAndFirmware( ModelAndFirmware, RealModel, RealFirmware); CheckEquals(ExpectedModel, RealModel, 'Error in Model, ModelAndFirmware: ' + ModelAndFirmware); CheckEquals(ExpectedFirmware, RealFirmware, 'Error in Firmware, ModelAndFirmware: ' + ModelAndFirmware); end; initialization // Register any test cases with the test runner RegisterTest(TestTWriteBufferSettingVerifier.Suite); end.
unit JATimer; {$mode objfpc}{$H+} {$i JA.inc} interface uses exec, timer, amigados, JATypes, JALog; const JATimer_SecondsPerMinute = 60; JATimer_SecondsPerHour = JATimer_SecondsPerMinute*60; JATimer_SecondsPerDay = JATimer_SecondsPerHour*24; {V50 of timer.device (morphOS AROS?)} UNIT_CPUCLOCK = 5; UNIT_WAITCPUCLOCK = 6; type TJATimer = record TimerPort : pMsgPort; TimerIORequest : ptimerequest; TimePrevious : ttimeval; TimeCurrent : ttimeval; end; PJATimer = ^TJATimer; function JATimerCreate() : PJATimer; function JATimerDestroy(ATimer : PJATimer) : boolean; procedure JATimerUpdate(ATimer : PJATimer; ATime : ptimeval); procedure JATimerGetTicksMS(ATimer : PJATimer; ATicksMS : PFloat32); procedure JATimerGetTicksMicro(ATimer : PJATimer; ATicksMicro : PFloat32); function JATimerLap(ATimer : PJATimer) : Float32; {just returns how long it's been since the last time it was called for this timer} procedure JATimerWait(ATimer : PJATimer; UntilTime : ptimeval); implementation function JATimerCreate : PJATimer; begin Log('JATimerCreate','Creating Timer'); Result := JAMemGet(SizeOf(TJATimer)); Result^.TimerPort := CreatePort(Nil, 0); if (Result^.TimerPort = nil) then begin JAMemFree(Result,SizeOf(TJATimer)); exit(nil); end; Result^.TimerIORequest := pTimeRequest(CreateExtIO(Result^.TimerPort,sizeof(tTimeRequest))); if (Result^.TimerIORequest = nil) then begin DeletePort(Result^.TimerPort); JAMemFree(Result,SizeOf(TJATimer)); exit(nil); end; //if OpenDevice(JADeviceNameTimer, UNIT_VBLANK, pIORequest(Result^.TimerIORequest), 0) <> 0 then if OpenDevice(JADeviceNameTimer, UNIT_MICROHZ, pIORequest(Result^.TimerIORequest), 0) <> 0 then begin DeleteExtIO(pIORequest(Result^.TimerIORequest)); DeletePort(Result^.TimerPort); JAMemFree(Result,SizeOf(TJATimer)); exit(nil); end; {TODO : the UNIT_MICROHZ and creation of the port etc - does this affect multiple JATimers? do we have lots of JATimers all querying the same amiga timer or is it useful to have one amiga timer per JATimer?} TimerBase := pointer(Result^.TimerIORequest^.tr_Node.io_Device); end; function JATimerDestroy(ATimer : PJATimer) : boolean; var TimerPort : pMsgPort; begin Log('JATimerDestroy','Destroying Timer'); TimerPort := ATimer^.TimerIORequest^.tr_Node.io_Message.mn_ReplyPort; if (TimerPort<>nil) then begin CloseDevice(pIORequest(ATimer^.TimerIORequest)); DeleteExtIO(pIORequest(ATimer^.TimerIORequest)); DeletePort(TimerPort); end; JAMemFree(ATimer,SizeOf(TJATimer)); Result := true; end; procedure JATimerUpdate(ATimer : PJATimer; ATime : ptimeval); begin ATimer^.TimerIORequest^.tr_node.io_Command := TR_GETSYSTIME; DoIO(pIORequest(ATimer^.TimerIORequest)); ATimer^.TimePrevious := ATimer^.TimeCurrent; ATimer^.TimeCurrent := ATimer^.TimerIORequest^.tr_time; if (ATime<>nil) then ATime^ := ATimer^.TimeCurrent; end; procedure JATimerGetTicksMS(ATimer : PJATimer; ATicksMS : PFloat32); begin ATimer^.TimerIORequest^.tr_node.io_Command := TR_GETSYSTIME; DoIO(pIORequest(ATimer^.TimerIORequest)); ATicksMS^ := (((ATimer^.TimerIORequest^.tr_time.tv_secs * 1000) * 1000) + (ATimer^.TimerIORequest^.tr_time.tv_micro)) / 1000; end; procedure JATimerGetTicksMicro(ATimer : PJATimer; ATicksMicro : PFloat32); begin ATimer^.TimerIORequest^.tr_node.io_Command := TR_GETSYSTIME; DoIO(pIORequest(ATimer^.TimerIORequest)); ATicksMicro^ := ((ATimer^.TimerIORequest^.tr_time.tv_secs * 1000) * 1000) + (ATimer^.TimerIORequest^.tr_time.tv_micro); end; function JATimerLap(ATimer : PJATimer) : Float32; begin ATimer^.TimerIORequest^.tr_node.io_Command := TR_GETSYSTIME; DoIO(pIORequest(ATimer^.TimerIORequest)); ATimer^.TimePrevious := ATimer^.TimeCurrent; ATimer^.TimeCurrent := ATimer^.TimerIORequest^.tr_time; Result := ((ATimer^.TimeCurrent.tv_secs - ATimer^.TimePrevious.tv_secs) * 1000) + ((ATimer^.TimeCurrent.tv_micro - ATimer^.TimePrevious.tv_micro) / 1000); end; procedure JATimerWait(ATimer : PJATimer; UntilTime : ptimeval); begin { add a new timer request } ATimer^.TimerIORequest^.tr_node.io_Command := TR_ADDREQUEST; { structure assignment } ATimer^.TimerIORequest^.tr_time.tv_secs := UntilTime^.tv_secs; ATimer^.TimerIORequest^.tr_time.tv_micro := UntilTime^.tv_micro; { post request to the timer -- will go to sleep till done } DoIO(pIORequest(ATimer^.TimerIORequest)); end; end.
unit IntentServiceUnit; interface uses AndroidApi.JNI.GraphicsContentViewText; type TIntentServiceHelper = record private FIntent: JIntent; FCode: Integer; FData: string; public class function Create(const Intent: JIntent): TIntentServiceHelper; overload; static; class function Create(const AServiceName: string; Code: Integer; Data: string): TIntentServiceHelper; overload; static; property Code: Integer read FCode; property Data: string read FData; property Intent: JIntent read FIntent; end; implementation uses System.SysUtils, Androidapi.Helpers, Androidapi.Jni, Androidapi.JNIBridge, Androidapi.JNI.JavaTypes; { TIntentServiceHelper } class function TIntentServiceHelper.Create(const Intent: JIntent): TIntentServiceHelper; begin Result.FCode := Intent.getIntExtra(TAndroidHelper.StringToJString('Code'), -1); Result.FData := TAndroidHelper.JStringToString(Intent.getStringExtra(TAndroidHelper.StringToJString('Data'))); end; class function TIntentServiceHelper.Create(const AServiceName: string; Code: Integer; Data: string): TIntentServiceHelper; var LService: string; begin Result.FIntent := TJIntent.Create; LService := AServiceName; if not LService.StartsWith('com.embarcadero.services.') then LService := 'com.embarcadero.services.' + LService; Result.FIntent.setClassName(TAndroidHelper.Context.getPackageName(), TAndroidHelper.StringToJString(LService)); Result.FIntent.putExtra(TAndroidHelper.StringToJString('Code'), Code); Result.FIntent.putExtra(TAndroidHelper.StringToJString('Data'), TAndroidHelper.StringToJString(Data)); end; end.
unit U_Disp; interface uses Windows, Messages, SysUtils, Classes; type T_Disp = class(TThread) private procedure Execute;override; function MyPostThreadMessage(msg:Cardinal; wParam:Integer; lParam:Integer):LongBool; procedure DispConnPro(); procedure DispDisConnPro(); procedure DispSndDataPro(); procedure DispRevDataPro(); procedure DispDevAddrPro(); procedure DispLogPro(); public constructor Create(); destructor Destroy; override; function DispConn(ip:string; port:Integer):Boolean; function DispDisConn(ip:string; port:Integer):Boolean; function DispSndData(pData:PByte; nDataLen:Integer; ip:string=''; port:Integer=0):Boolean; function DispRevData(pData:PByte; nDataLen:Integer; ip:string=''; port:Integer=0):Boolean; function DispDevAddr(ip:string; port:Integer; devAddr:Int64):Boolean; function DispLog(strLog:string; ip:string=''; port:Integer=0):Boolean; end; var g_disp:T_Disp; implementation uses U_Main, U_Frame, U_Operation; const WM_ON_CONN = WM_USER + 1; WM_ON_DISCONN = WM_USER + 2; WM_ON_SND_DATA = WM_USER + 3; WM_ON_REV_DATA = WM_USER + 4; WM_DEV_ADDR = WM_USER + 5; WM_LOG = WM_USER + 6; type PTDispNet = ^TDispNet; TDispNet = record ip:string; port:Integer; pData:PByte; nDataLen:Integer; nValue:Int64; strValue:string; end; var s_pDispNet:PTDispNet = nil; constructor T_Disp.Create(); begin FreeOnTerminate := False; inherited Create(False); end; destructor T_Disp.Destroy; begin Terminate(); inherited; end; procedure T_Disp.Execute; var msg:TMsg; begin while not Terminated do begin Sleep(50); while PeekMessage(msg, INVALID_HANDLE_VALUE, WM_ON_CONN, WM_LOG, PM_REMOVE) do begin s_pDispNet := nil; case msg.message of WM_ON_CONN: begin s_pDispNet := PTDispNet(msg.lParam); Synchronize(DispConnPro); end; WM_ON_DISCONN: begin s_pDispNet := PTDispNet(msg.lParam); Synchronize(DispDisConnPro); end; WM_ON_SND_DATA: begin s_pDispNet := PTDispNet(msg.lParam); Synchronize(DispSndDataPro); end; WM_ON_REV_DATA: begin s_pDispNet := PTDispNet(msg.lParam); Synchronize(DispRevDataPro); end; WM_DEV_ADDR: begin s_pDispNet := PTDispNet(msg.lParam); Synchronize(DispDevAddrPro); end; WM_LOG: begin s_pDispNet := PTDispNet(msg.lParam); Synchronize(DispLogPro); end; end; if s_pDispNet<>nil then begin if s_pDispNet.pData<>nil then begin FreeMemory(s_pDispNet.pData); s_pDispNet.pData := nil; end; Dispose(PTDispNet(s_pDispNet)); s_pDispNet := nil; end; end; end; end; function T_Disp.MyPostThreadMessage(msg:Cardinal; wParam:Integer; lParam:Integer):LongBool; begin PostThreadMessage(ThreadID, msg, wParam, lParam); Result := True; end; procedure T_Disp.DispConnPro(); begin if s_pDispNet<>nil then begin F_Main.AddConnection(s_pDispNet.ip, s_pDispNet.port); end; end; procedure T_Disp.DispDisConnPro(); begin if s_pDispNet<>nil then begin F_Main.DelConnection(s_pDispNet.ip, s_pDispNet.port); end; end; procedure T_Disp.DispSndDataPro(); begin if s_pDispNet<>nil then begin F_Frame.DisplayFrame(s_pDispNet.pData, s_pDispNet.nDataLen, True, s_pDispNet.ip, s_pDispNet.port); end; end; procedure T_Disp.DispRevDataPro(); begin if s_pDispNet<>nil then begin F_Frame.DisplayFrame(s_pDispNet.pData, s_pDispNet.nDataLen, False, s_pDispNet.ip, s_pDispNet.port); end; end; procedure T_Disp.DispDevAddrPro(); begin if s_pDispNet<>nil then begin F_Main.DispDevAddr(s_pDispNet.ip, s_pDispNet.port, s_pDispNet.nValue); end; end; procedure T_Disp.DispLogPro(); begin if s_pDispNet<>nil then begin F_Operation.DisplayOperation(s_pDispNet.strValue); end; end; function T_Disp.DispConn(ip:string; port:Integer):Boolean; var pDispNet:PTDispNet; begin New(pDispNet); pDispNet.ip := ip; pDispNet.port := port; pDispNet.pData := nil; pDispNet.nDataLen := 0; MyPostThreadMessage(WM_ON_CONN, 0, Integer(pDispNet)); Result := True; end; function T_Disp.DispDisConn(ip:string; port:Integer):Boolean; var pDispNet:PTDispNet; begin New(pDispNet); pDispNet.ip := ip; pDispNet.port := port; pDispNet.pData := nil; pDispNet.nDataLen := 0; MyPostThreadMessage(WM_ON_DISCONN, 0, Integer(pDispNet)); Result := True; end; function T_Disp.DispSndData(pData:PByte; nDataLen:Integer; ip:string=''; port:Integer=0):Boolean; var pDispNet:PTDispNet; pDataDisp:PByte; begin New(pDispNet); pDispNet.ip := ip; pDispNet.port := port; pDispNet.pData := nil; pDispNet.nDataLen := 0; if (pData<>nil) and (nDataLen>0) then begin pDataDisp := GetMemory(nDataLen); MoveMemory(pDataDisp, pData, nDataLen); pDispNet.pData := pDataDisp; pDispNet.nDataLen := nDataLen; end; MyPostThreadMessage(WM_ON_SND_DATA, 0, Integer(pDispNet)); Result := True; end; function T_Disp.DispRevData(pData:PByte; nDataLen:Integer; ip:string=''; port:Integer=0):Boolean; var pDispNet:PTDispNet; pDataDisp:PByte; begin New(pDispNet); pDispNet.ip := ip; pDispNet.port := port; pDispNet.pData := nil; pDispNet.nDataLen := 0; if (pData<>nil) and (nDataLen>0) then begin pDataDisp := GetMemory(nDataLen); MoveMemory(pDataDisp, pData, nDataLen); pDispNet.pData := pDataDisp; pDispNet.nDataLen := nDataLen; end; MyPostThreadMessage(WM_ON_REV_DATA, 0, Integer(pDispNet)); Result := True; end; function T_Disp.DispDevAddr(ip:string; port:Integer; devAddr:Int64):Boolean; var pDispNet:PTDispNet; begin New(pDispNet); pDispNet.ip := ip; pDispNet.port := port; pDispNet.nValue := devAddr; pDispNet.pData := nil; pDispNet.nDataLen := 0; Result := MyPostThreadMessage(WM_DEV_ADDR, 0, Integer(pDispNet)); end; function T_Disp.DispLog(strLog:string; ip:string=''; port:Integer=0):Boolean; var pDispNet:PTDispNet; begin New(pDispNet); pDispNet.ip := ip; pDispNet.port := port; pDispNet.strValue := strLog; pDispNet.pData := nil; Result := MyPostThreadMessage(WM_LOG, 0, Integer(pDispNet)); end; end.
unit SMCnst; interface {Brazilian Portuguese strings} {translated by Rodrigo Hjort, rodrigo_hjort@excite.com} {atualizado por Alexandre Sant'Anna em 06/08/2007, alex.santanna@globo.com} {atualizado por Francisco Ernesto Teixeira em 01/10/2013, fco.ernesto@gmail.com} const strMessage = 'Imprimir...'; strSaveChanges = 'Deseja realmente salvar alterações no Servidor de Banco de Dados?'; strErrSaveChanges = 'Não foi possível salvar um dado! Verifique a conexão com o Servidor ou validação de dados.'; strDeleteWarning = 'Deseja realmente excluir a tabela %s?'; strEmptyWarning = 'Deseja realmente esvaziar a tabela %s?'; const PopUpCaption: array [0..24] of string[33] = ('Incluir registro', 'Insert registro', 'Alterar registro', 'Excluir registro', '-', 'Imprimir ...', 'Exportar ...', 'Filtra ...', 'Pesquisa ...', '-', 'Salvar alterações', 'Cancelar alterações', 'Atualizar', '-', 'Selecionar/Desselecionar registros', 'Selecionar registro', 'Selecionar todos registros', '-', 'Desselecionar registro', 'Desselecionar todos registros', '-', 'Salvar layout da coluna', 'Abrir layout da coluna', '-', 'Configurar...'); const //for TSMSetDBGridDialog SgbTitle = ' Titulo '; SgbData = ' Data '; STitleCaption = 'Legenda:'; STitleAlignment = 'Alinhamento:'; STitleColor = 'Cor:'; STitleFont = 'Fonte:'; SWidth = 'Largura:'; SWidthFix = 'Fixos'; SAlignLeft = 'esquerda'; SAlignRight = 'direita'; SAlignCenter = 'centro'; const //for TSMDBFilterDialog strEqual = 'igual'; strNonEqual = 'diferente'; strNonMore = 'não maior'; strNonLess = 'não menor'; strLessThan = 'menor que'; strLargeThan = 'maior que'; strExist = 'vazio'; strNonExist = 'preenchido'; strIn = 'na lista'; strBetween = 'entre'; strLike = 'parecido'; strOR = 'OU'; strAND = 'E'; strField = 'Campo'; strCondition = 'Condição'; strValue = 'Valor'; strAddCondition = ' defina a condição adicional:'; strSelection = ' escolha os regritro pelo próxima condição:'; strAddToList = 'incluir na lista'; strEditInList = 'Editar a lista'; strDeleteFromList = 'Excluir da lista'; strTemplate = 'Dialogo de filtro padrão'; strFLoadFrom = 'Carregar de...'; strFSaveAs = 'Salvar como...'; strFDescription = 'descrição'; strFFileName = 'Arquivo'; strFCreate = 'Criado: %s'; strFModify = 'Modificado: %s'; strFProtect = 'Somente leitura'; strFProtectErr = 'Arquivo esta protegido!'; const //for SMDBNavigator SFirstRecord = 'Primeiro registro'; SPriorRecord = 'Registro anterior'; SNextRecord = 'Próximo registro'; SLastRecord = 'Último registro'; SInsertRecord = 'Inserir registro'; SCopyRecord = 'Copiar registro'; SDeleteRecord = 'Excluir registro'; SEditRecord = 'Alterar registro'; SFilterRecord = 'Condições de filtragem'; SFindRecord = 'Localizar registro'; SPrintRecord = 'Imprimir registros'; SExportRecord = 'Exportar registros'; SImportRecord = 'Importar os registros'; SPostEdit = 'Salvar alterações'; SCancelEdit = 'Cancelar alterações'; SRefreshRecord = 'Atualizar dados'; SChoice = 'Escolher registro'; SClear = 'Limpar escolha de registro'; SDeleteRecordQuestion = 'Excluir registro?'; SDeleteMultipleRecordsQuestion = 'Deseja realmente excluir registros selecionados?'; SRecordNotFound = 'Registro não encontrado'; SFirstName = 'Primeiro'; SPriorName = 'Anterior'; SNextName = 'Próximo'; SLastName = 'Último'; SInsertName = 'Inserir'; SCopyName = 'Copiar'; SDeleteName = 'Excluir'; SEditName = 'Alterar'; SFilterName = 'Filtrar'; SFindName = 'Localizar'; SPrintName = 'Imprimir'; SExportName = 'Exportar'; SImportName = 'Importar'; SPostName = 'Salvar'; SCancelName = 'Cancelar'; SRefreshName = 'Atualizar'; SChoiceName = 'Escolher'; SClearName = 'Limpar'; SBtnOk = '&OK'; SBtnCancel = '&Cancelar'; SBtnLoad = 'Carregar'; SBtnSave = 'Salvar'; SBtnCopy = 'Copiar'; SBtnPaste = 'Colar'; SBtnClear = 'Limpar'; SRecNo = '#'; SRecOf = ' de '; const //for EditTyped etValidNumber = 'número válido'; etValidInteger = 'número inteiro válido'; etValidDateTime = 'data/hora válida'; etValidDate = 'data válida'; etValidTime = 'hora válida'; etValid = 'válido'; etIsNot = 'não é um'; etOutOfRange = 'Valor %s está fora dos limites %s..%s'; SApplyAll = 'Aplicar em todos'; SNoDataToDisplay = '<Sem registros>'; SPrevYear = 'ano anterior'; SPrevMonth = 'mês anterior'; SNextMonth = 'próximo mês'; SNextYear = 'próximo mês'; implementation end.
unit uObjectDXFDrawing; interface uses SysUtils, Types, Vcl.Graphics, Contnrs, System.Math, uMyTypes, uObjectDXFEntity, uObjectDrawing; type TDXFDrawing = class(TObject) private objFullPath: string; // cesta a nazov suboru objCurrLayer: string; objEntities: TObjectList; objBoundingBox: TMyRect; objFileWriterHandle: TextFile; function objGetEntity(Index: Integer): TDXFEntity; procedure objSetEntity(Index: Integer; EntityObj: TDXFEntity); procedure objReadPair(var fhandle: TextFile; var pair: TDXFPair); procedure objWritePair(code: integer; val: string); procedure objAdjustBoundingBox; procedure objAdjustBoundingBoxPoint(value: Double; axis: string); public constructor Create; destructor Destroy; property Entities[Index: Integer]: TDXFEntity read objGetEntity write objSetEntity; property BoundingBox: TMyRect read objBoundingBox; published property CurrLayer: string read objCurrLayer write objCurrLayer; procedure Draw(papier: TDrawingObject); procedure LoadFromFile(filePath: string); procedure SaveToFile(filePath: string); function EntityCount: integer; function EntityAdd(entType:string): integer; function EntityAddLine(p1,p2: TMyPoint): integer; function EntityAddCircle(cen: TMyPoint; r: double): integer; function EntityAddArc(cen:TMyPoint; r,a1,a2:double): integer; function EntityAddText(pos:TMyPoint; txt: string; size: double; align: string): integer; function GetAllEntities: string; end; implementation uses uMain, uDebug; { TDXFDrawing } constructor TDXFDrawing.Create; begin inherited Create; objCurrLayer := '0'; objEntities := TObjectList.Create; end; destructor TDXFDrawing.Destroy; begin FreeAndNil(objEntities); inherited Destroy; end; procedure TDXFDrawing.Draw(papier: TDrawingObject); var i: Integer; entita: TDXFEntity; typ: string; p1, p2: TMyPoint; begin //fDebug.LogMessage('DXFDRAWING Draw(); entities:'+inttostr(objEntities.Count)); for i := 0 to objEntities.Count-1 do begin entita := (objEntities[i] as TDXFEntity); typ := entita.GetValueS(0); if typ = 'LINE' then begin p1.X := entita.GetValueF(10); p1.Y := entita.GetValueF(20); p2.X := entita.GetValueF(11); p2.Y := entita.GetValueF(21); papier.Line(p1, p2); end; end; end; procedure TDXFDrawing.objAdjustBoundingBox; var i, j: Integer; ent: TDXFEntity; begin objBoundingBox.TopL.X := 9.9E308; // nekonecno objBoundingBox.BtmR.X := -9.9E308; objBoundingBox.TopL.Y := 9.9E308; objBoundingBox.BtmR.Y := -9.9E308; for i := 0 to objEntities.Count-1 do begin ent := (objEntities[i] as TDXFEntity); if (ent.GetValueS(0) = 'LINE') then begin objAdjustBoundingBoxPoint( ent.GetValueF(10), 'x' ); objAdjustBoundingBoxPoint( ent.GetValueF(20), 'y' ); objAdjustBoundingBoxPoint( ent.GetValueF(11), 'x' ); objAdjustBoundingBoxPoint( ent.GetValueF(21), 'y' ); end else if ((ent.GetValueS(0) = 'ARC') OR (ent.GetValueS(0) = 'CIRCLE'))then begin objAdjustBoundingBoxPoint( ent.GetValueF(10) + ent.GetValueF(40), 'x' ); objAdjustBoundingBoxPoint( ent.GetValueF(10) - ent.GetValueF(40), 'x' ); objAdjustBoundingBoxPoint( ent.GetValueF(20) + ent.GetValueF(40), 'y' ); objAdjustBoundingBoxPoint( ent.GetValueF(20) - ent.GetValueF(40), 'y' ); end else if (ent.GetValueS(0) = 'POLYLINE') then begin for j := 0 to ent.SubEntitiesCount-1 do begin objAdjustBoundingBoxPoint( ent.SubEntities[j].GetValueF(10), 'x' ); objAdjustBoundingBoxPoint( ent.SubEntities[j].GetValueF(20), 'y' ); end; end; end; end; procedure TDXFDrawing.objAdjustBoundingBoxPoint(value: Double; axis: string); begin if (axis = 'x') then begin objBoundingBox.TopL.X := Min( objBoundingBox.TopL.X , value ); objBoundingBox.BtmR.X := Max( objBoundingBox.BtmR.X , value ); end else if (axis = 'y') then begin objBoundingBox.TopL.Y := Min( objBoundingBox.TopL.Y , value ); objBoundingBox.BtmR.Y := Max( objBoundingBox.BtmR.Y , value ); end; end; function TDXFDrawing.objGetEntity(Index: Integer): TDXFEntity; begin result := (objEntities.Items[Index] as TDXFEntity); end; procedure TDXFDrawing.objSetEntity(Index: Integer; EntityObj: TDXFEntity); begin objEntities.Items[Index] := EntityObj; end; procedure TDXFDrawing.objReadPair(var fhandle: TextFile; var pair: TDXFPair); var tmp: string; begin ReadLn(fhandle, tmp); pair.code := StrToInt(tmp); ReadLn(fhandle, pair.val); end; procedure TDXFDrawing.objWritePair(code: integer; val: string); begin Writeln(objFileWriterHandle, Format('%3d', [code])); Writeln(objFileWriterHandle, val); end; function TDXFDrawing.EntityCount: integer; begin result := objEntities.Count; end; function TDXFDrawing.EntityAdd(entType:string): integer; var i: integer; begin // vytvori entitu daneho typu v DXF drawingu a vrati jej novo-prideleny index i := objEntities.Add(TDXFEntity.Create); if entType <> '' then begin Entities[i].SetValue(0, entType); end; result := i; end; function TDXFDrawing.EntityAddLine(p1, p2: TMyPoint): integer; var i: integer; begin // vytvori entitu typu LINE v DXF drawingu a vrati jej novo-prideleny index i := objEntities.Add(TDXFEntity.Create); Entities[i].SetValue(0, 'LINE'); Entities[i].SetValue(8, objCurrLayer); Entities[i].SetValue(10, FloatToStr(p1.X)); Entities[i].SetValue(20, FloatToStr(p1.Y)); Entities[i].SetValue(11, FloatToStr(p2.X)); Entities[i].SetValue(21, FloatToStr(p2.Y)); result := i; end; function TDXFDrawing.EntityAddCircle(cen: TMyPoint; r: double): integer; var i: integer; begin // vytvori entitu typu CIRCLE v DXF drawingu a vrati jej novo-prideleny index i := objEntities.Add(TDXFEntity.Create); Entities[i].SetValue(0, 'CIRCLE'); Entities[i].SetValue(8, objCurrLayer); Entities[i].SetValue(10, FloatToStr(cen.X)); Entities[i].SetValue(20, FloatToStr(cen.Y)); Entities[i].SetValue(40, FloatToStr(r)); result := i; end; function TDXFDrawing.EntityAddArc(cen: TMyPoint; r, a1, a2: double): integer; var i: integer; begin // vytvori entitu typu ARC v DXF drawingu a vrati jej novo-prideleny index i := objEntities.Add(TDXFEntity.Create); Entities[i].SetValue(0, 'ARC'); Entities[i].SetValue(8, objCurrLayer); Entities[i].SetValue(10, FloatToStr(cen.X)); Entities[i].SetValue(20, FloatToStr(cen.Y)); Entities[i].SetValue(40, FloatToStr(r)); Entities[i].SetValue(50, FloatToStr(a1)); // obluk od uhla A1 po A2 v smere CCW Entities[i].SetValue(51, FloatToStr(a2)); result := i; end; function TDXFDrawing.EntityAddText(pos: TMyPoint; txt: string; size: double; align: string): integer; var i: integer; begin // vytvori entitu typu ARC v DXF drawingu a vrati jej novo-prideleny index i := objEntities.Add(TDXFEntity.Create); Entities[i].SetValue(0, 'TEXT'); Entities[i].SetValue(5, IntToStr(i)); // text musi mat v DXF svoje ID Entities[i].SetValue(8, objCurrLayer); Entities[i].SetValue(1, txt); Entities[i].SetValue(10, FloatToStr(pos.X)); Entities[i].SetValue(20, FloatToStr(pos.Y)); Entities[i].SetValue(11, FloatToStr(pos.X)); Entities[i].SetValue(21, FloatToStr(pos.Y)); Entities[i].SetValue(40, FloatToStr(size)); if align = '0' then Entities[i].SetValue(72, '1'); if align = '1' then Entities[i].SetValue(72, '0'); if align = '2' then Entities[i].SetValue(72, '2'); result := i; end; procedure TDXFDrawing.LoadFromFile(filePath: string); var fh: TextFile; pair: TDXFPair; newEnt, lastPolyLine: integer; b: TMyPoint; begin // nacita vsetky (podporovane) entity z DXF suboru objFullPath := filePath; if FileExists(objFullPath) then begin AssignFile(fh, objFullPath); Reset(fh); newEnt := -1; try while not EOF(fh) do begin objReadPair(fh, pair); if (pair.code=2) AND (pair.val='ENTITIES') then begin objReadPair(fh, pair); while pair.val <> 'ENDSEC' do begin if (pair.code=0) AND (pair.val<>'SEQEND') then begin // specialny pripad kodu '0' je koniec Polyline-y (SEQEND) if pair.val = 'POLYLINE' then begin lastPolyLine := EntityAdd(pair.val); newEnt := -1; while not ((pair.code=0) AND (pair.val='VERTEX')) do // prejdeme az k prvemu vertexu polyline-y objReadPair(fh, pair); while not ((pair.code=0) AND (pair.val='SEQEND')) do begin if ((pair.code=0) AND (pair.val='VERTEX')) then begin while not (pair.code=10) do objReadPair(fh, pair); b.X := StrToFloat(pair.val); while not (pair.code=20) do objReadPair(fh, pair); b.Y := StrToFloat(pair.val); Entities[lastPolyLine].SubEntityAddVertex( b, CurrLayer ); end; objReadPair(fh, pair); end; // while end else // if pair.val = 'POLYLINE' newEnt := EntityAdd(pair.val) end else // if pair.code=0 if newEnt > -1 then Entities[newEnt].SetValue(pair.code , pair.val); objReadPair(fh, pair); end; // while end; // if ENTITIES end; finally CloseFile(fh); end; objAdjustBoundingBox; end; end; procedure TDXFDrawing.SaveToFile(filePath: string); var i,j: integer; begin AssignFile(objFileWriterHandle, filePath); Rewrite(objFileWriterHandle); try objWritePair(0, 'SECTION'); objWritePair(2, 'TABLES'); objWritePair(0, 'TABLE'); // *** line types *** objWritePair(2, 'LTYPE'); objWritePair(70, '1'); objWritePair(0, 'LTYPE'); objWritePair(2, 'CONTINUOUS'); objWritePair(70, '0'); objWritePair(3, 'Solid line'); objWritePair(72, '65'); objWritePair(73, '0'); objWritePair(40, '0.0'); objWritePair(0, 'ENDTAB'); objWritePair(0, 'TABLE'); // *** layers *** objWritePair(2, 'LAYER'); objWritePair(70, '5'); // pocet vrstiev objWritePair(0, 'LAYER'); objWritePair(2, 'Panel'); objWritePair(70, '0'); objWritePair(62, '7'); objWritePair(6, 'CONTINUOUS'); objWritePair(0, 'LAYER'); objWritePair(2, 'ThruHoles'); objWritePair(70, '0'); objWritePair(62, '7'); objWritePair(6, 'CONTINUOUS'); objWritePair(0, 'LAYER'); objWritePair(2, 'Threads'); objWritePair(70, '0'); objWritePair(62, '90'); objWritePair(6, 'CONTINUOUS'); objWritePair(0, 'LAYER'); objWritePair(2, 'Pockets'); objWritePair(70, '0'); objWritePair(62, '150'); objWritePair(6, 'CONTINUOUS'); objWritePair(0, 'LAYER'); objWritePair(2, 'Engraving'); objWritePair(70, '0'); objWritePair(62, '30'); objWritePair(6, 'CONTINUOUS'); objWritePair(0, 'ENDTAB'); // end of TABLE - LAYERS objWritePair(0, 'ENDSEC'); // end of SECTION - TABLES objWritePair(0, 'SECTION'); objWritePair(2, 'ENTITIES'); for i := 0 to objEntities.Count - 1 do begin for j := 0 to Entities[i].PairsCount - 1 do begin objWritePair(Entities[i].Pairs[j].code, Entities[i].Pairs[j].val); end; end; objWritePair(0, 'ENDSEC'); // end of ENTITIES objWritePair(0, 'EOF'); finally CloseFile(objFileWriterHandle); end; end; function TDXFDrawing.GetAllEntities: string; var i: integer; begin // len pre potreby debugu for i := 0 to objEntities.Count - 1 do begin result := result + Entities[i].GetValueS(0) + ','; end; end; end.
unit MIRTCompressionSettingsFrm; ////////////////////////////////////////////////////// // // // Description: MIRT JPEG Compression Settings form // // // ////////////////////////////////////////////////////// interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, ComCtrls, ActnList; type TfrmCompressionSettings = class(TForm) actCancel: TAction; actOK: TAction; alActions: TActionList; btnCancel: TButton; btnOK: TButton; lblJPEGCompressionLevel: TLabel; lblJPEGLevel: TLabel; lblJPEGScale: TLabel; pcSettings: TPageControl; tbJPEGCompressionLevel: TTrackBar; tsJPEG: TTabSheet; procedure tbCompressionLevelChange(Sender: TObject); procedure actOKExecute(Sender: TObject); procedure actCancelExecute(Sender: TObject); private { Private declarations } FJPEGCompression: integer; procedure SetJPEGCompression(iJPEGCompression: integer); public { Public declarations } published property JPEGCompression: integer read FJPEGCompression write SetJPEGCompression; end; var frmCompressionSettings: TfrmCompressionSettings; implementation {$R *.dfm} procedure TfrmCompressionSettings.actOKExecute(Sender: TObject); begin ModalResult := mrOK; end; procedure TfrmCompressionSettings.actCancelExecute(Sender: TObject); begin ModalResult := mrCancel; end; procedure TfrmCompressionSettings.SetJPEGCompression( iJPEGCompression: integer); begin FJPEGCompression := iJPEGCompression; tbJPEGCompressionLevel.Position := FJPEGCompression; end; procedure TfrmCompressionSettings.tbCompressionLevelChange( Sender: TObject); begin lblJPEGLevel.Caption := IntToStr(tbJPEGCompressionLevel.Position) + ' %'; FJPEGCompression := tbJPEGCompressionLevel.Position; end; end.
unit eSocial.Models.Entities.Configuracao; interface uses eSocial.Models.Entities.Interfaces, eSocial.Models.Entities.Responsavel, eSocial.Models.DAO.Interfaces; type TConfiguracao = class private [weak] FParent : iModelDAOEntity<TConfiguracao>; FCodigoSIAFI : String; FUnidadeGestoraPrincipal : Integer; FNaturezaJuridica : String; FDataImplantacaoESocial : TDateTime; FResponsavel : IResponsavel<TConfiguracao>; FContador : IResponsavel<TConfiguracao>; FValorSubteto : Currency; FTipoSubteto : String; public constructor Create(aPArent : iModelDAOEntity<TConfiguracao>); destructor Destroy; override; function CodigoSIAFI(Value : String) : TConfiguracao; overload; function CodigoSIAFI : String; overload; function UnidadeGestoraPrincipal(Value : Integer) : TConfiguracao; overload; function UnidadeGestoraPrincipal : Integer; overload; function NaturezaJuridica(Value : String) : TConfiguracao; overload; function NaturezaJuridica : String; overload; function DataImplantacaoESocial(Value : TDateTime) : TConfiguracao; overload; function DataImplantacaoESocial : TDateTime; overload; function Responsavel(Value : IResponsavel<TConfiguracao>) : TConfiguracao; overload; function Responsavel : IResponsavel<TConfiguracao>; overload; function Contador(Value : IResponsavel<TConfiguracao>) : TConfiguracao; overload; function Contador : IResponsavel<TConfiguracao>; overload; function ValorSubteto(Value : Currency) : TConfiguracao; overload; function ValorSubteto : Currency; overload; function TipoSubteto(Value : String) : TConfiguracao; overload; function TipoSubteto : String; overload; function &End : iModelDAOEntity<TConfiguracao>; end; implementation uses System.SysUtils, System.DateUtils; { TConfiguracao } constructor TConfiguracao.Create(aPArent : iModelDAOEntity<TConfiguracao>); begin FParent := aPArent; FCodigoSIAFI := EmptyStr; FUnidadeGestoraPrincipal := 0; FNaturezaJuridica := EmptyStr; FDataImplantacaoESocial := EncodeDate(1899, 12, 30); FResponsavel := TResponsavel<TConfiguracao>.Create(Self); FContador := TResponsavel<TConfiguracao>.Create(Self); FValorSubteto := 0.0; FTipoSubteto := EmptyStr; end; function TConfiguracao.&End: iModelDAOEntity<TConfiguracao>; begin Result := FParent; end; function TConfiguracao.CodigoSIAFI: String; begin Result := FCodigoSIAFI; end; function TConfiguracao.CodigoSIAFI(Value: String): TConfiguracao; begin Result := Self; FCodigoSIAFI := Value.Trim; end; function TConfiguracao.Contador(Value: IResponsavel<TConfiguracao>): TConfiguracao; begin Result := Self; FContador := Value; end; function TConfiguracao.Contador: IResponsavel<TConfiguracao>; begin Result := FContador; end; function TConfiguracao.DataImplantacaoESocial(Value: TDateTime): TConfiguracao; begin Result := Self; FDataImplantacaoESocial := Value; end; function TConfiguracao.DataImplantacaoESocial: TDateTime; begin Result := FDataImplantacaoESocial; end; destructor TConfiguracao.Destroy; begin inherited; end; function TConfiguracao.NaturezaJuridica: String; begin Result := FNaturezaJuridica; end; function TConfiguracao.NaturezaJuridica(Value: String): TConfiguracao; begin Result := Self; FNaturezaJuridica := Value.Trim; end; function TConfiguracao.Responsavel: IResponsavel<TConfiguracao>; begin Result := FResponsavel; end; function TConfiguracao.TipoSubteto: String; begin Result := FTipoSubteto; end; function TConfiguracao.TipoSubteto(Value: String): TConfiguracao; begin Result := Self; FTipoSubteto := Value.Trim; end; function TConfiguracao.Responsavel(Value: IResponsavel<TConfiguracao>): TConfiguracao; begin Result := Self; FResponsavel := Value; end; function TConfiguracao.UnidadeGestoraPrincipal(Value: Integer): TConfiguracao; begin Result := Self; FUnidadeGestoraPrincipal := Value; end; function TConfiguracao.UnidadeGestoraPrincipal: Integer; begin Result := FUnidadeGestoraPrincipal; end; function TConfiguracao.ValorSubteto: Currency; begin Result := FValorSubteto; end; function TConfiguracao.ValorSubteto(Value: Currency): TConfiguracao; begin Result := Self; FValorSubteto := Value; end; end.
unit bool; interface uses structs; function bitcount(x:int32): Integer; function LSB(x: int32): Integer; implementation var LSBarray : array [0..255] of Byte; MSBarray : array [0..255] of Byte; bitsinbyte : array [0..255] of Byte; function recbitcount(n: int32): Integer; // counts & returns the number of bits which are set in a 32-bit integer // slower than a table-based bitcount if many bits are // set. used to make the table for the table-based bitcount on initialization var r :Integer; begin r := 0; while (n <> 0) do begin n := n and (n-1); Inc (r); end; Result := r; end; function bitcount(x:int32): Integer; // table-lookup bitcount // returns the number of bits set in the 32-bit integer x begin Result := (bitsinbyte[x and $FF] + bitsinbyte[(x shr 8)and $FF] + bitsinbyte[(x shr 16) and $FF] + bitsinbyte[(x shr 24)and $FF]); end; function LSB(x: int32): Integer; begin //----------------------------------------------------------------------------------------------------- // returns the position of the least significant bit in a 32-bit word x // or -1 if not found, if x=0. //----------------------------------------------------------------------------------------------------- if (x and $000000FF <> 0) then begin Result :=(LSBarray[x and $000000FF]); Exit; end; if (x and $0000FF00 <> 0) then begin Result :=(LSBarray[(x shr 8) and $000000FF]+8); Exit; end; if (x and $00FF0000 <> 0) then begin Result :=(LSBarray[(x shr 16) and $000000FF]+16); Exit; end; if (x and $FF000000 <> 0) then begin Result :=(LSBarray[(x shr 24) and $000000FF]+24); Exit; end; Result := -1; end; function MSB(x: int32): Integer; begin //----------------------------------------------------------------------------------------------------- // returns the position of the most significant bit in a 32-bit word x // or -1 if not found, if x=0. //----------------------------------------------------------------------------------------------------- if (x and $FF000000 <> 0) then begin Result :=(MSBarray[(x shr 24) and $FF]+24); Exit; end; if (x and $00FF0000 <> 0) then begin Result :=(MSBarray[(x shr 16) and $FF]+16); Exit; end; if (x and $0000FF00 <> 0) then begin Result :=(MSBarray[(x shr 8) and $FF]+8); Exit; end; Result :=(MSBarray[x and $FF]); //if x==0 return MSBarray[0], that's ok. end; procedure initbool; var i,j: Integer; begin // the boolean functions here are based on array lookups. initbool initializes these arrays. // init MSB for i := 0 to 255 do begin MSBarray[i] := 0; for j := 0 to 7 do begin if (i and (1 shl j)) <> 0 then MSBarray[i] := j; end; end; // init LSB for i := 0 to 255 do begin LSBarray[i] := 0; for j := 7 downto 0 do begin if (i and (1 shl j)) <> 0 then LSBarray[i] := j; end; end; // init bitcount for i := 0 to 255 do begin bitsinbyte[i] := recbitcount(i); end; end; initialization initbool; end.
unit lib_sincronizacao; interface uses IdHTTP, SysUtils, Windows, Classes, Variants, Dialogs, XMLDoc, XMLIntf, DateUtils, lib_db, DB, DBClient, IdURI, IdCookie; type TStatusAtualizacao = (saSucesso, saError); TSincronizacaoBase = class(TObject) protected FUrlToGetXML: string; FUrlToSendXML: string; FUrlBase: string; FModulo: string; Fmodel: string; FTabelaLocal : string; FCamposWebLocal : TListaMapaValor; FChavesTabela : string; FDataUltimaSinc: TDateTime; function VariantValueToStr(const value: Variant): String; protected procedure PreencheDataUltimaSinc; function GetUrlParametersLogin : String; public constructor create(const model, module: string; const CamposWebLocal: TListaMapaValor; const ChavesTabela: string; const TabelaLocal: string = ''); virtual; end; TSincronizacao = class(TSincronizacaoBase) private FCondicoesParaBaixar: String; function GetXMLText(FieldsSeparetedByPipe : String = ''): string; function CheckNodeValue(const field : IXMLNode): OleVariant; public property FiltroDownload: string read FCondicoesParaBaixar write FCondicoesParaBaixar; procedure GetWebData; virtual; constructor create(const model, module: string; const CamposWebLocal: TListaMapaValor; const ChavesTabela: string; const TabelaLocal: string = ''); override; end; TUpload = class(TSincronizacaoBase) private FCdsConfUpload: TClientDataSet; FCdsModels: TClientDataSet; FResponse: string; procedure ConfigurarCdsConfUpload; procedure AddRegistroMapa(Model, Module, CampoWeb, CampoLocal, TabelaLocal, ModelPai, NomeCampoPai, ChaveModelWeb, ValorFixo: String); procedure AddMapaTabelaPrincipal; procedure FilterCds(cds: TClientDataSet; const Filtro: String); function GetJsonParcial(const Model, ModelPai, Module: string; const ValorCampoPai: Variant): string; function GetURLUpload: String; function GetResponseError: String; procedure SetIdWeb; protected procedure ExecuteQuery(qry: TObjetoDB);virtual; public procedure AddModelFilho(const Model, Module, ChavesTabela, TabelaLocal, ModelPai: string; const CamposWebLocal: TListaMapaValor; const NomeCampoTabelaPai: string = 'id'); procedure SendData; constructor create(const model, module: string; const CamposWebLocal: TListaMapaValor; const ChavesTabela: string; const TabelaLocal: string = ''); override; destructor destroy; override; end; TTipoSincronizacao = (tsUpload, tsDownload); TMapeamento = class(TObject) private FTipoSincronizacao: TTipoSincronizacao; FEmpresa: Integer; FUnidade: Integer; FAlmoxarifado: Integer; public procedure AddEmpresaUpload(mapa: TListaMapaValor); procedure AddUnidadeUpload(mapa: TListaMapaValor); procedure AddAlmoxarifadoUpload(mapa: TListaMapaValor); function MapaPais: TListaMapaValor; function MapaEstado: TListaMapaValor; function MapaCidade: TListaMapaValor; function MapaBairro: TListaMapaValor; function MapaCliente: TListaMapaValor; function MapaFornecedor: TListaMapaValor; function MapaUnidadeMedida: TListaMapaValor; function MapaProduto: TListaMapaValor; function MapaFinalidade: TListaMapaValor; function MapaEntrada: TListaMapaValor; function MapaSaida: TListaMapaValor; function MapaItemProduto: TListaMapaValor; function MapaLote: TListaMapaValor; function MapaPosEstoque: TListaMapaValor; function MapaAgrupAdicional: TListaMapaValor; function MapaCategoria: TListaMapaValor; function MapaComposicaoProd: TListaMapaValor; function MapaItemCategoria: TListaMapaValor; function MapaItAgrupAdicional: TListaMapaValor; function MapaMesa: TListaMapaValor; function MapaAdicionais: TListaMapaValor; function MapaPedido: TListaMapaValor; function MapaItempedido: TListaMapaValor; function MapaItAdicional: TListaMapaValor; function MapaAberfechcaixa: TListaMapaValor; function MapaMovCaixa: TListaMapaValor; function MapaFuncionario: TListaMapaValor; function MapaCartaoBandeira: TListaMapaValor; constructor create(const TipoSincroniacao: TTipoSincronizacao; const Empresa, Unidade, Almoxarifado: Integer); end; TSincronizarTabelas = class public class function Sincronizado : Boolean; class procedure GravarDataSincronizacao(const Data: TDateTime; const Status: TStatusAtualizacao; const Log : string); class function Download(const Empresa, Unidade, Almoxarifado: Integer): String; class function Upload(const Empresa, Unidade, Almoxarifado: Integer): string; class function Sincronizar(const SincronizacaoForcada: Boolean): String; end; implementation uses StrUtils, lib_tratamentos_sincronizacao, uDmConexao; const SENHA_VMSIS = 'masterVMSIS123v'; USUARIO_VMSIS = 'vmsismaster'; URL_PARCIAL_GET_XML = '/getmodelasxml/'; URL_PARCIAL_SEND_XML = '/savejsonasmodel/'; NOME_CHAVE_PADRAO_FK = '[[*****{{FIELD_CONSIDER_FOREIGN_KEY}}****]]'; { TSincronizacao } constructor Tsincronizacao.create(const model, module: string; const CamposWebLocal: TListaMapaValor; const ChavesTabela: string; const TabelaLocal: string = ''); begin inherited; FCondicoesParaBaixar:= EmptyStr; end; function TSincronizacao.GetXMLText(FieldsSeparetedByPipe : string): string; var XML : string; url_param : string; http : TIdHTTP; begin http := TIdHTTP.Create(nil); try url_param := FUrlToGetXML + Format('?model=%s&module=%s&DataInicial=%s%s', [Fmodel, FModulo, VariantValueToStr(FDataUltimaSinc) ,GetUrlParametersLogin]); if FieldsSeparetedByPipe <> EmptyStr then url_param := url_param + '&fields=' + FieldsSeparetedByPipe; if FCondicoesParaBaixar <> EmptyStr then url_param := url_param + '&filter=' + FCondicoesParaBaixar; XML := http.Get(url_param); if Copy(XML, 1, 5) <> '<?xml' then Result := EmptyStr else Result := XML; finally if Assigned(http) then FreeAndnil(http) end; end; procedure TSincronizacao.GetWebData; var bd, bd_fk: TObjetoDB; i, k, j: Integer; doc: IXMLDocument; row, field: IXMLNode; campos, campo_atual, campo_fk, valor_adicional: string; lista_camposChave: TStringList; add_to_ignore, validar_chave : Boolean; begin bd:= TObjetoDB.create(FTabelaLocal); doc:= TXMLDocument.Create(nil); lista_camposChave:= TStringList.Create; try validar_chave:= True; lista_camposChave.Delimiter:= '|'; lista_camposChave.DelimitedText:= FChavesTabela; campos := ''; for i:= 0 to FCamposWebLocal.Count - 1 do begin if FCamposWebLocal.GetKey(i) <> EmptyStr then campos := campos + FCamposWebLocal.GetKey(i) + '|' else begin bd.AddParametro(FCamposWebLocal.GetValue(i), FCamposWebLocal.GetAdicional(i)); end; end; if campos <> EmptyStr then begin campos := Copy(campos, 1, Length(campos) - 1); end; doc.XML.Text:= GetXMLText(campos); doc.Active:= True; for i:= 0 to doc.ChildNodes.Nodes['django-objects'].ChildNodes.Count - 1 do begin row:= doc.ChildNodes.Nodes['django-objects'].ChildNodes[i]; bd.ClearIgnoreParam; for k:= 0 to row.ChildNodes.Count -1 do begin field:= row.ChildNodes[k]; campo_atual:= FCamposWebLocal.GetValue(VarToStr(field.Attributes['name'])); valor_adicional := FCamposWebLocal.GetAdicional(VarToStr(field.Attributes['name'])); if valor_adicional <> EmptyStr then begin bd.AddParametro(campo_atual, valor_adicional); end else begin if field.HasAttribute('to') then begin campo_fk:= varToStr(field.Attributes['to']); campo_fk:= ReverseString(campo_fk); campo_fk:= copy(campo_fk, 1, pos('.', campo_fk)-1); campo_fk:= ReverseString(campo_fk); bd_fk := TObjetoDB.create(campo_fk); try bd_fk.AddParametro('id_web', CheckNodeValue(field)); bd_fk.Select(['id']); bd.AddParametro(campo_atual, bd_fk.GetVal('id')); finally FreeAndNil(bd_fk); end; end else begin bd.AddParametro(campo_atual, CheckNodeValue(field)); end; end; if validar_chave then begin for j:= 0 to lista_camposChave.Count - 1 do begin if Pos(campo_atual + ',', lista_camposChave[0] + ',') = 0 then begin add_to_ignore:= True end else begin if campo_atual = lista_camposChave[0] then begin bd.Select(['*']); validar_chave:= bd.IsEmpty; if not validar_chave then break; end else begin add_to_ignore:= False; end; end end; end; if add_to_ignore then bd.AddIgnoreParam(campo_atual) end; bd.AddParametro('id_web', row.Attributes['pk']); if Pos('pk,', FChavesTabela) = 0 then bd.AddIgnoreParam('id_web'); if validar_chave then bd.Select(['id']); if not bd.IsEmpty then begin bd.SetParamsToNewValueUp(False); bd.Update; end else begin bd.ClearIgnoreParam; bd.Insert; end; end; finally FreeAndNil(bd); end; end; function TSincronizacao.CheckNodeValue(const field: IXMLNode): OleVariant; var field_type : string; value : Variant; const C_BOOLEAN_FIELD = 'BooleanField'; begin field_type := VarToStr(field.Attributes['type']); try value := field.NodeValue except Result := Null; Exit; end; if field_type = C_BOOLEAN_FIELD then begin if value = 'True' then Result := 1 else Result := 0 end else Result := value; end; procedure TUpload.AddMapaTabelaPrincipal; var i: Integer; ValorAdicional: string; begin for i:= 0 to FCamposWebLocal.Count - 1 do begin ValorAdicional:= FCamposWebLocal.GetAdicional(i); if ValorAdicional = NOME_CHAVE_PADRAO_FK then ValorAdicionaL:= EmptyStr; AddRegistroMapa(Fmodel, FModulo, FCamposWebLocal.GetKey(i), FCamposWebLocal.GetValue(i), FTabelaLocal, EmptyStr, EmptyStr, FChavesTabela, ValorAdicional); end; end; procedure TUpload.AddModelFilho(const Model, Module, ChavesTabela, TabelaLocal, ModelPai: string; const CamposWebLocal: TListaMapaValor; const NomeCampoTabelaPai: string = 'id'); var i: Integer; ValorAdicional: string; begin for i:= 0 to CamposWebLocal.Count - 1 do begin ValorAdicional:= CamposWebLocal.GetAdicional(i); if ValorAdicional = NOME_CHAVE_PADRAO_FK then begin AddRegistroMapa(Model, Module, CamposWebLocal.GetKey(i), CamposWebLocal.GetValue(i), TabelaLocal, ModelPai, NomeCampoTabelaPai, ChavesTabela, EmptyStr); end else begin AddRegistroMapa(Model, Module, CamposWebLocal.GetKey(i), CamposWebLocal.GetValue(i), TabelaLocal, ModelPai, EmptyStr, ChavesTabela, ValorAdicional); end; end; end; procedure TUpload.AddRegistroMapa(Model, Module, CampoWeb, CampoLocal, TabelaLocal, ModelPai, NomeCampoPai, ChaveModelWeb, ValorFixo: String); function AsteriscoSeVazio(Valor: String): string; begin Result:= IfThen(Valor = EmptyStr, '*', Valor); end; begin FCdsConfUpload.Insert; FCdsConfUpload.FieldByName('Model').AsString:= AsteriscoSeVazio(Model); FCdsConfUpload.FieldByName('Module').AsString:= AsteriscoSeVazio(Module); FCdsConfUpload.FieldByName('CampoWeb').AsString:= AsteriscoSeVazio(CampoWeb); FCdsConfUpload.FieldByName('CampoLocal').AsString:= AsteriscoSeVazio(CampoLocal); FCdsConfUpload.FieldByName('ModelPai').AsString:= AsteriscoSeVazio(ModelPai); FCdsConfUpload.FieldByName('NomeCampoPai').AsString:= AsteriscoSeVazio(NomeCampoPai); FCdsConfUpload.FieldByName('TabelaLocal').AsString:= AsteriscoSeVazio(TabelaLocal); FCdsConfUpload.FieldByName('ValorFixo').AsString:= ValorFixo; FCdsConfUpload.Post; if not FCdsModels.Locate('Model', VarArrayOf([Model]), [loCaseInsensitive]) then begin FCdsModels.Insert; FCdsModels.FieldByName('Model').AsString:= AsteriscoSeVazio(Model); FCdsModels.FieldByName('Module').AsString:= AsteriscoSeVazio(Module); FCdsModels.FieldByName('TabelaLocal').AsString:= AsteriscoSeVazio(TabelaLocal); FCdsModels.FieldByName('ModelPai').AsString:= AsteriscoSeVazio(ModelPai); FCdsModels.FieldByName('ChavesTabelaWeb').AsString:= ChaveModelWeb; FCdsModels.Post; end; end; procedure TUpload.ConfigurarCdsConfUpload; begin if not Assigned(FCdsConfUpload) then begin FCdsConfUpload:= TClientDataSet.Create(nil); FCdsConfUpload.FieldDefs.Add('Sequencial', ftAutoInc); FCdsConfUpload.FieldDefs.Add('Model', ftString, 100); FCdsConfUpload.FieldDefs.Add('Module', ftString, 300); FCdsConfUpload.FieldDefs.Add('CampoWeb', ftString, 100); FCdsConfUpload.FieldDefs.Add('CampoLocal', ftString, 100); FCdsConfUpload.FieldDefs.Add('ModelPai', ftString, 100); FCdsConfUpload.FieldDefs.Add('NomeCampoPai', ftString, 100); FCdsConfUpload.FieldDefs.Add('TabelaLocal', ftString, 100); FCdsConfUpload.FieldDefs.Add('ValorFixo', ftString, 300); FCdsConfUpload.CreateDataSet; end; FCdsConfUpload.IndexFieldNames:= 'Sequencial'; if not Assigned(FCdsModels) then begin FCdsModels:= TClientDataSet.Create(nil); FCdsModels.FieldDefs.Add('Sequencial', ftAutoInc); FCdsModels.FieldDefs.Add('Model', ftString, 100); FCdsModels.FieldDefs.Add('Module', ftString, 300); FCdsModels.FieldDefs.Add('TabelaLocal', ftString, 100); FCdsModels.FieldDefs.Add('ModelPai', ftString, 100); FCdsModels.FieldDefs.Add('ChavesTabelaWeb', ftString, 255); FCdsModels.CreateDataSet; end; FCdsModels.IndexFieldNames:= 'Sequencial'; end; { TSincronizarTabelas } class function TSincronizarTabelas.Download(const Empresa, Unidade, Almoxarifado: Integer): String; var sinc : TSincronizacao; map : TListaMapaValor; mapaCampos: TMapeamento; begin dmConexao.adoConexaoBd.BeginTrans; mapaCampos:= TMapeamento.create(tsDownload, Empresa, Unidade, Almoxarifado); try try //pais map:= mapaCampos.MapaPais; sinc := TSincronizacao.create('pais', 'cadastro.localidades.pais.models', map, 'cdpais', 'pais'); sinc.FiltroDownload:= format('{"empresa":"%d"}', [Empresa]); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); //estado map:= mapaCampos.MapaEstado; sinc := TSincronizacao.create('estado', 'cadastro.localidades.estado.models', map, 'cdestado|sgestado', 'estado'); sinc.FiltroDownload:= format('{"empresa":"%d"}', [Empresa]); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); //cidade map := mapaCampos.MapaCidade; sinc := TSincronizacao.create('cidade', 'cadastro.localidades.cidade.models', map, 'cdcidade', 'cidade'); sinc.FiltroDownload:= format('{"empresa":"%d"}', [Empresa]); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); //bairro map := mapaCampos.MapaBairro; sinc := TSincronizacao.create('bairro', 'cadastro.localidades.bairro.models', map, 'cdbairro', 'bairro'); sinc.FiltroDownload:= format('{"empresa":"%d"}', [Empresa]); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); //funcionario map:= mapaCampos.MapaFuncionario; sinc:= TSincronizacao.create('Funcionario', 'cadastro.funcionario.models', map, 'usuario'); sinc.FiltroDownload:= Format('{"unidade":"%d"}', [Unidade]); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); //cliente map := mapaCampos.MapaCliente; sinc := TSincronizacao.create('cliente', 'cadastro.cliente.models', map, 'telcel', 'cliente'); sinc.FiltroDownload:= format('{"empresa":"%d"}', [Empresa]); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); //fornecedor map := mapaCampos.MapaFornecedor; sinc := TSincronizacao.create('fornecedor', 'cadastro.fornecedor.models', map, 'telcel', 'fornecedor'); sinc.FiltroDownload:= format('{"empresa":"%d"}', [Empresa]); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); //unimedida map := mapaCampos.MapaUnidadeMedida; sinc := TSincronizacao.create('unimedida', 'cadastro.unimedida.models', map, 'nmmedida', 'unimedida'); sinc.FiltroDownload:= format('{"empresa":"%d"}', [Empresa]); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); //produto map := mapaCampos.MapaProduto; sinc := TSincronizacao.create('produto', 'cadastro.produto.models', map, 'pk', 'produto'); sinc.FiltroDownload:= format('{"empresa":"%d"}', [Empresa]); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); //finalidade map := mapaCampos.MapaFinalidade; sinc := TSincronizacao.create('finalidade', 'estoque.cadastro_estoque.finalidade.models', map, 'descricao', 'finalidade'); sinc.FiltroDownload:= format('{"empresa":"%d"}', [Empresa]); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); //entrada - estoque() map := mapaCampos.MapaEntrada; sinc := TSincronizacao.create('Entrada', 'estoque.entrada.models', map, 'pk', 'Entrada'); sinc.FiltroDownload:= format('{"unidade_id":"%d"}', [Unidade]); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); //saida map := mapaCampos.MapaSaida; sinc := TSincronizacao.create('Saida', 'estoque.saida.models', map, 'pk', 'Saida'); sinc.FiltroDownload:= format('{"unidade_id":"%d"}', [Unidade]); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); //itemproduto map := mapaCampos.MapaItemProduto; sinc := TSincronizacao.create('Itemproduto', 'estoque.itemproduto.models', map, 'pk', 'Itemproduto'); sinc.FiltroDownload:= format('{"almoxarifado_id":"%d"}', [Almoxarifado]); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); TTratamentos.PreencherIdEntradaSaidaItemProduto; //lote map := mapaCampos.MapaLote; sinc := TSincronizacao.create('Lote', 'estoque.lote.models', map, 'pk', 'Lote'); sinc.FiltroDownload:= format('{"unidade_id":"%d"}', [Unidade]); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); //posestoque map := mapaCampos.MapaPosEstoque; sinc := TSincronizacao.create('posestoque', 'estoque.posestoque.models', map, 'pk', 'posestoque'); sinc.FiltroDownload:= format('{"almoxarifado_id":"%d"}', [Almoxarifado]); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); //AgrupAdicional map := mapaCampos.MapaAgrupAdicional; sinc := TSincronizacao.create('AgrupAdicional', 'pedido.cadastro_pedido.agrupadicional.models', map, 'pk', 'AgrupAdicional'); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); //Categoria map := mapaCampos.MapaCategoria; sinc := TSincronizacao.create('categoria', 'pedido.cadastro_pedido.categoria.models', map, 'pk', 'categoria'); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); //ComposicaoProd map := mapaCampos.MapaComposicaoProd; sinc := TSincronizacao.create('ComposicaoProd', 'pedido.cadastro_pedido.composicaoproduto.models', map, 'pk', 'ComposicaoProd'); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); //ItemCategoria map := mapaCampos.MapaItemCategoria; sinc := TSincronizacao.create('ItemCategoria', 'pedido.cadastro_pedido.itemcategoria.models', map, 'pk', 'ItemCategoria'); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); //itagrupadicional map := mapaCampos.MapaItAgrupAdicional; sinc := TSincronizacao.create('itagrupadicional', 'pedido.cadastro_pedido.itemcategoria.models', map, 'pk', 'itagrupadicional'); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); //mesa map := mapaCampos.MapaMesa; sinc := TSincronizacao.create('Mesa', 'pedido.cadastro_pedido.mesa.models', map, 'nmmesa', 'Mesa'); sinc.FiltroDownload:= format('{"unidade_id":"%d"}', [Unidade]); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); //adicionais map := mapaCampos.MapaAdicionais; sinc := TSincronizacao.create('Adicionais', 'pedido.cadastro_pedido.agrupadicional.models', map, 'pk', 'Adicionais'); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); //cartao_bandeira map:= mapaCampos.MapaCartaoBandeira; sinc := TSincronizacao.create('Cartao_Bandeira', 'financeiro.cartao_bandeira.models', map, 'pk', 'Cartao_Bandeira'); sinc.GetWebData; FreeAndNil(sinc); FreeAndNil(map); dmConexao.adoConexaoBd.CommitTrans; except on E:Exception do begin dmConexao.adoConexaoBd.RollbackTrans; Result:= E.Message; end; end; finally if Assigned(sinc) then FreeAndNil(sinc); if Assigned(map) then FreeAndNil(map); end; end; class procedure TSincronizarTabelas.GravarDataSincronizacao( const Data: TDateTime; const Status: TStatusAtualizacao; const Log : string); var bd: TObjetoDB; begin bd:= TObjetoDB.create('CotroleSincronizacao'); try bd.AddParametro('dtsincronizacao', Data); case Status of saSucesso: bd.AddParametro('Status', 'S'); saError: bd.AddParametro('Status', 'E'); end; bd.AddParametro('Log', Log); bd.Insert; finally FreeAndNil(bd); end; end; class function TSincronizarTabelas.Sincronizado: Boolean; var bdDtSinc: TObjetoDB; bdParamSinc: TObjetoDB; diferencaMinutos : Integer; minutosParaIntervalo: Integer; begin Result:= True; bdDtSinc:= TObjetoDB.create('CotroleSincronizacao'); bdParamSinc:= TObjetoDB.create('ParametrosSincronizacao'); try bdDtSinc.AddParametro('Status', 'S'); bdDtSinc.Select(['IFNULL(MAX(dtsincronizacao), DATE_ADD(CURRENT_TIMESTAMP, INTERVAL -1000 YEAR)) AS Data']); bdParamSinc.Select(['IntervaloHora', 'IntervaloMinuto']); if bdParamSinc.IsEmpty then begin Result:= False; Exit; end; diferencaMinutos:= MinutesBetween(bdDtSinc.GetVal('Data'), now); minutosParaIntervalo:= (bdParamSinc.GetVal('IntervaloHora') * 60) + bdParamSinc.GetVal('IntervaloMinuto'); if diferencaMinutos >= minutosParaIntervalo then Result:= False; finally FreeAndNil(bdDtSinc); FreeAndNil(bdParamSinc); end; end; class function TSincronizarTabelas.Sincronizar(const SincronizacaoForcada: Boolean): String; var Empresa, Unidade, Almoxarifado: Integer; DataInicio : TDateTime; dbBuscaParametros : TObjetoDB; begin Result:= EmptyStr; if (Sincronizado) and (not SincronizacaoForcada) then Exit; dbBuscaParametros:= TObjetoDB.create('empresa'); try dbBuscaParametros.Select(['id']); Empresa:= dbBuscaParametros.GetVal('id') finally FreeAndNil(dbBuscaParametros); end; dbBuscaParametros:= TObjetoDB.create('unidade'); try dbBuscaParametros.Select(['id']); Unidade:= dbBuscaParametros.GetVal('id') finally FreeAndNil(dbBuscaParametros); end; dbBuscaParametros:= TObjetoDB.create('Almoxarifado'); try dbBuscaParametros.Select(['id']); Almoxarifado:= dbBuscaParametros.GetVal('id'); finally FreeAndNil(dbBuscaParametros); end; DataInicio:= Now; Result := Download(Empresa, Unidade, Almoxarifado); if Result <> EmptyStr then begin GravarDataSincronizacao(DataInicio, saError, Result); Exit; end; Result:= Upload(Empresa, Unidade, Almoxarifado); if Result <> EmptyStr then begin GravarDataSincronizacao(DataInicio, saError, Result); Exit; end; GravarDataSincronizacao(DataInicio, saSucesso, EmptyStr); end; class function TSincronizarTabelas.Upload(const Empresa, Unidade, Almoxarifado: Integer): string; var upload: TUpload; mapaCampos: TMapeamento; map, mapItemProduto, mapItemPedido, mapItAdicional: TListaMapaValor; begin Result:= EmptyStr; mapaCampos:= TMapeamento.create(tsUpload, Empresa, Unidade, Almoxarifado); dmConexao.adoConexaoBd.BeginTrans; try try map:= mapaCampos.MapaPais; upload:= TUpload.create('Pais', 'cadastro.localidade.pais.models', map, 'cdpais'); upload.SendData; map:= mapaCampos.MapaEstado; FreeAndNil(upload); upload:= TUpload.create('Estado', 'cadastro.localidade.estado.models', map, 'sgestado|cdestado'); upload.SendData; map:= mapaCampos.MapaCidade; FreeAndNil(upload); upload:= TUpload.create('Cidade', 'cadastro.localidade.cidade.models', map, 'cdcidade'); upload.SendData; map:= mapaCampos.MapaBairro; FreeAndNil(upload); upload:= TUpload.create('Bairro', 'cadastro.localidade.bairro.models', map, 'cdbairro'); upload.SendData; FreeAndNil(upload); map:= mapaCampos.MapaCliente; upload:= TUpload.create('Cliente', 'cadastro.cliente.models', map, 'telcel'); upload.SendData; FreeAndNil(upload); map:= mapaCampos.MapaFornecedor; upload:= TUpload.create('Fornecedor', 'cadastro.fornecedor.models', map, 'nrinscjurd'); upload.SendData; FreeAndNil(upload); map:= mapaCampos.MapaEntrada; upload:= TUpload.create('Entrada', 'estoque.entrada.models', map, 'id_desktop'); mapItemProduto:= mapaCampos.MapaItemProduto; mapItemProduto.Add('master_moviest', 'entrada_id', NOME_CHAVE_PADRAO_FK); upload.AddModelFilho('Itemproduto', 'estoque.itemproduto.models', 'id_desktop', 'Itemproduto', 'Entrada', mapItemProduto); upload.SendData; FreeAndNil(upload); map:= mapaCampos.MapaSaida; upload:= TUpload.create('Saida', 'estoque.saida.models', map, 'id_desktop'); mapItemProduto:= mapaCampos.MapaItemProduto; mapItemProduto.Add('master_moviest', 'saida_id', NOME_CHAVE_PADRAO_FK); upload.AddModelFilho('Itemproduto', 'estoque.itemproduto.models', 'id_desktop', 'Itemproduto', 'Entrada', mapItemProduto); upload.SendData; { FreeAndNil(upload); map:= mapaCampos.MapaPosEstoque; upload:= TUpload.create('Posestoque', 'estoque.posestoque.models', map, 'id_desktop'); upload.SendData;} FreeAndNil(upload); map:= mapaCampos.MapaPedido; upload:= TUpload.create('Pedido', 'pedido.frentecaixa.models', map, 'id_desktop'); mapItemPedido:= mapaCampos.MapaItempedido; upload.AddModelFilho('ItemPedido', 'pedido.frentecaixa.models', 'id_desktop', 'ItemPedido', 'Pedido', mapItemPedido); mapItAdicional:= mapaCampos.MapaItAdicional; upload.AddModelFilho('ItAdicional', 'pedido.frentecaixa.models', 'id_desktop', 'ItAdicional', 'ItemPedido', mapItAdicional); upload.SendData; FreeAndNil(upload); map:= mapaCampos.MapaAberfechcaixa; upload:= TUpload.create('AberFechCaixa', 'pedido.aberfechcaixa.models', map, 'id_desktop'); upload.SendData; FreeAndNil(upload); map:= mapaCampos.MapaMovCaixa; upload:= TUpload.create('MovCaixa', 'pedido.movcaixa.models', map, 'id_desktop'); upload.SendData; dmConexao.adoConexaoBd.CommitTrans; except on E:Exception do begin dmConexao.adoConexaoBd.RollbackTrans; Result:= E.Message; end; end; finally if Assigned(upload) then FreeAndNil(upload); if Assigned(mapItemProduto) then FreeAndNil(mapItemProduto); if Assigned(mapaCampos) then FreeAndNil(mapaCampos); if Assigned(mapItemPedido) then FreeAndNil(mapItemPedido); if Assigned(mapItAdicional) then FreeAndNil(mapItAdicional); end; end; { TSincronizacaoBase } constructor TSincronizacaoBase.create(const model, module: string; const CamposWebLocal: TListaMapaValor; const ChavesTabela: string; const TabelaLocal: string = ''); var bdSinc: TObjetoDB; begin bdSinc:= TObjetoDB.create('ParametrosSincronizacao'); FUrlBase:= ''; try bdSinc.Select(['IpSincronizacao']); FUrlBase:= bdSinc.GetVal('IpSincronizacao'); finally FreeAndNil(bdSinc); end; FUrlToGetXML:= FUrlBase + URL_PARCIAL_GET_XML; FUrlToSendXML:= FUrlBase + URL_PARCIAL_SEND_XML; Fmodel:= model; FModulo:= module; if TabelaLocal = EmptyStr then FTabelaLocal:= Fmodel else FTabelaLocal:= TabelaLocal; FChavesTabela:= ChavesTabela + ','; FCamposWebLocal:= CamposWebLocal; PreencheDataUltimaSinc; end; constructor TUpload.create(const model, module: string; const CamposWebLocal: TListaMapaValor; const ChavesTabela: string; const TabelaLocal: string = ''); begin inherited; ConfigurarCdsConfUpload; AddMapaTabelaPrincipal; end; destructor TUpload.destroy; begin FreeAndNil(FCdsConfUpload); inherited; end; procedure TUpload.FilterCds(cds: TClientDataSet; const Filtro: String); begin cds.Filtered:= False; cds.Filter:= Filtro; cds.Filtered:= True; end; function TUpload.GetURLUpload: String; begin Result:= FUrlToSendXML + '?data={' + GetJsonParcial(Fmodel, EmptyStr, FModulo, Null) + '}'; end; function TUpload.GetJsonParcial(const Model, ModelPai, Module: string; const ValorCampoPai: Variant): string; var cdsPaiTemp, cdsFilhosTemp, cdsFiltro: TClientDataSet; dbGetValores: TObjetoDB; tabelaLocal, json: string; begin cdsPaiTemp:= TClientDataSet.Create(nil); cdsFilhosTemp:= TClientDataSet.Create(nil); cdsFiltro:= TClientDataSet.Create(nil); try cdsPaiTemp.Data:= FCdsModels.Data; cdsFiltro.Data:= FCdsConfUpload.Data; FilterCds(cdsPaiTemp, 'Model = ' + QuotedStr(Model)); tabelaLocal:= cdsPaiTemp.FieldByName('TabelaLocal').AsString; if Assigned(dbGetValores) then FreeAndNil(dbGetValores); dbGetValores:= TObjetoDB.create(tabelaLocal); json:= '"model":"' + Model + '","module":"' + Module + '", "chaves":"' + cdsPaiTemp.FieldByName('ChavesTabelaWeb').AsString + '",'; if ModelPai <> EmptyStr then begin FilterCds(cdsFiltro, 'Model = ' + QuotedStr(Model) + ' and NomeCampoPai <> ' + QuotedStr('*')); json:= json + '"parent_field":"' + cdsFiltro.FieldByName('CampoWeb').AsString + '",'; dbGetValores.AddParametro(cdsFiltro.FieldByName('NomeCampoPai').AsString, ValorCampoPai); end; json:= json + '"rws":['; if dbGetValores.ParamCount > 0 then begin dbGetValores.AddSqlAdicional( ' AND (dtCreated >= :Data '+ #13 + ' OR ModifiedTime >= :Data1 '+ #13 + ' OR id_web is null) ' ); end else begin dbGetValores.AddSqlAdicional( ' WHERE (dtCreated >= :Data '+ #13 + ' OR ModifiedTime >= :Data1 '+ #13 + ' OR id_web is null) ' ); end; dbGetValores.FNomesParamAdic:= varArrayOf(['Data', 'Data1']); dbGetValores.FValoresParamAdic:= varArrayOf([FDataUltimaSinc, FDataUltimaSinc]); ExecuteQuery(dbGetValores); dbGetValores.First; while not dbGetValores.Eof do begin json:= json + '{'; FilterCds(cdsFiltro, 'Model = ' + QuotedStr(Model)); cdsFiltro.First; while not cdsFiltro.Eof do begin json:= json + '"' + cdsFiltro.FieldByName('CampoWeb').AsString + '":'; if cdsFiltro.FieldByName('ValorFixo').AsString = EmptyStr then begin json:= json + '"' + VariantValueToStr(dbGetValores.GetVal(cdsFiltro.FieldByName('CampoLocal').AsString)) + '"'; end else begin json:= json + '"' + cdsFiltro.FieldByName('ValorFixo').AsString + '"'; end; cdsFiltro.Next; if not cdsFiltro.Eof then json:= json + ','; end; //campo para mapear os ids do web com o do desktop json:= json + ',"id_desktop":' + '"' + VarToStr(dbGetValores.GetVal('id')) + '"'; FilterCds(cdsPaiTemp, 'ModelPai = ' + QuotedStr(Model)); if not cdsPaiTemp.IsEmpty then begin json:= json + ',"model_child":['; end; cdsPaiTemp.First; while not cdsPaiTemp.Eof do begin FilterCds(cdsFiltro, 'Model=' + QuotedStr(cdsPaiTemp.FieldByName('Model').AsString) + ' and NomeCampoPai <> ' + QuotedStr('*')); json:= json + '{'; json:= json + GetJsonParcial(cdsPaiTemp.FieldByName('Model').AsString, Model, cdsPaiTemp.FieldByName('Module').AsString, dbGetValores.GetVal(cdsFiltro.FieldByName('NomeCampoPai').AsString)); json:= json + '}'; cdsPaiTemp.Next; if not cdsPaiTemp.Eof then json:= json + ','; end; if not cdsPaiTemp.IsEmpty then begin json:= json + ']'; end; json:= json + '}'; dbGetValores.Next; if not dbGetValores.Eof then json:= json + ','; end; json:= json + ']'; Result:= json; finally if Assigned(dbGetValores) then FreeAndNil(dbGetValores); FreeAndNil(cdsPaiTemp); FreeAndNil(cdsFilhosTemp); end; end; procedure TUpload.SendData; var http : TIdHTTP; error: string; param: TStringList; begin http := TIdHTTP.Create(nil); param:= TStringList.Create; try param.Add('senha='+SENHA_VMSIS); param.Add('usuario=' + USUARIO_VMSIS); param.Add('data={'+GetJsonParcial(Fmodel, EmptyStr, FModulo, Null) + '}'); http.AllowCookies := True; http.HandleRedirects := False; http.Request.Accept := 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'; http.Request.AcceptCharSet := 'iso-8859-1, utf-8, utf-16, *;q=0.1'; http.Request.AcceptEncoding := 'gzip, deflate, sdch'; http.Request.Connection := 'Keep-Alive'; http.Request.ContentType := 'application/x-www-form-urlencoded'; http.Request.UserAgent := 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36'; FResponse:= http.Post(FUrlToSendXML, param); error:= GetResponseError; if error = EmptyStr then SetIdWeb() else raise Exception.Create(error); finally FreeAndNil(http); FreeAndNil(param); end; end; function TSincronizacaoBase.GetUrlParametersLogin: String; begin Result:= Format('&usuario=%s&senha=%s', [USUARIO_VMSIS, SENHA_VMSIS]) end; function TSincronizacaoBase.VariantValueToStr(const value: Variant): String; begin case VarType(value) of varDate: Result:= FormatDateTime('yyyy-mm-dd', value); varDouble, varCurrency : begin Result:= StringReplace(FormatFloat('#,##0.00' , value), ',', '.', [rfReplaceAll]); end else Result:= VarToStr(value); end end; procedure TSincronizacaoBase.PreencheDataUltimaSinc; var bdDtSinc: TObjetoDB; begin bdDtSinc:= TObjetoDB.create('cotrolesincronizacao'); try bdDtSinc.AddParametro('Status', 'S'); bdDtSinc.Select(['IFNULL(MAX(dtsincronizacao), DATE_ADD(CURRENT_TIMESTAMP, INTERVAL -1 YEAR)) AS Data']); FDataUltimaSinc:= bdDtSinc.GetVal('Data');//VariantValueToStr(bdDtSinc.GetVal('Data')); finally FreeAndNil(bdDtSinc); end; end; { TMapeamento } function TMapeamento.MapaCliente: TListaMapaValor; var map: TListaMapaValor; begin map := TListaMapaValor.create; map.Add('dtcadastro', 'dtcadastro', ''); map.Add('nrinscjurd', 'nrinscjurd', ''); map.Add('nmcliente', 'nmcliente', ''); map.Add('identificador', 'identificador', ''); map.Add('telcel', 'telcel', ''); map.Add('telfixo', 'telfixo', ''); map.Add('nmrua', 'nmrua', ''); map.Add('cdnumero', 'cdnumero', ''); map.Add('cdcep', 'cdcep', ''); map.Add('cdbairro', 'cdbairro_id', ''); AddEmpresaUpload(map); Result:= map; end; constructor TMapeamento.create(const TipoSincroniacao: TTipoSincronizacao; const Empresa, Unidade, Almoxarifado: Integer); begin FTipoSincronizacao:= TipoSincroniacao; FUnidade:= Unidade; FEmpresa:= Empresa; FAlmoxarifado:= Almoxarifado; end; function TMapeamento.MapaBairro: TListaMapaValor; var map: TListaMapaValor; begin map := TListaMapaValor.create; map.Add('dtcadastro', 'dtcadastro', ''); map.Add('cdbairro', 'cdbairro', ''); map.Add('nmbairro', 'nmbairro', ''); map.Add('cidade', 'cidade_id', ''); AddEmpresaUpload(map); Result:= map; end; function TMapeamento.MapaCidade: TListaMapaValor; var map : TListaMapaValor; begin map := TListaMapaValor.create; map.Add('dtcadastro', 'dtcadastro', ''); map.Add('cdcidade', 'cdcidade', ''); map.Add('nmcidade', 'nmcidade', ''); map.Add('pais', 'pais_id', ''); map.Add('estado', 'estado_id', ''); AddEmpresaUpload(map); Result:= map; end; function TMapeamento.MapaEstado: TListaMapaValor; var map : TListaMapaValor; begin map := TListaMapaValor.create; map.Add('dtcadastro', 'dtcadastro', ''); map.Add('cdestado', 'cdestado', ''); map.Add('nmestado', 'nmestado', ''); map.Add('sgestado', 'sgestado', ''); map.Add('dsregiao', 'dsregiao', ''); map.Add('pais', 'pais_id', ''); AddEmpresaUpload(map); Result:= map; end; function TMapeamento.MapaPais: TListaMapaValor; var map : TListaMapaValor; begin //pais map := TListaMapaValor.create; map.Add('dtcadastro', 'dtcadastro', ''); map.Add('cdpais', 'cdpais', ''); map.Add('nmpais', 'nmpais', ''); map.Add('cdsiscomex', 'cdsiscomex', ''); map.Add('sgpais2', 'sgpais2', ''); map.Add('sgpais3', 'sgpais3', ''); AddEmpresaUpload(map); Result:= map; end; function TUpload.GetResponseError: String; begin Result:= EmptyStr; if UpperCase(Copy(FResponse, 1, 5)) = 'ERROR' then begin Result:= Copy(FResponse, 7, Length(FResponse)); if Trim(Result) = EmptyStr then Result:= 'Erro desconheido ao realizar upload'; end; end; procedure TUpload.SetIdWeb; var splitModel, splitIds: TStringList; i: Integer; nomeModel, idWeb, idDesktop, tabelaLocal, linhaModel, linhaId: string; dbUpdateValue: TObjetoDB; const C_IDX_MODEL = 0; C_IDX_ID = 1; begin splitModel:= TStringList.Create; splitids:= TStringList.Create; try splitModel.Delimiter:= '|'; splitModel.DelimitedText:= FResponse; for i:= 0 to splitModel.Count - 1 do begin if (splitModel[i] = EmptyStr) or (UpperCase(splitModel[i]) = 'SUCCESS') then Continue; splitIds.Delimiter:= Pchar('')[0]; splitIds.Delimiter:= ';'; splitIds.DelimitedText:= splitModel[i]; linhaModel:= splitIds[C_IDX_MODEL]; linhaId:= splitIds[C_IDX_ID]; nomeModel:= Copy(linhaModel, Pos('=', linhaModel) + 1, Length(linhaModel)); idWeb:= Copy(linhaId, Pos(':', linhaId) + 1, Length(linhaId)); idDesktop:= Copy(linhaId, 1, Pos(':', linhaId)-1); if FCdsModels.Locate('Model', varArrayOf([nomeModel]), [loCaseInsensitive]) then begin tabelaLocal:= FCdsModels.FieldByName('TabelaLocal').AsString; end else begin raise Exception.Create(Format('Não foi possível completar o update dos campos no desktop. '+ 'Model %s não encontrado.', [nomeModel]) ); end; if Assigned(dbUpdateValue) then FreeAndNil(dbUpdateValue); dbUpdateValue:= TObjetoDB.create(tabelaLocal); dbUpdateValue.AddParametro('id', idDesktop); dbUpdateValue.AddParametroNewValueUp('id_web', idWeb); dbUpdateValue.Update; end; finally FreeAndNil(splitModel); FreeAndNil(splitIds); if Assigned(dbUpdateValue) then FreeAndNil(dbUpdateValue); end; end; procedure TUpload.ExecuteQuery(qry: TObjetoDB); begin qry.Select(['*']); end; function TMapeamento.MapaFornecedor: TListaMapaValor; var map: TListaMapaValor; begin map := TListaMapaValor.create; map.Add('dtcadastro', 'dtcadastro', ''); map.Add('nrinscjurd', 'nrinscjurd', ''); map.Add('nmfornecedor', 'nmfornecedor', ''); map.Add('identificador', 'identificador', ''); map.Add('telcel', 'telcel', ''); map.Add('telfixo', 'telfixo', ''); map.Add('nmrua', 'nmrua', ''); map.Add('cdnumero', 'cdnumero', ''); map.Add('cdcep', 'cdcep', ''); map.Add('cdbairro', 'cdbairro_id', ''); AddEmpresaUpload(map); Result:= map; end; function TMapeamento.MapaUnidadeMedida: TListaMapaValor; var map: TListaMapaValor; begin map := TListaMapaValor.create; map.Add('dtcadastro', 'dtcadastro', ''); map.Add('nmmedida', 'nmmedida', ''); map.Add('sgmedida', 'sgmedida', ''); map.Add('qtfatorconv', 'qtfatorconv', ''); map.Add('idtipomed', 'idtipomed', ''); AddEmpresaUpload(map); Result:= map; end; function TMapeamento.MapaProduto: TListaMapaValor; var map: TListaMapaValor; begin map := TListaMapaValor.create; map.Add('dtcadastro', 'dtcadastro'); map.Add('posarvore', 'posarvore'); map.Add('nmproduto', 'nmproduto'); map.Add('unimedida', 'unimedida_id'); map.Add('cdbarra', 'cdbarra'); map.Add('idprodvenda', 'idprodvenda'); map.Add('idadicional', 'idadicional'); map.Add('imgindex', 'imgindex'); AddEmpresaUpload(map); Result:= map; end; function TMapeamento.MapaFinalidade: TListaMapaValor; var map: TListaMapaValor; begin map := TListaMapaValor.create; map.Add('dtcadastro', 'dtcadastro'); map.Add('descricao', 'descricao'); AddEmpresaUpload(map); Result:= map; end; function TMapeamento.MapaEntrada: TListaMapaValor; var map: TListaMapaValor; begin map := TListaMapaValor.create; map.Add('dtentrada', 'dtentrada'); map.Add('fornecedor', 'fornecedor_id'); AddUnidadeUpload(map); Result:= map; end; function TMapeamento.MapaSaida: TListaMapaValor; var map: TListaMapaValor; begin map := TListaMapaValor.create; map.Add('dtsaida', 'dtsaida'); map.Add('cliente', 'cliente_id'); map.Add('finalidade', 'finalidade_id'); map.Add('idtipo', 'idtipo'); AddUnidadeUpload(map); Result:= map; end; function TMapeamento.MapaItemProduto: TListaMapaValor; var map: TListaMapaValor; begin map := TListaMapaValor.create; map.Add('dtcadastro', 'dtcadastro'); map.Add('produto', 'produto_id'); map.Add('lote', 'lote_id'); map.Add('qtdeprod', 'qtdeprod'); AddEmpresaUpload(map); AddUnidadeUpload(map); AddAlmoxarifadoUpload(map); Result:= map; end; function TMapeamento.MapaLote: TListaMapaValor; var map: TListaMapaValor; begin map := TListaMapaValor.create; map.Add('dtcadastro', 'dtcadastro'); map.Add('dslote', 'dslote'); map.Add('dtvalidade', 'dtvalidade'); map.Add('dtfabricacao', 'dtfabricacao'); AddUnidadeUpload(map); Result:= map; end; function TMapeamento.MapaPosEstoque: TListaMapaValor; var map: TListaMapaValor; begin map := TListaMapaValor.create; map.Add('dtcadastro', 'dtcadastro'); map.Add('produto', 'produto_id'); map.Add('lote', 'lote_id'); map.Add('qtdeproduto', 'qtdeproduto'); AddEmpresaUpload(map); AddAlmoxarifadoUpload(map); Result:= map; end; function TMapeamento.MapaAgrupAdicional: TListaMapaValor; var map: TListaMapaValor; begin map := TListaMapaValor.create; map.Add('nmagrupadic', 'nmagrupadic'); map.Add('vragrupadic', 'vragrupadic'); map.Add('idagrupativ', 'idagrupativ'); Result:= map; end; function TMapeamento.MapaCategoria: TListaMapaValor; var map:TListaMapaValor; begin map := TListaMapaValor.create; map.Add('nmcategoria', 'nmcategoria'); map.Add('idcategoriativ', 'idcategoriativ'); map.Add('imgindex', 'imgindex'); Result:= map; end; function TMapeamento.MapaComposicaoProd: TListaMapaValor; var map: TListaMapaValor; begin map := TListaMapaValor.create; map.Add('produto', 'produto_id'); map.Add('prodcomp', 'prodcomp_id'); map.Add('qtcomp', 'qtcomp'); map.Add('categoria', 'categoria_id'); map.Add('unimedida', 'unimedida_id'); Result:= map; end; function TMapeamento.MapaItemCategoria: TListaMapaValor; var map: TListaMapaValor; begin map := TListaMapaValor.create; map.Add('categoria', 'categoria_id'); map.Add('produto', 'produto_id'); map.Add('vrvenda', 'vrvenda'); map.Add('qtvenda', 'qtvenda'); map.Add('qtadicgratis', 'qtadicgratis'); map.Add('unimedida', 'unimedida_id'); map.Add('dsproduto', 'dsproduto'); Result:= map; end; function TMapeamento.MapaItAgrupAdicional: TListaMapaValor; var map: TListaMapaValor; begin map := TListaMapaValor.create; map.Add('cardapio', 'cardapio_id'); map.Add('agrupadicional', 'agrupadicional_id'); Result:= map; end; function TMapeamento.MapaMesa: TListaMapaValor; var map: TListaMapaValor; begin map := TListaMapaValor.create; map.Add('nmmesa', 'nmmesa'); map.Add('dsobsmesa', 'dsobsmesa'); map.Add('idmesaativ', 'idmesaativ'); AddUnidadeUpload(map); Result:= map; end; function TMapeamento.MapaAdicionais: TListaMapaValor; var map: TListaMapaValor; begin map:= TListaMapaValor.create; map.Add('agrupadicional', 'agrupadicional_id'); map.Add('item', 'item_id'); map.Add('valor', 'valor'); map.Add('quantidade', 'quantidade'); Result:= map; end; procedure TMapeamento.AddEmpresaUpload(mapa: TListaMapaValor); begin if FTipoSincronizacao = tsUpload then begin mapa.Add('empresa', '', IntToStr(FEmpresa)); end; end; procedure TMapeamento.AddUnidadeUpload(mapa: TListaMapaValor); begin if FTipoSincronizacao = tsUpload then begin mapa.Add('unidade', '', IntToStr(FUnidade)); end; end; procedure TMapeamento.AddAlmoxarifadoUpload(mapa: TListaMapaValor); begin if FTipoSincronizacao = tsUpload then begin mapa.Add('almoxarifado', '', IntToStr(FAlmoxarifado)); end; end; function TMapeamento.MapaPedido: TListaMapaValor; var map: TListaMapaValor; begin map:= TListaMapaValor.create; map.Add('idtipopedido', 'idtipopedido'); map.Add('cliente', 'cliente_id'); map.Add('nmcliente', 'nmcliente'); map.Add('mesa', 'mesa_id'); map.Add('vrpedido', 'vrpedido'); map.Add('idstatusped', 'idstatusped'); map.Add('dsmotivo', 'dsmotivo'); Result:= map; end; function TMapeamento.MapaItempedido: TListaMapaValor; var map: TListaMapaValor; begin map:= TListaMapaValor.create; map.Add('dtcadastro', 'dtcadastro'); map.Add('pedido', 'pedido_id', NOME_CHAVE_PADRAO_FK); map.Add('cardapio', 'cardapio_id'); AddEmpresaUpload(map); AddAlmoxarifadoUpload(map); map.Add('lote', 'lote_id'); map.Add('qtitem', 'qtitem'); map.Add('vrvenda', 'vrvenda'); map.Add('vrtotal', 'vrtotal'); map.Add('idadicional', 'idadicional'); map.Add('produto', 'Produto_id'); Result:= map; end; function TMapeamento.MapaItAdicional: TListaMapaValor; var map: TListaMapaValor; begin map:= TListaMapaValor.create; map.Add('itempedido', 'itempedido_id', NOME_CHAVE_PADRAO_FK); map.Add('item', 'item_id'); map.Add('qtitem', 'qtitem'); map.Add('valor', 'valor'); map.Add('VrVenda', 'VrVenda'); Result:= map; end; function TMapeamento.MapaAberfechcaixa: TListaMapaValor; var map: TListaMapaValor; begin map:= TListaMapaValor.create; map.Add('caixa', 'id_caixa'); map.Add('vrinicial', 'vrinicial'); map.Add('vrcorrigido', 'vrcorrigido'); map.Add('vrvenda', 'vrvenda'); map.Add('vrretirada', 'vrretirada'); map.Add('vrsangria', 'vrsangria'); map.Add('vrentrada', 'vrentrada'); map.Add('vrdebio', 'vrdebio'); map.Add('vrcredito', 'vrcredito'); map.Add('dtmovi', 'dtmovi'); map.Add('funciconfabertura', 'funciconfabertura'); map.Add('funcipreabertura', 'funcipreabertura'); map.Add('funcifechamento', 'funcifechamento'); map.Add('status', 'status'); Result:= map; end; function TMapeamento.MapaMovCaixa: TListaMapaValor; var map: TListaMapaValor; begin map:= TListaMapaValor.create; map.Add('caixa', 'id_caixa'); map.Add('dtmovi', 'dtmovi'); map.Add('vrmovi', 'vrmovi'); map.Add('tpmovi', 'tpmovi'); map.Add('formpgto', 'formpgto'); map.Add('pedido', 'id_pedido'); Result:= map; end; function TMapeamento.MapaFuncionario: TListaMapaValor; var map: TListaMapaValor; begin map:= TListaMapaValor.create; map.Add('nome', 'nome'); map.Add('usuario', 'usuario'); map.Add('sexo', 'sexo'); map.Add('email', 'email'); map.Add('senha', 'senha'); map.Add('confsenha', 'confsenha'); Result:= map; end; function TMapeamento.MapaCartaoBandeira: TListaMapaValor; var map: TListaMapaValor; begin map:= TListaMapaValor.create; map.Add('nmbandeira', 'nmbandeira'); map.Add('qtdias_cred', 'qtdias_cred'); map.Add('qtdias_deb', 'qtdias_deb'); map.Add('idativo', 'idativo'); Result:= map; end; end.
{ Данный пример демонстрирует использование очереди TThreadedQueue. При запуске программы создаётся один Consumer-поток, который исполняет команды, которые другие потоки кладут в очередь ConsumerQueue. Также есть несколько Producer-потоков, которые хотят получить у Consumer-потока какие-то данные. Producer-потоки периодически кладут в очередь ConsumerQueue команды, а затем читают ответ на команду из своей очереди. В каждом Producer-потоке создаётся своя очередь ResQueue. Ссылка на ResQueue передаётся в очередь ConsumerQueue вместе с идентификатором команды CmdId. Может быть любое количество Producer-потоков. Также можно запросить данные у Consumer-потока путём нажатия соответствующей кнопки на форме. Consumer-поток выполняет команды и возвращает ответ немедленно! Обратите внимание, что при нажатии кнопок "Запросить состояние" и "Запросить данные" программа сообщает время выполнения методов PushItem и PopItem в микросекундах. Вызов метода PushItem занимает от 2х до 4х микросекунд (в момент вызова работа потока не прерывается, иначе замер показал бы значительно большее время). Вызов метода PopItem занимает от 27 до 100 микросекунд (в среднем 85 мкс). Это время складывается из: 1) Consumer-поток ожидает на вызове ConsumerQueue.PopItem 2) Consumer-поток выполняет некоторый код (готовит результат) 3) Consumer-поток кладёт результат в очередь ResQueue 4) Producer-поток ожидает на вызове ResQueue.PopItem В лучшем случае 2 переключения контекста между Producer-потоком и Consumer-потоком выполняются в рамках одного ядра CPU (в этом случае достигается максимальная скорость: 27 мкс). Если при переключении между Producer-потоком и Consumer-потоком используются разные ядра CPU, то скорость будет ниже (до 100 мкс). Типовой расклад по времени переключения контекста между потоками: - ConsumerQueue.PushItem:[35 мкс]; - Process command:[13 мкс]; - ResQueue.PushItem:[42 мкс]; Это означает, что после помещения команды в очередь время разблокировки Consumer-потока (вызов ConsumerQueue.PopItem) составило 35 мкс (min=7, max=57). Затем был выполнен некоторый код (подготовка результата) в TConsumerThread.Execute (13 мкс). Затем Consumer-поток добавил результат в очередь ResQueue и Producer-поток был разблокирован (вызов ResQueue.PopItem) в течение 42 мкс (min=7, max=57). Информацию о ходе своей работы потоки пишут в лог-файл. Другие примеры использования очереди заданий: - организация очереди callback-функций / анонимных функций / задач - очередь команд контроллеру, подключенному через USB / RS-232 / RS-485 - очередь команд фискальному регистратору (очередь чеков) - очередь на запрос информации из базы данных (если принципиально важно обойтись одним коннектом к БД) - очередь на запрос информации у DCOM-сервера (в случае, если весь обмен с DCOM-сервером должен выполняться через один поток) - очередь платежей (например через платёжный шлюз CreditPilot) - и многое другое } unit ThreadedQueueUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Generics.Collections, MTLogger, MTUtils, TimeIntervals; const Q_CMD_STOP_THREAD = 0; Q_CMD_GET_CURR_STATE = 1; Q_CMD_GET_LAST_DATA = 2; type TQueueResult = record ResStr: string; end; PTimeIntervalEvents = ^TTimeIntervalEvents; TQueueCommand = record CmdId: Integer; // Команда, которую должен исполнить поток-consumer //CmpParams: Variant; // При необходимости у команды могут быть доп. параметры ResQueue: TThreadedQueue<TQueueResult>; // Очередь, куда будет отправляться результат pTimeEvents: PTimeIntervalEvents; end; TProducerType = ( ptQueryCurState, // Запрос текущего времени ptQueryLastData); // Запрос последних данных TProducerThread = class(TThread) private FProducerType: TProducerType; FConsumerThreadRef: TThread; ResQueue: TThreadedQueue<TQueueResult>; protected procedure Execute; override; public constructor Create(ProducerType: TProducerType; ConsumerThread: TThread); destructor Destroy; override; end; TConsumerThread = class(TThread) protected procedure Execute; override; public ConsumerQueue: TThreadedQueue<TQueueCommand>; constructor Create; destructor Destroy; override; end; TMainForm = class(TForm) Button1: TButton; Label1: TLabel; labProducersCount: TLabel; Button2: TButton; Button3: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private // Список потоков, которые запрашивают текущее время QueryCurStateThreads: TObjectList<TProducerThread>; // Список потоков, которые запрашивают последние данные QueryLastDataThreads: TObjectList<TProducerThread>; // Поток, который исполняет команды и возвращает результат ConsumerThread: TConsumerThread; // Создаёт пару Producer-потоков procedure CreateProducerThreads; public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.dfm} procedure TMainForm.Button1Click(Sender: TObject); begin CreateProducerThreads; end; procedure TMainForm.Button2Click(Sender: TObject); var Cmd: TQueueCommand; Res: TQueueResult; ResQueue: TThreadedQueue<TQueueResult>; tmEv, tmEvSwitch: TTimeIntervalEvents; QSize: Integer; begin ResQueue := TThreadedQueue<TQueueResult>.Create(10); if TButton(Sender).Tag = 1 then Cmd.CmdId := Q_CMD_GET_CURR_STATE else Cmd.CmdId := Q_CMD_GET_LAST_DATA; Cmd.ResQueue := ResQueue; Cmd.pTimeEvents := @tmEvSwitch; // Для замера времени tmEv.StartEvent('PushItem'); // Замер времени tmEvSwitch.StartEvent('ConsumerQueue.PushItem'); // Замер времени ConsumerThread.ConsumerQueue.PushItem(Cmd, QSize); tmEv.StartEvent('PopItem'); // Замер времени Res := ResQueue.PopItem; tmEv.StopEvent(); // Замер времени tmEvSwitch.StopEvent(); // Замер времени ShowMessageFmt('Consumer-поток вернул данные: %s. Ушло времени: %s; '+ 'Время переключения контекста: %s; Длина очереди: %d', [Res.ResStr, tmEv.GetEventsAsString([eoUseMicroSec]), tmEvSwitch.GetEventsAsString([eoUseMicroSec]), QSize]); ResQueue.Free; end; procedure TMainForm.CreateProducerThreads; begin QueryCurStateThreads.Add(TProducerThread.Create(ptQueryCurState, ConsumerThread)); QueryLastDataThreads.Add(TProducerThread.Create(ptQueryLastData, ConsumerThread)); labProducersCount.Caption := IntToStr(QueryCurStateThreads.Count + QueryLastDataThreads.Count); end; procedure TMainForm.FormCreate(Sender: TObject); begin CreateDefLogger(Application.ExeName + '.log'); DefLogger.AddToLog('Программа запущена'); // Создаём consumer-поток ConsumerThread := TConsumerThread.Create; // Создаем producer-потоки QueryCurStateThreads := TObjectList<TProducerThread>.Create; QueryLastDataThreads := TObjectList<TProducerThread>.Create; CreateProducerThreads; end; procedure TMainForm.FormDestroy(Sender: TObject); begin // Внимание! Очень важно уничтожать потоки в правильном порядке! Сначала уничтожаем // producer-потоки, а затем consumer-поток // Останавливаем producer-потоки FreeAndNil(QueryCurStateThreads); FreeAndNil(QueryLastDataThreads); // Останавливаем consumer-поток FreeAndNil(ConsumerThread); DefLogger.AddToLog('Программа остановлена'); FreeDefLogger; end; { TProducerThread } constructor TProducerThread.Create(ProducerType: TProducerType; ConsumerThread: TThread); begin ResQueue := TThreadedQueue<TQueueResult>.Create(10); FProducerType := ProducerType; FConsumerThreadRef := ConsumerThread; inherited Create(False); end; destructor TProducerThread.Destroy; begin Terminate; inherited; // Дожидаемся, когда consumer-поток вернёт результат ResQueue.Free; end; procedure TProducerThread.Execute; var Cmd: TQueueCommand; Res: TQueueResult; begin DefLogger.AddToLog('TProducerThread: Поток запущен. ProducerType=' + IntToStr(Integer(FProducerType))); Cmd.ResQueue := ResQueue; Cmd.pTimeEvents := nil; while not Terminated do begin if FProducerType = ptQueryCurState then Cmd.CmdId := Q_CMD_GET_CURR_STATE else Cmd.CmdId := Q_CMD_GET_LAST_DATA; // Добавляем команду в очередь consumer-потока TConsumerThread(FConsumerThreadRef).ConsumerQueue.PushItem(Cmd); DefLogger.AddToLog('TProducerThread: Отправлена команда в consumer-поток. CmdId=' + IntToStr(Cmd.CmdId)); // Получаем результат обработки команды consumer-потоком. Считаем, что consumer-поток // гарантированно вернет ответ на команду Res := ResQueue.PopItem; DefLogger.AddToLog('TProducerThread: consumer-поток вернул результат: ' + Res.ResStr); ThreadWaitTimeout(Self, Random(5000)); end; DefLogger.AddToLog('TProducerThread: Поток остановлен. ProducerType=' + IntToStr(Integer(FProducerType))); end; { TConsumerThread } constructor TConsumerThread.Create; begin ConsumerQueue := TThreadedQueue<TQueueCommand>.Create(10); inherited Create(False); end; destructor TConsumerThread.Destroy; var Cmd: TQueueCommand; begin // Для того, чтобы остановить этот поток, необходимо добавить команду в очередь Cmd.CmdId := Q_CMD_STOP_THREAD; Cmd.pTimeEvents := nil; ConsumerQueue.PushItem(Cmd); inherited; // Дожидаемся, когда поток обработает все команды, в том числе Q_CMD_STOP_THREAD ConsumerQueue.Free; end; procedure TConsumerThread.Execute; var Cmd: TQueueCommand; Res: TQueueResult; begin DefLogger.AddToLog('TConsumerThread запущен'); while True do begin Cmd := ConsumerQueue.PopItem; if Assigned(Cmd.pTimeEvents) then Cmd.pTimeEvents.StartEvent('Process command'); // Замер времени DefLogger.AddToLog('TConsumerThread: принята команда CmdId=' + IntToStr(Cmd.CmdId)); case Cmd.CmdId of Q_CMD_STOP_THREAD: Break; // Завершили работу потока Q_CMD_GET_CURR_STATE: begin Res.ResStr := 'CurrDateTime: ' + DateTimeToStr(Now); end; Q_CMD_GET_LAST_DATA: begin Res.ResStr := 'Current data count: ' + IntToStr(Random(1000)); end; end; // Кладём результат в очередь Producer-потока if Assigned(Cmd.pTimeEvents) then Cmd.pTimeEvents.StartEvent('ResQueue.PushItem'); // Замер времени Cmd.ResQueue.PushItem(Res); DefLogger.AddToLog('TConsumerThread: подготовлен ответ: ResStr=' + Res.ResStr); end; DefLogger.AddToLog('TConsumerThread остановлен'); end; end.
{*! * Fano Web Framework (https://fanoframework.github.io) * * @link https://github.com/fanoframework/fano * @copyright Copyright (c) 2018 Zamrony P. Juhara * @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT) *} unit TemplateFetcherIntf; interface {$MODE OBJFPC} {$H+} uses ViewParametersIntf; type (*!------------------------------------------------ * interface for any class having capability to * read template file and replace its content with value * and output to string * * @author Zamrony P. Juhara <zamronypj@yahoo.com> *-----------------------------------------------*) ITemplateFetcher = interface ['{22C26574-8709-4106-9EE9-84EA86F4567C}'] function fetch( const templatePath : string; const viewParams : IViewParameters ) : string; end; implementation end.
unit UFrmMain; interface uses FMX.Forms, DzXMLTable, FMX.StdCtrls, FMX.Controls.Presentation, System.Classes, FMX.Types, FMX.Controls, FMX.Layouts, FMX.ListBox; type TFrmMain = class(TForm) L: TListBox; Label1: TLabel; BtnAdd: TButton; BtnMod: TButton; BtnDel: TButton; XT: TDzXMLTable; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure BtnAddClick(Sender: TObject); procedure BtnModClick(Sender: TObject); procedure BtnDelClick(Sender: TObject); procedure LItemClick(const Sender: TCustomListBox; const Item: TListBoxItem); procedure LDblClick(Sender: TObject); private procedure LoadList; procedure UpdButtons; end; var FrmMain: TFrmMain; implementation {$R *.fmx} uses UFrmContact, System.SysUtils, FMX.Dialogs, FMX.DialogService, System.UITypes; procedure TFrmMain.FormCreate(Sender: TObject); begin XT.FileName := ExtractFilePath(ParamStr(0))+'..\..\Contacts.xml'; XT.Load; LoadList; UpdButtons; end; procedure TFrmMain.FormDestroy(Sender: TObject); begin XT.Save; end; procedure TFrmMain.LItemClick(const Sender: TCustomListBox; const Item: TListBoxItem); begin UpdButtons; end; procedure TFrmMain.LDblClick(Sender: TObject); begin if BtnMod.Enabled then BtnModClick(nil); end; procedure TFrmMain.LoadList; var R: TDzRecord; begin for R in XT do L.Items.Add(R['Name']); end; procedure TFrmMain.UpdButtons; begin BtnMod.Enabled := L.Selected <> nil; BtnDel.Enabled := L.Selected <> nil; end; procedure TFrmMain.BtnAddClick(Sender: TObject); var R: TDzRecord; begin if DoEditContact(False, R) then L.Items.Add(R['Name']); end; procedure TFrmMain.BtnModClick(Sender: TObject); var R: TDzRecord; begin R := XT[L.Selected.Index]; if DoEditContact(True, R) then L.Selected.Text := R['Name']; end; procedure TFrmMain.BtnDelClick(Sender: TObject); var R: TDzRecord; begin R := XT[L.Selected.Index]; TDialogService.MessageDialog( Format('Do you want to delete contact "%s"?', [R['Name']]), TMsgDlgType.mtConfirmation, mbYesNo, TMsgDlgBtn.mbNo, 0, procedure (const AResult: TModalResult) begin if AResult = mrYes then begin XT.Delete(L.Selected.Index); L.Items.Delete(L.Selected.Index); UpdButtons; end; end); end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLHeightTileFile<p> Access to large tiled height data files.<p> Performance vs Raw file accesses (for perfect tile match):<ul> <li>Cached data:<ul> <li>"Smooth" terrain 1:2 to 1:10 <li>Random terrain 1:1 </ul> <li>Non-cached data:<ul> <li>"Smooth" terrain 1:100 to 1:1000 <li>Random terrain 1:100 </ul> </ul><p> <b>Historique : </b><font size=-1><ul> <li>17/11/14 - PW - Renamed from HeightTileFile.pas to GLHeightTileFile.pas <li>20/05/10 - Yar - Fixes for Linux x64 <li>30/03/07 - DaStr - Added $I GLScene.inc <li>21/12/01 - Egg - Creation </ul></font> } unit GLHeightTileFile; interface {$I GLScene.inc} uses System.Classes, System.SysUtils, //GLS GLCrossPlatform, GLApplicationFileIO; type PByte = ^Byte; TIntegerArray = array [0..MaxInt shr 3] of Integer; PIntegerArray = ^TIntegerArray; PInteger = ^Integer; TSmallIntArray = array [0..MaxInt shr 2] of SmallInt; PSmallIntArray = ^TSmallIntArray; PSmallInt = ^SmallInt; TShortIntArray = array [0..MaxInt shr 2] of ShortInt; PShortIntArray = ^TShortIntArray; PShortInt = ^ShortInt; // THeightTileInfo // THeightTileInfo = packed record left, top, width, height : Integer; min, max, average : SmallInt; fileOffset : Int64; // offset to tile data in the file end; PHeightTileInfo = ^THeightTileInfo; PPHeightTileInfo = ^PHeightTileInfo; // THeightTile // THeightTile = packed record info : THeightTileInfo; data : array of SmallInt; end; PHeightTile = ^THeightTile; // THTFHeader // THTFHeader = packed record FileVersion : array [0..5] of AnsiChar; TileIndexOffset : Int64; SizeX, SizeY : Integer; TileSize : Integer; DefaultZ : SmallInt; end; const cHTFHashTableSize = 1023; cHTFQuadTableSize = 31; type // THeightTileFile // {: Interfaces a Tiled file } THeightTileFile = class (TObject) private { Private Declarations } FFile : TStream; FHeader : THTFHeader; FTileIndex : packed array of THeightTileInfo; FTileMark : array of Cardinal; FLastMark : Cardinal; FHashTable : array [0..cHTFHashTableSize] of array of Integer; FQuadTable : array [0..cHTFQuadTableSize, 0..cHTFQuadTableSize] of array of Integer; FCreating : Boolean; FHeightTile : THeightTile; FInBuf : array of ShortInt; protected { Protected Declarations } function GetTiles(index : Integer) : PHeightTileInfo; function QuadTableX(x : Integer) : Integer; function QuadTableY(y : Integer) : Integer; procedure PackTile(aWidth, aHeight : Integer; src : PSmallIntArray); procedure UnPackTile(source : PShortIntArray); property TileIndexOffset : Int64 read FHeader.TileIndexOffset write FHeader.TileIndexOffset; public { Public Declarations } {: Creates a new HTF file.<p> Read and data access methods are not available when creating. } constructor CreateNew(const fileName : String; aSizeX, aSizeY, aTileSize : Integer); constructor Create(const fileName : String); destructor Destroy; override; {: Returns tile index for corresponding left/top. } function GetTileIndex(aLeft, aTop : Integer) : Integer; {: Returns tile of corresponding left/top.<p> } function GetTile(aLeft, aTop : Integer; pTileInfo : PPHeightTileInfo = nil) : PHeightTile; {: Stores and compresses give tile data.<p> aLeft and top MUST be a multiple of TileSize, aWidth and aHeight MUST be lower or equal to TileSize. } procedure CompressTile(aLeft, aTop, aWidth, aHeight : Integer; aData : PSmallIntArray); {: Extract a single row from the HTF file.<p> This is NOT the fastest way to access HTF data.<br> All of the row must be contained in the world, otherwise result is undefined. } procedure ExtractRow(x, y, len : Integer; dest : PSmallIntArray); {: Returns the tile that contains x and y. } function XYTileInfo(anX, anY : Integer) : PHeightTileInfo; {: Returns the height at given coordinates.<p> This is definetely NOT the fastest way to access HTF data and should only be used as utility function. } function XYHeight(anX, anY : Integer) : SmallInt; {: Clears the list then add all tiles that overlap the rectangular area. } procedure TilesInRect(aLeft, aTop, aRight, aBottom : Integer; destList : TList); function TileCount : Integer; property Tiles[index : Integer] : PHeightTileInfo read GetTiles; function IndexOfTile(aTile : PHeightTileInfo) : Integer; function TileCompressedSize(tileIndex : Integer) : Integer; property SizeX : Integer read FHeader.SizeX; property SizeY : Integer read FHeader.SizeY; {: Maximum width and height for a tile.<p> Actual tiles may not be square, can assume random layouts, and may overlap. } property TileSize : Integer read FHeader.TileSize; property DefaultZ : SmallInt read FHeader.DefaultZ write FHeader.DefaultZ; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ const cFileVersion = 'HTF100'; {$IFNDEF GLS_NO_ASM} // FillSmallInt // procedure FillSmallInt(p : PSmallInt; count : Integer; v : SmallInt); register; // EAX contains p // EDX contains count // ECX contains v asm push edi mov edi, p mov ax, cx // expand v to 32 bits shl eax, 16 mov ax, cx mov ecx, edx // the "odd" case is handled by issueing a lone stosw shr ecx, 1 test dl, 1 jz @even_nb stosw or ecx, ecx je @fill_done @even_nb: rep stosd @fill_done: pop edi end; {$ELSE} procedure FillSmallInt(p : PSmallInt; count : Integer; v : SmallInt); var I: Integer; begin for I := count - 1 downto 0 do begin p^ := v; Inc(p); end; end; {$ENDIF} // ------------------ // ------------------ THeightTileFile ------------------ // ------------------ // CreateNew // constructor THeightTileFile.CreateNew(const fileName : String; aSizeX, aSizeY, aTileSize : Integer); begin with FHeader do begin FileVersion:=cFileVersion; SizeX:=aSizeX; SizeY:=aSizeY; TileSize:=aTileSize; end; FFile:=CreateFileStream(fileName, fmCreate); FFile.Write(FHeader, SizeOf(FHeader)); FCreating:=True; SetLength(FHeightTile.data, aTileSize*aTileSize); end; // Create // constructor THeightTileFile.Create(const fileName : String); var n, i, key, qx, qy : Integer; begin FFile:=CreateFileStream(fileName, fmOpenRead+fmShareDenyNone); // Read Header FFile.Read(FHeader, SizeOf(FHeader)); if FHeader.FileVersion<>cFileVersion then raise Exception.Create('Invalid file type'); // Read TileIndex FFile.Position:=TileIndexOffset; FFile.Read(n, 4); SetLength(FTileIndex, n); FFile.Read(FTileIndex[0], SizeOf(THeightTileInfo)*n); // Prepare HashTable & QuadTable for n:=0 to High(FTileIndex) do begin with FTileIndex[n] do begin key:=Left+(Top shl 4); key:=((key and cHTFHashTableSize)+(key shr 10)+(key shr 20)) and cHTFHashTableSize; i:=Length(FHashTable[key]); SetLength(FHashTable[key], i+1); FHashTable[key][i]:=n; for qx:=QuadTableX(left) to QuadTableX(left+width-1) do begin for qy:=QuadTableY(top) to QuadTableY(top+height-1) do begin i:=Length(FQuadTable[qx, qy]); SetLength(FQuadTable[qx, qy], i+1); FQuadTable[qx, qy][i]:=n; end; end; end; end; FHeightTile.info.left:=MaxInt; // mark as not loaded SetLength(FHeightTile.data, TileSize*TileSize); SetLength(FInBuf, TileSize*(TileSize+1)*2); SetLength(FTileMark, Length(FTileIndex)); end; // Destroy // destructor THeightTileFile.Destroy; var n : Integer; begin if FCreating then begin TileIndexOffset:=FFile.Position; // write tile index n:=Length(FTileIndex); FFile.Write(n, 4); FFile.Write(FTileIndex[0], SizeOf(THeightTileInfo)*n); // write data size FFile.Position:=0; FFile.Write(FHeader, SizeOf(FHeader)); end; FFile.Free; inherited Destroy; end; // QuadTableX // function THeightTileFile.QuadTableX(x : Integer) : Integer; begin Result:=((x*(cHTFQuadTableSize+1)) div (SizeX+1)) and cHTFQuadTableSize; end; // QuadTableY // function THeightTileFile.QuadTableY(y : Integer) : Integer; begin Result:=((y*(cHTFQuadTableSize+1)) div (SizeY+1)) and cHTFQuadTableSize; end; // PackTile // procedure THeightTileFile.PackTile(aWidth, aHeight : Integer; src : PSmallIntArray); var packWidth : Integer; function DiffEncode(src : PSmallIntArray; dest : PShortIntArray) : PtrUInt; var i : Integer; v, delta : SmallInt; begin Result:=PtrUInt(dest); v:=src[0]; PSmallIntArray(dest)[0]:=v; dest:=PShortIntArray(PtrUInt(dest)+2); i:=1; while i<packWidth do begin delta:=src[i]-v; v:=src[i]; if Abs(delta)<=127 then begin dest[0]:=ShortInt(delta); dest:=PShortIntArray(PtrUInt(dest)+1); end else begin dest[0]:=-128; dest:=PShortIntArray(PtrUInt(dest)+1); PSmallIntArray(dest)[0]:=v; dest:=PShortIntArray(PtrUInt(dest)+2); end; Inc(i); end; Result:=PtrUInt(dest)-Result; end; function RLEEncode(src : PSmallIntArray; dest : PAnsiChar) : Cardinal; var v : SmallInt; i, n : Integer; begin i:=0; Result:=PtrUInt(dest); while (i<packWidth) do begin v:=src[i]; Inc(i); n:=0; PSmallIntArray(dest)[0]:=v; Inc(dest, 2); while (src[i]=v) and (i<packWidth) do begin Inc(n); if n=255 then begin dest[0]:=#255; Inc(dest); n:=0; end; Inc(i); end; if (i<packWidth) or (n>0) then begin dest[0]:=AnsiChar(n); Inc(dest); end; end; Result:=PtrUInt(dest)-Result; end; var y : Integer; p : PSmallIntArray; buf, bestBuf : array of Byte; bestLength, len : Integer; leftPack, rightPack : Byte; bestMethod : Byte; // 0=RAW, 1=Diff, 2=RLE av : Int64; v : SmallInt; begin SetLength(buf, TileSize*4); // worst case situation SetLength(bestBuf, TileSize*4); // worst case situation with FHeightTile.info do begin min:=src[0]; max:=src[0]; av:=src[0]; for y:=1 to aWidth*aHeight-1 do begin v:=Src[y]; if v<min then min:=v else if v>max then max:=v; av:=av+v; end; average:=av div (aWidth*aHeight); if min=max then Exit; // no need to store anything end; for y:=0 to aHeight-1 do begin p:=@src[aWidth*y]; packWidth:=aWidth; // Lookup leftPack leftPack:=0; while (leftPack<255) and (packWidth>0) and (p[0]=DefaultZ) do begin p:=PSmallIntArray(PtrUInt(p)+2); Dec(packWidth); Inc(leftPack); end; // Lookup rightPack rightPack:=0; while (rightPack<255) and (packWidth>0) and (p[packWidth-1]=DefaultZ) do begin Dec(packWidth); Inc(rightPack); end; // Default encoding = RAW bestLength:=packWidth*2; bestMethod:=0; Move(p^, bestBuf[0], bestLength); // Diff encoding len:=DiffEncode(p, PShortIntArray(@buf[0])); if len<bestLength then begin bestLength:=len; bestMethod:=1; Move(buf[0], bestBuf[0], bestLength); end; // RLE encoding len:=RLEEncode(p, PAnsiChar(@buf[0])); if len<bestLength then begin bestLength:=len; bestMethod:=2; Move(buf[0], bestBuf[0], bestLength); end; // Write to file if (leftPack or rightPack)=0 then begin FFile.Write(bestMethod, 1); FFile.Write(bestBuf[0], bestLength); end else begin if leftPack>0 then begin if rightPack>0 then begin bestMethod:=bestMethod+$C0; FFile.Write(bestMethod, 1); FFile.Write(leftPack, 1); FFile.Write(rightPack, 1); FFile.Write(bestBuf[0], bestLength); end else begin bestMethod:=bestMethod+$80; FFile.Write(bestMethod, 1); FFile.Write(leftPack, 1); FFile.Write(bestBuf[0], bestLength); end; end else begin bestMethod:=bestMethod+$40; FFile.Write(bestMethod, 1); FFile.Write(rightPack, 1); FFile.Write(bestBuf[0], bestLength); end; end; end; end; // UnPackTile // procedure THeightTileFile.UnPackTile(source : PShortIntArray); var unpackWidth, tileWidth : Cardinal; src : PShortInt; dest : PSmallInt; procedure DiffDecode; var v : SmallInt; delta : SmallInt; locSrc : PShortInt; destEnd, locDest : PSmallInt; begin locSrc:=PShortInt(PtrUInt(src)-1); locDest:=dest; destEnd:=PSmallInt(PtrUInt(dest)+unpackWidth*2); while PtrUInt(locDest)<PtrUInt(destEnd) do begin Inc(locSrc); v:=PSmallInt(locSrc)^; Inc(locSrc, 2); locDest^:=v; Inc(locDest); while (PtrUInt(locDest)<PtrUInt(destEnd)) do begin delta:=locSrc^; if delta<>-128 then begin v:=v+delta; Inc(locSrc); locDest^:=v; Inc(locDest); end else Break; end; end; src:=locSrc; dest:=locDest; end; procedure RLEDecode; var n, j : Cardinal; v : SmallInt; locSrc : PShortInt; destEnd, locDest : PSmallInt; begin locSrc:=src; locDest:=dest; destEnd:=PSmallInt(PtrUInt(dest)+unpackWidth*2); while PtrUInt(locDest)<PtrUInt(destEnd) do begin v:=PSmallIntArray(locSrc)[0]; Inc(locSrc, 2); repeat if PtrUInt(locDest)=PtrUInt(destEnd)-2 then begin locDest^:=v; Inc(locDest); n:=0; end else begin n:=Integer(locSrc^ and 255); Inc(locSrc); for j:=0 to n do begin locDest^:=v; Inc(locDest); end; end; until (n<255) or (PtrUInt(locDest)>=PtrUInt(destEnd)); end; src:=locSrc; dest:=locDest; end; var y : Integer; n : Byte; method : Byte; begin dest:=@FHeightTile.Data[0]; with FHeightTile.info do begin if min=max then begin FillSmallInt(dest, width*height, min); Exit; end; tileWidth:=width; end; src:=PShortInt(source); n:=0; for y:=0 to FHeightTile.info.height-1 do begin method:=Byte(src^); Inc(src); unpackWidth:=tileWidth; // Process left pack if any if (method and $80)<>0 then begin n:=PByte(src)^; Inc(src); FillSmallInt(dest, n, DefaultZ); Dec(unpackWidth, n); Inc(dest, n); end; // Read right pack if any if (method and $40)<>0 then begin PByte(@n)^:=PByte(src)^; Inc(src); Dec(unpackWidth, n) end else n:=0; // Process main data case (method and $3F) of 1 : DiffDecode; 2 : RLEDecode; else Move(src^, dest^, unpackWidth*2); Inc(src, unpackWidth*2); Inc(dest, unpackWidth); end; // Process right pack if any if n>0 then begin FillSmallInt(dest, n, DefaultZ); Inc(dest, n); end; end; end; // GetTileIndex // function THeightTileFile.GetTileIndex(aLeft, aTop : Integer) : Integer; var i, key, n : Integer; p : PIntegerArray; begin Result:=-1; key:=aLeft+(aTop shl 4); key:=((key and cHTFHashTableSize)+(key shr 10)+(key shr 20)) and cHTFHashTableSize; n:=Length(FHashTable[key]); if n>0 then begin p:=@FHashTable[key][0]; for i:=0 to n-1 do begin with FTileIndex[p[i]] do begin if (left=aLeft) and (top=aTop) then begin Result:=p[i]; Break; end; end; end; end; end; // GetTile // function THeightTileFile.GetTile(aLeft, aTop : Integer; pTileInfo : PPHeightTileInfo = nil) : PHeightTile; var i, n : Integer; tileInfo : PHeightTileInfo; begin with FHeightTile.info do if (left=aLeft) and (top=aTop) then begin Result:=@FHeightTile; if Assigned(pTileInfo) then pTileInfo^:=@Result.info; Exit; end; i:=GetTileIndex(aLeft, aTop); if i>=0 then begin tileInfo:=@FTileIndex[i]; if Assigned(pTileInfo) then pTileInfo^:=tileInfo; if i<High(FTileIndex) then n:=FTileIndex[i+1].fileOffset-tileInfo.fileOffset else n:=TileIndexOffset-tileInfo.fileOffset; Result:=@FHeightTile; FHeightTile.info:=tileInfo^; FFile.Position:=tileInfo.fileOffset; FFile.Read(FInBuf[0], n); UnPackTile(@FInBuf[0]); end else begin Result:=nil; if Assigned(pTileInfo) then pTileInfo^:=nil; end; end; // CompressTile // procedure THeightTileFile.CompressTile(aLeft, aTop, aWidth, aHeight : Integer; aData : PSmallIntArray); begin Assert(aWidth<=TileSize); Assert(aHeight<=TileSize); with FHeightTile.info do begin left:=aLeft; top:=aTop; width:=aWidth; height:=aHeight; fileOffset:=FFile.Position; end; PackTile(aWidth, aHeight, aData); SetLength(FTileIndex, Length(FTileIndex)+1); FTileIndex[High(FTileIndex)]:=FHeightTile.info end; // ExtractRow // procedure THeightTileFile.ExtractRow(x, y, len : Integer; dest : PSmallIntArray); var rx : Integer; n : Cardinal; tileInfo : PHeightTileInfo; tile : PHeightTile; begin while len>0 do begin tileInfo:=XYTileInfo(x, y); if not Assigned(tileInfo) then Exit; rx:=x-tileInfo.left; n:=Cardinal(tileInfo.width-rx); if n>Cardinal(len) then n:=Cardinal(len); tile:=GetTile(tileInfo.left, tileInfo.top); Move(tile.data[(y-tileInfo.top)*tileInfo.width+rx], dest^, n*2); dest:=PSmallIntArray(PtrUInt(dest)+n*2); Dec(len, n); Inc(x, n); end; end; // TileInfo // function THeightTileFile.XYTileInfo(anX, anY : Integer) : PHeightTileInfo; var tileList : TList; begin tileList:=TList.Create; try TilesInRect(anX, anY, anX+1, anY+1, tileList); if tileList.Count>0 then Result:=PHeightTileInfo(tileList.First) else Result:=nil; finally tileList.Free; end; end; // XYHeight // function THeightTileFile.XYHeight(anX, anY : Integer) : SmallInt; var tileInfo : PHeightTileInfo; tile : PHeightTile; begin // Current tile per chance? with FHeightTile.info do begin if (left<=anX) and (left+width>anX) and (top<=anY) and (top+height>anY) then begin Result:=FHeightTile.Data[(anX-left)+(anY-top)*width]; Exit; end; end; // Find corresponding tile if any tileInfo:=XYTileInfo(anX, anY); if Assigned(tileInfo) then with tileInfo^ do begin tile:=GetTile(left, top); Result:=tile.Data[(anX-left)+(anY-top)*width]; end else Result:=DefaultZ; end; // TilesInRect // procedure THeightTileFile.TilesInRect(aLeft, aTop, aRight, aBottom : Integer; destList : TList); var i, n, qx, qy, idx : Integer; p : PIntegerArray; tileInfo : PHeightTileInfo; begin destList.Count:=0; // Clamp to world if (aLeft>SizeX) or (aRight<0) or (aTop>SizeY) or (aBottom<0) then Exit; if aLeft<0 then aLeft:=0; if aRight>SizeX then aRight:=SizeX; if aTop<0 then aTop:=0; if aBottom>SizeY then aBottom:=SizeY; // Collect tiles on quads Inc(FLastMark); for qy:=QuadTableY(aTop) to QuadTableY(aBottom) do begin for qx:=QuadTableX(aLeft) to QuadTableX(aRight) do begin n:=High(FQuadTable[qx, qy]); p:=@FQuadTable[qx, qy][0]; for i:=0 to n do begin idx:=p[i]; if FTileMark[idx]<>FLastMark then begin FTileMark[idx]:=FLastMark; tileInfo:=@FTileIndex[idx]; with tileInfo^ do begin if (left<=aRight) and (top<=aBottom) and (aLeft<left+width) and (aTop<top+height) then destList.Add(tileInfo); end; end; end; end; end; end; // TileCount // function THeightTileFile.TileCount : Integer; begin Result:=Length(FTileIndex); end; // GetTiles // function THeightTileFile.GetTiles(index : Integer) : PHeightTileInfo; begin Result:=@FTileIndex[index]; end; // IndexOfTile // function THeightTileFile.IndexOfTile(aTile : PHeightTileInfo) : Integer; var c : PtrUInt; begin c:=PtrUInt(aTile)-PtrUInt(@FTileIndex[0]); if (c mod SizeOf(THeightTileInfo))=0 then begin Result:=(c div SizeOf(THeightTileInfo)); if (Result<0) or (Result>High(FTileIndex)) then Result:=-1; end else Result:=-1; end; // TileCompressedSize // function THeightTileFile.TileCompressedSize(tileIndex : Integer) : Integer; begin if tileIndex<High(FTileIndex) then Result:=FTileIndex[tileIndex+1].fileOffset-FTileIndex[tileIndex].fileOffset else Result:=TileIndexOffset-FTileIndex[tileIndex].fileOffset; end; end.
unit ParameterValuesUnit; interface uses ParametricExcelDataModule, System.Generics.Collections, SearchParameterQuery, NotifyEvents; type TParameterValues = class(TObject) private class var public class procedure LoadParameters(AProductCategoryIDArray: TArray<Integer>; AExcelTable: TParametricExcelTable); static; class procedure LoadParameterValues(AExcelTable: TParametricExcelTable; ANotifyEventRef: TNotifyEventRef); static; end; implementation uses System.SysUtils, ParametersValueQuery, ProgressInfo, System.Classes, FieldInfoUnit, System.Math, ProjectConst, MaxCategoryParameterOrderQuery, IDTempTableQuery, UpdateParamValueRec, SearchFamilyParamValuesQuery, CategoryParametersQuery, SearchComponentParamSubParamsQuery, StrHelper; // Добавляет параметры на вкладку параметры class procedure TParameterValues.LoadParameters(AProductCategoryIDArray : TArray<Integer>; AExcelTable: TParametricExcelTable); var AFieldInfo: TFieldInfo; AParamSubParamID: Integer; AOrder: Integer; AParamOrders: TDictionary<Integer, Integer>; API: TProgressInfo; AProductCategoryID: Integer; qCategoryParams: TQueryCategoryParams; i: Integer; begin Assert(Length(AProductCategoryIDArray) > 0); qCategoryParams := TQueryCategoryParams.Create(nil); AParamOrders := TDictionary<Integer, Integer>.Create; API := TProgressInfo.Create;; try AOrder := TQueryMaxCategoryParameterOrder.Max_Order; API.TotalRecords := AExcelTable.FieldsInfo.Count; i := 0; // Цикл по всем описаниям полей for AFieldInfo in AExcelTable.FieldsInfo do begin // Извещаем о том, сколько параметров уже добавили Inc(i); API.ProcessRecords := i; AExcelTable.OnProgress.CallEventHandlers(API); // Если этому полю не соответствует связка параметра с подпараметром if not AExcelTable.GetParamSubParamIDByFieldName(AFieldInfo.FieldName, AParamSubParamID) then continue; // Если такой параметр уже добавляли if AParamOrders.ContainsKey(AParamSubParamID) then AOrder := AParamOrders[AParamSubParamID] else begin Inc(AOrder); // Новый порядковый номер нашей связи между параметром и подпараметром AParamOrders.Add(AParamSubParamID, AOrder); end; // Добавляем эту связь между параметром и подпараметром в очередную категорию for AProductCategoryID in AProductCategoryIDArray do qCategoryParams.AppendOrEdit(AProductCategoryID, AParamSubParamID, AOrder); end; finally FreeAndNil(AParamOrders); FreeAndNil(qCategoryParams); FreeAndNil(API); end; end; class procedure TParameterValues.LoadParameterValues (AExcelTable: TParametricExcelTable; ANotifyEventRef: TNotifyEventRef); var AFieldInfo: TFieldInfo; AIDComponent: Integer; AParamSubParamID: Integer; API: TProgressInfo; AQueryParametersValue: TQueryParametersValue; AUpdParamSubParamList: TUpdParamSubParamList; AUpdPSP: TUpdParamSubParam; AValue: String; i: Integer; Q: TQueryFamilyParamValues; r: TMySplitRec; S: string; begin if AExcelTable.RecordCount = 0 then Exit; // Если сначала нужно создать все необходимые параметры // if AProductCategoryID > 0 then // LoadParameters(AProductCategoryID, AExcelTable); AQueryParametersValue := TQueryParametersValue.Create(nil); AUpdParamSubParamList := TUpdParamSubParamList.Create; try AExcelTable.DisableControls; try AExcelTable.First; AExcelTable.CallOnProcessEvent; while not AExcelTable.Eof do begin AIDComponent := AExcelTable.IDComponent.AsInteger; Assert(AIDComponent > 0); // Цикл по всем описаниям полей for AFieldInfo in AExcelTable.FieldsInfo do begin AExcelTable.CallOnProcessEvent; // Если этому полю не соответствует связка параметра с подпараметром if not AExcelTable.GetParamSubParamIDByFieldName(AFieldInfo.FieldName, AParamSubParamID) then continue; AExcelTable.CallOnProcessEvent; AValue := AExcelTable.FieldByName(AFieldInfo.FieldName).AsString; // если значение для параметра пустое и нет необходимости удалять старве значения if AValue.IsEmpty and not AExcelTable.Replace then continue; // Ищем все значения для какой либо связки параметра с подпараметром AQueryParametersValue.Search(AIDComponent, AParamSubParamID); // Если нужно заменить значения загружаемого параметра if AExcelTable.Replace then // Удаляем все значения параметров для текущего компонента и связки параметра с подпараметром AQueryParametersValue.W.DeleteAll; // если значение для параметра пустое if AValue.IsEmpty then continue; // Делим строку на части по запятой (учитывая скобки) r := MySplit(AValue, ','); if r.BracketInBalance then begin for S in r.StringArray do begin AValue := S.Trim; if AValue.IsEmpty then continue; // Если загружаем значение для компонента (не для семейства) if AExcelTable.IDParentComponent.AsInteger > 0 then begin if AUpdParamSubParamList.Search (AExcelTable.IDParentComponent.AsInteger, AParamSubParamID) = -1 then begin AUpdParamSubParamList.Add (TUpdParamSubParam.Create (AExcelTable.IDParentComponent.AsInteger, AParamSubParamID)); end; end; // Добавляем значение в таблицу значений связки параметра с подпараметром AQueryParametersValue.W.LocateOrAppend(AValue); AExcelTable.CallOnProcessEvent; end; end; end; AExcelTable.Next; AExcelTable.CallOnProcessEvent; end; finally AExcelTable.EnableControls; end; // Если общее значение параметра компонентов семейства выводить в ячейку семейства if AExcelTable.CopyCommonValueToFamily then begin // Единственное значение выносим я ячейку семейства Q := TQueryFamilyParamValues.Create(nil); API := TProgressInfo.Create; try API.TotalRecords := AUpdParamSubParamList.Count; i := 0; for AUpdPSP in AUpdParamSubParamList do begin // Ищем этот параметр у семейства AQueryParametersValue.Search(AUpdPSP.FamilyID, AUpdPSP.ParamSubParamID); // Если ячейка семейства пустая if AQueryParametersValue.W.Value.F.AsString.Trim.IsEmpty then begin // Если найдено единственное значение if Q.SearchEx(AUpdPSP.FamilyID, AUpdPSP.ParamSubParamID) = 1 then begin // Добавляем значение параметра для семейства AQueryParametersValue.W.AddNewValue(Q.W.Value.F.AsString); end; end; Inc(i); API.ProcessRecords := i; if Assigned(ANotifyEventRef) then ANotifyEventRef(API); end; finally FreeAndNil(Q); FreeAndNil(API); end; end; finally FreeAndNil(AQueryParametersValue); FreeAndNil(AUpdParamSubParamList); end; end; end.
unit Delphi_Messenger_Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, IPPeerClient, IPPeerServer, System.Tether.Manager, System.Tether.AppProfile, System.Actions, Vcl.ActnList, Vcl.ComCtrls; const _TETHERING_MANAGER_TEXT_='TetheringManager_RGMessenger'; _TETHERING_PROFILE_TEXT_='TetheringAppProfile_RGMessenger'; type TForm_Messenger_Main = class(TForm) Edit_Sended_Message: TEdit; Button_Send_Message: TButton; TetheringAppProfile: TTetheringAppProfile; TetheringManager: TTetheringManager; RichEdit: TRichEdit; ActionList: TActionList; procedure Button_Send_MessageClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Edit_Sended_MessageKeyPress(Sender: TObject; var Key: Char); procedure TetheringManagerRequestManagerPassword(const Sender: TObject; const ARemoteIdentifier: string; var Password: string); procedure TetheringManagerEndManagersDiscovery(const Sender: TObject; const ARemoteManagers: TTetheringManagerInfoList); procedure TetheringManagerEndProfilesDiscovery(const Sender: TObject; const ARemoteProfiles: TTetheringProfileInfoList); procedure TetheringAppProfileResourceReceived(const Sender: TObject; const AResource: TRemoteResource); private { Déclarations privées } User_Id:String; session_password:String; PROCEDURE Add_Message_to_RichEdit(CONST xAuthor:String; CONST xMessage_Added:String); public { Déclarations publiques } end; var Form_Messenger_Main: TForm_Messenger_Main; implementation {$R *.dfm} PROCEDURE TForm_Messenger_Main.Add_Message_to_RichEdit(CONST xAuthor:String; CONST xMessage_Added:String); BEGIN if RichEdit.Text='' then RichEdit.Text:=xAuthor+' : '+xMessage_Added else RichEdit.Text:=RichEdit.Text+#13+xAuthor+' : '+xMessage_Added; END; procedure TForm_Messenger_Main.Button_Send_MessageClick(Sender: TObject); procedure Send_String_To_Others_Messenger(const xSenderID, xMessageToSend:String); var i_RemoteProfile: TTetheringProfileInfo; begin try for i_RemoteProfile in TetheringManager.RemoteProfiles do TetheringAppProfile.SendString(i_RemoteProfile, xSenderID, xMessageToSend); except on E : ETetheringException do begin //to do ShowMessage(E.ClassName+' Error in Send_String_To_Others_Messenger procedure : '+E.Message); end; on E : Exception do ShowMessage(E.ClassName+' Error in Send_String_To_Others_Messenger procedure : '+E.Message); end; end; begin Send_String_To_Others_Messenger(User_Id,Edit_Sended_Message.Text); //to do Add_Message_to_RichEdit(User_Id,Edit_Sended_Message.Text); Edit_Sended_Message.Text:=''; end; procedure TForm_Messenger_Main.Edit_Sended_MessageKeyPress(Sender: TObject; var Key: Char); begin //to do : send on ctr+enter end; procedure TForm_Messenger_Main.FormCreate(Sender: TObject); function Get_ID:String; // Will be change later var Temp : PChar; Size : Cardinal; begin Size:=254; Temp:=StrAlloc(Size); IF GetComputerName(Temp,Size) THEN Result:=Temp ELSE Result:=''; StrDispose(Temp); Result.Trim; end; begin TetheringAppProfile.Text:=_TETHERING_PROFILE_TEXT_; TetheringManager.Text:=_TETHERING_MANAGER_TEXT_; session_password:='Temp_Password';// to do : change the password system RichEdit.Text:=''; User_Id:=Get_ID; TetheringManager.Password:=session_password; TetheringManager.DiscoverManagers; end; procedure TForm_Messenger_Main.TetheringAppProfileResourceReceived(const Sender: TObject; const AResource: TRemoteResource); begin if AResource.ResType = TRemoteResourceType.Data then begin Add_Message_to_RichEdit('Received : ',AResource.Value.AsString); end; end; procedure TForm_Messenger_Main.TetheringManagerEndManagersDiscovery(const Sender: TObject; const ARemoteManagers: TTetheringManagerInfoList); var i_Manager:Smallint; begin FOR i_Manager := 0 to ARemoteManagers.Count - 1 DO BEGIN IF (ARemoteManagers[I_Manager].ManagerText=_TETHERING_MANAGER_TEXT_) THEN TetheringManager.PairManager(ARemoteManagers[I_Manager]); END; end; procedure TForm_Messenger_Main.TetheringManagerEndProfilesDiscovery(const Sender: TObject; const ARemoteProfiles: TTetheringProfileInfoList); var i_Profile:SmallInt; begin for i_Profile:=0 to TetheringManager.RemoteProfiles.Count-1 do begin if(TetheringManager.RemoteProfiles[i_Profile].ProfileText=_TETHERING_PROFILE_TEXT_) then begin TetheringAppProfile.Connect(TetheringManager.RemoteProfiles[i_Profile]); //index_profile:=i_Profile; end; end end; procedure TForm_Messenger_Main.TetheringManagerRequestManagerPassword(const Sender: TObject; const ARemoteIdentifier: string; var Password: string); begin Password:=session_password; end; end.
unit NodeHelper; interface uses SourceNode, SourceLocation; procedure InsertErrorNextTo(Node: TSourceNode; const Message: String; Location: PLocation); implementation uses NodeParsing; procedure InsertErrorNextTo(Node: TSourceNode; const Message: String; Location: PLocation); var Error: TSourceNode; begin Error.Kind := ErrorNodeKind; Error.Position := Location^; Error.Data := Message; Error.AttachNextTo(Node); end; end.
(** This module contains a class to represent a form for editing the applications global options. @Author David Hoyle @Version 1.0 @Date 05 Jan 2018 **) Unit ITHelper.GlobalOptionsDialogue; Interface Uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Buttons, ComCtrls, StdCtrls, ITHelper.Interfaces; Type (** A class which represents a form **) TfrmITHGlobalOptionsDialogue = Class(TForm) lblZIPEXE: TLabel; lblZipParams: TLabel; chkGroupMessages: TCheckBox; chkAutoScrollMessages: TCheckBox; edtZipEXE: TEdit; btnBrowseZipEXE: TButton; edtZipParams: TEdit; chkSwitchToMessages: TCheckBox; lblClearMessagesAfter: TLabel; edtClearMessages: TEdit; udClearMessages: TUpDown; btnOK: TBitBtn; btnCancel: TBitBtn; dlgOpenEXE: TOpenDialog; lblShortcuts: TLabel; hkShortcut: THotKey; btnAssign: TBitBtn; lvShortcuts: TListView; btnHelp: TBitBtn; Procedure btnBrowseZipEXEClick(Sender: TObject); Procedure lvShortcutsSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); Procedure btnAssignClick(Sender: TObject); Procedure btnHelpClick(Sender: TObject); Private { Private declarations } FGlobalOps: IITHGlobalOptions; Procedure InitialiseOptions(Const GlobalOps: IITHGlobalOptions); Procedure SaveOptions(Const GlobalOps: IITHGlobalOptions); Public { Public declarations } Class Procedure Execute(Const GlobalOps: IITHGlobalOptions); End; Implementation {$R *.dfm} Uses IniFiles, ActnList, ITHelper.TestingHelperUtils, Menus; { TfrmGlobalOptionsDialogue } (** This is an on click event handler for the Assign button. @precon None. @postcon Assigns the shortcut to the selected action. @param Sender as a TObject **) procedure TfrmITHGlobalOptionsDialogue.btnAssignClick(Sender: TObject); begin If lvShortcuts.ItemIndex > -1 Then lvShortcuts.Selected.SubItems[0] := ShortCutToText(hkShortcut.HotKey); end; (** This is an on click event handler for the Browse Version From EXE button. @precon None. @postcon Allows the user to select an executable from which to get version information. @param Sender as a TObject **) Procedure TfrmITHGlobalOptionsDialogue.btnBrowseZipEXEClick(Sender: TObject); Begin dlgOpenEXE.InitialDir := ExtractFilePath(edtZipEXE.Text); dlgOpenEXE.FileName := ExtractFileName(edtZipEXE.Text); If dlgOpenEXE.Execute Then edtZipEXE.Text := dlgOpenEXE.FileName; End; (** This is an on click event handler for the Help button. @precon None. @postcon Displays the HTML Help Global Options page. @param Sender as a TObject **) Procedure TfrmITHGlobalOptionsDialogue.btnHelpClick(Sender: TObject); Const strGlobalOptions = 'GlobalOptions'; Begin HTMLHelp(0, PChar(ITHHTMLHelpFile(strGlobalOptions)), HH_DISPLAY_TOPIC, 0); End; (** This is the forms main interface method for displaying the global options. @precon GlobalOps must be a valid instance. @postcon Displays the dialogue @param GlobalOps as a IITHGlobalOptions as a constant **) Class Procedure TfrmITHGlobalOptionsDialogue.Execute(Const GlobalOps: IITHGlobalOptions); Var frm: TfrmITHGlobalOptionsDialogue; Begin frm := TfrmITHGlobalOptionsDialogue.Create(Nil); Try frm.FGlobalOps := GlobalOps; frm.InitialiseOptions(GlobalOps); If frm.ShowModal = mrOK Then frm.SaveOptions(GlobalOps); Finally frm.Free; End; End; (** This method initialises the project options in the dialogue. @precon GlobalOps must be a valid instance. @postcon Initialises the project options in the dialogue. @param GlobalOps as a IITHGlobalOptions as a constant **) Procedure TfrmITHGlobalOptionsDialogue.InitialiseOptions(Const GlobalOps: IITHGlobalOptions); Var i: Integer; A : Taction; Item : TListItem; Begin chkGroupMessages.Checked := GlobalOps.GroupMessages; chkAutoScrollMessages.Checked := GlobalOps.AutoScrollMessages; udClearMessages.Position := GlobalOps.ClearMessages; edtZipEXE.Text := GlobalOps.ZipEXE; edtZipParams.Text := GlobalOps.ZipParameters; chkSwitchToMessages.Checked := GlobalOps.SwitchToMessages; For i := 0 To Actions.Count - 1 Do If Actions[i] Is TAction Then Begin A := Actions[i] As TAction; Item := lvShortcuts.Items.Add; Item.Caption := A.Name; Item.SubItems.Add(ShortCutToText(A.ShortCut)); End; hkShortcut.HotKey := 0; End; (** This is an on select item event handler for the list view. @precon None. @postcon Assigns the actions short cut to the Hot Key control. @param Sender as a TObject @param Item as a TListItem @param Selected as a Boolean **) procedure TfrmITHGlobalOptionsDialogue.lvShortcutsSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin If Selected Then hkShortcut.HotKey := TextToShortCut(Item.SubItems[0]); end; (** This method saves the project options to the ini file. @precon GlobalOps must be a valid instance. @postcon Saves the project options to the ini file. @param GlobalOps as a IITHGlobalOptions as a constant **) Procedure TfrmITHGlobalOptionsDialogue.SaveOptions(Const GlobalOps: IITHGlobalOptions); Var i: Integer; A: TAction; Begin GlobalOps.GroupMessages := chkGroupMessages.Checked; GlobalOps.AutoScrollMessages := chkAutoScrollMessages.Checked; GlobalOps.ClearMessages := udClearMessages.Position; GlobalOps.ZipEXE := edtZipEXE.Text; GlobalOps.ZipParameters := edtZipParams.Text; GlobalOps.SwitchToMessages := chkSwitchToMessages.Checked; For i := 0 To Actions.Count - 1 Do If Actions[i] Is TAction Then Begin A := Actions[i] As TAction; A.ShortCut := TextToShortCut(lvShortcuts.Items[i].SubItems[0]); End; End; End.
unit Parser; interface uses Grammar, Classes, FMX.Dialogs; function Parse(grammar: TGrammar; iteration: Integer): String; function FetchMovements(grammar: TGrammar; production: String): TStringList; implementation function Parse(grammar: TGrammar; iteration: Integer): String; var productionIn, productionOut: String; i, j: Integer; replacement: String; begin productionIn := grammar.axiom; productionOut := ''; { Iterate over each symbol in 'productionIn' (initially the grammar axiom), adding the replacement to 'productionOut', thereby getting the grammar production for the requested iteration step. } for i := 1 to iteration do begin // Build production for iteration step i for j := 1 to length(productionIn) do begin if grammar.rules.ContainsKey(productionIn[j]) then begin // Store matching value from TDictionary into 'replacement' grammar.rules.TryGetValue(productionIn[j], replacement); // Build the production productionOut := productionOut + replacement end else // If there is no replacement rule, it is assumed to be constant productionOut := productionOut + productionIn[j]; end; // Get ready for next iteration productionIn := productionOut; productionOut := ''; end; Result := productionIn; end; // Creates a list of turtle moves to make given a production and its grammar function FetchMovements(grammar: TGrammar; production: String): TStringList; var symbol: Char; movement: String; movementList: TStringList; begin movementList := TStringList.Create; for symbol in production do begin // Store corresponding turtle move into 'movement' grammar.movements.TryGetValue(symbol, movement); movementList.Add(movement); end; Result := movementList; end; end.
PROGRAM AproxPi; USES RandUnit; FUNCTION ApproximatePi(n: longint): real; var i: longint; nrOfPointsInCircle: longint; x, y: real; BEGIN (* ApproximatePi *) nrOfPointsInCircle := 0; for i := 1 to n do begin x := RealRand; y := RealRand; if (x * x + y * y) <= 1.0 then begin Inc(nrOfPointsInCircle); end; (* IF *) end; (* FOR *) ApproximatePi := 4 * (nrOfPointsInCircle / n); END; (* ApproximatePi *) BEGIN (* AproxPi *) Write(ApproximatePi(10000000):2:8); END. (* AproxPi *)
unit ALocalizaFracaoOP; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, ExtCtrls, PainelGradiente, Grids, DBGrids, Tabela, DBKeyViolation, Componentes1, StdCtrls, Buttons, Localizacao, Mask, numericos, UnDadosProduto, Db, DBTables, UnOrdemproducao, DBClient, UnDados, UnPedidoCompra, UnProdutos; type TFLocalizaFracaoOP = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor1: TPanelColor; GridIndice1: TGridIndice; PanelColor2: TPanelColor; Label7: TLabel; Label15: TLabel; SpeedButton6: TSpeedButton; Label16: TLabel; ENumeroOp: Tnumerico; EFilial: TEditLocaliza; Localiza: TConsultaPadrao; Fracoes: TSQL; DataFracoes: TDataSource; FracoesCODFILIAL: TFMTBCDField; FracoesSEQORDEM: TFMTBCDField; FracoesSEQFRACAO: TFMTBCDField; FracoesINDPLANOCORTE: TWideStringField; FracoesC_COD_PRO: TWideStringField; FracoesC_NOM_PRO: TWideStringField; CNaoAdicionados: TCheckBox; BAdicionar: TBitBtn; FracoesSEQPRODUTO: TFMTBCDField; BFechar: TBitBtn; PPedidoCompra: TPanelColor; EEstagio: TRBEditLocaliza; SpeedButton1: TSpeedButton; Label1: TLabel; Label2: TLabel; Label3: TLabel; SpeedButton3: TSpeedButton; Label4: TLabel; EProduto: TEditColor; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BCancelarClick(Sender: TObject); procedure EFilialFimConsulta(Sender: TObject); procedure BAdicionarClick(Sender: TObject); procedure BFecharClick(Sender: TObject); procedure EEstagioSelect(Sender: TObject); procedure EProdutoExit(Sender: TObject); procedure SpeedButton3Click(Sender: TObject); procedure EProdutoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } VprLocalizaPedidoCompra, VprAcao : Boolean; VprOrdem : string; VprSeqProduto : Integer; VprPlanoCorte : TRBDPlanoCorteCorpo; VprDPedidoCorpo : TRBDPedidoCompraCorpo; FunPedidoCompra : TRBFunPedidoCompra; procedure AtualizaConsulta; procedure AdicionaFiltros(VpaSelect : TStrings); procedure ConfiguraTela; procedure AdicionaProdutoTerceirizacao(VpaDPedidoCorpo : TRBDPedidoCompraCorpo); function ExisteProduto: Boolean; function LocalizaProduto: Boolean; public { Public declarations } function LocalizaFracao(VpaDPlanoCorte : TRBDPlanoCorteCorpo):boolean;overload; function LocalizaFracao(VpaDPedidoCompra : TRBDPedidoCompraCorpo) : boolean;overload; end; var FLocalizaFracaoOP: TFLocalizaFracaoOP; implementation uses APrincipal, FunObjeto, AAdicionaProdutosTerceirizacao, ALocalizaProdutos; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFLocalizaFracaoOP.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } FunPedidoCompra := TRBFunPedidoCompra.cria(FPrincipal.BaseDados); VprOrdem := 'order by PRO.C_COD_PRO '; VprAcao := false; VprLocalizaPedidoCompra := false; end; { ******************* Quando o formulario e fechado ************************** } procedure TFLocalizaFracaoOP.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } FunPedidoCompra.Free; Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************************************************************************} function TFLocalizaFracaoOP.LocalizaFracao(VpaDPedidoCompra: TRBDPedidoCompraCorpo): boolean; begin VprLocalizaPedidoCompra := true; VprDPedidoCorpo := VpaDPedidoCompra; ConfiguraTela; showmodal; result := VprAcao; end; {******************************************************************************} function TFLocalizaFracaoOP.LocalizaProduto: Boolean; var VpfCodProduto, VpfNomProduto, VpfDesUM, VpfClaFiscal: String; begin FlocalizaProduto := TFlocalizaProduto.criarSDI(Application,'',FPrincipal.VerificaPermisao('FlocalizaProduto')); Result:= FlocalizaProduto.LocalizaProduto(VprSeqProduto,VpfCodProduto,VpfNomProduto,VpfDesUM,VpfClaFiscal); FlocalizaProduto.free; if Result then begin EProduto.Text:= VpfCodProduto; Label4.Caption:= VpfNomProduto; end else begin EProduto.Text:= ''; Label4.Caption:= ''; end; end; {******************************************************************************} procedure TFLocalizaFracaoOP.BCancelarClick(Sender: TObject); begin close; end; {******************************************************************************} function TFLocalizaFracaoOP.LocalizaFracao(VpaDPlanoCorte : TRBDPlanoCorteCorpo):boolean; begin ConfiguraTela; VprPlanoCorte := VpaDPlanoCorte; EFilial.AInteiro := VprPlanoCorte.CodFilial; EFilial.Atualiza; // ENumeroOp.AsInteger := VpaDPlanoCorte.SeqOrdemProducao; showmodal; end; {******************************************************************************} procedure TFLocalizaFracaoOP.SpeedButton3Click(Sender: TObject); begin if LocalizaProduto then AtualizaConsulta; end; {******************************************************************************} procedure TFLocalizaFracaoOP.EEstagioSelect(Sender: TObject); begin EEstagio.ASelectValida.Text := 'Select CODEST, NOMEST ' + ' FROM ESTAGIOPRODUCAO '+ ' WHERE TIPEST = ''P'''+ ' AND CODEST = @ '; EEstagio.ASelectLocaliza.Text := 'Select CODEST, NOMEST ' + ' FROM ESTAGIOPRODUCAO '+ ' WHERE TIPEST = ''P'''; end; {******************************************************************************} procedure TFLocalizaFracaoOP.AdicionaProdutoTerceirizacao(VpaDPedidoCorpo: TRBDPedidoCompraCorpo); var VpfDProdutoPedido : TRBDProdutoPedidoCompra; begin VpfDProdutoPedido := FunPedidoCompra.RProdutoPedidoCompra(VpaDPedidoCorpo,FracoesSEQPRODUTO.AsInteger,0,0,0); if VpfDProdutoPedido = nil then begin VpfDProdutoPedido := VpaDPedidoCorpo.AddProduto; FunProdutos.ExisteProduto(FracoesC_COD_PRO.AsString,VpfDProdutoPedido); VpfDProdutoPedido.QtdProduto := 0; VpfDProdutoPedido.QtdSolicitada := 0; VpfDProdutoPedido.CodCor := 0; VpfDProdutoPedido.NomCor := ''; VpfDProdutoPedido.LarChapa := 0; VpfDProdutoPedido.ComChapa := 0; end; VpfDProdutoPedido.QtdProduto := VpfDProdutoPedido.QtdProduto + 1; VpfDProdutoPedido.QtdSolicitada := VpfDProdutoPedido.QtdSolicitada + 1; FAdicionaProdutosTerceirizacao := TFAdicionaProdutosTerceirizacao.CriarSDI(self,'',true); FAdicionaProdutosTerceirizacao.AdicionaProdutos(VprDPedidoCorpo,VpfDProdutoPedido,FracoesCODFILIAL.AsInteger,FracoesSEQORDEM.AsInteger,FracoesSEQFRACAO.AsInteger); FAdicionaProdutosTerceirizacao.Free; FunOrdemProducao.MarcaEstagioComoTerceirizado(FracoesCODFILIAL.AsInteger,FracoesSEQORDEM.AsInteger,FracoesSEQFRACAO.AsInteger,EEstagio.AInteiro); AtualizaConsulta; end; {******************************************************************************} procedure TFLocalizaFracaoOP.AtualizaConsulta; var VpfPosicao : TBookmark; begin VpfPosicao := Fracoes.GetBookmark; Fracoes.close; Fracoes.sql.clear; Fracoes.sql.add('select FRA.CODFILIAL, FRA.SEQORDEM, FRA.SEQFRACAO, INDPLANOCORTE, '+ ' FRA.SEQPRODUTO, '+ ' PRO.C_COD_PRO, PRO.C_NOM_PRO '+ ' from FRACAOOP FRA, CADPRODUTOS PRO '+ ' WHERE FRA.SEQPRODUTO = PRO.I_SEQ_PRO '); AdicionaFiltros(Fracoes.sql); Fracoes.Sql.add(VprOrdem); GridIndice1.ALinhaSQLOrderBy := Fracoes.SQL.count-1; Fracoes.open; try Fracoes.GotoBookmark(VpfPosicao); except Fracoes.Last; try Fracoes.GotoBookmark(VpfPosicao); except end; end; Fracoes.FreeBookmark(VpfPosicao); end; {******************************************************************************} procedure TFLocalizaFracaoOP.AdicionaFiltros(VpaSelect : TStrings); begin if EFilial.AInteiro <> 0 then VpaSelect.Add('and FRA.CODFILIAL = '+ EFilial.Text); if ENumeroOp.AsInteger <> 0 then VpaSelect.Add('and FRA.SEQORDEM = '+ENumeroOp.Text); if VprPlanoCorte <> nil then begin if VprPlanoCorte.SeqMateriaPrima <> 0 then VpaSelect.add(' and exists(Select FRC.CODFILIAL FROM FRACAOOPCONSUMO FRC '+ ' Where FRA.CODFILIAL = FRC.CODFILIAL '+ ' AND FRA.SEQORDEM = FRC.SEQORDEM '+ ' AND FRA.SEQFRACAO = FRC.SEQFRACAO '+ ' AND FRC.SEQPRODUTO = '+IntToStr(VprPlanoCorte.SeqMateriaPrima)+')'); end; if EEstagio.AInteiro <> 0 then begin VpaSelect.Add('and exists( Select FRE.CODFILIAL FROM FRACAOOPESTAGIO FRE ' + ' Where FRA.CODFILIAL = FRE.CODFILIAL '+ ' AND FRA.SEQORDEM = FRE.SEQORDEM '+ ' AND FRA.SEQFRACAO = FRE.SEQFRACAO '+ ' AND FRE.CODESTAGIO = '+IntToStr(EEstagio.AInteiro)); if CNaoAdicionados.Checked then VpaSelect.Add(' AND FRE.INDTERCEIRIZADO = ''N'''); VpaSelect.Add(')'); end; if VprSeqProduto <> 0 then begin VpaSelect.Add(' AND FRA.SEQPRODUTO = '+IntToStr(VprSeqProduto)); end; if not VprLocalizaPedidoCompra then if CNaoAdicionados.Checked then VpaSelect.add('AND FRA.INDPLANOCORTE = ''N'''); end; {******************************************************************************} procedure TFLocalizaFracaoOP.EFilialFimConsulta(Sender: TObject); begin AtualizaConsulta; end; {******************************************************************************} procedure TFLocalizaFracaoOP.EProdutoExit(Sender: TObject); begin ExisteProduto; AtualizaConsulta; end; procedure TFLocalizaFracaoOP.EProdutoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of 13: begin if ExisteProduto then AtualizaConsulta else if LocalizaProduto then AtualizaConsulta; end; 114: if LocalizaProduto then AtualizaConsulta; end; end; {******************************************************************************} function TFLocalizaFracaoOP.ExisteProduto: Boolean; var VpfUM, VpfNomProduto: String; begin Result:= FunProdutos.ExisteProduto(EProduto.Text,VprSeqProduto,VpfNomProduto,VpfUM); if Result then Label4.Caption:= VpfNomProduto else begin Label4.Caption:= ''; if EProduto.Text <> '' then LocalizaProduto; end; end; {******************************************************************************} procedure TFLocalizaFracaoOP.BAdicionarClick(Sender: TObject); var VpfDFracao : TRBDPlanoCorteFracao; begin if VprLocalizaPedidoCompra then begin AdicionaProdutoTerceirizacao(VprDPedidoCorpo); VprAcao := true; AtualizaConsulta; end else begin if VprPlanoCorte <> nil then begin if FracoesSEQPRODUTO.AsInteger <> 0 then begin VpfDFracao := FunOrdemProducao.AdicionaFracaoPlanoCorte(VprPlanoCorte,FracoesSEQPRODUTO.AsInteger,FracoesC_COD_PRO.AsString,FracoesC_NOM_PRO.AsString); VpfDFracao.CodFilial := FracoesCODFILIAL.AsInteger; VpfDFracao.SeqOrdem := FracoesSEQORDEM.AsInteger; VpfDFracao.SeqFracao := FracoesSEQFRACAO.AsInteger; FunOrdemProducao.SetaPlanoCorteGerado(FracoesCODFILIAL.AsInteger,FracoesSEQORDEM.AsInteger,FracoesSEQFRACAO.AsInteger,true); AtualizaConsulta; end; end; end; end; {******************************************************************************} procedure TFLocalizaFracaoOP.BFecharClick(Sender: TObject); begin close; end; {******************************************************************************} procedure TFLocalizaFracaoOP.ConfiguraTela; begin AlterarVisibleDet([PPedidoCompra],VprLocalizaPedidoCompra); if VprLocalizaPedidoCompra then begin PanelColor1.Height := EProduto.Top +EProduto.Height + 5 +PPedidoCompra.Height; end else PanelColor1.Height := EProduto.Top +EProduto.Height + 5; end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFLocalizaFracaoOP]); end.
unit uTestuDrawingArea; { 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, uDrawingArea, uBase, SysUtils, uEventModel, Graphics, uGraphicPrimitive, Classes, System.UITypes; type // Test methods for class TDrawingArea TestTDrawingArea = class(TTestCase) strict private FDrawingArea: TDrawingArea; FEventModel : TEventModel; public procedure SetUp; override; procedure TearDown; override; procedure TestOne; procedure TestFindPrimitive; end; implementation procedure TestTDrawingArea.SetUp; begin FEventModel := TEventModel.Create; end; procedure TestTDrawingArea.TearDown; begin FDrawingArea.Free; FDrawingArea := nil; FreeAndNil( FEventModel ); end; procedure TestTDrawingArea.TestFindPrimitive; begin // end; procedure TestTDrawingArea.TestOne; var i : integer; pt : TPrimitiveType; begin // тестируем изменение размера и рисование фона FDrawingArea.OnNewSize( Low(Integer), 1 ); FDrawingArea.AreaBitmap; FDrawingArea.OnNewSize( 1, Low(Integer) ); FDrawingArea.AreaBitmap; FDrawingArea.OnNewSize( High(Integer), 1 ); FDrawingArea.AreaBitmap; FDrawingArea.OnNewSize( 1, High(Integer) ); FDrawingArea.AreaBitmap; for I := -100 to 100 do begin FDrawingArea.OnNewSize( i, abs( i ) ); FDrawingArea.AreaBitmap; end; FDrawingArea.BackgroundColor := clBlue; FDrawingArea.OnMouseMove( 10, 10 ); // теструем рисование рамки FDrawingArea.OnNewSize( 100, 100 ); FDrawingArea.OnMouseDown( TMouseButton.mbLeft,10, 10 ); FDrawingArea.OnMouseMove( 20, 20 ); FDrawingArea.OnMouseMove( 5, 20 ); FDrawingArea.OnMouseMove( 6, 8 ); FDrawingArea.OnMouseMove( 20, 200 ); FDrawingArea.OnMouseUp( TMouseButton.mbLeft, 20, 200 ); for pt := ptBox to High( TPrimitiveType ) do begin FDrawingArea.CreatePrimitive( 10, 10, pt ); end; end; initialization // Register any test cases with the test runner RegisterTest(TestTDrawingArea.Suite); end.
{$A+,O+,R-,S+,I+,Q-,V-,B-,X+,T-,P-,} unit IPLX; { Iniquity Programming Language - Code Parser } interface uses {$IFDEF OS2} Use32, {$ENDIF} Crt; function iplExecute(fn, par : String) : Word; function iplModule(fn, par : string) : integer; var iplError : Word; implementation uses Global, StrProc, StatBar, Logs, Files, Output, Input, Misc, Users, ShowFile, MenuCmd, Nodes, DateTime; {$DEFINE ipx} {$I ipli.pas} var errStr : String; error : Byte; xPar : String; function xErrorMsg : String; var s : String; begin case error of xrrUeEndOfFile : s := 'Unexpected end-of-file'; xrrFileNotFound : s := 'File not found, "'+errStr+'"'; xrrInvalidFile : s := 'File is not executable, "'+errStr+'"'; xrrVerMismatch : s := 'File version mismatch (script: '+errStr+', parser: '+cVersion+')'; xrrUnknownOp : s := 'Unknown script command, "'+errStr+'"'; xrrTooManyVars : s := 'Too many variables initialized at once (max '+st(maxVar)+')'; xrrMultiInit : s := 'Variable initialized recursively'; xrrDivisionByZero : s := 'Division by zero'; xrrMathematical : s := 'Mathematical parsing error'; else s := ''; end; xErrorMsg := s; end; function xExecute(fn : String) : LongInt; var f : file; xVars : Word; xVar : tVars; xpos : LongInt; xid : String[idVersion]; xver : String[idLength-idVersion]; c : Char; w : Word; function xProcExec(dp : Pointer) : tIqVar; forward; procedure xParse(svar : Word); forward; function xEvalNumber : Real; forward; procedure xInit; begin error := 0; result := 0; errStr := ''; xVars := 0; xpos := 0; FillChar(xVar,SizeOf(xVar),0); end; procedure xError(err : Byte; par : String); begin if error > 0 then Exit; error := err; xExecute := xpos; errStr := par; end; procedure xToPos(p : LongInt); begin Seek(f,p+idLength); xPos := p+1; end; function xFilePos : LongInt; begin xFilePos := filePos(f)-idLength; end; procedure xGetChar; begin if (not Eof(f)) and (error = 0) then begin BlockRead(f,c,1); c := Chr(Byte(c) xor ((xFilePos-1) mod 255)); Inc(xpos); end else begin c := #0; xError(xrrUeEndOfFile,''); end; { sbInfo('(IPL) Executing "'+fn+'" ... [pos '+st(xpos)+']',True);} end; procedure xGetWord; var blah : array[1..2] of byte absolute w; begin if (not Eof(f)) and (error = 0) then begin BlockRead(f,blah[1],1); blah[1] := blah[1] xor ((xFilePos-1) mod 255); Inc(xpos); BlockRead(f,blah[2],1); blah[2] := blah[2] xor ((xFilePos-1) mod 255); Inc(xpos); end else begin w := 0; xError(xrrUeEndOfFile,''); end; end; procedure xGoBack; begin if (xpos = 0) or (error <> 0) then Exit; xToPos(xFilePos-1); end; function xFindVar(i : Word) : Word; var x, z : Byte; begin xFindVar := 0; if xVars = 0 then Exit; z := 0; x := 1; repeat if xVar[x]^.id = i then z := x; Inc(x); until (x > xVars) or (z > 0); xFindVar := z; end; function xDataPtr(vn : Word; var a : tArray) : Pointer; begin with xVar[vn]^ do begin if arr = 0 then xDataPtr := data else begin if arr = 1 then xDataPtr := @data^[size*(a[1]-1)+1] else if arr = 2 then xDataPtr := @data^[size*((a[1]-1)*arrdim[2]+a[2])] else if arr = 3 then xDataPtr := @data^[size*((a[1]-1)*(arrdim[2]*arrdim[3])+(a[2]-1)*arrdim[3]+a[3])]; end; end; end; procedure xCheckArray(vn : Word; var a : tArray); var z : Byte; begin for z := 1 to maxArray do a[z] := 1; if xVar[vn]^.arr = 0 then Exit; for z := 1 to xVar[vn]^.arr do a[z] := Round(xEvalNumber); end; function xVarNumReal(vn : Word; var a : tArray) : Real; begin case xVar[vn]^.vtype of vByte : xVarNumReal := Byte(xDataPtr(vn,a)^); vShort : xVarNumReal := ShortInt(xDataPtr(vn,a)^); vWord : xVarNumReal := Word(xDataPtr(vn,a)^); vInt : xVarNumReal := Integer(xDataPtr(vn,a)^); vLong : xVarNumReal := LongInt(xDataPtr(vn,a)^); vReal : xVarNumReal := Real(xDataPtr(vn,a)^); end; end; function xNumReal(var num; t : tIqVar) : Real; begin case t of vByte : xNumReal := Byte(num); vShort : xNumReal := ShortInt(num); vWord : xNumReal := Word(num); vInt : xNumReal := Integer(num); vLong : xNumReal := LongInt(num); vReal : xNumReal := Real(num); end; end; function xEvalNumber : Real; var cc : Char; vn : Word; me : Boolean; pr : Real; procedure ParseNext; begin xGetChar; if c = iqo[oCloseNum] then cc := ^M else cc := c; end; function add_subt : Real; var E : Real; Opr : Char; function mult_DIV : Real; var S : Real; Opr : Char; function Power : Real; var T : Real; function SignedOp : Real; function UnsignedOp : Real; { type stdFunc = (fabs, fsqrt, fsqr, fsin, fcos, farctan, fln, flog, fexp, ffact); stdFuncList = array[stdFunc] of String[6]; const StdFuncName : stdFuncList = ('ABS','SQRT','SQR','SIN','COS','ARCTAN','LN','LOG','EXP','FACT');} var E, L, Start : Integer; F : Real; {Sf : stdFunc;} ad : tArray; ns : String; function Fact(I : Integer) : Real; begin if I > 0 then Fact := I*Fact(I-1) else Fact := 1; end; begin if cc = iqo[oVariable] then begin xGetWord; vn := xFindVar(w); xCheckArray(vn,ad); F := xVarNumReal(vn,ad); ParseNext; end else if cc = iqo[oProcExec] then begin F := 0; F := xNumReal(F,xProcExec(@F)); ParseNext; end else if cc in chDigit then begin ns := ''; repeat ns := ns+cc; ParseNext; until not (cc in chDigit); if cc = '.' then repeat ns := ns+cc; ParseNext until not (cc in chDigit); if cc = 'E' then begin ns := ns+cc; ParseNext; repeat ns := ns+cc; ParseNext; until not (cc in chDigit); end; Val(ns,F,start); if start <> 0 then me := True; end else if cc = iqo[oOpenBrack] then begin ParseNext; F := add_subt; if cc = iqo[oCloseBrack] then ParseNext else me := True; end else begin me := True; f := 0; end; UnsignedOp := F; end; begin if cc = '-' then begin ParseNext; SignedOp := -UnsignedOp; end else SignedOp := UnsignedOp; end; begin T := SignedOp; while cc = '^' do begin ParseNext; if t <> 0 then t := Exp(Ln(abs(t))*SignedOp) else t := 0; end; Power:=t; end; begin s := Power; while cc in ['*','/'] do begin Opr := cc; ParseNext; case Opr of '*' : s := s*Power; '/' : begin pr := Power; if pr = 0 then xError(xrrDivisionByZero,'') else s := s/pr; end; end; end; mult_DIV := s; end; begin E := mult_DIV; while cc in ['+','-'] do begin Opr := cc; ParseNext; case Opr of '+' : e := e+mult_DIV; '-' : e := e-mult_DIV; end; end; add_subt := E; end; begin xGetChar; { open num } { while Pos(' ',Formula) > 0 do Delete(Formula,Pos(' ',Formula),1);} { if Formula[1] = '.' then Formula := '0'+Formula;} { if Formula[1] = '+' then Delete(Formula,1,1);} { for curPos := 1 to Ord(Formula[0]) do Formula[curPos] := UpCase(Formula[curPos]);} me := False; ParseNext; xEvalNumber := add_subt; if cc <> ^M then me := True; if me then xError(xrrMathematical,''); end; function xEvalString : String; var rn : Word; x : String; ps : Byte; ad : tArray; function esString : String; var z : String; ok : Boolean; begin z := ''; esString := ''; ok := False; xGetChar; { open " string } repeat xGetChar; if c = iqo[oCloseString] then begin xGetChar; if c = iqo[oCloseString] then z := z+c else begin xGoBack; ok := True; end; end else z := z+c; until (error <> 0) or (ok); if error <> 0 then Exit; esString := z; end; begin xGetChar; { check first char of string } x := ''; if c = iqo[oOpenString] then begin xGoBack; x := esString; end else if c = iqo[oVariable] then begin xGetWord; rn := xFindVar(w); xCheckArray(rn,ad); x := String(xDataPtr(rn,ad)^); end else if c = iqo[oProcExec] then begin xProcExec(@x); end; if error <> 0 then Exit; xGetChar; if c = iqo[oStrCh] then begin ps := Round(xEvalNumber); x := x[ps]; xGetChar; end; if c = iqo[oStrAdd] then x := x+xEvalString else xGoBack; xEvalString := x; end; function xEvalBool : Boolean; type tOp = (opNone,opEqual,opNotEqual,opGreater,opLess,opEqGreat,opEqLess); var ga, gb, final : Boolean; ta, tb : tIqVar; o : tOp; rn : Word; ab, bb, inot : Boolean; af, bf : file; ar, br : Real; as, bs : String; ad : tArray; begin ta := vNone; tb := vNone; ga := False; gb := False; o := opNone; inot := False; { get the first identifier .. } repeat xGetChar; if c = iqo[oOpenBrack] then begin ab := xEvalBool; ta := vBool; xGetChar; { close bracket } ga := True; end else if c = iqo[oNot] then begin inot := not inot; end else if c = iqo[oTrue] then begin ab := True; ta := vBool; ga := True; end else if c = iqo[oFalse] then begin ab := False; ta := vBool; ga := True; end else if c = iqo[oVariable] then begin xGetWord; { variable id } rn := xFindVar(w); xCheckArray(rn,ad); ta := xVar[rn]^.vType; if ta = vBool then ab := ByteBool(xDataPtr(rn,ad)^) else if ta = vStr then as := String(xDataPtr(rn,ad)^) else if ta in vnums then ar := xVarNumReal(rn,ad); ga := True; end else if c = iqo[oProcExec] then begin ta := xProcExec(@as); if ta = vBool then ab := ByteBool(as[0]) else { if ta = vStr then as := String(xVar[rn]^.data^) else} if ta in vnums then ar := xNumReal(as,ta); ga := True; end else if c = iqo[oOpenNum] then begin xGoBack; ar := xEvalNumber; ta := vReal; ga := True; end else if c in ['#','"'] then begin xGoBack; as := xEvalString; ta := vStr; ga := True; end; until (error <> 0) or (ga); if error <> 0 then Exit; xGetChar; { get the operator .. } if c = iqo[oOpEqual] then o := opEqual else if c = iqo[oOpNotEqual] then o := opNotEqual else if c = iqo[oOpGreater] then o := opGreater else if c = iqo[oOpLess] then o := opLess else if c = iqo[oOpEqGreat] then o := opEqGreat else if c = iqo[oOpEqLess] then o := opEqLess else begin final := ab; xGoBack; end; if o <> opNone then begin { get the second identifier if necessary .. } repeat xGetChar; if c = iqo[oOpenBrack] then begin bb := xEvalBool; tb := vBool; xGetChar; { close bracket } gb := True; end else if c = iqo[oTrue] then begin bb := True; tb := vBool; gb := True; end else if c = iqo[oFalse] then begin bb := False; tb := vBool; gb := True; end else if c = iqo[oVariable] then begin xGetWord; { variable id } rn := xFindVar(w); xCheckArray(rn,ad); tb := xVar[rn]^.vType; if tb = vBool then bb := ByteBool(xDataPtr(rn,ad)^) else if tb = vStr then bs := String(xDataPtr(rn,ad)^) else if tb in vnums then br := xVarNumReal(rn,ad); gb := True; end else if c = iqo[oProcExec] then begin tb := xProcExec(@bs); if tb = vBool then bb := ByteBool(bs[0]) else if tb in vnums then br := xNumReal(bs,tb); gb := True; end else if c = iqo[oOpenNum] then begin xGoBack; br := xEvalNumber; tb := vReal; gb := True; end else if c in ['#','"'] then begin xGoBack; bs := xEvalString; tb := vStr; gb := True; end; until (error <> 0) or (gb); if error <> 0 then Exit; final := False; case o of opEqual : if ta = vStr then final := as = bs else if ta = vBool then final := ab = bb else final := ar = br; opNotEqual : if ta = vStr then final := as <> bs else if ta = vBool then final := ab <> bb else final := ar <> br; opGreater : if ta = vStr then final := as > bs else if ta = vBool then final := ab > bb else final := ar > br; opLess : if ta = vStr then final := as < bs else if ta = vBool then final := ab < bb else final := ar < br; opEqGreat : if ta = vStr then final := as >= bs else if ta = vBool then final := ab >= bb else final := ar >= br; opEqLess : if ta = vStr then final := as <= bs else if ta = vBool then final := ab <= bb else final := ar <= br; end; end; if inot then final := not final; xGetChar; if c = iqo[oAnd] then final := xEvalBool and final else if c = iqo[oOr] then final := xEvalBool or final else xGoBack; xEvalBool := final; end; procedure xSetString(vn : Word; var a : tArray; s : String); begin if Ord(s[0]) >= xVar[vn]^.size then s[0] := Chr(xVar[vn]^.size-1); Move(s,xDataPtr(vn,a)^,xVar[vn]^.size); end; procedure xSetVariable(vn : Word); var ad : tArray; begin xCheckArray(vn,ad); case xVar[vn]^.vtype of vStr : xSetString(vn,ad,xEvalString); vByte : Byte(xDataPtr(vn,ad)^) := Round(xEvalNumber); vShort : ShortInt(xDataPtr(vn,ad)^) := Round(xEvalNumber); vWord : Word(xDataPtr(vn,ad)^) := Round(xEvalNumber); vInt : Integer(xDataPtr(vn,ad)^) := Round(xEvalNumber); vLong : LongInt(xDataPtr(vn,ad)^) := Round(xEvalNumber); vReal : Real(xDataPtr(vn,ad)^) := xEvalNumber; vBool : ByteBool(xDataPtr(vn,ad)^) := xEvalBool; { vFile : will never occur ? } end; end; procedure xSetNumber(vn : Word; r : Real; var a : tArray); begin case xVar[vn]^.vtype of vByte : Byte(xDataPtr(vn,a)^) := Round(r); vShort : ShortInt(xDataPtr(vn,a)^) := Round(r); vWord : Word(xDataPtr(vn,a)^) := Round(r); vInt : Integer(xDataPtr(vn,a)^) := Round(r); vLong : LongInt(xDataPtr(vn,a)^) := Round(r); vReal : Real(xDataPtr(vn,a)^) := r; end; end; function xDataSize(vn : Word) : Word; var sz, z : Word; begin with xVar[vn]^ do begin sz := size; for z := 1 to arr do sz := sz*arrdim[z]; xDataSize := sz; end; end; procedure xCreateVar; var t : tIqVar; ci, ni, fi, slen : Word; cn, ar : Byte; ard : tArray; begin xGetChar; { variable type } t := cVarType(c); xGetChar; { check for array/strlen } slen := 256; ar := 0; for cn := 1 to maxArray do ard[cn] := 1; if c = iqo[oStrLen] then begin slen := Round(xEvalNumber)+1; xGetChar; { now check for array } end; if c = iqo[oArrDef] then begin xGetWord; ar := w; for cn := 1 to ar do ard[cn] := Round(xEvalNumber); end; { else xGoBack; -- must be a normal string } xGetWord; { number of vars } ni := w; fi := xVars+1; for ci := 1 to ni do if error = 0 then begin if xVars >= maxVar then xError(xrrTooManyVars,'') else begin xGetWord; { variable id } if xFindVar(w) > 0 then begin xError(xrrMultiInit,''); Exit; end; Inc(xVars); New(xVar[xVars]); with xVar[xVars]^ do begin id := w; vtype := t; { param } numPar := 0; proc := False; ppos := 0; if t = vStr then size := slen else size := xVarSize(t); kill := True; arr := ar; arrdim := ard; dsize := xDataSize(xVars); GetMem(data,dsize); FillChar(data^,dsize,0); end; end; end; if error <> 0 then Exit; xGetChar; { check for setvar } if c = iqo[oVarDef] then begin xSetVariable(fi); for ci := fi+1 to xVars do Move(xVar[fi]^.data^,xVar[ci]^.data^,xVar[fi]^.dsize); end else xGoBack; sbUpdate; end; procedure xGetUser; var x : Word; ss : String[1]; b : ByteBool; begin x := xUstart-1; Move(User^.Number ,xVar[x+01]^.data^,SizeOf(User^.Number )); Move(User^.UserName ,xVar[x+02]^.data^,SizeOf(User^.UserName )); Move(User^.RealName ,xVar[x+03]^.data^,SizeOf(User^.RealName )); Move(User^.Password ,xVar[x+04]^.data^,SizeOf(User^.Password )); Move(User^.PhoneNum ,xVar[x+05]^.data^,SizeOf(User^.PhoneNum )); Move(User^.BirthDate ,xVar[x+06]^.data^,SizeOf(User^.BirthDate )); Move(User^.Location ,xVar[x+07]^.data^,SizeOf(User^.Location )); Move(User^.Address ,xVar[x+08]^.data^,SizeOf(User^.Address )); Move(User^.UserNote ,xVar[x+09]^.data^,SizeOf(User^.UserNote )); ss := User^.Sex; Move(ss ,xVar[x+10]^.data^,SizeOf(ss )); Move(User^.SL ,xVar[x+11]^.data^,SizeOf(User^.SL )); Move(User^.DSL ,xVar[x+12]^.data^,SizeOf(User^.DSL )); Move(User^.BaudRate ,xVar[x+13]^.data^,SizeOf(User^.BaudRate )); Move(User^.TotalCalls ,xVar[x+14]^.data^,SizeOf(User^.TotalCalls )); Move(User^.curMsgArea ,xVar[x+15]^.data^,SizeOf(User^.curMsgArea )); Move(User^.curFileArea ,xVar[x+16]^.data^,SizeOf(User^.curFileArea )); Move(User^.LastCall ,xVar[x+17]^.data^,SizeOf(User^.LastCall )); Move(User^.PageLength ,xVar[x+18]^.data^,SizeOf(User^.PageLength )); Move(User^.EmailWaiting ,xVar[x+19]^.data^,SizeOf(User^.EmailWaiting )); ss := User^.Level; Move(ss ,xVar[x+20]^.data^,SizeOf(ss )); Move(User^.AutoSigLns ,xVar[x+21]^.data^,SizeOf(User^.AutoSigLns )); Move(User^.AutoSig ,xVar[x+22]^.data^,SizeOf(User^.AutoSig )); Move(User^.confMsg ,xVar[x+23]^.data^,SizeOf(User^.confMsg )); Move(User^.confFile ,xVar[x+24]^.data^,SizeOf(User^.confFile )); Move(User^.FirstCall ,xVar[x+25]^.data^,SizeOf(User^.FirstCall )); Move(User^.StartMenu ,xVar[x+26]^.data^,SizeOf(User^.StartMenu )); Move(User^.SysOpNote ,xVar[x+27]^.data^,SizeOf(User^.SysOpNote )); Move(User^.Posts ,xVar[x+28]^.data^,SizeOf(User^.Posts )); Move(User^.Email ,xVar[x+29]^.data^,SizeOf(User^.Email )); Move(User^.Uploads ,xVar[x+30]^.data^,SizeOf(User^.Uploads )); Move(User^.Downloads ,xVar[x+31]^.data^,SizeOf(User^.Downloads )); Move(User^.UploadKb ,xVar[x+32]^.data^,SizeOf(User^.UploadKb )); Move(User^.DownloadKb ,xVar[x+33]^.data^,SizeOf(User^.DownloadKb )); Move(User^.CallsToday ,xVar[x+34]^.data^,SizeOf(User^.CallsToday )); b := acAnsi in User^.acFlag; Move(b ,xVar[x+35]^.data^,1); b := acAvatar in User^.acFlag; Move(b ,xVar[x+36]^.data^,1); b := acRip in User^.acFlag; Move(b ,xVar[x+37]^.data^,1); b := acYesNoBar in User^.acFlag; Move(b ,xVar[x+38]^.data^,1); b := acDeleted in User^.acFlag; Move(b ,xVar[x+39]^.data^,1); b := acExpert in User^.acFlag; Move(b ,xVar[x+40]^.data^,1); b := acHotKey in User^.acFlag; Move(b ,xVar[x+41]^.data^,1); b := acPause in User^.acFlag; Move(b ,xVar[x+42]^.data^,1); b := acQuote in User^.acFlag; Move(b ,xVar[x+43]^.data^,1); Move(User^.filePts ,xVar[x+44]^.data^,SizeOf(User^.filePts )); Move(User^.todayDL ,xVar[x+45]^.data^,SizeOf(User^.todayDL )); Move(User^.todayDLkb ,xVar[x+46]^.data^,SizeOf(User^.todayDLkb )); Move(User^.textLib ,xVar[x+47]^.data^,SizeOf(User^.textLib )); Move(User^.zipCode ,xVar[x+48]^.data^,SizeOf(User^.zipCode )); Move(User^.voteYes ,xVar[x+49]^.data^,SizeOf(User^.voteYes )); Move(User^.voteNo ,xVar[x+50]^.data^,SizeOf(User^.voteNo )); end; procedure xPutUser; var x : Word; ss : String[1]; begin x := xUstart-1; Move(xVar[x+01]^.data^,User^.Number ,SizeOf(User^.Number )); Move(xVar[x+02]^.data^,User^.UserName ,SizeOf(User^.UserName )); Move(xVar[x+03]^.data^,User^.RealName ,SizeOf(User^.RealName )); Move(xVar[x+04]^.data^,User^.Password ,SizeOf(User^.Password )); Move(xVar[x+05]^.data^,User^.PhoneNum ,SizeOf(User^.PhoneNum )); Move(xVar[x+06]^.data^,User^.BirthDate ,SizeOf(User^.BirthDate )); Move(xVar[x+07]^.data^,User^.Location ,SizeOf(User^.Location )); Move(xVar[x+08]^.data^,User^.Address ,SizeOf(User^.Address )); Move(xVar[x+09]^.data^,User^.UserNote ,SizeOf(User^.UserNote )); Move(xVar[x+10]^.data^,ss ,SizeOf(ss )); User^.Sex := ss[1]; Move(xVar[x+11]^.data^,User^.SL ,SizeOf(User^.SL )); Move(xVar[x+12]^.data^,User^.DSL ,SizeOf(User^.DSL )); Move(xVar[x+13]^.data^,User^.BaudRate ,SizeOf(User^.BaudRate )); Move(xVar[x+14]^.data^,User^.TotalCalls ,SizeOf(User^.TotalCalls )); Move(xVar[x+15]^.data^,User^.curMsgArea ,SizeOf(User^.curMsgArea )); Move(xVar[x+16]^.data^,User^.curFileArea ,SizeOf(User^.curFileArea )); Move(xVar[x+17]^.data^,User^.LastCall ,SizeOf(User^.LastCall )); Move(xVar[x+18]^.data^,User^.PageLength ,SizeOf(User^.PageLength )); Move(xVar[x+19]^.data^,User^.EmailWaiting ,SizeOf(User^.EmailWaiting )); Move(xVar[x+20]^.data^,ss ,SizeOf(ss )); User^.Level := ss[1]; Move(xVar[x+21]^.data^,User^.AutoSigLns ,SizeOf(User^.AutoSigLns )); Move(xVar[x+22]^.data^,User^.AutoSig ,SizeOf(User^.AutoSig )); Move(xVar[x+23]^.data^,User^.confMsg ,SizeOf(User^.confMsg )); Move(xVar[x+24]^.data^,User^.confFile ,SizeOf(User^.confFile )); Move(xVar[x+25]^.data^,User^.FirstCall ,SizeOf(User^.FirstCall )); Move(xVar[x+26]^.data^,User^.StartMenu ,SizeOf(User^.StartMenu )); Move(xVar[x+27]^.data^,User^.SysOpNote ,SizeOf(User^.SysOpNote )); Move(xVar[x+28]^.data^,User^.Posts ,SizeOf(User^.Posts )); Move(xVar[x+29]^.data^,User^.Email ,SizeOf(User^.Email )); Move(xVar[x+30]^.data^,User^.Uploads ,SizeOf(User^.Uploads )); Move(xVar[x+31]^.data^,User^.Downloads ,SizeOf(User^.Downloads )); Move(xVar[x+32]^.data^,User^.UploadKb ,SizeOf(User^.UploadKb )); Move(xVar[x+33]^.data^,User^.DownloadKb ,SizeOf(User^.DownloadKb )); Move(xVar[x+34]^.data^,User^.CallsToday ,SizeOf(User^.CallsToday )); User^.acFlag := []; if ByteBool(xVar[x+35]^.data^[1]) then User^.acFlag := User^.acFlag+[acAnsi]; if ByteBool(xVar[x+36]^.data^[1]) then User^.acFlag := User^.acFlag+[acAvatar]; if ByteBool(xVar[x+37]^.data^[1]) then User^.acFlag := User^.acFlag+[acRip]; if ByteBool(xVar[x+38]^.data^[1]) then User^.acFlag := User^.acFlag+[acYesNoBar]; if ByteBool(xVar[x+39]^.data^[1]) then User^.acFlag := User^.acFlag+[acDeleted]; if ByteBool(xVar[x+40]^.data^[1]) then User^.acFlag := User^.acFlag+[acExpert]; if ByteBool(xVar[x+41]^.data^[1]) then User^.acFlag := User^.acFlag+[acHotKey]; if ByteBool(xVar[x+42]^.data^[1]) then User^.acFlag := User^.acFlag+[acPause]; if ByteBool(xVar[x+43]^.data^[1]) then User^.acFlag := User^.acFlag+[acQuote]; Move(xVar[x+44]^.data^,User^.filePts ,SizeOf(User^.filePts )); Move(xVar[x+45]^.data^,User^.todayDL ,SizeOf(User^.todayDL )); Move(xVar[x+46]^.data^,User^.todayDLkb ,SizeOf(User^.todayDLkb )); Move(xVar[x+47]^.data^,User^.textLib ,SizeOf(User^.textLib )); Move(xVar[x+48]^.data^,User^.zipCode ,SizeOf(User^.zipCode )); Move(xVar[x+49]^.data^,User^.voteYes ,SizeOf(User^.voteYes )); Move(xVar[x+50]^.data^,User^.voteNo ,SizeOf(User^.voteNo )); end; procedure xFileReadLn(var f : file; var s; len : Word); var c : Char; z : String; begin c := #0; z := ''; while (not eof(f)) and (not (c in [#13,#10])) do begin {$I-} BlockRead(f,c,1); {$I+} if not (c in [#13,#10]) then z := z+c; end; if (z = '') and (eof(f)) then begin if ioError = 0 then ioError := 1; end else begin Move(z,s,len); {$I-} repeat BlockRead(f,c,1); until (eof(f)) or (not (c in [#13,#10])); if not eof(f) then Seek(f,filePos(f)-1); {$I+} if ioError = 0 then ioError := ioResult; end; end; procedure xFileWriteLn(var f : file; var s; len : Word); var lf : String[2]; begin lf := #13#10; {$I-} BlockWrite(f,s,len); BlockWrite(f,lf[1],2); {$I+} if (ioError = 0) and (ioResult <> 0) then ioError := ioResult; end; function xProcExec(dp : Pointer) : tIqVar; type tParam = record s : array[1..maxParam] of String; b : array[1..maxParam] of Byte; h : array[1..maxParam] of ShortInt; w : array[1..maxParam] of Word; i : array[1..maxParam] of Integer; l : array[1..maxParam] of LongInt; r : array[1..maxParam] of Real; o : array[1..maxParam] of Boolean; { f : array[1..maxParam] of File;} v : array[1..maxParam] of Word; end; var vn, x, pid, sv : Word; p : tParam; ts : String; tb : ByteBool; ty : Byte; sub : LongInt; tl : LongInt; ss : array[1..maxParam] of Word; ttb : Boolean; tw : Word; procedure par(var dat; siz : Word); begin if dp <> nil then Move(dat,dp^,siz); end; begin xGetWord; { proc id # } pid := w; vn := xFindVar(pid); for x := 1 to xVar[vn]^.numPar do with xVar[vn]^ do begin if param[x] = UpCase(param[x]) then begin xGetChar; { variable } xGetWord; { var id } p.v[x] := xFindVar(w); if xVar[p.v[x]]^.vType = vStr then ss[x] := xVar[p.v[x]]^.size; end else case param[x] of 's' : p.s[x] := xEvalString; 'b' : p.b[x] := Round(xEvalNumber); 'h' : p.h[x] := Round(xEvalNumber); 'w' : p.w[x] := Round(xEvalNumber); 'i' : p.i[x] := Round(xEvalNumber); 'l' : p.l[x] := Round(xEvalNumber); 'r' : p.r[x] := xEvalNumber; 'o' : p.o[x] := xEvalBool; end; xGetChar; { / var separator } end; xProcExec := xVar[vn]^.vtype; if xVar[vn]^.ppos > 0 then begin sub := xFilePos; xToPos(xVar[vn]^.ppos); { xPos := xVar[vn]^.ppos;} sv := xVars; for x := 1 to xVar[vn]^.numPar do begin if xVars >= maxVar then xError(errTooManyVars,''); Inc(xVars); New(xVar[xVars]); with xVar[xVars]^ do begin id := xVar[vn]^.pid[x]; vtype := cVarType(xVar[vn]^.param[x]); numPar := 0; proc := False; ppos := 0; if vtype = vStr then size := ss[xVars] else size := xVarSize(vtype); arr := 0; {arrdim} dsize := xDataSize(xVars); if xVar[vn]^.param[x] = upCase(xVar[vn]^.param[x]) then begin data := xVar[p.v[x]]^.data; kill := False; end else begin GetMem(data,dsize); case xVar[vn]^.param[x] of 's' : begin if Ord(p.s[x,0]) >= size then p.s[x,0] := Chr(size-1); Move(p.s[x],data^,size); end; 'b' : Byte(Pointer(data)^) := p.b[x]; 'h' : ShortInt(Pointer(data)^) := p.h[x]; 'w' : Word(Pointer(data)^) := p.w[x]; 'i' : Integer(Pointer(data)^) := p.i[x]; 'l' : LongInt(Pointer(data)^) := p.l[x]; 'r' : Real(Pointer(data)^) := p.r[x]; 'o' : Boolean(Pointer(data)^) := p.o[x]; { 'f' : should never occur ? } end; kill := True; end; end; end; if xVar[vn]^.vtype <> vNone then begin { xVar[vn]^.size := xVarSize(xVar[vn]^.vtype);} xVar[vn]^.dsize := xDataSize(vn); GetMem(xVar[vn]^.data,xVar[vn]^.dsize); FillChar(xVar[vn]^.data^,xVar[vn]^.dsize,0); end; xParse(sv); if xVar[vn]^.vtype <> vNone then begin if dp <> nil then Move(xVar[vn]^.data^,dp^,xVar[vn]^.dsize); FreeMem(xVar[vn]^.data,xVar[vn]^.dsize); xVar[vn]^.dsize := 0; end; xToPos(sub); Exit; end; { %%%%% internal procedures %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% } case pid of { output routines } 0 : oWrite(p.s[1]); 1 : oWriteLn(p.s[1]); 2 : oClrScr; 3 : oClrEol; 4 : oBeep; 5 : oCwrite(p.s[1]); 6 : oCwriteLn(p.s[1]); 7 : oDnLn(p.b[1]); 8 : oGotoXY(p.b[1],p.b[2]); 9 : oMoveUp(p.b[1]); 10 : oMoveDown(p.b[1]); 11 : oMoveLeft(p.b[1]); 12 : oMoveRight(p.b[1]); 13 : oPosX(p.b[1]); 14 : oPosY(p.b[1]); 15 : oSetBack(p.b[1]); 16 : oSetFore(p.b[1]); 17 : oSetBlink(p.o[1]); 18 : oSetColor(p.b[1],p.b[2]); 19 : output.oStr(p.s[1]); 20 : oStrLn(p.s[1]); 21 : oString(p.w[1]); 22 : oStringLn(p.w[1]); 23 : oStrCtr(p.s[1]); 24 : oStrCtrLn(p.s[1]); 25 : oWriteAnsi(p.s[1]); 26 : begin tb := sfShowTextFile(p.s[1],ftNormal); par(tb,1); end; 27 : begin tb := sfShowFile(p.s[1],ftNormal); par(tb,1); end; 28 : if oWhereX <> 1 then oDnLn(1); 29 : begin ty := oWhereX; par(ty,1); end; 30 : begin ty := oWhereY; par(ty,1); end; { input routines } 40 : begin ts[0] := #1; ts[1] := iReadKey; par(ts,256); end; 41 : begin ts := iGetString(p.s[2],p.s[3],p.s[4],st(p.b[5]),p.s[1],''); par(ts,256); end; 42 : begin ts := iGetString(p.s[2],p.s[3],p.s[4],st(p.b[5]),p.s[1],st(p.b[6])); par(ts,256); end; 43 : begin tb := iKeypressed; par(tb,1); end; 44 : begin ts := iReadDate(p.s[1]); par(ts,256); end; 45 : begin ts := iReadTime(p.s[1]); par(ts,256); end; 46 : begin ts := iReadPhone(p.s[1]); par(ts,256); end; 47 : begin ts := iReadPostalCode; par(ts,256); end; 48 : begin ts := iReadZipCode; par(ts,256); end; 49 : begin tb := iYesNo(p.o[1]); par(tb,1); end; { string functions } 60 : begin ts := upStr(p.s[1]); par(ts,256); end; 61 : begin ts := strLow(p.s[1]); par(ts,256); end; 62 : begin ts := b2st(p.o[1]); par(ts,256); end; 63 : begin ty := Pos(p.s[1],p.s[2]); par(ty,1); end; 64 : begin ts := cleanUp(p.s[1]); par(ts,256); end; 65 : begin ts := strMixed(p.s[1]); par(ts,256); end; 66 : begin ts := noColor(p.s[1]); par(ts,256); end; 67 : begin ts := Resize(p.s[1],p.b[2]); par(ts,256); end; 68 : begin ts := strResizeNc(p.s[1],p.b[1]); par(ts,256); end; 69 : begin ts := ResizeRt(p.s[1],p.b[1]); par(ts,256); end; 70 : begin ts := st(p.l[1]); par(ts,256); end; 71 : begin ts := strReal(p.r[1],p.b[2],p.b[3]); par(ts,256); end; 72 : begin ts := stc(p.l[1]); par(ts,256); end; 73 : begin ts := strSquish(p.s[1],p.b[1]); par(ts,256); end; 74 : begin ts := strReplace(p.s[1],p.s[2],p.s[3]); par(ts,256); end; 75 : begin ts := Copy(p.s[1],p.b[2],p.b[3]); par(ts,256); end; 76 : begin ts := p.s[1]; Delete(ts,p.b[2],p.b[3]); par(ts,256); end; 77 : begin ts := sRepeat(p.s[1,1],p.b[2]); par(ts,256); end; 78 : begin ty := Ord(p.s[1,0]); par(ty,1); end; 79 : begin ts := strCode(p.s[1],p.b[2],p.s[3]); par(ts,256); end; 80 : begin ts := mStr(p.w[1]); par(ts,256); end; 81 : begin tl := strtoint(p.s[1]); par(tl,4); end; { ipl-related routines } 90 : begin ts := cVersion; par(ts,256); end; 91 : begin ts := cTitle; par(ts,256); end; 92 : begin ts := mStrParam(xPar,p.b[1]); par(ts,256); end; 93 : begin ty := mStrParCnt(xPar); par(ty,1); end; { user manipulation } 100 : xGetUser; 101 : xPutUser; 102 : begin User^.Number := p.w[1]; userLoad(User^); end; 103 : userSave(User^); { file i/o routines } 110 : Assign(file(Pointer(xVar[p.v[1]]^.data)^),p.s[2]); 111 : begin {$I-} Reset(file(Pointer(xVar[p.v[1]]^.data)^),1); {$I+} ioError := ioResult; end; 112 : begin {$I-} Rewrite(file(Pointer(xVar[p.v[1]]^.data)^),1); {$I+} ioError := ioResult; end; 113 : begin {$I-} Close(file(Pointer(xVar[p.v[1]]^.data)^)); {$I+} ioError := ioResult; end; 114 : begin {$I-} BlockRead(file(Pointer(xVar[p.v[1]]^.data)^),xVar[p.v[2]]^.data^,p.w[3]); {$I+} ioError := ioResult; end; 115 : begin {$I-} BlockWrite(file(Pointer(xVar[p.v[1]]^.data)^),xVar[p.v[2]]^.data^,p.w[3]); {$I+} ioError := ioResult; end; 116 : begin {$I-} Seek(file(Pointer(xVar[p.v[1]]^.data)^),p.l[2]-1); {$I+} ioError := ioResult; end; 117 : begin {$I-} tb := Eof(file(Pointer(xVar[p.v[1]]^.data)^)); {$I+} ioError := ioResult; par(tb,1); end; 118 : begin {$I-} tl := FileSize(file(Pointer(xVar[p.v[1]]^.data)^)); {$I+} ioError := ioResult; par(tl,4); end; 119 : begin {$I-} tl := FilePos(file(Pointer(xVar[p.v[1]]^.data)^))+1; {$I+} ioError := ioResult; par(tl,4); end; 120 : begin {$I-} xFileReadLn(file(Pointer(xVar[p.v[1]]^.data)^),xVar[p.v[2]]^.data^,ss[2]); {$I+} end; 121 : begin {$I-} xFileWriteLn(file(Pointer(xVar[p.v[1]]^.data)^),p.s[2],Length(p.s[2])); {$I+} end; { misc routines } 130 : begin tb := menuCommand(ttb,#0+p.s[1]+p.s[2],newMenuCmd); par(tb,1); end; 131 : begin tb := (UpStr(p.s[1]) = 'NEW') or (UpStr(p.s[1]) = 'ALL') or (UpCase(p.s[1,1]) in ['0'..'9']); par(tb,1); end; 132 : logWrite(p.s[1]); 133 : begin User^.Username := p.s[1]; tb := userSearch(User^,p.o[2]); par(tb,1); end; { multinode routines } 150 : begin ty := nodeUser(p.s[1]); par(ty,1); end; 151 : begin nodeUpdate(p.s[1]); end; 152 : begin if multinode then ts := nodeinfo^.status else ts := ''; par(ts,256); end; { date/time routines } 170 : begin tb := dtValidDate(p.s[1]); par(tb,1); end; 171 : begin tw := dtAge(p.s[1]); par(tw,2); end; end; { %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% } end; procedure xSkip; begin xGetChar; { open block } xGetWord; { size of block } xToPos(xFilePos+w); end; procedure xProcDef; var k, pi, ni : Word; t : Char; begin if xVars >= maxVar then begin xError(xrrTooManyVars,''); Exit; end; xGetWord; { procedure var id } if xFindVar(w) > 0 then begin xError(xrrMultiInit,''); Exit; end; Inc(xVars); New(xVar[xVars]); with xVar[xVars]^ do begin id := w; vtype := vNone; numPar := 0; proc := False; ppos := 0; size := 0; dsize := 0; arr := 0; {arrdim} end; xGetChar; pi := 0; while (error = 0) and (not (c in [iqo[oProcType],iqo[oOpenBlock]])) do begin t := c; xGetWord; ni := w; for k := 1 to ni do begin Inc(pi); xVar[xVars]^.param[pi] := t; xGetWord; xVar[xVars]^.pid[pi] := w; end; xGetChar; end; if c = iqo[oProcType] then begin xGetChar; xVar[xVars]^.vtype := cVarType(c); xVar[xVars]^.size := xVarSize(xVar[xVars]^.vtype); end else xGoBack; xVar[xVars]^.numpar := pi; xVar[xVars]^.ppos := xFilePos; xSkip; {ToPos(xFilePos+pSize);} end; procedure xLoopFor; var vc : Word; nstart, nend, count : Real; up : Boolean; spos : LongInt; ad : tArray; begin xGetWord; { counter variable } vc := xFindVar(w); xCheckArray(vc,ad); nstart := xEvalNumber; { start num } xGetChar; { direction (to/downto) } up := c = iqo[oTo]; nend := xEvalNumber; { ending num } count := nstart; spos := xFilePos; { save pos } if (up and (nstart > nend)) or ((not up) and (nstart < nend)) then xSkip else if up then while count <= nend do begin xSetNumber(vc,count,ad); xToPos(spos); xParse(xVars); count := count+1; end else while count >= nend do begin xSetNumber(vc,count,ad); xToPos(spos); xParse(xVars); count := count-1; end; end; procedure xWhileDo; var ok : Boolean; spos : LongInt; begin spos := xFilePos; ok := True; while (error = 0) and (ok) do begin ok := xEvalBool; if ok then begin xParse(xVars); xToPos(spos); end else xSkip; end; end; procedure xRepeatUntil; var ok : Boolean; spos : LongInt; begin spos := xFilePos; ok := True; repeat xToPos(spos); xParse(xVars); until (error <> 0) or (xEvalBool); end; procedure xIfThenElse; var ok : Boolean; begin ok := xEvalBool; if ok then xParse(xVars) else xSkip; xGetChar; { check for else } if c = iqo[oElse] then begin if not ok then xParse(xVars) else xSkip; end else xGoBack; end; procedure xGotoPos; var p : LongInt; begin xGetWord; p := w; xToPos(p); end; procedure xExitModule; begin xGetChar; if c = iqo[oOpenBrack] then begin result := Round(xEvalNumber); xGetChar; { close brack } end else xGoBack; end; procedure xParse(svar : Word); var done : Boolean; z : Word; begin xGetChar; { open block } xGetWord; { size of block } done := False; repeat xGetChar; if c = iqo[oCloseBlock] then done := True else if c = iqo[oOpenBlock] then begin xGoBack; xParse(xVars); end else if c = iqo[oVarDeclare] then xCreateVar else if c = iqo[oSetVar] then begin xGetWord; xSetVariable(xFindVar(w)); end else if c = iqo[oProcExec] then xProcExec(nil) else if c = iqo[oProcDef] then xProcDef else if c = iqo[oFor] then xLoopFor else if c = iqo[oIf] then xIfThenElse else if c = iqo[oWhile] then xWhileDo else if c = iqo[oRepeat] then xRepeatUntil else if c = iqo[oGoto] then xGotoPos else if c = iqo[oExit] then begin xExitModule; done := True; end else xError(xrrUnknownOp,c); until (error <> 0) or (done); {xGetChar; { close block } for z := xVars downto svar+1 do begin if (xVar[z]^.kill) and (xVar[z]^.data <> nil) then FreeMem(xVar[z]^.data,xVar[z]^.dsize); Dispose(xVar[z]); end; xVars := svar; end; procedure xTerminate; var z : Word; begin for z := 1 to xVars do begin if (xVar[z]^.kill) and (xVar[z]^.data <> nil) then FreeMem(xVar[z]^.data,xVar[z]^.dsize); Dispose(xVar[z]); end; xVars := 0; end; begin xExecute := 0; xInit; w := 0; Assign(f,fn); {$I-} Reset(f,1); {$I+} if ioResult <> 0 then begin xError(xrrFileNotFound,fn); Exit; end; if FileSize(f) < idLength then begin Close(f); xError(xrrInvalidFile,fn); Exit; end; FillChar(xid,SizeOf(xid),32); FillChar(xver,SizeOf(xver),32); xid[0] := chr(idVersion); xver[0] := chr(idLength-idVersion); BlockRead(f,xid[1],idVersion); BlockRead(f,xver[1],idLength-idVersion); while not (xver[Ord(xver[0])] in ['0'..'9','a'..'z']) do Dec(xver[0]); if cleanUp(xid) <> cProgram then begin Close(f); xError(xrrInvalidFile,fn); Exit; end; if cleanUp(xver) <> cVersion then begin Close(f); xError(xrrVerMismatch,cleanUp(xver)); Exit; end; cInitProcs(xVar,xVars,w); xParse(xVars); xTerminate; Close(f); xExecute := xpos; end; function iplExecute(fn, par : String) : Word; var z, m1, m2 : LongInt; x : String; begin m1 := maxavail; xPar := par; iplExecute := 250; iplError := 0; fn := upStr(fn); if Pos('.',fn) = 0 then fn := fn+extIPLexe; if not fExists(fn) then begin x := cfg^.pathIPLX+fn; if not fExists(x) then begin logWrite('xIPL: Error opening "'+x+'"; file not found'); Exit; end else fn := x; end; { sbInfo('(IPL) Executing "'+fn+'" ...',True);} logWrite('IPL: Executed "'+fn+'"'); z := xExecute(fn); if error <> 0 then begin m2 := maxavail; if (error <> 0) or (m1-m2 <> 0) { then sbInfo('(IPL) Execution successful. ['+st(z)+' bytes] memdiff: '+st(m1-m2),False)} then sbInfo('(IPL) Error: '+xErrorMsg+' [pos '+st(z)+'] memdiff: '+st(m1-m2),False); iplError := error; end else iplExecute := result; end; function iplModule(fn, par : string) : integer; var r : word; begin iplModule := -1; if pos('\',fn) = 0 then fn := cfg^.pathIPLX+fn; if pos('.',strFilename(fn)) = 0 then fn := fn+extIPLexe; r := iplExecute(fn, par); if iplError <> 0 then exit; iplModule := r; end; end.
unit MediaServer.Definitions; interface uses SysUtils, Classes, Generics.Collections, SyncObjs, MediaProcessing.Definitions,MediaServer.Net.Definitions,RTSP.Definitions; type TMediaStreamWorkingConditions = (mscNormal,mscUnauthorizedUser,mscBlockedUser,mscDisconnected,mscInsufficientPrivileges, mscOverqueue); TForwarderDataInfo = record SkippedFrameCount: cardinal; SkippedFrameSize: cardinal end; IMediaStreamForwarder = interface ['{A32EC10F-BE08-4C1B-80C7-30A75F2CBFC5}'] procedure OnData(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal; const aDataInfo: TForwarderDataInfo); procedure Shutdown; function TypeName: string; function LastResponse: TDateTime; function DestinationDescription: string; function Remarks: string; //Сколько данных отправлено function DataSent: int64; end; IMediaStreamForwarderSyncExtension = interface ['{5AFC3317-75EC-4A56-BFEA-AB8BA0492DAE}'] function OnSync(aCurrentQueueSize,aCurrentQueueLength, aMaxQueueSize, aMaxQueueLength,aMaxQueueDuration: cardinal; out aDelayInFrames,aDelayInMs, aDelayInBytes: int64):boolean; end; IMediaStreamTransport = interface procedure Send(ABuffer: pointer; aBufferSize: integer; out aAck: boolean); procedure SendBytes(ABuffer: TBytes; out aAck: boolean); function DestinationDescription: string; function Name: string; procedure Shutdown; end; IMediaStreamTransportReadExtension = interface ['{0B85CB65-7FED-41E8-B064-345EACB08829}'] procedure ReadBytes(var ABuffer: TBytes); end; IRtspMediaStreamTransport = IMediaStreamTransport; IRtspMediaStreamForwarder = interface (IMediaStreamForwarder) ['{C16FBF1C-82F9-486C-9503-A47CC0D315C1}'] end; I3SMediaStreamForwarder = interface (IMediaStreamForwarder) ['{1FE4AD3B-A081-4EE5-9FA6-6695500C8890}'] procedure SetDataTransport(const aTransport: IMediaStreamTransport); procedure SetSyncTransport(const aSocket: THandle); end; IMscpMediaStreamForwarder = interface (IMediaStreamForwarder) ['{241532F3-DA23-46BE-804C-AC252ACDC878}'] //Получить снимок в формате BMP для универсальности данные передаются в виде потока //Чтобы загрузить из в Bitmap, можно сделать TBitmap.LoadFromStream procedure GetSnapshot(aStream: TStream); function DataReadyEventHandle: THandle; end; IRelayMediaStreamForwarder = interface (IMediaStreamForwarder) ['{2DEB1957-6EDE-4C9C-91C5-9E9F8354342E}'] end; IMediaStreamDataSink = interface procedure OnData(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); end; IMediaStreamDataSinkArray = array of IMediaStreamDataSink; TUserInfo = record UserName : string; Password: string; IsBlocked: boolean; IsUnauthorized: boolean; InsufficientPrivileges: boolean; //Для данного пользователя запрошенный источник не доступен end; EMediaServerCommandError = class (Exception); EMediaServerCommandError_WrongLogin = class (EMediaServerCommandError) public constructor Create; end; EMediaServerCommandError_WrongSourceName = class (EMediaServerCommandError) public constructor Create; end; EMediaServerCommandError_WrongSourceIndex = class (EMediaServerCommandError) public constructor Create; end; EMediaServerCommandError_WrongStreamHandle = class (EMediaServerCommandError) public constructor Create; end; EMediaServerCommandError_NeedAuthentication = class (EMediaServerCommandError) public constructor Create; end; EMediaServerCommandError_WrongUserNameOrPassword = class (EMediaServerCommandError) public constructor Create; end; EMediaServerCommandError_SourceUnavailable = class (EMediaServerCommandError) public constructor Create; end; EMediaServerCommandError_UnsupportedMediaType = class (EMediaServerCommandError) constructor Create; end; EMediaServerCommandError_ArchiveDisabled = class (EMediaServerCommandError) public constructor Create; end; EMediaServerCommandError_ArchiveSourceNotFound = class (EMediaServerCommandError) public constructor Create; end; EMediaServerCommandError_ArchiveUnavailable = class (EMediaServerCommandError) public constructor Create(const aInnerExceptionMessage: string); end; EMediaServerCommandError_ArchiveQueryIsEmpty = class (EMediaServerCommandError) public constructor Create; end; EMediaServerCommandError_UserBlocked = class (EMediaServerCommandError) public constructor Create; end; EMediaServerCommandError_SourceInaccessibleForUser = class (EMediaServerCommandError) public constructor Create; end; EMediaServerCommandError_TimedOut = class (EMediaServerCommandError) public constructor Create; overload; constructor Create(const aMessage: string); overload; end; EMediaServerCommandError_NotAppropriateState = class (EMediaServerCommandError) public constructor Create(const aCurrentState: string); end; implementation { EMediaServerCommandError_WrongSourceName } constructor EMediaServerCommandError_WrongSourceName.Create; begin inherited Create('Неверное имя устройства'); end; { EMediaServerCommandError_WrongLogin } constructor EMediaServerCommandError_WrongLogin.Create; begin inherited Create('Неверный логин'); end; { EMediaServerCommandError_Index } constructor EMediaServerCommandError_WrongSourceIndex.Create; begin inherited Create('Неверный индекс устройства'); end; { EMediaServerCommandError_WrongUserNameOrPassword } constructor EMediaServerCommandError_WrongUserNameOrPassword.Create; begin inherited Create('Неверное имя пользователя или пароль'); end; { EMediaServerCommandError_NeedAuthentication } constructor EMediaServerCommandError_NeedAuthentication.Create; begin inherited Create('Необходима аутентификация'); end; { EMediaServerCommandError_WrongStreamHandle } constructor EMediaServerCommandError_WrongStreamHandle.Create; begin inherited Create('Неверный дескриптор потока'); end; { EMediaServerCommandError_UnsupportedMediaType } constructor EMediaServerCommandError_UnsupportedMediaType.Create; begin inherited Create('Неподдерживаемый тип потока'); end; { EMediaServerCommandError_ArchiveDisabled } constructor EMediaServerCommandError_ArchiveDisabled.Create; begin inherited Create('Функция архива не подключена'); end; { EMediaServerCommandError_ArchiveUnavailable } constructor EMediaServerCommandError_ArchiveUnavailable.Create( const aInnerExceptionMessage: string); begin inherited CreateFmt('Не удалось подключиться к архиву: %s',[aInnerExceptionMessage]); end; { EMediaServerCommandError_ArchiveQueryIsEmpty } constructor EMediaServerCommandError_ArchiveQueryIsEmpty.Create; begin inherited Create('За указанный период в архиве нет сведений'); end; { EMediaServerCommandError_UserBlocked } constructor EMediaServerCommandError_UserBlocked.Create; begin inherited Create('Пользователь заблокирован'); end; { EMediaServerCommandError_TimedOut } constructor EMediaServerCommandError_TimedOut.Create; begin inherited Create('Таймаут выполнения операции'); end; constructor EMediaServerCommandError_TimedOut.Create(const aMessage: string); begin inherited Create(aMessage); end; { EMediaServerCommandError_SourceInaccessibleForUser } constructor EMediaServerCommandError_SourceInaccessibleForUser.Create; begin inherited Create('Источник для данного пользователя не доступен'); end; { EMediaServerCommandError_NotWorking } constructor EMediaServerCommandError_NotAppropriateState.Create(const aCurrentState: string); begin inherited CreateFmt('Сервер находится в состоянии %s',[aCurrentState]); end; { EMediaServerCommandError_ArchiveSourceNotFound } constructor EMediaServerCommandError_ArchiveSourceNotFound.Create; begin inherited Create('Указанный источник архива не найден'); end; { EMediaServerCommandError_SourceUnavailable } constructor EMediaServerCommandError_SourceUnavailable.Create; begin inherited Create('Устройство не доступно для подключения'); end; end.
unit Optimizer.Template; interface uses Generics.Collections, Getter.OS.Version, OS.Version.Helper; type IOptimizationUnit = interface['{4B334B0F-9AB0-4D12-8CCB-8307FA239698}'] function IsOptional: Boolean; function IsCompatible: Boolean; function IsApplied: Boolean; function GetName: String; procedure Apply; procedure Undo; end; TOptimizationUnit = class abstract(TInterfacedObject, IOptimizationUnit) public function IsOptional: Boolean; virtual; abstract; function IsCompatible: Boolean; virtual; abstract; function IsApplied: Boolean; virtual; abstract; function GetName: String; virtual; abstract; procedure Apply; virtual; abstract; procedure Undo; virtual; abstract; protected function IsBelowWindows8: Boolean; function IsAtLeastWindows10: Boolean; end; TOptimizerList = TList<IOptimizationUnit>; implementation { TOptimizationUnit } function TOptimizationUnit.IsAtLeastWindows10: Boolean; begin result := OS.Version.Helper.IsAtLeastWindows10(VersionHelper.Version); end; function TOptimizationUnit.IsBelowWindows8: Boolean; begin result := OS.Version.Helper.IsBelowWindows8(VersionHelper.Version); end; end.
unit UReadMemoryFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, PsAPI, TlHelp32; type TReadMemoryForm = class(TForm) stat1: TStatusBar; ReadMemoryProgress: TProgressBar; private { Private declarations } public { Public declarations } end; TReadMemory = class public function GetProcessInfo: TList; end; var ReadMemoryForm: TReadMemoryForm; implementation {$R *.dfm} uses UPubilcDefine; //1:CreateToolhelp32Snapshot()创建系统快照句柄(hSnapShot是我们声明用来保存 //创建的快照句柄) //2:Process32First、Process32Next是用来枚举进程 function TReadMemory.GetProcessInfo: TList; var ProcessInfoList : TList; ProcessInfo : PProcessInfo; hSnapShot : THandle; mProcessEntry32 : TProcessEntry32; bFound : Boolean; begin ProcessInfoList := TList.Create; ProcessInfoList.Clear; hSnapShot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); mProcessEntry32.dwSize := Sizeof(mProcessEntry32); bFound := Process32First(hSnapShot, mProcessEntry32); while bFound do begin New(ProcessInfo); ProcessInfo.ProcessExe := mProcessEntry32.szExeFile; ProcessInfo.ProcessId := mProcessEntry32.th32ProcessID; ProcessInfoList.Add(ProcessInfo); bFound := Process32Next(hSnapShot, mProcessEntry32); end; Result := ProcessInfoList; end; {=============内存查找=========================} function TReadMemoryForm.StartSearch: Boolean; var ProcHandle:Integer; begin Result:=False; ReadMemoryProgress.Position:=0; if Not CheckInput then Exit; if FileName=TabSheet1.Caption then //-----------------------------------------搜索次数>1次 begin PParameter.FirstSearch:=False; PParameter.Data:=StrToInt(EdtSearchData.Text); end else begin //-----------------------------------------第一次搜索 PParameter.FirstSearch:=True; if PParameter.ProcessHandle>0 then CloseHandle(PParameter.ProcessHandle); ProcHandle:=OpenProcess(PROCESS_ALL_ACCESS,false,StrToInt(EdtProcID.Text)); if ProcHandle>0 then begin PParameter.Data:=StrToInt(EdtSearchData.Text); Case DataType.ItemIndex of 0:PParameter.DataType:=1; 1:PParameter.DataType:=2; 2:PParameter.DataType:=4; end; end else Exit; FileName:=TabSheet1.Caption; PParameter.ProcessHandle:=ProcHandle; end; SearchButton.Enabled:=False; ToolSearchMemory.Enabled:=False; MemoryAddrList.Clear; PReadMemory.StartSearch; Result:=True; end; //1: HANDLE OpenProcess( //DWORD dwDesiredAccess, // 希望获得的访问权限 //BOOL bInheritHandle, // 指明是否希望所获得的句柄可以继承 //DWORD dwProcessId // 要访问的进程ID //); //分析内存块 //------------------------------------------------------------------------------分析内存块 function TReadMemoryThread.GetMemoryRegion: Boolean; var TempStartAddress : DWord; TempEndAddress : DWord; I,J,k : Integer; NewMemoryRegions : array [0..40000] of TmemoryRegion; begin Result:=False; MemoryRegionsIndex := 0; TempStartAddress := 1*1024*1024; TempEndAddress := 2*1024*1024; TempEndAddress := TempEndAddress*1024; While (VirtualQueryEx(PParameter.ProcessHandle, pointer(TempStartAddress), MBI, sizeof(MBI))>0) and (TempStartAddress<TempEndAddress) do begin if (MBI.State=MEM_COMMIT) then begin if (MBI.Protect=PAGE_READWRITE) or (MBI.Protect=PAGE_WRITECOPY) or (MBI.Protect=PAGE_EXECUTE_READWRITE) or (MBI.Protect=PAGE_EXECUTE_WRITECOPY) then begin PMemoryRegion[MemoryRegionsIndex].BaseAddress:=Dword(MBI.BaseAddress); PMemoryRegion[MemoryRegionsIndex].MemorySize:=MBI.RegionSize; Inc(MemoryRegionsIndex); end; end; TempStartAddress:=Dword(MBI.BaseAddress)+MBI.RegionSize; end; if MemoryRegionsIndex=0 then Exit; //------------------------------------------------------------------------------判断内存块是否过大 J:=0; for i:=0 to MemoryRegionsIndex-1 do begin if PMemoryRegion.MemorySize>$FFFF then begin for K:=0 to PMemoryRegion.MemorySize div $FFFF do begin if K=PMemoryRegion.MemorySize div $FFFF+1 then begin NewMemoryRegions[j].BaseAddress:=PMemoryRegion.BaseAddress+K*$FFFF; NewMemoryRegions[j].MemorySize:=PMemoryRegion.MemorySize Mod $FFFF; end else begin NewMemoryRegions[j].BaseAddress:=PMemoryRegion.BaseAddress+K*$FFFF; NewMemoryRegions[j].MemorySize:=$FFFF; end; Inc(J); end; end else begin NewMemoryRegions[j].BaseAddress:=PMemoryRegion.BaseAddress; NewMemoryRegions[j].MemorySize:=PMemoryRegion.MemorySize; Inc(J); end; end; //------------------------------------------------------------------------------数据转换 MemoryRegionsIndex:=j; for i:=0 to MemoryRegionsIndex-1 do begin PMemoryRegion.MemorySize:=NewMemoryRegions.MemorySize; PMemoryRegion.BaseAddress:=NewMemoryRegions.BaseAddress; end; Result:=True; end; //1:查找的内存大小 //TempStartAddress := 1*1024*1024; //TempEndAddress := 2*1024*1024; //TempEndAddress := TempEndAddress*1024; //2:VirtualQueryEx :查询地址空间中内存地址的信息。 //参数: //hProcess 进程句柄。 //LpAddress 查询内存的地址。 //LpBuffer 指向MEMORY_BASIC_INFORMATION结构的指针,用于接收内存信息。 //DwLength MEMORY_BASIC_INFORMATION结构的大小。 //返回值: //函数写入lpBuffer的字节数,如果不等于sizeof(MEMORY_BASIC_INFORMATION)表示失败。 //http://www.vckbase.com/vckbase/function/viewfunc.asp?id=139 讲了这个API的详细信息 {=============================================} {=============开始查找=========================} {=============================================} procedure TReadMemoryThread.Execute; var //StopAddr,StartAddr:Dword; BeginTime,EndTime:String; I:Integer; begin inherited; while Not Terminated do begin AddrCount := 0; if PParameter.FirstSearch then begin if Not GetMemoryRegion then Exit; GetMaxMemoryRange; GetMinMemoryRange; SendMessage(APPHandle,WM_READMEMORY,RM_MAXPROGRESS,MemoryRegionsIndex); BeginTime:=FloatToStr(CPUTimeCounterQPC); for I:=0 to MemoryRegionsIndex-1 do begin FirstCheckMemory(PMemoryRegion.BaseAddress,PMemoryRegion.MemorySize); end; EndTime:=FloatToStr(CPUTimeCounterQPC); SendMessage(APPHandle, WM_READMEMORY, RM_USETIME, StrToInt(Copy(EndTime,1,Pos('.',EndTime)-1))-StrToInt(Copy(BeginTime,1,Pos('.',BeginTime)-1))); SendMessage(APPHandle,WM_READMEMORY,RM_ADDRCOUNT,AddrCount); SendMessage(APPHandle,WM_READMEMORY,RM_FINISH,RM_FINISH); end else begin SendMessage(APPHandle,WM_READMEMORY,RM_MAXPROGRESS,100); BeginTime:=FloatToStr(CPUTimeCounterQPC); for i:=0 to High(PSearchAgain) do begin SecondCheckMemory(PSearchAgain.DataAddr); end; EndTime:=FloatToStr(CPUTimeCounterQPC); SendMessage(APPHandle, WM_READMEMORY, RM_USETIME, StrToInt(Copy(EndTime,1,Pos('.',EndTime)-1))-StrToInt(Copy(BeginTime,1,Pos('.',BeginTime)-1))); SendMessage(APPHandle,WM_READMEMORY,RM_ADDRCOUNT,AddrCount); SendMessage(APPHandle,WM_READMEMORY,RM_FINISH,RM_FINISH); end; Suspend; end; end; //------------------------------------------------------------------------------第一次查询 function TReadMemoryThread.FirstCheckMemory(Addr:Integer;ReadCount:Integer): Boolean; var i:Integer; Buffer:TByteArray; LPDW:DWORD; begin //Result:=False; SendMessage(APPHandle,WM_READMEMORY,RM_GETPOS,RM_GETPOS); //ZeroMemory(@Buffer,Sizeof(Buffer)); //SetLength(Buffer,ReadCount); if ReadProcessMemory(PParameter.processhandle,pointer(Addr),pointer(@(buffer)),ReadCount,Lpdw) then begin if Lpdw>0 then begin I:=1; While I<=Lpdw do begin case PParameter.DataType of 1: begin if PByte(@(Buffer))^=PParameter.Data then begin PSearchResult.Data:=PParameter.Data; PSearchResult.DataAddr:=Addr+i-1; PSearchResult.DataType:=PParameter.DataType; if AddrCount<=99 then begin PSearchAgain[AddrCount].Data:=PParameter.Data; PSearchAgain[AddrCount].DataType:=PParameter.DataType; PSearchAgain[AddrCount].DataAddr:=Addr+i-1; end; Inc(AddrCount); SendMessage(APPHandle,WM_READMEMORY,RM_GETADDR,RM_GETADDR); end; end; 2: begin if PWord(@(Buffer))^=PParameter.Data then begin PSearchResult.Data:=PParameter.Data; PSearchResult.DataAddr:=Addr+i-1; PSearchResult.DataType:=PParameter.DataType; if AddrCount<=99 then begin PSearchAgain[AddrCount].Data:=PParameter.Data; PSearchAgain[AddrCount].DataType:=PParameter.DataType; PSearchAgain[AddrCount].DataAddr:=Addr+i-1; end; Inc(AddrCount); SendMessage(APPHandle,WM_READMEMORY,RM_GETADDR,RM_GETADDR); end; end; 4: begin if PLongword(@(Buffer))^=PParameter.Data then begin PSearchResult.Data:=PParameter.Data; PSearchResult.DataAddr:=Addr+i-1; PSearchResult.DataType:=PParameter.DataType; if AddrCount<=99 then begin PSearchAgain[AddrCount].Data:=PParameter.Data; PSearchAgain[AddrCount].DataType:=PParameter.DataType; PSearchAgain[AddrCount].DataAddr:=Addr+i-1; end; Inc(AddrCount); SendMessage(APPHandle,WM_READMEMORY,RM_GETADDR,RM_GETADDR); end; end; end; Inc(I); end; end; end; Result:=True; end; //------------------------------------------------------------------------------多次查询 function TReadMemoryThread.SecondCheckMemory(Addr:Integer): Boolean; var Buffer:TByteArray1; Lpdw:DWord; begin SendMessage(APPHandle,WM_READMEMORY,RM_GETPOS,RM_GETPOS); if ReadProcessMemory(PParameter.processhandle, pointer(Addr), pointer(@(buffer[1])), PParameter.DataType,Lpdw) then begin Case PParameter.DataType of 1: begin if PByte(@(Buffer))^=PParameter.Data then begin PSearchResult.Data:=PParameter.Data; PSearchResult.DataAddr:=Addr; PSearchResult.DataType:=PParameter.DataType; Inc(AddrCount); SendMessage(APPHandle,WM_READMEMORY,RM_GETADDR,RM_GETADDR); end; end; 2: begin if PWord(@(Buffer))^=PParameter.Data then begin PSearchResult.Data:=PParameter.Data; PSearchResult.DataAddr:=Addr; PSearchResult.DataType:=PParameter.DataType; Inc(AddrCount); SendMessage(APPHandle,WM_READMEMORY,RM_GETADDR,RM_GETADDR); end; end; 4: begin if PLongword(@(Buffer))^=PParameter.Data then begin PSearchResult.Data:=PParameter.Data; PSearchResult.DataAddr:=Addr; PSearchResult.DataType:=PParameter.DataType; Inc(AddrCount); SendMessage(APPHandle,WM_READMEMORY,RM_GETADDR,RM_GETADDR); end; end; end; end; Result:=True; end; //1: ReadProcessMemory //http://www.vckbase.com/vckbase/funct ... sp?id=148 具体用法 //参数 //hProcess //目标进程的句柄,该句柄必须对目标进程具有PROCESS_VM_READ 的访问权限。 //lpBaseAddress //从目标进程中读取数据的起始地址。 在读取数据前,系统将先检验该地址的数据是否可读,如果不可读,函数将调用失败。 //lpBuffer //用来接收数据的缓存区地址。 //nSize //从目标进程读取数据的字节数。 //lpNumberOfBytesRead //实际被读取数据大小的存放地址。如果被指定为NULL,那么将忽略此参数。 //返回值 //如果函数执行成功,返回值非零。 //如果函数执行失败,返回值为零。调用 GetLastError 函数可以获取该函数执行错误的信息。 //如果要读取一个进程中不可访问空间的数据,该函数就会失败。 //2: //PByte = ^Byte; //PWord = ^Word; //PLongword = ^Longword; //数据类型指针 //如果在内存中是:AA BB CC DD //那么读出来实际上:PByte (@(Buffer))^ AA //PWord(@(Buffer))^ BBAA //PLongword (@(Buffer))^ DDCCBBAA {=============================================} {=============修改内存=========================} {=============================================} procedure TReadMemoryForm.ChangeMemoryClick(Sender: TObject); var LPDW:DWord; NewData:Integer; PDataType:Integer; begin if Not ElevPrivileges(False) Then begin DisMessage('提高程序权限失败'); Exit; end; if (EdtAddr.Text='') or (EdtDataType.Text='') or (EdtNewData.Text='') then begin DisMessage('请输入数据'); Exit; end; case EdtDataType.ItemIndex of 0: begin PDataType:=1; end; 1: begin PDataType:=2; end; 2: begin PDataType:=4; end; end; try NewData:=StrToInt(EdtNewData.Text); if WriteProcessMemory(PParameter.ProcessHandle, pointer(strtoint('$'+EdtAddr.Text)), @NewData, PDataType, LPDW) then begin DisMessage('修改成功'); end else begin DisMessage('修改失败'); end; except DisMessage('修改失败'); end; end; //1:WriteProcessMemory //参数含义同ReadProcessMemory,其中hProcess句柄要有对进程的PROCESS_VM_WRITE和PROCESS_VM_OPERATION权限.lpBuffer为要写到指定进程的数据的指针. //2:因为有写内存是只读的你可以修改内存属性来修改内存 function TBaseHOOK.GetMemoryProperty(Addr:Pointer): DWord; var lpBuffer: TMemoryBasicInformation; begin Result:=0; if VirtualQueryEx(DestHandle,Addr,lpBuffer,sizeof(lpBuffer))>0 then begin if lpBuffer.State=MEM_COMMIT then begin Result:=lpBuffer.Protect; end; end; end; //MemoryProperty:=GetMemoryProperty(OldFun); {得到内存属性} //VirtualProtectEx(DestHandle //,OldFun //,8 //,PAGE_READWRITE //,@GetCurrentProcessId); {修改内存属性} //if Not WriteProcessMemory(DestHandle, //OldFun, //@FunJumpCode[FunIndex[FunName]].NewJmpCode, //8, //dwSize)then Exit; //VirtualProtectEx(DestHandle {恢复内存属性} //,OldFun //,8 //,MemoryProperty //,@GetCurrentProcessId); end.
{*******************************************************} { } { Delphi Runtime Library } { SOAP Support } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit Soap.WSDLSOAP; interface uses Soap.InvokeRegistry, System.Types; type TWSDLSOAPPort = class(TRemotable) private FPortName: WideString; FAddresses: TWideStringDynArray; published property PortName: WideString read FPortName write FPortName; property Addresses: TWideStringDynArray read FAddresses write FAddresses; end; TWSDLSOAPPortArray = array of TWSDLSOAPPort; implementation uses Soap.SOAPConst; initialization RemClassRegistry.RegisterXSClass(TWSDLSOAPPort, SBorlandTypeNamespace); end.
{ ************************************************************** Package: XWB - Kernel RPCBroker Date Created: Sept 18, 1997 (Version 1.1) Site Name: Oakland, OI Field Office, Dept of Veteran Affairs Developers: Danila Manapsal, Don Craven, Joel Ivey, Herlan Westra Description: Contains TRPCBroker and related components. Unit: CCOWRPCBroker Authenticates user using CCOW Current Release: Version 1.1 Patch 65 *************************************************************** } { ************************************************** Changes in v1.1.65 (HGW 07/19/2016) XWB*1.1*65 1. Updated RPC Version to version 65. 2. Note that the use of CCOW RPC Broker to authenticate the user does NOT use 2-factor authentication and does not comply with the anticipated future security policy of the VA. This code may be deprecated in a future release. Changes in v1.1.60 (HGW 12/18/2013) XWB*1.1*60 1. Updated RPC Version to version 60 2. Reformated indentations and comments to make code more readable Changes in v1.1.31 (DCM ) XWB*1.1*31 1. Added new read only property BrokerVersion to TRPCBroker which should contain the version number for the RPCBroker (or SharedRPCBroker) in use. Changes in v1.1.13 (JLI 5/24/2001) XWB*1.1*13 1. More silent login code; deleted obsolete lines (DCM 9/10/99) Changes in v1.1.8 (REM 7/13/1999) XWB*1.1*8 1. Check for Multi-Division users. Changes in v1.1.6 (DPC 4/1999) XWB*1.1*6 1. Polling to support terminating orphaned server jobs. ************************************************** } unit CCOWRPCBroker; interface {$I IISBase.inc} uses {System} Classes, SysUtils, ComObj, {Vcl} Controls, Dialogs, Forms, Graphics, extctrls, OleCtrls, {VA} XWBut1, MFunStr, XWBHash, Trpcb, VERGENCECONTEXTORLib_TLB, {WinApi} Messages, WinProcs, WinTypes, Windows, ActiveX; const NoMore: boolean = False; MIN_RPCTIMELIMIT: integer = 30; CURRENT_RPC_VERSION: String = 'XWB*1.1*65'; type TCCOWRPCBroker = class(TRPCBroker) private { Private declarations } protected FCCOWLogonIDName: String; FCCOWLogonIDValue: String; FCCOWLogonName: String; FCCOWLogonNameValue: String; FContextor: TContextorControl; //CCOW FCCOWtoken: string; //CCOW FVistaDomain: String; FCCOWLogonVpid: String; FCCOWLogonVpidValue: String; FWasUserDefined: Boolean; function GetCCOWHandle(ConnectedBroker: TCCOWRPCBroker): string; function GetCCOWduz( Contextor: TContextorControl): string; procedure CCOWsetUser(Uname, token, Domain, Vpid: string; Contextor: TContextorControl); public { Public declarations } function GetCCOWtoken(Contextor: TContextorControl): string; function IsUserCleared: Boolean; function WasUserDefined: Boolean; function IsUserContextPending(aContextItemCollection: IContextItemCollection):Boolean; property Contextor: TContextorControl read Fcontextor write FContextor; //CCOW property CCOWLogonIDName: String read FCCOWLogonIDName; property CCOWLogonIDValue: String read FCCOWLogonIDValue; property CCOWLogonName: String read FCCOWLogonName; property CCOWLogonNameValue: String read FCCOWLogonNameValue; property CCOWLogonVpid: String read FCCOWLogonVpid; property CCOWLogonVpidValue: String read FCCOWLogonVpidValue; published property Connected: boolean read FConnected write SetConnected; end; procedure AuthenticateUser(ConnectingBroker: TCCOWRPCBroker); implementation uses {VA} Loginfrm, RpcbErr, WSockc, SelDiv, RpcSLogin, fRPCBErrMsg, CCOW_const; var CCOWToken: String; Domain: String; PassCode1: String; PassCode2: String; function TCCOWRPCBroker.WasUserDefined: Boolean; begin Result := FWasUserDefined; end; //function TCCOWRPCBroker.WasUserDefined function TCCOWRPCBroker.IsUserCleared: Boolean; var CCOWcontextItem: IContextItemCollection; //CCOW CCOWdataItem1: IContextItem; //CCOW Name: String; begin Result := False; Name := CCOW_LOGON_ID; if (Contextor <> nil) then try //See if context contains the ID item CCOWcontextItem := Contextor.CurrentContext; CCOWDataItem1 := CCowContextItem.Present(Name); if (CCOWdataItem1 <> nil) then begin if CCOWdataItem1.Value = '' then Result := True else FWasUserDefined := True; end //if else Result := True; finally end; //try end; //function TCCOWRPCBroker.IsUserCleared {------------------------ AuthenticateUser ------------------------ ------------------------------------------------------------------} procedure AuthenticateUser(ConnectingBroker: TCCOWRPCBroker); var SaveClearParmeters, SaveClearResults: boolean; SaveParam: TParams; SaveRemoteProcedure, SaveRpcVersion: string; SaveResults: TStrings; blnSignedOn: boolean; SaveKernelLogin: boolean; SaveVistaLogin: TVistaLogin; OldExceptionHandler: TExceptionEvent; OldHandle: THandle; begin with ConnectingBroker do begin SaveParam := TParams.Create(nil); SaveParam.Assign(Param); //save off settings SaveRemoteProcedure := RemoteProcedure; SaveRpcVersion := RpcVersion; SaveResults := Results; SaveClearParmeters := ClearParameters; SaveClearResults := ClearResults; ClearParameters := True; //set'em as I need'em ClearResults := True; SaveKernelLogin := KernelLogin; // p13 SaveVistaLogin := Login; // p13 end; //with blnSignedOn := False; //initialize to bad sign-on if ConnectingBroker.AccessVerifyCodes <> '' then // p13 handle as AVCode single signon begin ConnectingBroker.Login.AccessCode := Piece(ConnectingBroker.AccessVerifyCodes, ';', 1); ConnectingBroker.Login.VerifyCode := Piece(ConnectingBroker.AccessVerifyCodes, ';', 2); ConnectingBroker.Login.Mode := lmAVCodes; ConnectingBroker.KernelLogIn := False; end; //if //CCOW start if ConnectingBroker.KernelLogIn and (not (ConnectingBroker.Contextor = nil)) then begin CCOWtoken := ConnectingBroker.GetCCOWtoken(ConnectingBroker.Contextor); if length(CCOWtoken)>0 then begin ConnectingBroker.FKernelLogIn := false; ConnectingBroker.Login.Mode := lmAppHandle; ConnectingBroker.Login.LogInHandle := CCOWtoken; end; //if end; //if if not ConnectingBroker.FKernelLogIn then if ConnectingBroker.FLogin <> nil then //the user. vistalogin contains login info begin blnsignedon := SilentLogin(ConnectingBroker); // RpcSLogin unit if not blnSignedOn then begin //Switch back to Kernel Login ConnectingBroker.FKernelLogIn := true; ConnectingBroker.Login.Mode := lmAVCodes; end; //if end; //if //CCOW end if ConnectingBroker.FKernelLogIn then begin //p13 CCOWToken := ''; //if can't sign on with Token clear it so can get new one if Assigned(Application.OnException) then OldExceptionHandler := Application.OnException else OldExceptionHandler := nil; Application.OnException := TfrmErrMsg.RPCBShowException; frmSignon := TfrmSignon.Create(Application); try // ShowApplicationAndFocusOK(Application); OldHandle := GetForegroundWindow; SetForegroundWindow(frmSignon.Handle); PrepareSignonForm(ConnectingBroker); if SetUpSignOn then //SetUpSignOn in loginfrm unit. begin //True if signon needed if frmSignOn.lblServer.Caption <> '' then begin frmSignOn.ShowModal; //do interactive logon // p13 if frmSignOn.Tag = 1 then //Tag=1 for good logon blnSignedOn := True; //Successfull logon end //if end //if else //False when no logon needed blnSignedOn := NoSignOnNeeded; //Returns True always (for now!) if blnSignedOn then //P6 If logged on, retrieve user info. begin GetBrokerInfo(ConnectingBroker); if not ChooseDiv('',ConnectingBroker) then begin blnSignedOn := False;//P8 {Select division if multi-division user. First parameter is 'userid' (DUZ or username) for future use. (P8)} ConnectingBroker.Login.ErrorText := 'Failed to select Division'; // p13 set some text indicating problem end; //if end; //if SetForegroundWindow(OldHandle); finally frmSignon.Free; ShowApplicationAndFocusOK(Application); end; //try if Assigned(OldExceptionHandler) then Application.OnException := OldExceptionHandler; end; //if ConnectingBroker.FKernelLogIn // p13 following section for silent signon if (not ConnectingBroker.KernelLogIn) and (not blnsignedon) then // was doing the signon twice if already true if ConnectingBroker.Login <> nil then //the user. vistalogin contains login info blnsignedon := SilentLogin(ConnectingBroker); // RpcSLogin unit if not blnsignedon then begin TXWBWinsock(ConnectingBroker.XWBWinsock).NetworkDisconnect(ConnectingBroker.Socket); end //if else GetBrokerInfo(ConnectingBroker); //reset the Broker with ConnectingBroker do begin ClearParameters := SaveClearParmeters; ClearResults := SaveClearResults; Param.Assign(SaveParam); //restore settings SaveParam.Free; RemoteProcedure := SaveRemoteProcedure; RpcVersion := SaveRpcVersion; Results := SaveResults; FKernelLogin := SaveKernelLogin; // p13 FLogin := SaveVistaLogin; // p13 end; //with if not blnSignedOn then //Flag for unsuccessful signon. TXWBWinsock(ConnectingBroker.XWBWinsock).NetError('',XWB_BadSignOn); //Will raise error. end; //procedure AuthenticateUser {----------------------- GetCCOWHandle -------------------------- Private function to return a special CCOW Handle from the server which is set into the CCOW context. The Broker of a new application can get the CCOWHandle from the context and use it to do a ImAPPHandle Sign-on. ----------------------------------------------------------------} function TCCOWRPCBroker.GetCCOWHandle(ConnectedBroker : TCCOWRPCBroker): String; // p13 begin Result := ''; with ConnectedBroker do try // to permit it to work correctly if CCOW is not installed on the server. begin RemoteProcedure := 'XUS GET CCOW TOKEN'; Call; Result := Results[0]; Domain := Results[1]; RemoteProcedure := 'XUS CCOW VAULT PARAM'; Call; PassCode1 := Results[0]; PassCode2 := Results[1]; end; except Result := ''; end; //try end; //function TCCOWRPCBroker.GetCCOWHandle {----------------------- CCOWsetUser -------------------------- CCOW Start ----------------------------------------------------------------} procedure TCCOWRPCBroker.CCOWsetUser(Uname, token, Domain, Vpid: string; Contextor: TContextorControl); var CCOWdata: IContextItemCollection; //CCOW CCOWdataItem1,CCOWdataItem2,CCOWdataItem3: IContextItem; CCOWdataItem4,CCOWdataItem5: IContextItem; //CCOW Cname: string; begin if Contextor <> nil then begin try //Part 1 Contextor.StartContextChange; //Part 2 Set the new proposed context data CCOWdata := CoContextItemCollection.Create; CCOWdataItem1 := CoContextItem.Create; Cname := CCOW_LOGON_ID; CCOWdataItem1.Name := Cname; CCOWdataItem1.Value := domain; CCOWData.Add(CCOWdataItem1); CCOWdataItem2 := CoContextItem.Create; Cname := CCOW_LOGON_TOKEN; CCOWdataItem2.Name := Cname; CCOWdataItem2.Value := token; CCOWdata.Add(CCOWdataItem2); CCOWdataItem3 := CoContextItem.Create; Cname := CCOW_LOGON_NAME; CCOWdataItem3.Name := Cname; CCOWdataItem3.Value := Uname; CCOWdata.Add(CCOWdataItem3); // CCOWdataItem4 := CoContextItem.Create; Cname := CCOW_LOGON_VPID; CCOWdataItem4.Name := Cname; CCOWdataItem4.Value := Vpid; CCOWdata.Add(CCOWdataItem4); // CCOWdataItem5 := CoContextItem.Create; Cname := CCOW_USER_NAME; CCOWdataItem5.Name := Cname; CCOWdataItem5.Value := Uname; CCOWdata.Add(CCOWdataItem5); //Part 3 Make change Contextor.EndContextChange(true, CCOWdata); //We don't need to check CCOWresponce finally end; //try end; //if end; //procedure TCCOWRPCBroker.CCOWsetUser {----------------------- GetCCOWtoken -------------------------- Get Token from CCOW context ----------------------------------------------------------------} function TCCOWRPCBroker.GetCCOWtoken(Contextor: TContextorControl): string; var CCOWdataItem1: IContextItem; //CCOW CCOWcontextItem: IContextItemCollection; //CCOW name: string; begin result := ''; name := CCOW_LOGON_TOKEN; if (Contextor <> nil) then try CCOWcontextItem := Contextor.CurrentContext; //See if context contains the ID item CCOWdataItem1 := CCOWcontextItem.Present(name); if (CCOWdataItem1 <> nil) then //1 begin result := CCOWdataItem1.Value; if not (result = '') then FWasUserDefined := True; end; //if FCCOWLogonIDName := CCOW_LOGON_ID; FCCOWLogonName := CCOW_LOGON_NAME; FCCOWLogonVpid := CCOW_LOGON_VPID; CCOWdataItem1 := CCOWcontextItem.Present(CCOW_LOGON_ID); if CCOWdataItem1 <> nil then FCCOWLogonIdValue := CCOWdataItem1.Value; CCOWdataItem1 := CCOWcontextItem.Present(CCOW_LOGON_NAME); if CCOWdataItem1 <> nil then FCCOWLogonNameValue := CCOWdataItem1.Value; CCOWdataItem1 := CCOWcontextItem.Present(CCOW_LOGON_VPID); if CCOWdataItem1 <> nil then FCCOWLogonVpidValue := CCOWdataItem1.Value; finally end; //try end; //function TCCOWRPCBroker.GetCCOWtoken {----------------------- GetCCOWduz -------------------------- Get Name from CCOW context ----------------------------------------------------------------} function TCCOWRPCBroker.GetCCOWduz(Contextor: TContextorControl): string; var CCOWdataItem1: IContextItem; //CCOW CCOWcontextItem: IContextItemCollection; //CCOW name: string; begin result := ''; name := CCOW_LOGON_ID; if (Contextor <> nil) then try CCOWcontextItem := Contextor.CurrentContext; //See if context contains the ID item CCOWdataItem1 := CCOWcontextItem.Present(name); if (CCOWdataItem1 <> nil) then //1 begin result := CCOWdataItem1.Value; if result <> '' then FWasUserDefined := True; end; //if finally end; //try end; //function TCCOWRPCBroker.GetCCOWduz {----------------------- IsUserContextPending -------------------------- ----------------------------------------------------------------} function TCCOWRPCBroker.IsUserContextPending(aContextItemCollection: IContextItemCollection): Boolean; var CCOWdataItem1: IContextItem; //CCOW Val1: String; begin result := false; if WasUserDefined() then // indicates data was defined begin Val1 := ''; // look for any USER Context items defined result := True; // CCOWdataItem1 := aContextItemCollection.Present(CCOW_LOGON_ID); if CCOWdataItem1 <> nil then if not (CCOWdataItem1.Value = FCCOWLogonIDValue) then Val1 := '^' + CCOWdataItem1.Value; // CCOWdataItem1 := aContextItemCollection.Present(CCOW_LOGON_NAME); if CCOWdataItem1 <> nil then if not (CCOWdataItem1.Value = FCCOWLogonNameValue) then Val1 := Val1 + '^' + CCOWdataItem1.Value; // CCOWdataItem1 := aContextItemCollection.Present(CCOW_LOGON_VPID); if CCOWdataItem1 <> nil then if not (CCOWdataItem1.Value = FCCOWLogonVpidValue) then Val1 := Val1 + '^' + CCOWdataItem1.Value; // CCOWdataItem1 := aContextItemCollection.Present(CCOW_USER_NAME); if CCOWdataItem1 <> nil then if not (CCOWdataItem1.Value = user.Name) then Val1 := Val1 + '^' + CCOWdataItem1.Value; // if Val1 = '' then // nothing defined or all matches, so not user context change result := False; end; //if end; //function TCCOWRPCBroker.IsUserContextPending end.
{ This file is part of the Free Component Library Implementation of TJSONConfig class Copyright (c) 2007 Michael Van Canneyt michael@freepascal.org See the file COPYING.FPC, included in this distribution, for details about the copyright. 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. **********************************************************************} { TJSONConfig enables applications to use JSON files for storing their configuration data } { Modified(by Yauheni Nazimau) version of \packages\fcl-json\src\jsonconf.pp TODO: TvrJsonConfig = class(TJsonConfig) } {$IFDEF FPC} {$MODE objfpc} {$H+} {$ENDIF} unit vr_json_conf; interface uses SysUtils, Classes, fpjson, jsonparser, contnrs, types, vr_utils, LazUTF8Classes; //resourcestring // SWrongRootName = 'XML file has wrong root element name'; type EJSONConfigError = class(Exception); TPathFlags = set of (pfHasValue, pfWriteAccess); (* ******************************************************************** "APath" is the path and name of a value: A JSON configuration file is hierachical. "/" is the path delimiter, the part after the last "/" is the name of the value. The path components will be mapped to nested JSON objects, with the name equal to the part. In practice this means that "/my/path/value" will be written as: { "my" : { "path" : { "value" : Value } } } ******************************************************************** *) { TJSONConfig } TJSONConfig = class(TComponent) private FFilename: String; FKey: TJSONObject; FArrayKey: TJSONArray; FStartEmpty: Boolean; FKeyStack: TStack; FArrayKeyStack: TStack; procedure DoSetFilename(const AFilename: String; ForceReload: Boolean); procedure SetFilename(const AFilename: String); procedure SetStartEmpty(const AValue: Boolean); Function StripSlash(P : String) : String; function EnumSubKeys_(AKey: TJSONObject; AList : TStrings): Boolean; function EnumValues_(AKey: TJSONObject; AList : TStrings; WithValues: Boolean = False): Boolean; protected FJSON: TJSONObject; FModified: Boolean; procedure Loaded; override; function FindPath(Const APath: String; AllowCreate : Boolean) : TJSONObject; function FindObject(Const APath: String; AllowCreate : Boolean) : TJSONObject; function FindObject(Const APath: String; AllowCreate : Boolean;Out ElName : String) : TJSONObject; function FindElement(Const APath: String; CreateParent : Boolean) : TJSONData; function FindElement(Const APath: String; CreateParent : Boolean; Out AParent : TJSONObject; Out ElName : String) : TJSONData; public constructor Create(AOwner: TComponent); override; overload; constructor Create(const AFileName: string); overload; constructor CreateClean(const AFileName: string); destructor Destroy; override; procedure Clear; procedure Flush; // Writes the JSON file function TryOpenKey(const aPath: String; const AIsPushKey: Boolean = False): Boolean; procedure OpenKey(const aPath: String; AllowCreate : Boolean); function OpenArrayKey(const aPath: String; AllowCreate : Boolean): Boolean; function OpenKeyInArray(AIndex: Integer; AllowCreate : Boolean): Boolean; function GetArrayValues(out AValues: TStringDynArray): Boolean; overload; function GetArrayValues(AValues: TStrings): Boolean; overload; procedure SetArrayValues(const AValues: TStringDynArray); overload; procedure SetArrayValues(const AValues: TStrings); overload; procedure AddValueToArray(const AValue: string); function KeyExists(const AKey: string): Boolean; function SubKeyExists(const AKey: string): Boolean; function SubKeysExists: Boolean; procedure PushKey; procedure PopKey; procedure CloseKey; procedure ResetKey; function EnumSubKeys(Const APath : String; List: TStrings): Boolean; function EnumValues(Const APath : String; List: TStrings; WithValues: Boolean = False): Boolean; function EnumValues(Const APath : String; out arr: TStringDynArray; WithValues: Boolean = False): Boolean; function EnumCurrSubKeys(AList : TStrings): Boolean; function EnumCurrSubKeys(out arr : TStringDynArray): Boolean; function EnumCurrValues(List : TStrings; WithValues: Boolean = False): Boolean; function EnumCurrValues(out arr : TStringDynArray; WithValues: Boolean = False): Boolean; function GetValue(const APath: String; const ADefault: String): String; overload; function GetValue(const APath: String; ADefault: Integer): Integer; overload; function GetValue(const APath: String; ADefault: Int64): Int64; overload; function GetValue(const APath: String; ADefault: Boolean): Boolean; overload; function GetValue(const APath: String; ADefault: Double): Double; overload; procedure SetValue(const APath: String; const AValue: String); overload; procedure SetValue(const APath: String; AValue: Integer); overload; procedure SetValue(const APath: String; AValue: Int64); overload; procedure SetValue(const APath: String; AValue: Boolean); overload; procedure SetValue(const APath: String; AValue: Double); overload; procedure SetDeleteValue(const APath: String; const AValue, DefValue: String); overload; procedure SetDeleteValue(const APath: String; AValue, DefValue: Integer); overload; procedure SetDeleteValue(const APath: String; AValue, DefValue: Int64); overload; procedure SetDeleteValue(const APath: String; AValue, DefValue: Boolean); overload; procedure DeletePath(const APath: String); procedure DeleteValue(const APath: String); property Modified: Boolean read FModified; published property Filename: String read FFilename write SetFilename; property StartEmpty: Boolean read FStartEmpty write SetStartEmpty; end; // =================================================================== implementation Const SErrInvalidJSONFile = '"%s" is not a valid JSON configuration file.'; SErrCouldNotOpenKey = 'Could not open key "%s".'; constructor TJSONConfig.Create(AOwner: TComponent); begin inherited Create(AOwner); FJSON:=TJSONObject.Create; FKey:=FJSON; FKeyStack := TStack.Create; FArrayKeyStack := TStack.Create; end; constructor TJSONConfig.Create(const AFileName: string); begin Create(nil); DoSetFilename(AFileName, True); end; constructor TJSONConfig.CreateClean(const AFileName: string); begin Create(nil); StartEmpty := True; DoSetFilename(AFileName, False); end; destructor TJSONConfig.Destroy; begin FKeyStack.Free; FArrayKeyStack.Free; if Assigned(FJSON) then begin Flush; FreeANdNil(FJSON); end; inherited Destroy; end; procedure TJSONConfig.Clear; begin FJSON.Clear; FKey:=FJSON; end; procedure TJSONConfig.Flush; //Var // F : Text; begin if Modified then begin str_SaveToFile(FFilename, FJSON.AsJSON, True); //file_Assign(F,FFileName); //try // Rewrite(F); //except // Exit; //end; //Try // Writeln(F,FJSON.AsJSON); //Finally // CloseFile(F); //end; FModified := False; end; end; function TJSONConfig.FindObject(const APath: String; AllowCreate: Boolean ): TJSONObject; Var Dummy : String; begin Result:=FindObject(APath,AllowCreate,Dummy); end; function TJSONConfig.FindObject(const APath: String; AllowCreate: Boolean; out ElName: String): TJSONObject; Var S,El : String; P,I : Integer; T : TJSonObject; begin // Writeln('Looking for : ', APath); S:=APath; If Pos('/',S)=1 then Result:=FJSON else Result:=FKey; Repeat P:=Pos('/',S); If (P<>0) then begin // Only real paths, ignore double slash If (P<>1) then begin El:=Copy(S,1,P-1); If (Result.Count=0) then I:=-1 else I:=Result.IndexOfName(El); If (I=-1) then // No element with this name. begin If AllowCreate then begin // Create new node. T:=Result; Result:=TJSonObject.Create; T.Add(El,Result); end else Result:=Nil end else // Node found, check if it is an object begin if (Result.Items[i].JSONtype=jtObject) then Result:=Result.Objects[el] else begin // Writeln(el,' type wrong'); If AllowCreate then begin // Writeln('Creating ',el); Result.Delete(I); T:=Result; Result:=TJSonObject.Create; T.Add(El,Result); end else Result:=Nil end; end; end; Delete(S,1,P); end; Until (P=0) or (Result=Nil); ElName:=S; end; function TJSONConfig.FindElement(const APath: String; CreateParent: Boolean ): TJSONData; Var O : TJSONObject; ElName : String; begin Result:=FindElement(APath,CreateParent,O,ElName); end; function TJSONConfig.FindElement(const APath: String; CreateParent: Boolean; out AParent: TJSONObject; out ElName: String): TJSONData; Var I : Integer; begin Result:=Nil; Aparent:=FindObject(APath,CreateParent,ElName); If Assigned(Aparent) then begin // Writeln('Found parent, looking for element:',elName); I:=AParent.IndexOfName(ElName); // Writeln('Element index is',I); If (I<>-1) And (AParent.items[I].JSONType<>jtObject) then Result:=AParent.Items[i]; end; end; function TJSONConfig.GetValue(const APath: String; const ADefault: String): String; var El : TJSONData; begin try El:=FindElement(StripSlash(APath),False); If Assigned(El) then Result:=El.AsString else Result:=ADefault; except Result:=ADefault; end; end; function TJSONConfig.GetValue(const APath: String; ADefault: Integer): Integer; var El : TJSONData; begin try El:=FindElement(StripSlash(APath),False); If Not Assigned(el) then Result:=ADefault else if (el is TJSONNumber) then Result:=El.AsInteger else Result:=StrToIntDef(El.AsString,ADefault); except Result:=ADefault; end; end; function TJSONConfig.GetValue(const APath: String; ADefault: Int64): Int64; var El : TJSONData; begin try El:=FindElement(StripSlash(APath),False); If Not Assigned(el) then Result:=ADefault else if (el is TJSONNumber) then Result:=El.AsInt64 else Result:=StrToInt64Def(El.AsString,ADefault); except Result:=ADefault; end; end; function TJSONConfig.GetValue(const APath: String; ADefault: Boolean): Boolean; var El : TJSONData; begin try El:=FindElement(StripSlash(APath),False); If Not Assigned(el) then Result:=ADefault else if (el is TJSONBoolean) then Result:=El.AsBoolean else Result:=StrToBoolDef(El.AsString,ADefault); except Result:=ADefault; end; end; function TJSONConfig.GetValue(const APath: String; ADefault: Double): Double; var El : TJSONData; begin try El:=FindElement(StripSlash(APath),False); If Not Assigned(el) then Result:=ADefault else if (el is TJSONNumber) then Result:=El.AsFloat else Result:=StrToFloatDef(El.AsString,ADefault); except Result:=ADefault; end; end; procedure TJSONConfig.SetValue(const APath: String; const AValue: String); var El : TJSONData; ElName : String; O : TJSONObject; I : integer; begin El:=FindElement(StripSlash(APath),True,O,ElName); if Assigned(El) and (El.JSONType<>jtString) then begin I:=O.IndexOfName(elName); O.Delete(i); El:=Nil; end; If Not Assigned(el) then begin El:=TJSONString.Create(AValue); O.Add(ElName,El); end else El.AsString:=AVAlue; FModified:=True; end; procedure TJSONConfig.SetDeleteValue(const APath: String; const AValue, DefValue: String); begin if AValue = DefValue then DeleteValue(APath) else SetValue(APath, AValue); end; procedure TJSONConfig.SetValue(const APath: String; AValue: Integer); var El : TJSONData; ElName : String; O : TJSONObject; I : integer; begin El:=FindElement(StripSlash(APath),True,O,ElName); if Assigned(El) and (Not (El is TJSONIntegerNumber)) then begin I:=O.IndexOfName(elName); If (I<>-1) then // Normally not needed... O.Delete(i); El:=Nil; end; If Not Assigned(el) then begin El:=TJSONIntegerNumber.Create(AValue); O.Add(ElName,El); end else El.AsInteger:=AValue; FModified:=True; end; procedure TJSONConfig.SetValue(const APath: String; AValue: Int64); var El : TJSONData; ElName : String; O : TJSONObject; I : integer; begin El:=FindElement(StripSlash(APath),True,O,ElName); if Assigned(El) and (Not (El is TJSONInt64Number)) then begin I:=O.IndexOfName(elName); If (I<>-1) then // Normally not needed... O.Delete(i); El:=Nil; end; If Not Assigned(el) then begin El:=TJSONInt64Number.Create(AValue); O.Add(ElName,El); end else El.AsInt64:=AValue; FModified:=True; end; procedure TJSONConfig.SetDeleteValue(const APath: String; AValue, DefValue: Integer); begin if AValue = DefValue then DeleteValue(APath) else SetValue(APath, AValue); end; procedure TJSONConfig.SetDeleteValue(const APath: String; AValue, DefValue: Int64); begin if AValue = DefValue then DeleteValue(APath) else SetValue(APath, AValue); end; procedure TJSONConfig.SetValue(const APath: String; AValue: Boolean); var El : TJSONData; ElName : String; O : TJSONObject; I : integer; begin El:=FindElement(StripSlash(APath),True,O,ElName); if Assigned(El) and (el.JSONType<>jtBoolean) then begin I:=O.IndexOfName(elName); O.Delete(i); El:=Nil; end; If Not Assigned(el) then begin El:=TJSONBoolean.Create(AValue); O.Add(ElName,El); end else El.AsBoolean:=AValue; FModified:=True; end; procedure TJSONConfig.SetValue(const APath: String; AValue: Double); var El : TJSONData; ElName : String; O : TJSONObject; I : integer; begin El:=FindElement(StripSlash(APath),True,O,ElName); if Assigned(El) and (Not (El is TJSONFloatNumber)) then begin I:=O.IndexOfName(elName); O.Delete(i); El:=Nil; end; If Not Assigned(el) then begin El:=TJSONFloatNumber.Create(AValue); O.Add(ElName,El); end else El.AsFloat:=AValue; FModified:=True; end; procedure TJSONConfig.SetDeleteValue(const APath: String; AValue, DefValue: Boolean); begin if AValue = DefValue then DeleteValue(APath) else SetValue(APath,AValue); end; procedure TJSONConfig.DeletePath(const APath: String); Var P : String; L : integer; Node : TJSONObject; ElName : String; begin P:=StripSlash(APath); L:=Length(P); If (L>0) then begin Node := FindObject(P,False,ElName); If Assigned(Node) then begin L:=Node.IndexOfName(ElName); If (L<>-1) then begin Node.Delete(L); FModified := True; end; end; end; end; procedure TJSONConfig.DeleteValue(const APath: String); begin DeletePath(APath); end; procedure TJSONConfig.Loaded; begin inherited Loaded; if Length(Filename) > 0 then DoSetFilename(Filename,True); end; function TJSONConfig.FindPath(const APath: String; AllowCreate: Boolean ): TJSONObject; Var P : String; L : Integer; begin P:=APath; L:=Length(P); If (L=0) or (P[L]<>'/') then P:=P+'/'; Result:=FindObject(P,AllowCreate); end; procedure TJSONConfig.DoSetFilename(const AFilename: String; ForceReload: Boolean); Var P : TJSONParser; J : TJSONData; F : TFileStreamUTF8; begin if (not ForceReload) and file_SameName(FFilename, AFilename) then exit; FFilename := AFilename; if csLoading in ComponentState then exit; Flush; if not file_Exists(AFileName) or FStartEmpty then Clear else begin F:=TFileStreamUTF8.Create(AFileName,fmopenRead); try P:=TJSONParser.Create(F); try J:=P.Parse; If (J is TJSONObject) then begin FreeAndNil(FJSON); FJSON:=J as TJSONObject; FKey:=FJSON; end else Raise EJSONConfigError.CreateFmt(SErrInvalidJSONFile,[AFileName]); finally P.Free; end; finally F.Free; end; end; end; procedure TJSONConfig.SetFilename(const AFilename: String); begin DoSetFilename(AFilename, False); end; procedure TJSONConfig.SetStartEmpty(const AValue: Boolean); begin if AValue <> StartEmpty then begin FStartEmpty := AValue; if (not AValue) and not Modified then DoSetFilename(Filename, True); end; end; function TJSONConfig.StripSlash(P: String): String; Var L : Integer; begin L:=Length(P); If (L>0) and (P[l]='/') then Result:=Copy(P,1,L-1) else Result:=P; end; function TJSONConfig.EnumSubKeys_(AKey: TJSONObject; AList: TStrings): Boolean; Var I : Integer; begin AList.Clear; If Assigned(AKey) then begin For I:=0 to AKey.Count-1 do If AKey.Items[i] is TJSONObject then AList.Add(AKey.Names[i]); end; Result := AList.Count > 0; end; function TJSONConfig.EnumValues_(AKey: TJSONObject; AList: TStrings; WithValues: Boolean): Boolean; Var I : Integer; begin AList.Clear; If Assigned(AKey) then begin For I:=0 to AKey.Count-1 do If Not (AKey.Items[i] is TJSONObject) then begin if WithValues then AList.Add(AKey.Names[i] + '=' + AKey.Items[I].AsString) else AList.Add(AKey.Names[i]); end; end; Result := AList.Count > 0; end; procedure TJSONConfig.CloseKey; begin ResetKey; end; function TJSONConfig.TryOpenKey(const aPath: String; const AIsPushKey: Boolean): Boolean; begin if AIsPushKey then PushKey; try OpenKey(aPath, False); Result := FKey <> nil; except Result := False; end; if not Result then if AIsPushKey then PopKey else FKey := FJSON; end; procedure TJSONConfig.OpenKey(const aPath: String; AllowCreate: Boolean); Var P : String; L : Integer; begin P:=APath; L:=Length(P); If (L=0) then FKey:=FJSON else begin if (P[L]<>'/') then P:=P+'/'; FKey:=FindObject(P,AllowCreate); If (FKey=Nil) Then Raise EJSONConfigError.CreateFmt(SErrCouldNotOpenKey,[APath]); end; end; function TJSONConfig.OpenArrayKey(const aPath: String; AllowCreate: Boolean): Boolean; Var P : String; L : Integer; Parent: TJSONObject; sArray: String; arr: TJSONData; begin Result := False; FArrayKey := nil; P:=APath; L:=Length(P); If (L>0) then begin arr:=FindElement(P,AllowCreate, Parent, sArray); if (arr = nil) or not (arr is TJSONArray) then begin if (Parent = nil) or not AllowCreate then Exit; if (arr <> nil) then Parent.Remove(arr); arr := TJSONArray.Create; Parent.Add(sArray, arr); end; FArrayKey := TJSONArray(arr); Exit(True); end; //If (FArrayKey=Nil) Then // Raise EJSONConfigError.CreateFmt(SErrCouldNotOpenKey,[APath]); end; function TJSONConfig.OpenKeyInArray(AIndex: Integer; AllowCreate: Boolean): Boolean; var data: TJSONData; begin Result := False; FKey:=FJSON; if FArrayKey = nil then Exit; if AIndex >= FArrayKey.Count then begin if not AllowCreate then Exit; for AIndex := FArrayKey.Count to AIndex do FArrayKey.Add(TJSONObject.Create); end; data := FArrayKey.Items[AIndex]; if not (data is TJSONObject) then begin if not AllowCreate then Exit; FArrayKey.Remove(data); data := TJSONObject.Create; FArrayKey.Insert(AIndex, data); end; FKey := TJSONObject(data); Result := True; end; function TJSONConfig.GetArrayValues(out AValues: TStringDynArray): Boolean; var I, Len: Integer; a: TStringDynArray; begin Result := False; SetLength(AValues, 0); Len := FArrayKey.Count; if (FArrayKey = nil) or (Len = 0) then Exit; SetLength(a, Len); try for I := 0 to Len - 1 do begin a[I] := FArrayKey.Items[I].AsString; end; Result := True; AValues := a; except end; end; function TJSONConfig.GetArrayValues(AValues: TStrings): Boolean; var arr: TStringDynArray; begin Result := GetArrayValues(arr); if Result then arrS_SaveToStrs(arr, AValues) else AValues.Clear; end; procedure TJSONConfig.SetArrayValues(const AValues: TStringDynArray); var I: Integer; begin if FArrayKey <> nil then begin for I := 0 to Length(AValues) - 1 do FArrayKey.Add(AValues[I]); if Length(AValues) > 0 then FModified := True; end; end; procedure TJSONConfig.SetArrayValues(const AValues: TStrings); var arr: TStringDynArray; begin arrS_LoadFromStrs(arr, AValues); SetArrayValues(arr); end; procedure TJSONConfig.AddValueToArray(const AValue: string); begin if FArrayKey <> nil then begin FArrayKey.Add(AValue); FModified := True; end; end; function TJSONConfig.KeyExists(const AKey: string): Boolean;{$IFDEF VER3} var val: TJSONData;{$ENDIF} begin {$IFDEF VER3} Result := (FKey <> nil) and FKey.Find(AKey, val);{$ELSE} Result := (FKey <> nil) and (FKey.Find(AKey) <> nil);{$ENDIF} end; function TJSONConfig.SubKeyExists(const AKey: string): Boolean;{$IFDEF VER3} var val: TJSONData;{$ENDIF} begin Result := (FKey <> nil) and {$IFDEF VER3}FKey.Find(AKey, val) and (val is TJSONObject){$ELSE} (FKey.Find(AKey) is TJSONObject){$ENDIF}; end; function TJSONConfig.SubKeysExists: Boolean; var i: Integer; begin If Assigned(FKey) then For i:=0 to FKey.Count-1 do If FKey.Items[i] is TJSONObject then Exit(True); Result := False; end; procedure TJSONConfig.PushKey; begin FKeyStack.Push(FKey); FArrayKeyStack.Push(FArrayKey); end; procedure TJSONConfig.PopKey; begin FKey := TJSONObject(FKeyStack.Pop); FArrayKey := TJSONArray(FArrayKeyStack.Pop); end; procedure TJSONConfig.ResetKey; begin FKey:=FJSON; FArrayKey:=nil; end; function TJSONConfig.EnumSubKeys(const APath: String; List: TStrings): Boolean; Var AKey : TJSONObject; begin AKey:=FindPath(APath,False); Result := EnumSubKeys_(AKey, List); end; function TJSONConfig.EnumValues(const APath: String; List: TStrings; WithValues: Boolean): Boolean; Var AKey : TJSONObject; begin AKey:=FindPath(APath,False); Result := EnumValues_(AKey, List, WithValues); end; function TJSONConfig.EnumValues(const APath: String; out arr: TStringDynArray; WithValues: Boolean): Boolean; var strs: TStringListUTF8; begin strs := TStringListUTF8.Create; try Result := EnumValues(APath, strs, WithValues); if Result then arrS_LoadFromStrs(arr, strs) else SetLength(arr, 0); finally strs.Free; end; end; function TJSONConfig.EnumCurrSubKeys(AList: TStrings): Boolean; begin Result := EnumSubKeys_(FKey, AList); end; function TJSONConfig.EnumCurrSubKeys(out arr: TStringDynArray): Boolean; var strs: TStringListUTF8; begin strs := TStringListUTF8.Create; try Result := EnumSubKeys_(FKey, strs); if Result then arrS_LoadFromStrs(arr, strs) else SetLength(arr, 0); finally strs.Free; end; end; function TJSONConfig.EnumCurrValues(List: TStrings; WithValues: Boolean): Boolean; begin Result := EnumValues_(FKey, List, WithValues); end; function TJSONConfig.EnumCurrValues(out arr: TStringDynArray; WithValues: Boolean): Boolean; var strs: TStringListUTF8; begin strs := TStringListUTF8.Create; try Result := EnumValues_(FKey, strs, WithValues); if Result then arrS_LoadFromStrs(arr, strs) else SetLength(arr, 0); finally strs.Free; end; end; end.
unit form_VerifyCapacity; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls; const RETAIL_1_KB = 1000; RETAIL_1_MB = (RETAIL_1_KB * 1000); RETAIL_1_GB = (RETAIL_1_MB * 1000); SIZE_1_KB = 1024; SIZE_1_MB = (SIZE_1_KB * 1024); SIZE_1_GB = (SIZE_1_MB * 1024); type TVerifyBlock = array of byte; TfrmVerifyCapacity = class(TForm) pbClose: TButton; pbVerify: TButton; Label2: TLabel; cbDrive: TComboBox; reReport: TRichEdit; ckQuickCheck: TCheckBox; Label1: TLabel; Label3: TLabel; pbSave: TButton; SaveDialog1: TSaveDialog; Label4: TLabel; Label5: TLabel; procedure pbSaveClick(Sender: TObject); procedure pbVerifyClick(Sender: TObject); procedure pbCloseClick(Sender: TObject); procedure FormShow(Sender: TObject); private function TimerStart(): TDateTime; function TimerStop(startTime: TDateTime): string; procedure Verify(drive: char); function ReadWriteBulkData( driveDevice: string; opWriting: boolean; blockSize: integer; expectedSize: int64 ): int64; procedure GetVerifyDataBlock(blockNumber: integer; var outputBlock: TVerifyBlock); function HumanSize(bytes: int64): string; function RetailSize(capacity: int64): string; public { Public declarations } end; implementation {$R *.dfm} uses AppGlobals, SDUGeneral, SDUDialogs, SDUProgressDlg; procedure TfrmVerifyCapacity.FormShow(Sender: TObject); begin PopulateRemovableDrives(cbDrive); ckQuickCheck.checked := TRUE; SDUEnableControl(pbSave, FALSE); reReport.lines.clear(); reReport.ReadOnly := TRUE; reReport.PlainText := TRUE; end; procedure TfrmVerifyCapacity.pbCloseClick(Sender: TObject); begin Close(); end; procedure TfrmVerifyCapacity.pbSaveClick(Sender: TObject); begin if SaveDialog1.Execute then begin reReport.Lines.SaveToFile(SaveDialog1.Filename); end; end; procedure TfrmVerifyCapacity.pbVerifyClick(Sender: TObject); var allOK: boolean; driveItem: string; drive: char; begin allOK := TRUE; // Get rid of compiler warnings driveItem := ''; drive := #0; // Check user's input... if allOK then begin if (cbDrive.ItemIndex < 0) then begin SDUMessageDlg( 'Please select which drive you wish to verify.', mtError, [mbOK], 0 ); allOK := FALSE; end; end; if allOK then begin driveItem := cbDrive.Items[cbDrive.Itemindex]; drive := driveItem[1]; end; if allOK then begin allOK := (SDUMessageDlg( 'Verifying a drive''s capacity involves overwriting ALL data on it, and requiring it to be reformatted afterwards.'+SDUCRLF+ SDUCRLF+ 'Do you wish to verify the capacity of drive '+drive+':?', mtWarning, [mbYes, mbNo], 0 ) = mrYes); end; if allOK then begin Verify(drive); end; end; function TfrmVerifyCapacity.HumanSize(bytes: int64): string; begin Result := SDUFormatUnits( bytes, // Note: We don't include "GB" or "TB"; this // function rounds to nearest unit, and a 2GB // card with slightly less than that will // appear as 1GB if we include the "GB" units ['bytes', 'KB', 'MB'], 1024, 0 ); end; // Returns the number of bytes written to the partition procedure TfrmVerifyCapacity.Verify(drive: char); var expectedSize: int64; bytesWritten: int64; bytesRead: int64; driveDevice: string; possibleFake: boolean; opTime: TDateTime; totalTime: TDateTime; userCancel: boolean; failure: boolean; blockSize: integer; accurate: boolean; tmpStr: string; gotPartInfo: boolean; partInfo: TSDUPartitionInfo; gotDiskGeometry: boolean; diskGeometry: TSDUDiskGeometry; diskGeoCalc: int64; begin driveDevice := '\\.\'+drive+':'; possibleFake := FALSE; accurate := FALSE; // Get rid of compiler warning bytesRead := 0; totalTime := TimerStart(); reReport.lines.Add('Verifying capacity of drive: '+drive+':'); // Get the disk geometry... // (Not needed, but what the hell?) reReport.lines.Add('Determining disk geometry...'); gotDiskGeometry := SDUGetDiskGeometry(drive, diskGeometry); if not(gotDiskGeometry) then begin // Not like we care exactly, but... reReport.lines.Add('+++ UNABLE TO DETERMINE DISK''S CAPACITY'); end else begin reReport.lines.Add('Drive reports:'); reReport.lines.Add(' Cylinders : '+inttostr(diskGeometry.Cylinders.QuadPart)); reReport.lines.Add(' Media type : 0x'+inttohex(diskGeometry.MediaType, 2)+' ('+TSDUMediaTypeTitle[TSDUMediaType(diskGeometry.MediaType)]+')'); reReport.lines.Add(' Tracks per cylinder: '+inttostr(diskGeometry.TracksPerCylinder)); reReport.lines.Add(' Sectors per track : '+inttostr(diskGeometry.SectorsPerTrack)); reReport.lines.Add(' Bytes per sector : '+inttostr(diskGeometry.BytesPerSector)); diskGeoCalc := diskGeometry.Cylinders.QuadPart * int64(diskGeometry.TracksPerCylinder) * int64(diskGeometry.SectorsPerTrack) * int64(diskGeometry.BytesPerSector); reReport.lines.Add(' Total bytes (cylinders * tracks * sectors * bps): '+inttostr(diskGeoCalc)+' ('+HumanSize(diskGeoCalc)+')'); end; reReport.lines.Add('Determining partition information...'); gotPartInfo := SDUGetPartitionInfo(drive, partInfo); expectedSize := partInfo.PartitionLength; if not(gotPartInfo) then begin reReport.lines.Add('+++ UNABLE TO DETERMINE PARTITION''S CAPACITY'); expectedSize := 0; end else begin reReport.lines.Add('Drive reports:'); reReport.lines.Add(' Starting offset : '+SDUIntToStr(partInfo.StartingOffset)); reReport.lines.Add(' Partition length : '+SDUIntToStr(partInfo.PartitionLength)+' ('+HumanSize(partInfo.PartitionLength)+')'); reReport.lines.Add(' Hidden sectors : '+SDUIntToStr(partInfo.HiddenSectors)); reReport.lines.Add(' Partition number : '+SDUIntToStr(partInfo.PartitionNumber)); reReport.lines.Add(' Partition type : 0x'+inttohex(partInfo.PartitionType, 2)); tmpStr := 'Inactive'; if partInfo.BootIndicator then begin tmpStr := 'Active'; end; reReport.lines.Add(' Boot indicator : '+tmpStr); tmpStr := 'FALSE'; if partInfo.RecognizedPartition then begin tmpStr := 'TRUE'; end; reReport.lines.Add(' Recognized partition: '+tmpStr); tmpStr := 'FALSE'; if partInfo.RewritePartition then begin tmpStr := 'TRUE'; end; reReport.lines.Add(' Rewrite partition : '+tmpStr); end; reReport.lines.Add('Verifying reported capacity...'); reReport.lines.Add('Stage 1: Writing data...'); opTime := TimerStart(); blockSize := 512; if ckQuickCheck.checked then begin blockSize := SIZE_1_MB; end; bytesWritten := ReadWriteBulkData(driveDevice, TRUE, blockSize, expectedSize); userCancel := (bytesWritten = -2); failure := (bytesWritten <= 0); if ( not(userCancel) and failure ) then begin reReport.lines.Add('+++ Unable to write data'); end; if (bytesWritten >= 0) then begin reReport.lines.Add('Max bytes writable: '+inttostr(bytesWritten)+' ('+HumanSize(bytesWritten)+')'); end; reReport.lines.Add('Time taken for stage 1: '+TimerStop(opTime)); if ( not(userCancel) and not(failure) ) then begin reReport.lines.Add('Stage 2: Reading and verifying data...'); opTime := TimerStart(); bytesRead := ReadWriteBulkData(driveDevice, FALSE, blockSize, expectedSize); userCancel := (bytesWritten = -2); failure := (bytesWritten < 0); if ( not(userCancel) and failure ) then begin reReport.lines.Add('+++ Unable to read data'); end; if (bytesRead >= 0) then begin reReport.lines.Add('Verified max bytes writable: '+inttostr(bytesRead)+' ('+HumanSize(bytesRead)+')'); end; reReport.lines.Add('Time taken for stage 2: '+TimerStop(opTime)); end; if ( not(userCancel) and not(failure) ) then begin // Check read/write bytecounts... if (bytesWritten = bytesRead) then begin reReport.lines.Add('All data written could be read back correctly'); end else if (bytesWritten > bytesRead) then begin // Bit dodgy... The device allowed us to write more data than we could // read back. // If it's within a 1MB boundry we'll let it slip... if (abs(bytesWritten - bytesRead) <= (blockSize * 2)) then begin reReport.lines.Add('Able to write more data to the drive than we could successfully read back. This sounds a bit dodgy, though it''s not unheard of with some flash cards, and is less than twice the blocksize we''re using to test ('+inttostr(blockSize)+' bytes), so we''ll let it slip here...') end else begin // No - it's far enough out for it to be something else reReport.lines.Add('+++ POSSIBLE FAKE: Unable to read all data written to drive'); possibleFake := TRUE; end; end else if (bytesWritten < bytesRead) then begin reReport.lines.Add('+++ POSSIBLE FAKE: Able to read more data than could be written?!'); possibleFake := TRUE; end; if (bytesWritten = bytesRead) then begin if (bytesRead = expectedSize) then begin accurate := TRUE; reReport.lines.Add('Drive appears to be an authentic: '+HumanSize(expectedSize)+' drive'); end // If the difference is less than a reasonable amount... else begin if not(gotPartInfo) then begin // Can't say anything about what was expected... end else if (abs(expectedSize - bytesRead) <= (SIZE_1_MB * 2)) then begin reReport.lines.Add('Drive can read/write slightly less than it reports, but within reasonable boundaries for a '+HumanSize(expectedSize)+' drive'); end else begin reReport.lines.Add('+++ POSSIBLE FAKE: Drive reports itself as a '+HumanSize(expectedSize)+' drive, but is actually only a '+HumanSize(bytesRead)+' drive'); possibleFake := TRUE; end; end; end; reReport.lines.Add(''); reReport.lines.Add('Note: The *actual* capacity of the drive shown above may well be less than was claimed when it was sold to you as (e.g. a 64MB drive may be reported here as only having 61MB of storage.'); reReport.lines.Add('This is "normal", and can be caused by several things:'); reReport.lines.Add('1) Manufacturers pretending that there are 1,000,000 bytes to the MB instead of 1,048,576. This is pretty "normal" in the industry and done to make products sound better than they actually are'); reReport.lines.Add('2) Slight errors of a few KB in the testing process due to only checking the partition area of the drive selected. The MBR (incl partition table) would probably add another 16K or so'); if ckQuickCheck.checked then begin reReport.lines.Add('3) Opting to perform a quick check, as opposed to using this utility''s more thorough option. This can introduce an error of up to 1MB'); end; // Summary... reReport.lines.Add(''); reReport.lines.Add(''); reReport.lines.Add('Summary'); reReport.lines.Add('======='); reReport.lines.Add(''); if possibleFake then begin reReport.lines.Add('THIS DRIVE IS MISREPORTING IT''S CAPACITY AND IS PROBABLY A FAKE CARD/USB DRIVE'); end else begin if accurate then begin reReport.lines.Add('The capacity this drive reports itself as having is reasonably correct.'); end else begin reReport.lines.Add('The capacity this drive reports itself as having is accurate.'); end; end; reReport.lines.Add(''); reReport.lines.Add('This device SHOULD have been sold to you as a '+RetailSize(bytesRead)+' device.'); reReport.lines.Add(''); reReport.lines.Add('Total time taken: '+TimerStop(totalTime)); reReport.lines.Add(''); reReport.lines.Add(''); end; if userCancel then begin reReport.lines.Add(''); reReport.lines.Add('Operation cancelled by user'); SDUMessageDlg( 'Operation cancelled.', mtInformation, [mbOK], 0 ); end else if failure then begin reReport.lines.Add(''); reReport.lines.Add('Operation failed to complete'); SDUMessageDlg( 'Operation failed to complete. '+SDUCRLF+ SDUCRLF+ 'Please see analysis report for full results.', mtInformation, [mbOK], 0 ); end else begin SDUMessageDlg( 'Operation complete. '+SDUCRLF+ SDUCRLF+ 'Please see analysis report for full results.', mtInformation, [mbOK], 0 ); end; SDUEnableControl(pbSave, TRUE); end; // Returns: -1 on error // -2 on user cancel // 0 or +ve - the number of bytes which could be written to the volume function TfrmVerifyCapacity.ReadWriteBulkData( driveDevice: string; opWriting: boolean; blockSize: integer; expectedSize: int64 ): int64; var fileHandle : THandle; writeBytes: TVerifyBlock; readBytes: TVerifyBlock; bytesTransferred: DWORD; progressDlg: TSDUProgressDialog; zero: DWORD; retVal: int64; bytesToTransfer: DWORD; blockNumber: integer; finished: boolean; i: Integer; begin retVal := 0; zero := 0; // (Obviously!) SetLength(writeBytes, blockSize); SetLength(readBytes, blockSize); progressDlg:= TSDUProgressDialog.create(nil); try progressDlg.Show(); fileHandle := CreateFile(PChar(driveDevice), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL or FILE_FLAG_WRITE_THROUGH, 0); if (fileHandle = INVALID_HANDLE_VALUE) then begin retVal := -1; end else begin try progressDlg.i64Min := 0; progressDlg.i64Max := expectedSize; progressDlg.i64Position := 0; if opWriting then begin progressDlg.Caption := 'Stage 1/2: Writing'; end else begin progressDlg.Caption := 'Stage 2/2: Reading and verifying'; end; progressDlg.ShowTimeRemaining := TRUE; blockNumber := 0; // Reset the file ptr SetFilePointer(fileHandle, 0, @zero, FILE_BEGIN); finished := FALSE; while ( not(finished) and (retVal >= 0) ) do begin // Update progress bar... progressDlg.i64Position := retVal; // Has user cancelled? Application.ProcessMessages(); if progressDlg.Cancel then begin retVal := -2; break; end; // Fill a block with random garbage GetVerifyDataBlock(blockNumber, writeBytes); bytesToTransfer := blockSize; bytesTransferred := 0; if opWriting then begin finished := not(WriteFile( fileHandle, writeBytes[0], bytesToTransfer, bytesTransferred, nil )); end else begin // Read in the block... finished := not(ReadFile( fileHandle, readBytes[0], bytesToTransfer, bytesTransferred, nil )); // If block read in OK, check it... if not(finished) then begin // (Checking...) for i := 0 to (bytesToTransfer - 1) do begin if (writeBytes[i] <> readBytes[i]) then begin // If there was a problem, update retval to reflect the // last correct value read in retVal := retval + int64(i); break; end; end; end; end; finished := finished or (bytesTransferred <> bytesToTransfer); // Note: Cast to int64 to ensure no problems retval := retval + int64(bytesTransferred); inc(blockNumber); end; // Ensure that the buffer is flushed to disk (even through disk caching // software) [from Borland FAQ] FlushFileBuffers(fileHandle); finally FlushFileBuffers(fileHandle); CloseHandle(fileHandle); end; end; // ELSE PART - if (fileHandle = INVALID_HANDLE_VALUE) then finally progressDlg.Free(); end; Result := retVal; end; procedure TfrmVerifyCapacity.GetVerifyDataBlock(blockNumber: integer; var outputBlock: TVerifyBlock); var i: integer; strBlock: string; begin // Fill block with data for i:=low(outputBlock) to high(outputBlock) do begin outputBlock[i] := (i mod 256); end; // "Brand" the block with the decimal and hex representations of the block // number strBlock := Format('%d=%x#', [blockNumber, blockNumber]); for i:=low(outputBlock) to high(outputBlock) do begin outputBlock[i] := outputBlock[i] XOR ord(strBlock[ ((i mod length(strBlock)) + 1) ]); end; end; function TfrmVerifyCapacity.TimerStart(): TDateTime; begin Result := now; end; function TfrmVerifyCapacity.TimerStop(startTime: TDateTime): string; begin Result := TimeToStr(startTime - now); end; // Identify retail size of drive function TfrmVerifyCapacity.RetailSize(capacity: int64): string; const RETAIL_1_MB = 1000 * 1000; var retval: string; begin // We tack on 2MB to capacity in order to compensate for quick check // accuracy capacity := capacity + (int64(2) * SIZE_1_MB); // Minimum amounts for a device to be regarded as... if (capacity >= (int64(5) * RETAIL_1_GB)) then begin retval := '>4 GB'; end else if (capacity >= (int64(4) * RETAIL_1_GB)) then begin retval := '4 GB'; end else if (capacity >= (int64(2) * RETAIL_1_GB)) then begin retval := '2 GB'; end else if (capacity >= (int64(1) * RETAIL_1_GB)) then begin retval := '1 GB'; end else if (capacity >= (int64(512) * RETAIL_1_MB)) then begin retval := '512 MB'; end else if (capacity >= (int64(256) * RETAIL_1_MB)) then begin retval := '256 MB'; end else if (capacity >= (int64(128) * RETAIL_1_MB)) then begin retval := '128 MB'; end else if (capacity >= (int64(64) * RETAIL_1_MB)) then begin retval := '64 MB'; end else if (capacity >= (int64(32) * RETAIL_1_MB)) then begin retval := '32 MB'; end else if (capacity >= (int64(16) * RETAIL_1_MB)) then begin retval := '16 MB'; end else begin retval := '<16 MB'; end; Result := retval; end; END.
unit uCommon; interface uses SysUtils, IOUtils, Generics.Collections, IniFiles, DB, Classes, uGlobal, uLogger, uSQLHelper; procedure Initialize; procedure Finalizat; implementation procedure SQLError(const SQL, Description: string); begin logger.Error(Description + #13#10 + SQL); end; procedure Initialize; var appPath, logPath: string; ini: TIniFile; host, db, user, pwd: string; begin appPath := TPath.GetDirectoryName(ParamStr(0)); logPath := TPath.Combine(appPath, 'log'); if not TDirectory.Exists(logPath) then TDirectory.CreateDirectory(logPath); logPath := TPath.Combine(logPath, 'JJCSYIN.log'); logger := TLogger.Create(logPath); logger.MaxBackupIndex := 99; logger.Info('Application Initialize'); ini:= TIniFile.Create(TPath.Combine(appPath, 'Config.ini')); host:= ini.ReadString('DB', 'server', ''); db:= ini.ReadString('DB', 'dbname', 'yjitsdb'); user:= ini.ReadString('DB', 'user', 'vioadmin'); pwd:= ini.ReadString('DB', 'pwd', 'lgm1224,./'); sqlhelper := TSQLHelper.Create(host, db, user, pwd); sqlhelper.OnError := SqlError; logger.Level := ini.ReadInteger('sys', 'LogLevel', 0); gFilePath := ini.ReadString('sys', 'FilePath', ''); gIntervalSecond := ini.ReadInteger('sys', 'IntervalSecond', 1); ini.Free; end; procedure Finalizat; begin sqlHelper.Free; logger.Info('Application Finalizat'); logger.Free; end; end.
unit DAOMember; interface uses Generics.Collections, DataAccessObjects, LTClasses; type TDAOMember = class(TDAOBase) public function Authentication(ID: string; Password: string): TAcademy; function Validate(ID: string; Password: string): Boolean; function Login(ID: string; Password: string): Boolean; function Load(ID: string): TUser; function SearchMember(ID : String) : TObjectlist<TUser>; function GetAllMember: TObjectlist<TUser>; function CheckingTest(ID: string; TestIndex: integer): TObjectList<TLevelTestCheck>; procedure DeleteMember(ID : string); procedure ModifyMember(User : TUser); procedure InsertMember(user : TUser); procedure InsertGuest(Guest: TGuest); end; implementation { TDAOMember } function TDAOMember.Authentication(ID, Password: string): TAcademy; begin Result := TAcademy.Create; Query.CommandText := 'SELECT relation FROM g4_member ' + 'WHERE (mb_id = :mb_id) and (mb_password = :mb_password) and (mb_level > 3);'; Query.Params.ParamByName('mb_id').AsString := ID; Query.Params.ParamByName('mb_password').AsString := Password; Query.Open; Result.Code := Query.FieldByName('relation').AsInteger; Result.Name := 'Khan'; // todo : 추후 relation 정보를 갖고 Name를 검색 하여 추가 // todo : Authentication, Validate 중복되는 함수 합치기 end; function TDAOMember.CheckingTest(ID: string; TestIndex: integer): TObjectList<TLevelTestCheck>; var TestCheck: TLevelTestCheck; begin Result := TObjectList<TLevelTestCheck>.Create; Query.CommandText := 'SELECT idx, title, ' + '(SELECT COUNT(*) FROM leveltest_permission ' + 'WHERE mb_id = :userid AND test_idx = :testindex) AS permission, ' + '(SELECT idx FROM leveltest_result ' + 'WHERE mb_id = :userid AND test_idx = test.idx) AS result_idx FROM test;'; Query.Params.ParamByName('userid').AsString := ID; Query.Params.ParamByName('testindex').AsInteger := TestIndex; Query.Open; Query.First; while not Query.Eof do begin TestCheck := TLevelTestCheck.Create; TestCheck.Index := Query.FieldByName('idx').AsInteger; TestCheck.Title := Query.FieldByName('title').AsString; TestCheck.Permission := Query.FieldByName('permssion').AsInteger; TestCheck.ResultIndex := Query.FieldByName('result_idx').AsInteger; Result.Add(TestCheck); Query.Next; end; // todo : 이곳을 할 차례... 쿼리로 뽑은 내용을 // 호출 한 곳으로 넘겨주고 비교하여 리스트뷰에 뿌려줘야 함 end; procedure TDAOMember.DeleteMember(ID : string); begin Query.Close; Query.CommandText := 'DELETE FROM g4_member WHERE mb_id = :ID '; Query.Params.ParamByName('ID').AsString := Id; Query.Execute; end; function TDAOMember.GetAllMember: TObjectlist<TUser>; var User : TUser; begin Result := TObjectlist<TUser>.Create; query.Close; Query.CommandText :=' SELECT * FROM g4_member ; '; Query.Open; query.First; while not query.eof do begin User := TUser.Create; user.UserId := Query.FieldByName('mb_id').AsString; user.UserPassword := Query.FieldByName('mb_password').AsString; user.Level := Query.FieldByName('mb_level').AsInteger; user.Name := Query.FieldByName('mb_name').AsString; // user.Academy.Code := Query.FieldByName('relation').Asinteger; result.add(user); query.Next; end; end; procedure TDAOMember.InsertGuest(Guest: TGuest); begin Query.Close; Query.CommandText := 'INSERT INTO guest_member ' + '(g_id, g_name, g_phone, g_school, g_grade, relation) ' + 'VALUES (:id, :name, :phone, :school, :grade, :relation);'; Query.Params.ParamByName('id').AsString := Guest.UserId; Query.Params.ParamByName('name').AsString := Guest.Name; Query.Params.ParamByName('phone').AsString := Guest.Phone; Query.Params.ParamByName('school').AsString := Guest.School; Query.Params.ParamByName('grade').AsString := Guest.Grade; Query.Params.ParamByName('relation').AsInteger := Guest.Academy.Code; Query.Execute; end; procedure TDAOMember.InsertMember(user : TUser); begin Query.Close; Query.CommandText := 'INSERT INTO g4_member ' + 'mb_id = :mb_id, mb_name = :mb_name, relation = :relation, ' + 'mb_password = :mb_password, mb_level = :mb_level '; Query.Open; Query.Params.ParamByName('mb_id').AsString := user.UserId; Query.Params.ParamByName('mb_password').AsString := user.UserPassword; Query.Params.ParamByName('mb_level').AsInteger := user.Level; Query.Params.ParamByName('mb_name').AsString := user.Name; Query.Params.ParamByName('relation').AsInteger := user.relation; // Query.Params.ParamByName('auth').AsString := 'Y'; end; function TDAOMember.Load(ID: string): TUser; begin Result := TUser.Create; Query.CommandText := 'SELECT mb_id, mb_password, mb_level, mb_name FROM g4_member ' + 'WHERE mb_id = :mb_id;'; Query.Params.ParamByName('mb_id').AsString := ID; Query.Open; Result.UserId := Query.FieldByName('mb_id').AsString; Result.UserPassword := Query.FieldByName('mb_password').AsString; Result.Level := Query.FieldByName('mb_level').AsInteger; Result.Name := Query.FieldByName('mb_name').AsString; Result.Academy.Code := Query.FieldByName('relation').AsInteger; // todo : relation 을 이용하여 학원정보와 선생님 정보 추출 end; function TDAOMember.Login(ID, Password: string): Boolean; begin Query.Close; Query.CommandText := 'SELECT * FROM g4_member ' + 'WHERE (mb_id = :mb_id) and (mb_password = :mb_password);'; Query.Params.ParamByName('mb_id').AsString := ID; Query.Params.ParamByName('mb_password').AsString := Password; Query.Open; if Query.IsEmpty then Result := False else Result := True; end; procedure TDAOMember.ModifyMember(User: TUser); begin query.Close; Query.CommandText :=' UPDATE g4_member SET ' + 'mb_id = :mb_id, mb_name = :password, relation = :relation, ' + 'mb_password = :mb_password, auth = :auth, mb_level = :mb_level '; Query.Open; Query.Params.ParamByName('mb_id').AsString; Query.Params.ParamByName('mb_password').AsString; Query.Params.ParamByName('mb_level').AsInteger; Query.Params.ParamByName('mb_name').AsString; Query.Params.ParamByName('relation').AsString; Query.Params.ParamByName('auth').AsString; // user.Academy.Code := Query.FieldByName('relation').Asinteger; query.Execute; end; function TDAOMember.SearchMember(ID : String): TObjectlist<TUser>; var User : TUser; begin Result := TObjectlist<TUser>.Create; query.Close; Query.CommandText :=' SELECT * FROM g4_member WHERE mb_id like :ID; '; query.Params.ParamByName('ID').AsString := ID; Query.Open; query.First; while not query.eof do begin User := TUser.Create; user.UserId := Query.FieldByName('mb_id').AsString; user.UserPassword := Query.FieldByName('mb_password').AsString; user.Level := Query.FieldByName('mb_level').AsInteger; user.Name := Query.FieldByName('mb_name').AsString; // user.Academy.Code := Query.FieldByName('relation').Asinteger; result.add(user); query.Next; end; end; function TDAOMember.Validate(ID, Password: string): Boolean; begin Query.Close; Query.CommandText := 'SELECT * FROM g4_member ' + 'WHERE (mb_id = :mb_id) and (mb_password = :mb_password) and (mb_level > 3);'; Query.Params.ParamByName('mb_id').AsString := ID; Query.Params.ParamByName('mb_password').AsString := Password; Query.Open; if Query.IsEmpty then Result := False else Result := True; end; end.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit ExpertsModuleCreators; interface uses Classes, ExpertsBaseCreators, ToolsAPI, ExpertsIntf; type TExpertsNewImplSourceProc = reference to procedure(const ModuleIdent, FormIdent, AncestorIdent: string); TExpertsModuleCreator = class(TModuleCreator, IOTAModuleCreator, IOTACreator) private FExpertsModule: IExpertsModuleAccessor; FPersonality: string; FOnNewImplSource: TExpertsNewImplSourceProc; { IOTAModuleCreator } function GetAncestorName: string; function NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; function NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; function NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile; property Personality: string read FPersonality; { IOTACreator } function GetUnnamed: Boolean; function GetOwner: IOTAModule; public constructor Create(const APersonality: string; const AExpertsModule: IExpertsModuleAccessor; AOnNewImplSource: TExpertsNewImplSourceProc = nil); overload; end; // Create a module with a formname and ancestor name, but no designer. // For example: formname: MyComponentClass, ancestorName: TComponent. TExpertsModuleUnitCreator = class(TExpertsModuleCreator, IOTACreator) private { IOTACreator } function GetCreatorType: string; function GetOwner: IOTAModule; end; TExpertsUnitCreator = class(TUnitCreator, IOTAModuleCreator, IOTACreator) private FExpertsModule: IExpertsModuleAccessor; FPersonality: string; FOnNewImplSource: TExpertsNewImplSourceProc; { IOTAModuleCreator } function GetAncestorName: string; function NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; function NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; property Personality: string read FPersonality; { IOTACreator } function GetUnnamed: Boolean; function GetOwner: IOTAModule; public constructor Create(const APersonality: string; const AExpertsModule: IExpertsModuleAccessor; AOnNewImplSource: TExpertsNewImplSourceProc = nil); end; TExpertsTextFileCreator = class(TTextFileCreator, IOTAModuleCreator, IOTACreator) private FExpertsModule: IExpertsModuleAccessor; { IOTAModuleCreator } function NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; { IOTACreator } function GetUnnamed: Boolean; function GetOwner: IOTAModule; public constructor Create(const AExpertsModule: IExpertsModuleAccessor); end; TExpertsPchCreator = class(TPchCreator, IOTAModuleCreator, IOTACreator) private FExpertsModule: IExpertsModuleAccessor; { IOTAModuleCreator } function NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; { IOTACreator } function GetUnnamed: Boolean; function GetOwner: IOTAModule; public constructor Create(const AExpertsModule: IExpertsModuleAccessor); end; implementation uses SysUtils; { TExpertsModuleCreator } constructor TExpertsModuleCreator.Create(const APersonality: string; const AExpertsModule: IExpertsModuleAccessor; AOnNewImplSource: TExpertsNewImplSourceProc); begin FPersonality := APersonality; FExpertsModule := AExpertsModule; FOnNewImplSource := AOnNewImplSource; inherited Create(AExpertsModule.GetFileName, AExpertsModule.GetFormName); end; function TExpertsModuleCreator.GetAncestorName: string; begin Result := FExpertsModule.GetAncestorName; if Result = '' then Result := 'Form'; // Do not localize end; function TExpertsModuleCreator.GetOwner: IOTAModule; begin if FExpertsModule.Designing then Result := nil else Result := inherited; end; function TExpertsModuleCreator.GetUnnamed: Boolean; begin if FExpertsModule.Designing then Result := True else Result := FExpertsModule.GetUnnamed; end; function TExpertsModuleCreator.NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; begin if Assigned(FOnNewImplSource) then FOnNewImplSource(ModuleIdent, FormIdent, AncestorIdent); Result := FExpertsModule.NewSourceFile(ModuleIdent, FormIdent, AncestorIdent) end; function TExpertsModuleCreator.NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; begin if Personality = sCBuilderPersonality then begin Result := FExpertsModule.NewInterfaceFile(ModuleIdent, FormIdent, AncestorIdent); end else Result := nil; end; function TExpertsModuleCreator.NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile; begin Result := FExpertsModule.NewFormFile(FormIdent, AncestorIdent); end; { TExpertsUnitCreator } constructor TExpertsUnitCreator.Create(const APersonality: string; const AExpertsModule: IExpertsModuleAccessor; AOnNewImplSource: TExpertsNewImplSourceProc); begin FPersonality := APersonality; FExpertsModule := AExpertsModule; FOnNewImplSource := AOnNewImplSource; inherited Create(AExpertsModule.GetFileName); end; const sBlankLine = #13#10#13#10; sNewPasUnitSource = 'unit %0:s;'+sBlankLine+ 'interface'+sBlankLine+ 'implementation'+sBlankLine+ 'end.'#13#10; sNewCppUnitSource = '//---------------------------------------------------------------------------'+sBlankLine+ '#pragma hdrstop'+sBlankLine+ '#include "%0:s.h"'+sBlankLine+ '//---------------------------------------------------------------------------'+sBlankLine+ '#pragma package(smart_init)'#13#10; sNewCppUnitInterface = '//---------------------------------------------------------------------------'+sBlankLine+ '#ifndef %0:sH'+sBlankLine+ '#define %0:sH'+sBlankLine+ '//---------------------------------------------------------------------------'+sBlankLine+ '#endif'#13#10; function TExpertsUnitCreator.GetAncestorName: string; begin Result := FExpertsModule.GetAncestorName; end; function TExpertsUnitCreator.GetOwner: IOTAModule; begin if FExpertsModule.Designing then Result := nil else Result := inherited; end; function TExpertsUnitCreator.GetUnnamed: Boolean; begin if FExpertsModule.Designing then Result := True else Result := FExpertsModule.GetUnnamed; end; function TExpertsUnitCreator.NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; begin if Assigned(FOnNewImplSource) then FOnNewImplSource(ModuleIdent, FormIdent, AncestorIdent); Result := FExpertsModule.NewSourceFile(ModuleIdent, FormIdent, AncestorIdent); if Result = nil then begin // Must supply a file if FPersonality = sDelphiPersonality then Result := TOTAFile.Create(Format(sNewPasUnitSource, [ModuleIdent])) else if FPersonality = sCBuilderPersonality then Result := TOTAFile.Create(Format(sNewCppUnitSource, [ModuleIdent])) else Result := TOTAFile.Create('') end; end; function TExpertsUnitCreator.NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; begin if Personality = sCBuilderPersonality then begin Result := FExpertsModule.NewInterfaceFile(ModuleIdent, FormIdent, AncestorIdent); if Result = nil then begin // Must supply a file if FPersonality = sCBuilderPersonality then Result := TOTAFile.Create(Format(sNewCppUnitInterface, [ModuleIdent])) else Result := TOTAFile.Create('') end; end else Result := nil; end; { TExpertsTextFileCreator } constructor TExpertsTextFileCreator.Create(const AExpertsModule: IExpertsModuleAccessor); begin FExpertsModule := AExpertsModule; inherited Create(FExpertsModule.GetFileName, FExpertsModule.GetFileNameExt); end; function TExpertsTextFileCreator.GetOwner: IOTAModule; begin if FExpertsModule.Designing then Result := nil else Result := inherited; end; function TExpertsTextFileCreator.GetUnnamed: Boolean; begin if FExpertsModule.Designing then Result := True else Result := FExpertsModule.GetUnnamed; end; function TExpertsTextFileCreator.NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; begin Result := FExpertsModule.NewSourceFile(ModuleIdent, FormIdent, AncestorIdent); if Result = nil then begin // Must supply a file Result := TOTAFile.Create('') end; end; { TExpertsModuleUnitCreator } function TExpertsModuleUnitCreator.GetCreatorType: string; begin // No designer Result := sUnit; end; function TExpertsModuleUnitCreator.GetOwner: IOTAModule; begin if FExpertsModule.Designing then Result := nil else Result := inherited; end; { TExpertsPchCreator } constructor TExpertsPCHCreator.Create(const AExpertsModule: IExpertsModuleAccessor); begin FExpertsModule := AExpertsModule; inherited Create(FExpertsModule.GetFileName, FExpertsModule.GetFileNameExt); end; function TExpertsPCHCreator.GetOwner: IOTAModule; begin if FExpertsModule.Designing then Result := nil else Result := inherited; end; function TExpertsPCHCreator.GetUnnamed: Boolean; begin if FExpertsModule.Designing then Result := True else Result := FExpertsModule.GetUnnamed; end; function TExpertsPCHCreator.NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; begin Result := FExpertsModule.NewSourceFile(ModuleIdent, FormIdent, AncestorIdent); if Result = nil then begin // Must supply a file Result := TOTAFile.Create('') end; end; end.
Unit UnImportacaoDados; Interface Uses Classes, DBTables, Tabela, SysUtils, UnDados,SQLExpr, StdCtrls, ComCtrls ; //classe funcoes Type TRBFuncoesImportacaoDado = class private Aux, Tabela, TabelaMatriz : TSQL; VprLabelQtd : TLabel; VprBarraProgresso : TProgressBar; function RTipCampo(VpaCodTipoCampo : Integer): TRBDTipoCampo; procedure CarCamposChavePrimaria(VpaDTabela: TRBDImportacaoDados); procedure CarCamposChavePaiFilho(VpaDTabela: TRBDImportacaoDados); procedure CarCamposAIgnorar(VpaDTabela: TRBDImportacaoDados); function RFiltrosSelect(VpaDTabela : TRBDImportacaoDados; VpaTabelaMatriz : TSQL) : string; function RFiltroVendedor(VpaDTabela : TRBDImportacaoDados) : string; function RFiltrosTabelaPai(VpaDTabela : TRBDImportacaoDados) : string; function RNomTabelasSelect(VpaDTabela : TRBDImportacaoDados) : string; procedure AtualizaDataUltimaImportacao(VpaDTabela : TRBDImportacaoDados;VpaDatImportacao : tDateTime); Procedure InicializaImportacao(VpaQtdTotalRegistros : Integer); public constructor cria(VpaBaseDados, VpaBaseDadosMatriz : TSQLConnection;VpaLabelQtd : TLabel;VpaBarraProgresso : TProgressBar); destructor destroy;override; Function PosTabelasaImportar(VpaTabela : TSQl):Integer; function ImportaTabela(VpaDTabela: TRBDImportacaoDados;VpaDatImportacao : TDateTime): string; function CarDImportacao(VpaCodTabela : Integer):TRBDImportacaoDados; function RDataServidorMatriz : TDateTime; end; implementation Uses FunSql, FunObjeto, Constantes; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( eventos da classe TRBFuncoesImportacaoDado )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {********************************* cria a classe ********************************} constructor TRBFuncoesImportacaoDado.cria(VpaBaseDados, VpaBaseDadosMatriz : TSQLConnection;VpaLabelQtd : TLabel;VpaBarraProgresso : TProgressBar); begin inherited create; Aux :=TSQL.Create(nil); Aux.ASQlConnection := VpaBaseDados; Tabela :=TSQL.Create(nil); Tabela.ASQlConnection := VpaBaseDados; TabelaMatriz :=TSQL.Create(nil); TabelaMatriz.ASQlConnection := VpaBaseDadosMatriz; // TabelaMatriz.PacketRecords := 400; VprLabelQtd := VpaLabelQtd; VprBarraProgresso := VpaBarraProgresso; end; {********************************* ***********************************************} destructor TRBFuncoesImportacaoDado.destroy; begin Aux.Free; Tabela.Free; TabelaMatriz.Free; inherited; end; {********************************* ***********************************************} function TRBFuncoesImportacaoDado.PosTabelasaImportar(VpaTabela: TSql):Integer; begin AdicionaSQLAbreTabela(VpaTabela,'Select count(*) QTD from TABELAIMPORTACAO '); result := VpaTabela.FieldByName('QTD').AsInteger; AdicionaSQLAbreTabela(VpaTabela,'Select * from TABELAIMPORTACAO ' + // ' WHERE CODTABELA = 31 '+ ' ORDER BY SEQIMPORTACAO '); end; {********************************* ***********************************************} function TRBFuncoesImportacaoDado.ImportaTabela(VpaDTabela: TRBDImportacaoDados;VpaDatImportacao : TDateTime): string; var vpfLaco : Integer; VpfRegistroAtual : Integer; begin AdicionaSQLAbreTabela(TabelaMatriz,'Select TAB.* from '+RNomTabelasSelect(VpaDTabela) + ' Where '+SQLTextoIsNull('TAB.'+VpaDTabela.NomCampoData,SQLTextoDataAAAAMMMDD(VpaDatImportacao))+ '>= '+ SQLTextoDataAAAAMMMDD(VpaDTabela.DatUltimaImportacao)+ RFiltroVendedor(VpaDTabela)+ RFiltrosTabelaPai(VpaDTabela) ); InicializaImportacao(TabelaMatriz.RecordCount); VpfRegistroAtual := 0; while not TabelaMatriz.Eof do begin AdicionaSQLAbreTabela(Tabela,'Select * from '+VpaDTabela.Nomtabela + RFiltrosSelect(VpaDTabela,TabelaMatriz)); if Tabela.Eof then Tabela.Insert else Tabela.Edit; for vpfLaco := 0 to Tabela.Fields.Count - 1 do begin if VpaDTabela.CamposIgnorar.IndexOf(Tabela.Fields[vpfLaco].DisplayName) < 0 then Tabela.FieldByName(Tabela.Fields[vpfLaco].DisplayName).Value := TabelaMatriz.FieldByName(Tabela.Fields[vpfLaco].DisplayName).Value; end; inc(VpfRegistroAtual); VprLabelQtd.Caption := IntToStr(VpfRegistroAtual); VprLabelQtd.Refresh; VprBarraProgresso.Position := VprBarraProgresso.Position + 1; VprBarraProgresso.Refresh; Tabela.Post; TabelaMatriz.Next; end; AtualizaDataUltimaImportacao(VpaDTabela,VpaDatImportacao); end; {********************************* ***********************************************} procedure TRBFuncoesImportacaoDado.InicializaImportacao(VpaQtdTotalRegistros : Integer); begin VprLabelQtd.Caption := '0'; VprLabelQtd.Refresh; VprBarraProgresso.Position := 0; VprBarraProgresso.Max := VpaQtdTotalRegistros; end; {********************************* ***********************************************} function TRBFuncoesImportacaoDado.RDataServidorMatriz: TDateTime; begin AdicionaSQLAbreTabela(TabelaMatriz,'Select SYSDATE from DUAL'); result := TabelaMatriz.FieldByName('SYSDATE').AsDateTime; TabelaMatriz.Close; end; {********************************* ***********************************************} function TRBFuncoesImportacaoDado.RFiltrosSelect(VpaDTabela: TRBDImportacaoDados; VpaTabelaMatriz: TSQL): string; var VpfLaco : Integer; VpfDCampo : TRBDCamposImportacaoDados; begin result := ''; for Vpflaco := 0 to VpaDTabela.CamposChavePrimaria.Count - 1 do begin VpfDCampo := TRBDCamposImportacaoDados(VpaDTabela.CamposChavePrimaria.Items[VpfLaco]); if VpfLaco = 0 then result := ' Where ' else result := result + ' AND '; result := result + VpfDCampo.NomCampo + ' = '; case VpfDCampo.TipCampo of tcInteiro : result := result + VpaTabelaMatriz.FieldByName(VpfDCampo.NomCampo).AsString ; tcCaracter : result := result + ''''+ VpaTabelaMatriz.FieldByName(VpfDCampo.NomCampo).AsString +''''; tcData : result := result + SQLTextoDataAAAAMMMDD(VpaTabelaMatriz.FieldByName(VpfDCampo.NomCampo).AsDateTime); end; end; end; {********************************* ***********************************************} function TRBFuncoesImportacaoDado.RFiltrosTabelaPai(VpaDTabela: TRBDImportacaoDados): string; var VpfLaco : Integer; VpfDCampo : TRBDCamposImportacaoDados; begin result := ''; for VpfLaco := 0 to VpaDTabela.CamposChavePaiFilho.Count - 1 do begin VpfDCampo := TRBDCamposImportacaoDados(VpaDTabela.CamposChavePaiFilho.Items[VpfLaco]); result := RESULT + ' AND TAB.'+VpfDCampo.NomCampo + ' = PAI.'+ VpfDCampo.NomCampoPai end; end; {********************************* ***********************************************} function TRBFuncoesImportacaoDado.RFiltroVendedor(VpaDTabela: TRBDImportacaoDados): string; begin result := ''; if not config.ImportarTodosVendedores then begin if VpaDTabela.DesFiltroVendedor <> '' then begin if VpaDTabela.NomTabelaPai <> '' then result := 'AND PAI.'+VpaDTabela.DesFiltroVendedor +' = '+IntToStr(varia.CodVendedorSistemaPedidos) else result := 'AND TAB.'+VpaDTabela.DesFiltroVendedor +' = '+IntToStr(varia.CodVendedorSistemaPedidos); end; end; end; {********************************* ***********************************************} function TRBFuncoesImportacaoDado.RNomTabelasSelect(VpaDTabela: TRBDImportacaoDados): string; begin result := VpaDTabela.Nomtabela + ' TAB '; if VpaDTabela.NomTabelaPai <> '' then result := result +' , '+VpaDTabela.NomTabelaPai + ' PAI '; end; {********************************* ***********************************************} function TRBFuncoesImportacaoDado.RTipCampo(VpaCodTipoCampo: Integer): TRBDTipoCampo; begin case VpaCodTipoCampo of 1 : Result := tcInteiro; 2 : result := tcNumerico; 3 : Result := tcCaracter; 4 : Result := tcData; end; end; {********************************* ***********************************************} procedure TRBFuncoesImportacaoDado.AtualizaDataUltimaImportacao(VpaDTabela: TRBDImportacaoDados;VpaDatImportacao: tDateTime); begin AdicionaSQLAbreTabela(Tabela,'Select * from TABELAIMPORTACAO '+ ' Where CODTABELA = '+IntToStr(VpaDTabela.CodTabela)); Tabela.Edit; Tabela.FieldByName('DATIMPORTACAO').AsDateTime := VpaDatImportacao; Tabela.Post; Tabela.Close; end; {********************************* ***********************************************} procedure TRBFuncoesImportacaoDado.CarCamposAIgnorar(VpaDTabela: TRBDImportacaoDados); begin VpaDTabela.CamposIgnorar.Clear; AdicionaSQLAbreTabela(Tabela,'Select * from TABELAIMPORTACAOIGNORARCAMPO '+ ' Where CODTABELA = '+IntToStr(VpaDTabela.CodTabela)); while not Tabela.Eof do begin VpaDTabela.CamposIgnorar.Add(Tabela.FieldByName('NOMCAMPO').AsString); Tabela.Next; end; Tabela.Close; end; {********************************* ***********************************************} procedure TRBFuncoesImportacaoDado.CarCamposChavePaiFilho(VpaDTabela: TRBDImportacaoDados); var VpfDCampo : TRBDCamposImportacaoDados; begin FreeTObjectsList(VpaDTabela.CamposChavePaiFilho); AdicionaSQLAbreTabela(Tabela,'Select * from TABELAIMPORTACAOCAMPOPAIFILHO '+ ' Where CODTABELA = '+IntToStr(VpaDTabela.CodTabela)); while not Tabela.Eof do begin VpfDCampo := VpaDTabela.addCampoPaiFilho; VpfDCampo.NomCampo := Tabela.FieldByName('NOMCAMPO').AsString; VpfDCampo.NomCampoPai := Tabela.FieldByName('NOMCAMPOPAI').AsString; Tabela.Next; end; Tabela.Close; end; {********************************* ***********************************************} procedure TRBFuncoesImportacaoDado.CarCamposChavePrimaria(VpaDTabela: TRBDImportacaoDados); var VpfDCampo : TRBDCamposImportacaoDados; begin FreeTObjectsList(VpaDTabela.CamposChavePrimaria); AdicionaSQLAbreTabela(Tabela,'Select * from TABELAIMPORTACAOFILTRO '+ ' Where CODTABELA = '+IntToStr(VpaDTabela.CodTabela)); while not Tabela.Eof do begin VpfDCampo := VpaDTabela.addCampoFiltro; VpfDCampo.NomCampo := Tabela.FieldByName('NOMCAMPO').AsString; VpfDCampo.TipCampo := RTipCampo(Tabela.FieldByName('TIPCAMPO').AsInteger); Tabela.Next; end; Tabela.Close; end; {********************************* ***********************************************} function TRBFuncoesImportacaoDado.CarDImportacao(VpaCodTabela : Integer): TRBDImportacaoDados; begin result := TRBDImportacaoDados.cria; Result.CamposIgnorar.Clear; FreeTObjectsList(Result.CamposChavePrimaria); AdicionaSQLAbreTabela(Tabela,'Select * from TABELAIMPORTACAO ' + ' Where CODTABELA = '+IntToStr(VpaCodTabela)); Result.CodTabela := Tabela.FieldByName('CODTABELA').AsInteger; Result.Nomtabela := Tabela.FieldByName('NOMTABELA').AsString; Result.NomTabelaPai := Tabela.FieldByName('NOMTABELAPAI').AsString; Result.Destabela := Tabela.FieldByName('DESTABELA').AsString; result.NomCampoData := Tabela.FieldByName('DESCAMPODATA').AsString; result.DesFiltroVendedor := Tabela.FieldByName('DESFILTROVENDEDOR').AsString; result.DatUltimaImportacao := Tabela.FieldByName('DATIMPORTACAO').AsDateTime; if result.CodTabela > 0 then begin CarCamposChavePrimaria(Result); CarCamposAIgnorar(result); CarCamposChavePaiFilho(result); end; end; end.
unit ServerContainerUnit; interface uses System.SysUtils, System.Classes, Datasnap.DSTCPServerTransport, Datasnap.DSServer, Datasnap.DSCommonServer, Datasnap.DSAuth, IPPeerServer, vcl.ComCtrls, System.Generics.Collections, Datasnap.DSHTTP; type TServerContainer1 = class(TDataModule) DSServer1: TDSServer; DSTCPServerTransport1: TDSTCPServerTransport; DSServerClass1: TDSServerClass; DSHTTPService1: TDSHTTPService; procedure DSServerClass1GetClass(DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); procedure GetConnectedClient; procedure GetClientList; procedure DataModuleCreate(Sender: TObject); // ClientList에 클라목록 넣음 private { Private declarations } public ClientDic: TDictionary<string,string>; end; var ServerContainer1: TServerContainer1; implementation {$R *.dfm} uses Winapi.Windows, ServerMethodsUnit, UServerMain, UClient; procedure TServerContainer1.DataModuleCreate(Sender: TObject); begin ClientDic := TDictionary<string, string>.create; end; procedure TServerContainer1.DSServerClass1GetClass( DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); begin PersistentClass := ServerMethodsUnit.TServerMethods1; end; procedure TServerContainer1.GetClientList; var client: TClient; I: integer; begin ClientDIc.Clear; try for I := 0 to ServerContainer1.DSServer1.GetAllChannelClientId('MessageChannel').Count - 1 do begin ClientDic.Add(ServerContainer1.DSServer1.GetAllChannelCallbackId('MessageChannel')[i], ServerContainer1.DSServer1.GetAllChannelClientId('MessageChannel')[i]); MainForm.Memo1.Lines.Add( ClientDic.Items[ServerContainer1.DSServer1.GetAllChannelCallbackId('MessageChannel')[i]]); end; except MainForm.Memo1.Lines.Add('클라이언트 목록 작성 에러'); end; end; procedure TServerContainer1.GetConnectedClient; var I: integer; listI: TListItem; begin I := 0; Mainform.ListView1.Clear; try for I := 0 to ServerContainer1.DSServer1.GetAllChannelClientId('MessageChannel').Count - 1 do begin listI := MainForm.ListView1.Items.Add; listI.Caption := ServerContainer1.DSServer1.GetAllChannelCallbackId('MessageChannel')[i]; listI.SubItems.add(ServerContainer1.DSServer1.GetAllChannelClientId('MessageChannel')[i]); end; except MainForm.Memo1.Lines.Add('클라이언트 목록 받기 에러'); end; end; end.
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+} {$M 65520,0,655360} { by Behdad Esfahbod Algorithmic Problems Book September '1999 Problem 25 O(N2) Dfs Method } program DiameterOfTree; const MaxN = 10000; type TArr = array [1 .. MaxN] of Integer; var N, E : Integer; A : array [1 .. MaxN, 1 .. 2] of Integer; L : array [1 .. MaxN] of Integer; C1, C2, H : ^ TArr; I, J, K, X, Y, Z, D, D1, D2 : Integer; F : Text; procedure ReadInput; begin Assign(F, 'input.txt'); Reset(F); Readln(F, N); GetMem(H, SizeOf(H^[1]) * N); GetMem(C1, SizeOf(C1^[1]) * N); GetMem(C2, SizeOf(C2^[1]) * N); for I := 1 to N - 1 do Readln(F, A[I, 1], A[I, 2]); Close(F); end; procedure Dfs (V : Integer); begin L[V] := V; H^[V] := 0; for X := 1 to N - 1 do begin C1^[V] := X; for Y := 1 to 2 do begin C2^[V] := Y; if (A[X, Y] = V) and (L[A[X, 3 - Y]] = 0) then begin Dfs(A[X, 3 - Y]); K := A[C1^[V], 3 - C2^[V]]; if H^[V] + H^[K] + 1 > D then begin D := H^[V] + H^[K] + 1; D1 := L[V]; D2 := L[K]; end; if H^[V] < H^[K] + 1 then begin H^[V] := H^[K] + 1; L[V] := L[K]; end; end; Y := C2^[V]; end; X := C1^[V]; end; end; procedure WriteOutput; begin Assign(F, 'output.txt'); ReWrite(F); Writeln(F, 'Diameter = ', D); Writeln(F, D1, ' ', D2); Close(F); end; begin ReadInput; Dfs(1); WriteOutput; end.
unit fifo; interface uses windows, sysutils, math; type tFIFO=class private data:array of byte; write_pos:integer; read_pos:integer; v_count:integer; r_count:integer; v_max:integer; debug:integer; critical_section:_RTL_CRITICAL_SECTION; function get_free:integer; procedure put(v:byte); function get:byte; public stat_readed, stat_writed:int64; constructor create(size:integer); destructor destroy;override; procedure write_nonblock(buffer:pointer;size:integer); procedure read_nonblock(buffer:pointer;size:integer); procedure read_void(size:integer); procedure write(buffer:pointer;size:integer); procedure write_cmd(buffer:pbyte;size:integer); procedure read(buffer:pointer;size:integer); procedure reset; procedure stat_reset; function free_ratio:integer; function count_ratio:integer; property count:integer read r_count; property max:integer read v_max; property free_bytes:integer read get_free; end; tfifo_blocks=class private critical_section:_RTL_CRITICAL_SECTION; blocks:tfifo; data:tfifo; read_blocks_count:integer; read_blocks_free:integer; read_data_count:integer; read_data_free:integer; procedure update; function read_blocks_max:integer; function read_data_max:integer; public stat_bytes_readed, stat_bytes_writed:int64; stat_blocks_readed, stat_blocks_writed:int64; stat_blocks_overfulled, stat_bytes_overfulled:int64; stat_blocks_lost, stat_bytes_lost:int64; constructor create(data_size, blocks_count:integer); destructor destroy;override; function read(block:pointer; maxsize:integer):integer; function read_nonblock(block:pointer; maxsize:integer):integer; function read_void:integer; function read_str:string; procedure write(block:pointer; size:integer); procedure write_cmd(buffer:pbyte;size:integer); procedure write_nonblock(block:pointer; size:integer); procedure write_str(str:string); procedure reset; procedure stat_reset; function free_ratio:integer; function count_ratio:integer; property blocks_count:integer read read_blocks_count; property blocks_free:integer read read_blocks_free; property blocks_max:integer read read_blocks_max; property data_count:integer read read_data_count; property data_free:integer read read_data_free; property data_max:integer read read_data_max; end; procedure fifo_blocks_test; implementation uses classes; constructor tfifo_blocks.create; begin inherited create(); blocks:=tfifo.create(blocks_count*sizeof(integer)); data:=tfifo.create(data_size); InitializeCriticalSection(critical_section); update; end; destructor tfifo_blocks.destroy; begin inherited destroy; blocks.FreeInstance; blocks:=nil; data.FreeInstance; data:=nil; DeleteCriticalSection(critical_section); end; function tfifo_blocks.read_blocks_max; begin result:=blocks.max div sizeof(integer); end; function tfifo_blocks.read_data_max; begin result:=data.max; end; procedure tfifo_blocks.update; begin if self=nil then exit; if data=nil then exit; if blocks=nil then exit; read_blocks_count:=blocks.count div sizeof(integer); read_blocks_free:=blocks.free_bytes div sizeof(integer); read_data_count:=data.count; read_data_free:=data.free_bytes; end; procedure tfifo_blocks.reset; begin if self=nil then exit; EnterCriticalSection(critical_section); blocks.reset; data.reset; update; LeaveCriticalSection(critical_section); end; procedure tfifo_blocks.stat_reset; begin blocks.stat_reset; data.stat_reset; stat_bytes_readed:=0; stat_bytes_writed:=0; stat_blocks_readed:=0; stat_blocks_writed:=0; stat_blocks_overfulled:=0; stat_bytes_overfulled:=0; stat_blocks_lost:=0; stat_bytes_lost:=0; end; procedure tfifo_blocks.write(block:pointer;size:integer); begin if self=nil then exit; EnterCriticalSection(critical_section); write_nonblock(block, size); LeaveCriticalSection(critical_section); end; function tfifo_blocks.read(block:pointer;maxsize:integer):integer; begin result:=0; if self=nil then exit; EnterCriticalSection(critical_section); result:=read_nonblock(block, maxsize); LeaveCriticalSection(critical_section); end; procedure tfifo_blocks.write_str(str:string); begin if @self=nil then exit; if length(str)=0 then exit; write(@(str[1]), length(str)*sizeof(str[1])); end; function tfifo_blocks.read_str:string; var len:integer; begin result:=''; if @self=nil then exit; SetLength(result,$4000); len:=read(@(result[1]), length(result)*sizeof(result[1])); if len<length(result)*sizeof(result[1]) then SetLength(result, len div sizeof(result[1])); end; procedure tfifo_blocks.write_nonblock(block:pointer; size:integer); begin if self=nil then exit; if blocks=nil then exit; if data=nil then exit; if size>data.max then exit; if size=0 then exit; { assert(((blocks.free_bytes=0) and (data.free_bytes=0)) or ((blocks.free_bytes<>0) and (data.free_bytes<>0)));} assert((blocks.free_bytes mod sizeof(integer))=0); while (blocks.free_bytes div sizeof(integer)<=0) or (data.free_bytes<size) do begin inc(stat_bytes_overfulled, read_void); inc(stat_blocks_overfulled); end; assert(((blocks.free_bytes=0) and (data.free_bytes=0)) or ((blocks.free_bytes<>0) and (data.free_bytes<>0))); assert((blocks.free_bytes mod sizeof(integer))=0); data.write_nonblock(block, size); blocks.write_nonblock(@size, sizeof(size)); inc(stat_blocks_writed); inc(stat_bytes_writed, size); update; end; function tfifo_blocks.read_nonblock(block:pointer; maxsize:integer):integer; var current,limited:integer; begin result:=0; if self=nil then exit; if blocks=nil then exit; if data=nil then exit; if maxsize=0 then exit; { assert(((blocks.free_bytes=0) and (data.free_bytes=0)) or ((blocks.free_bytes<>0) and (data.free_bytes<>0)), ' blocks.free_bytes=' + inttostr(blocks.free_bytes)+ ' data.free_bytes=' + inttostr(data.free_bytes) ); } assert((blocks.free_bytes mod sizeof(integer))=0); if blocks.count=0 then begin result:=0; exit; end; assert(blocks.count<>0); blocks.read_nonblock(@current, sizeof(current)); assert(current<=data.count); assert(current<>0); if current>maxsize then limited:=maxsize else limited:=current; data.read_nonblock(block, limited); data.read_void(current-limited); if (current-limited)<>0 then begin inc(stat_bytes_lost, current-limited); inc(stat_blocks_lost); end; result:=current; inc(stat_blocks_readed); inc(stat_bytes_readed, limited); update; end; function tfifo_blocks.read_void; var current:integer; begin result:=0; if self=nil then exit; if blocks=nil then exit; if data=nil then exit; blocks.read_nonblock(@current, sizeof(current)); data.read_void(current); result:=current; update; end; function tfifo_blocks.free_ratio:integer; var p1,p2:integer; begin result:=0; if self=nil then exit; if blocks.max=0 then exit; if data.max=0 then exit; p1:=blocks.free_ratio; p2:=data.free_ratio; result:=min(p1,p2); end; function tfifo_blocks.count_ratio:integer; var p1,p2:integer; begin result:=0; if self=nil then exit; if blocks.max=0 then exit; if data.max=0 then exit; p1:=blocks.count_ratio; p2:=data.count_ratio; result:=max(p1,p2); end; //////////////////////////////////////////////////////////////////////////////// constructor tfifo.create(size:integer); begin inherited create(); v_max:=size; setlength(data,max); v_count:=0; r_count:=0; write_pos:=0; read_pos:=0; InitializeCriticalSection(critical_section); debug:=0; end; destructor tfifo.destroy; begin inherited destroy; setlength(data,0); DeleteCriticalSection(critical_section); end; procedure tfifo.reset; begin if self=nil then exit; EnterCriticalSection(critical_section); v_count:=0; r_count:=0; write_pos:=0; read_pos:=0; LeaveCriticalSection(critical_section); end; function tfifo.get_free; begin result:=0; if self=nil then exit; result:=max-v_count; end; procedure tfifo.put(v:byte); begin if self=nil then exit; data[write_pos]:=v; inc(write_pos); if write_pos>=max then write_pos:=0; if v_count<max then inc(v_count) else begin inc(read_pos); if read_pos>=max then read_pos:=0; end; end; function tfifo.get:byte; begin result:=0; if self=nil then exit; if v_count<=0 then begin result:=0; exit; end; result:=data[read_pos]; inc(read_pos); if read_pos>=max then read_pos:=0; dec(v_count); end; procedure tfifo.write(buffer:pointer;size:integer); begin if self=nil then exit; EnterCriticalSection(critical_section); write_nonblock(buffer, size); LeaveCriticalSection(critical_section); end; procedure tfifo.read(buffer:pointer;size:integer); begin if self=nil then exit; EnterCriticalSection(critical_section); read_nonblock(buffer, size); LeaveCriticalSection(critical_section); end; procedure tfifo.write_nonblock(buffer:pointer;size:integer); var buf:pbyte; begin if self=nil then exit; inc(stat_writed, size); buf:=buffer; if size>max then begin inc(buf, size-max); size:=max; end; if write_pos+size>max then begin move(buf^, data[write_pos], max-write_pos); inc(buf, max-write_pos); move(buf^, data[0], size-(max-write_pos)); end else move(buf^, data[write_pos], size); write_pos:=(write_pos + size) mod max; inc(v_count, size); if v_count>max then begin read_pos:=(read_pos + v_count-max) mod max; v_count:=max; end;{} { while size>0 do begin put(buf^); inc(buf); dec(size); end;{} r_count:=v_count; end; procedure tfifo.read_nonblock(buffer:pointer;size:integer); var buf:pbyte; need, part:integer; begin if self=nil then exit; inc(stat_readed, size); buf:=buffer; need:=size; if need>v_count then need:=v_count; if need<>0 then if read_pos+need>max then begin part:=max-read_pos; move(data[read_pos], buf^, part); inc(buf, part); part:=size-(max-read_pos); move(data[0], buf^, part); inc(buf, part); end else begin move(data[read_pos], buf^, need); inc(buf, need); end; if need<>size then fillchar(buf^, size-need, 0); read_pos:=(read_pos + need) mod max; dec(v_count, need); { while size>0 do begin buf^:=get; inc(buf); dec(size); end;{} r_count:=v_count; end; procedure tfifo.read_void(size:integer); var need:integer; begin if self=nil then exit; need:=size; if need>v_count then need:=v_count; read_pos:=(read_pos + need) mod max; dec(v_count, need); { while size>0 do begin get; dec(size); end;} r_count:=v_count; end; function rdtsc:int64; asm db $0F; db $31; end; procedure fifo_blocks_test; var a:array of longint; b:array of longint; k:integer; rd_pos:integer; wr_pos:integer; size:integer; s:tstringlist; // str:string; f:file; fifo:tfifo_blocks; begin randseed:=rdtsc and $7FFFFFFF; setlength(a, 25000000); setlength(b, 25000000); for k:=0 to length(a)-1 do a[k]:=rdtsc and $7FFFFFFF; s:=tstringlist.Create; fifo:=tfifo_blocks.create(length(a)*sizeof(a), 10000); AssignFile(f,'test_before.dat'); rewrite(f,1); blockwrite(f,a[0], length(a)*sizeof(a)); closefile(f); wr_pos:=0; rd_pos:=0; while wr_pos<length(a) do begin if random(100)>=50 then begin size:=1+random(10000); if rd_pos+size>length(a) then size:=length(a)-rd_pos; if rd_pos>=length(a) then fifo.write(@(a[0]), size*sizeof(a[0])) else fifo.write(@(a[rd_pos]), size*sizeof(a[0])); s.Add('fifo <-'#9+inttostr(size)+#9+inttostr(fifo.blocks_count)+#9+inttostr(fifo.data_count)+#9+inttostr(rd_pos)+#9+inttostr(wr_pos)); inc(rd_pos, size); end else begin size:=fifo.read(@(b[wr_pos]), 10000*sizeof(a[0])); assert((size mod 4)=0); size:=size div 4; inc(wr_pos, size); s.Add('fifo ->'#9+inttostr(size)+#9+inttostr(fifo.blocks_count)+#9+inttostr(fifo.data_count)+#9+inttostr(rd_pos)+#9+inttostr(wr_pos)); end; end; s.SaveToFile('fifo.log'); AssignFile(f,'test_after.dat'); rewrite(f,1); blockwrite(f,b[0], length(b)*sizeof(b)); closefile(f); setlength(a, 0); setlength(b, 0); fifo.Free; s.Free; end; procedure tfifo.stat_reset; begin stat_readed:=0; stat_writed:=0; end; function tfifo.count_ratio:integer; begin result:=round(count/max*1000); end; function tfifo.free_ratio:integer; begin result:=round(free_bytes/max*1000); end; procedure tfifo.write_cmd(buffer:pbyte;size:integer); begin self.write(buffer, size); end; procedure tfifo_blocks.write_cmd(buffer:pbyte;size:integer); begin self.write(buffer, size); end; end.
unit TestuCSVUpdater; { 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, System.SysUtils, System.Generics.Collections, System.Generics.Defaults, System.Types, System.Classes, uCSVUpdater, Functional.Value; type // Test methods for class TCSVUpdater TestTCSVUpdater = class(TTestCase) strict private FCSVUpdater: TCSVUpdater; public procedure SetUp; override; procedure TearDown; override; published procedure TestCSVFileName_Contains_full_Path; procedure TestCSVUpdater_Header_Row_Contains_Correct_Fields; procedure TestCSVUpdater_Row_1_contains_CR; end; implementation uses GlenKleidon.CSVUtils; procedure TestTCSVUpdater.SetUp; begin FCSVUpdater := TCSVUpdater.Create('.\data\fun-stuff.csv'); end; procedure TestTCSVUpdater.TearDown; begin FCSVUpdater.Free; FCSVUpdater := nil; end; procedure TestTCSVUpdater.TestCSVFileName_Contains_full_Path; begin check( self.FCSVUpdater.Filename.Contains(':'), 'Filename does not contain full path "' + self.FCSVUpdater.Filename+'"' ); end; procedure TestTCSVUpdater.TestCSVUpdater_Header_Row_Contains_Correct_Fields; var Expected:string; Actual : string; begin Expected := 'Sequence'#13#10'Date'#13#10'Title'#13#10'Description'#13#10'Comments'#13#10; Actual := FCSVUpdater.Headers; check(Expected=Actual,'Expected: '+Expected+ #13#10+ 'Actual :'+ Actual); end; procedure TestTCSVUpdater.TestCSVUpdater_Row_1_contains_CR; var Actual: string; begin Actual := self.FCSVUpdater.Row[1]; check (Actual.Contains(#13#10),'Row 1 did not contain CRLF as Expected.'#13#10 + Actual ); end; initialization // Register any test cases with the test runner RegisterTest(TestTCSVUpdater.Suite); end.
unit eSocial.Controllers.Configuracao; interface uses System.SysUtils, System.Classes, eSocial.Controllers.Interfaces, eSocial.Models.DAO.Interfaces, eSocial.Models.DAO.Factory, eSocial.Models.Entities.Configuracao; type TControllerConfiguracao = class(TInterfacedObject, IControllerConfiguracao) strict private class var _instance : IControllerConfiguracao; private FDAO : iModelDAOEntity<TConfiguracao>; FErros : TStringList; protected constructor Create; public destructor Destroy; override; class function GetInstance : IControllerConfiguracao; function DAO : iModelDAOEntity<TConfiguracao>; function ValidarConfiguracao : Boolean; function Erros : String; end; implementation { TControllerConfiguracao } constructor TControllerConfiguracao.Create; begin FDAO := _ModelDAOFactory.Configuracao; FErros := TStringList.Create; FErros.BeginUpdate; FErros.Clear; FErros.EndUpdate; end; function TControllerConfiguracao.DAO: iModelDAOEntity<TConfiguracao>; begin Result := FDAO; end; destructor TControllerConfiguracao.Destroy; begin inherited; end; function TControllerConfiguracao.Erros: String; begin Result := FErros.Text; end; class function TControllerConfiguracao.GetInstance: IControllerConfiguracao; begin if not Assigned(_instance) then _instance := TControllerConfiguracao.Create; Result := _instance; end; function TControllerConfiguracao.ValidarConfiguracao: Boolean; begin FErros.BeginUpdate; FErros.Clear; if (FDAO.This.CodigoSIAFI = EmptyStr) then FErros.Add(FormatFloat('#00" - "', FErros.Count + 1) + 'O código SIAFI do órgão'); if (FDAO.This.UnidadeGestoraPrincipal = 0) then FErros.Add(FormatFloat('#00" - "', FErros.Count + 1) + 'A Unidade Gestora Principal'); if (FDAO.This.NaturezaJuridica = EmptyStr) then FErros.Add(FormatFloat('#00" - "', FErros.Count + 1) + 'A Natureza Jurídíca do órgão'); if (FDAO.This.ValorSubteto <= 0.0) then FErros.Add(FormatFloat('#00" - "', FErros.Count + 1) + 'O valor do subteto salarial'); if (FDAO.This.TipoSubteto = EmptyStr) then FErros.Add(FormatFloat('#00" - "', FErros.Count + 1) + 'O tipo do subteto salarial'); if (FDAO.This.DataImplantacaoESocial = EncodeDate(1899, 12, 30)) then FErros.Add(FormatFloat('#00" - "', FErros.Count + 1) + 'A Data de Implatação do eSocial no órgão'); if (not FDAO.This.Responsavel.DadosCompletos) then FErros.Add(FormatFloat('#00" - "', FErros.Count + 1) + 'Os dados completos do responsável pelo e-Social'); FErros.EndUpdate; Result := (FErros.Count = 0); end; end.
unit uconfig; {$mode objfpc}{$H+} interface uses Classes, SysUtils, inifiles; const ConfigFile = 'config.cfg'; type { TConfig } TConfig = class private FCardPrefix: string; FComPortName: string; FCurrentCardValue: int64; FEncoderMode: integer; public procedure Load; procedure Save; property CurrentCardValue: int64 read FCurrentCardValue write FCurrentCardValue; property ComPortName: string read FComPortName write FComPortName; property CardPrefix: string read FCardPrefix write FCardPrefix; property EncoderMode: integer read FEncoderMode write FEncoderMode; end; var Config: TConfig; implementation { TConfig } procedure TConfig.Load; var Ini: TIniFile; begin Ini := nil; Ini := TIniFile.Create(Configfile); try CurrentCardValue := Ini.ReadInt64('card','current_value', 71242); CardPrefix := Ini.ReadString('card','prefix','778=217090001='); ComPortName := Ini.ReadString('msr','portname','COM4'); EncoderMode := Ini.ReadInteger('msr','encoder_mode',0); finally Ini.Free; end; end; procedure TConfig.Save; var Ini: TIniFile; begin Ini := nil; Ini := TIniFile.Create(Configfile); try Ini.WriteInt64('card','current_value', CurrentCardValue); Ini.WriteString('card','prefix',CardPrefix); Ini.WriteString('msr','portname',ComPortName); Ini.WriteInteger('msr','encoder_mode',EncoderMode); finally Ini.Free; end; end; initialization Config := TConfig.Create; Config.Load; finalization Config.Save; Config.Free; end.
unit Vigilante.Build.DI; interface uses ContainerDI.Base, ContainerDI.Base.Impl; type TBuildDI = class(TContainerDI) public class function New: IContainerDI; procedure Build; override; end; implementation uses ContainerDI, Vigilante.Build.View, Vigilante.View.BuildURLDialog, Vigilante.Build.Service.Impl, Vigilante.Build.Service, Vigilante.Controller.Build, Vigilante.Controller.Build.Impl, Vigilante.Build.Observer, Vigilante.Build.Observer.Impl, Vigilante.Build.Event, Vigilante.Build.DomainEvent.Impl, Vigilante.Infra.Build.JSONDataAdapter, Vigilante.Infra.Build.JSONDataAdapter.Impl, Vigilante.Infra.Build.Builder, Vigilante.Infra.Build.Builder.Impl, Vigilante.Build.Repositorio, Vigilante.Infra.Build.Repositorio.Impl; procedure TBuildDI.Build; begin CDI.RegisterType<TBuildService>.Implements<IBuildService>; CDI.RegisterType<TBuildURLDialog>.Implements<IBuildURLDialog>('IBuildURLDialog'); CDI.RegisterType<TfrmBuildView, TfrmBuildView>; CDI.RegisterType<TBuildSubject>.Implements<IBuildSubject>.AsSingleton; CDI.RegisterType<TBuildController>.Implements<IBuildController>; CDI.RegisterType<TBuildDomainEvent>.Implements<IBuildEvent>; CDI.RegisterType<TBuildJSONDataAdapter>.Implements<IBuildJSONDataAdapter>; CDI.RegisterType<TBuildBuilder>.Implements<IBuildBuilder>; CDI.RegisterType<TBuildRepositorio>.Implements<IBuildRepositorio>; end; class function TBuildDI.New: IContainerDI; begin Result := Create; end; end.
unit MoveToCellFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Spin, Matrix32; type TMoveToCellForm = class(TForm) Panel1: TPanel; btnOK: TButton; btnCancel: TButton; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; labRowNum: TLabel; seRow: TSpinEdit; labColNum: TLabel; seCol: TSpinEdit; procedure btnOKClick(Sender: TObject); private { Private declarations } FSourMatrix: TMatrix; FCellMatrix: TMatrix; public { Public declarations } end; var MoveToCellForm: TMoveToCellForm; function ShowMoveToCellForm(SourMatrix: TMatrix; CellMatrix: TMatrix): Boolean; implementation {$R *.dfm} function ShowMoveToCellForm(SourMatrix: TMatrix; CellMatrix: TMatrix): Boolean; begin if CellMatrix.DimensionCount > 2 then begin Result := False; ShowMessage('Данная возможность для многомерного массива ячеек не реализована!'); Exit; end; with TMoveToCellForm.Create(nil) do try FSourMatrix := SourMatrix; FCellMatrix := CellMatrix; if FCellMatrix.DimensionCount = 1 then begin labRowNum.Visible := False; seRow.Visible := False; labColNum.Caption := 'Номер элемента'; end; Result := ShowModal = mrOk; finally Free; end; end; procedure TMoveToCellForm.btnOKClick(Sender: TObject); begin ModalResult := mrNone; if FCellMatrix.DimensionCount = 1 then begin if seCol.Value > FCellMatrix.Cols then FCellMatrix.PreservResize([seCol.Value]); FCellMatrix.VecCells[seCol.Value - 1] := FSourMatrix; end else begin if seRow.Value > FCellMatrix.Rows then FCellMatrix.PreservResize([seRow.Value, FCellMatrix.Cols]); if seCol.Value > FCellMatrix.Cols then FCellMatrix.PreservResize([FCellMatrix.Rows, seCol.Value]); FCellMatrix.Cells[seRow.Value - 1, seCol.Value - 1] := FSourMatrix; end; ModalResult := mrOk; end; end.
{************************************************** llPDFLib Version 6.4.0.1389, 09.07.2016 Copyright (c) 2002-2016 Sybrex Systems Copyright (c) 2002-2016 Vadim M. Shakun All rights reserved mailto:em-info@sybrex.com **************************************************} unit llPDFDocument; {$i pdf.inc} interface uses {$ifndef USENAMESPACE} Windows, SysUtils, Classes, Graphics, ShellAPI, {$else} WinAPI.Windows, System.SysUtils, System.Classes, Vcl.Graphics, WinAPI.ShellAPI, {$endif} {$ifdef WIN64} System.ZLib, System.ZLibConst, {$else} llPDFFlate, {$endif} llPDFSecurity, llPDFEMF, llPDFEngine, llPDFCanvas, llPDFImage, llPDFFont, llPDFTypes, llPDFOutline, llPDFAction, llPDFAnnotation, llPDFNames; type /// <summary> /// A PDF document may include a document information containing general information such as the /// document's title, author, and creation and modification dates. <br />Such global information about /// the document itself (as opposed to its content or structure) is called metadata, and is intended to /// assist in cataloguing and searching for documents in external databases. <br />You can set this /// information with help of the TPDFDocInfo object. /// </summary> TPDFDocInfo = class(TPersistent) private FAuthor: string; FCreationDate: TDateTime; FCreator: string; FKeywords: string; FProducer: string; FSubject: string; FTitle: string; protected procedure Save(ID: Integer;PDFEngine: TPDFEngine); public /// <summary> /// Specifies creation date of the document /// </summary> property CreationDate: TDateTime read FCreationDate write FCreationDate; /// <summary> /// Specifies producer name of the generated file. /// </summary> /// <remarks> /// This property can not be changed because of restrictions in the license agreement /// </remarks> property Producer: string read FProducer; published /// <summary> /// Specifies author name of the generated file. /// </summary> property Author: string read FAuthor write FAuthor; /// <summary> /// Specifies application name where generated file was created /// </summary> property Creator: string read FCreator write FCreator; /// <summary> /// Specifies keywords in the generated document /// </summary> property Keywords: string read FKeywords write FKeywords; /// <summary> /// Specifies description of the generated document /// </summary> property Subject: string read FSubject write FSubject; /// <summary> /// Specifies title of the generated document /// </summary> property Title: string read FTitle write FTitle; end; TPDFDocument = class; /// <summary> /// The main class of library which is used to make all manipulations with the generated PDF document. /// </summary> TPDFDocument = class(TComponent) private FAborted: Boolean; FAcroForms: TPDFAcroForms; FActions: TPDFActions; FACURL: Boolean; FAutoLaunch: Boolean; FCompression: TCompressionType; FDocumentInfo: TPDFDocInfo; FEngine: TPDFEngine; FFileName: string; FImages: TPDFImages; FFonts: TPDFFonts; FForms: TPDFListManager; FPatterns: TPDFListManager; FGStates: TPDFListManager; FOptionalContents: TOptionalContents; FJPEGQuality: Integer; FNames: TPDFNames; FOnePass: Boolean; FOpenDocumentAction: TPDFAction; FOutlines: TPDFOutlines; FOutputStream: TStream; FPageLayout: TPageLayout; FPageMode: TPageMode; FPages: TPDFPages; FPrinting: Boolean; FResolution: Integer; FSecurity: TPDFSecurityOptions; FStream: TStream; FViewerPreferences: TViewerPreferences; FPDFACompatible: Boolean; FCMYKICCStream: TStream; FRGBICCStream: TStream; FDigSignature:TPDFSignature; procedure ClearAll; function GetAutoCreateURL: Boolean; function GetCanvas: TCanvas; function GetCount: Integer; function GetCurrentPage: TPDFPage; function GetCurrentPageIndex: Integer; function GetEMFOptions: TPDFEMFParseOptions; function GetImages: TPDFImages; function GetNonEmbeddedFonts: TStringList; function GetPage(Index: Integer): TPDFPage; function GetPageNumber: Integer; procedure SaveCryptDictionary(ID: Integer); procedure SetAutoCreateURL(const Value: Boolean); procedure SetCurrentPageIndex(Index: Integer); procedure SetDocumentInfo(const Value: TPDFDocInfo); procedure SetFileName(const Value: string); procedure SetJPEGQuality(const Value: Integer); procedure SetOnePass(const Value: Boolean); procedure SetOutputStream(const Value: TStream); procedure SetSecurity(const Value: TPDFSecurityOptions); procedure StoreDocument; procedure SetCompression(const Value: TCompressionType); procedure SetNonEmbeddedFonts(const Value: TStringList); procedure SetResolution(const Value: Integer); procedure SetOpenDocumentAction(const Value: TPDFAction); procedure SetPDFACompatible(const Value: Boolean); procedure SetCMYKICCStream(const Value: TStream); procedure SetRGBICCStream(const Value: TStream); public /// <summary> /// Creates and initializes an instance of TPDFDocument /// </summary> /// <param name="AOwner"> /// Establishes the relationship of a component and its Owner /// </param> constructor Create(AOwner: TComponent); override; destructor Destroy; override; /// <summary> /// It stops the creation of PDF document. All data that are sent to a file will be lost /// </summary> procedure Abort; /// <summary> /// Adds new extanded graphical state to PDF document /// </summary> /// <returns> /// Returns new, just created, extended graphical state. /// </returns> function AppendExtGState: TPDFGState; /// <summary> /// Procedure adds a new form in the document /// </summary> /// <param name="OptionalContent"> /// Optional content, at start of which this form will be seen. If the value /// is nil, the form will be seen everywhere, where it will be depicted. /// </param> /// <returns> /// Returns created and initialized form /// </returns> function AppendForm(OptionalContent:TOptionalContent= nil): TPDFForm; /// <summary> /// Adds a new pattern to the PDF document. /// </summary> function AppendPattern: TPDFPattern; /// <summary> /// Adds new optional content to the PDF document /// </summary> /// <param name="LayerName"> /// Name of new optional content /// </param> /// <param name="StartVisible"> /// Specifies, whether this content will be visible when opening the document /// </param> /// <param name="CanExchange"> /// Specifies the possibility to change this content by the user /// </param> function AppendOptionalContent(LayerName:AnsiString;StartVisible:Boolean;CanExchange:Boolean=True):TOptionalContent; /// <summary> /// Begins a new PDF document. Adds the first page in the created document. /// </summary> procedure BeginDoc; /// <summary> /// Ends creation work of PDF document. Resets to the output stream all unsaved data. /// </summary> procedure EndDoc; /// <summary> /// Adds a new page in PDF document and transfers Canvas to this page. /// </summary> procedure NewPage; /// <summary> /// Adds the digital signature to the generated document. /// </summary> /// <param name="APFXStream"> /// Stream with PFX structure inside /// </param> /// <param name="Password"> /// Password to decode PFX of the document /// </param> procedure AppendDigitalSignatureKeys(APFXStream:TStream;Password:string);overload; /// <summary> /// Adds the digital signature to the generated document. /// </summary> /// <param name="APFXFile"> /// File name with PFX structure inside /// </param> /// <param name="Password"> /// Password to decode PFX of the document /// </param> procedure AppendDigitalSignatureKeys(APFXFile:string;Password:string);overload; /// <summary> /// Parameter that specifies the digital signature of the generated document /// </summary> /// <remarks> /// This parameter will be available only after valid request of AppendDigitalSignatureKeys /// </remarks> property DigitalSignature:TPDFSignature read FDigSignature; /// <summary> /// Defines whether Abort was performed after beginning of creation of PDF document. /// </summary> property Aborted: Boolean read FAborted; /// <summary> /// Acroforms manager. Necessary at creating new acroform controls /// </summary> property AcroForms: TPDFAcroForms read FAcroForms; /// <summary> /// Actions manager, which is used when creating all actions in object. /// </summary> property Actions: TPDFActions read FActions; /// <summary> /// Images manager, allowing to add new images to the document /// </summary> property Images: TPDFImages read GetImages; /// <summary> /// Names manager, allowing to add named objects, such as files, destinations, /// javascripts /// </summary> property Names: TPDFNames read FNames; /// <summary> /// outlines manager, allowing to manipulate this objects in the generated file /// </summary> property Outlines: TPDFOutlines read FOutlines; /// <summary> /// Standard TCanvas, which you can manipulate as standard HDC /// </summary> property Canvas: TCanvas read GetCanvas; /// <summary> /// The current page in the document, which can be manipulate with drawing /// </summary> property CurrentPage: TPDFPage read GetCurrentPage; /// <summary> /// Determines the index of the current page in the document. It starts from zero for the first page. /// </summary> property CurrentPageIndex: Integer read GetCurrentPageIndex write SetCurrentPageIndex; /// <summary> /// Defines a list of TTF fonts that will not be introduced into the document. /// </summary> property NonEmbeddedFonts: TStringList read GetNonEmbeddedFonts write SetNonEmbeddedFonts; /// <summary> /// If this property is set, then the output of the generated document is active in /// stream and not in a file. /// </summary> property OutputStream: TStream read FOutputStream write SetOutputStream; /// <summary> /// It provides direct access to all pages of the document /// </summary> /// <remarks> /// When you try to access directly to the pages that One Pass is set as true, /// an exception will be called /// </remarks> property Page[Index: Integer]: TPDFPage read GetPage; default; /// <summary> /// Number of created pages in the document. /// </summary> property PageCount: Integer read GetCount; /// <summary> /// Determines the index of the current page in the document. It starts with one for the first page. Is made /// for compatibility with TPrinter. /// </summary> property PageNumber: Integer read GetPageNumber; /// <summary> /// Determines whether the component is in the process of creating a new document. /// </summary> property Printing: Boolean read FPrinting; /// <summary> /// It determines the action to be performed when you open a document in PDF viewer. /// </summary> property OpenDocumentAction: TPDFAction write SetOpenDocumentAction; /// <summary> /// Specifies the stream from which to read CMYK ICC data during the creation of PDF / A compliant /// document. /// </summary> /// <remarks> /// If the stream is not set, and the document uses CMYK colors, the exception will be called. /// </remarks> property CMYKICCStream: TStream read FCMYKICCStream write SetCMYKICCStream; /// <summary> /// Specifies the stream from which to read RGB ICC data during the creation of PDF / A compliant /// document. /// </summary> /// <remarks> /// If the stream is not specified in the document, RGB color is used in the document /// standard RGB ICC file will be used /// </remarks> property RGBICCStream: TStream read FRGBICCStream write SetRGBICCStream; published /// <summary> /// It determines need to create a URL when you create a document and add it to the outputted page. /// </summary> property AutoCreateURL: Boolean read GetAutoCreateURL write SetAutoCreateURL; /// <summary> /// Specifies whether to open the generated PDF file after it is created in default PDF /// viewer /// </summary> property AutoLaunch: Boolean read FAutoLaunch write FAutoLaunch; /// <summary> /// Specifies whether to use compression for the content of the canvas in the PDF document. /// </summary> property Compression: TCompressionType read FCompression write SetCompression; /// <summary> /// Property defines information about a PDF document. /// </summary> property DocumentInfo: TPDFDocInfo read FDocumentInfo write SetDocumentInfo; /// <summary> /// Defines a list of parameters to be taken into account when parsing an EMF document. /// </summary> property EMFOptions: TPDFEMFParseOptions read GetEMFOptions; /// <summary> /// Name of created PDF document. If OutputStream specified, this value is ignored. /// </summary> property FileName: string read FFileName write SetFileName; /// <summary> /// Specifies the compression level for images to be stored in JPEG. /// </summary> property JPEGQuality: Integer read FJPEGQuality write SetJPEGQuality; /// <summary> /// Document creation in one pass. /// </summary> /// <remarks> /// This property is recommended when creating large documents. When newly created /// The contents of the canvas will be directly written to the output stream, while creating the next page. In connection with /// this can not be changed CurrentPageIndex. /// </remarks> property OnePass: Boolean read FOnePass write SetOnePass; /// <summary> /// It determines the layout of the page at the time of opening /// </summary> property PageLayout: TPageLayout read FPageLayout write FPageLayout; /// <summary> /// It determines how the document should be displayed at the opening of the document /// </summary> property PageMode: TPageMode read FPageMode write FPageMode; /// <summary> /// Specifies the resolution, which is used in the newly created pages. /// </summary> property Resolution: Integer read FResolution write SetResolution; /// <summary> /// It defines the properties associated with the document encryption. /// </summary> property Security: TPDFSecurityOptions read FSecurity write SetSecurity; /// <summary> /// It specifies the properties of PDF viewer at the opening of the document /// </summary> property ViewerPreferences: TViewerPreferences read FViewerPreferences write FViewerPreferences; /// <summary> /// Specifies whether to create a document that is compatible with PDF / A standard. /// </summary> property PDFACompatible: Boolean read FPDFACompatible write SetPDFACompatible; end; implementation uses llPDFResources, llPDFMisc, llPDFPFX, llPDFJBIG2, llPDFCrypt; { ********************************* TPDFDocument ********************************* } constructor TPDFDocument.Create(AOwner: TComponent); begin inherited Create ( AOwner ); FOutputStream := nil; FJPEGQuality := 80; FAborted := False; FPrinting := False; FOnePass := False; FACURL := True; FAutoLaunch := False; FPDFACompatible := False; FSecurity := TPDFSecurityOptions.Create; FEngine := TPDFEngine.Create; Resolution := 72; FEngine.Resolution := 72; Compression := ctFlate; FFonts := TPDFFonts.Create( FEngine ); FPages := TPDFPages.Create(Self, FEngine, FFonts); FImages := TPDFImages.Create(FEngine); FActions := TPDFActions.Create(FEngine, FPages); FOutlines := TPDFOutlines.Create(FEngine); FAcroForms := TPDFAcroForms.Create(FEngine,FFonts); FForms := TPDFListManager.Create(FEngine); FPatterns := TPDFListManager.Create(FEngine); FGStates := TPDFListManager.Create( FEngine); FNames := TPDFNames.Create(FEngine, FPages); FOptionalContents := TOptionalContents.Create( FEngine); FPages.Patterns := FPatterns; FPages.Images := FImages; FPages.Actions := FActions; FDocumentInfo := TPDFDocInfo.Create; FDocumentInfo.Creator := 'llPDFLib Application'; FDocumentInfo.Keywords := 'llPDFLib'; FDocumentInfo.FProducer := 'llPDFLib 6.x (http://www.sybrex.com)'; FDocumentInfo.Author := 'Windows User'; FDocumentInfo.Title := 'No Title'; FDocumentInfo.Subject := 'None'; FSecurity.CryptMetadata := True; FDocumentInfo.CreationDate := Now; FSecurity.State := ssNone; end; destructor TPDFDocument.Destroy; begin ClearAll; FNames.Free; FPatterns.Free; FPages.Free; FDocumentInfo.Free; FSecurity.Free; FFonts.Free; FImages.Free; FOutlines.Free; FForms.Free; FAcroForms.Free; FGStates.Free; FOptionalContents.Free; FEngine.Free; FActions.Free; inherited; end; procedure TPDFDocument.Abort; begin ClearAll; if FOutputStream = nil then DeleteFile ( FileName ); FAborted := True; FPrinting := False; end; function TPDFDocument.AppendPattern: TPDFPattern; begin Result := TPDFPattern.Create(FEngine,FFonts); FPatterns.Add(Result); end; function TPDFDocument.AppendExtGState: TPDFGState; begin Result := TPDFGState.Create(FEngine); FGStates.Add(Result); end; procedure TPDFDocument.BeginDoc; begin ClearAll; if FPrinting then raise EPDFException.Create ( SGenerationPDFFileInProgress ); FEngine.InitSecurity ( FSecurity.State, FSecurity.Permissions, FSecurity.UserPassword, FSecurity.OwnerPassword, AnsiString(FileName), FSecurity.CryptMetadata); if FOutputStream = nil then FStream := TFileStream.Create ( FileName, fmCreate ) else FStream := TMemoryStream.Create; FEngine.Stream := FStream; if FEngine.SecurityInfo.State >= ss128AES then Randomize; FPrinting := True; FAborted := False; FPages.Add; FImages.JPEGQuality := FJPEGQuality; FEngine.PDFACompatibile := FPDFACompatible; FEngine.RGBICCStream := FRGBICCStream; FEngine.CMYKICCStream := FCMYKICCStream; if FSecurity.State >= ss128AES then FEngine.SaveHeader( pdfver17) else if FSecurity.State = ss128RC4 then FEngine.SaveHeader( pdfver15) else FEngine.SaveHeader( pdfver14); end; procedure TPDFDocument.ClearAll; begin FEngine.ClearManager(FForms); FEngine.ClearManager(FPatterns); FEngine.ClearManager(FPages); FEngine.ClearManager(FImages); FEngine.ClearManager(FFonts); FEngine.ClearManager(FActions); FEngine.ClearManager(FOutlines); FEngine.ClearManager(FAcroForms); FEngine.ClearManager(FGStates); FEngine.ClearManager(FOptionalContents); FEngine.ClearManager(FNames); FDigSignature.Free; FDigSignature := nil; if FStream <> nil then begin FStream.Free; FStream := nil; end; FEngine.Reset; end; procedure TPDFDocument.EndDoc; begin try StoreDocument; except on Exception do begin Abort; raise; end; end; if FOutputStream <> nil then begin FStream.Position := 0; FOutputStream.CopyFrom ( FStream, FStream.Size ); end; ClearAll; FPrinting := False; FAborted := False; if ( FOutputStream = nil ) and ( AutoLaunch ) then try ShellExecute ( GetActiveWindow, 'open', PChar ( FFileName ), nil, nil, SW_NORMAL ); except end; end; function TPDFDocument.GetAutoCreateURL: Boolean; begin Result := FPages.AutoURLCreate; end; function TPDFDocument.GetCanvas: TCanvas; begin if not FPrinting then raise EPDFException.Create ( SGenerationPDFFileNotActivated ); Result := FPages.CurrentPage.Canvas; FPages.RequestCanvas; end; function TPDFDocument.GetCount: Integer; begin if not FPrinting then raise EPDFException.Create ( SGenerationPDFFileNotActivated ); Result := FPages.Count; end; function TPDFDocument.GetCurrentPage: TPDFPage; begin if not FPrinting then raise EPDFException.Create ( SGenerationPDFFileNotActivated ); Result := FPages.CurrentPage; end; function TPDFDocument.GetCurrentPageIndex: Integer; begin if not FPrinting then raise EPDFException.Create ( SGenerationPDFFileNotActivated ); Result := FPages.CurrentPageIndex; end; function TPDFDocument.GetEMFOptions: TPDFEMFParseOptions; begin Result := TPDFEMFParseOptions(FPages.EMFOptions); end; function TPDFDocument.GetImages: TPDFImages; begin if not FPrinting then raise EPDFException.Create ( SGenerationPDFFileNotActivated ); Result := FImages; end; function TPDFDocument.GetNonEmbeddedFonts: TStringList; begin Result := FFonts.NonEmbeddedFonts; end; function TPDFDocument.GetPage(Index: Integer): TPDFPage; begin if not FPrinting then raise EPDFException.Create ( SGenerationPDFFileNotActivated ); if FOnePass then raise EPDFException.Create ( SCannotAccessToPageInOnePassMode ); if ( Index < 0 ) or ( Index > FPages.Count - 1 ) then raise EPDFException.Create ( SOutOfRange ); Result := FPages [ Index ]; end; function TPDFDocument.GetPageNumber: Integer; begin if not FPrinting then raise EPDFException.Create ( SGenerationPDFFileNotActivated ); Result := FPages.CurrentPageIndex + 1; end; procedure TPDFDocument.NewPage; var I:Integer; begin if not FPrinting then raise EPDFException.Create ( SGenerationPDFFileNotActivated ); I := FPages.CurrentPageIndex; FPages.Add; if FOnePass then begin FPages.SaveIndex(i); end; end; procedure TPDFDocument.SaveCryptDictionary(ID: Integer); begin FEngine.StartObj ( ID ); FEngine.SaveToStream ( '/Filter /Standard' ); case FEngine.SecurityInfo.State of ss40RC4: begin FEngine.SaveToStream ( '/V 1' ); FEngine.SaveToStream ( '/R 2' ); end; ss128RC4: begin FEngine.SaveToStream ( '/V 2' ); FEngine.SaveToStream ( '/R 3' ); FEngine.SaveToStream ( '/Length 128' ); end; ss128AES: begin FEngine.SaveToStream ( '/V 4' ); FEngine.SaveToStream ( '/R 4' ); FEngine.SaveToStream ( '/Length 128' ); FEngine.SaveToStream ( '/CF<</StdCF<</CFM/AESV2/Length 16/AuthEvent/DocOpen>>>>/StmF/StdCF/StrF/StdCF' ); end; ss256AES: begin FEngine.SaveToStream ( '/V 5' ); FEngine.SaveToStream ( '/R 5' ); FEngine.SaveToStream ( '/Length 256' ); FEngine.SaveToStream ( '/CF<</StdCF<</CFM/AESV3/Length 32/AuthEvent/DocOpen>>>>/StmF/StdCF/StrF/StdCF' ); FEngine.SaveToStream ( '/OE (' + EscapeSpecialChar ( FEngine.SecurityInfo.OE ) + ')' ); FEngine.SaveToStream ( '/UE (' + EscapeSpecialChar ( FEngine.SecurityInfo.UE ) + ')' ); FEngine.SaveToStream ( '/Perms (' + EscapeSpecialChar ( FEngine.SecurityInfo.Perm ) + ')' ); end; end; FEngine.SaveToStream ( '/P ' + IStr ( FEngine.SecurityInfo.Permission ) ); FEngine.SaveToStream ( '/O (' + EscapeSpecialChar ( FEngine.SecurityInfo.Owner ) + ')' ); FEngine.SaveToStream ( '/U (' + EscapeSpecialChar ( FEngine.SecurityInfo.User ) + ')' ); if FEngine.SecurityInfo.State = ss256AES then begin end; FEngine.CloseObj; end; procedure TPDFDocument.SetAutoCreateURL(const Value: Boolean); begin FPages.AutoURLCreate := Value; end; procedure TPDFDocument.SetCurrentPageIndex(Index: Integer); begin if not FPrinting then raise EPDFException.Create ( SGenerationPDFFileNotActivated ); if FOnePass then raise EPDFException.Create ( SCannotChangePageInOnePassMode ); if (Index >= FPages.Count) or (Index < 0 ) then raise EPDFException.Create( SOutOfRange); FPages.SetCurrentPage( Index ); end; procedure TPDFDocument.SetDocumentInfo(const Value: TPDFDocInfo); begin FDocumentInfo.Creator := Value.Creator; FDocumentInfo.CreationDate := Value.CreationDate; FDocumentInfo.Author := Value.Author; FDocumentInfo.Title := Value.Title; FDocumentInfo.Subject := Value.Subject; FDocumentInfo.Keywords := Value.Keywords; end; procedure TPDFDocument.SetFileName(const Value: string); begin if FPrinting then raise EPDFException.Create ( SGenerationPDFFileInProgress ); FFileName := Value; end; procedure TPDFDocument.SetJPEGQuality(const Value: Integer); begin FJPEGQuality := Value; if FPrinting then FImages.JPEGQuality := FJPEGQuality; end; procedure TPDFDocument.SetOnePass(const Value: Boolean); begin if FPrinting then raise EPDFException.Create ( SGenerationPDFFileInProgress ); FOnePass := Value; end; procedure TPDFDocument.SetOutputStream(const Value: TStream); begin if FPrinting then raise EPDFException.Create ( SGenerationPDFFileInProgress ); FOutputStream := Value; end; procedure TPDFDocument.SetSecurity(const Value: TPDFSecurityOptions); begin if FPrinting then raise EPDFException.Create ( SGenerationPDFFileInProgress ); if FPDFACompatible and ( Value.State <> ssNone ) then raise EPDFException.Create( SPDFACompatible ); FSecurity.State := Value.State; FSecurity.OwnerPassword := Value.OwnerPassword; FSecurity.UserPassword := Value.UserPassword; FSecurity.Permissions := Value.Permissions; FSecurity.CryptMetadata := Value.CryptMetadata; end; procedure TPDFDocument.StoreDocument; var i: Integer; CatalogID, InfoID, EncryptID, MetaID: Integer; begin InfoID := FEngine.GetNextID; FDocumentInfo.Save(InfoID, FEngine); FPages.CloseCanvas; if not FOnePass then begin for i := 0 to FPages.Count - 1 do FPages.SaveIndex(i); end else FPages.SaveIndex(FPages.Count - 1); if FEngine.SecurityInfo.State <> ssNone then begin EncryptID := FEngine.GetNextID; SaveCryptDictionary( EncryptID); end else begin EncryptID := 0; end; FEngine.SaveManager(FPages); FEngine.SaveManager(FFonts); FEngine.SaveManager(FOutlines); FEngine.SaveManager(FNames); FEngine.SaveManager(FAcroForms); FEngine.SaveManager(FActions); FEngine.SaveManager(FGStates); FEngine.SaveManager(FOptionalContents); FEngine.SaveManager(FForms); FEngine.SaveManager(FImages); FEngine.SaveManager(FPatterns); FEngine.SavePDFAFeatures; MetaID := FEngine.CreateMetadata(FDocumentInfo, Security.CryptMetadata); CatalogID := FEngine.GetNextID; FEngine.StartObj( CatalogID); FEngine.SaveToStream ( '/Type /Catalog' ); if Security.State = ss256AES then FEngine.SaveToStream ( '/Extensions<</ADBE<</BaseVersion/1.7/ExtensionLevel 3>>>>'); FEngine.SaveToStream ( '/Pages ' + FPages.RefID ); case PageLayout of plSinglePage: FEngine.SaveToStream ( '/PageLayout /SinglePage' ); plOneColumn: FEngine.SaveToStream ( '/PageLayout /OneColumn' ); plTwoColumnLeft: FEngine.SaveToStream ( '/Pagelayout /TwoColumnLeft' ); plTwoColumnRight: FEngine.SaveToStream ( '/PageLayout /TwoColumnRight' ); end; if ViewerPreferences <> [ ] then begin FEngine.SaveToStream ( '/ViewerPreferences <<' ); if vpHideToolBar in ViewerPreferences then FEngine.SaveToStream ( '/HideToolbar true' ); if vpHideMenuBar in ViewerPreferences then FEngine.SaveToStream ( '/HideMenubar true' ); if vpHideWindowUI in ViewerPreferences then FEngine.SaveToStream ( '/HideWindowUI true' ); if vpFitWindow in ViewerPreferences then FEngine.SaveToStream ( '/FitWindow true' ); if vpCenterWindow in ViewerPreferences then FEngine.SaveToStream ( '/CenterWindow true' ); FEngine.SaveToStream ( '>>' ); end; case PageMode of pmUseNone: FEngine.SaveToStream ( '/PageMode /UseNone' ); pmUseOutlines: FEngine.SaveToStream ( '/PageMode /UseOutlines' ); pmUseThumbs: FEngine.SaveToStream ( '/PageMode /UseThumbs' ); pmFullScreen: FEngine.SaveToStream ( '/PageMode /FullScreen' ); end; if FOutlines.Count <> 0 then FEngine.SaveToStream ( '/Outlines ' + FOutlines.RefID ); if FNames.Count <> 0 then FEngine.SaveToStream ( '/Names ' + FNames.RefID ); if FAcroForms.Count >0 then FEngine.SaveToStream ( '/AcroForm ' + FAcroForms.RefID ); if FOptionalContents.Count >0 then FEngine.SaveToStream ( '/OCProperties ' + FOptionalContents.RefID ); if FOpenDocumentAction <> nil then FEngine.SaveToStream ( '/OpenAction ' + FOpenDocumentAction.RefID); FEngine.SaveToStream('/Metadata '+GetRef ( MetaID )); FEngine.CloseObj; FEngine.SaveXREFAndTrailer( CatalogID, InfoID, EncryptID, FEngine.FileID); if Assigned(FDigSignature) then FEngine.SaveAdditional(FDigSignature); end; procedure TPDFDocument.SetCompression(const Value: TCompressionType); begin FCompression := Value; FEngine.Compression := Value; end; procedure TPDFDocument.SetNonEmbeddedFonts(const Value: TStringList); begin FFonts.NonEmbeddedFonts :=Value; end; procedure TPDFDocument.SetResolution(const Value: Integer); begin FResolution := Value; FEngine.Resolution := Value; end; procedure TPDFDocument.SetOpenDocumentAction(const Value: TPDFAction); begin if not FPrinting then raise EPDFException.Create ( SGenerationPDFFileNotActivated ); FOpenDocumentAction := Value end; procedure TPDFDocument.SetPDFACompatible(const Value: Boolean); begin if FPrinting then raise EPDFException.Create ( SGenerationPDFFileInProgress ); if FSecurity.State <> ssNone then raise EPDFException.Create ( SSecutityCompatible ); FPDFACompatible := Value; FEngine.PDFACompatibile := Value; end; procedure TPDFDocument.SetCMYKICCStream(const Value: TStream); begin if FPrinting then raise EPDFException.Create ( SGenerationPDFFileInProgress ); FCMYKICCStream := Value; FEngine.CMYKICCStream := Value; end; procedure TPDFDocument.SetRGBICCStream(const Value: TStream); begin if FPrinting then raise EPDFException.Create ( SGenerationPDFFileInProgress ); FRGBICCStream := Value; FEngine.RGBICCStream := Value; end; function TPDFDocument.AppendForm( OptionalContent: TOptionalContent): TPDFForm; begin Result := TPDFForm.Create(FEngine,FFonts, OptionalContent); FForms.Add(Result); end; function TPDFDocument.AppendOptionalContent(LayerName: AnsiString; StartVisible, CanExchange: Boolean): TOptionalContent; begin Result := TOptionalContent.Create(FEngine,LayerName,StartVisible,CanExchange); FOptionalContents.Add(Result); end; { TPDFDocInfo } procedure TPDFDocInfo.Save(ID: Integer;PDFEngine: TPDFEngine); begin PDFEngine.StartObj( ID ); {$ifdef UNICODE} PDFEngine.SaveToStream ( '/Creator ' + CryptString( PDFEngine.SecurityInfo, UnicodeChar(FCreator), ID ) ); PDFEngine.SaveToStream ( '/CreationDate ' + CryptString ( PDFEngine.SecurityInfo,'D:' + AnsiString(FormatDateTime ( 'yyyymmddhhnnss', FCreationDate ))+'Z' , ID) ); PDFEngine.SaveToStream ( '/ModDate ' + CryptString ( PDFEngine.SecurityInfo,'D:' + AnsiString(FormatDateTime ( 'yyyymmddhhnnss', Now ))+'Z' , ID) ); PDFEngine.SaveToStream ( '/Producer ' + CryptString (PDFEngine.SecurityInfo, UnicodeChar(FProducer) , ID) ); PDFEngine.SaveToStream ( '/Author ' + CryptString ( PDFEngine.SecurityInfo,UnicodeChar(FAuthor) , ID) ); PDFEngine.SaveToStream ( '/Title ' + CryptString ( PDFEngine.SecurityInfo,UnicodeChar(FTitle) , ID) ); PDFEngine.SaveToStream ( '/Subject ' + CryptString (PDFEngine.SecurityInfo, UnicodeChar(FSubject) , ID) ); PDFEngine.SaveToStream ( '/Keywords ' + CryptString (PDFEngine.SecurityInfo, UnicodeChar(FKeywords) , ID) ); {$else} PDFEngine.SaveToStream ( '/Creator ' + CryptString( PDFEngine.SecurityInfo, FCreator, ID ) ); PDFEngine.SaveToStream ( '/CreationDate ' + CryptString ( PDFEngine.SecurityInfo,'D:' + FormatDateTime ( 'yyyymmddhhnnss', FCreationDate )+'Z' , ID) ); PDFEngine.SaveToStream ( '/ModDate ' + CryptString ( PDFEngine.SecurityInfo,'D:' + AnsiString(FormatDateTime ( 'yyyymmddhhnnss', Now ))+'Z' , ID) ); PDFEngine.SaveToStream ( '/Producer ' + CryptString (PDFEngine.SecurityInfo, FProducer , ID) ); PDFEngine.SaveToStream ( '/Author ' + CryptString ( PDFEngine.SecurityInfo,FAuthor , ID) ); PDFEngine.SaveToStream ( '/Title ' + CryptString ( PDFEngine.SecurityInfo,FTitle , ID) ); PDFEngine.SaveToStream ( '/Subject ' + CryptString (PDFEngine.SecurityInfo, FSubject , ID) ); PDFEngine.SaveToStream ( '/Keywords ' + CryptString (PDFEngine.SecurityInfo, FKeywords , ID) ); {$endif} PDFEngine.CloseObj; end; procedure TPDFDocument.AppendDigitalSignatureKeys(APFXStream: TStream; Password: string); var PFX: TPKCS12Document; begin if not FPrinting then raise EPDFException.Create ( SGenerationPDFFileNotActivated ); if FDigSignature <> nil then raise EPDFException.Create( SOnlyOneDigitalSignatureAvaiable); PFX := TPKCS12Document.Create; try PFX.LoadFromStream(APFXStream); {$IFDEF UNICODE} PFX.CheckPassword(UTF8encode(Password)); {$else} PFX.CheckPassword(Password); {$ENDIF} PFX.Parse; FDigSignature := TPDFSignature.Create(Self,PFX); PFX := nil; finally PFX.Free; end; end; procedure TPDFDocument.AppendDigitalSignatureKeys(APFXFile, Password: string); var FS: TFileStream; begin FS := TFileStream.Create(APFXFile,fmOpenRead); try AppendDigitalSignatureKeys(FS,Password); finally FS.Free; end; end; end.
unit tariff_test; interface uses System, VM_System, VM_SysUtils, VM_DateUtils; implementation type TCZonePeriod = packed record BeginDate: TDate; EndDate: TDate; ZoneInDate: TDateTime; LastUseDate: TDateTime; MAC: UInt32; end; TCWallet = packed record BeginDate: TDateTime; EndDate: TDateTime; RFU: array[0..7] of UInt8; MainWallet: Int32; BonusWallet: Int32; LastUseDate: TDateTime; MAC: UInt32; end; TCalcResult = (CalcSuccess, CalcExpireDate, CalcNotEnoughMoney); var Hours: Int32; SDT: TDateTime; TotalSum: Int32; function Calc(const CZonePeriod: TCZonePeriod; var CWallet: TCWallet; TRDate: TDateTime; BasePrice: Int32): TCalcResult; begin SDT := CZonePeriod.ZoneInDate; Hours := HoursBetween(SDT, TRDate); if Hours <= 8 then TotalSum := Hours*BasePrice else TotalSum := (8*BasePrice) + (Hours - 8)*(BasePrice div 2); if CWallet.MainWallet >= TotalSum then begin CWallet.MainWallet := CWallet.MainWallet - TotalSum; CWallet.LastUseDate := TRDate; Result := CalcSuccess; end else Result := CalcNotEnoughMoney; end; var Z: TCZonePeriod; W: TCWallet; R: TCalcResult; var DT, NDT: TDateTime; procedure Test; begin DT := Now(); NDT := IncHour(DT, 13); Z.ZoneInDate := NDT; W.MainWallet := 100; R := Calc(Z, W, DT, 10); end; initialization Test(); finalization Assert(R = CalcNotEnoughMoney); end.
{**********************************************************************} {* Иллюстрация к книге "OpenGL в проектах Delphi" *} {* Краснов М.В. softgl@chat.ru *} {**********************************************************************} unit frmMain; interface uses Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Controls, SysUtils, Dialogs, OpenGL; type TfrmGL = class(TForm) procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private DC: HDC; hrc: HGLRC; Torus : GLint; procedure MakeList; procedure SetDCPixelFormat; protected procedure WMPaint(var Msg: TWMPaint); message WM_PAINT; end; var frmGL: TfrmGL; Angle : GLint = 0; const WIN_WIDTH = 200; WIN_HEIGHT = 200; implementation uses DGLUT; {$R *.DFM} {======================================================================= Подготовка списка} procedure TfrmGL.MakeList; begin Torus := glGenLists(1); glNewList(Torus, GL_COMPILE); glutSolidTorus(5.0, 15.0, 16, 32); glEndList; end; {======================================================================= Рисование картинки} procedure TfrmGL.WMPaint(var Msg: TWMPaint); var ps : TPaintStruct; Zbuf : Array [0..WIN_WIDTH - 1, 0..WIN_HEIGHT - 1] of GLfloat; begin BeginPaint(Handle, ps); glViewport(0,0,round(ClientWidth/2), ClientHeight); glScissor(0,0,round(ClientWidth/2), ClientHeight); glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity; gluPerspective(60.0, ClientWidth / ClientHeight, 5.0, 70.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity; glPushMatrix; gluLookAt(25.0,25.0,50.0,25.0,25.0,20.0,0.0,1.0,0.0); glTranslatef(25.0,25.0,10.0); glRotatef (Angle, 1.0, 0.0, 0.0); glCallList(Torus); glReadPixels(0, 0, WIN_WIDTH, WIN_HEIGHT, GL_DEPTH_COMPONENT, GL_FLOAT, @Zbuf); glPopMatrix; // View 2 glViewport(round(ClientWidth/2) + 1, 0, round(ClientWidth/2), ClientHeight); glScissor(round(ClientWidth/2) + 1, 0, round(ClientWidth/2), ClientHeight); glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); glPushMatrix; glMatrixMode(GL_PROJECTION); glLoadIdentity; glRasterPos2i (-1, -1); glDrawPixels(WIN_WIDTH, WIN_HEIGHT, GL_LUMINANCE, GL_FLOAT, @Zbuf); glPopMatrix; SwapBuffers(DC); EndPaint(Handle, ps); Angle := (Angle + 2) mod 360; InvalidateRect(Handle, nil, False); end; {======================================================================= Создание окна} procedure TfrmGL.FormCreate(Sender: TObject); const amb_dif : Array [0..3] of GLfloat = (0.9,0.5,1.0,1.0); spec : Array [0..3] of GLfloat = (1.0,1.0,1.0,1.0); begin DC := GetDC(Handle); SetDCPixelFormat; hrc := wglCreateContext(DC); wglMakeCurrent(DC, hrc); glMaterialfv(GL_FRONT,GL_AMBIENT_AND_DIFFUSE, @amb_dif); glMaterialfv(GL_FRONT,GL_SPECULAR,@spec); glMaterialf(GL_FRONT,GL_SHININESS,50.0); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); glEnable(GL_SCISSOR_TEST); glClearColor(0.5, 0.7, 1.0, 1.0); MakeList; end; {======================================================================= Обработка нажатия клавиши} procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_ESCAPE then Close; end; {======================================================================= Устанавливаем формат пикселей} procedure TfrmGL.SetDCPixelFormat; var nPixelFormat: Integer; pfd: TPixelFormatDescriptor; begin FillChar(pfd, SizeOf(pfd), 0); pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; nPixelFormat := ChoosePixelFormat(DC, @pfd); SetPixelFormat(DC, nPixelFormat, @pfd); end; {======================================================================= Изменение размеров окна} procedure TfrmGL.FormResize(Sender: TObject); begin InvalidateRect(Handle, nil, False); end; {======================================================================= Конец работы программы} procedure TfrmGL.FormDestroy(Sender: TObject); begin glDeleteLists (Torus, 1); wglMakeCurrent(0, 0); wglDeleteContext(hrc); ReleaseDC(Handle, DC); DeleteDC (DC); end; end.
unit GrievanceLawyerCodeDialogUnit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, wwdblook, Db, DBTables; type TGrievanceLawyerCodeDialog = class(TForm) OKButton: TBitBtn; CancelButton: TBitBtn; Label1: TLabel; Label2: TLabel; LawyerCodeTable: TTable; LawyerCodeLookupCombo: TwwDBLookupCombo; procedure OKButtonClick(Sender: TObject); procedure LawyerCodeLookupComboNotInList(Sender: TObject; LookupTable: TDataSet; NewValue: String; var Accept: Boolean); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } LawyerCode : String; end; var GrievanceLawyerCodeDialog: TGrievanceLawyerCodeDialog; implementation {$R *.DFM} {===============================================================} Procedure TGrievanceLawyerCodeDialog.FormCreate(Sender: TObject); begin try LawyerCodeTable.Open; except MessageDlg('Error opening lawyer code table.', mtError, [mbOK], 0); end; end; {FormCreate} {===============================================================} Procedure TGrievanceLawyerCodeDialog.OKButtonClick(Sender: TObject); begin LawyerCode := LawyerCodeLookupCombo.Text; end; {===============================================================} Procedure TGrievanceLawyerCodeDialog.LawyerCodeLookupComboNotInList( Sender: TObject; LookupTable: TDataSet; NewValue: String; var Accept: Boolean); begin If (NewValue = '') then Accept := True; end; {LawyerCodeLookupComboNotInList} end.
//------------------------------------------ // TASK 1 GLOBAL WARMING //------------------------------------------ Program GlobalWarming; TYPE OneDArray = Array of LongInt; // note: LongInt is 32 bits. //------------------------------------------ // Reading the input from standard output //------------------------------------------ PROCEDURE ReadInput ( Var Size : LongInt; Var H : OneDArray ); Var i :LongInt; begin Readln (Size); SetLength (H, Size); For i:=0 to (Size-1) DO Readln ( H[i] ); end; //------------------------------------------ // Main routine //------------------------------------------ FUNCTION GW ( Size: LongInt; // Size of input array Var H: Array of LongInt // The input sequence, indices start from 0. ): LongInt; begin // fill in your program here GW :=0; end; Var Size: LongInt; H : Array of LongInt; begin ReadInput ( Size, H ); Writeln ( GW( Size, H) ); end.
(***********************************************************) (* xPLRFX *) (* part of Digital Home Server project *) (* http://www.digitalhomeserver.net *) (* info@digitalhomeserver.net *) (***********************************************************) unit uxPLRFX_0x55; interface Uses uxPLRFXConst, u_xPL_Message, u_xpl_common, uxPLRFXMessages; procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages); implementation Uses SysUtils; (* Type $55 - Rain sensors Buffer[0] = packetlength = $0B; Buffer[1] = packettype Buffer[2] = subtype Buffer[3] = seqnbr Buffer[4] = id1 Buffer[5] = id2 Buffer[6] = rainratehigh Buffer[7] = rainratelow Buffer[8] = raintotal1 // high byte Buffer[9] = raintotal2 Buffer[10] = raintotal3 // low byte Buffer[11] = battery_level:4/rssi:4 Test strings : 0B550217B6000000004D3C69 xPL Schema sensor.basic { device=(rain1-rain6) 0x<hex sensor id> type=rainrate current=<mm/hr> unit=mmh } sensor.basic { device=(rain1-rain6) 0x<hex sensor id> type=raintotal current=<mm> unit=mm } sensor.basic { device=(rain1-rain6) 0x<hex sensor id> type=battery current=0-100 } *) const // Type RAIN = $55; // Subtype RAIN1 = $01; RAIN2 = $02; RAIN3 = $03; RAIN4 = $04; RAIN5 = $05; RAIN6 = $06; var SubTypeArray : array[1..6] of TRFXSubTypeRec = ((SubType : RAIN1; SubTypeString : 'rain1'), (SubType : RAIN2; SubTypeString : 'rain2'), (SubType : RAIN3; SubTypeString : 'rain3'), (SubType : RAIN4; SubTypeString : 'rain4'), (SubType : RAIN5; SubTypeString : 'rain5'), (SubType : RAIN6; SubTypeString : 'rain6')); procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages); var DeviceID : String; SubType : Byte; RainRate : Integer; RainTotal : Extended; BatteryLevel : Integer; xPLMessage : TxPLMessage; begin SubType := Buffer[2]; DeviceID := GetSubTypeString(SubType,SubTypeArray)+IntToHex(Buffer[4],2)+IntToHex(Buffer[5],2); RainRate := (Buffer[6] shl 8) + Buffer[7]; if SubType = RAIN2 then RainRate := RainRate div 100; if SubType <> RAIN6 then RainTotal := ((Buffer[8] shl 16) + (Buffer[9] shl 8) + Buffer[10]) / 10 else ; // TO CHECK : how does this flipcounter work ? if (Buffer[11] and $0F) = 0 then // zero out rssi BatteryLevel := 0 else BatteryLevel := 100; // Create sensor.basic messages xPLMessage := TxPLMessage.Create(nil); xPLMessage.schema.RawxPL := 'sensor.basic'; xPLMessage.MessageType := trig; xPLMessage.source.RawxPL := XPLSOURCE; xPLMessage.target.IsGeneric := True; xPLMessage.Body.AddKeyValue('device='+DeviceID); xPLMessage.Body.AddKeyValue('current='+IntToStr(RainRate)); xPLMessage.Body.AddKeyValue('units=mmh'); xPLMessage.Body.AddKeyValue('type=rainrate'); xPLMessages.Add(xPLMessage.RawXPL); xPLMessage.Free; xPLMessage := TxPLMessage.Create(nil); xPLMessage.schema.RawxPL := 'sensor.basic'; xPLMessage.MessageType := trig; xPLMessage.source.RawxPL := XPLSOURCE; xPLMessage.target.IsGeneric := True; xPLMessage.Body.AddKeyValue('device='+DeviceID); xPLMessage.Body.AddKeyValue('current='+FloatToStr(RainTotal)); xPLMessage.Body.AddKeyValue('units=mm'); xPLMessage.Body.AddKeyValue('type=raintotal'); xPLMessages.Add(xPLMessage.RawXPL); xPLMessage.Free; xPLMessage := TxPLMessage.Create(nil); xPLMessage.schema.RawxPL := 'sensor.basic'; xPLMessage.MessageType := trig; xPLMessage.source.RawxPL := XPLSOURCE; xPLMessage.target.IsGeneric := True; xPLMessage.Body.AddKeyValue('device='+DeviceID); xPLMessage.Body.AddKeyValue('current='+IntToStr(BatteryLevel)); xPLMessage.Body.AddKeyValue('type=battery'); xPLMessages.Add(xPLMessage.RawXPL); xPLMessage.Free; end; end.
(************************************************************************* Cephes Math Library Release 2.8: June, 2000 Copyright by Stephen L. Moshier Contributors: * Sergey Bochkanov (ALGLIB project). Translation from C to pseudocode. See subroutines comments for additional copyrights. >>> SOURCE LICENSE >>> 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 (www.fsf.org); 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. A copy of the GNU General Public License is available at http://www.fsf.org/licensing/licenses >>> END OF LICENSE >>> *************************************************************************) unit gammafunc; interface uses Math, Sysutils, Ap; function Gamma(x : AlglibFloat):AlglibFloat; function LnGamma(x : AlglibFloat; var SgnGam : AlglibFloat):AlglibFloat; implementation function GammaStirF(X : AlglibFloat):AlglibFloat;forward; (************************************************************************* Gamma function Input parameters: X - argument Domain: 0 < X < 171.6 -170 < X < 0, X is not an integer. Relative error: arithmetic domain # trials peak rms IEEE -170,-33 20000 2.3e-15 3.3e-16 IEEE -33, 33 20000 9.4e-16 2.2e-16 IEEE 33, 171.6 20000 2.3e-15 3.2e-16 Cephes Math Library Release 2.8: June, 2000 Original copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier Translated to AlgoPascal by Bochkanov Sergey (2005, 2006, 2007). *************************************************************************) function Gamma(x : AlglibFloat):AlglibFloat; var p : AlglibFloat; PP : AlglibFloat; q : AlglibFloat; QQ : AlglibFloat; z : AlglibFloat; i : AlglibInteger; SgnGam : AlglibFloat; begin SgnGam := 1; q := AbsReal(x); if AP_FP_Greater(q,33.0) then begin if AP_FP_Less(x,0.0) then begin p := floor(q); i := Round(p); if i mod 2=0 then begin SgnGam := -1; end; z := q-p; if AP_FP_Greater(z,0.5) then begin p := p+1; z := q-p; end; z := q*Sin(Pi*z); z := AbsReal(z); z := Pi/(z*GammaStirF(q)); end else begin z := GammaStirF(x); end; Result := SgnGam*z; Exit; end; z := 1; while AP_FP_Greater_Eq(x,3) do begin x := x-1; z := z*x; end; while AP_FP_Less(x,0) do begin if AP_FP_Greater(x,-0.000000001) then begin Result := z/((1+0.5772156649015329*x)*x); Exit; end; z := z/x; x := x+1; end; while AP_FP_Less(x,2) do begin if AP_FP_Less(x,0.000000001) then begin Result := z/((1+0.5772156649015329*x)*x); Exit; end; z := z/x; x := x+1.0; end; if AP_FP_Eq(x,2) then begin Result := z; Exit; end; x := x-2.0; PP := 1.60119522476751861407E-4; PP := 1.19135147006586384913E-3+X*PP; PP := 1.04213797561761569935E-2+X*PP; PP := 4.76367800457137231464E-2+X*PP; PP := 2.07448227648435975150E-1+X*PP; PP := 4.94214826801497100753E-1+X*PP; PP := 9.99999999999999996796E-1+X*PP; QQ := -2.31581873324120129819E-5; QQ := 5.39605580493303397842E-4+X*QQ; QQ := -4.45641913851797240494E-3+X*QQ; QQ := 1.18139785222060435552E-2+X*QQ; QQ := 3.58236398605498653373E-2+X*QQ; QQ := -2.34591795718243348568E-1+X*QQ; QQ := 7.14304917030273074085E-2+X*QQ; QQ := 1.00000000000000000320+X*QQ; Result := z*PP/QQ; Exit; end; (************************************************************************* Natural logarithm of gamma function Input parameters: X - argument Result: logarithm of the absolute value of the Gamma(X). Output parameters: SgnGam - sign(Gamma(X)) Domain: 0 < X < 2.55e305 -2.55e305 < X < 0, X is not an integer. ACCURACY: arithmetic domain # trials peak rms IEEE 0, 3 28000 5.4e-16 1.1e-16 IEEE 2.718, 2.556e305 40000 3.5e-16 8.3e-17 The error criterion was relative when the function magnitude was greater than one but absolute when it was less than one. The following test used the relative error criterion, though at certain points the relative error could be much higher than indicated. IEEE -200, -4 10000 4.8e-16 1.3e-16 Cephes Math Library Release 2.8: June, 2000 Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier Translated to AlgoPascal by Bochkanov Sergey (2005, 2006, 2007). *************************************************************************) function LnGamma(x : AlglibFloat; var SgnGam : AlglibFloat):AlglibFloat; var A : AlglibFloat; B : AlglibFloat; C : AlglibFloat; p : AlglibFloat; q : AlglibFloat; u : AlglibFloat; w : AlglibFloat; z : AlglibFloat; i : AlglibInteger; LogPi : AlglibFloat; LS2PI : AlglibFloat; Tmp : AlglibFloat; begin SgnGam := 1; LogPi := 1.14472988584940017414; LS2PI := 0.91893853320467274178; if AP_FP_Less(x,-34.0) then begin q := -x; w := LnGamma(q, Tmp); p := floor(q); i := Round(p); if i mod 2=0 then begin SgnGam := -1; end else begin SgnGam := 1; end; z := q-p; if AP_FP_Greater(z,0.5) then begin p := p+1; z := p-q; end; z := q*Sin(Pi*z); Result := LogPi-Ln(z)-w; Exit; end; if AP_FP_Less(x,13) then begin z := 1; p := 0; u := x; while AP_FP_Greater_Eq(u,3) do begin p := p-1; u := x+p; z := z*u; end; while AP_FP_Less(u,2) do begin z := z/u; p := p+1; u := x+p; end; if AP_FP_Less(z,0) then begin sgngam := -1; z := -z; end else begin sgngam := 1; end; if AP_FP_Eq(u,2) then begin Result := Ln(z); Exit; end; p := p-2; x := x+p; B := -1378.25152569120859100; B := -38801.6315134637840924+X*B; B := -331612.992738871184744+X*B; B := -1162370.97492762307383+X*B; B := -1721737.00820839662146+X*B; B := -853555.664245765465627+X*B; C := 1; C := -351.815701436523470549+X*C; C := -17064.2106651881159223+X*C; C := -220528.590553854454839+X*C; C := -1139334.44367982507207+X*C; C := -2532523.07177582951285+X*C; C := -2018891.41433532773231+X*C; p := x*B/C; Result := Ln(z)+p; Exit; end; q := (x-0.5)*Ln(x)-x+LS2PI; if AP_FP_Greater(x,100000000) then begin Result := q; Exit; end; p := 1/(x*x); if AP_FP_Greater_Eq(x,1000.0) then begin q := q+((7.9365079365079365079365*0.0001*p-2.7777777777777777777778*0.001)*p+0.0833333333333333333333)/x; end else begin A := 8.11614167470508450300*0.0001; A := -5.95061904284301438324*0.0001+p*A; A := 7.93650340457716943945*0.0001+p*A; A := -2.77777777730099687205*0.001+p*A; A := 8.33333333333331927722*0.01+p*A; q := q+A/x; end; Result := q; end; function GammaStirF(X : AlglibFloat):AlglibFloat; var y : AlglibFloat; w : AlglibFloat; v : AlglibFloat; Stir : AlglibFloat; begin w := 1/x; Stir := 7.87311395793093628397E-4; Stir := -2.29549961613378126380E-4+w*Stir; Stir := -2.68132617805781232825E-3+w*Stir; Stir := 3.47222221605458667310E-3+w*Stir; Stir := 8.33333333333482257126E-2+w*Stir; w := 1+w*Stir; y := Exp(x); if AP_FP_Greater(x,143.01608) then begin v := Power(x, 0.5*x-0.25); y := v*(v/y); end else begin y := Power(x, x-0.5)/y; end; Result := 2.50662827463100050242*y*w; end; end.
unit inc_1; interface implementation var i8: int8; u8: uint8; i16: int16; u16: uint16; i32: int32; u32: uint32; i64: int64; u64: uint64; procedure Init; begin i8 := 0; u8 := 0; i16 := 0; u16 := 0; i32 := 0; u32 := 0; i64 := 0; u64 := 0; end; procedure Test1; begin inc(i8); inc(u8); inc(i16); inc(u16); inc(i32); inc(u32); inc(i64); inc(u64); end; procedure Test2; begin inc(i8, 0); inc(u8, 1); inc(i16, 2); inc(u16, 3); inc(i32, 4); inc(u32, 5); inc(i64, 6); inc(u64, 7); end; procedure Test3; var D: Int32; begin D := 10; inc(i8, D); inc(u8, D); inc(i16, D); inc(u16, D); inc(i32, D); inc(u32, D); inc(i64, D); inc(u64, D); end; initialization Init(); Test1(); Test2(); Test3(); finalization Assert(i8 = 11); Assert(u8 = 12); Assert(i16 = 13); Assert(u16 = 14); Assert(i32 = 15); Assert(u32 = 16); Assert(i64 = 17); Assert(u64 = 18); end.
{******************************************} { TeeChart } { Scroll Bars Example } { Copyright (c) 1995-2001 by David Berneda } { All Rights Reserved } {******************************************} unit uscrollb; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Teengine, Series, ExtCtrls, Chart, TeeProcs; type TScrollBarForm = class(TForm) Chart1: TChart; LineSeries1: TLineSeries; ScrollBar2: TScrollBar; ScrollBar1: TScrollBar; procedure ScrollBar1Change(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ScrollBar2Change(Sender: TObject); procedure Chart1Scroll(Sender: TObject); procedure Chart1Zoom(Sender: TObject); procedure Chart1UndoZoom(Sender: TObject); procedure Chart1Resize(Sender: TObject); private { Private declarations } public { Public declarations } ChangingBars:Boolean; Procedure CalcScrollBarPos; end; implementation {$R *.dfm} procedure TScrollBarForm.ScrollBar1Change(Sender: TObject); var Difer:Double; begin if not ChangingBars then With Chart1.BottomAxis do Begin Difer:=Maximum-Minimum; Maximum:=Chart1.MaxXValue(Chart1.BottomAxis)-ScrollBar1.Position*Difer/100.0; Minimum:=Maximum-Difer; end; end; procedure TScrollBarForm.FormCreate(Sender: TObject); begin LineSeries1.FillSampleValues(1000); Chart1.ZoomPercent(115); CalcScrollBarPos; end; procedure TScrollBarForm.ScrollBar2Change(Sender: TObject); Var Difer:Double; begin if not ChangingBars then With Chart1.LeftAxis do Begin Difer:=Maximum-Minimum; Minimum:=Chart1.MinYValue(Chart1.LeftAxis)+ScrollBar2.Position*Difer/100.0; Maximum:=Minimum+Difer; end; end; Procedure TScrollBarForm.CalcScrollBarPos; Var Difer:Double; Begin ChangingBars:=True; With Chart1 do Begin if BottomAxis.Automatic then ScrollBar1.Enabled:=False else Begin ScrollBar1.Enabled:=True; Difer:=MaxXValue(BottomAxis)-MinXValue(BottomAxis); if Difer>0 then ScrollBar1.Position:= Round(100.0*(BottomAxis.Minimum-MinXValue(BottomAxis))/Difer); end; if LeftAxis.Automatic then ScrollBar2.Enabled:=False else Begin ScrollBar2.Enabled:=True; Difer:=MaxYValue(LeftAxis)-MinYValue(LeftAxis); if Difer>0 then ScrollBar2.Position:= Round(100.0*(LeftAxis.Minimum-MinYValue(LeftAxis))/Difer); end; end; ChangingBars:=False; End; procedure TScrollBarForm.Chart1Scroll(Sender: TObject); begin CalcScrollBarPos; end; procedure TScrollBarForm.Chart1Zoom(Sender: TObject); begin CalcScrollBarPos; end; procedure TScrollBarForm.Chart1UndoZoom(Sender: TObject); begin CalcScrollBarPos; end; procedure TScrollBarForm.Chart1Resize(Sender: TObject); begin ScrollBar1.Left:=0; ScrollBar1.Top:=Chart1.Height-ScrollBar1.Height; ScrollBar1.Width:=Chart1.Width; ScrollBar2.Left:=Chart1.Width-ScrollBar2.Width; ScrollBar2.Top:=0; ScrollBar2.Height:=Chart1.Height; end; end.
{*********************************************} { TeeChart Delphi Component Library } { Stacked Bar Series Example } { Copyright (c) 1995-1996 by David Berneda } { All rights reserved } {*********************************************} unit Ustack; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, Chart, Series, ExtCtrls, StdCtrls, Teengine, ArrowCha, Buttons, teeprocs; type TStackedForm = class(TForm) Chart1: TChart; BarSeries1: TBarSeries; BarSeries2: TBarSeries; RadioGroup1: TRadioGroup; Panel1: TPanel; Button1: TButton; RadioGroup2: TRadioGroup; ComboBox1: TComboBox; Label1: TLabel; CheckBox1: TCheckBox; Timer1: TTimer; BarSeries3: TBarSeries; Shape1: TShape; BitBtn3: TBitBtn; CheckBox2: TCheckBox; procedure FormCreate(Sender: TObject); procedure RadioGroup1Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure ComboBox1Change(Sender: TObject); procedure RadioGroup2Click(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure Shape1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure CheckBox2Click(Sender: TObject); private { Private declarations } public { Public declarations } Procedure RefreshShape; end; implementation {$R *.DFM} Uses UDemUtil,tecanvas; procedure TStackedForm.FormCreate(Sender: TObject); var t:Longint; begin { The Chart gradient is visible only with 16k Colors or greater video mode } Chart1.Gradient.Visible:=Chart1.IsScreenHighColor; { Add some random points to the three bar Series } Randomize; with BarSeries1 do for t:=1 to 12 do Add( Random(100),ShortMonthNames[t],clTeeColor); with BarSeries2 do for t:=1 to 12 do Add( Random(100),ShortMonthNames[t],clTeeColor); with BarSeries3 do for t:=1 to 12 do Add( Random(100),ShortMonthNames[t],clTeeColor); { Fill a ComboBox with the three Series titles } ComboBox1.Items.Clear; for t:=0 to Chart1.SeriesCount-1 do ComboBox1.Items.Add(Chart1.Series[t].Name); ComboBox1.ItemIndex:=0; RefreshShape; end; Procedure TStackedForm.RefreshShape; Begin { This method sets the Shape color to the active Series color in Combobox } With Chart1.Series[ComboBox1.ItemIndex] do Begin Shape1.Visible:=not ColorEachPoint; if Shape1.Visible then Shape1.Brush.Color:=SeriesColor; end; end; procedure TStackedForm.RadioGroup1Click(Sender: TObject); begin { Four ways to plot bar Series: } Case RadioGroup1.ItemIndex of 0: BarSeries1.MultiBar:=mbNone; 1: BarSeries1.MultiBar:=mbSide; 2: BarSeries1.MultiBar:=mbStacked; 3: BarSeries1.MultiBar:=mbStacked100; end; end; procedure TStackedForm.Button1Click(Sender: TObject); begin { Scroll two Bar Series } With Chart1 do Begin Series[SeriesCount-1].Marks.Visible:=False; { hide marks } SeriesDown(Series[0]); { move series 0 to back } Series[SeriesCount-1].Marks.Visible:=True; { show marks again } end; ComboBox1Change(Self); end; procedure TStackedForm.ComboBox1Change(Sender: TObject); begin { Change the active Bar Series } With Chart1.Series[ComboBox1.ItemIndex] as TBarSeries do RadioGroup2.Itemindex:=Ord(BarStyle); RefreshShape; end; procedure TStackedForm.RadioGroup2Click(Sender: TObject); begin { Change the active Bar Series Style } With Chart1.Series[ComboBox1.ItemIndex] as TBarSeries do BarStyle:=TBarStyle(RadioGroup2.Itemindex); end; procedure TStackedForm.CheckBox1Click(Sender: TObject); begin { Start / Stop Animation } Timer1.Enabled:=CheckBox1.Checked; RadioGroup1.Enabled:=not Timer1.Enabled; RadioGroup2.Enabled:=not Timer1.Enabled; if not Timer1.Enabled then ComboBox1Change(Self); end; procedure TStackedForm.Timer1Timer(Sender: TObject); { this function returns a random color from ColorPalette } Function RandomColor(CheckBack:Boolean):TColor; Begin Repeat result:=ColorPalette[1+Random(MaxDefaultColors)]; Until (not CheckBack) or ( (result<>Chart1.Color) and (result<>Chart1.BackColor) ); end; { this function returns a random angle from 0, 90, 180 or 270 } Function RandomAngle:Integer; Begin Case Random(4) of 0: result:=0; 1: result:=90; 2: result:=180; else { 3: } result:=270; end; end; { this function changes randomly the Pen parameter } Procedure RandomPen(APen:TChartPen); Begin With APen do if Visible then Case Random(3) of 0: Color:=RandomColor(True); 1: Style:=TPenStyle(Random(5)); 2: Width:=1+Random(3); end; end; { this function changes randomly the Brush parameter } Procedure RandomBrush(ABrush:TBrush); Begin With ABrush do Case Random(2) of 0: Color:=RandomColor(True); 1: if Random(10)<5 then Style:=TBrushStyle(Random(8)); end; end; { this function changes randomly the Font parameter } Procedure RandomFont(AFont:TFont); Begin With AFont do Case Random(2) of 0: Color:=RandomColor(True); 1: if Random(2)=0 then Size:=Size+1 else if Size>7 then Size:=Size-1; end; End; var tmpSeries:TBarSeries; t:Longint; begin { This long.... routine..... is only a random generator for Chart and Series properties. } Timer1.Enabled:=False; { stop timer } { Set all Series.Active } for t:=0 to Chart1.SeriesCount-1 do Chart1.Series[t].Active:=True; { Choose a Series randomly } tmpSeries:=Chart1.Series[Random(ComboBox1.Items.Count)] as TBarSeries; { Then, lets change this chart a little.... } Case Random(72) of 0: RadioGroup1.ItemIndex:=Random(RadioGroup1.Items.Count); 1,2,3,4,5: RadioGroup2.ItemIndex:=Random(RadioGroup2.Items.Count); 6: Button1Click(Self); 7: tmpSeries.SeriesColor:=RandomColor(False); 8: Chart1.Chart3dPercent:=5+Random(80); 9: Chart1.BackColor:=RandomColor(False); 10: if Chart1.Legend.Alignment=laRight then Chart1.Legend.Alignment:=laLeft else Chart1.Legend.Alignment:=laRight; 11: RandomFont(Chart1.BottomAxis.LabelsFont); 12: RandomFont(Chart1.LeftAxis.LabelsFont); 13: Chart1.View3d:=not Chart1.View3d; 14: tmpSeries.BarWidthPercent:=50+Random(40); 15: RandomFont(tmpSeries.Marks.Font); 16: Chart1.BottomAxis.Grid.Visible:=not Chart1.BottomAxis.Grid.Visible; 17: Chart1.LeftAxis.Grid.Visible:=not Chart1.LeftAxis.Grid.Visible; 18: RandomFont(Chart1.LeftAxis.Title.Font); 19: RandomFont(Chart1.BottomAxis.Title.Font); 20: tmpSeries.Marks.Style:=TSeriesMarksStyle(Random(9)); 21: With Chart1 do Begin BevelWidth:=1+Random(10); MarginTop :=TeeDefVerticalMargin+BevelWidth; MarginLeft :=TeeDefHorizMargin+BevelWidth; MarginRight :=TeeDefHorizMargin+BevelWidth; MarginBottom:=TeeDefVerticalMargin+BevelWidth; end; 22: Chart1.Legend.Visible:=not Chart1.Legend.Visible; 23: if Random(10)<5 then Chart1.Legend.LegendStyle:=lsSeries else Chart1.Legend.LegendStyle:=lsValues; 24: tmpSeries.Active:=not tmpSeries.Active; 25: tmpSeries.Marks.BackColor:=RandomColor(True); 26: tmpSeries.Marks.Visible:=not tmpSeries.Marks.Visible; 27: RandomPen(Chart1.BottomAxis.Grid); 28: RandomPen(Chart1.LeftAxis.Grid); 29: Chart1.Legend.Frame.Visible:=not Chart1.Legend.Frame.Visible; 30: RandomPen(Chart1.Legend.Frame); 31: RandomPen(tmpSeries.BarPen); 32: tmpSeries.ColorEachPoint:=not tmpSeries.ColorEachPoint; 33: Chart1.Title.Alignment:=TAlignment(Random(3)); 34: RandomFont(Chart1.Title.Font); 35: RandomFont(Chart1.Legend.Font); 36: Chart1.Legend.Color:=RandomColor(False); 37: Chart1.Legend.TextStyle:=TLegendTextStyle(Random(5)); 38: Chart1.Legend.TopPos:=5+Random(90); 39: RandomPen(Chart1.BottomAxis.Axis); 40: RandomPen(Chart1.LeftAxis.Axis); 41: RandomPen(Chart1.BottomAxis.Ticks); 42: RandomPen(Chart1.LeftAxis.Ticks); 43: RandomPen(Chart1.BottomAxis.TicksInner); 44: RandomPen(Chart1.LeftAxis.TicksInner); 45: Chart1.BottomAxis.TickLength:=Random(8); 46: Chart1.LeftAxis.TickLength:=Random(8); 47: Chart1.BottomAxis.TickInnerLength:=Random(8); 48: Chart1.LeftAxis.TickInnerLength:=Random(8); 49: RandomBrush(tmpSeries.BarBrush); 50: Chart1.Title.Frame.Visible:=not Chart1.Title.Frame.Visible; 51: RandomPen(Chart1.Title.Frame); 52: Chart1.Foot.Frame.Visible:=not Chart1.Foot.Frame.Visible; 53: RandomPen(Chart1.Foot.Frame); 54: Chart1.Title.AdjustFrame:=not Chart1.Title.AdjustFrame; 55: Chart1.Foot.AdjustFrame:=not Chart1.Foot.AdjustFrame; 56: RandomBrush(Chart1.Title.Brush); 57: RandomBrush(Chart1.Foot.Brush); 58: Chart1.BottomAxis.MinorTickLength:=Random(8); 59: Chart1.LeftAxis.MinorTickLength:=Random(8); 60: RandomPen(Chart1.BottomAxis.MinorTicks); 61: RandomPen(Chart1.LeftAxis.MinorTicks); 62: RandomPen(Chart1.LeftWall.Pen); 63: RandomPen(Chart1.BottomWall.Pen); 64: Chart1.LeftWall.Color:=RandomColor(False); 65: Chart1.BottomWall.Color:=RandomColor(False); 66: Chart1.LeftAxis.MinorTickCount:=1+Random(6); 67: Chart1.BottomAxis.MinorTickCount:=1+Random(6); 68: Chart1.LeftAxis.Title.Angle:=RandomAngle; 69: Chart1.BottomAxis.Title.Angle:=RandomAngle; 70: Chart1.LeftAxis.LabelsAngle:=RandomAngle; 71: Chart1.BottomAxis.LabelsAngle:=RandomAngle; end; { re-start timer } Timer1.Enabled:=True; end; procedure TStackedForm.Shape1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin { Run the Color dialog to change Series color } With Chart1.Series[ComboBox1.ItemIndex] do SeriesColor:=EditColor(Self,SeriesColor); RefreshShape; end; procedure TStackedForm.CheckBox2Click(Sender: TObject); begin { Turn on / off Chart 3D } Chart1.View3D:=CheckBox2.Checked; end; end.
{********************************************} { TeeChart Pro Charting Library } { Copyright (c) 1995-2004 by David Berneda } { All Rights Reserved } {********************************************} unit TeeDBSumEdit; {$I TeeDefs.inc} interface uses SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, {$ENDIF} Chart, TeEngine, TeeSourceEdit, TeeDBEdit, TeCanvas; type TDBChartSumEditor = class(TBaseDBChartEditor) Label1: TLabel; Label2: TLabel; CBAgg: TComboFlat; CBValue: TComboFlat; CBGroup: TComboFlat; CBTimeStep: TComboFlat; Label3: TLabel; Label4: TLabel; CBSort: TComboFlat; CBSortType: TComboFlat; procedure CBAggChange(Sender: TObject); procedure CBGroupChange(Sender: TObject); procedure BApplyClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure CBSourcesChange(Sender: TObject); procedure CBSortChange(Sender: TObject); procedure CBSortTypeChange(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } procedure CheckCount; Procedure EnableCombos; Procedure EnableTimeStep; public { Public declarations } end; TDBSummarySource=class(TTeeSeriesDBSource) public class Function Description:String; override; class Function Editor:TComponentClass; override; class Function HasSeries(ASeries:TChartSeries):Boolean; override; end; // Show modal dialog to edit Series Database Summary properties. Function TeeDBSummaryEditor(AOwner:TComponent; ASeries:TChartSeries):Boolean; implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} Uses {$IFDEF CLR} Variants, {$ENDIF} DBChart, TeeProcs, DB, TeeConst; Function TeeDBSummaryEditor(AOwner:TComponent; ASeries:TChartSeries):Boolean; begin // Show the Summary editor dialog... With TDBChartSumEditor.Create(AOwner) do try Align:=alNone; Tag:={$IFDEF CLR}Variant{$ELSE}Integer{$ENDIF}(ASeries); BorderStyle:=TeeBorderStyle; Caption:='Summary properties'; result:=ShowModal=mrOk; finally Free; end; end; Function TeeGetDBGroup(St:String; Var Step:TTeeDBGroup):Boolean; begin result:=False; St:=TeeGetDBPart(1,St); if St<>'' then begin result:=True; Step:=StrToDBGroup(St); end; end; procedure TDBChartSumEditor.CBAggChange(Sender: TObject); begin inherited; With CBValue do begin Enabled:=(DataSet<>nil) and (CBAgg.ItemIndex<>1); if ItemIndex<>-1 then Text:=Items[ItemIndex] { 5.01 } else Text:=''; end; BApply.Enabled:=True end; Procedure TDBChartSumEditor.EnableTimeStep; Function TheFieldType(Const AName:String):TFieldType; begin With DataSet do if FieldCount>0 then result:=FieldByName(AName).DataType else begin FieldDefs.Update; result:=FieldDefs[FieldDefs.IndexOf(AName)].DataType; end; end; var tmpName : String; begin if CBGroup.ItemIndex=-1 then begin CBTimeStep.ItemIndex:=-1; CBTimeStep.Enabled:=False; CBSort.Enabled:=False; CBSortType.Enabled:=False; end else begin With CBGroup do tmpName:=Items[ItemIndex]; CBTimeStep.Enabled:=TeeFieldType(TheFieldType(tmpName))=tftDateTime; CBSort.Enabled:=not CBTimeStep.Enabled; if not CBSort.Enabled then CBSort.ItemIndex:=0; CBSortType.Enabled:=CBSort.ItemIndex>0; end; end; procedure TDBChartSumEditor.CBGroupChange(Sender: TObject); begin inherited; EnableTimeStep; BApply.Enabled:=True; end; procedure TDBChartSumEditor.BApplyClick(Sender: TObject); Function TeeDBGroupToStr(Group:TTeeDBGroup):String; begin Case Group of dgHour : result:='HOUR'; dgDay : result:='DAY'; dgWeek : result:='WEEK'; dgWeekDay: result:='WEEKDAY'; dgMonth : result:='MONTH'; dgQuarter: result:='QUARTER'; dgYear : result:='YEAR' else result:=''; end; end; var tmp : String; tmpSt : String; begin inherited; Case CBAgg.ItemIndex of 0: tmp:='#SUM#'; 1: tmp:='#COUNT#'; 2: tmp:='#HIGH#'; 3: tmp:='#LOW#'; 4: tmp:='#AVG#'; else tmp:=''; end; TheSeries.DataSource:=nil; With CBValue do { 5.01 } if ItemIndex=-1 then TheSeries.MandatoryValueList.ValueSource:=tmp+Text else TheSeries.MandatoryValueList.ValueSource:=tmp+Items[ItemIndex]; tmpSt:=''; if CBGroup.ItemIndex<>-1 then begin tmpSt:=CBGroup.Items[CBGroup.ItemIndex]; if CBTimeStep.Enabled and (CBTimeStep.ItemIndex<>-1) then tmpSt:='#'+TeeDBGroupToStr(TTeeDBGroup(CBTimeStep.ItemIndex))+'#'+tmpSt else case CBSort.ItemIndex of 2: begin TheSeries.MandatoryValueList.Order:=loNone; if CBSortType.ItemIndex=0 then tmpSt:='#SORTASC#'+tmpSt else tmpSt:='#SORTDES#'+tmpSt; end; 1: begin TheSeries.NotMandatoryValueList.Order:=loNone; TheSeries.MandatoryValueList.Order:=TChartListOrder(CBSortType.ItemIndex); end; 0: begin TheSeries.MandatoryValueList.Order:=loNone; TheSeries.NotMandatoryValueList.Order:=loNone; end; end; end; With TheSeries do begin XLabelsSource:=tmpSt; DataSource:=Self.DataSet; end; BApply.Enabled:=False; end; procedure TDBChartSumEditor.FormShow(Sender: TObject); var tmp : TTeeDBGroup; tmpSource : String; tmpOrder : TChartListOrder; begin inherited; EnableCombos; FillFields([CBValue,CBGroup]); if Assigned(TheSeries) then begin tmpSource:=TheSeries.MandatoryValueList.ValueSource; With CBAgg do ItemIndex:=Items.IndexOf(TeeGetDBPart(1,tmpSource)); With CBValue do ItemIndex:=Items.IndexOf(TeeGetDBPart(2,tmpSource)); tmpSource:=TeeGetDBPart(2,TheSeries.XLabelsSource); tmpOrder:=loNone; if tmpSource='' then tmpSource:=TeeGetDBPart(1,TheSeries.XLabelsSource) else tmpOrder:=StrToDBOrder(TeeGetDBPart(1,TheSeries.XLabelsSource)); if tmpSource='' then tmpSource:=TheSeries.XLabelsSource; With CBGroup do ItemIndex:=Items.IndexOf(tmpSource); EnableTimeStep; With CBTimeStep do if Enabled then begin if TeeGetDBGroup(TheSeries.XLabelsSource,tmp) then ItemIndex:=Ord(tmp); end; CBSort.Enabled:=(not CBTimeStep.Enabled) and (CBGroup.ItemIndex<>-1); if CBSort.Enabled then if tmpOrder=loNone then begin if TheSeries.MandatoryValueList.Order<>loNone then begin CBSort.ItemIndex:=1; CBSortType.ItemIndex:=Ord(TheSeries.MandatoryValueList.Order); end else CBSort.ItemIndex:=0; end else begin CBSort.ItemIndex:=2; CBSortType.ItemIndex:=Ord(tmpOrder); end; CBSortType.Enabled:=CBSort.Enabled and (CBSort.ItemIndex>0); CheckCount; end; end; procedure TDBChartSumEditor.CheckCount; begin CBValue.Enabled:=(DataSet<>nil) and (CBAgg.ItemIndex<>1); if CBValue.Enabled then With CBValue do begin ItemIndex:=Items.IndexOf(TeeGetDBPart(2, TheSeries.MandatoryValueList.ValueSource)); if ItemIndex<>-1 then Text:=Items[ItemIndex] else Text:=''; end else CBValue.Text:=''; end; Procedure TDBChartSumEditor.EnableCombos; begin EnableControls(DataSet<>nil,[CBAgg,CBValue,CBTimeStep,CBGroup]); end; procedure TDBChartSumEditor.CBSourcesChange(Sender: TObject); begin inherited; EnableCombos; FillFields([CBValue,CBGroup]); end; procedure TDBChartSumEditor.CBSortChange(Sender: TObject); begin CBSortType.Enabled:=CBSort.ItemIndex>0; BApply.Enabled:=True; end; procedure TDBChartSumEditor.CBSortTypeChange(Sender: TObject); begin BApply.Enabled:=True; end; procedure TDBChartSumEditor.FormCreate(Sender: TObject); begin inherited; CBSortType.ItemIndex:=0; CBSort.ItemIndex:=0; end; { TDBSummarySource } class function TDBSummarySource.Description: String; begin result:=TeeMsg_Summary; end; class function TDBSummarySource.Editor: TComponentClass; begin result:=TDBChartSumEditor; end; class function TDBSummarySource.HasSeries( ASeries: TChartSeries): Boolean; begin result:=(ASeries.DataSource is TDataSet) and (Copy(ASeries.MandatoryValueList.ValueSource,1,1)='#'); end; initialization TeeSources.Add({$IFDEF CLR}TObject{$ENDIF}(TDBSummarySource)); finalization TeeSources.Remove({$IFDEF CLR}TObject{$ENDIF}(TDBSummarySource)); end.
unit PascalCoin.Update.Classes; interface uses Spring, System.SysUtils, System.Classes, System.Generics.Collections, PascalCoin.Update.Interfaces, PascalCoin.RPC.Interfaces; type TUpdatedAccount = class(TInterfacedObject, IUpdatedAccount) private FAccount: IPascalCoinAccount; FStatus: TAccountUpdateStatus; FUpdateId: Integer; protected function GetAccount: IPascalCoinAccount; procedure SetAccount(Value: IPascalCoinAccount); function GetStatus: TAccountUpdateStatus; procedure SetStatus(const Value: TAccountUpdateStatus); function GetUpdateId: Integer; procedure SetUpdateId(const Value: Integer); public constructor Create; end; TPascalCoinFetchThread = Class(TThread) private FAPI: IPascalCoinAPI; FKeyList: TStrings; FSleepInterval: Integer; FSyncMethod: TThreadMethod; FAccounts: IPascalCoinAccounts; FAccountsStore: TDictionary<Int64, IUpdatedAccount>; FUpdatedAccounts: IUpdatedAccounts; FKeyStyle: TKeyStyle; FSyncSuccess: boolean; FUpdateId: Integer; FPaused: boolean; procedure ProcessKeys; procedure SetNodeURI(const Value: String); protected procedure Execute; override; public constructor Create(rpcAPI: IPascalCoinAPI; AAccountsList: IPascalCoinAccounts); destructor Destroy; override; /// <summary> /// Only call this in Create and SyncMethod until I sort it out properly or /// Omni Thread Library is multi platform. /// </summary> procedure UpdateList(AKeyList: TStrings); property SleepInterval: Integer write FSleepInterval; property SyncMethod: TThreadMethod write FSyncMethod; property Accounts: IPascalCoinAccounts read FAccounts; property UpdatedAccounts: IUpdatedAccounts read FUpdatedAccounts; property KeyStyle: TKeyStyle write FKeyStyle; property SyncSuccess: boolean read FSyncSuccess; property NodeURI: String write SetNodeURI; property Pause: boolean write FPaused; End; TFetchAccountData = class(TInterfacedObject, IFetchAccountData) private FKeyStyle: TKeyStyle; FPublicKeys: TStringList; FKeysAdded: boolean; FSleepInterval: Integer; FThread: TPascalCoinFetchThread; FOnSync: Event<TOnAccountsUpdated>; FInitialised: boolean; FFailedInitProcessed: boolean; FIsRunning: boolean; FAccountsList: IPascalCoinAccounts; FPause: Boolean; procedure InitialiseThread; procedure ThreadSync; protected procedure SetURI(const Value: string); function GetIsRunning: boolean; function GetOnSync: IEvent<TOnAccountsUpdated>; function GetSleepInterval: Integer; procedure SetSleepInterval(const Value: Integer); procedure SetKeyStyle(const Value: TKeyStyle); function GetPause: Boolean; procedure SetPause(const Value: boolean); procedure AddPublicKey(const Value: string); procedure AddPublicKeys(Value: TStrings); function Execute: boolean; procedure Terminate; public constructor Create(AAPI: IPascalCoinAPI; AAccountsList: IPascalCoinAccounts); destructor Destroy; override; end; implementation uses PascalCoin.Utils.Classes, PascalCoin.RPC.Account; { TFetchAccountData } procedure TFetchAccountData.AddPublicKey(const Value: string); var lCount: Integer; begin lCount := FPublicKeys.Count; FPublicKeys.Add(Value); FKeysAdded := FKeysAdded or (FPublicKeys.Count > lCount); end; procedure TFetchAccountData.AddPublicKeys(Value: TStrings); var S: String; begin for S in Value do AddPublicKey(S); end; constructor TFetchAccountData.Create(AAPI: IPascalCoinAPI; AAccountsList: IPascalCoinAccounts); begin inherited Create; FSleepInterval := 10000; FFailedInitProcessed := False; FPublicKeys := TStringList.Create; FPublicKeys.Sorted := True; FPublicKeys.Duplicates := dupIgnore; FAccountsList := AAccountsList; FThread := TPascalCoinFetchThread.Create(AAPI, FAccountsList); FThread.SyncMethod := ThreadSync; FThread.SleepInterval := FSleepInterval; end; destructor TFetchAccountData.Destroy; begin Terminate; FPublicKeys.Free; inherited; end; function TFetchAccountData.Execute: boolean; begin InitialiseThread; if FThread.Suspended then FThread.Start; FIsRunning := True; Result := True; end; function TFetchAccountData.GetOnSync: IEvent<TOnAccountsUpdated>; begin result := FOnSync; end; function TFetchAccountData.GetPause: Boolean; begin result := FPause; end; function TFetchAccountData.GetSleepInterval: Integer; begin result := FSleepInterval; end; procedure TFetchAccountData.InitialiseThread; begin if FInitialised then Exit; FThread.UpdateList(FPublicKeys); FKeysAdded := False; FThread.KeyStyle := FKeyStyle; FInitialised := True; end; function TFetchAccountData.GetIsRunning: boolean; begin result := FIsRunning; end; procedure TFetchAccountData.SetKeyStyle(const Value: TKeyStyle); begin FKeyStyle := Value; end; procedure TFetchAccountData.SetPause(const Value: boolean); begin FPause := Value; FThread.Pause := FPause; end; procedure TFetchAccountData.SetSleepInterval(const Value: Integer); begin FSleepInterval := Value; end; procedure TFetchAccountData.SetURI(const Value: string); begin FThread.NodeURI := Value; end; procedure TFetchAccountData.Terminate; begin // waitfor? FThread.Terminate; FIsRunning := False; end; procedure TFetchAccountData.ThreadSync; begin if FThread.SyncSuccess then begin if (FThread.UpdatedAccounts.Count = 0) then Exit; FOnSync.Invoke(FThread.UpdatedAccounts); FThread.SleepInterval := FSleepInterval; if FKeysAdded then begin FThread.UpdateList(FPublicKeys); FKeysAdded := False; FThread.KeyStyle := FKeyStyle; end; FFailedInitProcessed := False; end else begin if not FFailedInitProcessed then begin FOnSync.Invoke(nil); FFailedInitProcessed := True; FIsRunning := False; end; end; end; { TPascalCoinFetchThread } constructor TPascalCoinFetchThread.Create(rpcAPI: IPascalCoinAPI; AAccountsList: IPascalCoinAccounts); begin inherited Create(True); FUpdateId := -1; FKeyList := TStringList.Create; TStringList(FKeyList).Sorted := True; TStringList(FKeyList).Duplicates := dupIgnore; FAPI := rpcAPI; FAccounts := AAccountsList; FAccountsStore := TDictionary<Int64, IUpdatedAccount>.Create; FUpdatedAccounts := TPascalCoinList<IUpdatedAccount>.Create; end; destructor TPascalCoinFetchThread.Destroy; begin FKeyList.Free; FAccountsStore.Free; inherited; end; procedure TPascalCoinFetchThread.Execute; begin while not Terminated do begin if FPaused then begin Sleep(100); Continue; end; if FAPI.NodeAvailability = TNodeAvailability.Avaialable then ProcessKeys else FSyncSuccess := False; Synchronize(FSyncMethod); // if not FSyncSuccess then // begin // Terminate; // Break; // end; Sleep(FSleepInterval) end; end; procedure TPascalCoinFetchThread.ProcessKeys; procedure AddUpdatedAccount(AUpdAcct: IUpdatedAccount); var lAcct: IUpdatedAccount; begin lAcct := TUpdatedAccount.Create; lAcct.Status := AUpdAcct.Status; lAcct.UpdateId := AUpdAcct.UpdateId; lAcct.Account.Assign(AUpdAcct.Account); FUpdatedAccounts.Add(lAcct); end; var I, J: Integer; ISF: Int64; lAccts: IPascalCoinAccounts; lUpdAcct: IUpdatedAccount; begin FAccounts.Clear; FUpdatedAccounts.Clear; for I := 0 to FKeyList.Count - 1 do begin try lAccts := FAPI.getwalletaccounts(FKeyList[I], FKeyStyle); for J := 0 to lAccts.Count - 1 do begin FAccounts.AddAccount(lAccts.Account[J]); end; FSyncSuccess := True; except on e: exception do FSyncSuccess := False; end; end; if not FSyncSuccess then Exit; Inc(FUpdateId); for I := 0 to FAccounts.Count -1 do begin if FAccountsStore.TryGetValue(FAccounts[I].account, lUpdAcct) then begin lUpdAcct.UpdateId := FUpdateId; if not lUpdAcct.Account.SameAs(FAccounts[I]) then begin lUpdAcct.Account.Assign(FAccounts[I]); lUpdAcct.Status := TAccountUpdateStatus.Changed; end else lUpdAcct.Status := TAccountUpdateStatus.NoChange; end else //Need to create one begin lUpdAcct := TUpdatedAccount.Create; lUpdAcct.Status := TAccountUpdateStatus.Added; lUpdAcct.UpdateId := FUpdateId; lUpdAcct.Account.Assign(FAccounts[I]); FAccountsStore.TryAdd(FAccounts[I].account, lUpdAcct); AddUpdatedAccount(lUpdAcct); end; end; //now are there any too delete? for ISF In FAccountsStore.Keys do begin lUpdAcct := FAccountsStore.Items[ISF]; if lUpdAcct.UpdateId <> FUpdateId then begin lUpdAcct.Status := TAccountUpdateStatus.Deleted; AddUpdatedAccount(lUpdAcct); FAccountsStore.Remove(ISF); end; end; end; procedure TPascalCoinFetchThread.SetNodeURI(const Value: String); begin FAPI.NodeURI := Value; end; procedure TPascalCoinFetchThread.UpdateList(AKeyList: TStrings); begin FKeyList.Assign(AKeyList); end; { TUpdatedAccount } constructor TUpdatedAccount.Create; begin { TODO : This is lazy } FAccount := TPascalCoinAccount.Create; end; function TUpdatedAccount.GetAccount: IPascalCoinAccount; begin result := FAccount; end; function TUpdatedAccount.GetStatus: TAccountUpdateStatus; begin result := FStatus; end; function TUpdatedAccount.GetUpdateId: Integer; begin result := FUpdateId; end; procedure TUpdatedAccount.SetAccount(Value: IPascalCoinAccount); begin FAccount := Value; end; procedure TUpdatedAccount.SetStatus(const Value: TAccountUpdateStatus); begin FStatus := Value; end; procedure TUpdatedAccount.SetUpdateId(const Value: Integer); begin FUpdateId := Value; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit System.UIConsts; interface uses System.UITypes, System.Classes; { Cursor string functions } function CursorToString(Cursor: TCursor): string; function StringToCursor(const S: string): TCursor; procedure GetCursorValues(const Proc: TGetStrProc); function CursorToIdent(Cursor: Longint; var Ident: string): Boolean; function IdentToCursor(const Ident: string; var Cursor: Longint): Boolean; procedure RegisterCursorIntegerConsts; { TColor string functions } function ColorToString(Color: TColor): string; function StringToColor(const S: string): TColor; procedure GetColorValues(Proc: TGetStrProc); function ColorToIdent(Color: Longint; var Ident: string): Boolean; function IdentToColor(const Ident: string; var Color: Longint): Boolean; procedure RegisterColorIntegerConsts; { TAlphaColor string functions } procedure GetAlphaColorValues(Proc: TGetStrProc); function AlphaColorToString(Value: TAlphaColor): string; function StringToAlphaColor(const Value: string): TAlphaColor; function AlphaColorToIdent(Color: Longint; var Ident: string): Boolean; function IdentToAlphaColor(const Ident: string; var Color: Longint): Boolean; procedure RegisterAlphaColorIntegerConsts; implementation uses System.SysUtils; { Cursor translation function } const DeadCursors = 1; const Cursors: array[0..21] of TIdentMapEntry = ( (Value: crDefault; Name: 'crDefault'), (Value: crArrow; Name: 'crArrow'), (Value: crCross; Name: 'crCross'), (Value: crIBeam; Name: 'crIBeam'), (Value: crSizeNESW; Name: 'crSizeNESW'), (Value: crSizeNS; Name: 'crSizeNS'), (Value: crSizeNWSE; Name: 'crSizeNWSE'), (Value: crSizeWE; Name: 'crSizeWE'), (Value: crUpArrow; Name: 'crUpArrow'), (Value: crHourGlass; Name: 'crHourGlass'), (Value: crDrag; Name: 'crDrag'), (Value: crNoDrop; Name: 'crNoDrop'), (Value: crHSplit; Name: 'crHSplit'), (Value: crVSplit; Name: 'crVSplit'), (Value: crMultiDrag; Name: 'crMultiDrag'), (Value: crSQLWait; Name: 'crSQLWait'), (Value: crNo; Name: 'crNo'), (Value: crAppStart; Name: 'crAppStart'), (Value: crHelp; Name: 'crHelp'), (Value: crHandPoint; Name: 'crHandPoint'), (Value: crSizeAll; Name: 'crSizeAll'), { Dead cursors } (Value: crSize; Name: 'crSize')); function CursorToString(Cursor: TCursor): string; begin if not CursorToIdent(Cursor, Result) then FmtStr(Result, '%d', [Cursor]); end; function StringToCursor(const S: string): TCursor; var L: Longint; begin if not IdentToCursor(S, L) then L := StrToInt(S); Result := L; end; procedure GetCursorValues(const Proc: TGetStrProc); var I: Integer; begin for I := Low(Cursors) to High(Cursors) - DeadCursors do Proc(Cursors[I].Name); end; function CursorToIdent(Cursor: Longint; var Ident: string): Boolean; begin Result := IntToIdent(Cursor, Ident, Cursors); end; function IdentToCursor(const Ident: string; var Cursor: Longint): Boolean; begin Result := IdentToInt(Ident, Cursor, Cursors); end; procedure RegisterCursorIntegerConsts; begin if not Assigned(FindIntToIdent(TypeInfo(TCursor))) then RegisterIntegerConsts(TypeInfo(TCursor), IdentToCursor, CursorToIdent); end; { Color mapping routines } const Colors: array[0..51] of TIdentMapEntry = ( (Value: TColors.Black; Name: 'clBlack'), (Value: TColors.Maroon; Name: 'clMaroon'), (Value: TColors.Green; Name: 'clGreen'), (Value: TColors.Olive; Name: 'clOlive'), (Value: TColors.Navy; Name: 'clNavy'), (Value: TColors.Purple; Name: 'clPurple'), (Value: TColors.Teal; Name: 'clTeal'), (Value: TColors.Gray; Name: 'clGray'), (Value: TColors.Silver; Name: 'clSilver'), (Value: TColors.Red; Name: 'clRed'), (Value: TColors.Lime; Name: 'clLime'), (Value: TColors.Yellow; Name: 'clYellow'), (Value: TColors.Blue; Name: 'clBlue'), (Value: TColors.Fuchsia; Name: 'clFuchsia'), (Value: TColors.Aqua; Name: 'clAqua'), (Value: TColors.White; Name: 'clWhite'), (Value: TColors.MoneyGreen; Name: 'clMoneyGreen'), // Use LegacySkyBlue to maintain consistency in VCL colors (Value: TColors.LegacySkyBlue; Name: 'clSkyBlue'), (Value: TColors.Cream; Name: 'clCream'), (Value: TColors.MedGray; Name: 'clMedGray'), (Value: TColors.SysActiveBorder; Name: 'clActiveBorder'), (Value: TColors.SysActiveCaption; Name: 'clActiveCaption'), (Value: TColors.SysAppWorkSpace; Name: 'clAppWorkSpace'), (Value: TColors.SysBackground; Name: 'clBackground'), (Value: TColors.SysBtnFace; Name: 'clBtnFace'), (Value: TColors.SysBtnHighlight; Name: 'clBtnHighlight'), (Value: TColors.SysBtnShadow; Name: 'clBtnShadow'), (Value: TColors.SysBtnText; Name: 'clBtnText'), (Value: TColors.SysCaptionText; Name: 'clCaptionText'), (Value: TColors.SysDefault; Name: 'clDefault'), (Value: TColors.SysGradientActiveCaption; Name: 'clGradientActiveCaption'), (Value: TColors.SysGradientInactiveCaption; Name: 'clGradientInactiveCaption'), (Value: TColors.SysGrayText; Name: 'clGrayText'), (Value: TColors.SysHighlight; Name: 'clHighlight'), (Value: TColors.SysHighlightText; Name: 'clHighlightText'), (Value: TColors.SysHotLight; Name: 'clHotLight'), (Value: TColors.SysInactiveBorder; Name: 'clInactiveBorder'), (Value: TColors.SysInactiveCaption; Name: 'clInactiveCaption'), (Value: TColors.SysInactiveCaptionText; Name: 'clInactiveCaptionText'), (Value: TColors.SysInfoBk; Name: 'clInfoBk'), (Value: TColors.SysInfoText; Name: 'clInfoText'), (Value: TColors.SysMenu; Name: 'clMenu'), (Value: TColors.SysMenuBar; Name: 'clMenuBar'), (Value: TColors.SysMenuHighlight; Name: 'clMenuHighlight'), (Value: TColors.SysMenuText; Name: 'clMenuText'), (Value: TColors.SysNone; Name: 'clNone'), (Value: TColors.SysScrollBar; Name: 'clScrollBar'), (Value: TColors.Sys3DDkShadow; Name: 'cl3DDkShadow'), (Value: TColors.Sys3DLight; Name: 'cl3DLight'), (Value: TColors.SysWindow; Name: 'clWindow'), (Value: TColors.SysWindowFrame; Name: 'clWindowFrame'), (Value: TColors.SysWindowText; Name: 'clWindowText')); function ColorToString(Color: TColor): string; begin if not ColorToIdent(Color, Result) then FmtStr(Result, '%s%0.8x', [HexDisplayPrefix, Integer(Color)]); end; function StringToColor(const S: string): TColor; var LColor: LongInt; begin if not IdentToColor(S, LColor) then Result := TColor(StrToInt(S)) else Result := TColor(LColor); end; procedure GetColorValues(Proc: TGetStrProc); var I: Integer; begin for I := Low(Colors) to High(Colors) do Proc(Colors[I].Name); end; function ColorToIdent(Color: Longint; var Ident: string): Boolean; begin Result := IntToIdent(Color, Ident, Colors); end; function IdentToColor(const Ident: string; var Color: Longint): Boolean; begin Result := IdentToInt(Ident, Color, Colors); end; procedure RegisterColorIntegerConsts; begin if not Assigned(FindIntToIdent(TypeInfo(TColor))) then RegisterIntegerConsts(TypeInfo(TColor), IdentToColor, ColorToIdent); end; { Colors ======================================================================== } const AlphaColors: array [0..147] of TIdentMapEntry = ( (Value: Integer($FFF0F8FF); Name: 'claAliceblue'), (Value: Integer($FFFAEBD7); Name: 'claAntiquewhite'), (Value: Integer($FF00FFFF); Name: 'claAqua'), (Value: Integer($FF7FFFD4); Name: 'claAquamarine'), (Value: Integer($FFF0FFFF); Name: 'claAzure'), (Value: Integer($FFF5F5DC); Name: 'claBeige'), (Value: Integer($FFFFE4C4); Name: 'claBisque'), (Value: Integer($FF000000); Name: 'claBlack';), (Value: Integer($FFFFEBCD); Name: 'claBlanchedalmond'), (Value: Integer($FF0000FF); Name: 'claBlue'), (Value: Integer($FF8A2BE2); Name: 'claBlueviolet'), (Value: Integer($FFA52A2A); Name: 'claBrown'), (Value: Integer($FFDEB887); Name: 'claBurlywood'), (Value: Integer($FF5F9EA0); Name: 'claCadetblue'), (Value: Integer($FF7FFF00); Name: 'claChartreuse'), (Value: Integer($FFD2691E); Name: 'claChocolate'), (Value: Integer($FFFF7F50); Name: 'claCoral'), (Value: Integer($FF6495ED); Name: 'claCornflowerblue'), (Value: Integer($FFFFF8DC); Name: 'claCornsilk'), (Value: Integer($FFDC143C); Name: 'claCrimson'), (Value: Integer($FF00FFFF); Name: 'claCyan'), (Value: Integer($FF00008B); Name: 'claDarkblue'), (Value: Integer($FF008B8B); Name: 'claDarkcyan'), (Value: Integer($FFB8860B); Name: 'claDarkgoldenrod'), (Value: Integer($FFA9A9A9); Name: 'claDarkgray'), (Value: Integer($FF006400); Name: 'claDarkgreen'), (Value: Integer($FFA9A9A9); Name: 'claDarkgrey'), (Value: Integer($FFBDB76B); Name: 'claDarkkhaki'), (Value: Integer($FF8B008B); Name: 'claDarkmagenta'), (Value: Integer($FF556B2F); Name: 'claDarkolivegreen'), (Value: Integer($FFFF8C00); Name: 'claDarkorange'), (Value: Integer($FF9932CC); Name: 'claDarkorchid'), (Value: Integer($FF8B0000); Name: 'claDarkred'), (Value: Integer($FFE9967A); Name: 'claDarksalmon'), (Value: Integer($FF8FBC8F); Name: 'claDarkseagreen'), (Value: Integer($FF483D8B); Name: 'claDarkslateblue'), (Value: Integer($FF2F4F4F); Name: 'claDarkslategray'), (Value: Integer($FF2F4F4F); Name: 'claDarkslategrey'), (Value: Integer($FF00CED1); Name: 'claDarkturquoise'), (Value: Integer($FF9400D3); Name: 'claDarkviolet'), (Value: Integer($FFFF1493); Name: 'claDeeppink'), (Value: Integer($FF00BFFF); Name: 'claDeepskyblue'), (Value: Integer($FF696969); Name: 'claDimgray'), (Value: Integer($FF696969); Name: 'claDimgrey'), (Value: Integer($FF1E90FF); Name: 'claDodgerblue'), (Value: Integer($FFB22222); Name: 'claFirebrick'), (Value: Integer($FFFFFAF0); Name: 'claFloralwhite'), (Value: Integer($FF228B22); Name: 'claForestgreen'), (Value: Integer($FFFF00FF); Name: 'claFuchsia'), (Value: Integer($FFDCDCDC); Name: 'claGainsboro'), (Value: Integer($FFF8F8FF); Name: 'claGhostwhite'), (Value: Integer($FFFFD700); Name: 'claGold'), (Value: Integer($FFDAA520); Name: 'claGoldenrod'), (Value: Integer($FF808080); Name: 'claGray'), (Value: Integer($FF008000); Name: 'claGreen'), (Value: Integer($FFADFF2F); Name: 'claGreenyellow'), (Value: Integer($FF808080); Name: 'claGrey'), (Value: Integer($FFF0FFF0); Name: 'claHoneydew'), (Value: Integer($FFFF69B4); Name: 'claHotpink'), (Value: Integer($FFCD5C5C); Name: 'claIndianred'), (Value: Integer($FF4B0082); Name: 'claIndigo'), (Value: Integer($FFFFFFF0); Name: 'claIvory'), (Value: Integer($FFF0E68C); Name: 'claKhaki'), (Value: Integer($FFE6E6FA); Name: 'claLavender'), (Value: Integer($FFFFF0F5); Name: 'claLavenderblush'), (Value: Integer($FF7CFC00); Name: 'claLawngreen'), (Value: Integer($FFFFFACD); Name: 'claLemonchiffon'), (Value: Integer($FFADD8E6); Name: 'claLightblue'), (Value: Integer($FFF08080); Name: 'claLightcoral'), (Value: Integer($FFE0FFFF); Name: 'claLightcyan'), (Value: Integer($FFFAFAD2); Name: 'claLightgoldenrodyellow'), (Value: Integer($FFD3D3D3); Name: 'claLightgray'), (Value: Integer($FF90EE90); Name: 'claLightgreen'), (Value: Integer($FFD3D3D3); Name: 'claLightgrey'), (Value: Integer($FFFFB6C1); Name: 'claLightpink'), (Value: Integer($FFFFA07A); Name: 'claLightsalmon'), (Value: Integer($FF20B2AA); Name: 'claLightseagreen'), (Value: Integer($FF87CEFA); Name: 'claLightskyblue'), (Value: Integer($FF778899); Name: 'claLightslategray'), (Value: Integer($FF778899); Name: 'claLightslategrey'), (Value: Integer($FFB0C4DE); Name: 'claLightsteelblue'), (Value: Integer($FFFFFFE0); Name: 'claLightyellow'), (Value: Integer($FF00FF00); Name: 'claLime'), (Value: Integer($FF32CD32); Name: 'claLimegreen'), (Value: Integer($FFFAF0E6); Name: 'claLinen'), (Value: Integer($FFFF00FF); Name: 'claMagenta'), (Value: Integer($FF800000); Name: 'claMaroon'), (Value: Integer($FF66CDAA); Name: 'claMediumaquamarine'), (Value: Integer($FF0000CD); Name: 'claMediumblue'), (Value: Integer($FFBA55D3); Name: 'claMediumorchid'), (Value: Integer($FF9370DB); Name: 'claMediumpurple'), (Value: Integer($FF3CB371); Name: 'claMediumseagreen'), (Value: Integer($FF7B68EE); Name: 'claMediumslateblue'), (Value: Integer($FF00FA9A); Name: 'claMediumspringgreen'), (Value: Integer($FF48D1CC); Name: 'claMediumturquoise'), (Value: Integer($FFC71585); Name: 'claMediumvioletred'), (Value: Integer($FF191970); Name: 'claMidnightblue'), (Value: Integer($FFF5FFFA); Name: 'claMintcream'), (Value: Integer($FFFFE4E1); Name: 'claMistyrose'), (Value: Integer($FFFFE4B5); Name: 'claMoccasin'), (Value: Integer($FFFFDEAD); Name: 'claNavajowhite'), (Value: Integer($FF000080); Name: 'claNavy'), (Value: Integer($FFFDF5E6); Name: 'claOldlace'), (Value: Integer($FF808000); Name: 'claOlive'), (Value: Integer($FF6B8E23); Name: 'claOlivedrab'), (Value: Integer($FFFFA500); Name: 'claOrange'), (Value: Integer($FFFF4500); Name: 'claOrangered'), (Value: Integer($FFDA70D6); Name: 'claOrchid'), (Value: Integer($FFEEE8AA); Name: 'claPalegoldenrod'), (Value: Integer($FF98FB98); Name: 'claPalegreen'), (Value: Integer($FFAFEEEE); Name: 'claPaleturquoise'), (Value: Integer($FFDB7093); Name: 'claPalevioletred'), (Value: Integer($FFFFEFD5); Name: 'claPapayawhip'), (Value: Integer($FFFFDAB9); Name: 'claPeachpuff'), (Value: Integer($FFCD853F); Name: 'claPeru'), (Value: Integer($FFFFC0CB); Name: 'claPink'), (Value: Integer($FFDDA0DD); Name: 'claPlum'), (Value: Integer($FFB0E0E6); Name: 'claPowderblue'), (Value: Integer($FF800080); Name: 'claPurple'), (Value: Integer($FFFF0000); Name: 'claRed'), (Value: Integer($FFBC8F8F); Name: 'claRosybrown'), (Value: Integer($FF4169E1); Name: 'claRoyalblue'), (Value: Integer($FF8B4513); Name: 'claSaddlebrown'), (Value: Integer($FFFA8072); Name: 'claSalmon'), (Value: Integer($FFF4A460); Name: 'claSandybrown'), (Value: Integer($FF2E8B57); Name: 'claSeagreen'), (Value: Integer($FFFFF5EE); Name: 'claSeashell'), (Value: Integer($FFA0522D); Name: 'claSienna'), (Value: Integer($FFC0C0C0); Name: 'claSilver'), (Value: Integer($FF87CEEB); Name: 'claSkyblue'), (Value: Integer($FF6A5ACD); Name: 'claSlateblue'), (Value: Integer($FF708090); Name: 'claSlategray'), (Value: Integer($FF708090); Name: 'claSlategrey'), (Value: Integer($FFFFFAFA); Name: 'claSnow'), (Value: Integer($FF00FF7F); Name: 'claSpringgreen'), (Value: Integer($FF4682B4); Name: 'claSteelblue'), (Value: Integer($FFD2B48C); Name: 'claTan'), (Value: Integer($FF008080); Name: 'claTeal'), (Value: Integer($FFD8BFD8); Name: 'claThistle'), (Value: Integer($FFFF6347); Name: 'claTomato'), (Value: Integer($FF40E0D0); Name: 'claTurquoise'), (Value: Integer($FFEE82EE); Name: 'claViolet'), (Value: Integer($FFF5DEB3); Name: 'claWheat'), (Value: Integer($FFFFFFFF); Name: 'claWhite'), (Value: Integer($FFF5F5F5); Name: 'claWhitesmoke'), (Value: Integer($FFFFFF00); Name: 'claYellow'), (Value: Integer($FF9ACD32); Name: 'claYellowgreen'), (Value: Integer($0); Name: 'claNull') ); { TAlphaColor string functions } procedure GetAlphaColorValues(Proc: TGetStrProc); var I: Integer; begin for I := Low(AlphaColors) to High(AlphaColors) do Proc(AlphaColorToString(TAlphaColor(AlphaColors[I].Value))); end; function AlphaColorToString(Value: TAlphaColor): string; begin AlphaColorToIdent(Longint(Value), Result); if Result[1] = 'x' then Result[1] := '#' else Delete(Result, 1, 3); end; function StringToAlphaColor(const Value: string): TAlphaColor; var LValue: string; LColor: Longint; begin LValue := Value; if LValue = #0 then LValue := '$0' else if (LValue <> '') and ((LValue[1] = '#') or (LValue[1] = 'x')) then LValue[1] := '$'; if (not IdentToAlphaColor('cla' + LValue, LColor)) and (not IdentToAlphaColor(LValue, LColor)) then Result := TAlphaColor(StrToInt64(LValue)) else Result := TAlphaColor(LColor); end; function AlphaColorToIdent(Color: Longint; var Ident: string): Boolean; begin Result := IntToIdent(Color, Ident, AlphaColors); if not Result then begin Ident := 'x' + IntToHex(Color, 8); Result := True; end; end; function IdentToAlphaColor(const Ident: string; var Color: Longint): Boolean; var LIdent: string; begin LIdent := Ident; if (Length(LIdent) > 0) and (LIdent[1] = 'x') then begin Color := Longint(StringToAlphaColor(LIdent)); Result := True; end else Result := IdentToInt(LIdent, Color, AlphaColors); // Allow "clXXXX" constants and convert it to TAlphaColor if not Result and (Length(LIdent) > 3) then begin Insert('a', LIdent, 3); Result := IdentToInt(LIdent, Longint(Color), AlphaColors); end; end; procedure RegisterAlphaColorIntegerConsts; begin if not Assigned(FindIntToIdent(TypeInfo(TAlphaColor))) then RegisterIntegerConsts(TypeInfo(TAlphaColor), IdentToAlphaColor, AlphaColorToIdent); end; end.
unit googledocs; {$mode objfpc}{$H+} interface uses Classes, SysUtils, sqlite3ds, otlog, configuration, utils, dateutils, spreadsheet, httpsend, synautil, ssl_openssl; type TStorageGoogleDocs = class(TThread) private CacheSS: Tstringlist; CacheWS: Tstringlist; CacheDocs: string; GAuthDocs: string; GAuthSpreadSheets: string; procedure CreateCache; function GetGAuthDocs:boolean; function GetGAuthSpreadSheets: boolean; function GetSSKey(timestart: string):string; function GetWSKey(timestart: string; spreadsheetkey: string):string; function AddRow(spreadsheetkey,worksheetkey:string; row: TSRow):boolean; public LOG: totlog; CFG: Totconfig; DB: TSqlite3Dataset; procedure Execute; override; Constructor Create(CreateSuspended: boolean; lLOG: totlog; lCFG: Totconfig; lDB: TSqlite3Dataset); end; implementation Constructor TStorageGoogleDocs.Create(CreateSuspended : boolean; lLOG: totlog; lCFG: Totconfig; lDB: TSqlite3Dataset); begin LOG := lLOG; CFG := lCFG;; DB := lDB; CacheDocs := ''; FreeOnTerminate := True; inherited Create(CreateSuspended); end; procedure TStorageGoogleDocs.CreateCache; var ldb: TSqlite3Dataset; begin lDB := TSqlite3Dataset.Create(DB.Owner); lDB.FileName:=DB.FileName; CacheSS := TStringList.Create; try lDB.SQL := 'SELECT * FROM storedata_gdss'; try lDB.Open; IF lDB.RecordCount > 0 THEN BEGIN lDB.first; WHILE (NOT Terminated) AND (NOT lDB.EOF) DO BEGIN CacheSS.Add(lDB.FieldByName('name').AsString+'='+lDB.FieldByName('key').AsString); lDB.Next; END; END; finally lDB.close; end; except on E: Exception do Log.add('Exception: '+E.ClassName+' '+E.Message); end; CacheWS := TStringList.Create; try lDB.SQL := 'SELECT * FROM storedata_gdws'; try lDB.Open; IF lDB.RecordCount > 0 THEN BEGIN lDB.first; WHILE (NOT Terminated) AND (NOT lDB.EOF) DO BEGIN CacheWS.Add(lDB.FieldByName('sskey').AsString+'_'+lDB.FieldByName('name').AsString+'='+lDB.FieldByName('key').AsString); lDB.Next; END; END; finally lDB.close; end; except on E: Exception do Log.add('Exception: '+E.ClassName+' '+E.Message); end; end; function TStorageGoogleDocs.GetGAuthDocs:boolean; var HTTP: THTTPSend; xmldata: string; rtmp: boolean; begin rtmp := false; Log.Add('GoogleDocs: Trying to get a valid Auth Docs Key'); HTTP := THTTPSend.Create; try WriteStrToStream(HTTP.Document, 'accountType=GOOGLE&Email='+CFG.Get('GoogledocsUsername')+'&Passwd='+CFG.Get('GoogleDocsPassword')+'&service=writely&source=openTempus'); HTTP.MimeType := 'application/x-www-form-urlencoded'; if HTTP.HTTPMethod('POST', 'https://www.google.com/accounts/ClientLogin') then begin xmldata := ReadStrFromStream(HTTP.Document,HTTP.Document.Size); Log.Add(xmldata); IF(Pos('Auth=',xmldata) > 0) THEN BEGIN Log.Add('GoogleDocs: Succes obtaining a Valid Auth Key'); rtmp := true; END ELSE Log.Add('GoogleDocs: Unable to obtain Valid Auth Key'); end ELSE Log.Add('GoogleDocs: Unable to obtain Valid Auth Key'); finally HTTP.Free; end; result := rtmp; end; function TStorageGoogleDocs.GetGAuthSpreadSheets: boolean; var HTTP: THTTPSend; xmldata: string; rtmp: boolean; begin rtmp := false; Log.Add('GoogleDocs: Trying to get a valid Auth SpreadSheet Key'); HTTP := THTTPSend.Create; try WriteStrToStream(HTTP.Document, 'accountType=GOOGLE&Email='+CFG.Get('GoogledocsUsername')+'&Passwd='+CFG.Get('GoogleDocsPassword')+'&service=wise&source=openTempus'); HTTP.MimeType := 'application/x-www-form-urlencoded'; if HTTP.HTTPMethod('POST', 'https://www.google.com/accounts/ClientLogin') then begin xmldata := ReadStrFromStream(HTTP.Document,HTTP.Document.Size); Log.Add(xmldata); IF(Pos('Auth=',xmldata) > 0) THEN BEGIN Log.Add('GoogleDocs: Succes obtaining a Valid Auth Key'); rtmp := true; END ELSE Log.Add('GoogleDocs: Unable to obtain Valid SpreadSheet Key'); end ELSE Log.Add('GoogleDocs: Unable to obtain Valid SpreadSheet Key'); finally HTTP.Free; end; result := rtmp; end; function TStorageGoogleDocs.GetSSKey(timestart: string):string; var HTTP: THTTPSend; xmldata: string; filename: string; rtmp: string; dateparts: tstringlist; week: integer; gauthavailable: boolean; begin rtmp := ''; dateparts := tstringlist.create; IF CFG.GET('GoogleDocsSpreadsheet') = 'Each Day' THEN BEGIN Split(' ',timestart,dateparts); filename := dateparts.Strings[0]; END ELSE IF CFG.GET('GoogleDocsSpreadsheet') = 'Each Week' THEN BEGIN Split(' ',timestart,dateparts); Split('-',dateparts[0],dateparts); week := WeekOfTheYear(EncodeDateTime(StrToInt(dateparts[0]),StrToInt(dateparts[1]),StrToInt(dateparts[2]),0,0,0,0)); filename := dateparts[0]+'_week_'+inttostr(week); END ELSE IF CFG.GET('GoogleDocsSpreadsheet') = 'Each Month' THEN BEGIN Split(' ',timestart,dateparts); Split('-',dateparts[0],dateparts); filename := dateparts[0]+'_month_'+dateparts[1]; END ELSE IF CFG.GET('GoogleDocsSpreadsheet') = 'Each Year' THEN BEGIN Split(' ',timestart,dateparts); Split('-',dateparts[0],dateparts); filename := dateparts[0]; END; filename := 'opentempus_'+filename; // Check cache IF CacheWS.IndexOfName(filename) > -1 THEN BEGIN rtmp := CacheWS.Values[filename]; END ELSE BEGIN IF CacheDocs = '' THEN BEGIN HTTP := THTTPSend.Create; try Log.Add('GoogleDocs: Trying to obtain list of spreadsheets'); HTTP.Headers.Add('Authorization: GoogleLogin auth='+GAuthSpreadSheets); if HTTP.HTTPMethod('GET', 'http://spreadsheets.google.com/feeds/spreadsheets/private/full') then begin xmldata := ReadStrFromStream(HTTP.Document,HTTP.Document.Size); Log.Add(xmldata); IF(Pos(filename+'<',xmldata) > 0) THEN BEGIN CacheDocs := xmldata; Log.Add('GoogleDocs: Succes obtaining a list of spreadsheets'); END ELSE Log.Add('GoogleDocs: Unable to obtain list of spreadsheets'); end ELSE Log.Add('GoogleDocs: Unable to obtain a list of spreadsheets'); finally HTTP.Free; end; END; // Create a new SpreadSheet and WorkSheet // PENDIENTE HTTP := THTTPSend.Create; try WriteStrToStream(HTTP.Document, 'col1,col2,col3'); HTTP.Headers.Add('Slug: '+filename); HTTP.Headers.Add('Authorization: GoogleLogin auth='+GAuthDocs); HTTP.MimeType := 'text/csv'; if HTTP.HTTPMethod('POST', 'http://docs.google.com/feeds/documents/private/full') then begin xmldata := ReadStrFromStream(HTTP.Document,HTTP.Document.Size); Log.Add(xmldata); IF(Pos('Auth=',xmldata) > 0) THEN BEGIN Log.Add('GoogleDocs: Succes obtaining a Valid Auth Key'); rtmp := ''; END ELSE Log.Add('GoogleDocs: Unable to obtain Valid Auth Key'); end ELSE Log.Add('GoogleDocs: Unable to create a WorkSheet'); finally HTTP.Free; end; END; result := rtmp; end; function TStorageGoogleDocs.GetWSKey(timestart: string; spreadsheetkey: string):string; begin result := ''; end; function TStorageGoogleDocs.AddRow(spreadsheetkey,worksheetkey:string; row: TSRow):boolean; begin result := false; end; procedure TStorageGoogleDocs.Execute; var rows: array of TSRow; i: integeR; spreadsheetkey, worksheetkey: string; lDB: TSqlite3Dataset; begin lDB := TSqlite3Dataset.Create(DB.Owner); lDB.FileName:=DB.FileName; Log.Add('Starting GoogleDocs storage'); i := 0; try lDB.SQL := 'SELECT idwp, t.seconds, strftime("%Y-%m-%d %H:%M:%S",dtimestart) as ts, strftime("%Y-%m-%d %H:%M:%S",dtimeend) as te, '+'w.title, p.name FROM storedata_wpt wpt, wp_track t, windows w, processes p WHERE wpt.idwp = t.id AND wpt.savegoogledocs = 0 AND t.idw = w.id AND t.idp = p.id'; try lDB.Open; IF lDB.RecordCount > 0 THEN BEGIN SetLength(rows, lDB.RecordCount); lDB.first; WHILE (NOT Terminated) AND (NOT lDB.EOF) DO BEGIN rows[i].idwp := lDB.FieldByName('idwp').AsInteger; rows[i].seconds := lDB.FieldByName('seconds').AsInteger; rows[i].timestart := lDB.FieldByName('ts').AsString; rows[i].timeend := lDB.FieldByName('te').AsString; rows[i].windowtitle := lDB.FieldByName('title').AsString; rows[i].processname := lDB.FieldByName('name').AsString; Inc(i); lDB.Next; END; END; finally lDB.close; end; except on E: Exception do Log.add('Exception: '+E.ClassName+' '+E.Message); end; IF (Length(rows) > 0) AND (GetGAuthSpreadSheets) THEN BEGIN i := 0; CreateCache; WHILE (NOT Terminated) AND (i < Length(rows) - 1) DO BEGIN spreadsheetkey := GetSSKey(rows[i].timestart); IF spreadsheetkey <> '' THEN BEGIN worksheetkey := GetWSKey(rows[i].timestart, spreadsheetkey); IF (worksheetkey <> '') AND (addrow(spreadsheetkey,worksheetkey, rows[i])) THEN BEGIN try lDB.ExecSQL('UPDATE storedata_wpt SET savespreadsheet = 1 WHERE idwp = '+inttostr(rows[i].idwp)); except on E: Exception do Log.add('Exception: '+E.ClassName+' '+E.Message); end; END; END; Inc(i); END; END; Log.Add('Finished GoogleDocs storage'); end; end.
{: GLRagdoll<p> Base abstract ragdoll class. Should be extended to use any physics system. <p> <b>History :</b><font size=-1><ul> <li>10/11/12 - PW - Added CPP compatibility: changed vector arrays to arrays of records <li>23/08/10 - Yar - Added GLVectorTypes to uses <li>09/11/05 - LucasG - Fixed joint and few small things <li>07/11/05 - LucasG - Fixed bone position and rotation (Align to animation) <li>02/11/05 - LucasG - First version created. </ul></font> } unit GLRagdoll; interface uses GLScene, GLPersistentClasses, GLVectorGeometry, GLVectorFileObjects, GLVectorLists, GLObjects; type TGLRagdoll = class; TRagdollBone = class; TRagdollJoint = class end; TRagdollBoneList = class (TPersistentObjectList) private { Private Declarations } FRagdoll : TGLRagdoll; protected { Protected Declarations } function GetRagdollBone(Index: Integer) : TRagdollBone; public { Public Declarations } constructor Create(Ragdoll: TGLRagdoll); reintroduce; destructor Destroy; override; procedure WriteToFiler(writer : TVirtualWriter); override; procedure ReadFromFiler(reader : TVirtualReader); override; property Ragdoll : TGLRagdoll read FRagdoll; property Items[Index: Integer] : TRagdollBone read GetRagdollBone; default; end; TRagdollBone = class (TRagdollBoneList) private { Private Declarations } FOwner : TRagdollBoneList; FName : String; FBoneID : Integer; //Refering to TGLActor Bone FBoundMax: TAffineVector; FBoundMin: TAffineVector; FBoundBoneDelta: TAffineVector; //Stores the diference from the bone.GlobalMatrix to the center of the bone's bounding box FOrigin: TAffineVector; FSize: TAffineVector; FBoneMatrix: TMatrix; FJoint: TRagdollJoint; FOriginalMatrix: TMatrix; //Stores the Bone.GlobalMatrix before the ragdoll start FReferenceMatrix: TMatrix; //Stores the first bone matrix to be used as reference FAnchor: TAffineVector; //The position of the joint procedure CreateBoundingBox; procedure SetAnchor(Anchor: TAffineVector); procedure AlignToSkeleton; procedure CreateBoundsChild; procedure StartChild; procedure AlignChild; procedure UpdateChild; procedure StopChild; protected { Protected Declarations } function GetRagdollBone(Index: Integer) : TRagdollBone; procedure Start; virtual; abstract; procedure Align; virtual; abstract; procedure Update; virtual; abstract; procedure Stop; virtual; abstract; public { Public Declarations } constructor CreateOwned(aOwner : TRagdollBoneList); constructor Create(Ragdoll: TGLRagdoll); destructor Destroy; override; procedure WriteToFiler(writer : TVirtualWriter); override; procedure ReadFromFiler(reader : TVirtualReader); override; property Owner : TRagdollBoneList read FOwner; property Name : String read FName write FName; property BoneID : Integer read FBoneID write FBoneID; property Origin : TAffineVector read FOrigin; property Size : TAffineVector read FSize; property BoneMatrix : TMatrix read FBoneMatrix; property ReferenceMatrix : TMatrix read FReferenceMatrix; property Anchor : TAffineVector read FAnchor; property Joint : TRagdollJoint read FJoint write FJoint; property Items[Index: Integer] : TRagdollBone read GetRagdollBone; default; end; TGLRagdoll = class(TPersistentObject) private { Private Declarations } FOwner : TGLBaseMesh; FRootBone : TRagdollBone; FEnabled: Boolean; FBuilt: Boolean; protected { Protected Declarations } public { Public Declarations } constructor Create(AOwner : TGLBaseMesh); reintroduce; destructor Destroy; override; procedure WriteToFiler(writer : TVirtualWriter); override; procedure ReadFromFiler(reader : TVirtualReader); override; {: Must be set before build the ragdoll } procedure SetRootBone(RootBone: TRagdollBone); {: Create the bounding box and setup the ragdoll do be started later } procedure BuildRagdoll; procedure Start; procedure Update; procedure Stop; property Owner : TGLBaseMesh read FOwner; property RootBone : TRagdollBone read FRootBone; property Enabled : Boolean read FEnabled; end; implementation uses GLVectorTypes; { TRagdollBoneList } constructor TRagdollBoneList.Create(Ragdoll: TGLRagdoll); begin inherited Create; FRagdoll := Ragdoll; end; destructor TRagdollBoneList.Destroy; var i: integer; begin for i:=0 to Count-1 do Items[i].Destroy; inherited; end; function TRagdollBoneList.GetRagdollBone(Index: Integer): TRagdollBone; begin Result:=TRagdollBone(List^[Index]); end; procedure TRagdollBoneList.ReadFromFiler(reader: TVirtualReader); begin inherited; //Not implemented end; procedure TRagdollBoneList.WriteToFiler(writer: TVirtualWriter); begin inherited; //Not implemented end; { TRagdollBone } constructor TRagdollBone.Create(Ragdoll: TGLRagdoll); begin inherited Create(Ragdoll); end; procedure TRagdollBone.CreateBoundingBox; var bone: TSkeletonBone; i, j: integer; BoneVertices : TAffineVectorList; BoneVertex, max,min: TAffineVector; invMat, mat: TMatrix; begin bone := Ragdoll.Owner.Skeleton.BoneByID(FBoneID); //Get all vertices weighted to this bone BoneVertices:=TAffineVectorList.Create; for i:=0 to Ragdoll.Owner.MeshObjects.Count-1 do with TSkeletonMeshObject(Ragdoll.Owner.MeshObjects[i]) do for j:=0 to Vertices.Count-1 do if bone.BoneID = VerticesBonesWeights[j][0].BoneID then BoneVertices.FindOrAdd(Vertices[j]); invMat := bone.GlobalMatrix; InvertMatrix(invMat); //For each vertex, get the max and min XYZ (Bounding box) if BoneVertices.Count > 0 then begin BoneVertex := VectorTransform(BoneVertices[0], invMat); max := BoneVertex; min := BoneVertex; for i:=1 to BoneVertices.Count-1 do begin BoneVertex := VectorTransform(BoneVertices[i], invMat); if (BoneVertex.V[0] > max.V[0]) then max.V[0] := BoneVertex.V[0]; if (BoneVertex.V[1] > max.V[1]) then max.V[1] := BoneVertex.V[1]; if (BoneVertex.V[2] > max.V[2]) then max.V[2] := BoneVertex.V[2]; if (BoneVertex.V[0] < min.V[0]) then min.V[0] := BoneVertex.V[0]; if (BoneVertex.V[1] < min.V[1]) then min.V[1] := BoneVertex.V[1]; if (BoneVertex.V[2] < min.V[2]) then min.V[2] := BoneVertex.V[2]; end; FBoundMax := max; FBoundMin := min; //Get the origin and subtract from the bone matrix FBoundBoneDelta := VectorScale(VectorAdd(FBoundMax, FBoundMin), 0.5); end else begin FBoundMax := NullVector; FBoundMin := NullVector; end; AlignToSkeleton; FReferenceMatrix := FBoneMatrix; mat := MatrixMultiply(bone.GlobalMatrix,FRagdoll.Owner.AbsoluteMatrix); //Set Joint position SetAnchor(AffineVectorMake(mat.V[3])); BoneVertices.Free; // NEW1 end; constructor TRagdollBone.CreateOwned(aOwner: TRagdollBoneList); begin Create(aOwner.Ragdoll); FOwner:=aOwner; aOwner.Add(Self); end; destructor TRagdollBone.Destroy; begin inherited; end; procedure TRagdollBone.AlignToSkeleton; var o: TAffineVector; bone: TSkeletonBone; mat, posMat: TMatrix; noBounds: Boolean; begin bone := Ragdoll.Owner.Skeleton.BoneByID(FBoneID); noBounds := VectorIsNull(FBoundMax) and VectorIsNull(FBoundMin); //Get the bone matrix relative to the Actor matrix mat := MatrixMultiply(bone.GlobalMatrix,FRagdoll.Owner.AbsoluteMatrix); //Set Rotation FBoneMatrix := mat; NormalizeMatrix(FBoneMatrix); if (noBounds) then begin FOrigin := AffineVectorMake(mat.V[3]); FSize := AffineVectorMake(0.1,0.1,0.1); end else begin //Set Origin posMat := mat; posMat.V[3] := NullHmgVector; o := VectorTransform(FBoundBoneDelta, posMat); FOrigin := VectorAdd(AffineVectorMake(mat.V[3]), o); //Set Size FSize := VectorScale(VectorSubtract(FBoundMax, FBoundMin),0.9); FSize.V[0] := FSize.V[0]*VectorLength(mat.V[0]); FSize.V[1] := FSize.V[1]*VectorLength(mat.V[1]); FSize.V[2] := FSize.V[2]*VectorLength(mat.V[2]); end; //Put the origin in the BoneMatrix FBoneMatrix.V[3] := VectorMake(FOrigin,1); end; function TRagdollBone.GetRagdollBone(Index: Integer): TRagdollBone; begin Result:=TRagdollBone(List^[Index]); end; procedure TRagdollBone.ReadFromFiler(reader: TVirtualReader); begin inherited; end; procedure TRagdollBone.StartChild; var i: integer; begin FOriginalMatrix := Ragdoll.Owner.Skeleton.BoneByID(FBoneID).GlobalMatrix; AlignToSkeleton; Start; for i := 0 to Count-1 do items[i].StartChild; end; procedure TRagdollBone.UpdateChild; var i: integer; begin Update; for i := 0 to Count-1 do items[i].UpdateChild; end; procedure TRagdollBone.WriteToFiler(writer: TVirtualWriter); begin inherited; end; procedure TRagdollBone.StopChild; var i: integer; begin Stop; Ragdoll.Owner.Skeleton.BoneByID(FBoneID).SetGlobalMatrix(FOriginalMatrix); for i := 0 to Count-1 do items[i].StopChild; end; procedure TRagdollBone.CreateBoundsChild; var i: integer; begin CreateBoundingBox; for i := 0 to Count-1 do items[i].CreateBoundsChild; end; procedure TRagdollBone.SetAnchor(Anchor: TAffineVector); begin FAnchor := Anchor; end; procedure TRagdollBone.AlignChild; var i: integer; begin Align; Update; for i := 0 to Count-1 do items[i].AlignChild; end; { TGLRagdoll } constructor TGLRagdoll.Create(AOwner : TGLBaseMesh); begin FOwner := AOwner; FEnabled := False; FBuilt := False; end; destructor TGLRagdoll.Destroy; begin if FEnabled then Stop; inherited Destroy; end; procedure TGLRagdoll.ReadFromFiler(reader: TVirtualReader); begin inherited; end; procedure TGLRagdoll.SetRootBone(RootBone: TRagdollBone); begin FRootBone := RootBone; end; procedure TGLRagdoll.Start; begin Assert(FBuilt, 'First you need to build the ragdoll. BuildRagdoll;'); if (FEnabled) then Exit; FEnabled:= True; //First start the ragdoll in the reference position RootBone.StartChild; //Now align it to the animation RootBone.AlignChild; //Now it recalculate the vertices to use as reference FOwner.Skeleton.StartRagDoll; end; procedure TGLRagdoll.Update; begin if FEnabled then begin RootBone.UpdateChild; FOwner.Skeleton.MorphMesh(true); end; end; procedure TGLRagdoll.Stop; begin if not FEnabled then Exit; FEnabled := False; RootBone.StopChild; //Restore the old information FOwner.Skeleton.StopRagDoll; FOwner.Skeleton.MorphMesh(true); end; procedure TGLRagdoll.WriteToFiler(writer: TVirtualWriter); begin inherited; end; procedure TGLRagdoll.BuildRagdoll; begin Assert(RootBone <> nil, 'First you need to set the root bone. SetRootBone();'); RootBone.CreateBoundsChild; FBuilt := True; end; end.
{***********************************<_INFO>************************************} { <Проект> Компоненты медиа-преобразования } { } { <Область> Мультимедиа } { } { <Задача> Преобразователь медиа-потока в формате BMP. Стабилизирует } { дрожание кадров } { Декларация } { } { <Автор> Фадеев Р.В. } { } { <Дата> 21.01.2011 } { } { <Примечание> Отсутствует } { } { <Атрибуты> ООО НПП "Спецстрой-Связь", ООО "Трисофт" } { } {***********************************</_INFO>***********************************} unit MediaProcessing.Stabilizer.RGB; interface uses SysUtils,Windows,Classes, MediaProcessing.Definitions,MediaProcessing.Global,Graphics; type TMediaProcessor_Stabilizer_Rgb=class (TMediaProcessor,IMediaProcessor_Stabilizer_Rgb) protected FBuildImageOutOfBorders: boolean; FDetectMovements: boolean; FDetectMovementsPeriod: integer; procedure SaveCustomProperties(const aWriter: IPropertiesWriter); override; procedure LoadCustomProperties(const aReader: IPropertiesReader); override; class function MetaInfo:TMediaProcessorInfo; override; public constructor Create; override; destructor Destroy; override; function HasCustomProperties: boolean; override; procedure ShowCustomProperiesDialog;override; end; implementation uses Controls,uBaseClasses,MediaProcessing.Stabilizer.RGB.SettingsDialog; { TMediaProcessor_Stabilizer_Rgb } constructor TMediaProcessor_Stabilizer_Rgb.Create; begin inherited; end; destructor TMediaProcessor_Stabilizer_Rgb.Destroy; begin inherited; end; function TMediaProcessor_Stabilizer_Rgb.HasCustomProperties: boolean; begin result:=true; end; class function TMediaProcessor_Stabilizer_Rgb.MetaInfo: TMediaProcessorInfo; begin result.Clear; result.TypeID:=IMediaProcessor_Stabilizer_Rgb; result.Name:='Стабилизатор'; result.Description:='Выполняет стабилизацию кадров в случае дрожания изображения'; result.SetInputStreamType(stRGB); result.OutputStreamType:=stRGB; result.ConsumingLevel:=9; end; procedure TMediaProcessor_Stabilizer_Rgb.LoadCustomProperties(const aReader: IPropertiesReader); begin inherited; FBuildImageOutOfBorders:=aReader.ReadBool('BuildImageOutOfBorders',true); FDetectMovements:=aReader.ReadBool('DetectMovements',true); FDetectMovementsPeriod:=aReader.ReadInteger('DetectMovementsPeriod',10); end; procedure TMediaProcessor_Stabilizer_Rgb.SaveCustomProperties(const aWriter: IPropertiesWriter); begin inherited; aWriter.WriteBool('BuildImageOutOfBorders',FBuildImageOutOfBorders); aWriter.WriteBool('DetectMovements',FDetectMovements); aWriter.WriteInteger('DetectMovementsPeriod',FDetectMovementsPeriod); end; procedure TMediaProcessor_Stabilizer_Rgb.ShowCustomProperiesDialog; var aDialog: TfmStabilizer_Rgb_Settings; begin aDialog:=TfmStabilizer_Rgb_Settings.Create(nil); try aDialog.ckBuildImageOutOfBorders.Checked:=FBuildImageOutOfBorders; aDialog.ckDetectMovements.Checked:=FDetectMovements; aDialog.edMovementPeriod.Value:=FDetectMovementsPeriod; if aDialog.ShowModal=mrOK then begin FBuildImageOutOfBorders:=aDialog.ckBuildImageOutOfBorders.Checked; FDetectMovements:=aDialog.ckDetectMovements.Checked; FDetectMovementsPeriod:=aDialog.edMovementPeriod.Value; end; finally aDialog.Free; end; end; initialization MediaProceccorFactory.RegisterMediaProcessor(TMediaProcessor_Stabilizer_Rgb); end.
{*******************************************************} { } { Delphi DBX Framework } { Copyright(c) 2012-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$HPPEMIT LINKUNIT} unit Data.DBXSqliteReadOnlyMetaData; interface uses Data.DBXMetaDataCommandFactory, Data.DBXMetaDataReader; type TDBXSqliteMetaDataCommandFactory = class(TDBXMetaDataCommandFactory) public function CreateMetaDataReader: TDBXMetaDataReader; override; end; implementation uses Data.DBXSqliteMetaDataReader; function TDBXSqliteMetaDataCommandFactory.CreateMetaDataReader: TDBXMetaDataReader; begin Result := TDBXSqliteMetaDataReader.Create; end; initialization TDBXMetaDataCommandFactory.RegisterMetaDataCommandFactory(TDBXSqliteMetaDataCommandFactory); finalization TDBXMetaDataCommandFactory.UnRegisterMetaDataCommandFactory(TDBXSqliteMetaDataCommandFactory); end.
unit GameService_Impl; {$I RemObjects.inc} interface uses System.SysUtils, System.Classes, System.TypInfo, uROXMLIntf, uROClientIntf, uROClasses, uROTypes, uROServer, uROServerIntf, uROSessions, uRORemoteDataModule, uRORTTIAttributes, uRORTTIServerSupport, uROArray; {$REGION 'brief info for Code-First Services'} (* set library name, uid, namespace, documentation: uRORTTIServerSupport.RODLLibraryName := 'LibraryName'; uRORTTIServerSupport.RODLLibraryID := '{2533A58A-49D9-47CC-B77A-FFD791F425BE}'; uRORTTIServerSupport.RODLLibraryNamespace := 'namespace'; uRORTTIServerSupport.RODLLibraryDocumentation := 'documentation'; mandatory identificators for services/methods/event sinks: [ROService('name')] - name parameter is optional [ROServiceMethod('name')] - name parameter is optional [ROEventSink('name')] - name parameter is optional (optional) class factory - service attribute, only one should be used [ROStandardClassFactory] - used by default [ROSingletonClassFactory] [ROSynchronizedSingletonClassFactory] [ROPooledClassFactory(PoolSize,PoolBehavior,PreInitializePool)] - only 1st param is mandatore [ROPerClientClassFactory(TimeoutSeconds)] other (optional) attributes: [ROAbstract] - Marks the service as abstract. it cannot be called directly (service only) [ROServiceRequiresLogin] - Sets the 'RequiresSession' property to true at runtime. (service only) [RORole('role')] - allow role (service&service methods only) [RORole('!role')] - deny role, (service&service methods only) [ROSkip] - for excluding type at generting RODL for clientside [ROCustom('myname','myvalue')] - custom attributes [RODocumentation('documentation')] - documentation [ROObsolete] - add "obsolete" message into documentation [ROObsolete('custom message')] - add specified message into documentation [ROEnumSoapName(EntityName,SoapEntityName)] - soap mapping. multiple (enums only) serialization mode for properties, method parameters, arrays and service's functions results [ROStreamAs(Ansi)] [ROStreamAs(UTF8)] backward compatibility attributes: [ROSerializeAsAnsiString] - alias for [ROStreamAs(Ansi)] [ROSerializeAsUTF8String] - alias for [ROStreamAs(UTF8)] [ROSerializeResultAsAnsiString] - alias for [ROStreamAs(Ansi)] [ROSerializeResultAsUTF8String] - alias for [ROStreamAs(UTF8)] *) {$ENDREGION} {$REGION 'examples'} (* [ROEnumSoapName('sxFemale','soap_sxFemale')] [ROEnumSoapName('sxMale','soap_sxMale')] TSex = ( sxMale, sxFemale ); TMyStruct = class(TROComplexType) private fA: Integer; published property A :Integer read fA write fA; [ROStreamAs(UTF8)] property AsUtf8: String read fAsUtf8 write fAsUtf8; end; TMyStructArray = class(TROArray<TMyStruct>); [ROStreamAs(UTF8)] TMyUTF8Array = class(TROArray<String>); [ROEventSink] IMyEvents = interface(IROEventSink) ['{75F9A466-518A-4B09-9DC4-9272B1EEFD95}'] procedure OnMyEvent([ROStreamAs(Ansi)] const aStr: String); end; [ROService('MyService')] TMyService = class(TRORemoteDataModule) private public [ROServiceMethod] [ROStreamAs(Ansi)] function Echo([ROStreamAs(Ansi)] const aValue: string):string; end; simple usage of event sinks: //ev: IROEventWriter<IMyEvents>; .. ev := EventRepository.GetWriter<IMyEvents>(Session.SessionID); ev.Event.OnMyEvent('Message'); for using custom class factories, use these attributes: [ROSingletonClassFactory] [ROSynchronizedSingletonClassFactory] [ROPooledClassFactory(PoolSize,PoolBehavior,PreInitializePool)] [ROPerClientClassFactory(TimeoutSeconds)] or replace ----------- initialization RegisterCodeFirstService(TNewService1); end. ----------- with ----------- procedure Create_NewService1(out anInstance : IUnknown); begin anInstance := TNewService1.Create(nil); end; var fClassFactory: IROClassFactory; initialization fClassFactory := TROClassFactory.Create(__ServiceName, Create_NewService1, TRORTTIInvoker); //RegisterForZeroConf(fClassFactory, Format('_TRORemoteDataModule_rosdk._tcp.',[__ServiceName])); finalization UnRegisterClassFactory(fClassFactory); fClassFactory := nil; end. ----------- *) {$ENDREGION} const __ServiceName = 'GameService'; type [ROService(__ServiceName)] TGameService = class(TRORemoteDataModule) private public // [ROServiceMethod] // procedure NewMethod; [ROServiceMethod] function Helloworld: string; end; implementation {%CLASSGROUP 'System.Classes.TPersistent'} {$R *.dfm} { TGameService } function TGameService.Helloworld: string; begin Result := 'hellworld' end; initialization RegisterCodeFirstService(TGameService); end.
{geovar.pas:} null2d : vt2d; null3d : vt3d; {Nullvektoren} scalefactor: real; {**fuer area_2d and curve2d:} origin2d : vt2d; {**fuer Parallel- und Zentral-Projektion:} u_angle,v_angle, {Projektionswinkel} rad_u,rad_v, {rad(u), rad(v)} sin_u,cos_u,sin_v,cos_v : real; {sin-,cos- Werte von u, v} e1vt,e2vt,n0vt : vt3d; {Basis-Vektoren} {Normalen-Vektor der Bildebene} {**fuer Zentral-Projektion:} mainpt, {Hauptpunkt} centre : vt3d; {Zentrum} distance : real; {Distanz Hauptpunkt-Zentrum}
unit ufrmTestToolbar; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, umyToolbars, System.Actions, Vcl.ActnList, Vcl.ImgList, Vcl.ComCtrls, Vcl.ToolWin, Vcl.StdCtrls, types; type TForm24 = class(TForm) ActionList1: TActionList; ImageList1: TImageList; Action1: TAction; Action2: TAction; Action3: TAction; Action4: TAction; ToolBar1: TToolBar; ToolButton1: TToolButton; ToolButton2: TToolButton; ToolButton3: TToolButton; ToolButton4: TToolButton; Button1: TButton; Action5: TAction; Memo1: TMemo; procedure FormCreate(Sender: TObject); procedure Action1Execute(Sender: TObject); procedure Action2Execute(Sender: TObject); procedure Action3Execute(Sender: TObject); procedure Action5Execute(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } FToolbar: TmyToolbar; public { Public declarations } end; var Form24: TForm24; implementation {$R *.dfm} type TacAction = class(TBasicAction); procedure PrintMsg(const Msg:string); overload; begin Form24.Memo1.Lines.Add(Msg); end; procedure PrintMsg(const AFormat: string; const Args: array of const); overload; begin PrintMsg(Format(AFormat, Args)); end; procedure TForm24.FormCreate(Sender: TObject); begin FToolbar := TmyToolbar.Create(Self); FToolbar.ShowHint := True; FToolbar.Parent := Self; FToolbar.Height := 30; FToolbar.Left := 100; FToolbar.Top := 100; //FToolbar.color := clSilver; FToolbar.Add(Action1); FToolbar.Add(Action2); FToolbar.Add(Action3); FToolbar.Add(Action5); FToolbar.Add(Action4); end; procedure TForm24.Action1Execute(Sender: TObject); begin Tag := Tag + 1; Caption := Format('Test %d', [tag]); end; procedure TForm24.Action2Execute(Sender: TObject); begin Action1.Visible := not Action1.Visible; if Action1.Visible then Action2.ImageIndex := 2 else Action2.ImageIndex := 1; end; procedure TForm24.Action3Execute(Sender: TObject); begin Action1.Enabled := not Action1.Enabled; end; procedure TForm24.Action5Execute(Sender: TObject); begin if Action1.ImageIndex < ImageList1.Count - 1 then Action1.ImageIndex := Action1.ImageIndex + 1 else Action1.ImageIndex := 0; end; procedure TForm24.Button1Click(Sender: TObject); var r: TRect; rFrame: TRect; procedure DrawSkinIndicator(v: TSkinIndicator); begin UISkin.DrawButtonState(canvas.Handle, v, r, 255); OffsetRect(r, r.Width + 2, 0); UISkin.DrawButtonState(canvas.Handle, v, r, 200); OffsetRect(r, r.Width + 2, 0); UISkin.DrawButtonState(canvas.Handle, v, r, 180); OffsetRect(r, r.Width + 2, 0); UISkin.DrawButtonState(canvas.Handle, v, r, 50); OffsetRect(r, r.Width + 2, 0); UISkin.DrawButtonState(canvas.Handle, v, r, 0); end; var cCtrl: TWinControl; begin Repaint; r := Rect(10, 30, 30, 50); rFrame := r; DrawSkinIndicator(siInactive); r := Rect(10, 30, 30, 50); OffsetRect(r, 0, r.Height + 2); DrawSkinIndicator(siHover); r := Rect(10, 30, 30, 50); OffsetRect(r, 0, r.Height + 2); OffsetRect(r, 0, r.Height + 2); DrawSkinIndicator(siHover); rFrame.BottomRight := r.BottomRight; InflateRect(rFrame, 2, 2); OffsetRect(rFrame, -1, -1); canvas.Pen.Color := clBlue; Canvas.MoveTo(rFrame.Left, rFrame.Top); Canvas.LineTo(rFrame.Right, rFrame.Top); Canvas.LineTo(rFrame.Right, rFrame.Bottom); Canvas.LineTo(rFrame.Left, rFrame.Bottom); Canvas.LineTo(rFrame.Left, rFrame.Top); cCtrl := FindVCLWindow(FToolbar.ClientToScreen(Point(10, 10))); if cCtrl = nil then PrintMsg('FToolbar : nil') else PrintMsg('FToolbar : %s', [cCtrl.ClassName]); cCtrl := FindVCLWindow(ToolBar1.ClientToScreen(Point(10, 10))); if cCtrl = nil then PrintMsg('ToolBar1 : nil') else PrintMsg('ToolBar1 : %s', [cCtrl.ClassName]); cCtrl := FindVCLWindow(ToolButton1.ClientToScreen(Point(10, 10))); if cCtrl = nil then PrintMsg('ToolButton1 : nil') else PrintMsg('ToolButton1 : %s', [cCtrl.ClassName]); end; end.
unit ComCtrls; { LLCL - FPC/Lazarus Light LCL based upon LVCL - Very LIGHT VCL ---------------------------- This file is a part of the Light LCL (LLCL). This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. Copyright (c) 2015-2016 ChrisF Based upon the Very LIGHT VCL (LVCL): Copyright (c) 2008 Arnaud Bouchez - http://bouchez.info Portions Copyright (c) 2001 Paul Toth - http://tothpaul.free.fr Version 1.02: Version 1.01: * TWinControl: notifications for child controls modified * TTrackBar: 'Orientation' and 'TickStyle' properties now accessible (design time only) Version 1.00: * File creation. * TProgressBar implemented * TTrackBar implemented * InitCommonControl function added } {$IFDEF FPC} {$define LLCL_FPC_MODESECTION} {$I LLCLFPCInc.inc} // For mode {$undef LLCL_FPC_MODESECTION} {$ENDIF} {$I LLCLOptions.inc} // Options //------------------------------------------------------------------------------ interface uses LLCLOSInt, Windows, {$IFDEF FPC}LCLType, LMessages{$ELSE}Messages{$ENDIF}, Classes, Controls; type TProgressBar = class(TWinControl) private fMin, fMax, fPosition, fStep: integer; procedure SetMin(Value: integer); procedure SetMax(Value: integer); procedure SetRange(ValueMin, ValueMax: integer); function GetPosition(): integer; procedure SetPosition(Value: integer); procedure SetStep(Value: integer); protected procedure CreateHandle; override; procedure CreateParams(var Params: TCreateParams); override; procedure ReadProperty(const PropName: string; Reader: TReader); override; public constructor Create(AOwner: TComponent); override; procedure StepIt; procedure StepBy(Value: integer); property Min: integer read fMin write SetMin; property Max: integer read fMax write SetMax; property Position: integer read GetPosition write SetPosition; property Step: integer read fStep write SetStep; end; type TOrientation = (trHorizontal, trVertical); TTickStyle = (tsAuto, tsManual, tsNone); type TTrackBar = class(TWinControl) private fMin, fMax, fPosition, fFrequency, fLineSize, fPageSize: integer; fOrientation: TOrientation; fTickStyle: TTickStyle; fOnChangeOK: boolean; EOnChange: TNotifyEvent; procedure SetMin(Value: integer); procedure SetMax(Value: integer); procedure SetRange(ValueMin, ValueMax: integer); function GetPosition(): integer; procedure SetPosition(Value: integer); procedure SetFrequency(Value: integer); procedure SetLineSize(Value: integer); procedure SetPageSize(Value: integer); protected procedure CreateHandle; override; procedure CreateParams(var Params: TCreateParams); override; procedure ReadProperty(const PropName: string; Reader: TReader); override; function ComponentNotif(var Msg: TMessage): boolean; override; public constructor Create(AOwner: TComponent); override; property Min: integer read fMin write SetMin; property Max: integer read fMax write SetMax; property Position: integer read GetPosition write SetPosition; property Frequency: integer read fFrequency write SetFrequency; property LineSize: integer read fLineSize write SetLineSize; property PageSize: integer read fPageSize write SetPageSize; property Orientation: TOrientation read fOrientation write fOrientation; // Run-time modification ignored; write present only for dynamical control creation purpose property TickStyle: TTickStyle read fTickStyle write fTickStyle; // Run-time modification ignored; write present only for dynamical control creation purpose property OnChange: TNotifyEvent read EOnChange write EOnChange; end; const ICC_LISTVIEW_CLASSES = $0001; ICC_TREEVIEW_CLASSES = $0002; ICC_BAR_CLASSES = $0004; ICC_TAB_CLASSES = $0008; ICC_UPDOWN_CLASS = $0010; ICC_PROGRESS_CLASS = $0020; ICC_STANDARD_CLASSES = $4000; function InitCommonControl(CC: integer): Boolean; //------------------------------------------------------------------------------ implementation {$IFNDEF FPC} uses CommCtrl; {$ENDIF} {$IFDEF FPC} {$PUSH} {$HINTS OFF} {$ENDIF} //------------------------------------------------------------------------------ {$IFDEF FPC} // Dummy function to avoid compilation hint (LMessages not used) function LMessages_Dummy(const Msg: TLMCommand): boolean; begin result := false; end; {$ENDIF FPC} { TProgressBar } constructor TProgressBar.Create(AOwner: TComponent); begin inherited; ATType := ATTProgressBar; TabStop := false; fMax := 100; fStep := 10; end; procedure TProgressBar.CreateHandle; begin InitCommonControl(ICC_PROGRESS_CLASS); inherited; SetRange(fMin, fMax); SetPosition(fPosition); SetStep(fStep); end; procedure TProgressBar.CreateParams(var Params: TCreateParams); const PROGRESS_CLASS = 'msctls_progress32'; begin inherited; with Params do begin WinClassName := PROGRESS_CLASS; end; end; procedure TProgressBar.ReadProperty(const PropName: string; Reader: TReader); const Properties: array[0..3] of PChar = ( 'Min', 'Max', 'Position', 'Step'); begin case StringIndex(PropName, Properties) of 0 : fMin := Reader.IntegerProperty; 1 : fMax := Reader.IntegerProperty; 2 : fPosition := Reader.IntegerProperty; 3 : fStep := Reader.IntegerProperty; else inherited; end; end; procedure TProgressBar.SetMin(Value: integer); begin SetRange(Value, fMax); end; procedure TProgressBar.SetMax(Value: integer); begin SetRange(fMin, Value); end; procedure TProgressBar.SetRange(ValueMin, ValueMax: integer); begin fMin := ValueMin; fMax := ValueMax; LLCL_SendMessage(Handle, PBM_SETRANGE, 0, LPARAM(fMin or (fMax shl 16))); end; function TProgressBar.GetPosition(): integer; begin fPosition := LLCL_SendMessage(Handle, PBM_GETPOS, 0, 0); result := fPosition; end; procedure TProgressBar.SetPosition(Value: integer); begin fPosition := Value; LLCL_SendMessage(Handle, PBM_SETPOS, WPARAM(fPosition), 0); end; procedure TProgressBar.SetStep(Value: integer); begin fStep := Value; LLCL_SendMessage(Handle, PBM_SETSTEP, WPARAM(fStep), 0); end; procedure TProgressBar.StepIt; begin fPosition := fPosition+fStep; LLCL_SendMessage(Handle, PBM_STEPIT, 0, 0); end; procedure TProgressBar.StepBy(Value: integer); begin SetPosition(fPosition+Value); end; { TTrackBar } constructor TTrackBar.Create(AOwner: TComponent); begin inherited; ATType := ATTTrackBar; ArrowKeysInternal := true; fMax := 10; fFrequency := 1; fLineSize := 1; fPageSize := 2; fTickStyle := tsAuto; end; procedure TTrackBar.CreateHandle; begin InitCommonControl(ICC_BAR_CLASSES); inherited; SetRange(fMin, fMax); SetPosition(fPosition); SetFrequency(fFrequency); SetLineSize(fLineSize); SetPageSize(fPageSize); fOnChangeOK := true; // OnChange is now OK for being activated end; procedure TTrackBar.CreateParams(var Params: TCreateParams); const TRACKBAR_CLASS = 'msctls_trackbar32'; begin inherited; with Params do begin WinClassName := TRACKBAR_CLASS; if fOrientation=trVertical then Style := Style or TBS_VERT; // Else TBS_HORZ =0 case fTickStyle of tsAuto: Style := Style or TBS_AUTOTICKS; tsManual: Style := Style or TBS_BOTH; else Style := Style or TBS_NOTICKS; // Else = tsNone end; Style := Style or TBS_ENABLESELRANGE // Not used, but has an impact on size {$IFDEF FPC};{$ELSE} or TBS_FIXEDLENGTH;{$ENDIF} end; end; procedure TTrackBar.ReadProperty(const PropName: string; Reader: TReader); const Properties: array[0..8] of PChar = ( 'Min', 'Max', 'Position', 'Frequency', 'LineSize', 'PageSize', 'Orientation', 'TickStyle', 'OnChange'); begin case StringIndex(PropName, Properties) of 0 : fMin := Reader.IntegerProperty; 1 : fMax := Reader.IntegerProperty; 2 : fPosition := Reader.IntegerProperty; 3 : fFrequency := Reader.IntegerProperty; 4 : fLineSize := Reader.IntegerProperty; 5 : fPageSize := Reader.IntegerProperty; 6 : Reader.IdentProperty(fOrientation, TypeInfo(TOrientation)); 7 : Reader.IdentProperty(fTickStyle, TypeInfo(TTickStyle)); 8 : TMethod(EOnChange) := FindMethod(Reader); else inherited; end; end; procedure TTrackBar.SetMin(Value: integer); begin SetRange(Value, fMax); end; procedure TTrackBar.SetMax(Value: integer); begin SetRange(fMin, Value); end; procedure TTrackBar.SetRange(ValueMin, ValueMax: integer); begin fMin := ValueMin; fMax := ValueMax; LLCL_SendMessage(Handle, TBM_SETRANGE, 0, LPARAM(fMin or (fMax shl 16))); end; function TTrackBar.GetPosition(): integer; begin fPosition := LLCL_SendMessage(Handle, TBM_GETPOS, 0, 0); result := fPosition; end; procedure TTrackBar.SetPosition(Value: integer); begin fPosition := Value; LLCL_SendMessage(Handle, TBM_SETPOS, WPARAM(fPosition), 0); end; procedure TTrackBar.SetFrequency(Value: integer); begin fFrequency := Value; LLCL_SendMessage(Handle, TBM_SETTICFREQ, WPARAM(fFrequency), 0); end; procedure TTrackBar.SetLineSize(Value: integer); begin fLineSize := Value; LLCL_SendMessage(Handle, TBM_SETLINESIZE, 0, LPARAM(fLineSize)); end; procedure TTrackBar.SetPageSize(Value: integer); begin fPageSize := Value; LLCL_SendMessage(Handle, TBM_SETPAGESIZE, 0, LPARAM(fPageSize)); end; // Scroll messages coming from form function TTrackBar.ComponentNotif(var Msg: TMessage): boolean; begin result := inherited ComponentNotif(Msg); case Msg.Msg of WM_HSCROLL, WM_VSCROLL: if fOnChangeOK and Assigned(EOnChange) then EOnChange(Self); end; end; //------------------------------------------------------------------------------ function InitCommonControl(CC: integer): Boolean; begin result := LLCLS_InitCommonControl(CC); end; //------------------------------------------------------------------------------ initialization RegisterClasses([TProgressBar, TTrackBar]); {$IFDEF FPC} {$POP} {$ENDIF} end.
unit URegistros; interface uses Classes, SysUtils, Graphics; type TRegistro = class(TCollectionItem) private FName: string; FForeground: TColor; FBackground: TColor; FBold: boolean; public published property Name: string read FName write FName; property Foreground: TColor read FForeground write FForeground; property Background: TColor read FBackground write FBackground; property Bold: boolean read FBold write FBold; end; TGrupoRegistros = class(TCollection) private function GetItem(Index: integer): TRegistro; //function GetPessoas(Idade: integer): TGrupo; public function AddItem: TRegistro; //property BuscaPessoa[Index: Integer]: TPessoa read GetPessoa; //property BuscaPessoas[Idade: Integer]: TGrupo read GetPessoas; constructor Create(ItemClass: TCollectionItemClass); property Items[Index: integer]: TRegistro read GetItem; end; implementation function TGrupoRegistros.AddItem: TRegistro; begin Result := add as TRegistro; end; constructor TGrupoRegistros.Create(ItemClass: TCollectionItemClass); begin inherited Create(ItemClass); end; function TGrupoRegistros.GetItem(Index: integer): TRegistro; begin Result := inherited Items[Index] as TRegistro; end; end.
unit search; interface uses WinApi.Windows, System.SysUtils, System.Classes, fileTools; type TFileLocation = fileTools.TFileLocation; PFileLocation = ^TFileLocation; TTextEcncodingType = (encASCII, encUTF8, encUTF16); TSearchField = (ffFolder,ffTime,ffFileAttr,ffFileSize,ffFileText); TSearchFields = set of TSearchField; TSearchParameters = packed record path,mask:WideString; recursive:boolean; attr:DWORD; minSize,maxSize:Int64; minTime,maxTime:TDateTime; text:WideString; enc:TTextEcncodingType; fields:TSearchFields; procedure search(aFolder:WideString;aFileMask:WideString='*.*'); procedure constraintTime(v:array of TDateTime); procedure constraintFileAttributes(v:DWORD); procedure constraintFileSize(aMin:Int64;aMax:Int64); procedure constraintFileContent(aText:WideString;aEncoding:TTextEcncodingType=encASCII); end; TSearchOperation = class(TThread) private FEOS:THandle; FQuery:TSearchQuery; FOnNewItemFound:TNotifyEvent; public constructor Create(aParameters:TSearchParameters;aOnNewItemFound:TNotifyEvent=nil);reintroduce; destructor Destroy;override; procedure Execute;override; property eos:THandle read FEOS write FEOS; end; implementation uses System.WideStrUtils; { TSearchParameters } procedure TSearchParameters.constraintFileAttributes(v: DWORD); begin end; procedure TSearchParameters.constraintFileContent(aText: WideString; aEncoding: TTextEcncodingType); begin end; procedure TSearchParameters.constraintFileSize(aMin, aMax: Int64); begin end; procedure TSearchParameters.constraintTime(v: array of TDateTime); begin end; procedure TSearchParameters.search(aFolder, aFileMask: WideString); begin path:=aFolder; mask:=aFileMask; if trim(mask)='' then mask:='*.*'; end; { TSearchOperation } constructor TSearchOperation.Create(aParameters: TSearchParameters; aOnNewItemFound: TNotifyEvent); var m:WideString; begin inherited Create(True); FOnNewItemFound:=aOnNewItemFound; if trim(aParameters.mask)<>'' then m:=aParameters.mask; FQuery.create(aParameters.path,m); FQuery.recursive:=aParameters.recursive; end; destructor TSearchOperation.Destroy; begin FOnNewItemFound:=nil; inherited Destroy; end; procedure TSearchOperation.Execute; var location:TFileLocation; buf:PFileLocation; begin while findNextFile(FQuery,location) do begin buf:=PFileLocation(AllocMem(SizeOf(TFileLocation))); buf^.path:=PWidechar(AllocMem(WStrLen(location.path))); WStrLCopy(buf^.path,location.path,WStrLen(location.path)); buf^.data:=location.data; if Assigned(FOnNewItemFound) then FOnNewItemFound(TObject(Pointer(buf))); end; SetEvent(FEOS); // report end of the scan end; end.
{** @Abstract(Выборка фреймов) @Author(Prof1983 prof1983@ya.ru) @Created(26.04.2006) @LastMod(28.06.2012) @Version(0.5) } unit AiSelectObj; interface uses ATypes, AiBase, AiFrameObj; type //** Выборка фреймов TAiSelectObject = class private FItems: array of TAId; FQuery: String; FSource: AiSourceObject; public function GetFreim(Index: Int32): TAiFrameObject; function GetItem(Index: Int32): TAId; public function Count: Int32; constructor Create(AQuery: string); public property Freims[Index: Int32]: TAiFrameObject read GetFreim; property Items[Index: Int32]: TAId read GetItem; property Query: String read FQuery; property Source: AiSourceObject read FSource write FSource; end; TAiSelect = TAiSelectObject; TAI_Select = TAiSelectObject; implementation uses AiSourceObj; { TAiSelect } function TAiSelectObject.Count(): Int32; begin Result := Length(FItems); end; constructor TAiSelectObject.Create(AQuery: String); begin inherited Create(); SetLength(FItems, 0); FQuery := AQuery; end; function TAiSelectObject.GetFreim(Index: Int32): TAiFrameObject; var Id: TAId; Source: TAiSourceObject; begin Source := TAiSourceObject(FSource); if not(Assigned(Source)) then begin Result := nil; Exit; end; Id := GetItem(Index); if (Id = 0) then begin Result := nil; Exit; end; Result := Source.Freims[ID]; end; function TAiSelectObject.GetItem(Index: Int32): TAId; begin if (Index >= 0) and (Index < Length(FItems)) then Result := FItems[Index] else Result := 0; end; end.
{----------------------------------------------------------------------------- The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: JvDockAdvTree.pas, released on 2005-02-14. The Initial Developer of the Original Code is luxiaoban. Portions created by luxiaoban are Copyright (C) 2002,2003 luxiaoban. All Rights Reserved. Contributor(s): Last Modified: 2005-02-08 You may retrieve the latest version of this file at the Project JEDI's JVCL home page, located at http://jvcl.delphi-jedi.org Description: Code split out from JvDockTree.pas because of compiler issues - WPostma. Known Issues: -----------------------------------------------------------------------------} // $Id$ unit JvDockAdvTree; {$I jvcl.inc} interface uses {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} Windows, Messages, Classes, Graphics, Controls, Forms, JvDockTree; type TJvDockAdvTree = class(TJvDockTree) private FButtonHeight: Integer; FButtonWidth: Integer; FLeftOffset: Integer; FRightOffset: Integer; FTopOffset: Integer; FBottomOffset: Integer; FButtonSplitter: Integer; FCloseButtonZone: TJvDockAdvZone; FDropDockSize: Integer; FDockHeightWidth: array [TDockOrientation] of Integer; FDockRectangles: array [TDockOrientation, Boolean] of Integer; function GetBottomOffset: Integer; function GetButtonHeight: Integer; function GetButtonSplitter: Integer; function GetButtonWidth: Integer; function GetLeftOffset: Integer; function GetRightOffset: Integer; function GetTopOffset: Integer; procedure SetBottomOffset(const Value: Integer); procedure SetButtonHeight(const Value: Integer); procedure SetButtonSplitter(const Value: Integer); procedure SetButtonWidth(const Value: Integer); procedure SetLeftOffset(const Value: Integer); procedure SetRightOffset(const Value: Integer); procedure SetTopOffset(const Value: Integer); function GetDockHeightWidth(Orient: TDockOrientation): Integer; procedure SetDockHeightWidth(Orient: TDockOrientation; const Value: Integer); function GetDockRectangles(Orient: TDockOrientation; AtLast: Boolean): Integer; procedure SetDockRectangles(Orient: TDockOrientation; AtLast: Boolean; const Value: Integer); procedure SetDropDockSize(const Value: Integer); protected function DoLButtonDown(var Msg: TWMMouse; var Zone: TJvDockZone; out HTFlag: Integer): Boolean; override; procedure DoLButtonUp(var Msg: TWMMouse; var Zone: TJvDockZone; out HTFlag: Integer); override; procedure DoMouseMove(var Msg: TWMMouse; var Zone: TJvDockZone; out HTFlag: Integer); override; procedure InsertSibling(NewZone, SiblingZone: TJvDockZone; InsertLast, Update: Boolean); override; procedure InsertNewParent(NewZone, SiblingZone: TJvDockZone; ParentOrientation: TDockOrientation; InsertLast, Update: Boolean); override; procedure InitDockHeightWidth(NoOrValue, HorValue, VerValue: Integer); procedure InitDockRectangles(ARect: TRect); procedure ScaleZone(Zone: TJvDockZone); override; procedure ScaleChildZone(Zone: TJvDockZone); override; procedure ScaleSiblingZone(Zone: TJvDockZone); override; procedure ShiftZone(Zone: TJvDockZone); override; procedure RemoveZone(Zone: TJvDockZone; Hide: Boolean); override; public constructor Create(DockSite: TWinControl; ADockZoneClass: TJvDockZoneClass; ADockStyle: TJvDockObservableStyle); override; property BottomOffset: Integer read GetBottomOffset write SetBottomOffset; property ButtonHeight: Integer read GetButtonHeight write SetButtonHeight; property ButtonSplitter: Integer read GetButtonSplitter write SetButtonSplitter; property ButtonWidth: Integer read GetButtonWidth write SetButtonWidth; property LeftOffset: Integer read GetLeftOffset write SetLeftOffset; property RightOffset: Integer read GetRightOffset write SetRightOffset; property TopOffset: Integer read GetTopOffset write SetTopOffset; property CloseButtonZone: TJvDockAdvZone read FCloseButtonZone write FCloseButtonZone; property DockHeightWidth[Orient: TDockOrientation]: Integer read GetDockHeightWidth write SetDockHeightWidth; property DockRectangles[Orient: TDockOrientation; AtLast: Boolean]: Integer read GetDockRectangles write SetDockRectangles; property DropDockSize: Integer read FDropDockSize write SetDropDockSize; end; {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$URL$'; Revision: '$Revision$'; Date: '$Date$'; LogPath: 'JVCL\run' ); {$ENDIF UNITVERSIONING} implementation //=== { TJvDockAdvTree } ===================================================== constructor TJvDockAdvTree.Create(DockSite: TWinControl; ADockZoneClass: TJvDockZoneClass; ADockStyle: TJvDockObservableStyle); begin inherited Create(DockSite, ADockZoneClass, ADockStyle); FButtonHeight := 12; FButtonWidth := 12; FLeftOffset := 0; FRightOffset := 0; FTopOffset := 0; FBottomOffset := 0; FButtonSplitter := 2; end; function TJvDockAdvTree.DoLButtonDown(var Msg: TWMMouse; var Zone: TJvDockZone; out HTFlag: Integer): Boolean; var TempZone: TJvDockAdvZone; begin Result := inherited DoLButtonDown(Msg, Zone, HTFlag); if (Zone <> nil) and (HTFlag = HTCLOSE) then begin TempZone := TJvDockAdvZone(Zone); TempZone.CloseBtnDown := True; TempZone.MouseDown := True; FCloseButtonZone := TempZone; DockSite.Invalidate; end; end; procedure TJvDockAdvTree.DoLButtonUp(var Msg: TWMMouse; var Zone: TJvDockZone; out HTFlag: Integer); begin inherited DoLButtonUp(Msg, Zone, HTFlag); if SizingZone = nil then begin FCloseButtonZone := nil; if (Zone <> nil) and (HTFlag = HTCLOSE) then TJvDockAdvZone(Zone).CloseBtnDown := False; end; end; procedure TJvDockAdvTree.DoMouseMove(var Msg: TWMMouse; var Zone: TJvDockZone; out HTFlag: Integer); var TempZone: TJvDockAdvZone; begin inherited DoMouseMove(Msg, Zone, HTFlag); if SizingZone = nil then begin TempZone := TJvDockAdvZone(Zone); if ((TempZone <> nil) and (TempZone.CloseBtnDown <> (HTFlag = HTCLOSE)) and ((FCloseButtonZone = TempZone) and FCloseButtonZone.MouseDown)) then begin TempZone.CloseBtnDown := (HTFlag = HTCLOSE) and FCloseButtonZone.MouseDown; DockSite.Invalidate; end; end; end; procedure TJvDockAdvTree.InsertSibling(NewZone, SiblingZone: TJvDockZone; InsertLast, Update: Boolean); var TempUpdate: Boolean; begin TempUpdate := Update; Update := False; try inherited InsertSibling(NewZone, SiblingZone, InsertLast, Update); if NewZone.ChildControl <> nil then InitDockHeightWidth(0, NewZone.ChildControl.TBDockHeight + BorderWidth, NewZone.ChildControl.LRDockWidth + BorderWidth) else InitDockHeightWidth(0, 0, 0); finally Update := TempUpdate; end; if Update then begin NewZone.Insert(FDropDockSize, False); SetNewBounds(NewZone.ParentZone); ForEachAt(NewZone.ParentZone, UpdateZone, tskForward); end; end; procedure TJvDockAdvTree.SetBottomOffset(const Value: Integer); begin FBottomOffset := Value; end; procedure TJvDockAdvTree.SetButtonHeight(const Value: Integer); begin FButtonHeight := Value; end; procedure TJvDockAdvTree.SetButtonSplitter(const Value: Integer); begin FButtonSplitter := Value; end; procedure TJvDockAdvTree.SetButtonWidth(const Value: Integer); begin FButtonWidth := Value; end; procedure TJvDockAdvTree.SetLeftOffset(const Value: Integer); begin FLeftOffset := Value; end; procedure TJvDockAdvTree.SetRightOffset(const Value: Integer); begin FRightOffset := Value; end; procedure TJvDockAdvTree.SetTopOffset(const Value: Integer); begin FTopOffset := Value; end; function TJvDockAdvTree.GetBottomOffset: Integer; begin Result := PPIScale(FBottomOffset); end; function TJvDockAdvTree.GetButtonHeight: Integer; begin Result := PPIScale(FButtonHeight); end; function TJvDockAdvTree.GetButtonSplitter: Integer; begin Result := PPIScale(FButtonSplitter); end; function TJvDockAdvTree.GetButtonWidth: Integer; begin Result := PPIScale(FButtonWidth); end; function TJvDockAdvTree.GetDockHeightWidth(Orient: TDockOrientation): Integer; begin Result := FDockHeightWidth[Orient]; end; procedure TJvDockAdvTree.SetDockHeightWidth(Orient: TDockOrientation; const Value: Integer); begin FDockHeightWidth[Orient] := Value; end; function TJvDockAdvTree.GetDockRectangles(Orient: TDockOrientation; AtLast: Boolean): Integer; begin Result := FDockRectangles[Orient, AtLast]; end; function TJvDockAdvTree.GetLeftOffset: Integer; begin Result := PPIScale(FLeftOffset); end; function TJvDockAdvTree.GetRightOffset: Integer; begin Result := PPIScale(FRightOffset); end; function TJvDockAdvTree.GetTopOffset: Integer; begin Result := PPIScale(FTopOffset); end; procedure TJvDockAdvTree.SetDockRectangles(Orient: TDockOrientation; AtLast: Boolean; const Value: Integer); begin FDockRectangles[Orient, AtLast] := Value; end; procedure TJvDockAdvTree.InitDockRectangles(ARect: TRect); begin FDockRectangles[doNoOrient, False] := 0; FDockRectangles[doNoOrient, True] := 0; FDockRectangles[doHorizontal, False] := ARect.Top; FDockRectangles[doHorizontal, True] := ARect.Bottom; FDockRectangles[doVertical, False] := ARect.Left; FDockRectangles[doVertical, True] := ARect.Right; end; procedure TJvDockAdvTree.InitDockHeightWidth(NoOrValue, HorValue, VerValue: Integer); begin FDockHeightWidth[doNoOrient] := NoOrValue; FDockHeightWidth[doHorizontal] := HorValue; FDockHeightWidth[doVertical] := VerValue; end; procedure TJvDockAdvTree.ScaleChildZone(Zone: TJvDockZone); begin if Zone = ReplacementZone then ShiftScaleOrientation := doNoOrient; inherited ScaleChildZone(Zone); end; procedure TJvDockAdvTree.ScaleSiblingZone(Zone: TJvDockZone); begin if Zone = ReplacementZone then ShiftScaleOrientation := doNoOrient; inherited ScaleSiblingZone(Zone); end; procedure TJvDockAdvTree.ScaleZone(Zone: TJvDockZone); begin if Zone = ReplacementZone then ShiftScaleOrientation := doNoOrient; inherited ScaleZone(Zone); end; procedure TJvDockAdvTree.ShiftZone(Zone: TJvDockZone); begin if Zone = ReplacementZone then ShiftScaleOrientation := doNoOrient; inherited ShiftZone(Zone); end; procedure TJvDockAdvTree.InsertNewParent(NewZone, SiblingZone: TJvDockZone; ParentOrientation: TDockOrientation; InsertLast, Update: Boolean); var TempUpdate: Boolean; begin TempUpdate := Update; Update := False; if NewZone.ChildControl <> nil then InitDockHeightWidth(0, NewZone.ChildControl.TBDockHeight + BorderWidth, NewZone.ChildControl.LRDockWidth + BorderWidth) else InitDockHeightWidth(0, 0, 0); if SiblingZone = nil then if InsertLast then ReplacementZone := TopZone else ReplacementZone := NewZone; try inherited InsertNewParent(NewZone, SiblingZone, ParentOrientation, InsertLast, Update); finally Update := TempUpdate; ReplacementZone := nil; end; if Update then begin NewZone.Insert(DropDockSize, False); ForEachAt(NewZone.ParentZone, UpdateZone, tskForward); SetNewBounds(NewZone.ParentZone); end; end; procedure TJvDockAdvTree.RemoveZone(Zone: TJvDockZone; Hide: Boolean); begin inherited RemoveZone(Zone, Hide); end; procedure TJvDockAdvTree.SetDropDockSize(const Value: Integer); begin FDropDockSize := Value; end; {$IFDEF UNITVERSIONING} initialization RegisterUnitVersion(HInstance, UnitVersioning); finalization UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
(* * Analizator LL(1) prostych wyrazen arytmetycznch. * * * wersja 1.01 * author: Jerzy Wawro * *>--Copyright (c) 1991-2016, Galicea <fundacja@galicea.org> *>--All rights reserved. *>--License FreeBSD: see license.txt for details. *) program kalk_ll1; uses Crt, Dos, scaner; const StackSize = 25; {Maksymalna wielkosc stosu dla analizatora} var Stack : array [0..StackSize] of Token; StackTop : word; ParseError : word; x : word; blad, koniec : boolean; TK : Token; t : word; sin : string; procedure parser; var res : real; procedure scan; begin NextToken(sin,TK,x,ParseError); t:=TK.symb; end; {scan} procedure expression; procedure term; { skladnik } var r1 : real; procedure factor; { czynnik } begin res:=0; if t=NUMSYM then begin res:=TK.r; scan end else if t=LPAREN then begin scan; expression; if blad then exit; if t=RPAREN then scan else blad:=TRUE; end; end; {factor} begin {term} factor; r1:=res; while (t in [MULSYM, DIVSYM]) and (not blad) do begin if t=MULSYM then begin scan; factor; r1:=r1*res end else begin scan; factor; r1:=r1/res end; end; res:=r1 end; {term} var r2 : real; begin {expression} res:=0; term; r2:=res; while (t in [ADDSYM, SUBSYM]) and (not blad) do begin if t=ADDSYM then begin scan; term; r2:=r2+res end else begin scan; term; r2:=r2-res end; end; res:=r2 end; {expression} begin {parser} scan; expression; if t<>EOINSYM then blad:=TRUE; TK.r:=res end; {parser} begin Stack[0].state:=0; StackTop :=0; ParseError:=0; x :=1; blad:=FALSE; koniec :=FALSE; write('wyrazenie:'); readln(sin); parser; if blad then writeln('Blad') else writeln('wynik: ',TK.r:10:2); write('Nacisnij Enter');readln; end.
unit Module1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, IBConnection, sqldb, db; type { TDataModule1 } TDataModule1 = class(TDataModule) IBCMaquina: TIBConnection; qrImpRomaneioBEBERCOCO: TLongintField; qrImpRomaneioBEBERLIMPO: TFloatField; qrImpRomaneioCANCELADO: TStringField; qrImpRomaneioCOD_CLI: TLongintField; qrImpRomaneioCOD_COMPRA: TLongintField; qrImpRomaneioCOD_DEPOSITADO: TLongintField; qrImpRomaneioCOD_PRO: TLongintField; qrImpRomaneioCOD_ROMANEIO: TLongintField; qrImpRomaneioDATA: TDateField; qrImpRomaneioDESCONTO1: TLongintField; qrImpRomaneioDESCONTO2: TLongintField; qrImpRomaneioIMPUREZA: TLongintField; qrImpRomaneioLEGENDA1: TStringField; qrImpRomaneioLEGENDA2: TStringField; qrImpRomaneioLOTECOCO: TLongintField; qrImpRomaneioOBS: TStringField; qrImpRomaneioPESOBRUTO: TLongintField; qrImpRomaneioPESOJUTA: TBCDField; qrImpRomaneioPESOPLASTICO: TBCDField; qrImpRomaneioPORCENTAGEM: TLongintField; qrImpRomaneioQUANJUTA: TLongintField; qrImpRomaneioQUANPLASTICO: TLongintField; qrImpRomaneioRENDA: TLongintField; qrImpRomaneioTOTALROMANEIO: TLongintField; SQLTMaquina: TSQLTransaction; private public end; var DataModule1: TDataModule1; implementation {$R *.lfm} end.
{** @Abstract Контрол фреймов @Author Prof1983 <prof1983@ya.ru> @Created 06.11.2006 @LastMod 17.12.2012 } unit AiFramesControl2; interface uses Classes, ComCtrls, Controls, StdCtrls, AControlImpl, AiKbCode, AiKbFrame; type //** @abstract(Контрол фреймов) TAIFramesControl = class(TAControl) private FTreeView: TTreeView; FMemo: TMemo; procedure TreeViewClick(Sender: TObject); protected procedure DoSelect(const AName: WideString); public function Initialize(): WordBool; procedure Refresh(); end; implementation { TAIFramesControl } procedure TAIFramesControl.DoSelect(const AName: WideString); begin FMemo.Clear(); if AName = 'Frame' then FMemo.Lines.Add(AIFrameSchema) else if AName = 'Code' then FMemo.Lines.Add(AiCodeSchema) else if AName = 'Reason' then //FMemo.Lines.Add(kbReason); end; function TAIFramesControl.Initialize(): WordBool; begin Result := True; FTreeView := TTreeView.Create(FControl); FTreeView.Parent := FControl; FTreeView.Align := alLeft; FTreeView.Width := 200; FTreeView.OnClick := TreeViewClick; FMemo := TMemo.Create(FControl); FMemo.Parent := FControl; FMemo.Align := alClient; FMemo.ScrollBars := ssBoth; Refresh() end; procedure TAIFramesControl.Refresh(); begin FTreeView.Items.AddChild(nil, 'Frame'); FTreeView.Items.AddChild(nil, 'Code'); FTreeView.Items.AddChild(nil, 'Reason'); end; procedure TAIFramesControl.TreeViewClick(Sender: TObject); begin if Assigned(FTreeView.Selected) then DoSelect(FTreeView.Selected.Text); end; end.
unit UnitCadastreCreditCard; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Objects, FMX.Controls.Presentation, FMX.Layouts, FMX.Edit, FMX.ListBox, DateUtils ,StrUtils, System.ImageList, FMX.ImgList, FMX.ExtCtrls; type TFormCadastreCreditCard = class(TForm) LayoutPrincipal: TLayout; Layout2: TLayout; Label1: TLabel; EditName: TEdit; Layout4: TLayout; Layout5: TLayout; Label4: TLabel; ComboboxMonth: TComboBox; ComboboxYear: TComboBox; ButtonSave: TSpeedButton; Layout7: TLayout; Label6: TLabel; EditNumber: TEdit; Layout6: TLayout; ImageFlag: TImage; Layout3: TLayout; procedure EditNameChange(Sender: TObject); procedure ButtonSaveClick(Sender: TObject); procedure EditNameKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure EditNumberChange(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); private { Private declarations } procedure SendCreditCard; var Id: Integer; protected { Protected declarations } procedure ValidateValuesComponents; virtual; var Flag: String; public { Public declarations } constructor Create(AWoner: TComponent); overload; constructor Create(AWoner: TComponent; NumberForEdit: String); overload; function GetFlag(): String; function GetNumber(): String; function GetName(): String; function GetMonth(): Integer; function GetYear(): Integer; end; var FormCadastreCreditCard: TFormCadastreCreditCard; implementation {$R *.fmx} uses UnitDataModuleGeral, UnitRoutines, UnitDataModuleLocal; procedure TFormCadastreCreditCard.ButtonSaveClick(Sender: TObject); begin try //Valida os valores dos campos. ValidateValuesComponents; //Envia o cartão de crédito em uma Thread paralela. ExecuteAsync(LayoutPrincipal ,procedure begin //Envia os dados do cartão de crédito para o servidor. SendCreditCard; end); except on Error: Exception do begin //Exibe o erro para o usuário. ShowMessage(Error.Message); end; end; end; constructor TFormCadastreCreditCard.Create(AWoner: TComponent); begin //Chama o construtor herdado. inherited Create(AWoner); Id := 0; end; constructor TFormCadastreCreditCard.Create(AWoner: TComponent; NumberForEdit: String); begin //Chama o construtor herdado. inherited Create(AWoner); //Busca o registro a ser editado no conjunto de cartões. if (DataModuleGeral.DataSetCreditCards.Locate('Number', NumberForEdit, [])) then begin //Carrega nos campos os valores do cartão de crédito a ser editado. Id := DataModuleGeral.GetIdCreditCardSelected(); EditName.Text := DataModuleGeral.GetNameCreditCardSelected(); EditNumber.Text := DataModuleGeral.GetNumberCreditCardSelected(); ComboboxMonth.ItemIndex:= DataModuleGeral.GetMonthCreditCardSelected - 1; ComboboxYear.ItemIndex := ComboboxYear.Items.IndexOf(IntToStr(DataModuleGeral.GetYearCreditCardSelected)); end; end; procedure TFormCadastreCreditCard.EditNameChange(Sender: TObject); begin //Permite apenas letras A-Z, e deixa as letras em maiúsculo. EditName.Text := GetJustLettersOfString(editName.Text); SetTextUpperCaseEditChange(Sender); end; procedure TFormCadastreCreditCard.EditNameKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin AllowJustLettersEditKeyDown(Sender, Key, KeyChar, Shift); end; procedure TFormCadastreCreditCard.EditNumberChange(Sender: TObject); var Index: Integer; begin //Permite apenas números no campo editNumber. EditNumber.Text := GetJustNumbersOfString(editNumber.Text); //Atualiza o ícone da bandeira relacionada ao cartão digitado~. {$IFDEF Win32 or Win64} Index := 1; {$ELSE} Index := 0; {$ENDIF} if (EditNumber.Text.Length > 0) and (EditNumber.Text[Index] = '4') then begin ImageFlag.Bitmap := DataModuleGeral.IconsGenericList.Bitmap(TSizeF.Create(32,32), 0); Flag := 'VISA'; end else begin ImageFlag.Bitmap := DataModuleGeral.IconsGenericList.Bitmap(TSizeF.Create(32,32), 1); Flag := 'MASTERCARD'; end; end; procedure TFormCadastreCreditCard.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := True; Hide; ModalResult := mrCancel; end; function TFormCadastreCreditCard.GetFlag: String; begin Result := Flag; end; function TFormCadastreCreditCard.GetMonth: Integer; begin Result := StrToInt(ComboboxMonth.Selected.Text); end; function TFormCadastreCreditCard.GetName: String; begin Result := EditName.Text; end; function TFormCadastreCreditCard.GetNumber: String; begin Result := EditNumber.Text.Replace('-', ''); end; function TFormCadastreCreditCard.GetYear: Integer; begin Result := StrToInt(ComboboxYear.Selected.Text); end; procedure TFormCadastreCreditCard.SendCreditCard; begin try //Envia o cartão de crédito para o servidor. DataModuleGeral.SendCreditCard(Id ,Flag ,EditName.Text ,EditNumber.Text ,StrToInt(ComboboxMonth.Selected.Text) ,StrToInt(ComboboxYear.Selected.Text) ,True); //Atualiza a interface na Thread principal. TThread.Synchronize(nil ,procedure begin //Fecha o cadastro do cartão de crédito. Hide; ModalResult := mrOk; end); except on Error: Exception do begin //Exibe a mensagem de erro na Thread principal. TThread.Synchronize(nil ,procedure begin ShowMessage(Error.Message); end); end; end; end; procedure TFormCadastreCreditCard.ValidateValuesComponents; var Month, Year, MonthCurrent, YearCurrent: Integer; begin //Valida os valores de todos os campos. Focused := nil; EditName.Text := GetJustLettersOfString(editName.Text); EditNumber.Text := GetJustNumbersOfString(editNumber.Text); ValidateValueComponent(EditName, editName.Text, 'Informe o nome impresso no cartão!'); ValidateValueComponent(EditNumber, editNumber.Text, 'Informe o número do cartão!', 16); //Verifica se o cartão de crédito está vencido. Month := StrToInt(ComboboxMonth.Selected.Text); Year := StrToInt(ComboboxYear.Selected.Text); MonthCurrent := MonthOf(Date); YearCurrent := YearOf(Date); if (Year < YearCurrent) or ((Month < MonthCurrent) and (Year = YearCurrent)) then begin //Levanta uma exceção informando sobre a validade do cartão de crédito. raise Exception.Create('Cartão de crédito vencido!'); end; end; end.
unit SSPatternBuilder; interface uses System.RegularExpressions, System.SysUtils, System.StrUtils, System.Generics.Collections, System.Generics.Defaults; type TSSPatternBuilder = record const { Predefined regular expressions } _CPF = '^([0-9]{3}\.){2}[0-9]{3}-[0-9]{2}$'; _Phone = '^\([0-9]{2}\) ?[0-9]{4}-?[0-9]{4}$'; Any = '.'; Digit = '[0-9]'; Letter = '[A-Za-z]'; UpperCaseLetter = '[A-Z]'; LowerCaseLetter = '[a-z]'; All = '.*'; class function EndsWith(aPattern: String): String; static; class function Group(aPattern: String): String; static; class function JoinLists(aLists: array of String): String; static; class function List(aValues: array of Char): String; static; class function Negate(aList: String): String; overload; static; class function Negate(aValues: array of Char): String; overload; static; class function Optional(aPattern: String): String; static; class function Range(aFirst, aLast: Char): String; static; class function RepeatIt(aPattern: String): String; overload; static; class function RepeatIt(aPattern: String; aMin, aMax: Integer): String; overload; static; class function RepeatIt(aPattern: String; aTimes: Integer): String; overload; static; class function RepeatItAtLeast(aPattern: String; aMin: Integer): String; static; class function RepeatItAtLeastOne(aPattern: String): String; static; class function RepeatItUntil(aPattern: String; aMax: Integer): String; static; class function StartsAndEndsWith(aPattern: String): String; static; class function StartsWith(aPattern: String): String; static; class function ToPattern(aValue: String): String; overload; static; class function ToPattern(aValues: array of Char): String; overload; static; end; implementation { Internal functions } function _CheckGroup(aPattern: String): String; forward; function _ExtractContentFromList(aList: String): String; forward; function _Group(aPattern: String): String; forward; function _RepeatList(aPattern: String; aMin, aMax: Integer): String; forward; function _CheckGroup(aPattern: String): String; begin Result := aPattern; if (aPattern.Length <> 1) and (not ((aPattern.Length = 2) and TRegEx.IsMatch(Result, '^\\.$'))) and (not TRegEx.IsMatch(Result, '^((\[.*\])|(\(.*\)))$')) then Result := _Group(aPattern); end; function _ExtractContentFromList(aList: String): String; begin Result := TRegEx.Replace(aList, '^\[(.*)\]$', '\1'); end; function _Group(aPattern: String): String; begin Result := '('+aPattern+')'; end; function _RepeatList(aPattern: String; aMin, aMax: Integer): String; begin Result := _CheckGroup(aPattern) + '{'; if aMin = aMax then Result := Result + IntToStr(aMin) else Result := Result + IfThen(aMin = -1, '', IntToStr(aMin))+','+IfThen(aMax = -1, '', IntToStr(aMax)); Result := Result + '}'; end; { TSSPatternBuilder } class function TSSPatternBuilder.EndsWith(aPattern: String): String; begin Result := aPattern+'$'; end; class function TSSPatternBuilder.Group(aPattern: String): String; begin Result := _Group(aPattern); end; class function TSSPatternBuilder.JoinLists(aLists: array of String): String; var CurrentList: String; begin for CurrentList in aLists do Result := Result + _ExtractContentFromList(CurrentList); if not Result.IsEmpty then Result := '[' + Result + ']'; end; class function TSSPatternBuilder.List(aValues: array of Char): String; function GetList: String; var Ch: Char; begin Result := ''; for Ch in aValues do Result := Result + Ch; end; begin Result := '['+GetList+']'; end; class function TSSPatternBuilder.Negate(aValues: array of Char): String; begin Result := Negate(List(aValues)); end; class function TSSPatternBuilder.Negate(aList: String): String; begin Result := '[^'+_ExtractContentFromList(aList)+']'; end; class function TSSPatternBuilder.Optional(aPattern: String): String; begin Result := aPattern+'?'; end; class function TSSPatternBuilder.RepeatIt(aPattern: String; aMin, aMax: Integer): String; begin Result := _RepeatList(aPattern, aMin, aMax); end; class function TSSPatternBuilder.RepeatIt(aPattern: String; aTimes: Integer): String; begin Result := _RepeatList(aPattern, aTimes, aTimes); end; class function TSSPatternBuilder.RepeatIt(aPattern: String): String; begin Result := _CheckGroup(aPattern)+'*'; end; class function TSSPatternBuilder.RepeatItAtLeast(aPattern: String; aMin: Integer): String; begin Result := _RepeatList(aPattern, aMin, -1); end; class function TSSPatternBuilder.RepeatItAtLeastOne(aPattern: String): String; begin Result := _CheckGroup(aPattern)+'+'; end; class function TSSPatternBuilder.Range(aFirst, aLast: Char): String; begin Result := '['+aFirst+'-'+aLast+']'; end; class function TSSPatternBuilder.RepeatItUntil(aPattern: String; aMax: Integer): String; begin Result := _RepeatList(aPattern, 0, aMax); end; class function TSSPatternBuilder.StartsAndEndsWith(aPattern: String): String; begin Result := StartsWith(EndsWith(aPattern)); end; class function TSSPatternBuilder.StartsWith(aPattern: String): String; begin Result := '^'+aPattern; end; class function TSSPatternBuilder.ToPattern(aValues: array of Char): String; function GetValuesToPattern: String; var Ch: Char; begin Result := ''; for Ch in aValues do Result := Result + TRegEx.Escape(Ch, False); end; begin Result := '['+GetValuesToPattern+']'; end; class function TSSPatternBuilder.ToPattern(aValue: String): String; begin Result := TRegEx.Escape(aValue, False); end; end.