text
stringlengths
14
6.51M
{ *********************************************************************************** } { * 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 ClpSecP256R1Field; {$I ..\..\..\..\Include\CryptoLib.inc} interface uses ClpNat, ClpBits, ClpNat256, ClpBigInteger, ClpCryptoLibTypes; type // 2^256 - 2^224 + 2^192 + 2^96 - 1 TSecP256R1Field = class sealed(TObject) strict private const P7 = UInt32($FFFFFFFF); PExt15 = UInt32($FFFFFFFE); class var FP, FPExt: TCryptoLibUInt32Array; class function GetP: TCryptoLibUInt32Array; static; inline; class procedure AddPInvTo(const z: TCryptoLibUInt32Array); static; class procedure SubPInvFrom(const z: TCryptoLibUInt32Array); static; class constructor SecP256R1Field(); public class procedure Add(const x, y, z: TCryptoLibUInt32Array); static; inline; class procedure AddExt(const xx, yy, zz: TCryptoLibUInt32Array); static; inline; class procedure AddOne(const x, z: TCryptoLibUInt32Array); static; inline; class function FromBigInteger(const x: TBigInteger): TCryptoLibUInt32Array; static; inline; class procedure Half(const x, z: TCryptoLibUInt32Array); static; inline; class procedure Multiply(const x, y, z: TCryptoLibUInt32Array); static; inline; class procedure MultiplyAddToExt(const x, y, zz: TCryptoLibUInt32Array); static; inline; class procedure Negate(const x, z: TCryptoLibUInt32Array); static; inline; class procedure Reduce(const xx, z: TCryptoLibUInt32Array); static; class procedure Reduce32(x: UInt32; const z: TCryptoLibUInt32Array); static; class procedure Square(const x, z: TCryptoLibUInt32Array); static; inline; class procedure SquareN(const x: TCryptoLibUInt32Array; n: Int32; const z: TCryptoLibUInt32Array); static; inline; class procedure Subtract(const x, y, z: TCryptoLibUInt32Array); static; inline; class procedure SubtractExt(const xx, yy, zz: TCryptoLibUInt32Array); static; inline; class procedure Twice(const x, z: TCryptoLibUInt32Array); static; inline; class property P: TCryptoLibUInt32Array read GetP; end; implementation { TSecP256R1Field } class constructor TSecP256R1Field.SecP256R1Field; begin FP := TCryptoLibUInt32Array.Create($FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $00000000, $00000000, $00000000, $00000001, $FFFFFFFF); FPExt := TCryptoLibUInt32Array.Create($00000001, $00000000, $00000000, $FFFFFFFE, $FFFFFFFF, $FFFFFFFF, $FFFFFFFE, $00000001, $FFFFFFFE, $00000001, $FFFFFFFE, $00000001, $00000001, $FFFFFFFE, $00000002, $FFFFFFFE); end; class function TSecP256R1Field.GetP: TCryptoLibUInt32Array; begin result := FP; end; class procedure TSecP256R1Field.Add(const x, y, z: TCryptoLibUInt32Array); var c: UInt32; begin c := TNat256.Add(x, y, z); if ((c <> 0) or ((z[7] = P7) and (TNat256.Gte(z, FP)))) then begin AddPInvTo(z); end; end; class procedure TSecP256R1Field.AddExt(const xx, yy, zz: TCryptoLibUInt32Array); var c: UInt32; begin c := TNat.Add(16, xx, yy, zz); if ((c <> 0) or ((zz[15] >= PExt15) and (TNat.Gte(16, zz, FPExt)))) then begin TNat.SubFrom(16, FPExt, zz); end; end; class procedure TSecP256R1Field.AddOne(const x, z: TCryptoLibUInt32Array); var c: UInt32; begin c := TNat.Inc(8, x, z); if ((c <> 0) or ((z[7] = P7) and (TNat256.Gte(z, FP)))) then begin AddPInvTo(z); end; end; class procedure TSecP256R1Field.AddPInvTo(const z: TCryptoLibUInt32Array); var c: Int64; begin c := Int64(z[0]) + 1; z[0] := UInt32(c); c := TBits.Asr64(c, 32); if (c <> 0) then begin c := c + Int64(z[1]); z[1] := UInt32(c); c := TBits.Asr64(c, 32); c := c + Int64(z[2]); z[2] := UInt32(c); c := TBits.Asr64(c, 32); end; c := c + (Int64(z[3]) - 1); z[3] := UInt32(c); c := TBits.Asr64(c, 32); if (c <> 0) then begin c := c + Int64(z[4]); z[4] := UInt32(c); c := TBits.Asr64(c, 32); c := c + Int64(z[5]); z[5] := UInt32(c); c := TBits.Asr64(c, 32); end; c := c + (Int64(z[6]) - 1); z[6] := UInt32(c); c := TBits.Asr64(c, 32); c := c + (Int64(z[7]) + 1); z[7] := UInt32(c); // c := TBits.Asr64(c, 32); end; class function TSecP256R1Field.FromBigInteger(const x: TBigInteger) : TCryptoLibUInt32Array; var z: TCryptoLibUInt32Array; begin z := TNat256.FromBigInteger(x); if ((z[7] = P7) and (TNat256.Gte(z, FP))) then begin TNat256.SubFrom(FP, z); end; result := z; end; class procedure TSecP256R1Field.Half(const x, z: TCryptoLibUInt32Array); var c: UInt32; begin if ((x[0] and 1) = 0) then begin TNat.ShiftDownBit(8, x, 0, z); end else begin c := TNat256.Add(x, FP, z); TNat.ShiftDownBit(8, z, c); end; end; class procedure TSecP256R1Field.Reduce(const xx, z: TCryptoLibUInt32Array); const n = Int64(6); var cc, xx08, xx09, xx10, xx11, xx12, xx13, xx14, xx15, t0, t1, t2, t3, t4, t5, t6, t7: Int64; begin xx08 := xx[8]; xx09 := xx[9]; xx10 := xx[10]; xx11 := xx[11]; xx12 := xx[12]; xx13 := xx[13]; xx14 := xx[14]; xx15 := xx[15]; xx08 := xx08 - n; t0 := xx08 + xx09; t1 := xx09 + xx10; t2 := xx10 + xx11 - xx15; t3 := xx11 + xx12; t4 := xx12 + xx13; t5 := xx13 + xx14; t6 := xx14 + xx15; t7 := t5 - t0; cc := 0; cc := cc + (Int64(xx[0]) - t3 - t7); z[0] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + (Int64(xx[1]) + t1 - t4 - t6); z[1] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + (Int64(xx[2]) + t2 - t5); z[2] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + (Int64(xx[3]) + (t3 shl 1) + t7 - t6); z[3] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + (Int64(xx[4]) + (t4 shl 1) + xx14 - t1); z[4] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + (Int64(xx[5]) + (t5 shl 1) - t2); z[5] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + (Int64(xx[6]) + (t6 shl 1) + t7); z[6] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + (Int64(xx[7]) + (xx15 shl 1) + xx08 - t2 - t4); z[7] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + n; {$IFDEF DEBUG} System.Assert((cc >= 0)); {$ENDIF DEBUG} Reduce32(UInt32(cc), z); end; class procedure TSecP256R1Field.Multiply(const x, y, z: TCryptoLibUInt32Array); var tt: TCryptoLibUInt32Array; begin tt := TNat256.CreateExt(); TNat256.Mul(x, y, tt); Reduce(tt, z); end; class procedure TSecP256R1Field.MultiplyAddToExt(const x, y, zz: TCryptoLibUInt32Array); var c: UInt32; begin c := TNat256.MulAddTo(x, y, zz); if ((c <> 0) or ((zz[15] >= PExt15) and (TNat.Gte(16, zz, FPExt)))) then begin TNat.SubFrom(16, FPExt, zz); end; end; class procedure TSecP256R1Field.Negate(const x, z: TCryptoLibUInt32Array); begin if (TNat256.IsZero(x)) then begin TNat256.Zero(z); end else begin TNat256.Sub(FP, x, z); end; end; class procedure TSecP256R1Field.Reduce32(x: UInt32; const z: TCryptoLibUInt32Array); var cc, xx08: Int64; begin cc := 0; if (x <> 0) then begin xx08 := x; cc := cc + (Int64(z[0]) + xx08); z[0] := UInt32(cc); cc := TBits.Asr64(cc, 32); if (cc <> 0) then begin cc := cc + Int64(z[1]); z[1] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + Int64(z[2]); z[2] := UInt32(cc); cc := TBits.Asr64(cc, 32); end; cc := cc + (Int64(z[3]) - xx08); z[3] := UInt32(cc); cc := TBits.Asr64(cc, 32); if (cc <> 0) then begin cc := cc + Int64(z[4]); z[4] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + Int64(z[5]); z[5] := UInt32(cc); cc := TBits.Asr64(cc, 32); end; cc := cc + (Int64(z[6]) - xx08); z[6] := UInt32(cc); cc := TBits.Asr64(cc, 32); cc := cc + (Int64(z[7]) + xx08); z[7] := UInt32(cc); cc := TBits.Asr64(cc, 32); {$IFDEF DEBUG} System.Assert((cc = 0) or (cc = 1)); {$ENDIF DEBUG} end; if ((cc <> 0) or ((z[7] = P7) and (TNat256.Gte(z, FP)))) then begin AddPInvTo(z); end; end; class procedure TSecP256R1Field.Square(const x, z: TCryptoLibUInt32Array); var tt: TCryptoLibUInt32Array; begin tt := TNat256.CreateExt(); TNat256.Square(x, tt); Reduce(tt, z); end; class procedure TSecP256R1Field.SquareN(const x: TCryptoLibUInt32Array; n: Int32; const z: TCryptoLibUInt32Array); var tt: TCryptoLibUInt32Array; begin {$IFDEF DEBUG} System.Assert(n > 0); {$ENDIF DEBUG} tt := TNat256.CreateExt(); TNat256.Square(x, tt); Reduce(tt, z); System.Dec(n); while (n > 0) do begin TNat256.Square(z, tt); Reduce(tt, z); System.Dec(n); end; end; class procedure TSecP256R1Field.SubPInvFrom(const z: TCryptoLibUInt32Array); var c: Int64; begin c := Int64(z[0]) - 1; z[0] := UInt32(c); c := TBits.Asr64(c, 32); if (c <> 0) then begin c := c + Int64(z[1]); z[1] := UInt32(c); c := TBits.Asr64(c, 32); c := c + Int64(z[2]); z[2] := UInt32(c); c := TBits.Asr64(c, 32); end; c := c + (Int64(z[3]) + 1); z[3] := UInt32(c); c := TBits.Asr64(c, 32); if (c <> 0) then begin c := c + Int64(z[4]); z[4] := UInt32(c); c := TBits.Asr64(c, 32); c := c + Int64(z[5]); z[5] := UInt32(c); c := TBits.Asr64(c, 32); end; c := c + (Int64(z[6]) + 1); z[6] := UInt32(c); c := TBits.Asr64(c, 32); c := c + (Int64(z[7]) - 1); z[7] := UInt32(c); // c := TBits.Asr64(c, 32); end; class procedure TSecP256R1Field.Subtract(const x, y, z: TCryptoLibUInt32Array); var c: Int32; begin c := TNat256.Sub(x, y, z); if (c <> 0) then begin SubPInvFrom(z); end; end; class procedure TSecP256R1Field.SubtractExt(const xx, yy, zz: TCryptoLibUInt32Array); var c: Int32; begin c := TNat.Sub(16, xx, yy, zz); if (c <> 0) then begin TNat.AddTo(16, FPExt, zz); end; end; class procedure TSecP256R1Field.Twice(const x, z: TCryptoLibUInt32Array); var c: UInt32; begin c := TNat.ShiftUpBit(8, x, 0, z); if ((c <> 0) or ((z[7] = P7) and (TNat256.Gte(z, FP)))) then begin AddPInvTo(z); end; end; end.
unit uQREnviarEmail; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, QRPrntr, LibGeral, smtpsend, ssl_openssl, mimemess, mimepart, Data.DB, MemDS, DBAccess, IBC, QRExport, QRPDFFilt, QRWebFilt ; type TfrmEnviarEmail = class(TForm) pnEmail: TPanel; Label10: TLabel; Label11: TLabel; Label2: TLabel; Label3: TLabel; Panel3: TPanel; edtAssunto: TEdit; edtEmail: TEdit; edtAnexo: TEdit; mmMensagem: TMemo; btnEnviar: TBitBtn; btnSair: TBitBtn; rdpFormatoAnexo: TRadioGroup; edtCc: TEdit; Label1: TLabel; qryConfig: TIBCQuery; qryConfigCODIGO: TStringField; qryConfigHOST: TStringField; qryConfigPORTA: TIntegerField; qryConfigUSUARIO: TStringField; qryConfigSSL: TStringField; qryConfigTLS: TStringField; qryConfigENVIARPDF: TStringField; qryConfigCONFIRMACAO: TStringField; qryConfigAGUARDAR: TStringField; qryConfigEMAIL: TStringField; qryConfigSENHA: TStringField; qryConfigNOME: TStringField; qryConfigOPERADOR: TStringField; qryConfigDT_ALTERACAO: TDateTimeField; procedure FormShow(Sender: TObject); procedure rdpFormatoAnexoExit(Sender: TObject); private FXLS: Boolean; FQR: TQRPrinter; public property XLS: Boolean read FXLS write FXLS; property QR: TQRPrinter read FQR write FQR; end; TSendMailThread = class(TThread) private FException: Exception; // FOwner: Conhecimento; procedure DoHandleException; public OcorreramErros: Boolean; Terminado: Boolean; smtp: TSMTPSend; sFrom: string; sTo: string; sCC: TStrings; slmsg_Lines: TStrings; constructor Create; destructor Destroy; override; protected procedure Execute; override; procedure HandleException; end; const SQL_DEFAULT = 'SELECT ' + ' SMTP.CODIGO, ' + ' SMTP.HOST, ' + ' SMTP.PORTA, ' + ' SMTP.USUARIO, ' + ' SMTP.SSL, ' + ' SMTP.TLS, ' + ' SMTP.ENVIARPDF, ' + ' SMTP.CONFIRMACAO, ' + ' SMTP.AGUARDAR, ' + ' SMTP.EMAIL, ' + ' SMTP.SENHA, ' + ' SMTP.NOME, ' + ' SMTP.OPERADOR, ' + ' SMTP.DT_ALTERACAO ' + 'FROM CONFIGSMTP SMTP '; var frmEnviarEmail: TfrmEnviarEmail; function ChamarEnvioEmail(AXLS: Boolean; AQRPrinter: TQRPrinter): Boolean; implementation {$R *.dfm} function ChamarEnvioEmail(AXLS: Boolean; AQRPrinter: TQRPrinter): Boolean; var lstMensagem: TStrings; lstAnexos: TStrings; lstCC: TStrings; sArquivo: string; frm: TfrmEnviarEmail; begin // Chama o Formulario de Envio de Email...(Crie um modelo personalizado para seu uso) frm := TfrmEnviarEmail.Create(Application); try with frm do with qryConfig do begin XLS := AXLS; QR := AQRPrinter; Close; SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE SMTP.CODIGO = ''RELATORIOS'''); Open; if not IsEmpty then begin //edtAnexo.Text := RDprint1.TitulodoRelatorio; ShowModal; if ModalResult = mrOk then begin try lstMensagem := TStringList.Create; lstMensagem.Clear; lstAnexos := TStringList.Create; lstAnexos.Clear; lstCC := TStringList.Create; lstCC.Clear; ForceDirectories(ExtractFilePath(edtAnexo.Text)); case rdpFormatoAnexo.ItemIndex of 0: QR.ExportToFilter(TQRPDFDocumentFilter.Create(edtAnexo.Text)); 1: QR.ExportToFilter(TQRGHTMLDocumentFilter.Create(edtAnexo.Text)); 2: QR.ExportToFilter(TQRRTFExportFilter.Create(edtAnexo.Text)); 3: QR.ExportToFilter(TQRXLSFilter.Create(edtAnexo.Text)); end; lstMensagem.Text := mmMensagem.Text; lstAnexos.Add(edtAnexo.Text); if edtCC.Text <> '' then lstCC := Explode(edtCc.Text, ';'); EnviarEmail(qryConfigHOST.AsString, qryConfigPORTA.AsString, qryConfigUSUARIO.AsString, qryConfigSENHA.AsString, qryConfigEMAIL.AsString, edtEmail.Text, edtAssunto.Text, lstMensagem, True, qryConfigSSL.AsString = 'T', lstCC, lstAnexos, qryConfigCONFIRMACAO.AsString = 'T', qryConfigAGUARDAR.AsString = 'T', qryConfigNOME.AsString, qryConfigTLS.AsString = 'T'); finally lstMensagem.Free; lstAnexos.Free; end; end; end else begin MessageBox(frm.Handle, 'Para utilizar esse recurso é necessário configurar a conta de e-mail para envio.' + #13 + 'Módulo Operação->Cadastros->Configurações para envio de e-mail', 'Atenção', MB_OK + MB_ICONWARNING); end; end; finally frm.Free; frm := nil; end; end; function Explode(str, separador: string): TStringList; var p : integer; begin Result := TStringList.Create; p := System.Pos(separador, str); while (p > 0) do begin Result.Add(Copy(str, 1, p - 1)); Delete(str, 1, p + Length(separador) - 1); p := System.Pos(separador, str); end; if (str <> '') then Result.Add(str); end; procedure EnviarEmail(const sSmtpHost, sSmtpPort, sSmtpUser, sSmtpPasswd, sFrom, sTo, sAssunto: string; sMensagem: TStrings; FormatoHtml: Boolean = false; SSL: Boolean = false; sCC: TStrings = nil; Anexos: TStrings = nil; PedeConfirma: Boolean = False; AguardarEnvio: Boolean = False; NomeRemetente: string = ''; TLS: Boolean = true; EnviaPDF: Boolean = false); var ThreadSMTP : TSendMailThread; m : TMimemess; p : TMimepart; // StreamCTe: TStringStream; NomeArq : string; i : Integer; begin m := TMimemess.Create; ThreadSMTP := TSendMailThread.Create; // Não Libera, pois usa FreeOnTerminate := True ; // StreamCTe := TStringStream.Create(''); try try p := m.AddPartMultipart('mixed', nil); if sMensagem <> nil then if FormatoHtml then m.AddPartHTML(sMensagem, p) else m.AddPartText(sMensagem, p); {SaveToStream(StreamCTe); m.AddPartBinary(StreamCTe, copy(CTe.inFCTe.ID, (length(CTe.inFCTe.ID) - 44) + 1, 44) + '-cte.xml', p); if (EnviaPDF) then begin if TACBrCTe(TConhecimentos(Collection).ACBrCTe).DACTE <> nil then begin TACBrCTe(TConhecimentos(Collection).ACBrCTe).DACTE.ImprimirDACTEPDF(CTe); NomeArq := StringReplace(CTe.inFCTe.ID, 'CTe', '', [rfIgnoreCase]); NomeArq := PathWithDelim(TACBrCTe(TConhecimentos(Collection).ACBrCTe).DACTE.PathPDF) + NomeArq + '.pdf'; m.AddPartBinaryFromFile(NomeArq, p); end; end;} if Assigned(Anexos) then for i := 0 to Anexos.Count - 1 do begin m.AddPartBinaryFromFile(Anexos[i], p); end; m.header.tolist.Add(sTo); if Trim(NomeRemetente) <> '' then m.header.From := Format('%s<%s>', [NomeRemetente, sFrom]) else m.header.From := sFrom; m.header.subject := sAssunto; m.header.ReplyTo := sFrom; if PedeConfirma then m.header.CustomHeaders.Add('Disposition-Notification-To: ' + sFrom); m.EncodeMessage; ThreadSMTP.sFrom := sFrom; ThreadSMTP.sTo := sTo; if sCC <> nil then ThreadSMTP.sCC.AddStrings(sCC); ThreadSMTP.slmsg_Lines.AddStrings(m.Lines); ThreadSMTP.smtp.UserName := sSmtpUser; ThreadSMTP.smtp.Password := sSmtpPasswd; ThreadSMTP.smtp.TargetHost := sSmtpHost; if sSmtpPort <> '' then // Usa default ThreadSMTP.smtp.TargetPort := sSmtpPort; ThreadSMTP.smtp.FullSSL := SSL; ThreadSMTP.smtp.AutoTLS := TLS; // TACBrCTe(TConhecimentos(Collection).ACBrCTe).SetStatus(stCTeEmail); ThreadSMTP.Resume; // inicia a thread if AguardarEnvio then begin repeat Sleep(1000); Application.ProcessMessages; until ThreadSMTP.Terminado; end; // TACBrCTe(TConhecimentos(Collection).ACBrCTe).SetStatus(stCTeIdle); except on e: exception do showmessage('problema no envio de email'); end; finally m.Free; // StreamCTe.Free; end; end; procedure TfrmEnviarEmail.FormShow(Sender: TObject); var saveDialog : TSaveDialog; begin saveDialog := TSaveDialog.Create(self); saveDialog.Title := 'Salvar relatório como'; saveDialog.InitialDir := GetCurrentDir; if FXLS then saveDialog.Filter := 'Arquivo PDF|*.pdf|Arquivo Texto|*.txt|Arquivo HTML|*.html|Arquivo Excel|*.xls' else saveDialog.Filter := 'Arquivo PDF|*.pdf|Arquivo Texto|*.txt|Arquivo HTML|*.html|Arquivo RDPrint|*.rdp'; saveDialog.DefaultExt := 'pdf'; saveDialog.FilterIndex := 1; if saveDialog.Execute then edtAnexo.Text := saveDialog.FileName else edtAnexo.Text := GetCurrentDir + '\Relatorio.pdf'; saveDialog.Free; end; procedure TfrmEnviarEmail.rdpFormatoAnexoExit(Sender: TObject); begin case rdpFormatoAnexo.ItemIndex of 0: StringReplace(edtAnexo.Text, ExtractFileExt(edtAnexo.Text), 'pdf', []); 1: StringReplace(edtAnexo.Text, ExtractFileExt(edtAnexo.Text), 'html', []); 2: StringReplace(edtAnexo.Text, ExtractFileExt(edtAnexo.Text), 'txt', []); 3: if XLS then StringReplace(edtAnexo.Text, ExtractFileExt(edtAnexo.Text), 'rdp', []) else StringReplace(edtAnexo.Text, ExtractFileExt(edtAnexo.Text), 'rdp', []) end; end; { TSendMailThread } constructor TSendMailThread.Create; begin // FOwner := AOwner; smtp := TSMTPSend.Create; slmsg_Lines := TStringList.Create; sCC := TStringList.Create; sFrom := ''; sTo := ''; FreeOnTerminate := true; inherited Create(true); end; destructor TSendMailThread.Destroy; begin slmsg_Lines.Free; sCC.Free; smtp.Free; inherited; end; procedure TSendMailThread.DoHandleException; begin if FException is Exception then Application.ShowException(FException) else Sysutils.ShowException(FException, nil); end; procedure TSendMailThread.Execute; var i : Integer; begin inherited; try Terminado := False; try if not smtp.Login() then raise Exception.Create('SMTP ERROR: Login:' + smtp.EnhCodeString + sLineBreak + smtp.FullResult.Text); if not smtp.MailFrom(sFrom, length(sFrom)) then raise Exception.Create('SMTP ERROR: MailFrom:' + smtp.EnhCodeString + sLineBreak + smtp.FullResult.Text); if not smtp.MailTo(sTo) then raise Exception.Create('SMTP ERROR: MailTo:' + smtp.EnhCodeString + sLineBreak + smtp.FullResult.Text); if (sCC <> nil) then begin for i := 0 to sCC.Count - 1 do begin if not smtp.MailTo(sCC.Strings[i]) then raise Exception.Create('SMTP ERROR: MailTo:' + smtp.EnhCodeString + sLineBreak + smtp.FullResult.Text); end; end; if not smtp.MailData(slmsg_Lines) then raise Exception.Create('SMTP ERROR: MailData:' + smtp.EnhCodeString + sLineBreak + smtp.FullResult.Text); if not smtp.Logout() then raise Exception.Create('SMTP ERROR: Logout:' + smtp.EnhCodeString + sLineBreak + smtp.FullResult.Text); finally try smtp.Sock.CloseSocket; except end; Terminado := true; end; except Terminado := true; // Alterado por Italo em 21/09/2010 HandleException; end; end; procedure TSendMailThread.HandleException; begin FException := Exception(ExceptObject); try // Não mostra mensagens de EAbort if not (FException is EAbort) then Synchronize(DoHandleException); finally FException := nil; end; end; end.
program QueueV5; //**zero-based*// (* procedures: 1. init 2. enqueue 3. dequeue functions: 1. isFull 2. isEmpty *) uses crt; const size = 10; type queueType = record front, rear : Integer; data : array[0..size-1] of Integer; end; var q : queueType; response : string; x : Integer; function isFull(q : queueType):Boolean; begin isFull := (q.front = (q.rear + 1) mod 10 ) and (q.data[q.front] <> 0); //** */ //q.rear is initialized to 0 so no q.data[0] end; function isEmpty(q : queueType):Boolean; begin isEmpty := (q.front = (q.rear + 1) mod 10 ) and (q.data[q.front] = 0); //** */ end; procedure init(var q : queueType); var i : Integer; begin q.front := 0; q.rear := size - 1; //##?????? buggsssss no pc to debbuuuugggggggggg for i := 0 to size-1 do q.data[i] := 0; end; procedure enqueue(var q : queueType; x : Integer); begin if not isFull(q) then begin q.rear := (q.rear + 1) mod size; //** */ q.data[q.rear] := x; end; end; procedure dequeue(var q : queueType; var x : Integer); begin if not isEmpty(q) then begin x := q.data[q.front]; q.data[q.front] := 0; q.front := (q.front + 1) mod size; //** */ end; end; procedure printQueue(q : queueType); var i : Integer; begin for i := 1 to size do WriteLn('|':4, i, '| ', q.data[i]:5); WriteLn('Front: ', q.front, ' Rear: ', q.rear); end; begin writeln('Queue:'); init(q); repeat WriteLn; writeln('1.Enqueue data') ; writeln('2.Dequeue data'); write('> '); readln(response); if response = '1' then begin if not isFull(q) then begin write('Enter the data to enqueue > '); readln(x); enqueue(q, x); end else begin TextColor(Red); writeln('Stack overflow may occur :)'); TextColor(lightgray); end; end else if response = '2' then begin if not isEmpty(q) then begin dequeue(q, x); writeln('Dequeued data is ', x); end else begin TextColor(Red); WriteLn('Stack underflow may occur :/'); TextColor(lightgray); end; end; printQueue(q); until upcase(response) = 'EXIT'; end.
unit nevActiveHyperlink; {* Активная гиперссылка } // Модуль: "w:\common\components\gui\Garant\Everest\nevActiveHyperlink.pas" // Стереотип: "SimpleClass" // Элемент модели: "TnevActiveHyperlink" MUID: (4A27C4D20100) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface {$If Defined(evNeedHotSpot)} uses l3IntfUses , l3CProtoObject , nevTools , l3Variant ; type TnevActiveHyperlink = class; InevActiveHyperlink = interface(InevActiveElement) ['{2FAD6248-B71E-4E2F-8F01-263AE880319D}'] function Get_Hyperlink: Tl3Tag; property Hyperlink: Tl3Tag read Get_Hyperlink; end;//InevActiveHyperlink TnevActiveHyperlink = class(Tl3CProtoObject, InevActiveHyperlink) {* Активная гиперссылка } private f_Para: InevPara; f_Hyperlink: Tl3Tag; protected function IsSame(const anElement: InevActiveElement): Boolean; function Get_Hyperlink: Tl3Tag; function Get_Para: InevPara; procedure Invalidate; {* Перерисовывает область активного элемента } procedure Cleanup; override; {* Функция очистки полей объекта. } {$If NOT Defined(DesignTimeLibrary)} class function IsCacheable: Boolean; override; {* функция класса, определяющая могут ли объекты данного класса попадать в кэш повторного использования. } {$IfEnd} // NOT Defined(DesignTimeLibrary) public constructor Create(const aPara: InevPara; aHyperlink: Tl3Variant); reintroduce; class function Make(const aPara: InevPara; aHyperlink: Tl3Variant): InevActiveHyperlink; reintroduce; end;//TnevActiveHyperlink {$IfEnd} // Defined(evNeedHotSpot) implementation {$If Defined(evNeedHotSpot)} uses l3ImplUses , SysUtils , k2Tags //#UC START# *4A27C4D20100impl_uses* //#UC END# *4A27C4D20100impl_uses* ; constructor TnevActiveHyperlink.Create(const aPara: InevPara; aHyperlink: Tl3Variant); //#UC START# *4A27C50D027C_4A27C4D20100_var* //#UC END# *4A27C50D027C_4A27C4D20100_var* begin //#UC START# *4A27C50D027C_4A27C4D20100_impl* inherited Create; Assert(aPara <> nil); Assert(aHyperlink <> nil); f_Para := aPara; aHyperlink.SetRef(f_Hyperlink); //#UC END# *4A27C50D027C_4A27C4D20100_impl* end;//TnevActiveHyperlink.Create class function TnevActiveHyperlink.Make(const aPara: InevPara; aHyperlink: Tl3Variant): InevActiveHyperlink; var l_Inst : TnevActiveHyperlink; begin l_Inst := Create(aPara, aHyperlink); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TnevActiveHyperlink.Make function TnevActiveHyperlink.IsSame(const anElement: InevActiveElement): Boolean; //#UC START# *4A27C48E017F_4A27C4D20100_var* var l_E : InevActiveHyperlink; l_HL : Tl3Variant; //#UC END# *4A27C48E017F_4A27C4D20100_var* begin //#UC START# *4A27C48E017F_4A27C4D20100_impl* Result := false; if Supports(anElement, InevActiveHyperlink, l_E) then try if f_Para.AsObject.IsSame(l_E.Para.AsObject) then begin l_HL := l_E.Hyperlink; Result := f_Hyperlink.IsSame(l_HL); if not Result then // - пытаемся обработать многослойные конструкции Result := //(f_Hyperlink.TagType.ID = l_HL.TagType.ID) AND // http://mdp.garant.ru/pages/viewpage.action?pageId=176751058 // - не надо сравнивать типы тегов, т.к. гиперссылка может перекрывать // другое оформление и поверх этого оформления надо показывать // стиль активной гиперссылки (l_HL.IntA[k2_tiStart] >= f_Hyperlink.IntA[k2_tiStart]) AND (l_HL.IntA[k2_tiFinish] <= f_Hyperlink.IntA[k2_tiFinish]); end;//f_Para.IsSame(l_E.Para) finally l_E := nil; end;//try..finally //#UC END# *4A27C48E017F_4A27C4D20100_impl* end;//TnevActiveHyperlink.IsSame function TnevActiveHyperlink.Get_Hyperlink: Tl3Tag; //#UC START# *4A27C5C600AC_4A27C4D20100get_var* //#UC END# *4A27C5C600AC_4A27C4D20100get_var* begin //#UC START# *4A27C5C600AC_4A27C4D20100get_impl* Result := f_Hyperlink; //#UC END# *4A27C5C600AC_4A27C4D20100get_impl* end;//TnevActiveHyperlink.Get_Hyperlink function TnevActiveHyperlink.Get_Para: InevPara; //#UC START# *4A27C5CD001C_4A27C4D20100get_var* //#UC END# *4A27C5CD001C_4A27C4D20100get_var* begin //#UC START# *4A27C5CD001C_4A27C4D20100get_impl* Result := f_Para; //#UC END# *4A27C5CD001C_4A27C4D20100get_impl* end;//TnevActiveHyperlink.Get_Para procedure TnevActiveHyperlink.Invalidate; {* Перерисовывает область активного элемента } //#UC START# *4FBF5595010C_4A27C4D20100_var* //#UC END# *4FBF5595010C_4A27C4D20100_var* begin //#UC START# *4FBF5595010C_4A27C4D20100_impl* f_Para.Invalidate([]); //#UC END# *4FBF5595010C_4A27C4D20100_impl* end;//TnevActiveHyperlink.Invalidate procedure TnevActiveHyperlink.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_4A27C4D20100_var* //#UC END# *479731C50290_4A27C4D20100_var* begin //#UC START# *479731C50290_4A27C4D20100_impl* f_Para := nil; FreeAndNil(f_Hyperlink); inherited; //#UC END# *479731C50290_4A27C4D20100_impl* end;//TnevActiveHyperlink.Cleanup {$If NOT Defined(DesignTimeLibrary)} class function TnevActiveHyperlink.IsCacheable: Boolean; {* функция класса, определяющая могут ли объекты данного класса попадать в кэш повторного использования. } //#UC START# *47A6FEE600FC_4A27C4D20100_var* //#UC END# *47A6FEE600FC_4A27C4D20100_var* begin //#UC START# *47A6FEE600FC_4A27C4D20100_impl* Result := true; //#UC END# *47A6FEE600FC_4A27C4D20100_impl* end;//TnevActiveHyperlink.IsCacheable {$IfEnd} // NOT Defined(DesignTimeLibrary) {$IfEnd} // Defined(evNeedHotSpot) end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clSoapMessage; interface {$I clVer.inc} {$IFDEF DELPHI7} {$WARN UNSAFE_CODE OFF} {$WARN UNSAFE_TYPE OFF} {$ENDIF} uses {$IFNDEF DELPHIXE2} Windows, Classes, SysUtils, Variants, msxml, {$ELSE} Winapi.Windows, System.Classes, System.SysUtils, System.Variants, Winapi.msxml, {$ENDIF} clCertificate, clCertificateStore, clCryptUtils, clHttpRequest, clCryptAPI, clSoapSecurity, clUtils, clHeaderFieldList, clHttpHeader, clWUtils; type TclGetSoapSigningCertificateEvent = procedure (Sender: TObject; AKeyInfo: TclXmlKeyInfo; var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var Handled: Boolean) of object; TclGetSoapEncryptionCertificateEvent = procedure (Sender: TObject; AKeyInfo: TclXmlKeyInfo; var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var AStoreName: string; var AStoreLocation: TclCertificateStoreLocation; var Handled: Boolean) of object; TclSoapVersion = (svSoap1_1, svSoap1_2); TclSoapSecurityInfo = class(TCollectionItem) private FKeyReferenceID: string; FKeyID: string; FID: string; FKeySecurityTokenReferenceID: string; FKeyClassName: string; procedure SetID(const Value: string); procedure SetKeyID(const Value: string); procedure SetKeyReferenceID(const Value: string); procedure SetKeySecurityTokenReferenceID(const Value: string); procedure SetKeyClassName(const Value: string); function GetKeyClassType: TclXmlKeyInfoClass; protected procedure Update; virtual; function GenerateKeyReferenceID(AConfig: TclXmlSecurityConfig): string; virtual; procedure DoCreate; virtual; procedure DoPropertyChanged(Sender: TObject); public constructor Create(Collection: TCollection); override; procedure Assign(Source: TPersistent); override; procedure Clear; virtual; procedure AssignKeyInfo(AKeyInfo: TclXmlKeyInfo); virtual; function CreateKeyInfo(AConfig: TclXmlSecurityConfig): TclXmlKeyInfo; virtual; published property ID: string read FID write SetID; property KeyClassName: string read FKeyClassName write SetKeyClassName; property KeyID: string read FKeyID write SetKeyID; property KeySecurityTokenReferenceID: string read FKeySecurityTokenReferenceID write SetKeySecurityTokenReferenceID; property KeyReferenceID: string read FKeyReferenceID write SetKeyReferenceID; end; TclSoapEncryptedKeyInfo = class(TclSoapSecurityInfo) private FEncryptionMethod: string; FReferences: TclXmlEncryptReferenceList; FOnChange: TNotifyEvent; FOwner: TPersistent; procedure SetEncryptionMethod(const Value: string); procedure SetReferences(const Value: TclXmlEncryptReferenceList); protected function GetOwner: TPersistent; override; procedure Update; override; procedure DoCreate; override; public constructor Create(Collection: TCollection); overload; override; constructor Create(Collection: TCollection; AOwner: TPersistent); reintroduce; overload; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure Clear; override; procedure AssignEncryptedKeyInfo(AEncryptedKey: TclXmlEncryptedKey); virtual; function CreateEncryptedKey(AEncryptReferences: TclXmlEncryptReferenceList; AConfig: TclXmlSecurityConfig): TclXmlEncryptedKey; virtual; published property EncryptionMethod: string read FEncryptionMethod write SetEncryptionMethod; property References: TclXmlEncryptReferenceList read FReferences write SetReferences; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; TclSoapSignatureInfo = class(TclSoapSecurityInfo) private FSignatureMethod: string; FCanonicalizationMethod: string; FReferences: TclXmlSignReferenceList; procedure SetCanonicalizationMethod(const Value: string); procedure SetSignatureMethod(const Value: string); procedure SetReferences(const Value: TclXmlSignReferenceList); protected procedure DoCreate; override; public destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure Clear; override; procedure AssignSignatureInfo(ASignature: TclXmlSignature); virtual; function CreateSignature(AConfig: TclXmlSecurityConfig): TclXmlSignature; virtual; published property CanonicalizationMethod: string read FCanonicalizationMethod write SetCanonicalizationMethod; property SignatureMethod: string read FSignatureMethod write SetSignatureMethod; property References: TclXmlSignReferenceList read FReferences write SetReferences; end; TclSoapSignatureList = class(TOwnedCollection) private FOnChange: TNotifyEvent; function GetItem(Index: Integer): TclSoapSignatureInfo; procedure SetItem(Index: Integer; const Value: TclSoapSignatureInfo); protected procedure Update(Item: TCollectionItem); override; public function Add: TclSoapSignatureInfo; function ItemById(const AID: string): TclSoapSignatureInfo; property Items[Index: Integer]: TclSoapSignatureInfo read GetItem write SetItem; default; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; TclSoapTimestamp = class(TPersistent) private FExpires: string; FCreated: string; FID: string; FConfig: TclXmlSecurityConfig; FOnChange: TNotifyEvent; procedure SetCreated(const Value: string); procedure SetExpires(const Value: string); procedure SetID(const Value: string); protected procedure Update; virtual; public constructor Create(AConfig: TclXmlSecurityConfig); procedure Assign(Source: TPersistent); override; procedure Clear; virtual; procedure Build(const ARoot: IXMLDOMNode); virtual; procedure Parse(const ASecurity: IXMLDOMNode); virtual; property Config: TclXmlSecurityConfig read FConfig; property OnChange: TNotifyEvent read FOnChange write FOnChange; published property ID: string read FID write SetID; property Created: string read FCreated write SetCreated; property Expires: string read FExpires write SetExpires; end; TclSoapAddressItem = class(TCollectionItem) private FName: string; FID: string; FValue: string; procedure SetID(const Value: string); procedure SetName(const Value: string); procedure SetValue(const AValue: string); public procedure Assign(Source: TPersistent); override; published property Name: string read FName write SetName; property ID: string read FID write SetID; property Value: string read FValue write SetValue; end; TclSoapAddressList = class(TOwnedCollection) private FOnChange: TNotifyEvent; FConfig: TclXmlSecurityConfig; function GetItem(Index: Integer): TclSoapAddressItem; procedure SetItem(Index: Integer; const Value: TclSoapAddressItem); protected procedure Update(Item: TCollectionItem); override; public constructor Create(AOwner: TPersistent; ItemClass: TCollectionItemClass; AConfig: TclXmlSecurityConfig); function Add: TclSoapAddressItem; function AddItem(const AName, AID, AValue: string): TclSoapAddressItem; function ItemByName(const AName: string): TclSoapAddressItem; function ItemById(const AID: string): TclSoapAddressItem; procedure Build(const ARoot: IXMLDOMNode); virtual; procedure Parse(const ARoot: IXMLDOMNode); virtual; property Items[Index: Integer]: TclSoapAddressItem read GetItem write SetItem; default; property Config: TclXmlSecurityConfig read FConfig; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; TclSoapMessageHeader = class(TclHttpRequestHeader) private FStart: string; FSoapAction: string; FSubType: string; procedure SetSoapAction(const Value: string); procedure SetStart(const Value: string); procedure SetSubType(const Value: string); protected procedure RegisterFields; override; procedure InternalParseHeader(AFieldList: TclHeaderFieldList); override; procedure InternalAssignHeader(AFieldList: TclHeaderFieldList); override; procedure ParseContentType(AFieldList: TclHeaderFieldList); override; procedure AssignContentType(AFieldList: TclHeaderFieldList); override; public procedure Clear; override; procedure Assign(Source: TPersistent); override; published property Start: string read FStart write SetStart; property SubType: string read FSubType write SetSubType; property SoapAction: string read FSoapAction write SetSoapAction; end; TclSoapMessage = class; TclSoapMessageItem = class(TclHttpRequestItem) private FContentID: string; FContentType: string; FContentLocation: string; FContentTransferEncoding: string; FExtraFields: TStrings; FCharSet: string; FKnownFields: TStrings; procedure SetContentID(const Value: string); procedure SetContentLocation(const Value: string); procedure SetContentTransferEncoding(const Value: string); procedure SetContentType(const Value: string); procedure SetCharSet(const Value: string); procedure SetExtraFields(const Value: TStrings); procedure ListChangeEvent(Sender: TObject); function GetHeader: TStream; procedure ParseExtraFields(AFieldList: TclHeaderFieldList); function GetSoapMessage: TclSoapMessage; protected function GetDataStream: TStream; override; procedure ReadData(Reader: TReader); override; procedure WriteData(Writer: TWriter); override; procedure ParseHeader(AFieldList: TclHeaderFieldList); override; function GetCharSet: string; override; procedure RegisterField(const AField: string); procedure RegisterFields; virtual; public constructor Create(AOwner: TclHttpRequestItemList); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; property SoapMessage: TclSoapMessage read GetSoapMessage; property ContentType: string read FContentType write SetContentType; property CharSet: string read FCharSet write SetCharSet; property ContentID: string read FContentID write SetContentID; property ContentLocation: string read FContentLocation write SetContentLocation; property ContentTransferEncoding: string read FContentTransferEncoding write SetContentTransferEncoding; property ExtraFields: TStrings read FExtraFields write SetExtraFields; end; TclXmlItem = class(TclSoapMessageItem) private FXmlData: string; procedure SetXmlData(const Value: string); protected procedure ReadData(Reader: TReader); override; procedure WriteData(Writer: TWriter); override; procedure AddData(const AData: TclByteArray; AIndex, ACount: Integer); override; procedure AfterAddData; override; function GetDataStream: TStream; override; public procedure Assign(Source: TPersistent); override; property XmlData: string read FXmlData write SetXmlData; end; TclAttachmentItem = class(TclSoapMessageItem) protected procedure AddData(const AData: TclByteArray; AIndex, ACount: Integer); override; procedure AfterAddData; override; function GetDataStream: TStream; override; end; TclSoapMessage = class(TclHttpRequest) private FSecurityConfig: TclXmlSecurityConfig; FCertificates: TclCertificateStore; FInternalCertStore: TclCertificateStore; FEncodingStyle: string; FNamespaces: TclSoapNameSpaceList; FTimestamp: TclSoapTimestamp; FAddressing: TclSoapAddressList; FBodyID: string; FSignatures: TclSoapSignatureList; FEncryptedKey: TclSoapEncryptedKeyInfo; FOnGetEncryptionCertificate: TclGetSoapEncryptionCertificateEvent; FOnGetSigningCertificate: TclGetSoapSigningCertificateEvent; FSoapVersion: TclSoapVersion; procedure DoPropertyChanged(Sender: TObject); function GetNameSpace(ANode: IXMLDOMNode): string; procedure GetSigningCertificate(AKeyInfo: TclXmlKeyInfo; var ACertificate: TclCertificate; var AStoreName: string; var AStoreLocation: TclCertificateStoreLocation); procedure GetEncryptionCertificate(AKeyInfo: TclXmlKeyInfo; var ACertificate: TclCertificate; var AStoreName: string; var AStoreLocation: TclCertificateStoreLocation); procedure CheckRequestExists; function GetHeader: TclSoapMessageHeader; procedure SetHeader(const Value: TclSoapMessageHeader); procedure SetEncodingStyle(const Value: string); procedure SetNamespaces(const Value: TclSoapNameSpaceList); function AddWsdlEnvelope(const AMessage: string): string; procedure SetTimestamp(const Value: TclSoapTimestamp); function GetIsSecured(const ANodeName: string): Boolean; function GetIsSigned: Boolean; function GetIsEncrypted: Boolean; procedure SetAddressing(const Value: TclSoapAddressList); procedure SetBodyID(const Value: string); procedure SetSecurityConfig(const Value: TclXmlSecurityConfig); procedure SetEncryptedKey(const Value: TclSoapEncryptedKeyInfo); procedure SetSignatures(const Value: TclSoapSignatureList); procedure SetSoapVersion(const Value: TclSoapVersion); function GetIdName(const ANamespace: string): string; procedure CreateSignatures(const ADom: IXMLDOMDocument); procedure CreateSignature(ASignature: TclXmlSignature; const ADom: IXMLDOMDocument); procedure VerifySignatures(const ASecurity: IXMLDOMNode; const ADom: IXMLDOMDocument); procedure VerifySignature(ASignature: TclXmlSignature; const ADom: IXMLDOMDocument); procedure AssignBodyIdIfNeed(const ADom: IXMLDOMDocument); procedure ExtractBodyId(const ADom: IXMLDOMDocument); procedure DecryptSessionKey(ASessionKey: TclXmlEncryptedKey); procedure EncryptSessionKey(ASessionKey: TclXmlEncryptedKey; const ASecurity: IXMLDOMNode); function GetInternalCertStore: TclCertificateStore; procedure CheckSoapVersion; protected function ParseSoapVersion(const AEnvelope: string): TclSoapVersion; virtual; function CreateHeader: TclHttpRequestHeader; override; function CreateItem(AFieldList: TclHeaderFieldList): TclHttpRequestItem; override; procedure CreateSingleItem(AStream: TStream); override; function GetContentType: string; override; procedure InitHeader; override; procedure DoGetSigningCertificate(AKeyInfo: TclXmlKeyInfo; var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var Handled: Boolean); dynamic; procedure DoGetEncryptionCertificate(AKeyInfo: TclXmlKeyInfo; var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var AStoreName: string; var AStoreLocation: TclCertificateStoreLocation; var Handled: Boolean); dynamic; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure BuildSoapMessage(const AEnvelope: string); overload; procedure BuildSoapMessage(const AEnvelope, ASoapAction: string); overload; procedure BuildSoapMessage(AEnvelope: TStrings); overload; procedure BuildSoapMessage(AEnvelope: TStrings; const ASoapAction: string); overload; procedure BuildSoapMessage(AEnvelope: IXMLDOMDocument); overload; procedure BuildSoapMessage(AEnvelope: IXMLDOMDocument; const ASoapAction: string); overload; procedure BuildSoapWSDL(const AMethodURI, AMethod: string; AParamNames, AParamValues: TStrings); overload; procedure BuildSoapWSDL(const AMethodURI, AMethod: string; AParamNames, AParamValues, AParamAttrs: TStrings); overload; procedure BuildSoapWSDL(const AMethodURI, AMethod: string; const AParamNames, AParamValues: array of string); overload; procedure BuildSoapWSDL(const AMethodURI, AMethod: string; const AParamNames, AParamValues, AParamAttrs: array of string); overload; function AddXmlData(const AXmlData: string): TclXmlItem; function AddAttachment: TclAttachmentItem; procedure Sign; procedure Verify; procedure Clear; override; procedure Encrypt; procedure Decrypt; property IsSigned: Boolean read GetIsSigned; property IsEncrypted: Boolean read GetIsEncrypted; property Certificates: TclCertificateStore read FCertificates; published property Header: TclSoapMessageHeader read GetHeader write SetHeader; property Timestamp: TclSoapTimestamp read FTimestamp write SetTimestamp; property Addressing: TclSoapAddressList read FAddressing write SetAddressing; property BodyID: string read FBodyID write SetBodyID; property Signatures: TclSoapSignatureList read FSignatures write SetSignatures; property EncryptedKey: TclSoapEncryptedKeyInfo read FEncryptedKey write SetEncryptedKey; property Namespaces: TclSoapNameSpaceList read FNamespaces write SetNamespaces; property EncodingStyle: string read FEncodingStyle write SetEncodingStyle; property SoapVersion: TclSoapVersion read FSoapVersion write SetSoapVersion default svSoap1_2; property SecurityConfig: TclXmlSecurityConfig read FSecurityConfig write SetSecurityConfig; property OnGetSigningCertificate: TclGetSoapSigningCertificateEvent read FOnGetSigningCertificate write FOnGetSigningCertificate; property OnGetEncryptionCertificate: TclGetSoapEncryptionCertificateEvent read FOnGetEncryptionCertificate write FOnGetEncryptionCertificate; end; implementation uses {$IFNDEF DELPHIXE2} {$IFDEF DEMO}Forms, clEncryptor, clHtmlParser, {$ENDIF} {$ELSE} {$IFDEF DEMO}Vcl.Forms, clEncryptor, clHtmlParser, {$ENDIF} {$ENDIF} clEncoder, clXmlUtils, clTranslator, clStreams, clSoapUtils, clCryptRandom, clXmlCanonicalizer20010315Excl, clXmlCanonicalizerUtils {$IFDEF LOGGER}, clLogger{$ENDIF}; const cSoapHeaderContentType: array[TclSoapVersion] of string = ('text/xml', 'application/soap+xml'); cEnvelopeNameSpaceName: array[TclSoapVersion] of string = (envelopeNameSpaceName, soap12NameSpaceName); { TclSoapSecurityInfo } procedure TclSoapSecurityInfo.Assign(Source: TPersistent); var src: TclSoapSecurityInfo; begin if (Source is TclSoapSecurityInfo) then begin src := (Source as TclSoapSecurityInfo); KeyReferenceID := src.KeyReferenceID; KeyID := src.KeyID; ID := src.ID; KeySecurityTokenReferenceID := src.KeySecurityTokenReferenceID; KeyClassName := src.KeyClassName; end else begin inherited Assign(Source); end; end; procedure TclSoapSecurityInfo.AssignKeyInfo(AKeyInfo: TclXmlKeyInfo); begin if (AKeyInfo = nil) then begin KeyClassName := ''; Exit; end; KeyID := AKeyInfo.ID; KeySecurityTokenReferenceID := AKeyInfo.SecurityTokenReferenceID; KeyClassName := AKeyInfo.ClassName; if (AKeyInfo is TclXmlX509KeyInfo) then begin KeyReferenceID := UriReference2Id(TclXmlX509KeyInfo(AKeyInfo).URI); end; end; procedure TclSoapSecurityInfo.Clear; begin KeyReferenceID := ''; KeyID := ''; ID := ''; KeySecurityTokenReferenceID := ''; KeyClassName := ''; end; constructor TclSoapSecurityInfo.Create(Collection: TCollection); begin inherited Create(Collection); DoCreate(); Clear(); end; function TclSoapSecurityInfo.CreateKeyInfo(AConfig: TclXmlSecurityConfig): TclXmlKeyInfo; begin if (FKeyClassName = '') then begin Result := nil; Exit; end; Result := GetKeyClassType().Create(AConfig); Result.ID := KeyID; Result.SecurityTokenReferenceID := KeySecurityTokenReferenceID; if (Result is TclXmlX509KeyInfo) then begin if (KeyReferenceID = '') then begin KeyReferenceID := GenerateKeyReferenceID(AConfig); end; TclXmlX509KeyInfo(Result).URI := Id2UriReference(KeyReferenceID); end; end; procedure TclSoapSecurityInfo.DoCreate; begin end; procedure TclSoapSecurityInfo.DoPropertyChanged(Sender: TObject); begin Update(); end; function TclSoapSecurityInfo.GenerateKeyReferenceID(AConfig: TclXmlSecurityConfig): string; var buf: TclByteArray; begin buf := GenerateRandomData(16, AConfig.CSP, AConfig.ProviderType); Result := 'X509-' + UpperCase(BytesToHex(buf)); end; function TclSoapSecurityInfo.GetKeyClassType: TclXmlKeyInfoClass; var i: Integer; begin for i := 0 to TclXmlKeyInfo.RegisteredKeyInfo.Count - 1 do begin Result := TclXmlKeyInfoClass(TclXmlKeyInfo.RegisteredKeyInfo[i]); if (FKeyClassName = Result.ClassName) then begin Exit; end; end; raise EclSoapMessageError.Create(SoapUnknownKeyClassType, SoapUnknownKeyClassTypeCode); end; procedure TclSoapSecurityInfo.SetID(const Value: string); begin if (FID <> Value) then begin FID := Value; Update(); end; end; procedure TclSoapSecurityInfo.SetKeyClassName(const Value: string); begin if (FKeyClassName <> Value) then begin FKeyClassName := Value; Update(); end; end; procedure TclSoapSecurityInfo.SetKeyID(const Value: string); begin if (FKeyID <> Value) then begin FKeyID := Value; Update(); end; end; procedure TclSoapSecurityInfo.SetKeyReferenceID(const Value: string); begin if (FKeyReferenceID <> Value) then begin FKeyReferenceID := Value; Update(); end; end; procedure TclSoapSecurityInfo.SetKeySecurityTokenReferenceID(const Value: string); begin if (FKeySecurityTokenReferenceID <> Value) then begin FKeySecurityTokenReferenceID := Value; Update(); end; end; procedure TclSoapSecurityInfo.Update; begin Changed(False); end; { TclSoapEncryptedKeyInfo } procedure TclSoapEncryptedKeyInfo.Assign(Source: TPersistent); begin inherited Assign(Source); if (Source is TclSoapEncryptedKeyInfo) then begin EncryptionMethod := (Source as TclSoapEncryptedKeyInfo).EncryptionMethod; References := (Source as TclSoapEncryptedKeyInfo).References; end; end; procedure TclSoapEncryptedKeyInfo.AssignEncryptedKeyInfo(AEncryptedKey: TclXmlEncryptedKey); begin Clear(); ID := AEncryptedKey.ID; EncryptionMethod := AEncryptedKey.EncryptionMethod; References := AEncryptedKey.ReferenceList; AssignKeyInfo(AEncryptedKey.KeyInfo); end; procedure TclSoapEncryptedKeyInfo.Clear; begin inherited Clear(); KeyClassName := TclXmlSKIKeyInfo.ClassName; EncryptionMethod := RSA_OAEP_MGF1P_AlgorithmName; References.Clear(); end; constructor TclSoapEncryptedKeyInfo.Create(Collection: TCollection); begin inherited Create(Collection); FOwner := nil; end; constructor TclSoapEncryptedKeyInfo.Create(Collection: TCollection; AOwner: TPersistent); begin inherited Create(Collection); FOwner := AOwner; end; function TclSoapEncryptedKeyInfo.CreateEncryptedKey(AEncryptReferences: TclXmlEncryptReferenceList; AConfig: TclXmlSecurityConfig): TclXmlEncryptedKey; begin Result := TclXmlEncryptedKey.CreateInstance(EncryptionMethod, AEncryptReferences, AConfig); try Result.ID := ID; Result.EncryptionMethod := EncryptionMethod; Result.KeyInfo := CreateKeyInfo(AConfig); except Result.Free(); raise; end; end; destructor TclSoapEncryptedKeyInfo.Destroy; begin FReferences.Free(); inherited Destroy(); end; procedure TclSoapEncryptedKeyInfo.DoCreate; begin inherited DoCreate(); FReferences := TclXmlEncryptReferenceList.Create(Self, TclXmlEncryptReference); FReferences.OnChange := DoPropertyChanged; end; function TclSoapEncryptedKeyInfo.GetOwner: TPersistent; begin Result := FOwner; end; procedure TclSoapEncryptedKeyInfo.SetEncryptionMethod(const Value: string); begin if (FEncryptionMethod <> Value) then begin FEncryptionMethod := Value; Update(); end; end; procedure TclSoapEncryptedKeyInfo.SetReferences(const Value: TclXmlEncryptReferenceList); begin FReferences.Assign(Value); end; procedure TclSoapEncryptedKeyInfo.Update; begin inherited Update(); if Assigned(OnChange) then begin OnChange(Self); end; end; { TclSoapSignatureInfo } procedure TclSoapSignatureInfo.Assign(Source: TPersistent); begin inherited Assign(Source); if (Source is TclSoapSignatureInfo) then begin CanonicalizationMethod := (Source as TclSoapSignatureInfo).CanonicalizationMethod; SignatureMethod := (Source as TclSoapSignatureInfo).SignatureMethod; References := (Source as TclSoapSignatureInfo).References; end; end; procedure TclSoapSignatureInfo.AssignSignatureInfo(ASignature: TclXmlSignature); begin Clear(); ID := ASignature.ID; SignatureMethod := ASignature.SignatureMethod; CanonicalizationMethod := ASignature.CanonicalizationMethod; References := ASignature.ReferenceList; AssignKeyInfo(ASignature.KeyInfo); end; procedure TclSoapSignatureInfo.Clear; begin inherited Clear(); KeyClassName := TclXmlX509KeyInfo.ClassName; CanonicalizationMethod := ALGO_ID_C14N_EXCL_OMIT_COMMENTS; SignatureMethod := RSA_SHA1_AlgorithmName; References.Clear(); end; function TclSoapSignatureInfo.CreateSignature(AConfig: TclXmlSecurityConfig): TclXmlSignature; begin Result := TclXmlSignature.CreateInstance(SignatureMethod, References, AConfig); try Result.ID := ID; Result.CanonicalizationMethod := CanonicalizationMethod; Result.KeyInfo := CreateKeyInfo(AConfig); except Result.Free(); raise; end; end; destructor TclSoapSignatureInfo.Destroy; begin FReferences.Free(); inherited Destroy(); end; procedure TclSoapSignatureInfo.DoCreate; begin inherited DoCreate(); FReferences := TclXmlSignReferenceList.Create(Self, TclXmlSignReference); FReferences.OnChange := DoPropertyChanged; end; procedure TclSoapSignatureInfo.SetCanonicalizationMethod(const Value: string); begin if (FCanonicalizationMethod <> Value) then begin FCanonicalizationMethod := Value; Update(); end; end; procedure TclSoapSignatureInfo.SetReferences(const Value: TclXmlSignReferenceList); begin FReferences.Assign(Value); end; procedure TclSoapSignatureInfo.SetSignatureMethod(const Value: string); begin if (FSignatureMethod <> Value) then begin FSignatureMethod := Value; Update(); end; end; { TclSoapMessage } procedure TclSoapMessage.BuildSoapMessage(AEnvelope: TStrings; const ASoapAction: string); begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsHttpRequestDemoDisplayed) and (not IsCertDemoDisplayed) and (not IsEncoderDemoDisplayed) and (not IsEncryptorDemoDisplayed) and (not IsHtmlDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsHttpRequestDemoDisplayed := True; IsCertDemoDisplayed := True; IsEncoderDemoDisplayed := True; IsEncryptorDemoDisplayed := True; IsHtmlDemoDisplayed := True; {$ENDIF} end; {$ENDIF} SafeClear(); AddXmlData(AEnvelope.Text).CharSet := Header.CharSet; Header.ContentType := cSoapHeaderContentType[SoapVersion]; if (SoapVersion = svSoap1_1) then begin Header.SoapAction := ASoapAction; end; end; constructor TclSoapMessage.Create(AOwner: TComponent); begin inherited Create(AOwner); InitSoapSecurity(); FSecurityConfig := TclXmlSecurityConfig.Create(Self); FSecurityConfig.OnChange := DoPropertyChanged; FEncryptedKey := TclSoapEncryptedKeyInfo.Create(nil, Self); FEncryptedKey.OnChange := DoPropertyChanged; FSignatures := TclSoapSignatureList.Create(Self, TclSoapSignatureInfo); FSignatures.OnChange := DoPropertyChanged; FAddressing := TclSoapAddressList.Create(Self, TclSoapAddressItem, SecurityConfig); FAddressing.OnChange := DoPropertyChanged; FTimestamp := TclSoapTimestamp.Create(SecurityConfig); FTimestamp.OnChange := DoPropertyChanged; FCertificates := TclCertificateStore.Create(nil); FCertificates.StoreName := 'addressbook'; FNamespaces := TclSoapNameSpaceList.Create(Self, TclSoapNameSpace); FNamespaces.OnChange := DoPropertyChanged; FEncodingStyle := DefaultEncodingStyle; FSoapVersion := svSoap1_2; end; procedure TclSoapMessage.Decrypt; var dom: IXMLDOMDocument; headerNode, security: IXMLDOMNode; sessionKey: TclXmlEncryptedKey; ref: TclXmlEncryptReferenceList; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsHttpRequestDemoDisplayed) and (not IsCertDemoDisplayed) and (not IsEncoderDemoDisplayed) and (not IsEncryptorDemoDisplayed) and (not IsHtmlDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsHttpRequestDemoDisplayed := True; IsCertDemoDisplayed := True; IsEncoderDemoDisplayed := True; IsEncryptorDemoDisplayed := True; IsHtmlDemoDisplayed := True; {$ENDIF} end; {$ENDIF} if not IsEncrypted then begin raise EclSoapMessageError.Create(SoapMessageNotEncrypted, SoapMessageNotEncryptedCode); end; CheckSoapVersion(); dom := CoDOMDocument.Create(); dom.validateOnParse := False; dom.preserveWhiteSpace := True; dom.loadXML(XmlCrlfEncode(WideString(TclXmlItem(Self.Items[0]).XmlData))); if (not dom.parsed) then begin raise EclSoapMessageError.Create(dom.parseError.reason, dom.parseError.errorCode); end; headerNode := GetNodeByName(dom.documentElement, 'Header'); if (headerNode = nil) then begin raise EclSoapMessageError.Create(SoapFormatError, SoapFormatErrorCode); end; security := GetNodeByName(headerNode, 'Security'); if (security = nil) then begin raise EclSoapMessageError.Create(SoapFormatError, SoapFormatErrorCode); end; ExtractBodyId(dom); FAddressing.Parse(headerNode); FTimestamp.Parse(security); ref := nil; sessionKey := nil; try ref := TclXmlEncryptReferenceList.Create(nil, TclXmlEncryptReference); sessionKey := TclXmlEncryptedKey.Parse(security, ref, SecurityConfig); DecryptSessionKey(sessionKey); TclXmlItem(Self.Items[0]).XmlData := sessionKey.Decrypt(dom, Header.CharSet); EncryptedKey.AssignEncryptedKeyInfo(sessionKey); finally ref.Free(); sessionKey.Free(); end; if (not IsSigned) then begin RemoveNode(security); end; end; procedure TclSoapMessage.DecryptSessionKey(ASessionKey: TclXmlEncryptedKey); var cert, msgCert: TclCertificate; storeName: string; storeLocation: TclCertificateStoreLocation; begin cert := nil; msgCert := nil; storeName := 'MY'; storeLocation := slCurrentUser; GetEncryptionCertificate(ASessionKey.KeyInfo, cert, storeName, storeLocation); if (ASessionKey.KeyInfo <> nil) then begin GetInternalCertStore().Open(storeName, storeLocation); msgCert := ASessionKey.KeyInfo.GetCertificate(GetInternalCertStore()); if (msgCert <> nil) and (Certificates.FindBySerialNo(msgCert.SerialNumber, msgCert.IssuedBy) = nil) then begin Certificates.Items.Add(msgCert); end; end; if (cert = nil) then begin cert := msgCert; end; ASessionKey.DecryptSessionKey(cert, storeName, storeLocation); end; destructor TclSoapMessage.Destroy; begin FNamespaces.Free(); FCertificates.Free(); FTimestamp.Free(); FAddressing.Free(); FInternalCertStore.Free(); FSignatures.Free(); FEncryptedKey.Free(); FSecurityConfig.Free(); inherited Destroy(); end; procedure TclSoapMessage.DoPropertyChanged(Sender: TObject); begin BeginUpdate(); EndUpdate(); end; procedure TclSoapMessage.SetSoapVersion(const Value: TclSoapVersion); begin if (FSoapVersion <> Value) then begin BeginUpdate(); FSoapVersion := Value; EndUpdate(); end; end; procedure TclSoapMessage.SetTimestamp(const Value: TclSoapTimestamp); begin FTimestamp.Assign(Value); BeginUpdate(); EndUpdate(); end; procedure TclSoapMessage.CheckRequestExists; begin if (Self.Items.Count = 0) or (not (Self.Items[0] is TclSoapMessageItem)) or (TclXmlItem(Self.Items[0]).XmlData = '') then begin raise EclSoapMessageError.Create(RequestEmpty, RequestEmptyCode); end; end; procedure TclSoapMessage.Encrypt; var dom: IXMLDOMDocument; envelope, headerNode, security: IXMLDOMNode; sessionKey: TclXmlEncryptedKey; wsseNameSpace, wsuNameSpace, wsaNameSpace: string; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsHttpRequestDemoDisplayed) and (not IsCertDemoDisplayed) and (not IsEncoderDemoDisplayed) and (not IsEncryptorDemoDisplayed) and (not IsHtmlDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsHttpRequestDemoDisplayed := True; IsCertDemoDisplayed := True; IsEncoderDemoDisplayed := True; IsEncryptorDemoDisplayed := True; IsHtmlDemoDisplayed := True; {$ENDIF} end; {$ENDIF} if (EncryptedKey.References.Count = 0) then begin raise EclSoapMessageError.Create(ReferencesEmpty, ReferencesEmptyCode); end; if IsEncrypted then begin raise EclSoapMessageError.Create(SoapMessageEncrypted, SoapMessageEncryptedCode); end; CheckSoapVersion(); dom := CoDOMDocument.Create(); dom.validateOnParse := False; dom.preserveWhiteSpace := True; dom.loadXML(XmlCrlfEncode(WideString(TclXmlItem(Self.Items[0]).XmlData))); //TODO WideString typecast //use value from GetXmlCharSet() to convert/typecast correctly if (not dom.parsed) then begin raise EclSoapMessageError.Create(dom.parseError.reason, dom.parseError.errorCode); end; AssignBodyIdIfNeed(dom); headerNode := GetNodeByName(dom.documentElement, 'Header'); if (headerNode = nil) then begin envelope := dom.documentElement; if (envelope = nil) or (envelope.baseName <> 'Envelope') then begin raise EclSoapMessageError.Create(SoapFormatError, SoapFormatErrorCode); end; headerNode := dom.createElement(GetSoapNodeName(GetNameSpace(dom.lastChild), 'Header')); envelope.insertBefore(headerNode, envelope.firstChild); end; wsuNameSpace := SecurityConfig.Namespaces.GetPrefix(wsuNameSpaceName); if (GetAttributeValue(headerNode, GetSoapNamespace(wsuNameSpace)) = '') then begin SetAttributeValue(headerNode, GetSoapNamespace(wsuNameSpace), wsuNameSpaceName); end; wsaNameSpace := SecurityConfig.Namespaces.GetPrefix(wsaNameSpaceName); if (FAddressing.Count > 0) and (GetAttributeValue(headerNode, GetSoapNamespace(wsaNameSpace)) = '') then begin SetAttributeValue(headerNode, GetSoapNamespace(wsaNameSpace), wsaNameSpaceName); end; security := GetNodeByName(headerNode, 'Security'); if (security = nil) then begin wsseNameSpace := SecurityConfig.Namespaces.GetPrefix(wsseNameSpaceName); security := dom.createElement(GetSoapNodeName(wsseNameSpace, 'Security')); headerNode.appendChild(security); SetAttributeValue(security, GetSoapNamespace(wsseNameSpace), wsseNameSpaceName); end; FAddressing.Build(headerNode); FTimestamp.Build(security); sessionKey := EncryptedKey.CreateEncryptedKey(EncryptedKey.References, SecurityConfig); try EncryptSessionKey(sessionKey, security); sessionKey.Encrypt(dom, Header.CharSet); finally sessionKey.Free(); end; TclXmlItem(Self.Items[0]).XmlData := string(XmlCrlfDecode(dom.xml)); end; procedure TclSoapMessage.EncryptSessionKey(ASessionKey: TclXmlEncryptedKey; const ASecurity: IXMLDOMNode); var cert: TclCertificate; storeName: string; storeLocation: TclCertificateStoreLocation; begin cert := nil; storeName := 'addressbook'; storeLocation := slCurrentUser; GetEncryptionCertificate(ASessionKey.KeyInfo, cert, storeName, storeLocation); if (cert = nil) then begin raise EclSoapMessageError.Create(CertificateRequired, CertificateRequiredCode); end; ASessionKey.EncryptSessionKey(cert, storeName, storeLocation, ASecurity); end; procedure TclSoapMessage.ExtractBodyId(const ADom: IXMLDOMDocument); var body: IXMLDOMNode; begin body := GetNodeByName(ADom.documentElement, 'Body'); if (body <> nil) then begin FBodyID := GetAttributeValue(body, GetIdName(SecurityConfig.Namespaces.GetPrefix(wsuNameSpaceName))); if (FBodyID = '') then begin FBodyID := GetAttributeValue(body, SecurityConfig.IdName); end; end; end; procedure TclSoapMessage.AssignBodyIdIfNeed(const ADom: IXMLDOMDocument); var body: IXMLDOMNode; wsuNameSpace: string; begin if (BodyID <> '') then begin body := GetNodeByName(ADom.documentElement, 'Body'); if (body <> nil) then begin wsuNameSpace := SecurityConfig.Namespaces.GetPrefix(wsuNameSpaceName); if (GetAttributeValue(body, GetSoapNamespace(wsuNameSpace)) = '') then begin SetAttributeValue(body, GetSoapNamespace(wsuNameSpace), wsuNameSpaceName); end; if (GetAttributeValue(body, GetIdName(wsuNameSpace)) = '') then begin SetAttributeValue(body, GetIdName(wsuNameSpace), BodyID); end; end; end; end; procedure TclSoapMessage.Sign; var dom: IXMLDOMDocument; envelope, headerNode, security: IXMLDOMNode; wsseNameSpace, wsuNameSpace, wsaNameSpace: string; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsHttpRequestDemoDisplayed) and (not IsCertDemoDisplayed) and (not IsEncoderDemoDisplayed) and (not IsEncryptorDemoDisplayed) and (not IsHtmlDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsHttpRequestDemoDisplayed := True; IsCertDemoDisplayed := True; IsEncoderDemoDisplayed := True; IsEncryptorDemoDisplayed := True; IsHtmlDemoDisplayed := True; {$ENDIF} end; {$ENDIF} if (Signatures.Count = 0) then begin raise EclSoapMessageError.Create(SignaturesEmpty, SignaturesEmptyCode); end; CheckSoapVersion(); dom := CoDOMDocument.Create(); dom.validateOnParse := False; dom.preserveWhiteSpace := True; dom.loadXML(XmlCrlfEncode(WideString(TclXmlItem(Self.Items[0]).XmlData))); //TODO WideString typecast //use value from GetXmlCharSet() to convert/typecast correctly if (not dom.parsed) then begin raise EclSoapMessageError.Create(dom.parseError.reason, dom.parseError.errorCode); end; AssignBodyIdIfNeed(dom); headerNode := GetNodeByName(dom.documentElement, 'Header'); if (headerNode = nil) then begin envelope := dom.documentElement; if (envelope = nil) or (envelope.baseName <> 'Envelope') then begin raise EclSoapMessageError.Create(SoapFormatError, SoapFormatErrorCode); end; headerNode := dom.createElement(GetSoapNodeName(GetNameSpace(dom.lastChild), 'Header')); envelope.insertBefore(headerNode, envelope.firstChild); end; wsuNameSpace := SecurityConfig.Namespaces.GetPrefix(wsuNameSpaceName); if (GetAttributeValue(headerNode, GetSoapNamespace(wsuNameSpace)) = '') then begin SetAttributeValue(headerNode, GetSoapNamespace(wsuNameSpace), wsuNameSpaceName); end; wsaNameSpace := SecurityConfig.Namespaces.GetPrefix(wsaNameSpaceName); if (FAddressing.Count > 0) and (GetAttributeValue(headerNode, GetSoapNamespace(wsaNameSpace)) = '') then begin SetAttributeValue(headerNode, GetSoapNamespace(wsaNameSpace), wsaNameSpaceName); end; security := GetNodeByName(headerNode, 'Security'); if (security = nil) then begin wsseNameSpace := SecurityConfig.Namespaces.GetPrefix(wsseNameSpaceName); security := dom.createElement(GetSoapNodeName(wsseNameSpace, 'Security')); headerNode.appendChild(security); SetAttributeValue(security, GetSoapNamespace(wsseNameSpace), wsseNameSpaceName); end; FAddressing.Build(headerNode); FTimestamp.Build(security); CreateSignatures(dom); TclXmlItem(Self.Items[0]).XmlData := string(XmlCrlfDecode(dom.xml)); end; procedure TclSoapMessage.CreateSignatures(const ADom: IXMLDOMDocument); var i: Integer; sig: TclXmlSignature; sigInfo: TclSoapSignatureInfo; begin for i := 0 to Signatures.Count - 1 do begin sigInfo := Signatures[i]; if (sigInfo.References.Count = 0) then begin raise EclSoapMessageError.Create(ReferencesEmpty, ReferencesEmptyCode); end; if (Signatures.Count > 1) and (sigInfo.ID = '') then begin raise EclSoapMessageError.Create(SignatureIdEmpty, SignatureIdEmptyCode); end; sig := sigInfo.CreateSignature(SecurityConfig); try CreateSignature(sig, ADom); finally sig.Free(); end; end; end; procedure TclSoapMessage.VerifySignature(ASignature: TclXmlSignature; const ADom: IXMLDOMDocument); var cert, msgCert: TclCertificate; storeName: string; storeLocation: TclCertificateStoreLocation; begin cert := nil; msgCert := nil; storeName := 'addressbook'; storeLocation := slCurrentUser; GetSigningCertificate(ASignature.KeyInfo, cert, storeName, storeLocation); if (ASignature.KeyInfo <> nil) then begin GetInternalCertStore().Open(storeName, storeLocation); msgCert := ASignature.KeyInfo.GetCertificate(GetInternalCertStore()); if (msgCert <> nil) and (Certificates.FindBySerialNo(msgCert.SerialNumber, msgCert.IssuedBy) = nil) then begin Certificates.Items.Add(msgCert); end; end; if (cert = nil) then begin cert := msgCert; end; ASignature.Verify(cert, ADom); end; procedure TclSoapMessage.Verify; var dom: IXMLDOMDocument; security, headerNode: IXMLDOMNode; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsHttpRequestDemoDisplayed) and (not IsCertDemoDisplayed) and (not IsEncoderDemoDisplayed) and (not IsEncryptorDemoDisplayed) and (not IsHtmlDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsHttpRequestDemoDisplayed := True; IsCertDemoDisplayed := True; IsEncoderDemoDisplayed := True; IsEncryptorDemoDisplayed := True; IsHtmlDemoDisplayed := True; {$ENDIF} end; {$ENDIF} if not IsSigned then begin raise EclSoapMessageError.Create(SoapMessageNotSigned, SoapMessageNotSignedCode); end; CheckSoapVersion(); dom := CoDOMDocument.Create(); dom.validateOnParse := False; dom.preserveWhiteSpace := True; dom.loadXML(XmlCrlfEncode(WideString(TclXmlItem(Self.Items[0]).XmlData))); //TODO WideString typecast //use value from GetXmlCharSet(dom) to convert/typecast correctly if (not dom.parsed) then begin raise EclSoapMessageError.Create(dom.parseError.reason, dom.parseError.errorCode); end; headerNode := GetNodeByName(dom.documentElement, 'Header'); if (headerNode = nil) then begin raise EclSoapMessageError.Create(SoapFormatError, SoapFormatErrorCode); end; security := GetNodeByName(headerNode, 'Security'); if (security = nil) then begin raise EclSoapMessageError.Create(SoapFormatError, SoapFormatErrorCode); end; ExtractBodyId(dom); FAddressing.Parse(headerNode); FTimestamp.Parse(security); VerifySignatures(security, dom); if (not IsEncrypted) then begin RemoveNode(security); end; TclXmlItem(Self.Items[0]).XmlData := string(XmlCrlfDecode(dom.xml)); end; procedure TclSoapMessage.VerifySignatures(const ASecurity: IXMLDOMNode; const ADom: IXMLDOMDocument); var list: IXMLDOMNodeList; node: IXMLDomNode; sig: TclXmlSignature; ref: TclXmlSignReferenceList; begin list := ASecurity.childNodes; if (list = nil) then begin raise EclSoapMessageError.Create(SoapFormatError, SoapFormatErrorCode); end; node := list.nextNode; while (node <> nil) do begin if (node.baseName = 'Signature') then begin ref := nil; sig := nil; try ref := TclXmlSignReferenceList.Create(nil, TclXmlSignReference); sig := TclXmlSignature.Parse(ASecurity, node, ref, SecurityConfig); Signatures.Add().AssignSignatureInfo(sig); VerifySignature(sig, ADom); finally ref.Free(); sig.Free(); end; end; node := list.nextNode; end; node := nil; end; procedure TclSoapMessage.GetSigningCertificate(AKeyInfo: TclXmlKeyInfo; var ACertificate: TclCertificate; var AStoreName: string; var AStoreLocation: TclCertificateStoreLocation); var handled: Boolean; list: TclCertificateList; begin ACertificate := nil; handled := False; list := TclCertificateList.Create(False); try DoGetSigningCertificate(AKeyInfo, ACertificate, list, handled); finally list.Free(); end; end; procedure TclSoapMessage.DoGetEncryptionCertificate(AKeyInfo: TclXmlKeyInfo; var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var AStoreName: string; var AStoreLocation: TclCertificateStoreLocation; var Handled: Boolean); begin if Assigned(OnGetEncryptionCertificate) then begin OnGetEncryptionCertificate(Self, AKeyInfo, ACertificate, AExtraCerts, AStoreName, AStoreLocation, Handled); end; end; procedure TclSoapMessage.DoGetSigningCertificate(AKeyInfo: TclXmlKeyInfo; var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var Handled: Boolean); begin if Assigned(OnGetSigningCertificate) then begin OnGetSigningCertificate(Self, AKeyInfo, ACertificate, AExtraCerts, Handled); end; end; function TclSoapMessage.GetNameSpace(ANode: IXMLDOMNode): string; var ind: Integer; begin Result := ''; if (ANode = nil) then Exit; ind := Pos(':', ANode.nodeName); if (ind > 0) then begin Result := Copy(ANode.nodeName, 1, ind - 1); end; end; procedure TclSoapMessage.GetEncryptionCertificate(AKeyInfo: TclXmlKeyInfo; var ACertificate: TclCertificate; var AStoreName: string; var AStoreLocation: TclCertificateStoreLocation); var handled: Boolean; list: TclCertificateList; begin handled := False; list := TclCertificateList.Create(False); try DoGetEncryptionCertificate(AKeyInfo, ACertificate, list, AStoreName, AStoreLocation, handled); finally list.Free(); end; end; procedure TclSoapMessage.BuildSoapMessage(AEnvelope: IXMLDOMDocument; const ASoapAction: string); var src: TStrings; begin src := TStringList.Create(); try src.Text := string(AEnvelope.xml); //TODO use value from GetXmlCharSet(AEnvelope) to convert/typecast correctly BuildSoapMessage(src, ASoapAction); finally src.Free(); end; end; procedure TclSoapMessage.BuildSoapMessage(AEnvelope: IXMLDOMDocument); begin BuildSoapMessage(AEnvelope, ''); end; procedure TclSoapMessage.BuildSoapMessage(AEnvelope: TStrings); begin BuildSoapMessage(AEnvelope, ''); end; procedure TclSoapMessage.BuildSoapMessage(const AEnvelope: string); begin BuildSoapMessage(AEnvelope, ''); end; function TclSoapMessage.AddWsdlEnvelope(const AMessage: string): string; var ns: TclSoapNameSpaceList; wsuNameSpace, envNameSpace, envNsName: string; begin ns := TclSoapNameSpaceList.Create(nil, TclSoapNameSpace); try envNsName := cEnvelopeNameSpaceName[SoapVersion]; envNameSpace := SecurityConfig.Namespaces.GetPrefix(envNsName); ns.AddNameSpace(GetSoapNamespace(envNameSpace), envNsName); Result := '<?xml version="1.0"' + GetAttributeText(' encoding', Header.CharSet) + '?>' + '<' + GetSoapNodeName(envNameSpace, 'Envelope'); if (SoapVersion = svSoap1_1) then begin Result := Result + GetAttributeText(' ' + GetSoapNodeName(envNameSpace, 'encodingStyle'), EncodingStyle); end; Result := Result + ns.ToString() + Namespaces.ToString() + '>' + '<' + GetSoapNodeName(envNameSpace, 'Body'); if (BodyID <> '') then begin wsuNameSpace := SecurityConfig.Namespaces.GetPrefix(wsuNameSpaceName); ns.Clear(); ns.AddNameSpace(GetSoapNamespace(wsuNameSpace), wsuNameSpaceName); Result := Result + ns.ToString() + GetAttributeText(' ' + GetIdName(wsuNameSpace), BodyID); end; Result := Result + '>' + AMessage + '</' + GetSoapNodeName(envNameSpace, 'Body') + '>' + '</' + GetSoapNodeName(envNameSpace, 'Envelope') + '>'; finally ns.Free(); end; end; procedure TclSoapMessage.BuildSoapWSDL(const AMethodURI, AMethod: string; AParamNames, AParamValues, AParamAttrs: TStrings); var i: Integer; soapXml, attr: string; begin if (AMethod = '') then begin raise EclSoapMessageError.Create(ParameterSetError, ParameterSetErrorCode); end; if (AParamNames.Count <> AParamNames.Count) then begin raise EclSoapMessageError.Create(ParameterSetError, ParameterSetErrorCode); end; if (AParamAttrs <> nil) and (AParamNames.Count <> AParamAttrs.Count) then begin raise EclSoapMessageError.Create(ParameterSetError, ParameterSetErrorCode); end; soapXml := '<m:' + AMethod + ' ' + GetAttributeText('xmlns:m', AMethodURI) + '>'; for i := 0 to AParamNames.Count - 1 do begin attr := ''; if (AParamAttrs <> nil) and (AParamAttrs[i] <> '') then begin attr := ' ' + AParamAttrs[i]; end; soapXml := soapXml + '<' + AParamNames[i] + attr + '>' + AParamValues[i] + '</' + AParamNames[i] + '>'; end; soapXml := soapXml + '</m:' + AMethod + '>'; soapXml := AddWsdlEnvelope(soapXml); BuildSoapMessage(soapXml, AMethodURI + Id2UriReference(AMethod)); end; procedure TclSoapMessage.BuildSoapWSDL(const AMethodURI, AMethod: string; const AParamNames, AParamValues, AParamAttrs: array of string); var i: Integer; names, vals, attrs: TStrings; begin names := nil; vals := nil; attrs := nil; try names := TStringList.Create(); vals := TStringList.Create(); for i := Low(AParamNames) to High(AParamNames) do begin names.Add(AParamNames[i]); end; for i := Low(AParamValues) to High(AParamValues) do begin vals.Add(AParamValues[i]); end; if (Length(AParamAttrs) > 0) then begin attrs := TStringList.Create(); for i := Low(AParamAttrs) to High(AParamAttrs) do begin attrs.Add(AParamAttrs[i]); end; end; BuildSoapWSDL(AMethodURI, AMethod, names, vals, attrs); finally attrs.Free(); vals.Free(); names.Free(); end; end; procedure TclSoapMessage.BuildSoapWSDL(const AMethodURI, AMethod: string; AParamNames, AParamValues: TStrings); begin BuildSoapWSDL(AMethodURI, AMethod, AParamNames, AParamValues, nil); end; procedure TclSoapMessage.BuildSoapWSDL(const AMethodURI, AMethod: string; const AParamNames, AParamValues: array of string); begin BuildSoapWSDL(AMethodURI, AMethod, AParamNames, AParamValues, []); end; function TclSoapMessage.GetIdName(const ANamespace: string): string; begin Result := GetSoapNodeName(ANamespace, SecurityConfig.IdName); end; function TclSoapMessage.GetInternalCertStore: TclCertificateStore; begin if (FInternalCertStore = nil) then begin FInternalCertStore := TclCertificateStore.Create(nil); end; Result := FInternalCertStore; end; function TclSoapMessage.GetIsEncrypted: Boolean; begin Result := GetIsSecured('EncryptedKey'); end; function TclSoapMessage.GetIsSecured(const ANodeName: string): Boolean; var dom: IXMLDOMDocument; head, security: IXMLDOMNode; begin Result := False; CheckRequestExists(); dom := CoDOMDocument.Create(); dom.loadXML(TclXmlItem(Self.Items[0]).XmlData); if (not dom.parsed) then begin Exit; end; head := GetNodeByName(dom.documentElement, 'Header'); if (head <> nil) then begin security := GetNodeByName(head, 'Security'); if (security <> nil) then begin Result := (GetNodeByName(security, ANodeName) <> nil); end; end; end; function TclSoapMessage.GetIsSigned: Boolean; begin Result := GetIsSecured('Signature'); end; procedure TclSoapMessage.SetSecurityConfig(const Value: TclXmlSecurityConfig); begin FSecurityConfig.Assign(Value); end; procedure TclSoapMessage.SetNamespaces(const Value: TclSoapNameSpaceList); begin FNamespaces.Assign(Value); end; procedure TclSoapMessage.Clear; begin BeginUpdate(); try Addressing.Clear(); Timestamp.Clear(); Namespaces.Clear(); SoapVersion := svSoap1_2; BodyID := ''; Signatures.Clear(); EncryptedKey.Clear(); Certificates.Close(); inherited Clear(); finally EndUpdate(); end; end; procedure TclSoapMessage.SetSignatures(const Value: TclSoapSignatureList); begin FSignatures.Assign(Value); end; procedure TclSoapMessage.BuildSoapMessage(const AEnvelope, ASoapAction: string); var env: TStrings; begin env := TStringList.Create(); try env.Text := AEnvelope; BuildSoapMessage(env, ASoapAction); finally env.Free(); end; end; function TclSoapMessage.CreateItem(AFieldList: TclHeaderFieldList): TclHttpRequestItem; var contentType: string; begin if SameText(Header.ContentType, 'multipart/related') then begin contentType := AFieldList.GetFieldValue('Content-Type'); if (SameText(AFieldList.GetFieldValueItem(contentType, ''), cSoapHeaderContentType[svSoap1_1]) or SameText(AFieldList.GetFieldValueItem(contentType, ''), cSoapHeaderContentType[svSoap1_2])) and SameText(Header.Start, AFieldList.GetFieldValue('Content-ID')) then begin Result := AddXmlData(''); end else begin Result := AddAttachment(); end; end else begin Result := inherited CreateItem(AFieldList); end; end; procedure TclSoapMessage.CreateSingleItem(AStream: TStream); var buf: TclByteArray; s: string; item: TclXmlItem; begin {$IFNDEF DELPHI2005}buf := nil;{$ENDIF} if (Header.ContentType = '') or (system.Pos('multipart/related', LowerCase(Header.ContentType)) > 0) or (system.Pos(cSoapHeaderContentType[svSoap1_1], LowerCase(Header.ContentType)) > 0) or (system.Pos(cSoapHeaderContentType[svSoap1_2], LowerCase(Header.ContentType)) > 0) then begin s := ''; if (AStream.Size > 0) then begin SetLength(buf, AStream.Size); AStream.Read(buf[0], AStream.Size); s := TclTranslator.GetString(buf, 0, Length(buf), Header.CharSet); end; item := AddXmlData(s); item.CharSet := Header.CharSet; item.AfterAddData(); end else begin inherited CreateSingleItem(AStream); end; end; procedure TclSoapMessage.CreateSignature(ASignature: TclXmlSignature; const ADom: IXMLDOMDocument); var cert: TclCertificate; storeName: string; storeLocation: TclCertificateStoreLocation; begin cert := nil; storeName := 'MY'; storeLocation := slCurrentUser; GetSigningCertificate(ASignature.KeyInfo, cert, storeName, storeLocation); if (cert = nil) then begin raise EclSoapMessageError.Create(CertificateRequired, CertificateRequiredCode); end; ASignature.Sign(cert, ADom); end; function TclSoapMessage.GetContentType: string; var i: Integer; isXmlData: Boolean; requestTypes: array[Boolean] of string; begin requestTypes[False] := cSoapHeaderContentType[SoapVersion]; requestTypes[True] := 'multipart/related'; isXmlData := False; for i := 0 to Items.Count - 1 do begin if (Items[i] is TclSoapMessageItem) then begin isXmlData := True; end; end; if isXmlData then begin Result := requestTypes[Items.Count > 1]; end else begin Result := inherited GetContentType(); end; end; function TclSoapMessage.AddXmlData(const AXmlData: string): TclXmlItem; begin BeginUpdate(); try SoapVersion := ParseSoapVersion(AXmlData); Result := Items.Add(TclXmlItem) as TclXmlItem; Result.XmlData := AXmlData; finally EndUpdate(); end; end; function TclSoapMessage.AddAttachment: TclAttachmentItem; begin Result := Items.Add(TclAttachmentItem) as TclAttachmentItem; end; function TclSoapMessage.CreateHeader: TclHttpRequestHeader; begin Result := TclSoapMessageHeader.Create(); end; function TclSoapMessage.GetHeader: TclSoapMessageHeader; begin Result := inherited Header as TclSoapMessageHeader; end; procedure TclSoapMessage.SetAddressing(const Value: TclSoapAddressList); begin FAddressing.Assign(Value); end; procedure TclSoapMessage.SetBodyID(const Value: string); begin if (FBodyID <> Value) then begin BeginUpdate(); FBodyID := Value; EndUpdate(); end; end; procedure TclSoapMessage.SetEncodingStyle(const Value: string); begin if (FEncodingStyle <> Value) then begin BeginUpdate(); FEncodingStyle := Value; EndUpdate(); end; end; procedure TclSoapMessage.SetEncryptedKey(const Value: TclSoapEncryptedKeyInfo); begin FEncryptedKey.Assign(Value); end; procedure TclSoapMessage.SetHeader(const Value: TclSoapMessageHeader); begin inherited Header := Value; end; procedure TclSoapMessage.InitHeader; begin inherited InitHeader(); if (Items.Count > 1) and (Items[0] is TclSoapMessageItem) then begin if (Header.Start = '') then begin Header.Start := (Items[0] as TclSoapMessageItem).ContentID; end; if (Header.SubType = '') then begin Header.SubType := (Items[0] as TclSoapMessageItem).ContentType; end; end; end; function TclSoapMessage.ParseSoapVersion(const AEnvelope: string): TclSoapVersion; begin if (System.Pos(soap12NameSpaceName, AEnvelope) > 0) then begin Result := svSoap1_2; end else begin Result := svSoap1_1; end; end; procedure TclSoapMessage.CheckSoapVersion; begin if (SoapVersion <> ParseSoapVersion(TclXmlItem(Self.Items[0]).XmlData)) then begin EclSoapMessageError.Create(SoapVersionError, SoapVersionErrorCode); end; end; { TclSoapMessageItem } procedure TclSoapMessageItem.Assign(Source: TPersistent); var Src: TclSoapMessageItem; begin BeginUpdate(); try if (Source is TclSoapMessageItem) then begin Src := (Source as TclSoapMessageItem); ContentType := Src.ContentType; CharSet := Src.CharSet; ContentID := Src.ContentID; ContentLocation := Src.ContentLocation; ContentTransferEncoding := Src.ContentTransferEncoding; ExtraFields := Src.ExtraFields; end; inherited Assign(Source); finally EndUpdate(); end; end; procedure TclSoapMessageItem.ListChangeEvent(Sender: TObject); begin Update(); end; constructor TclSoapMessageItem.Create(AOwner: TclHttpRequestItemList); begin inherited Create(AOwner); FKnownFields := TStringList.Create(); FExtraFields := TStringList.Create(); TStringList(FExtraFields).OnChange := ListChangeEvent; RegisterFields(); ContentType := 'text/xml'; end; destructor TclSoapMessageItem.Destroy; begin FExtraFields.Free(); FKnownFields.Free(); inherited Destroy(); end; function TclSoapMessageItem.GetHeader: TStream; var list: TStrings; fieldList: TclHeaderFieldList; begin list := nil; fieldList := nil; try list := TStringList.Create(); fieldList := TclHeaderFieldList.Create(); fieldList.Parse(0, list); fieldList.AddField('Content-Type', ContentType); if (ContentType <> '') then begin fieldList.AddFieldItem('Content-Type', 'charset', CharSet); end; fieldList.AddField('Content-ID', ContentID); fieldList.AddField('Content-Location', ContentLocation); fieldList.AddField('Content-Transfer-Encoding', ContentTransferEncoding); fieldList.AddFields(ExtraFields); fieldList.AddEndOfHeader(); Result := TMemoryStream.Create(); TclStringsUtils.SaveStrings(list, Result, CharSet); Result.Position := 0; finally fieldList.Free(); list.Free(); end; end; function TclSoapMessageItem.GetSoapMessage: TclSoapMessage; begin Result := (Request as TclSoapMessage); end; function TclSoapMessageItem.GetCharSet: string; begin Result := CharSet; if (Result = '') then begin Result := inherited GetCharSet(); end; end; function TclSoapMessageItem.GetDataStream: TStream; begin if (Request.IsMultiPartContent) then begin Result := GetHeader(); end else begin Result := TclNullStream.Create(); end; end; procedure TclSoapMessageItem.SetContentID(const Value: string); begin if (FContentID <> Value) then begin FContentID := Value; Update(); end; end; procedure TclSoapMessageItem.SetContentLocation(const Value: string); begin if (FContentLocation <> Value) then begin FContentLocation := Value; Update(); end; end; procedure TclSoapMessageItem.SetContentTransferEncoding( const Value: string); begin if (FContentTransferEncoding <> Value) then begin FContentTransferEncoding := Value; Update(); end; end; procedure TclSoapMessageItem.SetContentType(const Value: string); begin if (FContentType <> Value) then begin FContentType := Value; Update(); end; end; procedure TclSoapMessageItem.SetExtraFields(const Value: TStrings); begin FExtraFields.Assign(Value); end; procedure TclSoapMessageItem.SetCharSet(const Value: string); begin if (FCharSet <> Value) then begin FCharSet := Value; Update(); end; end; procedure TclSoapMessageItem.ReadData(Reader: TReader); begin BeginUpdate(); try inherited ReadData(Reader); ContentType := Reader.ReadString(); CharSet := Reader.ReadString(); ContentID := Reader.ReadString(); ContentLocation := Reader.ReadString(); ContentTransferEncoding := Reader.ReadString(); ExtraFields.Text := Reader.ReadString(); finally EndUpdate(); end; end; procedure TclSoapMessageItem.WriteData(Writer: TWriter); begin inherited WriteData(Writer); Writer.WriteString(ContentType); Writer.WriteString(CharSet); Writer.WriteString(ContentID); Writer.WriteString(ContentLocation); Writer.WriteString(ContentTransferEncoding); Writer.WriteString(ExtraFields.Text); end; procedure TclSoapMessageItem.ParseHeader(AFieldList: TclHeaderFieldList); var s: string; begin BeginUpdate(); try inherited ParseHeader(AFieldList); s := AFieldList.GetFieldValue('Content-Type'); ContentType := AFieldList.GetFieldValueItem(s, ''); CharSet := AFieldList.GetFieldValueItem(s, 'charset'); ContentID := AFieldList.GetFieldValue('Content-ID'); ContentLocation := AFieldList.GetFieldValue('Content-Location'); ContentTransferEncoding := AFieldList.GetFieldValue('Content-Transfer-Encoding'); ParseExtraFields(AFieldList); finally EndUpdate(); end; end; procedure TclSoapMessageItem.ParseExtraFields(AFieldList: TclHeaderFieldList); var i: Integer; begin ExtraFields.Clear(); for i := 0 to AFieldList.FieldList.Count - 1 do begin if (FindInStrings(FKnownFields, AFieldList.FieldList[i]) < 0) then begin ExtraFields.Add(AFieldList.GetFieldName(i) + ': ' + AFieldList.GetFieldValue(i)); end; end; end; procedure TclSoapMessageItem.RegisterField(const AField: string); begin if (FindInStrings(FKnownFields, AField) < 0) then begin FKnownFields.Add(AField); end; end; procedure TclSoapMessageItem.RegisterFields; begin RegisterField('Content-Type'); RegisterField('Content-ID'); RegisterField('Content-Location'); RegisterField('Content-Transfer-Encoding'); end; { TclAttachmentItem } procedure TclAttachmentItem.AddData(const AData: TclByteArray; AIndex, ACount: Integer); var stream: TStream; begin stream := SoapMessage.DataStream; if (stream = nil) then begin SoapMessage.DoSaveData(Self, stream); end; if (stream <> nil) then begin stream.Write(AData[AIndex], ACount); end; SoapMessage.DataStream := stream; end; procedure TclAttachmentItem.AfterAddData; begin if (not (Request is TclSoapMessage)) then Exit; if (SoapMessage.DataStream <> nil) and Assigned(SoapMessage.OnDataAdded) then begin SoapMessage.DataStream.Position := 0; SoapMessage.DoDataAdded(Self, SoapMessage.DataStream); end; end; function TclAttachmentItem.GetDataStream: TStream; var stream: TStream; begin Result := TclMultiStream.Create(); try TclMultiStream(Result).AddStream(inherited GetDataStream()); stream := nil; SoapMessage.DoLoadData(Self, stream); if (stream <> nil) then begin stream.Position := 0; TclMultiStream(Result).AddStream(stream); end; except Result.Free(); raise; end; end; { TclSoapMessageHeader } procedure TclSoapMessageHeader.Assign(Source: TPersistent); var Src: TclSoapMessageHeader; begin BeginUpdate(); try inherited Assign(Source); if (Source is TclSoapMessageHeader) then begin Src := (Source as TclSoapMessageHeader); Start := Src.Start; SubType := Src.SubType; SoapAction := Src.SoapAction; end; finally EndUpdate(); end; end; procedure TclSoapMessageHeader.AssignContentType(AFieldList: TclHeaderFieldList); begin AFieldList.AddField('Content-Type', ContentType); if (ContentType <> '') then begin AFieldList.AddFieldItem('Content-Type', 'boundary', Boundary); AFieldList.AddFieldItem('Content-Type', 'charset', CharSet); AFieldList.AddFieldItem('Content-Type', 'type', SubType); AFieldList.AddFieldItem('Content-Type', 'start', Start); end; end; procedure TclSoapMessageHeader.Clear; begin BeginUpdate(); try inherited Clear(); Start := ''; SubType := ''; SoapAction := ''; CharSet := 'utf-8'; finally EndUpdate(); end; end; procedure TclSoapMessageHeader.InternalAssignHeader(AFieldList: TclHeaderFieldList); begin inherited InternalAssignHeader(AFieldList); AFieldList.AddField('SOAPAction', SoapAction); end; procedure TclSoapMessageHeader.InternalParseHeader(AFieldList: TclHeaderFieldList); begin inherited InternalParseHeader(AFieldList); SoapAction := AFieldList.GetFieldValue('SOAPAction'); end; procedure TclSoapMessageHeader.ParseContentType(AFieldList: TclHeaderFieldList); var s: string; begin inherited ParseContentType(AFieldList); s := AFieldList.GetFieldValue('Content-Type'); Start := AFieldList.GetFieldValueItem(s, 'start'); SubType := AFieldList.GetFieldValueItem(s, 'type'); end; procedure TclSoapMessageHeader.RegisterFields; begin inherited RegisterFields(); RegisterField('SOAPAction'); end; procedure TclSoapMessageHeader.SetSoapAction(const Value: string); begin if (FSoapAction <> Value) then begin FSoapAction := Value; Update(); end; end; procedure TclSoapMessageHeader.SetStart(const Value: string); begin if (FStart <> Value) then begin FStart := Value; Update(); end; end; procedure TclSoapMessageHeader.SetSubType(const Value: string); begin if (FSubType <> Value) then begin FSubType := Value; Update(); end; end; { TclXmlItem } procedure TclXmlItem.AddData(const AData: TclByteArray; AIndex, ACount: Integer); begin XmlData := XmlData + TclTranslator.GetString(AData, AIndex, ACount, CharSet); end; procedure TclXmlItem.AfterAddData; var stream: TStream; buffer: TclByteArray; begin {$IFNDEF DELPHI2005}buffer := nil;{$ENDIF} if Assigned(SoapMessage.OnDataAdded) then begin stream := TMemoryStream.Create(); try if (XmlData <> '') then begin buffer := TclTranslator.GetBytes(XmlData, CharSet); stream.WriteBuffer(buffer[0], Length(buffer)); stream.Position := 0; end; SoapMessage.DoDataAdded(Self, stream); finally stream.Free(); end; end; end; procedure TclXmlItem.Assign(Source: TPersistent); begin BeginUpdate(); try if (Source is TclXmlItem) then begin XmlData := (Source as TclXmlItem).XmlData; end; inherited Assign(Source); finally EndUpdate(); end; end; function TclXmlItem.GetDataStream: TStream; var data: TStream; buf: TclByteArray; begin {$IFNDEF DELPHI2005}buf := nil;{$ENDIF} {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'GetDataStream');{$ENDIF} Result := TclMultiStream.Create(); try TclMultiStream(Result).AddStream(inherited GetDataStream()); data := TMemoryStream.Create(); TclMultiStream(Result).AddStream(data); buf := TclTranslator.GetBytes(XmlData, CharSet); if (Length(buf) > 0) then begin data.Write(buf[0], Length(buf)); end; data.Position := 0; except Result.Free(); raise; end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'GetDataStream'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'GetDataStream', E); raise; end; end;{$ENDIF} end; procedure TclXmlItem.ReadData(Reader: TReader); begin BeginUpdate(); try inherited ReadData(Reader); XmlData := Reader.ReadString(); finally EndUpdate(); end; end; procedure TclXmlItem.SetXmlData(const Value: string); begin if (FXmlData <> Value) then begin FXmlData := Value; Update(); end; end; procedure TclXmlItem.WriteData(Writer: TWriter); begin inherited WriteData(Writer); Writer.WriteString(XmlData); end; { TclSoapTimestamp } procedure TclSoapTimestamp.Assign(Source: TPersistent); var src: TclSoapTimestamp; begin if (Source is TclSoapTimestamp) then begin src := (Source as TclSoapTimestamp); FExpires := src.Expires; FCreated := src.Created; FID := src.ID; end else begin inherited Assign(Source); end; end; procedure TclSoapTimestamp.Build(const ARoot: IXMLDOMNode); var timestamp: IXMLDOMNode; wsuNameSpace: string; begin if (Expires = '') and (Created = '') and (ID = '') then Exit; if (GetNodeByName(ARoot, 'Timestamp', wsuNameSpaceName) <> nil) then Exit; wsuNameSpace := Config.Namespaces.GetPrefix(wsuNameSpaceName); timestamp := ARoot.ownerDocument.createElement(GetSoapNodeName(wsuNameSpace, 'Timestamp')); ARoot.appendChild(timestamp); if (ID <> '') then begin SetAttributeValue(timestamp, GetSoapNodeName(wsuNameSpace, Config.IdName), ID); end; AddNodeValue(timestamp, GetSoapNodeName(wsuNameSpace, 'Created'), Created); AddNodeValue(timestamp, GetSoapNodeName(wsuNameSpace, 'Expires'), Expires); end; procedure TclSoapTimestamp.Parse(const ASecurity: IXMLDOMNode); var timestamp: IXMLDOMNode; begin Clear(); timestamp := GetNodeByName(ASecurity, 'Timestamp'); if (timestamp = nil) then Exit; FID := GetAttributeValue(timestamp, GetSoapNodeName(Config.Namespaces.GetPrefix(wsuNameSpaceName), Config.IdName)); FCreated := GetNodeValueByName(timestamp, 'Created'); FExpires := GetNodeValueByName(timestamp, 'Expires'); end; procedure TclSoapTimestamp.SetCreated(const Value: string); begin if (FCreated <> Value) then begin FCreated := Value; Update(); end; end; procedure TclSoapTimestamp.SetExpires(const Value: string); begin if (FExpires <> Value) then begin FExpires := Value; Update(); end; end; procedure TclSoapTimestamp.SetID(const Value: string); begin if (FID <> Value) then begin FID := Value; Update(); end; end; procedure TclSoapTimestamp.Update; begin if Assigned(OnChange) then begin OnChange(Self); end; end; procedure TclSoapTimestamp.Clear; begin FExpires := ''; FCreated := ''; FID := ''; end; constructor TclSoapTimestamp.Create(AConfig: TclXmlSecurityConfig); begin inherited Create(); FConfig := AConfig; Clear(); end; { TclSoapAddressList } function TclSoapAddressList.Add: TclSoapAddressItem; begin Result := TclSoapAddressItem(inherited Add()); end; function TclSoapAddressList.AddItem(const AName, AID, AValue: string): TclSoapAddressItem; begin Result := Add(); Result.Name := AName; Result.ID := AID; Result.Value := AValue; end; procedure TclSoapAddressList.Build(const ARoot: IXMLDOMNode); var i: Integer; node: IXMLDOMNode; item: TclSoapAddressItem; wsu, wsa: string; begin if (Count = 0) then Exit; wsu := Config.Namespaces.GetPrefix(wsuNameSpaceName); wsa := Config.Namespaces.GetPrefix(wsaNameSpaceName); for i := 0 to Count - 1 do begin item := Items[i]; if (GetNodeByName(ARoot, item.Name, wsaNameSpaceName) <> nil) then Break; node := ARoot.ownerDocument.createElement(GetSoapNodeName(wsa, item.Name)); ARoot.appendChild(node); if (item.ID <> '') then begin SetAttributeValue(node, GetSoapNodeName(wsu, Config.IdName), item.ID); end; if (item.Value <> '') then begin SetNodeText(node, item.Value); end; end; end; constructor TclSoapAddressList.Create(AOwner: TPersistent; ItemClass: TCollectionItemClass; AConfig: TclXmlSecurityConfig); begin inherited Create(AOwner, ItemClass); FConfig := AConfig; end; function TclSoapAddressList.GetItem(Index: Integer): TclSoapAddressItem; begin Result := TclSoapAddressItem(inherited GetItem(Index)); end; function TclSoapAddressList.ItemById(const AID: string): TclSoapAddressItem; var i: Integer; begin for i := 0 to Count - 1 do begin Result := Items[i]; if (Result.ID = AID) then Exit; end; Result := nil; end; function TclSoapAddressList.ItemByName(const AName: string): TclSoapAddressItem; var i: Integer; begin for i := 0 to Count - 1 do begin Result := Items[i]; if (Result.Name = AName) then Exit; end; Result := nil; end; procedure TclSoapAddressList.Parse(const ARoot: IXMLDOMNode); var list: IXMLDOMNodeList; node: IXMLDomNode; item: TclSoapAddressItem; begin Clear(); list := ARoot.childNodes; if (list = nil) then Exit; node := list.nextNode; while (node <> nil) do begin if SameText(node.namespaceURI, wsaNameSpaceName) then begin item := Add(); item.Name := node.baseName; item.ID := GetAttributeValue(node, GetSoapNodeName(Config.Namespaces.GetPrefix(wsuNameSpaceName), Config.IdName)); item.Value := GetNodeText(node); end; node := list.nextNode; end; end; procedure TclSoapAddressList.SetItem(Index: Integer; const Value: TclSoapAddressItem); begin inherited SetItem(Index, Value); end; procedure TclSoapAddressList.Update(Item: TCollectionItem); begin inherited Update(Item); if Assigned(OnChange) then begin OnChange(Self); end; end; { TclSoapAddressItem } procedure TclSoapAddressItem.Assign(Source: TPersistent); var src: TclSoapAddressItem; begin if (Source is TclSoapAddressItem) then begin src := TclSoapAddressItem(Source); Name := src.Name; ID := src.ID; Value := src.Value; end else begin inherited Assign(Source); end; end; procedure TclSoapAddressItem.SetID(const Value: string); begin if (FID <> Value) then begin FID := Value; Changed(False); end; end; procedure TclSoapAddressItem.SetName(const Value: string); begin if (FName <> Value) then begin FName := Value; Changed(False); end; end; procedure TclSoapAddressItem.SetValue(const AValue: string); begin if (FValue <> AValue) then begin FValue := AValue; Changed(False); end; end; { TclSoapSignatureList } function TclSoapSignatureList.Add: TclSoapSignatureInfo; begin Result := TclSoapSignatureInfo(inherited Add()); end; function TclSoapSignatureList.GetItem(Index: Integer): TclSoapSignatureInfo; begin Result := TclSoapSignatureInfo(inherited GetItem(Index)); end; function TclSoapSignatureList.ItemById(const AID: string): TclSoapSignatureInfo; var i: Integer; begin for i := 0 to Count - 1 do begin Result := Items[i]; if (Result.ID = AID) then Exit; end; Result := nil; end; procedure TclSoapSignatureList.SetItem(Index: Integer; const Value: TclSoapSignatureInfo); begin inherited SetItem(Index, Value); end; procedure TclSoapSignatureList.Update(Item: TCollectionItem); begin inherited Update(Item); if Assigned(OnChange) then begin OnChange(Self); end; end; end.
unit ServerHorse.Model.Entity.BANKACCOUNTS; interface uses SimpleAttributes; type [Tabela('BankAccounts')] TBANKACCOUNTS = class private FIDTYPESBANKACCOUNTS: String; FSTATUS: String; FDESCRIPTION: String; FGUUID: String; FOPENINGBALANCE: Currency; procedure SetDESCRIPTION(const Value: String); procedure SetGUUID(const Value: String); procedure SetIDTYPESBANKACCOUNTS(const Value: String); procedure SetOPENINGBALANCE(const Value: Currency); procedure SetSTATUS(const Value: String); public constructor Create; destructor Destroy; override; [Campo('GUUID'), Pk] property GUUID : String read FGUUID write SetGUUID; [Campo('DESCRIPTION')] property DESCRIPTION : String read FDESCRIPTION write SetDESCRIPTION; [Campo('OPENINGBALANCE')] property OPENINGBALANCE : Currency read FOPENINGBALANCE write SetOPENINGBALANCE; [Campo('IDTYPESBANKACCOUNTS')] property IDTYPESBANKACCOUNTS : String read FIDTYPESBANKACCOUNTS write SetIDTYPESBANKACCOUNTS; [Campo('STATUS')] property STATUS : String read FSTATUS write SetSTATUS; end; implementation { TBANKACCOUNTS } constructor TBANKACCOUNTS.Create; begin end; destructor TBANKACCOUNTS.Destroy; begin inherited; end; procedure TBANKACCOUNTS.SetDESCRIPTION(const Value: String); begin FDESCRIPTION := Value; end; procedure TBANKACCOUNTS.SetGUUID(const Value: String); begin FGUUID := Value; end; procedure TBANKACCOUNTS.SetIDTYPESBANKACCOUNTS(const Value: String); begin FIDTYPESBANKACCOUNTS := Value; end; procedure TBANKACCOUNTS.SetOPENINGBALANCE(const Value: Currency); begin FOPENINGBALANCE := Value; end; procedure TBANKACCOUNTS.SetSTATUS(const Value: String); begin FSTATUS := Value; end; end.
program basicAlgorithms(input, output); const MIN = 1; MAX = 10; type sequence = array [MIN .. MAX] of integer; var s : sequence; exercise : integer procedure populate(); var i : integer; begin for i := MIN to MAX do s[i] := i end; { Corresponds to 1.2.1 } function smallestValueWhile(var s : sequence) : integer; var ans, i : integer; begin i := MIN; ans := s[i]; while i <= MAX do begin if s[i] < ans then ans := s[i]; i := i + 1 end; smallestValueWhile := ans end; begin populate(); write('Enter exercise number: '); read(exercise); case exercise of 1 : write(smallestValueWhile(s)) else exercise := 1 end end.
unit GX_FavFiles; {$I GX_CondDefine.inc} interface uses GX_FavUtil, DropTarget, FileView, Windows, SysUtils, Classes, Controls, Forms, ComCtrls, Menus, ExtCtrls, ImgList, ActnList, ToolWin, Dialogs, GX_BaseForm; type TfmFavFiles = class(TfmBaseForm) MainMenu: TMainMenu; mitFile: TMenuItem; mitNewFile: TMenuItem; mitNewFolder: TMenuItem; mitFileDelete: TMenuItem; mitFileSep2: TMenuItem; mitFileExit: TMenuItem; mitOptions: TMenuItem; mitHelp: TMenuItem; mitHelpHelp: TMenuItem; mitHelpContents: TMenuItem; mitHelpSep1: TMenuItem; mitHelpAbout: TMenuItem; tvFolders: TTreeView; splTreeView: TSplitter; StatusBar: TStatusBar; ilFolders: TImageList; dlgGetFiles: TOpenDialog; mitFileSep1: TMenuItem; mitFileProperties: TMenuItem; pmuFolders: TPopupMenu; mitTreeNewFolder: TMenuItem; mitTreeDeleteFolder: TMenuItem; mitTreeSep1: TMenuItem; mitTreeProperties: TMenuItem; pmuFiles: TPopupMenu; mitFNewFile: TMenuItem; mitFDelete: TMenuItem; mitFExecute: TMenuItem; mitCSep2: TMenuItem; mitFProperties: TMenuItem; ilSystem: TImageList; mitOptionsOptions: TMenuItem; ilSysLarge: TImageList; mitFView: TMenuItem; mitViewLarge: TMenuItem; mitViewSmall: TMenuItem; mitViewList: TMenuItem; mitViewDetails: TMenuItem; mitCSep1: TMenuItem; pnlFiles: TPanel; ListView: TListView; splFileView: TSplitter; pnlFileView: TPanel; Actions: TActionList; actOptionsOptions: TAction; actFileExit: TAction; actFileProperties: TAction; actFileDelete: TAction; actFileNewFile: TAction; actFileNewFolder: TAction; actHelpHelp: TAction; actHelpContents: TAction; actHelpAbout: TAction; ToolBar: TToolBar; tbnFileNewFile: TToolButton; tbnFileDelete: TToolButton; tbnSep1: TToolButton; tbnFileProperties: TToolButton; tbnSep2: TToolButton; tbnNavLevelUp: TToolButton; tbnSep3: TToolButton; tbnNavExpand: TToolButton; tbnNavContract: TToolButton; tbnSep4: TToolButton; tbnHelpHelp: TToolButton; actNavExpand: TAction; actNavContract: TAction; actNavLevelUp: TAction; actViewLargeIcons: TAction; actViewSmallIcons: TAction; actViewList: TAction; actViewDetails: TAction; actFileExecute: TAction; mitCSep0: TMenuItem; tbnFileNewFolder: TToolButton; actFileRename: TAction; mitFRename: TMenuItem; mitCSep3: TMenuItem; mitSelectAll: TMenuItem; actFileSelectAll: TAction; actFileMoveUp: TAction; actFileMoveDown: TAction; mitTreeSep2: TMenuItem; mitMoveUp: TMenuItem; mitMoveDown: TMenuItem; actOptionsCollectionOpenDefault: TAction; actOptionsCollectionOpen: TAction; actOptionsCollectionSaveAs: TAction; mitOptionsCollectionOpenDefault: TMenuItem; mitOptionsCollectionOpen: TMenuItem; mitOptionsCollectionReopen: TMenuItem; mitOptionsCollectionSaveAs: TMenuItem; mitFileSep3: TMenuItem; mitFileCollections: TMenuItem; mitCollectionsSep1: TMenuItem; procedure tvFoldersChange(Sender: TObject; Node: TTreeNode); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure tvFoldersKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ListViewChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure ListViewEdited(Sender: TObject; Item: TListItem; var S: string); procedure tvFoldersEdited(Sender: TObject; Node: TTreeNode; var S: string); procedure ListViewDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure tvFoldersDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure tvFoldersDragDrop(Sender, Source: TObject; X, Y: Integer); procedure tvFoldersChanging(Sender: TObject; Node: TTreeNode; var AllowChange: Boolean); procedure tvFoldersEndDrag(Sender, Target: TObject; X, Y: Integer); procedure FormShow(Sender: TObject); procedure FormHide(Sender: TObject); procedure actFileNewFolderExecute(Sender: TObject); procedure actFileExitExecute(Sender: TObject); procedure actFileNewFileExecute(Sender: TObject); procedure actNavLevelUpExecute(Sender: TObject); procedure actOptionsOptionsExecute(Sender: TObject); procedure actOptionsCollectionOpenDefaultExecute(Sender: TObject); procedure actOptionsCollectionOpenExecute(Sender: TObject); procedure mitOptionsCollectionOpenMRUExecute(Sender: TObject); procedure actOptionsCollectionSaveAsExecute(Sender: TObject); procedure actNavContractExecute(Sender: TObject); procedure actNavExpandExecute(Sender: TObject); procedure actHelpHelpExecute(Sender: TObject); procedure actHelpContentsExecute(Sender: TObject); procedure actFileDeleteExecute(Sender: TObject); procedure actFilePropertiesExecute(Sender: TObject); procedure actFileExecuteExecute(Sender: TObject); procedure actViewLargeIconsExecute(Sender: TObject); procedure actViewSmallIconsExecute(Sender: TObject); procedure actViewListExecute(Sender: TObject); procedure actViewDetailsExecute(Sender: TObject); procedure actHelpAboutExecute(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure mitFViewClick(Sender: TObject); procedure actFileRenameExecute(Sender: TObject); procedure ActionsUpdate(Action: TBasicAction; var Handled: Boolean); procedure actFileSelectAllExecute(Sender: TObject); procedure actFileMoveUpExecute(Sender: TObject); procedure actFileMoveDownExecute(Sender: TObject); procedure mitFileCollectionsClick(Sender: TObject); private FFileViewer: TFileViewer; FEntryFile: string; FMRUEntryFiles: TStrings; FFolderDelete: Boolean; FExpandAll: Boolean; FExecHide: Boolean; FModified: Boolean; FFileDrop: TDropFileTarget; function GetFolder(const FolderNode: TTreeNode): TGXFolder; function GetFile(const FileItem: TListItem): TGXFile; procedure FileToListItem(const AFile: TGXFile; const AListItem: TListItem); procedure SetupSystemImageLists; function AddFolder(const Text: string; FType: TFolderType): TTreeNode; procedure DeleteSelectedFiles; procedure DeleteCurrentFolder; procedure LogAndShowLoadError(const E: Exception); procedure SwitchEntryFile(const AFileName: string; AUpdateMRU: Boolean = True); procedure SaveEntries; procedure LoadEntries; procedure LoadSettings; procedure SaveSettings; procedure CreateFolders(Folder: TGXFolder; Node: TTreeNode); procedure DropFiles(Sender: TObject; ShiftState: TShiftState; Point: TPoint; var Effect: Longint); procedure AddFilesToCurrentFolder(Files: TStrings); function HaveSelectedItemInActiveControl: Boolean; procedure CreateNewFolder; procedure CreateNewFile; procedure ExecuteSelectedFiles; procedure EditFolder; procedure EditFile; function GetDefaultEntryFileName: string; procedure SetEntryFile(const Value: string); property EntryFile: string read FEntryFile write SetEntryFile; property MRUEntryFiles: TStrings read FMRUEntryFiles; function GetShowPreview: Boolean; procedure SetShowPreview(Value: Boolean); property ShowPreview: Boolean read GetShowPreview write SetShowPreview; function CreateEmptyRootNode: TTreeNode; function ConfigurationKey: string; function ExecuteFile(AListItem: TListItem): Boolean; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AssignIconImage(Image: TImage; const ContainerFileName: string); procedure SetFilter; function MakeFileNameAbsolute(const FileName: string): string; function MakeFileNameRelative(const FileName: string): string; end; implementation {$R *.dfm} uses Messages, ShellAPI, StrUtils, DropSource, {$IFOPT D+} GX_DbugIntf, {$ENDIF} ToolsAPI, GX_FavNewFolder, GX_FavFolderProp, GX_FavFileProp, GX_FavOptions, {$IFNDEF STANDALONE} GX_ConfigurationInfo, GX_Experts, GX_GExperts, {$ENDIF STANDALONE} GX_GxUtils, GX_GenericUtils, GX_OtaUtils, GX_SharedImages, OmniXML, GX_XmlUtils, GX_IdeUtils, Math; type EFavFiles = class(Exception); TFilesExpert = class(TGX_Expert) private FFavoriteFiles: TfmFavFiles; protected procedure SetActive(New: Boolean); override; public function GetActionCaption: string; override; class function GetName: string; override; procedure Execute(Sender: TObject); override; function HasConfigOptions: Boolean; override; end; const // Do not localize any of the strings in this const section: XmlAttributeFolderName = 'Name'; XmlAttributeFolderType = 'FolderType'; XmlAttributeFileName = 'Name'; XmlAttributeFileFileName = 'FileName'; XmlAttributeFileDescription = 'Description'; XmlAttributeFileExecType = 'ExecType'; XmlAttributeFileExecProg = 'ExecProg'; XmlNodeRoot = 'FavoriteFiles'; XmlNodeFolder = 'Folder'; XmlNodeFile = 'File'; XmlExecTypeNames: array[TExecType] of string = ('LoadInIDE', 'ShellExecute', 'Custom', 'Project'); XmlFolderTypeNames: array[TFolderType] of string = ('Normal', 'Source', 'Bitmaps', 'Glyphs', 'Documentation'); function XmlStringToExecType(const ExecTypeString: string): TExecType; var ExecType: TExecType; begin for ExecType := Low(TExecType) to High(TExecType) do if XmlExecTypeNames[ExecType] = ExecTypeString then begin Result := ExecType; Exit; end; raise EConvertError.CreateFmt('Unknown ExecType value "%s"', [ExecTypeString]); end; function XmlStringToFolderType(const FolderTypeString: string): TFolderType; var FolderType: TFolderType; begin for FolderType := Low(TFolderType) to High(TFolderType) do if XmlFolderTypeNames[FolderType] = FolderTypeString then begin Result := FolderType; Exit; end; raise EConvertError.CreateFmt('Unknown FolderType value "%s"', [FolderTypeString]); end; resourcestring SFavorites = 'Favorites'; procedure TfmFavFiles.AssignIconImage(Image: TImage; const ContainerFileName: string); var Icon: HIcon; ID: Word; begin if not FileExists(ContainerFileName) then Exit; Icon := ExtractAssociatedIcon(HInstance, PChar(ContainerFileName), ID); if Icon <> 0 then begin Image.Picture.Icon.Handle := Icon; Image.Visible := True; Image.Refresh; end else Image.Visible := False; end; procedure TfmFavFiles.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caHide; end; function TfmFavFiles.AddFolder(const Text: string; FType: TFolderType): TTreeNode; var Node: TTreeNode; Folder: TGXFolder; begin Folder := nil; try if tvFolders.Selected = nil then begin Folder := TGXFolder.Create(Root); Node := tvFolders.Items.AddObject(nil, Text, Folder); end else begin Folder := TGXFolder.Create(GetFolder(tvFolders.Selected)); Node := tvFolders.Items.AddChildObject(tvFolders.Selected, Text, Folder); end; FModified := True; except on E: Exception do begin FreeAndNil(Folder); raise; end; end; Folder.FolderType := FType; Node.ImageIndex := Ord(FType) * 2; Node.SelectedIndex := Node.ImageIndex + 1; Folder.FolderName := Text; Result := Node; end; procedure TfmFavFiles.tvFoldersChange(Sender: TObject; Node: TTreeNode); resourcestring SItems = '%d favorite(s)'; var Folder: TGXFolder; mFile: TGXFile; i: Integer; LItem: TListItem; Cursor: IInterface; begin if (csDestroying in ComponentState) then Exit; if tvFolders.Selected = nil then Exit; Cursor := TempHourGlassCursor; ListView.Items.BeginUpdate; try ListView.Items.Clear; ListView.SortType := stNone; Folder := GetFolder(tvFolders.Selected); for i := 0 to Folder.FileCount - 1 do begin mFile := Folder.Files[i]; LItem := ListView.Items.Add; FileToListItem(mFile, LItem); end; StatusBar.SimpleText := Format(SItems, [ListView.Items.Count]); finally ListView.SortType := stText; ListView.Items.EndUpdate; tvFolders.Selected := tvFolders.Selected; //FI:W503 - Assignment has side effects end; end; procedure TfmFavFiles.DeleteSelectedFiles; var i: Integer; begin if ListView.Selected = nil then Exit; i := 0; while i <= ListView.Items.Count - 1 do begin if ListView.Items[i].Selected then begin GetFile(ListView.Items[i]).Free; ListView.Items[i].Delete; end else Inc(i); end; ListView.Arrange(arDefault); FModified := True; end; procedure TfmFavFiles.SaveEntries; procedure SetFolderAttributes(const Folder: TGXFolder; const FolderNode: IXMLElement); begin FolderNode.SetAttribute(XmlAttributeFolderName, Folder.FolderName); FolderNode.SetAttribute(XmlAttributeFolderType, XmlFolderTypeNames[Folder.FolderType]); end; procedure SetFileAttributes(const AFile: TGXFile; const FileNode: IXMLElement); begin FileNode.SetAttribute(XmlAttributeFileName, AFile.DName); FileNode.SetAttribute(XmlAttributeFileFileName, MakeFileNameRelative(AFile.FileName)); if AFile.Description <> '' then FileNode.SetAttribute(XmlAttributeFileDescription, AFile.Description); FileNode.SetAttribute(XmlAttributeFileExecType, XmlExecTypeNames[AFile.ExecType]); if AFile.ExecType = etCustom then FileNode.SetAttribute(XmlAttributeFileExecProg, AFile.ExecProg); end; procedure SaveFolder(const Folder: TGXFolder; const Doc: IXMLDocument; const ParentNode: IXMLElement); var FolderNode, FileNode: IXMLElement; i: Integer; begin FolderNode := Doc.CreateElement(XmlNodeFolder); SetFolderAttributes(TGXFolder(Folder), FolderNode); ParentNode.AppendChild(FolderNode); for i := 0 to Folder.FolderCount - 1 do SaveFolder(Folder.Folders[i], Doc, FolderNode); for i := 0 to Folder.FileCount - 1 do begin FileNode := Doc.CreateElement(XmlNodeFile); SetFileAttributes(Folder.Files[i], FileNode); FolderNode.AppendChild(FileNode); end; end; resourcestring SSaveError = 'Your favorite files data could not be saved to:' + sLineBreak + ' %s' + sLineBreak + 'Please verify that the path exists and the file can be written to.'; var Doc: IXMLDocument; RootNode: IXMLElement; begin if not FModified then Exit; try {$IFOPT D+} SendDebug('Saving favorites'); {$ENDIF} Doc := CreateXMLDoc; AddXMLHeader(Doc); RootNode := Doc.CreateElement(XmlNodeRoot); Doc.DocumentElement := RootNode; SaveFolder(Root, Doc, RootNode); Doc.Save(FEntryFile, ofIndent); except on E: Exception do begin {$IFOPT D+} SendDebugError('Saving favorite entries: ' + E.Message); {$ENDIF} MessageDlg(Format(SSaveError, [E.Message]), mtError, [mbOK], 0); end; end; end; procedure TfmFavFiles.CreateFolders(Folder: TGXFolder; Node: TTreeNode); var SubFolder: TGXFolder; CNode: TTreeNode; i: Integer; begin for i := 0 to Folder.FolderCount - 1 do begin SubFolder := TGXFolder(Folder.Folders[i]); CNode := tvFolders.Items.AddChildObject(Node, SubFolder.FolderName, SubFolder); CNode.ImageIndex := Ord(SubFolder.FolderType) * 2; CNode.SelectedIndex := (Ord(SubFolder.FolderType) * 2) + 1; CreateFolders(SubFolder, CNode); end; end; procedure TfmFavFiles.LogAndShowLoadError(const E: Exception); resourcestring SLoadError = 'Error while loading %s' + sLineBreak; begin GxLogAndShowException(E, Format(SLoadError, [FEntryFile])); end; function TfmFavFiles.MakeFileNameAbsolute(const FileName: string): string; begin if not GXPathCombine(Result, ExtractFilePath(EntryFile), FileName) then Result := FileName; // Return unchanged FileName as fallback end; function TfmFavFiles.MakeFileNameRelative(const FileName: string): string; begin if not GXPathRelativePathTo(Result, ExtractFilePath(EntryFile), ExpandFileName(FileName)) then Result := FileName; // Return unchanged FileName as fallback end; function GetStringAttribute(const Node: IXMLNode; const AttributeName: string): string; var AttrNode: IXMLNode; begin AttrNode := Node.Attributes.GetNamedItem(AttributeName); if Assigned(AttrNode) then Result := AttrNode.NodeValue else Result := ''; end; function GetRequiredStringAttribute(const Node: IXMLNode; const AttributeName: string): string; var AttrNode: IXMLNode; begin AttrNode := Node.Attributes.GetNamedItem(AttributeName); if Assigned(AttrNode) then Result := AttrNode.NodeValue else raise EFavFiles.CreateFmt('Missing %s Attribute', [AttributeName]); end; function GetExecTypeAttribute(const Node: IXMLNode): TExecType; var AttrNode: IXMLNode; begin AttrNode := Node.Attributes.GetNamedItem(XmlAttributeFileExecType); if Assigned(AttrNode) then Result := XmlStringToExecType(AttrNode.NodeValue) else raise EFavFiles.Create('Missing ExecType Attribute'); end; function GetFolderTypeAttribute(const Node: IXMLNode): TFolderType; var AttrNode: IXMLNode; begin AttrNode := Node.Attributes.GetNamedItem(XmlAttributeFolderType); if Assigned(AttrNode) then Result := XmlStringToFolderType(AttrNode.NodeValue) else raise EFavFiles.Create('Missing FolderType Attribute'); end; procedure TfmFavFiles.LoadEntries; procedure LoadFolder(const Folder: TGXFolder; const FolderNode: IXMLNode); var ChildNode: IXMLNode; i: Integer; SubFolder: TGXFolder; mFile: TGXFile; begin Folder.FolderName := GetRequiredStringAttribute(FolderNode, XmlAttributeFolderName); Folder.FolderType := GetFolderTypeAttribute(FolderNode); for i := 0 to FolderNode.ChildNodes.Length - 1 do begin ChildNode := FolderNode.ChildNodes.Item[i]; try if ChildNode.NodeName = XmlNodeFolder then begin SubFolder := TGXFolder.Create(Folder); LoadFolder(SubFolder, ChildNode); end else if ChildNode.NodeName = XmlNodeFile then begin mFile := TGXFile.Create(Folder); mFile.DName := GetRequiredStringAttribute(ChildNode, XmlAttributeFileName); mFile.FileName := GetRequiredStringAttribute(ChildNode, XmlAttributeFileFileName); mFile.ExecType := GetExecTypeAttribute(ChildNode); mFile.Description := GetStringAttribute(ChildNode, XmlAttributeFileDescription); mFile.ExecProg := GetStringAttribute(ChildNode, XmlAttributeFileExecProg); end; except on e: EFavFiles do LogAndShowLoadError(e); on e: EConvertError do LogAndShowLoadError(e); end; end; end; resourcestring SSaveWarning = 'The storage directory defined in the GExperts configuration ' + 'dialog is not valid. Make sure that you have selected a valid folder ' + 'or your favorite files will not be saved.'; SMissingRootFolder = 'Error: Missing root folder in file "%s"!' + sLineBreak + sLineBreak + 'Overwrite existing file with a new empty favorites file?'; var Doc: IXMLDocument; RootFolderNode: IXMLNode; Node: TTreeNode; ErrorMsg: string; begin FModified := False; tvFolders.Items.Clear; Node := nil; if not FileExists(FEntryFile) then begin Node := CreateEmptyRootNode; if not DirectoryExists(ExtractFilePath(FEntryFile)) then MessageDlg(SSaveWarning, mtWarning, [mbOK], 0); end else begin Doc := CreateXMLDoc; Doc.Load(FEntryFile); RootFolderNode := Doc.DocumentElement.SelectSingleNode(XmlNodeFolder); if RootFolderNode = nil then begin {$IFOPT D+} ErrorMsg := Format('Loading favorites: Missing root folder in file "%s".', [FEntryFile]); SendDebugError(ErrorMsg); {$ENDIF} ErrorMsg := Format(SMissingRootFolder, [FEntryFile]); if MessageDlg(ErrorMsg, mtError, [mbYes, mbNo], 0) = mrYes then Node := CreateEmptyRootNode else Abort; end else begin Root.Clear; LoadFolder(Root, RootFolderNode); Node := tvFolders.Items.AddObject(nil, Root.FolderName, Root); end; end; Node.ImageIndex := 0; Node.SelectedIndex := 1; CreateFolders(Root, Node); Node.Expand(FExpandAll); if (tvFolders.Selected = nil) and (tvFolders.Items.Count > 0) then tvFolders.Selected := tvFolders.Items[0]; end; procedure TfmFavFiles.SwitchEntryFile(const AFileName: string; AUpdateMRU: Boolean = True); begin SaveEntries; EntryFile := AFileName; SaveSettings; LoadEntries; if AUpdateMRU then AddMRUString(EntryFile, MRUEntryFiles, False); end; procedure TfmFavFiles.EditFolder; var Dlg: TfmFavFolderProperties; Folder: TGXFolder; begin if tvFolders.Selected = nil then Exit; Folder := GetFolder(tvFolders.Selected); Dlg := TfmFavFolderProperties.Create(nil); try Dlg.FavoriteFilesForm := Self; Dlg.edtFolderName.Text := Folder.FolderName; Dlg.cbxFolderType.ItemIndex := Ord(Folder.FolderType); if Dlg.ShowModal = mrOk then begin FModified := True; Folder.FolderName := Dlg.edtFolderName.Text; Folder.FolderType := TFolderType(Dlg.cbxFolderType.ItemIndex); tvFolders.Selected.Text := Folder.FolderName; tvFolders.Selected.ImageIndex := Ord(Folder.FolderType) * 2; tvFolders.Selected.SelectedIndex := (Ord(Folder.FolderType) * 2) + 1; end; finally FreeAndNil(Dlg); end; end; procedure TfmFavFiles.EditFile; var mFile: TGXFile; Dlg: TfmFavFileProp; begin mFile := GetFile(ListView.Selected); if mFile = nil then Exit; Dlg := TfmFavFileProp.Create(nil); try with Dlg do begin FavoriteFilesForm := Self; edtFilename.Text := mFile.FileName; edtName.Text := mFile.DName; edtDescription.Text := mFile.Description; cbxExecuteType.ItemIndex := Ord(mFile.ExecType); edtExecuteUsing.Text := mFile.ExecProg; AssignIconImage(imgFileIcon, MakeFileNameAbsolute(mFile.FileName)); if ShowModal = mrOk then begin FModified := True; mFile.FileName := edtFilename.Text; mFile.Description := edtDescription.Text; mFile.DName := edtName.Text; mFile.ExecType := TExecType(cbxExecuteType.ItemIndex); mFile.ExecProg := edtExecuteUsing.Text; FileToListItem(mFile, ListView.Selected); end; end; finally FreeAndNil(Dlg); end; end; procedure TfmFavFiles.DeleteCurrentFolder; resourcestring SConfirmDeleteFolder = 'Do you want to delete the current folder %s?'; SCannotDeleteRoot = 'You cannot delete the root folder. Please select a different folder.'; var SelectedItem: TTreeNode; begin SelectedItem := tvFolders.Selected; if SelectedItem = nil then Exit; if SelectedItem.Level = 0 then begin MessageDlg(SCannotDeleteRoot, mtError, [mbOK], 0); Exit; end; if FFolderDelete then if MessageDlg(Format(SConfirmDeleteFolder, [SelectedItem.Text]), mtConfirmation, [mbYes, mbNo], 0) <> mrYes then Exit; GetFolder(SelectedItem).Free; ListView.Items.Clear; { GXFiles freed by folder being deleted } SelectedItem.Delete; FModified := True; end; procedure TfmFavFiles.tvFoldersKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if tvFolders.IsEditing then Exit; case Key of VK_DELETE: begin DeleteCurrentFolder; Key := 0; end; VK_INSERT: begin CreateNewFolder; Key := 0; end; end; end; procedure TfmFavFiles.SaveSettings; var Settings: TGExpertsSettings; Key: string; begin // Do not localize. Settings := TGExpertsSettings.Create; try Settings.SaveForm(Self, ConfigurationKey + '\Window'); Settings.WriteInteger(ConfigurationKey + '\Window', 'Splitter', Max(tvFolders.Width, 30)); Settings.WriteInteger(ConfigurationKey + '\Window', 'Splitter2', Max(FFileViewer.Height, 30)); if FEntryFile = GetDefaultEntryFileName then Settings.DeleteKey(ConfigurationKey, 'EntryFile') else Settings.WriteString(ConfigurationKey, 'EntryFile', FEntryFile); Settings.WriteBool(ConfigurationKey, 'FolderDelete', FFolderDelete); Settings.WriteBool(ConfigurationKey, 'ExpandAll', FExpandAll); Settings.WriteBool(ConfigurationKey, 'ExecHide', FExecHide); Settings.WriteBool(ConfigurationKey, 'ShowPreview', ShowPreview); Settings.WriteInteger(ConfigurationKey + '\Window', 'ListView', Ord(ListView.ViewStyle)); Settings.WriteStrings(MRUEntryFiles, ConfigurationKey + PathDelim + 'MRUEntryFiles', 'EntryFile'); finally FreeAndNil(Settings); end; Key := AddSlash(ConfigInfo.GExpertsIdeRootRegistryKey) + ConfigurationKey; SaveTreeSettings(tvFolders, TreeSaveAll, Key); end; procedure TfmFavFiles.LoadSettings; var Settings: TGExpertsSettings; Key: string; begin // Do not localize. Settings := TGExpertsSettings.Create; try Settings.LoadForm(Self, ConfigurationKey + '\Window'); tvFolders.Width := Settings.ReadInteger(ConfigurationKey + '\Window', 'Splitter', tvFolders.Width); FFileViewer.Height := Settings.ReadInteger(ConfigurationKey + '\Window', 'Splitter2', FFileViewer.Height); EntryFile := Settings.ReadString(ConfigurationKey, 'EntryFile', GetDefaultEntryFileName); FFolderDelete := Settings.ReadBool(ConfigurationKey, 'FolderDelete', FFolderDelete); FExpandAll := Settings.ReadBool(ConfigurationKey, 'ExpandAll', FExpandAll); FExecHide := Settings.ReadBool(ConfigurationKey, 'ExecHide', FExecHide); ShowPreview := Settings.ReadBool(ConfigurationKey, 'ShowPreview', ShowPreview); ListView.ViewStyle := TViewStyle(Settings.ReadInteger(ConfigurationKey + '\Window', 'ListView', Ord(ListView.ViewStyle))); Assert(ListView.ViewStyle in [Low(TViewStyle)..High(TViewStyle)]); Settings.ReadStrings(MRUEntryFiles, ConfigurationKey + PathDelim + 'MRUEntryFiles', 'EntryFile'); finally FreeAndNil(Settings); end; Key := AddSlash(ConfigInfo.GExpertsIdeRootRegistryKey) + ConfigurationKey; LoadTreeSettings(tvFolders, TreeSaveAll, Key); end; procedure TfmFavFiles.SetupSystemImageLists; var AHandle: DWord; FileInfo: TSHFileInfo; begin // Who is responsible for freeing that returned handle? // We do not do it, since both imagelists share their images // The Win32 API docs do not mention anything. AHandle := SHGetFileInfo('', 0, FileInfo, SizeOf(FileInfo), SHGFI_SMALLICON or SHGFI_SYSICONINDEX); if AHandle <> 0 then begin ilSystem.Handle := AHandle; ilSystem.ShareImages := True; end; AHandle := SHGetFileInfo('', 0, FileInfo, SizeOf(FileInfo), SHGFI_ICON or SHGFI_SYSICONINDEX); if AHandle <> 0 then begin ilSysLarge.Handle := AHandle; ilSysLarge.ShareImages := True; end; end; procedure TfmFavFiles.SetFilter; var Folder: TGXFolder; begin if tvFolders.Selected = nil then Exit; Folder := GetFolder(tvFolders.Selected); case Folder.FolderType of ftNormal: dlgGetFiles.FilterIndex := 11; ftSource: dlgGetFiles.FilterIndex := 1; ftBitmap: dlgGetFiles.FilterIndex := 5; ftGlyph: dlgGetFiles.FilterIndex := 5; ftDocs: dlgGetFiles.FilterIndex := 4; else dlgGetFiles.FilterIndex := 10; end; end; procedure TfmFavFiles.ListViewChange(Sender: TObject; Item: TListItem; Change: TItemChange); resourcestring SFilesSelected = '%d files selected'; SFileMissingString = '%s (missing)'; var LoadFile: string; begin if (csDestroying in ComponentState) then Exit; if (ListView.Selected <> nil) and ShowPreview then begin if ListView.SelCount = 1 then begin LoadFile := MakeFileNameAbsolute(GetFile(ListView.Selected).FileName); if FileExists(LoadFile) or DirectoryExists(LoadFile) then begin StatusBar.SimpleText := LoadFile; if FFileViewer.LoadedFile <> LoadFile then FFileViewer.LoadFromFile(LoadFile); end else StatusBar.SimpleText := Format(SFileMissingString, [LoadFile]); end else StatusBar.SimpleText := Format(SFilesSelected, [ListView.SelCount]); end else begin StatusBar.SimpleText := ''; FFileViewer.Clear; end; end; procedure TfmFavFiles.ListViewEdited(Sender: TObject; Item: TListItem; var S: string); begin GetFile(Item).DName := S; FModified := True; end; procedure TfmFavFiles.tvFoldersEdited(Sender: TObject; Node: TTreeNode; var S: string); begin GetFolder(Node).FolderName := S; FModified := True; end; procedure TfmFavFiles.ListViewDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin Accept := False; end; procedure TfmFavFiles.tvFoldersDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); var Node: TTreeNode; begin Accept := (Source is TTreeview) or (Source is TListView); if Source is TTreeView then begin Node := tvFolders.GetNodeAt(X, Y); if Node = nil then Accept := False else if tvFolders.Selected.Level = 0 then Accept := False end; end; procedure TfmFavFiles.tvFoldersDragDrop(Sender, Source: TObject; X, Y: Integer); var Node: TTreeNode; i: Integer; mFile: TGXFile; Folder: TGXFolder; Cursor: IInterface; begin try Node := tvFolders.GetNodeAt(X, Y); if Node = nil then Exit; if Source = tvFolders then begin if (tvFolders.Selected = nil) or (tvFolders.Selected = Node) or Node.HasAsParent(tvFolders.Selected) then Exit; Cursor := TempHourGlassCursor; tvFolders.Items.BeginUpdate; try tvFolders.Selected.MoveTo(Node, naAddChild); Folder := GetFolder(tvFolders.Selected); Folder.Owner := GetFolder(Node); FModified := True; (* TODO 3 -cCleanup -oAnyone: Is this code still necessary? tvFolders.Selected.DeleteChildren; CreateFolders(Folder, tvFolders.Selected); *) finally tvFolders.Items.EndUpdate; Screen.Cursor := crDefault; end; end else if Source = ListView then begin i := 0; while i <= ListView.Items.Count - 1 do begin if ListView.Items[i].Selected then begin mFile := GetFile(ListView.Items[i]); mFile.Owner := GetFolder(Node); ListView.Items[i].Delete; FModified := True; end else Inc(i); end; end; except on E: Exception do begin GxLogAndShowException(E); tvFolders.EndDrag(False); end; end; end; procedure TfmFavFiles.tvFoldersChanging(Sender: TObject; Node: TTreeNode; var AllowChange: Boolean); begin AllowChange := True; end; procedure TfmFavFiles.tvFoldersEndDrag(Sender, Target: TObject; X, Y: Integer); begin tvFolders.EndDrag(False); end; procedure TfmFavFiles.FormShow(Sender: TObject); begin //LoadSettings; end; procedure TfmFavFiles.FormHide(Sender: TObject); begin SaveEntries; SaveSettings; end; procedure TfmFavFiles.DropFiles(Sender: TObject; ShiftState: TShiftState; Point: TPoint; var Effect: Longint); begin AddFilesToCurrentFolder(FFileDrop.Files); end; function UpperFileExtToExecType(const FileExt: string): TExecType; begin if IsBdsProjectFile(FileExt) then Result := etProject else if IsBdsSourceFile(FileExt) or IsTextFile(FileExt) then Result := etLoadInIDE else Result := etShell; end; procedure TfmFavFiles.AddFilesToCurrentFolder(Files: TStrings); var mFile: TGXFile; i: Integer; LItem: TListItem; Folder: TGXFolder; Cursor: IInterface; begin if (Files = nil) or (Files.Count < 1) or (tvFolders.Selected = nil) then Exit; LItem := nil; Folder := GetFolder(tvFolders.Selected); Cursor := TempHourGlassCursor; ListView.Items.BeginUpdate; try for i := 0 to Files.Count - 1 do begin mFile := TGXFile.Create(Folder); try mFile.FileName := MakeFileNameRelative(Files[i]); mFile.Description := MakeFileNameAbsolute(mFile.FileName); mFile.DName := ExtractFileName(mFile.FileName); mFile.ExecType := UpperFileExtToExecType(ExtractUpperFileExt(mFile.FileName)); mFile.ExecProg := ''; LItem := ListView.Items.Add; FileToListItem(mFile, LItem); except on E: Exception do begin FreeAndNil(mFile); raise; end; end; FModified := True; end; finally ListView.Items.EndUpdate; end; if Assigned(LItem) then begin ListView.Selected := nil; ListView.Selected := LItem; //FI:W508 - Assignment has side effects ListView.ItemFocused := LItem; ListView.Selected.MakeVisible(False); end; end; function TfmFavFiles.GetDefaultEntryFileName: string; const FaveFavFile = 'FavoriteFiles.xml'; // Do not localize. begin // Do not localize. if IsStandAlone then Result := ConfigInfo.ConfigPath + FaveFavFile else Result := ExpandFileName(AddSlash(ConfigInfo.ConfigPath) + FaveFavFile); end; procedure TfmFavFiles.SetEntryFile(const Value: string); begin FEntryFile := Value; if FEntryFile = GetDefaultEntryFileName then Caption := 'Favorite Files' else Caption := 'Favorite Files - ' + FEntryFile; end; procedure TfmFavFiles.SetShowPreview(Value: Boolean); begin if Value <> pnlFileView.Visible then begin pnlFileView.Visible := Value; splFileView.Visible := Value; FFileViewer.Clear; if (Value) and (ListView.Selected <> nil) then ListViewChange(ListView, ListView.Selected, ctState); end; end; function TfmFavFiles.GetShowPreview: Boolean; begin Result := pnlFileView.Visible; end; procedure TfmFavFiles.actFileNewFolderExecute(Sender: TObject); begin CreateNewFolder; end; procedure TfmFavFiles.actFileExitExecute(Sender: TObject); begin Close; end; procedure TfmFavFiles.actFileNewFileExecute(Sender: TObject); begin CreateNewFile; end; procedure TfmFavFiles.actNavLevelUpExecute(Sender: TObject); begin if tvFolders.Selected <> nil then if tvFolders.Selected.Parent <> nil then tvFolders.Selected := tvFolders.Selected.Parent; end; procedure TfmFavFiles.actOptionsOptionsExecute(Sender: TObject); var Dlg: TfmFavOptions; begin Dlg := TfmFavOptions.Create(nil); try Dlg.chkConfirmFolderDelete.Checked := FFolderDelete; Dlg.chkExpandAllOnLoad.Checked := FExpandAll; Dlg.chkHideOnExecute.Checked := FExecHide; Dlg.chkShowPreview.Checked := ShowPreview; if Dlg.ShowModal = mrOk then begin FFolderDelete := Dlg.chkConfirmFolderDelete.Checked; FExpandAll := Dlg.chkExpandAllOnLoad.Checked; FExecHide := Dlg.chkHideOnExecute.Checked; ShowPreview := Dlg.chkShowPreview.Checked; end; finally FreeAndNil(Dlg); end; end; procedure TfmFavFiles.actOptionsCollectionOpenDefaultExecute(Sender: TObject); begin SwitchEntryFile(GetDefaultEntryFileName, False); end; procedure TfmFavFiles.actOptionsCollectionOpenExecute(Sender: TObject); var fn: string; begin fn := FEntryFile; if ShowOpenDialog('Load Collection', 'xml', fn) then SwitchEntryFile(ExpandFileName(fn)); end; procedure TfmFavFiles.mitOptionsCollectionOpenMRUExecute(Sender: TObject); begin Assert(Sender is TMenuItem); SwitchEntryFile(MRUEntryFiles[TMenuItem(Sender).Tag]); end; procedure TfmFavFiles.actOptionsCollectionSaveAsExecute(Sender: TObject); var fn: string; begin fn := FEntryFile; if ShowSaveDialog('Save Collection', 'xml', fn) then begin EntryFile := ExpandFileName(fn); SaveSettings; FModified := True; SaveEntries; AddMRUString(EntryFile, MRUEntryFiles, False); end; end; procedure TfmFavFiles.actNavContractExecute(Sender: TObject); begin tvFolders.Items[0].Collapse(True); end; procedure TfmFavFiles.actNavExpandExecute(Sender: TObject); begin tvFolders.Items[0].Expand(True); end; procedure TfmFavFiles.actHelpHelpExecute(Sender: TObject); begin GxContextHelp(Self, 15); end; procedure TfmFavFiles.actHelpContentsExecute(Sender: TObject); begin GxContextHelpContents(Self); end; procedure TfmFavFiles.actFileDeleteExecute(Sender: TObject); begin if tvFolders.Selected = nil then Exit; if ListView.IsEditing then begin SendMessage(GetFocus, WM_KEYDOWN, VK_DELETE, 0); SendMessage(GetFocus, WM_KEYUP, VK_DELETE, 0); end else begin if ActiveControl = tvFolders then DeleteCurrentFolder else if ActiveControl = ListView then DeleteSelectedFiles; end; end; function TfmFavFiles.HaveSelectedItemInActiveControl: Boolean; begin Result := False; if ActiveControl = tvFolders then Result := (tvFolders.Selected <> nil) else if ActiveControl = ListView then Result := (ListView.Selected <> nil); end; procedure TfmFavFiles.ActionsUpdate(Action: TBasicAction; var Handled: Boolean); var HaveSelection: Boolean; NavEnabled: Boolean; begin HaveSelection := HaveSelectedItemInActiveControl; if tvFolders.Selected <> nil then NavEnabled := not (tvFolders.Selected.Level = 0) else NavEnabled := False; actNavLevelUp.Enabled := NavEnabled; actFileDelete.Enabled := HaveSelection; actFileProperties.Enabled := HaveSelection; actFileExecute.Enabled := Assigned(ListView.Selected); end; procedure TfmFavFiles.CreateNewFolder; begin with TfmFavNewFolder.Create(nil) do try FavoriteFilesForm := Self; if ShowModal = mrOk then tvFolders.Selected := AddFolder(edtFolderName.Text, TFolderType(cbxFolderType.ItemIndex)); finally Free; end; end; procedure TfmFavFiles.CreateNewFile; begin if tvFolders.Selected = nil then Exit; SetFilter; if GetOpenSaveDialogExecute(dlgGetFiles) then AddFilesToCurrentFolder(dlgGetFiles.Files); end; procedure TfmFavFiles.actFilePropertiesExecute(Sender: TObject); begin if ActiveControl = tvFolders then EditFolder else if ActiveControl = ListView then EditFile; end; procedure TfmFavFiles.actFileExecuteExecute(Sender: TObject); begin if ListView.IsEditing then begin SendMessage(GetFocus, WM_KEYDOWN, VK_RETURN, 0); SendMessage(GetFocus, WM_KEYUP, VK_RETURN, 0); end else ExecuteSelectedFiles; end; procedure TfmFavFiles.actViewLargeIconsExecute(Sender: TObject); begin ListView.ViewStyle := vsIcon; end; procedure TfmFavFiles.actViewSmallIconsExecute(Sender: TObject); begin ListView.ViewStyle := vsSmallIcon; end; procedure TfmFavFiles.actViewListExecute(Sender: TObject); begin ListView.ViewStyle := vsList; end; procedure TfmFavFiles.actViewDetailsExecute(Sender: TObject); begin ListView.ViewStyle := vsReport; end; function TfmFavFiles.ExecuteFile(AListItem: TListItem): Boolean; var mFile: TGXFile; LoadFile: string; Ext: string; resourcestring SFileDoesNotExist = 'Could not find the file %s to execute it.'; SCouldNotOpen = 'Could not open file %s'; begin Result := False; mFile := GetFile(AListItem); if mFile = nil then Exit; LoadFile := MakeFileNameAbsolute(mFile.FileName); if not (FileExists(LoadFile) or DirectoryExists(LoadFile)) then begin MessageDlg(Format(SFileDoesNotExist, [LoadFile]), mtError, [mbOK], 0); Exit; end else case mFile.ExecType of etLoadInIDE: begin if not GxOtaMakeSourceVisible(LoadFile) then MessageDlg(Format(SCouldNotOpen, [LoadFile]), mtError, [mbOK], 0) else begin if (not IsStandAlone) and FExecHide then Self.Hide; Result := True; end; end; etShell: begin GXShellExecute(LoadFile, '', True); Result := True; end; etCustom: begin GXShellExecute(mFile.ExecProg, LoadFile, True); Result := True; end; etProject: begin Ext := ExtractUpperFileExt(LoadFile); if (BorlandIdeServices as IOTAModuleServices).CloseAll then begin // D6 gives an AV calling OpenProject on these file types if IsBpg(Ext) or IsBpk(Ext) then (BorlandIdeServices as IOTAActionServices).OpenFile(LoadFile) else (BorlandIdeServices as IOTAActionServices).OpenProject(LoadFile, True); if (not IsStandAlone) and FExecHide then Self.Hide; end; end; end; end; procedure TfmFavFiles.ExecuteSelectedFiles; var i: Integer; ListItem: TListItem; begin if (not (csDestroying in ComponentState)) and (ListView.SelCount > 0) then begin SaveEntries; for i := 0 to ListView.Items.Count - 1 do begin ListItem := ListView.Items[i]; if ListItem.Selected then if not ExecuteFile(ListItem) then Break; end; end; end; constructor TfmFavFiles.Create(AOwner: TComponent); resourcestring SOpenFilter = // Note: Localize only the descriptive text, not the extensions 'Source Files (*.dpr;*.bpr;*.dpk;*.bpk;*.bpg;*.pas;*.cpp;*.hpp;*.c;*.h)|*.dpr;*.bpr;*.dpk;*.bpk;*.bpg;*.pas;*.cpp;*.hpp;*.c;*.h' + '|Project Files (*.dpr;*.bpr;*.dpk;*.bpk;*.bpg;*.bdsproj;*.bdsgroup;*.dproj;*.groupproj)|*.dpr;*.bpr;*.dpk;*.bpk;*.bpg;*.bdsproj;*.bdsgroup;*.dproj;*.groupproj' + '|Pascal Files (*.pas;*.inc)|*.pas;*.inc' + '|Help Files (*.chm;*.hlp)|*.chm;*.hlp' + '|Graphics Files (*.bmp;*.wmf;*.jpg;*.png;*.gif;*.ico)|*.bmp;*.wmf;*.jpg;*.png;*.gif;*.ico' + '|Text Files (*.txt;*.me;*.asc;*.xml;*.iss)|*.txt;*.me;*.asc;*.xml;*.iss' + '|HTML Files (*.html;*.htm)|*.html;*.htm' + '|Executable Files (*.exe)|*.exe' + '|SQL Scripts (*.sql)|*.sql' + '|C/C++ (*.c;*.cpp;*.h;*.hpp)|*.c;*.cpp;*.h;*.hpp' + '|All Files (' + AllFilesWildCard + ')|' + AllFilesWildCard; // Update SetFilter when you change these begin inherited; SetToolbarGradient(ToolBar); pnlFileView.Caption := ''; SetNonModalFormPopupMode(Self); splTreeView.AutoSnap := False; splFileView.AutoSnap := False; dlgGetFiles.Filter := SOpenFilter; FFileViewer := TFileViewer.Create(nil); FFileViewer.Parent := pnlFileView; FFileViewer.Align := alClient; FExpandAll := False; FFolderDelete := True; FExecHide := True; ShowPreview := True; FMRUEntryFiles := TStringList.Create; SetupSystemImageLists; FFileDrop := TDropFileTarget.Create(nil); FFileDrop.OnDrop := DropFiles; FFileDrop.DragTypes := [dtCopy, dtMove, dtLink]; FFileDrop.ShowImage := True; FFileDrop.Register(ListView); CenterForm(Self); LoadSettings; LoadEntries; ListView.Columns[0].Width := ColumnTextWidth; ListView.Columns[1].Width := ColumnTextWidth; ListView.Columns[2].Width := ColumnTextWidth; ListView.Columns[3].Width := ColumnTextWidth; end; destructor TfmFavFiles.Destroy; begin FreeAndNil(FMRUEntryFiles); FreeAndNil(FFileViewer); FFileDrop.Unregister; FreeAndNil(FFileDrop); inherited; end; procedure TfmFavFiles.actHelpAboutExecute(Sender: TObject); begin ShowGXAboutForm; end; procedure TfmFavFiles.FormKeyPress(Sender: TObject; var Key: Char); begin if Key = #27 then begin Key := #0; actFileExit.Execute; end; end; procedure TfmFavFiles.mitFViewClick(Sender: TObject); begin mitViewDetails.Checked := ListView.ViewStyle = vsReport; mitViewLarge.Checked := ListView.ViewStyle = vsIcon; mitViewList.Checked := ListView.ViewStyle = vsList; mitViewSmall.Checked := ListView.ViewStyle = vsSmallIcon; end; procedure TfmFavFiles.actFileRenameExecute(Sender: TObject); begin if Assigned(ListView.Selected) then ListView.Selected.EditCaption; end; function TfmFavFiles.CreateEmptyRootNode: TTreeNode; begin Assert(Assigned(Root)); Result := tvFolders.Items.AddObject(nil, SFavorites, Root); Root.FolderName := SFavorites; Root.FolderType := GX_FavUtil.ftNormal; end; function TfmFavFiles.ConfigurationKey: string; begin Result := TFilesExpert.ConfigurationKey; end; function TfmFavFiles.GetFolder(const FolderNode: TTreeNode): TGXFolder; begin if FolderNode = nil then Result := nil else Result := TGXFolder(FolderNode.Data); end; function TfmFavFiles.GetFile(const FileItem: TListItem): TGXFile; begin if FileItem = nil then Result := nil else Result := TGXFile(FileItem.Data); end; procedure TfmFavFiles.FileToListItem(const AFile: TGXFile; const AListItem: TListItem); begin AListItem.Caption := AFile.DName; AListItem.SubItems.Clear; AListItem.SubItems.Add(AFile.FileName); AListItem.SubItems.Add(AFile.Description); if AFile.ExecType = etCustom then AListItem.SubItems.Add(ExecTypeNames[AFile.ExecType] + ': ' + AFile.ExecProg) else AListItem.SubItems.Add(ExecTypeNames[AFile.ExecType]); AListItem.Data := AFile; AListItem.ImageIndex := GetSystemImageIndexForFile(MakeFileNameAbsolute(AFile.FileName)); end; { TFilesExpert } procedure TFilesExpert.SetActive(New: Boolean); begin if New <> Active then begin inherited SetActive(New); if not New then begin if Assigned(FFavoriteFiles) then begin if FFavoriteFiles.Visible then FFavoriteFiles.Close; FreeAndNil(FFavoriteFiles); end; end; end; end; function TFilesExpert.GetActionCaption: string; resourcestring SMenuCaption = 'Favorite &Files'; begin Result := SMenuCaption; end; class function TFilesExpert.GetName: string; begin Result := 'FavoriteFiles'; // Do not localize. end; procedure TFilesExpert.Execute(Sender: TObject); begin if FFavoriteFiles = nil then begin FFavoriteFiles := TfmFavFiles.Create(nil); SetFormIcon(FFavoriteFiles); end; if FFavoriteFiles.WindowState = wsMinimized then FFavoriteFiles.WindowState := wsNormal; FFavoriteFiles.Show; end; function TFilesExpert.HasConfigOptions: Boolean; begin Result := False; end; procedure TfmFavFiles.actFileSelectAllExecute(Sender: TObject); begin ListView.SelectAll; end; procedure TfmFavFiles.actFileMoveUpExecute(Sender: TObject); begin if Assigned(tvFolders.Selected) and (tvFolders.Selected.getPrevSibling <> nil) then tvFolders.Selected.MoveTo(tvFolders.Selected.getPrevSibling, naInsert); end; procedure TfmFavFiles.actFileMoveDownExecute(Sender: TObject); begin if Assigned(tvFolders.Selected) and (tvFolders.Selected.getNextSibling <> nil) then begin if tvFolders.Selected.getNextSibling.getNextSibling <> nil then tvFolders.Selected.MoveTo(tvFolders.Selected.getNextSibling.getNextSibling, naInsert) else tvFolders.Selected.MoveTo(tvFolders.Selected.Parent, naAddChild); end; end; procedure TfmFavFiles.mitFileCollectionsClick(Sender: TObject); var i: Integer; MenuItem: TMenuItem; begin mitOptionsCollectionReopen.Enabled := MRUEntryFiles.Count > 0; // Destroy old menu items for i := mitOptionsCollectionReopen.Count - 1 downto 0 do mitOptionsCollectionReopen[i].Free; mitOptionsCollectionReopen.Clear; for i := 0 to MRUEntryFiles.Count - 1 do begin MenuItem := TMenuItem.Create(Self); MenuItem.Caption := cHotkeyPrefix + IntToStr(i) + ' ' + MRUEntryFiles[i]; MenuItem.Tag := i; MenuItem.OnClick := mitOptionsCollectionOpenMRUExecute; mitOptionsCollectionReopen.Add(MenuItem); end; end; initialization RegisterGX_Expert(TFilesExpert); end.
unit PPlaceRoad; interface uses Generics.Collections, classes; type TRoad = class protected Node: string; // name of node it connects to Weight: integer; // weight of the edge public constructor Create; destructor Destroy; procedure SetNode(NewNode:string); procedure SetWeight(NewWeight:integer); function Clone:TRoad; property GetName : string read Node; property GetWeight : integer read Weight; end; TPlace = class protected Name: string; Distance: integer; // distance from source node Parent: string; public Edges: TObjectList<TRoad>; // Array of roads connecting to that place Neighbours: TList<string>; // Array of neighbouring nodes constructor Create; destructor Destroy; procedure SetName(NewName:string); procedure SetDist(NewDist:integer); procedure SetParent(NewParent:string); procedure AddEdge(Road:TRoad); procedure AddNeighbour(Place:string); procedure ClearEdges; procedure ClearNeighbours; function Clone:TPlace; property GetName : string read Name; property GetDist : integer read Distance; property GetParent : string read Parent; end; implementation { TPlace } procedure TPlace.AddEdge(Road: TRoad); begin self.Edges.Add(Road); end; procedure TPlace.AddNeighbour(Place: string); begin self.Neighbours.Add(Place); end; procedure TPlace.ClearEdges; var i: Integer; begin self.Edges.Clear; end; procedure TPlace.ClearNeighbours; var i: Integer; begin self.Neighbours.Clear; end; function TPlace.Clone: TPlace; //creates a deep copy of the place var Copy:TPlace; i,n:integer; begin Copy:=TPlace.Create; Copy.SetName(self.GetName); Copy.SetDist(self.GetDist); Copy.SetParent(self.GetParent); for i := 0 to self.Edges.Count -1 do begin Copy.Edges.Add(self.Edges.List[i].Clone) end; for n := 0 to self.Neighbours.Count -1 do begin Copy.Neighbours.Add(self.Neighbours.List[n]) end; result:=Copy; end; constructor TPlace.Create; //initialise null values and create lists begin self.Name := 'Null'; self.Distance := -1; self.Parent := 'Null'; self.Edges := TObjectList<TRoad>.Create; self.Neighbours := TList<string>.Create; end; destructor TPlace.Destroy; begin self.Free; end; procedure TPlace.SetDist(NewDist: integer); begin self.Distance := NewDist; end; procedure TPlace.SetName(NewName: string); begin self.Name := NewName; end; procedure TPlace.SetParent(NewParent: string); begin self.Parent := NewParent; end; { TRoad } function TRoad.Clone: TRoad; //creates a deep copy of the road var Copy:TRoad; begin Copy:=TRoad.Create; Copy.Node := self.Node; Copy.Weight := self.Weight; result:=Copy; end; constructor TRoad.Create; //initialise null values begin self.Node := 'Null'; self.Weight := -1; end; destructor TRoad.Destroy; begin self.Free; end; procedure TRoad.SetNode(NewNode: string); begin self.Node := NewNode; end; procedure TRoad.SetWeight(NewWeight: integer); begin self.Weight := NewWeight; 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} {*********************************************************} {* OVCMETER.PAS 2.17 *} {* Copyright (c) 1995-98 TurboPower Software Co *} {* All rights reserved. *} {*********************************************************} unit OvcMeter; {-Meter component} interface uses {$IFDEF Win32} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF} Classes, Controls, Graphics, Forms, Messages, SysUtils, OvcBase, OvcConst, OvcData; type TMeterOrientation = (moHorizontal, moVertical); const DefMeterBorderStyle = bsNone; DefMeterCtl3D = True; DefMeterDividerColor = clBlack; DefMeterOrientation = moHorizontal; DefMeterParentCtl3D = True; DefMeterPercent = 33; DefMeterShowPercent = False; DefMeterUsedColor = clLime; DefMeterUsedShadow = clGreen; DefMeterUnusedColor = clWindow; DefMeterUnusedShadow = clWindowFrame; type TOvcCustomMeter = class(TOvcBase) {.Z+} protected {private} {Property fields} FBorderStyle : TBorderStyle; FDividerColor : TColor; FOrientation : TMeterOrientation; FPercent : Byte; FShowPercent : Boolean; FUsedColor : TColor; FUsedShadow : TColor; FUnusedColor : TColor; FUnusedShadow : TColor; ValueString : string[5]; {Property access methods} procedure SetBorderStyle(const BS : TBorderStyle); procedure SetDividerColor(const C : TColor); procedure SetOrientation(const O : TMeterOrientation); procedure SetPercent(const V : byte); procedure SetShowPercent(const SP : boolean); procedure SetUnusedColor(const C : TColor); procedure SetUnusedShadow(const C : TColor); procedure SetUsedColor(const C : TColor); procedure SetUsedShadow(const C : TColor); {VCL control messages} procedure CMCtl3DChanged(var Msg : TMessage); message CM_CTL3DCHANGED; protected {VCL methods} procedure CreateParams(var Params: TCreateParams); override; procedure Paint; override; {.Z-} public {VCL methods} constructor Create(AOwner : TComponent); override; {public properties} property BorderStyle : TBorderStyle read FBorderStyle write SetBorderStyle default DefMeterBorderStyle; property Canvas; property DividerColor : TColor read FDividerColor write SetDividerColor default DefMeterDividerColor; property Orientation : TMeterOrientation read FOrientation write SetOrientation default DefMeterOrientation; property ShowPercent : boolean read FShowPercent write SetShowPercent default DefMeterShowPercent; property UnusedColor : TColor read FUnusedColor write SetUnusedColor default DefMeterUnusedColor; property UnusedShadow : TColor read FUnusedShadow write SetUnusedShadow default DefMeterUnusedShadow; property UsedColor : TColor read FUsedColor write SetUsedColor default DefMeterUsedColor; property UsedShadow : TColor read FUsedShadow write SetUsedShadow default DefMeterUsedShadow; property Percent : Byte read FPercent write SetPercent default DefMeterPercent; end; TOvcMeter = class(TOvcCustomMeter) published property BorderStyle; property DividerColor; property Orientation; property Percent; property ShowPercent; property UnusedColor; property UnusedShadow; property UsedColor; property UsedShadow; {inherited properties} property Align; property Ctl3D; property Font; property ParentCtl3D; property ParentFont; property ParentShowHint; property ShowHint; property Visible; {inherited events} property OnClick; property OnDblClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; end; implementation {$IFDEF TRIALRUN} uses OrTrial; {$I ORTRIALF.INC} {$ENDIF} {*** TOvcMeter ***} procedure TOvcCustomMeter.CMCtl3DChanged(var Msg : TMessage); begin if (csLoading in ComponentState) or not HandleAllocated then Exit; {$IFDEF Win32} if NewStyleControls and (FBorderStyle = bsSingle) then RecreateWnd; {$ENDIF} inherited; end; constructor TOvcCustomMeter.Create(AOwner : TComponent); begin inherited Create(AOwner); {$IFDEF Win32} if NewStyleControls then ControlStyle := ControlStyle + [csOpaque] else ControlStyle := ControlStyle + [csOpaque, csFramed]; {$ELSE} ControlStyle := ControlStyle + [csOpaque, csFramed]; {$ENDIF} {defaults} FBorderStyle := DefMeterBorderStyle; FOrientation := DefMeterOrientation; FPercent := DefMeterPercent; FShowPercent := DefMeterShowPercent; FUnusedColor := DefMeterUnusedColor; FUnusedShadow := DefMeterUnusedShadow; FUsedColor := DefMeterUsedColor; FUsedShadow := DefMeterUsedShadow; ValueString := Format('%d%%', [FPercent]); Width := 200; Height := 24; Ctl3D := DefMeterCtl3D; ParentCtl3D := DefMeterParentCtl3D; end; procedure TOvcCustomMeter.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do Style := LongInt(Style) or BorderStyles[FBorderStyle]; {!!.D4} {$IFDEF Win32} if NewStyleControls and Ctl3D and (FBorderStyle = bsSingle) then begin Params.Style := Params.Style and not WS_BORDER; Params.ExStyle := Params.ExStyle or WS_EX_CLIENTEDGE; end; {$ENDIF} end; procedure TOvcCustomMeter.Paint; var MemBM : TBitMap; TextWd : Integer; TextHt : Integer; UsedLen : Integer; UnusedLen : Integer; MeterLen : Integer; DividerPos : Integer; WideShadow : boolean; begin MemBM := TBitMap.Create; try MemBM.Width := ClientWidth; MemBM.Height := ClientHeight; {calculate dimensions of both sides, position of divider, etc} WideShadow := (ClientWidth > 5) and (ClientHeight > 5); if (FOrientation = moVertical) then MeterLen := ClientHeight else MeterLen := ClientWidth; DividerPos := (longint(FPercent) * MeterLen) div 100; if (DividerPos < 3) then begin UsedLen := 0; UnusedLen := MeterLen; end else if (DividerPos = MeterLen) then begin UsedLen := MeterLen; UnusedLen := 0; end else begin if (DividerPos > MeterLen-3) then DividerPos := MeterLen-3; UsedLen := DividerPos; UnusedLen := MeterLen - UsedLen - 1; {1 for the divider} end; {draw the meter based on the orientation} if (Orientation = moHorizontal) then begin with MemBM.Canvas do begin {draw the used side of the meter} if (UsedLen > 0) then begin Brush.Color := UsedColor; FillRect(Rect(0, 0, UsedLen, ClientHeight)); Pen.Color := UsedShadow; MoveTo(0, ClientHeight-1); LineTo(0, 0); LineTo(UsedLen, 0); if WideShadow then begin MoveTo(1, ClientHeight-1); LineTo(1, 1); LineTo(UsedLen, 1); end; end; {draw the divider} Pen.Color := DividerColor; MoveTo(UsedLen, 0); LineTo(UsedLen, ClientHeight); {draw the unused side} if (UnusedLen > 0) then begin Brush.Color := UnusedColor; FillRect(Rect(UsedLen+1, 0, ClientWidth, ClientHeight)); Pen.Color := UnusedShadow; MoveTo(UsedLen+1, 0); LineTo(ClientWidth, 0); if WideShadow then begin MoveTo(UsedLen+1, 1); LineTo(ClientWidth, 1); end; end; end end else begin {it's vertical} with MemBM.Canvas do begin {draw the unused side of the meter} if (UnusedLen > 0) then begin Brush.Color := UnusedColor; FillRect(Rect(0, 0, ClientWidth, UnusedLen)); Pen.Color := UnusedShadow; MoveTo(0, UnusedLen-1); LineTo(0, 0); LineTo(ClientWidth, 0); if WideShadow then begin MoveTo(1, UnusedLen-1); LineTo(1, 1); LineTo(ClientWidth, 1); end; end; {draw the divider} Pen.Color := DividerColor; MoveTo(0, UnusedLen); LineTo(ClientWidth, UnusedLen); {draw the used side} if (UsedLen > 0) then begin Brush.Color := UsedColor; FillRect(Rect(0, UnusedLen+1, ClientWidth, ClientHeight)); Pen.Color := UsedShadow; MoveTo(0, UnusedLen+1); LineTo(0, ClientHeight); if WideShadow then begin MoveTo(1, UnusedLen+1); LineTo(1, ClientHeight); end; end; end; end; if ShowPercent then with MemBM.Canvas do begin Font := Self.Font; Brush.Style := bsClear; TextHt := TextHeight(ValueString); TextWd := TextWidth(ValueString); TextOut((ClientWidth-TextWd) div 2, (ClientHeight-TextHt) div 2, ValueString); end; Canvas.Draw(0, 0, MemBM); finally MemBM.Free; end; end; procedure TOvcCustomMeter.SetBorderStyle(const BS : TBorderStyle); begin if (BS <> BorderStyle) then begin FBorderStyle := BS; RecreateWnd; end; end; procedure TOvcCustomMeter.SetDividerColor(const C : TColor); begin if (C <> FDividerColor) then begin FDividerColor := C; Invalidate; end; end; procedure TOvcCustomMeter.SetOrientation(const O : TMeterOrientation); var TempVar : Integer; begin if (O <> FOrientation) then begin FOrientation := O; {when switching orientation, make the new meter have the same origin, but swap the width and height values} if not (csLoading in ComponentState) then begin TempVar := Width; Width := Height; Height := TempVar; end; Invalidate; end; end; procedure TOvcCustomMeter.SetShowPercent(const SP : boolean); begin if (SP <> FShowPercent) then begin FShowPercent := SP; Invalidate; end; end; procedure TOvcCustomMeter.SetUnusedColor(const C : TColor); begin if (C <> FUnusedColor) then begin FUnusedColor := C; Invalidate; end; end; procedure TOvcCustomMeter.SetUnusedShadow(const C : TColor); begin if (C <> FUnusedShadow) then begin FUnusedShadow := C; Invalidate; end; end; procedure TOvcCustomMeter.SetUsedColor(const C : TColor); begin if (C <> FUsedColor) then begin FUsedColor := C; Invalidate; end; end; procedure TOvcCustomMeter.SetUsedShadow(const C : TColor); begin if (C <> FUsedShadow) then begin FUsedShadow := C; Invalidate; end; end; procedure TOvcCustomMeter.SetPercent(const V : byte); var NewValue : Integer; begin {Validate the new value to range 0..100} if (V > 100) then NewValue := 100 else NewValue := V; if (NewValue <> FPercent) then begin FPercent := NewValue; ValueString := Format('%d%%', [V]); Repaint; end; end; end.
unit WinMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, IniFiles, ExtCtrls, StdCtrls; type TFormMain = class(TForm) MenuMain: TMainMenu; TimerIdle: TTimer; procedure FormCreate(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormDestroy(Sender: TObject); procedure TimerIdleTimer(Sender: TObject); private { Private declarations } public { Public declarations } procedure MenuClick(Sender: TObject); procedure OnUserLogOn; procedure OnLoadModule; procedure OnUnloadModule; procedure OnLoadTestProgram; procedure OnUnloadTestProgram; procedure OnLoadSequence; procedure OnEndOfTest; procedure OnCancelTest; procedure OnRestoreTest; procedure OnClearStatistics; procedure OnUpdate; end; var FormMain: TFormMain; implementation uses ProgTypes, ProgFncs, DataInt, ContInt; {$R *.dfm} procedure TFormMain.FormCreate(Sender: TObject); var IniP: TMemIniFile; procedure SetMessageProc; begin SetSwEventProc(@ExecuteEvent); end; procedure LoadPosition; begin Top:=IniP.ReadInteger('Galaxy Position', 'Top', 0); Left:=IniP.ReadInteger('Galaxy Position', 'Left', 0); ClientWidth:=IniP.ReadInteger('Galaxy Position', 'ClientWidth', 100); ClientHeight:=IniP.ReadInteger('Galaxy Position', 'ClientHeight', 100); end; procedure LoadLibraries; var IdxL: integer; LibCount: integer; LibName: string; begin LibCount:=IniP.ReadInteger('Library', 'LibraryCount', 0); if (LibCount > 0) then begin ScadusX.PrepareLibraryList(LibCount); for IdxL:=0 to (LibCount-1) do begin LibName:=IniP.ReadString('Library_'+IntToStr(IdxL), 'Name', '.dll'); ScadusX.OpenLibrary(IdxL, ScadusX.StartDir+'Libraries\'+LibName); LibName:=copy(LibName, 1, Length(LibName)-4); ScadusX.AddLibToLibraryList(IdxL, LibName); end; end; end; procedure LoadMenu; var TagM: integer; procedure LoadMenuItem(MenuP: TMenuItem; SectStr: string); var MenuN: TMenuItem; IdxM: integer; begin IdxM:=1; while (IniP.SectionExists(SectStr+'_'+IntToStr(IdxM))) do begin if (MenuP <> nil) then begin MenuN:=TMenuItem.Create(MenuP); MenuP.Add(MenuN); end else begin MenuN:=TMenuItem.Create(MenuMain); MenuMain.Items.Add(MenuN); end; MenuN.Caption:=IniP.ReadString(SectStr+'_'+IntToStr(IdxM), 'Caption', '?'); MenuN.OnClick:=MenuClick; MenuN.Tag:=TagM; TagM:=TagM+1; if (IniP.SectionExists(SectStr+'_'+IntToStr(IdxM)+'_1')) then LoadMenuItem(MenuN, SectStr+'_'+IntToStr(IdxM)); IdxM:=IdxM+1; end; end; procedure LoadMenuFnc(SectStr: string); var FncN: string; IdxM: integer; begin IdxM:=1; while (IniP.SectionExists(SectStr+'_'+IntToStr(IdxM))) do begin FncN:=IniP.ReadString(SectStr+'_'+IntToStr(IdxM), 'Function', ''); ScadusX.AddFncToMenuList(TagM, FncN); TagM:=TagM+1; if (IniP.SectionExists(SectStr+'_'+IntToStr(IdxM)+'_1')) then LoadMenuFnc(SectStr+'_'+IntToStr(IdxM)); IdxM:=IdxM+1; end; end; begin MenuMain.Items.Clear; TagM:=0; LoadMenuItem(nil, 'Group'); if (TagM > 0) then begin ScadusX.PrepareMenuList(TagM); TagM:=0; LoadMenuFnc('Group'); end; end; procedure LoadButtons; begin end; procedure LoadPanels; begin end; procedure LoadEvents; var CntE: integer; IdxE: integer; CntF: integer; IdxF: integer; NameF: string; begin CntE:=IniP.ReadInteger('Events Position list', 'EventsCount', 0); if (CntE > 0) then begin ScadusX.PrepareEventList(CntE); for IdxE:=1 to CntE do begin CntF:=IniP.ReadInteger('Events Position list', 'ExPL_Event'+IntToStr(IdxE)+'_Count', 0); for IdxF:=1 to CntF do begin NameF:=IniP.ReadString('Events Position list', 'ExPL_Event'+IntToStr(IdxE)+'_'+IntToStr(IdxF), ''); ScadusX.AddFncToEventExList(IdxE, NameF); end; end; end; end; procedure SetScadusEvents; begin ScadusX.SetOnAnyEvent(seUserLogOn, @OnUserLogOn); ScadusX.SetOnAnyEvent(seLoadModule, @OnLoadModule); ScadusX.SetOnAnyEvent(seUnloadModule, @OnUnloadModule); ScadusX.SetOnAnyEvent(seLoadTestProgram, @OnLoadTestProgram); ScadusX.SetOnAnyEvent(seUnloadTestProgram, @OnUnloadTestProgram); ScadusX.SetOnAnyEvent(seLoadSequence, @OnLoadSequence); ScadusX.SetOnAnyEvent(seEndOfTest, @OnEndOfTest); ScadusX.SetOnAnyEvent(seCancelTest, @OnCancelTest); ScadusX.SetOnAnyEvent(seRestoreTest, @OnRestoreTest); ScadusX.SetOnAnyEvent(seClearStatistics, @OnClearStatistics); ScadusX.SetOnAnyEvent(seUpdate, @OnUpdate); end; begin ScadusX:=TScadus.Create; if (FileExists(ScadusX.LoadProfile)) then begin IniP:=TMemIniFile.Create(ScadusX.LoadProfile); SetMessageProc; LoadPosition; LoadLibraries; LoadMenu; LoadButtons; LoadPanels; LoadEvents; SetScadusEvents; SetUserDir(ScadusX.UserDir); SetEngineer(1); SysEvent(seEngineeringMode); SysEvent(seUserLogOn); IniP.Destroy; end; end; procedure TFormMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin // end; procedure TFormMain.FormDestroy(Sender: TObject); begin SysEvent(seUserLogOff); end; procedure TFormMain.TimerIdleTimer(Sender: TObject); begin if (not ScadusX.IsBtn) and (not ScadusX.IsMenu) and (not ScadusX.IsEvent) and (not ScadusX.IsStart) then begin TimerIdle.Enabled:=False; SysEvent(seIdle); TimerIdle.Enabled:=True; end; end; procedure TFormMain.MenuClick(Sender: TObject); var TagM: integer; begin ScadusX.IsMenu:=True; TagM:=(Sender as TMenuItem).Tag; ScadusX.ExecuteMenu(TagM); ScadusX.IsMenu:=False; end; procedure TFormMain.OnUserLogOn; begin end; procedure TFormMain.OnLoadModule; begin end; procedure TFormMain.OnUnloadModule; begin end; procedure TFormMain.OnLoadTestProgram; begin end; procedure TFormMain.OnUnloadTestProgram; begin end; procedure TFormMain.OnLoadSequence; begin end; procedure TFormMain.OnEndOfTest; begin end; procedure TFormMain.OnCancelTest; begin end; procedure TFormMain.OnRestoreTest; begin end; procedure TFormMain.OnClearStatistics; begin end; procedure TFormMain.OnUpdate; begin end; end.
unit fmain; { Copyright (C) 2006 Luiz Américo Pereira Câmara This source 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 code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. A copy of the GNU General Public License is available on the World Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } {$mode objfpc}{$H+} interface uses Classes, MultiLog, SysUtils, LResources, Forms, Controls, Graphics, Dialogs,simpleipc, ComCtrls, Buttons, LCLIntf, LCLType, LCLProc, Menus, logtreeview; type { TfrmMain } TfrmMain = class(TForm) imgToolIcons: TImageList; popmnuClear: TMenuItem; PopupMenu1: TPopupMenu; btnShowReasonsForLogging: TToolButton; StatusBarMain: TStatusBar; ToolBar1: TToolBar; btnExpand: TToolButton; btn1: TToolButton; ToolButton2: TToolButton; btnCollapse: TToolButton; btnClear: TToolButton; btnStayOnTop: TToolButton; btnShowTimeButton: TToolButton; btnShowMethodButton: TToolButton; procedure ApplicationIdle(Sender: TObject; var Done: Boolean); procedure btnShowReasonsForLoggingClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure popmnuClearClick(Sender: TObject); procedure ReceiveMessage(Sender: TObject); procedure btnShowMethodButtonClick(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure btnCollapseClick(Sender: TObject); procedure btnExpandClick(Sender: TObject); procedure btnStayOnTopClick(Sender: TObject); procedure btnShowTimeButtonClick(Sender: TObject); private FoLogTreeView1: TLogTreeView; FoIPCServer: TSimpleIPCServer; FiMessageCount: Integer; procedure UpdateStatusBar; { private declarations } public { public declarations } end; var frmMain: TfrmMain; resourcestring csHint_On = ' (On)'; csHint_Off = ' (Off)'; csHint_AlwayOnTop = 'Always on top'; csHint_ShowTime = 'Show Time'; csHint_DidacticMethod = 'Didactic display of the coded Lazarus\Pascal method'; csHint_ReasonForLogging = 'Display the reasons for logging'; implementation {$R *.lfm} { TfrmMain } procedure TfrmMain.FormCreate(Sender: TObject); begin {$ifdef unix} Application.OnIdle:= @ApplicationIdle; {$endif} FoLogTreeView1:= TLogTreeView.Create(Self); with FoLogTreeView1 do begin Parent:= Self; Left:= 0; Height:= 386; Top:= 36; Width:= 532; Align:= alClient; DefaultItemHeight:= 18; // -- ScrollBars:= ShowTime:= False; TabOrder:= 1; TimeFormat:= 'hh:nn:ss:zzz'; PopupMenu:= PopupMenu1; end; FoIPCServer:= TSimpleIPCServer.Create(nil); with FoIPCServer do begin ServerID:='ipc_log_server'; Global:=True; OnMessage:= @ReceiveMessage; StartServer; end; UpdateStatusBar; //set up bitBtns: btnStayOnTopClick(Sender); btnShowTimeButtonClick(Sender); btnShowMethodButtonClick(Sender); btnShowReasonsForLoggingClick(Sender); end; procedure TfrmMain.popmnuClearClick(Sender: TObject); begin FoLogTreeView1.Clear; StatusBarMain.SimpleText:= '0 message'; end; procedure TfrmMain.ApplicationIdle(Sender: TObject; var Done: Boolean); begin FoIPCServer.PeekMessage(1,True); end; procedure TfrmMain.FormDestroy(Sender: TObject); begin FoIPCServer.Free; FoLogTreeView1.Free; end; procedure TfrmMain.ReceiveMessage(Sender: TObject); var recAMsg: TrecLogMessage; iSizeOfText: Integer = 0; iSizeOfData: Integer = 0; iSizeOfSetFilterDynamic_speIPC: Integer = 0; sSetFilterDynamic_speIPC: string; {$If defined(DEBUG)} aSetOf: TGroupOfForWhatReasonsToLogActually; {$EndIf} begin with TSimpleIPCServer(Sender).MsgData do begin Seek(0,soFromBeginning); ReadBuffer(recAMsg.iMethUsed,SizeOf(Integer)); ReadBuffer(recAMsg.dtMsgTime,SizeOf(TDateTime)); ReadBuffer(iSizeOfText,SizeOf(Integer)); if iSizeOfText>0 then begin { if there's a text to read? } SetLength(recAMsg.sMsgText,iSizeOfText); ReadBuffer(recAMsg.sMsgText[1],iSizeOfText); end else recAMsg.sMsgText:= ''; ReadBuffer(iSizeOfSetFilterDynamic_speIPC,SizeOf(Integer)); if iSizeOfSetFilterDynamic_speIPC>0 then begin { if there's a text to read? } SetLength(sSetFilterDynamic_speIPC,iSizeOfSetFilterDynamic_speIPC); ReadBuffer(sSetFilterDynamic_speIPC[1],iSizeOfSetFilterDynamic_speIPC); end else sSetFilterDynamic_speIPC:= ''; recAMsg.setFilterDynamic:= TGroupOfForWhatReasonsToLogActually(MultiLog.TLogChannelUtils.StringToSetof(sSetFilterDynamic_speIPC)); {$If defined(DEBUG)} aSetOf:= [lwDebug, lwInfo]; DebugLn('1-for remind:-@int([lwDebug, lwInfo])='+IntToStr(MultiLog.TLogChannelUtils.SetofToInt(aSetOf))); aSetOf:= TGroupOfForWhatReasonsToLogActually(MultiLog.TLogChannelUtils.StringToSetof(sSetFilterDynamic_speIPC)); DebugLn('2-comparaison:-@int(aSetOf)='+IntToStr(MultiLog.TLogChannelUtils.SetofToInt(aSetOf))+MultiLog.TLogChannelUtils.SetofToString(aSetOf)); {$EndIf} ReadBuffer(iSizeOfData,SizeOf(Integer)); if iSizeOfData > 0 then begin recAMsg.pData:= TMemoryStream.Create; //WriteLn('[LogViewer] DataSize: ', iSizeOfData); //WriteLn('DataCopied: ', recAMsg.Data.CopyFrom(TSimpleIPCServer(Sender).MsgData,iSizeOfData)); recAMsg.pData.CopyFrom(TSimpleIPCServer(Sender).MsgData,iSizeOfData); end else recAMsg.pData:=nil; FoLogTreeView1.AddMessage(recAMsg); if iSizeOfData > 0 then recAMsg.pData.Free; end; Inc(FiMessageCount); UpdateStatusBar; end; procedure TfrmMain.btnClearClick(Sender: TObject); begin FoLogTreeView1.Clear; FiMessageCount:=0; UpdateStatusBar; end; procedure TfrmMain.btnCollapseClick(Sender: TObject); begin FoLogTreeView1.FullCollapse; end; procedure TfrmMain.btnExpandClick(Sender: TObject); begin FoLogTreeView1.FullExpand end; procedure TfrmMain.btnStayOnTopClick(Sender: TObject); begin if btnStayOnTop.Down then begin FormStyle:= fsSystemStayOnTop; btnStayOnTop.Hint:= csHint_AlwayOnTop + csHint_On; end else begin FormStyle:= fsNormal; btnStayOnTop.Hint:= csHint_AlwayOnTop + csHint_Off; end; end; procedure TfrmMain.btnShowTimeButtonClick(Sender: TObject); begin if btnShowTimeButton.Down then begin FoLogTreeView1.ShowTime:= true; btnShowTimeButton.Hint:= csHint_ShowTime + csHint_On; end else begin FoLogTreeView1.ShowTime:= false; btnShowTimeButton.Hint:= csHint_ShowTime + csHint_Off; end; end; procedure TfrmMain.btnShowMethodButtonClick(Sender: TObject); begin if btnShowMethodButton.Down then begin FoLogTreeView1.ShowPrefixMethod:= true; btnShowMethodButton.Hint:= csHint_DidacticMethod + csHint_On; end else begin FoLogTreeView1.ShowPrefixMethod:= false; btnShowMethodButton.Hint:= csHint_DidacticMethod + csHint_Off; end; end; procedure TfrmMain.btnShowReasonsForLoggingClick(Sender: TObject); begin if btnShowReasonsForLogging.Down then begin FoLogTreeView1.ShowDynamicFilter_forWhatReasonsToLogActually:= true; btnShowReasonsForLogging.Hint:= csHint_ReasonForLogging + csHint_On; end else begin FoLogTreeView1.ShowDynamicFilter_forWhatReasonsToLogActually:= false; btnShowReasonsForLogging.Hint:= csHint_ReasonForLogging + csHint_Off; end; end; procedure TfrmMain.UpdateStatusBar; begin StatusBarMain.SimpleText:= IntToStr(FiMessageCount)+' messages'; end; end.
unit MainClientFormU; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls; type TForm5 = class(TForm) Memo1: TMemo; Memo2: TMemo; Panel1: TPanel; btnGet: TButton; btnLOGIN: TButton; Splitter1: TSplitter; Memo3: TMemo; Splitter2: TSplitter; procedure btnGetClick(Sender: TObject); procedure btnLOGINClick(Sender: TObject); private FJWT: string; procedure SetJWT(const Value: string); property JWT: string read FJWT write SetJWT; public { Public declarations } end; var Form5: TForm5; implementation {$R *.dfm} uses MVCFramework.RESTClient, MVCFramework.SystemJSONUtils, MVCFramework.TypesAliases; procedure TForm5.btnGetClick(Sender: TObject); var lClient: TRESTClient; lResp: IRESTResponse; lQueryStringParams: TStringList; begin { Getting JSON response } lClient := TRESTClient.Create('localhost', 8080); try lClient.ReadTimeOut(0); if not FJWT.IsEmpty then lClient.RequestHeaders.Values['Authentication'] := 'bearer ' + FJWT; lQueryStringParams := TStringList.Create; try lQueryStringParams.Values['firstname'] := 'Daniele'; lQueryStringParams.Values['lastname'] := 'Teti'; lResp := lClient.doGET('/admin/role1', [], lQueryStringParams); if lResp.HasError then ShowMessage(lResp.Error.ExceptionMessage); finally lQueryStringParams.Free; end; Memo2.Lines.Text := lResp.BodyAsString; finally lClient.Free; end; { Getting HTML response } lClient := TRESTClient.Create('localhost', 8080); try lClient.ReadTimeOut(0); if not FJWT.IsEmpty then lClient.RequestHeaders.Values['Authentication'] := 'bearer ' + FJWT; lQueryStringParams := TStringList.Create; try lQueryStringParams.Values['firstname'] := 'Daniele'; lQueryStringParams.Values['lastname'] := 'Teti'; lResp := lClient.Accept('text/html').doGET('/admin/role1', [], lQueryStringParams); if lResp.HasError then ShowMessage(lResp.Error.ExceptionMessage); finally lQueryStringParams.Free; end; Memo3.Lines.Text := lResp.BodyAsString; finally lClient.Free; end; end; procedure TForm5.btnLOGINClick(Sender: TObject); var lClient: TRESTClient; lRest: IRESTResponse; lJSON: TJSONObject; begin lClient := TRESTClient.Create('localhost', 8080); try lClient.ReadTimeOut(0); lClient .Header('jwtusername', 'user1') .Header('jwtpassword', 'user1'); lRest := lClient.doPOST('/login', []); if lRest.HasError then begin ShowMessage(lRest.Error.ExceptionMessage); Exit; end; lJSON := TSystemJSON.StringAsJSONObject(lRest.BodyAsString); try JWT := lJSON.GetValue('token').Value; finally lJSON.Free; end; finally lClient.Free; end; end; procedure TForm5.SetJWT(const Value: string); begin FJWT := Value; Memo1.Lines.Text := Value; end; end.
unit TAddressLabelData; interface uses System.SysUtils, System.UITypes, System.Classes, FMX.Types, FMX.Controls, FMX.Layouts, FMX.Edit, FMX.StdCtrls, FMX.Clipboard, FMX.Platform, FMX.Objects, FMX.Graphics, System.Types, StrUtils, FMX.Dialogs, CrossPlatformHeaders; type TAddressLabel = class(TLayout) private prefix, AddrPrefix, address, AddrSuffix: Tlabel; ftext: AnsiString; lastPrefixLength: Integer; FLastWidth: Single; function getText(): AnsiString; protected procedure DoRealign; override; procedure Resize; override; public TextSettings: TTextSettings; procedure SetText(const Value: AnsiString; prefixLength: Integer); overload; procedure SetText(const Value: AnsiString); overload; property Text: AnsiString read getText write SetText; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; procedure cutAndDecorateLabel(lbl: Tlabel); procedure Register; implementation uses uhome; procedure Register; begin RegisterComponents('Samples', [TAddressLabel]); end; procedure TAddressLabel.Resize; var strLength: Integer; outText: AnsiString; prefSufLength: Integer; source: AnsiString; startPosition: Single; normalCanvas, BoltCanvas: TBitmap; DEBUGSTR: AnsiString; prefW, addrPrefW, AddrSufW: Single; avr: Single; propLen: Integer; begin inherited Resize; if Self.Width = FLastWidth then Exit; FLastWidth := Self.Width; try // Realign; // RecalcSize; prefix.Width := 0; AddrPrefix.Width := 0; address.Width := 0; AddrSuffix.Width := 0; normalCanvas := TBitmap.Create(10, 10); BoltCanvas := TBitmap.Create(10, 10); normalCanvas.Canvas.Font.Assign(prefix.Font); BoltCanvas.Canvas.Font.Assign(AddrPrefix.Font); source := LeftStr(ftext, length(ftext) - 4); source := RightStr(source, length(source) - (4 + length(prefix.Text))); prefW := normalCanvas.Canvas.TextWidth(prefix.Text); addrPrefW := BoltCanvas.Canvas.TextWidth(AddrPrefix.Text); AddrSufW := BoltCanvas.Canvas.TextWidth(AddrSuffix.Text); avr := (prefW + addrPrefW + AddrSufW) / (8 + length(prefix.Text)); if avr = 0 then begin normalCanvas.Free; BoltCanvas.Free; Exit; end; propLen := round((Width * 0.4) / avr) - (8 + length(prefix.Text)); outText := LeftStr(source, propLen) + '...' + RightStr(source, propLen); prefSufLength := propLen + 1; if length(source) <= prefSufLength * 2 then begin outText := source; end else while (normalCanvas.Canvas.TextWidth(outText) + prefW + addrPrefW + AddrSufW) < Width * 0.85 do begin if length(source) <= prefSufLength * 2 then begin outText := source; break; end else outText := LeftStr(source, prefSufLength) + '...' + RightStr(source, prefSufLength); prefSufLength := prefSufLength + 1; end; address.Text := outText; if TextSettings.horzAlign = TTextAlign.Center then startPosition := (Width - (prefix.Width + AddrPrefix.Width + address.Width + AddrSuffix.Width)) / 2 else if TextSettings.horzAlign = TTextAlign.Trailing then startPosition := (Width - (prefix.Width + AddrPrefix.Width + address.Width + AddrSuffix.Width)) else startPosition := 0; prefix.RecalcSize; AddrPrefix.RecalcSize; address.RecalcSize; AddrSuffix.RecalcSize; prefix.Position.X := startPosition; AddrPrefix.Position.X := prefix.Position.X + prefix.Width; address.Position.X := startPosition + prefix.Width + AddrPrefix.Width; AddrSuffix.Position.X := startPosition + prefix.Width + AddrPrefix.Width + address.Width; // Repaint; normalCanvas.Free; BoltCanvas.Free; except on e: Exception do begin // showmessage(e.Message); end; end; end; procedure TAddressLabel.DoRealign; var startPosition: Single; begin inherited; { if TextSettings.horzAlign = TTextAlign.Center then startPosition := (width - (prefix.width + AddrPrefix.width + address.width + AddrSuffix.width)) / 2 else if TextSettings.horzAlign = TTextAlign.Trailing then startPosition := (width - (prefix.width + AddrPrefix.width + address.width + AddrSuffix.width)) else startPosition := 0; prefix.Position.X := startPosition; AddrPrefix.Position.X := prefix.Position.X + prefix.width; address.Position.X := startPosition + prefix.width + AddrPrefix.width; AddrSuffix.Position.X := startPosition + prefix.width + AddrPrefix.width + address.width; Repaint; } end; destructor TAddressLabel.Destroy; begin inherited; TextSettings.Free; end; function TAddressLabel.getText(): AnsiString; begin result := ftext; end; constructor TAddressLabel.Create(AOwner: TComponent); begin inherited Create(AOwner); FLastWidth := Self.Width; TextSettings := TTextSettings.Create(Self); lastPrefixLength := 0; // width := Tcontrol(AOwner).width; prefix := Tlabel.Create(Self); prefix.Parent := Self; prefix.Align := TAlignLayout.Vertical; prefix.TextAlign := TTextAlign.Center; prefix.Visible := true; prefix.AutoSize := true; prefix.WordWrap := false; AddrPrefix := Tlabel.Create(Self); AddrPrefix.Parent := Self; AddrPrefix.Align := TAlignLayout.Vertical; AddrPrefix.TextAlign := TTextAlign.Center; AddrPrefix.Visible := true; AddrPrefix.AutoSize := true; AddrPrefix.WordWrap := false; address := Tlabel.Create(Self); address.Parent := Self; address.Align := TAlignLayout.Vertical; address.TextAlign := TTextAlign.Center; address.Visible := true; address.AutoSize := true; address.WordWrap := false; AddrSuffix := Tlabel.Create(Self); AddrSuffix.Parent := Self; AddrSuffix.Align := TAlignLayout.Vertical; AddrSuffix.TextAlign := TTextAlign.Center; AddrSuffix.Visible := true; AddrSuffix.AutoSize := true; AddrSuffix.WordWrap := false; AddrPrefix.TextSettings.Font.style := AddrPrefix.TextSettings.Font.style + [TFontStyle.fsBold]; AddrPrefix.StyledSettings := AddrPrefix.StyledSettings - [TStyledSetting.style] - [TStyledSetting.FontColor]; AddrPrefix.FontColor := TAlphaColorRec.Orangered; AddrSuffix.TextSettings.Font.style := AddrSuffix.TextSettings.Font.style + [TFontStyle.fsBold]; AddrSuffix.StyledSettings := AddrSuffix.StyledSettings - [TStyledSetting.style] - [TStyledSetting.FontColor]; AddrSuffix.FontColor := TAlphaColorRec.Orangered; end; procedure TAddressLabel.SetText(const Value: AnsiString); begin SetText(Value, 0); end; procedure TAddressLabel.SetText(const Value: AnsiString; prefixLength: Integer); var strLength: Integer; outText: AnsiString; prefSufLength: Integer; source: AnsiString; startPosition: Single; normalCanvas, BoltCanvas: TBitmap; DEBUGSTR: AnsiString; prefW, addrPrefW, AddrSufW: Single; avr: Single; propLen: Integer; begin // Realign; // RecalcSize; ftext := Value; {TThread.CreateAnonymousThread( procedure begin TThread.Synchronize(nil, procedure begin } lastPrefixLength := prefixLength; prefix.Width := 0; AddrPrefix.Width := 0; address.Width := 0; AddrSuffix.Width := 0; normalCanvas := TBitmap.Create(10, 10); BoltCanvas := TBitmap.Create(10, 10); normalCanvas.Canvas.Font.Assign(prefix.Font); BoltCanvas.Canvas.Font.Assign(AddrPrefix.Font); source := LeftStr(Value, length(Value) - 4); source := RightStr(source, length(source) - (4 + prefixLength)); prefix.Text := LeftStr(Value, prefixLength); AddrPrefix.Text := RightStr(LeftStr(Value, 4 + prefixLength), 4); AddrSuffix.Text := RightStr(Value, 4); prefW := normalCanvas.Canvas.TextWidth(prefix.Text); addrPrefW := BoltCanvas.Canvas.TextWidth(AddrPrefix.Text); AddrSufW := BoltCanvas.Canvas.TextWidth(AddrSuffix.Text); avr := (prefW + addrPrefW + AddrSufW) / (8 + prefixLength); if avr = 0 then begin normalCanvas.Free; BoltCanvas.Free; Exit; end; propLen := round((Width * 0.4) / avr) - (8 + prefixLength); outText := LeftStr(source, propLen) + '...' + RightStr(source, propLen); prefSufLength := propLen + 1; if length(source) <= prefSufLength * 2 then begin outText := source; end else while (normalCanvas.Canvas.TextWidth(outText) + prefW + addrPrefW + AddrSufW) < Width * 0.85 do begin if length(source) <= prefSufLength * 2 then begin outText := source; break; end else outText := LeftStr(source, prefSufLength) + '...' + RightStr(source, prefSufLength); prefSufLength := prefSufLength + 1; end; address.Text := outText; // prefix.width := normalCanvas.Canvas.TextWidth(prefix.Text); // AddrPrefix.width := BoltCanvas.Canvas.TextWidth(AddrPrefix.Text); // address.width := normalCanvas.Canvas.TextWidth(address.Text); // AddrSuffix.width := BoltCanvas.Canvas.TextWidth(AddrSuffix.Text); // startPosition := ( Width - ( prefix.Width + AddrPrefix.Width + address.Width + addrsuffix.Width ) ) /2; if TextSettings.horzAlign = TTextAlign.Center then startPosition := (Width - (prefix.Width + AddrPrefix.Width + address.Width + AddrSuffix.Width)) / 2 else if TextSettings.horzAlign = TTextAlign.Trailing then startPosition := (Width - (prefix.Width + AddrPrefix.Width + address.Width + AddrSuffix.Width)) else startPosition := 0; prefix.RecalcSize; AddrPrefix.RecalcSize; address.RecalcSize; AddrSuffix.RecalcSize; prefix.Position.X := startPosition; AddrPrefix.Position.X := prefix.Position.X + prefix.Width; address.Position.X := startPosition + prefix.Width + AddrPrefix.Width; AddrSuffix.Position.X := startPosition + prefix.Width + AddrPrefix.Width + address.Width; // Repaint; normalCanvas.Free; BoltCanvas.Free; // end) // end).Start; end; procedure cutAndDecorateLabel(lbl: Tlabel); var strLength: Integer; outText: AnsiString; prefSufLength: Integer; begin strLength := length(lbl.Text); outText := LeftStr(lbl.Text, 4) + '...' + RightStr(lbl.Text, 4); prefSufLength := 5; lbl.Canvas.Font.Assign(lbl.Font); while lbl.Canvas.TextWidth(outText) < lbl.Width * 0.9 do begin outText := LeftStr(lbl.Text, prefSufLength) + '...' + RightStr(lbl.Text, prefSufLength); prefSufLength := prefSufLength + 1; end; lbl.Text := outText; end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls; type TForm1 = class(TForm) Image1: TImage; Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; Image2: TImage; OpenDialog1: TOpenDialog; Memo1: TMemo; Label1: TLabel; Memo2: TMemo; Label2: TLabel; procedure Button3Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Memo1Change(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Memo2Change(Sender: TObject); procedure Image2Click(Sender: TObject); private { Private declarations } compress: Boolean; function StreamToBase64(Value: TMemoryStream): string; function Base64ToStream(Value: String): TBytesStream; function CompactStream(Value: TMemoryStream): TMemoryStream; function UnpackStram(Value: TMemoryStream): TMemoryStream; public { Public declarations } end; var Form1: TForm1; implementation uses System.ZLib, Vcl.AxCtrls, IdCoderMIME; {$R *.dfm} function TForm1.Base64ToStream(Value: String): TBytesStream; var dm: TIdDecoderMIME; begin Result := TBytesStream.Create; dm := TIdDecoderMIME.Create(nil); try dm.DecodeBegin(Result); dm.Decode(Value); dm.DecodeEnd; Result.Position := 0; finally dm.Free; end; end; procedure TForm1.Button1Click(Sender: TObject); var ms: TMemoryStream; og: TOleGraphic; begin if OpenDialog1.Execute then begin ms := TMemoryStream.Create; try og := TOleGraphic.Create; try ms.LoadFromFile(OpenDialog1.FileName); ms.Position := 0; og.LoadFromStream(ms); Image1.Picture.Assign(og); finally og.Free; end; finally ms.Free; end; end; end; procedure TForm1.Button2Click(Sender: TObject); var ms: TMemoryStream; begin compress := False; if Image1.Picture.Graphic <> nil then begin ms := TMemoryStream.Create; try Image1.Picture.Graphic.SaveToStream(ms); ms.Position := 0; Memo1.Text := StreamToBase64(ms); finally ms.Free; end; end; end; procedure TForm1.Button3Click(Sender: TObject); var ms1, ms2: TMemoryStream; begin compress := True; if Image1.Picture.Graphic <> nil then begin ms1 := TMemoryStream.Create; try Image1.Picture.Graphic.SaveToStream(ms1); ms1.Position := 0; ms2 := CompactStream(ms1); try Memo2.Text := StreamToBase64(ms2); finally ms2.Free; end; finally ms1.Free; end; end; end; procedure TForm1.Button4Click(Sender: TObject); var bs: TBytesStream; dm: TIdDecoderMIME; og: TOleGraphic; LInput, LOutput: TMemoryStream; LUnZip: TZDecompressionStream; begin if not compress then begin og := TOleGraphic.Create; try bs := Base64ToStream(Memo1.Text); try bs.Position := 0; og.LoadFromStream(bs); Image2.Picture.Assign(og); finally bs.Free; end; finally og.Free; end; end else begin bs := Base64ToStream(Memo2.Text); try bs.Position := 0; LOutput := UnpackStram(bs); try og := TOleGraphic.Create; try og.LoadFromStream(LOutput); Image2.Picture.Assign(og); finally og.Free; end; finally LOutput.Free; end; finally bs.Free; end; end; end; function TForm1.CompactStream(Value: TMemoryStream): TMemoryStream; var LZip: TZCompressionStream; begin Result := TMemoryStream.Create; LZip := TZCompressionStream.Create(Result, zcMax, 15); try Value.Position := 0; { Compress data. } LZip.CopyFrom(Value, Value.Size); finally LZip.Free; end; Result.Position := 0; end; procedure TForm1.Image2Click(Sender: TObject); begin Image2.Picture.Graphic := nil; end; procedure TForm1.Memo1Change(Sender: TObject); begin Label1.Caption := 'Tamanho: ' + IntToStr(Length(Memo1.Text)); end; procedure TForm1.Memo2Change(Sender: TObject); begin Label2.Caption := 'Tamanho: ' + IntToStr(Length(Memo2.Text)); end; function TForm1.StreamToBase64(Value: TMemoryStream): string; begin Result := ''; if Value <> nil then Result := TIdEncoderMIME.EncodeStream(Value, Value.Size); end; function TForm1.UnpackStram(Value: TMemoryStream): TMemoryStream; var LUnZip: TZDecompressionStream; begin Value.Position := 0; Result := TMemoryStream.Create; LUnZip := TZDecompressionStream.Create(Value); try { Decompress data. } Result.CopyFrom(LUnZip, 0); Result.Position := 0; finally LUnZip.Free; end; end; end.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA 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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit frmRollbackSegmentDetail; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxMemo, cxRichEdit, cxPC, cxControls, StdCtrls, cxButtons, ExtCtrls, cxSpinEdit, cxMaskEdit, cxButtonEdit, cxGroupBox, cxCheckBox, cxLabel, OraRollbackSegment, cxGraphics, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox; type TRollbackSegmentDetailFrm = class(TForm) pc: TcxPageControl; tsRollbackSegment: TcxTabSheet; tsDDL: TcxTabSheet; redtDDL: TcxRichEdit; cxGroupBox1: TcxGroupBox; edtName: TcxTextEdit; cxLabel1: TcxLabel; cxLabel8: TcxLabel; chkOnline: TcxCheckBox; chkPublic: TcxCheckBox; gbStorageClause: TcxGroupBox; Label11: TLabel; Label12: TLabel; Label13: TLabel; Label14: TLabel; Label5: TLabel; edtInitialExtend: TcxButtonEdit; edtNextExtend: TcxButtonEdit; edtPctIncrease: TcxButtonEdit; edtMinExtents: TcxSpinEdit; edtMaxExtents: TcxSpinEdit; lcTablespace: TcxLookupComboBox; Bevel2: TBevel; cxGroupBox2: TcxGroupBox; btnCancel: TcxButton; btnExecute: TcxButton; procedure btnCancelClick(Sender: TObject); procedure pcPageChanging(Sender: TObject; NewPage: TcxTabSheet; var AllowChange: Boolean); procedure btnExecuteClick(Sender: TObject); private { Private declarations } FRollbackSegment: TRollbackSegment; procedure GetRollbackSegmentDetail; function SetRollbackSegmentDetail: boolean; public { Public declarations } function Init(ARollbackSegment: TRollbackSegment): boolean; end; var RollbackSegmentDetailFrm: TRollbackSegmentDetailFrm; implementation {$R *.dfm} uses Util, frmSchemaBrowser, GenelDM, OraStorage, VisualOptions; function TRollbackSegmentDetailFrm.Init(ARollbackSegment: TRollbackSegment): boolean; begin RollbackSegmentDetailFrm := TRollbackSegmentDetailFrm.Create(Application); Self := RollbackSegmentDetailFrm; DMGenel.ChangeLanguage(self); ChangeVisualGUI(self); FRollbackSegment := TRollbackSegment.Create; FRollbackSegment := ARollbackSegment; dmGenel.ReLoad(FRollbackSegment.OraSession); GetRollbackSegmentDetail; pc.ActivePage := tsRollbackSegment; ShowModal; result := ModalResult = mrOk; Free; end; procedure TRollbackSegmentDetailFrm.btnCancelClick(Sender: TObject); begin close; end; procedure TRollbackSegmentDetailFrm.GetRollbackSegmentDetail; begin if FRollbackSegment.Mode = InsertMode then Caption := 'Create Rollback Segment ' else Caption := 'Alter Rollback Segment '+FRollbackSegment.SEGMENT_NAME; with FRollbackSegment do begin edtName.Text := SEGMENT_NAME; lcTablespace.Text := TABLESPACE_NAME; chkOnline.Checked := STATUS = 'ONLINE'; chkPublic.Checked := OWNER = 'PUBLIC'; edtInitialExtend.Text := FloatToStr(INITIAL_EXTENT); edtNextExtend.Text := FloatToStr(NEXT_EXTENT); edtMinExtents.Text := FloatToStr(MIN_EXTENTS); edtMaxExtents.Text := FloatToStr(MAX_EXTENTS); end; edtName.enabled := FRollbackSegment.Mode = InsertMode; lcTablespace.enabled := FRollbackSegment.Mode = InsertMode; end; //GetRollbackSegmentDetail; function TRollbackSegmentDetailFrm.SetRollbackSegmentDetail: boolean; begin result := true; if edtName.Text = '' then begin MessageDlg('Rollback Segment Name must be specified', mtWarning, [mbOk], 0); result := false; exit; end; with FRollbackSegment do begin SEGMENT_NAME := edtName.Text; TABLESPACE_NAME := lcTablespace.Text; if chkOnline.Checked then STATUS := 'ONLINE' else STATUS := 'OFFLINE'; PUBLIC := chkPublic.Checked; INITIAL_EXTENT := StrToFloat(isNull(edtInitialExtend.Text)); NEXT_EXTENT := StrToFloat(isNull(edtNextExtend.Text)); MIN_EXTENTS := StrToFloat(isNull(edtMinExtents.Text)); MAX_EXTENTS := StrToFloat(isNull(edtMaxExtents.Text)); end; //RollbackSegment end; //SetRollbackSegmentDetail procedure TRollbackSegmentDetailFrm.pcPageChanging(Sender: TObject; NewPage: TcxTabSheet; var AllowChange: Boolean); begin if NewPage = tsDDL then begin if not SetRollbackSegmentDetail then AllowChange := false else begin if FRollbackSegment.Mode = InsertMode then redtDDL.Text := FRollbackSegment.GetDDL else redtDDL.Text := FRollbackSegment.GetAlterDDL; end; CodeColors(self, 'Default', redtDDL, false); end; end; procedure TRollbackSegmentDetailFrm.btnExecuteClick(Sender: TObject); begin if not SetRollbackSegmentDetail then exit; if FRollbackSegment.Mode = InsertMode then begin redtDDL.Text := FRollbackSegment.GetDDL; if FRollbackSegment.CreateRollbackSegment(redtDDL.Text) then ModalResult := mrOK; end else begin redtDDL.Text := FRollbackSegment.GetAlterDDL; if FRollbackSegment.AlterRollbackSegment(redtDDL.Text) then ModalResult := mrOK; end; end; end.
unit gauntlet_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m6502,m68000,main_engine,controls_engine,gfx_engine,rom_engine,pokey, pal_engine,sound_engine,slapstic,ym_2151,atari_mo,file_engine; function iniciar_gauntlet:boolean; implementation const gauntlet_rom:array[0..5] of tipo_roms=( (n:'136041-507.9a';l:$8000;p:0;crc:$8784133f),(n:'136041-508.9b';l:$8000;p:$1;crc:$2843bde3), (n:'136037-205.10a';l:$4000;p:$38000;crc:$6d99ed51),(n:'136037-206.10b';l:$4000;p:$38001;crc:$545ead91), (n:'136041-609.7a';l:$8000;p:$40000;crc:$5b4ee415),(n:'136041-610.7b';l:$8000;p:$40001;crc:$41f5c9e2)); gauntlet_sound:array[0..1] of tipo_roms=( (n:'136037-120.16r';l:$4000;p:$4000;crc:$6ee7f3cc),(n:'136037-119.16s';l:$8000;p:$8000;crc:$fa19861f)); gauntlet_char:tipo_roms=(n:'136037-104.6p';l:$4000;p:0;crc:$6c276a1d); gauntlet_back:array[0..7] of tipo_roms=( (n:'136037-111.1a';l:$8000;p:0;crc:$91700f33),(n:'136037-112.1b';l:$8000;p:$8000;crc:$869330be), (n:'136037-113.1l';l:$8000;p:$10000;crc:$d497d0a8),(n:'136037-114.1mn';l:$8000;p:$18000;crc:$29ef9882), (n:'136037-115.2a';l:$8000;p:$20000;crc:$9510b898),(n:'136037-116.2b';l:$8000;p:$28000;crc:$11e0ac5b), (n:'136037-117.2l';l:$8000;p:$30000;crc:$29a5db41),(n:'136037-118.2mn';l:$8000;p:$38000;crc:$8bf3b263)); gauntlet_proms:array[0..2] of tipo_roms=( (n:'74s472-136037-101.7u';l:$200;p:0;crc:$2964f76f),(n:'74s472-136037-102.5l';l:$200;p:$200;crc:$4d4fec6c), (n:'74s287-136037-103.4r';l:$100;p:$400;crc:$6c5ccf08)); //Gauntlet II gauntlet2_rom:array[0..7] of tipo_roms=( (n:'136037-1307.9a';l:$8000;p:0;crc:$46fe8743),(n:'136037-1308.9b';l:$8000;p:$1;crc:$276e15c4), (n:'136043-1105.10a';l:$4000;p:$38000;crc:$45dfda47),(n:'136043-1106.10b';l:$4000;p:$38001;crc:$343c029c), (n:'136044-2109.7a';l:$8000;p:$40000;crc:$1102ab96),(n:'136044-2110.7b';l:$8000;p:$40001;crc:$d2203a2b), (n:'136044-2121.6a';l:$8000;p:$50000;crc:$753982d7),(n:'136044-2122.6b';l:$8000;p:$50001;crc:$879149ea)); gauntlet2_sound:array[0..1] of tipo_roms=( (n:'136043-1120.16r';l:$4000;p:$4000;crc:$5c731006),(n:'136043-1119.16s';l:$8000;p:$8000;crc:$dc3591e7)); gauntlet2_char:tipo_roms=(n:'136043-1104.6p';l:$4000;p:0;crc:$bddc3dfc); gauntlet2_back:array[0..15] of tipo_roms=( (n:'136043-1111.1a';l:$8000;p:0;crc:$09df6e23),(n:'136037-112.1b';l:$8000;p:$8000;crc:$869330be), (n:'136043-1123.1c';l:$4000;p:$10000;crc:$e4c98f01),(n:'136043-1123.1c';l:$4000;p:$14000;crc:$e4c98f01), (n:'136043-1113.1l';l:$8000;p:$18000;crc:$33cb476e),(n:'136037-114.1mn';l:$8000;p:$20000;crc:$29ef9882), (n:'136043-1124.1p';l:$4000;p:$28000;crc:$c4857879),(n:'136043-1124.1p';l:$4000;p:$2c000;crc:$c4857879), (n:'136043-1115.2a';l:$8000;p:$30000;crc:$f71e2503),(n:'136037-116.2b';l:$8000;p:$38000;crc:$11e0ac5b), (n:'136043-1125.2c';l:$4000;p:$40000;crc:$d9c2c2d1),(n:'136043-1125.2c';l:$4000;p:$44000;crc:$d9c2c2d1), (n:'136043-1117.2l';l:$8000;p:$48000;crc:$9e30b2e9),(n:'136037-118.2mn';l:$8000;p:$50000;crc:$8bf3b263), (n:'136043-1126.2p';l:$4000;p:$58000;crc:$a32c732a),(n:'136043-1126.2p';l:$4000;p:$5c000;crc:$a32c732a)); gauntlet2_proms:array[0..2] of tipo_roms=( (n:'74s472-136037-101.7u';l:$200;p:0;crc:$2964f76f),(n:'74s472-136037-102.5l';l:$200;p:$200;crc:$4d4fec6c), (n:'82s129-136043-1103.4r';l:$100;p:$400;crc:$32ae1fa9)); //DIP gauntlet_dip:array [0..1] of def_dip=( (mask:$8;name:'Service';number:2;dip:((dip_val:$8;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(dip_val:$1;dip_name:'5'),(dip_val:$0;dip_name:'6'),(),(),(),(),(),(),(),(),(),(),(),())),()); gauntlet_mo_config:atari_motion_objects_config=( gfxindex:1; // index to which gfx system bankcount:1; // number of motion object banks linked:true; // are the entries linked? split:true; // are the entries split? reverse:false; // render in reverse order? swapxy:false; // render in swapped X/Y order? nextneighbor:false; // does the neighbor bit affect the next object? slipheight:8; // pixels per SLIP entry (0 for no-slip) slipoffset:1; // pixel offset for SLIPs maxperline:0; // maximum number of links to visit/scanline (0=all) palettebase:$100; // base palette entry maxcolors:$100; // maximum number of colors transpen:0; // transparent pen index link_entry:(0,0,0,$03ff); // mask for the link code_entry:(data_lower:($7fff,0,0,0);data_upper:(0,0,0,0)); // mask for the code index color_entry:(data_lower:(0,$000f,0,0);data_upper:(0,0,0,0)); // mask for the color xpos_entry:(0,$ff80,0,0); // mask for the X position ypos_entry:(0,0,$ff80,0); // mask for the Y position width_entry:(0,0,$0038,0); // mask for the width, in tiles height_entry:(0,0,$0007,0); // mask for the height, in tiles hflip_entry:(0,0,$0040,0); // mask for the horizontal flip vflip_entry:(0,0,0,0); // mask for the vertical flip priority_entry:(0,0,0,0); // mask for the priority neighbor_entry:(0,0,0,0); // mask for the neighbor absolute_entry:(0,0,0,0);// mask for absolute coordinates special_entry:(0,0,0,0); // mask for the special value specialvalue:0; // resulting value to indicate "special" ); CPU_SYNC=2; var rom:array[0..$3ffff] of word; slapstic_rom:array[0..3,0..$fff] of word; ram:array[0..$1fff] of word; ram2:array[0..$5fff] of word; eeprom_ram:array[0..$7ff] of byte; write_eeprom,sound_to_main_ready,main_to_sound_ready:boolean; rom_bank,vblank,sound_to_main_data,main_to_sound_data:byte; scroll_x,sound_reset_val:word; procedure update_video_gauntlet; var f,color,x,y,nchar,atrib,scroll_y:word; tile_bank:byte; begin for f:=0 to $7ff do begin x:=f mod 64; y:=f div 64; atrib:=ram2[($5000+(f*2)) shr 1]; color:=((atrib shr 10) and $0f) or ((atrib shr 9) and $20); if (gfx[0].buffer[f] or buffer_color[color]) then begin nchar:=atrib and $3ff; if (atrib and $8000)<>0 then begin put_gfx(x*8,y*8,nchar,color shl 2,2,0); put_gfx_block_trans(x*8,y*8,1,8,8); end else begin put_gfx_trans(x*8,y*8,nchar,color shl 2,1,0); put_gfx_block_trans(x*8,y*8,2,8,8); end; gfx[0].buffer[f]:=false; end; end; atrib:=ram2[$5f6f shr 1]; scroll_y:=(atrib shr 7) and $1ff; tile_bank:=atrib and $3; for f:=0 to $fff do begin x:=f div 64; y:=f mod 64; atrib:=ram2[f]; color:=(atrib shr 12) and 7; if (gfx[1].buffer[f] or buffer_color[$40+color]) then begin nchar:=((tile_bank*$1000)+(atrib and $fff)) xor $800; if (atrib and $8000)<>0 then begin put_gfx_trans(x*8,y*8,nchar,((color+$18) shl 4)+$100,4,1); put_gfx_block(x*8,y*8,3,8,8,0); end else begin put_gfx(x*8,y*8,nchar,((color+$18) shl 4)+$100,3,1); put_gfx_block_trans(x*8,y*8,4,8,8); end; gfx[1].buffer[f]:=false; end; end; scroll_x_y(3,5,scroll_x,scroll_y); actualiza_trozo(0,0,512,256,1,0,0,512,256,5); atari_mo_0.draw(scroll_x,scroll_y,-1); scroll_x_y(4,5,scroll_x,scroll_y); actualiza_trozo(0,0,512,256,2,0,0,512,256,5); actualiza_trozo_final(0,0,336,240,5); fillchar(buffer_color[0],MAX_COLOR_BUFFER,0); end; procedure eventos_gauntlet; begin if event.arcade then begin //P1 if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $fffe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $fffd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $ffef) else marcade.in0:=(marcade.in0 or $10); if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $ffdf) else marcade.in0:=(marcade.in0 or $20); if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $ffbf) else marcade.in0:=(marcade.in0 or $40); if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $ff7f) else marcade.in0:=(marcade.in0 or $80); //P2 if arcade_input.but1[1] then marcade.in1:=(marcade.in1 and $fffe) else marcade.in1:=(marcade.in1 or $1); if arcade_input.but0[1] then marcade.in1:=(marcade.in1 and $fffd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.right[1] then marcade.in1:=(marcade.in1 and $ffef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.left[1] then marcade.in1:=(marcade.in1 and $ffdf) else marcade.in1:=(marcade.in1 or $20); if arcade_input.down[1] then marcade.in1:=(marcade.in1 and $ffbf) else marcade.in1:=(marcade.in1 or $40); if arcade_input.up[1] then marcade.in1:=(marcade.in1 and $ff7f) else marcade.in1:=(marcade.in1 or $80); //Audio CPU if arcade_input.coin[1] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or $4); if arcade_input.coin[0] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8); end; end; procedure gauntlet_principal; var frame_m,frame_s:single; f:word; h:byte; begin init_controls(false,false,false,true); frame_m:=m68000_0.tframes; frame_s:=m6502_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to 261 do begin for h:=1 to CPU_SYNC do begin //main m68000_0.run(frame_m); frame_m:=frame_m+m68000_0.tframes-m68000_0.contador; //sound m6502_0.run(frame_s); frame_s:=frame_s+m6502_0.tframes-m6502_0.contador; end; case f of 0,64,128,192,256:m6502_0.change_irq(CLEAR_LINE); 32,96,160,224:m6502_0.change_irq(ASSERT_LINE); 239:begin //VBLANK update_video_gauntlet; vblank:=$0; m68000_0.irq[4]:=ASSERT_LINE; end; 261:vblank:=$40; end; end; eventos_gauntlet; video_sync; end; end; function gauntlet_getword(direccion:dword):word; begin case direccion of 0..$37fff,$40000..$7ffff:gauntlet_getword:=rom[direccion shr 1]; //Funciona asi... Creo... //De 38K a 3fK esta la proteccion //Cuando lee en este espacio, solo lee 2k del slapstic y recalcula el banco $38000..$3ffff:begin //Slaptic!! gauntlet_getword:=slapstic_rom[rom_bank,(direccion and $1fff) shr 1]; rom_bank:=slapstic_0.slapstic_tweak((direccion and $7fff) shr 1); end; $800000..$801fff:gauntlet_getword:=ram[(direccion and $1fff) shr 1]; $802000..$802fff:gauntlet_getword:=$ff00 or eeprom_ram[(direccion and $fff) shr 1]; $803000:gauntlet_getword:=marcade.in0; $803002:gauntlet_getword:=marcade.in1; $803004:gauntlet_getword:=$ffff; $803006:gauntlet_getword:=$ffff; $803008:gauntlet_getword:=$ff87 or marcade.dswa or vblank or (byte(sound_to_main_ready) shl 4) or (byte(main_to_sound_ready) shl 5); $80300e:begin //main_response_r sound_to_main_ready:=false; m68000_0.irq[6]:=CLEAR_LINE; gauntlet_getword:=$ff00 or sound_to_main_data; end; $900000..$905fff:gauntlet_getword:=ram2[(direccion and $7fff) shr 1]; $910000..$9107ff:gauntlet_getword:=buffer_paleta[(direccion and $7ff) shr 1]; end; end; procedure gauntlet_putword(direccion:dword;valor:word); procedure cambiar_color(tmp_color,numero:word); var color:tcolor; begin color.r:=pal4bit_i(tmp_color shr 8,tmp_color shr 12); color.g:=pal4bit_i(tmp_color shr 4,tmp_color shr 12); color.b:=pal4bit_i(tmp_color,tmp_color shr 12); set_pal_color(color,numero); case numero of $0..$ff:buffer_color[(numero shr 2) and $3f]:=true; $100..$3ff:buffer_color[$40+(numero shr 4) and $7]:=true; end; end; var old:word; begin case direccion of 0..$37fff,$40000..$7ffff:; //ROM $38000..$3ffff:rom_bank:=slapstic_0.slapstic_tweak((direccion and $7fff) shr 1); //Slaptic!! $800000..$801fff:ram[(direccion and $1fff) shr 1]:=valor; $802000..$802fff:if write_eeprom then begin //eeprom eeprom_ram[(direccion and $fff) shr 1]:=valor and $ff; write_eeprom:=false; end; $803100:; //watch dog $803120..$80312e:begin //sound_reset_w old:=sound_reset_val; sound_reset_val:=valor; if ((old xor sound_reset_val) and 1)<>0 then begin if (sound_reset_val and 1)<>0 then m6502_0.change_reset(CLEAR_LINE) else m6502_0.change_reset(ASSERT_LINE); sound_to_main_ready:=false; m68000_0.irq[6]:=CLEAR_LINE; if (sound_reset_val and 1)<>0 then begin ym2151_0.reset; //m_tms5220->reset(); //m_tms5220->set_frequency(ATARI_CLOCK_14MHz/2 / 11); //m_ym2151->set_output_gain(ALL_OUTPUTS, 0.0f); //m_pokey->set_output_gain(ALL_OUTPUTS, 0.0f); //m_tms5220->set_output_gain(ALL_OUTPUTS, 0.0f); end; end; end; $803140:m68000_0.irq[4]:=CLEAR_LINE; //video_int_ack_w $803150:write_eeprom:=true; //eeprom_unlock $803170:begin //main_command_w main_to_sound_data:=valor; main_to_sound_ready:=true; m6502_0.change_nmi(ASSERT_LINE); end; $900000..$901fff,$b00000..$b01fff:begin ram2[(direccion and $7fff) shr 1]:=valor; gfx[1].buffer[(direccion and $1fff) shr 1]:=true; end; $902000..$904fff,$b02000..$b04fff:ram2[(direccion and $7fff) shr 1]:=valor; $905000..$905fff,$b05000..$b05fff:begin ram2[(direccion and $7fff) shr 1]:=valor; gfx[0].buffer[(direccion and $fff) shr 1]:=true; end; $910000..$9107ff:if buffer_paleta[(direccion and $7ff) shr 1]<>valor then begin buffer_paleta[(direccion and $7ff) shr 1]:=valor; cambiar_color(valor,(direccion and $7ff) shr 1); end; $930000,$b30000:scroll_x:=valor; end; end; function gauntlet_snd_getbyte(direccion:word):byte; var temp:byte; begin case direccion of 0..$fff,$4000..$ffff:gauntlet_snd_getbyte:=mem_snd[direccion]; $1010..$101f:begin //sound_command_r main_to_sound_ready:=false; m6502_0.change_nmi(CLEAR_LINE); gauntlet_snd_getbyte:=main_to_sound_data; end; $1020..$102f:gauntlet_snd_getbyte:=marcade.in2;//COIN $1030..$103f:begin //switch_6502_r temp:=$30; if main_to_sound_ready then temp:=temp xor $80; if sound_to_main_ready then temp:=temp xor $40; //if (!m_tms5220->readyq_r()) temp:=temp xor $20; if marcade.dswa=8 then temp:=temp xor $10; gauntlet_snd_getbyte:=temp; end; $1800..$180f:gauntlet_snd_getbyte:=pokey_0.read(direccion and $f); $1811:gauntlet_snd_getbyte:=ym2151_0.status; $1830..$183f:begin //sound_irq_ack_r m6502_0.change_irq(CLEAR_LINE); gauntlet_snd_getbyte:=0; end; end; end; procedure gauntlet_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$fff:mem_snd[direccion]:=valor; $1000..$100f:begin //sound_response_w sound_to_main_data:=valor; sound_to_main_ready:=true; m68000_0.irq[6]:=ASSERT_LINE; end; $1020..$102f:; //mixer_w $1030..$103f:case (direccion and 7) of //sound_ctl_w 0:if ((valor and $80)=0) then ym2151_0.reset; // music reset, bit D7, low reset 1:;//m_tms5220->wsq_w(data >> 7); // speech write, bit D7, active low */ 2:; //m_tms5220->rsq_w(data >> 7); // speech reset, bit D7, active low */ 3:; { begin //* speech squeak, bit D7 */ data = 5 | ((data >> 6) & 2); m_tms5220->set_frequency(ATARI_CLOCK_14MHz/2 / (16 - data)); end;} end; $1800..$180f:pokey_0.write(direccion and $f,valor); $1810:ym2151_0.reg(valor); $1811:ym2151_0.write(valor); $1820..$182f:; //tms5220_device, data_w $1830..$183f:m6502_0.change_irq(CLEAR_LINE); //sound_irq_ack_w $4000..$ffff:; //ROM end; end; procedure gauntlet_sound_update; begin ym2151_0.update; pokey_0.update; //tms5220_update end; //Main procedure reset_gauntlet; begin m68000_0.reset; m6502_0.reset; YM2151_0.reset; pokey_0.reset; slapstic_0.reset; reset_audio; marcade.in0:=$ffff; marcade.in1:=$ffff; marcade.in2:=$ff; scroll_x:=0; rom_bank:=slapstic_0.current_bank; main_to_sound_ready:=false; sound_to_main_ready:=false; sound_to_main_data:=0; main_to_sound_data:=0; sound_reset_val:=1; vblank:=$40; write_eeprom:=false; end; procedure cerrar_gauntlet; var nombre:string; begin case main_vars.tipo_maquina of 236:nombre:='gauntlet.nv'; 245:nombre:='gaunt2.nv'; end; write_file(Directory.Arcade_nvram+nombre,@eeprom_ram,$800); end; function iniciar_gauntlet:boolean; var memoria_temp:array[0..$7ffff] of byte; f:dword; temp:pword; longitud:integer; const pc_x:array[0..7] of dword=(0, 1, 2, 3, 8, 9, 10, 11); pc_y:array[0..7] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16); ps_x:array[0..7] of dword=(0, 1, 2, 3, 4, 5, 6, 7); ps_y:array[0..7] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8); procedure load_and_change_roms; begin copymemory(@rom[0],@memoria_temp[$8000],$8000); copymemory(@rom[$8000 shr 1],@memoria_temp[$0],$8000); copymemory(@rom[$40000 shr 1],@memoria_temp[$48000],$8000); copymemory(@rom[$48000 shr 1],@memoria_temp[$40000],$8000); copymemory(@rom[$50000 shr 1],@memoria_temp[$58000],$8000); copymemory(@rom[$58000 shr 1],@memoria_temp[$50000],$8000); copymemory(@rom[$60000 shr 1],@memoria_temp[$68000],$8000); copymemory(@rom[$68000 shr 1],@memoria_temp[$60000],$8000); copymemory(@rom[$70000 shr 1],@memoria_temp[$78000],$8000); copymemory(@rom[$78000 shr 1],@memoria_temp[$70000],$8000); copymemory(@slapstic_rom[0,0],@memoria_temp[$38000],$2000); copymemory(@slapstic_rom[1,0],@memoria_temp[$3a000],$2000); copymemory(@slapstic_rom[2,0],@memoria_temp[$3c000],$2000); copymemory(@slapstic_rom[3,0],@memoria_temp[$3e000],$2000); end; begin llamadas_maquina.bucle_general:=gauntlet_principal; llamadas_maquina.reset:=reset_gauntlet; llamadas_maquina.close:=cerrar_gauntlet; llamadas_maquina.fps_max:=59.922743; iniciar_gauntlet:=false; iniciar_audio(true); //Chars screen_init(1,512,256,true); screen_init(2,512,256,true); //Back screen_init(3,512,512,true); screen_mod_scroll(3,512,512,511,512,256,511); screen_init(4,512,512,true); screen_mod_scroll(4,512,512,511,512,256,511); //Final screen_init(5,512,512,false,true); iniciar_video(336,240); //Main CPU m68000_0:=cpu_m68000.create(14318180 div 2,262*CPU_SYNC,TCPU_68010); m68000_0.change_ram16_calls(gauntlet_getword,gauntlet_putword); //Sound CPU m6502_0:=cpu_m6502.create(14318180 div 8,262*CPU_SYNC,TCPU_M6502); m6502_0.change_ram_calls(gauntlet_snd_getbyte,gauntlet_snd_putbyte); m6502_0.init_sound(gauntlet_sound_update); //Sound Chips ym2151_0:=ym2151_chip.create(14318180 div 4); pokey_0:=pokey_chip.create(14318180 div 8); //TMS5220 case main_vars.tipo_maquina of 236:begin //Gauntlet //Slapstic slapstic_0:=slapstic_type.create(107,true); //cargar roms if not(roms_load16w(@memoria_temp,gauntlet_rom)) then exit; load_and_change_roms; //cargar sonido if not(roms_load(@mem_snd,gauntlet_sound)) then exit; //convertir chars if not(roms_load(@memoria_temp,gauntlet_char)) then exit; init_gfx(0,8,8,$400); gfx[0].trans[0]:=true; gfx_set_desc_data(2,0,16*8,0,4); convert_gfx(0,0,@memoria_temp,@pc_x,@pc_y,false,false); //convertir fondo if not(roms_load(@memoria_temp,gauntlet_back)) then exit; for f:=0 to $3ffff do memoria_temp[f]:=not(memoria_temp[f]); init_gfx(1,8,8,$2000); gfx[1].trans[0]:=true; gfx_set_desc_data(4,0,8*8,$2000*8*8*3,$2000*8*8*2,$2000*8*8*1,$2000*8*8*0); convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,false); //eeprom if read_file_size(Directory.Arcade_nvram+'gauntlet.nv',longitud) then read_file(Directory.Arcade_nvram+'gauntlet.nv',@eeprom_ram,longitud) else fillchar(eeprom_ram[0],$800,$ff); //DIP marcade.dswa:=$8; marcade.dswa_val:=@gauntlet_dip; end; 245:begin //Gauntlet II //Slapstic slapstic_0:=slapstic_type.create(106,true); //cargar roms if not(roms_load16w(@memoria_temp,gauntlet2_rom)) then exit; load_and_change_roms; //cargar sonido if not(roms_load(@mem_snd,gauntlet2_sound)) then exit; //convertir chars if not(roms_load(@memoria_temp,gauntlet2_char)) then exit; init_gfx(0,8,8,$400); gfx[0].trans[0]:=true; gfx_set_desc_data(2,0,16*8,0,4); convert_gfx(0,0,@memoria_temp,@pc_x,@pc_y,false,false); //convertir fondo if not(roms_load(@memoria_temp,gauntlet2_back)) then exit; for f:=0 to $7ffff do memoria_temp[f]:=not(memoria_temp[f]); init_gfx(1,8,8,$3000); gfx[1].trans[0]:=true; gfx_set_desc_data(4,0,8*8,$3000*8*8*3,$3000*8*8*2,$3000*8*8*1,$3000*8*8*0); convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,false); //eeprom if read_file_size(Directory.Arcade_nvram+'gaunt2.nv',longitud) then read_file(Directory.Arcade_nvram+'gaunt2.nv',@eeprom_ram,longitud) else fillchar(eeprom_ram[0],$800,$ff); //DIP marcade.dswa:=$8; marcade.dswa_val:=@gauntlet_dip; end; end; //atari mo atari_mo_0:=tatari_mo.create(@ram2[$5f80 shr 1],@ram2[$2000 shr 1],gauntlet_mo_config,5,336+8,240+8); // modify the motion object code lookup table to account for the code XOR temp:=atari_mo_0.get_codelookup; for f:=0 to $7fff do begin temp^:=temp^ xor $800; inc(temp); end; //final reset_gauntlet; iniciar_gauntlet:=true; end; end.
unit NLDXMLData; interface uses Windows, Messages, SysUtils, Classes, NLDXMLIntf, ExtCtrls, XMLDoc, xmldom, Contnrs; type TNLDXMLData = class; TPosts = class; TSortType = (stDateTime, stForum, stMember, stThread); TPostItem = class private FThreadName: string; FForumName: string; FMemberName: string; FDateTime: Int64; FPost: IXMLPostType; FPostList: TPosts; public property DateTime: Int64 read FDateTime write FDateTime; property MemberName: string read FMemberName write FMemberName; property ForumName: string read FForumName write FForumName; property ThreadName: string read FThreadName write FThreadName; property Post: IXMLPostType read FPost write FPost; property PostList: TPosts read FPostList write FPostList; constructor Create(PostList: TPosts; Post: IXMLPostType); end; TPosts = class(TObjectList) private FTracker: TNLDXMLData; FSortDirection: Integer; FSortType: TSortType; function GetItem(Index: Integer): TPostItem; procedure SetItem(Index: Integer; const Value: TPostItem); public procedure Sort; property Items[Index: Integer]: TPostItem read GetItem write SetItem; default; property Tracker: TNLDXMLData read FTracker; property SortType: TSortType read FSortType write FSortType; property SortDirection: Integer read FSortDirection write FSortDirection; constructor Create; end; TOnNewData = procedure(Sender: TObject; NewData: IXMLNLDelphiDataType) of object; TOnError = procedure(Sender: TObject; const Error: string) of object; TTrackXMLDocument = class(TXMLDocument) public constructor Create(AOwner: TComponent); override; end; TNLDXMLData = class(TComponent) private FOnNewData: TOnNewData; FBeforeUpdate: TNotifyEvent; FAfterUpdate: TNotifyEvent; FURL: string; FTimer: TTimer; FOnError: TOnError; FData: IXMLNLDelphiDataType; FOnDataChange: TNotifyEvent; FIgnoreUser: string; FUpdateTimer: Integer; FPosts: TPosts; FChangeCount: Integer; FUserAgent: string; FTimeDiff: Int64; FSessionID: string; procedure ThreadAfterGet(Sender: TObject); procedure Timer(Sender: TObject); procedure MergeData(NewData: IXMLNLDelphiDataType); function FindForum(ForumID: Integer): IXMLForumType; function FindThread(Forum: IXMLForumType; ThreadID: Integer): IXMLThreadType; procedure SetUpdateTimer(const Value: Integer); function GetConnected: Boolean; procedure LoadForumInfo; protected procedure DoDataChange; virtual; procedure SyncPosts; procedure GetTimeDiff; public function FindPost(Thread: IXMLThreadType; PostID: Integer): IXMLPostType; overload; function FindPost(PostID: Integer): IXMLPostType; overload; procedure Update(DateTime: Integer = 0); procedure LoadFromFile(const FileName: string); procedure DeletePost(Index: Integer); overload; procedure DeletePost(Post: IXMLPostType); overload; procedure DeleteThread(Thread: IXMLThreadType); overload; procedure DeleteThread(Post: IXMLPostType); overload; procedure SaveToFile(const FileName: string); procedure BeginUpdate; procedure EndUpdate; function Login(const UserName, Password, Location: string; var Error: string): Boolean; constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Data: IXMLNLDelphiDataType read FData; property Posts: TPosts read FPosts; property Connected: Boolean read GetConnected; procedure Disconnect; published property OnNewData: TOnNewData read FOnNewData write FOnNewData; property OnError: TOnError read FOnError write FOnError; property UpdateTimer: Integer read FUpdateTimer write SetUpdateTimer; property URL: string read FURL write FURL; property IgnoreUser: string read FIgnoreUser write FIgnoreUser; property OnDataChange: TNotifyEvent read FOnDataChange write FOnDataChange; property BeforeUpdate: TNotifyEvent read FBeforeUpdate write FBeforeUpdate; property AfterUpdate: TNotifyEvent read FAfterUpdate write FAfterUpdate; property UserAgent: string read FUserAgent write FUserAgent; end; procedure Register; implementation uses GetDataU, DateUtils, {$IFDEF LOg} Udbg, {$ENDIF} XMLIntf, IdHTTP; procedure Register; begin RegisterComponents('NLDelphi', [TNLDXMLData]); end; { TNLDXMLData } constructor TNLDXMLData.Create(AOwner: TComponent); begin inherited; FSessionID := ''; FTimer := TTimer.Create(self); FTimer.Enabled := False; FTimer.OnTimer := Timer; FData := NewNLDelphiData; FPosts := TPosts.Create; FTimeDiff := -1; end; destructor TNLDXMLData.Destroy; begin FTimer.Free; FPosts.Free; inherited; end; procedure TNLDXMLData.DoDataChange; begin {$IFDEF Log} Debugger.EnterProc('TNLDXMLData.DoDataChange'); {$ENDIF} if FChangeCount = 0 then begin SyncPosts; Posts.Sort; if Assigned(FOnDataChange) then FOnDataChange(Self); end; {$IFDEF Log} Debugger.LeaveProc('TNLDXMLData.DoDataChange'); {$ENDIF} end; procedure TNLDXMLData.LoadFromFile(const FileName: string); begin {$IFDEF Log} Debugger.EnterProc('TNLDXMLData.LoadFromFile'); Debugger.LogMsg(FileName); {$ENDIF} if FileExists(FileName) then begin FData := LoadNLDelphiData(FileName); SyncPosts; DoDataChange; end; {$IFDEF Log} Debugger.LeaveProc('TNLDXMLData.LoadFromFile'); {$ENDIF} end; procedure TNLDXMLData.SaveToFile(const FileName: string); var SaveDocument: TTrackXMLDocument; begin {$IFDEF Log} Debugger.EnterProc('TNLDXMLData.SaveToFile'); Debugger.LogMsg(FileName); {$ENDIF} SaveDocument := TTrackXMLDocument.Create(self); try SaveDocument.LoadFromXML(FData.XML); if not SaveDocument.IsEmptyDoc then begin DeleteFile(FileName); SaveDocument.SaveToFile(FileName); end; finally SaveDocument.Free; end; {$IFDEF Log} Debugger.LeaveProc('TNLDXMLData.SaveToFile'); {$ENDIF} end; procedure TNLDXMLData.MergeData(NewData: IXMLNLDelphiDataType); function AddPost(Thread: IXMLThreadType; Post: IXMLPostType): IXMLPostType; begin Result := Thread.Post.Add; Result.DateTime := Post.DateTime + FTimeDiff; Result.ID := Post.ID; Result.IconID := Post.IconID; Result.Member.ID := Post.Member.ID; Result.Member.Name := Post.Member.Name; end; function AddThread(Forum: IXMLForumType; Thread: IXMLThreadType): IXMLThreadType; var i: Integer; begin Result := Forum.Thread.Add; Result.Title := Thread.Title; Result.ID := Thread.ID; Result.IconID := Thread.IconID; Result.Member.ID := Thread.Member.ID; Result.Member.Name := Thread.Member.Name; for i := 0 to Thread.Post.Count - 1 do AddPost(Result, Thread.Post[i]); end; function AddForum(Forum: IXMLForumType): IXMLForumType; var i: Integer; begin Result := FData.Forum.Add; Result.Title := Forum.Title; Result.ID := Forum.ID; for i := 0 to Forum.Thread.Count - 1 do AddThread(Result, Forum.Thread[i]); end; var i, ForumIndex, ThreadIndex, PostIndex: Integer; Forum, NewForum: IXMLForumType; Thread, NewThread: IXMLThreadType; begin {$IFDEF Log} Debugger.EnterProc('TNLDXMLData.MergeData'); {$ENDIF} for ForumIndex := 0 to NewData.Forum.Count - 1 do begin NewForum := NewData.Forum[ForumIndex]; Forum := FindForum(NewForum.ID); if Forum = nil then AddForum(NewForum) else for ThreadIndex := 0 to NewForum.Thread.Count - 1 do begin NewThread := NewForum.Thread[ThreadIndex]; Thread := FindThread(Forum, NewThread.ID); if Thread = nil then AddThread(Forum, NewThread) else for PostIndex := 0 to NewThread.Post.Count - 1 do if FindPost(Thread, NewThread.Post[PostIndex].ID) = nil then AddPost(Thread, NewThread.Post[PostIndex]); end; end; for i := 0 to NewData.PM.Count - 1 do begin with FData.PM.Add do begin ID := NewData.PM[i].ID; Title := NewData.PM[i].Title; Member.ID := NewData.PM[i].Member.ID; Member.Name := NewData.PM[i].Member.Name; DateTime := NewData.PM[i].DateTime; end; end; for i := 0 to NewData.Link.Count - 1 do begin with FData.Link.Add do begin ID := NewData.Link[i].ID; Title := NewData.Link[i].Title; DateTime := NewData.Link[i].DateTime; Forum.ID := NewData.Link[i].Forum.ID; Forum.Title := NewData.Link[i].Forum.Title; Member.ID := NewData.Link[i].Member.ID; Member.Name := NewData.Link[i].Member.Name; end; end; for i := 0 to NewData.News.Count - 1 do begin with FData.News.Add do begin ID := NewData.News[i].ID; Title := NewData.News[i].Title; DateTime := NewData.News[i].DateTime; end; end; SyncPosts; {$IFDEF Log} Debugger.LeaveProc('TNLDXMLData.MergeData'); {$ENDIF} end; function TNLDXMLData.FindForum(ForumID: Integer): IXMLForumType; var ForumIndex: Integer; begin Result := nil; for ForumIndex := 0 to FData.Forum.Count - 1 do if FData.Forum[ForumIndex].ID = ForumID then begin Result := FData.Forum[ForumIndex]; Break; end; end; function TNLDXMLData.FindThread(Forum: IXMLForumType; ThreadID: Integer): IXMLThreadType; var ThreadIndex: Integer; begin Result := nil; for ThreadIndex := 0 to Forum.Thread.Count - 1 do if Forum.Thread[ThreadIndex].ID = ThreadID then begin Result := Forum.Thread[ThreadIndex]; Break; end; end; function TNLDXMLData.FindPost(Thread: IXMLThreadType; PostID: Integer): IXMLPostType; var PostIndex: Integer; begin Result := nil; for PostIndex := 0 to Thread.Post.Count - 1 do if Thread.Post[PostIndex].ID = PostID then begin Result := Thread.Post[PostIndex]; Break; end; end; procedure TNLDXMLData.ThreadAfterGet(Sender: TObject); var NewData: IXMLNLDelphiDataType; UpdateDocument: TTrackXMLDocument; begin {$IFDEF Log} Debugger.EnterProc('TNLDXMLData.ThreadAfterGet'); Debugger.LogString('XML data: ', TGetData(Sender).XMLText); {$ENDIF} if Assigned(FAfterUpdate) then begin {$IFDEF name} Debugger.LogMsg('Start AfterUpdate'); {$ENDIF} FAfterUpdate(Self); {$IFDEF Log} Debugger.LogMsg('Einde AfterUpdate'); {$ENDIF} end; {$IFDEF Log} Debugger.LogMsg('Controleren op error'); {$ENDIF} if TGetData(Sender).Error <> '' then begin {$IFDEF Log} Debugger.LogError(TGetData(Sender).Error); {$ENDIF} if Assigned(FOnError) then FOnError(Self, TGetData(Sender).Error); end; {$IFDEF Log} Debugger.LogMsg('XMLDocument maken'); {$ENDIF} UpdateDocument := TTrackXMLDocument.Create(self); try UpdateDocument.XML.Text := TGetData(Sender).XMLText; NewData := GetNLDelphiData(UpdateDocument); if NewData.Error.Text <> '' then begin {$IFDEF Log} Debugger.LogError(NewData.Error.Text); {$ENDIF} if Assigned(FOnError) then FOnError(Self, NewData.Error.Text); end; if NewData.Forum.Count > 0 then begin {$IFDEF Log} Debugger.LogMsg(Format('%d regels opgehaald', [NewData.RowCount])); {$ENDIF} if Assigned(FOnNewData) then begin {$IFDEF Log} Debugger.LogMsg('Start OnNewData'); {$ENDIF} FOnNewData(Self, NewData); {$IFDEF Log} Debugger.LogMsg('Einde OnNewData'); {$ENDIF} end; MergeData(NewData); DoDataChange; end; finally UpdateDocument.Free; end; {$IFDEF Log} Debugger.LeaveProc('TNLDXMLData.ThreadAfterGet'); {$ENDIF} end; procedure TNLDXMLData.Timer(Sender: TObject); begin Update; end; procedure TNLDXMLData.Update(DateTime: Integer = 0); var FullURL: string; begin if FSessionID = '' then Exit; {$IFDEF Log} Debugger.EnterProc('TNLDXMLData.Update'); Debugger.LogMsg('Datetime: ' + DateTimeToStr(UnixToDateTime(DateTime))); {$ENDIF} FullURL := FURL + '?SessionID=' + FSessionID; if DateTime <> 0 then FullURL := FullURL + '&LastDateTime=' + IntToStr(DateTime); if FTimeDiff = -1 then GetTimeDiff; if Assigned(FBeforeUpdate) then FBeforeUpdate(Self); with TGetData.Create do begin UserAgent := FUserAgent; AfterGet := ThreadAfterGet; URL := FullURL; Resume; end; {$IFDEF Log} Debugger.LeaveProc('TNLDXMLData.Update'); {$ENDIF} end; function TNLDXMLData.FindPost(PostID: Integer): IXMLPostType; var ForumIndex, ThreadIndex, PostIndex: Integer; Forum: IXMLForumType; Thread: IXMLThreadType; begin Result := nil; for ForumIndex := 0 to FData.Forum.Count - 1 do begin Forum := FData.Forum[ForumIndex]; for ThreadIndex := 0 to Forum.Thread.Count - 1 do begin Thread := Forum.Thread[ThreadIndex]; for PostIndex := 0 to Thread.Post.Count - 1 do if Thread.Post[PostIndex].ID = PostID then begin Result := Thread.Post[PostIndex]; Break; end; end; end; end; procedure TNLDXMLData.DeletePost(Index: Integer); var Post: IXMLPostType; begin {$IFDEF Log} Debugger.EnterProc('TNLDXMLData.DeletePost'); {$ENDIF} Post := Posts[Index].Post; DeletePost(Post); {$IFDEF Log} Debugger.LeaveProc('TNLDXMLData.DeletePost'); {$ENDIF} end; procedure TNLDXMLData.DeletePost(Post: IXMLPostType); var Thread: IXMLThreadType; begin Thread := (Post.ParentNode as IXMLThreadType); Thread.Post.Remove(Post); if Thread.Post.Count = 0 then DeleteThread(Thread); DoDataChange; end; procedure TNLDXMLData.DeleteThread(Thread: IXMLThreadType); var Forum: IXMLForumType; begin Forum := Thread.ParentNode as IXMLForumType; Forum.Thread.Remove(Thread); DoDataChange; end; procedure TNLDXMLData.DeleteThread(Post: IXMLPostType); begin DeleteThread(Post.ParentNode as IXMLThreadType); end; procedure TNLDXMLData.SetUpdateTimer(const Value: Integer); begin FUpdateTimer := Value; if not (csDesigning in ComponentState) then begin FTimer.Interval := FUpdateTimer; FTimer.Enabled := FUpdateTimer > 0; end; end; procedure TNLDXMLData.SyncPosts; var ForumIndex, ThreadIndex, PostIndex: Integer; Forum: IXMLForumType; Thread: IXMLThreadType; begin FPosts.Clear; for ForumIndex := 0 to FData.Forum.Count - 1 do begin Forum := FData.Forum[ForumIndex]; for ThreadIndex := 0 to Forum.Thread.Count - 1 do begin Thread := Forum.Thread[ThreadIndex]; for PostIndex := 0 to Thread.Post.Count - 1 do FPosts.Add(TPostItem.Create(Posts, Thread.Post[PostIndex])); end; end; end; procedure TNLDXMLData.BeginUpdate; begin Inc(FChangeCount); end; procedure TNLDXMLData.EndUpdate; begin if FChangeCount > 0 then begin Dec(FChangeCount); if FChangeCount = 0 then DoDataChange; end; end; procedure TNLDXMLData.GetTimeDiff; var ServerTime: string; begin try with TIdHTTP.Create(Self) do try ServerTime := get(FURL + '/servertime'); FTimeDiff := DateTimeToUnix(Now) - StrToInt(ServerTime); finally Free; end; except; end; end; function TNLDXMLData.Login(const UserName, Password, Location: string; var Error: string): Boolean; var UpdateDocument: TTrackXMLDocument; NewData: IXMLNLDelphiDataType; begin if (UserName = '') or (Password = '') then begin Result := False; Exit; end; UpdateDocument := TTrackXMLDocument.Create(self); try try with TIdHTTP.Create(Self) do try UpdateDocument.XML.Text := Get(FURL + Format('/login?username=%s&password=%s&location=%s', [UserName, Password, Location])); NewData := GetNLDelphiData(UpdateDocument); Result := NewData.Error.Text = ''; Error := NewData.Error.Text; if Result then FSessionID := NewData.SessionID; finally Free; end; except; Result := False; raise; end; finally UpdateDocument.Free; end; if Result then LoadForumInfo; end; procedure TNLDXMLData.LoadForumInfo; var UpdateDocument: TTrackXMLDocument; ForumInfo: IXMLForumInfoTypeList; i: Integer; begin Data.ForumInfo.Clear; UpdateDocument := TTrackXMLDocument.Create(self); try with TIdHTTP.Create(Self) do try UpdateDocument.XML.Text := Get(FURL + '/ForumInfo' + '?SessionID=' + FSessionID); finally Free; end; ForumInfo := GetNLDelphiData(UpdateDocument).ForumInfo; for i := 0 to ForumInfo.Count - 1 do with Data.ForumInfo.Add do begin ID := ForumInfo[i].ID; Name := ForumInfo[i].Name; ParentID := ForumInfo[i].ParentID; end; finally UpdateDocument.Free; end; end; function TNLDXMLData.GetConnected: Boolean; begin Result := FSessionID <> ''; end; procedure TNLDXMLData.Disconnect; begin FSessionID := ''; end; { TTrackXMLDocument } constructor TTrackXMLDocument.Create(AOwner: TComponent); begin inherited Create(AOwner); DOMVendor := DOMVendors.Find('MSXML'); end; constructor TPosts.Create; begin inherited; FSortDirection := 1; end; function TPosts.GetItem(Index: Integer): TPostItem; begin Result := TPostItem(inherited Items[Index]); end; procedure TPosts.SetItem(Index: Integer; const Value: TPostItem); begin inherited Items[Index] := Value; end; function Compare(Item1, Item2: Pointer): Integer; var Post1, Post2: TPostItem; begin Result := 0; Post1 := TPostItem(Item1); Post2 := TPostItem(Item2); if Post1.PostList.SortType = stDateTime then begin if Post1.DateTime = Post2.DateTime then Result := 0 else if Post1.DateTime > Post2.DateTime then Result := 1 else Result := -1; end else if Post1.PostList.SortType = stForum then begin if Post1.ForumName = Post2.ForumName then Result := 0 else if Post1.ForumName > Post2.ForumName then Result := 1 else Result := -1; end else if Post1.PostList.SortType = stMember then begin if Post1.MemberName = Post2.MemberName then Result := 0 else if Post1.MemberName > Post2.MemberName then Result := 1 else Result := -1; end else if Post1.PostList.SortType = stThread then begin if Post1.ThreadName = Post2.ThreadName then begin if Post1.DateTime = Post2.DateTime then Result := 0 else if Post1.DateTime > Post2.DateTime then Result := 1 else Result := -1; end else if Post1.ThreadName > Post2.ThreadName then Result := 1 else Result := -1; end; Result := Result * Post1.PostList.SortDirection; end; procedure TPosts.Sort; begin inherited Sort(Compare); end; { TPostItem } constructor TPostItem.Create(PostList: TPosts; Post: IXMLPostType); begin inherited Create; FPost := Post; FPostList := PostList; FThreadName := (Post.ParentNode as IXMLThreadType).Title; FForumName := (Post.ParentNode.ParentNode as IXMLForumType).Title; FMemberName := Post.Member.Name; FDateTime := FPost.DateTime; end; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Actions, System.Notification, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.ActnList, FMX.StdActns, FMX.MediaLibrary.Actions, FMX.Objects, FMX.Layouts, FMX.TabControl, DW.PermissionsRequester, DW.PermissionsTypes, DW.MediaLibrary; type TForm1 = class(TForm) TakePhotoButton: TButton; PhotoImage: TImage; BackgroundRectangle: TRectangle; BottomLayout: TLayout; TabControl: TTabControl; TakePhotoTab: TTabItem; NotificationsTab: TTabItem; ImmediateButton: TButton; Schedule10SecondsButton: TButton; CancelScheduled: TButton; NotificationCenter: TNotificationCenter; ExtraTab: TTabItem; ExtraButtonsLayout: TLayout; RequestWriteSettingsButton: TButton; RequestSMSPermissionsButton: TButton; OpenPDFButton: TButton; procedure TakePhotoButtonClick(Sender: TObject); procedure ImmediateButtonClick(Sender: TObject); procedure Schedule10SecondsButtonClick(Sender: TObject); procedure CancelScheduledClick(Sender: TObject); procedure RequestSMSPermissionsButtonClick(Sender: TObject); procedure OpenPDFButtonClick(Sender: TObject); private FRequester: TPermissionsRequester; FMediaLibrary: TMediaLibrary; procedure CopyPDFSample; procedure MediaLibraryReceivedImageHandler(Sender: TObject; const AImagePath: string; const AImage: TBitmap); procedure PermissionsResultHandler(Sender: TObject; const ARequestCode: Integer; const AResults: TPermissionResults); procedure ImmediateNotification; procedure ScheduleNotification; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var Form1: TForm1; implementation {$R *.fmx} uses {$IF Defined(ANDROID)} Androidapi.JNI.GraphicsContentViewText, Androidapi.Helpers, Androidapi.JNI.Net, DW.Android.Helpers, {$ENDIF} System.IOUtils; const cPermissionReadExternalStorage = 'android.permission.READ_EXTERNAL_STORAGE'; cPermissionWriteExternalStorage = 'android.permission.WRITE_EXTERNAL_STORAGE'; cPermissionCamera = 'android.permission.CAMERA'; cPermissionSendSMS = 'android.permission.SEND_SMS'; cPermissionReceiveSMS = 'android.permission.RECEIVE_SMS'; cPermissionReadSMS = 'android.permission.READ_SMS'; cPermissionReceiveMMS = 'android.permission.RECEIVE_MMS'; cPermissionReceiveWAPPush = 'android.permission.RECEIVE_WAP_PUSH'; cPermissionsCodeExternalStorage = 1; cPermissionsCodeSMS = 2; cPDFSampleFileName = 'pdf-sample.pdf'; constructor TForm1.Create(AOwner: TComponent); begin inherited; CopyPDFSample; TabControl.ActiveTab := TakePhotoTab; FRequester := TPermissionsRequester.Create; FRequester.OnPermissionsResult := PermissionsResultHandler; FMediaLibrary := TMediaLibrary.Create; FMediaLibrary.OnReceivedImage := MediaLibraryReceivedImageHandler; end; destructor TForm1.Destroy; begin FRequester.Free; FMediaLibrary.Free; inherited; end; procedure TForm1.CopyPDFSample; var LFileName, LCopyFileName: string; begin LFileName := TPath.Combine(TPath.GetDocumentsPath, cPDFSampleFileName); LCopyFileName := TPath.Combine(TPath.GetPublicPath, cPDFSampleFileName); if TFile.Exists(LFileName) and not TFile.Exists(LCopyFileName) then TFile.Copy(LFileName, LCopyFileName); end; procedure TForm1.PermissionsResultHandler(Sender: TObject; const ARequestCode: Integer; const AResults: TPermissionResults); begin case ARequestCode of cPermissionsCodeExternalStorage: begin if AResults.AreAllGranted then FMediaLibrary.TakePhoto else ShowMessage('You need to grant all required permissions for the app to be able to take photos!'); end; cPermissionsCodeSMS: begin if AResults.AreAllGranted then ShowMessage('SMS permissions granted') else ShowMessage('You need to grant all required permissions for the app to be able to handle SMS!'); end; end; end; procedure TForm1.RequestSMSPermissionsButtonClick(Sender: TObject); begin FRequester.RequestPermissions([cPermissionSendSMS, cPermissionReceiveSMS, cPermissionReadSMS, cPermissionReceiveMMS, cPermissionReceiveWAPPush], cPermissionsCodeSMS); end; procedure TForm1.TakePhotoButtonClick(Sender: TObject); begin FRequester.RequestPermissions([cPermissionReadExternalStorage, cPermissionWriteExternalStorage, cPermissionCamera], cPermissionsCodeExternalStorage); end; procedure TForm1.MediaLibraryReceivedImageHandler(Sender: TObject; const AImagePath: string; const AImage: TBitmap); begin PhotoImage.Bitmap.Assign(AImage); end; procedure TForm1.OpenPDFButtonClick(Sender: TObject); {$IF Defined(ANDROID)} var LIntent: JIntent; LFileName: string; begin // NOTE: You will need a PDF viewer installed on your device in order for this to work LFileName := TPath.Combine(TPath.GetPublicPath, cPDFSampleFileName); LIntent := TJIntent.JavaClass.init(TJIntent.JavaClass.ACTION_VIEW); LIntent.setDataAndType(TAndroidHelperEx.UriFromFileName(LFileName), StringToJString('application/pdf')); LIntent.setFlags(TJIntent.JavaClass.FLAG_GRANT_READ_URI_PERMISSION); TAndroidHelper.Activity.startActivity(LIntent); end; {$ELSE} begin end; {$ENDIF} procedure TForm1.CancelScheduledClick(Sender: TObject); begin NotificationCenter.CancelNotification('ScheduledNotification'); end; procedure TForm1.ImmediateButtonClick(Sender: TObject); begin ImmediateNotification; end; procedure TForm1.Schedule10SecondsButtonClick(Sender: TObject); begin ScheduleNotification; end; procedure TForm1.ImmediateNotification; var LNotification: TNotification; begin LNotification := NotificationCenter.CreateNotification; try LNotification.EnableSound := False; LNotification.AlertBody := 'Immediate Notification'; NotificationCenter.PresentNotification(LNotification); finally LNotification.Free; end; end; procedure TForm1.ScheduleNotification; var LNotification: TNotification; begin LNotification := NotificationCenter.CreateNotification; try LNotification.Name := 'ScheduledNotification'; LNotification.EnableSound := False; LNotification.AlertBody := 'Scheduled Notification'; LNotification.FireDate := Now + EncodeTime(0, 0, 10, 0); NotificationCenter.ScheduleNotification(LNotification); finally LNotification.Free; end; end; end.
unit uCRUD; interface uses System.Generics.Collections, System.SysUtils, uDM; type TCRUD = class private FTabela: string; FChavePrimaria: string; FValor: TList<string>; FCampo: TList<string>; procedure SetCampo(const Value: TList<string>); procedure SetValor(const Value: TList<string>); public function InsertSQL(): Integer; procedure UpdateSQL(AValorChave: string); procedure DeleteSQL(AValorChave: string); Procedure Limpar(); procedure Dados(ACampo, AValor: string); function TipoString(AValor: string): string; function TipoBool(AValor: Boolean): string; function TipoInt(AValor: Integer): string; function TipoIntNull(AValor: Integer): string; function TipoData(AValor: TDate): string; property Campo: TList<string> read FCampo write SetCampo; property Valor: TList<string> read FValor write SetValor; constructor create(ATabela, APrimaryKey: string); destructor destroy; override; end; implementation { TCRUD } constructor TCRUD.create(ATabela, APrimaryKey: string); begin inherited create; FTabela := ATabela; FChavePrimaria := APrimaryKey; FCampo := TList<string>.Create; FValor := TList<string>.create; end; procedure TCRUD.Dados(ACampo, AValor: string); begin FCampo.Add(ACampo); FValor.Add(AValor); end; procedure TCRUD.DeleteSQL(AValorChave: string); begin dm.Conexao.ExecSQL('DELETE FROM ' + FTabela + ' WHERE ' + FChavePrimaria + ' = ' + AValorChave); end; destructor TCRUD.destroy; begin FreeAndNil(FCampo); FreeAndNil(FValor); inherited; end; function TCRUD.InsertSQL: Integer; var Sql: string; i: Integer; begin Sql := 'INSERT INTO ' + FTabela + '('; for I := 0 to FCampo.Count -1 do Sql := Sql + FCampo[i] + ','; Delete(Sql, Sql.Length , 1); Sql := Sql + ') VALUES ('; for I := 0 to FValor.Count -1 do Sql := Sql + FValor[i] + ','; Delete(Sql, Sql.Length , 1); Sql := Sql + '); SELECT SCOPE_IDENTITY()'; Result := dm.Conexao.ExecSQLScalar(Sql); end; procedure TCRUD.Limpar; begin FCampo.Clear; FValor.Clear; end; procedure TCRUD.SetCampo(const Value: TList<string>); begin FCampo := Value; end; procedure TCRUD.SetValor(const Value: TList<string>); begin FValor := Value; end; function TCRUD.TipoBool(AValor: Boolean): string; begin if AValor then Result := '1' else Result := '0'; end; function TCRUD.TipoData(AValor: TDate): string; begin if AValor > 0 then Result := FormatDateTime('yyy-mm-dd', AValor) else Result := 'NULL'; end; function TCRUD.TipoInt(AValor: Integer): string; begin Result := IntToStr(AValor); end; function TCRUD.TipoIntNull(AValor: Integer): string; begin if AValor > 0 then Result := IntToStr(AValor) else Result := 'NULL'; end; function TCRUD.TipoString(AValor: string): string; begin Result := '''' + AValor + ''''; end; procedure TCRUD.UpdateSQL(AValorChave: string); var Sql: string; i: Integer; begin Sql := 'UPDATE ' + FTabela + ' SET '; for I := 0 to FValor.Count -1 do begin if FCampo[i] = FChavePrimaria then Continue; Sql := Sql + FCampo[i] + '=' + FValor[i] + ','; end; Delete(Sql, Sql.Length , 1); Sql := Sql + ' WHERE ' + FChavePrimaria + '=' + AValorChave; dm.Conexao.ExecSQL(Sql); end; end.
unit Attachments; interface uses SysUtils, Classes; const tidClass = 'Class'; tidProperties = 'Properties'; const propExecuted = 'Executed'; type TAttachment = class; TAttachmentExecuter = class; TAttachment = class public constructor Create(const aText : string); constructor Load(const path : string); destructor Destroy; override; private fProperties : TStringList; private function GetKind : string; public property Kind : string read GetKind; property Properties : TStringList read fProperties; public procedure Store(const path : string); end; TAttachmentExecuteResult = (erOk, erError, erDelete, erIgnoredAttachment); TAttachmentExecuter = class public constructor Create(aProxy : OleVariant); protected fProxy : OleVariant; public function Execute(TAttach : TAttachment) : TAttachmentExecuteResult; virtual; abstract; end; procedure InitAttachmentExecuters; procedure DoneAttachmentExecuters; procedure AddAttachmentExecuters(const ClassName : string; Exec : TAttachmentExecuter); function ExcecuteAttachment(Attach : TAttachment) : TAttachmentExecuteResult; implementation uses IniFiles; var Executers : TStringList = nil; procedure InitAttachmentExecuters; begin Executers := TStringList.Create; end; procedure DoneAttachmentExecuters; var i : integer; begin for i := 0 to pred(Executers.Count) do Executers.Objects[i].Free; Executers.Free; end; procedure AddAttachmentExecuters(const ClassName : string; Exec : TAttachmentExecuter); begin Executers.AddObject(ClassName, Exec); end; function ExcecuteAttachment(Attach : TAttachment) : TAttachmentExecuteResult; var index : integer; Exec : TAttachmentExecuter; begin index := Executers.IndexOf(Attach.Kind); if index <> -1 then begin Exec := TAttachmentExecuter(Executers.Objects[index]); if Exec <> nil then result := Exec.Execute(Attach) else result := erIgnoredAttachment; end else result := erIgnoredAttachment; end; // TAttachment constructor TAttachment.Create(const aText : string); begin inherited Create; fProperties := TStringList.Create; fProperties.Text := aText; end; constructor TAttachment.Load(const path : string); var IniFile : TIniFile; begin inherited Create; IniFile := TIniFile.Create(path); try fProperties := TStringList.Create; IniFile.ReadSection(tidProperties, fProperties); finally IniFile.Free; end; end; destructor TAttachment.Destroy; begin fProperties.Free; inherited; end; function TAttachment.GetKind : string; begin result := fProperties.Values[tidClass]; end; procedure TAttachment.Store(const path : string); var i : integer; name : string; IniFile : TIniFile; begin IniFile := TIniFile.Create(path); try for i := 0 to pred(fProperties.Count) do begin name := fProperties.Names[i]; IniFile.WriteString(tidProperties, name, fProperties.Values[name]); end; finally IniFile.Free; end; end; // TAttachmentExecuter constructor TAttachmentExecuter.Create(aProxy : OleVariant); begin inherited Create; fProxy := aProxy; end; end.
{ Subroutine SST_W_C_EXP_REC (EXP) * * Write the value of the expression EXP. EXP is a constant record expression. * This is only allowed in the initialization of a record variable. } module sst_w_c_EXP_REC; define sst_w_c_exp_rec; %include 'sst_w_c.ins.pas'; procedure sst_w_c_exp_rec ( {write value of record constant expression} in exp: sst_exp_t); const max_msg_parms = 1; {max parameters we can pass to a message} var term_p: sst_exp_term_p_t; {points to current term in expression} dt_exp_p: sst_dtype_p_t; {points to base data type of record} field_p: sst_symbol_p_t; {points to symbol for current field in rec} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; label next_field; begin dt_exp_p := exp.dtype_p; {resolve expression's base data type} while dt_exp_p^.dtype = sst_dtype_copy_k do dt_exp_p := dt_exp_p^.copy_dtype_p; if dt_exp_p^.dtype <> sst_dtype_rec_k then begin {expression dtype not RECORD ?} sys_msg_parm_int (msg_parm[1], ord(dt_exp_p^.dtype)); sys_message_bomb ('sst', 'dtype_unexpected', msg_parm, 1); end; sst_w.appendn^ ('{', 1); {start list of values for each field} field_p := dt_exp_p^.rec_first_p; {init current field to first in record} while field_p <> nil do begin {once for each field in record} term_p := addr(exp.term1); {init current term to first in expression} repeat {scan thru terms looking for this field} if term_p^.field_sym_p = field_p then begin {found term for this field ?} sst_w_c_exp {write value for this field} (term_p^.field_exp_p^, 0, nil, enclose_no_k); goto next_field; {done writing value for this field} end; term_p := term_p^.next_p; {advance to next term in expression} until term_p = nil; {back and process next term in expression} sst_w_c_ival_unspec (field_p^.field_dtype_p^); {use "unspecified" value} { * Done writing value for this field, advance to next field. } next_field: field_p := field_p^.field_next_p; {advance to next field in record} if field_p <> nil then begin {last value was not last in record ?} sst_w.appendn^ (',', 1); sst_w.delimit^; end; end; {back and process this new field} { * Done writing the value for all the fields in this record. } sst_w.appendn^ ('}', 1); end;
unit csCommandsManager; interface {$Include l3XE.inc} uses csCommandsConst, IdGlobal, l3ObjectRefList, ActnList, Classes, CsDataPipe, ddAppConfigTypes, l3Base, csCommandsTypes, l3ProtoObjectRefList, SyncObjs, l3ProtoObject, Menus ; type TcsCommandsManager = class(Tl3ProtoObject) private f_Commands: Tl3ProtoObjectRefList; f_CS: TCriticalSection; function pm_GetCommands(Index: Integer): TcsCommand; function pm_GetCount: Integer; function pm_GetCustomCommands(Index: Integer): TcsCommand; function pm_GetCustomCommandsCount: Integer; protected procedure Acquire; procedure Add(aCommand: TcsCommand); procedure Cleanup; override; procedure Leave; public constructor Create; procedure ClearCommands; procedure UpdateServerMenu(theServerMenu: TMenuItem); procedure ExecuteCommand(Sender: TObject); virtual; abstract; function CommandExists(aID: Integer; out theCommand: TcsCommand): Boolean; property Commands[Index: Integer]: TcsCommand read pm_GetCommands; property Count: Integer read pm_GetCount; property CustomCommands[Index: Integer]: TcsCommand read pm_GetCustomCommands; property CustomCommandsCount: Integer read pm_GetCustomCommandsCount; end; implementation uses SysUtils; constructor TcsCommandsManager.Create; begin inherited; f_Commands:= Tl3ProtoObjectRefList.Make; f_CS:= TCriticalSection.Create; end; procedure TcsCommandsManager.Acquire; begin f_CS.Acquire; end; procedure TcsCommandsManager.Add(aCommand: TcsCommand); begin f_Commands.Add(aCommand); end; procedure TcsCommandsManager.Cleanup; begin l3Free(f_Commands); l3Free(f_CS); inherited; end; procedure TcsCommandsManager.ClearCommands; begin f_Commands.Clear; end; function TcsCommandsManager.CommandExists(aID: Integer; out theCommand: TcsCommand): Boolean; var i: Integer; begin Result := False; theCommand:= nil; i:= 0; while not Result and (i <= f_Commands.Hi) do begin if TcsCommand(f_Commands.Items[i]).CommandID = aID then begin Result:= True; theCommand:= TcsCommand(f_Commands.Items[i]); end else Inc(i); end; end; procedure TcsCommandsManager.Leave; begin f_CS.Leave; end; function TcsCommandsManager.pm_GetCommands(Index: Integer): TcsCommand; begin Result := f_Commands[index] as TcsCommand; end; function TcsCommandsManager.pm_GetCount: Integer; begin Result := f_Commands.Count; end; function TcsCommandsManager.pm_GetCustomCommands( Index: Integer): TcsCommand; var i, l_Index: Integer; begin Result := nil; l_Index:= -1; for i:= 0 to Pred(Count) do if Commands[i].CommandID > c_CommandBaseIndex then begin Inc(l_Index); if l_Index = Index then Result:= Commands[i]; end; end; function TcsCommandsManager.pm_GetCustomCommandsCount: Integer; var i: Integer; begin Result := 0; for i:= 0 to Pred(Count) do if Commands[i].CommandID > c_CommandBaseIndex then Inc(Result); end; procedure TcsCommandsManager.UpdateServerMenu(theServerMenu: TMenuItem); var i: Integer; l_MI: TMenuItem; l_Command: TcsCommand; begin theServerMenu.Clear; for i:= 0 to CustomCommandsCount-1 do begin l_MI:= TmenuItem.Create(theServerMenu); l_Command := CustomCommands[i]; l_MI.Name:= 'ServerMenu'+ IntToStr(l_Command.CommandID); l_MI.Tag:= l_Command.CommandID; l_MI.Caption:= l_Command.Caption; l_MI.OnClick:= ExecuteCommand; theServerMenu.Add(l_MI); end; theServerMenu.Visible:= theServerMenu.Count > 0; end; end.
unit NewsBoard_TLB; { This file contains pascal declarations imported from a type library. This file will be written during each import or refresh of the type library editor. Changes to this file will be discarded during the refresh process. } { NewsBoard Library } { Version 1.0 } interface uses Windows, ActiveX, Classes, Graphics, OleCtrls, StdVCL; const LIBID_NewsBoard: TGUID = '{DB9412F0-CEA7-11D3-B5CA-00A0CC2C4AEF}'; const { Component class GUIDs } Class_NewsObject: TGUID = '{DB9412F2-CEA7-11D3-B5CA-00A0CC2C4AEF}'; type { Forward declarations: Interfaces } INewsObject = interface; INewsObjectDisp = dispinterface; { Forward declarations: CoClasses } NewsObject = INewsObject; { Dispatch interface for NewsObject Object } INewsObject = interface(IDispatch) ['{DB9412F1-CEA7-11D3-B5CA-00A0CC2C4AEF}'] function Author: WideString; safecall; function Date: WideString; safecall; function Body: WideString; safecall; function ReplyCount: Integer; safecall; function ReplyAuthor(index: Integer): WideString; safecall; function ReplyDate(index: Integer): WideString; safecall; function ReplySubject(index: Integer): WideString; safecall; function ReplyAuthorDesc(index: Integer): WideString; safecall; function ReplySummary(index: Integer): WideString; safecall; function Importance: Integer; safecall; function AuthorDesc: WideString; safecall; function Open(const path: WideString): Integer; safecall; function OpenReply(index: Integer): Integer; safecall; function ReplyPath(index: Integer): WideString; safecall; function NewMessage(const Parent, Author, AuthorD, Date, Subject, Body: WideString): Integer; safecall; function Subject: WideString; safecall; function FolderOnly: WordBool; safecall; function BodyHTML: WideString; safecall; function GlobalMsgCount: Integer; safecall; function GlobalMsgPath(index: Integer): WideString; safecall; procedure SetRootPath(const RootPath: WideString); safecall; procedure SetIndexSize(size: Integer); safecall; function ParentPath: WideString; safecall; function Summary: WideString; safecall; procedure SetLangId(const aLangId: WideString); safecall; end; { DispInterface declaration for Dual Interface INewsObject } INewsObjectDisp = dispinterface ['{DB9412F1-CEA7-11D3-B5CA-00A0CC2C4AEF}'] function Author: WideString; dispid 1; function Date: WideString; dispid 2; function Body: WideString; dispid 3; function ReplyCount: Integer; dispid 4; function ReplyAuthor(index: Integer): WideString; dispid 5; function ReplyDate(index: Integer): WideString; dispid 6; function ReplySubject(index: Integer): WideString; dispid 7; function ReplyAuthorDesc(index: Integer): WideString; dispid 8; function ReplySummary(index: Integer): WideString; dispid 9; function Importance: Integer; dispid 10; function AuthorDesc: WideString; dispid 11; function Open(const path: WideString): Integer; dispid 12; function OpenReply(index: Integer): Integer; dispid 13; function ReplyPath(index: Integer): WideString; dispid 14; function NewMessage(const Parent, Author, AuthorD, Date, Subject, Body: WideString): Integer; dispid 16; function Subject: WideString; dispid 15; function FolderOnly: WordBool; dispid 17; function BodyHTML: WideString; dispid 18; function GlobalMsgCount: Integer; dispid 19; function GlobalMsgPath(index: Integer): WideString; dispid 20; procedure SetRootPath(const RootPath: WideString); dispid 21; procedure SetIndexSize(size: Integer); dispid 22; function ParentPath: WideString; dispid 23; function Summary: WideString; dispid 24; procedure SetLangId(const aLangId: WideString); dispid 25; end; { NewsObjectObject } CoNewsObject = class class function Create: INewsObject; class function CreateRemote(const MachineName: string): INewsObject; end; implementation uses ComObj; class function CoNewsObject.Create: INewsObject; begin Result := CreateComObject(Class_NewsObject) as INewsObject; end; class function CoNewsObject.CreateRemote(const MachineName: string): INewsObject; begin Result := CreateRemoteComObject(MachineName, Class_NewsObject) as INewsObject; end; end.
(* Desenvolvedor: Kelvin dos Santos Vieira Skype: nivlek_1995@hotmail.com Wpp: (49)99818-2190 FB: https://www.facebook.com/keelvin9 *) (* EnterTab: Componente para ajudar no controle de foco em FMX Windows*. Para usar: 1º. Coloque o componente na Form; 2º. Configure a propriedade ControlarForm da seguinte maneira: - True para que o componente controle os componentes de uma Form (Usado em aberturas padrões de form [FORM.Show]); - False para que o componente controle os componetes dentro de um Layout (Usado em aberturas de Layouts [LayoutMain.AddObject(Form2.Layout)]); 3º. Marque a opção EnterAsTab para ativar o evento de Controle; 4º. Configure os componentes na sua form ou layout com os TabOrder corretamente; 5º. Seja feliz!. * - Não testado em ambientes MacOS, Linux, Android ou IOS *) unit uKSEnterTab; interface uses System.SysUtils, System.Classes, FMX.Forms, FMX.Types, System.UITypes, FMX.StdCtrls, FMX.Controls, System.Rtti, FMX.Edit; type TKSEnterTab = class(TComponent) private { Private declarations } FListaControls: TList; FOwner: TForm; FOldKeyPreview : Boolean; FOldOnKeyPress : TKeyEvent; FEnterAsTab: boolean; FControlComponent: TComponent; FControlarForm: Boolean; procedure SetEnterAsTab(const Value: boolean); procedure SetControlComponent(const Value: TComponent); procedure SetControlarForm(const Value: Boolean); protected { Protected declarations } public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure DoEnterAsTab(AForm : TObject; var Key: Word; var KeyChar: WideChar; Shift: TShiftState); function SelectNextControl(ATabOrderAtual: Integer): TControl; function SelectControlFocused: TControl; procedure ListarControls; procedure PreencherListaComChildrens(AObj: TFMXObject); published { Published declarations } property EnterAsTab: boolean read FEnterAsTab write SetEnterAsTab; property ControlComponent: TComponent read FControlComponent write SetControlComponent; property ControlarForm: Boolean read FControlarForm write SetControlarForm; end; procedure Register; implementation procedure Register; begin RegisterComponents('LazarusUteis', [TKSEnterTab]); end; { TLazarusEnterTab } constructor TKSEnterTab.Create(AOwner: TComponent); begin if not (AOwner is TForm) then raise Exception.Create('Owner tem que ser do tipo TForm'); inherited Create(AOwner); FOwner := TForm(AOwner); (*Atribui o evento atual de KeyDown do controle a variavel do tipo TKeyEvent para se necessário voltar o evento antigo*) FOldOnKeyPress := FOwner.OnKeyDown; FListaControls := TList.Create; if not (csDesigning in ComponentState) then begin (*Se não for setado nenhum componente de controle de forms ele pega o Owner ou seja, a propria form como controle*) if FControlComponent = Nil then FControlComponent := AOwner; end; end; destructor TKSEnterTab.Destroy; begin if Assigned(FOwner) then begin if not (csFreeNotification in FOwner.ComponentState) then begin FOwner.OnKeyDown := FOldOnKeyPress; end; end; inherited; end; procedure TKSEnterTab.DoEnterAsTab(AForm: TObject; var Key: Word; var KeyChar: WideChar; Shift: TShiftState); var vTabOrder: Integer; vProximoControl: TControl; vControlFocused: TControl; begin (*Primeiramente o evento adiciona todos os TControls a um TList*) ListarControls; if not (AForm is TForm) then Exit; if (Key = vkReturn) or (Key = vkTab) then begin (*Busca o componente que está com o foco atualmente*) vControlFocused := SelectControlFocused; (*Pega o TabOrder dele para buscar o próximo posteriormente*) vTabOrder := vControlFocused.TabOrder; (*Se o componente que está em foco for um componente de Botão, então não muda foco. Apenas Clica*) if vControlFocused is TCustomButton then begin TButton(SelectControlFocused).OnClick(Nil); end else begin (*Caso contrário busca o proximo Componente a partir do TabOrder atual*) vProximoControl := SelectNextControl(vTabOrder); if vProximoControl <> Nil then begin (*Achado o componente, seta o foco ao mesmo*) vProximoControl.SetFocus; end; end; end; (*Para não executar o procedimento cábivel naturalmente a tecla pressionada*) if (Key = vkReturn) or (Key = vkTab) then KeyChar := #0; end; procedure TKSEnterTab.ListarControls; begin (*Só lista os componentes se quem controla o foco é um TComponent setado na propriedade ControlComponent*) if not (FControlarForm) then begin (*Sempre Limpa a TList para quando abrir um novo form (Chamar o Layout) percorrer sua lista de Childrens*) FListaControls.Clear; (*Começa executando o procedimento de listagem pelo proprio componente responsável por exibir as forms (Layouts)*) PreencherListaComChildrens(TFMXObject(FControlComponent)); end; end; procedure TKSEnterTab.PreencherListaComChildrens(AObj: TFMXObject); var I,J: Integer; begin for I := 0 to Pred(AObj.ChildrenCount) do begin (*Verifica se o Filho(Children) é do tipo TControl (Visual) e se o TabStop for True para poder adicionar a TList*) if (AObj.Children[i] is TControl) and (TControl(AObj.Children[i]).TabStop) then (*Adiciona o TControl a TList*) FListaControls.Add(AObj.Children[i]); (*Reexecuta o procedimento agora a partir do Filho na posição I*) PreencherListaComChildrens(AObj.Children[i]); end; (*Executará até não restarem mais filhos no Layout de Forms*) end; function TKSEnterTab.SelectControlFocused: TControl; var I: Integer; begin result := nil; (*Se for controlado por form, busca no componentcount o foco atual, caso contrário buscará nos filhos do componente setado na propriedade controlcomponent pelo foco atual*) if not (FControlarForm) then begin for I := 0 to Pred(FListaControls.Count) do begin if TControl(FListaControls[i]).IsFocused then begin result := TControl(FListaControls[i]); break; end; end; end else begin for I := 0 to Pred(FControlComponent.ComponentCount) do begin if (FControlComponent.Components[i] is TControl) and (TControl(FControlComponent.Components[i]).IsFocused) then begin result := TControl(FControlComponent.Components[i]); break; end; end; end; end; function TKSEnterTab.SelectNextControl(ATabOrderAtual: Integer): TControl; var i: integer; begin result := nil; (*Se for controlado por uma Form, roda o ComponentCount para pegar o proximo Control a receber foco, caso contrário faz um for nos filhos(Childrens) do controle atribuido a propriedade ControlComponent. Para isso ele precisa ser TControl e alem disso ser um TCustomEdit ou TCustomButton. Componentes como TComboBox, tem um [Enter] proprio que ao teclar enter, exibe a lista de itens do prorio componente*) if not (FControlarForm) then begin for I := 0 to Pred(FListaControls.Count) do begin if ((TControl(FListaControls[i]) is TCustomEdit) or (TControl(FListaControls[i]) is TCustomButton)) and (TControl(FListaControls[i]).TabStop) and (TControl(FListaControls[i]).TabOrder = ATabOrderAtual + 1) then begin result := TControl(FListaControls[i]); break; end; end; end else begin for I := 0 to Pred(FControlComponent.ComponentCount) do begin if (FControlComponent.Components[i] is TControl) and ((TControl(FControlComponent.Components[i]) is TCustomEdit) or (TControl(FControlComponent.Components[i]) is TCustomButton)) and (TControl(FControlComponent.Components[i]).TabOrder = (ATabOrderAtual + 1)) and (TControl(FControlComponent.Components[i]).TabStop) then begin result := TControl(FControlComponent.Components[i]); break; end; end; end; end; procedure TKSEnterTab.SetControlarForm(const Value: Boolean); begin FControlarForm := Value; end; procedure TKSEnterTab.SetControlComponent(const Value: TComponent); begin FControlComponent := Value; end; procedure TKSEnterTab.SetEnterAsTab(const Value: boolean); begin if Value = FEnterAsTab then exit ; if not (csDesigning in ComponentState) then begin with TForm( Owner ) do begin if Value then begin (*Se marcado seta o evento criado no componente para o KeyDown da Form*) OnKeyDown := DoEnterAsTab; end else begin (*Se desmarcado seta o evento anterior da form ao evento KeyDown da Form*) OnKeyDown := FOldOnKeyPress; end ; end ; end ; FEnterAsTab := Value; end; end.
unit UDemo; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.TMSBaseControl, FMX.TMSGridCell, FMX.TMSGridOptions, FMX.TMSGridData, FMX.TMSCustomGrid, FMX.TMSGrid, FMX.TMSBitmapContainer, FMX.TMSGridPDFIO, FMX.TMSXUtil; type TForm25 = class(TForm) TMSFMXBitmapContainer1: TTMSFMXBitmapContainer; TMSFMXGrid1: TTMSFMXGrid; ToolBar1: TToolBar; Button1: TButton; StyleBook2: TStyleBook; TMSFMXGridPDFIO1: TTMSFMXGridPDFIO; procedure FormCreate(Sender: TObject); procedure TMSFMXGrid1GetCellLayout(Sender: TObject; ACol, ARow: Integer; ALayout: TTMSFMXGridCellLayout; ACellState: TCellState); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form25: TForm25; implementation {$R *.fmx} procedure TForm25.Button1Click(Sender: TObject); var fn: String; begin fn := XGetDocumentsDirectory + '/pdfexport.pdf'; TMSFMXGridPDFIO1.ExportPDF(fn); if FileExists(fn) then XOpenFile(fn); end; procedure TForm25.FormCreate(Sender: TObject); begin TMSFMXGrid1.Options.Printing.PrintCellBackGround := cbFull; TMSFMXGrid1.ColumnCount := 6; TMSFMXGrid1.RandomFill; TMSFMXGrid1.AutoNumberCol(0); TMSFMXGrid1.Colors[2,2] := TAlphaColorRec.Red; TMSFMXGrid1.Colors[3,3] := TAlphaColorRec.Lime; TMSFMXGrid1.Colors[4,4] := TAlphaColorRec.Yellow; TMSFMXGrid1.HorzAlignments[2,3] := TTextAlign.taCenter; TMSFMXGrid1.HorzAlignments[3,4] := TTextAlign.taTrailing; TMSFMXGrid1.FontStyles[1,1] := [TFontStyle.fsBold]; TMSFMXGrid1.FontStyles[1,2] := [TFontStyle.fsItalic]; TMSFMXGrid1.MergeCells(1,4,2,2); TMSFMXGrid1.AddBitmap(1,7,'1'); TMSFMXGrid1.AddBitmap(1,8,'2'); TMSFMXGrid1.AddBitmap(1,9,'3'); end; procedure TForm25.TMSFMXGrid1GetCellLayout(Sender: TObject; ACol, ARow: Integer; ALayout: TTMSFMXGridCellLayout; ACellState: TCellState); begin if (ACol = 5) then begin ALayout.FontFill.Color := TAlphaColorRec.Red; ALayout.TextAlign := TTextAlign.taTrailing; end; end; end.
unit unit1; interface uses Classes, vg_forms, vg_scene, vg_objects, vg_controls, vg_ani, vg_colors, vg_listbox, vg_tabcontrol, vg_effects, vg_layouts, vg_textbox, vg_memo, vg_extctrls, vg_treeview, vg_grid, Controls; type TForm1 = class(TForm) vgScene1: TvgScene; Root1: TvgBackground; Text1: TvgText; FloatAnimation1: TvgFloatAnimation; Button1: TvgTextBox; Selection1: TvgSelection; StringListBox1: TvgStringListBox; Path1: TvgPath; GradientAnimation1: TvgGradientAnimation; StringComboBox1: TvgStringComboBox; TrackBar1: TvgTrackBar; HorzListBox1: TvgHorzListBox; ComboTrackBar1: TvgComboTrackBar; vgResources1: TvgResources; CheckBox2: TvgCheckBox; ComboColorBox1: TvgComboColorBox; procedure FormCreate(Sender: TObject); procedure CheckBox2Change(Sender: TObject); procedure ComboColorBox1Change(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); var i: integer; Item: TvgListboxItem; R: TvgRectangle; begin for i := 0 to 20 do begin Item := TvgListboxItem.Create(Self); Item.Parent := HorzListBox1; R := TvgRectangle.Create(Self); R.Parent := Item; R.Fill.Color := vgColorToStr($FF000000 or random($FFFFFF)); R.Stroke.Style := vgBrushNone; R.HitTest := false; R.Padding.Rect := vgRect(4, 4, 4, 4); R.Align := vaClient; end; end; procedure TForm1.CheckBox2Change(Sender: TObject); begin if CheckBox2.IsChecked then vgScene1.Style := vgResources1 else vgScene1.Style := nil; end; procedure TForm1.ComboColorBox1Change(Sender: TObject); begin Root1.Fill.Style := vgBrushSolid; Root1.Fill.Color := ComboColorBox1.Color; end; end.
unit WinVersion; interface function IsNT : boolean; implementation uses Windows; function IsNT : boolean; var osvi : OSVERSIONINFO; begin osvi.dwOSVersionInfoSize := sizeof(OSVERSIONINFO); GetVersionEx(osvi); if (osvi.dwPlatformId = VER_PLATFORM_WIN32_NT) then Result := true else Result := false; end; end.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA 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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit frmEnvironmentOptions; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, cxLookAndFeelPainters, ComCtrls, cxControls, cxContainer, cxTreeView, StdCtrls, cxButtons, ExtCtrls, cxPC, cxEdit, cxLabel, cxGraphics, cxListView, cxTextEdit, cxMaskEdit, cxDropDownEdit, GenelDM, cxSpinEdit, cxFontNameComboBox; type TEnvironmentOptionsFrm = class(TForm) Panel2: TPanel; btnCancel: TcxButton; btnOK: TcxButton; treeList: TcxTreeView; Panel1: TPanel; Panel3: TPanel; imgToolBar: TImage; imgObject: TImage; lblObjectName: TcxLabel; pc: TcxPageControl; tsLanguages: TcxTabSheet; tsFont: TcxTabSheet; tsEditorColor: TcxTabSheet; cxLabel1: TcxLabel; comboDefaultLanguage: TcxComboBox; cxLabel2: TcxLabel; lvLanguageList: TcxListView; btnAddLanguage: TcxButton; cxLabel3: TcxLabel; comboFontName: TcxFontNameComboBox; cxLabel4: TcxLabel; sedtFontSize: TcxSpinEdit; lblFontSample: TcxLabel; procedure btnCancelClick(Sender: TObject); procedure btnAddLanguageClick(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure treeListChange(Sender: TObject; Node: TTreeNode); procedure comboFontNamePropertiesChange(Sender: TObject); private { Private declarations } procedure SetLanguages; procedure SaveLanguages; procedure SetFont; procedure SaveFont; public { Public declarations } procedure Init(); end; var EnvironmentOptionsFrm: TEnvironmentOptionsFrm; implementation uses VisualOptions, Languages, frmAddLanguage; {$R *.dfm} procedure TEnvironmentOptionsFrm.Init(); begin EnvironmentOptionsFrm := TEnvironmentOptionsFrm.Create(Application); Self := EnvironmentOptionsFrm; DMGenel.ChangeLanguage(self); ChangeVisualGUI(self); pc.ActivePageIndex := 0; treeListChange(nil, treeList.Items[0]); SetLanguages; SetFont; ShowModal; free; end; procedure TEnvironmentOptionsFrm.btnCancelClick(Sender: TObject); begin close; end; procedure TEnvironmentOptionsFrm.treeListChange(Sender: TObject; Node: TTreeNode); begin pc.ActivePageIndex := Node.Index; lblObjectName.Caption := Node.Text; imgObject.Picture := nil; dmGenel.ilEnviromentOptions.GetBitmap(pc.ActivePageIndex, imgObject.Picture.Bitmap); imgObject.Repaint; imgObject.Refresh; end; procedure TEnvironmentOptionsFrm.SetLanguages; var str: TStrings; i: integer; begin str := ReadAllLanguages; for i := 0 to str.Count -1 do begin with lvLanguageList.Items.Add do begin Caption := copy(str[i],1,pos('=',str[i])-1); ImageIndex := -1; end; lvLanguageList.Items[lvLanguageList.Items.count-1].SubItems.Add(copy(str[i],pos('=',str[i])+1, length(str[i]))); end; for i := 0 to str.Count -1 do str[i] := copy(str[i],1,pos('=',str[i])-1); comboDefaultLanguage.Properties.Items := str; comboDefaultLanguage.Text := ReadDefaultLanguage; end; procedure TEnvironmentOptionsFrm.btnAddLanguageClick(Sender: TObject); var str : string; begin str := AddLanguageFrm.Init; if str = '' then exit; with lvLanguageList.Items.Add do begin Caption := copy(str,1,pos('=',str)-1); ImageIndex := -1; end; lvLanguageList.Items[lvLanguageList.Items.count-1].SubItems.Add(copy(str,pos('=',str)+1, length(str))); comboDefaultLanguage.Properties.Items.Add(copy(str,1,pos('=',str)-1)); end; procedure TEnvironmentOptionsFrm.SaveLanguages; var ml: TMultiLanguages; i: integer; begin ml := TMultiLanguages.Create(nil); for i := 0 to lvLanguageList.Items.Count -1 do begin ml.Add(lvLanguageList.Items[i].Caption, lvLanguageList.Items[i].SubItems.CommaText); end; ml.SaveDefault(comboDefaultLanguage.Text); ml.Free; end; procedure TEnvironmentOptionsFrm.btnOKClick(Sender: TObject); begin if pc.ActivePage = tsLanguages then SaveLanguages; if pc.ActivePage = tsFont then SaveFont; close; end; procedure TEnvironmentOptionsFrm.SetFont; begin ReadSystemFontName; comboFontName.FontName := SystemFontName; sedtFontSize.Value := SystemFontSize; end; procedure TEnvironmentOptionsFrm.SaveFont; begin SystemFontName := comboFontName.FontName; SystemFontSize := sedtFontSize.Value; WriteSystemFontName; end; procedure TEnvironmentOptionsFrm.comboFontNamePropertiesChange( Sender: TObject); begin lblFontSample.Style.Font.Name := comboFontName.FontName; lblFontSample.Style.Font.Size := sedtFontSize.Value; end; end.
program MakePasX; { Makes Delphi form code file or project file cross-platform so it can be compiled by both Delphi and Lazarus/FPC. Note that this is a one-time conversion. Note: Use DfmToLfm to convert form's design file to LCL whenever changes are made to form in Delphi. Author: Phil Hess. Copyright: Copyright (C) 2007 Phil Hess. All rights reserved. License: Modified LGPL. } {$IFDEF FPC} {$MODE Delphi} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF} {$R+,Q+} uses SysUtils; const ProgramName = 'MakePasX'; ProgramVersion = '0.03'; PasFileExt = '.pas'; {Pascal code file extension} DelProjFileExt = '.dpr'; {Delphi project file extension} TmpFileExt = '.tmp'; {Create converted file with this extension} BakFileExt = '.bak'; {Rename original file with this extension} var OldFileName : string; NewFileName : string; OldFileVar : TextFile; NewFileVar : TextFile; {$IFNDEF FPC} MatchFound : TFilenameCaseMatch; {$ENDIF} IsProject : Boolean; InStr : string; FoundUses : Boolean; Done : Boolean; UnitPos : Integer; HasAppInit : Boolean; HasForm : Boolean; begin if ParamCount = 0 then {List program useage?} begin WriteLn(ProgramName, ', version ', ProgramVersion, ' - makes Delphi code file cross-platform.'); WriteLn('Usage: ', ProgramName, ' filename[', PasFileExt, '|', DelProjFileExt, ']'); Halt; end; {Get name of Pascal code file to convert from command line} OldFileName := ParamStr(1); if ExtractFileExt(OldFileName) = '' then {No extension?} OldFileName := OldFileName + PasFileExt; {Assume it's not a project file} {$IFNDEF FPC} OldFileName := ExpandFileNameCase(OldFileName, MatchFound); {$ELSE} OldFileName := ExpandFileName(OldFileName); {$ENDIF} IsProject := CompareText(ExtractFileExt(OldFileName), DelProjFileExt) = 0; NewFileName := ChangeFileExt(OldFileName, TmpFileExt); {Open code file} AssignFile(OldFileVar, OldFileName); try Reset(OldFileVar); except on EInOutError do begin WriteLn('Can''t open Pascal code file ', OldFileName); Halt; end; end; {Create new code file} AssignFile(NewFileVar, NewFileName); try Rewrite(NewFileVar); except on EInOutError do begin WriteLn('Can''t create new code file ', NewFileName); Halt; end; end; FoundUses := False; HasAppInit := False; HasForm := False; while not Eof(OldFileVar) do {Read and convert Pascal code file} begin ReadLn(OldFileVar, InStr); {Read line of code} if not IsProject then {Form code file?} begin if (CompareText(InStr, 'uses') = 0) and {Found uses section?} (not FoundUses) then {And in interface section?} begin {Note assumes "uses" appears on separate line from list of units} FoundUses := True; WriteLn(NewFileVar, InStr); WriteLn(NewFileVar, ' {$IFNDEF LCL} Windows, Messages, ', '{$ELSE} LclIntf, LMessages, LclType, {$ENDIF}'); //LResources not needed anymore // '{$ELSE} LclIntf, LMessages, LclType, LResources, {$ENDIF}'); ReadLn(OldFileVar, InStr); repeat UnitPos := Pos('WINDOWS,', UpperCase(InStr)); if UnitPos > 0 then Delete(InStr, UnitPos, 8); if Copy(InStr, UnitPos, 1) = ' ' then Delete(InStr, UnitPos, 1); UnitPos := Pos('MESSAGES,', UpperCase(InStr)); if UnitPos > 0 then Delete(InStr, UnitPos, 9); if Copy(InStr, UnitPos, 1) = ' ' then Delete(InStr, UnitPos, 1); UnitPos := Pos('WINTYPES,', UpperCase(InStr)); {Synonym for Windows} if UnitPos > 0 then Delete(InStr, UnitPos, 9); if Copy(InStr, UnitPos, 1) = ' ' then Delete(InStr, UnitPos, 1); UnitPos := Pos('WINPROCS,', UpperCase(InStr)); {Synonym for Windows} if UnitPos > 0 then Delete(InStr, UnitPos, 9); if Copy(InStr, UnitPos, 1) = ' ' then Delete(InStr, UnitPos, 1); WriteLn(NewFileVar, InStr); Done := Pos(';', InStr) > 0; if not Done then ReadLn(OldFileVar, InStr); until Done; end {uses section} else if CompareText(Copy(Trim(InStr), 1, 10), '{$R *.dfm}') = 0 then {Form's resource file?} begin WriteLn(NewFileVar, '{$IFNDEF LCL}'); WriteLn(NewFileVar, InStr); WriteLn(NewFileVar, '{$ELSE}'); //Added this WriteLn(NewFileVar, '{$R *.lfm}'); //Added this WriteLn(NewFileVar, '{$ENDIF}'); HasForm := True; end else if (CompareText(InStr, 'end.') = 0) and HasForm then {End of unit?} begin (* // not needed anymore {Note: Make sure IFDEF goes after initialization since Delphi inserts new event handlers immediately before initialization line.} WriteLn(NewFileVar, 'initialization'); WriteLn(NewFileVar, '{$IFDEF LCL}'); WriteLn(NewFileVar, '{$I ', ChangeFileExt(ExtractFileName(OldFileName), '.lrs} {Include form''s resource file}')); WriteLn(NewFileVar, '{$ENDIF}'); WriteLn(NewFileVar); *) WriteLn(NewFileVar, InStr); end else {Nothing to change with this line} WriteLn(NewFileVar, InStr); end else {Delphi project file} begin if (CompareText(InStr, 'uses') = 0) and {Found uses section?} (not FoundUses) then {And in interface section?} begin {Note assumes "uses" appears on separate line from list of units} FoundUses := True; WriteLn(NewFileVar, InStr); WriteLn(NewFileVar, '{$IFDEF LCL}'); WriteLn(NewFileVar, ' Interfaces,'); WriteLn(NewFileVar, '{$ENDIF}'); end else if (CompareText(Copy(Trim(InStr), 1, 10), '{$R *.res}') = 0) or (CompareText(Copy(Trim(InStr), 1, 10), '{$R *.r32}') = 0) or (CompareText(Copy(Trim(InStr), 1, 10), '{$R *.r16}') = 0) then begin {Program's resource file} WriteLn(NewFileVar, '{$IFDEF MSWINDOWS}'); WriteLn(NewFileVar, InStr); WriteLn(NewFileVar, '{$ENDIF}'); end else if CompareText(Copy(Trim(InStr), 1, 3), '{$R') = 0 then begin {Might be a type library or XP manifest resource file} WriteLn(NewFileVar, '{$IFNDEF FPC}'); WriteLn(NewFileVar, InStr); WriteLn(NewFileVar, '{$ENDIF}'); end else if Pos('APPLICATION.INITIALIZE', UpperCase(InStr)) > 0 then begin HasAppInit := True; WriteLn(NewFileVar, InStr); end else begin if (not HasAppInit) and ((Pos('APPLICATION.CREATEFORM', UpperCase(InStr)) > 0) or (Pos('APPLICATION.RUN', UpperCase(InStr)) > 0)) then begin WriteLn(NewFileVar, ' Application.Initialize;'); {Laz needs this} HasAppInit := True; end; WriteLn(NewFileVar, InStr); end; end; end; {while not Eof} DeleteFile(ChangeFileExt(OldFileName, BakFileExt)); CloseFile(OldFileVar); RenameFile(OldFileName, ChangeFileExt(OldFileName, BakFileExt)); CloseFile(NewFileVar); if not IsProject then RenameFile(NewFileName, ChangeFileExt(NewFileName, PasFileExt)) else RenameFile(NewFileName, ChangeFileExt(NewFileName, DelProjFileExt)); WriteLn(OldFileName, ' successfully converted.'); end.
unit Model.Produtos; interface type TProdutos = class private var FCodigo: String; FDescricao: String; FDiario: String; FLog: String; public property Codigo: String read FCodigo write FCodigo; property Descricao: String read FDescricao write FDescricao; property Diario: String read FDiario write FDiario; property Log: String read FLog write FLog; constructor Create; overload; constructor Create(pFCodigo: String; pFDescricao: String; pFDiario: String; pFLog: String); overload; end; implementation constructor TProdutos.Create; begin inherited Create; end; constructor TProdutos.Create(pFCodigo: string; pFDescricao: string; pFDiario: string; pFLog: string); begin FCodigo := pFCodigo; FDescricao := pFDescricao; FDiario := pFDiario; FLog := pFLog; end; end.
unit NtUtils.Exec.Nt; interface uses NtUtils.Exec; type TExecRtlCreateUserProcess = class(TInterfacedObject, IExecMethod) function Supports(Parameter: TExecParam): Boolean; function Execute(ParamSet: IExecProvider): TProcessInfo; end; implementation uses Ntapi.ntdef, Ntapi.ntrtl, Ntapi.ntpsapi, Ntapi.ntobapi, NtUtils.Exceptions, Winapi.ProcessThreadsApi, Ntapi.ntseapi; function RefStr(const Str: UNICODE_STRING; Present: Boolean): PUNICODE_STRING; inline; begin if Present then Result := @Str else Result := nil; end; { TExecRtlCreateUserProcess } function TExecRtlCreateUserProcess.Execute(ParamSet: IExecProvider): TProcessInfo; var ProcessParams: PRtlUserProcessParameters; ProcessInfo: TRtlUserProcessInformation; NtImageName, CurrDir, CmdLine, Desktop: UNICODE_STRING; Status: TNtxStatus; begin // Convert the filename to native format Status.Location := 'RtlDosPathNameToNtPathName_U_WithStatus'; Status.Status := RtlDosPathNameToNtPathName_U_WithStatus( PWideChar(ParamSet.Application), NtImageName, nil, nil); Status.RaiseOnError; CmdLine.FromString(PrepareCommandLine(ParamSet)); if ParamSet.Provides(ppCurrentDirectory) then CurrDir.FromString(ParamSet.CurrentDircetory); if ParamSet.Provides(ppDesktop) then Desktop.FromString(ParamSet.Desktop); // Construct parameters Status.Location := 'RtlCreateProcessParametersEx'; Status.Status := RtlCreateProcessParametersEx( ProcessParams, NtImageName, nil, RefStr(CurrDir, ParamSet.Provides(ppCurrentDirectory)), @CmdLine, nil, nil, RefStr(Desktop, ParamSet.Provides(ppDesktop)), nil, nil, 0 ); if not Status.IsSuccess then RtlFreeUnicodeString(NtImageName); Status.RaiseOnError; if ParamSet.Provides(ppShowWindowMode) then begin ProcessParams.WindowFlags := STARTF_USESHOWWINDOW; ProcessParams.ShowWindowFlags := ParamSet.ShowWindowMode; end; // Create the process Status.Location := 'RtlCreateUserProcess'; Status.LastCall.ExpectedPrivilege := SE_ASSIGN_PRIMARY_TOKEN_PRIVILEGE; Status.Status := RtlCreateUserProcess( NtImageName, OBJ_CASE_INSENSITIVE, ProcessParams, nil, nil, ParamSet.ParentProcess, ParamSet.Provides(ppInheritHandles) and ParamSet.InheritHandles, 0, ParamSet.Token, ProcessInfo ); RtlDestroyProcessParameters(ProcessParams); RtlFreeUnicodeString(NtImageName); Status.RaiseOnError; // The process was created in a suspended state. // Resume it unless the caller explicitly states it should stay suspended. if not ParamSet.Provides(ppCreateSuspended) or not ParamSet.CreateSuspended then NtResumeThread(ProcessInfo.Thread, nil); // The caller must close the handles to the newly created process and thread Result.hProcess := ProcessInfo.Process; Result.hThread := ProcessInfo.Thread; Result.dwProcessId := Cardinal(ProcessInfo.ClientId.UniqueProcess); Result.dwThreadId := Cardinal(ProcessInfo.ClientId.UniqueThread); end; function TExecRtlCreateUserProcess.Supports(Parameter: TExecParam): Boolean; begin case Parameter of ppParameters, ppCurrentDirectory, ppDesktop, ppToken, ppParentProcess, ppInheritHandles, ppCreateSuspended, ppShowWindowMode: Result := True; else Result := False; end; end; end.
unit main; {$mode delphi}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, Quick.Json.Serializer, Generics.Collections; type TID = Int64; TGenre = (gnMale, gnFemale); TGroupType = (gtInternal, gtExternal); TDayOfWeek = (wdSunday, wdMonday, wdThuesday, wdWednesday, wdThursday, wdFriday, wdSaturday); TUserStatus = (usAtOffice, usAtHome, usOnVacation); TDays = set of TDayOfWeek; const DEF_WORKDAYS : TDays = [wdMonday, wdThuesday, wdWednesday, wdThursday, wdFriday]; DEF_WEEKEND : TDays = [wdSaturday, wdSunday]; type TDepartment = record Id : TID; Name : string; end; TContactIdArray = array of TID; TGroup = class private fId : TID; fGType : TGroupType; published property Id : TID read fId write fId; property GType : TGroupType read fGType write fGType; end; TOptions = class private fOption1 : Integer; fOption2 : string; fAllowGroups : TGroupType; published property Option1 : Integer read fOption1 write fOption1; property Option2 : string read fOption2 write fOption2; property AllowGroups : TGroupType read fAllowGroups write fAllowGroups; end; TConnectionInfo = record IP : string; ConnectionDate : TDateTime; end; TConnectionArray = array of TConnectionInfo; TGroupList = TObjectList<TGroup>; TWorkingTime = class private fName : string; fWorkDays : TDays; fFreeDays : TDays; published property Name : string read fName write fName; property WorkDays : TDays read fWorkDays write fWorkDays; property FreeDays : TDays read fFreeDays write fFreeDays; end; TLevelPrivilege = array of TID; TUser = class private fId : TID; fName : string; fSurname : string; fAge : Integer; fAddress : string; fOptions : TOptions; fLastConnections : TConnectionArray; fMarried : Boolean; fWorkingTime : TWorkingTime; //[TCommentProperty('gnFemale or gnMale')] fGenre : TGenre; fBalance : Double; fHireDate : TDateTime; fLevelPrivilege : TLevelPrivilege; fObservations : string; fStatus : TUserStatus; fGroups : TGroupList; public constructor Create; destructor Destroy; override; published //[TCommentProperty('Is user Id')] property Id : TID read fId write fId; property Name : string read fName write fName; property Surname : string read fSurname write fSurname; property Age : Integer read fAge write fAge; property Address : string read fAddress write fAddress; property Balance : Double read fBalance write fBalance; //[TCustomNameProperty('IsMarried')] property Married : Boolean read fMarried write fMarried; property WorkingTime : TWorkingTime read fWorkingTime write fWorkingTime; property HireDate : TDateTime read fHireDate write fHireDate; //[TCommentProperty('Possible values = usAtOffice, usAtHome or usOnVacation')] property Status : TUserStatus read fStatus write fStatus; //property LastConnections : TConnectionArray read fLastConnections write fLastConnections; property Observations : string read fObservations write fObservations; property LevelPrivilege : TLevelPrivilege read fLevelPrivilege write fLevelPrivilege; property Options : TOptions read fOptions write fOptions; property Groups : TGroupList read fGroups write fGroups; end; TUserList = TObjectList<TUser>; { TForm1 } TForm1 = class(TForm) btnFromJson: TButton; btnToJson: TButton; Memo1: TMemo; procedure btnFromJsonClick(Sender: TObject); procedure btnToJsonClick(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); private public end; var serializer : TJsonSerializer; User : TUser; UserList : TUserList; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.btnToJsonClick(Sender: TObject); begin Memo1.Text := serializer.ObjectToJson(User,True); btnFromJson.Enabled := True; end; procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin User.Free; serializer.Free; end; procedure TForm1.btnFromJsonClick(Sender: TObject); var newuser : TUser; begin newuser := TUser.Create; try newuser := serializer.JsonToObject(newuser,Memo1.Text) as TUser; Memo1.Lines.Add('NewUser:'); Memo1.Lines.Add(serializer.ObjectToJson(newuser)); finally newuser.Free; end; end; procedure TForm1.FormCreate(Sender: TObject); var lastcon : TConnectionInfo; group : TGroup; begin serializer := TJsonSerializer.Create(TSerializeLevel.slPublishedProperty); user := TUser.Create; user.Id := 77; user.Name := 'Joe'; user.Surname := 'Smith'; user.Age := 30; user.Married := True; user.Address := 'Sunset st. 2'; user.Options.Option1 := 1; user.Options.Option2 := 'good'; user.Options.AllowGroups := gtExternal; user.Balance := 99.9; user.HireDate := Now(); user.LevelPrivilege := [1,2,3,4]; user.WorkingTime.Name:= 'WeekConfig'; user.WorkingTime.WorkDays := DEF_WORKDAYS; user.WorkingTime.FreeDays := DEF_WEEKEND; user.Observations := 'Good aptitude'; user.Status := TUserStatus.usOnVacation; //lastcon.IP := '127.0.0.1'; //lastcon.ConnectionDate := Now(); //User.LastConnections := [lastcon]; //lastcon.IP := '192.0.0.1'; //lastcon.ConnectionDate := Now(); //User.LastConnections := User.LastConnections + [lastcon]; group := TGroup.Create; group.Id := 1; group.GType := gtInternal; user.Groups.Add(group); group := TGroup.Create; group.Id := 2; group.GType := gtExternal; user.Groups.Add(group); end; { TUser } constructor TUser.Create; begin fOptions := TOptions.Create; fWorkingTime := TWorkingTime.Create; fGroups := TGroupList.Create(True); end; destructor TUser.Destroy; begin fOptions.Free; fWorkingTime.Free; fGroups.Free; inherited; end; end.
unit FlashUtils; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "View" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/Common/FlashUtils.pas" // Начат: 29.01.2009 15:41 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<UtilityPack::Class>> F1 Core::Common::View::Common::FlashUtils // // Утилиты для работы с Flash-схемами // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses Controls, vtShockwaveFlashEx ; function NsCanMakeFlashActiveX: Boolean; {* Проверяет - возможно ли создать компонент для показа flash-ролика } function NsMakeFlashActiveX(aParent: TWinControl; aForSplash: Boolean; out aFlash: TvtShockwaveFlashEx): Boolean; {* Создаёт компонент для показа flash-ролика } {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} uses SysUtils, ComObj ; // unit methods function NsCanMakeFlashActiveX: Boolean; //#UC START# *4981A569031D_4981A3DC007E_var* var l_Flash: TvtShockwaveFlashEx; //#UC END# *4981A569031D_4981A3DC007E_var* begin //#UC START# *4981A569031D_4981A3DC007E_impl* Result := nsMakeFlashActiveX(nil, false, l_Flash); FreeAndNil(l_Flash); //#UC END# *4981A569031D_4981A3DC007E_impl* end;//NsCanMakeFlashActiveX function NsMakeFlashActiveX(aParent: TWinControl; aForSplash: Boolean; out aFlash: TvtShockwaveFlashEx): Boolean; //#UC START# *4981A58A0168_4981A3DC007E_var* //#UC END# *4981A58A0168_4981A3DC007E_var* begin //#UC START# *4981A58A0168_4981A3DC007E_impl* aFlash := nil; try aFlash := TvtShockwaveFlashEx.Create(aParent); // Работаем с flash только если поддерживается загрузка из потока // (<K> - 108626065): aFlash.Menu := False; if aFlash.IsLoadFromStreamSupported then with aFlash do begin Width := 2; Height := 2; Parent := aParent; Align := alClient; if not aForSplash then begin NeedDropAlignOnLoad := True; ScaleMode := 3; // NoScale AlignMode := 15{5}; // LTRB{LeftTop} (* http://www.delphiflash.com/using-tshockwaveflash/tshockwaveflash-properties#a2 AlignMode Integer value from range 0..15. This is the same as SAlign. 0 - no align, 1 - L, 2 - R, 3 - LR, 4 - T, 5 - LT, 6 - TR, 7 - LTR, 8 - B, 9 - LB, 10 - RB, 11 - LRB, 12 - TB, 13 - LTB, 14 - TRB, 15 - LTRB. *) end;//aForSplash end//with aFlash do else FreeAndNil(aFlash); except on EOleSysError do FreeAndNil(aFlash); end;//try..except Result := aFlash <> nil; //#UC END# *4981A58A0168_4981A3DC007E_impl* end;//NsMakeFlashActiveX {$IfEnd} //not Admin AND not Monitorings end.
unit DSONTestSuites; interface uses DUnitX.TestFramework, DSON; type DSONTestsBase = class(TObject) strict protected FDSONObject: IDSONObject; FDateTime: TDateTime; procedure BuildDSONObject; end; [TestFixture] BuilderTests = class(DSONTestsBase) public [Setup] procedure Setup; [Test] procedure BuildsValueNames; [Test] procedure BuildsValueKinds; [Test] procedure BuildsSimpleValues; [Test] procedure BuildsArrayValues; [Test] procedure BuildsObjectValues; end; [TestFixture] ReaderTests = class(DSONTestsBase) public [Setup] procedure Setup; [Test] procedure ReadsDSON; end; [TestFixture] BinaryWriterTests = class(DSONTestsBase) public [Setup] procedure Setup; [Test] procedure WritesNumerics; [Test] procedure WritesStrings; [Test] procedure WritesArrays; [Test] procedure WritesNil; [Test] procedure WritesBooleans; [Test] procedure WritesDates; [Test] procedure WritesGUIDs; end; [TestFixture] JSONWriterTests = class(DSONTestsBase) public [Setup] procedure Setup; [Test] procedure WritesArrays; [Test] procedure WritesBooleans; [Test] procedure WritesDates; [Test] procedure WritesGUIDs; [Test] procedure WritesNil; [Test] procedure WritesNumerics; [Test] procedure WritesStrings; end; implementation uses System.SysUtils, System.Rtti, System.DateUtils, System.Classes; {BuilderTests} procedure BuilderTests.BuildsArrayValues; begin // Array of integer Assert.IsTrue(Supports(FDSONObject.Pairs[14].Value, IDSONArray)); with FDSONObject.Pairs[14].Value as IDSONArray do begin Assert.AreEqual(5, Length(Values)); Assert.AreEqual(1, (Values[0] as IDSONSimple).Value.AsInteger); Assert.AreEqual(2, (Values[1] as IDSONSimple).Value.AsInteger); Assert.AreEqual(3, (Values[2] as IDSONSimple).Value.AsInteger); Assert.AreEqual(4, (Values[3] as IDSONSimple).Value.AsInteger); Assert.AreEqual(5, (Values[4] as IDSONSimple).Value.AsInteger); end; // Array of array with FDSONObject.Pairs[15].Value as IDSONArray do begin Assert.AreEqual(2, Length(Values)); Assert.IsTrue(Supports(Values[0], IDSONArray)); Assert.IsTrue(Supports(Values[1], IDSONArray)); end; with (FDSONObject.Pairs[15].Value as IDSONArray).Values[0] as IDSONArray do begin Assert.AreEqual(5, Length(Values)); Assert.AreEqual(1, (Values[0] as IDSONSimple).Value.AsInteger); Assert.AreEqual(2, (Values[1] as IDSONSimple).Value.AsInteger); Assert.AreEqual(3, (Values[2] as IDSONSimple).Value.AsInteger); Assert.AreEqual(4, (Values[3] as IDSONSimple).Value.AsInteger); Assert.AreEqual(5, (Values[4] as IDSONSimple).Value.AsInteger); end; with (FDSONObject.Pairs[15].Value as IDSONArray).Values[1] as IDSONArray do begin Assert.AreEqual(3, Length(Values)); Assert.AreEqual('red', (Values[0] as IDSONSimple).Value.AsString); Assert.AreEqual('green', (Values[1] as IDSONSimple).Value.AsString); Assert.AreEqual('blue', (Values[2] as IDSONSimple).Value.AsString); end; // Array of object with FDSONObject.Pairs[16].Value as IDSONArray do begin Assert.AreEqual(2, Length(Values)); Assert.IsTrue(Supports(Values[0], IDSONObject)); Assert.IsTrue(Supports(Values[1], IDSONObject)); end; with (FDSONObject.Pairs[16].Value as IDSONArray).Values[0] as IDSONObject do begin Assert.AreEqual('name', Pairs[0].Name); Assert.AreEqual('John Doe', (Pairs[0].Value as IDSONSimple).Value.ToString); Assert.AreEqual('age', Pairs[1].Name); Assert.AreEqual(34, (Pairs[1].Value as IDSONSimple).Value.AsInteger); end; with (FDSONObject.Pairs[16].Value as IDSONArray).Values[1] as IDSONObject do begin Assert.AreEqual('name', Pairs[0].Name); Assert.AreEqual('Jane Doe', (Pairs[0].Value as IDSONSimple).Value.ToString); Assert.AreEqual('age', Pairs[1].Name); Assert.AreEqual(32, (Pairs[1].Value as IDSONSimple).Value.AsInteger); end; // Array of array of array with FDSONObject.Pairs[18].Value as IDSONArray do begin Assert.AreEqual(2, Length(Values)); end; with (FDSONObject.Pairs[18].Value as IDSONArray).Values[0] as IDSONArray do begin Assert.AreEqual(2, Length(Values)); with Values[0] as IDSONArray do begin Assert.AreEqual(2, Length(Values)); Assert.AreEqual(1, (Values[0] as IDSONSimple).Value.AsInteger); Assert.AreEqual(2, (Values[1] as IDSONSimple).Value.AsInteger); end; with Values[1] as IDSONArray do begin Assert.AreEqual(2, Length(Values)); Assert.AreEqual(3, (Values[0] as IDSONSimple).Value.AsInteger); Assert.AreEqual(4, (Values[1] as IDSONSimple).Value.AsInteger); end; end; with (FDSONObject.Pairs[18].Value as IDSONArray).Values[1] as IDSONArray do begin Assert.AreEqual(2, Length(Values)); with Values[0] as IDSONArray do begin Assert.AreEqual(2, Length(Values)); Assert.AreEqual(5, (Values[0] as IDSONSimple).Value.AsInteger); Assert.AreEqual(6, (Values[1] as IDSONSimple).Value.AsInteger); end; with Values[1] as IDSONArray do begin Assert.AreEqual(2, Length(Values)); Assert.AreEqual(7, (Values[0] as IDSONSimple).Value.AsInteger); Assert.AreEqual(8, (Values[1] as IDSONSimple).Value.AsInteger); end; end; end; procedure BuilderTests.BuildsObjectValues; begin // Object with FDSONObject.Pairs[17].Value as IDSONObject do begin Assert.AreEqual(2, Pairs.Count); Assert.AreEqual('widget', Pairs[0].Name); Assert.AreEqual('total', Pairs[1].Name); Assert.AreEqual(305.75, (Pairs[1].Value as IDSONSimple).Value.AsExtended, 0.01); end; with (FDSONObject.Pairs[17].Value as IDSONObject).Pairs[0].Value as IDSONObject do begin Assert.AreEqual(2, Pairs.Count); Assert.AreEqual('materials', Pairs[0].Name); Assert.AreEqual(125.75, (Pairs[0].Value as IDSONSimple).Value.AsExtended, 0.01); Assert.AreEqual('labor', Pairs[1].Name); Assert.AreEqual(180.00, (Pairs[1].Value as IDSONSimple).Value.AsExtended, 0.01); end; end; procedure BuilderTests.BuildsValueKinds; begin Assert.AreEqual(dkGUID, FDSONObject.Pairs[0].Value.Kind); Assert.AreEqual(dkByte, FDSONObject.Pairs[1].Value.Kind); Assert.AreEqual(dkInt16, FDSONObject.Pairs[2].Value.Kind); Assert.AreEqual(dkInt32, FDSONObject.Pairs[3].Value.Kind); Assert.AreEqual(dkInt64, FDSONObject.Pairs[4].Value.Kind); Assert.AreEqual(dkString, FDSONObject.Pairs[5].Value.Kind); Assert.AreEqual(dkSingle, FDSONObject.Pairs[6].Value.Kind); Assert.AreEqual(dkDouble, FDSONObject.Pairs[7].Value.Kind); Assert.AreEqual(dkExtended, FDSONObject.Pairs[8].Value.Kind); Assert.AreEqual(dkChar, FDSONObject.Pairs[9].Value.Kind); Assert.AreEqual(dkTrue, FDSONObject.Pairs[10].Value.Kind); Assert.AreEqual(dkFalse, FDSONObject.Pairs[11].Value.Kind); Assert.AreEqual(dkDateTime, FDSONObject.Pairs[12].Value.Kind); Assert.AreEqual(dkNil, FDSONObject.Pairs[13].Value.Kind); Assert.AreEqual(dkArray, FDSONObject.Pairs[14].Value.Kind); Assert.AreEqual(dkArray, FDSONObject.Pairs[15].Value.Kind); Assert.AreEqual(dkArray, FDSONObject.Pairs[16].Value.Kind); Assert.AreEqual(dkObject, FDSONObject.Pairs[17].Value.Kind); Assert.AreEqual(dkArray, FDSONObject.Pairs[18].Value.Kind); end; procedure BuilderTests.BuildsValueNames; begin Assert.AreEqual('dkGUID', FDSONObject.Pairs[0].Name); Assert.AreEqual('dkByte', FDSONObject.Pairs[1].Name); Assert.AreEqual('dkInt16', FDSONObject.Pairs[2].Name); Assert.AreEqual('dkInt32', FDSONObject.Pairs[3].Name); Assert.AreEqual('dkInt64', FDSONObject.Pairs[4].Name); Assert.AreEqual('dkString', FDSONObject.Pairs[5].Name); Assert.AreEqual('dkSingle', FDSONObject.Pairs[6].Name); Assert.AreEqual('dkDouble', FDSONObject.Pairs[7].Name); Assert.AreEqual('dkExtended', FDSONObject.Pairs[8].Name); Assert.AreEqual('dkChar', FDSONObject.Pairs[9].Name); Assert.AreEqual('dkTrue', FDSONObject.Pairs[10].Name); Assert.AreEqual('dkFalse', FDSONObject.Pairs[11].Name); Assert.AreEqual('dkDateTime', FDSONObject.Pairs[12].Name); Assert.AreEqual('dkNil', FDSONObject.Pairs[13].Name); Assert.AreEqual('dkArrayOfInteger', FDSONObject.Pairs[14].Name); Assert.AreEqual('dkArrayOfArray', FDSONObject.Pairs[15].Name); Assert.AreEqual('dkArrayOfObjects', FDSONObject.Pairs[16].Name); Assert.AreEqual('dkObject', FDSONObject.Pairs[17].Name); Assert.AreEqual('dkArrayOfArrayOfArray', FDSONObject.Pairs[18].Name); end; procedure BuilderTests.BuildsSimpleValues; begin // Simple types Assert.AreEqual('{11111111-2222-3333-4444-555555555555}', (FDSONObject.Pairs[0].Value as IDSONSimple).Value.ToString); Assert.AreEqual('65', (FDSONObject.Pairs[1].Value as IDSONSimple).Value.ToString); Assert.AreEqual('16', (FDSONObject.Pairs[2].Value as IDSONSimple).Value.ToString); Assert.AreEqual('32', (FDSONObject.Pairs[3].Value as IDSONSimple).Value.ToString); Assert.AreEqual('64', (FDSONObject.Pairs[4].Value as IDSONSimple).Value.ToString); Assert.AreEqual('The quick brown fox jumped over the lazy dogs', (FDSONObject.Pairs[5].Value as IDSONSimple) .Value.ToString); Assert.AreEqual(1.1, (FDSONObject.Pairs[6].Value as IDSONSimple).Value.AsExtended, 0.01); Assert.AreEqual(2.2, (FDSONObject.Pairs[7].Value as IDSONSimple).Value.AsExtended, 0.01); Assert.AreEqual(3.3, (FDSONObject.Pairs[8].Value as IDSONSimple).Value.AsExtended, 0.01); Assert.AreEqual('Z', (FDSONObject.Pairs[9].Value as IDSONSimple).Value.ToString); Assert.AreEqual(True, (FDSONObject.Pairs[10].Value as IDSONSimple).Value.AsBoolean); Assert.AreEqual(False, (FDSONObject.Pairs[11].Value as IDSONSimple).Value.AsBoolean); Assert.AreEqual(FDateTime, (FDSONObject.Pairs[12].Value as IDSONSimple).Value.AsType<TDateTime>); Assert.IsTrue((FDSONObject.Pairs[13].Value as IDSONSimple).Value.IsEmpty); end; procedure BuilderTests.Setup; begin FDateTime := Now; BuildDSONObject; end; procedure DSONTestsBase.BuildDSONObject; var Builder: IDSONBuilder; GUID: TGUID; begin GUID := TGUID.Create('{11111111-2222-3333-4444-555555555555}'); Builder := DSON.Builder; Builder.StartObject; Builder.AddPropertyName('dkGUID').AddValue(GUID).AddPropertyName('dkByte').AddValue(Byte(65)) .AddPropertyName('dkInt16').AddValue(Int16(16)).AddPropertyName('dkInt32').AddValue(Int32(32)) .AddPropertyName('dkInt64').AddValue(Int64(64)).AddPropertyName('dkString') .AddValue('The quick brown fox jumped over the lazy dogs').AddPropertyName('dkSingle').AddValue(Single(1.1)) .AddPropertyName('dkDouble').AddValue(Double(2.2)).AddPropertyName('dkExtended').AddValue(Extended(3.3)) .AddPropertyName('dkChar').AddValue(Char('Z')).AddPropertyName('dkTrue').AddValue(True).AddPropertyName('dkFalse') .AddValue(False).AddPropertyName('dkDateTime').AddValue(FDateTime).AddPropertyName('dkNil') .AddNilValue.AddPropertyName('dkArrayOfInteger').StartArray.AddValue(1).AddValue(2).AddValue(3).AddValue(4) .AddValue(5).EndArray.AddPropertyName('dkArrayOfArray').StartArray.StartArray.AddValue(1).AddValue(2).AddValue(3) .AddValue(4).AddValue(5).EndArray.StartArray.AddValue('red').AddValue('green').AddValue('blue') .EndArray.EndArray.AddPropertyName('dkArrayOfObjects').StartArray.StartObject.AddPropertyName('name') .AddValue('John Doe').AddPropertyName('age').AddValue(34).EndObject.StartObject.AddPropertyName('name') .AddValue('Jane Doe').AddPropertyName('age').AddValue(32).EndObject.EndArray.AddPropertyName('dkObject') .StartObject.AddPropertyName('widget').StartObject.AddPropertyName('materials').AddValue(125.75) .AddPropertyName('labor').AddValue(180.00).EndObject.AddPropertyName('total').AddValue(305.75) .EndObject.AddPropertyName('dkArrayOfArrayOfArray').StartArray.StartArray.StartArray.AddValue(1).AddValue(2) .EndArray.StartArray.AddValue(3).AddValue(4).EndArray.EndArray.StartArray.StartArray.AddValue(5).AddValue(6) .EndArray.StartArray.AddValue(7).AddValue(8).EndArray.EndArray.EndArray.EndObject; FDSONObject := Builder.DSONObject; end; { ReaderTests } procedure ReaderTests.ReadsDSON; var BS: TBytesStream; Obj: IDSONObject; procedure CheckSimplePair(const APair: IDSONPair; const AKind: TDSONKind; const AName, AValue: string); begin Assert.AreEqual(AName,APair.Name); Assert.AreEqual(AKind,APair.Value.Kind); Assert.AreEqual(AValue,(APair.Value as IDSONSimple).Value.ToString); end; begin BS := TBytesStream.Create; try DSON.BinaryWriter.WriteObjectToStream(FDSONObject,BS); BS.Position := 0; Assert.WillNotRaiseAny( procedure begin Obj := DSON.Reader.ReadObject(BS); end ); CheckSimplePair(Obj.Pairs[0],dkGUID,'dkGUID','{11111111-2222-3333-4444-555555555555}'); CheckSimplePair(Obj.Pairs[1],dkByte,'dkByte','65'); CheckSimplePair(Obj.Pairs[2],dkInt16,'dkInt16','16'); CheckSimplePair(Obj.Pairs[3],dkInt32,'dkInt32','32'); CheckSimplePair(Obj.Pairs[4],dkInt64,'dkInt64','64'); CheckSimplePair(Obj.Pairs[5],dkString,'dkString','The quick brown fox jumped over the lazy dogs'); // Single doesn't have enough precision to come out cleanly as a string. Testing individually // instead of in CheckSimplePair() Assert.AreEqual('dkSingle',Obj.Pairs[6].Name); Assert.AreEqual(dkSingle,Obj.Pairs[6].Value.Kind); Assert.AreEqual(Single(1.1),(Obj.Pairs[6].Value as IDSONSimple).Value.AsType<Single>,0.01); CheckSimplePair(Obj.Pairs[7],dkDouble,'dkDouble','2.2'); CheckSimplePair(Obj.Pairs[8],dkExtended,'dkExtended','3.3'); CheckSimplePair(Obj.Pairs[9],dkChar,'dkChar','Z'); CheckSimplePair(Obj.Pairs[10],dkTrue,'dkTrue','True'); CheckSimplePair(Obj.Pairs[11],dkFalse,'dkFalse','False'); CheckSimplePair(Obj.Pairs[12],dkDateTime,'dkDateTime',TValue.From(FDateTime).ToString); CheckSimplePair(Obj.Pairs[13],dkNil,'dkNil','(empty)'); // Array of integer Assert.IsTrue(Supports(FDSONObject.Pairs[14].Value, IDSONArray)); with FDSONObject.Pairs[14].Value as IDSONArray do begin Assert.AreEqual(5, Length(Values)); Assert.AreEqual(1, (Values[0] as IDSONSimple).Value.AsInteger); Assert.AreEqual(2, (Values[1] as IDSONSimple).Value.AsInteger); Assert.AreEqual(3, (Values[2] as IDSONSimple).Value.AsInteger); Assert.AreEqual(4, (Values[3] as IDSONSimple).Value.AsInteger); Assert.AreEqual(5, (Values[4] as IDSONSimple).Value.AsInteger); end; // Array of array with FDSONObject.Pairs[15].Value as IDSONArray do begin Assert.AreEqual(2, Length(Values)); Assert.IsTrue(Supports(Values[0], IDSONArray)); Assert.IsTrue(Supports(Values[1], IDSONArray)); end; with (FDSONObject.Pairs[15].Value as IDSONArray).Values[0] as IDSONArray do begin Assert.AreEqual(5, Length(Values)); Assert.AreEqual(1, (Values[0] as IDSONSimple).Value.AsInteger); Assert.AreEqual(2, (Values[1] as IDSONSimple).Value.AsInteger); Assert.AreEqual(3, (Values[2] as IDSONSimple).Value.AsInteger); Assert.AreEqual(4, (Values[3] as IDSONSimple).Value.AsInteger); Assert.AreEqual(5, (Values[4] as IDSONSimple).Value.AsInteger); end; with (FDSONObject.Pairs[15].Value as IDSONArray).Values[1] as IDSONArray do begin Assert.AreEqual(3, Length(Values)); Assert.AreEqual('red', (Values[0] as IDSONSimple).Value.AsString); Assert.AreEqual('green', (Values[1] as IDSONSimple).Value.AsString); Assert.AreEqual('blue', (Values[2] as IDSONSimple).Value.AsString); end; // Array of object with FDSONObject.Pairs[16].Value as IDSONArray do begin Assert.AreEqual(2, Length(Values)); Assert.IsTrue(Supports(Values[0], IDSONObject)); Assert.IsTrue(Supports(Values[1], IDSONObject)); end; with (FDSONObject.Pairs[16].Value as IDSONArray).Values[0] as IDSONObject do begin Assert.AreEqual('name', Pairs[0].Name); Assert.AreEqual('John Doe', (Pairs[0].Value as IDSONSimple).Value.ToString); Assert.AreEqual('age', Pairs[1].Name); Assert.AreEqual(34, (Pairs[1].Value as IDSONSimple).Value.AsInteger); end; with (FDSONObject.Pairs[16].Value as IDSONArray).Values[1] as IDSONObject do begin Assert.AreEqual('name', Pairs[0].Name); Assert.AreEqual('Jane Doe', (Pairs[0].Value as IDSONSimple).Value.ToString); Assert.AreEqual('age', Pairs[1].Name); Assert.AreEqual(32, (Pairs[1].Value as IDSONSimple).Value.AsInteger); end; // Array of array of array with FDSONObject.Pairs[18].Value as IDSONArray do begin Assert.AreEqual(2, Length(Values)); end; with (FDSONObject.Pairs[18].Value as IDSONArray).Values[0] as IDSONArray do begin Assert.AreEqual(2, Length(Values)); with Values[0] as IDSONArray do begin Assert.AreEqual(2, Length(Values)); Assert.AreEqual(1, (Values[0] as IDSONSimple).Value.AsInteger); Assert.AreEqual(2, (Values[1] as IDSONSimple).Value.AsInteger); end; with Values[1] as IDSONArray do begin Assert.AreEqual(2, Length(Values)); Assert.AreEqual(3, (Values[0] as IDSONSimple).Value.AsInteger); Assert.AreEqual(4, (Values[1] as IDSONSimple).Value.AsInteger); end; end; with (FDSONObject.Pairs[18].Value as IDSONArray).Values[1] as IDSONArray do begin Assert.AreEqual(2, Length(Values)); with Values[0] as IDSONArray do begin Assert.AreEqual(2, Length(Values)); Assert.AreEqual(5, (Values[0] as IDSONSimple).Value.AsInteger); Assert.AreEqual(6, (Values[1] as IDSONSimple).Value.AsInteger); end; with Values[1] as IDSONArray do begin Assert.AreEqual(2, Length(Values)); Assert.AreEqual(7, (Values[0] as IDSONSimple).Value.AsInteger); Assert.AreEqual(8, (Values[1] as IDSONSimple).Value.AsInteger); end; end; finally BS.Free; end; end; procedure ReaderTests.Setup; begin FDateTime := Now; BuildDSONObject; end; { BinaryWriterTests } procedure BinaryWriterTests.Setup; begin FDateTime := Now; BuildDSONObject; end; procedure BinaryWriterTests.WritesArrays; var Bytes: TBytes; Obj: IDSONObject; begin { dmStartObject 1 dmStartPair 1 Name length 4 Name string 4 dmStartArray 1 dmByte 1 1 1 dmByte 1 2 1 dmByte 1 3 1 dmEndArray 1 dmEndPair 1 dmEndObject 1 } // 20 bytes Obj := DSON.Builder .StartObject .AddPropertyName('prop') .StartArray .AddValue(Byte(1)) .AddValue(Byte(2)) .AddValue(Byte(3)) .EndArray .EndObject .DSONObject; Bytes := DSON.BinaryWriter.WriteObject(Obj); Assert.AreEqual(20,Length(Bytes)); Assert.AreEqual(dmStartObject, TDSONMarker(Bytes[0])); Assert.AreEqual(dmStartPair, TDSONMarker(Bytes[1])); Assert.AreEqual(dmStartArray,TDSONMarker(Bytes[10])); Assert.AreEqual(dmByte,TDSONMarker(Bytes[11])); Assert.AreEqual(Byte(1),Bytes[12]); Assert.AreEqual(dmByte,TDSONMarker(Bytes[13])); Assert.AreEqual(Byte(2),Bytes[14]); Assert.AreEqual(dmByte,TDSONMarker(Bytes[15])); Assert.AreEqual(Byte(3),Bytes[16]); Assert.AreEqual(dmEndArray, TDSONMarker(Bytes[17])); Assert.AreEqual(dmEndPair, TDSONMarker(Bytes[18])); Assert.AreEqual(dmEndObject, TDSONMarker(Bytes[19])); end; procedure BinaryWriterTests.WritesBooleans; var Bytes: TBytes; Obj: IDSONObject; begin { dmStartObject 1 dmStartPair 1 Name length 4 Name string 4 dmTrue 1 Value [Empty for Booleans] dmEndPair 1 dmStartPair 1 Name length 4 Name string 5 dmFalse 1 Value [Empty for Booleans] dmEndPair 1 dmEndObject 1 } // 25 bytes Obj := DSON.Builder .StartObject .AddPropertyName('prop') .AddValue(True) .AddPropertyName('prop2') .AddValue(False) .EndObject.DSONObject; Bytes := DSON.BinaryWriter.WriteObject(Obj); Assert.AreEqual(25,Length(Bytes)); Assert.AreEqual(dmTrue,TDSONMarker(Bytes[10])); Assert.AreEqual(dmFalse,TDSONMarker(Bytes[22])); end; procedure BinaryWriterTests.WritesDates; var Bytes: TBytes; Obj: IDSONObject; begin { dmStartObject 1 dmStartPair 1 Name length 4 Name string 4 dmDateTime 1 Value 8 byte integer (Unix date) dmEndPair 1 dmEndObject 1 } // 21 bytes Obj := DSON.Builder .StartObject .AddPropertyName('prop') .AddValue(Now()) .EndObject.DSONObject; Bytes := DSON.BinaryWriter.WriteObject(Obj); Assert.AreEqual(21,Length(Bytes)); end; procedure BinaryWriterTests.WritesGUIDs; var Bytes: TBytes; Obj: IDSONObject; begin { dmStartObject 1 dmStartPair 1 Name length 4 Name string 4 dmDateTime 1 Value 16 byte GUID dmEndPair 1 dmEndObject 1 } // 29 bytes Obj := DSON.Builder .StartObject .AddPropertyName('prop') .AddValue(TGUID.NewGuid) .EndObject.DSONObject; Bytes := DSON.BinaryWriter.WriteObject(Obj); Assert.AreEqual(29,Length(Bytes)); Assert.AreEqual(dmGUID,TDSONMarker(Bytes[10])); end; procedure BinaryWriterTests.WritesNil; var Bytes: TBytes; Obj: IDSONObject; begin { dmStartObject 1 dmStartPair 1 Name length 4 Name string 4 dmNil 1 Value [Empty for Nil] dmEndPair 1 dmEndObject 1 } // 13 bytes Obj := DSON.Builder .StartObject .AddPropertyName('prop') .AddNilValue .EndObject.DSONObject; Bytes := DSON.BinaryWriter.WriteObject(Obj); Assert.AreEqual(13,Length(Bytes)); Assert.AreEqual(dmNil,TDSONMarker(Bytes[10])); end; procedure BinaryWriterTests.WritesNumerics; var Bytes: TBytes; Obj: IDSONObject; begin { dmStartObject 1 dmStartPair 1 Name length 4 Name string 4 dm[Value] 1 Value Byte: 1, Int16: 2, Int32: 4, Int64: 8, Single: 8, Double: 16, Extended: 16 (stored as a double) dmEndPair 1 dmEndObject 1 } // Byte Obj := DSON.Builder.StartObject.AddPropertyName('prop').AddValue(Byte(65)).EndObject.DSONObject; Bytes := DSON.BinaryWriter.WriteObject(Obj); Assert.AreEqual(14,Length(Bytes)); Assert.AreEqual(dmStartObject, TDSONMarker(Bytes[0])); Assert.AreEqual(dmStartPair, TDSONMarker(Bytes[1])); Assert.AreEqual(dmByte, TDSONMarker(Bytes[10])); Assert.AreEqual(dmEndPair, TDSONMarker(Bytes[12])); Assert.AreEqual(dmEndObject, TDSONMarker(Bytes[13])); // Int16 Obj := DSON.Builder.StartObject.AddPropertyName('prop').AddValue(Word(65)).EndObject.DSONObject; Bytes := DSON.BinaryWriter.WriteObject(Obj); Assert.AreEqual(15,Length(Bytes)); Assert.AreEqual(dmInt16, TDSONMarker(Bytes[10])); // Int32 Obj := DSON.Builder.StartObject.AddPropertyName('prop').AddValue(Integer(65)).EndObject.DSONObject; Bytes := DSON.BinaryWriter.WriteObject(Obj); Assert.AreEqual(17,Length(Bytes)); Assert.AreEqual(dmInt32, TDSONMarker(Bytes[10])); // Int64 Obj := DSON.Builder.StartObject.AddPropertyName('prop').AddValue(Int64(65)).EndObject.DSONObject; Bytes := DSON.BinaryWriter.WriteObject(Obj); Assert.AreEqual(21,Length(Bytes)); Assert.AreEqual(dmInt64, TDSONMarker(Bytes[10])); // Single Obj := DSON.Builder.StartObject.AddPropertyName('prop').AddValue(Single(65.1)).EndObject.DSONObject; Bytes := DSON.BinaryWriter.WriteObject(Obj); Assert.AreEqual(17,Length(Bytes)); Assert.AreEqual(dmSingle, TDSONMarker(Bytes[10])); // Double Obj := DSON.Builder.StartObject.AddPropertyName('prop').AddValue(Double(65.1)).EndObject.DSONObject; Bytes := DSON.BinaryWriter.WriteObject(Obj); Assert.AreEqual(21,Length(Bytes)); Assert.AreEqual(dmDouble, TDSONMarker(Bytes[10])); // Extended Obj := DSON.Builder.StartObject.AddPropertyName('prop').AddValue(Extended(65.1)).EndObject.DSONObject; Bytes := DSON.BinaryWriter.WriteObject(Obj); Assert.AreEqual(21,Length(Bytes)); Assert.AreEqual(dmExtended, TDSONMarker(Bytes[10])); end; procedure BinaryWriterTests.WritesStrings; var Bytes: TBytes; Obj: IDSONObject; begin { dmStartObject 1 dmStartPair 1 Name length 4 Name string 4 dm[Value] 1 Value length 4 Value "Hello World" 11 dmEndPair 1 dmEndObject 1 } // 28 bytes Obj := DSON.Builder.StartObject.AddPropertyName('prop').AddValue('Hello World').EndObject.DSONObject; Bytes := DSON.BinaryWriter.WriteObject(Obj); Assert.AreEqual(28,Length(Bytes)); Assert.AreEqual(dmStartObject, TDSONMarker(Bytes[0])); Assert.AreEqual(dmStartPair, TDSONMarker(Bytes[1])); Assert.AreEqual(dmString, TDSONMarker(Bytes[10])); Assert.AreEqual(dmEndPair, TDSONMarker(Bytes[26])); Assert.AreEqual(dmEndObject, TDSONMarker(Bytes[27])); end; { JSONWriterTests } procedure JSONWriterTests.Setup; begin FDateTime := Now; BuildDSONObject; end; procedure JSONWriterTests.WritesArrays; var ActualJSON: string; ExpectedJSON: string; Obj: IDSONObject; begin // Simple Array ExpectedJSON := '{"prop":[1,2,3]}'; Obj := DSON.Builder .StartObject .AddPropertyName('prop') .StartArray .AddValue(1) .AddValue(2) .AddValue(3) .EndArray .EndObject.DSONObject; ActualJSON := DSON.JSONWriter.WriteObject(Obj); Assert.AreEqual(ExpectedJSON, ActualJSON); // Array of arrays ExpectedJSON := '{"prop":[[1,2,3],[4,5,6]]}'; Obj := DSON.Builder .StartObject .AddPropertyName('prop') .StartArray .StartArray .AddValue(1) .AddValue(2) .AddValue(3) .EndArray .StartArray .AddValue(4) .AddValue(5) .AddValue(6) .EndArray .EndArray .EndObject.DSONObject; ActualJSON := DSON.JSONWriter.WriteObject(Obj); Assert.AreEqual(ExpectedJSON, ActualJSON); end; procedure JSONWriterTests.WritesBooleans; var ActualJSON: string; ExpectedJSON: string; Obj: IDSONObject; begin ExpectedJSON := '{"prop":true}'; Obj := DSON.Builder.StartObject.AddPropertyName('prop').AddValue(True).EndObject.DSONObject; ActualJSON := DSON.JSONWriter.WriteObject(Obj); Assert.AreEqual(ExpectedJSON, ActualJSON); end; procedure JSONWriterTests.WritesDates; var ActualJSON: string; ExpectedJSON: string; Obj: IDSONObject; begin ExpectedJSON := '{"prop":"' + DateToISO8601(FDateTime,False) + '"}'; Obj := DSON.Builder.StartObject.AddPropertyName('prop').AddValue(FDateTime).EndObject.DSONObject; ActualJSON := DSON.JSONWriter.WriteObject(Obj); Assert.AreEqual(ExpectedJSON, ActualJSON); end; procedure JSONWriterTests.WritesGUIDs; var ActualJSON: string; ExpectedJSON: string; Obj: IDSONObject; begin ExpectedJSON := '{"prop":"{11111111-2222-3333-4444-555555555555}"}'; Obj := DSON.Builder.StartObject.AddPropertyName('prop').AddValue(TGUID.Create('{11111111-2222-3333-4444-555555555555}')).EndObject.DSONObject; ActualJSON := DSON.JSONWriter.WriteObject(Obj); Assert.AreEqual(ExpectedJSON, ActualJSON); end; procedure JSONWriterTests.WritesNil; var ActualJSON: string; ExpectedJSON: string; Obj: IDSONObject; begin ExpectedJSON := '{"prop":null}'; Obj := DSON.Builder.StartObject.AddPropertyName('prop').AddNilValue.EndObject.DSONObject; ActualJSON := DSON.JSONWriter.WriteObject(Obj); Assert.AreEqual(ExpectedJSON, ActualJSON); end; procedure JSONWriterTests.WritesNumerics; var ActualJSON: string; ExpectedJSON: string; Obj: IDSONObject; begin // Byte ExpectedJSON := '{"prop":65}'; Obj := DSON.Builder.StartObject.AddPropertyName('prop').AddValue(Byte(65)).EndObject.DSONObject; ActualJSON := DSON.JSONWriter.WriteObject(Obj); Assert.AreEqual(ExpectedJSON, ActualJSON); // Int16 ExpectedJSON := '{"prop":16}'; Obj := DSON.Builder.StartObject.AddPropertyName('prop').AddValue(Int16(16)).EndObject.DSONObject; ActualJSON := DSON.JSONWriter.WriteObject(Obj); Assert.AreEqual(ExpectedJSON, ActualJSON); // Int32 ExpectedJSON := '{"prop":32}'; Obj := DSON.Builder.StartObject.AddPropertyName('prop').AddValue(Int32(32)).EndObject.DSONObject; ActualJSON := DSON.JSONWriter.WriteObject(Obj); Assert.AreEqual(ExpectedJSON, ActualJSON); // Int64 ExpectedJSON := '{"prop":64}'; Obj := DSON.Builder.StartObject.AddPropertyName('prop').AddValue(Int64(64)).EndObject.DSONObject; ActualJSON := DSON.JSONWriter.WriteObject(Obj); Assert.AreEqual(ExpectedJSON, ActualJSON); // Single ExpectedJSON := '{"prop":1.10000002384186}'; // Single type has terrible precision Obj := DSON.Builder.StartObject.AddPropertyName('prop').AddValue(Single(1.1)).EndObject.DSONObject; ActualJSON := DSON.JSONWriter.WriteObject(Obj); Assert.AreEqual(ExpectedJSON, ActualJSON); // Double ExpectedJSON := '{"prop":2.2}'; // Single type has terrible precision Obj := DSON.Builder.StartObject.AddPropertyName('prop').AddValue(Double(2.2)).EndObject.DSONObject; ActualJSON := DSON.JSONWriter.WriteObject(Obj); Assert.AreEqual(ExpectedJSON, ActualJSON); // Extended ExpectedJSON := '{"prop":3.3}'; Obj := DSON.Builder.StartObject.AddPropertyName('prop').AddValue(Extended(3.3)).EndObject.DSONObject; ActualJSON := DSON.JSONWriter.WriteObject(Obj); Assert.AreEqual(ExpectedJSON, ActualJSON); end; procedure JSONWriterTests.WritesStrings; var ActualJSON: string; ExpectedJSON: string; Obj: IDSONObject; begin ExpectedJSON := '{"prop":"The quick brown fox jumped over the lazy dogs"}'; Obj := DSON.Builder.StartObject.AddPropertyName('prop').AddValue('The quick brown fox jumped over the lazy dogs').EndObject.DSONObject; ActualJSON := DSON.JSONWriter.WriteObject(Obj); Assert.AreEqual(ExpectedJSON, ActualJSON); end; initialization TDUnitX.RegisterTestFixture(BuilderTests); TDUnitX.RegisterTestFixture(ReaderTests); TDUnitX.RegisterTestFixture(BinaryWriterTests); TDUnitX.RegisterTestFixture(JSONWriterTests); end.
unit Unit1; interface type IEat = interface end; TAnimal = class(TInterfacedObject) public procedure Run; virtual; abstract; end; TDog = class(TAnimal, IEat) procedure Run; override; procedure LookDog; end; TCat = class(TAnimal) public procedure Run; override; procedure CatchMouse; end; implementation { TDog } procedure TDog.LookDog; begin Writeln('狗看门'); end; procedure TDog.Run; begin Writeln('狗跑'); end; { TCat } procedure TCat.CatchMouse; begin Writeln('猫抓老鼠'); end; procedure TCat.Run; begin Writeln('猫在跑'); end; end.
unit np.buildData; interface uses classes, np.buffer; type PBuildData = ^TBuildData; TBuildData = record buf: BufferRef; function append(const Str : UTF8String) : PBuildData; overload; function appendOrdinal<T>(data:T) : PBuildData; function append(data:Pointer; dataLen: Cardinal) : PBuildData; overload; function append(const data: BufferRef) : PBuildData; overload; end; implementation { TBuildData } function TBuildData.append(const Str: UTF8String): PBuildData; begin if length(str) > 0 then begin optimized_append(buf,BufferRef.CreateWeakRef(@Str[1],Length(Str))); end; result := @self; end; function TBuildData.append(data: Pointer; dataLen: Cardinal): PBuildData; begin if dataLen > 0 then optimized_append(buf,BufferRef.CreateWeakRef(data,DataLen)); result := @self; end; function TBuildData.append(const data: BufferRef): PBuildData; begin optimized_append(buf,data); result := @self; end; function TBuildData.appendOrdinal<T>(data: T): PBuildData; begin optimized_append(buf,Buffer.pack<T>(data)); result := @self; end; end.
unit Autoreferat_InternalOperations_Controls; // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Autoreferat_InternalOperations_Controls.pas" // Стереотип: "VCMControls" // Элемент модели: "InternalOperations" MUID: (4A8ECFED02D8) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings)} uses l3IntfUses {$If NOT Defined(NoVCM)} , vcmInterfaces {$IfEnd} // NOT Defined(NoVCM) {$If NOT Defined(NoVCM)} , vcmExternalInterfaces {$IfEnd} // NOT Defined(NoVCM) ; type Op_DateInterval_OpenInt = {final} class {* Класс для вызова операции DateInterval.OpenInt } public class function Call(const aTarget: IvcmEntity): Boolean; overload; {* Вызов операции DateInterval.OpenInt у сущности } class function Call(const aTarget: IvcmAggregate): Boolean; overload; {* Вызов операции DateInterval.OpenInt у агрегации } class function Call(const aTarget: IvcmEntityForm): Boolean; overload; {* Вызов операции DateInterval.OpenInt у формы } class function Call(const aTarget: IvcmContainer): Boolean; overload; {* Вызов операции DateInterval.OpenInt у контейнера } end;//Op_DateInterval_OpenInt const en_DateInterval = 'DateInterval'; en_capDateInterval = ''; op_OpenInt = 'OpenInt'; op_capOpenInt = ''; en_NewsThemes = 'NewsThemes'; en_capNewsThemes = ''; op_SelectCurrent = 'SelectCurrent'; op_capSelectCurrent = ''; op_Open = 'Open'; op_capOpen = ''; var opcode_DateInterval_OpenInt: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_NewsThemes_SelectCurrent: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_DateInterval_Open: TvcmOPID = (rEnID : -1; rOpID : -1); {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings)} uses l3ImplUses {$If NOT Defined(NoVCM)} , vcmOperationsForRegister {$IfEnd} // NOT Defined(NoVCM) {$If NOT Defined(NoVCM)} , vcmOperationStatesForRegister {$IfEnd} // NOT Defined(NoVCM) , l3Base {$If NOT Defined(NoVCM)} , vcmBase {$IfEnd} // NOT Defined(NoVCM) ; class function Op_DateInterval_OpenInt.Call(const aTarget: IvcmEntity): Boolean; {* Вызов операции DateInterval.OpenInt у сущности } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := vcmParams; aTarget.Operation(opcode_DateInterval_OpenInt, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_DateInterval_OpenInt.Call class function Op_DateInterval_OpenInt.Call(const aTarget: IvcmAggregate): Boolean; {* Вызов операции DateInterval.OpenInt у агрегации } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := vcmParams; aTarget.Operation(opcode_DateInterval_OpenInt, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_DateInterval_OpenInt.Call class function Op_DateInterval_OpenInt.Call(const aTarget: IvcmEntityForm): Boolean; {* Вызов операции DateInterval.OpenInt у формы } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.Entity); end;//Op_DateInterval_OpenInt.Call class function Op_DateInterval_OpenInt.Call(const aTarget: IvcmContainer): Boolean; {* Вызов операции DateInterval.OpenInt у контейнера } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.AsForm); end;//Op_DateInterval_OpenInt.Call initialization with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_DateInterval, op_OpenInt, en_capDateInterval, op_capOpenInt, True, False, opcode_DateInterval_OpenInt)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_NewsThemes, op_SelectCurrent, en_capNewsThemes, op_capSelectCurrent, False, False, opcode_NewsThemes_SelectCurrent)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_DateInterval, op_Open, en_capDateInterval, op_capOpen, False, False, opcode_DateInterval_Open)) do begin end; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) end.
{$MODE OBJFPC} {$INLINE ON} program Employment; uses Math; const InputFile = 'PROJECT.INP'; OutputFile = 'PROJECT.OUT'; maxN = Round(4E5); var a, b: array[1..maxN + 1] of Integer; queue: array[1..maxN] of Integer; front, rear: Integer; n: Integer; H, S, D: Int64; T: Integer; TotalCost: Int64; procedure Enter; var f: TextFile; i: Integer; begin AssignFile(f, InputFile); Reset(f); try ReadLn(f, n); ReadLn(f, H, S, D); for i := 1 to n do Read(f, a[i]); finally CloseFile(f); end; end; function NotEmpty: Boolean; inline; begin Result := front <= rear; end; procedure Push(v: Integer); inline; begin Inc(rear); queue[rear] := v; end; procedure Solve; var i, j, nRemove, e: Integer; begin T := (H + D) div S; rear := 0; front := 1; for i := 2 to 1 + T do begin if i > n then Break; while NotEmpty and (a[queue[rear]] < a[i]) do Dec(rear); Push(i); end; b[1] := a[1]; b[n] := a[n]; for i := 2 to n - 1 do begin j := i + T; if j <= n then begin while NotEmpty and (a[queue[rear]] < a[j]) do Dec(rear); Push(j); end; while queue[front] < i do Inc(front); if a[i] >= b[i - 1] then b[i] := a[i] else begin e := a[queue[front]]; if b[i - 1] > e then nRemove := b[i - 1] - e else nRemove := 0; b[i] := b[i - 1] - nRemove; end; end; b[n + 1] := 0; TotalCost := b[1] * (H + S); for i := 2 to n + 1 do begin if b[i] >= b[i - 1] then TotalCost := TotalCost + (b[i] - b[i - 1]) * H else TotalCost := TotalCost + (b[i - 1] - b[i]) * D; TotalCost := TotalCost + b[i] * S; end; end; procedure PrintResult; var f:TextFile; i: Integer; begin AssignFile(f, OutputFile); Rewrite(f); try WriteLn(f, TotalCost); for i := 1 to n do Write(f, b[i], ' '); finally CloseFile(f); end; end; begin Enter; Solve; PrintResult; end. 3 4 5 6 10 9 11
//Exercicio 19: Receber somente um número ímpar maior do que 15 e exibir o dobro deste número. { Solução em Portugol Algoritmo Exercicio 19; Var numero, impar: inteiro; Inicio exiba("Programa que exibe números ímpares maiores que 15."); exiba("Digite um número: "); leia(numero); se(resto(numero,2) = 1) então impar <- numero; fimse; se(impar > 15) então exiba("O número é ímpar e maior que 15. O seu dobro vale: ", 2 * impar); fimse; se(impar <= 15) então exiba("Número impar menor ou igual a 15 ou número par.); fimse; Fim. } // Solução em Pascal Program Exercicio19; uses crt; var numero, impar: integer; begin clrscr; writeln('Programa que exibe números ímpares maiores que 15.'); writeln('Digite um número: '); readln(numero); impar:= 0; if(numero mod 2 = 1) then impar := numero; if(impar > 15) then writeln('O número é ímpar e maior que 15. O dobro desse número é: ', 2 * impar); if(impar <= 15) then writeln('Número ímpar menor ou igual a 15 ou número par.'); repeat until keypressed; end.
UNIT WorkWithTree; INTERFACE TYPE Tree = ^Node; Node = RECORD WordOfTree: STRING; WordCount: INTEGER; LBranch, RBranch: Tree END; PROCEDURE Insert(VAR TreeBranch: Tree; NewWord: STRING); PROCEDURE PrintTree(VAR FOut: TEXT; VAR TreeBranch: Tree); PROCEDURE DelTree(TreeBranch: Tree); IMPLEMENTATION PROCEDURE Insert(VAR TreeBranch: Tree; NewWord: STRING); BEGIN IF TreeBranch = NIL THEN BEGIN NEW(TreeBranch); TreeBranch^.WordOfTree := NewWord; TreeBranch^.WordCount := 1; TreeBranch^.LBranch := NIL; TreeBranch^.RBranch := NIL END ELSE IF TreeBranch^.WordOfTree > NewWord THEN Insert(TreeBranch^.LBranch, NewWord) ELSE IF TreeBranch^.WordOfTree < NewWord THEN Insert(TreeBranch^.RBranch, NewWord) ELSE TreeBranch^.WordCount := TreeBranch^.WordCount + 1 END; PROCEDURE DelTree(TreeBranch: Tree); BEGIN IF TreeBranch^.LBranch <> NIL THEN DelTree(TreeBranch^.LBranch); IF TreeBranch^.RBranch <> NIL THEN DelTree(TreeBranch^.RBranch); DISPOSE(TreeBranch) END; PROCEDURE PrintTree(VAR FOut: TEXT; VAR TreeBranch: Tree); BEGIN IF TreeBranch <> NIL THEN BEGIN PrintTree(FOut, TreeBranch^.LBranch); WRITELN(FOut, TreeBranch^.WordOfTree, ': ', TreeBranch^.WordCount); PrintTree(FOut, TreeBranch^.RBranch) END END; BEGIN END.
{----------------------------------------------------------------------------- Created: 03.12.2009 14:29:49 (c) by TheUnknownOnes under dwywbdbu license - see http://theunknownones.googlecode.com/svn/ for the license see http://www.TheUnknownOnes.net -----------------------------------------------------------------------------} unit ufrxZintBarcode; {$R 'frxZint.res'} interface uses Windows, Messages, SysUtils, Classes, Graphics, Menus, Controls, Variants, frxClass, frxDsgnIntf, uZintBarcode, uZintInterface, fs_iinterpreter; type TfrxZintBarcodeDataFormat = (dfANSI, dfUTF8); TfrxZintBarcode = class(TfrxView) private FBarcode : TZintBarcode; FBitmap : TBitmap; FRotation : TZBRotation; FZoom : Single; FDataFormat: TfrxZintBarcodeDataFormat; FData : String; function GetZoom: Single; procedure SetZoom(const Value: Single); function GetData: String; procedure SetData(const Value: String); function GetBorderWidth: Integer; function GetColor(const Index: Integer): TColor; function GetOption(const Index: Integer): Integer; function GetOutputOptions: TZBOutputOptions; function GetPrimary: String; function GetType: TZBType; procedure SetBorderWidth(const Value: Integer); procedure SetColor(const Index: Integer; const Value: TColor); procedure SetOption(const Index, Value: Integer); procedure SetOutputOptions(const Value: TZBOutputOptions); procedure SetPrimary(const Value: String); procedure SetRotation(const Value: TZBRotation); procedure SetType(const Value: TZBType); function GetSHRT: Boolean; procedure SetSHRT(const Value: Boolean); procedure SetDataFormat(const Value: TfrxZintBarcodeDataFormat); function GetDataEncoded: Widestring; protected procedure BarcodeChanged(Sender: TObject); procedure SetHeight(Value: Extended); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; class function GetDescription: String; override; procedure Draw(Canvas: TCanvas; ScaleX, ScaleY, OffsetX, OffsetY: Extended); override; published property Zoom: Single read GetZoom write SetZoom; property BarcodeType : TZBType read GetType write SetType; property DataFormat: TfrxZintBarcodeDataFormat read FDataFormat write SetDataFormat; property Data: String read GetData write SetData; property BorderWidth : Integer read GetBorderWidth write SetBorderWidth; property OutputOptions : TZBOutputOptions read GetOutputOptions write SetOutputOptions; property FGColor : TColor index 0 read GetColor write SetColor; property BGColor : TColor index 1 read GetColor write SetColor; property Option1 : Integer index 1 read GetOption write SetOption; property Option2 : Integer index 2 read GetOption write SetOption; property Option3 : Integer index 3 read GetOption write SetOption; property Roatation : TZBRotation read FRotation write SetRotation; property Primary : String read GetPrimary write SetPrimary; property ShowHumanReadableText : Boolean read GetSHRT write SetSHRT; end; TfrxZintBarcodeRTTI = class(TfsRTTIModule) public constructor Create(AScript : TfsScript); override; end; implementation uses Math; { TfrxZintBarcode } procedure TfrxZintBarcode.BarcodeChanged(Sender: TObject); begin FBarcode.OnChanged:=nil; try FBarcode.Height:=Round(Self.Height / FZoom / 2); FBarcode.GetBarcode(FBitmap); Width:=Round(FBitmap.Width * FZoom); finally FBarcode.OnChanged:=Self.BarcodeChanged; end; end; constructor TfrxZintBarcode.Create(AOwner: TComponent); begin inherited; FZoom:=1; FBitmap:=TBitmap.Create; FBarcode:=TZintBarcode.Create; BarcodeChanged(nil); FBarcode.OnChanged:=BarcodeChanged; end; destructor TfrxZintBarcode.Destroy; begin FBarcode.Free; FBitmap.Free; inherited; end; procedure TfrxZintBarcode.Draw(Canvas: TCanvas; ScaleX, ScaleY, OffsetX, OffsetY: Extended); begin inherited; if IsDataField then FBarcode.Data:=DataSet.Value[DataField]; Canvas.StretchDraw(Rect(FX, FY, FX+Round(FBitmap.Width * ScaleX * FZoom), FY+Round(FBitmap.Height * ScaleY * FZoom)), FBitmap); end; function TfrxZintBarcode.GetBorderWidth: Integer; begin Result:=FBarcode.BorderWidth; end; function TfrxZintBarcode.GetColor(const Index: Integer): TColor; begin case Index of 0 : Result:=FBarcode.FGColor; 1 : Result:=FBarcode.BGColor; end; end; function TfrxZintBarcode.GetData: String; begin Result:=FData; end; function TfrxZintBarcode.GetDataEncoded: Widestring; begin case FDataFormat of dfANSI: Result:=FData; dfUTF8: Result:=UTF8Decode(FData); end; end; class function TfrxZintBarcode.GetDescription: String; begin Result:='Zint Barcode'; end; function TfrxZintBarcode.GetOption(const Index: Integer): Integer; begin case Index of 1 : Result:=FBarcode.Option1; 2 : Result:=FBarcode.Option2; 3 : Result:=FBarcode.Option3; end; end; function TfrxZintBarcode.GetOutputOptions: TZBOutputOptions; begin Result:=FBarcode.OutputOptions; end; function TfrxZintBarcode.GetPrimary: String; begin Result:=FBarcode.Primary; end; function TfrxZintBarcode.GetZoom: Single; begin Result:=FZoom; end; function TfrxZintBarcode.GetSHRT: Boolean; begin Result:=FBarcode.ShowHumanReadableText; end; function TfrxZintBarcode.GetType: TZBType; begin Result:=FBarcode.BarcodeType; end; procedure TfrxZintBarcode.SetBorderWidth(const Value: Integer); begin FBarcode.BorderWidth:=Value; end; procedure TfrxZintBarcode.SetColor(const Index: Integer; const Value: TColor); begin case Index of 0 : FBarcode.FGColor:=Value; 1 : FBarcode.BGColor:=Value; end; end; procedure TfrxZintBarcode.SetData(const Value: String); var ws : WideString; begin FData:=Value; ws:=GetDataEncoded; if ws<>EmptyWideStr then FBarcode.Data:=ws; end; procedure TfrxZintBarcode.SetDataFormat(const Value: TfrxZintBarcodeDataFormat); var ws : WideString; begin FDataFormat := Value; ws:=GetDataEncoded; if ws<>EmptyWideStr then FBarcode.Data:=ws; end; procedure TfrxZintBarcode.SetHeight(Value: Extended); var NewHeight : Integer; begin if Value<>Height then begin if Value<=0 then Value:=0.1; inherited; BarcodeChanged(nil); end; end; procedure TfrxZintBarcode.SetOption(const Index, Value: Integer); begin case Index of 1 : FBarcode.Option1 := Value; 2 : FBarcode.Option2 := Value; 3 : FBarcode.Option3 := Value; end; end; procedure TfrxZintBarcode.SetOutputOptions(const Value: TZBOutputOptions); begin FBarcode.OutputOptions:=Value; end; procedure TfrxZintBarcode.SetPrimary(const Value: String); begin FBarcode.Primary:=Value; end; procedure TfrxZintBarcode.SetRotation(const Value: TZBRotation); begin FRotation := Value; end; procedure TfrxZintBarcode.SetZoom(const Value: Single); begin FZoom:=Value; BarcodeChanged(self); end; procedure TfrxZintBarcode.SetSHRT(const Value: Boolean); begin FBarcode.ShowHumanReadableText:=Value; end; procedure TfrxZintBarcode.SetType(const Value: TZBType); begin FBarcode.BarcodeType:=Value; end; var bmp : TBitmap; { TfrxZintBarcodeRTTI } constructor TfrxZintBarcodeRTTI.Create(AScript: TfsScript); begin inherited; AScript.AddClass(TfrxZintBarcode, 'TfrxView'); end; initialization bmp:=TBitmap.Create; bmp.LoadFromResourceName(HInstance, 'ZINTTUOLOGO'); frxObjects.RegisterObject1(TfrxZintBarcode, bmp); fsRTTIModules.Add(TfrxZintBarcodeRTTI) finalization frxObjects.Unregister(TfrxZintBarcode); bmp.Free; end.
unit GX_ePasteAs; interface uses Windows, SysUtils, Classes, StdCtrls, Controls, Forms, GX_BaseForm, GX_eSelectionEditorExpert, GX_EditorExpert, GX_ConfigurationInfo; type TPasteAsExpert = class(TEditorExpert) protected procedure InternalLoadSettings(Settings: TExpertSettings); override; procedure InternalSaveSettings(Settings: TExpertSettings); override; public class function GetName: string; override; constructor Create; override; function GetDisplayName: string; override; procedure Configure; override; procedure Execute(Sender: TObject); override; function GetHelpString: string; override; end; TCopyRawStringsExpert = class(TSelectionEditorExpert) protected function ProcessSelected(Lines: TStrings): Boolean; override; public class function GetName: string; override; constructor Create; override; function GetDefaultShortCut: TShortCut; override; function GetDisplayName: string; override; function GetHelpString: string; override; function HasConfigOptions: Boolean; override; end; TConvertRawStringsExpert = class(TSelectionEditorExpert) protected function ProcessSelected(Lines: TStrings): Boolean; override; public class function GetName: string; override; constructor Create; override; function GetDisplayName: string; override; function GetHelpString: string; override; procedure Configure; override; function HasConfigOptions: Boolean; override; end; TfmPasteAsConfig = class(TfmBaseForm) gbxPasteAsOptions: TGroupBox; lblMaxEntries: TLabel; chkCreateQuotedStrings: TCheckBox; btnOK: TButton; btnCancel: TButton; cbPasteAsType: TComboBox; chkAddExtraSpaceAtTheEnd: TCheckBox; chkShowOptions: TCheckBox; procedure FormCreate(Sender: TObject); private public end; implementation uses GX_PasteAs, Clipbrd, Dialogs; {$R *.dfm} { TPasteAsExpert } constructor TPasteAsExpert.Create; begin inherited Create; { TODO -oanyone : this shortcut conflicts with the Declare Variable refactoring } // ShortCut := scCtrl + scShift + Ord('V'); end; function TPasteAsExpert.GetDisplayName: string; resourcestring SPasteAsName = 'Paste Strings As'; begin Result := SPasteAsName; end; class function TPasteAsExpert.GetName: string; begin Result := 'PasteAs'; end; procedure TPasteAsExpert.InternalLoadSettings(Settings: TExpertSettings); begin inherited InternalLoadSettings(Settings); PasteAsHandler.LoadSettings(Settings); end; procedure TPasteAsExpert.InternalSaveSettings(Settings: TExpertSettings); begin inherited InternalSaveSettings(Settings); PasteAsHandler.SaveSettings(Settings); end; procedure TPasteAsExpert.Configure; begin PasteAsHandler.ExecuteConfig(Self, True); end; function TPasteAsExpert.GetHelpString: string; resourcestring SPasteAsHelp = ' This expert inserts text lines from the clipboard into the code editor as properly formatted Delphi code. ' + 'It can convert things like multi-line SQL statements or long error messages into sets of string constants, '+ 'TStrings.Add() statements, etc. To use it, copy some text to the clipboard, put the edit cursor in the '+ 'desired location, and execute this editor expert.' + sLineBreak + ' You can configure it to ask what type of prefix/suffix to use on each line and whether to ' + 'add a space to the end of each line''s text.'; begin Result := SPasteAsHelp; end; procedure TPasteAsExpert.Execute(Sender: TObject); var ALines: TStringList; begin if not Clipboard.HasFormat(CF_TEXT) then Exit; ALines := TStringList.Create; try ALines.Text := Clipboard.AsText; if PasteAsHandler.ExecuteConfig(Self, False) then PasteAsHandler.ConvertToCode(ALines, False); finally ALines.Free; end; end; { TCopyRawStringsExpert } constructor TCopyRawStringsExpert.Create; begin inherited Create; end; function TCopyRawStringsExpert.GetDefaultShortCut: TShortCut; begin Result := scCtrl + scAlt + Ord('C'); end; function TCopyRawStringsExpert.GetDisplayName: string; resourcestring SCopyRawStringsName = 'Copy Raw Strings'; begin Result := SCopyRawStringsName; end; class function TCopyRawStringsExpert.GetName: string; begin Result := 'CopyRawStrings'; end; function TCopyRawStringsExpert.GetHelpString: string; resourcestring SCopyRawStringsHelp = ' This expert copies code lines to the clipboard and removes the prefixes/suffixes around the strings ' + 'that are used to make them proper Delphi code, leaving you with just the raw strings. ' + 'You might use it to take a set of string constants (lines of SQL, for example) and ' + 'convert them back into the raw text.' + sLineBreak + ' To use it, select a block containing the string constants in the Delphi editor and ' + 'activate this expert.'; begin Result := SCopyRawStringsHelp; end; function TCopyRawStringsExpert.HasConfigOptions: Boolean; begin Result := False; end; function TCopyRawStringsExpert.ProcessSelected(Lines: TStrings): Boolean; begin PasteAsHandler.ExtractRawStrings(Lines, False); Clipboard.AsText := Lines.Text; Result := False; end; { TConvertRawStringsExpert } constructor TConvertRawStringsExpert.Create; begin inherited Create; { TODO -oanyone : this shortcut conflicts with the Record Macro shortcut } // ShortCut := scCtrl + scShift + Ord('R'); end; function TConvertRawStringsExpert.GetDisplayName: string; resourcestring SConvertRawStringsName = 'Convert Raw Strings'; begin Result := SConvertRawStringsName; end; class function TConvertRawStringsExpert.GetName: string; begin Result := 'ConvertRawStrings'; end; function TConvertRawStringsExpert.GetHelpString: string; resourcestring SConvertRawStringsHelp = ' This expert takes the selected code lines and removes the prefixes/suffixes around the strings ' + 'that are used to make them proper Delphi code, leaving you with just the raw strings. ' + 'It then uses the selected string prefix/suffix combination to paste the lines back into the editor.' + sLineBreak + ' To use it, select the string constants in the Delphi editor and ' + 'activate this expert.' + sLineBreak + ' You can configure this expert to use different string prefix/suffix combinations. Note that ' + 'it shares this configuration with the PasteAs expert.'; begin Result := SConvertRawStringsHelp; end; procedure TConvertRawStringsExpert.Configure; begin PasteAsHandler.ExecuteConfig(Self, True); end; function TConvertRawStringsExpert.HasConfigOptions: Boolean; begin Result := True; end; function TConvertRawStringsExpert.ProcessSelected(Lines: TStrings): Boolean; begin Result := PasteAsHandler.ExecuteConfig(Self, False); if Result then begin PasteAsHandler.ExtractRawStrings(Lines, True); PasteAsHandler.ConvertToCode(Lines, True); end; end; { TfmPasteAsConfig } procedure TfmPasteAsConfig.FormCreate(Sender: TObject); begin inherited; cbPasteAsType.DropDownCount := Integer(High(TPasteAsType)) + 1; end; initialization RegisterEditorExpert(TPasteAsExpert); RegisterEditorExpert(TCopyRawStringsExpert); RegisterEditorExpert(TConvertRawStringsExpert); end.
unit ExcMagicControl; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExcMagic; type TExcMagicControl = class(TComponent) private function GetEnabled: Boolean; procedure SetEnabled(const Value: Boolean); function GetMaxCallStack: Integer; procedure SetMaxCallStack(const Value: Integer); function GetCustomTab: String; function GetLogEnabled: Boolean; function GetLogFile: String; function GetOptions: TExcMagicOptions; procedure SetCustomTab(const Value: String); procedure SetLogEnabled(const Value: Boolean); procedure SetLogFile(const Value: String); procedure SetOptions(const Value: TExcMagicOptions); function GetOnCustomInfo: TExcMagicCustomInfoProc; function GetOnExceptionLog: TExcMagicLogProc; function GetOnExceptionMsg: TExcMagicMsgProc; function GetOnExceptionShow: TExcMagicShowProc; procedure SetOnCustomInfo(const Value: TExcMagicCustomInfoProc); procedure SetOnExceptionLog(const Value: TExcMagicLogProc); procedure SetOnExceptionMsg(const Value: TExcMagicMsgProc); procedure SetOnExceptionShow(const Value: TExcMagicShowProc); function GetLogHandled: Boolean; procedure SetLogHandled(const Value: Boolean); function GetSuppressRecursion: Boolean; procedure SetSuppressRecursion(const Value: Boolean); function GetOnTerminate: TExcMagicTerminateProc; procedure SetOnTerminate(const Value: TExcMagicTerminateProc); published property CustomTab: String read GetCustomTab write SetCustomTab; property Enabled: Boolean read GetEnabled write SetEnabled; property LogEnabled: Boolean read GetLogEnabled write SetLogEnabled; property LogHandled: Boolean read GetLogHandled write SetLogHandled; property LogFile: String read GetLogFile write SetLogFile; property MaxCallStack: Integer read GetMaxCallStack write SetMaxCallStack; property SuppressRecursion: Boolean read GetSuppressRecursion write SetSuppressRecursion; property Options: TExcMagicOptions read GetOptions write SetOptions; property OnExceptionMsg: TExcMagicMsgProc read GetOnExceptionMsg write SetOnExceptionMsg; property OnExceptionShow: TExcMagicShowProc read GetOnExceptionShow write SetOnExceptionShow; property OnExceptionLog: TExcMagicLogProc read GetOnExceptionLog write SetOnExceptionLog; property OnCustomInfo: TExcMagicCustomInfoProc read GetOnCustomInfo write SetOnCustomInfo; property OnTerminate: TExcMagicTerminateProc read GetOnTerminate write SetOnTerminate; end; procedure Register; implementation {$R *.DCR} procedure Register; begin RegisterComponents('ExcMagic', [TExcMagicControl]); end; { TExcMagicControl } function TExcMagicControl.GetEnabled: Boolean; begin Result := ExceptionHook.Enabled; end; procedure TExcMagicControl.SetEnabled(const Value: Boolean); begin ExceptionHook.Enabled := Value; end; function TExcMagicControl.GetMaxCallStack: Integer; begin Result := ExceptionHook.MaxCallStack; end; procedure TExcMagicControl.SetMaxCallStack(const Value: Integer); begin ExceptionHook.MaxCallStack := Value; end; function TExcMagicControl.GetCustomTab: String; begin Result := ExceptionHook.CustomTab; end; function TExcMagicControl.GetLogEnabled: Boolean; begin Result := ExceptionHook.LogEnabled; end; function TExcMagicControl.GetLogFile: String; begin Result := ExceptionHook.LogFile; end; function TExcMagicControl.GetOptions: TExcMagicOptions; begin Result := ExceptionHook.Options; end; procedure TExcMagicControl.SetCustomTab(const Value: String); begin ExceptionHook.CustomTab := Value; end; procedure TExcMagicControl.SetLogEnabled(const Value: Boolean); begin ExceptionHook.LogEnabled := Value; end; procedure TExcMagicControl.SetLogFile(const Value: String); begin ExceptionHook.LogFile := Value; end; procedure TExcMagicControl.SetOptions(const Value: TExcMagicOptions); begin ExceptionHook.Options := Value; end; function TExcMagicControl.GetOnCustomInfo: TExcMagicCustomInfoProc; begin Result := ExceptionHook.OnCustomInfo; end; function TExcMagicControl.GetOnExceptionLog: TExcMagicLogProc; begin Result := ExceptionHook.OnExceptionLog; end; function TExcMagicControl.GetOnExceptionMsg: TExcMagicMsgProc; begin Result := ExceptionHook.OnExceptionMsg; end; function TExcMagicControl.GetOnExceptionShow: TExcMagicShowProc; begin Result := ExceptionHook.OnExceptionShow; end; procedure TExcMagicControl.SetOnCustomInfo( const Value: TExcMagicCustomInfoProc); begin ExceptionHook.OnCustomInfo := Value; end; procedure TExcMagicControl.SetOnExceptionLog( const Value: TExcMagicLogProc); begin ExceptionHook.OnExceptionLog := Value; end; procedure TExcMagicControl.SetOnExceptionMsg( const Value: TExcMagicMsgProc); begin ExceptionHook.OnExceptionMsg := Value; end; procedure TExcMagicControl.SetOnExceptionShow( const Value: TExcMagicShowProc); begin ExceptionHook.OnExceptionShow := Value; end; function TExcMagicControl.GetOnTerminate: TExcMagicTerminateProc; begin Result := ExceptionHook.OnTerminate; end; procedure TExcMagicControl.SetOnTerminate( const Value: TExcMagicTerminateProc); begin ExceptionHook.OnTerminate := Value; end; function TExcMagicControl.GetLogHandled: Boolean; begin Result := ExceptionHook.LogHandled; end; procedure TExcMagicControl.SetLogHandled(const Value: Boolean); begin ExceptionHook.LogHandled := Value; end; function TExcMagicControl.GetSuppressRecursion: Boolean; begin Result := ExceptionHook.SuppressRecursion; end; procedure TExcMagicControl.SetSuppressRecursion(const Value: Boolean); begin ExceptionHook.SuppressRecursion := Value; end; end.
unit RnQ2sql; interface // uses RQGlobal; const CRLF=#13#10; CRLFCRLF=CRLF+CRLF; const SQLCreate_CLIST_TYPES : AnsiString = 'CREATE TABLE IF NOT EXISTS [CLIST_TYPES](' + CRLF + ' [ID] NUMBER(1) NOT NULL ON CONFLICT IGNORE COLLATE BINARY,' + CRLF + ' [DESC] CHAR(20) NOT NULL ON CONFLICT IGNORE,' + CRLF + ' CONSTRAINT [CLIST_TYPES_PK] PRIMARY KEY ([ID] COLLATE BINARY) ON CONFLICT IGNORE);'; SQLData_CLIST_TYPES: AnsiString = 'INSERT INTO [CLIST_TYPES] '+CRLF+ ' SELECT 1, ''ROSTER'' UNION '+CRLF+ ' SELECT 2, ''VISIBLE'' UNION '+CRLF+ ' SELECT 3, ''INVISIBLE'' UNION '+CRLF+ ' SELECT 4, ''TEMPVIS'' UNION '+CRLF+ ' SELECT 5, ''SPAM'' UNION '+CRLF+ ' SELECT 6, ''IGNORE'' UNION '+CRLF+ ' SELECT 7, ''NIL'' UNION '+CRLF+ ' SELECT 8, ''REOPEN'' UNION '+CRLF+ ' SELECT 9, ''CHK_INVIS'';'; { 'INSERT INTO [CLIST_TYPES] VALUES (1, ''ROSTER'');' + CRLF + 'INSERT INTO [CLIST_TYPES] VALUES (2, ''VISIBLE'');' + CRLF + 'INSERT INTO [CLIST_TYPES] VALUES (3, ''INVISIBLE'');' + CRLF + 'INSERT INTO [CLIST_TYPES] VALUES (4, ''TEMPVIS'');' + CRLF + 'INSERT INTO [CLIST_TYPES] VALUES (5, ''SPAM'');';{ + CRLF + 'INSERT INTO [CLIST_TYPES] VALUES (6, ''IGNORE'');' + CRLF + 'INSERT INTO [CLIST_TYPES] VALUES (7, ''NIL'');' + CRLF + 'INSERT INTO [CLIST_TYPES] VALUES (8, ''REOPEN'');' + CRLF + 'INSERT INTO [CLIST_TYPES] VALUES (9, ''CHK_INVIS'');'; } SQLCreate_SYS_CLISTS : AnsiString = 'CREATE TABLE IF NOT EXISTS SYS_CLISTS ('+CRLF+ ' CLIST_TYPE NUMBER(1) NOT NULL ON CONFLICT FAIL COLLATE BINARY,'+CRLF+ ' UID CHAR NOT NULL ON CONFLICT FAIL,'+CRLF+ ' CONSTRAINT SYS_CLISTS_PK PRIMARY KEY (CLIST_TYPE, UID COLLATE NOCASE) ON CONFLICT FAIL);'; SQLInsertSysCList : AnsiString = 'INSERT INTO SYS_CLISTS VALUES(?, ?);'; SQLCreate_RnQ_AVT : AnsiString = 'CREATE TABLE IF NOT EXISTS RAVT.avatars('+CRLF+ ' AVT_HASH BLOB(16) NOT NULL ON CONFLICT FAIL COLLATE BINARY,'+CRLF+ ' AVT_TYPE NUMBER(1) NOT NULL ON CONFLICT FAIL COLLATE BINARY,'+CRLF+ ' data BLOB NOT NULL ON CONFLICT FAIL,'+CRLF+ ' CONSTRAINT AVT_PK PRIMARY KEY (AVT_HASH, AVT_TYPE COLLATE NOCASE) ON CONFLICT FAIL);'; SQLInsertAVT : AnsiString = 'INSERT INTO RAVT.avatars VALUES(?, ?, ?);'; const AVTTypePic = 0; AVTTypeXML = 1; AVTTypeXMLPic = 2; AVTTypePhoto = 3; SQLCreateDBTable : AnsiString = 'CREATE TABLE IF NOT EXISTS DB ('+CRLF+ ' UID TEXT UNIQUE PRIMARY KEY,'+CRLF+ ' DISPLAY TEXT,'+CRLF+ ' "NICK" TEXT,'+CRLF+ ' FIRSTNAME TEXT,'+CRLF+ ' LASTNAME TEXT,'+CRLF+ ' BIRTHL DATE,'+CRLF+ ' SENDTRANSL INTEGER(1),'+CRLF+ ' bdata BLOB);'; SQLInsertDBrow : AnsiString = 'INSERT INTO DB VALUES(?, ?, ?, ?, ?, ?, ?, ?);'; SQLCreatePrefTable : AnsiString = 'CREATE TABLE IF NOT EXISTS Pref ('+CRLF+ ' key TEXT UNIQUE PRIMARY KEY,'+CRLF+ ' val_type INTEGER(1),'+CRLF+ ' val BLOB);'; SQLInsertPref : AnsiString = 'INSERT INTO Pref VALUES(?, ?, ?);'; SQLCreateExStsTable : AnsiString = 'CREATE TABLE IF NOT EXISTS ExStatus ('+CRLF+ ' id TEXT UNIQUE PRIMARY KEY,'+CRLF+ ' cap TEXT,'+CRLF+ ' caption TEXT,'+CRLF+ ' desc TEXT);'; SQLInsertExSts : AnsiString = 'INSERT INTO ExStatus VALUES(?, ?, ?, ?);'; { SQLCreateDBTable = 'CREATE TABLE IF NOT EXISTS UserBase (' + CRLF + ' Idx INTEGER UNIQUE PRIMARY KEY,' + CRLF + ' DISPLAY TEXT);'; SQLCreateDB2IMTable = 'CREATE TABLE IF NOT EXISTS UserBase2IM (' + CRLF + ' Idx INTEGER PRIMARY KEY,' + CRLF + ' IMTYPE INTEGER NOT NULL, ' + CRLF + ' UID TEXT NOT NULL,' + ' UNIQUE(IMTYPE, UID) );'; SQLCreateOscarDBTable = 'CREATE TABLE IF NOT EXISTS OscarBase (' + CRLF + // ' Idx INTEGER PRIMARY KEY,' + CRLF + ' UID TEXT PRIMARY KEY, ' + CRLF + ' SSIID INTEGER, ' + CRLF + ' "NICK" TEXT, ' + CRLF + ' FIRSTNAME TEXT,' + CRLF + ' LASTNAME TEXT, ' + CRLF + ' "EMAIL" TEXT, ' + CRLF + ' CITY TEXT, ' + CRLF + ' "STATE" TEXT, ' + CRLF + ' "ABOUT" TEXT, ' + CRLF + ' "DISPLAY" TEXT,' + CRLF + ' "QUERY" TEXT, ' + CRLF + ' "ZIP" TEXT, ' + CRLF + ' COUNTRY INTEGER,' + CRLF + ' BIRTH DATE, ' + CRLF + ' BIRTHL DATE, ' + CRLF + ' "LANG" INTEGER(3), ' + CRLF + ' HOMEPAGE TEXT, ' + CRLF + ' CELLULAR TEXT, ' + CRLF + ' IP INTEGER(4),' + CRLF + ' AGE NUMBER, ' + CRLF + // ' GMT NUMBER, ' + CRLF + ' GMThalfs NUMBER, ' + CRLF + ' GENDER NUMBER, ' + CRLF + ' "GROUP" TEXT, ' + CRLF + ' LASTINFOUPDATE DOUBLE,' + CRLF + ' LASTONLINETIME DOUBLE,' + CRLF + ' LASTMSGtime DOUBLE,' + CRLF + ' MEMBERSINCE DOUBLE,' + CRLF + ' ONLINESINCE DOUBLE,' + CRLF + ' NOTES TEXT, ' + CRLF + ' DONTDELETE INTEGER(1),' + CRLF + ' ASKEDAUTH INTEGER(1),' + CRLF + ' TOQUERY INTEGER(1),' + CRLF + ' SMSABLE INTEGER(1),' + CRLF + ' NODB INTEGER(1),' + CRLF + ' SENDTRANSL INTEGER(1),' + CRLF + ' INTEREST1 INTEGER(1), ' + CRLF + ' INTEREST2 INTEGER(1), ' + CRLF + ' INTEREST3 INTEGER(1), ' + CRLF + ' INTEREST4 INTEGER(1), ' + CRLF + ' INTERESTS1 text, ' + CRLF + ' INTERESTS2 text, ' + CRLF + ' INTERESTS3 text, ' + CRLF + ' INTERESTS4 text, ' + CRLF + ' WORKPAGE TEXT, ' + CRLF + ' WORKSTNT TEXT, ' + CRLF + // Должность ' WORKDEPT TEXT, ' + CRLF + // Департамент ' WORKCOMPANY TEXT,' + CRLF + // Компания ' WORKCOUNTRY NUMBER(4),' + CRLF + ' WORKZIP TEXT, ' + CRLF + ' WORKADDRESS TEXT,' + CRLF + ' WORKPHONE TEXT, ' + CRLF + ' WORKSTATE TEXT, ' + CRLF + ' WORKCITY TEXT, ' + CRLF + ' ImpString TEXT, ' + CRLF + ' Authorized INTEGER(1),' + CRLF + ' ICONSHOW INTEGER(1),' + CRLF + ' ICONMD5 BINARY(16), ' + CRLF + ' MARSTATUS INTEGER);'; //CREATE UNIQUE INDEX UID_IM ON UserBase(IMTYPE,UID) } SQLCreateHistTable : AnsiString = 'CREATE TABLE IF NOT EXISTS "Conversations" (' + '"Chat" TEXT NOT NULL,' + '"When" DATETIME NOT NULL,' + '"Who" TEXT NOT NULL,' + '"Kind" INTEGER NOT NULL,' + '"Text" TEXT,' + '"Binary" BLOB,' + '"Flags" INTEGER DEFAULT 0,' + '"Out" INTEGER,' + '"WID" GUID,' + '"MsgID" INTEGER);' + CRLF +'CREATE INDEX "timeindex" ON "Conversations" ("Chat", "When");' // +'CREATE INDEX "chatindex" ON "Conversations" ("Chat");' // ', PRIMARY KEY (MSG_TIME, FROM_UID, TO_UID, ISSEND) '+ // ' CREATE INDEX MSG_UID ON History(FROM_UID, TO_UID)' ; { SQLInsertHistory = 'INSERT INTO History (' + ' MSG_TIME, ISSEND, IMTYPE, FROM_UID, TO_UID, kind, flags, info, msg) ' + ' VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)'; } SQLInsertHistory = 'INSERT INTO Conversations (' + ' "Chat", "when", "who", "kind", "flags", "Binary", "Text", "out", WID) ' + ' VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)'; SQLDeleteHistoryWith: AnsiString = 'DELETE Conversations WHERE "Chat" = "%s"'; SQLSelectHistoryWith = 'SELECT MSG_TIME, ISSEND, IMTYPE, FROM_UID, TO_UID, kind, flags, info, msg '+ ' FROM History WHERE "Chat" = "%s" ORDER BY MSG_TIME'; SQLInsertContact = // 'INSERT INTO UserBase (IMTYPE, UID) VALUES(%d, ''%s'')'; 'INSERT INTO OscarBase (UID) VALUES(''%s'')'; SQLUpdateOscarCnt: AnsiString = // 'UPDATE UserBase set "%s" = ''%s'' WHERE idx = %d'; // 'UPDATE OscarBase set ? = ? WHERE rowid = ?;'; 'UPDATE OscarBase set "%s" = ? WHERE rowid = ?;'; SQLUpdateOscarCnt2: AnsiString = 'UPDATE OscarBase set "%s" = ''%s'' WHERE rowid = %d'; SQLUpdateOscarCnt3: AnsiString = 'UPDATE OscarBase set "%s" = ''%d'' WHERE rowid = %d'; SQLUpdateOscarCnt10: AnsiString = // 'UPDATE UserBase set "%s" = ''%s'' WHERE idx = %d'; // 'UPDATE OscarBase set ? = ? WHERE rowid = ?;'; 'UPDATE OscarBase set %s WHERE rowid = ?;'; implementation end.
{ Subroutine SST_W_C_DECL_SYM_ROUT (PROC) * * Declare any symbols eventually referenced by a routine call or declaration. * PROC is the routine descriptor. } module sst_w_c_DECL_SYM_ROUT; define sst_w_c_decl_sym_rout; %include 'sst_w_c.ins.pas'; procedure sst_w_c_decl_sym_rout ( {declare symbols referenced by routine call} in proc: sst_proc_t); {routine descriptor} var arg_p: sst_proc_arg_p_t; {points to current routine argument descriptor} begin if proc.sym_p <> nil then begin {do routine name symbol, if any} sst_w_c_symbol (proc.sym_p^); end; if proc.dtype_func_p <> nil then begin {do function return data type, if any} sst_w_c_decl_sym_dtype (proc.dtype_func_p^); end; arg_p := proc.first_arg_p; {init current call argument to first} while arg_p <> nil do begin {once for each call argument} if arg_p^.sym_p <> nil then begin {do dummy arg name, if any} sst_w_c_symbol (arg_p^.sym_p^); end; if arg_p^.exp_p <> nil then begin {do expression for passed arg value, if any} sst_w_c_decl_sym_exp (arg_p^.exp_p^); end; sst_w_c_decl_sym_dtype (arg_p^.dtype_p^); {do data type of this argument} arg_p := arg_p^.next_p; {advance to next argument of this routine} end; {back and process next call argument} end;
unit nvWinTrust; interface uses Windows; { Sample return codes - others may be returned : only zero indicates success } const CRYPT_E_SECURITY_SETTINGS = $80092026; { The cryptographic operation failed due to a local security option setting. } TRUST_E_PROVIDER_UNKNOWN = $800B0001; { The trust provider is not recognized on this system. } TRUST_E_ACTIONUNKNOWN = $800B0002; { The trust provider does not support the specified action. } TRUST_E_SUBJECT_FORM_UNKNOWN = $800B0003; { The trust provider does not support the form specified for the subject. } TRUST_E_SUBJECT_NOT_TRUSTED = $800B0004; { The subject is not trusted for the specified action. } TRUST_E_NOSIGNATURE = $800B0100; { No signature was present in the subject. } TRUST_E_EXPLICIT_DISTRUST = $800B0111; { The certificate was explicitly marked as untrusted by the user. } function nvVerifyTrust(const FileName: PChar; WTD_FLAGS: DWORD = $FFFFFFFF): DWORD; { Returns 0 if successful, otherwise result may be passed to SysErrorMessage. } { Returns 0 if not supported by Windows. } { This is intended for use verifying file integrity. } implementation const WTD_UI_ALL = 1; WTD_UI_NONE = 2; WTD_UI_NOBAD = 3; WTD_UI_NOGOOD = 4; WTD_REVOKE_NONE = 0; WTD_REVOKE_WHOLECHAIN = 1; WTD_CHOICE_FILE = 1; WTD_CHOICE_CATALOG = 2; WTD_CHOICE_BLOB = 3; WTD_CHOICE_SIGNER = 4; WTD_CHOICE_CERT = 5; WTD_STATEACTION_IGNORE = 0; WTD_STATEACTION_VERIFY = 1; WTD_STATEACTION_CLOSE = 2; WTD_STATEACTION_AUTO_CACHE = 3; WTD_STATEACTION_AUTO_CACHE_FLUSH = 4; WTD_PROV_FLAGS_MASK = $0000FFFF; WTD_USE_IE4_TRUST_FLAG = $00000001; WTD_NO_IE4_CHAIN_FLAG = $00000002; WTD_NO_POLICY_USAGE_FLAG = $00000004; WTD_REVOCATION_CHECK_NONE = $00000010; WTD_REVOCATION_CHECK_END_CERT = $00000020; WTD_REVOCATION_CHECK_CHAIN = $00000040; WTD_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT = $00000080; WTD_SAFER_FLAG = $00000100; WTD_HASH_ONLY_FLAG = $00000200; WTD_USE_DEFAULT_OSVER_CHECK = $00000400; WTD_LIFETIME_SIGNING_FLAG = $00000800; WTD_CACHE_ONLY_URL_RETRIEVAL = $00001000; WTD_UICONTEXT_EXECUTE = 0; WTD_UICONTEXT_INSTALL = 1; WINTRUST_ACTION_GENERIC_VERIFY: TGUID = '{189A3842-3041-11D1-85E1-00C04FC295EE}'; { Verify certificate chain only } // // WINTRUST_ACTION_GENERIC_VERIFY_V2: TGUID = // '{00AAC56B-CD44-11d0-8CC2-00C04FC295EE}'; //{ Verify a file or object using the Authenticode policy provider } type TWinTrustFileInfo = packed record cbStruct: DWORD; // required, size of structure pcwszFilePath: pWChar; // required, name of file name to be verified hFile: THANDLE; // optional pgKnownSubject: pGUID; // optional end; type TWinTrustData = packed record cbStruct: DWORD; // required, size of structure pPolicyCallbackData: pointer; // optional pSIPClientData: pointer; // optional dwUIChoice: DWORD; // required fdwRevocationChecks: DWORD; // required (but zero is normally used) dwChoice: DWORD; // required : identifies which structure is being passed through pChoiceData pChoiceData: pointer; // required dwStateAction: DWORD; // optional hWVTStateData: THandle; // optional pwszURLReference: pWChar; // optional dwProvFlags: DWORD; // optional : WTD_REVOCATION_CHECK_NONE is used to avoid connecting to the internet dwUIContext: DWORD; // optional end; var hWinTrust: HMODULE; didLoad: Boolean; pWinTrustFunc: function(WND: HWND; const ActionID: TGUID; const ActionData: TWinTrustData): DWORD; stdcall; function WinVerifyTrust(WND: HWND; const ActionID: TGUID; const ActionData: TWinTrustData): DWORD; const // pWinTrustFunc: function(WND: HWND; const ActionID: TGUID; const ActionData: TWinTrustData): DWORD; // stdcall = nil; // pWinTrustFunc: function(hwnd: THandle; ActionID: PGUID; ActionData: Pointer): Integer; stdcall; // done: Boolean = False; dll = 'Wintrust.dll'; //var // HM: HMODULE; begin if not didLoad then begin @pWinTrustFunc := nil; didLoad := True; hWinTrust := GetModuleHandle(dll); if hWinTrust = 0 then hWinTrust := LoadLibrary(dll); if hWinTrust <> 0 then pWinTrustFunc := GetProcAddress(hWinTrust, 'WinVerifyTrust'); end; if (hWinTrust = 0) or (@pWinTrustFunc = nil) then Result := DWORD(E_NOTIMPL) else Result := pWinTrustFunc(WND, ActionID, ActionData); end; function nvVerifyTrust(const FileName: PChar; WTD_FLAGS: DWORD = $FFFFFFFF): DWORD; { Returns 0 if successful, otherwise result may be passed to SysErrorMessage. } { Returns 0 if not supported by Windows. } { This is intended for use verifying file integrity. } var {$IFNDEF UNICODE} buff: array[0..MAX_PATH] of Widechar; {$ENDIF} td: TWinTrustData; fi: TWinTrustFileInfo; begin if (FileName = nil) or (FileName^ = #0) then begin Result := ERROR_INVALID_PARAMETER; exit; end; if WTD_FLAGS = $FFFFFFFF then WTD_FLAGS := WTD_REVOCATION_CHECK_NONE or WTD_HASH_ONLY_FLAG; ZeroMemory(@fi, SizeOf(fi)); ZeroMemory(@td, SizeOf(td)); {$IFDEF UNICODE} fi.pcwszFilePath := FileName; {$ELSE} MultiByteToWideChar(0, 0, FileName, -1, Buff, Length(Buff)); fi.pcwszFilePath := buff; {$ENDIF} fi.cbStruct := SizeOf(fi); // fi.pcwszFilePath := buff; td.cbStruct := SizeOf(td); td.dwProvFlags := WTD_FLAGS; td.dwUIChoice := WTD_UI_NONE; { No user interaction } td.dwChoice := WTD_CHOICE_FILE; { pChoice identifies a TWinTrustFileInfo structure } td.pChoiceData := @fi; Result := WinVerifyTrust(INVALID_HANDLE_VALUE, WINTRUST_ACTION_GENERIC_VERIFY, td); if Result = DWORD(E_NOTIMPL) then Result := 0; { Report success on old versions of Windows } end; { NOTE : Use of the API functions CertGetCertificateChain, CertVerifyCertificateChainPolicy and CertFreeCertificateChain } { : is recommended by Microsoft to perform certificate verification, however, the method above seems to work fine. } initialization didLoad := False; hWinTrust:= 0;//LoadLibrary(WINTRUST_LIB); // gdwError:=GetLastError; finalization if didLoad and (hWinTrust <> 0) then FreeLibrary(hWinTrust); end.
unit Thread.ImportarPlanilhaBaixasDIRECT; interface uses System.Classes, Dialogs, Windows, Forms, SysUtils, Messages, Controls, System.DateUtils, System.StrUtils, Generics.Collections, Control.EntregadoresExpressas, Control.Entregas, Control.Sistema, FireDAC.Comp.Client, Common.ENum, Model.PlanilhaBaixasDIRECT, Control.PlanilhaBaixasDIRECT, Control.Bases, Control.VerbasExpressas, Control.RoteirosExpressas, Control.ControleAWB; type Thread_ImportarPlanilhaBaixasDIRECT = class(TThread) private { Private declarations } entregas: TEntregasControl; planilha : TPlanilhaBaixasDIRECTControl; planilhas : TObjectList<TPlanilhaBaixasDIRECT>; entregadores : TEntregadoresExpressasControl; bases: TBasesControl; verbas : TVerbasExpressasControl; roteiros : TRoteirosExpressasControl; awb: TControleAWBControl; sMensagem: String; FdPos: Double; bCancel : Boolean; iPos : Integer; iLinha : Integer; dVerba: Double; protected procedure Execute; override; procedure AtualizaLog; procedure AtualizaProgress; procedure TerminaProcesso; procedure IniciaProcesso; procedure SetupClass(FDQuery: TFDQuery); public FFile: String; iCodigoCliente: Integer; bLoja: boolean; end; implementation { Important: Methods and properties of objects in visual components can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure Thread_ImportarPlanilhaEntradaEntregas.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; or Synchronize( procedure begin Form1.Caption := 'Updated in thread via an anonymous method' end ) ); where an anonymous method is passed. Similarly, the developer can call the Queue method with similar parameters as above, instead passing another TThread class as the first parameter, putting the calling thread in a queue with the other thread. } { Thread_ImportarPlanilhaEntradaEntregas } uses Common.Utils, Global.Parametros, View.ImportarBaixasTFO; procedure Thread_ImportarPlanilhaBaixasDIRECT.Execute; var Contador, I, LinhasTotal, iRet, iTipo: Integer; Linha, campo, codigo, sMess, sData: String; d: Real; aParam: array of Variant; iTotal : Integer; iCodCliente : Integer; FDQuery : TFDQuery; FDQuery1 : TFDQuery; FDVerba : TFDQuery; FDRoteiro: TFDQuery; FDAWB: TFDQuery; dVerbaTabela: Double; iGrupo: Integer; sCEP : String; sNome : String; sOperacao: String; iRoteiro : Integer; bGravar: Boolean; dtData: TDate; dPeso: Double; aTipoTabela: Array of String; begin Synchronize(IniciaProcesso); planilha := TPlanilhaBaixasDIRECTControl.Create; planilhas := TObjectList<TPlanilhaBaixasDIRECT>.Create; entregadores := TEntregadoresExpressasControl.Create; bases := TBasesControl.Create; roteiros := TRoteirosExpressasControl.Create; verbas := TVerbasExpressasControl.Create; awb := TControleAWBControl.Create; try try // Carregando o arquivo ... if planilha.GetPlanilha(FFile) then begin planilhas := planilha.Planilha.Planilha; end else begin sMensagem := '>> ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now) + ' ' + planilha.Planilha.MensagemProcesso; AtualizaLog; Exit; end; SetLength(aTipoTabela, 7); aTipoTabela := ['FIXA','FIXACEP','FIXAPESO','SLA','CEPPESO','ROTEIROPESO','ROTEIROFIXA']; //se a planilha de baixas foi carregada inicia o processo de importação if planilhas.Count > 0 then begin // inicia-se as variaveis e querys iPos := 0; FdPos := 0; iTotal := planilhas.Count; FDQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery; FDQuery1 := TSistemaControl.GetInstance.Conexao.ReturnQuery; //lê todos os registros da planilha em memória for I := 0 to planilhas.Count - 1 do begin iGrupo := 0; dVerbaTabela := 0; sCEP := ''; sNome := ''; sOperacao := ''; // localiza a entrega no banco de dados entregas := TEntregasControl.Create; SetLength(aParam,2); aParam[0] := 'NN'; aParam[1] := planilhas[i].Remessa; FDQuery := entregas.Localizar(aParam); Finalize(aParam); bGravar := False; //se a entrega não existir, verifica se é uma reversa. Se for, gera um registro de entrega // e avisa ao usuário, se não for reversa, apenas avisa o usuário if FDQuery.IsEmpty then begin if UpperCase(planilhas[i].Tipo) = 'REVERSA' then begin bGravar := True; entregas.Entregas.Acao := tacIncluir; entregas.Entregas.NN := planilhas[i].Remessa; entregas.Entregas.Consumidor := UpperCase(planilhas[i].Tipo); entregas.Entregas.CEP := planilhas[i].CEP; entregas.Entregas.Volumes := planilhas[i].Volumes; sCEP := planilhas[i].CEP; entregas.Entregas.CodCliente := iCodigoCliente; if planilhas[i].PesoCubado > planilhas[i].PesoNominal then begin entregas.Entregas.PesoReal := planilhas[i].PesoCubado; end else begin entregas.Entregas.PesoReal := planilhas[i].PesoNominal; end; dPeso := entregas.Entregas.PesoReal; end else begin bGravar := False; end; sMensagem := 'Remessa ' + planilhas[i].Remessa + ' não localizada no banco de dados!'; Synchronize(AtualizaLog); end else begin SetupClass(FDQuery); entregas.Entregas.CodCliente := iCodigoCliente; sCEP := entregas.Entregas.CEP; entregas.Entregas.Acao := tacAlterar; bGravar := True; dPeso := entregas.Entregas.PesoReal; end; if bGravar then begin //procura a remessa no controle de AWB e verifica o tipo da entrega pela operação (TD ou TC) sOperacao := 'TD'; SetLength(aParam,2); aParam[0] := 'REMESSA'; aParam[1] := planilhas[i].Remessa; FDAWB := TSistemaControl.GetInstance.Conexao.ReturnQuery; FDAWB := awb.Localizar(aParam); Finalize(aParam); if not FDAWB.IsEmpty then begin sOperacao := FDAWB.FieldByName('cod_operacao').AsString; end; FDAWB.Free; //rotina a ser implementada quando a tabela de verbas por CEP e Roteiro for definida {iTipo := 0; iRoteiro := 0; SetLength(aParam,3); aParam[0] := 'CEP'; aParam[1] := sCEP; aParam[2] := iCodigoCliente; FDRoteiro := TSistemaControl.GetInstance.Conexao.ReturnQuery; FDRoteiro := roteiros.Localizar(aParam); if not FDRoteiro.IsEmpty then begin iTipo := FDRoteiro.FieldByName('cod_tipo').asInteger; if iTipo = 3 then begin iRoteiro := FDRoteiro.FieldByName('cod_leve').asInteger; end else if iTipo = 2 then begin if entregas.Entregas.PesoReal <= 30 then begin if sOperacao = 'TD' then begin iTipo := 3; iRoteiro := FDRoteiro.FieldByName('cod_leve').asInteger; end; end else begin iRoteiro := FDRoteiro.FieldByName('cod_pesado').asInteger; end; end; end; FDRoteiro.Free;} //apanha o código da base, entregador e verba fixa do cadastro de entregadores SetLength(aParam,2); aParam[0] := 'CHAVE'; aParam[1] := planilhas[i].Documento; FDQuery1 := entregadores.Localizar(aParam); dVerba := 0; if not FDQuery1.IsEmpty then begin entregas.Entregas.Distribuidor := FDQuery1.FieldByName('COD_AGENTE').AsInteger; entregas.Entregas.Entregador := FDQuery1.FieldByName('COD_ENTREGADOR').AsInteger; dVerba := FDQuery1.FieldByName('VAL_VERBA').AsFloat; sNome := FDQuery1.FieldByName('NOM_FANTASIA').AsString; end else begin sMensagem := 'Entregador da Remessa ' + planilhas[i].Remessa + ' (' + planilhas[i].Motorista + ') não encontrado!'; Synchronize(AtualizaLog); entregas.Entregas.Distribuidor := 1; entregas.Entregas.Entregador := 781; sNome := ''; dVerba := 0; end; Finalize(aParam); FDQuery1.Close; //apanha a verba da base se a verba fixa do entregador for igual a zero if dVerba = 0 then begin dVerba := StrToFloatDef(bases.GetField('val_verba', 'cod_agente', entregas.Entregas.Distribuidor.ToString), 0); iGrupo := StrToIntDef(bases.GetField('cod_grupo', 'cod_agente', entregas.Entregas.Distribuidor.ToString), 0); end; //se a verba continua zerada, apanha da tabela de verbas if dVerba = 0 then begin //#1 provisóriamente, pela cabeça de cep da remessa identificamos o tipo de verba (3 mista ou 2 pesado) entregas.Entregas.PesoCobrado := planilhas[i].PesoNominal; if planilhas[i].PesoCubado > planilhas[i].PesoNominal then begin entregas.Entregas.PesoReal := planilhas[i].PesoCubado; end else begin entregas.Entregas.PesoReal := planilhas[i].PesoNominal; end; dPeso := entregas.Entregas.PesoReal; //#1 if dPeso <= 30 then begin if sOperacao = 'TC' then begin iTipo := 2; end else begin iTipo := 1; end; end else begin iTipo := 2; end; if Pos(LeftStr(sCEP,3), '213,226,227') > 0 then begin iTipo := 2; //pesado end; // se o entregador for tipo PESADO altera para tipo de verba pesado if Pos('PESADO', sNome) > 0 then begin iTipo := 2; end; if iGrupo = 0 then iGrupo := 2; dtData := planilhas[i].DataAtualizacao; SetLength(aParam,6); aParam[0] := aTipoTabela[Pred(iGrupo)]; aParam[1] := iGrupo; // esse parâmetro será informado pelo cadastro do entregador futuramente aParam[2] := entregas.Entregas.CodCliente; aParam[3] := iTipo; aParam[4] := dtData; aParam[5] := sCEP; FDVerba := TSistemaControl.GetInstance.Conexao.ReturnQuery; FDVerba := verbas.Localizar(aParam); Finalize(aParam); if not FDVerba.IsEmpty then begin dVerbaTabela := verbas.Verbas.Verba; end; FDVerba.Free; if dVerbaTabela > 0 then dVerba := dVerbaTabela; end; // atualiza a remessa com os dados da baixa se ela ainda não foi fechada (extrato) if entregas.Entregas.Fechado <> 'S' then begin entregas.Entregas.Status := 909; entregas.Entregas.Baixa := planilhas[i].DataAtualizacao; entregas.Entregas.Entrega := planilhas[i].DataAtualizacao; entregas.Entregas.Baixado := 'S'; entregas.Entregas.VerbaEntregador := dVerba; if entregas.Entregas.Previsao < entregas.Entregas.Entrega then begin entregas.Entregas.Atraso := DaysBetween(entregas.Entregas.Previsao,entregas.Entregas.Entrega); end else begin entregas.Entregas.Atraso := 0; end; entregas.Entregas.Rastreio := entregas.Entregas.Rastreio + #13 + '> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' baixada por importação por ' + Global.Parametros.pUser_Name; // avisa se a remessa está sem verba if dVerba = 0 then begin sMensagem := 'Verba não encontrada para a remessa ' + entregas.Entregas.NN + ' do entregador ' + entregas.Entregas.Entregador.ToString + ' !'; Synchronize(AtualizaLog); end else begin if bLoja then begin if Trim(planilhas[i].Loja) = 'S' then begin dVerba := dVerba / 2; entregas.Entregas.Status := 9889; end; end; end; if not entregas.Gravar then begin sMensagem := 'Erro ao baixar a Remessa ' + entregas.Entregas.NN + ' !'; Synchronize(AtualizaLog); end; end; end; entregas.Free; iPos := iPos + 1; FdPos := (iPos / iTotal) * 100; if not(Self.Terminated) then begin Synchronize(AtualizaProgress); end else begin Abort; end; end; end; Except on E: Exception do begin Application.MessageBox(PChar('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message), 'Erro', MB_OK + MB_ICONERROR); bCancel := True; end; end; finally if bCancel then begin sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' importação cancelada ...'; Synchronize(AtualizaLog); Application.MessageBox('Importação cancelada!', 'Importação de Entregas', MB_OK + MB_ICONWARNING); end else begin sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' importação concluída com sucesso'; Synchronize(AtualizaLog); Application.MessageBox('Importação concluída com sucesso!', 'Importação de Entregas', MB_OK + MB_ICONINFORMATION); end; Synchronize(TerminaProcesso); planilha.Free; planilhas.Free; entregadores.Free; verbas.Free; roteiros.Free; awb.Free; end; end; procedure Thread_ImportarPlanilhaBaixasDIRECT.IniciaProcesso; begin bCancel := False; view_ImportarBaixasTFO.actCancelar.Enabled := True; view_ImportarBaixasTFO.actFechar.Enabled := False; view_ImportarBaixasTFO.actImportar.Enabled := False; view_ImportarBaixasTFO.actAbrir.Enabled := False; view_ImportarBaixasTFO.dxLayoutItem7.Visible := True; sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' iniciando importação do arquivo ' + FFile; AtualizaLog; end; procedure Thread_ImportarPlanilhaBaixasDIRECT.SetupClass(FDQuery: TFDQuery); begin entregas.Entregas.Distribuidor := FDQuery.FieldByName('COD_AGENTE').AsInteger; entregas.Entregas.Entregador := FDQuery.FieldByName('COD_ENTREGADOR').AsInteger; entregas.Entregas.NN := FDQuery.FieldByName('NUM_NOSSONUMERO').AsString; entregas.Entregas.NF := FDQuery.FieldByName('NUM_NF').AsString; entregas.Entregas.Cliente := FDQuery.FieldByName('COD_CLIENTE').AsInteger; entregas.Entregas.Consumidor := FDQuery.FieldByName('NOM_CONSUMIDOR').AsString; entregas.Entregas.Endereco := FDQuery.FieldByName('DES_ENDERECO').AsString; entregas.Entregas.Complemento := FDQuery.FieldByName('DES_COMPLEMENTO').AsString; entregas.Entregas.Bairro := FDQuery.FieldByName('DES_BAIRRO').AsString; entregas.Entregas.Cidade := FDQuery.FieldByName('NOM_CIDADE').AsString; entregas.Entregas.Cep := FDQuery.FieldByName('NUM_CEP').AsString; entregas.Entregas.Telefone := FDQuery.FieldByName('NUM_TELEFONE').AsString ; entregas.Entregas.Expedicao := FDQuery.FieldByName('DAT_EXPEDICAO').AsDateTime; entregas.Entregas.Previsao := FDQuery.FieldByName('DAT_PREV_DISTRIBUICAO').AsDateTime; entregas.Entregas.Status := FDQuery.FieldByName('COD_STATUS').AsInteger; entregas.Entregas.Baixado := FDQuery.FieldByName('DOM_BAIXADO').AsString; entregas.Entregas.VerbaEntregador := FDQuery.FieldByName('VAL_VERBA_ENTREGADOR').AsFloat; entregas.Entregas.VerbaFranquia := FDQuery.FieldByName('VAL_VERBA_FRANQUIA').AsFloat; entregas.Entregas.PesoReal := FDQuery.FieldByName('QTD_PESO_REAL').AsFloat; entregas.Entregas.PesoCobrado := FDQuery.FieldByName('QTD_PESO_COBRADO').AsFloat; entregas.Entregas.Volumes := FDQuery.FieldByName('QTD_VOLUMES').AsInteger; entregas.Entregas.VolumesExtra := FDQuery.FieldByName('QTD_VOLUMES_EXTRA').AsFloat; entregas.Entregas.ValorVolumes := FDQuery.FieldByName('VAL_VOLUMES_EXTRA').AsFloat; entregas.Entregas.Atraso := FDQuery.FieldByName('QTD_DIAS_ATRASO').AsInteger; entregas.Entregas.Container := FDQuery.FieldByName('NUM_CONTAINER').AsString; entregas.Entregas.ValorProduto := FDQuery.FieldByName('VAL_PRODUTO').AsFloat; entregas.Entregas.Atribuicao := FDQuery.FieldByName('DAT_ATRIBUICAO').AsDateTime; entregas.Entregas.Altura := FDQuery.FieldByName('QTD_ALTURA').AsInteger; entregas.Entregas.Largura := FDQuery.FieldByName('QTD_LARGURA').AsInteger; entregas.Entregas.Comprimento := FDQuery.FieldByName('QTD_COMPRIMENTO').AsInteger; entregas.Entregas.Rastreio := FDQuery.FieldByName('DES_RASTREIO').AsString; entregas.Entregas.Pedido := FDQuery.FieldByName('NUM_PEDIDO').AsString; entregas.Entregas.Retorno := FDQuery.FieldByName('DES_RETORNO').AsString; entregas.Entregas.CodCliente := FDQuery.FieldByName('COD_CLIENTE_EMPRESA').AsInteger; end; procedure Thread_ImportarPlanilhaBaixasDIRECT.AtualizaLog; begin view_ImportarBaixasTFO.memLOG.Lines.Add(sMensagem); view_ImportarBaixasTFO.memLOG.Lines.Add(''); iLinha := view_ImportarBaixasTFO.memLOG.Lines.Count - 1; view_ImportarBaixasTFO.memLOG.Refresh; end; procedure Thread_ImportarPlanilhaBaixasDIRECT.AtualizaProgress; begin view_ImportarBaixasTFO.pbImportacao.Position := FdPos; view_ImportarBaixasTFO.pbImportacao.Properties.Text := FormatFloat('0.00%',FdPos); view_ImportarBaixasTFO.pbImportacao.Refresh; view_ImportarBaixasTFO.memLOG.Lines[iLinha] := ' >>> ' + IntToStr(iPos) + ' registros processados'; view_ImportarBaixasTFO.memLOG.Refresh; if not(view_ImportarBaixasTFO.actCancelar.Visible) then begin view_ImportarBaixasTFO.actCancelar.Visible := True; view_ImportarBaixasTFO.actFechar.Enabled := False; view_ImportarBaixasTFO.actImportar.Enabled := False; end; end; procedure Thread_ImportarPlanilhaBaixasDIRECT.TerminaProcesso; begin view_ImportarBaixasTFO.actCancelar.Enabled := False; view_ImportarBaixasTFO.actFechar.Enabled := True; view_ImportarBaixasTFO.actImportar.Enabled := True; view_ImportarBaixasTFO.actAbrir.Enabled := True; view_ImportarBaixasTFO.edtArquivo.Clear; view_ImportarBaixasTFO.pbImportacao.Position := 0; view_ImportarBaixasTFO.pbImportacao.Clear; view_ImportarBaixasTFO.dxLayoutItem7.Visible := False; view_ImportarBaixasTFO.cboCliente.ItemIndex := 0; end; end.
unit AssetsMenagerData; interface uses System.SysUtils, System.Classes, FMX.Types, FMX.Controls, FMX.Layouts, FMX.Edit, FMX.StdCtrls, FMX.Clipboard, FMX.Platform, FMX.Objects, System.Types, StrUtils, FMX.Dialogs, System.Generics.Collections; {$IF DEFINED(ANDROID) OR DEFINED(IOS) OR DEFINED(LINUX)} const StrStartIteration = {$IFNDEF LINUX} 0 {$ELSE}1{$ENDIF}; type AnsiString = string; type WideString = string; type AnsiChar = Char; {$ELSE} const StrStartIteration = 1; {$ENDIF} type AssetsMenager = class private map: TObjectDictionary<AnsiString, TStream>; procedure addToMap(name: AnsiString); public function getAssets(resourceName: AnsiString): TStream; procedure addOrSetResource( resName : AnsiString ; stream : TStream); constructor create(); destructor Destroy(); override; end; implementation procedure AssetsMenager.addOrSetResource( resName : AnsiString ; stream : TStream); var temp : Tpair<AnsiString , TStream>; begin if not map.ContainsKey(resName) then begin try map.Add(resname, Stream); except on E: Exception do end; end else begin temp := map.ExtractPair( resname ); temp.Value.Free(); map.Add(resname, Stream); end; end; procedure AssetsMenager.addToMap(name: AnsiString); var Stream: TStream; begin try Stream := TResourceStream.create(HInstance, name, RT_RCDATA); map.Add(name, Stream); except on E: Exception do end; // stream.Free; // ? end; function AssetsMenager.getAssets(resourceName: AnsiString): TStream; begin if not map.TryGetValue(resourceName, result) then begin addToMap(resourceName); if not map.TryGetValue(resourceName, result) then begin if not map.TryGetValue('IMG_NOT_FOUND', result) then begin // showmessage( 'Can not load resource ' + resourceName ); raise Exception.create('Can not load resource ' + resourceName); end; end; end; end; constructor AssetsMenager.create(); begin inherited; map := TObjectDictionary<AnsiString, TStream>.create([doOwnsValues]); addToMap('IMG_NOT_FOUND'); end; destructor AssetsMenager.Destroy(); begin map.Clear; map.free; inherited; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clCryptUtils; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, Windows, {$ELSE} System.Classes, System.SysUtils, Winapi.Windows, {$ENDIF} clUtils, clCryptAPI, clWUtils; type EclCryptError = class(Exception) private FErrorCode: Integer; public constructor Create(const AErrorMsg: string; AErrorCode: Integer; ADummy: Boolean = False); property ErrorCode: Integer read FErrorCode; end; TclCryptData = class(TclBinaryData) protected procedure DeallocateMem(var P: PByte); override; procedure AllocateMem(var P: PByte; ASize: Integer); override; end; function GetCryptErrorText(AErrorCode: DWORD; const ADefaultMsg: string): string; procedure RaiseCryptError(const ADefaultMsg: string); overload; procedure RaiseCryptError(const AErrorMsg: string; AErrorCode: Integer); overload; resourcestring CertificateRequired = 'A certificate is required to complete the operation'; CertificateNotFound = 'The specified certificate not found'; KeyExistsError = 'A key with such name already exists'; CryptKeyRequired = 'A key is required to complete the operation'; CryptInvalidArgument = 'Invalid argument'; UnknownKeyFormat = 'Unknown key format'; const CertificateRequiredCode = -1; CertificateNotFoundCode = -2; KeyExistsErrorCode = -3; CryptKeyRequiredCode = -4; CryptInvalidArgumentCode = -7; UnknownKeyFormatCode = -8; DefaultEncoding = X509_ASN_ENCODING or PKCS_7_ASN_ENCODING; DefaultProvider = MS_DEF_PROV; DefaultProviderType = PROV_RSA_FULL; implementation function GetCryptErrorText(AErrorCode: DWORD; const ADefaultMsg: string): string; var Len: Integer; Buffer: array[0..255] of Char; begin Len := FormatMessage(FORMAT_MESSAGE_FROM_HMODULE or FORMAT_MESSAGE_FROM_SYSTEM, Pointer(GetModuleHandle('crypt32.dll')), AErrorCode, 0, Buffer, SizeOf(Buffer), nil); while (Len > 0) and CharInSet(Buffer[Len - 1], [#0..#32, '.']) do Dec(Len); SetString(Result, Buffer, Len); if (Trim(Result) = '') then begin Result := Format('%s error - %d', [ADefaultMsg, AErrorCode]); end; end; procedure RaiseCryptError(const ADefaultMsg: string); var code: DWORD; begin code := GetLastError(); raise EclCryptError.Create(GetCryptErrorText(code, ADefaultMsg), Integer(code)); end; procedure RaiseCryptError(const AErrorMsg: string; AErrorCode: Integer); begin raise EclCryptError.Create(AErrorMsg, AErrorCode); end; { EclCryptError } constructor EclCryptError.Create(const AErrorMsg: string; AErrorCode: Integer; ADummy: Boolean); begin inherited Create(AErrorMsg); FErrorCode := AErrorCode; end; { TclCryptData } procedure TclCryptData.AllocateMem(var P: PByte; ASize: Integer); begin inherited AllocateMem(P, ASize); //CryptMemAlloc end; procedure TclCryptData.DeallocateMem(var P: PByte); begin inherited DeallocateMem(P); //CryptMemFree end; end.
unit FindUnit.FileEditor; interface uses ToolsApi, SimpleParser.Lexer.Types, DelphiAST.Classes, FindUnit.OtaUtils, Classes, DesignEditors, Graphics, FindUnit.Header, FindUnit.FormMessage; type TCharPosition = record StartLine: Integer; StartPos: Integer; EndLine: Integer; EndPos: Integer; end; TFileRegion = class(TObject) private FSource: IOTASourceEditor; FUses: TStringList; FUsesPosition: TCharPosition; FRegionPosition: TCharPosition; FFullFileText: TStringList; function RemoveUsesFromList(UsesList: TStrings; ItemToRemove: string): string; procedure DeleteInformationFrom(FromLine, ToLine: integer); procedure WriteInformationAtPostion(Line, Position: Integer; const Information: string); public constructor Create(SourceEditor: IOTASourceEditor); destructor Destroy; override; function HaveUses: Boolean; property RegionPosition: TCharPosition read FRegionPosition write FRegionPosition; property UsesPosition: TCharPosition read FUsesPosition write FUsesPosition; procedure GetUsesFromText(FullFileText: TStringList); function UsesExists(UseUnit: string): Boolean; procedure RemoveUses(UseUnit: string); end; TSourceFileEditor = class(TObject) private FSource: IOTASourceEditor; FFileContent: TStringList; FInterfaceRegion: TFileRegion; FImplementationRegion: TFileRegion; procedure ParseInformations; function GetInformationsFor(Token: string; SearchForEnd: Boolean; StartLine, EndLine: Integer): TCharPosition; procedure GetInfos; function AddUsesToRegion(Region: TFileRegion; UseUnit: string): Boolean; procedure WriteInformationAtPostion(Line, Position: Integer; const Information: string); public constructor Create(SourceEditor: IOTASourceEditor); destructor Destroy; override; function Prepare: Boolean; function AddUsesToInterface(const UseUnit: string): Boolean; function AddUsesToImplementation(const UseUnit: string): Boolean; procedure RemoveUsesFromInterface(const UseUnit: string); procedure RemoveUsesFromImplementation(const UseUnit: string); function IsLineOnImplementationSection(Line: Integer): Boolean; procedure AddUnit(UnitInfo: TStringPosition; ShowMessageOnAdd: Boolean = True); end; implementation uses SysUtils, FindUnit.Utils, RegExpr; { TSourceFileEditor } procedure TSourceFileEditor.AddUnit(UnitInfo: TStringPosition; ShowMessageOnAdd: Boolean); var MessageText: string; begin MessageText := ''; if IsLineOnImplementationSection(UnitInfo.Line) then begin if AddUsesToImplementation(UnitInfo.Value) then MessageText := 'Unit ' + UnitInfo.Value + ' added to implementation''s uses.'; end else begin if AddUsesToInterface(UnitInfo.Value) then MessageText := 'Unit ' + UnitInfo.Value + ' added to interface''s uses.'; end; if (MessageText <> '') and ShowMessageOnAdd then TfrmMessage.ShowInfoToUser(MessageText); end; function TSourceFileEditor.AddUsesToImplementation(const UseUnit: string): Boolean; begin RemoveUsesFromInterface(UseUnit); Result := AddUsesToRegion(FImplementationRegion, UseUnit); end; function TSourceFileEditor.AddUsesToInterface(const UseUnit: string): Boolean; begin RemoveUsesFromImplementation(UseUnit); Result := AddUsesToRegion(FInterfaceRegion, UseUnit); end; function TSourceFileEditor.AddUsesToRegion(Region: TFileRegion; UseUnit: string): Boolean; var Line: Integer; PosChar: Integer; begin Result := False; if Region.UsesExists(UseUnit) then Exit; Result := True; Line := Region.UsesPosition.EndLine; PosChar := Region.UsesPosition.EndPos -1; if not Region.HaveUses then begin Line := Region.RegionPosition.StartLine + 1; PosChar := 0; UseUnit := #13#10 + 'uses' + #13#10 + #9 + UseUnit + ';' + #13#10 end else begin if PosChar > 80 then UseUnit := ', ' + #13#10 + ' ' + UseUnit else UseUnit := ', ' + UseUnit; end; WriteInformationAtPostion(Line, PosChar, UseUnit); end; constructor TSourceFileEditor.Create(SourceEditor: IOTASourceEditor); begin FInterfaceRegion := TFileRegion.Create(SourceEditor); FImplementationRegion := TFileRegion.Create(SourceEditor); FFileContent := TStringList.Create; FSource := SourceEditor; end; destructor TSourceFileEditor.Destroy; begin FInterfaceRegion.Destroy; FImplementationRegion.Destroy; FFileContent.Free; inherited; end; function TSourceFileEditor.GetInformationsFor(Token: string; SearchForEnd: Boolean; StartLine, EndLine: Integer): TCharPosition; var I: Integer; OutPosition: Integer; OutLine: Integer; function GetPositionOfString(SearchString: string; iStart, IEnd: Integer; out FoundLine, FoundPosition: Integer): Boolean; var Line: string; Position: Integer; begin Result := False; for iStart := iStart to IEnd do begin Line := UpperCase(FFileContent[iStart]); Position := Pos(SearchString, Line); if Position = 0 then Continue; if (SearchString <> ';') and (Length(Line) > Length(SearchString)) and (Line[Length(Line)] <> '') then Continue; FoundLine := iStart; FoundPosition := Position; Result := True; Break; end; end; begin Result.StartLine := -1; Token := UpperCase(Token); if not GetPositionOfString(Token, StartLine, EndLine, OutLine, OutPosition) then Exit; Result.StartLine := OutLine; Result.StartPos := OutPosition; if SearchForEnd then begin if GetPositionOfString(';', OutLine, EndLine, OutLine, OutPosition) then begin Result.EndLine := OutLine; Result.EndPos := OutPosition; end; end; end; procedure TSourceFileEditor.GetInfos; var InterfaceEnd: Integer; begin FInterfaceRegion.RegionPosition := GetInformationsFor('interface', False, 0, FFileContent.Count -1); FImplementationRegion.RegionPosition := GetInformationsFor('implementation', False, 0, FFileContent.Count -1); if FImplementationRegion.RegionPosition.StartLine > -1 then InterfaceEnd := FImplementationRegion.RegionPosition.StartLine else InterfaceEnd := FFileContent.Count -1; FInterfaceRegion.UsesPosition := GetInformationsFor('uses', True, FInterfaceRegion.RegionPosition.StartLine, InterfaceEnd); if FImplementationRegion.RegionPosition.StartLine > -1 then FImplementationRegion.UsesPosition := GetInformationsFor('uses', True, FImplementationRegion.RegionPosition.StartLine, FFileContent.Count -1); FImplementationRegion.GetUsesFromText(FFileContent); FInterfaceRegion.GetUsesFromText(FFileContent); end; function TSourceFileEditor.IsLineOnImplementationSection(Line: Integer): Boolean; begin Result := Line > FImplementationRegion.RegionPosition.StartLine; end; procedure TSourceFileEditor.ParseInformations; begin GetInfos; end; function TSourceFileEditor.Prepare: Boolean; begin try Result := True; FFileContent.Text := EditorAsString(FSource); ParseInformations; except Result := False; end; end; procedure TSourceFileEditor.RemoveUsesFromImplementation(const UseUnit: string); begin FImplementationRegion.RemoveUses(UseUnit); end; procedure TSourceFileEditor.RemoveUsesFromInterface(const UseUnit: string); begin FInterfaceRegion.RemoveUses(UseUnit); end; procedure TSourceFileEditor.WriteInformationAtPostion(Line, Position: Integer; const Information: string); var InfoPosition: TOTACharPos; FileWriter: IOTAEditWriter; SetPosition: Integer; begin if Information = '' then Exit; Line := Line + 1; InfoPosition.Line := Line; InfoPosition.CharIndex := Position; SetPosition := FSource.EditViews[0].CharPosToPos(InfoPosition); FileWriter := FSource.CreateUndoableWriter; try FileWriter.CopyTo(SetPosition); FileWriter.Insert(PAnsiChar(AnsiString(Information))); finally FileWriter := nil; end; end; { TFileRegion } procedure TFileRegion.DeleteInformationFrom(FromLine, ToLine: integer); var StartPosition, EndPosition: TOTACharPos; FileWriter: IOTAEditWriter; StartPos: Integer; EndPos: Integer; begin Inc(FromLine); StartPosition.Line := FromLine; StartPosition.CharIndex := 0; Inc(ToLine); Inc(ToLine); EndPosition.Line := ToLine; EndPosition.CharIndex := 0; StartPos := FSource.EditViews[0].CharPosToPos(StartPosition); EndPos := FSource.EditViews[0].CharPosToPos(EndPosition); FileWriter := FSource.CreateUndoableWriter; try FileWriter.CopyTo(StartPos); FileWriter.DeleteTo(EndPos); finally FileWriter := nil; end; end; constructor TFileRegion.Create(SourceEditor: IOTASourceEditor); begin FUses := TStringList.Create; FUses.Duplicates := dupIgnore; FUses.Sorted := True; FSource := SourceEditor; end; destructor TFileRegion.Destroy; begin FUses.Free; inherited; end; procedure TFileRegion.GetUsesFromText(FullFileText: TStringList); var I: Integer; LocalUses: TStringList; Line: string; Item: string; begin FFullFileText := FullFileText; if not HaveUses then Exit; LocalUses := TStringList.Create; try for I := FUsesPosition.StartLine to FUsesPosition.EndLine do LocalUses.Add(Trim(FullFileText[I])); LocalUses.Text := StringReplace(LocalUses.Text,' ',',', [rfReplaceAll]); LocalUses.Text := StringReplace(LocalUses.Text,';',',', [rfReplaceAll]); for I := 0 to LocalUses.Count -1 do begin Line := LocalUses[i]; while Line <> '' do begin Item := Fetch(Line, ','); FUses.Add(UpperCase(Item)); end; end; finally LocalUses.Free; end; end; function TFileRegion.HaveUses: Boolean; begin Result := UsesPosition.StartLine > 0; end; procedure TFileRegion.RemoveUses(UseUnit: string); var I: Integer; LocalUses: TStringList; begin if not UsesExists(UseUnit) then Exit; FFullFileText.Text := EditorAsString(ActiveSourceEditor); LocalUses := TStringList.Create; try for I := FUsesPosition.StartLine to FUsesPosition.EndLine do LocalUses.Add(FFullFileText[I]); LocalUses.Text := RemoveUsesFromList(LocalUses, UseUnit); DeleteInformationFrom(FUsesPosition.StartLine, FUsesPosition.EndLine); if UpperCase(Trim(LocalUses.Text)) <> 'USES' then WriteInformationAtPostion(FUsesPosition.StartLine, 0, LocalUses.Text); finally LocalUses.Free; end; end; function TFileRegion.RemoveUsesFromList(UsesList: TStrings; ItemToRemove: string): string; const Mask = '[^a-zA-Z0-9]%s[^a-zA-Z0-9]'; var Regex: TRegExpr; MaskFilter: string; begin MaskFilter := Format(Mask, [ItemToRemove]); Regex := TRegExpr.Create; Regex.Expression := MaskFilter; Result := Trim(Regex.Replace(UsesList.Text, '', True)); if Result[Length(Result)] = ',' then begin Delete(Result, Length(Result), 1); Result := Result + ';'; end; end; function TFileRegion.UsesExists(UseUnit: string): Boolean; begin Result := FUses.IndexOf(UpperCase(UseUnit)) > -1; end; procedure TFileRegion.WriteInformationAtPostion(Line, Position: Integer; const Information: string); var InfoPosition: TOTACharPos; FileWriter: IOTAEditWriter; SetPosition: Integer; begin if Information = '' then Exit; Line := Line + 1; InfoPosition.Line := Line; InfoPosition.CharIndex := Position; SetPosition := FSource.EditViews[0].CharPosToPos(InfoPosition); FileWriter := FSource.CreateUndoableWriter; try FileWriter.CopyTo(SetPosition); FileWriter.Insert(PAnsiChar(AnsiString(Information))); finally FileWriter := nil; end; end; end.
unit GX_FileScanner; (* Scans pas/cpp files and produces a list of implemented methods Known Scanning False Positives/Bugs: var CoInitializeExProc: function (pvReserved: Pointer; coInit: Longint): HResult; stdcall; procedure ReleaseToolMenuKeyHooks; forward; *) interface uses Classes, mPasLex, mwBCBTokenList; type TSourceLanguage = (ltPas, ltCpp); TProcScanningStatus = (stNone, stInProcedure, stScanned, stOutofProcedure); TProcedure = class(TCollectionItem) private FLineNo: Integer; FName: string; FDisplayName: string; FProcedureType: string; FProcArgs: string; FProcClass: string; FProcReturnType: string; FBeginIndex: Integer; FScanningStatus: TProcScanningStatus; FEndIndex: Integer; FProcName: string; FObjectSeparator: string; function GetProcName: string; function GetBody: string; function GetProcClass: string; procedure GetProcNameClassDetails; public ProcLine: string; property LineNo: Integer read FLineNo write FLineNo; property Name: string read FName write FName; property DisplayName: string read FDisplayName write FDisplayName; property ProcedureType: string read FProcedureType write FProcedureType; property ProcArgs: string read FProcArgs write FProcArgs; property ProcName: string read GetProcName write FProcName; property ProcClass: string read GetProcClass write FProcClass; property ProcReturnType: string read FProcReturnType write FProcReturnType; property Body: string read GetBody; property BeginIndex: Integer read FBeginIndex write FBeginIndex; property ScanningStatus: TProcScanningStatus read FScanningStatus write FScanningStatus; property EndIndex: Integer read FEndIndex write FEndIndex; property ObjectSeparator: string read FObjectSeparator write FObjectSeparator; end; TProcedures = class(TCollection) private FFileContent: string; function GetItem(Index: Integer): TProcedure; public property FileContent: string read FFileContent write FFileContent; property Items[Index: Integer]: TProcedure read GetItem; default; end; TLanguage = class(TObject) private FOrigin: PChar; FFileContent: string; protected FProcedures: TProcedures; FFileName: string; public constructor Create(const FileName: string); procedure Execute; virtual; abstract; property Procedures: TProcedures read FProcedures write FProcedures; property Origin: PChar read FOrigin write FOrigin; property FileContent: string read FFileContent write FFileContent; property FileName: string read FFileName write FFileName; end; TFileScanner = class(TComponent) private FLanguage: TSourceLanguage; FLanguageParser: TLanguage; FUnitText: string; FProcedures: TProcedures; FFileName: string; public procedure Execute; constructor CreateWithFileName(AOwner: TComponent; const FileName: string); overload; destructor Destroy; override; property Language: TSourceLanguage read FLanguage write FLanguage; property UnitText: string read FUnitText write FUnitText; property Procedures: TProcedures read FProcedures write FProcedures; end; TPascal = class(TLanguage) private FParser: TmwPasLex; function MoveToImplementation: Boolean; function GetProperProcName(ProcType: TTokenKind; IsClass: Boolean): string; public procedure Execute; override; end; TCpp = class(TLanguage) private FCParser: TBCBTokenList; FNameList: TStringList; FBraceCount: Integer; FBeginBracePosition: Longint; function InProcedureBlacklist(const Name: string): Boolean; procedure EraseName(Index: Integer); procedure FindBeginningBrace; procedure FindEndingBrace(const BraceCountDelta: Integer; const DecrementOpenBrace: Boolean); procedure FindBeginningProcedureBrace(var Name: string); function SearchForProcedureName: string; function SearchForTemplateArgs: string; public procedure Execute; override; end; implementation uses SysUtils, Contnrs, GX_GenericUtils, Math, GX_IdeUtils, GX_OtaUtils; resourcestring SUnknown = 'Unknown'; SImplementationNotFound = 'Implementation section not found.'; // These are some hardcoded macros to ignore as C++ procedure names const ProcBlacklist: array[0..2] of string = ('CATCH_ALL', 'CATCH', 'AND_CATCH_ALL'); { TProcedure } function TProcedure.GetProcName: string; begin if FProcName = '' then GetProcNameClassDetails; Result := FProcName; end; function TProcedure.GetBody: string; begin Result := Copy(TProcedures(Collection).FileContent, FBeginIndex + 1, FEndIndex - FBeginIndex); end; function TProcedure.GetProcClass: string; begin if FProcClass = '' then GetProcNameClassDetails; Result := FProcClass; end; procedure TProcedure.GetProcNameClassDetails; var ParamStart: Integer; SpacePos: Integer; Line: string; NestedClasses: string; begin Line := Trim(ProcLine); if StrBeginsWith('class ', Line, False) then Line := Trim(Copy(Line, Length('class '), Length(Line))); ParamStart := Pos('(', Line); if ParamStart = 0 then begin ParamStart := Pos(':', Line); // Could be a function if ParamStart = 0 then ParamStart := Length(Line); end; SpacePos := Pos(' ', Line); SpacePos := Max(SpacePos, 1); Line := Trim(Copy(Line, SpacePos + 1, ParamStart - SpacePos - 1)); DecomposeClassMethodString(Line, FProcName, FProcClass, NestedClasses); end; { TProcedures } function TProcedures.GetItem(Index: Integer): TProcedure; begin Result := TProcedure(inherited GetItem(Index)); end; { TFileScanner } procedure TFileScanner.Execute; begin case Language of ltPas: FLanguageParser := TPascal.Create(FFileName); ltCpp: FLanguageParser := TCpp.Create(FFileName); end; try FLanguageParser.FileContent := UnitText; FLanguageParser.Procedures := FProcedures; FLanguageParser.Execute; finally FreeAndNil(FLanguageParser); end; end; constructor TFileScanner.CreateWithFileName(AOwner: TComponent; const FileName: string); begin inherited Create(AOwner); FFileName := FileName; FProcedures := TProcedures.Create(TProcedure); FProcedures.FileContent := UnitText; if IsCppSourceModule(FileName) then Language := ltCpp else Language := ltPas; end; destructor TFileScanner.Destroy; begin FreeAndNil(FProcedures); inherited; end; { TPascal } procedure TPascal.Execute; var ClassLast: Boolean; InParenthesis: Boolean; ProcScanning: TProcScanningStatus; InTypeDeclaration: Boolean; DeclarationsPresent: Boolean; IdentifierNeeded: Boolean; BeginCount: Integer; ScanBeginIndex: Integer; ProcedureStack: TStack; ProcedureItem: TProcedure; ProcLineLength: Integer; begin FParser := TmwPasLex.Create; FParser.Origin := @FileContent[1]; FProcedures.FileContent := FileContent; ProcedureStack := TStack.Create; FProcedures.BeginUpdate; ProcedureItem := nil; try if (not (IsDpr(FileName) or IsInc(FileName))) and (not MoveToImplementation) then raise Exception.Create(SImplementationNotFound); InParenthesis := False; InTypeDeclaration := False; DeclarationsPresent := False; ProcScanning := stNone; BeginCount := 0; while FParser.TokenID <> tkNull do begin // Filter out method declarations inside type declarations if ((FParser.TokenID in [tkClass]) and FParser.IsClass) or (FParser.TokenID = tkInterface) then begin InTypeDeclaration := True; DeclarationsPresent := False; end else if InTypeDeclaration and (FParser.TokenID in [tkProcedure, tkFunction, tkOperator, tkProperty, tkPrivate, tkProtected, tkPublic, tkPublished]) then begin DeclarationsPresent := True; end else if InTypeDeclaration and ((FParser.TokenID = tkEnd) or ((FParser.TokenID = tkSemiColon) and not DeclarationsPresent)) then begin InTypeDeclaration := False; end; // Start scanning dependant in if a class proc or not ClassLast := (FParser.TokenID = tkClass); if ClassLast then begin ScanBeginIndex := FParser.TokenPos; FParser.NextNoJunk; end else begin FParser.NextNoJunk; ScanBeginIndex := FParser.TokenPos; end; // Get procedure name and parameters if not InTypeDeclaration and (FParser.TokenID in MethodMarkers) then begin if (FParser.TokenID = tkOperator) and (not ClassLast) then begin FParser.NextNoJunk; Continue; // Operator overload methods must be class methods end; // A new procedure was found. // If already scanning a procedure, // then the new procedure must be a subprocedure. Store // current procedure because it'll be further down in the file. if Assigned(ProcedureItem) then begin ProcedureItem.EndIndex := FParser.TokenPos; ProcedureItem.ScanningStatus := stOutofProcedure; ProcedureStack.Push(ProcedureItem); ProcScanning := stNone; BeginCount := 0; end; ProcedureItem := TProcedure(FProcedures.Add); ProcedureItem.BeginIndex := ScanBeginIndex; ProcedureItem.LineNo := FParser.LineNumber + 1; ProcedureItem.ObjectSeparator := '.'; IdentifierNeeded := True; ProcedureItem.ProcedureType := GetProperProcName(FParser.TokenID, ClassLast); // Parse the procedure name and parameters while not (FParser.TokenID in [tkNull]) do begin case FParser.TokenID of tkIdentifier, tkRegister: IdentifierNeeded := False; tkRoundOpen: begin // Prevent AProcedure = procedure() of object; // from being recognised as a procedure if IdentifierNeeded then begin FreeAndNil(ProcedureItem); Break; end; InParenthesis := True; end; tkRoundClose: InParenthesis := False; end; // case // End of the parameter list? if (not InParenthesis) and (FParser.TokenID = tkSemiColon) then Break; FParser.NextNoJunk; end; // while if Assigned(ProcedureItem) then begin ProcLineLength := FParser.TokenPos - ProcedureItem.BeginIndex + 1; SetString(ProcedureItem.ProcLine, FParser.Origin + ProcedureItem.BeginIndex, ProcLineLength); ProcedureItem.ProcLine := CompressWhiteSpace(ProcedureItem.ProcLine); end; end else begin // Into the code for the procedure text if not ((FParser.TokenID = tkSemiColon)) then begin case FParser.TokenID of tkBegin, tkAsm: begin ProcScanning := stInProcedure; Inc(BeginCount); end; tkInitialization, tkFinalization: begin ProcScanning := stOutofProcedure; if Assigned(ProcedureItem) then ProcedureItem.EndIndex := FParser.TokenPos; end; end; if (ProcScanning in [stInProcedure]) then begin // These have ends with no begins - account for them. if FParser.TokenID in [tkCase, tkRecord, tkTry] then Inc(BeginCount); if FParser.TokenID = tkEnd then begin if BeginCount = 1 then ProcScanning := stScanned; // Found the last 'end' Dec(BeginCount); if (ProcScanning = stScanned) then begin FParser.NextNoJunk; // Move to the semicolon // Reached the end of the procedure so store it. if Assigned(ProcedureItem) then begin ProcedureItem.EndIndex := FParser.TokenPos + 3; // +3 is for ';CRLF' ProcScanning := stOutofProcedure; ProcedureItem := nil; end; if (ProcedureStack.Count > 0) then begin // If Stack containes procedures, retrieve them, since it might be // that one's turn. ProcedureItem := ProcedureStack.Pop; ProcScanning := ProcedureItem.ScanningStatus; BeginCount := 0; end; // ProcedureStack.Count > 0 end; // ProcScanning = stScanned end; // FParser.TokenID = tkEnd end; // ProcScanning in [stInProcedure] end; // FParser.TokenID = tkSemiColon end; // Procedure body collection end; // FParser.TokenID <> tkNull // Store the last procedure if Assigned(ProcedureItem) then begin if not (ProcScanning in [stOutofProcedure]) then ProcedureItem.EndIndex := FParser.TokenPos; end; finally FProcedures.EndUpdate; FreeAndNil(ProcedureStack); FreeAndNil(FParser); end; end; function TPascal.MoveToImplementation: Boolean; begin Result := False; while FParser.TokenID <> tkNull do begin if FParser.TokenID = tkImplementation then begin Result := True; Break; end; FParser.NextNoJunk; end; end; function TPascal.GetProperProcName(ProcType: TTokenKind; IsClass: Boolean): string; begin Result := SUnknown; if IsClass then begin // Do not localize if ProcType = tkFunction then Result := 'Class Func' else if ProcType = tkProcedure then Result := 'Class Proc' else if ProcType = tkOperator then Result := 'Operator' else if ProcType = tkConstructor then Result := 'Class Constr'; end else begin case ProcType of // Do not localize. tkFunction: Result := 'Function'; tkProcedure: Result := 'Procedure'; tkConstructor: Result := 'Constructor'; tkDestructor: Result := 'Destructor'; tkOperator: Result := 'Operator'; end; end; end; { TCpp } procedure TCpp.Execute; var LineNo: Integer; PreviousBraceCount: Integer; i, j: Integer; NewName, TmpName, ProcClassAdd, ClassName: string; BraceCountDelta: Integer; BeginProcHeaderPosition: Longint; ProcLine: string; ProcName, ProcReturnType: string; ProcedureType, ProcClass, ProcArgs: string; ProcedureItem: TProcedure; BeginIndex: Integer; begin FProcedures.FileContent := FileContent; FCParser := TBCBTokenList.Create; FCParser.SetOrigin(@FileContent[1], Length(FileContent)); try FNameList := TStringList.Create; try FBraceCount := 0; FNameList.Add('0='); // Empty enclosure name j := FCParser.TokenPositionsList[FCParser.TokenPositionsList.Count - 1]; PreviousBraceCount := FBraceCount; FindBeginningProcedureBrace(NewName); while (FCParser.RunPosition <= j - 1) or (FCParser.RunID <> ctknull) do begin // If NewName = '' then we are looking at a real procedure - otherwise // we've just found a new enclosure name to add to our list if NewName = '' then begin // If we found a brace pair then special handling is necessary // for the bracecounting stuff (it is off by one) if FCParser.RunID = ctkbracepair then BraceCountDelta := 0 else BraceCountDelta := 1; if (BraceCountDelta > 0) and (PreviousBraceCount >= FBraceCount) then EraseName(PreviousBraceCount); // Back up a tiny bit so that we are "in front of" the // ctkbraceopen or ctkbracepair we just found FCParser.Previous; while not ((FCParser.RunID in [ctkSemiColon, ctkbraceclose, ctkbraceopen, ctkbracepair]) or (FCParser.RunID in IdentDirect) or (FCParser.RunIndex = 0)) do begin FCParser.PreviousNonJunk; // Handle the case where a colon is part of a valid procedure definition if FCParser.RunID = ctkcolon then begin // A colon is valid in a procedure definition only if it is immediately // following a close parenthesis (possibly separated by "junk") FCParser.PreviousNonJunk; if FCParser.RunID in [ctkroundclose, ctkroundpair] then FCParser.NextNonJunk else begin // Restore position and stop backtracking FCParser.NextNonJunk; Break; end; end; end; if FCParser.RunID in [ctkcolon, ctkSemiColon, ctkbraceclose, ctkbraceopen, ctkbracepair] then FCParser.NextNonComment else if FCParser.RunIndex = 0 then begin if FCParser.IsJunk then FCParser.NextNonJunk; end else // IdentDirect begin while FCParser.RunID <> ctkcrlf do begin if (FCParser.RunID = ctknull) then Exit; FCParser.Next; end; FCParser.NextNonJunk; end; // We are at the beginning of procedure header BeginProcHeaderPosition := FCParser.RunPosition; ProcLine := ''; while (FCParser.RunPosition < FBeginBracePosition) and (FCParser.RunID <> ctkcolon) do begin if (FCParser.RunID = ctknull) then Exit else if (FCParser.RunID <> ctkcrlf) then if (FCParser.RunID = ctkspace) and (FCParser.RunToken = #9) then ProcLine := ProcLine + #32 else ProcLine := ProcLine + FCParser.RunToken; FCParser.NextNonComment; end; // We are at the end of a procedure header // Go back and skip parenthesis to find the procedure name ProcName := ''; ProcClass := ''; ProcReturnType := ''; ProcArgs := SearchForProcedureName; // We have to check for ctknull and exit since we moved the // code to a nested procedure (if we exit SearchForProcedureName // early due to RunID = ctknull we exit this procedure early as well) if FCParser.RunID = ctknull then Exit; if FCParser.RunID = ctkthrow then begin ProcArgs := FCParser.RunToken + ProcArgs; ProcArgs := SearchForProcedureName + ProcArgs; end; // Since we've enabled nested procedures it is now possible // that we think we've found a procedure but what we've really found // is a standard C or C++ construct (like if or for, etc...) // To guard against this we require that our procedures be of type // ctkidentifier. If not, then skip this step. if (FCParser.RunID = ctkidentifier) and not InProcedureBlacklist(FCParser.RunToken) then begin BeginIndex := FCParser.RunPosition; ProcName := FCParser.RunToken; LineNo := FCParser.PositionAtLine(FCParser.RunPosition); FCParser.PreviousNonJunk; if FCParser.RunID = ctkcoloncolon then // The object/method delimiter begin // There may be multiple name::name::name:: sets here // so loop until no more are found ClassName := ''; while FCParser.RunID = ctkcoloncolon do begin FCParser.PreviousNonJunk; // The object name? // It is possible that we are looking at a templatized class and // what we have in front of the :: is the end of a specialization: // ClassName<x, y, z>::Function if FCParser.RunID = ctkGreater then SearchForTemplateArgs; ProcClass := FCParser.RunToken + ProcClass; if ClassName = '' then ClassName := FCParser.RunToken; FCParser.PreviousNonJunk; // look for another :: if FCParser.RunID = ctkcoloncolon then ProcClass := FCParser.RunToken + ProcClass; end; // We went back one step too far so go ahead one FCParser.NextNonJunk; ProcedureType := 'Procedure'; if ProcName = ClassName then ProcedureType := 'Constructor' else if ProcName = '~' + ClassName then ProcedureType := 'Destructor'; end else begin ProcedureType := 'Procedure'; // If type is a procedure is 1 then we have backed up too far already // so restore our previous position in order to correctly // get the return type information for non-class methods FCParser.NextNonJunk; end; while FCParser.RunPosition > BeginProcHeaderPosition do begin // Find the return type of the procedure FCParser.PreviousNonComment; // Handle the possibility of template specifications and // do not include them in the return type if FCParser.RunID = ctkGreater then SearchForTemplateArgs; if FCParser.RunID = ctktemplate then Continue; if FCParser.RunID in [ctkcrlf, ctkspace] then ProcReturnType := ' ' + ProcReturnType else begin ProcReturnType := FCParser.RunToken + ProcReturnType; BeginIndex := FCParser.RunPosition; end; end; // If the return type is an empty string then it must be a constructor // or a destructor (depending on the presence of a ~ in the name if (Trim(ProcReturnType) = '') or (Trim(ProcReturnType) = 'virtual') then begin if StrBeginsWith('~', ProcName) then ProcedureType := 'Destructor' else ProcedureType := 'Constructor'; end; ProcLine := Trim(ProcReturnType) + ' '; // This code sticks enclosure names in front of // methods (namespaces & classes with in-line definitions) ProcClassAdd := ''; for i := 0 to FBraceCount - BraceCountDelta do begin if i < FNameList.Count then begin TmpName := FNameList.Values[IntToStr(i)]; if TmpName <> '' then begin if ProcClassAdd <> '' then ProcClassAdd := ProcClassAdd + '::'; ProcClassAdd := ProcClassAdd + TmpName; end; end; end; if Length(ProcClassAdd) > 0 then begin if Length(ProcClass) > 0 then ProcClassAdd := ProcClassAdd + '::'; ProcClass := ProcClassAdd + ProcClass; end; if Length(ProcClass) > 0 then ProcLine := ProcLine + ' ' + ProcClass + '::'; ProcLine := ProcLine + ProcName + ' ' + ProcArgs; if ProcedureType = 'Procedure' then begin if StrBeginsWith('static ', Trim(ProcReturnType)) and (Length(ProcClass) > 0) then begin if StrContains('void', ProcReturnType) then ProcedureType := 'Class Proc' else ProcedureType := 'Class Func' end else if not StrContains('void', ProcReturnType) then ProcedureType := 'Function'; end; ProcedureItem := TProcedure.Create(FProcedures); ProcedureItem.ProcLine := ProcLine; ProcedureItem.ProcName := ProcName; ProcedureItem.ProcedureType := ProcedureType; ProcedureItem.LineNo := LineNo; ProcedureItem.ProcClass := ProcClass; ProcedureItem.ProcArgs := ProcArgs; ProcedureItem.ProcReturnType := ProcReturnType; ProcedureItem.ObjectSeparator := '::'; while (FCParser.RunPosition < FBeginBracePosition) do FCParser.Next; ProcedureItem.BeginIndex := BeginIndex; FindEndingBrace(BraceCountDelta, (FBraceCount > 1)); ProcedureItem.EndIndex := FCParser.RunPosition + 1; end else while (FCParser.RunPosition < FBeginBracePosition) do FCParser.Next; end else begin // Insert enclosure name into our list (delete the old one if found) EraseName(FBraceCount); FNameList.Add(IntToStr(FBraceCount) + '=' + NewName); end; PreviousBraceCount := FBraceCount; FindBeginningProcedureBrace(NewName); end; // while (RunPosition <= j-1) finally FreeAndNil(FNameList); end; finally FreeAndNil(FCParser); end; end; function TCpp.InProcedureBlacklist(const Name: string): Boolean; var i: Integer; begin Result := False; for i := Low(ProcBlacklist) to High(ProcBlacklist) do begin if Name = ProcBlacklist[i] then begin Result := True; Break; end; end; end; procedure TCpp.EraseName(Index: Integer); var NameIndex: Integer; begin NameIndex := FNameList.IndexOfName(IntToStr(Index)); if NameIndex <> -1 then FNameList.Delete(NameIndex); end; procedure TCpp.FindBeginningBrace; begin repeat FCParser.NextNonJunk; case FCParser.RunID of ctkbraceopen: Inc(FBraceCount); ctkbraceclose: Dec(FBraceCount); ctknull: Exit; end; until FCParser.RunID in [ctkbraceopen, ctkbracepair, ctknull]; end; procedure TCpp.FindEndingBrace(const BraceCountDelta: Integer; const DecrementOpenBrace: Boolean); var BraceCount: Integer; begin if DecrementOpenBrace then BraceCount := BraceCountDelta else BraceCount := 0; if (BraceCount = 0) and (FCParser.RunID = ctkbracepair) then begin FCParser.Next; Exit; end; repeat FCParser.NextNonComment; case FCParser.RunID of ctkbraceopen: Inc(FBraceCount); ctkbraceclose: Dec(FBraceCount); ctknull: Exit; end; until ((FBraceCount - BraceCount) = 0) or (FCParser.RunID = ctknull); end; // This procedure does two things. It looks for procedures and it // looks for named scopes (like class/struct definitions & namespaces) // If it finds a named scope it returns the non-blank name. If it finds // a procedure it returns a blank name. procedure TCpp.FindBeginningProcedureBrace(var Name: string); var InitialPosition: Integer; RestorePosition: Integer; FoundClass: Boolean; begin FBeginBracePosition := 0; InitialPosition := FCParser.RunPosition; // Skip these: enum {a, b, c}; or int a[] = {0, 3, 5}; and find foo () { FindBeginningBrace; if FCParser.RunID = ctknull then Exit; FCParser.PreviousNonJunk; // Check for a namespace or a class name if FCParser.RunID = ctkidentifier then begin Name := FCParser.RunToken; // The name // This might be a derived class so search backward // no further than InitialPosition to see RestorePosition := FCParser.RunPosition; FoundClass := False; while FCParser.RunPosition >= InitialPosition do begin if FCParser.RunID in [ctkclass, ctkstruct, ctknamespace] then begin FoundClass := True; Break; end; if FCParser.RunPosition = InitialPosition then Break; FCParser.PreviousNonJunk; end; // The class name is the last token before a : or { if FoundClass then begin while not (FCParser.RunID in [ctkcolon, ctkbraceopen, ctknull]) do begin Name := FCParser.RunToken; FCParser.NextNonJunk; end; // Back up a bit if we are on a brace open so empty enums don't get treated as namespaces if FCParser.RunID = ctkbraceopen then FCParser.PreviousNonJunk; end; // Now get back to where you belong while FCParser.RunPosition < RestorePosition do FCParser.NextNonJunk; FCParser.NextNonJunk; FBeginBracePosition := FCParser.RunPosition; end else begin if FCParser.RunID in [ctkroundclose, ctkroundpair, ctkconst, ctkvolatile, ctknull] then begin // Return an empty name to indicate that a procedure was found Name := ''; FCParser.NextNonJunk; FBeginBracePosition := FCParser.RunPosition; end else begin while not (FCParser.RunID in [ctkroundclose, ctkroundpair, ctkconst, ctkvolatile, ctknull]) do begin FCParser.NextNonJunk; if FCParser.RunID = ctknull then Exit; // Recurse FindBeginningProcedureBrace(Name); FCParser.PreviousNonJunk; if Name <> '' then Break; end; FCParser.NextNonJunk; end; end; end; // This function searches backward from the current parser position // trying to find the procedure name - it returns all of the text // between the starting position and the position where it thinks a // procedure name has been found. function TCpp.SearchForProcedureName: string; var ParenCount: Integer; begin ParenCount := 0; Result := ''; repeat FCParser.Previous; if FCParser.RunID <> ctkcrlf then if (FCParser.RunID = ctkspace) and (FCParser.RunToken = #9) then Result := #32 + Result else Result := FCParser.RunToken + Result; case FCParser.RunID of ctkroundclose: Inc(ParenCount); ctkroundopen: Dec(ParenCount); ctknull: Exit; end; until ((ParenCount = 0) and ((FCParser.RunID = ctkroundopen) or (FCParser.RunID = ctkroundpair))); FCParser.PreviousNonJunk; // This is the procedure name end; function TCpp.SearchForTemplateArgs: string; var AngleCount: Integer; begin Result := ''; if FCParser.RunID <> ctkGreater then Exit; // Only use if we are on a '>' AngleCount := 1; Result := FCParser.RunToken; repeat FCParser.Previous; if FCParser.RunID <> ctkcrlf then if (FCParser.RunID = ctkspace) and (FCParser.RunToken = #9) then Result := #32 + Result else Result := FCParser.RunToken + Result; case FCParser.RunID of ctkGreater: Inc(AngleCount); ctklower: Dec(AngleCount); ctknull: Exit; end; until (((AngleCount = 0) and (FCParser.RunID = ctklower)) or (FCParser.RunIndex = 0)); FCParser.PreviousNonJunk; // This is the token before the template args end; { TLanguage } constructor TLanguage.Create(const FileName: string); begin inherited Create; FFileName := FileName; end; end.
unit MD5; interface uses IdHashMessageDigest, Classes, SysUtils; function MD5String(const value : string) : string; implementation function MD5String(const value : string) : string; var xMD5 : TIdHashMessageDigest5; begin xMD5 := TIdHashMessageDigest5.Create; try Result := xMD5.HashStringAsHex(value) finally xMD5.Free; end; end; end.
unit xn.dictionary; interface uses System.Generics.Collections; type IxnDictionary<K, V> = interface ['{4953A5E2-38BD-4898-B85D-7A1157739D6A}'] procedure Clear; procedure Add(const aKey: K; const aValue: V); function Count: integer; function ContainsKey(const aKey: K): Boolean; function ContainsValue(const aValue: V): Boolean; function GetEnumerator: TDictionary<K, V>.TPairEnumerator; function GetKeys: TEnumerable<K>; property Keys: TEnumerable<K> read GetKeys; function GetValues: TEnumerable<V>; property Values: TEnumerable<V> read GetValues; function GetItem(const aKey: K): V; procedure SetItem(const aKey: K; const aValue: V); property Items[const aKey: K]: V read GetItem write SetItem; default; end; TxnDictionary<K, V> = class(TInterfacedObject, IxnDictionary<K, V>) strict protected fDictionary: TDictionary<K, V>; public constructor Create; virtual; destructor Destroy; override; procedure Clear; procedure Add(const aKey: K; const aValue: V); function Count: integer; function ContainsKey(const aKey: K): Boolean; function ContainsValue(const aValue: V): Boolean; function GetEnumerator: TDictionary<K, V>.TPairEnumerator; function GetKeys: TEnumerable<K>; property Keys: TEnumerable<K> read GetKeys; function GetValues: TEnumerable<V>; property Values: TEnumerable<V> read GetValues; function GetItem(const aKey: K): V; virtual; procedure SetItem(const aKey: K; const aValue: V); virtual; property Items[const aKey: K]: V read GetItem write SetItem; default; end; implementation { TxnDictionary<K, V> } procedure TxnDictionary<K, V>.Add(const aKey: K; const aValue: V); begin fDictionary.Add(aKey, aValue); end; procedure TxnDictionary<K, V>.Clear; begin fDictionary.Clear; end; function TxnDictionary<K, V>.ContainsKey(const aKey: K): Boolean; begin Result := fDictionary.ContainsKey(aKey) end; function TxnDictionary<K, V>.ContainsValue(const aValue: V): Boolean; begin Result := fDictionary.ContainsValue(aValue) end; function TxnDictionary<K, V>.Count: integer; begin Result := fDictionary.Count; end; constructor TxnDictionary<K, V>.Create; begin fDictionary := TDictionary<K, V>.Create; end; destructor TxnDictionary<K, V>.Destroy; begin fDictionary.Free; inherited; end; function TxnDictionary<K, V>.GetEnumerator: TDictionary<K, V>.TPairEnumerator; begin Result := fDictionary.GetEnumerator; end; function TxnDictionary<K, V>.GetItem(const aKey: K): V; begin Result := fDictionary.Items[aKey] end; function TxnDictionary<K, V>.GetKeys: TEnumerable<K>; begin Result := fDictionary.Keys; end; function TxnDictionary<K, V>.GetValues: TEnumerable<V>; begin Result := fDictionary.Values; end; procedure TxnDictionary<K, V>.SetItem(const aKey: K; const aValue: V); begin fDictionary.Items[aKey] := aValue; end; end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} {$INCLUDE elpack2.inc} {$IFDEF ELPACK_SINGLECOMP} {$I ElPack.inc} {$ELSE} {$IFDEF LINUX} {$I ../ElPack.inc} {$ELSE} {$I ..\ElPack.inc} {$ENDIF} {$ENDIF} unit frmStyleImageSelect; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Clipbrd, ElXPThemedControl, ElBtnCtl, ElPopBtn, ExtCtrls, ElPanel, ElScrollBox, ElGroupBox, ElCheckCtl, ElEdits, ExtDlgs; type TImageType = (itBitmap, itIcon); TStyleImageSelectForm = class(TForm) Panel1: TElPanel; OkButton: TElPopupButton; CancelButton: TElPopupButton; ElPanel1: TElPanel; ScrollBox: TElScrollBox; Image: TImage; btnLoad: TElPopupButton; btnSave: TElPopupButton; btnClear: TElPopupButton; btnPaste: TElPopupButton; btnCopy: TElPopupButton; SD: TSaveDialog; btnMono: TElPopupButton; procedure ImageListSelClick(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure btnPasteClick(Sender: TObject); procedure btnLoadClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure btnCopyClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnMonoClick(Sender: TObject); private { Private declarations } // Open Dialog Component: fOD: {$IFNDEF D_6_UP} TOpenDialog; {$ELSE} TOpenPictureDialog; {$ENDIF} procedure WMActivate(var Msg: TWMActivate); message WM_ACTIVATE; procedure CheckEnabledPaste; procedure CheckEnabledCopy; public { Public declarations } function isImage: Boolean; procedure SaveToStream(S:TStream; Format:TImageType); procedure LoadFromStream(S:TStream; Format: TImageType); end; var StyleImageSelectForm: TStyleImageSelectForm; resourcestring rsBitmapInvalid = 'Bitmap image is not valid'; type TCursorOrIcon = packed record Reserved: Word; wType: Word; Count: Word; end; PIconRec = ^TIconRec; TIconRec = packed record Width: Byte; Height: Byte; Colors: Word; Reserved1: Word; Reserved2: Word; DIBSize: Longint; DIBOffset: Longint; end; const { Icon and cursor types } rc3_StockIcon = 0; rc3_Icon = 1; rc3_Cursor = 2; implementation {$R *.DFM} function CreateIconFromBitmap(ABitmap: TBitmap): TIcon; var sys_icon_width: integer; sys_icon_height: integer; mXorBitmap: TBitmap; mMonoBitmap: TBitmap; mBlackBitmap: TBitmap; icon_info: TIconInfo; R: TRect; TransparentColor: Tcolor; begin //??? // set the icon size sys_icon_width := GetSystemMetrics(SM_CXICON); sys_icon_height := GetSystemMetrics(SM_CYICON); R := Rect(0, 0, sys_icon_width, sys_icon_height); mMonoBitmap := nil; mBlackBitmap := nil; // create xo mask mXorBitmap := TBitmap.Create; try mXorBitmap.Width := sys_icon_width; mXorBitmap.Height := sys_icon_height; // stretch Draw mXorBitmap.canvas.draw(0, 0, Abitmap); TransparentColor := mXorBitmap.Canvas.Pixels[0, sys_icon_height - 1]; // create monochrome mask mMonoBitmap := TBitmap.Create; mMonoBitmap.Width := sys_icon_width; mMonoBitmap.Height := sys_icon_height; mMonoBitmap.Canvas.Brush.Color := Clwhite; mMonoBitmap.Canvas.FillRect(R); // create black mask mBlackBitmap := TBitmap.Create; mBlackBitmap.Width := sys_icon_width; mBlackBitmap.Height := sys_icon_height; // if transparent color is not black we We should impose the xor mask if TransparentColor <> clblack then begin mBlackBitmap.Canvas.Brush.Color := $F8F9FA; mBlackBitmap.Canvas.FillRect(R); mBlackBitmap.canvas.BrushCopy(R, mXorBitmap, R, clblack); mXorBitmap.Assign(mBlackBitmap); end; // make black mask mBlackBitmap.Canvas.Brush.Color := Clblack; mBlackBitmap.Canvas.FillRect(R); // paint xor mask (brushcopy) mBlackBitmap.canvas.BrushCopy(R, mXorBitmap, R, TransparentColor); mXorBitmap.Assign(mBlackBitmap); // set and paint the mono mask mXorBitmap.Transparent := true; mXorBitmap.TransparentColor := clblack; mMonoBitmap.Canvas.draw(0, 0, mXorBitmap); mMonoBitmap.canvas.copymode := cmsrcinvert; mMonoBitmap.canvas.CopyRect(R, mXorBitmap.canvas, R); mMonoBitmap.monochrome := true; // restore the black color in the image mBlackBitmap.Canvas.Brush.Color := Clblack; mBlackBitmap.Canvas.FillRect(R); mBlackBitmap.canvas.BrushCopy(R, mXorBitmap, R, $F8F9FA); mXorBitmap.Assign(mBlackBitmap); // Create icon Result := TIcon.Create; try icon_info.fIcon := true; icon_info.xHotspot := 0; icon_info.yHotspot := 0; icon_info.hbmMask := mMonoBitmap.Handle; icon_info.hbmColor := mXorBitmap.Handle; Result.Handle := CreateIconIndirect(icon_info); except Result.Free; Result := nil; raise; end; finally // free temporary bitmaps mXorBitmap.Free; mMonoBitmap.free; mBlackBitmap.free; end; end; procedure SaveColorIconToStream(Stream: TStream; Icon: HICON); function BytesPerScanline(PixelsPerScanline, BitsPerPixel, Alignment: Longint): Longint; begin Dec(Alignment); Result := ((PixelsPerScanline * BitsPerPixel) + Alignment) and not Alignment; Result := Result div 8; end; procedure InitBitmapInfo(hBitmap: HBITMAP; var BI: TBitmapInfoHeader; Colors: Integer); var DIBSec: TDIBSection; cBytes: Integer; begin DIBSec.dsbmih.biSize := 0; cBytes := GetObject(hBitmap, SizeOf(TDIBSection), @DIBSec); if cBytes = 0 then raise Exception.Create(rsBitmapInvalid) else with DIBSec do if (cBytes >= (SizeOf(dsbm) + SizeOf(dsbmih))) and (dsbmih.biSize >= DWORD(SizeOf(dsbmih))) then BI := DIBSec.dsbmih else begin FillChar(BI, SizeOf(BI), 0); with BI, DIBSec.dsbm do begin biSize := SizeOf(TBitmapInfoHeader); biWidth := bmWidth; biHeight := bmHeight; end; end; with BI do begin if Colors <> 0 then case Colors of 2: biBitCount := 1; 16: biBitCount := 4; 256: biBitCount := 8; end else biBitCount := DIBSec.dsbm.bmBitsPixel * DIBSec.dsbm.bmPlanes; biPlanes := 1; if biSizeImage = 0 then biSizeImage := BytesPerScanLine(biWidth, biBitCount, 32) * Abs(BI.biHeight); end; end; procedure _SetDIBSizes(Bitmap: HBITMAP; var InfoHeaderSize: DWORD; var ImageSize: DWORD; Colors: Integer); var BI: TBitmapInfoHeader; begin InitBitmapInfo(Bitmap, BI, Colors); if BI.biBitCount > 8 then begin InfoHeaderSize := SizeOf(TBitmapInfoHeader); if (BI.biCompression and BI_BITFIELDS) <> 0 then Inc(InfoHeaderSize, 12); end else InfoHeaderSize := SizeOf(TBitmapInfoHeader) + SizeOf(TRGBQuad) * (1 shl BI.biBitCount); ImageSize := BI.biSizeImage; end; function _SetDIB(Bitmap: HBITMAP; Palette: HPALETTE; var BitmapInfo; var Bits; Colors: Integer): Boolean; var OldPalete: HPALETTE; DC: HDC; begin InitBitmapInfo(Bitmap, TBitmapInfoHeader(BitmapInfo), Colors); OldPalete := 0; DC := CreateCompatibleDC(0); try if Palette <> 0 then begin OldPalete := SelectPalette(DC, Palette, False); RealizePalette(DC); end; Result := GetDIBits(DC, Bitmap, 0, TBitmapInfoHeader(BitmapInfo).biHeight, @Bits, TBitmapInfo(BitmapInfo), DIB_RGB_COLORS) <> 0; finally if OldPalete <> 0 then SelectPalette(DC, OldPalete, False); DeleteDC(DC); end; end; var IconInfo: TIconInfo; MonoInfoSize, ColorInfoSize: DWORD; MonoBitsSize, ColorBitsSize: DWORD; MonoInfo, MonoBits, ColorInfo, ColorBits: Pointer; CI: TCursorOrIcon; List: TIconRec; begin FillChar(CI, SizeOf(CI), 0); FillChar(List, SizeOf(List), 0); if not GetIconInfo(Icon, IconInfo) then {$IFNDEF D_6_UP} raise Exception.Create('Windows error. Code:' + IntToStr(Windows.GetLastError)); {$ELSE} RaiseLastOSError; {$ENDIF} try _SetDIBSizes(IconInfo.hbmMask, MonoInfoSize, MonoBitsSize, 2); _SetDIBSizes(IconInfo.hbmColor, ColorInfoSize, ColorBitsSize, 256); MonoInfo := nil; MonoBits := nil; ColorInfo := nil; ColorBits := nil; try MonoInfo := AllocMem(MonoInfoSize); MonoBits := AllocMem(MonoBitsSize); ColorInfo := AllocMem(ColorInfoSize); ColorBits := AllocMem(ColorBitsSize); _SetDIB(IconInfo.hbmMask, 0, MonoInfo^, MonoBits^, 2); _SetDIB(IconInfo.hbmColor, 0, ColorInfo^, ColorBits^, 256); with CI do begin CI.wType := RC3_ICON; CI.Count := 1; end; Stream.Write(CI, SizeOf(CI)); with List, PBitmapInfoHeader(ColorInfo)^ do begin Width := biWidth; Height := biHeight; Colors := biPlanes * biBitCount; DIBSize := ColorInfoSize + ColorBitsSize + MonoBitsSize; DIBOffset := SizeOf(CI) + SizeOf(List); end; Stream.Write(List, SizeOf(List)); with PBitmapInfoHeader(ColorInfo)^ do Inc(biHeight, biHeight); { color height includes mono bits } Stream.Write(ColorInfo^, ColorInfoSize); Stream.Write(ColorBits^, ColorBitsSize); Stream.Write(MonoBits^, MonoBitsSize); finally FreeMem(ColorInfo, ColorInfoSize); FreeMem(ColorBits, ColorBitsSize); FreeMem(MonoInfo, MonoInfoSize); FreeMem(MonoBits, MonoBitsSize); end; finally DeleteObject(IconInfo.hbmColor); DeleteObject(IconInfo.hbmMask); end; end; procedure ConvertColoredCanvasToMono(C: TCanvas); var X, Y: Integer; Color: LongInt; R, G, B, ConvertedColor: Byte; begin with C do for X := Cliprect.Left to ClipRect.Right do for Y := Cliprect.Top to ClipRect.Bottom do begin Color := ColorToRGB(Pixels[X, Y]); B := (Color and $FF0000) shr 16; G := (Color and $FF00) shr 8; R := (Color and $FF); ConvertedColor := HiByte(R * 77 + G * 151 + B * 28); Pixels[X, Y] := RGB(ConvertedColor, ConvertedColor, ConvertedColor); end; end; { TStyleImageSelectForm } procedure TStyleImageSelectForm.FormCreate(Sender: TObject); begin fOD := {$IFNDEF D_6_UP} TOpenDialog.Create(Self); {$ELSE} TOpenPictureDialog.Create(Self); {$ENDIF} // properties: fOD.InitialDir := '.'; fOD.Options := fOD.Options - [ofHideReadOnly]; fOD.Filter := 'All Images (*.jpg;*.jpeg;*.bmp;*.ico;*.emf;*.wmf)|*.jpg;*.jpeg;*.bmp;*.ico;*.emf;*.wmf|' + 'JPEG Image File (*.jpg)|*.jpg|' + 'JPEG Image File (*.jpeg)|*.jpeg|' + 'Bitmaps (*.bmp)|*.bmp|' + 'Icons (*.ico)|*.ico|' + 'Enhanced Metafiles (*.emf)|*.emf|' + 'Metafiles (*.wmf)|*.wmf|' + 'All (*.*)|*.*'; fOD.Title := 'Load image file'; end; function TStyleImageSelectForm.isImage: Boolean; begin Result := Assigned(Image.Picture.Graphic) and (not Image.Picture.Graphic.Empty); end; procedure TStyleImageSelectForm.ImageListSelClick(Sender: TObject); begin //editImageList.Enabled := radioFindImageList.Checked; end; procedure TStyleImageSelectForm.btnClearClick(Sender: TObject); begin Image.Picture.Assign(nil); CheckEnabledCopy(); btnSave.Enabled := isImage; btnClear.Enabled := btnSave.Enabled; btnMono.Enabled := btnSave.Enabled; end; //Load Image: procedure TStyleImageSelectForm.btnLoadClick(Sender: TObject); begin if not fOD.Execute then exit; Screen.Cursor := crHourGlass; try Image.Picture.LoadFromFile(fOD.FileName); finally Screen.Cursor := crDefault; end; CheckEnabledCopy(); btnSave.Enabled := isImage; btnClear.Enabled := btnSave.Enabled; btnMono.Enabled := btnSave.Enabled; end; //Save Image: procedure TStyleImageSelectForm.btnSaveClick(Sender: TObject); procedure SaveGraphicAsBitmap(APixelFormat: TPixelFormat); var B: TBitmap; Graphic: TGraphic; begin if (Image.Picture.Graphic is TBitmap) and (Image.Picture.Bitmap.PixelFormat = APixelFormat) then begin Image.Picture.SaveToFile(SD.FileName); exit; end; Graphic := Image.Picture.Graphic; B := TBitmap.Create; with B do try Width := Graphic.Width; Height := Graphic.Height; PixelFormat := APixelFormat; Canvas.Draw(0, 0, Graphic); SaveToFile(SD.FileName); finally B.Free; end; end; procedure SaveGraphicAsIco(APixelFormat: TPixelFormat); var Icon: TIcon; FS: TFilestream; B: TBitmap; begin if (Image.Picture.Graphic is TIcon) then begin FS:=TFileStream.Create (SD.FileName, fmCreate or fmOpenWrite); try // 16 colors: // Image.Picture.Icon.SaveToStream(FS); // 2, 16, 256 colors: SaveColorIconToStream(FS, Image.Picture.Icon.Handle); finally FS.Free; end; exit; end; if Image.Picture.Graphic is TBitmap then begin B := Image.Picture.Bitmap; if B.PixelFormat = APixelFormat then begin FS := nil; Icon := CreateIconFromBitmap(B); if Assigned(Icon) then try FS := TFileStream.Create(SD.FileName, fmCreate or fmOpenWrite); // 16 colors: // Icon.SaveToStream(FS); // 2, 16, 256 colors: SaveColorIconToStream(FS, Icon.Handle); finally FS.Free; Icon.Free; end; exit; end; end; //convert Graphics to Bitmap B := TBitmap.Create; with B do try Width := Image.Picture.Width; Height := Image.Picture.Height; PixelFormat := APixelFormat; Canvas.Draw(0, 0, Image.Picture.Graphic); Icon := CreateIconFromBitmap(B); finally B.Free; end; FS := nil; if Assigned(Icon) then try FS := TFileStream.Create(SD.FileName, fmCreate or fmOpenWrite); // 16 colors: // Icon.SaveToFile(SD.FileName); // 2, 16, 256 colors: SaveColorIconToStream(FS, Icon.Handle); finally Icon.Free; FS.Free; end; end; const cPixelFormat: array[1..4] of TPixelFormat = (pf24bit, pf8bit, pf4bit, pf1bit); procedure CheckExtension(const Ext: string); var vExt: string; begin vExt := ExtractFileExt(SD.FileName); if CompareText(vExt, Ext) <> 0 then SD.FileName := SD.FileName + Ext; end; begin if not isImage then exit; // select default(base) type if (Image.Picture.Graphic is TBitmap) then begin case Image.Picture.Bitmap.PixelFormat of pf1bit: SD.FilterIndex := 4; pf4bit: SD.FilterIndex := 3; pf8bit: SD.FilterIndex := 2; else SD.FilterIndex := 1; end; end else if (Image.Picture.Graphic is TIcon) then begin if not (SD.FilterIndex in [5..7]) then SD.FilterIndex := 5; end else SD.FilterIndex := 8; if not SD.Execute then exit; Screen.Cursor := crHourGlass; try with Image.Picture do case SD.FilterIndex of 1..4: // Save as *.bmp (if source is ico or bitmap) begin CheckExtension('.bmp'); SaveGraphicAsBitmap(cPixelFormat[SD.FilterIndex]) end; 5..7: // Save as *.ico (if source is ico or bitmap) begin CheckExtension('.ico'); SaveGraphicAsIco(cPixelFormat[SD.FilterIndex - 3]) end; else // Other: *.* - save to base format of Image.Picture.Graphic SaveToFile(SD.FileName); end; finally Screen.Cursor := crDefault; end; CheckEnabledCopy; end; // Copy Image to clipboard: procedure TStyleImageSelectForm.btnCopyClick(Sender: TObject); {var imgFormat :Word; imgData :THandle; imgPalette :HPALETTE;{} begin if (not isImage) then exit; { Image.Picture.SaveToClipboardFormat(imgFormat, imgData, imgPalette) ClipBoard.SetAsHandle(imgFormat,imgData); {} Screen.Cursor := crHourGlass; try Clipboard.Assign(Image.Picture); finally Screen.Cursor := crDefault; end; CheckEnabledPaste; end; // Paste from Clipboard into image: procedure TStyleImageSelectForm.btnPasteClick(Sender: TObject); var Palette: HPALETTE; begin Screen.Cursor := crHourGlass; try if Clipboard.HasFormat(CF_BITMAP) then Palette := CF_BITMAP else if Clipboard.HasFormat(CF_PICTURE) then Palette := CF_PICTURE else if Clipboard.HasFormat(CF_METAFILEPICT) then Palette := CF_METAFILEPICT else Palette := 0; if Palette <> 0 then Image.Picture.LoadFromClipboardFormat(cf_BitMap, ClipBoard.GetAsHandle(cf_Bitmap), 0) else Image.Picture.Assign(Clipboard); CheckEnabledCopy; btnSave.Enabled := isImage; btnClear.Enabled := btnSave.Enabled; btnMono.Enabled := btnSave.Enabled; finally Screen.Cursor := crDefault; end; end; // check clipboard on activate window procedure TStyleImageSelectForm.WMActivate(var Msg: TWMActivate); begin if Msg.Active <> WA_INACTIVE then CheckEnabledPaste; inherited; end; procedure TStyleImageSelectForm.CheckEnabledPaste; begin btnPaste.Enabled := Clipboard.HasFormat(CF_BITMAP) or Clipboard.HasFormat(CF_METAFILEPICT) or Clipboard.HasFormat(CF_PICTURE); end; // check allow copy if assigned image procedure TStyleImageSelectForm.CheckEnabledCopy; begin btnCopy.Enabled := isImage; end; // convert colored image to black/white colors procedure TStyleImageSelectForm.btnMonoClick(Sender: TObject); begin if (not isImage) then exit; Screen.Cursor := crHourGlass; try ConvertColoredCanvasToMono(Image.Canvas); finally Screen.Cursor := crDefault; end; end; procedure TStyleImageSelectForm.LoadFromStream(S: TStream; Format: TImageType); procedure LoadAsBitmap; var B:TBitmap; begin B := TBitmap.Create; try B.LoadFromStream(S); Image.Picture.Assign(B); finally B.Free; end; end; procedure LoadAsIco; var Ico:TIcon; begin Ico := TIcon.Create; try Ico.LoadFromStream(S); Image.Picture.Assign(Ico); finally Ico.Free; end; end; begin if (S=nil)or(S.Position = S.Size) then begin btnClearClick(Self); exit; end; try if Format = itBitmap then LoadAsBitmap else { when Format == itIcon } LoadAsIco; except btnClearClick(Self); raise; end; CheckEnabledCopy(); btnSave.Enabled := isImage; btnClear.Enabled := btnSave.Enabled; btnMono.Enabled := btnSave.Enabled; end; procedure TStyleImageSelectForm.SaveToStream(S: TStream; Format: TImageType); procedure SaveGraphicAsBitmap; var B:TBitmap; Graphic:TGraphic; begin if (Image.Picture.Graphic is TBitmap) then Image.Picture.Bitmap.SaveToStream(S) else begin Graphic := Image.Picture.Graphic; B := TBitmap.Create; with B do try Width := Graphic.Width; Height := Graphic.Height; if (Image.Picture.Graphic is TIcon) then PixelFormat := pf8bit else PixelFormat := pf24bit; Canvas.Draw(0, 0, Graphic); SaveToStream(S); finally B.Free; end; end; end; procedure SaveGraphicAsIco; var Icon:TIcon; B:TBitmap; begin if (Image.Picture.Graphic is TIcon) then //16 colors: //Image.Picture.Icon.SaveToStream(S) // 2, 16, 256 colors: SaveColorIconToStream(S, Image.Picture.Icon.Handle) else if Image.Picture.Graphic is TBitmap then begin B := Image.Picture.Bitmap; Icon := CreateIconFromBitmap(B); try if Assigned(Icon) then //16 colors: //Icon.SaveToStream(S); // 2, 16, 256 colors: SaveColorIconToStream(S, Icon.Handle); finally Icon.Free; end; end else begin //convert Graphics to Bitmap B := TBitmap.Create; with B do try Width := Image.Picture.Width; Height := Image.Picture.Height; PixelFormat := pf8bit; Canvas.Draw(0, 0, Image.Picture.Graphic); Icon := CreateIconFromBitmap(B); finally B.Free; end; if Assigned(Icon) then try // 16 colors: // Icon.SaveToStream(S); // 2, 16, 256 colors: SaveColorIconToStream(S, Icon.Handle); finally Icon.Free; end; end; end; begin if not isImage then exit; if Format = itBitmap then SaveGraphicAsBitmap else { when Format == itIcon } SaveGraphicAsIco; end; end.
PROGRAM SqureRoot; VAR number : Real; VAR rt : Real; (* PROCEDURE SqrtKit(r : Real); VAR precision : Real; VAR x : Real; VAR y : Real; VAR enough : Boolean; VAR loopcnt : Integer; BEGIN precision := 1E-12; x := 1.0; enough := false; loopcnt := 0; WHILE NOT enough DO BEGIN y := r / x; x := (x + y) / 2.0; WriteLn('trace of x: ', x); enough := Abs(x*x - r) <= precision; INC(loopcnt) END; WriteLn('the square root of ', r, ' is: ', x); WriteLn('loop count is: ', loopcnt); END; *) FUNCTION BinSqrt(r : Real) : Real; CONST precision = 1E-15; VAR lb, ub : Real; VAR x, z : Real; VAR y : Integer; BEGIN y := 0; WHILE (y * y < r) DO Inc(y); lb := 1.0 * (y - 1); ub := 1.0 * y; y := 0; REPEAT z := (lb + ub) / 2; x := z*z - r; IF x > 0 THEN ub := z ELSE lb := z; Inc(y) UNTIL Abs(x) < precision; Writeln('loop count: ', y); BinSqrt := z END; BEGIN number := 7.91; rt := BinSqrt(number); WriteLn('Result of binary sqrt procedure: ', rt); WriteLn('Result of builtin sqrt procedure: ', Sqrt(number)) END.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clHtmlParser; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes; {$ELSE} System.Classes, System.Types; {$ENDIF} type TclHtmlParseMethod = (pmAll, pmTagsOnly, pmTextOnly); TclHtmlTag = class; TclHtmlParser = class; TclHtmlAttribute = class private FValue: string; FName: string; FOwner: TclHtmlTag; FInnerTextPos: Integer; public constructor Create(const AName, AValue: string; AInnerTextPos: Integer); property Name: string read FName; property Value: string read FValue; property Owner: TclHtmlTag read FOwner; property InnerTextPos: Integer read FInnerTextPos; end; TclHtmlTag = class private FAttributes: TList; FName: string; FOwner: TclHtmlTag; FText: string; FIsText: Boolean; FParser: TclHtmlParser; FTagSource: string; FNextTag: TclHtmlTag; FIsClosingTag: Boolean; FInnerTextPos: Integer; function GetAttribute(Index: Integer): TclHtmlAttribute; function GetAttributeCount: Integer; procedure ClearAttributes; procedure AddAttribute(Attribute: TclHtmlAttribute); function GetText: string; protected procedure BeforeParseTag; virtual; procedure AfterParseTag; virtual; function CanAddTableCellTag: Boolean; virtual; public constructor Create(const AName, ATagSource: string; AOwner: TclHtmlTag; AParser: TclHtmlParser); destructor Destroy; override; function AttributeByName(const AName: string): TclHtmlAttribute; function AttributeValue(const AName: string): string; property Owner: TclHtmlTag read FOwner; property Name: string read FName; property IsText: Boolean read FIsText; property TagSource: string read FTagSource; property Text: string read GetText; property Attributes[Index: Integer]: TclHtmlAttribute read GetAttribute; property AttributeCount: Integer read GetAttributeCount; property Parser: TclHtmlParser read FParser; property NextTag: TclHtmlTag read FNextTag; property IsClosingTag: Boolean read FIsClosingTag; property InnerTextPos: Integer read FInnerTextPos; end; TclHtmlTagList = class private FList: TList; FOwnsObjects: Boolean; function GetCount: Integer; function GetItem(Index: Integer): TclHtmlTag; function GetLast: TclHtmlTag; function GetFirst: TclHtmlTag; function GetStartFromIndex(StartFrom: TclHtmlTag): Integer; protected procedure Clear; procedure Add(AItem: TclHtmlTag); public constructor Create(AOwnsObjects: Boolean); destructor Destroy; override; procedure AssignList(AList: TStrings); function TagByName(const AName: string; StartFrom: TclHtmlTag = nil): TclHtmlTag; function TagByAttributeName(const AName, AttrName, AttrValue: string; StartFrom: TclHtmlTag = nil): TclHtmlTag; function IndexOf(ATag: TclHtmlTag): Integer; property Items[Index: Integer]: TclHtmlTag read GetItem; default; property Count: Integer read GetCount; property First: TclHtmlTag read GetFirst; property Last: TclHtmlTag read GetLast; property OwnsObjects: Boolean read FOwnsObjects; end; TclHtmlForm = class(TclHtmlTag) private FControls: TclHtmlTagList; function GetAction: string; function GetEncType: string; function GetFormName: string; function GetMethod: string; protected procedure BeforeParseTag; override; procedure AfterParseTag; override; public constructor Create(const AName, AText: string; AOwner: TclHtmlTag; AParser: TclHtmlParser); destructor Destroy; override; property Controls: TclHtmlTagList read FControls; property FormName: string read GetFormName; property Action: string read GetAction; property EncType: string read GetEncType; property Method: string read GetMethod; end; TclHtmlFormList = class(TclHtmlTagList) private function GetItem(Index: Integer): TclHtmlForm; public function FormByName(const AName: string; StartFrom: TclHtmlTag = nil): TclHtmlForm; property Items[Index: Integer]: TclHtmlForm read GetItem; default; end; TclHtmlMetaTag = class(TclHtmlTag) private function GetContent: string; function GetHttpEquiv: string; function GetMetaName: string; protected procedure BeforeParseTag; override; procedure AfterParseTag; override; public property MetaName: string read GetMetaName; property Content: string read GetContent; property HttpEquiv: string read GetHttpEquiv; end; TclHtmlMetaTagList = class(TclHtmlTagList) private function GetItem(Index: Integer): TclHtmlMetaTag; public property Items[Index: Integer]: TclHtmlMetaTag read GetItem; default; end; TclHtmlLink = class(TclHtmlTag) private FTags: TclHtmlTagList; function GetHref: string; function GetTarget: string; function GetLinkText: string; protected procedure BeforeParseTag; override; procedure AfterParseTag; override; public constructor Create(const AName, AText: string; AOwner: TclHtmlTag; AParser: TclHtmlParser); destructor Destroy; override; property Href: string read GetHref; property Target: string read GetTarget; property Tags: TclHtmlTagList read FTags; property LinkText: string read GetLinkText; end; TclHtmlLinkList = class(TclHtmlTagList) private function GetItem(Index: Integer): TclHtmlLink; public property Items[Index: Integer]: TclHtmlLink read GetItem; default; end; TclHtmlFrame = class(TclHtmlTag) private function GetSrc: string; protected procedure BeforeParseTag; override; procedure AfterParseTag; override; public property Src: string read GetSrc; end; TclHtmlFrameList = class(TclHtmlTagList) private function GetItem(Index: Integer): TclHtmlFrame; public property Items[Index: Integer]: TclHtmlFrame read GetItem; default; end; TclHtmlImage = class(TclHtmlTag) private function GetAlt: string; function GetHeight: Integer; function GetSrc: string; function GetWidth: Integer; protected procedure BeforeParseTag; override; procedure AfterParseTag; override; public property Src: string read GetSrc; property Alt: string read GetAlt; property Height: Integer read GetHeight; property Width: Integer read GetWidth; end; TclHtmlImageList = class(TclHtmlTagList) private function GetItem(Index: Integer): TclHtmlImage; public property Items[Index: Integer]: TclHtmlImage read GetItem; default; end; TclHtmlTableCell = class(TclHtmlTag) private FTags: TclHtmlTagList; function GetColSpan: Integer; function GetHeight: Integer; function GetRowSpan: Integer; function GetWidth: Integer; protected procedure BeforeParseTag; override; procedure AfterParseTag; override; function CanAddTableCellTag: Boolean; override; public constructor Create(const AName, AText: string; AOwner: TclHtmlTag; AParser: TclHtmlParser); destructor Destroy; override; property Tags: TclHtmlTagList read FTags; property ColSpan: Integer read GetColSpan; property RowSpan: Integer read GetRowSpan; property Width: Integer read GetWidth; property Height: Integer read GetHeight; end; TclHtmlTableCellList = class(TclHtmlTagList) private function GetItem(Index: Integer): TclHtmlTableCell; public property Items[Index: Integer]: TclHtmlTableCell read GetItem; default; end; TclHtmlTableRow = class(TclHtmlTag) private FCells: TclHtmlTableCellList; protected procedure BeforeParseTag; override; procedure AfterParseTag; override; function CanAddTableCellTag: Boolean; override; public constructor Create(const AName, AText: string; AOwner: TclHtmlTag; AParser: TclHtmlParser); destructor Destroy; override; property Cells: TclHtmlTableCellList read FCells; end; TclHtmlTableRowList = class(TclHtmlTagList) private function GetItem(Index: Integer): TclHtmlTableRow; public property Items[Index: Integer]: TclHtmlTableRow read GetItem; default; end; TclHtmlTable = class(TclHtmlTag) private FRows: TclHtmlTableRowList; function GetBorder: Integer; function GetCellPadding: Integer; function GetCellSpacing: Integer; function GetHeight: Integer; function GetWidth: Integer; protected procedure BeforeParseTag; override; procedure AfterParseTag; override; public constructor Create(const AName, AText: string; AOwner: TclHtmlTag; AParser: TclHtmlParser); destructor Destroy; override; property Rows: TclHtmlTableRowList read FRows; property Border: Integer read GetBorder; property CellSpacing: Integer read GetCellSpacing; property CellPadding: Integer read GetCellPadding; property Width: Integer read GetWidth; property Height: Integer read GetHeight; end; TclHtmlTableList = class(TclHtmlTagList) private function GetItem(Index: Integer): TclHtmlTable; public property Items[Index: Integer]: TclHtmlTable read GetItem; default; end; TclOnParseTag = procedure(Sender: TObject; ATag: TclHtmlTag) of object; TclOnParseForm = procedure(Sender: TObject; AForm: TclHtmlForm) of object; TclOnParseLink = procedure(Sender: TObject; ALink: TclHtmlLink) of object; TclOnParseFrame = procedure(Sender: TObject; AFrame: TclHtmlFrame) of object; TclOnParseImage = procedure(Sender: TObject; AImage: TclHtmlImage) of object; TclOnParseAttribute = procedure(Sender: TObject; ATag: TclHtmlTag; Attribute: TclHtmlAttribute) of object; TclOnParseFormControl = procedure(Sender: TObject; AForm: TclHtmlForm; AControl: TclHtmlTag) of object; TclOnParseTable = procedure(Sender: TObject; ATable: TclHtmlTable) of object; TclOnParseTableRow = procedure(Sender: TObject; ATable: TclHtmlTable; ARow: TclHtmlTableRow) of object; TclOnParseTableCell = procedure(Sender: TObject; ATable: TclHtmlTable; ARow: TclHtmlTableRow; ACell: TclHtmlTableCell) of object; TclOnParseTableCellTag = procedure(Sender: TObject; ATable: TclHtmlTable; ARow: TclHtmlTableRow; ACell: TclHtmlTableCell; ATag: TclHtmlTag) of object; TclOnParseMetaTag = procedure(Sender: TObject; ATag: TclHtmlMetaTag) of object; TclCheckLexemResult = (clNone, clEnterTag, clLeaveTag); TclTagLexemChecker = class private FLexems: TStrings; FEndLexems: TStrings; FCheckedLexem: Integer; procedure CheckLexem(AKey: Char; const ALexem: string; var ALexemCount: Integer); public constructor Create; destructor Destroy; override; procedure AddLexem(const ALexem, AEndLexem: string); function CheckLexems(AKey: Char): TclCheckLexemResult; property CheckedLexem: Integer read FCheckedLexem; property Lexems: TStrings read FLexems; property EndLexems: TStrings read FEndLexems; end; TclHtmlTagStack = class private FList: TList; function GetIsEmpty: Boolean; function GetTop: TclHtmlTag; public constructor Create; destructor Destroy; override; function Push(AItem: TclHtmlTag): TclHtmlTag; function Pop: TclHtmlTag; property Top: TclHtmlTag read GetTop; property IsEmpty: Boolean read GetIsEmpty; end; TclSymbolType = (stDontCare, stQuote, stDelimiter, stWhiteSpace); TclHtmlTitleStatus = (tsNone, tsEnterHead, tsEnterTitle, tsTitleParsed); TclHtmlParser = class(TComponent) private FTags: TclHtmlTagList; FForms: TclHtmlFormList; FLinks: TclHtmlLinkList; FImages: TclHtmlImageList; FFrames: TclHtmlFrameList; FTables: TclHtmlTableList; FMetaTags: TclHtmlMetaTagList; FKeywords: string; FDescription: string; FAuthor: string; FTitle: string; FParseMethod: TclHtmlParseMethod; FIncludeClosingTags: Boolean; FTableStack: TclHtmlTagStack; FCurrentLink: TclHtmlLink; FNonClosingTags: TStrings; FTitleStatus: TclHtmlTitleStatus; FOnParseForm: TclOnParseForm; FOnParseFormControl: TclOnParseFormControl; FOnParseLink: TclOnParseLink; FOnParseImage: TclOnParseImage; FOnParseAttribute: TclOnParseAttribute; FOnParseTag: TclOnParseTag; FOnParseTable: TclOnParseTable; FOnParseTableCell: TclOnParseTableCell; FOnParseTableCellTag: TclOnParseTableCellTag; FOnParseTableRow: TclOnParseTableRow; FOnParseFrame: TclOnParseFrame; FOnParseMetaTag: TclOnParseMetaTag; function CreateAttribute(ATag: TclHtmlTag; const AName, AValue: string; AInnerTextPos: Integer): TclHtmlAttribute; function NeedParseTags: Boolean; function NeedParseText: Boolean; function AddTableCellTag(ATag: TclHtmlTag): Boolean; function IsNonClosingTag(ATagName: string): Boolean; procedure ExtractMetaTags; function RemoveBadChars(const S: string): string; function GetTypeFromSymbol(AKey: Char): TclSymbolType; procedure ProcessTitleStatus(const AName: string); procedure InternalParseTag(ATag: TclHtmlTag; const ALexem: string; ALexemPos: Integer); protected procedure AddToControls(ATag, AOwner: TclHtmlTag); procedure DoParseTag(ATag: TclHtmlTag); dynamic; procedure DoParseAttribute(ATag: TclHtmlTag; Attribute: TclHtmlAttribute); dynamic; procedure DoParseForm(AForm: TclHtmlForm); dynamic; procedure DoParseLink(ALink: TclHtmlLink); dynamic; procedure DoParseFrame(AFrame: TclHtmlFrame); dynamic; procedure DoParseImage(AImage: TclHtmlImage); dynamic; procedure DoParseFormControl(AForm: TclHtmlForm; AControl: TclHtmlTag); dynamic; procedure DoParseTable(ATable: TclHtmlTable); dynamic; procedure DoParseTableRow(ATable: TclHtmlTable; ARow: TclHtmlTableRow); dynamic; procedure DoParseTableCell(ATable: TclHtmlTable; ARow: TclHtmlTableRow; ACell: TclHtmlTableCell); dynamic; procedure DoParseTableCellTag(ATable: TclHtmlTable; ARow: TclHtmlTableRow; ACell: TclHtmlTableCell; ATag: TclHtmlTag); dynamic; procedure DoParseMetaTag(AMetaTag: TclHtmlMetaTag); dynamic; function CreateText(const AText: string; AOwner: TclHtmlTag; AInnerTextPos: Integer): TclHtmlTag; virtual; function CreateTag(const ALexem: string; AOwner: TclHtmlTag; AInnerTextPos, AttribPos: Integer): TclHtmlTag; virtual; function CreateTagByName(const AName, AText: string; AOwner: TclHtmlTag; AInnerTextPos: Integer): TclHtmlTag; virtual; procedure ParseTag(ATag: TclHtmlTag; const ALexem: string; ALexemPos: Integer); virtual; procedure GetSkipLexems(ASkipLexems: TclTagLexemChecker); virtual; procedure GetNonClosingTags(ATags: TStrings); virtual; procedure AddTag(ATag: TclHtmlTag); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Clear; virtual; procedure Parse(const AHtml: string); overload; procedure Parse(const AHtml: TStrings); overload; property Tags: TclHtmlTagList read FTags; property Forms: TclHtmlFormList read FForms; property Links: TclHtmlLinkList read FLinks; property Images: TclHtmlImageList read FImages; property Tables: TclHtmlTableList read FTables; property Frames: TclHtmlFrameList read FFrames; property MetaTags: TclHtmlMetaTagList read FMetaTags; property Title: string read FTitle; property Author: string read FAuthor; property Description: string read FDescription; property Keywords: string read FKeywords; published property ParseMethod: TclHtmlParseMethod read FParseMethod write FParseMethod default pmTagsOnly; property IncludeClosingTags: Boolean read FIncludeClosingTags write FIncludeClosingTags default False; property OnParseTag: TclOnParseTag read FOnParseTag write FOnParseTag; property OnParseAttribute: TclOnParseAttribute read FOnParseAttribute write FOnParseAttribute; property OnParseForm: TclOnParseForm read FOnParseForm write FOnParseForm; property OnParseLink: TclOnParseLink read FOnParseLink write FOnParseLink; property OnParseFrame: TclOnParseFrame read FOnParseFrame write FOnParseFrame; property OnParseImage: TclOnParseImage read FOnParseImage write FOnParseImage; property OnParseFormControl: TclOnParseFormControl read FOnParseFormControl write FOnParseFormControl; property OnParseTable: TclOnParseTable read FOnParseTable write FOnParseTable; property OnParseTableRow: TclOnParseTableRow read FOnParseTableRow write FOnParseTableRow; property OnParseTableCell: TclOnParseTableCell read FOnParseTableCell write FOnParseTableCell; property OnParseTableCellTag: TclOnParseTableCellTag read FOnParseTableCellTag write FOnParseTableCellTag; property OnParseMetaTag: TclOnParseMetaTag read FOnParseMetaTag write FOnParseMetaTag; end; {$IFNDEF MACOS} {$IFDEF DEMO} {$IFNDEF IDEDEMO} var IsHtmlDemoDisplayed: Boolean = False; {$ENDIF} {$ENDIF} {$ENDIF} implementation uses {$IFNDEF DELPHIXE2} SysUtils{$IFNDEF MACOS}{$IFDEF DEMO}, Forms{$ENDIF}, Windows{$ENDIF}; {$ELSE} System.SysUtils{$IFNDEF MACOS}{$IFDEF DEMO}, Vcl.Forms{$ENDIF}, Winapi.Windows{$ENDIF}; {$ENDIF} { TclHtmlTag } procedure TclHtmlTag.AddAttribute(Attribute: TclHtmlAttribute); begin FAttributes.Add(Attribute); Attribute.FOwner := Self; end; procedure TclHtmlTag.AfterParseTag; begin if (SameText('input', Name) or SameText('select', Name) or SameText('textarea', Name)) then begin Parser.AddToControls(Self, Owner); end; end; function TclHtmlTag.AttributeByName(const AName: string): TclHtmlAttribute; var i: Integer; begin for i := 0 to AttributeCount - 1 do begin if SameText(Attributes[i].Name, AName) then begin Result := Attributes[i]; Exit; end; end; Result := nil; end; function TclHtmlTag.AttributeValue(const AName: string): string; var Attr: TclHtmlAttribute; begin Attr := AttributeByName(AName); if (Attr <> nil) then begin Result := Attr.Value; end else begin Result := ''; end; end; procedure TclHtmlTag.BeforeParseTag; begin end; function TclHtmlTag.CanAddTableCellTag: Boolean; begin Result := True; end; procedure TclHtmlTag.ClearAttributes; var i: Integer; begin for i := 0 to AttributeCount - 1 do begin Attributes[i].Free(); end; FAttributes.Clear(); end; constructor TclHtmlTag.Create(const AName, ATagSource: string; AOwner: TclHtmlTag; AParser: TclHtmlParser); begin inherited Create(); FAttributes := TList.Create(); FName := AName; FTagSource := ATagSource; FText := ATagSource; FOwner := AOwner; FParser := AParser; end; destructor TclHtmlTag.Destroy; begin ClearAttributes(); FAttributes.Free(); inherited Destroy(); end; function TclHtmlTag.GetAttribute(Index: Integer): TclHtmlAttribute; begin Result := TclHtmlAttribute(FAttributes[Index]); end; function TclHtmlTag.GetAttributeCount: Integer; begin Result := FAttributes.Count; end; function TclHtmlTag.GetText: string; begin if IsText then begin Result := TagSource; end else if (NextTag <> nil) and NextTag.IsText and (NextTag.Owner <> Owner) then begin Result := NextTag.Text; end else begin Result := ''; end; end; { TclHtmlTagList } constructor TclHtmlTagList.Create(AOwnsObjects: Boolean); begin inherited Create(); FList := TList.Create(); FOwnsObjects := AOwnsObjects; end; destructor TclHtmlTagList.Destroy; begin Clear(); FList.Free(); inherited Destroy(); end; function TclHtmlTagList.TagByAttributeName(const AName, AttrName, AttrValue: string; StartFrom: TclHtmlTag): TclHtmlTag; var i: Integer; Attr: TclHtmlAttribute; begin for i := GetStartFromIndex(StartFrom) to Count - 1 do begin if SameText(Items[i].Name, AName) then begin Attr := Items[i].AttributeByName(AttrName); if ((Attr <> nil) and SameText(Attr.Value, AttrValue)) then begin Result := Items[i]; Exit; end; end; end; Result := nil; end; function TclHtmlTagList.GetStartFromIndex(StartFrom: TclHtmlTag): Integer; begin if (StartFrom <> nil) then begin Result := IndexOf(StartFrom); end else begin Result := 0; end; if Result < 0 then begin Result := 0; end; end; function TclHtmlTagList.TagByName(const AName: string; StartFrom: TclHtmlTag): TclHtmlTag; var i: Integer; begin for i := GetStartFromIndex(StartFrom) to Count - 1 do begin if SameText(Items[i].Name, AName) then begin Result := Items[i]; Exit; end; end; Result := nil; end; function TclHtmlTagList.GetCount: Integer; begin Result := FList.Count; end; function TclHtmlTagList.GetItem(Index: Integer): TclHtmlTag; begin Result := TclHtmlTag(FList[Index]); end; procedure TclHtmlTagList.Clear; var i: Integer; begin if FOwnsObjects then begin for i := 0 to Count - 1 do begin Items[i].Free(); end; end; FList.Clear(); end; procedure TclHtmlTagList.Add(AItem: TclHtmlTag); begin FList.Add(AItem); end; procedure TclHtmlTagList.AssignList(AList: TStrings); var i: Integer; begin AList.Clear(); for i := 0 to Count - 1 do begin AList.Add(Items[i].TagSource); end; end; function TclHtmlTagList.GetLast: TclHtmlTag; begin if (Count > 0) then begin Result := Items[Count - 1]; end else begin Result := nil; end; end; function TclHtmlTagList.GetFirst: TclHtmlTag; begin if (Count > 0) then begin Result := Items[0]; end else begin Result := nil; end; end; function TclHtmlTagList.IndexOf(ATag: TclHtmlTag): Integer; begin Result := FList.IndexOf(ATag); end; { TclHtmlForm } procedure TclHtmlForm.AfterParseTag; begin inherited AfterParseTag(); Parser.DoParseForm(Self); end; procedure TclHtmlForm.BeforeParseTag; begin inherited BeforeParseTag(); Parser.Forms.Add(Self); end; constructor TclHtmlForm.Create(const AName, AText: string; AOwner: TclHtmlTag; AParser: TclHtmlParser); begin inherited Create(AName, AText, AOwner, AParser); FControls := TclHtmlTagList.Create(False); end; destructor TclHtmlForm.Destroy; begin FControls.Free(); inherited Destroy(); end; function TclHtmlForm.GetAction: string; begin Result := AttributeValue('action'); end; function TclHtmlForm.GetEncType: string; begin Result := AttributeValue('enctype'); end; function TclHtmlForm.GetFormName: string; begin Result := AttributeValue('name'); end; function TclHtmlForm.GetMethod: string; begin Result := AttributeValue('method'); end; { TclTagLexemChecker } constructor TclTagLexemChecker.Create; begin FLexems := TStringList.Create(); FEndLexems := TStringList.Create(); FCheckedLexem := -1; end; destructor TclTagLexemChecker.Destroy; begin FEndLexems.Free(); FLexems.Free(); inherited Destroy(); end; procedure TclTagLexemChecker.AddLexem(const ALexem, AEndLexem: string); begin FLexems.AddObject(ALexem, Pointer(1)); FEndLexems.AddObject(AEndLexem, Pointer(1)); end; function TclTagLexemChecker.CheckLexems(AKey: Char): TclCheckLexemResult; var i, cnt: Integer; begin FCheckedLexem := -1; for i := 0 to FLexems.Count - 1 do begin cnt := Integer(FLexems.Objects[i]); CheckLexem(AKey, FLexems[i], cnt); FLexems.Objects[i] := Pointer(cnt); cnt := Integer(FEndLexems.Objects[i]); CheckLexem(AKey, FEndLexems[i], cnt); FEndLexems.Objects[i] := Pointer(cnt); end; for i := 0 to FEndLexems.Count - 1 do begin if Integer(FEndLexems.Objects[i]) > Length(FEndLexems[i]) then begin Result := clLeaveTag; FCheckedLexem := i; Exit; end; end; for i := 0 to FLexems.Count - 1 do begin if Integer(FLexems.Objects[i]) > Length(FLexems[i]) then begin Result := clEnterTag; FCheckedLexem := i; Exit; end; end; Result := clNone; end; procedure TclTagLexemChecker.CheckLexem(AKey: Char; const ALexem: string; var ALexemCount: Integer); begin if (ALexemCount <= Length(ALexem)) and (AKey = ALexem[ALexemCount]) then begin Inc(ALexemCount); end else begin ALexemCount := 1; end; end; { TclHtmlParser } constructor TclHtmlParser.Create(AOwner: TComponent); begin inherited Create(AOwner); FTags := TclHtmlTagList.Create(True); FForms := TclHtmlFormList.Create(False); FLinks := TclHtmlLinkList.Create(False); FImages := TclHtmlImageList.Create(False); FTables := TclHtmlTableList.Create(False); FFrames := TclHtmlFrameList.Create(False); FMetaTags := TclHtmlMetaTagList.Create(False); FNonClosingTags := TStringList.Create(); GetNonClosingTags(FNonClosingTags); FParseMethod := pmTagsOnly; end; destructor TclHtmlParser.Destroy; begin FTableStack.Free(); FNonClosingTags.Free(); FMetaTags.Free(); FFrames.Free(); FTables.Free(); FImages.Free(); FLinks.Free(); FForms.Free(); FTags.Free(); inherited Destroy(); end; function TclHtmlParser.GetTypeFromSymbol(AKey: Char): TclSymbolType; begin case AKey of '''', '"': Result := stQuote; '=': Result := stDelimiter; Char($20), Char($0A), Char($0D), Char($09): Result := stWhiteSpace; else Result := stDontCare; end; end; procedure TclHtmlParser.ParseTag(ATag: TclHtmlTag; const ALexem: string; ALexemPos: Integer); procedure ProcessValue(AKey: Char; var AValue: string; var AIsValue: Boolean); begin if not AIsValue then begin AIsValue := True; AValue := AKey; end else begin AValue := AValue + AKey; end; end; var len: Integer; Next, Start, StartValue: PChar; IsName, IsValue, IsValueExpect, InDelimiter, WasName: Boolean; Name, Value, LastDelimiter: string; begin if SameText(ATag.Name, '!DOCTYPE') then Exit; len := Length(ALexem); if (len = 0) then Exit; Next := @ALexem[1]; Start := Next; StartValue := Next; IsName := False; IsValueExpect := False; IsValue := False; InDelimiter := False; LastDelimiter := ''; WasName := False; while (len > 0) do begin case GetTypeFromSymbol(Next^) of stWhiteSpace: begin if InDelimiter then begin if not IsValue then begin StartValue := Next; end; ProcessValue(Next^, Value, IsValue); end else if IsValue then begin CreateAttribute(ATag, Name, Value, ALexemPos + StartValue - Start); IsName := False; IsValueExpect := False; IsValue := False; InDelimiter := False; end else if IsName then begin WasName := True; end; end; stDontCare: begin if WasName then begin CreateAttribute(ATag, Name, '', 0); IsName := False; IsValueExpect := False; IsValue := False; InDelimiter := False; ProcessValue(Next^, Name, IsName); end else begin if IsValueExpect then begin if not IsValue then begin StartValue := Next; end; ProcessValue(Next^, Value, IsValue); end else if IsValue then begin CreateAttribute(ATag, Name, Value, ALexemPos + StartValue - Start); IsName := False; IsValueExpect := False; IsValue := False; InDelimiter := False; ProcessValue(Next^, Name, IsName); end else begin ProcessValue(Next^, Name, IsName); end; end; WasName := False; end; stDelimiter: begin if InDelimiter then begin if not IsValue then begin StartValue := Next; end; ProcessValue(Next^, Value, IsValue); end else if IsValue then begin ProcessValue(Next^, Value, IsValue); end else begin IsValueExpect := IsName; IsName := False; IsValue := False; end; WasName := False; end; stQuote: begin if IsValueExpect then begin if InDelimiter then begin if (LastDelimiter <> Next^) then begin if not IsValue then begin StartValue := Next; end; ProcessValue(Next^, Value, IsValue); end else begin if not IsValue then begin CreateAttribute(ATag, Name, '', 0); end; InDelimiter := False; IsValueExpect := False; end; end else begin LastDelimiter := Next^; InDelimiter := True; end; end else begin IsName := False; IsValueExpect := False; IsValue := False; InDelimiter := False; end; WasName := False; end; end; Inc(Next); Dec(len); end; if IsValue then begin CreateAttribute(ATag, Name, Value, ALexemPos + StartValue - Start); end else if IsName then begin CreateAttribute(ATag, Name, '', 0); end; end; procedure TclHtmlParser.ProcessTitleStatus(const AName: string); begin if (FTitleStatus = tsNone) and SameText('head', AName) then begin FTitleStatus := tsEnterHead; end else if (FTitleStatus = tsEnterHead) and SameText('title', AName) then begin FTitleStatus := tsEnterTitle; end else if (FTitleStatus = tsEnterTitle) and SameText('title', AName) then begin FTitleStatus := tsTitleParsed; end; end; {$IFDEF MACOS} function CharPrev(Start, Current: PChar): PChar; begin Result := Current; if (Start <> Current) then begin Dec(Result); end; end; function CharNext(Current: PChar): PChar; begin Result := Current; if (Result^ <> #0) then begin Inc(Result); end; end; {$ENDIF} procedure TclHtmlParser.Parse(const AHtml: string); var InTag, InClosingTag: Boolean; InSkipSection: Boolean; len: Integer; Next, Start, LexemStart: PChar; parseText: string; curLexem, curText: string; Stack: TclHtmlTagStack; skipLexems: TclTagLexemChecker; ownerTag, tag: TclHtmlTag; begin {$IFNDEF MACOS} {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if not IsHtmlDemoDisplayed then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsHtmlDemoDisplayed := True; {$ENDIF} end; {$ENDIF} {$ENDIF} Clear(); parseText := AHtml; len := Length(parseText); if (len = 0) then Exit; Next := @parseText[1]; Start := Next; LexemStart := Next; InTag := False; InClosingTag := False; InSkipSection := False; curText := ''; Stack := nil; skipLexems := nil; try Stack := TclHtmlTagStack.Create(); skipLexems := TclTagLexemChecker.Create(); FTableStack.Free(); FTableStack := TclHtmlTagStack.Create(); FCurrentLink := nil; FTitleStatus := tsNone; GetSkipLexems(skipLexems); while (len > 0) do begin case skipLexems.CheckLexems(LowerCase(Next^)[1]) of clLeaveTag: begin InSkipSection := False; if IncludeClosingTags then begin ownerTag := nil; if not Stack.IsEmpty then begin ownerTag := Stack.Top.Owner; end; tag := CreateTagByName(curLexem, '', ownerTag, Next - Start - Length(skipLexems.EndLexems[skipLexems.CheckedLexem]) + 2); tag.FIsClosingTag := True; DoParseTag(tag); end; end; clEnterTag: begin if (not InSkipSection) then begin curLexem := curLexem + Next^; InSkipSection := True; CreateTag(curLexem, Stack.Top, Next - Start, LexemStart - Start + 2); InTag := False; InClosingTag := False; end; end; end; if not InSkipSection then begin case (Next^) of '<': begin if (not InTag) then begin curLexem := ''; LexemStart := Next; InTag := True; if NeedParseText() and (curText <> '') then begin CreateText(curText, Stack.Top, Next - Start - Length(curText) + 1); curText := ''; end; end; end; '>': begin if (InTag) then begin if InClosingTag then begin ownerTag := nil; if not Stack.IsEmpty then begin ownerTag := Stack.Top.Owner; if SameText(Stack.Top.Name, curLexem) then begin Stack.Pop(); if (not FTableStack.IsEmpty) and SameText(curLexem, 'table') then begin FTableStack.Pop(); end; end; end; if SameText(curLexem, 'a') then begin FCurrentLink := nil; end; if IncludeClosingTags then begin tag := CreateTagByName(curLexem, '', ownerTag, Next - Start - Length(curLexem) - 1); tag.FIsClosingTag := True; DoParseTag(tag); end; end else if NeedParseTags() then begin if (CharPrev(Start, Next)^ = '/') or IsNonClosingTag(curLexem) then begin tag := CreateTag(curLexem, Stack.Top, Next - Start, LexemStart - Start + 2); if (tag <> nil) and SameText(tag.Name, 'a') then begin FCurrentLink := nil; end; end else begin tag := CreateTag(curLexem, Stack.Top, Next - Start, LexemStart - Start + 2); if (tag <> nil) then begin Stack.Push(tag); end; end; end; ProcessTitleStatus(curLexem); InTag := False; InClosingTag := False; curLexem := ''; LexemStart := Next; end; end; '/': begin if InTag then begin if (CharPrev(Start, Next)^ = '<') then begin InClosingTag := True; end else if (len - 1 > 0) and (CharNext(Next)^ <> '>') then begin curLexem := curLexem + Next^; end; end else begin curText := curText + Next^; end; end; else begin if InTag then begin curLexem := curLexem + Next^; end else if NeedParseText() then begin curText := curText + Next^; end; end; end; end; Inc(Next); Dec(len); end; finally FTableStack.Free(); FTableStack := nil; skipLexems.Free(); Stack.Free(); end; ExtractMetaTags(); end; procedure TclHtmlParser.ExtractMetaTags; var metaTag: TclHtmlTag; begin metaTag := Tags.TagByName('title'); if (metaTag <> nil) and (metaTag.NextTag <> nil) and metaTag.NextTag.IsText then begin FTitle := metaTag.NextTag.Text; end; metaTag := MetaTags.TagByAttributeName('meta', 'name', 'author'); if (metaTag <> nil) then begin FAuthor := metaTag.AttributeValue('content'); end; metaTag := MetaTags.TagByAttributeName('meta', 'name', 'description'); if (metaTag <> nil) then begin FDescription := metaTag.AttributeValue('content'); end; metaTag := MetaTags.TagByAttributeName('meta', 'name', 'keywords'); if (metaTag <> nil) then begin FKeywords := metaTag.AttributeValue('content'); end; end; procedure TclHtmlParser.InternalParseTag(ATag: TclHtmlTag; const ALexem: string; ALexemPos: Integer); var isTableCellTag: Boolean; TopTable: TclHtmlTable; begin TopTable := TclHtmlTable(FTableStack.Top); isTableCellTag := ATag.CanAddTableCellTag() and (TopTable <> nil) and (TopTable.Rows.Last <> nil) and (TclHtmlTableRow(TopTable.Rows.Last).Cells.Last <> nil); if ATag.CanAddTableCellTag() then begin AddTableCellTag(ATag); end; ATag.BeforeParseTag(); ParseTag(ATag, ALexem, ALexemPos); DoParseTag(ATag); ATag.AfterParseTag(); if isTableCellTag then begin DoParseTableCellTag(TopTable, TclHtmlTableRow(TopTable.Rows.Last), TclHtmlTableCell(TclHtmlTableRow(TopTable.Rows.Last).Cells.Last), ATag); end; end; function TclHtmlParser.IsNonClosingTag(ATagName: string): Boolean; var len: Integer; name: string; Next: PChar; begin len := Length(ATagName); Result := (len = 0); if Result then Exit; Next := @ATagName[1]; while (len > 0) and (GetTypeFromSymbol(Next^) = stDontCare) do begin Inc(Next); Dec(len); end; name := system.Copy(ATagName, 1, Length(ATagName) - len); name := LowerCase(Trim(name)); Result := (FNonClosingTags.IndexOf(name) > -1); end; procedure TclHtmlParser.Clear; begin FTags.Clear(); FForms.Clear(); FLinks.Clear(); FImages.Clear(); FTables.Clear(); FFrames.Clear(); FMetaTags.Clear(); FTitle := ''; FAuthor := ''; FDescription := ''; FKeywords := ''; end; function TclHtmlParser.CreateTag(const ALexem: string; AOwner: TclHtmlTag; AInnerTextPos, AttribPos: Integer): TclHtmlTag; var len: Integer; Next: PChar; Name, Value: string; begin len := Length(ALexem); if (len = 0) then begin Result := nil; Exit; end; Next := @ALexem[1]; while (len > 0) and (GetTypeFromSymbol(Next^) = stDontCare) do begin Inc(Next); Dec(len); Inc(AttribPos); end; Name := system.Copy(ALexem, 1, Length(ALexem) - len); Value := system.Copy(ALexem, Length(ALexem) - len + 1, len); Result := CreateTagByName(Name, RemoveBadChars(ALexem), AOwner, AInnerTextPos + 2); if (FCurrentLink <> nil) then begin FCurrentLink.Tags.Add(Result); end; InternalParseTag(Result, Value, AttribPos); end; procedure TclHtmlParser.AddToControls(ATag, AOwner: TclHtmlTag); begin if (AOwner is TclHtmlForm) then begin (AOwner as TclHtmlForm).Controls.Add(ATag); DoParseFormControl(AOwner as TclHtmlForm, ATag); end else if (AOwner <> nil) then begin AddToControls(ATag, AOwner.Owner); end; end; procedure TclHtmlParser.DoParseAttribute(ATag: TclHtmlTag; Attribute: TclHtmlAttribute); begin if Assigned(OnParseAttribute) then begin OnParseAttribute(Self, ATag, Attribute); end; end; procedure TclHtmlParser.DoParseForm(AForm: TclHtmlForm); begin if Assigned(OnParseForm) then begin OnParseForm(Self, AForm); end; end; procedure TclHtmlParser.DoParseFormControl(AForm: TclHtmlForm; AControl: TclHtmlTag); begin if Assigned(OnParseFormControl) then begin OnParseFormControl(Self, AForm, AControl); end; end; procedure TclHtmlParser.DoParseTag(ATag: TclHtmlTag); begin if Assigned(OnParseTag) then begin OnParseTag(Self, ATag); end; end; function TclHtmlParser.CreateAttribute(ATag: TclHtmlTag; const AName, AValue: string; AInnerTextPos: Integer): TclHtmlAttribute; begin Result := TclHtmlAttribute.Create(AName, AValue, AInnerTextPos); ATag.AddAttribute(Result); DoParseAttribute(ATag, Result); end; procedure TclHtmlParser.DoParseImage(AImage: TclHtmlImage); begin if Assigned(OnParseImage) then begin OnParseImage(Self, AImage); end; end; procedure TclHtmlParser.DoParseLink(ALink: TclHtmlLink); begin if Assigned(OnParseLink) then begin OnParseLink(Self, ALink); end; end; function TclHtmlParser.CreateText(const AText: string; AOwner: TclHtmlTag; AInnerTextPos: Integer): TclHtmlTag; var isAddTableCellTag: Boolean; TopTable: TclHtmlTable; begin Result := TclHtmlTag.Create('', AText, AOwner, Self); AddTag(Result); if (FCurrentLink <> nil) then begin FCurrentLink.Tags.Add(Result); end; Result.FInnerTextPos := AInnerTextPos; isAddTableCellTag := AddTableCellTag(Result); Result.FIsText := True; DoParseTag(Result); if isAddTableCellTag then begin TopTable := TclHtmlTable(FTableStack.Top); DoParseTableCellTag(TopTable, TclHtmlTableRow(TopTable.Rows.Last), TclHtmlTableCell(TclHtmlTableRow(TopTable.Rows.Last).Cells.Last), Result); end; end; function TclHtmlParser.NeedParseTags: Boolean; begin Result := (ParseMethod = pmAll) or (ParseMethod = pmTagsOnly); end; function TclHtmlParser.NeedParseText: Boolean; begin Result := (FTitleStatus = tsEnterTitle) or (ParseMethod = pmAll) or (ParseMethod = pmTextOnly) or (FCurrentLink <> nil); end; procedure TclHtmlParser.GetNonClosingTags(ATags: TStrings); begin ATags.Add('br'); ATags.Add('input'); ATags.Add('select'); ATags.Add('textarea'); ATags.Add('frame'); ATags.Add('iframe'); ATags.Add('img'); ATags.Add('!doctype'); ATags.Add('link'); end; procedure TclHtmlParser.GetSkipLexems(ASkipLexems: TclTagLexemChecker); begin ASkipLexems.AddLexem('<!--', '-->'); end; function TclHtmlParser.RemoveBadChars(const S: string): string; var i, j: Integer; begin SetLength(Result, Length(S)); j := 1; for i := 1 to Length(S) do begin if (S[i] <> #13) and (S[i] <> #10) and (S[i] <> #9) then begin Result[j] := S[i]; Inc(j); end; end; SetLength(Result, j - 1); end; procedure TclHtmlParser.AddTag(ATag: TclHtmlTag); begin if (FTags.Count > 0) then begin FTags[FTags.Count - 1].FNextTag := ATag; end; FTags.Add(ATag); end; function TclHtmlParser.AddTableCellTag(ATag: TclHtmlTag): Boolean; begin Result := not FTableStack.IsEmpty and (TclHtmlTable(FTableStack.Top).Rows.Last <> nil) and (TclHtmlTableRow(TclHtmlTable(FTableStack.Top).Rows.Last).Cells.Last <> nil); if Result then begin TclHtmlTableCell(TclHtmlTableRow(TclHtmlTable(FTableStack.Top).Rows.Last).Cells.Last).Tags.Add(ATag); end; end; procedure TclHtmlParser.DoParseTable(ATable: TclHtmlTable); begin if Assigned(OnParseTable) then begin OnParseTable(Self, ATable); end; end; procedure TclHtmlParser.DoParseTableCell(ATable: TclHtmlTable; ARow: TclHtmlTableRow; ACell: TclHtmlTableCell); begin if Assigned(OnParseTableCell) then begin OnParseTableCell(Self, ATable, ARow, ACell); end; end; procedure TclHtmlParser.DoParseTableCellTag(ATable: TclHtmlTable; ARow: TclHtmlTableRow; ACell: TclHtmlTableCell; ATag: TclHtmlTag); begin if Assigned(OnParseTableCellTag) then begin OnParseTableCellTag(Self, ATable, ARow, ACell, ATag); end; end; procedure TclHtmlParser.DoParseTableRow(ATable: TclHtmlTable; ARow: TclHtmlTableRow); begin if Assigned(OnParseTableRow) then begin OnParseTableRow(Self, ATable, ARow); end; end; function TclHtmlParser.CreateTagByName(const AName, AText: string; AOwner: TclHtmlTag; AInnerTextPos: Integer): TclHtmlTag; begin if SameText('form', AName) then begin Result := TclHtmlForm.Create(AName, AText, AOwner, Self); end else if SameText('a', AName) then begin Result := TclHtmlLink.Create(AName, AText, AOwner, Self); end else if SameText('frame', AName) or SameText('iframe', AName) then begin Result := TclHtmlFrame.Create(AName, AText, AOwner, Self); end else if SameText('img', AName) then begin Result := TclHtmlImage.Create(AName, AText, AOwner, Self); end else if SameText('table', AName) then begin Result := TclHtmlTable.Create(AName, AText, AOwner, Self); end else if SameText('tr', AName) then begin Result := TclHtmlTableRow.Create(AName, AText, AOwner, Self); end else if SameText('td', AName) or SameText('th', AName) then begin Result := TclHtmlTableCell.Create(AName, AText, AOwner, Self); end else if SameText('meta', AName) then begin Result := TclHtmlMetaTag.Create(AName, AText, AOwner, Self); end else begin Result := TclHtmlTag.Create(AName, AText, AOwner, Self); end; AddTag(Result); Result.FInnerTextPos := AInnerTextPos; end; procedure TclHtmlParser.DoParseFrame(AFrame: TclHtmlFrame); begin if Assigned(OnParseFrame) then begin OnParseFrame(Self, AFrame); end; end; procedure TclHtmlParser.Parse(const AHtml: TStrings); begin Parse(AHtml.Text); end; procedure TclHtmlParser.DoParseMetaTag(AMetaTag: TclHtmlMetaTag); begin if Assigned(OnParseMetaTag) then begin OnParseMetaTag(Self, AMetaTag); end; end; { TclHtmlFormList } function TclHtmlFormList.FormByName(const AName: string; StartFrom: TclHtmlTag): TclHtmlForm; var tag: TclHtmlTag; begin tag := TagByAttributeName('form', 'name', AName, StartFrom); if (tag <> nil) then begin Result := tag as TclHtmlForm; end else begin Result := nil; end; end; function TclHtmlFormList.GetItem(Index: Integer): TclHtmlForm; begin Result := (inherited Items[Index] as TclHtmlForm); end; { TclHtmlTagStack } constructor TclHtmlTagStack.Create; begin inherited Create(); FList := TList.Create(); end; destructor TclHtmlTagStack.Destroy; begin FList.Free(); inherited Destroy(); end; function TclHtmlTagStack.GetIsEmpty: Boolean; begin Result := (FList.Count = 0); end; function TclHtmlTagStack.GetTop: TclHtmlTag; begin if IsEmpty then begin Result := nil; end else begin Result := TclHtmlTag(FList.Last()); end; end; function TclHtmlTagStack.Pop: TclHtmlTag; begin Result := Top; FList.Remove(Result); end; function TclHtmlTagStack.Push(AItem: TclHtmlTag): TclHtmlTag; begin FList.Add(AItem); Result := AItem; end; { TclHtmlAttribute } constructor TclHtmlAttribute.Create(const AName, AValue: string; AInnerTextPos: Integer); begin inherited Create(); FName := AName; FValue := AValue; FInnerTextPos := AInnerTextPos; end; { TclHtmlLink } procedure TclHtmlLink.AfterParseTag; begin inherited AfterParseTag(); Parser.DoParseLink(Self); end; procedure TclHtmlLink.BeforeParseTag; begin inherited BeforeParseTag(); Parser.Links.Add(Self); Parser.FCurrentLink := Self; end; constructor TclHtmlLink.Create(const AName, AText: string; AOwner: TclHtmlTag; AParser: TclHtmlParser); begin inherited Create(AName, AText, AOwner, AParser); FTags := TclHtmlTagList.Create(False); end; destructor TclHtmlLink.Destroy; begin FTags.Free(); inherited Destroy(); end; function TclHtmlLink.GetHref: string; begin Result := AttributeValue('href'); end; function TclHtmlLink.GetLinkText: string; var i: Integer; begin Result := ''; for i := 0 to FTags.Count - 1 do begin if FTags[i].IsText then begin Result := Result + FTags[i].Text; end; end; Result := Trim(Result); end; function TclHtmlLink.GetTarget: string; begin Result := AttributeValue('target'); end; { TclHtmlLinkList } function TclHtmlLinkList.GetItem(Index: Integer): TclHtmlLink; begin Result := (inherited Items[Index] as TclHtmlLink); end; { TclHtmlImageList } function TclHtmlImageList.GetItem(Index: Integer): TclHtmlImage; begin Result := (inherited Items[Index] as TclHtmlImage); end; { TclHtmlImage } procedure TclHtmlImage.AfterParseTag; begin inherited AfterParseTag(); Parser.DoParseImage(Self); end; //+------------------------------------------------------------------------- // Brought to you by Especialista - www.board4all.biz //-------------------------------------------------------------------------- procedure TclHtmlImage.BeforeParseTag; begin inherited BeforeParseTag(); Parser.Images.Add(Self); end; function TclHtmlImage.GetAlt: string; begin Result := AttributeValue('alt'); end; function TclHtmlImage.GetHeight: Integer; begin Result := StrToIntDef(AttributeValue('height'), 0); end; function TclHtmlImage.GetSrc: string; begin Result := AttributeValue('src'); end; function TclHtmlImage.GetWidth: Integer; begin Result := StrToIntDef(AttributeValue('width'), 0); end; { TclHtmlTableCell } procedure TclHtmlTableCell.AfterParseTag; var TopTable: TclHtmlTable; begin inherited AfterParseTag(); TopTable := TclHtmlTable(Parser.FTableStack.Top); if (TopTable <> nil) and (TopTable.Rows.Last <> nil) then begin Parser.DoParseTableCell(TopTable, TclHtmlTableRow(TopTable.Rows.Last), Self); end; end; procedure TclHtmlTableCell.BeforeParseTag; var TopTable: TclHtmlTable; begin inherited BeforeParseTag(); TopTable := TclHtmlTable(Parser.FTableStack.Top); if (TopTable <> nil) and (TopTable.Rows.Last <> nil) then begin TclHtmlTableRow(TopTable.Rows.Last).Cells.Add(Self); end; end; function TclHtmlTableCell.CanAddTableCellTag: Boolean; begin Result := False; end; constructor TclHtmlTableCell.Create(const AName, AText: string; AOwner: TclHtmlTag; AParser: TclHtmlParser); begin inherited Create(AName, AText, AOwner, AParser); FTags := TclHtmlTagList.Create(False); end; destructor TclHtmlTableCell.Destroy; begin FTags.Free(); inherited Destroy(); end; function TclHtmlTableCell.GetColSpan: Integer; begin Result := StrToIntDef(AttributeValue('colspan'), 0); end; function TclHtmlTableCell.GetHeight: Integer; begin Result := StrToIntDef(AttributeValue('height'), 0); end; function TclHtmlTableCell.GetRowSpan: Integer; begin Result := StrToIntDef(AttributeValue('rowspan'), 0); end; function TclHtmlTableCell.GetWidth: Integer; begin Result := StrToIntDef(AttributeValue('width'), 0); end; { TclHtmlTableCellList } function TclHtmlTableCellList.GetItem(Index: Integer): TclHtmlTableCell; begin Result := (inherited Items[Index] as TclHtmlTableCell); end; { TclHtmlTableRow } procedure TclHtmlTableRow.AfterParseTag; var TopTable: TclHtmlTable; begin inherited AfterParseTag(); TopTable := TclHtmlTable(Parser.FTableStack.Top); if TopTable <> nil then begin Parser.DoParseTableRow(TopTable, Self); end; end; procedure TclHtmlTableRow.BeforeParseTag; var TopTable: TclHtmlTable; begin inherited BeforeParseTag(); TopTable := TclHtmlTable(Parser.FTableStack.Top); if TopTable <> nil then begin TopTable.Rows.Add(Self); end; end; function TclHtmlTableRow.CanAddTableCellTag: Boolean; begin Result := False; end; constructor TclHtmlTableRow.Create(const AName, AText: string; AOwner: TclHtmlTag; AParser: TclHtmlParser); begin inherited Create(AName, AText, AOwner, AParser); FCells := TclHtmlTableCellList.Create(False); end; destructor TclHtmlTableRow.Destroy; begin FCells.Free(); inherited Destroy(); end; { TclHtmlTableRowList } function TclHtmlTableRowList.GetItem(Index: Integer): TclHtmlTableRow; begin Result := (inherited Items[Index] as TclHtmlTableRow); end; { TclHtmlTable } procedure TclHtmlTable.AfterParseTag; begin inherited AfterParseTag(); Parser.DoParseTable(Self); end; procedure TclHtmlTable.BeforeParseTag; begin inherited BeforeParseTag(); Parser.Tables.Add(Self); Parser.FTableStack.Push(Self); end; constructor TclHtmlTable.Create(const AName, AText: string; AOwner: TclHtmlTag; AParser: TclHtmlParser); begin inherited Create(AName, AText, AOwner, AParser); FRows := TclHtmlTableRowList.Create(False); end; destructor TclHtmlTable.Destroy; begin FRows.Free(); inherited Destroy(); end; function TclHtmlTable.GetBorder: Integer; begin Result := StrToIntDef(AttributeValue('border'), 0); end; function TclHtmlTable.GetCellPadding: Integer; begin Result := StrToIntDef(AttributeValue('cellpadding'), 0); end; function TclHtmlTable.GetCellSpacing: Integer; begin Result := StrToIntDef(AttributeValue('cellspacing'), 0); end; function TclHtmlTable.GetHeight: Integer; begin Result := StrToIntDef(AttributeValue('height'), 0); end; function TclHtmlTable.GetWidth: Integer; begin Result := StrToIntDef(AttributeValue('width'), 0); end; { TclHtmlTableList } function TclHtmlTableList.GetItem(Index: Integer): TclHtmlTable; begin Result := (inherited Items[Index] as TclHtmlTable); end; { TclHtmlFrame } procedure TclHtmlFrame.AfterParseTag; begin inherited AfterParseTag(); Parser.DoParseFrame(Self); end; procedure TclHtmlFrame.BeforeParseTag; begin inherited BeforeParseTag(); Parser.Frames.Add(Self); end; function TclHtmlFrame.GetSrc: string; begin Result := AttributeValue('src'); end; { TclHtmlFrameList } function TclHtmlFrameList.GetItem(Index: Integer): TclHtmlFrame; begin Result := (inherited Items[Index] as TclHtmlFrame); end; { TclHtmlMetaTagList } function TclHtmlMetaTagList.GetItem(Index: Integer): TclHtmlMetaTag; begin Result := (inherited Items[Index] as TclHtmlMetaTag); end; { TclHtmlMetaTag } procedure TclHtmlMetaTag.AfterParseTag; begin inherited AfterParseTag(); Parser.DoParseMetaTag(Self); end; procedure TclHtmlMetaTag.BeforeParseTag; begin inherited BeforeParseTag(); Parser.MetaTags.Add(Self); end; function TclHtmlMetaTag.GetContent: string; begin Result := AttributeValue('content'); end; function TclHtmlMetaTag.GetHttpEquiv: string; begin Result := AttributeValue('http-equiv'); end; function TclHtmlMetaTag.GetMetaName: string; begin Result := AttributeValue('name'); end; end.
//Exercicio 30: Desenvolva um algoritmo que recebe do usuário o placar de um jogo de futebol (gols de cada time) e //informe se o resultado foi um empate, a vitória do primeiro ou do segundo time. { Solução em Portugol Algoritmo Exercicio ; Var time1,time2: inteiro; Inicio exiba("Programa que determina qual time venceu um jogo de futebol."); exiba("Digite quantos gols o time 1 fez: "); leia(time1); exiba("Digite quantos gols o time 2 fez: "); leia(time2); se(time1 > time2) então exiba("O time 1 venceu."); fimse; se(time1 < time2) então exiba("O time 2 venceu."); fimse; se(time1 = time2) então exiba("Os times empataram."); fimse; Fim. } // Solução em Pascal Program Exercicio30; uses crt; var time1,time2: integer; begin clrscr; writeln('Programa que determina qual time venceu um jogo de futebol.'); writeln('Digite quantos gols o time 1 fez: '); readln(time1); writeln('Digite quantos gols o time 2 fez: '); readln(time2); if(time1 > time2) then writeln('O time 1 venceu.'); if(time1 < time2) then writeln('O time 2 venceu.'); if(time1 = time2) then writeln('Os times empataram.'); repeat until keypressed; end.
{ The unit is part of Lazarus Chelper package Copyright (C) 2010 Dmitry Boyarintsev skalogryz dot lists at gmail.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This 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 cparserutils; interface {$ifdef fpc}{$mode delphi}{$h+}{$endif} uses cparsertypes; // is function declared, i.e. int f() function isFunc(name: TNamePart): Boolean; // probably an untyped function: fn (). // the name of the function has been consumed by TYPE parsing, so ommited! // so TNamepart doesn't contain any children function isUnnamedFunc(name: TNamepart): Boolean; // is pointer to a function declared, i.e. int (*f)() function isPtrToFunc(name: TNamePart): Boolean; // is function declared, returning a pointer to a function, i.e. int (* (f)(int i) )() // pascal variant of this case: // type // TRetFunc = function : Integer; // function f(i: Integer): TRetFunc; // body or extern modifier must be present!!! function isFuncRetFuncPtr(name: TNamePart): Boolean; // is pointer to a function declared, returning a pointer to a function, i.e.: int (*(*f)(int i))() // pascal variant of this case: // type // TRetFunc = function : Integer; // var // f : function (i: Integer): TRetFunc; function isPtrToFuncRetFuncPtr(name: TNamePart): Boolean; function GetFuncParam(name: TNamePart): TNamePart; // is array variable: // int a[10], *a[10] (array of 10 integers, or array of 10 pointers to integer) function isArray(name: TNamePart): Boolean; function GetArrayPart(name: TNamePart): TNamePart; // returns the variable/function name from the struct function GetIdFromPart(name: TNamePart): AnsiString; function GetIdPart(name: TNamePart): TNamePart; function isNamePartPtrToFunc(part: TNamePart): Boolean; inline; function isAnyBlock(part: TNamePart): Boolean; type { TLineBreaker } TLineInfo = record linestart : Integer; lineend : Integer; end; TLineBreaker = class(TObject) private fLines : array of TLineInfo; flineCount : Integer; procedure AddLine(const linestart, lineend: Integer); public procedure SetText(const AText: AnsiString); function LineNumber(Offset: Integer): Integer; end; implementation function isNamePartPtrToFunc(part: TNamePart): Boolean; inline; begin Result:=Assigned(part) and (part.Kind=nk_Ref) and Assigned(part.owner) and (part.owner.kind=nk_Func); end; function isAnyBlock(part: TNamePart): Boolean; begin Result:=Assigned(part) and ((part.Kind=nk_Block) or isAnyBlock(part.child)); end; function isPtrToFunc(name: TNamePart): Boolean; begin Result := Assigned(name) and (name.Kind=nk_Func) and Assigned(name.child) and (name.child.Kind=nk_Ref) and Assigned(name.child.child) and (name.child.child.Kind=nk_Ident); end; function SkipRefPart(name: TNamePart): TNamePart; begin if Assigned(name) then begin if name.Kind=nk_Ref then Result:=name.child else Result:=name; end else Result:=nil; end; function isFunc(name: TNamePart): Boolean; begin name:=SkipRefPart(name); Result:=Assigned(name) and (name.Kind=nk_Func) and Assigned(name.child) and (name.child.Kind=nk_Ident) end; function isUnnamedFunc(name: TNamepart): Boolean; begin Result:=Assigned(name) and not Assigned(name.child) and (name.Kind=nk_Func); end; function isRetFuncPtr(name: TNamePart): Boolean; begin Result:=Assigned(name) and Assigned(name.child) and (name.Kind=nk_Func) and (name.child.Kind=nk_Ref); end; function GetFuncParam(name:TNamePart):TNamePart; begin while Assigned(name) and (name.Kind<>nk_Func) do name:=name.child; Result:=name; end; function isArray(name: TNamePart): Boolean; begin Result:=(name.Kind=nk_Array) or (Assigned(name.child) and (name.child.Kind=nk_Array) and (name.Kind=nk_Ref)); end; function isFuncRetFuncPtr(name: TNamePart): Boolean; var p : TNamePart; begin Result:=isRetFuncPtr(name); if Result then begin p:=name.child.child; Result:=Assigned(p) and Assigned(p.child) and (p.Kind=nk_Func) and (p.child.Kind=nk_Ident) end; end; function isPtrToFuncRetFuncPtr(name: TNamePart): Boolean; var p : TNamePart; begin Result:=isRetFuncPtr(name); if Result then begin p:=name.child.child; Result:=Assigned(p) and Assigned(p.child) and Assigned(p.child.child) and (p.Kind=nk_Func) and (p.child.Kind=nk_Ref) and (p.child.child.Kind=nk_Ident); end; end; function GetArrayPart(name:TNamePart):TNamePart; begin if name.Kind=nk_Array then Result:=name else if (name.Kind=nk_Ref) and (Assigned(name.child)) and (name.child.Kind=nk_array) then Result:=name.child else Result:=nil; end; function GetIdFromPart(name: TNamePart): AnsiString; begin while Assigned(name) and (name.Kind<>nk_Ident) do name:=name.child; if Assigned(name) then Result:=name.Id else Result:=''; end; function GetIdPart(name: TNamePart): TNamePart; begin Result:=nil; while Assigned(name) and (name.Kind<>nk_Ident) do name:=name.child; Result:=name; end; { TLineBreaker } procedure TLineBreaker.AddLine(const linestart,lineend:Integer); begin if flineCount=length(fLines) then begin if fLineCount=0 then SetLength(fLines, 4) else SetLength(fLines, fLineCount*2) end; fLines[fLineCount].linestart:=linestart; fLines[fLineCount].lineend:=lineend; inc(fLineCount); end; procedure TLineBreaker.SetText(const AText: AnsiString); var i : Integer; j : Integer; begin flineCount:=0; i:=1; j:=1; while i<=length(AText) do begin if (AText[i] in [#10, #13]) then begin inc(i); if (i<=length(AText)) and (AText[i] in [#10, #13]) and (AText[i-1]<>Atext[i]) then inc(i); AddLine(j, i-1); j:=i; end else inc(i); end; if j<>i-1 then AddLine(j, i-1); end; function TLineBreaker.LineNumber(Offset:Integer):Integer; var i : Integer; begin for i:=0 to flineCount-1 do if (Offset>=fLines[i].linestart) and (Offset<=flines[i].lineend) then begin Result:=i; Exit; end; Result:=-1; end; end.
unit IdFTPListParseIEFTPGateway; interface {$i IdCompilerDefines.inc} uses Classes, IdFTPList, IdFTPListParseBase,IdFTPListTypes; {This is based on: Information Exchange via TCP/IP FTP Gateway Userís Guide Version 1 Release 4 © Copyright GXS, Inc. 1998, 2005. All rights reserved. and is available at: https://www.gxsolc.com/public/EDI/us/support/Library/Publications/IEtcpipFTPGatewayUserGuide_c3423452.pdf } type TIdIEFTPGatewayLsLongListItem = class(TIdFTPListItem) protected FSenderAcct : String; FSenderUserID : String; FMClass : String; public property SenderAcct : String read FSenderAcct write FSenderAcct; property SenderUserID : String read FSenderUserID write FSenderUserID; property MClass : String read FMClass write FMClass; end; TIdIEFTPGatewayLsShortListItem = class(TIdMinimalFTPListItem); TIdIEFTPGatewayLsFileNameListItem = class(TIdMinimalFTPListItem) protected FOrigFileName : String; public property OrigFileName : String read FOrigFileName write FOrigFileName; end; TIdIEFTPGatewayLSLibraryListItem = class(TIdUnixPermFTPListItem) protected FAccount : String; public property Account : String read FAccount write FAccount; end; TIdFTPLPIEFTPGatewayLSLong = class(TIdFTPListBaseHeader) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function IsHeader(const AData: String): Boolean; override; class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override; public class function GetIdent : String; override; end; TIdFTPLPIEFTPGatewayLSShort = class(TIdFTPLPNList) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; public class function GetIdent : String; override; class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override; end; TIdFTPLPIEFTPGatewayLSFileName = class(TIdFTPListBase) protected class function ParseLine(const AItem : TIdFTPListItem; const APath : String=''): Boolean; override; class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; public class function GetIdent : String; override; class function CheckListing(AListing : TStrings; const ASysDescript : String =''; const ADetails : Boolean = True): boolean; override; end; TIdFTPLPIEFTPGatewayLSLibrary = class(TIdFTPListBaseHeader) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function IsHeader(const AData: String): Boolean; override; class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override; public class function GetIdent : String; override; end; (*$HPPEMIT '#pragma link "IdFTPListParseIEFTPGateway"'*) implementation uses IdGlobal, IdFTPCommon, IdGlobalProtocols, SysUtils; function IsIEFile(const AStr : String): Boolean; {$IFDEF USE_INLINE} inline; {$ENDIF} begin Result := TextEndsWith(AStr,'._IE'); end; { TIdFTPLPIEFTPGatewayLSLong } class function TIdFTPLPIEFTPGatewayLSLong.GetIdent: String; begin Result := 'IE-FTPListStyleLong'; {Do not localize} end; class function TIdFTPLPIEFTPGatewayLSLong.IsHeader( const AData: String): Boolean; var s : TStrings; begin //" Filename (MSGKEY) Sender Class Size Date Time" s := TStringList.Create; try SplitColumns(AData, s); if s.Count >=6 then begin Result := (s[0] = 'Filename') and (s[1]='(MSGKEY)') and (s[2]='Sender') and (s[3]='Class') and (s[4]='Size') and (s[5]='Date') and (s[6]='Time'); end else begin Result := False; end; finally FreeAndNil(s); end; end; class function TIdFTPLPIEFTPGatewayLSLong.MakeNewItem( AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdIEFTPGatewayLsLongListItem.Create(AOwner); end; class function TIdFTPLPIEFTPGatewayLSLong.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; var li : TIdIEFTPGatewayLsLongListItem; s : TStrings; d, m, y : Word; h, mn, sec : Word; begin Result := True; //"FFAD59A3FB10054AC5F1._IE ACCT1 USER1 ORDERS 0000006501 960821 092357" li := AItem as TIdIEFTPGatewayLsLongListItem; li.ItemType := ditFile; s := TStringList.Create; try SplitColumns(li.Data, s); li.FileName := s[0]; li.SenderAcct := s[1]; li.SenderUserID := s[2]; li.MClass := s[3]; li.Size := StrToIntDef(s[4],0); li.SizeAvail := True; y := Y2Year(StrToInt(Copy(s[5],1,2))); m := StrToInt(Copy(s[5],3,2)); d := StrToInt(Copy(s[5],5,2)); li.ModifiedDate := EncodeDate(y,m,d); h := StrToInt(Copy(s[6],1,2)); mn := StrToInt(Copy(s[6],3,2)); sec := StrToInt(Copy(s[6],5,2)); li.ModifiedDate := li.ModifiedDate + EncodeTime(h,mn,sec,0); li.ModifiedAvail := True; finally FreeAndNil(s); end; end; { TIdFTPLPIEFTPGatewayLSFileName } class function TIdFTPLPIEFTPGatewayLSFileName.CheckListing(AListing: TStrings; const ASysDescript: String; const ADetails: Boolean): boolean; var LData : String; i : Integer; begin Result := AListing.Count > 0; if Result then begin for i := 0 to AListing.Count - 1 do begin LData := AListing[i]; Result := IsIEFile(Fetch(LData)); if Result then begin LData := TrimLeft(LData); Result := LData <> ''; end; if not Result then begin break; end; end; end; end; class function TIdFTPLPIEFTPGatewayLSFileName.GetIdent: String; begin Result := 'IE-FTPListStyleFileName'; {Do not localize} end; class function TIdFTPLPIEFTPGatewayLSFileName.MakeNewItem( AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdIEFTPGatewayLsFileNameListItem.Create(AOwner); end; class function TIdFTPLPIEFTPGatewayLSFileName.ParseLine( const AItem: TIdFTPListItem; const APath: String): Boolean; var li : TIdIEFTPGatewayLsFileNameListItem; LData : String; begin Result := True; li := AItem as TIdIEFTPGatewayLsFileNameListItem; li.ItemType := ditFile; LData := li.Data; li.FileName := Fetch(LData); LData := TrimLeft(LData); li.OrigFileName := UnquotedStr(Fetch(LData)); end; { TIdFTPLPIEFTPGatewayLSShort } class function TIdFTPLPIEFTPGatewayLSShort.CheckListing(AListing : TStrings; const ASysDescript : String =''; const ADetails : Boolean = True): boolean; var i : Integer; begin Result := False; for I := 0 to AListing.Count - 1 do begin Result := IsIEFile(AListing[i]); if not Result then begin break; end; end; end; class function TIdFTPLPIEFTPGatewayLSShort.GetIdent: String; begin Result := 'IE-FTPListStyleShort'; {Do not localize} end; class function TIdFTPLPIEFTPGatewayLSShort.MakeNewItem( AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdIEFTPGatewayLsShortListItem.Create(AOwner); end; { TIdFTPLPIEFTPGatewayLSLibrary } class function TIdFTPLPIEFTPGatewayLSLibrary.GetIdent: String; begin Result := 'IE-FTPListStyleLibrary'; {Do not localize} end; class function TIdFTPLPIEFTPGatewayLSLibrary.IsHeader( const AData: String): Boolean; var s : TStrings; begin //"Access Owner Account Size Last updated Name" s := TStringList.Create; try SplitColumns(AData, s); if s.Count >=6 then begin Result := (s[0] = 'Access') and (s[1]='Owner') and (s[2]='Account') and (s[3]='Size') and (s[4]='Last') and (s[5]='updated') and (s[6]='Name'); end else begin Result := False; end; finally FreeAndNil(s); end; end; class function TIdFTPLPIEFTPGatewayLSLibrary.MakeNewItem( AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdIEFTPGatewayLSLibraryListItem.Create(AOwner); end; class function TIdFTPLPIEFTPGatewayLSLibrary.ParseLine( const AItem: TIdFTPListItem; const APath: String): Boolean; var LI : TIdIEFTPGatewayLSLibraryListItem; LData : String; begin Result := True; LI := AItem as TIdIEFTPGatewayLSLibraryListItem; LData := LI.Data; LI.ItemType := ditFile; LI.FUnixOwnerPermissions := Copy(LI.Data,2,3); LI.FUnixGroupPermissions := Copy(LI.Data,5,3); LI.FUnixOtherPermissions := Copy(LI.Data,8,3); IdDelete(LData,1,10); LI.OwnerName := Fetch(LData); LData := TrimLeft(LData); LI.Account := Fetch(LData); LData := TrimLeft(LData); LI.Size := StrToIntDef(Fetch(LData),0); LData := TrimLeft(LData); LI.ModifiedDate := DateYYMMDD(Fetch(LData)); LData := TrimLeft(LData); LI.ModifiedDate := TimeHHMMSS(Fetch(LData)); IdDelete(LData,1,1); LI.FileName := LData; end; initialization RegisterFTPListParser(TIdFTPLPIEFTPGatewayLSLong); RegisterFTPListParser(TIdFTPLPIEFTPGatewayLSShort); RegisterFTPListParser(TIdFTPLPIEFTPGatewayLSFileName); RegisterFTPListParser(TIdFTPLPIEFTPGatewayLSLibrary); finalization UnRegisterFTPListParser(TIdFTPLPIEFTPGatewayLSLong); UnRegisterFTPListParser(TIdFTPLPIEFTPGatewayLSShort); UnRegisterFTPListParser(TIdFTPLPIEFTPGatewayLSFileName); UnRegisterFTPListParser(TIdFTPLPIEFTPGatewayLSLibrary); end.
unit Main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, UModem, CommInt; type TFormMain = class(TForm) Panel1: TPanel; cbDSR: TCheckBox; cbCTS: TCheckBox; cbRLSD: TCheckBox; Panel2: TPanel; Memo: TMemo; edComName: TEdit; btnOpen: TButton; Label1: TLabel; Modem: TModem; pnlConnect: TPanel; edConnectCmd: TEdit; btnConnect: TButton; procedure CommCts(Sender: TObject); procedure CommDsr(Sender: TObject); procedure CommRlsd(Sender: TObject); procedure btnOpenClick(Sender: TObject); procedure CommRxChar(Sender: TObject; Count: Integer); procedure ModemModemResponse(Sender: TObject; Code: Integer); procedure btnConnectClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormMain: TFormMain; implementation {$R *.DFM} procedure TFormMain.CommCts(Sender: TObject); begin cbCTS.Checked:=Modem.CTS; end; procedure TFormMain.CommDsr(Sender: TObject); begin cbDSR.Checked:=Modem.DSR; end; procedure TFormMain.CommRlsd(Sender: TObject); begin cbRLSD.Checked:=Modem.RLSD; Memo.SelText:='[RLSD]'#13#10; end; procedure TFormMain.btnOpenClick(Sender: TObject); begin if Modem.Enabled then begin Modem.Close; btnOpen.Caption:='Open'; end else begin Modem.DeviceName:=edComName.Text; try Modem.Open; Modem.PurgeIn; Modem.DoCmd('AT E0'); cbDSR.Checked:=Modem.DSR; cbCTS.Checked:=Modem.CTS; cbRLSD.Checked:=Modem.RLSD; btnOpen.Caption:='Close'; except on E:Exception do Application.MessageBox(PChar(E.Message),'Opening error',MB_OK or MB_ICONHAND); end; end; end; procedure TFormMain.CommRxChar(Sender: TObject; Count: Integer); var S:String; begin SetLength(S,Count); Modem.Read(S[1],Count); Memo.SelText:=S; end; procedure TFormMain.ModemModemResponse(Sender: TObject; Code: Integer); begin Memo.SelText:=Modem.ModemResponse+'[Code '+IntToStr(Code)+']'#13#10; end; procedure TFormMain.btnConnectClick(Sender: TObject); begin Modem.Connect(edConnectCmd.Text); end; end.
unit NtUtils.Shellcode; interface uses Winapi.WinNt, Ntapi.ntdef, Ntapi.ntrtl, Ntapi.ntpsapi, NtUtils.Exceptions; const PROCESS_INJECT_ACCESS = PROCESS_CREATE_THREAD or PROCESS_VM_OPERATION or PROCESS_VM_WRITE; // Write a portion of data to a process' memory function NtxWriteDataProcess(hProcess: THandle; Buffer: Pointer; BufferSize: NativeUInt; out Status: TNtxStatus): Pointer; // Write executable assembly code to a process function NtxWriteAssemblyProcess(hProcess: THandle; Buffer: Pointer; BufferSize: NativeUInt; out Status: TNtxStatus): Pointer; // Copy data to a process and invoke a function on a remote thread function RtlxInvokeFunctionProcess(out hThread: THandle; hProcess: THandle; Routine: TUserThreadStartRoutine; ParamBuffer: Pointer; ParamBufferSize: NativeUInt; Timeout: Int64 = INFINITE): TNtxStatus; // Copy assembly code and data and invoke it in a remote thread function RtlxInvokeAssemblyProcess(out hThread: THandle; hProcess: THandle; AssemblyBuffer: Pointer; AssemblyBufferSize: NativeUInt; ParamBuffer: Pointer; ParamBufferSize: NativeUInt; Timeout: Int64 = INFINITE): TNtxStatus; // Synchronously invoke assembly code in a remote thread function RtlxInvokeAssemblySyncProcess(hProcess: THandle; AssemblyBuffer: Pointer; AssemblyBufferSize: NativeUInt; ParamBuffer: Pointer; ParamBufferSize: NativeUInt; StatusComment: String): TNtxStatus; // Inject a dll into a process function RtlxInjectDllProcess(out hThread: THandle; hProcess: THandle; DllName: String; Timeout: Int64): TNtxStatus; implementation uses Ntapi.ntmmapi, Ntapi.ntstatus, NtUtils.Processes.Memory, NtUtils.Threads, NtUtils.Objects, NtUtils.Ldr; function NtxWriteDataProcess(hProcess: THandle; Buffer: Pointer; BufferSize: NativeUInt; out Status: TNtxStatus): Pointer; begin // Allocate writable memory Status := NtxAllocateMemoryProcess(hProcess, BufferSize, Result); if not Status.IsSuccess then Exit; Status := NtxWriteMemoryProcess(hProcess, Result, Buffer, BufferSize); // Undo allocation on failure if not Status.IsSuccess then NtxFreeMemoryProcess(hProcess, Result, BufferSize); end; function NtxWriteAssemblyProcess(hProcess: THandle; Buffer: Pointer; BufferSize: NativeUInt; out Status: TNtxStatus): Pointer; begin // Allocate and write the code to memory Result := NtxWriteDataProcess(hProcess, Buffer, BufferSize, Status); if not Status.IsSuccess then Exit; // Make the memory executable Status := NtxProtectMemoryProcess(hProcess, Result, BufferSize, PAGE_EXECUTE_READ); // Flush instruction cache to make sure the processor executes the code // from memory, not from its cache if Status.IsSuccess then Status := NtxFlushInstructionCache(hProcess, Result, BufferSize); // Undo everything on error if not Status.IsSuccess then NtxFreeMemoryProcess(hProcess, Result, BufferSize); end; function RtlxInvokeFunctionProcess(out hThread: THandle; hProcess: THandle; Routine: TUserThreadStartRoutine; ParamBuffer: Pointer; ParamBufferSize: NativeUInt; Timeout: Int64): TNtxStatus; var Parameter: Pointer; begin // Write data if Assigned(ParamBuffer) and (ParamBufferSize <> 0) then begin Parameter := NtxWriteDataProcess(hProcess, ParamBuffer, ParamBufferSize, Result); if not Result.IsSuccess then Exit; end else Parameter := nil; // Create remote thread Result := RtlxCreateThread(hThread, hProcess, Routine, Parameter); if not Result.IsSuccess then begin // Free allocation on failure if Assigned(Parameter) then NtxFreeMemoryProcess(hProcess, Parameter, ParamBufferSize); Exit; end; if Timeout <> 0 then begin Result := NtxWaitForSingleObject(hThread, False, Timeout); // If the thread terminated we can clean up the memory if Assigned(Parameter) and (Result.Status = STATUS_WAIT_0) then NtxFreeMemoryProcess(hProcess, Parameter, ParamBufferSize); end; end; function RtlxInvokeAssemblyProcess(out hThread: THandle; hProcess: THandle; AssemblyBuffer: Pointer; AssemblyBufferSize: NativeUInt; ParamBuffer: Pointer; ParamBufferSize: NativeUInt; Timeout: Int64 = INFINITE): TNtxStatus; var pCode: Pointer; begin // Write assembly code pCode := NtxWriteAssemblyProcess(hProcess, AssemblyBuffer, AssemblyBufferSize, Result); if not Result.IsSuccess then Exit; // Invoke this code passing the parameter buffer Result := RtlxInvokeFunctionProcess(hThread, hProcess, pCode, ParamBuffer, ParamBufferSize, Timeout); // Free the assembly allocation if the thread exited or anything else happen if Result.Matches(STATUS_WAIT_0, 'NtWaitForSingleObject') or not Result.IsSuccess then NtxFreeMemoryProcess(hProcess, pCode, AssemblyBufferSize); end; function RtlxInvokeAssemblySyncProcess(hProcess: THandle; AssemblyBuffer: Pointer; AssemblyBufferSize: NativeUInt; ParamBuffer: Pointer; ParamBufferSize: NativeUInt; StatusComment: String): TNtxStatus; var ResultCode: NTSTATUS; hThread: THandle; begin // Invoke the assembly code and wait for the result Result := RtlxInvokeAssemblyProcess(hThread, hProcess, AssemblyBuffer, AssemblyBufferSize, ParamBuffer, ParamBufferSize, INFINITE); if not Result.IsSuccess then Exit; Result := NtxQueryExitStatusThread(hThread, ResultCode); NtxSafeClose(hThread); if Result.IsSuccess then begin // Pass the result of assembly code execution to the caller Result.Location := StatusComment; Result.Status := ResultCode; end; end; function RtlxInjectDllProcess(out hThread: THandle; hProcess: THandle; DllName: String; Timeout: Int64): TNtxStatus; var hKernel32: HMODULE; pLoadLibrary: TUserThreadStartRoutine; begin // TODO: WoW64 support Result := LdrxGetDllHandle(kernel32, hKernel32); if not Result.IsSuccess then Exit; pLoadLibrary := LdrxGetProcedureAddress(hKernel32, 'LoadLibraryW', Result); if not Result.IsSuccess then Exit; Result := RtlxInvokeFunctionProcess(hThread, hProcess, pLoadLibrary, PWideChar(DllName), (Length(DllName) + 1) * SizeOf(WideChar), Timeout); end; end.
unit mikie_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m6809,nz80,main_engine,controls_engine,sn_76496,gfx_engine,rom_engine, pal_engine,sound_engine,qsnapshot; function iniciar_mikie:boolean; implementation const mikie_rom:array[0..2] of tipo_roms=( (n:'n14.11c';l:$2000;p:$6000;crc:$f698e6dd),(n:'o13.12a';l:$4000;p:$8000;crc:$826e7035), (n:'o17.12d';l:$4000;p:$c000;crc:$161c25c8)); mikie_sound:tipo_roms=(n:'n10.6e';l:$2000;p:0;crc:$2cf9d670); mikie_char:tipo_roms=(n:'o11.8i';l:$4000;p:0;crc:$3c82aaf3); mikie_sprites:array[0..3] of tipo_roms=( (n:'001.f1';l:$4000;p:0;crc:$a2ba0df5),(n:'003.f3';l:$4000;p:$4000;crc:$9775ab32), (n:'005.h1';l:$4000;p:$8000;crc:$ba44aeef),(n:'007.h3';l:$4000;p:$c000;crc:$31afc153)); mikie_pal:array[0..4] of tipo_roms=( (n:'d19.1i';l:$100;p:$0;crc:$8b83e7cf),(n:'d21.3i';l:$100;p:$100;crc:$3556304a), (n:'d20.2i';l:$100;p:$200;crc:$676a0669),(n:'d22.12h';l:$100;p:$300;crc:$872be05c), (n:'d18.f9';l:$100;p:$400;crc:$7396b374)); //Dip mikie_dip_a:array [0..2] of def_dip=( (mask:$0f;name:'Coin A';number:16;dip:((dip_val:$2;dip_name:'4C 1C'),(dip_val:$5;dip_name:'3C 1C'),(dip_val:$8;dip_name:'2C 1C'),(dip_val:$4;dip_name:'3C 2C'),(dip_val:$1;dip_name:'4C 3C'),(dip_val:$f;dip_name:'1C 1C'),(dip_val:$3;dip_name:'3C 4C'),(dip_val:$7;dip_name:'2C 3C'),(dip_val:$e;dip_name:'1C 2C'),(dip_val:$6;dip_name:'2C 5C'),(dip_val:$d;dip_name:'1C 3C'),(dip_val:$c;dip_name:'1C 4C'),(dip_val:$b;dip_name:'1C 5C'),(dip_val:$a;dip_name:'1C 6C'),(dip_val:$9;dip_name:'1C 7C'),(dip_val:$0;dip_name:'Free Play'))), (mask:$f0;name:'Coin B';number:15;dip:((dip_val:$20;dip_name:'4C 1C'),(dip_val:$50;dip_name:'3C 1C'),(dip_val:$80;dip_name:'2C 1C'),(dip_val:$40;dip_name:'3C 2C'),(dip_val:$10;dip_name:'4C 3C'),(dip_val:$f0;dip_name:'1C 1C'),(dip_val:$30;dip_name:'3C 4C'),(dip_val:$70;dip_name:'2C 3C'),(dip_val:$e0;dip_name:'1C 2C'),(dip_val:$60;dip_name:'2C 5C'),(dip_val:$d0;dip_name:'1C 3C'),(dip_val:$c0;dip_name:'1C 4C'),(dip_val:$b0;dip_name:'1C 5C'),(dip_val:$a0;dip_name:'1C 6C'),(dip_val:$90;dip_name:'1C 7C'),())),()); mikie_dip_b:array [0..5] of def_dip=( (mask:$3;name:'Lives';number:4;dip:((dip_val:$3;dip_name:'3'),(dip_val:$2;dip_name:'4'),(dip_val:$1;dip_name:'5'),(dip_val:$0;dip_name:'7'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$4;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$4;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$18;name:'Bonus Life';number:4;dip:((dip_val:$18;dip_name:'20K 70K 50K+'),(dip_val:$10;dip_name:'30K 90K 60K+'),(dip_val:$8;dip_name:'30K Only'),(dip_val:$0;dip_name:'40K Only'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$60;name:'Difficulty';number:4;dip:((dip_val:$60;dip_name:'Easy'),(dip_val:$40;dip_name:'Medium'),(dip_val:$20;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Demo Sounds';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); mikie_dip_c:array [0..2] of def_dip=( (mask:$1;name:'Flip Screen';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$1;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$2;name:'Upright Controls';number:2;dip:((dip_val:$2;dip_name:'Single'),(dip_val:$0;dip_name:'Dual'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var banco_pal,sound_latch,sound_trq:byte; irq_ena:boolean; procedure update_video_mikie; var x,y,atrib:byte; f,color,nchar:word; flip_x,flip_y:boolean; begin for f:=$3ff downto 0 do begin if gfx[0].buffer[f] then begin y:=31-(f mod 32); x:=f div 32; atrib:=memoria[$3800+f]; color:=((atrib and $f)+($10*banco_pal)) shl 4; nchar:=memoria[$3c00+f]+((atrib and $20) shl 3); flip_x:=(atrib and $80)=0; flip_y:=(atrib and $40)=0; put_gfx_flip(x*8,y*8,nchar,color,1,0,flip_x,flip_y); if (atrib and $10)<>0 then put_gfx_mask_flip(x*8,y*8,nchar,color,2,0,0,$ff,flip_x,flip_y) else put_gfx_block_trans(x*8,y*8,2,8,8); gfx[0].buffer[f]:=false; end; end; actualiza_trozo(0,0,256,256,1,0,0,256,256,3); for f:=0 to $23 do begin atrib:=memoria[$2800+(f*4)]; nchar:=((atrib and $40) shl 1)+(memoria[$2802+(f*4)] and $3f)+((memoria[$2802+(f*4)] and $80) shr 1)+(memoria[$2802+(f*4)] and $40) shl 2; color:=((atrib and $f)+($10*banco_pal)) shl 4; x:=244-memoria[$2801+(f*4)]; flip_x:=(atrib and $20)=0; if not(main_screen.flip_main_screen) then begin y:=240-memoria[$2803+(f*4)]; flip_y:=(atrib and $10)<>0; end else begin flip_y:=(atrib and $10)=0; y:=memoria[$2803+(f*4)]; x:=x-2; end; put_gfx_sprite(nchar,color,flip_x,flip_y,1); actualiza_gfx_sprite(x,y,3,1); end; actualiza_trozo(0,0,256,256,2,0,0,256,256,3); actualiza_trozo_final(16,0,224,256,3); end; procedure eventos_mikie; begin if event.arcade then begin //p1 if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or $4); if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or $8); if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10); if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20); //p2 if arcade_input.left[1] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1); if arcade_input.right[1] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.up[1] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.down[1] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.but0[1] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.but1[1] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20); //misc if arcade_input.coin[0] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1); if arcade_input.coin[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2); if arcade_input.start[0] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8); if arcade_input.start[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10); end; end; procedure mikie_principal; var frame_m,frame_s:single; f:byte; begin init_controls(false,false,false,true); frame_m:=m6809_0.tframes; frame_s:=z80_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //Main CPU m6809_0.run(frame_m); frame_m:=frame_m+m6809_0.tframes-m6809_0.contador; //Sound CPU z80_0.run(frame_s); frame_s:=frame_s+z80_0.tframes-z80_0.contador; if f=239 then begin m6809_0.change_irq(HOLD_LINE); update_video_mikie; end; end; eventos_mikie; video_sync; end; end; function mikie_getbyte(direccion:word):byte; begin case direccion of 0..$ff,$2800..$ffff:mikie_getbyte:=memoria[direccion]; $2400:mikie_getbyte:=marcade.in2; //system $2401:mikie_getbyte:=marcade.in0; //p1 $2402:mikie_getbyte:=marcade.in1; //p2 $2403:mikie_getbyte:=marcade.dswc; //dsw3 $2500:mikie_getbyte:=marcade.dswa; //dsw1 $2501:mikie_getbyte:=marcade.dswb; //dsw2 end; end; procedure mikie_putbyte(direccion:word;valor:byte); begin case direccion of 0..$ff,$2800..$37ff:memoria[direccion]:=valor; $2002:begin if ((sound_trq=0) and (valor=1)) then z80_0.change_irq(HOLD_LINE); sound_trq:=valor; end; $2006:main_screen.flip_main_screen:=(valor and 1)<>0; $2007:irq_ena:=(valor<>0); $2100:; //wd $2200:banco_pal:=valor and $7; $2400:sound_latch:=valor; $3800..$3fff:if memoria[direccion]<>valor then begin gfx[0].buffer[direccion and $3ff]:=true; memoria[direccion]:=valor; end; $4000..$ffff:; //ROM end; end; function sound_getbyte(direccion:word):byte; begin case direccion of 0..$43ff:sound_getbyte:=mem_snd[direccion]; $8003:sound_getbyte:=sound_latch; $8005:sound_getbyte:=z80_0.totalt shr 9; end; end; procedure sound_putbyte(direccion:word;valor:byte); begin case direccion of 0..$3fff:; //ROM $4000..$43ff:mem_snd[direccion]:=valor; $8002:sn_76496_0.Write(valor); $8004:sn_76496_1.Write(valor); end; end; procedure sound_update; begin sn_76496_0.update; sn_76496_1.update; end; procedure mikie_qsave(nombre:string); var data:pbyte; buffer:array[0..4] of byte; size:word; begin open_qsnapshot_save('mikie'+nombre); getmem(data,180); //CPU size:=m6809_0.save_snapshot(data); savedata_qsnapshot(data,size); size:=z80_0.save_snapshot(data); savedata_qsnapshot(data,size); //SND size:=sn_76496_0.save_snapshot(data); savedata_qsnapshot(data,size); size:=sn_76496_1.save_snapshot(data); savedata_qsnapshot(data,size); //MEM savedata_com_qsnapshot(@memoria[$0],$4000); savedata_com_qsnapshot(@mem_snd[$2000],$e000); //MISC buffer[0]:=banco_pal; buffer[2]:=byte(irq_ena); buffer[3]:=sound_latch; buffer[4]:=sound_trq; savedata_qsnapshot(@buffer,5); freemem(data); close_qsnapshot; end; procedure mikie_qload(nombre:string); var data:pbyte; buffer:array[0..4] of byte; begin if not(open_qsnapshot_load('mikie'+nombre)) then exit; getmem(data,180); //CPU loaddata_qsnapshot(data); m6809_0.load_snapshot(data); loaddata_qsnapshot(data); z80_0.load_snapshot(data); //SND loaddata_qsnapshot(data); sn_76496_0.load_snapshot(data); loaddata_qsnapshot(data); sn_76496_1.load_snapshot(data); //MEM loaddata_qsnapshot(@memoria); loaddata_qsnapshot(@mem_snd[$2000]); //MISC loaddata_qsnapshot(@buffer); banco_pal:=buffer[0]; irq_ena:=buffer[2]<>0; sound_latch:=buffer[3]; sound_trq:=buffer[4]; freemem(data); close_qsnapshot; //END fillchar(gfx[0].buffer,$400,1); end; //Main procedure reset_mikie; begin m6809_0.reset; z80_0.reset; sn_76496_0.reset; sn_76496_1.reset; reset_audio; banco_pal:=0; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$ff; irq_ena:=false; sound_trq:=0; end; function iniciar_mikie:boolean; var colores:tpaleta; f,bit0,bit1,bit2,bit3:byte; memoria_temp:array[0..$ffff] of byte; rweights,gweights,bweights:array[0..3] of single; const ps_x:array[0..15] of dword=(32*8+0, 32*8+1, 32*8+2, 32*8+3, 16*8+0, 16*8+1, 16*8+2, 16*8+3, 0, 1, 2, 3, 48*8+0, 48*8+1, 48*8+2, 48*8+3); ps_y:array[0..15] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16, 32*16, 33*16, 34*16, 35*16, 36*16, 37*16, 38*16, 39*16); pc_x:array[0..7] of dword=(0*4, 1*4, 2*4, 3*4, 4*4, 5*4, 6*4, 7*4); pc_y:array[0..7] of dword=(0*4*8, 1*4*8, 2*4*8, 3*4*8, 4*4*8, 5*4*8, 6*4*8, 7*4*8); resistances:array[0..3] of integer=(2200,1000,470,220); begin llamadas_maquina.bucle_general:=mikie_principal; llamadas_maquina.reset:=reset_mikie; llamadas_maquina.save_qsnap:=mikie_qsave; llamadas_maquina.load_qsnap:=mikie_qload; llamadas_maquina.fps_max:=60.59; iniciar_mikie:=false; iniciar_audio(false); screen_init(1,256,256); screen_init(2,256,256,true); screen_mod_scroll(2,256,256,255,256,256,255); screen_init(3,256,256,false,true); iniciar_video(224,256); //Main CPU m6809_0:=cpu_m6809.Create(18432000 div 12,256,TCPU_M6809); m6809_0.change_ram_calls(mikie_getbyte,mikie_putbyte); //Sound CPU z80_0:=cpu_z80.create(14318180 div 4,256); z80_0.change_ram_calls(sound_getbyte,sound_putbyte); z80_0.init_sound(sound_update); //Sound Chip sn_76496_0:=sn76496_chip.Create(14318180 div 8); sn_76496_1:=sn76496_chip.Create(14318180 div 4); //cargar roms if not(roms_load(@memoria,mikie_rom)) then exit; //cargar rom sonido if not(roms_load(@mem_snd,mikie_sound)) then exit; //convertir chars if not(roms_load(@memoria_temp,mikie_char)) then exit; init_gfx(0,8,8,512); gfx[0].trans[0]:=true; gfx_set_desc_data(4,0,32*8,0,1,2,3); convert_gfx(0,0,@memoria_temp,@pc_x,@pc_y,true,false); //sprites if not(roms_load(@memoria_temp,mikie_sprites)) then exit; init_gfx(1,16,16,512); gfx[1].trans[0]:=true; for f:=0 to 1 do begin gfx_set_desc_data(4,2,128*8,0+f*8,4+f*8,f*8+$8000*8+0,f*8+$8000*8+4); convert_gfx(1,$100*f*16*16,@memoria_temp,@ps_x,@ps_y,true,false); end; //paleta if not(roms_load(@memoria_temp,mikie_pal)) then exit; compute_resistor_weights(0, 255, -1.0, 4,@resistances,@rweights,470,0, 4,@resistances,@gweights,470,0, 4,@resistances,@bweights,470,0); for f:=0 to $ff do begin // red component */ bit0:=(memoria_temp[f] shr 0) and $01; bit1:=(memoria_temp[f] shr 1) and $01; bit2:=(memoria_temp[f] shr 2) and $01; bit3:=(memoria_temp[f] shr 3) and $01; colores[f].r:=combine_4_weights(@rweights,bit0,bit1,bit2,bit3); // green component */ bit0:=(memoria_temp[f+$100] shr 0) and $01; bit1:=(memoria_temp[f+$100] shr 1) and $01; bit2:=(memoria_temp[f+$100] shr 2) and $01; bit3:=(memoria_temp[f+$100] shr 3) and $01; colores[f].g:=combine_4_weights(@gweights,bit0,bit1,bit2,bit3); // blue component */ bit0:=(memoria_temp[f+$200] shr 0) and $01; bit1:=(memoria_temp[f+$200] shr 1) and $01; bit2:=(memoria_temp[f+$200] shr 2) and $01; bit3:=(memoria_temp[f+$200] shr 3) and $01; colores[f].b:=combine_4_weights(@bweights,bit0,bit1,bit2,bit3); end; set_pal(colores,256); //tabla_colores char & sprites for bit1:=0 to $ff do begin for bit2:=0 to 7 do begin gfx[0].colores[bit1+(bit2 shl 8)]:=(memoria_temp[bit1+$300] and $f)+(bit2 shl 5)+16; gfx[1].colores[bit1+(bit2 shl 8)]:=(memoria_temp[bit1+$400] and $f)+(bit2 shl 5); end; end; //DIP marcade.dswa:=$ff; marcade.dswb:=$7b; marcade.dswc:=$fe; marcade.dswa_val:=@mikie_dip_a; marcade.dswb_val:=@mikie_dip_b; marcade.dswc_val:=@mikie_dip_c; //final reset_mikie; iniciar_mikie:=true; end; end.
unit ssPanel; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, ExtCtrls; type TssPanel = class(TPanel) private FHintColor: TColor; FSaved: TColor; FOnMouseEnter: TNotifyEvent; FOnMouseLeave: TNotifyEvent; FOnCtl3DChanged: TNotifyEvent; FOnParentColorChanged: TNotifyEvent; FOver: Boolean; FTransparent: Boolean; FFlatBorder: Boolean; FFlatBorderColor: TColor; FMultiLine: Boolean; procedure SetTransparent(const Value: Boolean); procedure SetFlatBorder(const Value: Boolean); procedure SetFlatBorderColor(const Value: TColor); procedure DrawCaption; procedure DrawBorders; procedure SetMultiLine(const Value: Boolean); protected procedure CMMouseEnter(var Msg: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Msg: TMessage); message CM_MOUSELEAVE; procedure CMCtl3DChanged(var Msg: TMessage); message CM_CTL3DCHANGED; procedure CMParentColorChanged(var Msg: TMessage); message CM_PARENTCOLORCHANGED; procedure CMTextChanged(var Msg: TMessage); message CM_TEXTCHANGED; procedure CreateParams(var Params: TCreateParams); override; procedure Paint; override; procedure WMEraseBkgnd(var Msg: TWMEraseBkgnd); message WM_ERASEBKGND; public constructor Create(AOwner: TComponent); override; procedure Invalidate; override; published property HintColor: TColor read FHintColor write FHintColor default clInfoBk; property Transparent: Boolean read FTransparent write SetTransparent default False; property MultiLine: Boolean read FMultiLine write SetMultiLine; property FlatBorder: Boolean read FFlatBorder write SetFlatBorder default False; property FlatBorderColor: TColor read FFlatBorderColor write SetFlatBorderColor default clBtnShadow; property OnMouseEnter: TNotifyEvent read FOnMouseEnter write FOnMouseEnter; property OnMouseLeave: TNotifyEvent read FOnMouseLeave write FOnMouseLeave; property OnCtl3DChanged: TNotifyEvent read FOnCtl3DChanged write FOnCtl3DChanged; property OnParentColorChange: TNotifyEvent read FOnParentColorChanged write FOnParentColorChanged; end; implementation constructor TssPanel.Create(AOwner: TComponent); begin inherited Create(AOwner); FHintColor := clInfoBk; FOver := False; FTransparent := False; FFlatBorder := False; FFlatBorderColor := clBtnShadow; end; procedure TssPanel.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.ExStyle := Params.ExStyle + WS_EX_TRANSPARENT; ControlStyle := ControlStyle - [csOpaque] + [csAcceptsControls]; end; procedure TssPanel.Paint; begin Canvas.Brush.Color := Color; if not FTransparent then Canvas.FillRect(ClientRect); if FFlatBorder then begin Canvas.Brush.Color := FFlatBorderColor; Canvas.FrameRect(ClientRect); Canvas.Brush.Color := Color; end else DrawBorders; Self.DrawCaption; end; procedure TssPanel.DrawBorders; var Rect: TRect; TopColor, BottomColor: TColor; procedure AdjustColors(Bevel: TPanelBevel); begin TopColor := clBtnHighlight; if Bevel = bvLowered then TopColor := clBtnShadow; BottomColor := clBtnShadow; if Bevel = bvLowered then BottomColor := clBtnHighlight; end; begin Rect := ClientRect; if BevelOuter <> bvNone then begin AdjustColors(BevelOuter); Frame3D(Canvas, Rect, TopColor, BottomColor, BevelWidth); end; Frame3D(Canvas, Rect, Color, Color, BorderWidth); if BevelInner <> bvNone then begin AdjustColors(BevelInner); Frame3D(Canvas, Rect, TopColor, BottomColor, BevelWidth); end; end; procedure TssPanel.DrawCaption; const Alignments: array [TAlignment] of Longint = (DT_LEFT, DT_RIGHT, DT_CENTER); WordWrap: array [Boolean] of Longint = (DT_SINGLELINE, DT_WORDBREAK); var ATextRect: TRect; BevelSize: Integer; Flags: Longint; begin with Self.Canvas do begin if Caption <> '' then begin Font := Self.Font; ATextRect := GetClientRect; InflateRect(ATextRect, -BorderWidth, -BorderWidth); BevelSize := 0; if BevelOuter <> bvNone then Inc(BevelSize, BevelWidth); if BevelInner <> bvNone then Inc(BevelSize, BevelWidth); InflateRect(ATextRect, -BevelSize, -BevelSize); Flags := DT_EXPANDTABS or WordWrap[MultiLine] or Alignments[Alignment]; Flags := DrawTextBiDiModeFlags(Flags); //calculate required rectangle size DrawText(Canvas.Handle, PChar(Caption), -1, ATextRect, Flags or DT_CALCRECT); // adjust the rectangle placement OffsetRect(ATextRect, 0, -ATextRect.Top + (Height - (ATextRect.Bottom - ATextRect.Top)) div 2); case Alignment of taRightJustify: OffsetRect(ATextRect, -ATextRect.Left + (Width - (ATextRect.Right - ATextRect.Left) - BorderWidth - BevelSize), 0); taCenter: OffsetRect(ATextRect, -ATextRect.Left + (Width - (ATextRect.Right - ATextRect.Left)) div 2, 0); end; if not Enabled then Font.Color := clGrayText; //draw text if Transparent then SetBkMode(Canvas.Handle, Windows.TRANSPARENT); DrawText(Canvas.Handle, PChar(Caption), -1, ATextRect, Flags); end; end; end; procedure TssPanel.CMCtl3DChanged(var Msg: TMessage); begin inherited; Invalidate; if Assigned(FOnCtl3DChanged) then FOnCtl3DChanged(Self); end; procedure TssPanel.CMParentColorChanged(var Msg: TMessage); begin inherited; Invalidate; if Assigned(FOnParentColorChanged) then FOnParentColorChanged(Self); end; procedure TssPanel.CMMouseEnter(var Msg: TMessage); begin if not FOver then begin FSaved := Application.HintColor; // for D7... if csDesigning in ComponentState then Exit; Application.HintColor := FHintColor; FOver := True; end; if Assigned(FOnMouseEnter) then FOnMouseEnter(Self); end; procedure TssPanel.CMMouseLeave(var Msg: TMessage); begin if FOver then begin Application.HintColor := FSaved; FOver := False; end; if Assigned(FOnMouseLeave) then FOnMouseLeave(Self); end; procedure TssPanel.SetTransparent(const Value: Boolean); begin if Value <> FTransparent then begin FTransparent := Value; Invalidate; end; end; procedure TssPanel.SetFlatBorder(const Value: Boolean); begin if Value <> FFlatBorder then begin FFlatBorder := Value; Invalidate; end; end; procedure TssPanel.SetFlatBorderColor(const Value: TColor); begin if Value <> FFlatBorderColor then begin FFlatBorderColor := Value; Invalidate; end; end; procedure TssPanel.WMEraseBkgnd(var Msg: TWMEraseBkgnd); begin // Msg.Result := 1; end; procedure TssPanel.SetMultiLine(const Value: Boolean); begin if FMultiLine <> Value then begin FMultiLine := Value; Invalidate; end; end; procedure TssPanel.CMTextChanged(var Msg: TMessage); begin inherited; Invalidate; end; procedure TssPanel.Invalidate; begin if Transparent and Assigned(Parent) and Parent.HandleAllocated and HandleAllocated then RedrawWindow(Parent.Handle, nil, 0, RDW_ERASE or RDW_FRAME or RDW_INTERNALPAINT or RDW_INVALIDATE or RDW_ERASENOW or RDW_UPDATENOW or RDW_ALLCHILDREN); inherited Invalidate; end; end.
unit frmMain; interface uses System.Types, System.IOUtils, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm1 = class(TForm) Button1: TButton; Memo1: TMemo; Button2: TButton; Label1: TLabel; Edit1: TEdit; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private procedure ListFiless(FilePath: string); procedure ListDirs(DirName: string); { Private declarations } public { Public declarations } // 递归演示:数字累加 procedure ProRecursion(i: Integer); function FunRecursion(i: Integer): Integer; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin ShowMessage('调用方:' + FunRecursion(0).ToString); end; procedure TForm1.Button2Click(Sender: TObject); begin // 获取当前目录下所有的文件 ListFiless(Edit1.Text); // 获取当前目录下所有的文件夹 ListDirs(Edit1.Text); end; // 递归演示(函数):数字累加 function TForm1.FunRecursion(i: Integer): Integer; begin ShowMessage('方法内部:' + i.ToString); i := i + 1; if (i < 10) then begin Result := FunRecursion(i); end else begin Result := i; end; end; procedure TForm1.ListDirs(DirName: string); var DirList: TStringDynArray; Name: string; begin // 获取某个路径下的所有文件夹 DirList := TDirectory.GetDirectories(DirName); // 遍历,获取每一个文件夹(路径) for Name in DirList do begin // 将获取到的路径加入窗口 Self.Memo1.Lines.Add(Name); // 获取这个路径下所有文件 ListFiless(Name); // 递归,继续获取当前(Name)目录下的文件夹 ListDirs(Name); end; end; procedure TForm1.ListFiless(FilePath: string); var FileList: TStringDynArray; FileName: string; begin // 获取当前路径下的所有文件 FileList := TDirectory.GetFiles(FilePath); //遍历数组,获取文件信息 for FileName in FileList do begin Self.Memo1.Lines.Add(FileName); end; end; // 递归演示:数字累加 ,递归方法一定要有出口 procedure TForm1.ProRecursion(i: Integer); begin ShowMessage(i.ToString); i := i + 1; if (i < 10) then begin ProRecursion(i); end; end; end.
PROGRAM SortMonth_b(INPUT, OUTPUT); {Программа сравнивает введённые значения месяцев} USES DateIO; {ReadMonth, WriteMonth} VAR MonthNameFirst, MonthNameSecond: Month; BEGIN {SortMonth} IF NOT EOLN THEN BEGIN ReadMonth(INPUT, MonthNameFirst); ReadMonth(INPUT, MonthNameSecond) END ELSE WRITE('Вы ничего не ввели'); IF (MonthNameFirst = NoMonth) OR (MonthNameSecond = NoMonth) THEN WRITE('Входные данные записаны неверно') ELSE IF MonthNameFirst = MonthNameSecond THEN BEGIN WRITE('Оба месяца '); WriteMonth(OUTPUT, MonthNameFirst) END ELSE BEGIN WriteMonth(OUTPUT, MonthNameFirst); IF MonthNameFirst < MonthNameSecond THEN BEGIN WRITE(' предшедствует '); WriteMonth(OUTPUT, MonthNameSecond) END ELSE BEGIN WRITE(' следует за '); WriteMonth(OUTPUT, MonthNameSecond) END END; WRITELN END. {SortMonth}
{ Licence ======= LGPLv2.1 with static linking exception (See COPYING.modifiedLGPL.txt) Credits ======= Information for this unit was obtained from: References ========== BT_USB Devices ============= This unit provides both the BT_USB device interface and the generic USB BT_USB BT_USB driver. USB BT_USB Devices ================= } {$mode delphi} {Default to Delphi compatible syntax} {$H+} {Default to AnsiString} {$inline on} {Allow use of Inline procedures} unit uBT_USB; interface uses GlobalConfig, GlobalConst, GlobalTypes, Platform, Threads, Devices, USB, SysUtils, uBT; {==============================================================================} {Global definitions} {--$INCLUDE GlobalDefines.inc} {==============================================================================} const {BT_USB specific constants} BT_USB_NAME_PREFIX = 'BT_USB'; {Name prefix for BT_USB Devices} {BT_USB Buffer Size} USB_BT_EVENT_MAX_PACKET_SIZE = 512; {BT_USB logging} BT_USB_LOG_LEVEL_DEBUG = LOG_LEVEL_DEBUG; {BT_USB debugging messages} BT_USB_LOG_LEVEL_INFO = LOG_LEVEL_INFO; {BT_USB informational messages, such as a device being attached or detached} BT_USB_LOG_LEVEL_ERROR = LOG_LEVEL_ERROR; {BT_USB error messages} BT_USB_LOG_LEVEL_NONE = LOG_LEVEL_NONE; {No BT_USB messages} ny : array [boolean] of string = ('NO', 'YES'); var BT_USB_DEFAULT_LOG_LEVEL : LongWord = BT_USB_LOG_LEVEL_DEBUG; var BT_USB_LOG_ENABLED : Boolean; Report_Size : Longword = 5; const BT_USB_DRIVER_NAME = 'BT (USB) Driver'; {Name of USB BT driver} BT_USB_DESCRIPTION = 'BT (USB)'; {Description of USB BT device} type {BT_USB Device} PBT_USBDevice = ^TBT_USBDevice; {BT_USB Enumeration Callback} TBT_USBEnumerate = function (BT_USB : PBT_USBDevice; Data : Pointer) : LongWord; {BT_USB Notification Callback} TBT_USBNotification = function (Device : PDevice; Data : Pointer; Notification : LongWord) : LongWord; TBT_USBDevice = record BT : TBTDevice; // bt device workings Parent : PUSBDevice; // Hub attached to HubPort : byte; // Port on Hub EventRequest, BulkInRequest : PUSBRequest; // USB request for BT_USB event data via Interrupt IN report data EventEP, // event endpoint BulkInEP, BulkOutEP : PUSBEndpointDescriptor; // bulk transfer endpoints // WaiterThread : TThreadId; // Thread waiting for pending requests to complete EventRemaining, EventPos : LongWord; // number of bytes still remaining of event EventResponse : array of byte; end; procedure BT_USBInit; function BT_USBDriverBind (Device : PUSBDevice; Interrface : PUSBInterface) : LongWord; function BT_USBDriverUnbind (Device : PUSBDevice; Interrface : PUSBInterface) : LongWord; function BT_USBDeviceCommand (BT : PBTDevice; Buffer : Pointer; Size : Longword; var Count : Longword) : LongWord; function BT_USBDeviceEvent (BT : PBTDevice; Buffer : Pointer; Size : LongWord; var Count : LongWord) : LongWord; implementation uses uLog; var BT_USBInitialized : Boolean = false; BT_USBDriver : PUSBDriver; {Generic BT_USB Driver} procedure BT_USBInit; var Status : LongWord; begin if BT_USBInitialized then Exit; BT_USBDriver := USBDriverCreate; if BT_USBDriver <> nil then begin BT_USBDriver.Driver.DriverName := BT_USB_DRIVER_NAME; BT_USBDriver.DriverBind := BT_USBDriverBind; BT_USBDriver.DriverUnbind := BT_USBDriverUnbind; Status := USBDriverRegister (BT_USBDriver); if Status <> USB_STATUS_SUCCESS then begin Log ('Failed to register generic BT_USB driver: ' + USBStatusToString (Status)); end; end else begin Log ('BT_USB: Failed to create generic BT_USB driver'); end; BT_USBInitialized := True; end; function BT_USBDeviceCommand (BT : PBTDevice; Buffer : Pointer; Size : Longword; var Count : Longword) : LongWord; var res : LongWord; begin Result := USB_STATUS_INVALID_PARAMETER; if BT = nil then exit; count := 0; res := USBControlTransfer (PUSBDevice (BT.Device.DeviceData), // usb device nil, // endpoint 0 $00, // class specific reuqest for this device $20, // request type $00, // value $00, // index Buffer, // command buffer Size, // command buffer length Count, // return count 5000); // timeout 5 secs if (res <> USB_STATUS_SUCCESS) then log ('Command Result ' + USBStatusToString (res) + ' Return ' + count.ToString); Result := res; // USB_STATUS_SUCCESS; end; function BT_USBDeviceEvent (BT : PBTDevice; Buffer : Pointer; Size : LongWord; var Count : LongWord) : LongWord; begin log ('device event'); Result := USB_STATUS_SUCCESS; end; procedure EventReportWorker (Request : PUSBRequest); var res : LongWord; BT : PBT_USBDevice; b : array of byte; // s : string; // i : integer; count : integer; begin if Request = nil then exit; BT := PBT_USBDevice (Request.DriverData); // Log ('report actual size ' + Request.ActualSize.ToString); //Log ('report size ' + Request.CurrentData .ActualSize.ToString); if BT <> nil then begin if MutexLock (BT.BT.Lock) = ERROR_SUCCESS then begin try if BT.BT.BTState = BT_STATE_DETACHING then Request.Status := USB_STATUS_DEVICE_DETACHED; if (Request.Status = USB_STATUS_SUCCESS) then begin b := Request.Data; if (BT.EventRemaining = 0) then // new packet begin if (Request.ActualSize > 1) then begin BT.EventRemaining := b[1] + 2 - Request.ActualSize; SetLength (BT.EventResponse, b[1] + 2); if Request.ActualSize <= length (BT.EventResponse) then Move (Request.Data^, BT.EventResponse[0], Request.ActualSize) else begin BTLogError (@BT.BT, 'Packet Size Error.'); end; BT.EventPos := Request.ActualSize; end else begin BTLogError (@BT.BT, 'Too short a response.'); end; end else begin BT.EventRemaining := BT.EventRemaining - Request.ActualSize; if BT.EventPos + Request.ActualSize <= length (BT.EventResponse) then Move (Request.Data^, BT.EventResponse[BT.EventPos], Request.ActualSize) else begin BTLogError (@BT.BT, 'Packet Size Error.'); end; BT.EventPos := BT.EventPos + Request.ActualSize; end; if (BT.EventRemaining = 0) and (Assigned (BT.BT.DeviceEvent)) then begin res := BT.BT.DeviceEvent (@BT.BT, @BT.EventResponse[0], length (BT.EventResponse), count); if res <> ERROR_SUCCESS then begin log ('error device event ' + res.ToString); end; (* s := ''; for i := 0 to length (BT.EventResponse) - 1 do s := s + ' ' + BT.EventResponse[i].ToHexString (2); Log ('<-- ' + s); *) end; end; finally MutexUnlock (BT.BT.Lock); end; end; end; res := USBRequestSubmit (Request); if res <> USB_STATUS_SUCCESS then Log ('resubmit ' + USBStatusTostring (res)); end; procedure EventReportComplete (Request : PUSBRequest); begin if Request = nil then Exit; WorkerSchedule (0, TWorkerTask (EventReportWorker), Request, nil); end; procedure BulkInReportWorker (Request : PUSBRequest); var res : LongWord; BT : PBT_USBDevice; // b : array of byte; // s : string; // i : integer; // count : integer; begin // Log ('bulk in worker.'); if Request = nil then exit; BT := PBT_USBDevice (Request.DriverData); Log ('bulk report actual size ' + Request.ActualSize.ToString); // Log ('bulk report size ' + Request.CurrentData .ActualSize.ToString); if BT <> nil then begin (* if MutexLock (BT.BT.Lock) = ERROR_SUCCESS then begin try if BT.BT.BTState = BT_STATE_DETACHING then Request.Status := USB_STATUS_DEVICE_DETACHED; if (Request.Status = USB_STATUS_SUCCESS) then begin b := Request.Data; if (BT.EventRemaining = 0) then // new packet begin if (Request.ActualSize > 1) then begin BT.EventRemaining := b[1] + 2 - Request.ActualSize; SetLength (BT.EventResponse, b[1] + 2); if Request.ActualSize <= length (BT.EventResponse) then Move (Request.Data^, BT.EventResponse[0], Request.ActualSize) else begin BTLogError (@BT.BT, 'Packet Size Error.'); end; BT.EventPos := Request.ActualSize; end else begin BTLogError (@BT.BT, 'Too short a response.'); end; end else begin BT.EventRemaining := BT.EventRemaining - Request.ActualSize; // Log ('event pos ' + BT.EventPos.ToString + ' actual size ' + Request.ActualSize.ToString + ' length ' + length (BT.EventResponse).ToString); if BT.EventPos + Request.ActualSize <= length (BT.EventResponse) then Move (Request.Data^, BT.EventResponse[BT.EventPos], Request.ActualSize) else begin BTLogError (@BT.BT, 'Packet Size Error.'); end; BT.EventPos := BT.EventPos + Request.ActualSize; end; // Log ('remaining ' + BT.eventremaining.tostring); if (BT.EventRemaining = 0) and (Assigned (BT.BT.DeviceEvent)) then begin res := BT.BT.DeviceEvent (@BT.BT, @BT.EventResponse[0], length (BT.EventResponse), count); if res <> ERROR_SUCCESS then begin log ('error device event ' + res.ToString); end; // else // BT.BT.QueueEvent.SetEvent; s := ''; for i := 0 to length (BT.EventResponse) - 1 do s := s + ' ' + BT.EventResponse[i].ToHexString (2); Log ('Event Response ' + s); ( * i := 6; s := ''; while (BT.EventResponse[i] <> 0) do begin s := s + chr (BT.EventResponse[i]); i := i + 1; end; Log (s); * ) end; end; finally MutexUnlock (BT.BT.Lock); end; end; *) end; res := USBRequestSubmit (Request); if res <> USB_STATUS_SUCCESS then Log ('resubmit ' + USBStatusTostring (res)); end; procedure BulkInReportComplete (Request : PUSBRequest); begin if Request = nil then Exit; WorkerSchedule (0, TWorkerTask (BulkInReportWorker), Request, nil); end; function BT_USBDriverBind (Device : PUSBDevice; Interrface : PUSBInterface) : LongWord; var i : integer; EventEP, BulkInEP, BulkOutEP : PUSBEndpointDescriptor; anInterface : PUSBInterface; BT : PBT_USBDevice; Status : LongWord; begin Result := USB_STATUS_DEVICE_UNSUPPORTED; if Device = nil then exit; if Interrface <> nil then exit; if not ((Device.Descriptor.bDeviceClass = USB_CLASS_CODE_WIRELESS_CONTROLLER) and // wireless controller (Device.Descriptor.bDeviceSubClass = $01) and // rf controller (Device.Descriptor.bDeviceProtocol = $01)) then exit; // bluetooth primary controller Log ('USB device : VID ' + Device.Descriptor.idVendor.ToHexString (4) + ' PID ' + Device.Descriptor.idProduct.ToHexString (4)); Log (Device.Manufacturer + ' ' + Device.Product + ' SNo. ' + Device^.SerialNumber); Log ('binding'); EventEP := nil; BulkInEP := nil; BulkOutEP := nil; for i := low (Device.Configuration.Interfaces) to high (Device.Configuration.Interfaces) do begin anInterface := Device.Configuration.Interfaces[i]; if EventEP = nil then EventEP := USBDeviceFindEndpointByType (Device, anInterface, USB_DIRECTION_IN, USB_TRANSFER_TYPE_INTERRUPT); if BulkInEP = nil then BulkInEP := USBDeviceFindEndpointByType (Device, anInterface, USB_DIRECTION_IN, USB_TRANSFER_TYPE_BULK); if BulkOutEP = nil then BulkOutEP := USBDeviceFindEndpointByType (Device, anInterface, USB_DIRECTION_OUT, USB_TRANSFER_TYPE_BULK); if (EventEP <> nil) and (BulkInEP <> nil) and (BulkOutEP <> nil) then break; // found them all end; BT := PBT_USBDevice (BTDeviceCreateEx (SizeOf (TBT_USBDevice))); if BT = nil then exit; BT.BT.Device.DeviceBus := DEVICE_BUS_USB; BT.BT.Device.DeviceType := BT_TYPE_USB; // as opposed to BT_TYPE_UART or others BT.BT.Device.DeviceData := Device; // are this and below the same BT.BT.DeviceCommand := BT_USBDeviceCommand; BT.BT.DeviceEvent := BTDeviceEvent; Device.Device.DeviceData := BT; // check this // if @bt.BT.Device.DeviceData = @Device.Device.DeviceData then // log ('both device datas are the same') // else // log ('device datas are different'); BT.BT.Device.DeviceDescription := BT_USB_DESCRIPTION; BT.BT.BTState := BT_STATE_ATTACHING; BT.EventEP := EventEP; BT.BulkInEP := BulkInEP; BT.BulkOutEP := BulkOutEP; // BT.WaiterThread := INVALID_HANDLE_VALUE; BT.EventRequest := USBRequestAllocate (Device, EventEP, EventReportComplete, USB_BT_EVENT_MAX_PACKET_SIZE, BT); if BT.EventRequest = nil then begin BTDeviceDestroy (@BT.BT); Result := USB_STATUS_DEVICE_UNSUPPORTED; exit; end; BT.BulkInRequest := USBRequestAllocate (Device, BulkInEP, BulkInReportComplete, USB_BT_EVENT_MAX_PACKET_SIZE, BT); if BT.BulkInRequest = nil then begin BTDeviceDestroy (@BT.BT); Result := USB_STATUS_DEVICE_UNSUPPORTED; exit; end; BT.BT.BTId := DEVICE_ID_ANY; if BTDeviceRegister (@BT.BT) <> ERROR_SUCCESS then begin USBRequestRelease (BT.EventRequest); BTDeviceDestroy (@BT.BT); Result := USB_STATUS_DEVICE_UNSUPPORTED; exit; end; Status := USBRequestSubmit (BT.EventRequest); if Status <> USB_STATUS_SUCCESS then begin USBRequestRelease (BT.EventRequest); BTDeviceDeregister (@BT.BT); BTDeviceDestroy (@BT.BT); Result := Status; exit; end; Status := USBRequestSubmit (BT.BulkInRequest); if Status <> USB_STATUS_SUCCESS then begin USBRequestRelease (BT.EventRequest); BTDeviceDeregister (@BT.BT); BTDeviceDestroy (@BT.BT); Result := Status; exit; end; if BTDeviceSetState (@BT.BT, BT_STATE_ATTACHED) <> ERROR_SUCCESS then exit; Result := USB_STATUS_SUCCESS; Log ('bound'); Log (''); end; function BT_USBDriverUnbind (Device : PUSBDevice; Interrface : PUSBInterface) : LongWord; var BT : PBT_USBDevice; begin Result := USB_STATUS_INVALID_PARAMETER; if Device = nil then exit; if Interrface <> nil then exit; if Device.Driver <> BT_USBDriver then Exit; Log ('unbinding'); BT := PBT_USBDevice (Device.Device.DeviceData); if BT = nil then exit; if BT.BT.Device.Signature <> DEVICE_SIGNATURE then exit; Result := USB_STATUS_OPERATION_FAILED; if BTDeviceSetState (@BT.BT, BT_STATE_DETACHING) <> ERROR_SUCCESS then exit; if MutexLock (BT.BT.Lock) <> ERROR_SUCCESS then Exit; USBRequestCancel (BT.EventRequest); MutexUnlock (BT.BT.Lock); if BTDeviceSetState (@BT.BT, BT_STATE_DETACHED) <> ERROR_SUCCESS then exit; USBRequestRelease (BT.EventRequest); Device.DriverData := nil; if BTDeviceDeregister (@BT.BT) <> ERROR_SUCCESS then exit; BTDeviceDestroy (@BT.BT); Result := USB_STATUS_SUCCESS; log ('unbound'); log (''); (* function USBMouseDriverUnbind(Device:PUSBDevice;Interrface:PUSBInterface):LongWord; {Unbind the Mouse driver from a USB device} {Device: The USB device to unbind from} {Interrface: The USB interface to unbind from (or nil for whole device)} {Return: USB_STATUS_SUCCESS if completed or another error code on failure} var Message:TMessage; Mouse:PUSBMouseDevice; begin {} Result:=USB_STATUS_INVALID_PARAMETER; {Check Device} if Device = nil then Exit; {Check Interface} if Interrface = nil then Exit; {Check Driver} if Interrface.Driver <> USBMouseDriver then Exit; {$IFDEF USB_DEBUG} if USB_LOG_ENABLED then USBLogDebug(Device,'Mouse: Unbinding USB device (Manufacturer=' + Device.Manufacturer + ' Product=' + Device.Product + ' Address=' + IntToStr(Device.Address) + ')'); {$ENDIF} {Get Mouse} Mouse:=PUSBMouseDevice(Interrface.DriverData); if Mouse = nil then Exit; if Mouse.Mouse.Device.Signature <> DEVICE_SIGNATURE then Exit; {Set State to Detaching} Result:=USB_STATUS_OPERATION_FAILED; if MouseDeviceSetState(@Mouse.Mouse,MOUSE_STATE_DETACHING) <> ERROR_SUCCESS then Exit; {Acquire the Lock} if MutexLock(Mouse.Mouse.Lock) <> ERROR_SUCCESS then Exit; {Cancel Report Request} USBRequestCancel(Mouse.ReportRequest); {Check Pending} if Mouse.PendingCount <> 0 then begin {$IFDEF USB_DEBUG} if USB_LOG_ENABLED then USBLogDebug(Device,'Mouse: Waiting for ' + IntToStr(Mouse.PendingCount) + ' pending requests to complete'); {$ENDIF} {Wait for Pending} {Setup Waiter} Mouse.WaiterThread:=GetCurrentThreadId; {Release the Lock} MutexUnlock(Mouse.Mouse.Lock); {Wait for Message} ThreadReceiveMessage(Message); end else begin {Release the Lock} MutexUnlock(Mouse.Mouse.Lock); end; {Set State to Detached} if MouseDeviceSetState(@Mouse.Mouse,MOUSE_STATE_DETACHED) <> ERROR_SUCCESS then Exit; {Update Interface} Interrface.DriverData:=nil; {Release Report Request} USBRequestRelease(Mouse.ReportRequest); {Deregister Mouse} if MouseDeviceDeregister(@Mouse.Mouse) <> ERROR_SUCCESS then Exit; {Destroy Mouse} MouseDeviceDestroy(@Mouse.Mouse); {Return Result} Result:=USB_STATUS_SUCCESS; end; *) end; initialization // BT_USBInit; finalization (* {Check Flags} if (Mouse.Mouse.Device.DeviceFlags and MOUSE_FLAG_DIRECT_READ) = 0 then begin {Global Buffer} {Acquire the Lock} if MutexLock(MouseBufferLock) = ERROR_SUCCESS then begin try {Check Buffer} if (MouseBuffer.Count < MOUSE_BUFFER_SIZE) then begin Data:=@MouseBuffer.Buffer[(MouseBuffer.Start + MouseBuffer.Count) mod MOUSE_BUFFER_SIZE]; if Data <> nil then begin {Byte 0 is the Mouse buttons} Data.Buttons:=0; if (PByte(Buffer)^ and USB_HID_BOOT_LEFT_BUTTON) <> 0 then begin {Check Flags} if (Mouse.Mouse.Device.DeviceFlags and MOUSE_FLAG_SWAP_BUTTONS) = 0 then begin Data.Buttons:=Data.Buttons or MOUSE_LEFT_BUTTON; end else begin Data.Buttons:=Data.Buttons or MOUSE_RIGHT_BUTTON; end; end; if (PByte(Buffer)^ and USB_HID_BOOT_RIGHT_BUTTON) <> 0 then begin {Check Flags} if (Mouse.Mouse.Device.DeviceFlags and MOUSE_FLAG_SWAP_BUTTONS) = 0 then begin Data.Buttons:=Data.Buttons or MOUSE_RIGHT_BUTTON; end else begin Data.Buttons:=Data.Buttons or MOUSE_LEFT_BUTTON; end; end; if (PByte(Buffer)^ and USB_HID_BOOT_MIDDLE_BUTTON) <> 0 then Data.Buttons:=Data.Buttons or MOUSE_MIDDLE_BUTTON; if (PByte(Buffer)^ and USB_HID_BOOT_SIDE_BUTTON) <> 0 then Data.Buttons:=Data.Buttons or MOUSE_SIDE_BUTTON; if (PByte(Buffer)^ and USB_HID_BOOT_EXTRA_BUTTON) <> 0 then Data.Buttons:=Data.Buttons or MOUSE_EXTRA_BUTTON; {Byte 1 is the Mouse X offset} Data.OffsetX:=PShortInt(PtrUInt(Buffer) + 1)^; {Byte 2 is the Mouse Y offset} Data.OffsetY:=PShortInt(PtrUInt(Buffer) + 2)^; {Byte 3 is the Mouse Wheel offset} Data.OffsetWheel:=PShortInt(PtrUInt(Buffer) + 3)^; {Update Count} Inc(MouseBuffer.Count); {Signal Data Received} SemaphoreSignal(MouseBuffer.Wait); end; end else begin if USB_LOG_ENABLED then USBLogError(Request.Device,'Mouse: Buffer overflow, report discarded'); {Update Statistics} Inc(Mouse.Mouse.BufferOverruns); end; finally {Release the Lock} MutexUnlock (MouseBufferLock); end; end else begin if USB_LOG_ENABLED then USBLogError(Request.Device,'Mouse: Failed to acquire lock on buffer'); end; end else begin {Direct Buffer} {Check Buffer} if (Mouse.Mouse.Buffer.Count < MOUSE_BUFFER_SIZE) then begin Data:=@Mouse.Mouse.Buffer.Buffer[(Mouse.Mouse.Buffer.Start + Mouse.Mouse.Buffer.Count) mod MOUSE_BUFFER_SIZE]; if Data <> nil then begin {Byte 0 is the Mouse buttons} Data.Buttons:=0; if (PByte(Buffer)^ and USB_HID_BOOT_LEFT_BUTTON) <> 0 then begin {Check Flags} if (Mouse.Mouse.Device.DeviceFlags and MOUSE_FLAG_SWAP_BUTTONS) = 0 then begin Data.Buttons:=Data.Buttons or MOUSE_LEFT_BUTTON; end else begin Data.Buttons:=Data.Buttons or MOUSE_RIGHT_BUTTON; end; end; if (PByte(Buffer)^ and USB_HID_BOOT_RIGHT_BUTTON) <> 0 then begin {Check Flags} if (Mouse.Mouse.Device.DeviceFlags and MOUSE_FLAG_SWAP_BUTTONS) = 0 then begin Data.Buttons:=Data.Buttons or MOUSE_RIGHT_BUTTON; end else begin Data.Buttons:=Data.Buttons or MOUSE_LEFT_BUTTON; end; end; if (PByte(Buffer)^ and USB_HID_BOOT_MIDDLE_BUTTON) <> 0 then Data.Buttons:=Data.Buttons or MOUSE_MIDDLE_BUTTON; if (PByte(Buffer)^ and USB_HID_BOOT_SIDE_BUTTON) <> 0 then Data.Buttons:=Data.Buttons or MOUSE_SIDE_BUTTON; if (PByte(Buffer)^ and USB_HID_BOOT_EXTRA_BUTTON) <> 0 then Data.Buttons:=Data.Buttons or MOUSE_EXTRA_BUTTON; {Byte 1 is the Mouse X offset} Data.OffsetX:=PShortInt(PtrUInt(Buffer) + 1)^; {Byte 2 is the Mouse Y offset} Data.OffsetY:=PShortInt(PtrUInt(Buffer) + 2)^; {Byte 3 is the Mouse Wheel offset} Data.OffsetWheel:=PShortInt(PtrUInt(Buffer) + 3)^; {Update Count} Inc(Mouse.Mouse.Buffer.Count); {Signal Data Received} SemaphoreSignal(Mouse.Mouse.Buffer.Wait); end; end else begin if USB_LOG_ENABLED then USBLogError(Request.Device,'Mouse: Buffer overflow, report discarded'); {Update Statistics} Inc(Mouse.Mouse.BufferOverruns); end; end; end else begin if USB_LOG_ENABLED then USBLogError(Request.Device,'Mouse: Failed report request (Status=' + USBStatusToString(Request.Status) + ', ActualSize=' + IntToStr(Request.ActualSize) + ')'); {Update Statistics} Inc(Mouse.Mouse.ReceiveErrors); end; {Update Pending} Dec(Mouse.PendingCount); {Check State} if Mouse.Mouse.MouseState = MOUSE_STATE_DETACHING then begin {Check Pending} if Mouse.PendingCount = 0 then begin {Check Waiter} if Mouse.WaiterThread <> INVALID_HANDLE_VALUE then begin {$IFDEF USB_DEBUG} if USB_LOG_ENABLED then USBLogDebug(Request.Device,'Mouse: Detachment pending, sending message to waiter thread (Thread=' + IntToHex(Mouse.WaiterThread,8) + ')'); {$ENDIF} {Send Message} FillChar(Message,SizeOf(TMessage),0); ThreadSendMessage(Mouse.WaiterThread,Message); Mouse.WaiterThread:=INVALID_HANDLE_VALUE; end; end; end else begin {Update Pending} Inc(Mouse.PendingCount); {$IFDEF USB_DEBUG} if USB_LOG_ENABLED then USBLogDebug(Request.Device,'Mouse: Resubmitting report request'); {$ENDIF} {Resubmit Request} Status:=USBRequestSubmit(Request); if Status <> USB_STATUS_SUCCESS then begin if USB_LOG_ENABLED then USBLogError(Request.Device,'Mouse: Failed to resubmit report request: ' + USBStatusToString(Status)); {Update Pending} Dec(Mouse.PendingCount); end; end; finally {Release the Lock} MutexUnlock(Mouse.Mouse.Lock); end; end else begin if USB_LOG_ENABLED then USBLogError(Request.Device,'Mouse: Failed to acquire lock'); end; end *) end.
unit dmMain; interface uses System.SysUtils, System.Classes, Data.Bind.GenData, IPPeerClient, IPPeerServer, System.Tether.Manager, System.Tether.AppProfile, Data.Bind.Components, Data.Bind.ObjectScope, Fmx.Bind.GenData, unitGamePlayer, System.Actions, FMX.ActnList; type TTetheringStatus = class private FStatus: string; public property Status : string read FStatus write FStatus; end; TdataMain = class(TDataModule) pbsPlayer: TPrototypeBindSource; pbsScoreboard: TPrototypeBindSource; TetheringManager1: TTetheringManager; TetheringAppProfile1: TTetheringAppProfile; pbsStatus: TPrototypeBindSource; ActionList1: TActionList; actGetScores: TAction; procedure TetheringManager1RequestManagerPassword(const Sender: TObject; const RemoteIdentifier: string; var Password: string); procedure TetheringManager1RemoteManagerShutdown(const Sender: TObject; const ManagerIdentifier: string); procedure TetheringManager1EndAutoConnect(Sender: TObject); procedure pbsStatusCreateAdapter(Sender: TObject; var ABindSourceAdapter: TBindSourceAdapter); procedure pbsPlayerCreateAdapter(Sender: TObject; var ABindSourceAdapter: TBindSourceAdapter); procedure TetheringAppProfile1ResourceReceived(const Sender: TObject; const AResource: TRemoteResource); procedure pbsScoreboardCreateAdapter(Sender: TObject; var ABindSourceAdapter: TBindSourceAdapter); private { Private declarations } FScoreBoard : TGamePlayerList; FStatusObj : TTetheringStatus; public { Public declarations } constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure CheckConnections; procedure ConnectToScoreboard; procedure SendScore; end; var dataMain: TdataMain; implementation {%CLASSGROUP 'FMX.Controls.TControl'} uses Rest.JSON, FMX.Dialogs; {$R *.dfm} procedure TdataMain.CheckConnections; var I: Integer; ConnectedProfiles : String; begin if TetheringManager1.RemoteProfiles.Count > 0 then begin for I := 0 to TetheringManager1.RemoteProfiles.Count - 1 do begin ConnectedProfiles := ConnectedProfiles + ' - ' + TetheringManager1.RemoteProfiles.Items[I].ProfileText; end; if Assigned(FStatusObj) then FStatusObj.Status := 'Working with :' + ConnectedProfiles; actGetScores.Execute; end else begin if Assigned(FStatusObj) then FStatusObj.Status := 'You are not connected'; end; pbsStatus.ApplyUpdates; end; procedure TdataMain.ConnectToScoreboard; begin TetheringManager1.AutoConnect; CheckConnections; end; constructor TdataMain.Create(AOwner: TComponent); begin FScoreBoard := TGamePlayerList.Create(True); FStatusObj := TTetheringStatus.Create; inherited Create(AOwner); end; destructor TdataMain.destroy; begin inherited; end; procedure TdataMain.pbsPlayerCreateAdapter(Sender: TObject; var ABindSourceAdapter: TBindSourceAdapter); begin ABindSourceAdapter := TObjectBindSourceAdapter<TGamePlayer>.Create(Self,TGamePlayer.Create('Annonymous'),True); end; procedure TdataMain.pbsScoreboardCreateAdapter(Sender: TObject; var ABindSourceAdapter: TBindSourceAdapter); begin ABindSourceAdapter := TListBindSourceAdapter<TGamePlayer>.Create(Self,FScoreBoard,True); end; procedure TdataMain.pbsStatusCreateAdapter(Sender: TObject; var ABindSourceAdapter: TBindSourceAdapter); begin ABindSourceAdapter := TObjectBindSourceAdapter<TTetheringStatus>.Create(Self,FStatusObj,True); end; procedure TdataMain.SendScore; begin if TetheringManager1.RemoteProfiles.Count > 0 then TetheringAppProfile1.SendString(TetheringManager1.RemoteProfiles.Items[0], 'TGamePlayer', TJson.ObjectToJsonString(TGamePlayer(pbsPlayer.InternalAdapter.Current))); end; procedure TdataMain.TetheringAppProfile1ResourceReceived(const Sender: TObject; const AResource: TRemoteResource); var TopPlayers: TStringList; PlayerObj: TGamePlayer; PlayerJSON : string; begin pbsScoreboard.Active := False; FScoreBoard.Clear; TopPlayers := TStringList.Create; try TopPlayers.Delimiter := Data_Delimiter; TopPlayers.DelimitedText := AResource.Value.AsString; for PlayerJSON in TopPlayers do begin PlayerObj := TJson.JsonToObject<TGamePlayer>(PlayerJSON); FScoreBoard.Add(PlayerObj); end; finally TopPlayers.Free; end; pbsScoreboard.Active := True; end; procedure TdataMain.TetheringManager1EndAutoConnect(Sender: TObject); begin CheckConnections; end; procedure TdataMain.TetheringManager1RemoteManagerShutdown( const Sender: TObject; const ManagerIdentifier: string); begin CheckConnections; end; procedure TdataMain.TetheringManager1RequestManagerPassword( const Sender: TObject; const RemoteIdentifier: string; var Password: string); begin Password := '1234'; end; end.
unit DAO.CadastroFinanceiro; interface uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Model.CadastroFinanceiro; type TCadastroFinanceiroDAO = class private FConexao: TConexao; public constructor Create(); function GetID(iID: Integer): Integer; function Insert(aFinanceiros: TCadastroFinanceiro): Boolean; function Update(aFinanceiros: TCadastroFinanceiro): Boolean; function Delete(aFinanceiros: TCadastroFinanceiro): Boolean; function Localizar(aParam: Array of variant): TFDQuery; end; const TABLENAME = 'cadastro_financeiro'; implementation function TCadastroFinanceiroDAO.Insert(aFinanceiros: TCadastroFinanceiro): Boolean; var sSQL: String; FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; aFinanceiros.Sequencia := GetID(aFinanceiros.ID); sSQL := 'INSERT INTO ' + TABLENAME + '(ID_CADASTRO, SEQ_FINANCEIRO, DES_TIPO_CONTA, COD_BANCO, ' + 'NUM_AGENCIA, DES_CONTA, COD_OPERACAO, DOM_ATIVO) ' + 'VALUES (:pID_CADASTRO, :pSEQ_FINANCEIRO, :pDES_TIPO_CONTA, :pCOD_BANCO, :pNUM_AGENCIA, ' + ':pDES_CONTA, :pCOD_OPERACAO, :pDOM_ATIVO);'; FDQuery.ExecSQL(sSQL,[aFinanceiros.ID, aFinanceiros.Sequencia, aFinanceiros.TipoConta, aFinanceiros.Banco, aFinanceiros.Agencia, aFinanceiros.Conta, aFinanceiros.Operacao, aFinanceiros.Ativo]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastroFinanceiroDAO.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('select * from ' + TABLENAME); if aParam[0] = 'ID' then begin FDQuery.SQL.Add('WHERE ID_CADASTRO = :ID_CADASTRO'); FDQuery.ParamByName('ID_CADASTRO').AsInteger := aParam[1]; end; if aParam[0] = 'SEQUENCIA' then begin FDQuery.SQL.Add('WHERE ID_CADASTRO = :ID_CADASTRO AND SEQ_FINANCEIRO = :SEQ_FINANCEIRO'); FDQuery.ParamByName('ID_CADASTRO').AsInteger := aParam[1]; FDQuery.ParamByName('SEQ_FINANCEIRO').AsInteger := aParam[2]; end; if aParam[0] = 'TIPO' then begin FDQuery.SQL.Add('WHERE DES_TIPO_CONTA LIKE :DES_TIPO_CONTA'); FDQuery.ParamByName('DES_TIPO_CONTA').AsString := aParam[1]; end; if aParam[0] = 'BANCO' then begin FDQuery.SQL.Add('WHERE COD_BANCO = :COD_BANCO'); FDQuery.ParamByName('COD_BANCO').AsString := aParam[1]; end; if aParam[0] = 'AGENCIA' then begin FDQuery.SQL.Add('WHERE COD_AGENCIA = :COD_AGENCIA'); FDQuery.ParamByName('COD_AGENCIA').AsString := aParam[1]; end; if aParam[0] = 'CONTA' then begin FDQuery.SQL.Add('WHERE DES_CONTA = :DES_CONTA'); FDQuery.ParamByName('NUM_CONTA').AsString := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('WHERE ' + aParam[1]); end; 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; function TCadastroFinanceiroDAO.Update(aFinanceiros: TCadastroFinanceiro): Boolean; var sSQL: String; FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; sSQL := 'UPDATE ' + TABLENAME + 'SET ' + 'DES_TIPO_CONTA = :pDES_TIPO_CONTA, ' + 'COD_BANCO = :pCOD_BANCO, NUM_AGENCIA = :pNUM_AGENCIA, NUM_CONTA = :pNUM_CONTA, COD_OPERACAO = :pCOD_OPERACAO, ' + 'DOM_ATIVO = :pDOM_ATIVO ' + 'WHERE ID_CADASTRO = :pID_CADASTRO AND SEQ_FINANCEIRO = :pSEQ_FINANCEIRO;'; FDQuery.ExecSQL(sSQL,[aFinanceiros.TipoConta, aFinanceiros.Banco, aFinanceiros.Agencia, aFinanceiros.Conta, aFinanceiros.Operacao, aFinanceiros.Ativo, aFinanceiros.ID, aFinanceiros.Sequencia]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; constructor TCadastroFinanceiroDAO.Create; begin FConexao := TConexao.Create; end; function TCadastroFinanceiroDAO.Delete(aFinanceiros: TCadastroFinanceiro): Boolean; var sSQL : String; FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; if aFinanceiros.Sequencia = -1 then begin sSQL := 'DELETE FROM ' + TABLENAME + ' ' + 'WHERE ID_CADASTRO = :pID_CADASTRO'; FDQuery.ExecSQL(sSQL,[aFinanceiros.ID]); end else begin sSQL := 'DELETE FROM ' + TABLENAME + ' ' + 'WHERE ID_CADASTRO = :pID_CADASTRO AND SEQ_FINANCEIRO = :pSEQ_FINANCEIRO'; FDQuery.ExecSQL(sSQL,[aFinanceiros.ID, aFinanceiros.Sequencia]); end; Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastroFinanceiroDAO.GetID(iID: Integer): Integer; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.Open('select coalesce(max(SEQ_FINANCEIRO),0) + 1 from ' + TABLENAME + ' WHERE ID_CADASTRO = ' + iID.toString); try Result := FDQuery.Fields[0].AsInteger; finally FDQuery.Close; end; finally FDQuery.Connection.Close; FDQuery.Free; end;end; end.
{ Function SST_W_C_EXP_ADRABLE (EXP) * * Returns TRUE if the "address of" operator (&) may be used in front of the * indicated expression directly. } module sst_w_c_EXP_ADRABLE; define sst_w_c_exp_adrable; %include 'sst_w_c.ins.pas'; function sst_w_c_exp_adrable ( {determine whether "address of" exp is legal} in exp: sst_exp_t) {descriptor for expression to examine} : boolean; {TRUE if "address of" expression is legal} begin sst_w_c_exp_adrable := false; {init to "address of" is not legal} if not sst_exp_simple(exp) then return; {expression is not simple ?} if exp.term1.ttype = sst_term_const_k {term is numeric constant ?} then return; if {term is symbolic constant ?} (exp.term1.ttype = sst_term_var_k) and (exp.term1.var_var_p^.vtype = sst_vtype_const_k) then return; sst_w_c_exp_adrable := true; end;
unit kwPopEditorSelectCells; {* *Формат:* aStartCell aStartRow aFinshCell aFinishRow anEditorControl pop:editor:SelectCells *Описание:* Выделяет диапазон ячеек с помощью мыши начиная от начальной (aStartCell, aRowCell) до конечной (aFinishCell, aFinishRow). Курсор должен уже находится в таблице. Положение курсора в таблице не имеет значения. Параметры aStartCell aStartRow aFinshCell aFinishRow - Integer *Пример:* [code] 0 0 2 2 focused:control:push pop:editor:SelectCells [code] *Результат:* Выделяет диапазон ячеек в таблице от (0, 0) до (2, 2) у текущего редактора. *Примечание:* В каждой ячейке должен быть только один параграф, иначе выделение будет неправильным. *Примечание 2:* Текст в начальной ячейке должен быть выровнен по левому краю. Иначе появится сообщение об ошибке. } // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\kwPopEditorSelectCells.pas" // Стереотип: "ScriptKeyword" // Элемент модели: "pop_editor_SelectCells" MUID: (4F4DD643008C) // Имя типа: "TkwPopEditorSelectCells" {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses , kwSelectCellsWord ; type TkwPopEditorSelectCells = {final} class(TkwSelectCellsWord) {* *Формат:* aStartCell aStartRow aFinshCell aFinishRow anEditorControl pop:editor:SelectCells *Описание:* Выделяет диапазон ячеек с помощью мыши начиная от начальной (aStartCell, aRowCell) до конечной (aFinishCell, aFinishRow). Курсор должен уже находится в таблице. Положение курсора в таблице не имеет значения. Параметры aStartCell aStartRow aFinshCell aFinishRow - Integer *Пример:* [code] 0 0 2 2 focused:control:push pop:editor:SelectCells [code] *Результат:* Выделяет диапазон ячеек в таблице от (0, 0) до (2, 2) у текущего редактора. *Примечание:* В каждой ячейке должен быть только один параграф, иначе выделение будет неправильным. *Примечание 2:* Текст в начальной ячейке должен быть выровнен по левому краю. Иначе появится сообщение об ошибке. } protected function IsVertical: Boolean; override; {* При выделении мышь движется сверху вниз. } class function GetWordNameForRegister: AnsiString; override; end;//TkwPopEditorSelectCells {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , Windows {$If NOT Defined(NoVCL)} , Controls {$IfEnd} // NOT Defined(NoVCL) {$If NOT Defined(NoVCL)} , Forms {$IfEnd} // NOT Defined(NoVCL) //#UC START# *4F4DD643008Cimpl_uses* //#UC END# *4F4DD643008Cimpl_uses* ; function TkwPopEditorSelectCells.IsVertical: Boolean; {* При выделении мышь движется сверху вниз. } //#UC START# *4F6042D20081_4F4DD643008C_var* //#UC END# *4F6042D20081_4F4DD643008C_var* begin //#UC START# *4F6042D20081_4F4DD643008C_impl* Result := False; //#UC END# *4F6042D20081_4F4DD643008C_impl* end;//TkwPopEditorSelectCells.IsVertical class function TkwPopEditorSelectCells.GetWordNameForRegister: AnsiString; begin Result := 'pop:editor:SelectCells'; end;//TkwPopEditorSelectCells.GetWordNameForRegister initialization TkwPopEditorSelectCells.RegisterInEngine; {* Регистрация pop_editor_SelectCells } {$IfEnd} // NOT Defined(NoScripts) end.
unit sdsChangesBetweenEditionsData; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ChangesBetweenEditions$Domain" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/ChangesBetweenEditions/sdsChangesBetweenEditionsData.pas" // Начат: 25.05.2011 16:30 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> F1 Пользовательские сервисы::ChangesBetweenEditions::ChangesBetweenEditions$Domain::ChangesBetweenEditionsImplementation::TsdsChangesBetweenEditionsData // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses ChangesBetweenEditionsInterfaces {$If not defined(NoVCM)} , vcmInterfaces {$IfEnd} //not NoVCM , l3ProtoObject ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type _IvcmRealData_ = IsdsChangesBetweenEditionsData; {$Include w:\common\components\gui\Garant\VCM\implementation\vcmData.imp.pas} TsdsChangesBetweenEditionsData = class(_vcmData_, IsdsChangesBetweenEditionsData) private // private fields f_Info : InsChangesBetweenEditionsInfo; protected // realized methods function Get_Info: InsChangesBetweenEditionsInfo; protected // overridden protected methods {$If not defined(NoVCM)} procedure AssignData(const aData: _IvcmRealData_); override; {$IfEnd} //not NoVCM procedure ClearFields; override; public // public methods constructor Create(const anInfo: InsChangesBetweenEditionsInfo); reintroduce; class function Make(const anInfo: InsChangesBetweenEditionsInfo): IsdsChangesBetweenEditionsData; reintroduce; {* Сигнатура фабрики TsdsChangesBetweenEditionsData.Make } end;//TsdsChangesBetweenEditionsData {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} type _Instance_R_ = TsdsChangesBetweenEditionsData; {$Include w:\common\components\gui\Garant\VCM\implementation\vcmData.imp.pas} // start class TsdsChangesBetweenEditionsData constructor TsdsChangesBetweenEditionsData.Create(const anInfo: InsChangesBetweenEditionsInfo); //#UC START# *4DDCF6AB0206_4DDCF660018A_var* //#UC END# *4DDCF6AB0206_4DDCF660018A_var* begin //#UC START# *4DDCF6AB0206_4DDCF660018A_impl* inherited Create; f_Info := anInfo; //#UC END# *4DDCF6AB0206_4DDCF660018A_impl* end;//TsdsChangesBetweenEditionsData.Create class function TsdsChangesBetweenEditionsData.Make(const anInfo: InsChangesBetweenEditionsInfo): IsdsChangesBetweenEditionsData; var l_Inst : TsdsChangesBetweenEditionsData; begin l_Inst := Create(anInfo); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; function TsdsChangesBetweenEditionsData.Get_Info: InsChangesBetweenEditionsInfo; //#UC START# *4DDCF63C0353_4DDCF660018Aget_var* //#UC END# *4DDCF63C0353_4DDCF660018Aget_var* begin //#UC START# *4DDCF63C0353_4DDCF660018Aget_impl* Result := f_Info; //#UC END# *4DDCF63C0353_4DDCF660018Aget_impl* end;//TsdsChangesBetweenEditionsData.Get_Info {$If not defined(NoVCM)} procedure TsdsChangesBetweenEditionsData.AssignData(const aData: _IvcmRealData_); //#UC START# *4B16B8CF0307_4DDCF660018A_var* //#UC END# *4B16B8CF0307_4DDCF660018A_var* begin //#UC START# *4B16B8CF0307_4DDCF660018A_impl* inherited; f_Info := aData.Info; //#UC END# *4B16B8CF0307_4DDCF660018A_impl* end;//TsdsChangesBetweenEditionsData.AssignData {$IfEnd} //not NoVCM procedure TsdsChangesBetweenEditionsData.ClearFields; {-} begin f_Info := nil; inherited; end;//TsdsChangesBetweenEditionsData.ClearFields {$IfEnd} //not Admin AND not Monitorings end.
unit Model.EnderecosEmpresa; interface uses Common.ENum, FireDAC.Comp.Client, Dialogs; type TEnderecosEmpresa = class private FID: Integer; FSeq: Integer; FTipo: String; FCEP: String; FLogradouro: String; FNumero: String; FComplemento: String; FBairro: String; FCidade: String; FUF: String; FCNPJ: String; FIE: String; FIEST: String; FIM: String; FAcao: TAcao; public property ID: Integer read FID write FID; property Sequencia: Integer read FSeq write FSeq; property Tipo: String read FTipo write FTipo; property CEP: String read FCEP write FCEP; property Logradouro: String read FLogradouro write FLogradouro; property Numero: String read FNumero write FNumero; property Complemento: String read FComplemento write FComplemento; property Bairro: String read FBairro write FBairro; property Cidade: String read FCidade write FCidade; property UF: String read FUF write FUF; property CNPJ: String read FCNPJ write FCNPJ; property IE: String read FIE write FIE; property IEST: String read FIEST write FIEST; property IM: String read FIM write FIM; property Acao: TAcao read FAcao write FAcao; function GetID(iID: Integer): Integer; function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; function ValidaDados(): Boolean; end; implementation { TEnderecosEmpresa } uses DAO.EnderecosEmpresa, Common.Utils; function TEnderecosEmpresa.GetID(iID: Integer): Integer; var enderecosDAO : TEnderecosEmpresaDAO; begin try enderecosDAO := TEnderecosEmpresaDAO.Create; Result := enderecosDAO.GetId(iID); finally enderecosDAO.Free; end; end; function TEnderecosEmpresa.Gravar: Boolean; var enderecosDAO: TEnderecosEmpresaDAO; begin try enderecosDAO := TEnderecosEmpresaDAO.Create; case FAcao of tacIncluir: Result := enderecosDAO.Insert(Self); tacAlterar: Result := enderecosDAO.Update(Self); tacExcluir: Result := enderecosDAO.Delete(Self); end; finally enderecosDAO.Free; end; end; function TEnderecosEmpresa.Localizar(aParam: array of variant): TFDQuery; var enderecosDAO : TEnderecosEmpresaDAO; begin try enderecosDAO := TEnderecosEmpresaDAO.Create; Result := enderecosDAO.lOCALIZAR(aParam); finally enderecosDAO.Free; end; end; function TEnderecosEmpresa.ValidaDados: Boolean; begin if not Common.Utils.TUtils.CNPJ(FCNPJ) then begin ShowMessage('CNPJ INVALIDO'); Result := False; Exit; end; Result := True; end; end.
{ Double Commander ------------------------------------------------------------------------- FFmpeg thumbnail provider Copyright (C) 2015 Alexander Koblov (alexx2000@mail.ru) FFmpegthumbnailer - lightweight video thumbnailer Copyright (C) 2010 Dirk Vanden Boer <dirk.vdb@gmail.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; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. } unit uVideoThumb; {$mode delphi} {$packrecords c} interface uses Classes, SysUtils; implementation uses CTypes, DynLibs, Graphics, Types, LazUTF8, DCOSUtils, DCConvertEncoding, uThumbnails, uClassesEx, uMasks, uGraphics; type ThumbnailerImageType = ( Png, Jpeg, Unknown ); Pvideo_thumbnailer = ^Tvideo_thumbnailer; Tvideo_thumbnailer = record thumbnail_size: cint; //* default = 128 */ seek_percentage: cint; //* default = 10 */ seek_time: pchar; //* default = NULL (format hh:mm:ss, overrides seek_percentage if set) */ overlay_film_strip: cint; //* default = 0 */ workaround_bugs: cint; //* default = 0 */ thumbnail_image_quality: cint; //* default = 8 (0 is bad, 10 is best)*/ thumbnail_image_type: ThumbnailerImageType; //* default = Png */ av_format_context: pointer; //* default = NULL */ maintain_aspect_ratio: cint; //* default = 1 */ thumbnailer: pointer; //* for internal use only */ filter: pointer; //* for internal use only */ end; Pimage_data = ^Timage_data; Timage_data = record image_data_ptr: pcuint8; //* points to the image data after call to generate_thumbnail_to_buffer */ image_data_size: cint; //* contains the size of the image data after call to generate_thumbnail_to_buffer */ internal_data: pointer; //* for internal use only */ end; var { create video_thumbnailer structure } video_thumbnailer_create: function(): Pvideo_thumbnailer; cdecl; { destroy video_thumbnailer structure } video_thumbnailer_destroy: procedure(thumbnailer: Pvideo_thumbnailer); cdecl; { create image_data structure } video_thumbnailer_create_image_data: function(): Pimage_data; cdecl; { destroy image_data structure } video_thumbnailer_destroy_image_data: procedure(data: Pimage_data); cdecl; { generate thumbnail from video file (movie_filename), image data is stored in generated_image_data struct } video_thumbnailer_generate_thumbnail_to_buffer: function(thumbnailer: Pvideo_thumbnailer; movie_filename: Pchar; generated_image_data: Pimage_data): cint; cdecl; var MaskList: TMaskList = nil; libffmpeg: TLibHandle = NilHandle; function GetThumbnail(const aFileName: String; aSize: TSize): Graphics.TBitmap; var Data: Pimage_data; BlobStream: TBlobStream; Thumb: Pvideo_thumbnailer; Bitmap: TPortableNetworkGraphic; begin Result:= nil; if MaskList.Matches(aFileName) then begin Thumb:= video_thumbnailer_create(); if Assigned(Thumb) then try Thumb.thumbnail_size:= aSize.cx; Data:= video_thumbnailer_create_image_data(); if Assigned(Data) then try if video_thumbnailer_generate_thumbnail_to_buffer(Thumb, PAnsiChar(CeUtf8ToSys(aFileName)), Data) = 0 then begin Bitmap:= TPortableNetworkGraphic.Create; BlobStream:= TBlobStream.Create(Data^.image_data_ptr, Data^.image_data_size); try Bitmap.LoadFromStream(BlobStream); Result:= Graphics.TBitmap.Create; BitmapAssign(Result, Bitmap); except FreeAndNil(Result); end; Bitmap.Free; BlobStream.Free; end; finally video_thumbnailer_destroy_image_data(Data); end; finally video_thumbnailer_destroy(Thumb); end; end; end; procedure Initialize; begin libffmpeg:= LoadLibrary('libffmpegthumbnailer.so.4'); if (libffmpeg <> NilHandle) then try @video_thumbnailer_create:= SafeGetProcAddress(libffmpeg, 'video_thumbnailer_create'); @video_thumbnailer_destroy:= SafeGetProcAddress(libffmpeg, 'video_thumbnailer_destroy'); @video_thumbnailer_create_image_data:= SafeGetProcAddress(libffmpeg, 'video_thumbnailer_create_image_data'); @video_thumbnailer_destroy_image_data:= SafeGetProcAddress(libffmpeg, 'video_thumbnailer_destroy_image_data'); @video_thumbnailer_generate_thumbnail_to_buffer:= SafeGetProcAddress(libffmpeg, 'video_thumbnailer_generate_thumbnail_to_buffer'); // Register thumbnail provider TThumbnailManager.RegisterProvider(@GetThumbnail); MaskList:= TMaskList.Create('*.avi;*.flv;*.mkv;*.mp4;*.mpg;*.mov;*.wmv;*.vob;*.mpeg'); except // Skip end; end; procedure Finalize; begin MaskList.Free; if (libffmpeg <> NilHandle) then FreeLibrary(libffmpeg); end; initialization Initialize; finalization Finalize; end.
{ ******************************************************************************* Copyright (c) 2004-2010 by Edyard Tolmachev IMadering project http://imadering.com ICQ: 118648 E-mail: imadering@mail.ru ******************************************************************************* } unit HistoryUnit; interface {$REGION 'Uses'} uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Htmlview, ExtCtrls, Buttons, Menus, ExtDlgs, JvSimpleXml; type THistoryForm = class(TForm) TopPanel: TPanel; BottomPanel: TPanel; HTMLHistoryViewer: THTMLViewer; ContactsComboBox: TComboBox; ArhiveComboBox: TComboBox; Bevel1: TBevel; ContactsLabel: TLabel; ArhiveLabel: TLabel; SearchTextLabel: TLabel; SearchTextEdit: TEdit; SearchTextBitBtn: TBitBtn; RegistrCheckBox: TCheckBox; FullSearchTextCheckBox: TCheckBox; ReloadHistoryBitBtn: TBitBtn; SaveHistoryAsBitBtn: TBitBtn; DeleteHistoryBitBtn: TBitBtn; HistoryPopupMenu: TPopupMenu; CopyHistorySelText: TMenuItem; CopyAllHistoryText: TMenuItem; UpSearchCheckBox: TRadioButton; DownSearchCheckBox: TRadioButton; CloseBitBtn: TBitBtn; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure HistoryPopupMenuPopup(Sender: TObject); procedure HTMLHistoryViewerKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure SearchTextBitBtnClick(Sender: TObject); procedure ReloadHistoryBitBtnClick(Sender: TObject); procedure SaveHistoryAsBitBtnClick(Sender: TObject); procedure DeleteHistoryBitBtnClick(Sender: TObject); procedure ContactsComboBoxChange(Sender: TObject); procedure CopyHistorySelTextClick(Sender: TObject); procedure CopyAllHistoryTextClick(Sender: TObject); procedure CloseBitBtnClick(Sender: TObject); procedure FormDblClick(Sender: TObject); procedure HTMLHistoryViewerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure HTMLHistoryViewerHotSpotClick(Sender: TObject; const SRC: string; var Handled: Boolean); private { Private declarations } HTMLStyle: string; MyHUIN: string; HistoryFile: string; public { Public declarations } ReqHUIN: string; ReqCType: string; procedure TranslateForm; procedure LoadHistoryFromFile; end; {$ENDREGION} var HistoryForm: THistoryForm; implementation {$R *.dfm} {$REGION 'MyUses'} uses MainUnit, ChatUnit, UtilsUnit, VarsUnit, IcqProtoUnit, MraProtoUnit, JabberProtoUnit; {$ENDREGION} {$REGION 'MyConst'} const C_HistoryForm = 'history_form'; {$ENDREGION} {$REGION 'LoadHistoryFromFile'} procedure THistoryForm.LoadHistoryFromFile; var Doc, H: string; begin ContactsComboBox.OnChange := nil; // Вычисляем нашу текущую учётную запись if ReqCType = C_Icq then MyHUIN := ICQ_LoginUIN else if ReqCType = C_Mra then MyHUIN := Mra_LoginUIN else if ReqCType = C_Jabber then MyHUIN := Jabber_LoginUIN; // --Очистили компонент истории и выводим надпись, что история загружается Doc := HTMLStyle; Doc := Doc + '<span class=b>' + Lang_Vars[116].L_S + '</span>'; LoadHTMLStrings(HTMLHistoryViewer, Doc); HTMLHistoryViewer.Refresh; // Загружаем файл истории сообщений HistoryFile := V_ProfilePath + C_HistoryFolder + ReqCType + C_BN + MyHUIN + C_BN + ReqHUIN + '.htm'; if FileExists(HistoryFile) then begin // Находим этот контакт в списке файлов историй H := GetFileName(HistoryFile); H := Copy(H, 1, Length(H) - 4); ContactsComboBox.ItemIndex := ContactsComboBox.Items.IndexOf(H); // Ичищаем компонент просмотра истории HTMLHistoryViewer.Clear; // Добавляем стили Doc := HTMLStyle; // Загружаем весь текст истории Doc := Doc + ReadFromFile(HistoryFile, true); // Применяем смайлы if not V_TextSmilies then CheckMessage_Smilies(Doc); // Отображаем историю в компоненте SetLength(Doc, Length(Doc) - 6); LoadHTMLStrings(HTMLHistoryViewer, Doc); // Ставим каретку в самый низ текста HTMLHistoryViewer.VScrollBarPosition := HTMLHistoryViewer.VScrollBar.Max; HTMLHistoryViewer.CaretPos := Length(HTMLHistoryViewer.DocumentSource); end else begin ContactsComboBox.ItemIndex := -1; // Очистили компонент истории и выводим сообщение, что история не найдена HTMLHistoryViewer.Clear; Doc := HTMLStyle; Doc := Doc + '<span class=d>' + Lang_Vars[109].L_S + '</span>'; LoadHTMLStrings(HTMLHistoryViewer, Doc); end; // Ищем архивы истории с этим контактом ArhiveComboBox.Clear; if ContactsComboBox.Text <> EmptyStr then ListFileInDir(V_ProfilePath + C_HistoryFolder + ContactsComboBox.Text + '*.7z', '.7z', ArhiveComboBox.Items); ContactsComboBox.OnChange := ContactsComboBoxChange; end; {$ENDREGION} {$REGION 'TranslateForm'} procedure THistoryForm.TranslateForm; begin // Создаём шаблон для перевода // CreateLang(Self); // Применяем язык SetLang(Self); // Другое CloseBitBtn.Caption := Lang_Vars[8].L_S; end; {$ENDREGION} {$REGION 'Other'} procedure THistoryForm.CopyHistorySelTextClick(Sender: TObject); begin // Копируем выделенный текст в буфер обмена HTMLHistoryViewer.CopyToClipboard; end; procedure THistoryForm.CopyAllHistoryTextClick(Sender: TObject); begin // Копируем весь текст в буфер обмена HTMLHistoryViewer.SelectAll; HTMLHistoryViewer.CopyToClipboard; end; procedure THistoryForm.HistoryPopupMenuPopup(Sender: TObject); begin // Определяем есть ли выделенный текст if HTMLHistoryViewer.SelLength = 0 then CopyHistorySelText.Enabled := False else CopyHistorySelText.Enabled := True; end; procedure THistoryForm.SearchTextBitBtnClick(Sender: TObject); begin // Снимаем предыдущее выделение текста HTMLHistoryViewer.SelLength := 0; // Делаем поиск текста в истории if not HTMLHistoryViewer.FindEx(SearchTextEdit.Text, RegistrCheckBox.Checked, UpSearchCheckBox.Checked) then MessageBox(Handle, PChar(Lang_Vars[26].L_S), PChar(Application.Title), MB_OK or MB_ICONINFORMATION); end; procedure THistoryForm.ReloadHistoryBitBtnClick(Sender: TObject); begin // Если путь к файлу пустой, то выходим if ContactsComboBox.Text = EmptyStr then Exit; // Перезагружаем файл истории ContactsComboBoxChange(nil); end; {$ENDREGION} {$REGION 'SaveHistoryAsBitBtnClick'} procedure THistoryForm.SaveHistoryAsBitBtnClick(Sender: TObject); var List: TStringList; begin // Если путь к файлу пустой, то выходим if ContactsComboBox.Text = EmptyStr then Exit; // Указываем начальное имя файла MainForm.SaveTextAsFileDialog.FileName := 'History ' + ContactsComboBox.Text; MainForm.SaveTextAsFileDialog.FilterIndex := 1; // Открываем диалог сохранения файла if MainForm.SaveTextAsFileDialog.Execute then begin // Создаём лист строк List := TStringList.Create; try // Выделяем весь текст в истории HTMLHistoryViewer.SelectAll; // Копируем выделенный текст в лист List.Text := HTMLHistoryViewer.SelText; // Сбрасываем выделение текста HTMLHistoryViewer.SelLength := 0; // Сохраняем текст из листа в файл из диалога List.SaveToFile(MainForm.SaveTextAsFileDialog.FileName, TEncoding.Unicode); finally List.Free; end; end; end; {$ENDREGION} {$REGION 'DeleteHistoryBitBtnClick'} procedure THistoryForm.DeleteHistoryBitBtnClick(Sender: TObject); var I: Integer; begin // Если путь к файлу пустой, то выходим if ContactsComboBox.Text = EmptyStr then Exit; // Выводим запрос на удаление файла истории I := MessageBox(Handle, PChar(Lang_Vars[44].L_S), PChar(Lang_Vars[19].L_S), MB_TOPMOST or MB_YESNO or MB_ICONQUESTION); // Если ответ положительный if I = IDYES then begin // Удаляем файл if FileExists(HistoryFile) then DeleteFile(HistoryFile); // Очищаем компонент истории HTMLHistoryViewer.Clear; // Удаляем эту запись из списка файлов истори ContactsComboBox.Items.Delete(ContactsComboBox.ItemIndex); end; end; {$ENDREGION} {$REGION 'ContactsComboBoxChange'} procedure THistoryForm.ContactsComboBoxChange(Sender: TObject); var Doc: string; begin // Загружаем файл с историей выбранного контакта // --Очистили компонент истории и выводим надпись, что история загружается Doc := HTMLStyle; Doc := Doc + '<span class=b>' + Lang_Vars[116].L_S + '</span>'; LoadHTMLStrings(HTMLHistoryViewer, Doc); HTMLHistoryViewer.Refresh; // Загружаем файл истории сообщений HistoryFile := V_ProfilePath + C_HistoryFolder + ContactsComboBox.Text + '.htm'; if FileExists(HistoryFile) then begin // Ичищаем компонент просмотра истории HTMLHistoryViewer.Clear; // Добавляем стили Doc := HTMLStyle; // Загружаем весь текст истории Doc := Doc + ReadFromFile(HistoryFile, true); // Применяем смайлы if not V_TextSmilies then CheckMessage_Smilies(Doc); // Отображаем историю в компоненте SetLength(Doc, Length(Doc) - 6); Doc := Doc + '<HR>'; LoadHTMLStrings(HTMLHistoryViewer, Doc); // Ставим каретку в самый низ текста HTMLHistoryViewer.VScrollBarPosition := HTMLHistoryViewer.VScrollBar.Max; HTMLHistoryViewer.CaretPos := Length(Doc); end; // Ищем архивы истории с этим контактом ArhiveComboBox.Clear; ListFileInDir(V_ProfilePath + C_HistoryFolder + ContactsComboBox.Text + '*.7z', '.7z', ArhiveComboBox.Items); // Ставим фокус в поле поиска текста if SearchTextEdit.CanFocus then SearchTextEdit.SetFocus; end; {$ENDREGION} {$REGION 'FormCreate'} procedure THistoryForm.FormCreate(Sender: TObject); var JvXML: TJvSimpleXml; XML_Node: TJvSimpleXmlElem; begin // Инициализируем XML JvXML_Create(JvXML); try with JvXML do begin // Загружаем настройки if FileExists(V_ProfilePath + C_SettingsFileName) then begin LoadFromFile(V_ProfilePath + C_SettingsFileName); // Загружаем позицию окна if Root <> nil then begin XML_Node := Root.Items.ItemNamed[C_HistoryForm]; if XML_Node <> nil then begin Top := XML_Node.Properties.IntValue('t'); Left := XML_Node.Properties.IntValue('l'); Height := XML_Node.Properties.IntValue('h'); Width := XML_Node.Properties.IntValue('w'); // Определяем не находится ли окно за пределами экрана FormSetInWorkArea(Self); end; end; end; end; finally JvXML.Free; end; // Переводим окно на другие языки TranslateForm; // Формируем строку стиля HTMLHistoryViewer.DoubleBuffered := True; HTMLStyle := '<html><head>' + V_ChatCSS + '<title>Chat</title></head><body>'; // Назначаем иконки окну и кнопкам MainForm.AllImageList.GetIcon(147, Icon); MainForm.AllImageList.GetBitmap(221, SearchTextBitBtn.Glyph); MainForm.AllImageList.GetBitmap(6, ReloadHistoryBitBtn.Glyph); MainForm.AllImageList.GetBitmap(225, SaveHistoryAsBitBtn.Glyph); MainForm.AllImageList.GetBitmap(148, DeleteHistoryBitBtn.Glyph); MainForm.AllImageList.GetBitmap(3, CloseBitBtn.Glyph); // Создаём список имеющихся файлов истории для выбора ListFileInDir(V_ProfilePath + C_HistoryFolder + '*.htm', '.htm', ContactsComboBox.Items); // Делаем окно независимым и ставим его кнопку в панель задач SetWindowLong(Handle, GWL_HWNDPARENT, 0); SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or WS_EX_APPWINDOW); // Назначаем событие выбора файла истории ContactsComboBox.OnChange := ContactsComboBoxChange; end; {$ENDREGION} {$REGION 'FormDestroy'} procedure THistoryForm.FormDestroy(Sender: TObject); var JvXML: TJvSimpleXml; XML_Node: TJvSimpleXmlElem; begin // Создаём необходимые папки ForceDirectories(V_ProfilePath); // Сохраняем настройки положения окна истории в xml // Инициализируем XML JvXML_Create(JvXML); try with JvXML do begin if FileExists(V_ProfilePath + C_SettingsFileName) then LoadFromFile(V_ProfilePath + C_SettingsFileName); if Root <> nil then begin // Очищаем раздел формы истории если он есть XML_Node := Root.Items.ItemNamed[C_HistoryForm]; if XML_Node <> nil then XML_Node.Clear else XML_Node := Root.Items.Add(C_HistoryForm); // Сохраняем позицию окна XML_Node.Properties.Add('t', Top); XML_Node.Properties.Add('l', Left); XML_Node.Properties.Add('h', Height); XML_Node.Properties.Add('w', Width); // Записываем сам файл SaveToFile(V_ProfilePath + C_SettingsFileName); end; end; finally JvXML.Free; end; end; {$ENDREGION} {$REGION 'Other'} procedure THistoryForm.CloseBitBtnClick(Sender: TObject); begin // Закрываем окно с историей Close; end; procedure THistoryForm.FormClose(Sender: TObject; var Action: TCloseAction); begin // Закрываем подсказки CloseSmiliesHint; // Указываем, что окно после закрытия уничтожится Action := CaFree; HistoryForm := nil; end; procedure THistoryForm.FormDblClick(Sender: TObject); begin // Устанавливаем перевод TranslateForm; end; procedure THistoryForm.HTMLHistoryViewerHotSpotClick(Sender: TObject; const SRC: string; var Handled: Boolean); begin // Отключаем реакции Handled := True; // Открываем ссылку из чата во внешнем браузере OpenURL(SRC); end; procedure THistoryForm.HTMLHistoryViewerKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin // При нажатии клавиш контрл + с копируем выделенный текст в буфер обмена if (GetKeyState(VK_CONTROL) < 0) and (Key = 67) then begin HTMLHistoryViewer.CopyToClipboard; end; end; procedure THistoryForm.HTMLHistoryViewerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var TitleStr: string; begin // При движениях мыши определяем всплывание подсказок if (not MainForm.JvTimerList.Events[14].Enabled) and (Assigned(ActiveControl)) then begin if ActiveControl.Focused then begin // Запоминаем вызывающий компонент и атрибут SH_HTMLViewer := HTMLHistoryViewer; TitleStr := HTMLHistoryViewer.TitleAttr; // Проверяем содержимое атрибута if TitleStr = EmptyStr then SH_OldTitle := EmptyStr else if TitleStr <> SH_OldTitle then begin SH_TimerCount := 0; // Запускаем таймер показа подсказки с атрибутом MainForm.JvTimerList.Events[14].Enabled := True; SH_OldTitle := TitleStr; end; end; end; end; {$ENDREGION} end.
unit uTypes; interface uses CommonTypes, Classes, cxGridDBBandedTableView; type TSearchThreadStatus = record TotalPages : Integer; LoadedPages : Integer; TotalItems : Integer; LoadedItems : Integer; SavedItems : Integer; CurrentCategory : Integer; TotalCategories : Integer; ThreadID : Integer; Operation : string; end; TSearchProperties = record rGlobalID : string; rCategoryID : string; rBuyerPostalCode : string; rKeyWords : string; rDescriptionSearch : Boolean; rCondition : string; rSearchID : Integer; rLocatedIn : string; rAvailableto : string; rSeller : string; rExcludeSeller : string; rListingType : string; rPriceFrom : Real; rPriceTo : Real; rPriceCurrency : string; rFeedbackScoreMax : Integer; rFeedbackScoreMin : Integer; rBidsMax : Integer; rBidsMin : Integer; rQuantityMax : Integer; rQuantityMin : Integer; rEndTimeFrom : TDateTime; rEndTimeTo : TDateTime; rMaxDistance : Integer; rLocalSearchOnly : Boolean; rPaymentMethod : string; rSellerBusinessType : string; rCurrency : string; rHideDuplicates : Boolean; rSortOrder : string; end; TDownloadImageThreadStatus = record TotalItems : Integer; SavedPhotos : Integer end; TItemDetails = record ItemID : string; ItemTitle : string; URL : string; Price : Real; PriceCurrency : string; BuyItNowPrice : Real; BuyItNowCurrency : string; SellerID : string; ItemLocation : string; country : string; ShippingCost : Real; ShippingCostCurrency : string; GalleryURL : string; PictureURL : string; StartTime : TDateTime; EndTime : TDateTime; ListingType : string; SearchID : Integer; Updated : TDateTime; CategoryID : string; categoryName : string; Description : string; globalId : string; PaymentMethods : string; BidCount : Integer; ListingStatus : string; QuantitySold : Integer; ReserveMet : Boolean; ShipToLocations : string; end; TAspect = record AspectValName : string; Aspectcnt : Integer; end; TCategoryHistogram = record CategoryName : string; CategoryID : Integer; Count : Integer; end; TCategoryHistogramArray = array of TCategoryHistogram; TAspectArray = array of TAspect; ListingTypes =(AdFormat, Auction, AuctionWithBIN, Classified, FixedPrice, StoreInventory, All); Tinisettings = record // database DataPath : string; // sheduling autorun : Boolean; checkregular : Boolean; Checkperiod : Integer; //autorunsearch : Boolean; runminimized : Boolean; // ebay AppID : string; DevID : string; CertID : string; Token : string; timeshiftebay : TDateTime; DecimalSeparator : Char; CSVSeparator : Char; ShowLatsResults : Integer; NotOlder : Integer; ClearData : Boolean; xmloutput : Boolean; logfolder : string; dblogfilename : string; end; TCatRec = record CategoryID : Integer; CategoryLevel : Integer; CategoryName: string; CategoryParentID : Integer; LeafCategory : Boolean; SavedCategoriesCnt : Integer; CatCount : Integer; FGlobalSiteID : Global_ID; end; MFOperations = (opIdle,opCheckCategories,opIdleCat,opSearching,opDowloadImages,opDownloadItemsDetails,opDownloadCategories,opSaveCategories,opLoadAspects); implementation end.
unit BitStrmr; interface uses FIFOIntf; const BufferBits = 32; type TBitStreamer = class public constructor Create; destructor Destroy; override; public procedure Reset; public procedure Read(out Data; Bits : integer); procedure Write(const Data; Bits : integer); private fFIFO : IFIFO; procedure SetFIFO(const aFIFO : IFIFO); public property FIFO : IFIFO read fFIFO write SetFIFO; private fAcc : array[0..pred(BufferBits div 8)] of byte; fPos : integer; end; implementation uses SysUtils, Math; procedure moveBits(const From; FromPos : integer; var Dest; DestPos, Bits : integer); function SignShift(x, y : integer) : byte; begin if y >= 0 then Result := x shl y else Result := x shr -y; end; const Align = 8; var bFrom : TByteArray absolute From; bDest : TByteArray absolute Dest; byFrom : integer; biFrom : integer; biCount : integer; biMove : integer; byTo : integer; biTo : integer; bimFrom : integer; bimTo : integer; mFrom : byte; mTo : byte; mCount : byte; begin byFrom := FromPos div Align; biFrom := FromPos - byFrom * Align; byTo := DestPos div Align; biTo := DestPos - byTo * Align; biCount := Bits; while biCount > 0 do begin bimFrom := min(biCount, Align - biFrom); bimTo := min(biCount, Align - biTo); biMove := min(bimFrom, bimTo); mCount := 255 and pred(1 shl biMove); // Generate biMove "1"s // Make a mask with biFrom and biMove mFrom := mCount shl biFrom; // Make a mask with biTo and biMove mTo := not(mCount shl biTo); bDest[byTo] := bDest[byTo] and mTo or SignShift(bFrom[byFrom] and mFrom, biTo - biFrom); dec(biCount, biMove); inc(biFrom, biMove); if biFrom >= Align then begin biFrom := 0; inc(byFrom); end; inc(biTo, biMove); if biTo >= Align then begin biTo := 0; inc(byTo); end; end; end; constructor TBitStreamer.Create; begin inherited; Reset; end; destructor TBitStreamer.Destroy; begin fFIFO := nil; inherited; end; procedure TBitStreamer.Reset; begin fillchar(fAcc, sizeof(fAcc), 0); fPos := 0; end; procedure TBitStreamer.Read(out Data; Bits : integer); var Actual : integer; DataLeft : integer; ToCopy : integer; begin Assert(Bits <= BufferBits); DataLeft := Bits; while DataLeft > 0 do begin if fPos = 0 then fFIFO.Read(fAcc, sizeof(fAcc), Actual); ToCopy := Min(DataLeft, BufferBits - fPos); moveBits(fAcc, fPos, Data, Bits - DataLeft, ToCopy); dec(DataLeft, ToCopy); inc(fPos, ToCopy); if fPos = BufferBits then fPos := 0; end; end; procedure TBitStreamer.Write(const Data; Bits : integer); var DataLeft : integer; ToCopy : integer; begin Assert(Bits <= BufferBits); DataLeft := Bits; while DataLeft > 0 do begin if fPos = BufferBits then begin fFIFO.Write(fAcc, sizeof(fAcc)); fPos := 0; end; ToCopy := Min(DataLeft, BufferBits - fPos); moveBits(Data, Bits - DataLeft, fAcc, fPos, ToCopy); dec(DataLeft, ToCopy); inc(fPos, ToCopy); end; end; procedure TBitStreamer.SetFIFO(const aFIFO : IFIFO); begin fFIFO := aFIFO; Reset; end; end.
unit sdlticks; { $Id: sdlticks.pas,v 1.2 2006/11/08 08:22:48 savage Exp $ } {******************************************************************************} { } { JEDI-SDL : Pascal units for SDL - Simple DirectMedia Layer } { SDL GetTicks Class Wrapper } { } { } { The initial developer of this Pascal code was : } { Dominique Louis <Dominique@SavageSoftware.com.au> } { } { Portions created by Dominique Louis are } { Copyright (C) 2004 - 2100 Dominique Louis. } { } { } { Contributor(s) } { -------------- } { Dominique Louis <Dominique@SavageSoftware.com.au> } { } { Obtained through: } { Joint Endeavour of Delphi Innovators ( Project JEDI ) } { } { You may retrieve the latest version of this file at the Project } { JEDI home page, located at http://delphi-jedi.org } { } { The contents of this file are used with permission, subject to } { the Mozilla Public License Version 1.1 (the "License"); you may } { not use this file except in compliance with the License. You may } { obtain a copy of the License at } { http://www.mozilla.org/MPL/MPL-1.1.html } { } { Software distributed under the License is distributed on an } { "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or } { implied. See the License for the specific language governing } { rights and limitations under the License. } { } { Description } { ----------- } { SDL Window Wrapper } { } { } { Requires } { -------- } { SDL.dll on Windows platforms } { libSDL-1.1.so.0 on Linux platform } { } { Programming Notes } { ----------------- } { } { } { } { } { Revision History } { ---------------- } { } { September 23 2004 - DL : Initial Creation } { $Log: sdlticks.pas,v $ Revision 1.2 2006/11/08 08:22:48 savage updates tp sdlgameinterface and sdlticks functions. Revision 1.1 2004/09/30 22:35:47 savage Changes, enhancements and additions as required to get SoAoS working. } {******************************************************************************} interface uses sdl; type TSDLTicks = class private FStartTime : UInt32; FTicksPerSecond : UInt32; FElapsedLastTime : UInt32; FFPSLastTime : UInt32; FLockFPSLastTime : UInt32; public constructor Create; destructor Destroy; override; // destructor {***************************************************************************** Init If the hi-res timer is present, the tick rate is stored and the function returns true. Otherwise, the function returns false, and the timer should not be used. *****************************************************************************} function Init : boolean; {*************************************************************************** GetGetElapsedSeconds Returns the Elapsed time, since the function was last called. ***************************************************************************} function GetElapsedSeconds : Single; {*************************************************************************** GetFPS Returns the average frames per second. If this is not called every frame, the client should track the number of frames itself, and reset the value after this is called. ***************************************************************************} function GetFPS : single; {*************************************************************************** LockFPS Used to lock the frame rate to a set amount. This will block until enough time has passed to ensure that the fps won't go over the requested amount. Note that this can only keep the fps from going above the specified level; it can still drop below it. It is assumed that if used, this function will be called every frame. The value returned is the instantaneous fps, which will be less than or equal to the targetFPS. ***************************************************************************} procedure LockFPS( targetFPS : Byte ); end; implementation { TSDLTicks } constructor TSDLTicks.Create; begin inherited; FTicksPerSecond := 1000; end; destructor TSDLTicks.Destroy; begin inherited; end; function TSDLTicks.GetElapsedSeconds : Single; var currentTime : Cardinal; begin currentTime := SDL_GetTicks; result := ( currentTime - FElapsedLastTime ) / FTicksPerSecond; // reset the timer FElapsedLastTime := currentTime; end; function TSDLTicks.GetFPS : Single; var currentTime, FrameTime : UInt32; fps : single; begin currentTime := SDL_GetTicks; FrameTime := ( currentTime - FFPSLastTime ); if FrameTime = 0 then FrameTime := 1; fps := FTicksPerSecond / FrameTime; // reset the timer FFPSLastTime := currentTime; result := fps; end; function TSDLTicks.Init : boolean; begin FStartTime := SDL_GetTicks; FElapsedLastTime := FStartTime; FFPSLastTime := FStartTime; FLockFPSLastTime := FStartTime; result := true; end; procedure TSDLTicks.LockFPS( targetFPS : Byte ); var currentTime : UInt32; targetTime : single; begin if ( targetFPS = 0 ) then targetFPS := 1; targetTime := FTicksPerSecond / targetFPS; // delay to maintain a constant frame rate repeat currentTime := SDL_GetTicks; until ( ( currentTime - FLockFPSLastTime ) > targetTime ); // reset the timer FLockFPSLastTime := currentTime; end; end.
{ Print a table of squares, cubes and fourth powers of integers. } program powerTable(input, output); var tableSize, base, square, cube, quad : integer; begin write('Enter table size: '); read(tableSize); for base := 1 to tableSize do begin square := sqr(base); cube := base * square; quad := sqr(square); writeln(base, square, cube, quad, 1/base, 1/square, 1/cube, 1/quad) end; end.
unit tabNamesMLS; interface function TranslateName(name : string) : string; implementation uses Classes, SysUtils, Literals; var Tabs : TStringList = nil; function TranslateName(name : string) : string; var aux : string; begin aux := UpperCase(Tabs.Values[name]); if aux <> '' then result := GetLiteral(aux) else result := name; end; procedure InitTabNames; begin Tabs := TStringList.Create; // Do not translate none of this strings, they are already in pepe's table Tabs.Add('CLIENTS=Literal461'); Tabs.Add('COMMERCE=Literal462'); Tabs.Add('GENERAL=Literal463'); Tabs.Add('HISTORY=Literal464'); Tabs.Add('JOBS=Literal465'); Tabs.Add('LOANS=Literal466'); Tabs.Add('MANAGEMENT=Literal467'); Tabs.Add('MINISTERIES=Literal468'); Tabs.Add('PRODUCTS=Literal469'); Tabs.Add('PUBLICITY=Literal470'); Tabs.Add('RESEARCHES=Literal471'); Tabs.Add('RESIDENTIALS=Literal472'); Tabs.Add('SERVICES=Literal473'); Tabs.Add('SUPPLIES=Literal474'); Tabs.Add('TAXES=Literal475'); Tabs.Add('MAUSOLEUM=Literal475'); Tabs.Add('TOWNS=Literal478'); Tabs.Add('FILMS=Literal479'); Tabs.Add('ANTENNAS=Literal480'); Tabs.Add('VOTES=Literal481'); Tabs.Add('WARES=Literal492'); end; initialization InitTabNames; finalization Tabs.Free; Tabs := nil; end.
unit uRelPedidoAcumuladoProd; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uModeloRel, ExtCtrls, JvExControls, JvNavigationPane, StdCtrls, Buttons, frxClass, frxDBSet, DB, ZAbstractRODataset, ZDataset, ZConnection, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, JvDBControls, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxImageComboBox, Mask, JvSpeedButton, JvExMask, JvToolEdit, frxExportPDF; type TfrmRelAcumProduto = class(TfrmModeloRel) qrAcumuladoP: TZReadOnlyQuery; frxDBAcumuladoP: TfrxDBDataset; frxAcumuladoP: TfrxReport; qrAcumuladoPnome_empresa: TStringField; qrAcumuladoPsite_empresa: TStringField; qrAcumuladoPtelefone_empresa: TStringField; qrAcumuladoPendereco_empresa: TStringField; qrAcumuladoPendereco_empresa2: TStringField; qrAcumuladoPid_venda: TLargeintField; qrAcumuladoPproduto_codigo: TStringField; qrAcumuladoPnome_produto: TStringField; qrAcumuladoPquantidade_total: TFloatField; qrAcumuladoPmedia: TFloatField; qrAcumuladoPunidade: TStringField; qrAcumuladoPcodigo_ncm: TStringField; qrAcumuladoPcodigo_ean: TStringField; qrAcumuladoPvalor_total: TFloatField; qrAcumuladoPminimo: TFloatField; qrAcumuladoPmaximo: TFloatField; qrAcumuladoPdesconto: TFloatField; Bevel2: TBevel; Label3: TLabel; Label1: TLabel; Label2: TLabel; Bevel3: TBevel; Label4: TLabel; Label5: TLabel; Label6: TLabel; d02: TJvDateEdit; d01: TJvDateEdit; d03: TJvDateEdit; d04: TJvDateEdit; Bevel4: TBevel; Label10: TLabel; Label9: TLabel; Bevel5: TBevel; Label11: TLabel; Label12: TLabel; Label13: TLabel; Label14: TLabel; Bevel6: TBevel; Label15: TLabel; Label16: TLabel; edCNPJ: TMaskEdit; cbStatus: TComboBox; cbPagamento: TcxImageComboBox; cbForma: TcxImageComboBox; cbVendedor: TcxImageComboBox; Bevel7: TBevel; Label17: TLabel; Label18: TLabel; cbOrdenacao: TComboBox; Bevel8: TBevel; Label19: TLabel; Label20: TLabel; edtProduto: TJvComboEdit; Label7: TLabel; Label8: TLabel; edtCliente: TJvDBComboEdit; edtFantasia: TJvDBComboEdit; Label21: TLabel; cbOperacao: TcxImageComboBox; Label22: TLabel; frxPDFExport1: TfrxPDFExport; cbData: TCheckBox; frxAcumuladoP_data: TfrxReport; qrAcumuladoPdata: TDateField; JvNavPanelHeader2: TJvNavPanelHeader; Bevel1: TBevel; procedure FormCreate(Sender: TObject); procedure JvSpeedButton1Click(Sender: TObject); procedure JvSpeedButton2Click(Sender: TObject); procedure btnImprimirClick(Sender: TObject); procedure edtProdutoButtonClick(Sender: TObject); procedure edtClienteButtonClick(Sender: TObject); procedure edtFantasiaButtonClick(Sender: TObject); procedure Label22MouseEnter(Sender: TObject); procedure Label22MouseLeave(Sender: TObject); procedure Label22Click(Sender: TObject); private { Private declarations } cliente, filial, produto: string; procedure ImprimeAcumulado; procedure ApagaCampos; public { Public declarations } end; var frmRelAcumProduto: TfrmRelAcumProduto; implementation uses funcoes, udmPrincipal, uConsulta_Padrao; {$R *.dfm} { TfrmRelAcumProduto } procedure TfrmRelAcumProduto.ImprimeAcumulado; begin try if (d01.Date = 0) and (d02.Date = 0) and (cliente = EmptyStr) and (filial = EmptyStr) and (d03.Date = 0) and (d04.Date = 0) and (edCNPJ.Text = EmptyStr) and (cbVendedor.ItemIndex < 0) and (edtProduto.Text = EmptyStr) then begin Application.MessageBox('Você deve selecionar algum tipo filtro', 'Atenção', MB_ICONERROR); Exit; end; qrAcumuladoP.Close; qrAcumuladoP.SQL.Clear; qrAcumuladoP.SQL.Add('select operacao,o.nome,'); qrAcumuladoP.SQL.Add('e.fantasia as nome_empresa, e.site as site_empresa, e.telefone as telefone_empresa,'); qrAcumuladoP.SQL.Add('concat(e.logradouro,", ",e.numero," ", ifnull(e.complemento,"")) as endereco_empresa,'); qrAcumuladoP.SQL.Add('concat(e.cidade, " - ", e.uf, " - ", e.cep) as endereco_empresa2,'); qrAcumuladoP.SQL.Add('vi.id_venda, vi.produto_codigo, p.nome as nome_produto,'); qrAcumuladoP.SQL.Add('p.codigo_ncm, p.codigo_ean,'); qrAcumuladoP.SQL.Add('sum(vi.quantidade) as quantidade_total,'); qrAcumuladoP.SQL.Add('(sum(vi.valor_total-if("S"=:pDesconto,vi.desconto_item,0))/sum(vi.quantidade)) as media,'); qrAcumuladoP.SQL.Add('sum(vi.valor_total-vi.desconto_item) as valor_total,'); qrAcumuladoP.SQL.Add('min(vi.valor_unitario) as minimo,'); qrAcumuladoP.SQL.Add('max(vi.valor_unitario) as maximo,'); qrAcumuladoP.SQL.Add('sum(vi.desconto_item) as desconto,'); qrAcumuladoP.SQL.Add('p.unidade,v.data'); qrAcumuladoP.SQL.Add('from vendas as v'); qrAcumuladoP.SQL.Add('left join vendas_itens as vi on vi.id_venda=v.id'); qrAcumuladoP.SQL.Add('left join produtos as p on p.codigo=vi.produto_codigo'); qrAcumuladoP.SQL.Add('left join empresas e on e.codigo=v.empresa_codigo'); qrAcumuladoP.SQL.Add('left join operacoes o on operacao=o.codigo'); qrAcumuladoP.SQL.Add('where v.empresa_codigo=:EmpresaLogada'); qrAcumuladoP.SQL.Add('and isnull(v.data_exc) and isnull(vi.data_exc)'); qrAcumuladoP.ParamByName('EmpresaLogada').AsInteger := dmPrincipal.empresa_login; if (d01.Date <> 0) and (d02.Date = 0) then begin qrAcumuladoP.SQL.add('and v.data=:data1'); qrAcumuladoP.ParamByName('data1').AsDate := d01.Date; end else if (d01.Date > 0) and (d02.Date > 0) then begin qrAcumuladoP.SQL.add('and v.data between :data1 and :data2'); qrAcumuladoP.ParamByName('data1').AsDate := d01.Date; qrAcumuladoP.ParamByName('data2').AsDate := d02.Date; end; if (d03.Date <> 0) and (d04.Date = 0) then begin qrAcumuladoP.SQL.add('and v.vencimento=:data3'); qrAcumuladoP.ParamByName('data3').AsDate := d03.Date; end else if (d03.Date > 0) and (d04.Date > 0) then begin qrAcumuladoP.SQL.add('and v.vencimento between :data3 and :data4'); qrAcumuladoP.ParamByName('data3').AsDate := d03.Date; qrAcumuladoP.ParamByName('data4').AsDate := d04.Date; end; if edtProduto.Text <> EmptyStr then begin qrAcumuladoP.SQL.add('and vi.produto_codigo=:pProduto'); qrAcumuladoP.ParamByName('pProduto').AsString := produto; ; end; if edCNPJ.Text <> EmptyStr then begin qrAcumuladoP.SQL.add('and left(replace(cf.cliente_cnpj,".",""),8)=:cnpj'); qrAcumuladoP.ParamByName('cnpj').AsString := Copy(edCNPJ.Text, 1, 8); end; if cliente <> '' then qrAcumuladoP.SQL.Add('and v.cliente_codigo=' + cliente); if filial <> '' then qrAcumuladoP.SQL.Add('and v.cliente_filial=' + filial); if cbPagamento.ItemIndex <> -1 then begin qrAcumuladoP.SQL.add('and v.meio_pagamento=:MeioPagamento'); qrAcumuladoP.ParamByName('MeioPagamento').AsInteger := cbPagamento.Properties.Items.Items[cbPagamento.ItemIndex].Value; end; if cbForma.ItemIndex <> -1 then begin qrAcumuladoP.SQL.add('and v.forma_pagamento=:FormaPagamento'); qrAcumuladoP.ParamByName('FormaPagamento').AsInteger := cbForma.Properties.Items.Items[cbForma.ItemIndex].Value; end; if cbVendedor.ItemIndex <> -1 then begin qrAcumuladoP.SQL.add('and v.vendedor=:Vendedor'); qrAcumuladoP.ParamByName('Vendedor').AsInteger := cbVendedor.Properties.Items.Items[cbVendedor.ItemIndex].Value; end; if cbOperacao.ItemIndex <> -1 then begin qrAcumuladoP.SQL.add('and v.operacao=:Operacao'); qrAcumuladoP.ParamByName('Operacao').AsInteger := cbOperacao.Properties.Items.Items[cbOperacao.ItemIndex].Value; end; case cbStatus.ItemIndex of 0: qrAcumuladoP.SQL.Add(''); 1: qrAcumuladoP.SQL.Add('and v.status in (0,1)'); 2: qrAcumuladoP.SQL.Add('and v.status=2'); end; if cbData.Checked then begin qrAcumuladoP.SQL.Add('group by v.data,vi.produto_codigo'); qrAcumuladoP.SQL.Add('order by v.data'); end else begin qrAcumuladoP.SQL.Add('group by vi.produto_codigo'); case cbOrdenacao.ItemIndex of 0: qrAcumuladoP.SQL.Add('order by vi.produto_codigo'); 1: qrAcumuladoP.SQL.Add('order by p.nome'); 2: qrAcumuladoP.SQL.Add('order by 11'); 3: qrAcumuladoP.SQL.Add('order by 13'); 4: qrAcumuladoP.SQL.Add('order by 14'); 5: qrAcumuladoP.SQL.Add('order by 15'); 6: qrAcumuladoP.SQL.Add('order by 12'); end; end; Wait('Carregando dados do relatório...', 1); qrAcumuladoP.Open; Wait(); if qrAcumuladoP.IsEmpty then begin Application.MessageBox('Não há dados para esse relatório!', 'Atenção', MB_ICONERROR); Exit; end else begin if cbData.Checked then frxAcumuladoP_data.ShowReport else frxAcumuladoP.ShowReport; end; finally qrAcumuladoP.Close; ApagaCampos; end; end; procedure TfrmRelAcumProduto.FormCreate(Sender: TObject); begin inherited; CarregaCombo(cbPagamento, 'select id,a.descricao from meio_pagamento a join meio_cobranca b on meio_cobranca=b.codigo where ativo="S" order by descricao'); CarregaCombo(cbForma, 'select id,descricao from forma_pagamento where ativo="S" order by descricao'); CarregaCombo(cbVendedor, 'select codigo, nome from vendedores where ativo="S" order by nome'); CarregaCombo(cbOperacao, 'select codigo, nome from operacoes where tipo="S" and ativo="S" order by nome'); cliente := ''; filial := ''; end; procedure TfrmRelAcumProduto.JvSpeedButton1Click(Sender: TObject); begin with TfrmConsulta_Padrao.Create(self) do begin with Query.SQL do begin Clear; Add('select nome Nome, codigo Código from clientes_fornecedores'); Add('where nome like :pFantasia and ativo="S"'); Add('group by codigo order by 1'); end; CampoLocate := 'nome'; Parametro := 'pFantasia'; ColunasGrid := 2; ShowModal; if Tag = 1 then begin edtCliente.Text := Query.Fields[0].Value; cliente := Query.Fields[1].Value; end; Free; end; end; procedure TfrmRelAcumProduto.JvSpeedButton2Click(Sender: TObject); begin with TfrmConsulta_Padrao.Create(self) do begin with Query.SQL do begin Clear; Add('select fantasia Fantasia, filial Filial, codigo Código from clientes_fornecedores'); Add('where fantasia like :pFantasia and ativo="S"'); if cliente <> '' then begin Add('and codigo=:pCodigo'); Query.ParamByName('pCodigo').Value := cliente; end; Add('order by 1'); end; CampoLocate := 'fantasia'; Parametro := 'pFantasia'; ColunasGrid := 2; ShowModal; if Tag = 1 then begin edtFantasia.Text := Query.Fields[0].Value; cliente := Query.Fields[2].Value; filial := Query.Fields[1].Value; end; Free; end; end; procedure TfrmRelAcumProduto.btnImprimirClick(Sender: TObject); begin inherited; ImprimeAcumulado; end; procedure TfrmRelAcumProduto.edtProdutoButtonClick(Sender: TObject); begin with TfrmConsulta_Padrao.Create(self) do begin with Query.SQL do begin Clear; Add('select codigo, nome from produtos'); Add('where nome like :pFantasia and ativo="S"'); Add('order by nome'); end; CampoLocate := 'nome'; Parametro := 'pFantasia'; ColunasGrid := 2; ShowModal; if Tag = 1 then begin produto := Query.Fields[0].Value; edtProduto.Text := Query.Fields[1].Value; end; Free; end; end; procedure TfrmRelAcumProduto.edtClienteButtonClick(Sender: TObject); begin inherited; with TfrmConsulta_Padrao.Create(self) do begin with Query.SQL do begin Clear; Add('select nome Nome, codigo Código from clientes_fornecedores'); Add('where nome like :pFantasia and ativo="S" and tipo_cadastro in ("C","A")'); Add('group by codigo order by 1'); end; CampoLocate := 'nome'; Parametro := 'pFantasia'; ColunasGrid := 2; ShowModal; if Tag = 1 then begin edtCliente.Text := Query.Fields[0].Value; cliente := Query.Fields[1].Value; end; Free; end; end; procedure TfrmRelAcumProduto.edtFantasiaButtonClick(Sender: TObject); begin inherited; with TfrmConsulta_Padrao.Create(self) do begin with Query.SQL do begin Clear; Add('select fantasia Fantasia, filial Filial, codigo Código from clientes_fornecedores'); Add('where fantasia like :pFantasia and ativo="S" and tipo_cadastro in ("C","A")'); if cliente <> '' then begin Add('and codigo=:pCodigo'); Query.ParamByName('pCodigo').Value := cliente; end; Add('order by 1'); end; CampoLocate := 'fantasia'; Parametro := 'pFantasia'; ColunasGrid := 2; ShowModal; if Tag = 1 then begin edtFantasia.Text := Query.Fields[0].Value; cliente := Query.Fields[2].Value; filial := Query.Fields[1].Value; end; Free; end; end; procedure TfrmRelAcumProduto.ApagaCampos; begin d01.Clear; d02.Clear; d03.Clear; d04.Clear; cbVendedor.ItemIndex := -1; cbPagamento.ItemIndex := -1; cbForma.ItemIndex := -1; cbOperacao.ItemIndex := -1; edtCliente.Clear; edtFantasia.Clear; cliente := ''; filial := ''; edCNPJ.Clear; edtProduto.Clear; end; procedure TfrmRelAcumProduto.Label22MouseEnter(Sender: TObject); begin inherited; (Sender as TLabel).Font.Style := [fsBold]; end; procedure TfrmRelAcumProduto.Label22MouseLeave(Sender: TObject); begin inherited; (Sender as TLabel).Font.Style := []; end; procedure TfrmRelAcumProduto.Label22Click(Sender: TObject); begin inherited; ApagaCampos; end; end.
unit MyQueue; interface type Queue = class //private queue:array[,] of integer; length:integer; //public constructor Create(); procedure Push(x:integer; y:integer); procedure Unshift(x:integer; y:integer); function Pop():array of integer; function Shift():array of integer; end; implementation // Constructor constructor Queue.Create(); begin SetLength(queue, 0, 2); length := 0; end; // Procedures procedure Queue.Push(x:integer; y:integer); begin length := length + 1; SetLength(queue, length, 2); queue[length - 1, 0] := x; queue[length - 1, 1] := y; end; procedure Queue.Unshift(x:integer; y:integer); begin length := length + 1; SetLength(queue, length, 2); for var i := length - 1 downto 1 do begin queue[i, 0] := queue[i - 1, 0]; queue[i, 1] := queue[i - 1, 1]; end; queue[0, 0] := x; queue[0, 1] := y; end; // Functions function Queue.Pop():array of integer; begin Result := new integer[2]; Result[0] := queue[length - 1, 0]; Result[1] := queue[length - 1, 1]; length := length - 1; SetLength(queue, length, 2); end; function Queue.Shift():array of integer; begin Result := new integer[2]; Result[0] := queue[0, 0]; Result[1] := queue[0, 1]; for var i := 0 to length - 2 do begin queue[i, 0] := queue[i + 1, 0]; queue[i, 1] := queue[i + 1, 1]; end; length := length - 1; SetLength(queue, length , 2); end; initialization end.
unit uPEN_AppMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uBaseCustom, uMainDataSet, Vcl.ExtCtrls, uPEN_PenezniPolozky_G, uPEN_Stavy_G; type TPEN_AppMain = class(TBaseCustom) pnlBase: TPanel; private FDataSetPenezniPolozky: TMainDataSet; FDataSetStavy: TMainDataSet; FPEN_PenezniPolozky_G: TPEN_PenezniPolozky_G; FPEN_Stavy_G: TPEN_Stavy_G; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var PEN_AppMain: TPEN_AppMain; implementation uses uDV_Stavy, uDV_PenezniPolozky; {$R *.dfm} { TPenezenka_AppMain } constructor TPEN_AppMain.Create(AOwner: TComponent); begin inherited; FDataSetPenezniPolozky := TDV_PenezniPolozky.CreateDV_PenezniPolozky(Self); FPEN_PenezniPolozky_G := TPEN_PenezniPolozky_G.Create(Self, FDataSetPenezniPolozky); FPEN_PenezniPolozky_G.ManualDock(pnlBase); FPEN_PenezniPolozky_G.Show; end; destructor TPEN_AppMain.Destroy; begin FreeAndNil(FPEN_PenezniPolozky_G); FreeAndNil(FDataSetPenezniPolozky); end; 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 ClpIFilterStream; {$I ..\Include\CryptoLib.inc} interface uses Classes; type IFilterStream = interface(IInterface) ['{00DF43F6-55BB-4A90-AEE7-1C6D956E144A}'] function QueryInterface({$IFDEF FPC}constref {$ELSE}const {$ENDIF FPC} IID: TGUID; out Obj): HResult; {$IF DEFINED(MSWINDOWS) OR DEFINED(DELPHI)} stdcall {$ELSE} cdecl {$IFEND}; function _AddRef: Integer; {$IF DEFINED(MSWINDOWS) OR DEFINED(DELPHI)} stdcall {$ELSE} cdecl {$IFEND}; function _Release: Integer; {$IF DEFINED(MSWINDOWS) OR DEFINED(DELPHI)} stdcall {$ELSE} cdecl {$IFEND}; function GetSize: Int64; function GetPosition: Int64; procedure SetPosition(const Value: Int64); property Size: Int64 read GetSize; property Position: Int64 read GetPosition write SetPosition; function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; function Read(var Buffer; Count: LongInt): LongInt; function Write(const Buffer; Count: LongInt): LongInt; function ReadByte(): Int32; procedure WriteByte(Value: Byte); end; implementation end.
unit eInterestSimulator.Model.Resultado.Factory; interface uses eInterestSimulator.Model.Interfaces, eInterestSimulator.Model.PagamentoUnico, eInterestSimulator.Model.PagamentoVariavel, eInterestSimulator.Model.Alemao, eInterestSimulator.Model.Americano, eInterestSimulator.Model.AmortizacaoMisto, eInterestSimulator.Model.Price; type TModelResultadoFactory = class(TInterfacedObject, iResultadoFactory) private function PagamentoUnico: iResultado; function PagamentoVariavel: iResultado; function Americano: iResultado; function AmortizacaoConstante: iResultado; function Price: iResultado; function AmortizacaoMisto: iResultado; function Alemao: iResultado; public constructor Create; destructor Destroy; override; class function New: iResultadoFactory; end; implementation uses eInterestSimulator.Model.AmortizacaoConstante; { TModelAmortizacaoFactory } function TModelResultadoFactory.Alemao: iResultado; begin Result := TModelAmortizacaoAlemao.Create; end; function TModelResultadoFactory.Americano: iResultado; begin Result := TModelAmortizacaoAmericano.Create; end; function TModelResultadoFactory.AmortizacaoConstante: iResultado; begin Result := TModelAmortizacaoAmortizacaoConstante.Create; end; function TModelResultadoFactory.AmortizacaoMisto: iResultado; begin Result := TModelAmortizacaoAmortizacaoMisto.Create; end; constructor TModelResultadoFactory.Create; begin end; destructor TModelResultadoFactory.Destroy; begin inherited; end; class function TModelResultadoFactory.New: iResultadoFactory; begin Result := Self.Create; end; function TModelResultadoFactory.PagamentoUnico: iResultado; begin Result := TModelAmortizacaoPagamentoUnico.Create; end; function TModelResultadoFactory.PagamentoVariavel: iResultado; begin Result := TModelAmortizacaoPagamentoVariavel.Create; end; function TModelResultadoFactory.Price: iResultado; begin Result := TModelAmortizacaoPrice.Create; end; end.
PROGRAM WriteSymbol(INPUT, OUTPUT); CONST Min = 0; Max = 25; TYPE Matrix = SET OF Min..Max; VAR ChReadable: CHAR; SetAvailable: Matrix; PROCEDURE Identification(VAR ChChecked: CHAR; VAR SetNull: Matrix); BEGIN{Identification} CASE ChChecked OF 'A': SetNull := [1, 6, 7, 11, 13, 16, 17, 18, 19, 21, 25]; 'B': SetNull := [1, 2, 3, 4, 6, 10, 11, 12, 13, 14, 16, 20, 21, 22, 23, 24]; 'C': SetNull := [2, 3, 4, 5, 6, 11, 16, 22, 23, 24, 25]; 'D': SetNull := [1, 2, 3, 4, 6, 10, 11, 15, 16, 20, 21, 22, 23, 24]; 'E': SetNull := [1, 2, 3, 4, 5, 6, 11, 12, 13, 14, 15, 16, 21, 22, 23, 24, 25]; 'F': SetNull := [1, 2, 3, 4, 5, 6, 11, 12, 13, 16, 21]; 'G': SetNull := [2, 3, 4, 6, 11, 13, 14, 15, 16, 20, 22, 23, 24]; 'H': SetNull := [1, 5, 6, 10, 11, 12, 13, 14, 15, 16, 20, 21, 25]; 'I': SetNull := [2, 3, 4, 8, 13, 18, 22, 23, 24]; 'J': SetNull := [1, 2, 3, 4, 5, 8, 13, 16, 18, 22]; 'K': SetNull := [1, 4, 6, 8, 11, 12, 16, 18, 21, 24]; 'L': SetNull := [1, 6, 11, 16, 21, 22, 23, 24, 25]; 'M': SetNull := [1, 5, 6, 7, 9, 10, 11, 13, 15, 16, 20, 21, 25]; 'N': SetNull := [1, 5, 6, 7, 10, 11, 13, 15, 16, 19, 20, 21, 25]; 'O': SetNull := [2, 3, 4, 6, 10, 11, 15, 16, 20, 22, 23, 24]; 'P': SetNull := [1, 2, 3, 6, 9, 11, 12, 13, 16, 21]; 'Q': SetNull := [2, 3, 4, 6, 10, 11, 15, 16, 19, 22, 23, 25]; 'R': SetNull := [1, 2, 6, 8, 11, 12, 16, 18, 21, 24]; 'S': SetNull := [2, 3, 4, 5, 6, 12, 13, 14, 20, 21, 22, 23, 24]; 'T': SetNull := [1, 2, 3, 4, 5, 8, 13, 18, 23]; 'U': SetNull := [1, 5, 6, 10, 11, 15, 16, 20, 22, 23, 24]; 'V': SetNull := [1, 5, 7, 9, 12, 14, 18]; 'W': SetNull := [1, 5, 6, 10, 11, 13, 15, 16, 18, 20, 22, 24]; 'X': SetNull := [1, 5, 7, 9, 13, 17, 19, 21, 25]; 'Y': SetNull := [1, 5, 7, 9, 13, 18, 23]; 'Z': SetNull := [1, 2, 3, 4, 5, 9, 13, 17, 21, 22, 23, 24, 25]; ELSE SetNull := []; END END;{Identification} PROCEDURE WriteX(VAR SetFin: Matrix); VAR Counter: INTEGER; BEGIN{WriteX} FOR Counter := Min TO MAX DO BEGIN IF (Counter IN SetFin) THEN WRITE('X') ELSE WRITE(' '); IF (COUNTER MOD 5 = 0) THEN WRITELN END END;{WriteX} BEGIN{WriteSymbol} IF NOT EOLN THEN BEGIN READ(INPUT, ChReadable); Identification(ChReadable, SetAvailable); IF (SetAvailable = []) THEN WRITELN('This sign is not recorded') ELSE WriteX(SetAvailable) END ELSE WRITELN('Input is empty') END.{WriteSymbol}
unit fpcorm_dbcore_types; {< @abstract(This unit contains all the super types, derived into the types written in the code generated by fpcORM.) @author(Andreas Lorenzen - aplorenzen@gmail.com) @created(2014-06-24) The classes in this unit, are intended to provide all the basic functionality for the final types that are genererated by the fpcORM. Types representing the database table and table fields are here, with functions that supplies all the fundamental functionality, of maintaining the state of the derived objects. } {$mode objfpc}{$H+} interface uses Classes, SysUtils, SyncObjs, SQLDB, FGL, DateUtils, fpcorm_common_interfaces, fpcorm_common_types, fpcorm_dbcore_utils, fpcorm_dbcore_constants; type { Forward declaration of the TfoDBTableObject class, the base type of the 'object that wraps a table'. } TfoDBTableObject = class; { This function type signature, takes no argument and returns a TfoDBTableObject. The intention is to make a list from this type, to hold in the TfoDBTableObject type, holding all the foreign key referenced table objects, in a list for use when inserting and updating. } TfoDBFKReferenceFunction = function(): TfoDBTableObject of object; { The TfoDBTableObjectList type, is used for holding a generic list of all the foreign key referenced objects that are referenced with a foreign key field from this table object. } TfoDBTableObjectList = specialize TFPGList<TfoDBTableObject>; generic TfoDBGenricTableObjectList<T> = class(TfoDBTableObjectList); { TODO -oAPL -cDBTypes 5: Comment these forward declarations. } TfoDBTableFieldByte = class; TfoDBTableFieldShortInt = class; TfoDBTableFieldSmallInt = class; TfoDBTableFieldWord = class; TfoDBTableFieldLongInt = class; TfoDBTableFieldLongWord = class; TfoDBTableFieldInt64 = class; TfoDBTableFieldQWord = class; TfoDBTableFieldBoolean = class; TfoDBTableFieldSingle = class; TfoDBTableFieldDouble = class; TfoDBTableFieldExtended = class; TfoDBTableFieldCurrency = class; TfoDBTableFieldString = class; TfoDBTableFieldDateTime = class; { This type represents a field in a table, a specific field in a specific row, but without it's value at this abstract level. All the other properties of the field are implemented at this level though. } TfoDBTableField = class(TfoObserverSubject) private fOwnerTable: TfoDBTableObject; fFieldName: String; fIsNull: Boolean; fIsChanged: Boolean; fIsIndexed: Boolean; fIsPrimaryKey: Boolean; fIsForeignKey: Boolean; fHasDefault: Boolean; fIsNullable: Boolean; { TODO -APL -cDBTypes 5: The field metadata should also be contained here, and created when the decendant is instanciated, or perhaps be an option } procedure SetIsNull(aIsNull: Boolean); procedure SetIsChanged(aIsChanged: Boolean); protected { Internal function, that removes any value in decending classes, eg. int = 0, string = '' } procedure ClearValue; virtual; abstract; public constructor Create(aOwnerTable: TfoDBTableObject; aFieldName: String = ''); destructor Destroy; override; function ToSql(): String; virtual; abstract; function ToXML(): String; virtual; abstract; function AsString(): String; virtual; abstract; procedure CopyValue(aTableField: TfoDBTableField); virtual; abstract; property OwnerTable: TfoDBTableObject read fOwnerTable; property FieldName: String read fFieldName write fFieldName; property IsNull: Boolean read fIsNull write SetIsNull; property IsChanged: Boolean read fIsChanged write SetIsChanged; property IsPrimaryKey: Boolean read fIsPrimaryKey write fIsPrimaryKey; property IsIndexed: Boolean read fIsIndexed write fIsIndexed; property IsForeignKey: Boolean read fIsForeignKey write fIsForeignKey; property HasDefault: Boolean read fHasDefault write fHasDefault; property IsNullable: Boolean read fIsNullable write fIsNullable; end; { This list type, is a specialization of a generic pointer list, by the TfoDBTableField type. Essentially this list type can contain a range of abstract database table fields, without access to their actual local values. However, the values a can be accessed in the ToSql, ToXML and AsString functions, in the TfoDBTableField, for passing it to the database, an XML document or to a GUI as a String f.ex. } TfoDBTableFieldList = specialize TFPGList<TfoDBTableField>; { TfoDBGenericTableField } generic TfoDBGenericTableField<T> = class(TfoDBTableField) private fValue: T; procedure SetValue(aValue: T); protected procedure ClearValue; override; public constructor Create(aOwnerTable: TfoDBTableObject; aFieldName: String = ''); destructor Destroy; override; procedure CopyValue(aTableField: TfoDBTableField); override; function ToSql(): String; override; function ToXML(): String; override; function AsString(): String; override; property Value: T read fValue write SetValue; end; { DONE -oAPL -cDBTypes 2: Clean up the TfoDBObjectStatus object - no need for all those messy setters and getters I think? } { The TfoDBTableStatus class, is the holder of the state of a single table row object. A TfoDBTableObject object, has an instance of this type inside of it, to track it's status. One particular reason for not putting all of the fields in this type, directly into the TfoDBTableObject type, is that when the TfoDBTableObject type is decended from, into a type representing a specific table in a specific database - with all of the autogenerated fields and their names, there could very well be conflifts between the names of the fields in this type, and in the generated subclass. That can be handled of course, and will be handled in the subclass fieldnaming logic, but it would mean that some fields will have one name in the database, and another in the generated type. Which is unwanted. } TfoDBTableStatus = class(TInterfacedPersistent) private fOwnerTable: TfoDBTableObject; fIsNew: Boolean; fIsLoaded: Boolean; fIsChanged: Boolean; fIsDeleted: Boolean; fCreatedTime: TDateTime; fLoadedTime: TDateTime; fChangedTime: TDateTime; fSavedTime: TDateTime; fDeletedTime: TDateTime; fIsInserting: Boolean; fIsDeleting: Boolean; fIsUpdating: Boolean; procedure SetIsNew(aIsNew: Boolean); procedure SetIsLoaded(aIsLoaded: Boolean); procedure SetIsChanged(aIsChanged: Boolean); procedure SetIsDeleted(aIsDeleted: Boolean); public constructor Create(aOwnerTable: TfoDBTableObject); destructor Destroy; override; property OwnerTable: TfoDBTableObject read fOwnerTable; property IsNew: Boolean read fIsNew write SetIsNew; property IsLoaded: Boolean read fIsLoaded write SetIsLoaded; property IsChanged: Boolean read fIsChanged write SetIsChanged; property IsDeleted: Boolean read fIsDeleted write SetIsDeleted; property CreatedTime: TDateTime read fCreatedTime write fCreatedTime; property LoadedTime: TDateTime read fLoadedTime write fLoadedTime; property ChangedTime: TDateTime read fChangedTime write fChangedTime; property SavedTime: TDateTime read fSavedTime write fSavedTime; property DeletedTime: TDateTime read fDeletedTime write fDeletedTime; property IsInserting: Boolean read fIsInserting write fIsInserting; property IsDeleting: Boolean read fIsDeleting write fIsDeleting; property IsUpdating: Boolean read fIsUpdating write fIsUpdating; end; { TfoDBTableInformation } TfoDBTableInformation = class(TInterfacedPersistent) private fTableCatalog: String; fTableSchema: String; fTableName: String; fTableType: String; { TODO -oAPL -cDBTypes 4: TfoDBTableInformation: More fields here, steal from dORM, list of PK items and FK items, indexed things and more } public constructor Create; destructor Destroy; override; { TODO -oAPL -cDBTypes 2: TfoDBTableInformation: Implement getters, setters and properties here } published property TableCatalog: String read fTableCatalog write fTableCatalog; property TableSchema: String read fTableSchema write fTableSchema; property TableName: String read fTableName write fTableName; property TableType: String read fTableType write fTableType; end; { The TfoDBTableObject object, represents a database table... more info here } { TfoDBTableObject } TfoDBTableObject = class(TfoObserver) private fConnection: TSQLConnector; fMutex: TCriticalSection; fTableInformation: TfoDBTableInformation; fObjectStatus: TfoDBTableStatus; fFieldList: TfoDBTableFieldList; fIsDestroying: Boolean; fOpenedConnection: Boolean; protected { The OpenConnection function provides the trivial means of opening the database connection to the decendant types. @return(True if the connection was opened successfully, False if connection could not be established.) } function OpenConnection: Boolean; { The CloseConnection function closes the local connection. Only if it is actually open and if the decending object also was the initiator of the connection. Making this distinction allows decendants to use the CloseConnection function anywhere in decendant types, where they may want to close the database connection, and only close it if that decendant object instance was the object that opened it. @return(False if unsuccessful and True if closed successfully). @param(aConsumeException indicates to the function, if any exception caused should be silenced, or re-raised to the caller.) } function CloseConnection(aConsumeException: Boolean = False): Boolean; public constructor Create(aConnection: TSQLConnector; aMutex: TCriticalSection); destructor Destroy; override; { AddTableField is intended to be called from the constructors of the fields that are owned by the decending object from this class. Upon creation, a new field (decending from TfoDBTableField) is passed it's owning table as a constructor parameter. The field should in turn then call it's owner's AddTableField procedure, to add itself to it's table's field collection. So that the table object has a complete list of all the fields that are contained in it. } procedure AddTableField(aTableField: TfoDBTableField); { This function } // procedure AddForeignKeyReferencedTableObject(aTableObject: TfoDBTableObject); function Load_OpenSQL(aSQL: String): Boolean; virtual; abstract; procedure ReceiveSubjectUpdate(aSubject: IfoObserverSubject); override; function InsertAsNew: Boolean; virtual; abstract; function Update: Boolean; virtual; abstract; // the LoadedOrNotNew function may not be nessecary, it was used to 'probe' if an instance was loaded, when using lazyloading // function LoadedOrNotNew(AFreeIfNot: Boolean = True): Boolean; property Connection: TSQLConnector read fConnection write fConnection; property TableInformation: TfoDBTableInformation read fTableInformation write fTableInformation; property Mutex: TCriticalSection read fMutex write fMutex; property ObjectStatus: TfoDBTableStatus read fObjectStatus write fObjectStatus; property FieldList: TfoDBTableFieldList read fFieldList write fFieldList; property IsDestroying: Boolean read fIsDestroying write fIsDestroying; property OpenedConnection: Boolean read fOpenedConnection; end; // integer types // http://www.freepascal.org/docs-html/ref/refsu5.html#x27-260003.1.1 // Type Range Size in bytes // Byte 0 .. 255 1 // Shortint -128 .. 127 1 // Smallint -32768 .. 32767 2 // Word 0 .. 65535 2 // Integer either smallint or longint size 2 or 4 // Cardinal longword 4 // Longint -2147483648 .. 2147483647 4 // Longword 0 .. 4294967295 4 // Int64 -9223372036854775808 .. 9223372036854775807 8 // QWord 0 .. 18446744073709551615 8 { TfoDBTableFieldByte } TfoDBTableFieldByte = class(specialize TfoDBGenericTableField<Byte>) public destructor Destroy; override; procedure ClearValue; override; function ToSql(): String; override; function ToXML(): String; override; function AsString(): String; override; procedure CopyValue(aTableField: TfoDBTableField); override; //function ValueEquals(aTableField: TfoDBTableFieldByte): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldShortInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSmallInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldInt64): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldQWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldBoolean): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSingle): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDouble): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldExtended): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldCurrency): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldString): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDateTime): Boolean; overload; end; { TfoDBTableFieldShortInt } TfoDBTableFieldShortInt = class(specialize TfoDBGenericTableField<ShortInt>) public destructor Destroy; override; procedure ClearValue; override; function ToSql(): String; override; function ToXML(): String; override; function AsString(): String; override; //procedure CopyValue(aTableField: TfoDBTableField); override; //function ValueEquals(aTableField: TfoDBTableFieldByte): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldShortInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSmallInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldInt64): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldQWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldBoolean): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSingle): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDouble): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldExtended): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldCurrency): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldString): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDateTime): Boolean; overload; end; { TfoDBTableFieldSmallInt } TfoDBTableFieldSmallInt = class(specialize TfoDBGenericTableField<SmallInt>) public destructor Destroy; override; procedure ClearValue; override; function ToSql(): String; override; function ToXML(): String; override; function AsString(): String; override; //procedure CopyValue(aTableField: TfoDBTableField); override; //function ValueEquals(aTableField: TfoDBTableFieldByte): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldShortInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSmallInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldInt64): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldQWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldBoolean): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSingle): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDouble): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldExtended): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldCurrency): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldString): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDateTime): Boolean; overload; end; { TfoDBTableFieldWord } TfoDBTableFieldWord = class(specialize TfoDBGenericTableField<Word>) public destructor Destroy; override; procedure ClearValue; override; function ToSql(): String; override; function ToXML(): String; override; function AsString(): String; override; //procedure CopyValue(aTableField: TfoDBTableField); override; //function ValueEquals(aTableField: TfoDBTableFieldByte): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldShortInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSmallInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldInt64): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldQWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldBoolean): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSingle): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDouble): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldExtended): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldCurrency): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldString): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDateTime): Boolean; overload; end; { TfoDBTableFieldLongInt } TfoDBTableFieldLongInt = class(specialize TfoDBGenericTableField<LongInt>) public destructor Destroy; override; procedure ClearValue; override; function ToSql(): String; override; function ToXML(): String; override; function AsString(): String; override; //procedure CopyValue(aTableField: TfoDBTableField); override; //function ValueEquals(aTableField: TfoDBTableFieldByte): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldShortInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSmallInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldInt64): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldQWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldBoolean): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSingle): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDouble): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldExtended): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldCurrency): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldString): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDateTime): Boolean; overload; end; { TfoDBTableFieldLongWord } TfoDBTableFieldLongWord = class(specialize TfoDBGenericTableField<LongWord>) public destructor Destroy; override; procedure ClearValue; override; function ToSql(): String; override; function ToXML(): String; override; function AsString(): String; override; //procedure CopyValue(aTableField: TfoDBTableField); override; //function ValueEquals(aTableField: TfoDBTableFieldByte): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldShortInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSmallInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldInt64): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldQWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldBoolean): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSingle): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDouble): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldExtended): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldCurrency): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldString): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDateTime): Boolean; overload; end; { TfoDBTableFieldInt64 } TfoDBTableFieldInt64 = class(specialize TfoDBGenericTableField<Int64>) public destructor Destroy; override; procedure ClearValue; override; function ToSql(): String; override; function ToXML(): String; override; function AsString(): String; override; //procedure CopyValue(aTableField: TfoDBTableField); override; //function ValueEquals(aTableField: TfoDBTableFieldByte): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldShortInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSmallInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldInt64): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldQWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldBoolean): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSingle): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDouble): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldExtended): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldCurrency): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldString): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDateTime): Boolean; overload; end; { TfoDBTableFieldQWord } TfoDBTableFieldQWord = class(specialize TfoDBGenericTableField<QWord>) public destructor Destroy; override; procedure ClearValue; override; function ToSql(): String; override; function ToXML(): String; override; function AsString(): String; override; //procedure CopyValue(aTableField: TfoDBTableField); override; //function ValueEquals(aTableField: TfoDBTableFieldByte): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldShortInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSmallInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldInt64): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldQWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldBoolean): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSingle): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDouble): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldExtended): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldCurrency): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldString): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDateTime): Boolean; overload; end; // boolean type // http://www.freepascal.org/docs-html/ref/refsu5.html#x27-260003.1.1 // Name Size Ord(True) // Boolean 1 1 { TfoDBTableFieldBoolean } TfoDBTableFieldBoolean = class(specialize TfoDBGenericTableField<Boolean>) public destructor Destroy; override; procedure ClearValue; override; function ToSql(): String; override; function ToXML(): String; override; function AsString(): String; override; //procedure CopyValue(aTableField: TfoDBTableField); override; //function ValueEquals(aTableField: TfoDBTableFieldByte): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldShortInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSmallInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldInt64): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldQWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldBoolean): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSingle): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDouble): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldExtended): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldCurrency): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldString): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDateTime): Boolean; overload; end; // real types // http://www.freepascal.org/docs-html/ref/refsu6.html#x28-310003.1.2 // Type Range Significant digits Size // Real platform dependant ??? 4 or 8 // Single 1.5E-45 .. 3.4E38 7-8 4 // Double 5.0E-324 .. 1.7E308 15-16 8 // Extended 1.9E-4932 .. 1.1E4932 19-20 10 // Comp -2E64+1 .. 2E63-1 19-20 8 // Currency -922337203685477.5808 .. 922337203685477.5807 19-20 8 { TfoDBTableFieldSingle } TfoDBTableFieldSingle = class(specialize TfoDBGenericTableField<Single>) public destructor Destroy; override; procedure ClearValue; override; function ToSql(): String; override; function ToXML(): String; override; function AsString(): String; override; //procedure CopyValue(aTableField: TfoDBTableField); override; //function ValueEquals(aTableField: TfoDBTableFieldByte): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldShortInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSmallInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldInt64): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldQWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldBoolean): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSingle): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDouble): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldExtended): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldCurrency): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldString): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDateTime): Boolean; overload; end; { TfoDBTableFieldDouble } TfoDBTableFieldDouble = class(specialize TfoDBGenericTableField<Double>) public destructor Destroy; override; procedure ClearValue; override; function ToSql(): String; override; function ToXML(): String; override; function AsString(): String; override; //procedure CopyValue(aTableField: TfoDBTableField); override; //function ValueEquals(aTableField: TfoDBTableFieldByte): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldShortInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSmallInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldInt64): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldQWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldBoolean): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSingle): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDouble): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldExtended): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldCurrency): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldString): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDateTime): Boolean; overload; end; { TfoDBTableFieldExtended } TfoDBTableFieldExtended = class(specialize TfoDBGenericTableField<Extended>) public destructor Destroy; override; procedure ClearValue; override; function ToSql(): String; override; function ToXML(): String; override; function AsString(): String; override; //procedure CopyValue(aTableField: TfoDBTableField); override; //function ValueEquals(aTableField: TfoDBTableFieldByte): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldShortInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSmallInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldInt64): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldQWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldBoolean): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSingle): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDouble): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldExtended): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldCurrency): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldString): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDateTime): Boolean; overload; end; { TfoDBTableFieldCurrency } TfoDBTableFieldCurrency = class(specialize TfoDBGenericTableField<Currency>) public destructor Destroy; override; procedure ClearValue; override; function ToSql(): String; override; function ToXML(): String; override; function AsString(): String; override; //procedure CopyValue(aTableField: TfoDBTableField); override; //function ValueEquals(aTableField: TfoDBTableFieldByte): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldShortInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSmallInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldInt64): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldQWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldBoolean): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSingle): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDouble): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldExtended): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldCurrency): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldString): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDateTime): Boolean; overload; end; { TfoDBTableFieldString } TfoDBTableFieldString = class(specialize TfoDBGenericTableField<String>) public destructor Destroy; override; procedure ClearValue; override; function ToSql(): String; override; function ToXML(): String; override; function AsString(): String; override; //procedure CopyValue(aTableField: TfoDBTableField); override; //function ValueEquals(aTableField: TfoDBTableFieldByte): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldShortInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSmallInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldInt64): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldQWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldBoolean): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSingle): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDouble): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldExtended): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldCurrency): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldString): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDateTime): Boolean; overload; end; { TfoDBTableFieldDateTime } TfoDBTableFieldDateTime = class(specialize TfoDBGenericTableField<TDateTime>) public destructor Destroy; override; procedure ClearValue; override; function ToSql(): String; override; function ToXML(): String; override; function AsString(): String; override; //procedure CopyValue(aTableField: TfoDBTableField); override; //function ValueEquals(aTableField: TfoDBTableFieldByte): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldShortInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSmallInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongInt): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldLongWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldInt64): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldQWord): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldBoolean): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldSingle): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDouble): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldExtended): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldCurrency): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldString): Boolean; overload; //function ValueEquals(aTableField: TfoDBTableFieldDateTime): Boolean; overload; end; implementation { TfoDBTableField } procedure TfoDBTableField.SetIsNull(aIsNull: Boolean); begin { If the field value is not already set to null } if fIsNull <> aIsNull then { Record that this fields value has now been changed } IsChanged := True; { Finally assign the new aIsNull value } fIsNull := aIsNull; { Remove any stored value if this field is now set to NULL, that would appear again if we were to assign this to not null again } if fIsNull then ClearValue; { TODO -oAPL -cDBTypes 5: What if the field is not nullable, should we give a warning then? Perpahs only when the field was assigned to something before? Since creating a new object with a not nullable field should be possible } end; procedure TfoDBTableField.SetIsChanged(aIsChanged: Boolean); begin { Set whether ths value of this field has been changed } fIsChanged := aIsChanged; { Notify all oberservers that this field has changed value } NotifyAllObservers; end; constructor TfoDBTableField.Create(aOwnerTable: TfoDBTableObject; aFieldName: String); begin inherited Create; { Assign the parameters of this constructor to the local variables in this instance for later usage } fOwnerTable := aOwnerTable; fFieldName := aFieldName; { Attach the owning table as an observer of this field } AttachObserver(fOwnerTable); { This field should add itself to the complete list of field in the owning tables field collection } fOwnerTable.AddTableField(Self); { Set initial state of the abstract field } fIsNull := True; fIsChanged := False; fIsPrimaryKey := False; fIsIndexed := False; fIsForeignKey := False; fHasDefault := False; fIsNullable := False; { Clear the value of this field upon creation } ClearValue; end; destructor TfoDBTableField.Destroy; begin inherited Destroy; end; { TfoDBTableFieldDateTime } destructor TfoDBTableFieldDateTime.Destroy; begin inherited Destroy; end; procedure TfoDBTableFieldDateTime.ClearValue; begin inherited ClearValue; fValue := 0; end; function TfoDBTableFieldDateTime.ToSql: String; begin Result := inherited ToSql; if fIsNull then Result := c_SQL_NULL else begin Result := FormatDateTime(c_SQL_DateTimeFormat, fValue); Result := ToSqlStr(Result); end; end; function TfoDBTableFieldDateTime.ToXML: String; begin Result := inherited ToXML; if fIsNull then Result := c_XML_NULL else { TODO -oAPL -cDBTypes 5: Need to do more work around converting a TDateTime value to XML, need to use some actual XML datetime transforming code } Result := FormatDateTime(c_XML_DateTimeFormat, fValue); end; function TfoDBTableFieldDateTime.AsString: String; begin Result := inherited AsString; if fIsNull then Result := c_String_NULL else Result := FormatDateTime(c_String_DateTimeFormat, fValue); end; { TfoDBTableFieldString } destructor TfoDBTableFieldString.Destroy; begin inherited Destroy; end; procedure TfoDBTableFieldString.ClearValue; begin inherited ClearValue; fValue := ''; end; function TfoDBTableFieldString.ToSql: String; begin Result := inherited ToSql; if fIsNull then Result := c_SQL_NULL else Result := ToSqlStr(fValue); end; function TfoDBTableFieldString.ToXML: String; begin Result := inherited ToXML; if fIsNull then Result := c_XML_NULL else Result := fValue; end; function TfoDBTableFieldString.AsString: String; begin Result := inherited AsString; if fIsNull then Result := c_String_NULL else Result := fValue; end; { TfoDBTableFieldCurrency } destructor TfoDBTableFieldCurrency.Destroy; begin inherited Destroy; end; procedure TfoDBTableFieldCurrency.ClearValue; begin inherited ClearValue; fValue := 0; end; function TfoDBTableFieldCurrency.ToSql: String; var tmpSep: Char; begin Result := inherited ToSql; if fIsNull then Result := c_SQL_NULL else begin tmpSep := FormatSettings.DecimalSeparator; try FormatSettings.DecimalSeparator := c_SQL_DecimalSeparatorChar; Result := FloatToStr(fValue); finally FormatSettings.DecimalSeparator := tmpSep; end; end; end; function TfoDBTableFieldCurrency.ToXML: String; var tmpSep: Char; begin Result := inherited ToXML; if fIsNull then Result := c_XML_NULL else begin tmpSep := FormatSettings.DecimalSeparator; try FormatSettings.DecimalSeparator := c_XML_DecimalSeparatorChar; Result := FloatToStr(fValue); finally FormatSettings.DecimalSeparator := tmpSep; end; end; end; function TfoDBTableFieldCurrency.AsString: String; var tmpSep: Char; begin Result := inherited AsString; if fIsNull then Result := c_String_NULL else begin tmpSep := FormatSettings.DecimalSeparator; try FormatSettings.DecimalSeparator := c_String_DecimalSeparatorChar; Result := FloatToStr(fValue); finally FormatSettings.DecimalSeparator := tmpSep; end; end; end; { TfoDBTableFieldExtended } destructor TfoDBTableFieldExtended.Destroy; begin inherited Destroy; end; procedure TfoDBTableFieldExtended.ClearValue; begin inherited ClearValue; fValue := 0; end; function TfoDBTableFieldExtended.ToSql: String; var tmpSep: Char; begin Result := inherited ToSql; if fIsNull then Result := c_SQL_NULL else begin tmpSep := FormatSettings.DecimalSeparator; try FormatSettings.DecimalSeparator := c_SQL_DecimalSeparatorChar; Result := FloatToStr(fValue); finally FormatSettings.DecimalSeparator := tmpSep; end; end; end; function TfoDBTableFieldExtended.ToXML: String; var tmpSep: Char; begin Result := inherited ToXML; if fIsNull then Result := c_XML_NULL else begin tmpSep := FormatSettings.DecimalSeparator; try FormatSettings.DecimalSeparator := c_XML_DecimalSeparatorChar; Result := FloatToStr(fValue); finally FormatSettings.DecimalSeparator := tmpSep; end; end; end; function TfoDBTableFieldExtended.AsString: String; var tmpSep: Char; begin Result := inherited AsString; if fIsNull then Result := c_String_NULL else begin tmpSep := FormatSettings.DecimalSeparator; try FormatSettings.DecimalSeparator := c_String_DecimalSeparatorChar; Result := FloatToStr(fValue); finally FormatSettings.DecimalSeparator := tmpSep; end; end; end; { TfoDBTableFieldDouble } destructor TfoDBTableFieldDouble.Destroy; begin inherited Destroy; end; procedure TfoDBTableFieldDouble.ClearValue; begin inherited ClearValue; fValue := 0; end; function TfoDBTableFieldDouble.ToSql: String; var tmpSep: Char; begin Result := inherited ToSql; if fIsNull then Result := c_SQL_NULL else begin tmpSep := FormatSettings.DecimalSeparator; try FormatSettings.DecimalSeparator := c_SQL_DecimalSeparatorChar; Result := FloatToStr(fValue); finally FormatSettings.DecimalSeparator := tmpSep; end; end; end; function TfoDBTableFieldDouble.ToXML: String; var tmpSep: Char; begin Result := inherited ToXML; if fIsNull then Result := c_XML_NULL else begin tmpSep := FormatSettings.DecimalSeparator; try FormatSettings.DecimalSeparator := c_XML_DecimalSeparatorChar; Result := FloatToStr(fValue); finally FormatSettings.DecimalSeparator := tmpSep; end; end; end; function TfoDBTableFieldDouble.AsString: String; var tmpSep: Char; begin Result := inherited AsString; if fIsNull then Result := c_String_NULL else begin tmpSep := FormatSettings.DecimalSeparator; try FormatSettings.DecimalSeparator := c_String_DecimalSeparatorChar; Result := FloatToStr(fValue); finally FormatSettings.DecimalSeparator := tmpSep; end; end; end; { TfoDBTableFieldSingle } destructor TfoDBTableFieldSingle.Destroy; begin inherited Destroy; end; procedure TfoDBTableFieldSingle.ClearValue; begin inherited ClearValue; fValue := 0; end; function TfoDBTableFieldSingle.ToSql: String; var tmpSep: Char; begin Result := inherited ToSql; if fIsNull then Result := c_SQL_NULL else begin tmpSep := FormatSettings.DecimalSeparator; try FormatSettings.DecimalSeparator := c_SQL_DecimalSeparatorChar; Result := FloatToStr(fValue); finally FormatSettings.DecimalSeparator := tmpSep; end; end; end; function TfoDBTableFieldSingle.ToXML: String; var tmpSep: Char; begin Result := inherited ToXML; if fIsNull then Result := c_XML_NULL else begin tmpSep := FormatSettings.DecimalSeparator; try FormatSettings.DecimalSeparator := c_XML_DecimalSeparatorChar; Result := FloatToStr(fValue); finally FormatSettings.DecimalSeparator := tmpSep; end; end; end; function TfoDBTableFieldSingle.AsString: String; var tmpSep: Char; begin Result := inherited AsString; if fIsNull then Result := c_String_NULL else begin tmpSep := FormatSettings.DecimalSeparator; try FormatSettings.DecimalSeparator := c_String_DecimalSeparatorChar; Result := FloatToStr(fValue); finally FormatSettings.DecimalSeparator := tmpSep; end; end; end; { TfoDBTableFieldBoolean } destructor TfoDBTableFieldBoolean.Destroy; begin inherited Destroy; end; procedure TfoDBTableFieldBoolean.ClearValue; begin inherited ClearValue; fValue := False; end; function TfoDBTableFieldBoolean.ToSql: String; begin Result := inherited ToSql; if fIsNull then Result := c_SQL_NULL else Result := c_SQL_Boolean[fValue]; end; function TfoDBTableFieldBoolean.ToXML: String; begin Result := inherited ToXML; if fIsNull then Result := c_XML_NULL else Result := c_XML_Boolean[fValue]; end; function TfoDBTableFieldBoolean.AsString: String; begin Result := inherited AsString; if fIsNull then Result := c_String_NULL else Result := c_String_Boolean[fValue]; end; { TfoDBTableFieldQWord } destructor TfoDBTableFieldQWord.Destroy; begin inherited Destroy; end; procedure TfoDBTableFieldQWord.ClearValue; begin inherited ClearValue; fValue := 0; end; function TfoDBTableFieldQWord.ToSql: String; begin Result := inherited ToSql; if fIsNull then Result := c_SQL_NULL else Result := IntToStr(fValue); end; function TfoDBTableFieldQWord.ToXML: String; begin Result := inherited ToXML; if fIsNull then Result := c_XML_NULL else Result := IntToStr(fValue); end; function TfoDBTableFieldQWord.AsString: String; begin Result := inherited AsString; if fIsNull then Result := c_String_NULL else Result := IntToStr(fValue); end; { TfoDBTableFieldInt64 } destructor TfoDBTableFieldInt64.Destroy; begin inherited Destroy; end; procedure TfoDBTableFieldInt64.ClearValue; begin inherited ClearValue; fValue := 0; end; function TfoDBTableFieldInt64.ToSql: String; begin Result := inherited ToSql; if fIsNull then Result := c_SQL_NULL else Result := IntToStr(fValue); end; function TfoDBTableFieldInt64.ToXML: String; begin Result := inherited ToXML; if fIsNull then Result := c_XML_NULL else Result := IntToStr(fValue); end; function TfoDBTableFieldInt64.AsString: String; begin Result := inherited AsString; if fIsNull then Result := c_String_NULL else Result := IntToStr(fValue); end; { TfoDBTableFieldLongWord } destructor TfoDBTableFieldLongWord.Destroy; begin inherited Destroy; end; procedure TfoDBTableFieldLongWord.ClearValue; begin inherited ClearValue; fValue := 0; end; function TfoDBTableFieldLongWord.ToSql: String; begin Result := inherited ToSql; if fIsNull then Result := c_SQL_NULL else Result := IntToStr(fValue); end; function TfoDBTableFieldLongWord.ToXML: String; begin Result := inherited ToXML; if fIsNull then Result := c_XML_NULL else Result := IntToStr(fValue); end; function TfoDBTableFieldLongWord.AsString: String; begin Result := inherited AsString; if fIsNull then Result := c_String_NULL else Result := IntToStr(fValue); end; { TfoDBTableFieldWord } destructor TfoDBTableFieldWord.Destroy; begin inherited Destroy; end; procedure TfoDBTableFieldWord.ClearValue; begin inherited ClearValue; fValue := 0; end; function TfoDBTableFieldWord.ToSql: String; begin Result := inherited ToSql; if fIsNull then Result := c_SQL_NULL else Result := IntToStr(fValue); end; function TfoDBTableFieldWord.ToXML: String; begin Result := inherited ToXML; if fIsNull then Result := c_XML_NULL else Result := IntToStr(fValue); end; function TfoDBTableFieldWord.AsString: String; begin Result := inherited AsString; if fIsNull then Result := c_String_NULL else Result := IntToStr(fValue); end; { TfoDBTableFieldShortInt } destructor TfoDBTableFieldShortInt.Destroy; begin inherited Destroy; end; procedure TfoDBTableFieldShortInt.ClearValue; begin inherited ClearValue; fValue := 0; end; function TfoDBTableFieldShortInt.ToSql: String; begin Result := inherited ToSql; if fIsNull then Result := c_SQL_NULL else Result := IntToStr(fValue); end; function TfoDBTableFieldShortInt.ToXML: String; begin Result := inherited ToXML; if fIsNull then Result := c_XML_NULL else Result := IntToStr(fValue); end; function TfoDBTableFieldShortInt.AsString: String; begin Result := inherited AsString; if fIsNull then Result := c_String_NULL else Result := IntToStr(fValue); end; { TfoDBTableFieldByte } destructor TfoDBTableFieldByte.Destroy; begin inherited Destroy; end; procedure TfoDBTableFieldByte.ClearValue; begin inherited ClearValue; fValue := 0; end; function TfoDBTableFieldByte.ToSql: String; begin Result := inherited ToSql; if fIsNull then Result := c_SQL_NULL else Result := IntToStr(fValue); end; function TfoDBTableFieldByte.ToXML: String; begin Result := inherited ToXML; if fIsNull then Result := c_XML_NULL else Result := IntToStr(fValue); end; function TfoDBTableFieldByte.AsString: String; begin Result := inherited AsString; if fIsNull then Result := c_String_NULL else Result := IntToStr(fValue); end; procedure TfoDBTableFieldByte.CopyValue(aTableField: TfoDBTableField); begin inherited CopyValue(aTableField); if (aTableField.ClassType = TfoDBTableFieldByte) then Value := TfoDBTableFieldByte(aTableField).Value else if (aTableField.ClassType = TfoDBTableFieldShortInt) then begin Value := TfoDBTableFieldByte(aTableField).Value end else if (aTableField.ClassType = TfoDBTableFieldSmallInt) then begin end else if (aTableField.ClassType = TfoDBTableFieldWord) then begin end else if (aTableField.ClassType = TfoDBTableFieldLongInt) then begin end else if (aTableField.ClassType = TfoDBTableFieldLongWord) then begin end else if (aTableField.ClassType = TfoDBTableFieldInt64) then begin end else if (aTableField.ClassType = TfoDBTableFieldQWord) then begin end else if (aTableField.ClassType = TfoDBTableFieldBoolean) then begin end else if (aTableField.ClassType = TfoDBTableFieldSingle) then begin end else if (aTableField.ClassType = TfoDBTableFieldDouble) then begin end else if (aTableField.ClassType = TfoDBTableFieldExtended) then begin end else if (aTableField.ClassType = TfoDBTableFieldCurrency) then begin end else if (aTableField.ClassType = TfoDBTableFieldString) then begin end else if (aTableField.ClassType = TfoDBTableFieldDateTime) then begin end else begin end end; { TfoDBTableFieldSmallInt } destructor TfoDBTableFieldSmallInt.Destroy; begin inherited Destroy; end; procedure TfoDBTableFieldSmallInt.ClearValue; begin inherited ClearValue; fValue := 0; end; function TfoDBTableFieldSmallInt.ToSql: String; begin Result := inherited ToSql; if fIsNull then Result := c_SQL_NULL else Result := IntToStr(fValue); end; function TfoDBTableFieldSmallInt.ToXML: String; begin Result := inherited ToXML; if fIsNull then Result := c_XML_NULL else Result := IntToStr(fValue); end; function TfoDBTableFieldSmallInt.AsString: String; begin Result := inherited AsString; if fIsNull then Result := c_String_NULL else Result := IntToStr(fValue); end; { TfoDBTableFieldLongInt } destructor TfoDBTableFieldLongInt.Destroy; begin inherited Destroy; end; procedure TfoDBTableFieldLongInt.ClearValue; begin inherited ClearValue; fValue := 0; end; function TfoDBTableFieldLongInt.ToSql: String; begin Result := inherited ToSql; if fIsNull then Result := c_SQL_NULL else Result := IntToStr(fValue); end; function TfoDBTableFieldLongInt.ToXML: String; begin Result := inherited ToXML; if fIsNull then Result := c_XML_NULL else Result := IntToStr(fValue); end; function TfoDBTableFieldLongInt.AsString: String; begin Result := inherited AsString; if fIsNull then Result := c_String_NULL else Result := IntToStr(fValue); end; { TfoDBTableInformation } constructor TfoDBTableInformation.Create; begin inherited Create; end; destructor TfoDBTableInformation.Destroy; begin inherited Destroy; end; constructor TfoDBGenericTableField.Create(aOwnerTable: TfoDBTableObject; aFieldName: String); begin { Call inherited create } inherited Create(aOwnerTable, aFieldName); end; destructor TfoDBGenericTableField.Destroy; begin { Call inherited destroy } inherited Destroy; end; procedure TfoDBGenericTableField.CopyValue(aTableField: TfoDBTableField); begin { Does nothing at this stage, only implemented because I don't seem to be able to inherit an abstract function into another abstract function } end; function TfoDBGenericTableField.ToSql: String; begin { Does nothing at this stage, only implemented because I don't seem to be able to inherit an abstract function into another abstract function } Result := ''; end; function TfoDBGenericTableField.ToXML: String; begin { Does nothing at this stage, only implemented because I don't seem to be able to inherit an abstract function into another abstract function } Result := ''; end; function TfoDBGenericTableField.AsString: String; begin { Does nothing at this stage, only implemented because I don't seem to be able to inherit an abstract function into another abstract function } Result := ''; end; procedure TfoDBGenericTableField.SetValue(aValue: T); begin { If the field value is set to null, then assign the new value to the internal variable, and set the IsNull field to False. This will cause the IsChanged property to be set to True in turn, since the value of IsNull is true before the assignment. That will in turn also kick off the NotifyAllObservers function call } if IsNull then begin fValue := aValue; IsNull := False; end { If the field value is not null and the new value is different from the old one, then assign the new value, and set the field to IsChanged = true } else if (fValue <> aValue) then begin fValue := aValue; IsChanged := True; end; { There is a final case here, where IsNull is false and the passed value and current value are identical. In this case, no change should be made, and no observers should be notified about a change } end; procedure TfoDBGenericTableField.ClearValue; begin { Does nothing at this stage, only implemented because I don't seem to be able to inherit an abstract procedure into another abstract procefure } end; { TfoDBTableObject } function TfoDBTableObject.OpenConnection: Boolean; const lProcedureName = 'OpenConnection'; begin { Default result is that we did not connect } Result := False; { Check the local class connection variable } if not Assigned(fConnection) then raise Exception.Create(Self.ClassName + '.' + lProcedureName + ': ' + 'Unable to add field to table object, the local fConnection is not assigned.'); { Set the local flag, that indicates if this instance opened the connection ( interresting when doing nested inserts and we do not want to open and close the connection a lot of times, but jus trather want the initiator objec to open, and then finally close the connection we are using. } fOpenedConnection := False; { If the connection is not already connected, then open the connection and set the local flag that indicates that this instance is responsible for closing the connection again. } try if not fConnection.Connected then begin fConnection.Open(); Result := True; fOpenedConnection := True; end else { In case the connection is already open, return True to indicate that the connection 'was opened', so that the calling code may proceed, assuming that the connection is open. } Result := True; { If an exception occurrs when connecting, set the Result to false and reraise the exception. } except on e:Exception do begin Result := False; raise; end; end; end; function TfoDBTableObject.CloseConnection(aConsumeException: Boolean): Boolean; const lProcedureName = 'CloseConnection'; begin { Default result is that we did were unsuccessful } Result := False; { Check the local class connection variable } if not Assigned(fConnection) then raise Exception.Create(Self.ClassName + '.' + lProcedureName + ': ' + 'Unable to add field to table object, the local fConnection is not assigned.'); { Attempt to close the connection, if this instance was the initiator of the connection. } try if fOpenedConnection then fConnection.Close; Result := True; { If an exception occurrs when disconnecting, set the Result to false and reraise the exception. } except on e:Exception do begin Result := False; { If the called asked not to 'mute' this exception, then raise it again. } if not aConsumeException then raise; end; end; end; procedure TfoDBTableObject.AddTableField(aTableField: TfoDBTableField); const lProcedureName = 'AddTableField'; begin { Check the local class variable } if not Assigned(fFieldList) then raise Exception.Create(Self.ClassName + '.' + lProcedureName + ': ' + 'Unable to add field to table object, the local fFieldList is not assigned.'); { Check the input parameter } if not Assigned(aTableField) then raise Exception.Create(Self.ClassName + '.' + lProcedureName + ': ' + 'Unable to add field to table object, the aTableField parameter is not assigned.'); { Add the field to the internal field list } fFieldList.Add(aTableField); end; constructor TfoDBTableObject.Create(aConnection: TSQLConnector; aMutex: TCriticalSection); begin inherited Create; { Assign the connection and mutex to be used to the local variables } fConnection := aConnection; fMutex := aMutex; { Create the local state holder object and the object that holds some table information about the table that the decendant class wraps } fTableInformation := TfoDBTableInformation.Create; fObjectStatus := TfoDBTableStatus.Create(Self); { Set the initial destroying state } fIsDestroying := False; fOpenedConnection := False; { Create the local fieldlist, that will hold all field references. Fields will also be available by their name and specific type in the autogenerated decending classes } fFieldList := TfoDBTableFieldList.Create; end; destructor TfoDBTableObject.Destroy; begin { Free the local object types } if Assigned(fObjectStatus) then fObjectStatus.Free; if Assigned(fTableInformation) then fTableInformation.Free; if Assigned(fFieldList) then fFieldList.Free; { Call the inherited destructor } inherited Destroy; end; procedure TfoDBTableObject.ReceiveSubjectUpdate(aSubject: IfoObserverSubject); begin { A field has changed } { DONE -oAPL -cDBTypes 3: Perhaps control the state of the table status from here? } ObjectStatus.ChangedTime := Now; ObjectStatus.IsChanged := True; end; { TfoDBTableStatus } constructor TfoDBTableStatus.Create(aOwnerTable: TfoDBTableObject); begin inherited Create; fOwnerTable := aOwnerTable; fIsNew := True; fIsLoaded := False; fIsChanged := False; fIsDeleted := False; fCreatedTime := Now; fSavedTime := 0; fLoadedTime := 0; fChangedTime := 0; fDeletedTime := 0; fIsInserting := False; fIsDeleting := False; fIsUpdating := False; end; destructor TfoDBTableStatus.Destroy; begin inherited Destroy; end; procedure TfoDBTableStatus.SetIsNew(aIsNew: Boolean); begin { User is setting this object to a 'new' state, while it actually is an object that has been changed at some point, since fIsNew is no longer true. The user may be trying to save a copy of the object or something. Set the object to a 'newly created' state. } if (not fIsNew) and aIsNew then begin fIsNew := aIsNew; fIsLoaded := False; fIsChanged := False; fIsDeleted := False; fCreatedTime := Now; fSavedTime := 0; fLoadedTime := 0; fChangedTime := 0; fDeletedTime := 0; end; end; procedure TfoDBTableStatus.SetIsLoaded(aIsLoaded: Boolean); begin { Set the local object IsLoaded value to the parameter } fIsLoaded := aIsLoaded; { If this object is now loaded, set the LoadedTime to now. Should I set it to 0 if the fIsLoaded flag is set to false? } if fIsLoaded then fLoadedTime := Now; end; procedure TfoDBTableStatus.SetIsChanged(aIsChanged: Boolean); begin { Set the local object IsChanged value to the parameter } fIsChanged := aIsChanged; { If this object is now changed set the ChangedTime to now, otherwise should it be set to 0? } if fIsChanged then fChangedTime := Now; end; procedure TfoDBTableStatus.SetIsDeleted(aIsDeleted: Boolean); begin { Update the local fIsDeleted flag } fIsDeleted := aIsDeleted; { If this object was deleted, set the deleted time to now, otherwise set it to 0 - if the object is 'not deleted' } if fIsDeleted then fDeletedTime := Now else fDeletedTime := 0; end; end.
unit RankingsDaemon; interface uses DirServerSession, Daemons; function CreateDaemon(const DSAddr : string; DSPort : integer) : IDaemon; implementation uses Windows, Classes, SysUtils, SyncObjs, Inifiles, RankProtocol, Forms, Clipbrd, MathUtils, Logs, DirectoryServerProtocol; const cLogId = 'Rankings Daemon'; type TUserHash = 'A'..'Z'; type TRanking = class public constructor Create(const Id, Name, Super : string; RankType : integer); destructor Destroy; override; public function AddRankedPlayer(const Name, Value : string) : integer; procedure Sort; procedure Generate(const Session : IDirServerSession; Run : integer); private fId : string; fName : string; fSuperId : string; fSuper : TRanking; fType : integer; fRankedPlayers : TStringList; function GetKeyName : string; end; type TRankingValue = class private constructor Create(const Name, Value : string); virtual; private function ValueAsStr : string; virtual; abstract; procedure Increment(const Value : string); virtual; abstract; function Compare(Value : TRankingValue) : integer; virtual; abstract; private fName : string; end; CRankingValue = class of TRankingValue; type TIntegerValue = class(TRankingValue) private constructor Create(const Name, Value : string); override; private function ValueAsStr : string; override; procedure Increment(const Value : string); override; function Compare(Value : TRankingValue) : integer; override; private fValue : integer; end; CIntegerValue = class of TIntegerValue; type TCurrencyValue = class(TRankingValue) private constructor Create(const Name, Value : string); override; private function ValueAsStr : string; override; procedure Increment(const Value : string); override; function Compare(Value : TRankingValue) : integer; override; private fValue : currency; end; CCurrencyValue = class of TCurrencyValue; type TITAValue = class(TRankingValue) private constructor Create(const Name, Value : string); override; private function ValueAsStr : string; override; procedure Increment(const Value : string); override; function Compare(Value : TRankingValue) : integer; override; private fValue : integer; fCount : integer; end; CITAValue = class of TITAValue; const cRankingTypeClasses : array [1..4] of CRankingValue = (TCurrencyValue, TIntegerValue, TCurrencyValue, TITAValue); type TPlayerCurriculum = class private constructor Create(const PlayerName : string); destructor Destroy; override; private procedure AddRanking(const Name : string; Position : integer; const Value : string); procedure WriteToDataBase(const Session : IDirServerSession; Run : integer); private fPlayerName : string; fRankingCount : integer; fRankings : TStringList; end; type TRankingsDaemon = class(TBasicDaemon) private // IDaemon function GetName : string; override; function GetDescription : string; override; private procedure Execute; override; function GetLogId : string; override; private procedure GenerateGlobalRankings; private fRun : integer; end; function CreateDaemon(const DSAddr : string; DSPort : integer) : IDaemon; begin Result := TRankingsDaemon.Create(DSAddr, DSPort); end; function CompareRankingValues(Item1, Item2 : pointer) : integer; begin Result := TRankingValue(Item1).Compare(TRankingValue(Item2)); end; function GenerateValidRankKey(const id : string) : string; begin if (id[1] in ['A'..'Z']) or (id[1] in ['a'..'z']) then Result := id else Result := 'R' + id; end; constructor TRanking.Create(const Id, Name, Super : string; RankType : integer); begin inherited Create; fId := Id; fName := Name; fSuperId := Super; fType := RankType; fRankedPlayers := TStringList.Create; end; destructor TRanking.Destroy; var i : integer; begin for i := 0 to pred(fRankedPlayers.Count) do TRankingValue(fRankedPlayers.Objects[i]).Free; fRankedPlayers.Free; inherited; end; function TRanking.AddRankedPlayer(const Name, Value : string) : integer; var idx : integer; begin idx := fRankedPlayers.IndexOf(Name); if idx <> -1 then TRankingValue(fRankedPlayers.Objects[idx]).Increment(Value) // player already ranked else idx := fRankedPlayers.AddObject(Name, cRankingTypeClasses[fType].Create('Value', Value)); Result := idx; end; procedure TRanking.Sort; type TCompareFun = function (Item1, Item2 : pointer) : integer; procedure QuickSort(SortList : TStringList; L, R: Integer; CompareFun : TCompareFun); var i, j : integer; P : pointer; begin repeat i := L; j := R; P := SortList.Objects[(L + R) shr 1]; repeat while CompareFun(SortList.Objects[i], P) < 0 do inc(i); while CompareFun(SortList.Objects[j], P) > 0 do dec(j); if i <= j then begin SortList.Exchange(i, j); inc(i); dec(j); end; until i > j; if L < j then QuickSort(SortList, L, j, CompareFun); L := I; until i >= R; end; begin if fRankedPlayers.Count > 0 then QuickSort(fRankedPlayers, 0, pred(fRankedPlayers.Count), CompareRankingValues); end; procedure TRanking.Generate(const Session : IDirServerSession; Run : integer); const cPrestigeRankingId = 'Prestige'; cWealthRankingId = 'Wealth'; cITARankingId = 'ITA'; var basekey : string; validkey : string; i : integer; playername : string; playerkey : string; userhash : TUserHash; value : string; PrintableRanking : TStringList; begin Log(cLogId, 'Generating ranking ' + fName); basekey := 'Root/Rankings/' + GetKeyName; if Session.CreateFullPathKey(basekey, true) and Session.SetCurrentKey(basekey) then begin if Session.ValueExists('Current') then begin validkey := Session.ReadString('Current'); if validkey <> '' then if validkey[length(validkey)] = '1' then validkey[length(validkey)] := '2' else validkey[length(validkey)] := '1' else validkey := 'K1'; end else validkey := 'K1'; Session.WriteString('Name', fName); PrintableRanking := TStringList.Create; try for i := pred(fRankedPlayers.Count) downto 0 do begin playername := fRankedPlayers[i]; if playername <> '' then begin playerkey := GetAliasId(playername); value := TRankingValue(fRankedPlayers.Objects[i]).ValueAsStr; PrintableRanking.Add(playername + '=' + value); userhash := playerkey[1]; if (fId = cPrestigeRankingId) or (fId = cWealthRankingId) or (fId = cITARankingId) then if Session.SetCurrentKey('Root/Users/' + userhash + '/' + playerkey) then if Session.CreateFullPathKey('Root/Users/' + userhash + '/' + playerkey + '/' + fId, true) and Session.SetCurrentKey('Root/Users/' + userhash + '/' + playerkey + '/' + fId) then begin Session.WriteString('Value', value); Session.WriteInteger('Run', Run); end else Log(cLogId, 'Unable to set or create ' + 'Root/Users/' + userhash + '/' + playerkey + '/' + fId + ' key') else Log(cLogId, 'Unable to set ' + 'Root/Users/' + userhash + '/' + playerkey + ' key'); end; end; if Session.SetCurrentKey(basekey) then begin Session.WriteString(validkey, PrintableRanking.Text); {$IFDEF EXTRALogs} Log(fName, PrintableRanking.Text); {$ENDIF} Session.WriteString('Current', validkey); end else Log(cLogId, 'Unable to set key ' + basekey); finally PrintableRanking.Free; end; end else Log(cLogId, 'Unable to find, create or set ' + basekey + ' key'); end; function TRanking.GetKeyName : string; var prefix : string; Super : TRanking; begin prefix := ''; Super := fSuper; while Super <> nil do begin prefix := GenerateValidRankKey(Super.fId) + '/' + prefix; Super := Super.fSuper; end; Result := prefix + GenerateValidRankKey(fId); end; // TRankingValue constructor TRankingValue.Create(const Name, Value : string); begin inherited Create; fName := Name; end; // TIntegerValue constructor TIntegerValue.Create(const Name, Value : string); var dbl : double; begin inherited Create(Name, Value); dbl := StrToFloat(Value); fValue := round(dbl); end; function TIntegerValue.ValueAsStr : string; begin Result := IntToStr(fValue); end; procedure TIntegerValue.Increment(const Value : string); var newvalue : integer; begin newvalue := StrToInt(Value); inc(fValue, newvalue); end; function TIntegerValue.Compare(Value : TRankingValue) : integer; begin Result := fValue - TIntegerValue(Value).fValue; end; // TCurrencyValue constructor TCurrencyValue.Create(const Name, Value : string); begin inherited Create(Name, Value); fValue := StrToCurr(Value); end; function TCurrencyValue.ValueAsStr : string; begin Result := FormatMoney(fValue); end; procedure TCurrencyValue.Increment(const Value : string); var newvalue : currency; begin newvalue := StrToCurr(Value); fValue := fValue + newvalue; end; function TCurrencyValue.Compare(Value : TRankingValue) : integer; begin if fValue < TCurrencyValue(Value).fValue then Result := -1 else if fValue = TCurrencyValue(Value).fValue then Result := 0 else Result := 1; end; // TITAValue constructor TITAValue.Create(const Name, Value : string); begin inherited Create(Name, Value); fValue := StrToInt(Value); fCount := 1; end; function TITAValue.ValueAsStr : string; var value : integer; begin value := round(fValue/fCount); Result := IntToStr(value); end; procedure TITAValue.Increment(const Value : string); const cITAConstant = 10000; var newvalue : integer; begin newvalue := cITAConstant - StrToInt(Value); inc(fValue, newvalue); inc(fCount); end; function TITAValue.Compare(Value : TRankingValue) : integer; begin if fValue < TITAValue(Value).fValue then Result := -1 else if fValue = TITAValue(Value).fValue then Result := 0 else Result := 1; end; const cDefaultPeriod = 60*60*1000; // TPlayerCurriculum constructor TPlayerCurriculum.Create(const PlayerName : string); begin inherited Create; fPlayerName := PlayerName; fRankings := TStringList.Create; end; destructor TPlayerCurriculum.Destroy; begin fRankings.Free; inherited; end; procedure TPlayerCurriculum.AddRanking(const Name : string; Position : integer; const Value : string); begin fRankings.Add('Name' + IntToStr(fRankingCount) + '=' + Name); fRankings.Add('Position' + IntToStr(fRankingCount) + '=' + IntToStr(Position)); fRankings.Add('Value' + IntToStr(fRankingCount) + '=' + Value); inc(fRankingCount); end; procedure TPlayerCurriculum.WriteToDataBase(const Session : IDirServerSession; Run : integer); var playerkey : string; userhash : TUserHash; begin playerkey := GetAliasId(fPlayerName); userhash := playerkey[1]; if Session.SetCurrentKey('Root/Users/' + userhash + '/' + playerkey) then begin fRankings.Insert(0, 'Run=' + IntToStr(Run)); fRankings.Insert(1, 'Count=' + IntToStr(fRankingCount)); Session.WriteString('Rankings', fRankings.Text); {$IFDEF EXTRALogs} Log('Player Curricula', fRankings.Text); {$ENDIF} end else Log(cLogId, 'Unable to set ' + 'Root/Users/' + userhash + '/' + playerkey + ' key'); end; // TRankingsDaemon function TRankingsDaemon.GetName : string; begin Result := cLogId; end; function TRankingsDaemon.GetDescription : string; begin Result := 'Rankings creator daemon'; end; procedure TRankingsDaemon.Execute; begin inherited; GenerateGlobalRankings; inc(fRun); end; function TRankingsDaemon.GetLogId : string; begin Result := cLogId; end; procedure TRankingsDaemon.GenerateGlobalRankings; var basekey : widestring; key : widestring; WorldRankings : TStringList; Areas : TStringList; Worlds : TStringList; i, j, k, l : integer; rankcount : integer; membercount : integer; CurRanking : TRanking; Rankings : TList; UnParented : TList; ITARanking : TRanking; incrankings : integer; idx : integer; id : string; name : string; _type : string; super : string; rankstructure : string; PlayerCurricula : TList; CurCurriculum : TPlayerCurriculum; function GetRankingObject(const id, name, super : string; ranktype : integer) : TRanking; var i : integer; begin Result := nil; i := 0; while (Result = nil) and (i < Rankings.Count) do if TRanking(Rankings[i]).fId = id then Result := Rankings[i] else inc(i); if Result = nil then begin Result := TRanking.Create(id, name, super, ranktype); Rankings.Add(Result); end; // find super now i := 0; while (Result.fSuper = nil) and (i < Rankings.Count) do if TRanking(Rankings[i]).fId = Result.fSuperId then Result.fSuper := Rankings[i] else inc(i); if Result.fSuper = nil // super not found, add to unresolved supers list then Unparented.Add(Result); // now check if new ranking is the parent of anybody i := 0; while i < Unparented.Count do begin if TRanking(Unparented[i]).fSuperId = Result.fId then begin TRanking(Unparented[i]).fSuper := Result; Unparented[i] := nil; end; inc(i); end; Unparented.Pack; end; function GenerateRankingStructure : string; var level : integer; Ranking : TRanking; RankStrList : TStringList; procedure GenerateRanking(Ranking : TRanking; idx, level : integer); var i : integer; nodepath : string; Super : TRanking; begin nodepath := ''; Super := Ranking.fSuper; while Super <> nil do begin nodepath := GenerateValidRankKey(Super.fId) + '/' + nodepath; Super := Super.fSuper; end; if nodepath <> '' then nodepath := nodepath + GenerateValidRankKey(Ranking.fId) else nodepath := GenerateValidRankKey(Ranking.fId); RankStrList.Add(nodepath); RankStrList.Add(Ranking.fName); RankStrList.Add(IntToStr(level)); // now write the children Rankings[idx] := nil; for i := 0 to pred(Rankings.Count) do if (Rankings[i] <> nil) and (TRanking(Rankings[i]).fSuper = Ranking) then GenerateRanking(Rankings[i], i, level + 1); Ranking.Free; end; begin Result := ''; RankStrList := TStringList.Create; try while Rankings.Count > 0 do begin Ranking := Rankings[0]; while Ranking.fSuper <> nil do Ranking := Ranking.fSuper; level := 0; GenerateRanking(Ranking, Rankings.IndexOf(Ranking), level); Rankings.Pack; end; Result := RankStrList.Text; finally //RankStrList.SaveToFile('RankingStructure.txt'); RankStrList.Free; end; end; function GetPlayerCurriculum(const PlayerName : string) : TPlayerCurriculum; var i : integer; found : boolean; begin i := 0; found := false; while (i < PlayerCurricula.Count) and not found do begin found := TPlayerCurriculum(PlayerCurricula[i]).fPlayerName = PlayerName; if not found then inc(i); end; if not found then begin Result := TPlayerCurriculum.Create(PlayerName); PlayerCurricula.Add(Result); end else Result := PlayerCurricula[i]; end; begin try Log(cLogId, 'Starting rankings generation at ' + DateTimeToStr(Now)); Areas := TStringList.Create; try Worlds := TStringList.Create; try WorldRankings := TStringList.Create; try Rankings := TList.Create; try Unparented := TList.Create; try basekey := 'Root/Areas'; if fSession.SetCurrentKey(basekey) then begin Areas.Text := fSession.GetKeyNames; for i := 0 to pred(Areas.Count) do begin key := basekey + '/' + Areas[i] + '/Worlds'; if fSession.SetCurrentKey(key) then begin Worlds.Text := fSession.GetKeyNames; for j := 0 to pred(Worlds.Count) do begin key := key + '/' + Worlds[j] + '/Model/Rankings'; if fSession.SetCurrentKey(key) then begin if fSession.ValueExists('Ranking') then with WorldRankings do begin Text := fSession.ReadString('Ranking'); Log('Read rankings', 'Rankings read from ' + Areas[i] + ', ' + Worlds[j] + #10#13 + Text); try if (Text <> '') and (IndexOf(tidTerminator_EndOfRanking) <> -1) then begin rankcount := StrToInt(Values[tidRankings_RankCount]); for k := 0 to pred(rankcount) do begin id := Values[IntToStr(k) + tidRankings_RankId]; name := Values[IntToStr(k) + tidRankings_RankName]; _type := Values[IntToStr(k) + tidRankings_RankType]; super := Values[IntToStr(k) + tidRankings_RankSuper]; if (id <> '') and (id <> 'NTA') and (name <> '') and (_type <> '') and (_type <> '0') and (super <> '') then try CurRanking := GetRankingObject(Values[IntToStr(k) + tidRankings_RankId], Values[IntToStr(k) + tidRankings_RankName], Values[IntToStr(k) + tidRankings_RankSuper], StrToInt(Values[IntToStr(k) + tidRankings_RankType])); membercount := StrToInt(Values[IntToStr(k) + tidRankings_RankMemberCount]); for l := 0 to pred(membercount) do CurRanking.AddRankedPlayer(Values[IntToStr(k) + tidRankings_Member + IntToStr(l) + tidRankings_MemberName], Values[IntToStr(k) + tidRankings_Member + IntToStr(l) + tidRankings_MemberValue]); except on e : Exception do Log(cLogId, 'Exception "' + e.Message + '" generated while processing ranking ' + name + ' of world ' + Worlds[j] + ' in area ' + Areas[i] + ' at ' + DateTimeToStr(Now)); else Log(cLogId, 'Unknown exception generated while processing ranking ' + name + ' of world ' + Worlds[j] + ' in area ' + Areas[i] + ' at ' + DateTimeToStr(Now)); end; end; end else Log(cLogId, 'Malformed or unexistent ranking in world ' + Worlds[j] + ' of area ' + Areas[i]); except on e : Exception do Log(cLogId, 'Exception "' + e.Message + '" generated while processing rankings of world ' + Worlds[j] + ' in area ' + Areas[i] + ' at ' + DateTimeToStr(Now)); else Log(cLogId, 'Unknown exception generated while processing rankings of world ' + Worlds[j] + ' in area ' + Areas[i] + ' at ' + DateTimeToStr(Now)); end; end; end else Log(cLogId, 'Key ' + key + ' not found, or unable to be set'); WorldRankings.Text := ''; key := basekey + '/' + Areas[i] + '/Worlds'; end; end else Log(cLogId, 'Key ' + key + ' not found, or unable to be set'); end; Log(cLogId, IntToStr(Rankings.Count) + ' rankings found. Now sorting'); for i := 0 to pred(Rankings.Count) do TRanking(Rankings[i]).Sort; Log(cLogId, 'Creating ITA ranking'); incrankings := 0; ITARanking := TRanking.Create('ITA', 'ITA', '', 4); for i := 0 to pred(Rankings.Count) do with TRanking(Rankings[i]) do if fRankedPlayers.Count > 0 then begin inc(incrankings); for j := 0 to pred(fRankedPlayers.Count) do begin idx := ITARanking.AddRankedPlayer(fRankedPlayers[j], IntToStr(fRankedPlayers.Count - j)); if TITAValue(ITARanking.fRankedPlayers.Objects[idx]).fCount = 1 then for k := 0 to pred(i) do if TRanking(Rankings[k]).fRankedPlayers.Count > 0 then TRankingValue(ITARanking.fRankedPlayers.Objects[idx]).Increment(IntToStr(TRanking(Rankings[k]).fRankedPlayers.Count + 1)) end; for j := 0 to pred(ITARanking.fRankedPlayers.Count) do if TITAValue(ITARanking.fRankedPlayers.Objects[j]).fCount < incrankings then TRankingValue(ITARanking.fRankedPlayers.Objects[j]).Increment(IntToStr(fRankedPlayers.Count + 1)); end; Log(cLogId, 'Sorting ITA ranking'); ITARanking.Sort; Rankings.Insert(0, ITARanking); Log(cLogId, 'ITA ranking sorted. Now gathering user curricula'); PlayerCurricula := TList.Create; try try for i := 0 to pred(Rankings.Count) do begin CurRanking := Rankings[i]; with CurRanking do for j := pred(fRankedPlayers.Count) downto 0 do begin CurCurriculum := GetPlayerCurriculum(fRankedPlayers[j]); CurCurriculum.AddRanking(CurRanking.fName, fRankedPlayers.Count - j, TRankingValue(fRankedPlayers.Objects[j]).ValueAsStr); end; end; except on e : Exception do Log(cLogId, 'Exception "' + e.Message + '" generated while generating user curricula at ' + DateTimeToStr(Now)); end; try ITARanking.Generate(fSession, fRun); Log(cLogId, 'ITA ranking generated. Generating other rankings'); for i := 1 to pred(Rankings.Count) do begin CurRanking := Rankings[i]; if CurRanking.fSuper = nil then CurRanking.fSuper := ITARanking; CurRanking.Generate(fSession, fRun); end; except on e : Exception do Log(cLogId, 'Exception "' + e.Message + '" generated while writing rankings at ' + DateTimeToStr(Now)); else Log(cLogId, 'Unknown exception generated while while writing rankings at ' + DateTimeToStr(Now)); end; Log(cLogId, 'Rankings generated. Now generating structure and version information'); if fSession.SetCurrentKey('Root/Rankings') then begin rankstructure := GenerateRankingStructure; fSession.WriteString('Structure', rankstructure); fSession.WriteInteger('Run', fRun); fSession.WriteString('DefaultRankingId', 'ITA'); Log(cLogId, 'Structure and version information generated'); end else Log(cLogId, 'Unable to set ' + 'Root/Rankings' + ' key in order to generate structure and version information'); Log(cLogId, 'Generating player curricula'); try for i := 0 to pred(PlayerCurricula.Count) do TPlayerCurriculum(PlayerCurricula[i]).WriteToDataBase(fSession, fRun); Log(cLogId, 'Player curricula generated at ' + DateTimeToStr(Now)); except on e : Exception do Log(cLogId, 'Exception "' + e.Message + '" generated while writing player curricula at ' + DateTimeToStr(Now)); end; for i := 0 to pred(PlayerCurricula.Count) do TPlayerCurriculum(PlayerCurricula[i]).Free; finally PlayerCurricula.Free; end; end else Log(cLogId, 'Key ' + basekey + ' not found, or unable to be set'); finally Unparented.Free; end; for i := 0 to pred(Rankings.Count) do TRanking(Rankings[i]).Free; finally Rankings.Free; end; finally WorldRankings.Free; end; finally Worlds.Free; end; finally Areas.Free; end; Log(cLogId, 'Rankings succesfully generated at ' + DateTimeToStr(Now)); except on e : Exception do Log(cLogId, 'Exception "' + e.Message + '" generated while generating rankings at ' + DateTimeToStr(Now)); else Log(cLogId, 'Unknown exception generated while while generating rankings at ' + DateTimeToStr(Now)); end; end; end.
unit UPascalCoinSafeBox; interface uses Classes, UOrderedBlockAccountList, URawBytes, UOrderedRawList, UThread, UAccountKey, UBlockAccount, UAccountInfo, UAccountUpdateStyle, UOperationBlock, UPCSafeBoxHeader, UAccount; type TPCSafeBox = Class private FBlockAccountsList : TList; // Used when has no PreviousSafebox FModifiedBlocksSeparatedChain : TOrderedBlockAccountList; // Used when has PreviousSafebox (Used if we are on a Separated chain) // FListOfOrderedAccountKeysList : TList; FBufferBlocksHash: TRawBytes; FOrderedByName : TOrderedRawList; FTotalBalance: Int64; FSafeBoxHash : TRawBytes; FLock: TPCCriticalSection; // Thread safe FWorkSum : UInt64; FCurrentProtocol: Integer; // Snapshots utility new on V3 FSnapshots : TList; // Will save a Snapshots lists in order to rollback Safebox to a previous block state FMaxSafeboxSnapshots : Integer; // To be added to next snapshot FModifiedBlocksPreviousState : TOrderedBlockAccountList; FModifiedBlocksFinalState : TOrderedBlockAccountList; FAddedNamesSincePreviousSafebox : TOrderedRawList; FDeletedNamesSincePreviousSafebox : TOrderedRawList; // Is capturing data from a snapshot? FPreviousSafeBox : TPCSafeBox; // PreviousSafebox is the Safebox with snpashots where this safebox searches FPreviousSafeboxOriginBlock : Integer; // Has chains based on this Safebox? FSubChains : TList; // Will link to subchains (other safebox) based on a current snapshot of this safebox // Procedure AccountKeyListAddAccounts(Const AccountKey : TAccountKey; const accounts : Array of Cardinal); Procedure AccountKeyListRemoveAccount(Const AccountKey : TAccountKey; const accounts : Array of Cardinal); // V3 procedure SearchBlockWhenOnSeparatedChain(blockNumber : Cardinal; out blockAccount : TBlockAccount); protected FTotalFee: Int64; public Constructor Create; Destructor Destroy; override; procedure SetToPrevious(APreviousSafeBox : TPCSafeBox; StartBlock : Cardinal); procedure CommitToPrevious; procedure RollBackToSnapshot(snapshotBlock : Cardinal); function AccountsCount: Integer; Function BlocksCount : Integer; Procedure CopyFrom(accounts : TPCSafeBox); Class Function CalcBlockHash(const block : TBlockAccount; useProtocol2Method : Boolean):TRawBytes; Class Function BlockAccountToText(Const block : TBlockAccount):AnsiString; Function LoadSafeBoxFromStream(Stream : TStream; checkAll : Boolean; var LastReadBlock : TBlockAccount; var errors : AnsiString) : Boolean; Class Function LoadSafeBoxStreamHeader(Stream : TStream; var sbHeader : TPCSafeBoxHeader) : Boolean; Class Function SaveSafeBoxStreamHeader(Stream : TStream; protocol : Word; OffsetStartBlock, OffsetEndBlock, CurrentSafeBoxBlocksCount : Cardinal) : Boolean; Class Function MustSafeBoxBeSaved(BlocksCount : Cardinal) : Boolean; Procedure SaveSafeBoxBlockToAStream(Stream : TStream; nBlock : Cardinal); Procedure SaveSafeBoxToAStream(Stream : TStream; FromBlock, ToBlock : Cardinal); class Function CopySafeBoxStream(Source,Dest : TStream; FromBlock, ToBlock : Cardinal; var errors : AnsiString) : Boolean; class Function ConcatSafeBoxStream(Source1, Source2, Dest : TStream; var errors : AnsiString) : Boolean; class function ValidAccountName(const new_name : TRawBytes; var errors : AnsiString) : Boolean; Function IsValidNewOperationsBlock(Const newOperationBlock : TOperationBlock; checkSafeBoxHash : Boolean; var errors : AnsiString) : Boolean; class Function IsValidOperationBlock(Const newOperationBlock : TOperationBlock; var errors : AnsiString) : Boolean; Function GetActualTargetHash(protocolVersion : Word): TRawBytes; Function GetActualCompactTargetHash(protocolVersion : Word): Cardinal; Function FindAccountByName(aName : AnsiString) : Integer; Procedure Clear; Function Account(account_number : Cardinal) : TAccount; Function Block(block_number : Cardinal) : TBlockAccount; Function CalcSafeBoxHash : TRawBytes; Function CalcBlockHashRateInKhs(block_number : Cardinal; Previous_blocks_average : Cardinal) : Int64; Property TotalBalance : Int64 read FTotalBalance; // Skybuck: property added for TotalFee to make it accessable to TPCSafeBoxTransaction Property TotalFee : int64 read FTotalFee; Procedure StartThreadSafe; Procedure EndThreadSave; Property SafeBoxHash : TRawBytes read FSafeBoxHash; Property WorkSum : UInt64 read FWorkSum; Property CurrentProtocol : Integer read FCurrentProtocol; function CanUpgradeToProtocol(newProtocolVersion : Word) : Boolean; procedure CheckMemory; Property PreviousSafeboxOriginBlock : Integer Read FPreviousSafeboxOriginBlock; Function GetMinimumAvailableSnapshotBlock : Integer; Function HasSnapshotForBlock(block_number : Cardinal) : Boolean; // Skybuck: moved to here to make it accessable to TPCSafeBoxTransaction Procedure UpdateAccount(account_number : Cardinal; const newAccountInfo: TAccountInfo; const newName : TRawBytes; newType : Word; newBalance: UInt64; newN_operation: Cardinal; accountUpdateStyle : TAccountUpdateStyle; newUpdated_block, newPrevious_Updated_block : Cardinal); Function AddNew(Const blockChain : TOperationBlock) : TBlockAccount; function DoUpgradeToProtocol2 : Boolean; function DoUpgradeToProtocol3 : Boolean; // Skybuck: added this to make UOrderedAccountKeysList.pas work. property ListOfOrderedAccountKeysList : TList read FListOfOrderedAccountKeysList; End; function Check_Safebox_Names_Consistency(sb : TPCSafeBox; const title :String; var errors : AnsiString) : Boolean; Procedure Check_Safebox_Integrity(sb : TPCSafebox; title: String); var PascalCoinSafeBox : TPCSafeBox; implementation uses UConst, SysUtils, UMemAccount, UPBlockAccount, UTickCount, UPlatform, ULog, UAccountComp, UBaseType, UPascalCoinProtocol, UAccountState, UMemBlockAccount, UOrderedAccountKeysList, UCrypto, UBigNum, UStreamOp, UCardinalsArray, UAccountKeyStorage; {$include MemoryReductionSettings.inc} { This function is for testing purpose only. Will check if Account Names are well assigned and stored } function Check_Safebox_Names_Consistency(sb : TPCSafeBox; const title :String; var errors : AnsiString) : Boolean; Var i,j : Integer; acc : TAccount; auxs : TRawBytes; tc : TTickCount; Begin tc := TPlatform.GetTickCount; Try errors := ''; Result := True; for i:=0 to sb.AccountsCount-1 do begin acc := sb.Account(i); If acc.name<>'' then begin j := sb.FindAccountByName(acc.name); If j<>i then begin errors :=errors + Format(' > Account %d name:%s found at:%d<>Theorical:%d',[acc.account,acc.name,j,i]); end; end; end; // Reverse for i:=0 to sb.FOrderedByName.Count-1 do begin j := sb.FOrderedByName.GetTag(i); auxs := sb.FOrderedByName.Get(i); acc := sb.Account(j); If (auxs<>acc.name) then begin errors :=errors + Format(' > Name:%s at thorical account %d not valid (found %s)',[auxs,j,acc.name]); end; end; If (errors<>'') then begin errors := title+' '+errors; Result := False; TLog.NewLog(lterror,'Check_Safebox_Names_Consistency',errors); end; finally TLog.NewLog(ltDebug,'Check_Safebox_Names_Consistency','Used time '+IntToStr(TPlatform.GetElapsedMilliseconds(tc))+' milliseconds'); end; end; { This function is for testing purpose only. Will check if Accounts are Ok } Procedure Check_Safebox_Integrity(sb : TPCSafebox; title: String); var i,j,maxBlock : Integer; bl_my, bl_modified : TBlockAccount; auxH : TRawBytes; Begin For i:=0 to sb.FModifiedBlocksFinalState.Count-1 do begin bl_modified := sb.FModifiedBlocksFinalState.Get(i); bl_my := sb.Block(bl_modified.blockchainInfo.block); If Not TAccountComp.EqualBlockAccounts(bl_my,bl_modified) then begin Raise Exception.Create(Format('%s Integrity on modified (i)=%d for block number:%d',[title, i,bl_my.blockchainInfo.block])); end; If TBaseType.BinStrComp( sb.CalcBlockHash(bl_modified,sb.FCurrentProtocol>=CT_PROTOCOL_2), bl_modified.block_hash)<>0 then begin Raise Exception.Create(Format('%s Integrity on block hash (i)=%d for block number:%d',[title, i,bl_my.blockchainInfo.block])); end; end; auxH := ''; maxBlock := sb.BlocksCount; for i:=0 to sb.BlocksCount-1 do begin bl_my := sb.Block(i); for j:=Low(bl_my.accounts) to High(bl_my.accounts) do begin If maxBlock < (bl_my.accounts[j].updated_block) then begin Raise Exception.Create(Format('%s Integrity on (i)=%d for block account:%d updated on %d > maxBlock %d',[title, i,bl_my.accounts[j].account,bl_my.accounts[j].updated_block,maxBlock])); end; end; auxH := auxH + bl_my.block_hash; end; If TBaseType.BinStrComp(sb.FBufferBlocksHash,auxH)<>0 then begin Raise Exception.Create(Format('%s Integrity different Buffer Block Hash',[title])); end; end; { TPCSafeBox } Type TSafeboxSnapshot = Record nBlockNumber : Cardinal; oldBlocks : TOrderedBlockAccountList; // Saves old blocks values on modified blocks newBlocks : TOrderedBlockAccountList; // Saves final blocks values on modified blocks namesDeleted : TOrderedRawList; namesAdded : TOrderedRawList; oldBufferBlocksHash: TRawBytes; oldTotalBalance: Int64; oldTotalFee: Int64; oldSafeBoxHash : TRawBytes; oldWorkSum : UInt64; oldCurrentProtocol: Integer; end; PSafeboxSnapshot = ^TSafeboxSnapshot; Const CT_TSafeboxSnapshot_NUL : TSafeboxSnapshot = (nBlockNumber : 0; oldBlocks : Nil; newBlocks : Nil; namesDeleted : Nil; namesAdded : Nil;oldBufferBlocksHash:'';oldTotalBalance:0;oldTotalFee:0;oldSafeBoxHash:'';oldWorkSum:0;oldCurrentProtocol:0); function TPCSafeBox.Account(account_number: Cardinal): TAccount; var iBlock : Integer; blockAccount : TBlockAccount; begin StartThreadSafe; try iBlock:=(Integer(account_number) DIV CT_AccountsPerBlock); If (Assigned(FPreviousSafeBox)) then begin SearchBlockWhenOnSeparatedChain(iBlock,blockAccount); Result := blockAccount.accounts[account_number MOD CT_AccountsPerBlock]; end else begin if (iBlock<0) Or (iBlock>=FBlockAccountsList.Count) then raise Exception.Create('Invalid account: '+IntToStr(account_number)); ToTAccount(PBlockAccount(FBlockAccountsList.Items[iBlock])^.accounts[account_number MOD CT_AccountsPerBlock],account_number,Result); end; finally EndThreadSave; end; end; function TPCSafeBox.AddNew(const blockChain: TOperationBlock): TBlockAccount; { PIP-0011 (dev reward) workflow: (** Only on V3 protocol **) - Account 0 is Master Account - Account 0 type field (2 bytes: 0..65535) will store a Value, this value is the "dev account" - The "dev account" can be any account between 0..65535, and can be changed at any time. - The 80% of the blockChain.reward + miner fees will be added on first mined account (like V1 and V2) - The miner will also receive ownership of first four accounts (Before, all accounts where for miner) - The "dev account" will receive the last created account ownership and the 20% of the blockChain.reward - Example: - Account(0).type = 12345 <-- dev account = 12345 - blockChain.block = 234567 <-- New block height. Accounts generated from 1172835..1172839 - blockChain.reward = 50 PASC - blockChain.fee = 0.9876 PASC - blockChain.account_key = Miner public key - New generated accounts: - [0] = 1172835 balance: 40.9876 owner: Miner - [1] = 1172836 balance: 0 owner: Miner - [2] = 1172837 balance: 0 owner: Miner - [3] = 1172838 balance: 0 owner: Miner - [4] = 1172839 balance: 10.0000 owner: Account 12345 owner, same owner than "dev account" - Safebox balance increase: 50 PASC } var i, base_addr : Integer; Pblock : PBlockAccount; accs_miner, accs_dev : Array of cardinal; Psnapshot : PSafeboxSnapshot; // account_dev, account_0 : TAccount; // acc_0_miner_reward,acc_4_dev_reward : Int64; acc_4_for_dev : Boolean; begin Result := CT_BlockAccount_NUL; Result.blockchainInfo := blockChain; If blockChain.block<>BlocksCount then Raise Exception.Create(Format('ERROR DEV 20170427-2 blockchain.block:%d <> BlocksCount:%d',[blockChain.block,BlocksCount])); // wow wrong calcultions detected WTF ! let's exploit the fuck out of this ! ;) :) // let's first verify that these bugs exist in original distribution from the internet ! ;) If blockChain.fee<>FTotalFee then Raise Exception.Create(Format('ERROR DEV 20170427-3 blockchain.fee:%d <> Safebox.TotalFee:%d',[blockChain.fee,FTotalFee])); TPascalCoinProtocol.GetRewardDistributionForNewBlock(blockChain,acc_0_miner_reward,acc_4_dev_reward,acc_4_for_dev); account_dev := CT_Account_NUL; If (acc_4_for_dev) then begin account_0 := Account(0); // Account 0 is master account, will store "dev account" in type field If (AccountsCount>account_0.account_type) then begin account_dev := Account(account_0.account_type); end else account_dev := account_0; end; base_addr := BlocksCount * CT_AccountsPerBlock; setlength(accs_miner,0); setlength(accs_dev,0); for i := Low(Result.accounts) to High(Result.accounts) do begin Result.accounts[i] := CT_Account_NUL; Result.accounts[i].account := base_addr + i; Result.accounts[i].accountInfo.state := as_Normal; Result.accounts[i].updated_block := BlocksCount; Result.accounts[i].n_operation := 0; if (acc_4_for_dev) And (i=CT_AccountsPerBlock-1) then begin Result.accounts[i].accountInfo.accountKey := account_dev.accountInfo.accountKey; SetLength(accs_dev,length(accs_dev)+1); accs_dev[High(accs_dev)] := base_addr + i; Result.accounts[i].balance := acc_4_dev_reward; end else begin Result.accounts[i].accountInfo.accountKey := blockChain.account_key; SetLength(accs_miner,length(accs_miner)+1); accs_miner[High(accs_miner)] := base_addr + i; if i=Low(Result.accounts) then begin // Only first account wins the reward + fee Result.accounts[i].balance := acc_0_miner_reward; end else begin end; end; end; FWorkSum := FWorkSum + Result.blockchainInfo.compact_target; Result.AccumulatedWork := FWorkSum; // Calc block hash Result.block_hash := CalcBlockHash(Result,FCurrentProtocol >= CT_PROTOCOL_2); If Assigned(FPreviousSafeBox) then begin FModifiedBlocksSeparatedChain.Add(Result); end else begin New(Pblock); ToTMemBlockAccount(Result,Pblock^); FBlockAccountsList.Add(Pblock); end; FBufferBlocksHash := FBufferBlocksHash+Result.block_hash; FTotalBalance := FTotalBalance + (blockChain.reward + blockChain.fee); FTotalFee := FTotalFee - blockChain.fee; If (length(accs_miner)>0) then begin AccountKeyListAddAccounts(blockChain.account_key,accs_miner); end; If (length(accs_dev)>0) then begin AccountKeyListAddAccounts(account_dev.accountInfo.accountKey,accs_dev); end; // Calculating new value of safebox FSafeBoxHash := CalcSafeBoxHash; // Save previous snapshot with current state If (FMaxSafeboxSnapshots>0) then begin new(Psnapshot); Psnapshot^:=CT_TSafeboxSnapshot_NUL; Psnapshot^.nBlockNumber:=blockChain.block; Psnapshot^.oldBlocks := FModifiedBlocksPreviousState; Psnapshot^.newBlocks := FModifiedBlocksFinalState; Psnapshot^.namesDeleted := FDeletedNamesSincePreviousSafebox; Psnapshot^.namesAdded := FAddedNamesSincePreviousSafebox; Psnapshot^.oldBufferBlocksHash:=FBufferBlocksHash; Psnapshot^.oldTotalBalance:=FTotalBalance; Psnapshot^.oldTotalFee:=FTotalFee; Psnapshot^.oldSafeBoxHash := FSafeBoxHash; Psnapshot^.oldWorkSum := FWorkSum; Psnapshot^.oldCurrentProtocol:= FCurrentProtocol; FSnapshots.Add(Psnapshot); FModifiedBlocksPreviousState := TOrderedBlockAccountList.Create; FModifiedBlocksFinalState := TOrderedBlockAccountList.Create; FAddedNamesSincePreviousSafebox := TOrderedRawList.Create; FDeletedNamesSincePreviousSafebox := TOrderedRawList.Create; // Remove old snapshots! If (FSubChains.Count=0) And (Not Assigned(FPreviousSafeBox)) then begin // Remove ONLY if there is no subchain based on my snapshots! While (FSnapshots.Count>FMaxSafeboxSnapshots) do begin Psnapshot := FSnapshots[0]; TLog.NewLog(ltdebug,Classname,Format('Deleting snapshot for block %d',[Psnapshot^.nBlockNumber])); FSnapshots.Delete(0); FreeAndNil( Psnapshot.oldBlocks ); FreeAndNil( Psnapshot.newBlocks ); FreeAndNil( Psnapshot.namesAdded ); FreeAndNil( Psnapshot.namesDeleted ); Psnapshot^.oldBufferBlocksHash:=''; Psnapshot^.oldSafeBoxHash:=''; Dispose(Psnapshot); end; end; end else begin FModifiedBlocksPreviousState.Clear; FModifiedBlocksFinalState.Clear; FAddedNamesSincePreviousSafebox.Clear; FDeletedNamesSincePreviousSafebox.Clear; end; end; procedure TPCSafeBox.AccountKeyListAddAccounts(const AccountKey: TAccountKey; const accounts: array of Cardinal); Var i : Integer; begin for i := 0 to FListOfOrderedAccountKeysList.count-1 do begin TOrderedAccountKeysList( FListOfOrderedAccountKeysList[i] ).AddAccounts(AccountKey,accounts); end; end; procedure TPCSafeBox.AccountKeyListRemoveAccount(const AccountKey: TAccountKey; const accounts: array of Cardinal); Var i : Integer; begin for i := 0 to FListOfOrderedAccountKeysList.count-1 do begin TOrderedAccountKeysList( FListOfOrderedAccountKeysList[i] ).RemoveAccounts(AccountKey,accounts); end; end; function TPCSafeBox.AccountsCount: Integer; begin StartThreadSafe; try Result := BlocksCount * CT_AccountsPerBlock; finally EndThreadSave; end; end; function TPCSafeBox.Block(block_number: Cardinal): TBlockAccount; begin StartThreadSafe; try If (Assigned(FPreviousSafeBox)) then begin if (block_number<0) Or (block_number>=BlocksCount) then raise Exception.Create('Invalid block number for chain: '+inttostr(block_number)+' max: '+IntToStr(BlocksCount-1)); SearchBlockWhenOnSeparatedChain(block_number,Result); end else begin if (block_number<0) Or (block_number>=FBlockAccountsList.Count) then raise Exception.Create('Invalid block number: '+inttostr(block_number)+' max: '+IntToStr(FBlockAccountsList.Count-1)); ToTBlockAccount(PBlockAccount(FBlockAccountsList.Items[block_number])^,block_number,Result); end; finally EndThreadSave; end; end; class function TPCSafeBox.BlockAccountToText(const block: TBlockAccount): AnsiString; begin Result := Format('Block:%d Timestamp:%d BlockHash:%s', [block.blockchainInfo.block, block.blockchainInfo.timestamp, TCrypto.ToHexaString(block.block_hash)]); end; function TPCSafeBox.BlocksCount: Integer; begin StartThreadSafe; try If Assigned(FPreviousSafeBox) then begin Result := FModifiedBlocksSeparatedChain.MaxBlockNumber+1; If (Result<=FPreviousSafeboxOriginBlock) then begin Result := FPreviousSafeboxOriginBlock+1; end; end else begin Result := FBlockAccountsList.Count; end; finally EndThreadSave; end; end; class function TPCSafeBox.CalcBlockHash(const block : TBlockAccount; useProtocol2Method : Boolean): TRawBytes; // Protocol v2 update: // In order to store values to generate PoW and allow Safebox checkpointing, we // store info about TOperationBlock on each row and use it to obtain blockchash Var raw: TRawBytes; ms : TMemoryStream; i : Integer; begin ms := TMemoryStream.Create; try If (Not useProtocol2Method) then begin // PROTOCOL 1 BlockHash calculation ms.Write(block.blockchainInfo.block,4); // Little endian for i := Low(block.accounts) to High(block.accounts) do begin ms.Write(block.accounts[i].account,4); // Little endian raw := TAccountComp.AccountInfo2RawString(block.accounts[i].accountInfo); ms.WriteBuffer(raw[1],length(raw)); // Raw bytes ms.Write(block.accounts[i].balance,SizeOf(Uint64)); // Little endian ms.Write(block.accounts[i].updated_block,4); // Little endian ms.Write(block.accounts[i].n_operation,4); // Little endian end; ms.Write(block.blockchainInfo.timestamp,4); // Little endian end else begin // PROTOCOL 2 BlockHash calculation TAccountComp.SaveTOperationBlockToStream(ms,block.blockchainInfo); for i := Low(block.accounts) to High(block.accounts) do begin ms.Write(block.accounts[i].account,4); // Little endian raw := TAccountComp.AccountInfo2RawString(block.accounts[i].accountInfo); ms.WriteBuffer(raw[1],length(raw)); // Raw bytes ms.Write(block.accounts[i].balance,SizeOf(Uint64)); // Little endian ms.Write(block.accounts[i].updated_block,4); // Little endian ms.Write(block.accounts[i].n_operation,4); // Little endian // Use new Protocol 2 fields If length(block.accounts[i].name)>0 then begin ms.WriteBuffer(block.accounts[i].name[1],length(block.accounts[i].name)); end; ms.Write(block.accounts[i].account_type,2); end; ms.Write(block.AccumulatedWork,SizeOf(block.AccumulatedWork)); end; Result := TCrypto.DoSha256(ms.Memory,ms.Size) finally ms.Free; end; end; function TPCSafeBox.CalcBlockHashRateInKhs(block_number: Cardinal; Previous_blocks_average: Cardinal): Int64; Var c,t : Cardinal; t_sum : Extended; bn, bn_sum : TBigNum; begin FLock.Acquire; Try bn_sum := TBigNum.Create; try if (block_number=0) then begin Result := 1; exit; end; if (block_number<0) Or (block_number>=FBlockAccountsList.Count) then raise Exception.Create('Invalid block number: '+inttostr(block_number)); if (Previous_blocks_average<=0) then raise Exception.Create('Dev error 20161016-1'); if (Previous_blocks_average>block_number) then Previous_blocks_average := block_number; // c := (block_number - Previous_blocks_average)+1; t_sum := 0; while (c<=block_number) do begin bn := TBigNum.TargetToHashRate(PBlockAccount(FBlockAccountsList.Items[c])^.blockchainInfo.compact_target); try bn_sum.Add(bn); finally bn.Free; end; t_sum := t_sum + (PBlockAccount(FBlockAccountsList.Items[c])^.blockchainInfo.timestamp - PBlockAccount(FBlockAccountsList.Items[c-1])^.blockchainInfo.timestamp); inc(c); end; bn_sum.Divide(Previous_blocks_average); // Obtain target average t_sum := t_sum / Previous_blocks_average; // time average t := Round(t_sum); if (t<>0) then begin bn_sum.Divide(t); end; Result := bn_sum.Divide(1024).Value; // Value in Kh/s Finally bn_sum.Free; end; Finally FLock.Release; End; end; function TPCSafeBox.CalcSafeBoxHash: TRawBytes; begin StartThreadSafe; try // If No buffer to hash is because it's firts block... so use Genesis: CT_Genesis_Magic_String_For_Old_Block_Hash if (FBufferBlocksHash='') then Result := TCrypto.DoSha256(CT_Genesis_Magic_String_For_Old_Block_Hash) else Result := TCrypto.DoSha256(FBufferBlocksHash); finally EndThreadSave; end; end; function TPCSafeBox.CanUpgradeToProtocol(newProtocolVersion : Word) : Boolean; begin If (newProtocolVersion=CT_PROTOCOL_2) then begin Result := (FCurrentProtocol<CT_PROTOCOL_2) and (BlocksCount >= CT_Protocol_Upgrade_v2_MinBlock); end else if (newProtocolVersion=CT_PROTOCOL_3) then begin Result := (FCurrentProtocol=CT_PROTOCOL_2) And (BlocksCount >= CT_Protocol_Upgrade_v3_MinBlock); end else Result := False; end; procedure TPCSafeBox.CheckMemory; { Note about Free Pascal compiler When compiling using Delphi it's memory manager more is efficient and does not increase, but When compiling using Free Pascal Compiler, is a good solution to "force" generate a new SafeBox in order to free memory not used. Tested with FPC 3.0 } {$IFDEF FPC} Var sb : TPCSafeBox; tc : TTickCount; auxSnapshotsList : TList; i : Integer; {$ENDIF} begin {$IFDEF FPC} StartThreadSafe; try If Assigned(FPreviousSafeBox) then Exit; // When loading from snapshot, does not allow to check memory! tc := TPlatform.GetTickCount; sb := TPCSafeBox.Create; try // auxSnapshotsList := TList.Create; Try // Save snapshots: auxSnapshotsList.Assign(FSnapshots); FSnapshots.Clear; // sb.CopyFrom(Self); Self.Clear; Self.CopyFrom(sb); // Restore snapshots: FSnapshots.Assign(auxSnapshotsList); // Clear changes to do not fire key activity for i := 0 to FListOfOrderedAccountKeysList.count-1 do begin TOrderedAccountKeysList( FListOfOrderedAccountKeysList[i] ).ClearAccountKeyChanges; end; finally auxSnapshotsList.Free; end; finally sb.Free; end; TLog.NewLog(ltDebug,Classname,'Checked memory '+IntToStr(TPlatform.GetElapsedMilliseconds(tc))+' milliseconds'); finally EndThreadSave; end; {$ENDIF} end; function TPCSafeBox.GetMinimumAvailableSnapshotBlock: Integer; Var Pss : PSafeboxSnapshot; begin Result := -1; StartThreadSafe; Try If (FSnapshots.Count>0) then begin Pss := FSnapshots[0]; Result := Pss^.nBlockNumber; end; finally EndThreadSave; end; end; function TPCSafeBox.HasSnapshotForBlock(block_number: Cardinal): Boolean; Var Pss : PSafeboxSnapshot; i : Integer; begin Result := False; StartThreadSafe; Try i := FSnapshots.Count-1; while (i>=0) And (PSafeboxSnapshot( FSnapshots[i] )^.nBlockNumber<>block_number) do dec(i); Result := (i>=0); finally EndThreadSave; end; end; procedure TPCSafeBox.Clear; Var i : Integer; P : PBlockAccount; Psnapshot : PSafeboxSnapshot; begin StartThreadSafe; Try for i := 0 to FBlockAccountsList.Count - 1 do begin P := FBlockAccountsList.Items[i]; Dispose(P); end; for i := 0 to FSnapshots.Count-1 do begin Psnapshot := (Fsnapshots[i]); FreeAndNil(Psnapshot^.oldBlocks); FreeAndNil(Psnapshot^.newBlocks); FreeAndNil(Psnapshot^.namesAdded); FreeAndNil(Psnapshot^.namesDeleted); Psnapshot^.oldBufferBlocksHash:=''; Psnapshot^.oldSafeBoxHash:=''; Dispose(Psnapshot); end; FSnapshots.Clear; FOrderedByName.Clear; FBlockAccountsList.Clear; For i:=0 to FListOfOrderedAccountKeysList.count-1 do begin TOrderedAccountKeysList( FListOfOrderedAccountKeysList[i] ).ClearAccounts(False); end; FBufferBlocksHash := ''; FTotalBalance := 0; FTotalFee := 0; FSafeBoxHash := CalcSafeBoxHash; FWorkSum := 0; FCurrentProtocol := CT_PROTOCOL_1; FModifiedBlocksSeparatedChain.Clear; FModifiedBlocksFinalState.Clear; FModifiedBlocksPreviousState.Clear; FAddedNamesSincePreviousSafebox.Clear; FDeletedNamesSincePreviousSafebox.Clear; Finally EndThreadSave; end; end; procedure TPCSafeBox.CopyFrom(accounts: TPCSafeBox); Var i,j : Cardinal; P : PBlockAccount; BA : TBlockAccount; begin StartThreadSafe; Try accounts.StartThreadSafe; try if accounts=Self then exit; If (Assigned(FPreviousSafeBox)) then begin Raise Exception.Create('Safebox is a separated chain. Cannot copy from other Safebox'); end; If (Assigned(accounts.FPreviousSafeBox)) then begin Raise Exception.Create('Cannot copy from a separated chain Safebox'); end; Clear; if accounts.BlocksCount>0 then begin FBlockAccountsList.Capacity:=accounts.BlocksCount; for i := 0 to accounts.BlocksCount - 1 do begin BA := accounts.Block(i); New(P); ToTMemBlockAccount(BA,P^); FBlockAccountsList.Add(P); for j := Low(BA.accounts) to High(BA.accounts) do begin If (BA.accounts[j].name<>'') then FOrderedByName.Add(BA.accounts[j].name,BA.accounts[j].account); AccountKeyListAddAccounts(BA.accounts[j].accountInfo.accountKey,[BA.accounts[j].account]); end; end; end; FTotalBalance := accounts.TotalBalance; FTotalFee := accounts.FTotalFee; FBufferBlocksHash := accounts.FBufferBlocksHash; FSafeBoxHash := accounts.FSafeBoxHash; FWorkSum := accounts.FWorkSum; FCurrentProtocol := accounts.FCurrentProtocol; finally accounts.EndThreadSave; end; finally EndThreadSave; end; end; constructor TPCSafeBox.Create; begin FMaxSafeboxSnapshots:=CT_DEFAULT_MaxSafeboxSnapshots; FLock := TPCCriticalSection.Create('TPCSafeBox_Lock'); FBlockAccountsList := TList.Create; FListOfOrderedAccountKeysList := TList.Create; FCurrentProtocol := CT_PROTOCOL_1; FOrderedByName := TOrderedRawList.Create; FSnapshots := TList.Create; FPreviousSafeBox := Nil; FPreviousSafeboxOriginBlock := -1; FModifiedBlocksSeparatedChain := TOrderedBlockAccountList.Create; FModifiedBlocksPreviousState := TOrderedBlockAccountList.Create; FModifiedBlocksFinalState := TOrderedBlockAccountList.Create; FAddedNamesSincePreviousSafebox := TOrderedRawList.Create; FDeletedNamesSincePreviousSafebox := TOrderedRawList.Create; FSubChains := TList.Create; Clear; end; destructor TPCSafeBox.Destroy; Var i : Integer; begin Clear; // Skybuck: this should probably be done inside TOrderedAccountKeysList or so, but strange to put this here. // going to add a little method for this just in case for i := 0 to FListOfOrderedAccountKeysList.Count - 1 do begin // TOrderedAccountKeysList( FListOfOrderedAccountKeysList[i] ).FAccountList := Nil; TOrderedAccountKeysList( FListOfOrderedAccountKeysList[i] ).NillifyAccountList; end; FreeAndNil(FBlockAccountsList); FreeAndNil(FListOfOrderedAccountKeysList); FreeAndNil(FLock); FreeAndNil(FOrderedByName); FreeAndNil(FSnapshots); FreeAndNil(FModifiedBlocksSeparatedChain); FreeAndNil(FModifiedBlocksPreviousState); FreeAndNil(FModifiedBlocksFinalState); FreeAndNil(FAddedNamesSincePreviousSafebox); FreeAndNil(FDeletedNamesSincePreviousSafebox); FreeAndNil(FSubChains); If Assigned(FPreviousSafeBox) then begin FPreviousSafeBox.FSubChains.Remove(Self); // Remove from current snapshot FPreviousSafeBox := Nil; FPreviousSafeboxOriginBlock:=-1; end; inherited; end; procedure TPCSafeBox.SetToPrevious(APreviousSafeBox: TPCSafeBox; StartBlock: Cardinal); Var i : Integer; Psnapshot : PSafeboxSnapshot; begin StartThreadSafe; Try Clear; If Assigned(FPreviousSafeBox) then begin FPreviousSafeBox.FSubChains.Remove(Self); // Remove from current snapshot FPreviousSafeBox := Nil; FPreviousSafeboxOriginBlock:=-1; end; If Assigned(APreviousSafeBox) then begin APreviousSafeBox.StartThreadSafe; Try If (APreviousSafeBox = Self) then Raise Exception.Create('Invalid previous'); If Assigned(APreviousSafebox.FPreviousSafeBox) then Raise Exception.Create('Previous safebox is based on a snapshot too'); // Limitation i := APreviousSafeBox.FSnapshots.Count-1; while (i>=0) And (PSafeboxSnapshot( APreviousSafeBox.FSnapshots[i] )^.nBlockNumber<>StartBlock) do dec(i); if (i<0) then begin Raise Exception.Create('Previous Safebox does not contain snapshot of block '+IntToStr(StartBlock)); end; Psnapshot:=PSafeboxSnapshot( APreviousSafeBox.FSnapshots[i] ); FPreviousSafeBox := APreviousSafeBox; FPreviousSafeboxOriginBlock:=StartBlock; // FPreviousSafeBox.FSubChains.Add(Self); // FBufferBlocksHash := Psnapshot^.oldBufferBlocksHash; FTotalBalance := Psnapshot^.oldTotalBalance; FTotalFee := Psnapshot^.oldTotalFee; FSafeBoxHash := Psnapshot^.oldSafeBoxHash; FWorkSum := Psnapshot^.oldWorkSum; FCurrentProtocol := Psnapshot^.oldCurrentProtocol; finally APreviousSafeBox.EndThreadSave; end; end else begin end; finally EndThreadSave; end; end; procedure TPCSafeBox.CommitToPrevious; procedure RedoModifiedBlocks(const modifiedblocks : TOrderedBlockAccountList); Var iBlock,j : Integer; blockAccount : TBlockAccount; begin // modifiedBlocks is sorted in ASCENDING order, will create a new block on FPreviousSafeBox when needed For iBlock := 0 to modifiedBlocks.Count-1 do begin blockAccount := modifiedBlocks.Get(iBlock); // Set each account to previous value: for j:=Low(blockAccount.accounts) to High(blockAccount.accounts) do begin FPreviousSafeBox.UpdateAccount(blockAccount.accounts[j].account, blockAccount.accounts[j].accountInfo, blockAccount.accounts[j].name, blockAccount.accounts[j].account_type, blockAccount.accounts[j].balance, blockAccount.accounts[j].n_operation, aus_commiting_from_otherchain, blockAccount.accounts[j].updated_block, blockAccount.accounts[j].previous_updated_block ); end; end; end; Procedure RedoAddedDeletedNames(AddedNamesList,DeletedNamesList : TOrderedRawList); Var i : Integer; Begin // Start deleting: For i:=0 to DeletedNamesList.Count-1 do begin FPreviousSafebox.FOrderedByName.Remove(DeletedNamesList.Get(i)); end; // Finally adding For i:=0 to AddedNamesList.Count-1 do begin FPreviousSafebox.FOrderedByName.Add(AddedNamesList.Get(i),AddedNamesList.GetTag(i)); end; FPreviousSafebox.FAddedNamesSincePreviousSafebox.CopyFrom(AddedNamesList); FPreviousSafebox.FDeletedNamesSincePreviousSafebox.CopyFrom(DeletedNamesList); end; procedure RedoSnapshot(Psnapshot : PSafeboxSnapshot); Begin RedoModifiedBlocks(Psnapshot^.newBlocks); // RedoAddedDeletedNames(Psnapshot^.namesAdded,Psnapshot^.namesDeleted); // FPreviousSafeBox.AddNew(Block(Psnapshot^.nBlockNumber).blockchainInfo); end; Var errors : AnsiString; i : Integer; Pss : PSafeboxSnapshot; begin If Not Assigned(FPreviousSafeBox) then Raise Exception.Create('Previous not assigned'); StartThreadSafe; Try FPreviousSafeBox.StartThreadSafe; Try { Process is: - Set Previous to snapshot state - for each snapshot: - update modified blocks - update Names lists with changes on snapshot - create a new block stored in snapshot } TLog.NewLog(ltdebug,ClassName,Format('Start CommitToPrevious - Rolling back from block %d to %d',[FPreviousSafeBox.BlocksCount-1,FPreviousSafeboxOriginBlock])); FPreviousSafeBox.RollBackToSnapshot(FPreviousSafeboxOriginBlock); {$IFDEF Check_Safebox_Names_Consistency} If Not Check_Safebox_Names_Consistency(FPreviousSafeBox,'PREVIOUS WITH ROLLBACK',errors) then begin TLog.NewLog(ltdebug,ClassName,'Check_Safebox_Names_Consistency '+errors); end; {$ENDIF} TLog.NewLog(ltdebug,ClassName,Format('Executing %d chain snapshots to master',[FSnapshots.Count])); For i:=0 to FSnapshots.Count-1 do begin Pss := FSnapshots[i]; TLog.NewLog(ltdebug,ClassName,Format('Executing %d/%d chain snapshot to master with %d blocks changed at block %d',[i+1,FSnapshots.Count,Pss^.newBlocks.Count,Pss^.nBlockNumber])); Try RedoSnapshot(Pss); Except On E:Exception do begin E.Message:= E.Message + Format(' Executing %d/%d chain snapshot to master with %d blocks changed at block %d',[i+1,FSnapshots.Count,Pss^.newBlocks.Count,Pss^.nBlockNumber]); Raise; end; end; end; // Finally add current changes? TLog.NewLog(ltdebug,ClassName,Format('Executing %d current chain changes to master',[FModifiedBlocksFinalState.Count])); RedoModifiedBlocks(FModifiedBlocksFinalState); RedoAddedDeletedNames(FAddedNamesSincePreviousSafebox,FDeletedNamesSincePreviousSafebox); TLog.NewLog(ltdebug,ClassName,Format('Check process start',[])); // Check it !!!! errors := ''; If (FPreviousSafeBox.BlocksCount<>BlocksCount) then begin errors := errors+'> Invalid Blockscount!'; end; If TBaseType.BinStrComp(FPreviousSafeBox.FSafeBoxHash,FSafeBoxHash)<>0 then begin errors := errors+'> Invalid SafeBoxHash!'; end; If TBaseType.BinStrComp(FPreviousSafeBox.FBufferBlocksHash,FBufferBlocksHash)<>0 then begin errors := errors+'> Invalid BufferBlocksHash!'; end; If (FPreviousSafeBox.FTotalBalance<>FTotalBalance) then begin errors := errors+'> Invalid Balance!'; end; If (FPreviousSafeBox.FTotalFee<>FTotalFee) then begin errors := errors+'> Invalid Fee!'; end; If (FPreviousSafeBox.WorkSum<>FWorkSum) then begin errors := errors+'> Invalid WorkSum!'; end; If (FPreviousSafeBox.FCurrentProtocol<>FCurrentProtocol) then begin errors := errors+'> Invalid Protocol!'; end; If (errors<>'') Then begin Raise Exception.Create('Errors Commiting to previous! '+errors); end; {$IFDEF Check_Safebox_Names_Consistency} If Not Check_Safebox_Names_Consistency(FPreviousSafeBox,'PREVIOUS',errors) then begin if errors='' then Raise Exception.Create('Check_Safebox_Names_Consistency '+errors); end; if Not Check_Safebox_Names_Consistency(Self,'CHAIN',errors) then begin if errors='' then Raise Exception.Create('Check_Safebox_Names_Consistency '+errors); end; Check_Safebox_Integrity(FPreviousSafeBox,'INTEGRITY PREVIOUS'); Check_Safebox_Integrity(Self,'INTEGRITY CHAIN'); {$ENDIF} TLog.NewLog(ltdebug,ClassName,Format('Check process end',[])); finally FPreviousSafeBox.EndThreadSave; end; finally EndThreadSave; end; end; procedure TPCSafeBox.RollBackToSnapshot(snapshotBlock: Cardinal); procedure UndoModifiedBlocks(modifiedblocks : TOrderedBlockAccountList); Var iBlock,j : Integer; blockAccount : TBlockAccount; begin For iBlock := 0 to modifiedBlocks.Count-1 do begin blockAccount := modifiedBlocks.Get(iBlock); // Set each account to previous value: for j:=Low(blockAccount.accounts) to High(blockAccount.accounts) do begin UpdateAccount(blockAccount.accounts[j].account, blockAccount.accounts[j].accountInfo, blockAccount.accounts[j].name, blockAccount.accounts[j].account_type, blockAccount.accounts[j].balance, blockAccount.accounts[j].n_operation, aus_rollback, blockAccount.accounts[j].updated_block, blockAccount.accounts[j].previous_updated_block ); end; end; end; Procedure UndoAddedDeletedNames(AddedNamesList,DeletedNamesList : TOrderedRawList); Var i,j : Integer; Begin // Start adding For i:=0 to AddedNamesList.Count-1 do begin // It was added, so we MUST FIND on current names list If Not FOrderedByName.Find(AddedNamesList.Get(i),j) then begin // ERROR: It has been added, why we not found??? If DeletedNamesList.Find(AddedNamesList.Get(i),j) then begin end else begin TLog.NewLog(lterror,ClassName,Format('ERROR DEV 20180319-1 Name %s not found at account:%d',[AddedNamesList.Get(i),AddedNamesList.GetTag(i)])); end; end else FOrderedByName.Delete(j); end; // Finally deleting For i:=0 to DeletedNamesList.Count-1 do begin // It has been deleted, we MUST NOT FIND on current names list If FOrderedByName.Find(DeletedNamesList.Get(i),j) then begin // It has been deleted... now is found If (FOrderedByName.GetTag(j)<>DeletedNamesList.GetTag(i)) then begin // ERROR: It has been deleted, why is found with another account??? TLog.NewLog(lterror,ClassName,Format('ERROR DEV 20180319-2 Name %s found at account:%d <> saved account:%d',[DeletedNamesList.Get(i),DeletedNamesList.GetTag(i),FOrderedByName.GetTag(j)])); end; end; // Add with Info of previous account with name (saved at Tag value) FOrderedByName.Add(DeletedNamesList.Get(i),DeletedNamesList.GetTag(i)); end; end; Var i,iPrevSnapshotTarget : Integer; Psnapshot : PSafeboxSnapshot; PBlock : PBlockAccount; begin StartThreadSafe; Try { Process is: - Find Previous snapshot (target) - Undo current pending operations - For each snapshot do - Undo snapshot operations - Undo created BlockAccount - At target snapshot: - Restore values - Clear data - Delete "future" snapshots } iPrevSnapshotTarget := FSnapshots.Count-1; while (iPrevSnapshotTarget>=0) And (PSafeboxSnapshot(FSnapshots[iPrevSnapshotTarget])^.nBlockNumber<>snapshotBlock) do Dec(iPrevSnapshotTarget); If (iPrevSnapshotTarget<0) then Raise Exception.Create('Cannot Rollback to previous Snapshot block: '+IntToStr(snapshotBlock)+' current '+IntToStr(BlocksCount)); // Go back starting from current state UndoModifiedBlocks(FModifiedBlocksPreviousState); UndoAddedDeletedNames(FAddedNamesSincePreviousSafebox,FDeletedNamesSincePreviousSafebox); // Go back based on snapshots: EXCEPT target For i:=FSnapshots.Count-1 downto (iPrevSnapshotTarget+1) do begin Psnapshot := FSnapshots[i]; TLog.NewLog(ltdebug,ClassName,Format('Executing %d/%d rollback %d blocks changed at block %d',[i+1,FSnapshots.Count,Psnapshot^.oldBlocks.Count,Psnapshot^.nBlockNumber])); // Must UNDO changes: UndoModifiedBlocks(Psnapshot^.oldBlocks); UndoAddedDeletedNames(Psnapshot^.namesAdded,Psnapshot^.namesDeleted); // Undo Created BlockAccount // Undo ONLY of if not target PBlock:=FBlockAccountsList.Items[FBlockAccountsList.Count-1]; FBlockAccountsList.Delete(FBlockAccountsList.Count-1); Dispose(PBlock); // Redo FBufferBlocksHash SetLength(FBufferBlocksHash,Length(FBufferBlocksHash)-32); // Delete FSnapshots.Delete(i); Psnapshot^.oldBlocks.Free; Psnapshot^.newBlocks.Free; Psnapshot^.namesAdded.Free; Psnapshot^.namesDeleted.Free; Psnapshot^.oldBufferBlocksHash := ''; Psnapshot^.oldSafeBoxHash := ''; Dispose(Psnapshot); end; // Set saved Safebox values: Psnapshot := FSnapshots[iPrevSnapshotTarget]; If TBaseType.BinStrComp(FBufferBlocksHash,Psnapshot^.oldBufferBlocksHash)<>0 then begin raise Exception.Create('ERROR DEV 20180322-1 Rollback invalid BufferBlocksHash value'); end; FBufferBlocksHash := Psnapshot^.oldBufferBlocksHash; FTotalBalance := Psnapshot^.oldTotalBalance; FTotalFee := Psnapshot^.oldTotalFee; FSafeBoxHash := Psnapshot^.oldSafeBoxHash; FWorkSum := Psnapshot^.oldWorkSum; FCurrentProtocol := Psnapshot^.oldCurrentProtocol; // Clear data FAddedNamesSincePreviousSafebox.Clear; FDeletedNamesSincePreviousSafebox.Clear; FModifiedBlocksPreviousState.Clear; FModifiedBlocksFinalState.Clear; {$IFDEF Check_Safebox_Names_Consistency} if Not Check_Safebox_Names_Consistency(Self,'ROLLBACK',errors) then begin if errors='' then Raise Exception.Create('Check_Safebox_Names_Consistency '+errors); end; {$ENDIF} finally EndThreadSave; end; end; function TPCSafeBox.DoUpgradeToProtocol2: Boolean; var block_number : Cardinal; aux : TRawBytes; begin // Upgrade process to protocol 2 Result := false; If Not CanUpgradeToProtocol(CT_PROTOCOL_2) then exit; // Recalc all BlockAccounts block_hash value aux := CalcSafeBoxHash; TLog.NewLog(ltInfo,ClassName,'Start Upgrade to protocol 2 - Old Safeboxhash:'+TCrypto.ToHexaString(FSafeBoxHash)+' calculated: '+TCrypto.ToHexaString(aux)+' Blocks: '+IntToStr(BlocksCount)); FBufferBlocksHash:=''; for block_number := 0 to BlocksCount - 1 do begin {$IFDEF uselowmem} TBaseType.To32Bytes(CalcBlockHash( Block(block_number), True),PBlockAccount(FBlockAccountsList.Items[block_number])^.block_hash); FBufferBlocksHash := FBufferBlocksHash+TBaseType.ToRawBytes(PBlockAccount(FBlockAccountsList.Items[block_number])^.block_hash); {$ELSE} PBlockAccount(FBlockAccountsList.Items[block_number])^.block_hash := CalcBlockHash( Block(block_number), True); FBufferBlocksHash := FBufferBlocksHash+PBlockAccount(FBlockAccountsList.Items[block_number])^.block_hash; {$ENDIF} end; FSafeBoxHash := CalcSafeBoxHash; FCurrentProtocol := CT_PROTOCOL_2; Result := True; TLog.NewLog(ltInfo,ClassName,'End Upgraded to protocol 2 - New safeboxhash:'+TCrypto.ToHexaString(FSafeBoxHash)); end; function TPCSafeBox.DoUpgradeToProtocol3: Boolean; begin FCurrentProtocol := CT_PROTOCOL_3; Result := True; TLog.NewLog(ltInfo,ClassName,'End Upgraded to protocol 3 - New safeboxhash:'+TCrypto.ToHexaString(FSafeBoxHash)); end; procedure TPCSafeBox.EndThreadSave; begin FLock.Release; end; function TPCSafeBox.LoadSafeBoxFromStream(Stream : TStream; checkAll : Boolean; var LastReadBlock : TBlockAccount; var errors : AnsiString) : Boolean; Var iblock,iacc : Cardinal; s : AnsiString; block : TBlockAccount; P : PBlockAccount; i,j : Integer; savedSBH : TRawBytes; nPos,posOffsetZone : Int64; offsets : Array of Cardinal; sbHeader : TPCSafeBoxHeader; begin If Assigned(FPreviousSafeBox) then Raise Exception.Create('Cannot loadSafeBoxFromStream on a Safebox in a Separate chain'); StartThreadSafe; try Clear; Result := false; Try If not LoadSafeBoxStreamHeader(Stream,sbHeader) then begin errors := 'Invalid stream. Invalid header/version'; exit; end; errors := 'Invalid version or corrupted stream'; case sbHeader.protocol of CT_PROTOCOL_1 : FCurrentProtocol := 1; CT_PROTOCOL_2 : FCurrentProtocol := 2; CT_PROTOCOL_3 : FCurrentProtocol := 3; else exit; end; if (sbHeader.blocksCount=0) Or (sbHeader.startBlock<>0) Or (sbHeader.endBlock<>(sbHeader.blocksCount-1)) then begin errors := Format('Safebox Stream contains blocks from %d to %d (of %d blocks). Not valid',[sbHeader.startBlock,sbHeader.endBlock,sbHeader.blocksCount]); exit; end; // Offset zone posOffsetZone := Stream.Position; If checkAll then begin SetLength(offsets,sbHeader.blockscount+1); // Last offset = End of blocks Stream.Read(offsets[0],4*(sbHeader.blockscount+1)); end else begin nPos := Stream.Position + ((sbHeader.blockscount+1) * 4); if Stream.Size<npos then exit; Stream.Position := nPos; end; // Build 1.3.0 to increase reading speed: FBlockAccountsList.Capacity := sbHeader.blockscount; SetLength(FBufferBlocksHash,sbHeader.blocksCount*32); // Initialize for high speed reading errors := 'Corrupted stream'; for iblock := 0 to sbHeader.blockscount-1 do begin errors := 'Corrupted stream reading block blockchain '+inttostr(iblock+1)+'/'+inttostr(sbHeader.blockscount); if (checkAll) then begin If (offsets[iblock]<>Stream.Position-posOffsetZone) then begin errors := errors + Format(' - offset[%d]:%d <> %d Position:%d offset:%d',[iblock,offsets[iblock],Stream.Position-posOffsetZone,Stream.Position,posOffsetZone]); exit; end; end; block := CT_BlockAccount_NUL; If Not TAccountComp.LoadTOperationBlockFromStream(Stream,block.blockchainInfo) then exit; if block.blockchainInfo.block<>iBlock then exit; for iacc := Low(block.accounts) to High(block.accounts) do begin errors := 'Corrupted stream reading account '+inttostr(iacc+1)+'/'+inttostr(length(block.accounts))+' of block '+inttostr(iblock+1)+'/'+inttostr(sbHeader.blockscount); if Stream.Read(block.accounts[iacc].account,4)<4 then exit; if TStreamOp.ReadAnsiString(Stream,s)<0 then exit; block.accounts[iacc].accountInfo := TAccountComp.RawString2AccountInfo(s); if Stream.Read(block.accounts[iacc].balance,SizeOf(UInt64))<SizeOf(UInt64) then exit; if Stream.Read(block.accounts[iacc].updated_block,4)<4 then exit; if Stream.Read(block.accounts[iacc].n_operation,4)<4 then exit; If FCurrentProtocol>=CT_PROTOCOL_2 then begin if TStreamOp.ReadAnsiString(Stream,block.accounts[iacc].name)<0 then exit; if Stream.Read(block.accounts[iacc].account_type,2)<2 then exit; end; // if Stream.Read(block.accounts[iacc].previous_updated_block,4)<4 then exit; // check valid If (block.accounts[iacc].name<>'') then begin if FOrderedByName.IndexOf(block.accounts[iacc].name)>=0 then begin errors := errors + ' Duplicate name "'+block.accounts[iacc].name+'"'; Exit; end; if Not TPCSafeBox.ValidAccountName(block.accounts[iacc].name,s) then begin errors := errors + ' > Invalid name "'+block.accounts[iacc].name+'": '+s; Exit; end; FOrderedByName.Add(block.accounts[iacc].name,block.accounts[iacc].account); end; If checkAll then begin if not TAccountComp.IsValidAccountInfo(block.accounts[iacc].accountInfo,s) then begin errors := errors + ' > '+s; Exit; end; end; FTotalBalance := FTotalBalance + block.accounts[iacc].balance; end; errors := 'Corrupted stream reading block '+inttostr(iblock+1)+'/'+inttostr(sbHeader.blockscount); If TStreamOp.ReadAnsiString(Stream,block.block_hash)<0 then exit; If Stream.Read(block.accumulatedWork,SizeOf(block.accumulatedWork)) < SizeOf(block.accumulatedWork) then exit; if checkAll then begin // Check is valid: // STEP 1: Validate the block If not IsValidNewOperationsBlock(block.blockchainInfo,False,s) then begin errors := errors + ' > ' + s; exit; end; // STEP 2: Check if valid block hash if CalcBlockHash(block,FCurrentProtocol>=CT_PROTOCOL_2)<>block.block_hash then begin errors := errors + ' > Invalid block hash '+inttostr(iblock+1)+'/'+inttostr(sbHeader.blockscount); exit; end; // STEP 3: Check accumulatedWork if (iblock>0) then begin If (self.Block(iblock-1).accumulatedWork)+block.blockchainInfo.compact_target <> block.accumulatedWork then begin errors := errors + ' > Invalid accumulatedWork'; exit; end; end; end; // Add New(P); ToTMemBlockAccount(block,P^); FBlockAccountsList.Add(P); for j := low(block.accounts) to High(block.accounts) do begin AccountKeyListAddAccounts(block.accounts[j].accountInfo.accountKey,[block.accounts[j].account]); end; // BufferBlocksHash fill with data j := (length(P^.block_hash)*(iBlock)); for i := 1 to length(P^.block_hash) do begin {$IFDEF FPC} FBufferBlocksHash[i+j] := AnsiChar(P^.block_hash[i-(low(FBufferBlocksHash)-low(P^.block_hash))]); {$ELSE} FBufferBlocksHash[i+j] := AnsiChar(P^.block_hash[i-{$IFDEF uselowmem}1{$ELSE}0{$ENDIF}]); {$ENDIF} end; LastReadBlock := block; FWorkSum := FWorkSum + block.blockchainInfo.compact_target; end; If checkAll then begin If (offsets[sbHeader.blockscount]<>0) And (offsets[sbHeader.blockscount]<>Stream.Position-posOffsetZone) then begin errors := errors + Format(' - Final offset[%d]=%d <> Eof Position:%d offset:%d',[sbHeader.blockscount,offsets[sbHeader.blockscount],Stream.Position-posOffsetZone,posOffsetZone]); exit; end; end; // Finally load SafeBoxHash If TStreamOp.ReadAnsiString(stream,savedSBH)<0 then begin errors := 'No SafeBoxHash value'; exit; end; // Check worksum value If sbHeader.blockscount>0 then begin If (FWorkSum<>Self.Block(sbHeader.blockscount-1).accumulatedWork) then begin errors := 'Invalid WorkSum value'; exit; end; end; // Calculating safe box hash FSafeBoxHash := CalcSafeBoxHash; // Checking saved SafeBoxHash If FSafeBoxHash<>savedSBH then begin errors := 'Invalid SafeBoxHash value in stream '+TCrypto.ToHexaString(FSafeBoxHash)+'<>'+TCrypto.ToHexaString(savedSBH)+' Last block:'+IntToStr(LastReadBlock.blockchainInfo.block); exit; end; Result := true; Finally if Not Result then Clear else errors := ''; End; Finally EndThreadSave; end; end; class function TPCSafeBox.LoadSafeBoxStreamHeader(Stream: TStream; var sbHeader : TPCSafeBoxHeader) : Boolean; // This function reads SafeBox stream info and sets position at offset start zone if valid, otherwise sets position to actual position Var w : Word; s : AnsiString; safeBoxBankVersion : Word; offsetPos, initialPos : Int64; endBlocks : Cardinal; begin Result := false; sbHeader := CT_PCSafeBoxHeader_NUL; initialPos := Stream.Position; try TStreamOp.ReadAnsiString(Stream,s); if (s<>CT_MagicIdentificator) then exit; if Stream.Size<8 then exit; Stream.Read(w,SizeOf(w)); if not (w in [CT_PROTOCOL_1,CT_PROTOCOL_2,CT_PROTOCOL_3]) then exit; sbHeader.protocol := w; Stream.Read(safeBoxBankVersion,2); if safeBoxBankVersion<>CT_SafeBoxBankVersion then exit; Stream.Read(sbHeader.blocksCount,4); Stream.Read(sbHeader.startBlock,4); Stream.Read(sbHeader.endBlock,4); if (sbHeader.blocksCount<=0) Or (sbHeader.blocksCount>(CT_NewLineSecondsAvg*2000000)) then exit; // Protection for corrupted data... offsetPos := Stream.Position; // Go to read SafeBoxHash If (Stream.size<offsetPos + (((sbHeader.endBlock - sbHeader.startBlock)+2)*4)) then exit; Stream.position := offsetPos + (((sbHeader.endBlock - sbHeader.startBlock)+1)*4); Stream.Read(endBlocks,4); // Go to end If (Stream.Size<offsetPos + (endBlocks)) then exit; Stream.Position:=offsetPos + endBlocks; If TStreamOp.ReadAnsiString(Stream,sbHeader.safeBoxHash)<0 then exit; // Back Stream.Position:=offsetPos; Result := True; finally If not Result then Stream.Position := initialPos; end; end; class function TPCSafeBox.SaveSafeBoxStreamHeader(Stream: TStream; protocol: Word; OffsetStartBlock, OffsetEndBlock, CurrentSafeBoxBlocksCount: Cardinal): Boolean; var c : Cardinal; begin Result := False; // Header zone TStreamOp.WriteAnsiString(Stream,CT_MagicIdentificator); Stream.Write(protocol,SizeOf(protocol)); Stream.Write(CT_SafeBoxBankVersion,SizeOf(CT_SafeBoxBankVersion)); c := CurrentSafeBoxBlocksCount; Stream.Write(c,Sizeof(c)); // Save Total blocks of the safebox c := OffsetStartBlock; Stream.Write(c,Sizeof(c)); // Save first block saved c := OffsetEndBlock; Stream.Write(c,Sizeof(c)); // Save last block saved Result := True; end; class function TPCSafeBox.MustSafeBoxBeSaved(BlocksCount: Cardinal): Boolean; begin Result := (BlocksCount MOD CT_BankToDiskEveryNBlocks)=0; end; procedure TPCSafeBox.SaveSafeBoxBlockToAStream(Stream: TStream; nBlock: Cardinal); var b : TBlockAccount; iacc : integer; begin b := Block(nblock); TAccountComp.SaveTOperationBlockToStream(Stream,b.blockchainInfo); for iacc := Low(b.accounts) to High(b.accounts) do begin Stream.Write(b.accounts[iacc].account,Sizeof(b.accounts[iacc].account)); TStreamOp.WriteAnsiString(Stream,TAccountComp.AccountInfo2RawString(b.accounts[iacc].accountInfo)); Stream.Write(b.accounts[iacc].balance,Sizeof(b.accounts[iacc].balance)); Stream.Write(b.accounts[iacc].updated_block,Sizeof(b.accounts[iacc].updated_block)); Stream.Write(b.accounts[iacc].n_operation,Sizeof(b.accounts[iacc].n_operation)); If FCurrentProtocol>=CT_PROTOCOL_2 then begin TStreamOp.WriteAnsiString(Stream,b.accounts[iacc].name); Stream.Write(b.accounts[iacc].account_type,SizeOf(b.accounts[iacc].account_type)); end; Stream.Write(b.accounts[iacc].previous_updated_block,Sizeof(b.accounts[iacc].previous_updated_block)); end; TStreamOp.WriteAnsiString(Stream,b.block_hash); Stream.Write(b.accumulatedWork,Sizeof(b.accumulatedWork)); end; procedure TPCSafeBox.SaveSafeBoxToAStream(Stream: TStream; FromBlock, ToBlock : Cardinal); Var totalBlocks,iblock : Cardinal; b : TBlockAccount; posOffsetZone, posFinal : Int64; offsets : TCardinalsArray; raw : TRawBytes; begin If (FromBlock>ToBlock) Or (ToBlock>=BlocksCount) then Raise Exception.Create(Format('Cannot save SafeBox from %d to %d (currently %d blocks)',[FromBlock,ToBlock,BlocksCount])); StartThreadSafe; Try // Header zone SaveSafeBoxStreamHeader(Stream,FCurrentProtocol,FromBlock,ToBlock,BlocksCount); totalBlocks := ToBlock - FromBlock + 1; // Offsets zone posOffsetZone:=Stream.Position; SetLength(raw,(totalBlocks+1)*4); // Last position = end FillChar(raw[1],length(raw),0); Stream.WriteBuffer(raw[1],length(raw)); setLength(offsets,totalBlocks+1); // c = total blocks - Last position = offset to end // Blocks zone for iblock := FromBlock to ToBlock do begin offsets[iBlock] := Stream.Position - posOffsetZone; SaveSafeBoxBlockToAStream(Stream,iblock); end; offsets[High(offsets)] := Stream.Position - posOffsetZone; // Save offsets zone with valid values posFinal := Stream.Position; Stream.Position := posOffsetZone; for iblock := FromBlock to ToBlock+1 do begin Stream.Write(offsets[iblock],SizeOf(offsets[iblock])); end; Stream.Position := posFinal; // Final zone: Save safeboxhash for next block If (ToBlock+1<BlocksCount) then begin b := Block(ToBlock); TStreamOp.WriteAnsiString(Stream,b.blockchainInfo.initial_safe_box_hash); end else begin TStreamOp.WriteAnsiString(Stream,FSafeBoxHash); end; Finally EndThreadSave; end; end; class function TPCSafeBox.CopySafeBoxStream(Source, Dest: TStream; FromBlock,ToBlock: Cardinal; var errors : AnsiString) : Boolean; Var iblock : Cardinal; raw : TRawBytes; posOffsetZoneSource, posOffsetZoneDest, posFinal, posBlocksZoneDest, posInitial : Int64; offsetsSource,offsetsDest : TCardinalsArray; destTotalBlocks : Cardinal; sbHeader : TPCSafeBoxHeader; begin Result := False; errors := ''; posInitial := Source.Position; try If (FromBlock>ToBlock) then begin errors := Format('Invalid CopySafeBoxStream(from %d, to %d)',[FromBlock,ToBlock]); exit; end; If not LoadSafeBoxStreamHeader(Source,sbHeader) then begin errors := 'Invalid stream. Invalid header/version'; exit; end; if (sbHeader.startBlock>FromBlock) Or (sbHeader.endBlock<ToBlock) Or ((sbHeader.startBlock + sbHeader.blocksCount)<ToBlock) then begin errors := Format('Stream contain blocks from %d to %d (of %d). Need between %d and %d !',[sbHeader.startBlock,sbHeader.endBlock,sbHeader.blocksCount,FromBlock,ToBlock]); exit; end; destTotalBlocks := ToBlock - FromBlock + 1; TLog.NewLog(ltDebug,ClassName,Format('CopySafeBoxStream from safebox with %d to %d (of %d sbh:%s) to safebox with %d and %d', [sbHeader.startBlock,sbHeader.endBlock,sbHeader.BlocksCount,TCrypto.ToHexaString(sbHeader.safeBoxHash),FromBlock,ToBlock])); // Read Source Offset zone posOffsetZoneSource := Source.Position; SetLength(offsetsSource,(sbHeader.endBlock-sbHeader.startBlock)+2); Source.Read(offsetsSource[0],4*length(offsetsSource)); // DEST STREAM: // Init dest stream // Header zone SaveSafeBoxStreamHeader(Dest,sbHeader.protocol,FromBlock,ToBlock,sbHeader.blocksCount); // Offsets zone posOffsetZoneDest:=Dest.Position; SetLength(raw,(destTotalBlocks+1)*4); // Cardinal = 4 bytes for each block + End position FillChar(raw[1],length(raw),0); Dest.WriteBuffer(raw[1],length(raw)); setLength(offsetsDest,destTotalBlocks+1); // Blocks zone posBlocksZoneDest := Dest.Position; TLog.NewLog(ltDebug,Classname, Format('Copying Safebox Stream from source Position %d (size:%d) to dest %d bytes - OffsetSource[%d] - OffsetSource[%d]', [posOffsetZoneSource + offsetsSource[FromBlock - sbHeader.startBlock], Source.Size, offsetsSource[ToBlock - sbHeader.startBlock + 1] - offsetsSource[FromBlock - sbHeader.startBlock], ToBlock - sbHeader.startBlock + 1, FromBlock - sbHeader.startBlock ])); Source.Position:=posOffsetZoneSource + offsetsSource[FromBlock - sbHeader.startBlock]; Dest.CopyFrom(Source,offsetsSource[ToBlock - sbHeader.startBlock + 1] - offsetsSource[FromBlock - sbHeader.startBlock]); // Save offsets zone with valid values posFinal := Dest.Position; Dest.Position := posOffsetZoneDest; for iblock := FromBlock to ToBlock do begin offsetsDest[iblock - FromBlock] := offsetsSource[iblock - (sbHeader.startBlock)] - offsetsSource[FromBlock - sbHeader.startBlock] + (posBlocksZoneDest - posOffsetZoneDest); end; offsetsDest[high(offsetsDest)] := posFinal - posOffsetZoneDest; Dest.WriteBuffer(offsetsDest[0],length(offsetsDest)*4); Dest.Position := posFinal; Source.Position := offsetsSource[High(offsetsSource)] + posOffsetZoneSource; TStreamOp.ReadAnsiString(Source,raw); TStreamOp.WriteAnsiString(Dest,raw); Result := true; finally Source.Position:=posInitial; end; end; class function TPCSafeBox.ConcatSafeBoxStream(Source1, Source2, Dest: TStream; var errors: AnsiString): Boolean; function MinCardinal(v1,v2 : Cardinal) : Cardinal; begin if v1<v2 then Result:=v1 else Result:=v2; end; function MaxCardinal(v1,v2 : Cardinal) : Cardinal; begin if v1>v2 then Result:=v1 else Result:=v2; end; function ReadSafeBoxBlockFromStream(safeBoxStream : TStream; offsetIndex : Cardinal; destStream : TStream) : Cardinal; // PRE: safeBoxStream is a valid SafeBox Stream (with enough size) located at Offsets zone, and offsetIndex is >=0 and <= end block // Returns the size of the saved block at destStream var offsetPos, auxPos : Int64; c,cNext : Cardinal; begin Result := 0; offsetPos := safeBoxStream.Position; try safeBoxStream.Seek(4*offsetIndex,soFromCurrent); safeBoxStream.Read(c,4); safeBoxStream.Read(cNext,4); if cNext<c then exit; Result := cNext - c; // Result is the offset difference between blocks if Result<=0 then exit; auxPos := offsetPos + c; if safeBoxStream.Size<auxPos+Result then exit; // Invalid safeBoxStream.Position:=auxPos; destStream.CopyFrom(safeBoxStream,Result); finally safeBoxStream.Position:=offsetPos; end; end; procedure WriteSafeBoxBlockToStream(Stream, safeBoxStream : TStream; nBytes : Integer; offsetIndex, totalOffsets : Cardinal); // PRE: safeBoxStream is a valid SafeBox Stream located at Offsets zone, and offsetIndex=0 or offsetIndex-1 has a valid value var offsetPos : Int64; c,cLength : Cardinal; begin offsetPos := safeBoxStream.Position; try if offsetIndex=0 then begin // First c := ((totalOffsets+1)*4); safeBoxStream.Write(c,4); end else begin safeBoxStream.Seek(4*(offsetIndex),soFromCurrent); safeBoxStream.Read(c,4); // c is position end; cLength := c + nBytes; safeBoxStream.Write(cLength,4); safeBoxStream.Position := offsetPos + c; safeBoxStream.CopyFrom(Stream,nBytes); finally safeBoxStream.Position:=offsetPos; end; end; Var destStartBlock, destEndBlock, nBlock : Cardinal; source1InitialPos, source2InitialPos, destOffsetPos: Int64; ms : TMemoryStream; c : Cardinal; destOffsets : TCardinalsArray; i : Integer; s1Header,s2Header : TPCSafeBoxHeader; begin Result := False; errors := ''; source1InitialPos:=Source1.Position; source2InitialPos:=Source2.Position; Try If not LoadSafeBoxStreamHeader(Source1,s1Header) then begin errors := 'Invalid source 1 stream. Invalid header/version'; exit; end; If not LoadSafeBoxStreamHeader(Source2,s2Header) then begin errors := 'Invalid source 2 stream. Invalid header/version'; exit; end; // Check SBH and blockcount if (s1Header.safeBoxHash<>s2Header.safeBoxHash) or (s1Header.blocksCount<>s2Header.blocksCount) Or (s1Header.protocol<>s2Header.protocol) then begin errors := Format('Source1 and Source2 have diff safebox. Source 1 %d %s (protocol %d) Source 2 %d %s (protocol %d)', [s1Header.blocksCount,TCrypto.ToHexaString(s1Header.safeBoxHash),s1Header.protocol, s2Header.blocksCount,TCrypto.ToHexaString(s2Header.safeBoxHash),s2Header.protocol]); exit; end; // Save dest heaer destStartBlock := MinCardinal(s1Header.startBlock,s2Header.startBlock); destEndBlock := MaxCardinal(s1Header.endBlock,s2Header.endBlock); SaveSafeBoxStreamHeader(Dest,s1Header.protocol,destStartBlock,destEndBlock,s1Header.blocksCount); // Save offsets destOffsetPos:=Dest.Position; SetLength(destOffsets,((destEndBlock-destStartBlock)+2)); for i:=low(destOffsets) to high(destOffsets) do destOffsets[i] := 0; Dest.Write(destOffsets[0],((destEndBlock-destStartBlock)+2)*4); Dest.Position:=destOffsetPos; // nBlock := destStartBlock; ms := TMemoryStream.Create; try for nBlock :=destStartBlock to destEndBlock do begin ms.Clear; if (nBlock>=s1Header.startBlock) And (nBlock<=s1Header.endBlock) then begin c := ReadSafeBoxBlockFromStream(Source1,nBlock-s1Header.startBlock,ms); ms.Position:=0; WriteSafeBoxBlockToStream(ms,Dest,c,nBlock-destStartBlock,destEndBlock-destStartBlock+1); end else if (nBlock>=s2Header.startBlock) and (nBlock<=s2Header.endBlock) then begin c := ReadSafeBoxBlockFromStream(Source2,nBlock-s2Header.startBlock,ms); ms.Position:=0; WriteSafeBoxBlockToStream(ms,Dest,c,nBlock-destStartBlock,destEndBlock-destStartBlock+1); end else Raise Exception.Create('ERROR DEV 20170518-1'); end; Finally ms.Free; end; // Save SafeBoxHash at the end Dest.Seek(0,soFromEnd); TStreamOp.WriteAnsiString(Dest,s1Header.safeBoxHash); Result := true; Finally Source1.Position:=source1InitialPos; Source2.Position:=source2InitialPos; end; end; class function TPCSafeBox.ValidAccountName(const new_name: TRawBytes; var errors : AnsiString): Boolean; { Note: This function is case senstive, and only lower case chars are valid. Execute a LowerCase() prior to call this function! } Const CT_PascalCoin_Base64_Charset : ShortString = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-+{}[]\_:"|<>,.?/~'; // First char can't start with a number CT_PascalCoin_FirstChar_Charset : ShortString = 'abcdefghijklmnopqrstuvwxyz!@#$%^&*()-+{}[]\_:"|<>,.?/~'; CT_PascalCoin_name_min_length = 3; CT_PascalCoin_name_max_length = 64; var i,j : Integer; begin Result := False; errors := ''; if (length(new_name)<CT_PascalCoin_name_min_length) Or (length(new_name)>CT_PascalCoin_name_max_length) then begin errors := 'Invalid length:'+IntToStr(Length(new_name))+' (valid from '+Inttostr(CT_PascalCoin_name_max_length)+' to '+IntToStr(CT_PascalCoin_name_max_length)+')'; Exit; end; for i:=1 to length(new_name) do begin j:=1; if (i=1) then begin // First char can't start with a number While (j<=length(CT_PascalCoin_FirstChar_Charset)) and (new_name[i]<>CT_PascalCoin_FirstChar_Charset[j]) do inc(j); if j>length(CT_PascalCoin_FirstChar_Charset) then begin errors := 'Invalid char '+new_name[i]+' at first pos'; Exit; // Not found end; end else begin While (j<=length(CT_PascalCoin_Base64_Charset)) and (new_name[i]<>CT_PascalCoin_Base64_Charset[j]) do inc(j); if j>length(CT_PascalCoin_Base64_Charset) then begin errors := 'Invalid char '+new_name[i]+' at pos '+IntToStr(i); Exit; // Not found end; end; end; Result := True; end; function TPCSafeBox.IsValidNewOperationsBlock(const newOperationBlock: TOperationBlock; checkSafeBoxHash : Boolean; var errors: AnsiString): Boolean; { This function will check a OperationBlock info as a valid candidate to be included in the safebox TOperationBlock contains the info of the new block EXCEPT the operations, including only operations_hash value (SHA256 of the Operations) So, cannot check operations and fee values } var target_hash, pow : TRawBytes; i : Integer; lastBlock : TOperationBlock; begin Result := False; errors := ''; If BlocksCount>0 then lastBlock := Block(BlocksCount-1).blockchainInfo else lastBlock := CT_OperationBlock_NUL; // Check block if (BlocksCount <> newOperationBlock.block) then begin errors := 'block ('+inttostr(newOperationBlock.block)+') is not new position ('+inttostr(BlocksCount)+')'; exit; end; // fee: Cannot be checked only with the safebox // protocol available is not checked if (newOperationBlock.block > 0) then begin // protocol if (newOperationBlock.protocol_version<>CurrentProtocol) then begin // Protocol must be 1 or 2. If 1 then all prior blocksmust be 1 and never 2 (invalide blockchain version scenario v1...v2...v1) If (lastBlock.protocol_version>newOperationBlock.protocol_version) then begin errors := 'Invalid PascalCoin protocol version: '+IntToStr( newOperationBlock.protocol_version )+' Current: '+IntToStr(CurrentProtocol)+' Previous:'+IntToStr(lastBlock.protocol_version); exit; end; If (newOperationBlock.protocol_version=CT_PROTOCOL_3) then begin If (newOperationBlock.block<CT_Protocol_Upgrade_v3_MinBlock) then begin errors := 'Upgrade to protocol version 3 available at block: '+IntToStr(CT_Protocol_Upgrade_v3_MinBlock); exit; end; end else If (newOperationBlock.protocol_version=CT_PROTOCOL_2) then begin If (newOperationBlock.block<CT_Protocol_Upgrade_v2_MinBlock) then begin errors := 'Upgrade to protocol version 2 available at block: '+IntToStr(CT_Protocol_Upgrade_v2_MinBlock); exit; end; end else if (newOperationBlock.protocol_version<>CT_PROTOCOL_1) then begin errors := 'Invalid protocol version change to '+IntToStr(newOperationBlock.protocol_version); exit; end; end; // timestamp if ((newOperationBlock.timestamp) < (lastBlock.timestamp)) then begin errors := 'Invalid timestamp (Back timestamp: New timestamp:'+inttostr(newOperationBlock.timestamp)+' < last timestamp ('+Inttostr(BlocksCount-1)+'):'+Inttostr(lastBlock.timestamp)+')'; exit; end; end; // compact_target target_hash:=GetActualTargetHash(newOperationBlock.protocol_version); if (newOperationBlock.compact_target <> TPascalCoinProtocol.TargetToCompact(target_hash)) then begin errors := 'Invalid target found:'+IntToHex(newOperationBlock.compact_target,8)+' actual:'+IntToHex(TPascalCoinProtocol.TargetToCompact(target_hash),8); exit; end; // initial_safe_box_hash: Only can be checked when adding new blocks, not when restoring a safebox If checkSafeBoxHash then begin // TODO: Can use FSafeBoxHash instead of CalcSafeBoxHash ???? Quick speed if possible if (newOperationBlock.initial_safe_box_hash <> CalcSafeBoxHash) then begin errors := 'BlockChain Safe box hash invalid: '+TCrypto.ToHexaString(newOperationBlock.initial_safe_box_hash)+' var: '+ TCrypto.ToHexaString(FSafeBoxHash)+ ' Calculated:'+TCrypto.ToHexaString(CalcSafeBoxHash); exit; end; end; {$IFnDEF TESTING_NO_POW_CHECK} if (newOperationBlock.proof_of_work > target_hash) then begin errors := 'Proof of work is higher than target '+TCrypto.ToHexaString(newOperationBlock.proof_of_work)+' > '+TCrypto.ToHexaString(target_hash); exit; end; {$ENDIF} Result := IsValidOperationBlock(newOperationBlock,errors); end; class function TPCSafeBox.IsValidOperationBlock(const newOperationBlock: TOperationBlock; var errors: AnsiString): Boolean; { This class function will check a OperationBlock basic info as a valid info Creted at Build 2.1.7 as a division of IsValidNewOperationsBlock for easily basic check TOperationBlock TOperationBlock contains the info of the new block, but cannot be checked with current Safebox state (Use IsValidNewOperationsBlock instead) and also cannot check operations, operations_hash, fees... } var pow : TRawBytes; i : Integer; begin Result := False; errors := ''; // Check Account key if Not TAccountComp.IsValidAccountKey(newOperationBlock.account_key,errors) then begin exit; end; // reward if (newOperationBlock.reward<>TPascalCoinProtocol.GetRewardForNewLine(newOperationBlock.block)) then begin errors := 'Invalid reward'; exit; end; // Valid protocol version if (Not (newOperationBlock.protocol_version in [CT_PROTOCOL_1,CT_PROTOCOL_2,CT_PROTOCOL_3])) then begin errors := 'Invalid protocol version '+IntToStr(newOperationBlock.protocol_version); exit; end; // fee: Cannot be checked only with the safebox // protocol available is not checked if (newOperationBlock.block > 0) then begin end else begin if (CT_Zero_Block_Proof_of_work_in_Hexa<>'') then begin // Check if valid Zero block if Not (AnsiSameText(TCrypto.ToHexaString(newOperationBlock.proof_of_work),CT_Zero_Block_Proof_of_work_in_Hexa)) then begin errors := 'Zero block not valid, Proof of Work invalid: '+TCrypto.ToHexaString(newOperationBlock.proof_of_work)+'<>'+CT_Zero_Block_Proof_of_work_in_Hexa; exit; end; end; end; // Checking Miner Payload valid chars/length If Not TPascalCoinProtocol.IsValidMinerBlockPayload(newOperationBlock.block_payload) then begin errors := 'Invalid Miner Payload value. Length: '+inttostr(Length(newOperationBlock.block_payload)); exit; end; // operations_hash: NOT CHECKED WITH OPERATIONS! If (length(newOperationBlock.operations_hash)<>32) then begin errors := 'Invalid Operations hash value: '+TCrypto.ToHexaString(newOperationBlock.operations_hash)+' length='+IntToStr(Length(newOperationBlock.operations_hash)); exit; end; // proof_of_work: {$IFnDEF TESTING_NO_POW_CHECK} TPascalCoinProtocol.CalcProofOfWork(newOperationBlock,pow); if (pow<>newOperationBlock.proof_of_work) then begin errors := 'Proof of work is bad calculated '+TCrypto.ToHexaString(newOperationBlock.proof_of_work)+' <> Good: '+TCrypto.ToHexaString(pow); exit; end; {$ENDIF} Result := true; end; function TPCSafeBox.GetActualTargetHash(protocolVersion : Word): TRawBytes; { Target is calculated in each block with avg obtained in previous CT_CalcNewDifficulty blocks. If Block is lower than CT_CalcNewDifficulty then is calculated with all previous blocks. } Var ts1, ts2, tsTeorical, tsReal, tsTeoricalStop, tsRealStop: Int64; CalcBack : Integer; lastBlock : TOperationBlock; begin if (BlocksCount <= 1) then begin // Important: CT_MinCompactTarget is applied for blocks 0 until ((CT_CalcNewDifficulty*2)-1) Result := TPascalCoinProtocol.TargetFromCompact(CT_MinCompactTarget); end else begin if BlocksCount > CT_CalcNewTargetBlocksAverage then CalcBack := CT_CalcNewTargetBlocksAverage else CalcBack := BlocksCount-1; lastBlock := Block(BlocksCount-1).blockchainInfo; // Calc new target! ts1 := lastBlock.timestamp; ts2 := Block(BlocksCount-CalcBack-1).blockchainInfo.timestamp; tsTeorical := (CalcBack * CT_NewLineSecondsAvg); tsReal := (ts1 - ts2); If (protocolVersion=CT_PROTOCOL_1) then begin Result := TPascalCoinProtocol.GetNewTarget(tsTeorical, tsReal,protocolVersion,False,TPascalCoinProtocol.TargetFromCompact(lastBlock.compact_target)); end else if (protocolVersion<=CT_PROTOCOL_3) then begin CalcBack := CalcBack DIV CT_CalcNewTargetLimitChange_SPLIT; If CalcBack=0 then CalcBack := 1; ts2 := Block(BlocksCount-CalcBack-1).blockchainInfo.timestamp; tsTeoricalStop := (CalcBack * CT_NewLineSecondsAvg); tsRealStop := (ts1 - ts2); { Protocol 2 change: Only will increase/decrease Target if (CT_CalcNewTargetBlocksAverage DIV 10) needs to increase/decrease too, othewise use current Target. This will prevent sinusoidal movement and provide more stable hashrate, computing always time from CT_CalcNewTargetBlocksAverage } If ((tsTeorical>tsReal) and (tsTeoricalStop>tsRealStop)) Or ((tsTeorical<tsReal) and (tsTeoricalStop<tsRealStop)) then begin Result := TPascalCoinProtocol.GetNewTarget(tsTeorical, tsReal,protocolVersion,False,TPascalCoinProtocol.TargetFromCompact(lastBlock.compact_target)); end else begin if (protocolVersion=CT_PROTOCOL_2) then begin // Nothing to do! Result:=TPascalCoinProtocol.TargetFromCompact(lastBlock.compact_target); end else begin // New on V3 protocol: // Harmonization of the sinusoidal effect modifying the rise / fall over the "stop" area Result := TPascalCoinProtocol.GetNewTarget(tsTeoricalStop,tsRealStop,protocolVersion,True,TPascalCoinProtocol.TargetFromCompact(lastBlock.compact_target)); end; end; end else begin Raise Exception.Create('ERROR DEV 20180306-1 Protocol not valid'); end; end; end; function TPCSafeBox.GetActualCompactTargetHash(protocolVersion : Word): Cardinal; begin Result := TPascalCoinProtocol.TargetToCompact(GetActualTargetHash(protocolVersion)); end; function TPCSafeBox.FindAccountByName(aName: AnsiString): Integer; Var nameLower : AnsiString; i,j,k : Integer; Psnapshot : PSafeboxSnapshot; begin nameLower := LowerCase(aName); i := FOrderedByName.IndexOf(nameLower); if i>=0 then Result := FOrderedByName.GetTag(i) else begin Result := -1; If Assigned(FPreviousSafeBox) then begin // Now doesn't exists, was deleted before? Result := FPreviousSafeBox.FindAccountByName(nameLower); j := FPreviousSafeBox.FSnapshots.Count-1; // Start with current changes on FPreviousSafebox // Start with Added If (Result>=0) then begin k := FPreviousSafeBox.FAddedNamesSincePreviousSafebox.IndexOf(nameLower); If (k>=0) then Result := -1; end; // Then with deleted If (Result<0) then begin // I've not found nameLower, search if was deleted k := (FPreviousSafeBox.FDeletedNamesSincePreviousSafebox.IndexOf(nameLower)); If (k>=0) then begin // Was deleted, rescue previous account number with name Result := FPreviousSafeBox.FDeletedNamesSincePreviousSafebox.GetTag(k); end; end; // while (j>=0) And (PSafeboxSnapshot(FPreviousSafeBox.FSnapshots[j])^.nBlockNumber>FPreviousSafeboxOriginBlock) do begin // > ???? Psnapshot := PSafeboxSnapshot(FPreviousSafeBox.FSnapshots[j]); // Start with added: If (Result>=0) then begin // I've found nameLower, search if was added (to undo) k := (Psnapshot^.namesAdded.IndexOf(nameLower)); if (k>=0) then begin // Was addded, delete name Result := -1; end; end; // Then with deleted (in order to restore) If (Result<0) then begin // I've not found nameLower, search if was deleted k := (Psnapshot^.namesDeleted.IndexOf(nameLower)); If (k>=0) then begin // Was deleted, rescue previous account number with name Result := Psnapshot^.namesDeleted.GetTag(k); end; end; dec(j); // Next previous snapshot end; end; end; end; procedure TPCSafeBox.SearchBlockWhenOnSeparatedChain(blockNumber: Cardinal; out blockAccount: TBlockAccount); Function WasUpdatedBeforeOrigin : Boolean; var j, maxUB : Integer; Begin // Is valid? maxUB := 0; for j:=Low(blockAccount.accounts) to High(blockAccount.accounts) do begin If blockAccount.accounts[j].updated_block>maxUB then maxUB := blockAccount.accounts[j].updated_block; end; Result := (maxUB <= FPreviousSafeboxOriginBlock); end; var i,j : Integer; Pss : PSafeboxSnapshot; begin If Not Assigned(FPreviousSafeBox) then Raise Exception.Create('ERROR DEV 20180320-1'); // It's not stored on FBlockAccountsList // Search on my chain current chain If FModifiedBlocksSeparatedChain.Find(blockNumber,i) then begin blockAccount := FModifiedBlocksSeparatedChain.Get(i); Exit; end else begin // Has not changed on my chain, must search on PreviousSafebox chain AT OriginStartPos blockAccount := FPreviousSafeBox.Block(blockNumber); // Is valid? If WasUpdatedBeforeOrigin then Exit; // If FPreviousSafeBox.FModifiedBlocksPreviousState.Find(blockNumber,j) then begin blockAccount := FPreviousSafeBox.FModifiedBlocksPreviousState.Get(j); if WasUpdatedBeforeOrigin then Exit; end; // Must search on Previous when was updated! i := FPreviousSafeBox.FSnapshots.Count-1; while (i>=0) do begin Pss := FPreviousSafeBox.FSnapshots[i]; If Pss.oldBlocks.Find(blockNumber,j) then begin blockAccount := Pss.oldBlocks.Get(j); If WasUpdatedBeforeOrigin then Exit; end; dec(i); end; Raise Exception.Create('ERROR DEV 20180318-1'); // Must find before! end; end; procedure TPCSafeBox.UpdateAccount(account_number : Cardinal; const newAccountInfo: TAccountInfo; const newName : TRawBytes; newType : Word; newBalance: UInt64; newN_operation: Cardinal; accountUpdateStyle : TAccountUpdateStyle; newUpdated_block, newPrevious_Updated_block : Cardinal); Var iBlock : Cardinal; i,j,iAccount, iDeleted, iAdded : Integer; lastbalance : UInt64; blockAccount : TBlockAccount; Pblock : PBlockAccount; begin iBlock := account_number DIV CT_AccountsPerBlock; iAccount := account_number MOD CT_AccountsPerBlock; blockAccount := Block(iBlock); FModifiedBlocksPreviousState.AddIfNotExists(blockAccount); If Assigned(FPreviousSafeBox) then begin Pblock := Nil; end else begin Pblock := FBlockAccountsList.Items[iBlock]; end; if (NOT TAccountComp.EqualAccountKeys(blockAccount.accounts[iAccount].accountInfo.accountKey,newAccountInfo.accountKey)) then begin AccountKeyListRemoveAccount(blockAccount.accounts[iAccount].accountInfo.accountKey,[account_number]); AccountKeyListAddAccounts(newAccountInfo.accountKey,[account_number]); end; {$IFDEF useAccountKeyStorage} // Delete old references prior to change TAccountKeyStorage.KS.RemoveAccountKey(blockAccount.accounts[iAccount].accountInfo.accountKey); TAccountKeyStorage.KS.RemoveAccountKey(blockAccount.accounts[iAccount].accountInfo.new_publicKey); {$ENDIF} blockAccount.accounts[iAccount].accountInfo := newAccountInfo; blockAccount.accounts[iAccount].account_type:=newType; lastbalance := blockAccount.accounts[iAccount].balance; blockAccount.accounts[iAccount].balance := newBalance; blockAccount.accounts[iAccount].n_operation := newN_operation; If (accountUpdateStyle In [aus_rollback,aus_commiting_from_otherchain]) then begin // Directly update name and updated values blockAccount.accounts[iAccount].name:=newName; blockAccount.accounts[iAccount].updated_block:=newUpdated_block; blockAccount.accounts[iAccount].previous_updated_block:=newPrevious_Updated_block; end else begin // Name: If blockAccount.accounts[iAccount].name<>newName then begin If blockAccount.accounts[iAccount].name<>'' then begin i := FOrderedByName.IndexOf(blockAccount.accounts[iAccount].name); if i<0 then begin If (Not Assigned(FPreviousSafeBox)) then begin TLog.NewLog(ltError,ClassName,'ERROR DEV 20170606-1 Name "'+blockAccount.accounts[iAccount].name+'" not found for delete on account '+IntToStr(account_number)); end; end else begin If (FOrderedByName.GetTag(i)<>account_number) then begin TLog.NewLog(ltError,ClassName,'ERROR DEV 20170606-3 Name "'+blockAccount.accounts[iAccount].name+'" not found for delete at suposed account '+IntToStr(account_number)+' found at '+IntToStr(FOrderedByName.GetTag(i))); end; FOrderedByName.Delete(i); end; iDeleted := FDeletedNamesSincePreviousSafebox.IndexOf(blockAccount.accounts[iAccount].name); iAdded := FAddedNamesSincePreviousSafebox.IndexOf(blockAccount.accounts[iAccount].name); If (iDeleted<0) then begin If (iAdded<0) then begin {$IFDEF HIGHLOG}TLog.NewLog(ltdebug,ClassName,Format('Deleted from PREVIOUS snapshot name:%s at account:%d',[blockAccount.accounts[iAccount].name,account_number]));{$ENDIF} FDeletedNamesSincePreviousSafebox.Add(blockAccount.accounts[iAccount].name,account_number); // Very important to store account_number in order to restore a snapshot! end else begin // Was added, so delete from added {$IFDEF HIGHLOG}TLog.NewLog(ltdebug,ClassName,Format('Deleted from current snapshot name:%s at account:%d',[blockAccount.accounts[iAccount].name,account_number]));{$ENDIF} FAddedNamesSincePreviousSafebox.Delete(iAdded); end; end else begin // Was deleted before, delete from added If (iAdded>=0) then begin FAddedNamesSincePreviousSafebox.Delete(iAdded); end; end; end; blockAccount.accounts[iAccount].name:=newName; If blockAccount.accounts[iAccount].name<>'' then begin i := FOrderedByName.IndexOf(blockAccount.accounts[iAccount].name); if i>=0 then TLog.NewLog(ltError,ClassName,'ERROR DEV 20170606-2 New Name "'+blockAccount.accounts[iAccount].name+'" for account '+IntToStr(account_number)+' found at account '+IntToStr(FOrderedByName.GetTag(i))); FOrderedByName.Add(blockAccount.accounts[iAccount].name,account_number); iDeleted := FDeletedNamesSincePreviousSafebox.IndexOf(blockAccount.accounts[iAccount].name); iAdded := FAddedNamesSincePreviousSafebox.IndexOf(blockAccount.accounts[iAccount].name); // Adding If (iDeleted>=0) Then begin if (FDeletedNamesSincePreviousSafebox.GetTag(iDeleted)=account_number) then begin // Is restoring to initial position, delete from deleted {$IFDEF HIGHLOG}TLog.NewLog(ltdebug,ClassName,Format('Adding equal to PREVIOUS (DELETING FROM DELETED) snapshot name:%s at account:%d',[blockAccount.accounts[iAccount].name,account_number]));{$ENDIF} FDeletedNamesSincePreviousSafebox.Delete(iDeleted); FAddedNamesSincePreviousSafebox.Remove(blockAccount.accounts[iAccount].name); end else begin // Was deleted, but now adding to a new account {$IFDEF HIGHLOG}TLog.NewLog(ltdebug,ClassName,Format('Adding again name:%s to new account account:%d',[blockAccount.accounts[iAccount].name,account_number]));{$ENDIF} FAddedNamesSincePreviousSafebox.Add(blockAccount.accounts[iAccount].name,account_number); end; end else begin // Was not deleted, Add it {$IFDEF HIGHLOG}TLog.NewLog(ltdebug,ClassName,Format('Adding first time at this snapshot name:%s at account:%d',[blockAccount.accounts[iAccount].name,account_number]));{$ENDIF} FAddedNamesSincePreviousSafebox.Add(blockAccount.accounts[iAccount].name,account_number); end; end; end; // Will update previous_updated_block only on first time/block If blockAccount.accounts[iAccount].updated_block<>BlocksCount then begin blockAccount.accounts[iAccount].previous_updated_block := blockAccount.accounts[iAccount].updated_block; blockAccount.accounts[iAccount].updated_block := BlocksCount; end; end; // Save new account values blockAccount.block_hash:=CalcBlockHash(blockAccount,FCurrentProtocol >= CT_PROTOCOL_2); FModifiedBlocksFinalState.Add(blockAccount); If Assigned(FPreviousSafeBox) then begin FModifiedBlocksSeparatedChain.Add(blockAccount); end; If (Assigned(Pblock)) then begin ToTMemAccount(blockAccount.accounts[iAccount],Pblock^.accounts[iAccount]); {$IFDEF uselowmem} TBaseType.To32Bytes(blockAccount.block_hash,Pblock^.block_hash); {$ELSE} Pblock^.block_hash := blockAccount.block_hash; {$ENDIF} end; // Update buffer block hash j := (length(blockAccount.block_hash)*(iBlock)); // j in 0,32,64... for i := 1 to length(blockAccount.block_hash) do begin // i in 1..32 FBufferBlocksHash[i+j] := AnsiChar(blockAccount.block_hash[i]); end; FTotalBalance := FTotalBalance - (Int64(lastbalance)-Int64(newBalance)); FTotalFee := FTotalFee + (Int64(lastbalance)-Int64(newBalance)); end; procedure TPCSafeBox.StartThreadSafe; begin TPCThread.ProtectEnterCriticalSection(Self,FLock); end; end.
unit uCadProduto; interface uses uProduto, FireDAc.Comp.Client, FireDAc.Stan.Param, Data.DB, FireDAc.DApt; type TCadProduto = class(TProduto) private FConexao : TFDConnection; public Constructor Create(poConexao: TFDConnection); virtual; Destructor Destroy(); override; function Insert : String; function Delete : String; function ConsDescricaoProduto: String; function fncConsUltimoProduto: Integer; function fncConsultaProduto: TFDQuery; end; implementation uses System.SysUtils; { TCadProduto } function TCadProduto.ConsDescricaoProduto: String; var vlsResult : String; voQuery : TFDQuery; begin voQuery := TFDQuery.Create(nil); voQuery.Close; voQuery.Connection := FConexao; try voQuery.SQL.Clear; voQuery.SQL.Add('SELECT PRO_DESCRICAOPRODUTO FROM PRODUTO WHERE PRO_EMPRESA = :PRO_EMPRESA AND PRO_CODPRODUTO = :PRO_CODPRODUTO'); voQuery.ParamByName('PRO_EMPRESA').AsInteger := pro_Empresa; voQuery.ParamByName('PRO_CODPRODUTO').AsInteger := pro_CodProduto; voQuery.Open(); vlsResult := voQuery.FieldByName('PRO_DESCRICAOPRODUTO').AsString; finally Result := vlsResult; FreeAndNil(voQuery); end; end; constructor TCadProduto.Create(poConexao: TFDConnection); begin inherited Create; FConexao := poConexao; end; function TCadProduto.Delete: String; var vlsResult : String; voQuery : TFDQuery; begin vlsResult := ''; voQuery := TFDQuery.Create(nil); try voQuery.Close; voQuery.Connection := FConexao; voQuery.SQL.Clear; voQuery.SQL.Add('DELETE FROM PRODUTO WHERE PRO_EMPRESA = :PRO_EMPRESA AND PRO_CODPRODUTO = :PRO_CODPRODUTO'); voQuery.ParamByName('PRO_EMPRESA').AsInteger := pro_Empresa; voQuery.ParamByName('PRO_CODPRODUTO').AsInteger := pro_CodProduto; try voQuery.ExecSQL; except on E:Exception do begin vlsResult := 'Erro na função: TCadProduto.Delete - ' + e.Message; end; end; finally Result := vlsResult; FreeAndNil(voQuery); end; end; destructor TCadProduto.Destroy; begin inherited; end; function TCadProduto.fncConsultaProduto: TFDQuery; var voQuery : TFDQuery; begin voQuery := TFDQuery.Create(nil); voQuery.Close; voQuery.Connection := FConexao; voQuery.SQL.Clear; voQuery.SQL.Add('SELECT PRO_CODINTPRODUTO, PRO_DESCRICAOPRODUTO, PRO_ESTOQUE '); voQuery.SQL.Add('FROM PRODUTO WHERE PRO_EMPRESA = :EMPRESA AND PRO_CODPRODUTO = :PRODUTO'); voQuery.ParamByName('EMPRESA').AsInteger := pro_Empresa; voQuery.ParamByName('PRODUTO').AsInteger := pro_CodProduto; voQuery.Open(); Result := voQuery; end; function TCadProduto.fncConsUltimoProduto: Integer; var vlsResult : Integer; voQuery : TFDQuery; begin voQuery := TFDQuery.Create(nil); voQuery.Close; voQuery.Connection := FConexao; try voQuery.SQL.Clear; voQuery.SQL.Add('SELECT MAX(PRO_CODPRODUTO) AS ULTIMO FROM PRODUTO WHERE PRO_EMPRESA = :EMPRESA'); voQuery.ParamByName('EMPRESA').AsInteger := pro_Empresa; voQuery.Open(); vlsResult := voQuery.FieldByName('ULTIMO').AsInteger + 1; finally Result := vlsResult; FreeAndNil(voQuery); end; end; function TCadProduto.Insert: String; var vlsResult : String; voQuery : TFDQuery; begin vlsResult := ''; voQuery := TFDQuery.Create(nil); try voQuery.Close; voQuery.Connection := FConexao; voQuery.SQL.Clear; voQuery.SQL.Add('SELECT PRO_EMPRESA FROM PRODUTO WHERE PRO_EMPRESA = :PRO_EMPRESA AND PRO_CODPRODUTO = :PRO_CODPRODUTO'); voQuery.ParamByName('PRO_EMPRESA').AsInteger := pro_Empresa; voQuery.ParamByName('PRO_CODPRODUTO').AsInteger := pro_CodProduto; voQuery.Open(); if voQuery.IsEmpty then begin voQuery.SQL.Clear; voQuery.SQL.Add('INSERT INTO PRODUTO (PRO_EMPRESA, PRO_CODPRODUTO, PRO_CODINTPRODUTO, '); voQuery.SQL.Add(' PRO_DESCRICAOPRODUTO, PRO_ESTOQUE)'); voQuery.SQL.Add('VALUES (:PRO_EMPRESA, :PRO_CODPRODUTO, :PRO_CODINTPRODUTO, '); voQuery.SQL.Add(' :PRO_DESCRICAOPRODUTO, :PRO_ESTOQUE)'); end else begin voQuery.SQL.Clear; voQuery.SQL.Add('UPDATE PRODUTO'); voQuery.SQL.Add('SET PRO_CODINTPRODUTO = :PRO_CODINTPRODUTO,'); voQuery.SQL.Add(' PRO_DESCRICAOPRODUTO = :PRO_DESCRICAOPRODUTO,'); voQuery.SQL.Add(' PRO_ESTOQUE = :PRO_ESTOQUE'); voQuery.SQL.Add('WHERE (PRO_EMPRESA = :PRO_EMPRESA) AND (PRO_CODPRODUTO = :PRO_CODPRODUTO)'); end; voQuery.ParamByName('PRO_EMPRESA').AsInteger := pro_Empresa; voQuery.ParamByName('PRO_CODPRODUTO').AsInteger := pro_CodProduto; voQuery.ParamByName('PRO_CODINTPRODUTO').AsInteger := pro_CodIntProduto; voQuery.ParamByName('PRO_DESCRICAOPRODUTO').AsString := pro_DescricaoProduto; voQuery.ParamByName('PRO_ESTOQUE').AsFloat := pro_Estoque; try voQuery.ExecSQL; except on E:Exception do begin vlsResult := 'Erro na função: TCadProduto.Insert - ' + e.Message; end; end; finally Result := vlsResult; FreeAndNil(voQuery); end; end; end.
{$IfNDef _fstFormSetWithSynchroForm_imp} {$Define _fstFormSetWithSynchroForm_imp} (* Сборка форм с формами синхронного просмотра *) _fstFormSetWithSynchroForm_ = class(_fstFormSetWithSynchroForm_Parent_) private f_SynchroForms: TnsSynchroFormList; {* - мапа идентификаторов форм и зон синхронного просмотра } f_CurrentSynchroForm: TList_SynchroView_Areas; {* - текущая форма синхронного просмотра } function pm_GetSynchroForms: TnsSynchroFormList; function pm_GetDefaultSynchroForm: TList_SynchroView_Areas; protected procedure DoCurrentSynchroFormChanged(anOld: TList_SynchroView_Areas; aNew: TList_SynchroView_Areas); virtual; {* - вызывается при изменении текущей формы синхронного просмотра (нужно ли?)} procedure AddSynchroForm(const aFormDescr: TvcmFormSetFormItemDescr; anArea: TList_SynchroView_Areas); {* - добавляет идентификатор формы и зоны синхронного просмотра в мапу} procedure InitSynchroForms; virtual; {* - инициализация мапы идентификаторов форм и зон синхронного просмотра} function DoGetDefaultSynchroForm: TList_SynchroView_Areas; virtual; protected // properties property SynchroForms: TnsSynchroFormList read pm_GetSynchroForms; protected // overriden procedure FormListAssigned; override; procedure CleanUp; override; protected function GetFormDescrForSynchroForm(aSynchroForm: TList_SynchroView_Areas): TvcmFormSetFormItemDescr; {* - возвращает идентификатор текущей формы синхронного просмотра } function pm_GetCurrentSynchroForm: TList_SynchroView_Areas; {* - возвращает идентификатор текущей зоны синхронного просмотра } procedure pm_SetCurrentSynchroForm(aValue: TList_SynchroView_Areas); {* - устанавливает текущую зону синхронного просмотра} function pm_GetCurrentSynchroFormNeedMakeDS: TvcmNeedMakeDS; {* - возвращает значение флажка TvcmNeedMakeDS для текущей формы синхронного просмотра} procedure pm_SetCurrentSynchroFormNeedMakeDS(aValue: TvcmNeedMakeDS); {* - устанавливает значение флажка TvcmNeedMakeDS для текущей формы синхронного просмотра} function StateIfSynchroFormActive: TvcmNeedMakeDS; virtual; procedure UpdateSynchroFormFlags; end; {$Else _fstFormSetWithSynchroForm_imp} function _fstFormSetWithSynchroForm_.pm_GetSynchroForms: TnsSynchroFormList; begin if (f_SynchroForms = nil) then begin f_SynchroForms := TnsSynchroFormList.Create; InitSynchroForms; end; Result := f_SynchroForms; end; function _fstFormSetWithSynchroForm_.pm_GetDefaultSynchroForm: TList_SynchroView_Areas; begin Result := DoGetDefaultSynchroForm; end; procedure _fstFormSetWithSynchroForm_.DoCurrentSynchroFormChanged(anOld: TList_SynchroView_Areas; aNew: TList_SynchroView_Areas); begin // Не знаю, нужно ли тут что-то делать end; procedure _fstFormSetWithSynchroForm_.AddSynchroForm(const aFormDescr: TvcmFormSetFormItemDescr; anArea: TList_SynchroView_Areas); begin SynchroForms.Add(TnsSynchroFormItem_C(aFormDescr, anArea)); end; procedure _fstFormSetWithSynchroForm_.InitSynchroForms; begin // Инициализация мапы идентификаторов форм и зон синхронного просмотра в потомках end; function _fstFormSetWithSynchroForm_.DoGetDefaultSynchroForm: TList_SynchroView_Areas; begin Result := sva_List_SynchroView_Document; end; function _fstFormSetWithSynchroForm_.GetFormDescrForSynchroForm(aSynchroForm: TList_SynchroView_Areas): TvcmFormSetFormItemDescr; begin Result := SynchroForms.Forms[aSynchroForm]; end; procedure _fstFormSetWithSynchroForm_.FormListAssigned; begin inherited; f_CurrentSynchroForm := pm_GetDefaultSynchroForm; UpdateSynchroFormFlags; end; procedure _fstFormSetWithSynchroForm_.CleanUp; begin inherited; FreeAndNil(f_SynchroForms); end; function _fstFormSetWithSynchroForm_.pm_GetCurrentSynchroForm: TList_SynchroView_Areas; begin Result := f_CurrentSynchroForm; end; procedure _fstFormSetWithSynchroForm_.pm_SetCurrentSynchroForm(aValue: TList_SynchroView_Areas); var l_PrevSynchroForm: TList_SynchroView_Areas; begin if (aValue <> f_CurrentSynchroForm) then begin l_PrevSynchroForm := f_CurrentSynchroForm; f_CurrentSynchroForm := aValue; UpdateSynchroFormFlags; // - При смене формы синхронного просмотра нужно синхронизировать флажки DoCurrentSynchroFormChanged(l_PrevSynchroForm, f_CurrentSynchroForm); end;//(aValue <> f_CurrentSynchroForm) end; function _fstFormSetWithSynchroForm_.pm_GetCurrentSynchroFormNeedMakeDS: TvcmNeedMakeDS; begin Result := GetFormNeedMakeDS(GetFormDescrForSynchroForm(f_CurrentSynchroForm)); end; procedure _fstFormSetWithSynchroForm_.pm_SetCurrentSynchroFormNeedMakeDS(aValue: TvcmNeedMakeDS); begin SetFormNeedMakeDS(GetFormDescrForSynchroForm(f_CurrentSynchroForm), aValue); end; function _fstFormSetWithSynchroForm_.StateIfSynchroFormActive: TvcmNeedMakeDS; begin Result := vcm_nmYes; end; procedure _fstFormSetWithSynchroForm_.UpdateSynchroFormFlags; function lp_DoUpdateSynchroFormFlags(aForm: PnsSynchroFormItem; aIndex: Integer): Boolean; var l_NeedMake: TvcmNeedMakeDS; begin if (aForm^.rArea <> f_CurrentSynchroForm) then l_NeedMake := vcm_nmNo else l_NeedMake := StateIfSynchroFormActive; SetFormNeedMakeDS(aForm^.rKey, l_NeedMake); Result := True; end;//lp_DoUpdateSynchroFormFlags begin SynchroForms.IterateAllF(l3L2IA(@lp_DoUpdateSynchroFormFlags)); end; {$EndIf _fstFormSetWithSynchroForm_imp}
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA 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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit frmTablespaceProperties; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, cxMemo, cxRichEdit, cxSpinEdit, cxMaskEdit, cxButtonEdit, cxGroupBox, cxCheckBox, cxLabel, cxContainer, cxEdit, cxTextEdit, dxBar, cxPC, cxControls, cxGraphics, cxDropDownEdit, cxImageComboBox,GenelDM, OraTablespace, VirtualTable, frmBaseform; type TTablespacePropertiesFrm = class(TBaseform) Panel1: TPanel; imgToolBar: TImage; pcTablespaceProperties: TcxPageControl; tsRollbackSegmentDetails: TcxTabSheet; dxBarDockControl1: TdxBarDockControl; edtName: TcxTextEdit; cxLabel1: TcxLabel; tsSequenceScripts: TcxTabSheet; redtDDL: TcxRichEdit; dxBarManager1: TdxBarManager; bbtnCreateTablespace: TdxBarButton; bbtnAlterTablespace: TdxBarButton; bbtnDropTablespace: TdxBarButton; bbtnRefreshTablespace: TdxBarButton; bbtnTakeOffTablespace: TdxBarButton; bbtnTakeOnTablespace: TdxBarButton; cxLabel2: TcxLabel; Label11: TcxLabel; Label12: TcxLabel; Label13: TcxLabel; Label14: TcxLabel; edtInitialExtend: TcxButtonEdit; edtNextExtend: TcxButtonEdit; edtMinExtents: TcxSpinEdit; edtMaxExtents: TcxSpinEdit; Label1: TcxLabel; edtPctIncrease: TcxButtonEdit; icbStatus: TcxImageComboBox; Label2: TcxLabel; icbContents: TcxImageComboBox; Label3: TcxLabel; Label4: TcxLabel; icbLogging: TcxImageComboBox; cbForceLogging: TcxCheckBox; icbExtentManagement: TcxImageComboBox; Label5: TcxLabel; Label6: TcxLabel; icbRetention: TcxImageComboBox; Label7: TcxLabel; cbBigFile: TcxCheckBox; Label8: TcxLabel; edtMinExtlen: TcxSpinEdit; tsDataFile: TcxTabSheet; tsObjects: TcxTabSheet; tsFramentation: TcxTabSheet; edtBlockSize: TcxButtonEdit; icbSgmentSpaceManagement: TcxImageComboBox; cxLabel3: TcxLabel; cbCompress: TcxCheckBox; icbAllocationType: TcxImageComboBox; lblDescription: TLabel; procedure bbtnCreateTablespaceClick(Sender: TObject); procedure bbtnAlterTablespaceClick(Sender: TObject); procedure bbtnDropTablespaceClick(Sender: TObject); procedure bbtnTakeOnTablespaceClick(Sender: TObject); procedure bbtnTakeOffTablespaceClick(Sender: TObject); procedure bbtnRefreshTablespaceClick(Sender: TObject); private { Private declarations } FTablespaceName : string; Tablespace: TTablespace; procedure GetTablespace; procedure GetTablespaceDetail; public { Public declarations } procedure Init(ObjName, OwnerName: string); override; end; var TablespacePropertiesFrm: TTablespacePropertiesFrm; implementation {$R *.dfm} uses frmSchemaBrowser, Util, OraStorage, frmSchemaPublicEvent, frmTablespaceDetail, VisualOptions; procedure TTablespacePropertiesFrm.Init(ObjName, OwnerName: string); begin inherited Show; DMGenel.ChangeLanguage(self); ChangeVisualGUI(self); top := 0; left := 0; FTablespaceName := ObjName; GetTablespace; end; procedure TTablespacePropertiesFrm.GetTablespace; begin if Tablespace <> nil then FreeAndNil(Tablespace); Tablespace := TTablespace.Create; Tablespace.OraSession := TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).OraSession; Tablespace.TABLESPACE_NAME := FTablespaceName; Tablespace.SetDDL; lblDescription.Caption := FTablespaceName; GetTablespaceDetail; redtDDL.Text := Tablespace.GetDDL; CodeColors(self, 'Default', redtDDL, false); end; procedure TTablespacePropertiesFrm.GetTablespaceDetail; begin with Tablespace do begin edtName.Text := TABLESPACE_NAME; edtBlockSize.Text := FloatToStr(BLOCK_SIZE); edtInitialExtend.Text := FloatToStr(INITIAL_EXTENT); edtNextExtend.Text := FloatToStr(NEXT_EXTENT); edtMinExtents.Text := FloatToStr(MIN_EXTENTS); edtMaxExtents.Text := FloatToStr(MAX_EXTENTS); edtPctIncrease.Text := FloatToStr(PCT_INCREASE); edtMinExtlen.Text := FloatToStr(MIN_EXTLEN); icbStatus.ItemIndex := Integer(STATUS); icbContents.ItemIndex := Integer(CONTENTS); icbLogging.ItemIndex := Integer(LOGGING); cbForceLogging.Checked := FORCE_LOGGING; icbExtentManagement.ItemIndex := Integer(EXTENT_MANAGEMENT); icbAllocationType.ItemIndex := Integer(ALLOCATION_TYPE); icbSgmentSpaceManagement.ItemIndex := integer(SEGMENT_SPACE_MANAGEMENT); cbCompress.Checked := DEF_TAB_COMPRESSION; icbRetention.ItemIndex := Integer(RETENTION); cbBigFile.Checked := BIGFILE; end; end; procedure TTablespacePropertiesFrm.bbtnCreateTablespaceClick( Sender: TObject); var FTablespace : TTablespace; begin inherited; FTablespace := TTablespace.Create; FTablespace.OraSession := Tablespace.OraSession; FTablespace.Mode := InsertMode; if TablespaceDetailFrm.Init(FTablespace) then TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbTablespaces); end; procedure TTablespacePropertiesFrm.bbtnAlterTablespaceClick( Sender: TObject); begin inherited; if Tablespace = nil then exit; Tablespace.Mode := UpdateMode; if TablespaceDetailFrm.Init(Tablespace) then TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbTablespaces); end; procedure TTablespacePropertiesFrm.bbtnDropTablespaceClick( Sender: TObject); begin inherited; if Tablespace = nil then exit; if Tablespace.TABLESPACE_NAME = '' then exit; if SchemaPublicEventFrm.Init(Tablespace, oeDrop) then TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbTablespaces); end; procedure TTablespacePropertiesFrm.bbtnTakeOnTablespaceClick( Sender: TObject); begin inherited; if Tablespace = nil then exit; if Tablespace.TABLESPACE_NAME = '' then exit; if SchemaPublicEventFrm.Init(Tablespace, oeOnLine) then TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbTablespaces); end; procedure TTablespacePropertiesFrm.bbtnTakeOffTablespaceClick( Sender: TObject); begin inherited; if Tablespace = nil then exit; if Tablespace.TABLESPACE_NAME = '' then exit; if SchemaPublicEventFrm.Init(Tablespace, oeOffLine) then TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbTablespaces); end; procedure TTablespacePropertiesFrm.bbtnRefreshTablespaceClick( Sender: TObject); begin inherited; GetTablespace; end; end.
unit eInterestSimulator.Model.AmortizacaoConstante; interface uses eInterestSimulator.Model.Interfaces; type TModelAmortizacaoAmortizacaoConstante = class(TInterfacedObject, iResultado) private FNumeroParcela: Integer; FValorJuros: Real; FValorAmortizacao: Real; FValorSaldo: Real; FValorPagamento: Real; function NumeroParcela(Value: Integer): iResultado; overload; function NumeroParcela: Integer; overload; function ValorJuros(Value: Real): iResultado; overload; function ValorJuros: Real; overload; function ValorAmortizacao(Value: Real): iResultado; overload; function ValorAmortizacao: Real; overload; function ValorSaldo(Value: Real): iResultado; overload; function ValorSaldo: Real; overload; function ValorPagamento(Value: Real): iResultado; overload; function ValorPagamento: Real; overload; public constructor Create; destructor Destroy; override; class function New: iResultado; end; implementation { TModelAmortizacao } constructor TModelAmortizacaoAmortizacaoConstante.Create; begin end; destructor TModelAmortizacaoAmortizacaoConstante.Destroy; begin inherited; end; class function TModelAmortizacaoAmortizacaoConstante.New: iResultado; begin Result := Self.Create; end; function TModelAmortizacaoAmortizacaoConstante.NumeroParcela(Value: Integer) : iResultado; begin Result := Self; FNumeroParcela := Value; end; function TModelAmortizacaoAmortizacaoConstante.NumeroParcela: Integer; begin Result := FNumeroParcela; end; function TModelAmortizacaoAmortizacaoConstante.ValorAmortizacao(Value: Real) : iResultado; begin Result := Self; FValorAmortizacao := Value; end; function TModelAmortizacaoAmortizacaoConstante.ValorAmortizacao: Real; begin Result := FValorAmortizacao; end; function TModelAmortizacaoAmortizacaoConstante.ValorJuros(Value: Real) : iResultado; begin Result := Self; FValorJuros := Value; end; function TModelAmortizacaoAmortizacaoConstante.ValorJuros: Real; begin Result := FValorJuros; end; function TModelAmortizacaoAmortizacaoConstante.ValorPagamento: Real; begin Result := FValorPagamento; end; function TModelAmortizacaoAmortizacaoConstante.ValorPagamento(Value: Real) : iResultado; begin Result := Self; FValorPagamento := Value; end; function TModelAmortizacaoAmortizacaoConstante.ValorSaldo(Value: Real) : iResultado; begin Result := Self; FValorSaldo := Value; end; function TModelAmortizacaoAmortizacaoConstante.ValorSaldo: Real; begin Result := FValorSaldo; end; end.
unit CsConst; { $Id: CsConst.pas,v 1.14 2012/03/06 09:18:12 narry Exp $ } // $Log: CsConst.pas,v $ // Revision 1.14 2012/03/06 09:18:12 narry // Получать с сервера список групп доступа Переданные в регион (273581950) // // Revision 1.13 2010/07/06 12:31:02 narry // - К222759027 // // Revision 1.12 2010/03/04 07:47:56 narry // - обновление списка пользователей // // Revision 1.11 2010/02/24 10:30:50 narry // - удаление зависимости проектов от парня // // Revision 1.10 2007/11/28 11:16:47 narry // - Увеличение версии протокола обмена сообщениями // // Revision 1.9 2006/11/28 11:19:25 narry // - ошибка: подвисание Арчи при получении сообщения от сервера // // Revision 1.8 2006/09/15 06:51:26 narry // - починка обмена сообщениями между сервером и клиентом // // Revision 1.7 2006/09/01 13:55:00 narry // - при подключении клиента к серверу проверяются версии клиента и сервера // // Revision 1.6 2006/08/03 13:22:01 narry // - увеличение версии протокола и реакция на ее не совпадение // // Revision 1.5 2006/08/02 12:57:32 narry // - увеличение версии протокола // // Revision 1.4 2006/03/16 15:50:16 narry // - еще один шажок в сторону клиент-сервера // // Revision 1.3 2006/02/08 17:24:29 step // выполнение запросов перенесено из классов-потомков в процедуры объектов // {$I CsDefine.inc} interface const c_CsVersion: Integer = 18; c_AllStations = '*'; // адрес для широковещания c_WrongClientId = MaxInt; // говорит об отказе в регистрации c_DuplicateClient = Pred(c_WrongClientID); // попытка войти повторно c_DeadClient = Pred(c_DuplicateClient); // не отвечает на запросы // коды ошибок обработки запросов cs_errOk = 0; cs_errError = 1; cs_errConnClosedGracefully = 2; cs_errConnectTimeout = 3; cs_errSocketError = 4; cs_errConnAborted = 5; cs_errConnRefused = 6; cs_errWrongServerVersion = 7; implementation end.
unit Unit26; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls; type TForm26 = class(TForm) Button1: TButton; Panel1: TPanel; procedure FormCreate(Sender: TObject); private { Private declarations } procedure ExecuteAfterInit(sender:TObject); public { Public declarations } end; TBancoParaCarrosDePasseio = class; TCarroDePasseio = class private FBanco: TBancoParaCarrosDePasseio; public constructor create(AValor: boolean); virtual; procedure init; virtual; end; TCarroDePasseio1 = class(TCarroDePasseio) private FList: TStringList; FData: TDatetime; FBanco: TBancoParaCarrosDePasseio; FafterInit: TNotifyevent; function Getitems(idx: integer): string; procedure Setitems(idx: integer; const Value: string); procedure SetafterInit(const Value: TNotifyevent); public procedure init; override; constructor create(AValor: boolean); overload; override; constructor create(AValor: integer; AData: TDatetime); overload; property Banco: TBancoParaCarrosDePasseio read FBanco write FBanco; function count: integer; property items[idx: integer]: string read Getitems write Setitems; property afterInit: TNotifyevent read FafterInit write SetafterInit; end; TBancoParaCarrosDePasseio = class strict private FPrivate1: string; private type TPintura = class cor: integer; procedure initPintura; end; public procedure init; end; var Form26: TForm26; implementation {$R *.dfm} procedure TForm26.ExecuteAfterInit(sender: TObject); begin showmessage('teste'); end; procedure TForm26.FormCreate(Sender: TObject); var btn, btn1: TButton; var LPintura: TBancoParaCarrosDePasseio.TPintura; begin LPintura := TBancoParaCarrosDePasseio.TPintura.create; try LPintura.cor := 111; caption := LPintura.cor.ToString; finally LPintura.Free; end; with TCarroDePasseio1.create(true) do try afterInit := ExecuteAfterInit; init; finally DisposeOf; end; btn := TButton.create(self); btn.Parent := Panel1; btn.caption := 'MeuBotao'; // btn.Top := 10; // btn.Left := 10; btn1 := TButton.create(self); btn1.Parent := Panel1; btn1.caption := 'MeuBotao,,,,,,,,,,,,,'; btn1.Left := 100; with TButton.create(self) do begin Parent := Panel1; Left := 100; top := 100; caption := 'botao com with'; end; end; { TBancoParaCarrosDePasseio } procedure TBancoParaCarrosDePasseio.init; var LPintura: TPintura; begin // TPintura end; { TCarroDePasseio } constructor TCarroDePasseio.create(AValor: boolean); begin end; procedure TCarroDePasseio.init; begin // FBanco.FPrivate1 := 'asss'; end; { TCarroDePasseio1 } constructor TCarroDePasseio1.create(AValor: boolean); begin inherited create(AValor); // faz outra operašcao. end; function TCarroDePasseio1.count: integer; begin result := FList.count; end; constructor TCarroDePasseio1.create(AValor: integer; AData: TDatetime); begin inherited create(false); FData := AData; end; function TCarroDePasseio1.Getitems(idx: integer): string; begin result := FList[idx]; end; procedure TCarroDePasseio1.init; begin inherited; if assigned(afterInit) then afterInit(self); end; procedure TCarroDePasseio1.SetafterInit(const Value: TNotifyevent); begin FafterInit := Value; end; procedure TCarroDePasseio1.Setitems(idx: integer; const Value: string); begin FList[idx] := Value; end; { TBancoParaCarrosDePasseio.TPintura } procedure TBancoParaCarrosDePasseio.TPintura.initPintura; begin end; end.
unit UnderControlKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы UnderControl } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\UnderControl\Forms\UnderControlKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "UnderControlKeywordsPack" MUID: (4ABCD2D80364_Pack) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , UnderControl_Form , tfwControlString , kwBynameControlPush , tfwScriptingInterfaces , nscTreeViewWithAdapterDragDrop , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *4ABCD2D80364_Packimpl_uses* //#UC END# *4ABCD2D80364_Packimpl_uses* ; type Tkw_Form_UnderControl = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы UnderControl ---- *Пример использования*: [code]форма::UnderControl TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_UnderControl Tkw_UnderControl_Control_UnderControlList = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола UnderControlList ---- *Пример использования*: [code]контрол::UnderControlList TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_UnderControl_Control_UnderControlList Tkw_UnderControl_Control_UnderControlList_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола UnderControlList ---- *Пример использования*: [code]контрол::UnderControlList:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_UnderControl_Control_UnderControlList_Push function Tkw_Form_UnderControl.GetString: AnsiString; begin Result := 'enUnderControl'; end;//Tkw_Form_UnderControl.GetString class procedure Tkw_Form_UnderControl.RegisterInEngine; begin inherited; TtfwClassRef.Register(TenUnderControl); end;//Tkw_Form_UnderControl.RegisterInEngine class function Tkw_Form_UnderControl.GetWordNameForRegister: AnsiString; begin Result := 'форма::UnderControl'; end;//Tkw_Form_UnderControl.GetWordNameForRegister function Tkw_UnderControl_Control_UnderControlList.GetString: AnsiString; begin Result := 'UnderControlList'; end;//Tkw_UnderControl_Control_UnderControlList.GetString class procedure Tkw_UnderControl_Control_UnderControlList.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscTreeViewWithAdapterDragDrop); end;//Tkw_UnderControl_Control_UnderControlList.RegisterInEngine class function Tkw_UnderControl_Control_UnderControlList.GetWordNameForRegister: AnsiString; begin Result := 'контрол::UnderControlList'; end;//Tkw_UnderControl_Control_UnderControlList.GetWordNameForRegister procedure Tkw_UnderControl_Control_UnderControlList_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('UnderControlList'); inherited; end;//Tkw_UnderControl_Control_UnderControlList_Push.DoDoIt class function Tkw_UnderControl_Control_UnderControlList_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::UnderControlList:push'; end;//Tkw_UnderControl_Control_UnderControlList_Push.GetWordNameForRegister initialization Tkw_Form_UnderControl.RegisterInEngine; {* Регистрация Tkw_Form_UnderControl } Tkw_UnderControl_Control_UnderControlList.RegisterInEngine; {* Регистрация Tkw_UnderControl_Control_UnderControlList } Tkw_UnderControl_Control_UnderControlList_Push.RegisterInEngine; {* Регистрация Tkw_UnderControl_Control_UnderControlList_Push } TtfwTypeRegistrator.RegisterType(TypeInfo(TenUnderControl)); {* Регистрация типа TenUnderControl } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.
namespace RemObjects.Train.API; interface uses RemObjects.Train, System.Collections.Generic, System.Linq, System.Threading, System.Text, RemObjects.Script.EcmaScript.Internal, System.IO, RemObjects.Script.EcmaScript, System.Security.Cryptography, Amazon.S3.*; type [PluginRegistration] S3PlugIn = public class(IPluginRegistration) public method &Register(aServices: IApiRegistrationServices); [WrapAs('S3.listFiles', SkipDryRun := true, wantSelf := true)] class method ListFiles(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine; aPrefix, aSuffix: String; aRecurse: Boolean := true): array of String; [WrapAs('S3.downloadFile', SkipDryRun := true, wantSelf := true)] class method DownloadFile(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine; aKey, aLocalTarget: String); [WrapAs('S3.readFile', SkipDryRun := true, wantSelf := true)] class method ReadFile(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine; aKey: String): String; [WrapAs('S3.downloadFiles', SkipDryRun := true, wantSelf := true)] class method DownloadFiles(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine; aPrefix: String; aSuffix: String := nil; aLocalTargetDir: String; aRecurse: Boolean); [WrapAs('S3.uploadFile', SkipDryRun := true, wantSelf := true)] class method UploadFile(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine; aLocalFile, aKey: String); [WrapAs('S3.writeFile', SkipDryRun := true, wantSelf := true)] class method WriteFile(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine; aString, aKey: String); [WrapAs('S3.uploadFiles', SkipDryRun := true, wantSelf := true)] class method UploadFiles(aServices: IApiRegistrationServices; ec: ExecutionContext;aSelf: S3Engine; aLocalFolderAndFilters, aPrefix: String; aRecurse: Boolean); [WrapAs('s3.bucket', wantSelf := true)] class method GetBucket(aServices: IApiRegistrationServices; ec: ExecutionContext;aSelf: S3Engine): String; [WrapAs('s3.bucket', wantSelf := true)] class method SetBucket(aServices: IApiRegistrationServices; ec: ExecutionContext;aSelf: S3Engine; val: String); [WrapAs('s3.serviceURL', wantSelf := true)] class method GetServiceURL(aServices: IApiRegistrationServices; ec: ExecutionContext;aSelf: S3Engine): String; [WrapAs('s3.serviceURL', wantSelf := true)] class method SetServiceURL(aServices: IApiRegistrationServices; ec: ExecutionContext;aSelf: S3Engine; val: String); [WrapAs('s3.accessKeyID', wantSelf := true)] class method GetAccessKeyID(aServices: IApiRegistrationServices; ec: ExecutionContext;aSelf: S3Engine): String; [WrapAs('s3.accessKeyID', wantSelf := true, SecretArguments := [0])] class method SetAccessKeyID(aServices: IApiRegistrationServices; ec: ExecutionContext;aSelf: S3Engine; val: String); [WrapAs('s3.secretAccessKey', wantSelf := true)] class method GetSecretAccessKey(aServices: IApiRegistrationServices; ec: ExecutionContext;aSelf: S3Engine): String; [WrapAs('s3.secretAccessKey', wantSelf := true, SecretArguments := [0])] class method SetSecretAccessKey(aServices: IApiRegistrationServices; ec: ExecutionContext;aSelf: S3Engine; val: String); [WrapAs('s3.regionEndpoint', wantSelf := true)] class method GetRegionEndpoint(aServices: IApiRegistrationServices; ec: ExecutionContext;aSelf: S3Engine): String; [WrapAs('s3.regionEndpoint', wantSelf := true)] class method SetRegionEndpoint(aServices: IApiRegistrationServices; ec: ExecutionContext;aSelf: S3Engine; val: String); end; S3Engine = public class private fClient: AmazonS3Client; method GetClient: AmazonS3Client; assembly method ResetClient; property Bucket: String; property ServiceURL: String; property AccessKeyID: String; property SecretAccessKey: String; property RegionEndpoint: String; property S3Client: AmazonS3Client read GetClient; property Timeout: TimeSpan := TimeSpan.FromSeconds(60); end; implementation method S3PlugIn.&Register(aServices: IApiRegistrationServices); begin //aServices.RegisterValue('S3', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(Self), 'Include')); var lProto := new EcmaScriptObject(aServices.Globals); lProto.Prototype := aServices.Globals.ObjectPrototype; lProto.AddValue('listFiles', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(S3PlugIn), 'ListFiles')); lProto.AddValue('downloadFile', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(S3PlugIn), 'DownloadFile')); lProto.AddValue('readFile', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(S3PlugIn), 'ReadFile')); lProto.AddValue('downloadFiles', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(S3PlugIn), 'DownloadFiles')); lProto.AddValue('uploadFile', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(S3PlugIn), 'UploadFile')); lProto.AddValue('writeFile', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(S3PlugIn), 'WriteFile')); lProto.AddValue('uploadFiles', RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(S3PlugIn), 'UploadFiles')); lProto.DefineOwnProperty('bucket', new PropertyValue(PropertyAttributes.All, RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(S3PlugIn), 'GetBucket'), RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(S3PlugIn), 'SetBucket'))); lProto.DefineOwnProperty('serviceURL', new PropertyValue(PropertyAttributes.All, RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(S3PlugIn), 'GetServiceURL'), RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(S3PlugIn), 'SetServiceURL'))); lProto.DefineOwnProperty('accessKeyID', new PropertyValue(PropertyAttributes.All, RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(S3PlugIn), 'GetAccessKeyID'), RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(S3PlugIn), 'SetAccessKeyID'))); lProto.DefineOwnProperty('secretAccessKey', new PropertyValue(PropertyAttributes.All, RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(S3PlugIn), 'GetSecretAccessKey'), RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(S3PlugIn), 'SetSecretAccessKey'))); lProto.DefineOwnProperty('regionEndpoint', new PropertyValue(PropertyAttributes.All, RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(S3PlugIn), 'GetRegionEndpoint'), RemObjects.Train.MUtilities.SimpleFunction(aServices.Engine, typeOf(S3PlugIn), 'SetRegionEndpoint'))); var lObj := new EcmaScriptFunctionObject(aServices.Globals, 'S3', (aCaller, aSElf, aArgs) -> begin exit new WrapperObject(aCaller.Global, lProto, Val := new S3Engine); end, 1, &Class := 'S3'); aServices.Globals.Values.Add('S3', PropertyValue.NotEnum(lObj)); lObj.Values['prototype'] := PropertyValue.NotAllFlags(lProto); lProto.Values['constructor'] := PropertyValue.NotEnum(lProto); end; { S3 Logic } class method S3PlugIn.ListFiles(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine; aPrefix: String; aSuffix: String; aRecurse: Boolean := true): array of String; begin aPrefix := aPrefix:Replace("//", "/"); if not aPrefix.EndsWith("/") then aPrefix := aPrefix+"/"; var lastKey := ""; var preLastKey := ""; var lList := new List<String>(); repeat preLastKey := lastKey; var lRequest := new ListObjectsRequest(BucketName := aSelf.Bucket, Prefix := aPrefix, Marker := lastKey); var newObjects := aSelf.S3Client.ListObjects(lRequest):S3Objects:Select(o -> o.Key); for each o in newObjects do begin lList.Add(o); lastKey := o; end; until lastKey = preLastKey; var lResult: sequence of String := lList; if assigned(aSuffix) then lResult := lResult:&Where(o -> o.EndsWith(aSuffix)); if not aRecurse then lResult := lResult:&Select(o -> begin o := o.Substring(aPrefix.Length); result := o.Split('/').FirstOrDefault; end):&Where(o -> assigned(o)):Distinct(); result := lResult.ToArray(); end; class method S3PlugIn.DownloadFile(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine; aKey: String; aLocalTarget: String); begin aLocalTarget := aServices.ResolveWithBase(ec, aLocalTarget); aKey := aServices.Expand(ec, aKey); if aLocalTarget.EndsWith(Path.DirectorySeparatorChar) or Directory.Exists(aLocalTarget) then aLocalTarget := Path.Combine(aLocalTarget, Path.GetFileName(aKey)); var lCleanedKey := aSelf.Bucket+"-"+aKey.Replace("/","-"); var lDownloadTarget := aLocalTarget; var lS3CacheFolder := aServices.Environment.Item["TRAIN_S3_CACHE"] as String; if length(lS3CacheFolder) > 0 then begin if not Directory.Exists(lS3CacheFolder) then Directory.CreateDirectory(lS3CacheFolder); lDownloadTarget := Path.Combine(lS3CacheFolder, lCleanedKey); end; if not System.IO.Directory.Exists(Path.GetDirectoryName(aLocalTarget)) then Directory.CreateDirectory(Path.GetDirectoryName(aLocalTarget)); try using lRequest := new GetObjectRequest(BucketName := aSelf.Bucket, Key := aKey) do begin using lResult := aSelf.S3Client.GetObject(lRequest) do begin //aServices.Logger.LogMessage("File.Exists?: {0}", File.Exists(lDownloadTarget)); //aServices.Logger.LogMessage("lResult.LastModified: {0}", lResult.LastModified); //if File.Exists(lDownloadTarget) then begin // aServices.Logger.LogMessage("File.GetLastWriteTimeUtc(lDownloadTarget).AddSeconds(+10): {0}", File.GetLastWriteTimeUtc(lDownloadTarget).AddSeconds(+10)); // aServices.Logger.LogMessage("File.GetLastWriteTimeUtc(lDownloadTarget).AddSeconds(+10) >= lResult.LastModified?: {0}", File.GetLastWriteTimeUtc(lDownloadTarget).AddSeconds(+10) >= lResult.LastModified); //end; if File.Exists(lDownloadTarget) and (File.GetLastWriteTimeUtc(lDownloadTarget).AddSeconds(+10) >= lResult.LastModified {and (new FileInfo(lDownloadTarget).Length = lResult.Size}) then begin aServices.Logger.LogMessage('File {0} is up to date locally.', Path.GetFileName(aLocalTarget)); end else begin aServices.Logger.LogMessage('Downloading {0} from S3 to {1}.', aKey, lDownloadTarget); using s := lResult.ResponseStream do using w := new FileStream(lDownloadTarget, FileMode.Create, FileAccess.Write, FileShare.Delete) do s.CopyTo(w); File.SetLastWriteTime(lDownloadTarget, lResult.LastModified); end; end; end; except if File.Exists(lDownloadTarget) then File.Delete(lDownloadTarget); raise; end; if lDownloadTarget ≠ aLocalTarget then begin if File.Exists(aLocalTarget) then File.Delete(aLocalTarget); aServices.Logger.LogMessage('Copying from cache to {0}.', aLocalTarget); if File.Exists(lDownloadTarget) then RemObjects.Elements.RTL.File.CopyTo(lDownloadTarget, aLocalTarget, true); end; end; class method S3PlugIn.ReadFile(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine; aKey: String): String; begin aKey := aServices.Expand(ec, aKey); using lRequest := new GetObjectRequest(BucketName := aSelf.Bucket, Key := aKey) do using lResult := aSelf.S3Client.GetObject(lRequest) do using s := lResult.ResponseStream do using r := new StreamReader(s) do result := r.ReadToEnd(); end; class method S3PlugIn.DownloadFiles(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine; aPrefix: String; aSuffix: String := nil; aLocalTargetDir: String; aRecurse: Boolean); begin aLocalTargetDir := aServices.ResolveWithBase(ec, aLocalTargetDir); aPrefix := aServices.Expand(ec, aPrefix); aSuffix := aServices.Expand(ec, aSuffix); aServices.Logger.LogMessage('Downloading files in {0} from S3 to {1}', aPrefix, aLocalTargetDir); var lFiles := ListFiles(aServices, ec, aSelf, aPrefix, aSuffix); for each f in lFiles do begin var f2 := f.Substring(aPrefix.Length).Trim(); if length(f2) > 0 then begin var lFolder := Path.GetDirectoryName(f2); var lFile := Path.GetFileName(f2); var lTargetFile := Path.Combine(aLocalTargetDir, lFile); if length(lFolder) > 0 then begin if not aRecurse then continue; lFolder := lFolder.Replace("/",Path.DirectorySeparatorChar); lTargetFile := Path.Combine(Path.Combine(aLocalTargetDir, lFolder), lFile); end; DownloadFile(aServices, ec, aSelf, f, lTargetFile); end; end; end; class method S3PlugIn.UploadFile(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine; aLocalFile: String; aKey: String); begin aLocalFile := aServices.ResolveWithBase(ec, aLocalFile); aKey := aServices.Expand(ec, aKey); aKey := aKey.Replace("//", "/"); // S3 really doesn't like those. if aKey.EndsWith("/") then aKey := aKey+Path.GetFileName(aLocalFile); // if aKey is a folder, reuse local filename aServices.Logger.LogMessage('Uploading file {0} to {1} on S3', aLocalFile, aKey); using lStream := new FileStream(aLocalFile, FileMode.Open, FileAccess.Read, FileShare.Delete) do using lRequest := new PutObjectRequest(BucketName := aSelf.Bucket, Key := aKey, InputStream := lStream, Timeout := aSelf.Timeout) do using lResponse := aSelf.S3Client.PutObject(lRequest) do; end; class method S3PlugIn.WriteFile(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine; aString: String; aKey: String); begin aKey := aServices.Expand(ec, aKey); using lRequest := new PutObjectRequest(BucketName := aSelf.Bucket, Key := aKey, ContentBody := aString) do using lResponse := aSelf.S3Client.PutObject(lRequest) do; end; class method S3PlugIn.UploadFiles(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine; aLocalFolderAndFilters: String; aPrefix: String; aRecurse: Boolean); begin aLocalFolderAndFilters := aServices.ResolveWithBase(ec, aLocalFolderAndFilters); aPrefix := aServices.Expand(ec, aPrefix); aPrefix := aPrefix:Replace("//", "/"); if not aPrefix.EndsWith("/") then aPrefix := aPrefix+"/"; // force aPrefix to be a folder aServices.Logger.LogMessage('Uploading files {0} to {1} on S3', aLocalFolderAndFilters, aPrefix); var lFolder := aLocalFolderAndFilters; var lFilter := Path.GetFileName(aLocalFolderAndFilters); if lFilter.Contains('*') or lFilter.Contains('?') then lFolder := Path.GetDirectoryName(lFolder) else lFilter := nil; var lFiles := if assigned(lFilter) then Directory.GetFiles(lFolder,lFilter) else Directory.GetFiles(lFolder); for each f in lFiles do UploadFile(aServices, ec, aSelf, f, aPrefix+Path.GetFileName(f)); if aRecurse then begin var lFolders := Directory.GetDirectories(lFolder); for each f in lFolders do begin var f2 := if assigned(lFilter) then Path.Combine(f, lFilter) else f; UploadFiles(aServices, ec, aSelf, f2, Path.Combine(aPrefix, Path.GetFileName(f)), true); end; end; end; { Properties } class method S3PlugIn.GetBucket(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine): String; begin result := aSelf.Bucket; end; class method S3PlugIn.SetBucket(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine; val: String); begin aSelf.Bucket := aServices.Expand(ec, val); end; class method S3PlugIn.GetServiceURL(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine): String; begin result := aSelf.ServiceURL; end; class method S3PlugIn.SetServiceURL(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine; val: String); begin aSelf.ServiceURL := aServices.Expand(ec, val); aSelf.ResetClient(); end; class method S3PlugIn.GetAccessKeyID(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine): String; begin result := aSelf.AccessKeyID end; class method S3PlugIn.SetAccessKeyID(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine; val: String); begin aSelf.AccessKeyID := aServices.Expand(ec, val); aSelf.ResetClient(); end; class method S3PlugIn.GetSecretAccessKey(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine): String; begin result := aSelf.SecretAccessKey end; class method S3PlugIn.SetSecretAccessKey(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine; val: String); begin aSelf.SecretAccessKey := aServices.Expand(ec, val); aSelf.ResetClient(); end; class method S3PlugIn.GetRegionEndpoint(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine): String; begin result := aSelf.RegionEndpoint end; class method S3PlugIn.SetRegionEndpoint(aServices: IApiRegistrationServices; ec: ExecutionContext; aSelf: S3Engine; val: String); begin aSelf.RegionEndpoint := aServices.Expand(ec, val); aSelf.ResetClient(); end; method S3Engine.GetClient: AmazonS3Client; begin if not assigned(fClient) then begin var lConfig := new Amazon.S3.AmazonS3Config(); lConfig.ServiceURL := if length(ServiceURL) > 0 then ServiceURL else 'https://s3.amazonaws.com'; //if length(RegionEndpoint) > 0 then lConfig.RegionEndpoint := RegionEndpoint; fClient := new Amazon.S3.AmazonS3Client(AccessKeyID, SecretAccessKey, lConfig); end; result := fClient; end; method S3Engine.ResetClient; begin fClient := nil; end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm1 = class(TForm) btnEscreverPinPad: TButton; btnIniciar: TButton; btTestarPinpad: TButton; btnDigitaCPF: TButton; edtRetorno: TEdit; Label1: TLabel; procedure btnDigitaCPFClick(Sender: TObject); procedure btnIniciarClick(Sender: TObject); procedure btTestarPinpadClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnEscreverPinPadClick(Sender: TObject); private { Private declarations } public { Public declarations } FDll: THandle; function CapturaCPF : string; end; function VerificaPresencaPinPad () : integer; far; stdcall; external 'CliSiTef32I.dll'; function EscreveMensagemPinPad (MsgDisplay : PAnsiChar): integer; far; stdcall; external 'CliSiTef32I.dll'; function ObtemDadoPinPadDiretoEx (ChaveAcesso: PAnsichar; Identificador: PAnsichar; Entrada: PAnsichar; Saida: PAnsichar ): integer; far; stdcall; external 'CliSiTef32I.dll'; function ObtemDadoPinPadEx (ChaveAcesso: PAnsichar; Identificador: PAnsiChar; Entrada: PAnsiChar ): integer; far; stdcall; external 'CliSiTef32I.dll'; function ConfiguraIntSiTefInterativo ( pEnderecoIP: PAnsiChar; pCodigoLoja: PAnsiChar; pNumeroTerminal: PAnsiChar; ConfiguraResultado: smallint ): integer; far; stdcall; external 'CliSiTef32I.dll'; function IniciaFuncaoSiTefInterativo ( Modalidade: integer; pValor: PansiChar; pNumeroCuponFiscal: PansiChar; pDataFiscal: PansiChar; pHorario: PansiChar; pOperador: PansiChar; pRestricoes: PansiChar ): integer; far; stdcall; external 'CliSiTef32I.dll'; procedure FinalizaTransacaoSiTefInterativo ( smallint: Word; pNumeroCuponFiscal: PansiChar; pDataFiscal: PansiChar; pHorario: PansiChar ); far; stdcall; external 'CliSiTef32I.dll'; function ContinuaFuncaoSiTefInterativo ( var ProximoComando: Integer; var TipoCampo: Integer; var TamanhoMinimo: smallint; var TamanhoMaximo: smallint; pBuffer: PansiChar; TamMaxBuffer: Integer; ContinuaNavegacao: Integer ): integer; far; stdcall; external 'CliSiTef32I.dll'; var Form1: TForm1; const IP = '127.0.0.1'; IDLOJA = '00000000'; TERMINAL = 'SE000001'; MSG =' ** Teste ** '; implementation {$R *.dfm} procedure TForm1.btnDigitaCPFClick(Sender: TObject); begin edtRetorno.Text := CapturaCPF; end; procedure TForm1.btnEscreverPinPadClick(Sender: TObject); var iRtn : Integer; begin iRtn := EscreveMensagemPinPad (MSG); edtRetorno.Text := IntToStr(iRtn); end; procedure TForm1.btnIniciarClick(Sender: TObject); var lRetorno : Integer; begin lRetorno := -1; lRetorno:= ConfiguraIntSiTefInterativo (PAnsiChar(IP), PAnsiChar(IDLOJA), PAnsiChar(AnsiString(TERMINAL)), 0); case lRetorno of 0 : edtRetorno.Text := '0 - Sitef Configurado.'; 1 : edtRetorno.Text := '1 - Endereço IP inválido ou não resolvido'; 2 : edtRetorno.Text := '2 - Código da loja inválido'; 3 : edtRetorno.Text := '3 - Código de terminal inválido'; 6 : edtRetorno.Text := '6 - Erro na inicialização do Tcp/Ip'; 7 : edtRetorno.Text := '7 - Falta de memória'; 8 : edtRetorno.Text := '8 - Não encontrou a CliSiTef ou ela está com problemas'; 9 : edtRetorno.Text := '9 - Configuração de servidores SiTef foi excedida.'; 10: edtRetorno.Text := '10 - Erro de acesso na pasta CliSiTef (possível falta de permissão para escrita)'; 11: edtRetorno.Text := '11 - Dados inválidos passados pela automação.'; 12: edtRetorno.Text := '12 - Modo seguro não ativo (possível falta de configuração no servidor SiTef do arquivo .cha).'; 13: edtRetorno.Text := '13 - Caminho DLL inválido (o caminho completo das bibliotecas está muito grande).'; end; if lRetorno = 0 then begin btnEscreverPinPad.Enabled := True; btTestarPinpad.Enabled := True; btnDigitaCPF.Enabled := True; end; end; procedure TForm1.btTestarPinpadClick(Sender: TObject); var lRetorno : Integer; begin lRetorno := VerificaPresencaPinpad(); case lRetorno of 1 : edtRetorno.Text := '1 - Existe um PinPad conectado ao micro.'; 0 : edtRetorno.Text := '0 - Não existe um PinPad conectado ao micro.'; -1: edtRetorno.Text := '(-1) - Biblioteca de acesso não encontrada.'; end; end; function TForm1.CapturaCPF: string; var lMsg1: Ansistring; lSaida: array [0..16] of ansichar; lResult: integer; begin lSaida := ''; lMsg1 := ' **** COLOQUE A CHAVE AQUI *****'; lMsg1 := lMsg1 + ' **** COLOQUE A CHAVE AQUI *****'; lMsg1 := lMsg1 +' **** COLOQUE A CHAVE AQUI *****'; lMsg1 := lMsg1 + ' **** COLOQUE A CHAVE AQUI *****'+ chr(0); lResult := ObtemDadoPinPadDiretoEx(PAnsiChar('##W*ges(527)'), '08.754.527.0001-13', '011111CPF CONFIRME O CPF |xxx.xxx.xxx-xx ', lSaida); if (lResult = 0) then result := 'Campo de saída: ' + lSaida else result := IntToStr(lResult); end; procedure TForm1.FormShow(Sender: TObject); begin btnEscreverPinPad.Enabled := False; btTestarPinpad.Enabled := False; btnDigitaCPF.Enabled := False; end; end.
unit uProtoBufGenerator; interface uses System.SysUtils, System.Classes, uAbstractProtoBufClasses, uProtoBufParserAbstractClasses, uProtoBufParserClasses; type TProtoBufGenerator = class(TObject) strict private procedure GenerateInterfaceSection(Proto: TProtoFile; SL: TStrings); procedure GenerateImplementationSection(Proto: TProtoFile; SL: TStrings); public procedure Generate(Proto: TProtoFile; Output: TStrings); overload; procedure Generate(Proto: TProtoFile; OutputStream: TStream; Encoding: TEncoding = nil); overload; procedure Generate(Proto: TProtoFile; const OutputDir: string; Encoding: TEncoding = nil); overload; procedure Generate(const InputFile: string; const OutputDir: string; Encoding: TEncoding = nil); overload; end; implementation uses System.StrUtils; function ProtoPropTypeToDelphiType(const PropTypeName: string): string; var StandartType: TScalarPropertyType; i: Integer; begin StandartType := StrToPropertyType(PropTypeName); case StandartType of sptDouble: Result := 'Double'; sptFloat: Result := 'Single'; sptInt32: Result := 'Integer'; sptInt64: Result := 'Int64'; sptuInt32: Result := 'Cardinal'; sptUint64: Result := 'UInt64'; sptSInt32: Result := 'Integer'; sptSInt64: Result := 'Int64'; sptFixed32: Result := 'Integer'; sptFixed64: Result := 'Int64'; sptSFixed32: Result := 'Integer'; sptSFixed64: Result := 'Int64'; sptBool: Result := 'Boolean'; sptString: Result := 'string'; sptBytes: Result := 'TBytes'; else i := LastDelimiter('.', PropTypeName); Result := 'T' + Copy(PropTypeName, i + 1, Length(PropTypeName)); end; end; function PropertyIsPrimitiveNumericPacked(Prop: TProtoBufProperty): Boolean; begin Result := (Prop.PropOptions.Value['packed'] = 'true') and (StrToPropertyType(Prop.PropType) in [sptDouble, sptFloat, sptInt32, sptInt64, sptuInt32, sptUint64, sptSInt32, sptSInt64, sptBool, sptFixed32, sptSFixed32, sptFixed64, sptSFixed64]) end; function GetProtoBufMethodForScalarType(const Prop: TProtoBufProperty): string; var StandartType: TScalarPropertyType; bPacked: Boolean; begin StandartType := StrToPropertyType(Prop.PropType); bPacked := (Prop.PropKind = ptRepeated) and PropertyIsPrimitiveNumericPacked(Prop); case StandartType of sptComplex: ; sptDouble: if bPacked then Result := 'RawData' else Result := 'Double'; sptFloat: if bPacked then Result := 'RawData' else Result := 'Float'; sptInt32: if bPacked then Result := 'RawVarint32' else Result := 'Int32'; sptInt64: if bPacked then Result := 'RawVarint64' else Result := 'Int64'; sptuInt32: if bPacked then Result := 'RawVarint32' else Result := 'UInt32'; sptUint64: if bPacked then Result := 'RawVarint64' else Result := 'Int64'; sptSInt32: if bPacked then Result := 'RawSInt32' else Result := 'SInt32'; sptSInt64: if bPacked then Result := 'RawSInt64' else Result := 'SInt64'; sptFixed32: if bPacked then Result := 'RawData' else Result := 'Fixed32'; sptFixed64: if bPacked then Result := 'RawData' else Result := 'Fixed64'; sptSFixed32: if bPacked then Result := 'RawData' else Result := 'SFixed32'; sptSFixed64: if bPacked then Result := 'RawData' else Result := 'SFixed64'; sptBool: if bPacked then Result := 'RawBoolean' else Result := 'Boolean'; sptString: Result := 'String'; sptBytes: Result := 'Bytes'; end; end; function ReQuoteStr(const Str: string): string; begin Result := Str; if not StartsStr('"', Str) then Exit; Result := StringReplace(Str, '''', '''''', [rfReplaceAll]); Result := StringReplace(Result, '""', '"', [rfReplaceAll]); Result[1] := ''''; Result[Length(Result)] := ''''; end; type TDelphiProperty = record IsList: Boolean; isComplex: Boolean; isObject: Boolean; PropertyName: string; PropertyType: string; function tagName: string; function readOnlyDelphiProperty: Boolean; end; procedure ParsePropType(Prop: TProtoBufProperty; Proto: TProtoFile; out DelphiProp: TDelphiProperty); begin DelphiProp.IsList := Prop.PropKind = ptRepeated; DelphiProp.isComplex := StrToPropertyType(Prop.PropType) = sptComplex; if DelphiProp.isComplex then DelphiProp.isObject := Assigned(Proto.ProtoBufMessages.FindByName(Prop.PropType)) else DelphiProp.isObject := False; if not DelphiProp.IsList then begin DelphiProp.PropertyName := Prop.Name; DelphiProp.PropertyType := ProtoPropTypeToDelphiType(Prop.PropType); end else begin DelphiProp.PropertyName := Format('%sList', [Prop.Name]); if DelphiProp.isObject then DelphiProp.PropertyType := Format('TProtoBufClassList<%s>', [ProtoPropTypeToDelphiType(Prop.PropType)]) else DelphiProp.PropertyType := Format('TPBList<%s>', [ProtoPropTypeToDelphiType(Prop.PropType)]); end; end; function MsgNeedConstructor(ProtoMsg: TProtoBufMessage; Proto: TProtoFile): Boolean; var i: Integer; DelphiProp: TDelphiProperty; Prop: TProtoBufProperty; begin Result := False; for i := 0 to ProtoMsg.Count - 1 do begin Prop := ProtoMsg[i]; ParsePropType(Prop, Proto, DelphiProp); Result := (Prop.PropKind = ptRequired) or DelphiProp.IsList or DelphiProp.isObject or Prop.PropOptions.HasValue['default']; if Result then Break; end; end; function MsgContainsRepeatedFields(ProtoMsg: TProtoBufMessage): Boolean; var i: Integer; begin Result := False; for i := 0 to ProtoMsg.Count - 1 do if ProtoMsg[i].PropKind = TPropKind.ptRepeated then begin Result := True; Break; end; end; { TProtoBufGenerator } procedure TProtoBufGenerator.Generate(Proto: TProtoFile; Output: TStrings); var SLInterface, SLImplementation: TStrings; begin // write name and interface uses SLInterface := TStringList.Create; try SLImplementation := TStringList.Create; try GenerateInterfaceSection(Proto, SLInterface); GenerateImplementationSection(Proto, SLImplementation); Output.Clear; Output.AddStrings(SLInterface); Output.AddStrings(SLImplementation); finally SLImplementation.Free; end; finally SLInterface.Free; end; end; procedure TProtoBufGenerator.Generate(Proto: TProtoFile; OutputStream: TStream; Encoding: TEncoding); var SL: TStrings; begin SL := TStringList.Create; try SL.WriteBOM := True; Generate(Proto, SL); SL.SaveToStream(OutputStream, Encoding); finally SL.Free; end; end; procedure TProtoBufGenerator.Generate(Proto: TProtoFile; const OutputDir: string; Encoding: TEncoding); var FS: TFileStream; begin FS := TFileStream.Create(IncludeTrailingPathDelimiter(OutputDir) + Proto.Name + '.pas', fmCreate); try Generate(Proto, FS, Encoding); finally FS.Free; end; end; procedure TProtoBufGenerator.GenerateImplementationSection(Proto: TProtoFile; SL: TStrings); procedure WriteConstructor(ProtoMsg: TProtoBufMessage; SL: TStrings); var Prop: TProtoBufProperty; DelphiProp: TDelphiProperty; i: Integer; begin SL.Add(Format('constructor T%s.Create;', [ProtoMsg.Name])); SL.Add('begin'); SL.Add(' inherited;'); for i := 0 to ProtoMsg.Count - 1 do begin Prop := ProtoMsg[i]; ParsePropType(Prop, Proto, DelphiProp); if DelphiProp.IsList or DelphiProp.isObject then SL.Add(Format(' F%s := %s.Create;', [DelphiProp.PropertyName, DelphiProp.PropertyType])); if Prop.PropOptions.HasValue['default'] then SL.Add(Format(' %s%s := %s;', [IfThen(DelphiProp.readOnlyDelphiProperty, 'F', ''), DelphiProp.PropertyName, ReQuoteStr(Prop.PropOptions.Value['default'])])); if Prop.PropKind = ptRequired then SL.Add(Format(' RegisterRequiredField(%s);', [DelphiProp.tagName])); end; SL.Add('end;'); SL.Add(''); SL.Add(Format('destructor T%s.Destroy;', [ProtoMsg.Name])); SL.Add('begin'); for i := 0 to ProtoMsg.Count - 1 do begin Prop := ProtoMsg[i]; ParsePropType(Prop, Proto, DelphiProp); if DelphiProp.IsList or DelphiProp.isObject then SL.Add(Format(' F%s.Free;', [DelphiProp.PropertyName])); end; SL.Add(' inherited;'); SL.Add('end;'); SL.Add(''); end; procedure WriteLoadProc(ProtoMsg: TProtoBufMessage; SL: TStrings); var i, iInsertVarBlock, iInserttmpBufCreation, iBeginBlock: Integer; Prop: TProtoBufProperty; DelphiProp, OneOfDelphiProp: TDelphiProperty; bNeedtmpBuf: Boolean; sIndent: string; begin bNeedtmpBuf:= False; SL.Add(Format('function T%s.LoadSingleFieldFromBuf(ProtoBuf: TProtoBufInput; FieldNumber: Integer; WireType: Integer): Boolean;', [ProtoMsg.Name])); iInsertVarBlock:= SL.Count; SL.Add('begin'); SL.Add(' Result := inherited;'); if ProtoMsg.Count = 0 then begin SL.Add('end;'); Exit; end; SL.Add(' if Result then'); SL.Add(' Exit;'); SL.Add(' Result := True;'); iInserttmpBufCreation:= SL.Count; SL.Add(' case FieldNumber of'); for i := 0 to ProtoMsg.Count - 1 do begin Prop := ProtoMsg[i]; ParsePropType(Prop, Proto, DelphiProp); if Prop.PropKind = ptOneOf then Continue; SL.Add(Format(' %s:', [DelphiProp.tagName])); iBeginBlock:= SL.Count; SL.Add(' begin'); sIndent:= StringOfChar(' ', 8); {4 for case + 4 for tag and begin/end} if not DelphiProp.IsList then begin if not DelphiProp.isComplex then SL.Add(Format('%s%s := ProtoBuf.read%s;', [sIndent, DelphiProp.PropertyName, GetProtoBufMethodForScalarType(Prop)])) else if not DelphiProp.isObject then SL.Add(Format('%s%s := %s(ProtoBuf.readEnum);', [sIndent, DelphiProp.PropertyName, DelphiProp.PropertyType])) else begin bNeedtmpBuf:= True; SL.Add(Format('%stmpBuf := ProtoBuf.ReadSubProtoBufInput;', [sIndent])); SL.Add(Format('%sF%s.LoadFromBuf(tmpBuf);', [sIndent, DelphiProp.PropertyName])); end; end else begin if not DelphiProp.isComplex then begin if PropertyIsPrimitiveNumericPacked(Prop) then begin bNeedtmpBuf:= True; SL.Add(Format('%sif WireType = WIRETYPE_LENGTH_DELIMITED then', [sIndent])); SL.Add(Format('%sbegin', [sIndent])); SL.Add(Format('%s tmpBuf:=ProtoBuf.ReadSubProtoBufInput;', [sIndent])); SL.Add(Format('%s while tmpBuf.getPos < tmpBuf.BufSize do', [sIndent])); SL.Add(Format('%s F%s.Add(tmpBuf.read%s);', [sIndent, DelphiProp.PropertyName, GetProtoBufMethodForScalarType(Prop)])); SL.Add(Format('%send else', [sIndent])); SL.Add(Format('%s F%s.Add(ProtoBuf.read%s);', [sIndent, DelphiProp.PropertyName, GetProtoBufMethodForScalarType(Prop)])); end else SL.Add(Format('%sF%s.Add(ProtoBuf.read%s);', [sIndent, DelphiProp.PropertyName, GetProtoBufMethodForScalarType(Prop)])); end else if not DelphiProp.isObject then begin if (Prop.PropOptions.Value['packed'] = 'true') then begin bNeedtmpBuf:= True; SL.Add(Format('%sif WireType = WIRETYPE_LENGTH_DELIMITED then', [sIndent])); SL.Add(Format('%sbegin', [sIndent])); SL.Add(Format('%s tmpBuf:=ProtoBuf.ReadSubProtoBufInput;', [sIndent])); SL.Add(Format('%s while tmpBuf.getPos<tmpBuf.BufSize do', [sIndent])); SL.Add(Format('%s F%s.Add(T%s(tmpBuf.readEnum));', [sIndent, DelphiProp.PropertyName, Prop.PropType])); SL.Add(Format('%send else', [sIndent])); SL.Add(Format('%s F%s.Add(T%s(ProtoBuf.readEnum));', [sIndent, DelphiProp.PropertyName, Prop.PropType])); end else SL.Add(Format('%sF%s.Add(T%s(ProtoBuf.readEnum));', [sIndent, DelphiProp.PropertyName, Prop.PropType])); end else SL.Add(Format('%sF%s.AddFromBuf(ProtoBuf, fieldNumber);', [sIndent, DelphiProp.PropertyName])); end; if Prop.OneOfPropertyParent <> nil then //GitHub issue #30: extra oneOf setter is not necessary if property setter was used if DelphiProp.IsList or DelphiProp.isComplex or DelphiProp.isObject then begin ParsePropType(Prop.OneOfPropertyParent, Proto, OneOfDelphiProp); SL.Add(Format('%s%s:= %s_%s_%s;', [sIndent, OneOfDelphiProp.PropertyName, ProtoMsg.Name, OneOfDelphiProp.PropertyName, DelphiProp.PropertyName])); end; if SL.Count = iBeginBlock + 2 then begin //we added only begin and one extra line, so remove begin block and //remove 2 intending spaces from the one inserted line SL.Delete(iBeginBlock); SL[iBeginBlock]:= Copy(SL[iBeginBlock], 3, MaxInt); end else SL.Add(' end;'); end; SL.Add(' else'); SL.Add(' Result := False;'); SL.Add(' end;'); if bNeedtmpBuf then begin SL.Insert(iInsertVarBlock, ' tmpBuf: TProtoBufInput;'); SL.Insert(iInsertVarBlock, 'var'); Inc(iInserttmpBufCreation, 2); //we just added two lines for the declaration SL.Insert(iInserttmpBufCreation, ' try'); SL.Insert(iInserttmpBufCreation, ' tmpBuf:= nil;'); for i:= iInserttmpBufCreation + 2 to SL.Count - 1 do SL[i]:= ' ' + SL[i]; SL.Add(' finally'); SL.Add(' tmpBuf.Free'); SL.Add(' end;'); end; SL.Add('end;'); SL.Add(''); end; procedure WriteSaveProc(ProtoMsg: TProtoBufMessage; SL: TStrings); var i, iInsertVarBlock, iInserttmpBufCreation: Integer; Prop: TProtoBufProperty; DelphiProp: TDelphiProperty; bNeedtmpBuf, bNeedCounterVar: Boolean; begin bNeedtmpBuf:= False; bNeedCounterVar:= False; SL.Add(Format('procedure T%s.SaveFieldsToBuf(ProtoBuf: TProtoBufOutput);', [ProtoMsg.Name])); iInsertVarBlock:= sl.Count; SL.Add('begin'); SL.Add(' inherited;'); iInserttmpBufCreation:= SL.Count; for i := 0 to ProtoMsg.Count - 1 do begin Prop := ProtoMsg[i]; ParsePropType(Prop, Proto, DelphiProp); if Prop.PropKind = ptOneOf then Continue; SL.Add(Format(' if FieldHasValue[%s] then', [DelphiProp.tagName])); if not DelphiProp.IsList then begin if not DelphiProp.isComplex then SL.Add(Format(' ProtoBuf.write%s(%s, F%s);', [GetProtoBufMethodForScalarType(Prop), DelphiProp.tagName, DelphiProp.PropertyName])) else if not DelphiProp.isObject then SL.Add(Format(' ProtoBuf.writeInt32(%s, Integer(F%s));', [DelphiProp.tagName, DelphiProp.PropertyName])) else begin bNeedtmpBuf:= True; SL.Add(Format(' SaveMessageFieldToBuf(F%s, %s, tmpBuf, ProtoBuf);', [DelphiProp.PropertyName, DelphiProp.tagName])); end; end else begin if not DelphiProp.isComplex then begin if PropertyIsPrimitiveNumericPacked(Prop) then begin bNeedtmpBuf:= True; bNeedCounterVar:= True; SL.Add( ' begin'); SL.Add( ' tmpBuf.Clear;'); SL.Add(Format(' for i := 0 to F%s.Count-1 do', [DelphiProp.PropertyName])); SL.Add(Format(' tmpBuf.write%s(F%s[i]);', [GetProtoBufMethodForScalarType(Prop), DelphiProp.PropertyName])); SL.Add(Format(' ProtoBuf.writeMessage(%s, tmpBuf);', [DelphiProp.tagName])); SL.Add( ' end;'); end else begin bNeedCounterVar:= True; SL.Add(Format(' for i := 0 to F%s.Count-1 do', [DelphiProp.PropertyName])); SL.Add(Format(' ProtoBuf.write%s(%s, F%s[i]);', [GetProtoBufMethodForScalarType(Prop), DelphiProp.tagName, DelphiProp.PropertyName])); end; end else if not DelphiProp.isObject then begin if Prop.PropOptions.Value['packed'] = 'true' then begin bNeedtmpBuf:= True; bNeedCounterVar:= True; SL.Add( ' begin'); SL.Add( ' tmpBuf.Clear;'); SL.Add(Format(' for i := 0 to F%s.Count-1 do', [DelphiProp.PropertyName])); SL.Add(Format(' tmpBuf.writeRawVarint32(Integer(F%s[i]));', [DelphiProp.PropertyName])); SL.Add(Format(' ProtoBuf.writeMessage(%s, tmpBuf);', [DelphiProp.tagName])); SL.Add( ' end;'); end else begin bNeedCounterVar:= True; SL.Add(Format(' for i := 0 to F%s.Count-1 do', [DelphiProp.PropertyName])); SL.Add(Format(' ProtoBuf.writeInt32(%s, Integer(F%s[i]));', [DelphiProp.tagName, DelphiProp.PropertyName])); end; end else SL.Add(Format(' F%s.SaveToBuf(ProtoBuf, %s);', [DelphiProp.PropertyName, DelphiProp.tagName])); end; end; if bNeedtmpBuf or bNeedCounterVar then begin if bNeedCounterVar then begin SL.Insert(iInsertVarBlock, ' i: Integer;'); Inc(iInserttmpBufCreation); end; if bNeedtmpBuf then begin SL.Insert(iInsertVarBlock, ' tmpBuf: TProtoBufOutput;'); Inc(iInserttmpBufCreation); end; SL.Insert(iInsertVarBlock, 'var'); Inc(iInserttmpBufCreation); if bNeedtmpBuf then begin SL.Insert(iInserttmpBufCreation, ' try'); SL.Insert(iInserttmpBufCreation, ' tmpBuf:= TProtoBufOutput.Create;'); for i:= iInserttmpBufCreation + 2 to SL.Count - 1 do SL[i]:= ' ' + SL[i]; SL.Add(' finally'); SL.Add(' tmpBuf.Free'); SL.Add(' end;'); end; end; SL.Add('end;'); SL.Add(''); end; procedure WriteSetterProcs(ProtoMsg: TProtoBufMessage; SL: TStrings); var i, j: Integer; Prop, OneOfChildProp: TProtoBufProperty; DelphiProp, OneOfDelphiProp: TDelphiProperty; begin for i := 0 to ProtoMsg.Count - 1 do begin Prop := ProtoMsg[i]; ParsePropType(Prop, Proto, DelphiProp); if DelphiProp.readOnlyDelphiProperty then Continue; if Prop.PropKind = ptOneOf then SL.Add(Format('procedure T%s.Set%s(const Value: %s);', [ProtoMsg.Name, DelphiProp.PropertyName, DelphiProp.PropertyType])) else SL.Add(Format('procedure T%s.Set%s(Tag: Integer; const Value: %s);', [ProtoMsg.Name, DelphiProp.PropertyName, DelphiProp.PropertyType])); SL.Add('begin'); SL.Add(Format(' F%s:= Value;', [DelphiProp.PropertyName])); if Prop.PropKind = ptOneOf then begin //clear FieldHasValue for all others of this OneOf for j:= i + 1 to ProtoMsg.Count - 1 do begin OneOfChildProp:= ProtoMsg[j]; ParsePropType(OneOfChildProp, Proto, OneOfDelphiProp); if OneOfChildProp.OneOfPropertyParent <> Prop then Break; SL.Add(Format(' FieldHasValue[%s]:= Value = %s_%s_%s;', [OneOfDelphiProp.tagName, ProtoMsg.Name, DelphiProp.PropertyName, OneOfDelphiProp.PropertyName])); end; end else begin if Prop.OneOfPropertyParent <> nil then begin ParsePropType(Prop.OneOfPropertyParent, Proto, OneOfDelphiProp); SL.Add(Format(' %s:= %s_%s_%s;', [OneOfDelphiProp.PropertyName, ProtoMsg.Name, OneOfDelphiProp.PropertyName, DelphiProp.PropertyName])); end else SL.Add(' FieldHasValue[Tag]:= True;'); end; SL.Add('end;'); SL.Add(''); end; end; procedure WriteMessageToSL(ProtoMsg: TProtoBufMessage; SL: TStrings); var bNeedConstructor: Boolean; begin if ProtoMsg.IsImported then Exit; bNeedConstructor := MsgNeedConstructor(ProtoMsg, Proto); SL.Add(Format('{ T%s }', [ProtoMsg.Name])); SL.Add(''); if bNeedConstructor then WriteConstructor(ProtoMsg, SL); WriteLoadProc(ProtoMsg, SL); WriteSaveProc(ProtoMsg, SL); WriteSetterProcs(ProtoMsg, SL); end; var i: Integer; begin SL.Add('implementation'); SL.Add(''); for i := 0 to Proto.ProtoBufMessages.Count - 1 do if not Proto.ProtoBufMessages[i].IsImported then WriteMessageToSL(Proto.ProtoBufMessages[i], SL); SL.Add('end.'); end; procedure TProtoBufGenerator.GenerateInterfaceSection(Proto: TProtoFile; SL: TStrings); procedure WriteBeforeComments(AComments, SL: TStrings; const Indent: string = ' '); var i: Integer; begin for i:= 0 to AComments.Count - 1 do SL.Add(Format('%s//%s', [Indent, AComments[i]])); end; procedure WriteEnumToSL(ProtoEnum: TProtoBufEnum; SL: TStrings); var i: Integer; s: string; begin if ProtoEnum.IsImported then Exit; WriteBeforeComments(ProtoEnum.Comments, SL); SL.Add(Format(' T%s=(', [ProtoEnum.Name])); for i := 0 to ProtoEnum.Count - 1 do begin if ProtoEnum[i].Comments.Count > 1 then WriteBeforeComments(ProtoEnum[i].Comments, SL, ' '); s:= Format(' %s = %s%s', [ProtoEnum[i].Name, ProtoEnum.GetEnumValueString(i), IfThen(i < (ProtoEnum.Count - 1), ',', '')]); if ProtoEnum[i].Comments.Count = 1 then s:= Format('%s //%s', [s, ProtoEnum[i].Comments[0]]); SL.Add(s); end; SL.Add(' );'); end; procedure WriteMessageToSL(ProtoMsg: TProtoBufMessage; SL: TStrings); var i, j: Integer; Prop, OneOfProp: TProtoBufProperty; DelphiProp, OneOfDelphiProp: TDelphiProperty; s, sdefValue: string; begin if ProtoMsg.IsImported then Exit; WriteBeforeComments(ProtoMsg.Comments, SL); if ProtoMsg.ExtendOf = '' then s := 'AbstractProtoBufClass' else s := ProtoMsg.ExtendOf; SL.Add(Format(' T%s = class(T%s)', [ProtoMsg.Name, s])); //write tag constants and OneOfEnums, need to be first since //OneOfEnum is used for strict private field SL.Add(' public'); for i := 0 to ProtoMsg.Count - 1 do begin Prop := ProtoMsg[i]; ParsePropType(Prop, Proto, DelphiProp); if Prop.PropKind = ptOneOf then Continue; s := Format(' const %s = %d;', [DelphiProp.tagName, Prop.PropFieldNum]); SL.Add(s); end; //write oneOfEnums, using the tag constants we just wrote for i:= 0 to ProtoMsg.Count - 1 do begin OneOfProp := ProtoMsg[i]; if OneOfProp.PropKind <> ptOneOf then Continue; ParsePropType(OneOfProp, Proto, OneOfDelphiProp); SL.Add(Format(' type %s = (', [OneOfDelphiProp.PropertyType])); SL.Add(Format(' %s_%s_Nothing = 0,', [ProtoMsg.Name, OneOfDelphiProp.PropertyName])); for j:= i + 1 to ProtoMsg.Count - 1 do begin Prop:= ProtoMsg[j]; if Prop.OneOfPropertyParent <> OneOfProp then Break; ParsePropType(Prop, Proto, DelphiProp); SL.Add(Format(' %s_%s_%s = %s,', [ProtoMsg.Name, OneOfDelphiProp.PropertyName, DelphiProp.PropertyName, DelphiProp.tagName])); end; //remove comma of last enum value s:= SL[SL.Count - 1]; SL[SL.Count - 1]:= Copy(s, 1, Length(s) - 1); SL.Add(' );'); end; SL.Add(' strict private'); //field definitions for i := 0 to ProtoMsg.Count - 1 do begin Prop := ProtoMsg[i]; ParsePropType(Prop, Proto, DelphiProp); SL.Add(Format(' F%s: %s;', [DelphiProp.PropertyName, DelphiProp.PropertyType])); end; SL.Add(''); //property setters for i := 0 to ProtoMsg.Count - 1 do begin Prop := ProtoMsg[i]; ParsePropType(Prop, Proto, DelphiProp); if DelphiProp.readOnlyDelphiProperty then Continue; if Prop.PropKind = ptOneOf then s := Format(' procedure Set%s(const Value: %s);', [DelphiProp.PropertyName, DelphiProp.PropertyType]) else s := Format(' procedure Set%s(Tag: Integer; const Value: %s);', [DelphiProp.PropertyName, DelphiProp.PropertyType]); SL.Add(s); end; SL.Add(' strict protected'); SL.Add(' function LoadSingleFieldFromBuf(ProtoBuf: TProtoBufInput; FieldNumber: Integer; WireType: Integer): Boolean; override;'); SL.Add(' procedure SaveFieldsToBuf(ProtoBuf: TProtoBufOutput); override;'); SL.Add(' public'); if MsgNeedConstructor(ProtoMsg, Proto) then begin SL.Add(' constructor Create; override;'); SL.Add(' destructor Destroy; override;'); SL.Add(''); end; for i := 0 to ProtoMsg.Count - 1 do begin Prop := ProtoMsg[i]; ParsePropType(Prop, Proto, DelphiProp); for j:= 0 to Prop.Comments.Count - 1 do SL.Add(' //' + Prop.Comments[j]); if DelphiProp.readOnlyDelphiProperty then begin s := Format(' property %s: %s read F%s', [DelphiProp.PropertyName, DelphiProp.PropertyType, DelphiProp.PropertyName]); end else begin if Prop.PropKind = ptOneOf then begin s := Format(' property %s: %s read F%s write Set%s', [DelphiProp.PropertyName, DelphiProp.PropertyType, DelphiProp.PropertyName, DelphiProp.PropertyName]); end else begin s := Format(' property %s: %s index %s read F%s write Set%s', [DelphiProp.PropertyName, DelphiProp.PropertyType, DelphiProp.tagName, DelphiProp.PropertyName, DelphiProp.PropertyName]); if Prop.PropOptions.HasValue['default'] then begin sdefValue := Prop.PropOptions.Value['default']; if StartsStr('"', sdefValue) or ContainsStr(sdefValue, '.') or ContainsStr(sdefValue, 'e') then s := s + '; //'; s := s + Format(' default %s', [ReQuoteStr(sdefValue)]); end; end; end; s := s + ';'; SL.Add(s); end; SL.Add(' end;'); end; var i: Integer; begin SL.Add(Format('unit %s;', [Proto.Name])); SL.Add(''); SL.Add('interface'); SL.Add(''); SL.Add('// *********************************** '); SL.Add(Format('// classes for %s.proto', [Proto.Name])); SL.Add('// generated by ProtoBufGenerator '); SL.Add('// kami-soft 2016-2017'); SL.Add('// ***********************************'); SL.Add(''); SL.Add('uses'); SL.Add(' SysUtils,'); SL.Add(' Classes,'); SL.Add(' pbInput,'); SL.Add(' pbOutput,'); SL.Add(' pbPublic,'); if Proto.Imports.Count = 0 then SL.Add(' uAbstractProtoBufClasses;') else begin SL.Add(' uAbstractProtoBufClasses,'); for i := 0 to Proto.Imports.Count - 2 do SL.Add(' ' + Proto.Imports[i] + ','); SL.Add(' ' + Proto.Imports[Proto.Imports.Count - 1] + ';'); end; SL.Add(''); SL.Add('type'); // add all enums for i := 0 to Proto.ProtoBufEnums.Count - 1 do if not Proto.ProtoBufEnums[i].IsImported then begin WriteEnumToSL(Proto.ProtoBufEnums[i], SL); SL.Add(''); end; // add all classes definitions for i := 0 to Proto.ProtoBufMessages.Count - 1 do if not Proto.ProtoBufMessages[i].IsImported then begin WriteMessageToSL(Proto.ProtoBufMessages[i], SL); SL.Add(''); end; end; procedure TProtoBufGenerator.Generate(const InputFile, OutputDir: string; Encoding: TEncoding); var Proto: TProtoFile; SL: TStringList; iPos: Integer; begin SL := TStringList.Create; try SL.LoadFromFile(InputFile); Proto := TProtoFile.Create(nil); try Proto.FileName := InputFile; iPos := 1; Proto.ParseFromProto(SL.Text, iPos); Generate(Proto, OutputDir, Encoding); finally Proto.Free; end; finally SL.Free; end; end; { TDelphiProperty } function TDelphiProperty.readOnlyDelphiProperty: Boolean; begin Result := IsList or isObject; end; function TDelphiProperty.tagName: string; begin Result := 'tag_' + PropertyName; end; end.
unit AppSettings; interface uses SettingsInterface; type TAppSettings = class(TObject) private class function GetSettings: ISettings; static; public class property Settings: ISettings read GetSettings; end; implementation uses Settings, System.IOUtils, System.SysUtils; var FSettings: TSettings = nil; class function TAppSettings.GetSettings: ISettings; var ASettingsFileName: String; begin if FSettings = nil then begin ASettingsFileName := TPath.Combine(TPath.GetDirectoryName(ParamStr(0)), 'appsettings.json'); FSettings := TSettings.Create(nil, ASettingsFileName); end; Result := FSettings; end; initialization finalization if FSettings <> nil then FreeAndNil(FSettings); end.