text stringlengths 14 6.51M |
|---|
unit NtUtils.Files;
{
This module defines the interfaces for preparing parameters for file open and
create operations and provides filename manipulation routines.
}
interface
uses
Ntapi.ntdef, Ntapi.ntioapi, Ntapi.WinBase, NtUtils;
type
TFileNameMode = (
fnNative,
fnWin32
);
// File open operation parameteres; see NtUtils.Files.Open
IFileOpenParameters = interface
// Fluent builder
function UseFileName(const FileName: String; Mode: TFileNameMode = fnNative): IFileOpenParameters;
function UseFileId(const FileId: TFileId): IFileOpenParameters;
function UseAccess(const AccessMask: TFileAccessMask): IFileOpenParameters;
function UseRoot(const RootDirectory: IHandle): IFileOpenParameters;
function UseHandleAttributes(const Attributes: TObjectAttributesFlags): IFileOpenParameters;
function UseShareMode(const ShareMode: TFileShareMode): IFileOpenParameters;
function UseOpenOptions(const OpenOptions: TFileOpenOptions): IFileOpenParameters;
// Accessor functions
function GetFileName: String;
function GetFileId: TFileId;
function GetAccess: TFileAccessMask;
function GetRoot: IHandle;
function GetHandleAttributes: TObjectAttributesFlags;
function GetShareMode: TFileShareMode;
function GetOpenOptions: TFileOpenOptions;
function GetObjectAttributes: PObjectAttributes;
// Accessors
property FileName: String read GetFileName;
property FileId: TFileId read GetFileId;
property Access: TFileAccessMask read GetAccess;
property Root: IHandle read GetRoot;
property HandleAttributes: TObjectAttributesFlags read GetHandleAttributes;
property ShareMode: TFileShareMode read GetShareMode;
property OpenOptions: TFileOpenOptions read GetOpenOptions;
property ObjectAttributes: PObjectAttributes read GetObjectAttributes;
end;
// File create operation parameteres; see NtUtils.Files.Open
IFileCreateParameters = interface
// Fluent builder
function UseFileName(const FileName: String; Mode: TFileNameMode = fnNative): IFileCreateParameters;
function UseAccess(const AccessMask: TFileAccessMask): IFileCreateParameters;
function UseRoot(const RootDirectory: IHandle): IFileCreateParameters;
function UseHandleAttributes(const Attributes: TObjectAttributesFlags): IFileCreateParameters;
function UseSecurity(const SecurityDescriptor: ISecurityDescriptor): IFileCreateParameters;
function UseShareMode(const ShareMode: TFileShareMode): IFileCreateParameters;
function UseCreateOptions(const CreateOptions: TFileOpenOptions): IFileCreateParameters;
function UseFileAttributes(const Attributes: TFileAttributes): IFileCreateParameters;
function UseAllocationSize(const Size: UInt64): IFileCreateParameters;
function UseDisposition(const Disposition: TFileDisposition): IFileCreateParameters;
// Accessor functions
function GetFileName: String;
function GetAccess: TFileAccessMask;
function GetRoot: IHandle;
function GetHandleAttributes: TObjectAttributesFlags;
function GetSecurity: ISecurityDescriptor;
function GetShareMode: TFileShareMode;
function GetCreateOptions: TFileOpenOptions;
function GetFileAttributes: TFileAttributes;
function GetAllocationSize: UInt64;
function GetDisposition: TFileDisposition;
function GetObjectAttributes: PObjectAttributes;
// Accessors
property FileName: String read GetFileName;
property Access: TFileAccessMask read GetAccess;
property Root: IHandle read GetRoot;
property HandleAttributes: TObjectAttributesFlags read GetHandleAttributes;
property Security: ISecurityDescriptor read GetSecurity;
property ShareMode: TFileShareMode read GetShareMode;
property CreateOptions: TFileOpenOptions read GetCreateOptions;
property FileAttributes: TFileAttributes read GetFileAttributes;
property AllocationSize: UInt64 read GetAllocationSize;
property Disposition: TFileDisposition read GetDisposition;
property ObjectAttributes: PObjectAttributes read GetObjectAttributes;
end;
{ Paths }
// Make a Win32 filename absolute
function RtlxGetFullDosPath(
const Path: String
): String;
// Convert a Win32 filename to Native format
function RtlxDosPathToNativePath(
const Path: String
): String;
// Convert a Native filename to Win32 format
function RtlxNativePathToDosPath(
const Path: String
): String;
// Query a name of a file in various formats
function RltxGetFinalNameFile(
[Access(0)] hFile: THandle;
out FileName: String;
Flags: TFileFinalNameFlags = FILE_NAME_OPENED or VOLUME_NAME_NT
): TNtxStatus;
// Get the current directory
function RtlxGetCurrentDirectory: String;
// Set the current directory
function RtlxSetCurrentDirectory(
const CurrentDir: String
): TNtxStatus;
implementation
uses
Ntapi.WinNt, Ntapi.ntrtl, Ntapi.ntstatus, Ntapi.ntpebteb, NtUtils.SysUtils,
DelphiUtils.AutoObjects;
{$BOOLEVAL OFF}
{$IFOPT R+}{$DEFINE R+}{$ENDIF}
{$IFOPT Q+}{$DEFINE Q+}{$ENDIF}
{ Paths }
function RtlxGetFullDosPath;
var
Buffer: IMemory<PWideChar>;
Required: Cardinal;
begin
Required := RtlGetLongestNtPathLength;
repeat
IMemory(Buffer) := Auto.AllocateDynamic(Required);
Required := RtlGetFullPathName_U(PWideChar(Path), Buffer.Size,
Buffer.Data, nil);
until Required <= Buffer.Size;
SetString(Result, Buffer.Data, Required div SizeOf(WideChar));
end;
function RtlxDosPathToNativePath;
var
Buffer: TNtUnicodeString;
BufferDeallocator: IAutoReleasable;
begin
Buffer := Default(TNtUnicodeString);
if not NT_SUCCESS(RtlDosPathNameToNtPathName_U_WithStatus(
PWideChar(Path), Buffer, nil, nil)) then
Exit('');
BufferDeallocator := RtlxDelayFreeUnicodeString(@Buffer);
Result := Buffer.ToString;
end;
function RtlxNativePathToDosPath;
const
DOS_DEVICES = '\??\';
SYSTEM_ROOT = '\SystemRoot';
begin
Result := Path;
// Remove the DOS devices prefix
if RtlxPrefixString(DOS_DEVICES, Result) then
Delete(Result, Low(String), Length(DOS_DEVICES))
// Expand the SystemRoot symlink
else if RtlxPrefixString(SYSTEM_ROOT, Result) then
Result := USER_SHARED_DATA.NtSystemRoot + Copy(Result,
Succ(Length(SYSTEM_ROOT)), Length(Result))
// Otherwise, follow the symlink to the global root of the namespace
else if Path <> '' then
Result := '\\.\GlobalRoot' + Path;
end;
function RltxGetFinalNameFile;
var
Buffer: IMemory<PWideChar>;
Required: Cardinal;
begin
Result.Location := 'GetFinalPathNameByHandleW';
IMemory(Buffer) := Auto.AllocateDynamic(RtlGetLongestNtPathLength *
SizeOf(WideChar));
repeat
Required := GetFinalPathNameByHandleW(hFile, Buffer.Data,
Buffer.Size div SizeOf(WideChar), Flags);
if Required >= Buffer.Size div SizeOf(WideChar) then
Result.Status := STATUS_BUFFER_TOO_SMALL
else
Result.Win32Result := Required > 0;
until not NtxExpandBufferEx(Result, IMemory(Buffer),
Succ(Required) * SizeOf(WideChar), nil);
if not Result.IsSuccess then
Exit;
SetString(FileName, Buffer.Data, Required);
// Remove the excessive prefix
if (Flags and VOLUME_NAME_MASK = VOLUME_NAME_DOS) and
RtlxPrefixString('\\?\', FileName, True) then
Delete(FileName, 1, Length('\\?\'));
end;
function RtlxGetCurrentDirectory;
var
Buffer: IMemory<PWideChar>;
Required: Cardinal;
begin
Required := RtlGetLongestNtPathLength;
repeat
IMemory(Buffer) := Auto.AllocateDynamic(Required);
Required := RtlGetCurrentDirectory_U(Buffer.Size, Buffer.Data);
until Required <= Buffer.Size;
SetString(Result, Buffer.Data, Required div SizeOf(WideChar));
end;
function RtlxSetCurrentDirectory;
begin
Result.Location := 'RtlSetCurrentDirectory_U';
Result.Status := RtlSetCurrentDirectory_U(TNtUnicodeString.From(CurrentDir));
end;
end.
|
unit UIconFontImageFMX;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls, System.ImageList, FMX.ImgList,
FMX.Objects, FMX.MultiresBitmap, System.Rtti, System.Messaging,
FMX.IconFontsImageList, FMX.ListBox, FMX.Colors, FMX.IconFontImage;
type
TIconFontImageForm = class(TForm)
IconFontImage: TIconFontImage;
Button: TButton;
Panel1: TPanel;
edtColor: TColorComboBox;
procedure FormCreate(Sender: TObject);
procedure ButtonClick(Sender: TObject);
procedure IconFontImageResize(Sender: TObject);
procedure edtColorChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
IconFontImageForm: TIconFontImageForm;
implementation
uses
System.Math
, FMX.Consts;
{$R *.fmx}
procedure TIconFontImageForm.ButtonClick(Sender: TObject);
var
I: Integer;
begin
for I := 0 to IconFontImage.MultiResBitmap.Count -1 do
(IconFontImage.MultiResBitmap.Items[I] as TIconFontFixedBitmapItem).FontIconDec :=
(IconFontImage.MultiResBitmap.Items[I]as TIconFontFixedBitmapItem).FontIconDec+1;
IconFontImage.Repaint;
end;
procedure TIconFontImageForm.edtColorChange(Sender: TObject);
var
I: Integer;
begin
for I := 0 to IconFontImage.MultiResBitmap.Count -1 do
(IconFontImage.MultiResBitmap.Items[I] as TIconFontFixedBitmapItem).FontColor :=
edtColor.Color;
IconFontImage.Repaint;
end;
procedure TIconFontImageForm.FormCreate(Sender: TObject);
begin
;
end;
procedure TIconFontImageForm.IconFontImageResize(Sender: TObject);
begin
;
end;
initialization
ReportMemoryLeaksOnShutdown := True;
end.
|
unit LoginDetails;
interface
uses
System.SysUtils, System.Variants, System.Classes, Winapi.Windows, Winapi.Messages,
System.Win.Registry, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
BaseModalForm, RzButton, Vcl.ExtCtrls, RzPanel, Vcl.StdCtrls, RzLabel, Vcl.Mask,
RzEdit, Utilities, DataServices, RzRadChk, FireDAC.Comp.Client, Settings;
type
TfmLoginDetails = class(TfmBaseModalForm)
RzGroupBox1: TRzGroupBox;
RzLabel3: TRzLabel;
RzLabel5: TRzLabel;
RzLabel6: TRzLabel;
ebEMDBUsername: TRzEdit;
ebEMDBPassword: TRzEdit;
ebEMDBHost: TRzEdit;
ebEMDBDatabasename: TRzEdit;
RzLabel1: TRzLabel;
ckbWindowsAuth: TRzCheckBox;
procedure FormShow(Sender: TObject);
procedure ckbWindowsAuthClick(Sender: TObject);
private
{ Private declarations }
procedure GetPreviousLogin;
procedure SetPreviousLogin;
procedure SetWindowsLogin(AWindowsLogin: Boolean);
function ConnectionOK: Boolean;
protected
{ Protected declarations }
function RaiseOKError: Boolean; override;
function RaiseCancelError: Boolean; override;
function CanOK: Integer; override;
function CanCancel: Boolean; override;
public
{ Public declarations }
constructor Create(AOwner: TComponent); reintroduce;
end;
implementation
{$R *.dfm}
constructor TfmLoginDetails.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
GetPreviousLogin;
end;
procedure TfmLoginDetails.GetPreviousLogin;
begin
ebEMDBHost.Text := TUtilities.GetFormKey('LoginDetail', 'Host');
ebEMDBDatabasename.Text := TUtilities.GetFormKey('LoginDetail', 'DBName');
ebEMDBUsername.Text := TUtilities.GetFormKey('LoginDetail', 'UserName');
ckbWindowsAuth.Checked := (1 = TUtilities.GetIntegerFormKey('LoginDetail', 'UseWindowsAuth'));
end;
procedure TfmLoginDetails.SetPreviousLogin;
begin
TUtilities.SetFormKey('LoginDetail', 'Host', ebEMDBHost.Text);
TUtilities.SetFormKey('LoginDetail', 'DBName', ebEMDBDatabasename.Text);
TUtilities.SetFormKey('LoginDetail', 'UserName', ebEMDBUsername.Text);
if ckbWindowsAuth.Checked then
TUtilities.SetIntegerFormKey('LoginDetail', 'UseWindowsAuth', 1)
else
TUtilities.SetIntegerFormKey('LoginDetail', 'UseWindowsAuth', 0);
end;
procedure TfmLoginDetails.SetWindowsLogin(AWindowsLogin: Boolean);
begin
if AWindowsLogin then
begin
ebEMDBUsername.Text := String.Format('%s\%s', [TUtilities.GetLoggedInDomain, TUtilities.GetLoggedInUserName]);
ebEMDBPassword.Text := String.Empty;
end;
ebEMDBUsername.Enabled := not AWindowsLogin;
ebEMDBPassword.Enabled := not AWindowsLogin;
end;
function TfmLoginDetails.ConnectionOK: Boolean;
begin
Result := FALSE;
var LConn := TDataServices.GetConnection(ebEMDBHost.Text, ebEMDBDatabaseName.Text, ebEMDBUsername.Text, ebEMDBPassword.Text, ckbWindowsAuth.Checked);
try
try
LConn.Open;
LConn.Close;
Result := TRUE;
except on E:Exception do
MessageDlg(String.Format('Connection Error: %s', [E.Message]), mtError, [mbOK], 0);
end;
finally
LConn.Free;
end;
end;
function TfmLoginDetails.RaiseOKError: Boolean;
begin
Result := (mrYes = MessageDlg('Are you sure you wish to leave the password blank?', mtConfirmation, [mbYes, mbNo], 0));
end;
function TfmLoginDetails.RaiseCancelError: Boolean;
begin
Result := TRUE;
end;
function TfmLoginDetails.CanOK: Integer;
begin
Result := 0;
if '' = Trim(ebEMDBHost.Text) then
begin
MessageDlg('EMDB Host cannot be empty.', mtError, [mbOK], 0);
EXIT;
end;
if '' = Trim(ebEMDBDatabaseName.Text) then
begin
Result := -1;
EXIT;
end;
if '' = Trim(ebEMDBUsername.Text) then
begin
MessageDlg('EMDB User Name cannot be empty.', mtError, [mbOK], 0);
EXIT;
end;
if '' = Trim(ebEMDBPassword.Text) then
begin
Result := -1;
EXIT;
end;
if ConnectionOK then
begin
TSettings.Settings.Host := Trim(ebEMDBHost.Text);
TSettings.Settings.Database := Trim(ebEMDBDatabaseName.Text);
TSettings.Settings.UserName := Trim(ebEMDBUsername.Text);
TSettings.Settings.Password := Trim(ebEMDBPassword.Text);
SetPreviousLogin;
Result := 1;
end else
Result := -1;
end;
function TfmLoginDetails.CanCancel: Boolean;
begin
Result := TRUE;
end;
procedure TfmLoginDetails.FormShow(Sender: TObject);
begin
inherited;
var LDBName := ebEMDBDatabaseName.Text;
if String.IsNullOrWhiteSpace(LDBName) then
ebEMDBDatabaseName.Text := 'LogRhythmEMDB';
var LUserName := ebEMDBUsername.Text;
if String.IsNullOrWhiteSpace(LUserName) then
ebEMDBHost.SetFocus
else
ebEMDBPassword.SetFocus;
end;
procedure TfmLoginDetails.ckbWindowsAuthClick(Sender: TObject);
begin
inherited;
SetWindowsLogin(ckbWindowsAuth.Checked);
end;
end.
|
unit cCadCliente;
interface
uses classes, controls, SysUtils,ExtCtrls, Dialogs, ZAbstractConnection, ZConnection,
ZAbstractRODataset, ZAbstractDataset, ZDataset;
Type
TCliente = class
private
ConexaoDB:TZConnection; //passando a conexão em tempo de criação da classe
F_ClienteId:integer;
F_nome:String;
F_endereco:String;
F_cidade:String;
F_bairro:String;
F_estado:String;
F_cep:String;
F_telefone:String;
F_email:String;
F_dataNascimento:TDateTime;
public
constructor Create(aConexao:TZConnection);
destructor Destroy; override;
function Inserir:Boolean;
function Atualizar:Boolean;
function Apagar:Boolean;
function Selecionar(id:integer):Boolean;
published
property codigo :integer read F_ClienteId write F_ClienteId;
property nome:string read F_nome write F_nome;
property endereco:string read F_endereco write F_endereco;
property cidade:string read F_cidade write F_cidade;
property bairro:string read F_bairro write F_bairro;
property estado:string read F_estado write F_estado;
property cep:string read F_cep write F_cep;
property telefone:string read F_telefone write F_telefone;
property email:string read F_email write F_email;
property dataNascimento:TDateTime read F_dataNascimento write F_dataNascimento;
end;
implementation
{ TCliente }
constructor TCliente.Create(aConexao: TZConnection);
begin
ConexaoDB:= aConexao;
end;
destructor TCliente.Destroy;
begin
inherited;
end;
function TCliente.Apagar: Boolean;
var Qry:TZQuery;
begin
if MessageDlg('Apagar o Registro: '+#13+#13+
'Código: '+IntToStr(F_ClienteId)+ #13+
'Descrição: '+F_nome, mtConfirmation, [mbYes, mbNo],0)=mrNo then
begin
Result:=false;
Abort;
end;
try
Qry:= TZQuery.Create(nil);
Qry.Connection:=ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('delete from clientes where clienteId=:clienteId');
Qry.ParamByName('clienteId').AsInteger:= F_ClienteId;
try
Qry.ExecSQL
except
result:=false;
end;
finally
if Assigned(Qry)then
FreeAndNil(Qry);
end;
end;
function TCliente.Atualizar: Boolean;
var Qry:TZQuery;
begin
result:=true;
try
Qry:= TZQuery.Create(nil);
Qry.Connection:=ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add(' Update clientes '+
'set nome = :nome ,'+
'endereco = :endereco, '+
'cidade = :cidade, '+
'bairro = :bairro, '+
'estado = :estado, '+
'cep = :cep, '+
'telefone = :telefone, '+
'email = :email, '+
'dataNascimento = :dataNascimento ' +
'where clienteId = :clienteId');
Qry.ParamByName('clienteId').AsInteger:=Self.F_ClienteId;
Qry.ParamByName('nome').AsString:=Self.F_nome;
Qry.ParamByName('endereco').AsString:=Self.F_endereco;
Qry.ParamByName('cidade').AsString:=Self.F_cidade;
Qry.ParamByName('bairro').AsString:=Self.F_bairro;
Qry.ParamByName('estado').AsString:=Self.F_estado;
Qry.ParamByName('cep').AsString:=Self.F_cep;
Qry.ParamByName('telefone').AsString:=Self.F_telefone;
Qry.ParamByName('email').AsString:=Self.F_email;
Qry.ParamByName('dataNascimento').AsDateTime:=Self.F_dataNascimento;
try
Qry.ExecSQL
except
result:=false;
end;
finally
if Assigned(Qry)then
FreeAndNil(Qry);
end;
end;
function TCliente.Inserir: Boolean;
var Qry:TZQuery;
begin
result:=true;
try
Qry:= TZQuery.Create(nil);
Qry.Connection:=ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('insert into clientes '+
' ( nome, '+
' endereco, '+
' cidade, '+
' bairro, '+
' estado, '+
' cep, '+
' telefone, '+
' email, '+
' dataNascimento) '+
' values (:nome , '+
' :endereco , '+
' :cidade, '+
' :bairro, '+
' :estado, '+
' :cep, '+
' :telefone, '+
' :email, '+
' :dataNascimento)');
Qry.ParamByName('nome').AsString:=Self.F_nome;
Qry.ParamByName('endereco').AsString:=Self.F_endereco;
Qry.ParamByName('cidade').AsString:=Self.F_cidade;
Qry.ParamByName('bairro').AsString:=Self.F_bairro;
Qry.ParamByName('estado').AsString:=Self.F_estado;
Qry.ParamByName('cep').AsString:=Self.F_cep;
Qry.ParamByName('telefone').AsString:=Self.F_telefone;
Qry.ParamByName('email').AsString:=Self.F_email;
Qry.ParamByName('dataNascimento').AsDateTime:=Self.F_dataNascimento;
try
Qry.ExecSQL
except
result:=false;
end;
finally
if Assigned(Qry)then
FreeAndNil(Qry);
end;
end;
function TCliente.Selecionar(id: integer): Boolean;
var Qry:TZQuery;
begin
result:=true;
try
Qry:= TZQuery.Create(nil);
Qry.Connection:=ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add( 'select ClienteId,'+
' nome, '+
' endereco, '+
' cidade, '+
' bairro, '+
' estado, '+
' cep, '+
' telefone, '+
' email, '+
' dataNascimento '+
' From Clientes '+
' Where clienteId =:ClienteId');
Qry.ParamByName('ClienteId').Value:=id;
try
Qry.Open;
Self.F_clienteId:= Qry.FieldByName('ClienteId').AsInteger;
Self.F_nome:= Qry.FieldByName('nome').AsString;
Self.F_endereco:= Qry.FieldByName('endereco').AsString;
Self.F_cidade:= Qry.FieldByName('cidade').AsString;
Self.F_bairro:= Qry.FieldByName('bairro').AsString;
Self.F_estado:= Qry.FieldByName('estado').AsString;
Self.F_cep:= Qry.FieldByName('cep').AsString;
Self.F_telefone:= Qry.FieldByName('telefone').AsString;
Self.F_email:= Qry.FieldByName('email').AsString;
Self.F_dataNascimento:= Qry.FieldByName('dataNascimento').AsDateTime;
except
result:=false;
end;
finally
if Assigned(Qry)then
FreeAndNil(Qry);
end;
end;
end.
|
Unit ShortcutControl;
Interface
Uses
Winapi.Messages, Winapi.Windows, System.SysUtils, System.Classes, Vcl.Controls, Vcl.Graphics, Vcl.StdCtrls,
Winapi.GDIPAPI, Winapi.GDIPOBJ;
Type
THotkeyEvent = Procedure(Sender: TObject; HotKey: DWORD) Of Object;
TShortcutInput = Class(TCustomEdit)
Private
FHotKey : DWORD;
FOnHotkey: THotkeyEvent;
Procedure SetHotKey(Value: DWORD);
Public
Constructor Create(AOwner: TComponent); Override;
Property HotKey: DWORD Read FHotKey Write SetHotKey;
Procedure SetDescText(Const Desc: String);
Published
Property OnHotkey: THotkeyEvent Read FOnHotkey Write FOnHotkey;
Published
Property OnEnter;
Property OnExit;
End;
Procedure Register;
Implementation
Procedure Register;
Begin
RegisterComponents('Samples', [TShortcutInput]);
End;
{ TShortcutInput }
Constructor TShortcutInput.Create(AOwner: TComponent);
Begin
Inherited;
ReadOnly := TRUE;
AutoSize := TRUE;
AutoSelect := FALSE;
ImeMode := imDisable;
End;
Procedure TShortcutInput.SetHotKey(Value: DWORD);
Begin
FHotKey := Value;
If Assigned(FOnHotkey) Then FOnHotkey(Self, FHotKey);
End;
Procedure TShortcutInput.SetDescText(Const Desc: String);
Begin
Self.Text := Desc;
Self.SelStart := Length(Desc);
End;
End.
|
{$ifdef license}
(*
Copyright 2020 ChapmanWorld LLC ( https://chapmanworld.com )
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be
used to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
{$endif}
unit testcase.cwTypes.StringHelper;
{$ifdef fpc} {$mode delphiunicode} {$endif}
{$M+}
interface
uses
cwTest
, cwTest.Standard
, cwTypes
;
type
TTestStringHelper = class(TTestCase)
published
procedure SetAsPChar;
procedure LeftPad;
procedure RightPad;
procedure Explode;
procedure Combine;
procedure Trim;
procedure Uppercase;
procedure UppercaseTrim;
procedure Lowercase;
procedure LowercaseTrim;
procedure StringReplace;
procedure LeftStr;
procedure RightStr;
procedure MidStr;
procedure Pos;
procedure PadLeft;
procedure PadRight;
procedure AsBoolean;
procedure AsUInt8;
procedure AsUInt16;
procedure AsUint32;
procedure AsUint64;
procedure AsInt8;
procedure AsInt16;
procedure AsInt32;
procedure AsInt64;
procedure AsSingle;
procedure AsDouble;
procedure AsExtended;
{$if defined(fpc) or defined(MSWINDOWS)}
procedure AsAnsiString;
{$endif}
end;
implementation
function Within(A,B: double; Precision: double ):boolean;
begin
Result := (A>B-Precision) and (A<B+Precision);
end;
{$if defined(fpc) or defined(MSWINDOWS)}
procedure TTestStringHelper.AsAnsiString;
var
S: string;
ToAnsi: ansistring;
FromAnsi: string;
begin
// Arrange:
ToAnsi := '';
FromAnsi := '';
S := '[{6A5972B7-B7B8-478B-9970-F571021195A9}]';
// Act:
ToAnsi := S.AsAnsiString;
FromAnsi.AsAnsiString := ToAnsi;
// Assert:
TTest.Expect(S,FromAnsi);
end;
{$endif}
procedure TTestStringHelper.AsBoolean;
var
STrue: string;
SFalse: string;
T: boolean;
F: boolean;
begin
// Arrange:
STrue := 'TRUE';
SFALSE := 'FALSE';
// Act:
T := STrue.AsBoolean;
F := SFalse.AsBoolean(TRUE);
// Assert:
TTest.Expect(TRUE,T);
TTest.Expect(FALSE,F);
end;
procedure TTestStringHelper.AsDouble;
var
F: double;
S: string;
begin
// Arrange:
S := '16.431';
// Act:
F := S.AsDouble;
// Assert:
TTest.Expect(16.431,F,0.0001);
end;
procedure TTestStringHelper.AsExtended;
var
F: Extended;
S: string;
begin
// Arrange:
S := '16.431';
// Act:
F := S.AsExtended;
// Assert:
TTest.Expect(16.431,F,0.0001);
end;
procedure TTestStringHelper.AsInt16;
var
V: int16;
S: string;
begin
// Arrange:
S := '-16000';
// Act:
V := S.AsInt16;
// Assert:
TTest.Expect(TRUE,V=-16000);
end;
procedure TTestStringHelper.AsInt32;
var
V: int32;
S: string;
begin
// Arrange:
S := '-65530';
// Act:
V := S.AsInt32;
// Assert:
TTest.Expect(TRUE,V=-65530);
end;
procedure TTestStringHelper.AsInt64;
var
V: int64;
S: string;
begin
// Arrange:
S := '-165530';
// Act:
V := S.AsInt64;
// Assert:
TTest.Expect(TRUE,V=-165530);
end;
procedure TTestStringHelper.AsInt8;
var
V: int8;
S: string;
begin
// Arrange:
S := '-100';
// Act:
V := S.AsInt8;
// Assert:
TTest.Expect(TRUE,V=-100);
end;
procedure TTestStringHelper.AsSingle;
var
F: single;
S: string;
begin
// Arrange:
S := '16.431';
// Act:
F := S.AsSingle;
// Assert:
TTest.Expect(TRUE,Within(F,16.431,0.001));
end;
procedure TTestStringHelper.AsUInt16;
var
V: uint16;
S: string;
begin
// Arrange:
S := '16000';
// Act:
V := S.AsUInt16;
// Assert:
TTest.Expect(TRUE,V=16000);
end;
procedure TTestStringHelper.AsUint32;
var
V: uint32;
S: string;
begin
// Arrange:
S := '65530';
// Act:
V := S.AsUInt32;
// Assert:
TTest.Expect(TRUE,V=65530);
end;
procedure TTestStringHelper.AsUint64;
var
V: uint64;
S: string;
begin
// Arrange:
S := '165530';
// Act:
V := S.AsUInt64;
// Assert:
TTest.Expect(TRUE,V=165530);
end;
procedure TTestStringHelper.AsUInt8;
var
V: uint8;
S: string;
begin
// Arrange:
S := '200';
// Act:
V := S.AsUInt8;
// Assert:
TTest.Expect(TRUE,V=200);
end;
procedure TTestStringHelper.Combine;
var
S: string;
Arr: TArrayOfString;
begin
// Arrange:
{$hints off} SetLength(Arr,5); {$hints on} // hints that this is not initialized, this is initialization.
S := '';
Arr[0]:='Monday';
Arr[1]:='Tuesday';
Arr[2]:='Wednesday';
Arr[3]:='Thursday';
Arr[4]:='Friday';
// Act:
S.Combine(';',Arr);
// Assert:
TTest.Expect(TRUE,S='Monday;Tuesday;Wednesday;Thursday;Friday');
end;
procedure TTestStringHelper.Explode;
var
S: string;
Arr: TArrayOfString;
begin
// Arrange:
S := 'Monday;Tuesday;Wednesday;Thursday;Friday';
// Act:
Arr := S.Explode(';');
// Assert:
TTest.Expect('Monday',Arr[0]);
TTest.Expect('Tuesday',Arr[1]);
TTest.Expect('Wednesday',Arr[2]);
TTest.Expect('Thursday',Arr[3]);
TTest.Expect('Friday',Arr[4]);
end;
procedure TTestStringHelper.LeftPad;
var
S: string;
T: string;
begin
// Arrange:
S := 'Hello';
// Act:
T := S.LeftPad(11,'!');
// Assert:
TTest.Expect('!!!!!!'+S,T);
end;
procedure TTestStringHelper.LeftStr;
var
S: string;
T: string;
begin
// Arrange:
S := 'Left Middle Right';
// Act:
T := S.LeftStr(4);
// Assert:
TTest.Expect('Left',T);
end;
procedure TTestStringHelper.Lowercase;
var
S: string;
T: string;
begin
// Arrange:
S := 'HELLO CRUEL WORLD';
// Act:
T := S.Lowercase;
// Assert:
TTest.Expect('hello cruel world',T);
end;
procedure TTestStringHelper.LowercaseTrim;
var
S: string;
T: string;
begin
// Arrange:
S := ' HELLO CRUEL WORLD ';
// Act:
T := S.LowercaseTrim;
// Assert:
TTest.Expect('hello cruel world',T);
end;
procedure TTestStringHelper.MidStr;
var
S: string;
T: string;
begin
// Arrange:
S := 'Left Middle Right';
// Act:
T := S.MidStr(6,6);
// Assert:
TTest.Expect('Middle',T);
end;
procedure TTestStringHelper.PadLeft;
var
S: string;
T: string;
begin
// Arrange:
S := 'Hello';
// Act:
T := S.PadLeft(6,'!');
// Assert:
TTest.Expect('!!!!!!'+S,T);
end;
procedure TTestStringHelper.PadRight;
var
S: string;
T: string;
begin
// Arrange:
S := 'Hello';
// Act:
T := S.PadRight(6,'!');
// Assert:
TTest.Expect(S+'!!!!!!',T);
end;
procedure TTestStringHelper.Pos;
var
S: string;
T: uint32;
begin
// Arrange:
S := 'Left Middle Right';
// Act:
T := S.Pos('Middle');
// Assert:
TTest.Expect(uint32(6),T);
end;
procedure TTestStringHelper.RightPad;
var
S: string;
T: string;
begin
// Arrange:
S := 'Hello';
// Act:
T := S.RightPad(11,'!');
// Assert:
TTest.Expect(S+'!!!!!!',T);
end;
procedure TTestStringHelper.RightStr;
var
S: string;
T: string;
begin
// Arrange:
S := 'Left Middle Right';
// Act:
T := S.RightStr(5);
// Assert:
TTest.Expect('Right',T);
end;
procedure TTestStringHelper.SetAsPChar;
var
Data: array[0..17] of uint8;
S: string;
begin
// Arrange:
S := '';
Data[00] := ord('h');
Data[01] := ord('e');
Data[02] := ord('l');
Data[03] := ord('l');
Data[04] := ord('o');
Data[05] := ord(' ');
Data[06] := ord('c');
Data[07] := ord('r');
Data[08] := ord('u');
Data[09] := ord('e');
Data[10] := ord('l');
Data[11] := ord(' ');
Data[12] := ord('w');
Data[13] := ord('o');
Data[14] := ord('r');
Data[15] := ord('l');
Data[16] := ord('d');
Data[17] := 0;
// Act:
S.SetAsPChar( @Data[0] );
// Assert:
TTest.Expect('hello cruel world',S);
end;
procedure TTestStringHelper.StringReplace;
var
S: string;
T: string;
begin
// Arrange:
S := 'hello replace world';
// Act:
T := S.StringReplace('replace','cruel',TRUE,TRUE);
// Assert:
TTest.Expect('hello cruel world',T);
end;
procedure TTestStringHelper.Trim;
var
S: string;
T: string;
begin
// Arrange:
S := ' hello cruel world ';
// Act:
T := S.Trim;
// Assert:
TTest.Expect('hello cruel world',T);
end;
procedure TTestStringHelper.Uppercase;
var
S: string;
T: string;
begin
// Arrange:
S := 'hello cruel world';
// Act:
T := S.Uppercase;
// Assert:
TTest.Expect('HELLO CRUEL WORLD',T);
end;
procedure TTestStringHelper.UppercaseTrim;
var
S: string;
T: string;
begin
// Arrange:
S := ' hello cruel world ';
// Act:
T := S.UppercaseTrim;
// Assert:
TTest.Expect('HELLO CRUEL WORLD',T);
end;
initialization
TestSuite.RegisterTestCase(TTestStringHelper);
end.
|
unit uDetailedModbusForm;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs,
upropertyeditor, VirtualTrees, uConfiguratorData;
type
{ TDetailedModbusForm }
TDetailedModbusForm = class(TDetailedForm)
SettingTree: TVirtualStringTree;
procedure SettingTreeColumnDblClick(Sender: TBaseVirtualTree;
Column: TColumnIndex; {%H-}Shift: TShiftState);
procedure SettingTreeCreateEditor(Sender: TBaseVirtualTree;
{%H-}Node: PVirtualNode; {%H-}Column: TColumnIndex; out EditLink: IVTEditLink);
procedure SettingTreeEditing(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; var Allowed: Boolean);
procedure SettingTreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode);
procedure SettingTreeGetNodeDataSize(Sender: TBaseVirtualTree;
var NodeDataSize: Integer);
procedure SettingTreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; {%H-}TextType: TVSTTextType; var CellText: String);
procedure SettingTreePaintText(Sender: TBaseVirtualTree;
const TargetCanvas: TCanvas; {%H-}Node: PVirtualNode; Column: TColumnIndex;
{%H-}TextType: TVSTTextType);
private
fModbusData: TModbusData;
private
procedure PopulateSettingTree;
public
procedure Load(const aContentData: array of TContentData); override;
procedure Unload; override;
end;
implementation
uses
uModbus,
uModbusFormData;
{$R *.lfm}
{ TDetailedModbusForm }
procedure TDetailedModbusForm.SettingTreeGetNodeDataSize(
Sender: TBaseVirtualTree; var NodeDataSize: Integer);
begin
NodeDataSize := SizeOf(TModbusBaseData);
end;
procedure TDetailedModbusForm.SettingTreeGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: String);
var
P: Pointer;
begin
P := Sender.GetNodeData(Node);
case Column of
0: CellText := TModbusBaseData(P^).Caption;
1: CellText := TModbusBaseData(P^).Value;
end;
end;
procedure TDetailedModbusForm.SettingTreePaintText(Sender: TBaseVirtualTree;
const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex;
TextType: TVSTTextType);
begin
case Column of
0: TargetCanvas.Font.Style := [fsBold];
1: TargetCanvas.Font.Style := [];
end;
end;
procedure TDetailedModbusForm.PopulateSettingTree;
var
ModbusBaseData: TModbusBaseData;
begin
SettingTree.BeginUpdate;
try
case fModbusData.Controller.TypeController of
mbRtu:
begin
SettingTree.AddChild(nil, TBaudRate.Create(fModbusData));
SettingTree.AddChild(nil, TParity.Create(fModbusData));
SettingTree.AddChild(nil, TByteSize.Create(fModbusData));
SettingTree.AddChild(nil, TStopBits.Create(fModbusData));
SettingTree.AddChild(nil, TThreeAndHalf.Create(fModbusData));
end;
mbAcTcp:
begin
ModbusBaseData := TIpAddress.Create(fModbusData);
ModbusBaseData.ReadOnly := True;
SettingTree.AddChild(nil, ModbusBaseData);
ModbusBaseData := TPort.Create(fModbusData);
ModbusBaseData.ReadOnly := True;
SettingTree.AddChild(nil, ModbusBaseData);
end;
mbCnTcp:
begin
SettingTree.AddChild(nil, TIpAddress.Create(fModbusData));
SettingTree.AddChild(nil, TPort.Create(fModbusData));
end;
end;
finally
SettingTree.EndUpdate;
end;
end;
procedure TDetailedModbusForm.SettingTreeFreeNode(Sender: TBaseVirtualTree;
Node: PVirtualNode);
var
P: Pointer;
begin
P := Sender.GetNodeData(Node);
if TObject(P^) is TModbusBaseData then
TModbusBaseData(P^).Free;
end;
procedure TDetailedModbusForm.SettingTreeCreateEditor(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; out EditLink: IVTEditLink);
begin
EditLink := TPropertyEditor.Create(Sender);
end;
procedure TDetailedModbusForm.SettingTreeEditing(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; var Allowed: Boolean);
var
P: Pointer;
begin
P := Sender.GetNodeData(Node);
Allowed := (Column = 1) and not TModbusBaseData(P^).ReadOnly;
end;
procedure TDetailedModbusForm.SettingTreeColumnDblClick(
Sender: TBaseVirtualTree; Column: TColumnIndex; Shift: TShiftState);
var
Node: PVirtualNode;
P: Pointer;
begin
if Column = 1 then
begin
Node := Sender.FocusedNode;
if Node = nil then
Exit;
P := Sender.GetNodeData(Node);
if not TModbusBaseData(P^).ReadOnly then
Sender.EditNode(Node, Column);
end;
end;
procedure TDetailedModbusForm.Load(const aContentData: array of TContentData);
begin
{$IFDEF DEBUG}
Assert(Length(aContentData) = 1);
{$ENDIF}
if aContentData[0] is TModbusData then
fModbusData := TModbusData(aContentData[0]);
{$IFDEF DEBUG}
Assert(fModbusData <> nil);
{$ENDIF}
PopulateSettingTree;
end;
procedure TDetailedModbusForm.Unload;
begin
SettingTree.Clear;
end;
end.
|
unit OAuth2.Contract.Repository.AccessToken;
interface
uses
OAuth2.Contract.Entity.Client,
OAuth2.Contract.Entity.Scope,
OAuth2.Contract.Entity.AccessToken;
type
IOAuth2AccessTokenRepository = interface
['{C63B4BC6-3959-41BC-8016-5FE3A70EF122}']
function GetNewToken(AClientEntity: IOAuth2ClientEntity; AScopes: TArray<IOAuth2ScopeEntity>; const AUserIdentifier: string = ''): IOAuth2AccessTokenEntity;
procedure PersistNewAccessToken(AAccessTokenEntity: IOAuth2AccessTokenEntity);
procedure RevokeAccessToken(ATokenId: string);
function IsAccessTokenRevoked(ATokenId: string): Boolean;
end;
implementation
end.
|
{$optimize 7}
{---------------------------------------------------------------}
{ }
{ Header }
{ }
{ Handles saving and reading precompiled headers. }
{ }
{---------------------------------------------------------------}
unit Header;
interface
{$LibPrefix '0/obj/'}
uses CCommon, MM, Scanner, Symbol, CGI;
{$segment 'SCANNER'}
const
symFileVersion = 16; {version number of .sym file format}
var
inhibitHeader: boolean; {should .sym includes be blocked?}
procedure EndInclude (chPtr: ptr);
{ Saves symbols created by the include file }
{ }
{ Parameters: }
{ chPtr - chPtr when the file returned }
{ }
{ Notes: }
{ 1. Call this subroutine right after processing an }
{ include file. }
{ 2. Declared externally in Symbol.pas }
procedure FlagPragmas (pragma: pragmas);
{ record the effects of a pragma }
{ }
{ parameters: }
{ pragma - pragma to record }
{ }
{ Notes: }
{ 1. Defined as extern in Scanner.pas }
{ 2. For the purposes of this unit, the segment statement is }
{ treated as a pragma. }
procedure InitHeader (var fName: gsosOutString);
{ look for a header file, reading it if it exists }
{ }
{ parameters: }
{ fName - source file name (var for efficiency) }
procedure TermHeader;
{ Stop processing the header file }
{ }
{ Note: This is called when the first code-generating }
{ subroutine is found, and again when the compile ends. It }
{ closes any open symbol file, and should take no action if }
{ called twice. }
procedure StartInclude (name: gsosOutStringPtr);
{ Marks the start of an include file }
{ }
{ Notes: }
{ 1. Call this subroutine right after opening an include }
{ file. }
{ 2. Defined externally in Scanner.pas }
{---------------------------------------------------------------}
implementation
const
symFiletype = $5E; {symbol file type}
symAuxtype = $008008;
{file buffer}
{-----------}
bufSize = 1024; {size of output buffer}
type
closeOSDCB = record
pcount: integer;
refNum: integer;
end;
createOSDCB = record
pcount: integer;
pathName: gsosInStringPtr;
access: integer;
fileType: integer;
auxType: longint;
storageType: integer;
dataEOF: longint;
resourceEOF: longint;
end;
destroyOSDCB = record
pcount: integer;
pathName: gsosInStringPtr;
end;
getFileInfoOSDCB = record
pcount: integer;
pathName: gsosInStringPtr;
access: integer;
fileType: integer;
auxType: longint;
storageType: integer;
createDateTime: timeField;
modDateTime: timeField;
optionList: optionListPtr;
dataEOF: longint;
blocksUsed: longint;
resourceEOF: longint;
resourceBlocks: longint;
end;
getMarkOSDCB = record
pcount: integer;
refNum: integer;
displacement: longint;
end;
openOSDCB = record
pcount: integer;
refNum: integer;
pathName: gsosInStringPtr;
requestAccess: integer;
resourceNumber: integer;
access: integer;
fileType: integer;
auxType: longint;
storageType: integer;
createDateTime: timeField;
modDateTime: timeField;
optionList: optionListPtr;
dataEOF: longint;
blocksUsed: longint;
resourceEOF: longint;
resourceBlocks: longint;
end;
readWriteOSDCB = record
pcount: integer;
refNum: integer;
dataBuffer: ptr;
requestCount: longint;
transferCount: longint;
cachePriority: integer;
end;
setMarkOSDCB = record
pcount: integer;
refNum: integer;
base: integer;
displacement: longint;
end;
{file buffer}
{-----------}
bufferType = array[0..bufSize] of byte; {output buffer}
var
codeStarted: boolean; {has code generation started?}
includeLevel: 0..maxint; {nested include level}
includeMark: boolean; {has the mark field been written?}
savePragmas: set of pragmas; {pragmas to record}
saveSource: boolean; {save source streams?}
symChPtr: ptr; {chPtr at start of current source sequence}
symEndPtr: ptr; {points to first byte past end of file}
symMark: longint; {start of current block}
symName: gsosOutString; {symbol file name}
symStartPtr: ptr; {first byte in the symbol file}
symPtr: ptr; {next byte in the symbol file}
symRefnum: integer; {symName reference number}
tokenMark: longint; {start of last token list}
{file buffer}
{-----------}
buffer: ^bufferType; {output buffer}
bufPtr: ^byte; {next available byte}
bufLen: 0..bufSize; {bytes left in buffer}
{---------------------------------------------------------------}
procedure BlockMove (sourcPtr, destPtr: ptr; count: longint); tool ($02, $2B);
procedure CloseGS (var parms: closeOSDCB); prodos ($2014);
procedure CreateGS (var parms: createOSDCB); prodos ($2001);
procedure DestroyGS (var parms: destroyOSDCB); prodos ($2002);
procedure GetFileInfoGS (var parms: getFileInfoOSDCB); prodos ($2006);
procedure GetMarkGS (var parms: getMarkOSDCB); prodos ($2017);
procedure OpenGS (var parms: openOSDCB); prodos ($2010);
procedure SetEOFGS (var parms: setMarkOSDCB); prodos ($2018);
procedure SetMarkGS (var parms: setMarkOSDCB); prodos ($2016);
procedure WriteGS (var parms: readWriteOSDCB); prodos ($2013);
{---------------------------------------------------------------}
procedure DestroySymbolFile;
{ Delete any existing symbol file }
var
dsRec: destroyOSDCB; {DestroyGS record}
giRec: getFileInfoOSDCB; {GetFileInfoGS record}
begin {DestroySymbolFile}
giRec.pCount := 4;
giRec.pathname := @symName.theString;
GetFileInfoGS(giRec);
if (giRec.filetype = symFiletype) and (giRec.auxtype = symAuxtype) then begin
dsRec.pCount := 1;
dsRec.pathname := @symName.theString;
DestroyGS(dsRec);
end; {if}
end; {DestroySymbolFile}
procedure Purge;
{ Purge the output buffer }
var
clRec: closeOSDCB; {CloseGS record}
wrRec: readWriteOSDCB; {WriteGS record}
begin {Purge}
wrRec.pcount := 4;
wrRec.refnum := symRefnum;
wrRec.dataBuffer := pointer(buffer);
wrRec.requestCount := (bufSize - bufLen);
WriteGS(wrRec);
if ToolError <> 0 then begin
clRec.pCount := 1;
clRec.refnum := symRefnum;
CloseGS(clRec);
DestroySymbolFile;
saveSource := false;
end; {if}
bufLen := bufSize;
bufPtr := pointer(buffer);
end; {Purge}
procedure CloseSymbols;
{ Close the symbol file }
var
clRec: closeOSDCB; {CloseGS record}
begin {CloseSymbols}
Purge;
clRec.pCount := 1;
clRec.refnum := symRefnum;
CloseGS(clRec);
if numErrors <> 0 then
DestroySymbolFile;
end; {CloseSymbols}
function ReadExtended: extended;
{ Read an extended precision real from the symbol file }
{ }
{ Returns: value read }
type
extendedptr = ^extended;
begin {ReadExtended}
ReadExtended := extendedptr(symPtr)^;
symPtr := pointer(ord4(symPtr)+10);
end; {ReadExtended}
function ReadLong: longint;
{ Read a long word from the symbol file }
{ }
{ Returns: long word read }
type
longptr = ^longint;
begin {ReadLong}
ReadLong := longptr(symPtr)^;
symPtr := pointer(ord4(symPtr)+4);
end; {ReadLong}
function ReadLongString: longStringPtr;
{ Read a long string from the symbol file }
{ }
{ Returns: string read }
var
len: 0..maxint; {string buffer length}
sp1, sp2: longStringPtr; {work pointers}
begin {ReadLongString}
sp1 := longStringPtr(symPtr);
len := sp1^.length + 2;
symPtr := pointer(ord4(symPtr) + len);
sp2 := pointer(GMalloc(len));
BlockMove(sp1, sp2, len);
ReadLongString := sp2;
end; {ReadLongString}
function ReadString: stringPtr;
{ Read a string from the symbol file }
{ }
{ Returns: string read }
var
len: 0..255; {string buffer length}
sp1, sp2: stringPtr; {work pointers}
begin {ReadString}
sp1 := stringptr(symPtr);
len := length(sp1^) + 1;
symPtr := pointer(ord4(symPtr) + len);
sp2 := pointer(GMalloc(len));
BlockMove(sp1, sp2, len);
ReadString := sp2;
end; {ReadString}
function ReadByte: integer;
{ Read a byte from the symbol file }
{ }
{ Returns: byte read }
type
intptr = ^integer;
begin {ReadByte}
ReadByte := (intptr(symPtr)^) & $00FF;
symPtr := pointer(ord4(symPtr)+1);
end; {ReadByte}
function ReadWord: integer;
{ Read a word from the symbol file }
{ }
{ Returns: word read }
type
intptr = ^integer;
begin {ReadWord}
ReadWord := intptr(symPtr)^;
symPtr := pointer(ord4(symPtr)+2);
end; {ReadWord}
procedure ReadChars (var p1, p2: ptr);
{ Read a character stream from the file }
{ }
{ parameters: }
{ p1 - (output) pointer to first char in stream }
{ p2 - (output) points one past last char in stream }
var
len: integer; {length of the stream}
begin {ReadChars}
len := ReadWord;
p1 := pointer(GMalloc(len));
p2 := pointer(ord4(p1) + len);
BlockMove(symPtr, p1, len);
symPtr := pointer(ord4(symPtr) + len);
end; {ReadChars}
procedure WriteExtended (e: extended);
{ Write an extended constant to the symbol file }
{ }
{ parameters: }
{ e - constant to write }
var
ePtr: ^extended; {work pointer}
begin {WriteExtended}
if bufLen < 10 then
Purge;
ePtr := pointer(bufPtr);
ePtr^ := e;
bufPtr := pointer(ord4(bufPtr) + 10);
bufLen := bufLen - 10;
end; {WriteExtended}
procedure WriteLong (i: longint);
{ Write a long word to the symbol file }
{ }
{ parameters: }
{ i - long word to write }
var
lPtr: ^longint; {work pointer}
begin {WriteLong}
if bufLen < 4 then
Purge;
lPtr := pointer(bufPtr);
lPtr^ := i;
bufPtr := pointer(ord4(bufPtr) + 4);
bufLen := bufLen - 4;
end; {WriteLong}
procedure WriteByte (i: integer);
{ Write a byte to the symbol file }
{ }
{ parameters: }
{ i - byte to write }
var
iPtr: ^byte; {work pointer}
begin {WriteByte}
if bufLen = 0 then
Purge;
iPtr := pointer(bufPtr);
iPtr^ := i;
bufPtr := pointer(ord4(bufPtr) + 1);
bufLen := bufLen - 1;
end; {WriteByte}
procedure WriteWord (i: integer);
{ Write a word to the symbol file }
{ }
{ parameters: }
{ i - word to write }
var
iPtr: ^integer; {work pointer}
begin {WriteWord}
if bufLen < 2 then
Purge;
iPtr := pointer(bufPtr);
iPtr^ := i;
bufPtr := pointer(ord4(bufPtr) + 2);
bufLen := bufLen - 2;
end; {WriteWord}
procedure WriteLongString (s: longStringPtr);
{ Write a long string to the symbol file }
{ }
{ parameters: }
{ s - pointer to the string to write }
var
i: 0..maxint; {loop/index variables}
len: 0..maxint; {string length}
wrRec: readWriteOSDCB; {WriteGS record}
begin {WriteLongString}
len := s^.length;
if bufLen < len+2 then
Purge;
if bufLen < len+2 then begin
wrRec.pcount := 4;
wrRec.refnum := symRefnum;
wrRec.dataBuffer := pointer(s);
wrRec.requestCount := s^.length + 2;
WriteGS(wrRec);
if ToolError <> 0 then begin
CloseSymbols;
DestroySymbolFile;
saveSource := false;
end; {if}
end {if}
else begin
WriteWord(len);
for i := 1 to len do begin
bufPtr^ := ord(s^.str[i]);
bufPtr := pointer(ord4(bufPtr) + 1);
end; {for}
bufLen := bufLen - len;
end; {else}
end; {WriteLongString}
procedure WriteChars (p1, p2: ptr);
{ Write a stream of chars as a longString }
{ }
{ parameters: }
{ p1 - points to the first char to write }
{ p2 - points to the byte following the last char }
var
i: 0..maxint; {loop/index variables}
len: 0..maxint; {char length}
wrRec: readWriteOSDCB; {WriteGS record}
begin {WriteChars}
len := ord(ord4(p2) - ord4(p1));
WriteWord(len);
if bufLen < len then
Purge;
if bufLen < len then begin
if saveSource then begin
wrRec.pcount := 4;
wrRec.refnum := symRefnum;
wrRec.dataBuffer := pointer(p1);
wrRec.requestCount := ord4(p2) - ord4(p1);
WriteGS(wrRec);
if ToolError <> 0 then begin
CloseSymbols;
DestroySymbolFile;
saveSource := false;
end; {if}
end; {if}
end {if}
else begin
for i := 1 to len do begin
bufPtr^ := p1^;
bufPtr := pointer(ord4(bufPtr)+1);
p1 := pointer(ord4(p1)+1);
end; {for}
bufLen := bufLen - len;
end; {else}
end; {WriteChars}
procedure WriteString (s: stringPtr);
{ Write a string to the symbol file }
{ }
{ parameters: }
{ s - pointer to the string to write }
var
i: 0..255; {loop/index variable}
len: 0..255; {length of the string}
begin {WriteString}
len := length(s^);
if bufLen < len+1 then
Purge;
for i := 0 to len do begin
bufPtr^ := ord(s^[i]);
bufPtr := pointer(ord4(bufPtr)+1);
end; {for}
bufLen := bufLen - (len + 1);
end; {WriteString}
procedure MarkBlock;
{ Mark the length of the current block }
var
l: longint; {block length}
smRec: setMarkOSDCB; {SetMarkGS record}
gmRec: getMarkOSDCB; {GetMarkGS record}
wrRec: readWriteOSDCB; {WriteGS record}
begin {MarkBlock}
Purge; {purge the buffer}
gmRec.pCount := 2; {get the current EOF}
gmRec.refnum := symRefnum;
GetMarkGS(gmRec);
if ToolError = 0 then begin
smRec.pcount := 3; {set the mark to the block length field}
smRec.refnum := symRefnum;
smRec.base := 0;
smRec.displacement := symMark;
SetMarkGS(smRec);
if ToolError = 0 then begin
l := gmRec.displacement - smRec.displacement - 4;
wrRec.pcount := 4;
wrRec.refnum := symRefnum;
wrRec.dataBuffer := @l;
wrRec.requestCount := 4;
WriteGS(wrRec);
if ToolError <> 0 then begin
CloseSymbols;
DestroySymbolFile;
saveSource := false;
end; {if}
smRec.displacement := gmRec.displacement;
SetMarkGS(smRec);
end; {if}
end; {if}
if ToolError <> 0 then begin {for errors, delete the symbol file}
CloseSymbols;
DestroySymbolFile;
saveSource := false;
end; {if}
end; {MarkBlock}
function GetMark: longint;
{ Find the current file mark }
{ }
{ Returns: file mark }
var
gmRec: getMarkOSDCB; {GetMarkGS record}
begin {GetMark}
gmRec.pCount := 2;
gmRec.refnum := symRefnum;
GetMarkGS(gmRec);
GetMark := gmRec.displacement + (bufSize - bufLen);
if ToolError <> 0 then begin
CloseSymbols;
DestroySymbolFile;
saveSource := false;
end; {else}
end; {GetMark}
procedure SetMark;
{ Mark the start of a block }
begin {SetMark}
symMark := GetMark;
WriteLong(0);
end; {SetMark}
{---------------------------------------------------------------}
procedure EndInclude {chPtr: ptr};
{ Saves symbols created by the include file }
{ }
{ Parameters: }
{ chPtr - chPtr when the file returned }
{ }
{ Notes: }
{ 1. Call this subroutine right after processing an }
{ include file. }
{ 2. Declared externally in Scanner.pas }
procedure SaveMacroTable;
{ Save macros to the symbol file }
procedure SaveMacros;
{ Write the macros to the symbol file }
var
i: 0..hashSize; {loop/index variable}
mp: macroRecordPtr; {used to trace macro lists}
tp: tokenListRecordPtr; {used to trace token lists}
procedure WriteToken (var token: tokenType);
{ Write a token in the header file }
{ }
{ parameters: }
{ token - token to write }
begin {WriteToken}
WriteByte(ord(token.kind));
WriteByte(ord(token.class));
if token.numstring = nil then
WriteByte(0)
else begin
WriteByte(1);
WriteString(token.numstring);
end; {else}
case token.class of
identifier: WriteString(token.name);
intConstant: WriteWord(token.ival);
longConstant: WriteLong(token.lval);
longlongConstant: begin
WriteLong(token.qval.lo);
WriteLong(token.qval.hi);
end;
realConstant: WriteExtended(token.rval);
stringConstant: begin
WriteLongString(token.sval);
WriteByte(ord(token.ispstring));
end;
macroParameter: WriteWord(token.pnum);
reservedSymbol: if token.kind in [lbracech,rbracech,lbrackch,
rbrackch,poundch,poundpoundop] then
WriteByte(ord(token.isDigraph));
otherwise: ;
end; {case}
end; {WriteToken}
begin {SaveMacros}
for i := 0 to hashSize do begin {loop over hash buckets}
mp := macros^[i]; {loop over macro records in hash bucket}
while mp <> nil do begin
if not mp^.saved then begin
mp^.saved := true; {mark this one as saved}
WriteString(mp^.name); {write the macroRecord}
WriteByte(mp^.parameters);
WriteByte(ord(mp^.isVarargs));
WriteByte(ord(mp^.readOnly));
WriteByte(mp^.algorithm);
tp := mp^.tokens; {loop over token list}
while tp <> nil do begin
WriteByte(1); {write tokenListRecord}
WriteLongString(tp^.tokenString);
WriteToken(tp^.token);
WriteByte(ord(tp^.expandEnabled));
WriteChars(tp^.tokenStart, tp^.tokenEnd);
tp := tp^.next;
end; {while}
WriteByte(0); {mark end of token list}
end; {if}
mp := mp^.next;
end; {while}
end; {for}
end; {SaveMacros}
begin {SaveMacroTable}
SetMark; {set the macro table length mark}
if saveSource then {write the macro table}
SaveMacros;
if saveSource then {mark the length of the table}
MarkBlock;
end; {SaveMacroTable}
procedure SavePragmaEffects;
{ Save the variables effected by any pragmas encountered }
var
count: 0..maxint; {number of path names}
i: 1..10; {loop/index variable}
p: pragmas; {loop variable}
pp: pathRecordPtr; {used to trace pathname list}
begin {SavePragmaEffects}
SetMark;
if saveSource then
for p := succ(p_startofenum) to pred(p_endofenum) do
if p in savePragmas then
if saveSource then begin
WriteByte(ord(p));
case p of
p_cda: begin
WriteString(@menuLine);
WriteString(openName);
WriteString(closeName);
end;
p_cdev: WriteString(openName);
p_float: begin
WriteWord(floatCard);
WriteWord(floatSlot);
end;
p_keep: WriteLongString(@outFileGS.theString);
p_line: begin
WriteWord(lineNumber);
WriteLongString(@sourceFileGS.theString);
end;
p_nda: begin
WriteString(openName);
WriteString(closeName);
WriteString(actionName);
WriteString(initName);
WriteWord(refreshPeriod);
WriteWord(eventMask);
WriteString(@menuLine);
end;
p_nba:
WriteString(openName);
p_xcmd:
WriteString(openName);
p_debug:
WriteWord(ord(rangeCheck)
| (ord(debugFlag) << 1)
| (ord(profileFlag) << 2)
| (ord(traceBack) << 3)
| (ord(checkStack) << 4)
| (ord(debugStrFlag) << 15));
p_lint: begin
WriteWord(lint);
WriteByte(ord(lintIsError));
end;
p_memorymodel: WriteByte(ord(smallMemoryModel));
p_expand: WriteByte(ord(printMacroExpansions));
p_optimize:
WriteByte(ord(peepHole)
| (ord(npeepHole) << 1)
| (ord(registers) << 2)
| (ord(saveStack) << 3)
| (ord(commonSubexpression) << 4)
| (ord(loopOptimizations) << 5)
| (ord(strictVararg) << 6));
p_stacksize: WriteWord(stackSize);
p_toolparms: WriteByte(ord(toolParms));
p_databank: WriteByte(ord(dataBank));
p_rtl: ;
p_noroot: ;
p_path: begin
pp := pathList;
count := 0;
while pp <> nil do begin
count := count+1;
pp := pp^.next;
end; {while}
WriteWord(count);
pp := pathList;
while pp <> nil do begin
WriteString(pp^.path);
pp := pp^.next;
end; {while}
end; {p_path}
p_ignore:
WriteByte(ord(skipIllegalTokens)
| (ord(allowLongIntChar) << 1)
| (ord(allowTokensAfterEndif) << 2)
| (ord(allowSlashSlashComments) << 3)
| (ord(allowMixedDeclarations) << 4)
| (ord(looseTypeChecks) << 5));
p_segment: begin
for i := 1 to 10 do begin
WriteByte(defaultSegment[i]);
WriteByte(currentSegment[i]);
end; {for}
WriteWord(segmentKind);
end;
p_unix: WriteByte(ord(unix_1));
p_fenv_access: WriteByte(ord(fenvAccess));
end; {case}
end; {if}
if saveSource then
MarkBlock;
savePragmas := [];
end; {SavePragmaEffects}
procedure SaveSourceStream;
{ Save the source stream for later compares }
var
wrRec: readWriteOSDCB; {WriteGS record}
begin {SaveSourceStream}
WriteLong(ord4(chPtr) - ord4(symChPtr));
Purge;
wrRec.pcount := 4;
wrRec.refnum := symRefnum;
wrRec.dataBuffer := pointer(symChPtr);
wrRec.requestCount := ord4(chPtr) - ord4(symChPtr);
WriteGS(wrRec);
symChPtr := chPtr;
if ToolError <> 0 then begin
CloseSymbols;
DestroySymbolFile;
saveSource := false;
end; {if}
end; {SaveSourceStream}
procedure SaveSymbolTable;
{ Save symbols to the symbol file }
procedure SaveSymbol;
{ Write the symbols to the symbol file }
var
abort: boolean; {abort due to initialized var?}
efRec: setMarkOSDCB; {SetEOFGS record}
i: 0..hashSize; {loop/index variable}
sp: identPtr; {used to trace symbol lists}
procedure WriteIdent (ip: identPtr);
{ write a symbol to the symbol file }
{ }
{ parameters: }
{ ip - pointer to symbol entry }
procedure WriteType (tp: typePtr);
{ write a type entry to the symbol file }
{ }
{ parameters: }
{ tp - pointer to type entry }
var
ip: identPtr; {for tracing field list}
procedure WriteParm (pp: parameterPtr);
{ write a parameter list to the symbol file }
{ }
{ parameters: }
{ pp - parameter pointer }
begin {WriteParm}
while pp <> nil do begin
WriteByte(1);
WriteType(pp^.parameterType);
pp := pp^.next;
end; {while}
WriteByte(0);
end; {WriteParm}
begin {WriteType}
if tp = sCharPtr then
WriteByte(2)
else if tp = charPtr then
WriteByte(3)
else if tp = intPtr then
WriteByte(4)
else if tp = uIntPtr then
WriteByte(5)
else if tp = longPtr then
WriteByte(6)
else if tp = uLongPtr then
WriteByte(7)
else if tp = floatPtr then
WriteByte(8)
else if tp = doublePtr then
WriteByte(9)
else if tp = extendedPtr then
WriteByte(10)
else if tp = stringTypePtr then
WriteByte(11)
else if tp = voidPtr then
WriteByte(12)
else if tp = voidPtrPtr then
WriteByte(13)
else if tp = defaultStruct then
WriteByte(14)
else if tp = uCharPtr then
WriteByte(15)
else if tp = shortPtr then
WriteByte(16)
else if tp = uShortPtr then
WriteByte(17)
else if tp^.saveDisp <> 0 then begin
WriteByte(1);
WriteLong(tp^.saveDisp);
end {if}
else begin
WriteByte(0);
tp^.saveDisp := GetMark;
WriteLong(tp^.size);
WriteByte(ord(tqConst in tp^.qualifiers)
| (ord(tqVolatile in tp^.qualifiers) << 1)
| (ord(tqRestrict in tp^.qualifiers) << 2));
WriteByte(ord(tp^.kind));
case tp^.kind of
scalarType: begin
WriteByte(ord(tp^.baseType));
WriteByte(ord(tp^.cType));
end;
arrayType: begin
WriteLong(tp^.elements);
WriteType(tp^.aType);
end;
pointerType:
WriteType(tp^.pType);
functionType: begin
WriteByte((ord(tp^.varargs) << 2)
| (ord(tp^.prototyped) << 1) | ord(tp^.isPascal));
WriteWord(tp^.toolnum);
WriteLong(tp^.dispatcher);
WriteType(tp^.fType);
WriteParm(tp^.parameterList);
end;
enumConst:
WriteWord(tp^.eval);
definedType:
WriteType(tp^.dType);
structType, unionType: begin
ip := tp^.fieldList;
while ip <> nil do begin
WriteByte(1);
WriteIdent(ip);
ip := ip^.next;
end; {while}
WriteByte(0);
WriteByte(ord(tp^.constMember));
end;
otherwise: ;
end; {case}
end; {else}
end; {WriteType}
begin {WriteIdent}
WriteString(ip^.name);
WriteType(ip^.itype);
if (ip^.disp = 0) and (ip^.bitDisp = 0) and (ip^.bitSize = 0) then
WriteByte(0)
else if (ip^.bitSize = 0) and (ip^.bitDisp = 0) then begin
if ip^.disp < maxint then begin
WriteByte(1);
WriteWord(ord(ip^.disp));
end {if}
else begin
WriteByte(2);
WriteLong(ip^.disp);
end; {else}
end {else if}
else begin
WriteByte(3);
WriteLong(ip^.disp);
WriteByte(ip^.bitDisp);
WriteByte(ip^.bitSize);
end; {else}
if ip^.iPtr <> nil then
abort := true;
WriteByte(ord(ip^.state));
WriteByte(ord(ip^.isForwardDeclared));
WriteByte(ord(ip^.class));
WriteByte(ord(ip^.storage));
end; {WriteIdent}
begin {SaveSymbol}
abort := false; {no reason to abort, yet}
for i := 0 to hashSize2 do begin {loop over hash buckets}
sp := globalTable^.buckets[i]; {loop over symbol records in hash bucket}
while sp <> nil do begin
if not sp^.saved then begin
sp^.saved := true; {mark this one as saved}
WriteWord(i); {save the symbol}
WriteIdent(sp);
end; {if}
sp := sp^.next;
end; {while}
end; {for}
if abort then begin
Purge;
efRec.pcount := 3;
efRec.refnum := symRefnum;
efRec.base := 0;
efRec.displacement := tokenMark;
SetEOFGS(efRec);
if ToolError <> 0 then begin
CloseSymbols;
DestroySymbolFile;
end; {if}
saveSource := false;
end; {if}
end; {SaveSymbol}
begin {SaveSymbolTable}
SetMark; {set the symbol table length mark}
if saveSource then {write the symbol table}
if globalTable <> nil then
SaveSymbol;
if saveSource then {mark the length of the table}
MarkBlock;
end; {SaveSymbolTable}
begin {EndInclude}
if not ignoreSymbols then begin
includeLevel := includeLevel-1;
if includeLevel = 0 then
if saveSource then begin
MarkBlock; {set the include name mark}
SaveSourceStream; {save the source stream}
SaveMacroTable; {save the macro table}
SaveSymbolTable; {save the symbol table}
SavePragmaEffects; {save the effects of pragmas}
tokenMark := GetMark; {record mark for early exit}
includeMark := false; {no include mark, yet}
end; {if}
end; {if}
end; {EndInclude}
procedure FlagPragmas {pragma: pragmas};
{ record the effects of a pragma }
{ }
{ parameters: }
{ pragma - pragma to record }
{ }
{ Notes: }
{ 1. Defined as extern in Scanner.pas }
{ 2. For the purposes of this unit, the segment statement }
{ and #line directive are treated as pragmas. }
begin {FlagPragmas}
savePragmas := savePragmas + [pragma];
end; {FlagPragmas}
procedure InitHeader {var fName: gsosOutString};
{ look for a header file, reading it if it exists }
{ }
{ parameters: }
{ fName - source file name (var for efficiency) }
type
typeDispPtr = ^typeDispRecord; {type displacement/pointer table}
typeDispRecord = record
next: typeDispPtr;
saveDisp: longint;
tPtr: typePtr;
end;
var
done: boolean; {for loop termination test}
typeDispList: typeDispPtr; {type displacement/pointer table}
procedure DisposeTypeDispList;
{ Dispose of the type displacement list }
var
tp: typeDispPtr; {work pointer}
begin {DisposeTypeDispList}
while typeDispList <> nil do begin
tp := typeDispList;
typeDispList := tp^.next;
dispose(tp);
end; {while}
end; {DisposeTypeDispList}
function EndOfSymbols: boolean;
{ See if we're at the end of the symbol file }
{ }
{ Returns: True if at the end, else false }
begin {EndOfSymbols}
EndOfSymbols := ord4(symPtr) >= ord4(symEndPtr);
end; {EndOfSymbols}
function OpenSymbols: boolean;
{ open and initialize the symbol file }
{ }
{ Returns: True if successful, else false }
var
crRec: createOSDCB; {CreateGS record}
opRec: openOSDCB; {OpenGS record}
begin {OpenSymbols}
OpenSymbols := false; {assume we will fail}
DestroySymbolFile; {destroy any existing file}
crRec.pCount := 5; {create a symbol file}
crRec.pathName := @symName.theString;
crRec.access := $C3;
crRec.fileType := symFiletype;
crRec.auxType := symAuxtype;
crRec.storageType := 1;
CreateGS(crRec);
if ToolError = 0 then begin
opRec.pCount := 3;
opRec.pathname := @symName.theString;
opRec.requestAccess := 3;
OpenGS(opRec);
if ToolError = 0 then begin
symRefnum := opRec.refnum;
OpenSymbols := true;
WriteWord(symFileVersion);
tokenMark := GetMark;
includeMark := false;
end; {if}
end; {if}
end; {OpenSymbols}
procedure PurgeSymbols;
{ Purge the symbol input file }
var
ffDCBGS: fastFileDCBGS; {fast file DCB}
begin {PurgeSymbols}
with ffDCBGS do begin {purge the file}
pCount := 5;
action := 7;
pathName := @symName.theString;
end; {with}
FastFileGS(ffDCBGS);
end; {PurgeSymbols}
function DatesMatch: boolean;
{ Make sure the create/mod dates have not changed }
var
giRec: getFileInfoOSDCB; {GetFileInfoGS record}
i: 1..maxint; {loop/index variable}
len: longint; {length of names}
match: boolean; {do the dates match?}
begin {DatesMatch}
match := true;
len := ReadLong;
while len > 0 do begin
giRec.pCount := 7;
giRec.pathname := pointer(ReadLongString);
len := len - (giRec.pathname^.size + 18);
GetFileInfoGS(giRec);
if ToolError = 0 then begin
for i := 1 to 8 do
match := match and (giRec.createDateTime[i] = ReadByte);
for i := 1 to 8 do
match := match and (giRec.modDateTime[i] = ReadByte);
end {if}
else begin
match := false;
len := 0;
end; {else}
if match and progress then begin
write('Including ');
for i := 1 to giRec.pathname^.size do
write(giRec.pathname^.theString[i]);
writeln;
end; {if}
end; {while}
DatesMatch := match;
end; {DatesMatch}
procedure ReadMacroTable;
{ Read macros from the symbol file }
var
bp: ^macroRecordPtr; {pointer to head of hash bucket}
ep: tokenListRecordPtr; {last token record}
mePtr: ptr; {end of macro table}
mp: macroRecordPtr; {new macro record}
tlen: integer; {length of the token name}
tp: tokenListRecordPtr; {new token record}
procedure ReadToken (var token: tokenType);
{ read a token }
{ }
{ parameters: }
{ token - (output) token read) }
begin {ReadToken}
token.kind := tokenEnum(ReadByte);
token.class := tokenClass(ReadByte);
if ReadByte = 0 then
token.numString := nil
else
token.numstring := ReadString;
case token.class of
identifier: token.name := ReadString;
intConstant: token.ival := ReadWord;
longConstant: token.lval := ReadLong;
longlongConstant: begin
token.qval.lo := ReadLong;
token.qval.hi := ReadLong;
end;
realConstant: token.rval := ReadExtended;
stringConstant: begin
token.sval := ReadLongString;
token.ispstring := ReadByte <> 0;
end;
macroParameter: token.pnum := ReadWord;
reservedSymbol: if token.kind in [lbracech,rbracech,lbrackch,
rbrackch,poundch,poundpoundop] then
token.isDigraph := boolean(ReadByte);
otherwise: ;
end; {case}
end; {ReadToken}
begin {ReadMacroTable}
mePtr := symPtr; {read the block length}
mePtr := pointer(ord4(mePtr) + ReadLong + 4);
while ord4(symPtr) < ord4(mePtr) do {process the macros}
begin
Spin;
mp := pointer(GMalloc(sizeof(macroRecord)));
mp^.saved := false;
mp^.name := ReadString;
bp := pointer(ord4(macros) + Hash(mp^.name));
mp^.next := bp^;
bp^ := mp;
mp^.parameters := ReadByte;
if mp^.parameters & $0080 <> 0 then
mp^.parameters := mp^.parameters | $FF00;
mp^.isVarargs := boolean(ReadByte);
mp^.readOnly := boolean(ReadByte);
mp^.algorithm := ReadByte;
mp^.tokens := nil;
ep := nil;
while ReadByte <> 0 do begin
tp := pointer(GMalloc(sizeof(tokenListRecord)));
tp^.next := nil;
tp^.tokenString := ReadLongString;
ReadToken(tp^.token);
tp^.expandEnabled := boolean(ReadByte);
ReadChars(tp^.tokenStart, tp^.tokenEnd);
if ep = nil then
mp^.tokens := tp
else
ep^.next := tp;
ep := tp;
end; {while}
end; {while}
symPtr := mePtr;
end; {ReadMacroTable}
procedure ReadPragmas;
{ Read pragma effects }
var
i: 0..maxint; {loop/index variable}
lsPtr: longStringPtr; {work pointer}
p: pragmas; {kind of pragma being processed}
pePtr: ptr; {end of pragma table}
pp, ppe: pathRecordPtr; {used to create a path name list}
sPtr: stringPtr; {work pointer}
val: integer; {temp value}
begin {ReadPragmas}
pePtr := symPtr; {read the block length}
pePtr := pointer(ord4(pePtr) + ReadLong + 4);
while ord4(symPtr) < ord4(pePtr) do {process the pragmas}
begin
Spin;
p := pragmas(ReadByte);
case p of
p_cda: begin
isClassicDeskAcc := true;
sPtr := ReadString;
menuLine := sPtr^;
openName := ReadString;
closeName := ReadString;
end;
p_cdev: begin
isCDev := true;
openName := ReadString;
end;
p_float: begin
floatCard := ReadWord;
floatSlot := ReadWord;
end;
p_keep: begin
liDCBGS.kFlag := 1;
lsPtr := ReadLongString;
outFileGS.theString.size := lsPtr^.length;
for i := 1 to outFileGS.theString.size do
outFileGS.theString.theString[i] := lsPtr^.str[i];
end;
p_line: begin
lineNumber := ReadWord;
lsPtr := ReadLongString;
sourceFileGS.theString.size := lsPtr^.length;
for i := 1 to sourceFileGS.theString.size do
sourceFileGS.theString.theString[i] := lsPtr^.str[i];
end;
p_nda: begin
isNewDeskAcc := true;
openName := ReadString;
closeName := ReadString;
actionName := ReadString;
initName := ReadString;
refreshPeriod := ReadWord;
eventMask := ReadWord;
sPtr := ReadString;
menuLine := sPtr^;
end;
p_nba: begin
isNBA := true;
openName := ReadString;
end;
p_xcmd: begin
isXCMD := true;
openName := ReadString;
end;
p_debug: begin
val := ReadWord;
rangeCheck := odd(val);
debugFlag := odd(val >> 1);
profileFlag := odd(val >> 2);
traceback := odd(val >> 3);
checkStack := odd(val >> 4);
debugStrFlag := odd(val >> 15);
end;
p_lint: begin
lint := ReadWord;
lintIsError := boolean(ReadByte);
end;
p_memorymodel: smallMemoryModel := boolean(ReadByte);
p_expand: printMacroExpansions := boolean(ReadByte);
p_optimize: begin
val := ReadByte;
peepHole := odd(val);
npeepHole := odd(val >> 1);
registers := odd(val >> 2);
saveStack := odd(val >> 3);
commonSubexpression := odd(val >> 4);
loopOptimizations := odd(val >> 5);
strictVararg := odd(val >> 6);
end;
p_stacksize: stackSize := ReadWord;
p_toolparms: toolParms := boolean(ReadByte);
p_databank: dataBank := boolean(ReadByte);
p_rtl: rtl := true;
p_noroot: noroot := true;
p_path: begin
i := ReadWord;
pathList := nil;
ppe := nil;
while i <> 0 do begin
pp := pathRecordPtr(GMalloc(sizeof(pathRecord)));
pp^.path := ReadString;
pp^.next := nil;
if pathList = nil then
pathList := pp
else
ppe^.next := pp;
ppe := pp;
i := i-1;
end; {while}
end; {p_path}
p_ignore: begin
i := ReadByte;
skipIllegalTokens := odd(i);
allowLongIntChar := odd(i >> 1);
allowTokensAfterEndif := odd(i >> 2);
allowSlashSlashComments := odd(i >> 3);
allowMixedDeclarations := odd(i >> 4);
c99Scope := allowMixedDeclarations;
looseTypeChecks := odd(i >> 5);
end;
p_segment: begin
for i := 1 to 10 do begin
defaultSegment[i] := chr(ReadByte);
currentSegment[i] := chr(ReadByte);
end; {for}
segmentKind := ReadWord;
end;
p_unix: unix_1 := boolean(ReadByte);
p_fenv_access: fenvAccess := boolean(ReadByte);
otherwise: begin
PurgeSymbols;
DestroySymbolFile;
TermError(12);
end;
end; {case}
end; {while}
symPtr := pePtr;
end; {ReadPragmas}
procedure ReadSymbolTable;
{ Read symbols from the symbol file }
var
hashPtr: ^identPtr; {pointer to hash bucket in symbol table}
sePtr: ptr; {end of symbol table}
sp: identPtr; {identifier being constructed}
function ReadIdent: identPtr;
{ Read an identifier from the file }
{ }
{ Returns: Pointer to the new identifier }
var
format: 0..3; {storage format}
sp: identPtr; {identifier being constructed}
procedure ReadType (var tp: typePtr);
{ read a type from the symbol file }
{ }
{ parameters: }
{ tp - (output) type entry }
var
disp: longint; {disp read from symbol file}
ep: identPtr; {end of list of field names}
ip: identPtr; {for tracing field list}
tdisp: typeDispPtr; {used to trace, add to typeDispList}
val: integer; {temp word}
procedure ReadParm (var pp: parameterPtr);
{ read a parameter list from the symbol file }
{ }
{ parameters: }
{ pp - (output) parameter pointer }
var
ep: parameterPtr; {last parameter in list}
np: parameterPtr; {new parameter}
begin {ReadParm}
pp := nil;
ep := nil;
while ReadByte = 1 do begin
np := parameterPtr(GMalloc(sizeof(parameterRecord)));
np^.next := nil;
np^.parameter := nil;
ReadType(np^.parameterType);
if ep = nil then
pp := np
else
ep^.next := np;
ep := np;
end; {while}
end; {ReadParm}
begin {ReadType}
case ReadByte of
0: begin {read a new type}
tp := typePtr(GMalloc(sizeof(typeRecord)));
new(tdisp);
tdisp^.next := typeDispList;
typeDispList := tdisp;
tdisp^.saveDisp := ord4(symPtr) - ord4(symStartPtr);
tdisp^.tPtr := tp;
tp^.size := ReadLong;
tp^.saveDisp := 0;
val := ReadByte;
if odd(val) then
tp^.qualifiers := [tqConst]
else
tp^.qualifiers := [];
if odd(val >> 1) then begin
tp^.qualifiers := tp^.qualifiers + [tqVolatile];
volatile := true;
end; {if}
if odd(val >> 2) then
tp^.qualifiers := tp^.qualifiers + [tqRestrict];
tp^.kind := typeKind(ReadByte);
case tp^.kind of
scalarType: begin
tp^.baseType := baseTypeEnum(ReadByte);
tp^.cType := cTypeEnum(ReadByte);
end;
arrayType: begin
tp^.elements := ReadLong;
ReadType(tp^.aType);
end;
pointerType:
ReadType(tp^.pType);
functionType: begin
val := ReadByte;
tp^.varargs := odd(val >> 2);
tp^.prototyped := odd(val >> 1);
tp^.isPascal := odd(val);
tp^.toolnum := ReadWord;
tp^.dispatcher := ReadLong;
ReadType(tp^.fType);
ReadParm(tp^.parameterList);
end;
enumConst:
tp^.eval := ReadWord;
definedType:
ReadType(tp^.dType);
structType, unionType: begin
tp^.fieldList := nil;
ep := nil;
while ReadByte = 1 do begin
ip := ReadIdent;
if ep = nil then
tp^.fieldList := ip
else
ep^.next := ip;
ep := ip;
end; {while}
tp^.constMember := boolean(ReadByte);
end;
enumType: ;
otherwise: begin
PurgeSymbols;
DestroySymbolFile;
TermError(12);
end;
end; {case}
end; {case 0}
1: begin {read a type displacement}
tdisp := typeDispList;
disp := ReadLong;
tp := nil;
while tdisp <> nil do
if tdisp^.saveDisp = disp then begin
tp := tdisp^.tPtr;
tdisp := nil;
end {if}
else
tdisp := tdisp^.next;
if tp = nil then begin
PurgeSymbols;
DestroySymbolFile;
TermError(12);
end; {if}
end; {case 1}
2: tp := sCharPtr;
3: tp := charPtr;
4: tp := intPtr;
5: tp := uIntPtr;
6: tp := longPtr;
7: tp := uLongPtr;
8: tp := floatPtr;
9: tp := doublePtr;
10: tp := extendedPtr;
11: tp := stringTypePtr;
12: tp := voidPtr;
13: tp := voidPtrPtr;
14: tp := defaultStruct;
15: tp := uCharPtr;
16: tp := shortPtr;
17: tp := uShortPtr;
otherwise: begin
PurgeSymbols;
DestroySymbolFile;
TermError(12);
end;
end; {case}
end; {ReadType}
begin {ReadIdent}
sp := pointer(GMalloc(sizeof(identRecord)));
sp^.next := nil;
sp^.saved := false;
sp^.name := ReadString;
ReadType(sp^.itype);
format := ReadByte;
if format = 0 then begin
sp^.disp := 0;
sp^.bitDisp := 0;
sp^.bitSize := 0;
end {if}
else if format = 1 then begin
sp^.disp := ReadWord;
sp^.bitDisp := 0;
sp^.bitSize := 0;
end {else if}
else if format = 2 then begin
sp^.disp := ReadLong;
sp^.bitDisp := 0;
sp^.bitSize := 0;
end {else if}
else begin
sp^.disp := ReadLong;
sp^.bitDisp := ReadByte;
sp^.bitSize := ReadByte;
end; {else}
sp^.iPtr := nil;
sp^.state := stateKind(ReadByte);
sp^.isForwardDeclared := boolean(ReadByte);
sp^.class := tokenEnum(ReadByte);
sp^.storage := storageType(ReadByte);
ReadIdent := sp;
end; {ReadIdent}
begin {ReadSymbolTable}
sePtr := symPtr; {read the block length}
sePtr := pointer(ord4(sePtr) + ReadLong + 4);
while ord4(symPtr) < ord4(sePtr) do {process the symbols}
begin
Spin;
hashPtr := pointer(ord4(globalTable) + ReadWord*4);
sp := ReadIdent;
sp^.next := hashPtr^;
hashPtr^ := sp;
end; {while}
symPtr := sePtr;
end; {ReadSymbolTable}
function OpenSymbolFile (var fName: gsosOutString): boolean;
{ Look for and open a symbol file }
{ }
{ parameters: }
{ fName - source file name (var for efficiency) }
{ }
{ Returns: True if the file was found and opened, else false }
{ }
{ Notes: As a side effect, this subroutine creates the }
{ pathname for the symbol file (symName). }
var
ffDCBGS: fastFileDCBGS; {fast file DCB}
i: integer; {loop/index variable}
begin {OpenSymbolFile}
symName := fName; {create the symbol file name}
i := symName.theString.size - 1;
while not (symName.theString.theString[i] in [':', '/', '.']) do
i := i-1;
if symName.theString.theString[i] <> '.' then
i := symName.theString.size;
if i > maxPath-5 then
i := maxPath-5;
symName.theString.theString[i] := '.';
symName.theString.theString[i+1] := 's';
symName.theString.theString[i+2] := 'y';
symName.theString.theString[i+3] := 'm';
symName.theString.theString[i+4] := chr(0);
symName.theString.size := i+3;
if rebuildSymbols then begin {rebuild any existing symbol file}
DestroySymbolFile;
OpenSymbolFile := false;
end {if}
else begin
with ffDCBGS do begin {read the symbol file}
pCount := 14;
action := 0;
flags := $C000;
pathName := @symName.theString;
end; {with}
FastFileGS(ffDCBGS);
if ToolError = 0 then begin
if (ffDCBGS.filetype = symFiletype) and (ffDCBGS.auxtype = symAuxtype) then
OpenSymbolFile := true
else begin
OpenSymbolFile := false;
PurgeSymbols;
end; {else}
symPtr := ffDCBGS.fileHandle^;
symStartPtr := symPtr;
symEndPtr := pointer(ord4(symPtr) + ffDCBGS.fileLength);
end {if}
else
OpenSymbolFile := false;
end; {else}
end; {OpenSymbolFile}
function SymbolVersion: integer;
{ Read the symbol file version number }
{ }
{ Returns: version number }
begin {SymbolVersion}
SymbolVersion := ReadWord;
end; {SymbolVersion}
function SourceMatches: boolean;
{ Make sure the token streams match up to the next include }
type
intPtr = ^integer; {for faster compares}
var
len, len2: longint; {size of stream to compare}
match: boolean; {result flag}
p1, p2: ptr; {work pointers}
begin {SourceMatches}
match := true;
len := ReadLong;
len2 := len;
p1 := symPtr;
p2 := chPtr;
while len > 1 do
if intPtr(p1)^ <> intPtr(p2)^ then begin
match := false;
len := 0;
end {if}
else begin
len := len-2;
p1 := pointer(ord4(p1)+2);
p2 := pointer(ord4(p2)+2);
end; {else}
if len = 1 then
if p1^ <> p2^ then
match := false;
if match then begin
symPtr := pointer(ord4(symPtr)+len2);
symChPtr := pointer(ord4(chPtr)+len2);
while chPtr <> symChPtr do
NextCh;
end; {if}
SourceMatches := match;
end; {SourceMatches}
begin {InitHeader}
inhibitHeader := false; {don't block .sym files}
if not ignoreSymbols then begin
codeStarted := false; {code generation has not started}
new(buffer); {allocate an output buffer}
bufPtr := pointer(buffer);
bufLen := bufSize;
includeLevel := 0; {no nested includes}
symChPtr := chPtr; {record initial source location}
if OpenSymbolFile(fName) then begin {check for symbol file}
if SymbolVersion = symFileVersion then begin
done := EndOfSymbols; {valid file found - process it}
if done then
PurgeSymbols;
typeDispList := nil;
while not done do begin
if DatesMatch then begin
if SourceMatches then begin
ReadMacroTable;
ReadSymbolTable;
ReadPragmas;
if EndOfSymbols then begin
done := true;
PurgeSymbols;
end; {if}
end {if}
else begin
PurgeSymbols;
DestroySymbolFile;
done := true;
end; {else}
end {if}
else begin
PurgeSymbols;
DestroySymbolFile;
done := true;
end; {else}
end; {while}
DisposeTypeDispList;
saveSource := false;
if ord4(symPtr) > ord4(symEndPtr) then begin
PurgeSymbols;
DestroySymbolFile;
TermError(12);
end; {if}
end {if}
else begin
PurgeSymbols; {no file found}
saveSource := true;
end; {else}
end {if}
else
saveSource := true;
if saveSource then begin {start saving source}
saveSource := OpenSymbols;
savePragmas := [];
DoDefaultsDotH;
end; {if}
end {if}
else
DoDefaultsDotH;
end; {InitHeader}
procedure StartInclude {name: gsosOutStringPtr};
{ Marks the start of an include file }
{ }
{ Notes: }
{ 1. Call this subroutine right after opening an include }
{ file. }
{ 2. Defined externally in Scanner.pas }
var
giRec: getFileInfoOSDCB; {GetFileInfoGS record}
i: 1..8; {loop/index counter}
begin {StartInclude}
if inhibitHeader then
TermHeader;
if not ignoreSymbols then begin
includeLevel := includeLevel+1;
if saveSource then begin
if not includeMark then begin
includeMark := true;
SetMark;
end; {if}
giRec.pCount := 7;
giRec.pathname := pointer(ord4(name)+2);
GetFileInfoGS(giRec);
WriteLongString(pointer(giRec.pathname));
for i := 1 to 8 do
WriteByte(giRec.createDateTime[i]);
for i := 1 to 8 do
WriteByte(giRec.modDateTime[i]);
end {if}
else if not codeStarted then
DestroySymbolFile;
end; {if}
end; {StartInclude}
procedure TermHeader;
{ Stop processing the header file }
{ }
{ Note: This is called when the first code-generating }
{ subroutine is found, and again when the compile ends. It }
{ closes any open symbol file, and should take no action if }
{ called twice. }
begin {TermHeader}
if not ignoreSymbols then begin
codeStarted := true;
if saveSource then begin
CloseSymbols;
saveSource := false;
dispose(buffer);
end; {if}
end; {if}
end; {TermHeader}
end.
|
unit Main;
interface
(*
On http://docwiki.embarcadero.com/RADStudio/XE2/en/Creating_the_Application_and_Placing_the_Visual_Objects
you can see an example on how to use LiveBindings in a VCL application in Delphi XE2.
However it actually requires lots of things to do and in fact you end up having
more code to write than doing it the "traditional way". You actually have to
implement the OnChange event for the SpinEdits - so where is the point actually
using bindings?!
In this sample you can see how this exact same example is done with
DSharp Bindings and how you can benefit from using them.
If you are using Delphi XE2 feel free to compare both possibilities.
DSharp bindings work in Delphi 2010 and later.
*)
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, ComCtrls, Grids, DSharp.Bindings.VCLControls,
DSharp.Bindings, Spin,
// the following unit is added manually (needs to be after Spin.pas)
// it's not included in the DSharp Bindings package
// because if would cause requiring the samples package
DSharp.Bindings.VCLControls.SpinEdit;
type
TForm1 = class(TForm)
seTop: TSpinEdit;
seLeft: TSpinEdit;
seWidth: TSpinEdit;
seHeight: TSpinEdit;
lblTop: TLabel;
lblLeft: TLabel;
lblWidth: TLabel;
lblHeight: TLabel;
pnlPicture: TPanel;
Image1: TImage;
BindingGroup1: TBindingGroup;
procedure FormCreate(Sender: TObject);
private
procedure ResizeImage(Sender: TObject);
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
type
// Yeah I know, a hack to access protected member,
// but hey why manually triggering the repaint when we can use the resize event?!
TImageHack = class(ExtCtrls.TImage);
procedure TForm1.FormCreate(Sender: TObject);
begin
TImageHack(Image1).OnResize := ResizeImage;
// trigger it manually to paint the image when the application starts
ResizeImage(nil);
end;
procedure TForm1.ResizeImage(Sender: TObject);
var
I, J: Integer;
Bitmap: TBitmap;
begin
Bitmap := TBitmap.Create;
Bitmap.Width := Image1.Width;
Bitmap.Height := Image1.Height;
for I := 0 to Bitmap.Width do
for J := 0 to Bitmap.Height do
Bitmap.Canvas.Pixels[I, J] := RGB(I, J, 128);
Image1.Picture.Bitmap := Bitmap;
Bitmap.Free;
end;
end.
|
unit Facebook.Aniversario.Model;
interface
uses
System.SysUtils,
System.Classes,
IdIOHandler,
IdIOHandlerSocket,
IdIOHandlerStack,
IdSSL,
IdSSLOpenSSL,
IdBaseComponent,
IdComponent,
IdTCPConnection,
IdTCPClient,
IdHTTP,
Data.DB,
Datasnap.DBClient;
type
TdmModel = class(TDataModule)
IdHTTP1: TIdHTTP;
IdSSLIOHandlerSocketOpenSSL1: TIdSSLIOHandlerSocketOpenSSL;
cdsDados: TClientDataSet;
cdsDadosID: TStringField;
cdsDadosNOME: TStringField;
cdsDadosFOTO: TGraphicField;
cdsDadosDIA: TIntegerField;
cdsDadosMES: TIntegerField;
cdsDadosANO: TIntegerField;
procedure cdsDadosAfterScroll(DataSet: TDataSet);
private
{ Private declarations }
public
procedure EsvaziarTabela;
procedure ListarAmigos(const AIDFacebook: string; const access_token: string);
procedure RecuperarAniversarios(const AIDFacebook: string; const access_token: string);
procedure RecuperarFotoPerfil(const IDAmigo: string);
procedure PostarMensagem(const AIDFacebook: string; const access_token: string);
end;
var
dmModel: TdmModel;
implementation
uses
Data.DBXJSON,
jpeg,
Vcl.Graphics,
GIFImg,
System.RegularExpressions;
{ %CLASSGROUP 'System.Classes.TPersistent' }
{$R *.dfm}
{ TDataModule1 }
procedure TdmModel.cdsDadosAfterScroll(DataSet: TDataSet);
begin
if (Self.cdsDadosFOTO.IsNull) then
begin
Self.RecuperarFotoPerfil(Self.cdsDadosID.AsString);
end;
end;
procedure TdmModel.EsvaziarTabela;
begin
Self.cdsDados.EmptyDataSet;
end;
procedure TdmModel.ListarAmigos(const AIDFacebook: string; const access_token: string);
const
C_AMIGOS = 'https://graph.facebook.com.br/%s/friends?access_token=%s';
var
sURL : string;
oResponse : TStringStream;
oConteudoJSON : TJSONObject;
oAmigos : TJSONArray;
oItemAmigo : TJSONValue;
oItemAmigoObject: TJSONObject;
begin
oResponse := TStringStream.Create;
oConteudoJSON := nil;
try
Self.cdsDados.DisableControls;
sURL := Format(C_AMIGOS, [AIDFacebook, access_token]);
Self.IdHTTP1.Get(sURL, oResponse);
oConteudoJSON := (TJSONObject.ParseJSONValue(oResponse.DataString) as TJSONObject);
if Assigned(oConteudoJSON) then
begin
oAmigos := (oConteudoJSON.Get('data').JsonValue as TJSONArray);
for oItemAmigo in oAmigos do
begin
oItemAmigoObject := (oItemAmigo as TJSONObject);
Self.cdsDados.Append;
Self.cdsDadosID.Value := (oItemAmigoObject.Get('id').JsonValue as TJSONString).Value;
Self.cdsDadosNOME.Value := (oItemAmigoObject.Get('name').JsonValue as TJSONString).Value;
Self.cdsDados.Post;
end;
end;
finally
if (Assigned(oConteudoJSON)) then
begin
oConteudoJSON.Free;
end;
oResponse.Free;
Self.cdsDados.EnableControls;
end;
end;
procedure TdmModel.PostarMensagem(const AIDFacebook, access_token: string);
const
C_POST = 'https://graph.facebook.com.br/me/feed?message=%s&access_token=%s';
var
sURL : string;
oConteudo: TStringStream;
sDados : string;
sMensagem: string;
begin
oConteudo := TStringStream.Create;
try
try
sMensagem := 'Mensagem%20postada%20a%20partir%20de%20um%20aplicativo%20feito%20em%20Delphi';
sURL := Format(C_POST, [sMensagem, access_token]);
Self.IdHTTP1.Post(sURL, oConteudo);
except
on E: Exception do
begin
oConteudo.LoadFromStream(Self.IdHTTP1.Response.ContentStream);
sDados := oConteudo.DataString;
end;
end;
finally
oConteudo.Free;
end;
end;
procedure TdmModel.RecuperarAniversarios(const AIDFacebook: string; const access_token: string);
type
TAniversario = record
ANO: Integer;
MES: Integer;
DIA: Integer;
end;
function _ProcessarData(const AData: string): TAniversario;
const
C_DATA = '([\d]+)/([\d]+)(/([\d]+))?';
var
_data : TMatch;
_grupo: TGroup;
begin
_data := TRegEx.Match(AData, C_DATA, []);
if _data.Success then
begin
for _grupo in _data.Groups do
begin
case _grupo.Index of
1:
Result.DIA := StrToIntDef(_grupo.Value, 0);
4:
Result.MES := StrToIntDef(_grupo.Value, 0);
7:
Result.ANO := StrToIntDef(_grupo.Value, 0);
end;
end;
end;
end;
const
C_NASCIMENTO = 'https://graph.facebook.com.br/%s/friends?fields=gender,birthday&access_token=%s';
var
oResponse : TStringStream;
oConteudoJSON : TJSONObject;
oAmigos : TJSONArray;
oItemAmigo : TJSONValue;
oItemAmigoObject: TJSONObject;
sURL : string;
rAniversario : TAniversario;
begin
oResponse := TStringStream.Create;
Self.cdsDados.AfterScroll := nil;
try
sURL := Format(C_NASCIMENTO, [AIDFacebook, access_token]);
Self.IdHTTP1.Get(sURL, oResponse);
oConteudoJSON := (TJSONObject.ParseJSONValue(oResponse.DataString) as TJSONObject);
if Assigned(oConteudoJSON) then
begin
oAmigos := (oConteudoJSON.Get('data').JsonValue as TJSONArray);
for oItemAmigo in oAmigos do
begin
oItemAmigoObject := (oItemAmigo as TJSONObject);
if (Assigned(oItemAmigoObject.Get('birthday'))) then
begin
if Self.cdsDados.FindKey([(oItemAmigoObject.Get('id').JsonValue as TJSONString).Value]) then
begin
rAniversario := _ProcessarData((oItemAmigoObject.Get('birthday').JsonValue as TJSONString).Value);
Self.cdsDados.Edit;
Self.cdsDadosDIA.Value := rAniversario.DIA;
Self.cdsDadosMES.Value := rAniversario.MES;
Self.cdsDadosANO.Value := rAniversario.ANO;
Self.cdsDados.Post;
end;
end;
end;
end;
finally
if Assigned(oConteudoJSON) then
begin
oConteudoJSON.Free;
end;
oResponse.Free;
Self.cdsDados.AfterScroll := Self.cdsDadosAfterScroll;
end;
end;
procedure TdmModel.RecuperarFotoPerfil(const IDAmigo: string);
const
C_FOTO = 'https://graph.facebook.com.br/%s/picture?type=large';
var
oJPG : TJPEGImage;
oGIF : TGIFImage;
oBMP : TBitmap;
oResponse : TStringStream;
sURL : string;
sLocalFoto: string;
begin
if (Self.cdsDados.State <> dsBrowse) then
begin
Exit;
end;
oResponse := TStringStream.Create;
oJPG := TJPEGImage.Create;
oBMP := TBitmap.Create;
oGIF := TGIFImage.Create;
try
sURL := Format(C_FOTO, [IDAmigo]);
try
Self.IdHTTP1.Get(sURL, oResponse);
except
on E: Exception do
begin
sLocalFoto := Self.IdHTTP1.Response.Location;
end;
end;
Self.IdHTTP1.Get(sLocalFoto, oResponse);
oResponse.Seek(0, 0);
if (oResponse.Size > 0) then
begin
if (Self.IdHTTP1.Response.ContentType = 'image/jpeg') then
begin
oJPG.LoadFromStream(oResponse);
oBMP.Assign(oJPG);
oResponse.Clear;
oBMP.SaveToStream(oResponse);
end;
if (Self.IdHTTP1.Response.ContentType = 'image/gif') then
begin
oGIF.LoadFromStream(oResponse);
oBMP.Assign(oGIF);
oResponse.Clear;
oBMP.SaveToStream(oResponse);
end;
Self.cdsDados.Edit;
Self.cdsDadosFOTO.LoadFromStream(oResponse);
Self.cdsDados.Post;
end;
finally
oJPG.Free;
oBMP.Free;
oGIF.Free;
oResponse.Free;
end;
end;
end.
|
unit DatosDonantesRecurrentes;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DatosModule, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, Menus, cxLookAndFeelPainters, dxPSGlbl,
dxPSUtl, dxPSEngn, dxPrnPg, dxBkgnd, dxWrap, dxPrnDev, dxPSCompsProvider,
dxPSFillPatterns, dxPSEdgePatterns, ABSMain, JvStringHolder, StdActns,
ActnList, ADODB, cxGridCustomPopupMenu, cxGridPopupMenu, dxPSContainerLnk,
dxPSdxLCLnk, dxPSCore, dxPScxCommon, dxPScxGridLnk, JvComponentBase,
JvFormPlacement, ExtCtrls, dxLayoutControl, StdCtrls, cxButtons, cxGridLevel,
cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, cxPC, JvExControls, JvComponent,
JvEnterTab;
type
TfrmDatosDonantesRecurrentes = class(TfrmDatosModule)
qrDatos: TADOQuery;
qrDatosDonaciones: TIntegerField;
qrDatosPacienteID: TStringField;
qrDatosDonacionStatus: TWideStringField;
qrDatosNOMBRE: TStringField;
tvDatosDonaciones: TcxGridDBColumn;
tvDatosPacienteID: TcxGridDBColumn;
tvDatosDonacionStatus: TcxGridDBColumn;
tvDatosNOMBRE: TcxGridDBColumn;
tvDatosTipoSangre: TcxGridDBColumn;
qrDatosTipoSangre: TWideStringField;
qrDatosRH: TWideStringField;
tvDatosRH: TcxGridDBColumn;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
function CanAdd: Boolean;
public
{ Public declarations }
end;
var
frmDatosDonantesRecurrentes: TfrmDatosDonantesRecurrentes;
implementation
{$R *.dfm}
function TfrmDatosDonantesRecurrentes.CanAdd;
begin
result:= false;
end;
procedure TfrmDatosDonantesRecurrentes.FormCreate(Sender: TObject);
begin
inherited;
qrDatos.Close;
qrDatos.Open;
end;
end.
|
// Fit4Delphi Copyright (C) 2008. Sabre Inc.
// 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.
//
// Ported to Delphi by Michal Wojcik.
//
unit RegexTest;
interface
uses
StrUtils,
TestFramework;
type
TRegexTest = class(TTestCase)
protected
procedure assertMatches(regexp : string; str : string);
procedure assertNotMatches(regexp : string; str : string);
procedure assertHasRegexp(regexp : string; output : string);
procedure assertDoesntHaveRegexp(regexp : string; output : string);
procedure assertSubString(substring : string; str : string);
procedure assertNotSubString(subString : string; str : string);
function divWithIdAndContent(id : string; expectedDivContent : string) : string;
end;
implementation
uses
Matcher;
{ TRegexTest }
procedure TRegexTest.assertMatches(regexp : string; str : string);
begin
assertHasRegexp(regexp, str);
end;
procedure TRegexTest.assertNotMatches(regexp : string; str : string);
begin
assertDoesntHaveRegexp(regexp, str);
end;
procedure TRegexTest.assertHasRegexp(regexp : string; output : string);
var
match : TRegExpr;
found : boolean;
begin
match := TRegExpr.Create;
try
match.ModifierS := true;
match.Expression := regexp;
// match:=Pattern.compile(regexp,Pattern.MULTILINE|Pattern.DOTALL).matcher(output);
found := match.Exec(output);
if (not found) then
begin
fail('The regexp <' + regexp + '> was not found in: ' + output + '.');
end;
finally
match.Free;
end;
end;
procedure TRegexTest.assertDoesntHaveRegexp(regexp : string; output : string);
var
match : TRegExpr;
found : boolean;
begin
match := TRegExpr.Create;
try
match.ModifierS := true;
match.Expression := regexp;
// match := Pattern.compile(regexp, Pattern.MULTILINE).matcher(output);
found := match.Exec(output);
if (found) then
begin
fail('The regexp <' + regexp + '> was found.');
end;
finally
match.Free;
end;
end;
procedure TRegexTest.assertSubString(substring : string; str : string);
begin
if (Pos(substring, str) = 0) then
begin
fail('substring '+substring+' not found.');
end;
end;
procedure TRegexTest.assertNotSubString(subString : string; str : string);
begin
if (Pos(subString, str) > 0) then
begin
fail('expecting substring:'+subString+' in string:'+str+'');
end;
end;
function TRegexTest.divWithIdAndContent(id : string; expectedDivContent : string) : string;
begin
result := '<div.*?id=\"' + id + '\".*?>' + expectedDivContent + '</div>';
end;
end.
|
unit ExceptSafe;
interface
uses SysUtils;
{
Exceptions derived from this ENotFatal will be displayed to the user
in a pop-up message box, exactly as for the default Delphi exception
handling. All other exception types will be displayed, and then the
application will be shut down once the user clicks the "Close" button.
For example:
type EProject = class( Exception );
type EProject = class( ENotFatal );
}
type ESafe = class( Exception );
implementation
end.
|
unit uLocalize;
{$MODE Delphi}
interface
uses LCLIntf, LCLType, LMessages, SysUtils{, Consts};
const
rs_Error = 'Chyba';
rs_Question = 'Potvrzení';
rs_Warning = 'Varování';
rs_Exclamation = 'Upozornìní';
rs_Asterisk = 'Informace';
rs_Yes = '&Ano';
rs_No = '&Ne';
rs_Cancel = '&Storno';
rs_All = '&Ve';
rs_OK = '&OK';
type
TLocalizeResString = record
ResString: PResStringRec;
LocalizedText: string;
end;
{ lokalizace dialogu MessageDlg }
procedure LocalizeDialogs;
implementation
{-----------------------------------------------------------------
Prepsani resource v dialozich
------------------------------------------------------------------}
procedure LocalizeResStrings(const Strings: array of TLocalizeResString);
var
I: Integer;
OldProtect, Dummy: DWORD;
begin
for I := Low(Strings) to High(Strings) do
with Strings[I] do
begin
Win32Check(VirtualProtect(ResString, SizeOf(TResStringRec),
PAGE_READWRITE, OldProtect));
try
ResString^.Identifier := Integer(PChar(LocalizedText));
finally
VirtualProtect(ResString, SizeOf(TResStringRec), OldProtect, Dummy);
end;
end;
end;
{-----------------------------------------------------------------
Lokalizace dialogu
------------------------------------------------------------------}
procedure LocalizeDialogs;
var
ResStrings: array[0..7] of TLocalizeResString;
begin
ResStrings[0].ResString := @SMsgDlgYes;
ResStrings[0].LocalizedText := rs_Yes;
ResStrings[1].ResString := @SMsgDlgNo;
ResStrings[1].LocalizedText:= rs_No;
ResStrings[2].ResString := @SMsgDlgWarning;
ResStrings[2].LocalizedText:= rs_Warning ;
ResStrings[3].ResString := @SMsgDlgError;
ResStrings[3].LocalizedText:= rs_Error;
ResStrings[4].ResString := @SMsgDlgInformation;
ResStrings[4].LocalizedText:= rs_Asterisk;
ResStrings[5].ResString := @SMsgDlgConfirm;
ResStrings[5].LocalizedText:= rs_Question;
ResStrings[6].ResString := @SMsgDlgAll;
ResStrings[6].LocalizedText:= rs_All;
ResStrings[7].ResString := @SMsgDlgCancel;
ResStrings[7].LocalizedText:= rs_Cancel;
LocalizeResStrings(ResStrings);
end;
end.
|
(*============================================================================
-----BEGIN PGP SIGNED MESSAGE-----
This code (c) 1994, 1997 Graham THE Ollis
GENERAL NOTES
=============
This is 16bit DOS TURBO PASCAL source code. It has been tested using
TURBO PASCAL 7.0. You will need AT LEAST version 5.0 to compile this
source code. You may need 7.0.
This is a generic pascal header for all my old pascal programs. Most of
these programs were written before I really got excited enough about 32bit
operating systems. In general this code dates back to 1994. Some of it
is important enough that I still work on it. For the most part though,
it's not the best code and it's probably the worst example of
documentation in all of computer science. oh well, you've been warned.
PGP NOTES
=========
This PGP signed message is provided in the hopes that it will prove useful
and informative. My name is Graham THE Ollis <ollisg@ns.arizona.edu> and my
public PGP key can be found by fingering my university account:
finger ollisg@u.arizona.edu
LEGAL NOTES
===========
You are free to use, modify and distribute this source code provided these
headers remain in tact. If you do make modifications to these programs,
i'd appreciate it if you documented your changes and leave some contact
information so that others can blame you and me, rather than just me.
If you maintain a anonymous ftp site or bbs feel free to archive this
stuff away. If your pressing CDs for commercial purposes again have fun.
It would be nice if you let me know about it though.
HOWEVER- there is no written or implied warranty. If you don't trust this
code then delete it NOW. I will in no way be held responsible for any
losses incurred by your using this software.
CONTACT INFORMATION
===================
You may contact me for just about anything relating to this code through
e-mail. Please put something in the subject line about the program you
are working with. The source file would be best in this case (e.g.
frag.pas, hexed.pas ... etc)
ollisg@ns.arizona.edu
ollisg@idea-bank.com
ollisg@lanl.gov
The first address is the most likely to work.
all right. that all said... HAVE FUN!
-----BEGIN PGP SIGNATURE-----
Version: 2.6.2
iQCVAwUBMv1UFoazF2irQff1AQFYNgQAhjiY/Dh3gSpk921FQznz4FOwqJtAIG6N
QTBdR/yQWrkwHGfPTw9v8LQHbjzl0jjYUDKR9t5KB7vzFjy9q3Y5lVHJaaUAU4Jh
e1abPhL70D/vfQU3Z0R+02zqhjfsfKkeowJvKNdlqEe1/kSCxme9mhJyaJ0CDdIA
40nefR18NrA=
=IQEZ
-----END PGP SIGNATURE-----
==============================================================================
| pcx.pas
| module for viewing pcx files. pcx is a horrible format, but really
| easy to parse. this module is independant of the rest of hexed.
|
| History:
| Date Author Comment
| ---- ------ -------
| -- --- 94 G. Ollis created and developed program
============================================================================*)
{$I-,O+,F+}
Unit PCX;
INTERFACE
Uses Ollis;
{++PROCEDURES++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
{++FUNCTIONS+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
Function DrawPCXMem(Var buff:Pointer; Var p:Pal):String;
{++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
IMPLEMENTATION
Uses Crt;
Type
pcxHeader=Record
Manufacturer, (* should be set to $A0 *)
version, (* version number. We suport 5 only *)
encoding, (* defines compression mode. 1 is the only known *)
bits_per_pixel:Byte; (* # of bits per pixel. should be 8 *)
X1,Y1,X2,Y2, (* defines location an size of image *)
hres,vres:Integer; (* resolution of screen saved on. useless *)
EGAPalette:Array [1..48] of Byte; (*EGA palette. ignore *)
reserved,
color_planes:Byte;
bytes_per_line,
palette_type:Integer;
filler:Array [1..58] of Byte;
End;
{--------------------------------------------------------------------}
Function InBox(x,y,X1,Y1,X2,Y2:Integer):Boolean;
Begin
If (x>=X1) And (x<=X2) And (y>=Y1) And (y<=Y2) Then
InBox:=True
Else
InBox:=False;
End;
{--------------------------------------------------------------------}
Procedure CheckPCXHeader(S:String; Var errstr:String; h:pcxHeader; szc:Boolean);
Begin
errstr:='';
With h Do
Begin
If (manufacturer<>10) Then
errstr:='manufacturer byte != 10 $0A';
If (encoding<>1) Then
errstr:='encoding byte != 1';
If bits_per_pixel<>8 Then
errstr:='is not a 256 color PCX file.';
If szc Then
If Not (InBox(X1,Y1,0,0,MaxX,MaxY)) Or
Not (InBox(X2,Y2,0,0,MaxX,MaxY)) Then
errstr:='does not fit in a '+IntToStr(MaxX+1)+
'x'+IntToStr(MaxY+1)+' res screen';
End;
End;
{--------------------------------------------------------------------}
Type
BytePointer=^Byte;
Procedure IncPtr(Var ofst:BytePointer; Var b:Byte);
Begin
ofst:=@mem[Seg(ofst^):Ofs(ofst^)+1];
b:=ofst^;
End;
{--------------------------------------------------------------------}
Function DrawPCXMem(Var buff:Pointer; Var p:Pal):String;
Var h:^PCXHeader; ofst:BytePointer; b:Byte; x,y:Word; I:Integer;
errstr:String;
Begin
DrawPCXMem:='Unknown error.';
h:=buff;
CheckPCXHeader('MEMORY PCX FILE',errstr,h^,TRUE);
If (errstr<>'') Then
Begin
DrawPCXMem:=errstr;
Exit;
End;
ofst:=@h^.filler[58];
x:=h^.X1; y:=h^.Y1;
Repeat
Repeat
IncPtr(ofst,b);
If (b And $C0)=$C0 Then
Begin
I:=b And $3F;
IncPtr(ofst,b);
For I:=I DownTo 1 Do
Begin
GraphAcc1^[y,x]:=b;
Inc(x);
End;
End
Else
Begin
GraphAcc1^[y,x]:=b;
Inc(x);
End;
Until x>h^.X2;
y:=y+1;
x:=h^.X1;
If KeyPressed Then
Begin
DrawPCXMem:='';
Exit;
End;
Until y>h^.Y2;
IncPtr(ofst,b);
If b=$0C Then
For I:=0 To $FF Do
With p[I] Do
Begin
IncPtr(ofst,b);
Red:=b shr 2;
IncPtr(ofst,b);
Green:=b shr 2;
IncPtr(ofst,b);
Blue:=b shr 2;
End;
DrawPCXMem:='';
End;
{======================================================================}
End. |
unit surfaceview;
{$mode delphi}
interface
uses
Classes, SysUtils, And_jni, AndroidWidget, systryparent;
type
TOnSurfaceViewCreated = procedure(Sender: TObject; surfaceHolder: jObject) of object;
TOnSurfaceViewDraw = procedure(Sender: TObject; canvas: jObject) of object;
TOnSurfaceViewChanged = procedure(Sender: TObject; width: integer; height: integer) of object;
TOnDrawingInBackgroundRunning = procedure(Sender: TObject; progress: single; out running: boolean) of object;
TOnDrawingInBackgroundExecuted = procedure(Sender: TObject; progress: single) of object;
{Draft Component code by "Lazarus Android Module Wizard" [6/3/2015 2:25:12]}
{https://github.com/jmpessoa/lazandroidmodulewizard}
{jVisualControl template}
jSurfaceView = class(jVisualControl)
private
FPaintColor: TARGBColorBridge;
FOnSurfaceCreated: TOnSurfaceViewCreated;
FOnSurfaceDraw: TOnSurfaceViewDraw;
FOnSurfaceChanged: TOnSurfaceViewChanged;
FOnDrawingInBackgroundRunning: TOnDrawingInBackgroundRunning;
FOnDrawingInBackgroundExecuted: TOnDrawingInBackgroundExecuted;
FOnTouchDown : TOnTouchEvent;
FOnTouchMove : TOnTouchEvent;
FOnTouchUp : TOnTouchEvent;
FMouches : TMouches;
procedure SetVisible(Value: Boolean);
procedure SetColor(Value: TARGBColorBridge); //background
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Init; override;
procedure Refresh;
procedure UpdateLayout; override;
//procedure GenEvent_OnClick(Obj: TObject);
function jCreate(): jObject;
procedure jFree();
procedure SetViewParent(_viewgroup: jObject); override;
procedure RemoveFromViewParent(); override;
function GetView(): jObject; override;
procedure SetLParamWidth(_w: integer);
procedure SetLParamHeight(_h: integer);
procedure SetLeftTopRightBottomWidthHeight(_left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer);
procedure AddLParamsAnchorRule(_rule: integer);
procedure AddLParamsParentRule(_rule: integer);
procedure SetLayoutAll(_idAnchor: integer);
procedure ClearLayout();
procedure SetHolderFixedSize(_width: integer; _height: integer);
procedure DrawLine(_canvas: jObject; _x1: single; _y1: single; _x2: single; _y2: single); overload;
procedure DrawPoint(_canvas: jObject; _x1: single; _y1: single);
procedure SetPaintStrokeWidth(_width: single);
procedure SetPaintStyle(_style: TPaintStyle); //TPaintStyle
procedure SetPaintColor( _color: TARGBColorBridge); //
procedure SetPaintTextSize(_textsize: single);
procedure DrawText(_canvas: jObject; _text: string; _x: single; _y: single);
procedure DrawBitmap(_canvas: jObject; _bitmap: jObject; _b: integer; _l: integer; _r: integer; _t: integer); overload;
procedure DispatchOnDraw(_value: boolean);
procedure SaveToFile(_path: string; _fileName: string);
function GetLockedCanvas(): jObject;
procedure UnLockCanvas(_canvas: jObject);
procedure DoDrawingInBackground(_value: boolean);
procedure DrawBitmap(_canvas: jObject; _bitmap: jObject; _left: single; _top: single); overload;
procedure DrawCircle(_canvas: jObject; _cx: single; _cy: single; _radius: single);
procedure DrawBackground(_canvas: jObject; _color: TARGBColorBridge);
procedure DrawRect(_canvas: jObject; _left: single; _top: single; _right: single; _bottom: single);
procedure PostInvalidate();
procedure Invalidate();
procedure SetDrawingInBackgroundSleeptime(_sleepTime: int64);
procedure SetKeepScreenOn(_value: boolean);
procedure SetFocusable(_value: boolean);
procedure SetProgress(_startValue: single; _step: single);
procedure DrawLine(_canvas: jObject; var _points: TDynArrayOfSingle); overload;
function GetDrawingCache(): jObject;
function GetImage(): jObject;
procedure GenEvent_OnSurfaceViewCreated(Obj: TObject; surfaceHolder: jObject);
procedure GenEvent_OnSurfaceViewDraw(Obj: TObject; canvas: jObject);
procedure GenEvent_OnSurfaceViewTouch(Obj: TObject; Act,Cnt: integer; X1,Y1,X2,Y2: Single);
procedure GenEvent_OnSurfaceViewChanged(Obj: TObject; width: integer; height: integer);
procedure GenEvent_OnSurfaceViewDrawingInBackground(Obj: TObject; progress: single; out running: boolean);
procedure GenEvent_OnSurfaceViewDrawingPostExecute(Obj: TObject; progress: single);
published
property BackgroundColor: TARGBColorBridge read FColor write SetColor;
property PaintColor: TARGBColorBridge read FPaintColor write SetPaintColor;
//property OnClick: TOnNotify read FOnClick write FOnClick;
property OnSurfaceCreated: TOnSurfaceViewCreated read FOnSurfaceCreated write FOnSurfaceCreated;
property OnSurfaceDraw: TOnSurfaceViewDraw read FOnSurfaceDraw write FOnSurfaceDraw;
property OnSurfaceChanged: TOnSurfaceViewChanged read FOnSurfaceChanged write FOnSurfaceChanged;
property OnDrawInBackground: TOnDrawingInBackgroundRunning read FOnDrawingInBackgroundRunning write FOnDrawingInBackgroundRunning;
property OnDrawOutBackground: TOnDrawingInBackgroundExecuted read FOnDrawingInBackgroundExecuted write FOnDrawingInBackgroundExecuted;
// Event - Touch
property OnTouchDown : TOnTouchEvent read FOnTouchDown write FOnTouchDown;
property OnTouchMove : TOnTouchEvent read FOnTouchMove write FOnTouchMove;
property OnTouchUp : TOnTouchEvent read FOnTouchUp write FOnTouchUp;
end;
function jSurfaceView_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject;
procedure jSurfaceView_jFree(env: PJNIEnv; _jsurfaceview: JObject);
procedure jSurfaceView_SetViewParent(env: PJNIEnv; _jsurfaceview: JObject; _viewgroup: jObject);
procedure jSurfaceView_RemoveFromViewParent(env: PJNIEnv; _jsurfaceview: JObject);
function jSurfaceView_GetView(env: PJNIEnv; _jsurfaceview: JObject): jObject;
procedure jSurfaceView_SetLParamWidth(env: PJNIEnv; _jsurfaceview: JObject; _w: integer);
procedure jSurfaceView_SetLParamHeight(env: PJNIEnv; _jsurfaceview: JObject; _h: integer);
procedure jSurfaceView_SetLeftTopRightBottomWidthHeight(env: PJNIEnv; _jsurfaceview: JObject; _left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer);
procedure jSurfaceView_AddLParamsAnchorRule(env: PJNIEnv; _jsurfaceview: JObject; _rule: integer);
procedure jSurfaceView_AddLParamsParentRule(env: PJNIEnv; _jsurfaceview: JObject; _rule: integer);
procedure jSurfaceView_SetLayoutAll(env: PJNIEnv; _jsurfaceview: JObject; _idAnchor: integer);
procedure jSurfaceView_ClearLayoutAll(env: PJNIEnv; _jsurfaceview: JObject);
procedure jSurfaceView_SetId(env: PJNIEnv; _jsurfaceview: JObject; _id: integer);
procedure jSurfaceView_SetHolderFixedSize(env: PJNIEnv; _jsurfaceview: JObject; _width: integer; _height: integer);
procedure jSurfaceView_DrawLine(env: PJNIEnv; _jsurfaceview: JObject; _canvas: jObject; _x1: single; _y1: single; _x2: single; _y2: single); overload;
procedure jSurfaceView_DrawPoint(env: PJNIEnv; _jsurfaceview: JObject; _canvas: jObject; _x1: single; _y1: single);
procedure jSurfaceView_SetPaintStrokeWidth(env: PJNIEnv; _jsurfaceview: JObject; _width: single);
procedure jSurfaceView_SetPaintStyle(env: PJNIEnv; _jsurfaceview: JObject; _style: integer);
procedure jSurfaceView_SetPaintColor(env: PJNIEnv; _jsurfaceview: JObject; _color: integer);
procedure jSurfaceView_SetPaintTextSize(env: PJNIEnv; _jsurfaceview: JObject; _textsize: single);
procedure jSurfaceView_DrawText(env: PJNIEnv; _jsurfaceview: JObject; _canvas: jObject; _text: string; _x: single; _y: single);
procedure jSurfaceView_DrawBitmap(env: PJNIEnv; _jsurfaceview: JObject; _canvas: jObject; _bitmap: jObject; _b: integer; _l: integer; _r: integer; _t: integer); overload;
procedure jSurfaceView_DispatchOnDraw(env: PJNIEnv; _jsurfaceview: JObject; _value: boolean);
procedure jSurfaceView_SaveToFile(env: PJNIEnv; _jsurfaceview: JObject; _path: string; _fileName: string);
function jSurfaceView_GetLockedCanvas(env: PJNIEnv; _jsurfaceview: JObject): jObject;
procedure jSurfaceView_UnLockCanvas(env: PJNIEnv; _jsurfaceview: JObject; _canvas: jObject);
procedure jSurfaceView_DoDrawingInBackground(env: PJNIEnv; _jsurfaceview: JObject; _value: boolean);
procedure jSurfaceView_DrawBitmap(env: PJNIEnv; _jsurfaceview: JObject; _canvas: jObject; _bitmap: jObject; _left: single; _top: single); overload;
procedure jSurfaceView_DrawCircle(env: PJNIEnv; _jsurfaceview: JObject; _canvas: jObject; _cx: single; _cy: single; _radius: single);
procedure jSurfaceView_DrawBackground(env: PJNIEnv; _jsurfaceview: JObject; _canvas: jObject; _color: integer);
procedure jSurfaceView_DrawRect(env: PJNIEnv; _jsurfaceview: JObject; _canvas: jObject; _left: single; _top: single; _right: single; _bottom: single);
procedure jSurfaceView_PostInvalidate(env: PJNIEnv; _jsurfaceview: JObject);
procedure jSurfaceView_Invalidate(env: PJNIEnv; _jsurfaceview: JObject);
procedure jSurfaceView_SetDrawingInBackgroundSleeptime(env: PJNIEnv; _jsurfaceview: JObject; _sleepTime: int64);
procedure jSurfaceView_SetKeepScreenOn(env: PJNIEnv; _jsurfaceview: JObject; _value: boolean);
procedure jSurfaceView_SetFocusable(env: PJNIEnv; _jsurfaceview: JObject; _value: boolean);
procedure jSurfaceView_SetProgress(env: PJNIEnv; _jsurfaceview: JObject; _startValue: single; _step: single);
procedure jSurfaceView_DrawLine(env: PJNIEnv; _jsurfaceview: JObject; _canvas: jObject; var _points: TDynArrayOfSingle); overload;
function jSurfaceView_GetDrawingCache(env: PJNIEnv; _jsurfaceview: JObject): jObject;
implementation
{--------- jSurfaceView --------------}
constructor jSurfaceView.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
if gapp <> nil then FId := gapp.GetNewId();
FMarginLeft := 10;
FMarginTop := 10;
FMarginBottom := 10;
FMarginRight := 10;
FHeight := 96; //??
FWidth := 96; //??
FLParamWidth := lpMatchParent; //lpWrapContent
FLParamHeight := lpWrapContent; //lpMatchParent
FAcceptChildrenAtDesignTime:= False;
//your code here....
FPaintColor:= colbrRed;
FMouches.Mouch.Active := False;
FMouches.Mouch.Start := False;
FMouches.Mouch.Zoom := 1.0;
FMouches.Mouch.Angle := 0.0;
end;
destructor jSurfaceView.Destroy;
begin
if not (csDesigning in ComponentState) then
begin
if FjObject <> nil then
begin
jFree();
FjObject:= nil;
end;
end;
//you others free code here...'
inherited Destroy;
end;
procedure jSurfaceView.Init;
var
rToP: TPositionRelativeToParent;
rToA: TPositionRelativeToAnchorID;
begin
if not FInitialized then
begin
inherited Init; //set default ViewParent/FjPRLayout as jForm.View!
//your code here: set/initialize create params....
FjObject := jCreate(); if FjObject = nil then exit;
if FParent <> nil then
sysTryNewParent( FjPRLayout, FParent);
FjPRLayoutHome:= FjPRLayout;
jSurfaceView_SetViewParent(gApp.jni.jEnv, FjObject, FjPRLayout);
jSurfaceView_SetId(gApp.jni.jEnv, FjObject, Self.Id);
end;
jSurfaceView_setLeftTopRightBottomWidthHeight(gApp.jni.jEnv, FjObject ,
FMarginLeft,FMarginTop,FMarginRight,FMarginBottom,
sysGetLayoutParams( FWidth, FLParamWidth, Self.Parent, sdW, fmarginLeft + fmarginRight ),
sysGetLayoutParams( FHeight, FLParamHeight, Self.Parent, sdH, fMargintop + fMarginbottom ));
for rToA := raAbove to raAlignRight do
begin
if rToA in FPositionRelativeToAnchor then
begin
jSurfaceView_AddLParamsAnchorRule(gApp.jni.jEnv, FjObject, GetPositionRelativeToAnchor(rToA));
end;
end;
for rToP := rpBottom to rpCenterVertical do
begin
if rToP in FPositionRelativeToParent then
begin
jSurfaceView_AddLParamsParentRule(gApp.jni.jEnv, FjObject, GetPositionRelativeToParent(rToP));
end;
end;
if Self.Anchor <> nil then Self.AnchorId:= Self.Anchor.Id
else Self.AnchorId:= -1; //dummy
jSurfaceView_SetLayoutAll(gApp.jni.jEnv, FjObject, Self.AnchorId);
if not FInitialized then
begin
FInitialized:= True;
if FColor <> colbrDefault then
View_SetBackGroundColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FColor));
if FPaintColor <> colbrDefault then
jSurfaceView_SetPaintColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FPaintColor));
View_SetVisible(gApp.jni.jEnv, FjObject, FVisible);
end;
end;
procedure jSurfaceView.SetColor(Value: TARGBColorBridge);
begin
FColor:= Value;
if (FInitialized = True) and (FColor <> colbrDefault) then
View_SetBackGroundColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FColor));
end;
procedure jSurfaceView.SetVisible(Value : Boolean);
begin
FVisible:= Value;
if FInitialized then
View_SetVisible(gApp.jni.jEnv, FjObject, FVisible);
end;
procedure jSurfaceView.UpdateLayout;
begin
if not FInitialized then exit;
ClearLayout();
inherited UpdateLayout;
init;
end;
procedure jSurfaceView.Refresh;
begin
if FInitialized then
View_Invalidate(gApp.jni.jEnv, FjObject);
end;
//Event : Java -> Pascal
(*
procedure jSurfaceView.GenEvent_OnClick(Obj: TObject);
begin
if Assigned(FOnClick) then FOnClick(Obj);
end;
*)
function jSurfaceView.jCreate(): jObject;
begin
Result:= jSurfaceView_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis);
end;
procedure jSurfaceView.jFree();
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_jFree(gApp.jni.jEnv, FjObject);
end;
procedure jSurfaceView.SetViewParent(_viewgroup: jObject);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_SetViewParent(gApp.jni.jEnv, FjObject, _viewgroup);
end;
procedure jSurfaceView.RemoveFromViewParent();
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_RemoveFromViewParent(gApp.jni.jEnv, FjObject);
end;
function jSurfaceView.GetView(): jObject;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jSurfaceView_GetView(gApp.jni.jEnv, FjObject);
end;
procedure jSurfaceView.SetLParamWidth(_w: integer);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_SetLParamWidth(gApp.jni.jEnv, FjObject, _w);
end;
procedure jSurfaceView.SetLParamHeight(_h: integer);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_SetLParamHeight(gApp.jni.jEnv, FjObject, _h);
end;
procedure jSurfaceView.SetLeftTopRightBottomWidthHeight(_left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_SetLeftTopRightBottomWidthHeight(gApp.jni.jEnv, FjObject, _left ,_top ,_right ,_bottom ,_w ,_h);
end;
procedure jSurfaceView.AddLParamsAnchorRule(_rule: integer);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_AddLParamsAnchorRule(gApp.jni.jEnv, FjObject, _rule);
end;
procedure jSurfaceView.AddLParamsParentRule(_rule: integer);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_AddLParamsParentRule(gApp.jni.jEnv, FjObject, _rule);
end;
procedure jSurfaceView.SetLayoutAll(_idAnchor: integer);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_SetLayoutAll(gApp.jni.jEnv, FjObject, _idAnchor);
end;
procedure jSurfaceView.ClearLayout();
var
rToP: TPositionRelativeToParent;
rToA: TPositionRelativeToAnchorID;
begin
//in designing component state: set value here...
if FInitialized then
begin
jSurfaceView_clearLayoutAll(gApp.jni.jEnv, FjObject);
for rToP := rpBottom to rpCenterVertical do
if rToP in FPositionRelativeToParent then
jSurfaceView_addlParamsParentRule(gApp.jni.jEnv, FjObject , GetPositionRelativeToParent(rToP));
for rToA := raAbove to raAlignRight do
if rToA in FPositionRelativeToAnchor then
jSurfaceView_addlParamsAnchorRule(gApp.jni.jEnv, FjObject , GetPositionRelativeToAnchor(rToA));
end;
end;
procedure jSurfaceView.SetHolderFixedSize(_width: integer; _height: integer);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_SetHolderFixedSize(gApp.jni.jEnv, FjObject, _width ,_height);
end;
procedure jSurfaceView.DrawLine(_canvas: jObject; _x1: single; _y1: single; _x2: single; _y2: single);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_DrawLine(gApp.jni.jEnv, FjObject, _canvas ,_x1 ,_y1 ,_x2 ,_y2);
end;
procedure jSurfaceView.DrawPoint(_canvas: jObject; _x1: single; _y1: single);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_DrawPoint(gApp.jni.jEnv, FjObject, _canvas ,_x1 ,_y1);
end;
procedure jSurfaceView.SetPaintStrokeWidth(_width: single);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_SetPaintStrokeWidth(gApp.jni.jEnv, FjObject, _width);
end;
procedure jSurfaceView.SetPaintStyle(_style: TPaintStyle);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_SetPaintStyle(gApp.jni.jEnv, FjObject, Ord(_style));
end;
procedure jSurfaceView.SetPaintColor(_color: TARGBColorBridge);
begin
//in designing component state: set value here...
FPaintColor:= _color;
if FInitialized then
jSurfaceView_SetPaintColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, _color));
end;
procedure jSurfaceView.SetPaintTextSize(_textsize: single);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_SetPaintTextSize(gApp.jni.jEnv, FjObject, _textsize);
end;
procedure jSurfaceView.DrawText(_canvas: jObject; _text: string; _x: single; _y: single);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_DrawText(gApp.jni.jEnv, FjObject, _canvas ,_text ,_x ,_y);
end;
procedure jSurfaceView.DrawBitmap(_canvas: jObject; _bitmap: jObject; _b: integer; _l: integer; _r: integer; _t: integer);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_DrawBitmap(gApp.jni.jEnv, FjObject, _canvas ,_bitmap ,_b ,_l ,_r ,_t);
end;
procedure jSurfaceView.DispatchOnDraw(_value: boolean);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_DispatchOnDraw(gApp.jni.jEnv, FjObject, _value);
end;
procedure jSurfaceView.SaveToFile(_path: string; _fileName: string);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_SaveToFile(gApp.jni.jEnv, FjObject, _path, _fileName);
end;
procedure jSurfaceView.GenEvent_OnSurfaceViewCreated(Obj: TObject; surfaceHolder: jObject);
begin
if Assigned(FOnSurfaceCreated) then FOnSurfaceCreated(Obj, surfaceHolder);
end;
procedure jSurfaceView.GenEvent_OnSurfaceViewDraw(Obj: TObject; canvas: jObject);
begin
if Assigned(FOnSurfaceDraw) then FOnSurfaceDraw(Obj, canvas);
end;
Procedure jSurfaceView.GenEvent_OnSurfaceViewTouch(Obj: TObject; Act,Cnt: integer; X1,Y1,X2,Y2: Single);
begin
case Act of
cTouchDown : VHandler_touchesBegan_withEvent(Obj,Cnt,fXY(X1,Y1),fXY(X2,Y2),FOnTouchDown,FMouches);
cTouchMove : VHandler_touchesMoved_withEvent(Obj,Cnt,fXY(X1,Y1),fXY(X2,Y2),FOnTouchMove,FMouches);
cTouchUp : VHandler_touchesEnded_withEvent(Obj,Cnt,fXY(X1,Y1),fXY(X2,Y2),FOnTouchUp ,FMouches);
end;
end;
procedure jSurfaceView.GenEvent_OnSurfaceViewChanged(Obj: TObject; width: integer; height: integer);
begin
if Assigned(FOnSurfaceChanged) then FOnSurfaceChanged(Obj, width, height);
end;
procedure jSurfaceView.GenEvent_OnSurfaceViewDrawingInBackground(Obj: TObject; progress: single; out running: boolean);
begin
running:= True;
if Assigned(FOnDrawingInBackgroundRunning) then FOnDrawingInBackgroundRunning(Obj, progress, running);
end;
procedure jSurfaceView.GenEvent_OnSurfaceViewDrawingPostExecute(Obj: TObject; progress: single);
begin
if Assigned(FOnDrawingInBackgroundExecuted) then FOnDrawingInBackgroundExecuted(Obj, progress);
end;
function jSurfaceView.GetLockedCanvas(): jObject;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jSurfaceView_GetLockedCanvas(gApp.jni.jEnv, FjObject);
end;
procedure jSurfaceView.UnLockCanvas(_canvas: jObject);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_UnLockCanvas(gApp.jni.jEnv, FjObject, _canvas);
end;
procedure jSurfaceView.DoDrawingInBackground(_value: boolean);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_DoDrawingInBackground(gApp.jni.jEnv, FjObject, _value);
end;
procedure jSurfaceView.DrawBitmap(_canvas: jObject; _bitmap: jObject; _left: single; _top: single);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_DrawBitmap(gApp.jni.jEnv, FjObject, _canvas ,_bitmap ,_left ,_top);
end;
procedure jSurfaceView.DrawCircle(_canvas: jObject; _cx: single; _cy: single; _radius: single);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_DrawCircle(gApp.jni.jEnv, FjObject, _canvas ,_cx ,_cy ,_radius);
end;
procedure jSurfaceView.DrawBackground(_canvas: jObject; _color: TARGBColorBridge);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_DrawBackground(gApp.jni.jEnv, FjObject, _canvas , GetARGB(FCustomColor, _color));
end;
procedure jSurfaceView.DrawRect(_canvas: jObject; _left: single; _top: single; _right: single; _bottom: single);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_DrawRect(gApp.jni.jEnv, FjObject, _canvas ,_left ,_top ,_right ,_bottom);
end;
procedure jSurfaceView.PostInvalidate();
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_PostInvalidate(gApp.jni.jEnv, FjObject);
end;
procedure jSurfaceView.Invalidate();
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_Invalidate(gApp.jni.jEnv, FjObject);
end;
procedure jSurfaceView.SetDrawingInBackgroundSleeptime(_sleepTime: int64);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_SetDrawingInBackgroundSleeptime(gApp.jni.jEnv, FjObject, _sleepTime);
end;
procedure jSurfaceView.SetKeepScreenOn(_value: boolean);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_SetKeepScreenOn(gApp.jni.jEnv, FjObject, _value);
end;
procedure jSurfaceView.SetFocusable(_value: boolean);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_SetFocusable(gApp.jni.jEnv, FjObject, _value);
end;
procedure jSurfaceView.SetProgress(_startValue: single; _step: single);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_SetProgress(gApp.jni.jEnv, FjObject, _startValue ,_step);
end;
procedure jSurfaceView.DrawLine(_canvas: jObject; var _points: TDynArrayOfSingle);
begin
//in designing component state: set value here...
if FInitialized then
jSurfaceView_DrawLine(gApp.jni.jEnv, FjObject, _canvas ,_points);
end;
function jSurfaceView.GetDrawingCache(): jObject;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jSurfaceView_GetDrawingCache(gApp.jni.jEnv, FjObject);
end;
function jSurfaceView.GetImage(): jObject;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jSurfaceView_GetDrawingCache(gApp.jni.jEnv, FjObject);
end;
{-------- jSurfaceView_JNI_Bridge ----------}
function jSurfaceView_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject;
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].j:= _Self;
jCls:= Get_gjClass(env);
jMethod:= env^.GetMethodID(env, jCls, 'jSurfaceView_jCreate', '(J)Ljava/lang/Object;');
Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams);
Result:= env^.NewGlobalRef(env, Result);
end;
(*
//Please, you need insert:
public java.lang.Object jSurfaceView_jCreate(long _Self) {
return (java.lang.Object)(new jSurfaceView(this,_Self));
}
//to end of "public class Controls" in "Controls.java"
*)
procedure jSurfaceView_jFree(env: PJNIEnv; _jsurfaceview: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'jFree', '()V');
env^.CallVoidMethod(env, _jsurfaceview, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_SetViewParent(env: PJNIEnv; _jsurfaceview: JObject; _viewgroup: jObject);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= _viewgroup;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'SetViewParent', '(Landroid/view/ViewGroup;)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_RemoveFromViewParent(env: PJNIEnv; _jsurfaceview: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'RemoveFromViewParent', '()V');
env^.CallVoidMethod(env, _jsurfaceview, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
function jSurfaceView_GetView(env: PJNIEnv; _jsurfaceview: JObject): jObject;
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'GetView', '()Landroid/view/View;');
Result:= env^.CallObjectMethod(env, _jsurfaceview, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_SetLParamWidth(env: PJNIEnv; _jsurfaceview: JObject; _w: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _w;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'SetLParamWidth', '(I)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_SetLParamHeight(env: PJNIEnv; _jsurfaceview: JObject; _h: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _h;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'SetLParamHeight', '(I)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_SetLeftTopRightBottomWidthHeight(env: PJNIEnv; _jsurfaceview: JObject; _left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer);
var
jParams: array[0..5] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _left;
jParams[1].i:= _top;
jParams[2].i:= _right;
jParams[3].i:= _bottom;
jParams[4].i:= _w;
jParams[5].i:= _h;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'SetLeftTopRightBottomWidthHeight', '(IIIIII)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_AddLParamsAnchorRule(env: PJNIEnv; _jsurfaceview: JObject; _rule: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _rule;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'AddLParamsAnchorRule', '(I)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_AddLParamsParentRule(env: PJNIEnv; _jsurfaceview: JObject; _rule: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _rule;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'AddLParamsParentRule', '(I)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_SetLayoutAll(env: PJNIEnv; _jsurfaceview: JObject; _idAnchor: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _idAnchor;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'SetLayoutAll', '(I)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_ClearLayoutAll(env: PJNIEnv; _jsurfaceview: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'ClearLayoutAll', '()V');
env^.CallVoidMethod(env, _jsurfaceview, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_SetId(env: PJNIEnv; _jsurfaceview: JObject; _id: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _id;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'setId', '(I)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_SetHolderFixedSize(env: PJNIEnv; _jsurfaceview: JObject; _width: integer; _height: integer);
var
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _width;
jParams[1].i:= _height;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'SetHolderFixedSize', '(II)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_DrawLine(env: PJNIEnv; _jsurfaceview: JObject; _canvas: jObject; _x1: single; _y1: single; _x2: single; _y2: single);
var
jParams: array[0..4] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= _canvas;
jParams[1].f:= _x1;
jParams[2].f:= _y1;
jParams[3].f:= _x2;
jParams[4].f:= _y2;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'DrawLine', '(Landroid/graphics/Canvas;FFFF)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_DrawPoint(env: PJNIEnv; _jsurfaceview: JObject; _canvas: jObject; _x1: single; _y1: single);
var
jParams: array[0..2] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= _canvas;
jParams[1].f:= _x1;
jParams[2].f:= _y1;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'DrawPoint', '(Landroid/graphics/Canvas;FF)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_SetPaintStrokeWidth(env: PJNIEnv; _jsurfaceview: JObject; _width: single);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].f:= _width;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'SetPaintStrokeWidth', '(F)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_SetPaintStyle(env: PJNIEnv; _jsurfaceview: JObject; _style: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _style;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'SetPaintStyle', '(I)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_SetPaintColor(env: PJNIEnv; _jsurfaceview: JObject; _color: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _color;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'SetPaintColor', '(I)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_SetPaintTextSize(env: PJNIEnv; _jsurfaceview: JObject; _textsize: single);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].f:= _textsize;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'SetPaintTextSize', '(F)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_DrawText(env: PJNIEnv; _jsurfaceview: JObject; _canvas: jObject; _text: string; _x: single; _y: single);
var
jParams: array[0..3] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= _canvas;
jParams[1].l:= env^.NewStringUTF(env, PChar(_text));
jParams[2].f:= _x;
jParams[3].f:= _y;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'DrawText', '(Landroid/graphics/Canvas;Ljava/lang/String;FF)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[1].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_DrawBitmap(env: PJNIEnv; _jsurfaceview: JObject; _canvas: jObject; _bitmap: jObject; _b: integer; _l: integer; _r: integer; _t: integer);
var
jParams: array[0..5] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= _canvas;
jParams[1].l:= _bitmap;
jParams[2].i:= _b;
jParams[3].i:= _l;
jParams[4].i:= _r;
jParams[5].i:= _t;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'DrawBitmap', '(Landroid/graphics/Canvas;Landroid/graphics/Bitmap;IIII)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_DispatchOnDraw(env: PJNIEnv; _jsurfaceview: JObject; _value: boolean);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].z:= JBool(_value);
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'DispatchOnDraw', '(Z)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_SaveToFile(env: PJNIEnv; _jsurfaceview: JObject; _path: string; _fileName: string);
var
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_path));
jParams[1].l:= env^.NewStringUTF(env, PChar(_fileName));
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'SaveToFile', '(Ljava/lang/String;Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env,jParams[1].l);
env^.DeleteLocalRef(env, jCls);
end;
function jSurfaceView_GetLockedCanvas(env: PJNIEnv; _jsurfaceview: JObject): jObject;
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'GetLockedCanvas', '()Landroid/graphics/Canvas;');
Result:= env^.CallObjectMethod(env, _jsurfaceview, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_UnLockCanvas(env: PJNIEnv; _jsurfaceview: JObject; _canvas: jObject);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= _canvas;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'UnLockCanvas', '(Landroid/graphics/Canvas;)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_DoDrawingInBackground(env: PJNIEnv; _jsurfaceview: JObject; _value: boolean);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].z:= JBool(_value);
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'DoDrawingInBackground', '(Z)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_DrawBitmap(env: PJNIEnv; _jsurfaceview: JObject; _canvas: jObject; _bitmap: jObject; _left: single; _top: single);
var
jParams: array[0..3] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= _canvas;
jParams[1].l:= _bitmap;
jParams[2].f:= _left;
jParams[3].f:= _top;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'DrawBitmap', '(Landroid/graphics/Canvas;Landroid/graphics/Bitmap;FF)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_DrawCircle(env: PJNIEnv; _jsurfaceview: JObject; _canvas: jObject; _cx: single; _cy: single; _radius: single);
var
jParams: array[0..3] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= _canvas;
jParams[1].f:= _cx;
jParams[2].f:= _cy;
jParams[3].f:= _radius;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'DrawCircle', '(Landroid/graphics/Canvas;FFF)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_DrawBackground(env: PJNIEnv; _jsurfaceview: JObject; _canvas: jObject; _color: integer);
var
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= _canvas;
jParams[1].i:= _color;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'DrawBackground', '(Landroid/graphics/Canvas;I)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_DrawRect(env: PJNIEnv; _jsurfaceview: JObject; _canvas: jObject; _left: single; _top: single; _right: single; _bottom: single);
var
jParams: array[0..4] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= _canvas;
jParams[1].f:= _left;
jParams[2].f:= _top;
jParams[3].f:= _right;
jParams[4].f:= _bottom;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'DrawRect', '(Landroid/graphics/Canvas;FFFF)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_PostInvalidate(env: PJNIEnv; _jsurfaceview: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'PostInvalidate', '()V');
env^.CallVoidMethod(env, _jsurfaceview, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_Invalidate(env: PJNIEnv; _jsurfaceview: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'Invalidate', '()V');
env^.CallVoidMethod(env, _jsurfaceview, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_SetDrawingInBackgroundSleeptime(env: PJNIEnv; _jsurfaceview: JObject; _sleepTime: int64);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].j:= _sleepTime;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'SetDrawingInBackgroundSleeptime', '(J)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_SetKeepScreenOn(env: PJNIEnv; _jsurfaceview: JObject; _value: boolean);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].z:= JBool(_value);
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'SetKeepScreenOn', '(Z)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_SetFocusable(env: PJNIEnv; _jsurfaceview: JObject; _value: boolean);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].z:= JBool(_value);
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'SetFocusable', '(Z)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_SetProgress(env: PJNIEnv; _jsurfaceview: JObject; _startValue: single; _step: single);
var
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].f:= _startValue;
jParams[1].f:= _step;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'SetProgress', '(FF)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jSurfaceView_DrawLine(env: PJNIEnv; _jsurfaceview: JObject; _canvas: jObject; var _points: TDynArrayOfSingle);
var
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
newSize0: integer;
jNewArray0: jObject=nil;
begin
jParams[0].l:= _canvas;
newSize0:= Length(_points);
jNewArray0:= env^.NewFloatArray(env, newSize0); // allocate
env^.SetFloatArrayRegion(env, jNewArray0, 0 , newSize0, @_points[0] {source});
jParams[1].l:= jNewArray0;
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'DrawLine', '(Landroid/graphics/Canvas;[F)V');
env^.CallVoidMethodA(env, _jsurfaceview, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[1].l);
env^.DeleteLocalRef(env, jCls);
end;
function jSurfaceView_GetDrawingCache(env: PJNIEnv; _jsurfaceview: JObject): jObject;
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jsurfaceview);
jMethod:= env^.GetMethodID(env, jCls, 'GetDrawingCache', '()Landroid/graphics/Bitmap;');
Result:= env^.CallObjectMethod(env, _jsurfaceview, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
end.
|
{$optimize 7}
{---------------------------------------------------------------}
{ }
{ Table }
{ }
{ Initialized arrays and records. }
{ }
{---------------------------------------------------------------}
unit Table;
{$LibPrefix '0/obj/'}
interface
uses CCommon;
var
{from scanner.pas}
{----------------}
charKinds: array[minChar..maxChar] of charEnum; {character kinds}
charSym: array[minChar..maxChar] of tokenEnum; {symbols for single char symbols}
reservedWords: array[_Alignassy..whilesy] of string[14]; {reserved word strings}
wordHash: array[0..25] of tokenEnum; {for hashing reserved words}
{from ASM.PAS}
{------------}
{names of the opcodes}
names: array[opcode] of packed array[1..3] of char;
{binary values for the opcodes}
iOpcodes: array[o_clc..o_xce] of byte;
rOpcodes: array[o_bcc..o_bvs] of byte;
nOpcodes: array[o_adc..o_tsb,operands] of byte;
{from EXPRESSION.PAS}
{-------------------}
icp: array[tokenEnum] of byte; {in-coming priorities}
isp: array[tokenEnum] of byte; {in-stack priorities}
{from Charset.pas}
{----------------}
macRomanToUCS: array[$80..$FF] of integer; {mapping from MacRoman charset to UCS}
implementation
end.
|
unit Principal;
interface
Uses System.Classes;
procedure register;
type
TNotifyEvent = procedure (Sender : TObject) of Object;
TEventos = class(TComponent)
private
FNome: String;
FStatus: TNotifyEvent;
procedure SetNome(const Value: String);
procedure SetStatus(const Value: TNotifyEvent);
public
Function TamanhoString(Value : String): Integer;
procedure OnStatus;
published
property Nome : String read FNome write SetNome;
property Status : TNotifyEvent read FStatus write SetStatus;
end;
implementation
{ TEventos }
procedure register;
begin
RegisterComponents('DelphiUpdate', [TEventos]);
end;
procedure TEventos.OnStatus;
begin
if Assigned(Status) then
Status(Self);
end;
procedure TEventos.SetNome(const Value: String);
begin
FNome := Value;
end;
procedure TEventos.SetStatus(const Value: TNotifyEvent);
begin
FStatus := Value;
end;
function TEventos.TamanhoString(Value: String): Integer;
begin
Nome := Value;
Result := Length(Value);
OnStatus;
end;
end.
|
unit TripServiceImpl;
interface
uses
System.Generics.Defaults,
TripServiceInterface,
System.Generics.Collections,
uDrone,
uDelivery,
uSent;
type
TTripService = class(TInterfacedObject, ITripService)
private
FEvent: TEventMsg;
procedure orderDelivery(ADelivery: TObjectList<TDelivery>);
procedure OrderDrone(ADrone: TObjectList<TDrone>);
procedure delivery(const ADrone: TObjectList<TDrone>;
const ADelivery: TObjectList<TDelivery>; ASent: TObjectList<TSent>;
ATrip: Integer);
procedure printDelivery(LSent: System.Generics.Collections.TObjectList<TSent>);
function isExistsDelivery(const ADelivery: TObjectList<TDelivery>): Boolean;
function isPossibleDelivery(const ADrone: TObjectList<TDrone>;
const ADelivery: TObjectList<TDelivery>): Boolean;
procedure printDeliveryNoSent(ADelivery: TObjectList<TDelivery>);
public
function GetEvent: TEventMsg;
procedure SetEvent(const Value: TEventMsg);
function Trip(const ADrone: TObjectList<TDrone>;
const ADelivery: TObjectList<TDelivery>): ITripService;
class function New: ITripService;
constructor Create;
destructor Destroy; override;
end;
implementation
uses
System.Math,
System.SysUtils;
{ TTripService }
constructor TTripService.Create;
begin
end;
destructor TTripService.Destroy;
begin
inherited;
end;
procedure TTripService.printDeliveryNoSent(ADelivery: TObjectList<TDelivery>);
var
LDelivery: TDelivery;
begin
for LDelivery in ADelivery do
begin
if not LDelivery.Sent then
FEvent(Format('Undeliverable package(s)-> %s', [LDelivery.Location] ));
end;
end;
procedure TTripService.printDelivery(LSent: TObjectList<TSent>);
var
LDroneName: string;
LTrip: Integer;
LValue: TSent;
begin
LDroneName := EmptyStr;
LTrip := 0;
for LValue in LSent do
begin
if not SameText(LDroneName, LValue.Drone.Name) then
begin
LDroneName := LValue.Drone.Name;
FEvent(Format('[Drone # %s]', [LDroneName]));
end;
if LTrip <> LValue.Trip then
begin
LTrip := LValue.Trip;
FEvent(Format('Trip # %d', [LTrip]));
end;
if Assigned(FEvent) then
begin
FEvent(Format('[Location # %s]', [LValue.Delivery.Location]));
end;
end;
end;
function TTripService.GetEvent: TEventMsg;
begin
Result := FEvent;
end;
class function TTripService.New: ITripService;
begin
Result := Self.Create;
end;
procedure TTripService.orderDelivery(ADelivery: TObjectList<TDelivery>);
begin
ADelivery.Sort(TComparer<TDelivery>.Construct(
function(const A, B: TDelivery) : Integer
begin
Result := CompareValue(A.PackageWeight, B.PackageWeight);
end
));
end;
procedure TTripService.OrderDrone(ADrone: TObjectList<TDrone>);
begin
ADrone.Sort(TComparer<TDrone>.Construct(
function (const A, B: TDrone): Integer
begin
Result := CompareValue(B.MaximumWeight, A.MaximumWeight);
end
));
end;
procedure TTripService.SetEvent(const Value: TEventMsg);
begin
FEvent := Value;
end;
function TTripService.isExistsDelivery(
const ADelivery: TObjectList<TDelivery>): Boolean;
var
LDelivery: TDelivery;
begin
Result := False;
for LDelivery in ADelivery do
if not LDelivery.Sent then Exit(True);
end;
function TTripService.isPossibleDelivery(const ADrone: TObjectList<TDrone>;
const ADelivery: TObjectList<TDelivery>): Boolean;
var
LDrone: TDrone;
LDelivery: TDelivery;
begin
Result := False;
for LDrone in ADrone do
begin
for LDelivery in ADelivery do
begin
if not LDelivery.Sent then
begin
if LDrone.MaximumWeight >= LDelivery.PackageWeight then
Exit(True);
end;
end;
end;
end;
procedure TTripService.delivery(const ADrone: TObjectList<TDrone>;
const ADelivery: TObjectList<TDelivery>; ASent: TObjectList<TSent>;
ATrip: Integer);
var
LDrone: TDrone;
LWeight: Double;
LDelivery: TDelivery;
begin
for LDrone in ADrone do
begin
LWeight := 0;
for LDelivery in ADelivery do
begin
if not LDelivery.Sent then
begin
LWeight := LWeight + LDelivery.PackageWeight;
if LDrone.MaximumWeight >= LWeight then
begin
ASent.Add(TSent.Create(LDrone, LDelivery, ATrip));
LDelivery.Sent := True;
end else
Break;
end;
end;
Inc(ATrip);
end;
if isExistsDelivery(ADelivery) and isPossibleDelivery(ADrone, ADelivery) then
delivery(ADrone, ADelivery, ASent, ATrip)
else
Exit;
end;
function TTripService.Trip(const ADrone: TObjectList<TDrone>;
const ADelivery: TObjectList<TDelivery>): ITripService;
var
LSent: TObjectList<TSent>;
begin
Result := Self;
LSent := TObjectList<TSent>.Create;
try
orderDelivery(ADelivery);
OrderDrone(ADrone);
delivery(ADrone, ADelivery, LSent, 1);
if LSent.Count = 0 then
raise Exception.Create('No deliveries');
if not Assigned(FEvent) then Exit;
printDelivery(LSent);
printDeliveryNoSent(ADelivery);
finally
LSent.Free;
end;
end;
end.
|
unit BancoOperacion;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxGraphics, Menus, cxLookAndFeelPainters, cxStyles,
cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, ADODB,
dxLayoutControl, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGrid,
StdCtrls, cxButtons, cxTextEdit, cxContainer, cxMaskEdit, cxDropDownEdit,
DialogCobro, CustomModule, ppComm, ppRelatv, ppDB, ppDBPipe, DBActns, cxMemo,
cxCheckBox, cxDBEdit, cxCalendar, StdActns, ActnList, JvComponentBase,
JvFormPlacement, ExtCtrls, JvExControls, JvComponent, JvEnterTab;
type
TfrmBancoOperacion = class(Tform)
dxLayoutControl1: TdxLayoutControl;
dxLayoutGroup3: TdxLayoutGroup;
dsDatos: TDataSource;
dxLayoutControl1Group2: TdxLayoutGroup;
dsPaciente: TDataSource;
dsDonacion: TDataSource;
dsDonante: TDataSource;
qrPaciente: TADOQuery;
qrDonacion: TADOQuery;
qrDonante: TADOQuery;
qrDonantePacienteID: TStringField;
qrDonanteTipoDonante: TWideStringField;
qrDonanteEstado: TWideStringField;
qrDonanteRechaso: TWideStringField;
qrDonanteRechasoNota: TWideStringField;
qrEntradaPaciente: TADOQuery;
qrEntradaPacienteEntredaID: TStringField;
qrEntradaPacienteFecha: TDateTimeField;
qrEntradaPacientePacienteID: TStringField;
qrEntradaPacienteClienteID: TStringField;
qrEntradaPacienteDoctorID: TStringField;
qrEntradaPacientePolizaID: TStringField;
qrEntradaPacienteEnClinica: TBooleanField;
qrEntradaPacienteRecordClinica: TStringField;
qrEntradaPacienteResultadoPaciente: TIntegerField;
qrEntradaPacienteResultadoDoctor: TIntegerField;
qrEntradaPacienteFechaPrometida: TDateTimeField;
qrEntradaPacienteHoraPrometida: TStringField;
qrEntradaPacienteFlebotomistaID: TStringField;
qrEntradaPacienteNota: TMemoField;
qrEntradaPacienteCoberturaConfirmada: TBooleanField;
qrEntradaPacienteProyectoID: TStringField;
qrEntradaPacienteRecid: TLargeintField;
qrEntradaPacienteBruto: TBCDField;
qrEntradaPacienteDescuento: TBCDField;
qrEntradaPacienteSubTotal: TBCDField;
qrEntradaPacienteCoberturaSeguro: TBCDField;
qrEntradaPacienteNeto: TBCDField;
qrEntradaPacienteNombrePaciente: TStringField;
qrEntradaPacienteDireccion: TMemoField;
qrEntradaPacienteTelefonos: TStringField;
qrEntradaPacienteEmail: TStringField;
qrEntradaPacienteClienteNombre: TStringField;
qrEntradaPacienteSucursalId: TStringField;
qrEntradaPacienteUserID: TStringField;
qrEntradaPacienteTotalPendiente: TFloatField;
qrEntradaPacienteCobroID: TStringField;
qrEntradaPacienteTotalPagado: TBCDField;
qrEntradaPacienteHoraEntrada: TStringField;
qrEntradaPacientePrioridad: TIntegerField;
qrEntradaPacienteFax: TStringField;
qrEntradaPacienteTipoDocumento: TIntegerField;
qrEntradaPacienteCoberturaPorc: TBCDField;
qrEntradaPacienteCoberturaValor: TBCDField;
qrEntradaPacienteDescuentoPorc: TBCDField;
qrEntradaPacienteDescuentoValor: TBCDField;
qrEntradaPacienteAprobadoPor: TStringField;
qrEntradaPacienteMuestraNo: TStringField;
qrEntradaPacienteAprobacionNo: TStringField;
qrEntradaPacienteMonedaID: TStringField;
qrEntradaPacienteFechaEntrada: TDateTimeField;
qrEntradaPacienteCoberturaExpPorc: TBooleanField;
qrEntradaPacienteEdadPaciente: TBCDField;
qrEntradaPacienteNombreDoctor: TStringField;
qrEntradaPacientePublicarInternet: TBooleanField;
qrEntradaPacienteOrigen: TStringField;
qrEntradaPacienteCarnet: TStringField;
qrEntradaPacientePublicarInternetDoctor: TBooleanField;
qrEntradaPacienteCuadreGlobal: TStringField;
qrEntradaPacienteCuadreUsuario: TStringField;
qrEntradaPacienteDescAutorizadoPor: TStringField;
qrEntradaPacienteGastosVarios: TBCDField;
qrEntradaPacienteNoAS400: TBooleanField;
qrEntradaPacienteNoAxapta: TBooleanField;
qrEntradaPacienteNoFactura: TBooleanField;
qrEntradaPacienteFactExterior: TBooleanField;
qrEntradaPacienteHold: TBooleanField;
qrEntradaPacienteRepMuestra: TBooleanField;
qrEntradaPacienteEntradaIdAnt: TStringField;
qrEntradaPacienteDetalle: TADOQuery;
qrEntradaPacienteDetallePruebaID: TStringField;
qrEntradaPacienteDetalleComboPruebaID: TStringField;
qrEntradaPacienteDetallePrecio: TBCDField;
qrEntradaPacienteDetalleDescuento: TBCDField;
qrEntradaPacienteDetalleDescuentoExtra: TBCDField;
qrEntradaPacienteDetalleCodigoAutorizacion: TStringField;
qrEntradaPacienteDetalleTotalLinea: TBCDField;
qrEntradaPacienteDetalleRefRecid: TLargeintField;
qrEntradaPacienteDetalleSecuencia: TLargeintField;
qrEntradaPacienteDetalleDescripcion: TStringField;
qrEntradaPacienteDetalleDescPct: TBCDField;
qrEntradaPacienteDetalleCoberturaAplica: TBooleanField;
qrEntradaPacienteDetalleCoberturaEspecial: TBCDField;
qrEntradaPacienteDetalleCoberturaEspecialPorc: TBCDField;
qrEntradaPacienteDetalleCoberturaAplicada: TBCDField;
qrEntradaPacienteDetalleDescuentoLineaAplicado: TBCDField;
qrEntradaPacienteDetalleMuestraNo: TStringField;
qrEntradaPacienteDetalleComentario: TMemoField;
qrEntradaPacienteDetalleCoberturaExpPorc: TBooleanField;
qrEntradaPacienteDetalleRepMuestra: TBooleanField;
qrEntradaPacienteDetalleMuestraAnt: TStringField;
dsEntradaPacienteDetalle: TDataSource;
dsEntradaPaciente: TDataSource;
ppEntradaPaciente: TppDBPipeline;
ppEntradaPacienteDetalle: TppDBPipeline;
qrPacienteClienteID: TStringField;
qrPacienteNombre: TStringField;
qrPacienteContacto: TStringField;
qrPacienteTelefono: TStringField;
qrPacienteFax: TStringField;
qrPacienteGrupoCliente: TStringField;
qrPacienteIncluirPrecioTicket: TBooleanField;
qrPacienteAutoConfirmar: TBooleanField;
qrPacienteEmpleadoID: TStringField;
qrPacienteCodigoAxapta: TStringField;
qrPacienteemail: TStringField;
qrPacientedireccionweb: TStringField;
qrPacienteTelefono2: TStringField;
qrPacienteMonedaID: TStringField;
qrPacienteIdentificacion: TStringField;
qrPacienteOrigen: TIntegerField;
qrPacienteDireccion: TMemoField;
qrPacienteCiudadID: TStringField;
qrPacientePruebasPorDia: TSmallintField;
qrPacienteCoberturaPorc: TBCDField;
qrPacientePrincipal: TStringField;
qrPacienteEnvioResultado: TIntegerField;
qrPacientePublicarInternet: TBooleanField;
qrPacienteSexo: TIntegerField;
qrPacienteFechaNacimiento: TDateTimeField;
qrPacienteSeguro: TStringField;
qrPacientePoliza: TStringField;
qrPacienteCobrarDiferencia: TBooleanField;
qrPacienteEnviarFax: TBooleanField;
qrPacienteActivarDescuentos: TBooleanField;
qrPacienteUsarAliasNombre: TBooleanField;
qrPacienteUsarAliasPrueba: TBooleanField;
qrPacienteSiempreInternet: TBooleanField;
qrPacienteImprimirAliasNombre: TBooleanField;
qrPacienteImprimirAliasPrueba: TBooleanField;
qrPacienteImprimirSoloTotales: TBooleanField;
qrPacienteImprimirAliasResultados: TBooleanField;
qrPacienteAlias: TStringField;
qrPacienteQuienPaga: TStringField;
qrPacienteTipoCliente: TStringField;
qrPacienteEntregarResultados: TStringField;
qrPacienteTextoReferencia: TStringField;
qrPacienteSiempreImprimir: TBooleanField;
qrPacienteTipoSangre: TStringField;
qrPacientePacienteCiaId: TStringField;
qrDonanteDonanteActivo: TSmallintField;
DataSetInsert1: TDataSetInsert;
DataSetPost1: TDataSetPost;
DataSetCancel1: TDataSetCancel;
DataSetDelete1: TDataSetDelete;
DataSetEdit1: TDataSetEdit;
DataSetDelete2: TDataSetDelete;
qrDetalles: TADOQuery;
dsDetalles: TDataSource;
qrDetallesProductoID: TWideStringField;
qrDetallesCantidad: TBCDField;
qrDetallesFecha: TDateTimeField;
qrDetallesDonacionId: TStringField;
ActDetalles: TAction;
qrDonacionDonacionID: TStringField;
qrDonacionFecha: TDateTimeField;
qrDonacionPacienteID: TStringField;
qrDonacionNotaEntrevista: TMemoField;
qrDonacionDonacionStatus: TWideStringField;
qrDonacionDonacionEstado: TStringField;
qrDonacionDonacionTipo: TStringField;
qrDonacionComentario: TMemoField;
qrDonacionCantidadRecogida: TBCDField;
qrDonacionTemperatura: TBCDField;
qrDonacionPeso: TBCDField;
qrDonacionPulsoMinimo: TBCDField;
qrDonacionPulsoEstado: TStringField;
qrDonacionTensionArteriar: TStringField;
qrDonacionHoraInicio: TDateTimeField;
qrDonacionHoraFin: TDateTimeField;
qrDonacionDirigidoNombre: TStringField;
qrDonacionHospital: TStringField;
qrDonacionFechaTranfusion: TDateTimeField;
qrDonacionMedico: TStringField;
qrDonacionTelefono: TStringField;
qrDonacionTelefono2: TStringField;
qrDonacionDireccionMedico: TMemoField;
qrDonacionPagina: TSmallintField;
qrDonacionTipoFundaID: TWideStringField;
qrDonacionHemoglobina: TStringField;
qrDonacionHematocito: TStringField;
qrDonacionGlobulosBlancos: TStringField;
qrDonacionPlaquetas: TStringField;
qrDonacionNotasCuestionario: TMemoField;
qrDonacionProductoID: TWideStringField;
dxLayoutControl1Item1: TdxLayoutItem;
cxDBTextEdit4: TcxDBTextEdit;
dxLayoutGroup1: TdxLayoutGroup;
dxLayoutGroup2: TdxLayoutGroup;
dxLayoutItem1: TdxLayoutItem;
dxLayoutGroup4: TdxLayoutGroup;
qrDetallesReservado: TBooleanField;
cxButton1: TcxButton;
Item1: TdxLayoutItem;
Item4: TdxLayoutItem;
cxGrid3: TcxGrid;
cxGridDBTableView3: TcxGridDBTableView;
cxGridDBColumn1: TcxGridDBColumn;
cxGridLevel3: TcxGridLevel;
Item3: TdxLayoutItem;
cgDatos: TcxGrid;
dbDatos: TcxGridDBTableView;
dbDatosCodigoId: TcxGridDBColumn;
dbDatosCantidad: TcxGridDBColumn;
dbDatosFecha: TcxGridDBColumn;
dbDatosHora: TcxGridDBColumn;
dbDatosDonacionId: TcxGridDBColumn;
dbDatosReservado: TcxGridDBColumn;
lvDatos: TcxGridLevel;
qrDetallesCodigoId: TStringField;
Group1: TdxLayoutGroup;
Item2: TdxLayoutItem;
cxDBTextEdit1: TcxDBTextEdit;
Item5: TdxLayoutItem;
cxDBTextEdit2: TcxDBTextEdit;
qrDetallesNombrePaciente: TStringField;
Group2: TdxLayoutGroup;
Item6: TdxLayoutItem;
cxDBTextEdit3: TcxDBTextEdit;
Item7: TdxLayoutItem;
cxDBTextEdit5: TcxDBTextEdit;
Item8: TdxLayoutItem;
cxDBDateEdit1: TcxDBDateEdit;
cxButton2: TcxButton;
Item9: TdxLayoutItem;
qrReceptor: TADOQuery;
dsReceptor: TDataSource;
qrDetallesProcesoID: TWideStringField;
qrDetallesReservadoHasta: TDateTimeField;
qrDetallesDias: TIntegerField;
qrDetallesCruce: TBooleanField;
qrDetallesCrucePacienteId: TStringField;
qrDetallesDisponible: TBooleanField;
qrDetallesPacienteID: TStringField;
Item10: TdxLayoutItem;
cxDBTextEdit6: TcxDBTextEdit;
Group3: TdxLayoutGroup;
Group4: TdxLayoutGroup;
qrReceptorNombre: TStringField;
cxDBCheckBox1: TcxDBCheckBox;
Item11: TdxLayoutItem;
Group5: TdxLayoutGroup;
Item12: TdxLayoutItem;
cxDBCheckBox2: TcxDBCheckBox;
qrDetallesHora: TStringField;
cxDBTextEdit7: TcxDBTextEdit;
Item13: TdxLayoutItem;
Item14: TdxLayoutItem;
cxDBTextEdit8: TcxDBTextEdit;
cxButton3: TcxButton;
Item15: TdxLayoutItem;
ActFindReceptor: TAction;
ActFindDoctor: TAction;
Group8: TdxLayoutGroup;
Item16: TdxLayoutItem;
cxDBTextEdit9: TcxDBTextEdit;
Group6: TdxLayoutGroup;
Group7: TdxLayoutGroup;
qrDoctor: TADOQuery;
dsDoctor: TDataSource;
qrDoctorDoctorID: TStringField;
qrDoctorNombre: TStringField;
qrDetallesVence: TDateTimeField;
qrDonanteRH: TWideStringField;
qrDonanteTipoSangre: TWideStringField;
cxDBTextEdit10: TcxDBTextEdit;
Item19: TdxLayoutItem;
cxMemo1: TcxMemo;
Group13: TdxLayoutGroup;
Item20: TdxLayoutItem;
ActLiberarReservacion: TAction;
cxDBTextEdit11: TcxDBTextEdit;
Item17: TdxLayoutItem;
qrDetallesTipoSangre: TWideStringField;
qrDetallesRH: TWideStringField;
dbDatosProductoID: TcxGridDBColumn;
dbDatosTipoSangre: TcxGridDBColumn;
dbDatosRH: TcxGridDBColumn;
procedure cxDBTextEdit11PropertiesChange(Sender: TObject);
procedure ActLiberarReservacionExecute(Sender: TObject);
procedure qrDetallesProductoIDChange(Sender: TField);
procedure cxDBTextEdit7PropertiesChange(Sender: TObject);
procedure cxButton3Click(Sender: TObject);
procedure cxButton1Click(Sender: TObject);
procedure cxButton2Click(Sender: TObject);
procedure cxDBTextEdit6PropertiesChange(Sender: TObject);
procedure cxDBTextEdit5PropertiesChange(Sender: TObject);
procedure ActDetallesExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure run;
end;
var
frmBancoOperacion: TfrmBancoOperacion;
implementation
uses Main, DataModule, DataBanco, DialogoTipoDonacion, DialogoEntrevista,DialogConsulta;
{$R *.dfm}
procedure TfrmBancoOperacion.run;
Var
qfind : TADOQuery;
begin
frmBancoOperacion.showmodal;
{if ModalResult = mrOk then
begin
frmMain.frmTmp.qrEntradaPacienteDetalle.Insert;
frmMain.frmTmp.qrEntradaPacienteDetallePruebaID.Value := qrDetallesCodigoId.Value;
frmMain.frmTmp.qrEntradaPacienteDetalleDescripcion.Value := qrBancoInventarioProductoDes.Value;
frmMain.frmTmp.qrEntradaPacienteDetallePrecio.Value := qrBancoInventarioPrecio.Value;
frmMain.frmTmp.qrEntradaPacienteDetalle.Post;
end; }
end;
procedure TfrmBancoOperacion.ActDetallesExecute(Sender: TObject);
begin
inherited;
qrDetalles.Close;
qrDetalles.Parameters.ParamByName('ProductoId').Value:= DMB.qrBancoInventarioProductoID.Value;
qrDetalles.Open;
qrDonante.Close;
qrDonante.Parameters.ParamByName('PacienteId').Value:= qrDetallesPacienteID.Value;
qrDonante.Open;
end;
procedure TfrmBancoOperacion.ActLiberarReservacionExecute(Sender: TObject);
begin
inherited;
//DMB.LiberarReservacion(qrDetallesCodigoId.Value, cxMemo2.Text);
end;
procedure TfrmBancoOperacion.cxButton1Click(Sender: TObject);
begin
inherited;
if (DMB.qrReservar.State in [dsinsert,dsedit]) then
begin
DMB.qrReservar.Post;
DMB.Reservar(qrDetallesCodigoId.Value,
DMB.qrReservarReceptorId.Value,
DMB.qrReservarDoctorId.Value,
DMB.qrReservarReservadoHasta.AsString,
DMB.qrReservarCruce.Value,
cxMemo1.Text );
end;
end;
procedure TfrmBancoOperacion.cxButton2Click(Sender: TObject);
begin
inherited;
frmMain.LanzaVentana(-6002);
end;
procedure TfrmBancoOperacion.cxButton3Click(Sender: TObject);
begin
inherited;
DMB.qrReservarDoctorId.Value:= DMB.BuscarDoctor;
end;
procedure TfrmBancoOperacion.cxDBTextEdit11PropertiesChange(Sender: TObject);
begin
inherited;
DMB.qrReservar.Close;
DMB.qrReservar.Parameters.ParamByName('CodigoId').Value:= qrDetallesCodigoId.Value;
DMB.qrReservar.Open;
qrDonante.Close;
qrDonante.Parameters.ParamByName('PacienteId').Value:= qrDetallesPacienteID.Value;
qrDonante.Open;
cxMemo1.Text:= '';
//cxMemo2.Text:= '';
end;
procedure TfrmBancoOperacion.cxDBTextEdit5PropertiesChange(Sender: TObject);
begin
inherited;
qrReceptor.Close;
qrReceptor.Parameters.ParamByName('PacienteId').Value:= DMB.qrReservarReceptorId.Value;
qrReceptor.Open;
end;
procedure TfrmBancoOperacion.cxDBTextEdit6PropertiesChange(Sender: TObject);
begin
inherited;
DMB.qrReservar.Close;
DMB.qrReservar.Parameters.ParamByName('CodigoId').Value:= qrDetallesCodigoId.Value;
DMB.qrReservar.Open;
DMB.qrReservar.Edit;
end;
procedure TfrmBancoOperacion.cxDBTextEdit7PropertiesChange(Sender: TObject);
begin
inherited;
if (trim(cxDBTextEdit7.Text) = '') then
begin
qrDoctor.Parameters.ParamByName('DoctorId').Value:= '';
cxDBTextEdit9.Text:= '';
Exit;
end;
qrDoctor.Close;
qrDoctor.Parameters.ParamByName('DoctorId').Value:= cxDBtextEdit7.Text;
qrDoctor.Open;
end;
procedure TfrmBancoOperacion.FormCreate(Sender: TObject);
begin
inherited;
DMB.qrBancoInventario.Close;
DMB.qrBancoInventario.Open;
ActDetallesExecute(Sender);
end;
procedure TfrmBancoOperacion.qrDetallesProductoIDChange(Sender: TField);
begin
inherited;
qrDoctor.Close;
qrDoctor.Parameters.ParamByName('DoctorId').Value:= cxDBtextEdit7.Text;
qrDoctor.Open;
end;
end.
|
unit UMapLabels;
interface
uses
Windows, Controls, Classes, SysUtils, Graphics, UMapUtils, ExtCtrls, Messages;
type
TLongLatPos = record
Long: Double;
Lat: Double;
end;
TPointerOrient = (poWNW, poNNW, poNNE, poENE, poESE, poSSE, poSSW, poWSW);
TMapQuadrant = (mqNW, mqNE, mqSW, mqSE);
TDrawTextFlags = (dtDraw, dtMeasure);
TMapPin2 = class(TGraphicControl)
private
FMouseDown: Boolean;
FStartX, FStartY: Integer;
FColor: TColor;
FBorderColor: TColor;
FBorderWidth: Integer;
FPinName: string;
FTxLine1: string;
FTxLine2: string;
FCoordinates: TLongLatPos;
FQuadPos: TMapQuadrant;
FOffsetPoint: TPoint;
FMoved: Boolean;
// FNotes: TStrings;
FPointerOrient: TPointerOrient;
FPointPos: TPoint;
FTextRect: TRect;
FTipRect: TRect;
FTipRadius: Integer;
FNeedResetBounds: Boolean;
FAnchorPt: TPoint; //tip point
FPtInLabel: Boolean; //mousepoint is in the lable area
FShowAddress: Boolean; //toggle showing addresses or just lable name
FSeparation: TPoint; //initial seperation between tip and lable
FMinWidth: Integer; //min width of the label
FTxLnHeight: Integer; //text line spacing in lable
FLabelGeoRect: TGeoRect;
procedure SetCoordinates(const Value: TLongLatPos);
// procedure SetNotes(const Value: TStrings);
procedure SetPinName(const Value: string);
procedure SetBorderColor(const Value: TColor);
procedure SetBorderWidth(const Value: Integer);
procedure SetColor(const Value: TColor);
procedure SetAnchorPt(const Value: TPoint);
procedure SetTextPos(const Value: TPoint);
function GetTextPos: TPoint;
function GetLocalTipRect: TRect;
function GetQuadPos(p: TPoint):TMapQuadrant;
function GetBrushColor: TColor;
protected
procedure Paint; override;
procedure ResetBounds(Relative2Tip: Boolean);
// procedure DoDrawText(Canvas: TCanvas; Flags: TDrawTextFlags; var Rect: TRect); virtual;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
public
constructor Create(AOwner: TComponent); override;
// destructor Destroy; override;
procedure Setup(Title, Line1, Line2: String; TipPt: TPoint; GRect: TGeoRect);
procedure SetupPoint (TipPt: TPoint; AOwner: TComponent; GRect : TGeoRect);
published
property Color: TColor read FColor write SetColor;
property BorderColor: TColor read FBorderColor write SetBorderColor;
property BorderWidth: Integer read FBorderWidth write SetBorderWidth;
property PinName: string read FPinName write SetPinName;
// property Notes: TStrings read FNotes write SetNotes;
property Coordinates: TLongLatPos read FCoordinates write SetCoordinates;
property TextPos: TPoint read GetTextPos write SetTextPos;
property AnchorPt: TPoint read FAnchorPt write SetAnchorPt;
property LabelGeoRect: TGeoRect read FLabelGeoRect write FLabelGeoRect;
property PointPos: TPoint read FPointPos write FPointPos;
property Moved: Boolean read FMoved write FMoved;
end;
TMapLabel = class(TGraphicControl)
private
FMouseDown: Boolean;
FMouseDownPt: TPoint; //FStartX, FStartY: Integer;
FColor: TColor;
FName: string;
FAnchorPt: TPoint;
FPointPos: TPoint;
FPointOut: TPoint;
FTipPt: TPoint;
FTextRect: TRect;
FMinWidth: Integer;
FPts: Array of TPoint;
FPtTxOut: Array of TPoint;
FRotateHdl: Array of TPoint;
FDispPts: Array of TPoint;
FDispTxPts: Array of TPoint;
FDispRHdl: Array of TPoint;
FPointerMoved: Boolean;
FPointerRotated: Boolean;
FLabelGeoRect: TGeoRect;
FRotating: Boolean;
FAngle: Integer;
FoffestY: Integer;
FoffestYFix: Integer;
FText: string;
FEditMode : Boolean;
FType : Integer;
FMapLabelMoved: TNotifyEvent;
protected
procedure Paint; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
function ClickInRotationHandle(X, Y: Integer): Boolean;
function GetBrushColor: TColor;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Setup(AName: String; labelType: Integer; TipPt: TPoint; GRect: TGeoRect);
procedure Rotate(Deg: Integer);
function RotationAngle(Shift: TShiftState; X, Y: Integer): Integer;
published
property PointerMoved: Boolean read FPointerMoved write FPointerMoved;
property PointerRotated: Boolean read FPointerRotated write FPointerRotated;
property LabelGeoRect: TGeoRect read FLabelGeoRect write FLabelGeoRect;
property PointPos: TPoint read FPointPos write FPointPos;
property PointOut: TPoint read FPointOut write FPointOut;
property Angle: Integer read FAngle write FAngle;
property Text: String read FText write FText;
property EditMode: Boolean read FEditMode write FEditMode;
property LabelType: Integer read FType write FType;
property MapLabelMoved: TNotifyEvent read FMapLabelMoved write FMapLabelMoved;
end;
TMapPinList = class(TList)
protected
function Get(Index: Integer): TGraphicControl;
procedure Put(Index: Integer; Item: TGraphicControl);
public
function First: TGraphicControl;
function Last: TGraphicControl;
function IndexOf(Item: TGraphicControl): Integer;
function Remove(Item: TGraphicControl): Integer;
property MapPin[Index: Integer]: TGraphicControl read Get write Put; default;
end;
implementation
uses
Math, RzCommon, UStatus, UGlobals, UUtil1, StrUtils;
{ TMapPin2 }
constructor TMapPin2.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Parent := TWinControl(AOwner);
// FNotes := TStringList.Create;
FColor := clInfoBk;
FBorderColor := clBlue;
FBorderWidth := 2;
FTipRadius := 4;
FPtInLabel := False;
FMoved := False;
FSeparation := Point (100,100);
FOffsetPoint := Point(0,0);
Top := 50;
Left := 100;
Width := 150;
Height := 100;
FTextRect := Rect(0, 0, 80, 35);
end;
(*
destructor TMapPin2.Destroy;
begin
FNotes.Free;
inherited;
end;
*)
procedure TMapPin2.SetupPoint (TipPt: TPoint; AOwner: TComponent; GRect : TGeoRect);
begin
// FLabelGeoRect := GRect;
Setup(FPinName, FTxLine1, FTxLine2, TipPt, GRect);
SetParent (TWinControl(AOwner));
end;
function TMapPin2.GetQuadPos(p: TPoint): TMapQuadrant;
var
R: TRect;
w,l: Integer;
begin
R := Parent.BoundsRect;
w:= abs(R.Left- R.Right);
l:= abs(R.Top - R.Bottom);
if (p.X < w/2) and (p.Y < l/2) then
result := mqNW
else if (p.X > w/2) and (p.Y < l/2) then
result := mqNE
else if (p.X > w/2) and (p.Y > l/2) then
result := mqSE
else if (p.X < w/2) and (p.Y > l/2) then
result := mqSE
else
result := mqNW; // unknown
end;
procedure TMapPin2.Setup(Title, Line1, Line2: String; TipPt: TPoint; GRect: TGeoRect);
var
h, w: Integer;
Size: TSize;
TipBall: TRect;
Tip: TPoint;
begin
FShowAddress := True;
FMinWidth := 72;
FLabelGeoRect := GRect;
//set the lable text
FPinName := Title;
FTxLine1 := Line1;
FTxLine2 := Line2;
//set the tip
FPointPos := TipPt;
TipBall := Rect(FPointPos.x-FTipRadius, FPointPos.y-FTipRadius, FPointPos.x+FTipRadius, FPointPos.y+FTipRadius);
SetBounds(TipBall.Left, TipBall.Top, TipBall.Right-TipBall.Left, TipBall.Bottom-TipBall.top);
//get dimensions of pin label
Size := Canvas.TextExtent(FPinName);
w := Max(FMinWidth, Size.cx+6); //96dpi = 1 inch long is min
h := Size.cy + 6; //3 pixel border
if FShowAddress then
begin
if length(FTxLine1)> 0 then
begin
Size := Canvas.TextExtent(FTxLine1);
w := Max(w, Size.cx+6);
h := h + Size.cy;
end;
if length(FTxLine2)> 0 then
begin
Size := Canvas.TextExtent(FTxLine2);
w := Max(w, Size.cx+6);
h := h + Size.cy;
end;
FTxLnHeight := Size.cy;
end;
FQuadPos := GetQuadPos (TipPt);
//position in designated quad
FTipRect.TopLeft := Point(0,0);
FTipRect.BottomRight := Point(TipBall.Right-TipBall.Left, TipBall.Bottom - TipBall.Top);
if (FSeparation.X = 100) and (FSeparation.Y = 100) then
begin
if FQuadPos in [mqNW] then
begin
FTextRect.Top := FTipRect.Bottom - FSeparation.Y;
FTextRect.Left := FTipRect.Right - FSeparation.X;
FTextRect.Bottom := FTextRect.Top + h;
FTextRect.Right := FTextRect.Left + w;
end
else if FQuadPos in [mqNE] then
begin
FTextRect.Right := FTipRect.Left + FSeparation.X;
FTextRect.Top := FTipRect.Bottom - FSeparation.Y;
FTextRect.Bottom := FTextRect.Top + h;
FTextRect.Left := FTextRect.Right - w;
end
else if FQuadPos in [mqSW] then
begin
FTextRect.Left := FTipRect.Right - FSeparation.X;
FTextRect.Bottom := FTipRect.Top + FSeparation.Y;
FTextRect.Top := FTextRect.Bottom - h;
FTextRect.Right := FTextRect.Left + w;
end
else if FQuadPos in [mqSE] then
begin
FTextRect.Bottom := FTipRect.Top + FSeparation.Y;
FTextRect.Right := FTipRect.Left + FSeparation.X;
FTextRect.Top := FTextRect.Bottom - h;
FTextRect.Left := FTextRect.Right - w;
end;
end
else
begin
FTextRect.Top := FTipRect.Bottom - FSeparation.Y;
FTextRect.Left := FTipRect.Right + FSeparation.X;
FTextRect.Bottom := FTextRect.Top + h;
FTextRect.Right := FTextRect.Left + w;
end;
ResetBounds(True);
//reset the tip relative to new bnounds
Tip := ParentToClient(FPointPos);
FTipRect := Rect(Tip.x-FTipRadius, Tip.y-FTipRadius, Tip.x+FTipRadius, Tip.y+FTipRadius);
end;
function TMapPin2.GetLocalTipRect: TRect;
var
Pt: TPoint;
begin
Pt := ParentToClient(FPointPos);
result := Rect(Pt.x-FTipRadius, Pt.y-FTipRadius, Pt.x+FTipRadius, Pt.y+FTipRadius);
end;
//Anchor point is in Parent coordinates
procedure TMapPin2.SetAnchorPt(const Value: TPoint);
begin
FPointPos := Value;
FTipRect := GetLocalTipRect;
ResetBounds(True);
end;
function TMapPin2.GetBrushColor: TColor;
begin
if AnsiContainsStr(FPinName, 'SUBJ') then
result := clRed
else
result := clYellow;
end;
procedure TMapPin2.Paint;
var
RectRgn, PointerRgn: THandle;
Points: array[0..2] of TPoint;
XOff, YOff: Integer;
FrBrush : HBRUSH;
begin
with Canvas do
begin
Pen.Color := clBlack;
Pen.Width := 1;
Brush.Color := GetBrushColor;
Brush.Style := bsSolid;
RectRgn := 0;
PointerRgn := 0;
try
//create label region
RectRgn := CreateRectRgnIndirect(FTextRect);
// Make triangular region for pointer
Points[0] := ParentToClient(FPointPos);
if FPointerOrient in [poWNW, poNNW] then
Points[1] := FTextRect.TopLeft
else if FPointerOrient in [poENE, poNNE] then
Points[1] := Point(FTextRect.Left + (FTextRect.Right - FTextRect.Left), FTextRect.Top)
else if FPointerOrient in [poESE, poSSE] then
Points[1] := FTextRect.BottomRight
else if FPointerOrient in [poWSW, poSSW] then
Points[1] := Point(FTextRect.Left, FTextRect.Top + (FTextRect.Bottom - FTextRect.Top));
Points[2] := Points[1];
XOff := Max((FTextRect.Right - FTextRect.Left) div 4, 15);
YOff := Max((FTextRect.Bottom - FTextRect.Top) div 2, 15);
if FPointerOrient in [poWNW, poENE] then
Inc(Points[2].Y, YOff)
else if FPointerOrient in [poESE, poWSW] then
Dec(Points[2].Y, YOff)
else if FPointerOrient in [poNNW, poSSW] then
Inc(Points[2].X, XOff)
else if FPointerOrient in [poNNE, poSSE] then
Dec(Points[2].X, XOff);
PointerRgn := CreatePolygonRgn(Points, High(Points) + 1, WINDING);
// combine two regions into one
CombineRgn(RectRgn, RectRgn, PointerRgn, RGN_OR);
PaintRgn(Canvas.Handle, RectRgn);
Canvas.Font.Style := [fsBold];
Canvas.TextOut(FTextRect.Left+2, FTextRect.Top+2, PinName);
if FShowAddress then
begin
Canvas.Font.Style := [];
Canvas.TextOut(FTextRect.Left+2, FTextRect.Top+2+FTxLnHeight, FTxLine1);
Canvas.TextOut(FTextRect.Left+2, FTextRect.Top+2+FTxLnHeight+FTxLnHeight, FTxLine2);
end;
//frame the region
Canvas.Brush.color := clBlack;
FrBrush := CreateSolidBrush(COLORREF($111111));
FrameRgn(Canvas.Handle, RectRgn, FrBrush, 1,1);
// Canvas.FrameRect(ClientRect);
//draw the red dot
Canvas.Brush.Color := clRed;
Canvas.Ellipse(FTipRect);
finally
if PointerRgn <> 0 then DeleteObject(PointerRgn);
if RectRgn <> 0 then DeleteObject(RectRgn);
end;
end;
end;
procedure TMapPin2.SetBorderColor(const Value: TColor);
begin
if FBorderColor <> Value then
begin
FBorderColor := Value;
Invalidate;
end;
end;
procedure TMapPin2.SetBorderWidth(const Value: Integer);
begin
if FBorderWidth <> Value then
begin
FBorderWidth := Value;
Invalidate;
end;
end;
procedure TMapPin2.SetColor(const Value: TColor);
begin
if FColor <> Value then
begin
FColor := Value;
Invalidate;
end;
end;
procedure TMapPin2.SetCoordinates(const Value: TLongLatPos);
begin
if (Value.Long <> FCoordinates.Long) and (Value.Lat <> FCoordinates.Lat) then
begin
FCoordinates := Value;
FNeedResetBounds := True;
Invalidate;
end;
end;
(*
procedure TMapPin2.SetNotes(const Value: TStrings);
begin
FNotes.Assign(Value);
FNeedResetBounds := True;
Invalidate;
end;
*)
procedure TMapPin2.SetPinName(const Value: string);
begin
if FPinName <> Value then
begin
FNeedResetBounds := True;
FPinName := Value;
Invalidate;
end;
end;
procedure TMapPin2.ResetBounds(Relative2Tip: Boolean);
var
MaxT, MaxL, MaxB, MaxR: Integer;
Tip, Center: TPoint;
Slope: Double;
ParTxtRect: TRect;
ParTipRect: TRect;
begin
ParTxtRect.TopLeft := ClientToParent(FTextRect.TopLeft);
ParTxtRect.BottomRight := ClientToParent(FTextRect.BottomRight);
ParTipRect.TopLeft := ClientToParent(FTipRect.TopLeft);
ParTipRect.BottomRight := ClientToParent(FTipRect.BottomRight);
MaxT := MinIntValue([ParTxtRect.Top, ParTipRect.Top]);
MaxL := MinIntValue([ParTxtRect.Left, ParTipRect.left])-2;
MaxB := MaxIntValue([ParTxtRect.Bottom, ParTipRect.Bottom])+6;
MaxR := MaxIntValue([ParTxtRect.Right, ParTipRect.Right])+2;
SetBounds(MaxL, MaxT, abs(MaxR - MaxL), abs(MaxB - MaxT));
//reposition rects within bounds
if Relative2Tip then
begin
// readjust dimensions of FTextRect based on new window bounds
FTextRect.TopLeft := ParentToClient(ParTxtRect.TopLeft);
FTextRect.BottomRight := ParentToClient(ParTxtRect.BottomRight);
FPointPos.X := ParTipRect.Left + ((ParTipRect.Right - ParTipRect.Left) div 2);
FPointPos.Y := ParTipRect.Top + ((ParTipRect.Bottom - ParTipRect.Top) div 2);
end
else {Relative2Label}
begin
//reset TipRect relative to new boundsrect
Tip := ParentToClient(FPointPos);
FTipRect := Rect(Tip.x-FTipRadius, Tip.y-FTipRadius, Tip.x+FTipRadius, Tip.y+FTipRadius);
end;
// figure out what octent relative to the text box should contain the pointer
Center.X := ParTxtRect.Left + ((ParTxtRect.Right - ParTxtRect.Left) div 2);
Center.Y := ParTxtRect.Top + ((ParTxtRect.Bottom - ParTxtRect.Top) div 2);
try
if (FPointPos.X - Center.X) = 0 then
Slope := 0
else
Slope := Abs((FPointPos.Y - Center.Y) / (FPointPos.X - Center.X));
except
on E: EZeroDivide do
Slope := 0;
end;
if FPointPos.Y >= Center.Y then
begin
if FPointPos.X >= Center.X then
begin
if Slope >= 1 then FPointerOrient := poSSE
else FPointerOrient := poESE;
end
else begin
if Slope >= 1 then FPointerOrient := poSSW
else FPointerOrient := poWSW;
end;
end
else begin
if FPointPos.X >= Center.X then
begin
if Slope >= 1 then FPointerOrient := poNNE
else FPointerOrient := poENE;
end
else begin
if Slope >= 1 then FPointerOrient := poNNW
else FPointerOrient := poWNW;
end;
end;
end;
function TMapPin2.GetTextPos: TPoint;
begin
Result := ClientToParent(FTextRect.TopLeft);
end;
procedure TMapPin2.SetTextPos(const Value: TPoint);
var
ClientRelPt: TPoint;
begin
ClientRelPt := ParentToClient(Value);
if (FTextRect.Left <> ClientRelPt.X) or (FTextRect.Top <> ClientRelPt.Y) then
begin
FTextRect := Rect(ClientRelPt.X, ClientRelPt.Y,
ClientRelPt.X + (FTextRect.Right - FTextRect.Left),
ClientRelPt.Y + (FTextRect.Bottom - FTextRect.Top));
FNeedResetBounds := True;
Invalidate;
end;
end;
(*
procedure TMapPin2.DoDrawText(Canvas: TCanvas; Flags: TDrawTextFlags; var Rect: TRect);
const
SText = '%s'#13#10'Lat: %f, Lon: %f'#13#10'%s';
var
Text: string;
Size: TSize;
begin
Text := Format(SText, [FPinName, FCoordinates.Lat, FCoordinates.Long, ''{FNotes.Text}]);
if Flags = dtMeasure then
begin
Size := Canvas.TextExtent(Text);
Rect.Right := Rect.Left + Size.cx;
Rect.Bottom := Rect.Top + (Size.cy * 3); // hard coded to three lines
end
else
DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, DT_NOCLIP or DT_CENTER);
end;
*)
//this is not being hit - non windows control
(*
procedure TMapPin2.WMNCHitTest(var Message: TMessage);
var
MousePos: TPoint;
begin
// inherited;
if (Message.Result = HTCLIENT) then
begin
MousePos := ScreenToClient(Point(LoWord(Message.LParam), HiWord(Message.LParam)));
if PtInRect(FTextRect, MousePos) then
Message.Result := HTCAPTION;
end;
end;
*)
(*
procedure TMapPin2.WMMove(var Message: TWMMove); //TMessage);
var
A,B: TPoint; //testing
begin
//testing
A := Point(Message.XPos, Message.YPos);
B := ScreenToClient(A);
DebugPoints(A,B);
OutputDebugString(PChar(Format('BEFORE:Bounds L: %d, T: %d, W: %d, H: %d', [Left, Top, Left + Width, Top + Height])));
inherited;
OutputDebugString(PChar(Format('AFTER: Bounds L: %d, T: %d, W: %d, H: %d', [Left, Top, Left + Width, Top + Height])));
FNeedResetBounds := True;
Invalidate;
end;
*)
procedure TMapPin2.MouseDown(Button: TMouseButton; Shift: TShiftState; X,Y: Integer);
begin
FStartX := X;
FStartY := Y;
FMouseDown := True;
FPtInLabel := PtInRect(FTextRect, Point(x,y));
end;
procedure TMapPin2.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
if FMouseDown then
begin
if FPtInLabel then
begin
OffsetRect(FTextRect, X-FStartX, Y-FStartY);
ResetBounds(False);
FStartX := X;
FStartY := Y;
invalidate;
end
else //if PtInRect(FTipRect, Point(x,y)) then
begin
FMoved := True;
OffsetRect(FTipRect, X-FStartX, Y-FStartY);
ResetBounds(True);
FStartX := X;
FStartY := Y;
invalidate;
end;
end;
end;
procedure TMapPin2.MouseUp(Button: TMouseButton; Shift: TShiftState; X,Y: Integer);
begin
FMouseDown := False;
FSeparation.X := FTextRect.Left - FTipRect.Right;
FSeparation.Y := FTipRect.Bottom - FTextRect.Top ;
end;
{ TMapLabel }
constructor TMapLabel.Create(AOwner: TComponent);
begin
inherited;
Parent := TWinControl(AOwner);
Font.Name := 'ARIAL';
FColor := clYellow;
FMinWidth := 72;
FAngle := 0;
FoffestY:= 0;
FoffestYFix := - 1;
FPointerMoved := False;
FPointerRotated := False;
FEditMode := False;
SetLength(FPts, 5); //5 pts define this ghost
SetLength(FPtTxOut, 2); //2 pts for text out positions
SetLength(FRotateHdl, 4); //4 pts that define rotation handle
//rotated display points
SetLength(FDispPts, 5);
SetLength(FDispTxPts, 2);
SetLength(FDispRHdl, 4);
end;
destructor TMapLabel.Destroy;
begin
Finalize(FPts);
Finalize(FPtTxOut);
Finalize(FRotateHdl);
Finalize(FDispPts);
Finalize(FDispTxPts);
Finalize(FDispRHdl);
inherited;
end;
function TMapLabel.RotationAngle(Shift: TShiftState; X, Y: Integer): Integer;
var
Pt: TPoint;
begin
FTipPt := PointPos;
Pt := ClientToParent (Point(X,Y));
X := Pt.X - FTipPt.X; //rotate about the tip
Y := FTipPt.Y - Pt.Y;
result := Round(ArcTan2(Y,X) * 180 / pi);
if result < 0 then result := 360 + result; //need pos degees for Font rotation
end;
procedure TMapLabel.MouseDown(Button: TMouseButton; Shift: TShiftState; X,Y: Integer);
begin
if mbRight = Button then exit;
FRotating := ClickInRotationHandle(X,Y);
if FRotating then
FPointerRotated := True;
FMouseDownPt := Point(x,y);
FMouseDown := True;
FPointerMoved := True;
end;
procedure TMapLabel.MouseMove(Shift: TShiftState; X, Y: Integer);
var
NewAngle: Integer;
begin
if FMouseDown then
begin
if FRotating then
begin
NewAngle := RotationAngle(Shift, X, Y);
if NewAngle <> FAngle then
Rotate(NewAngle); //do rotation
end
else
SetBounds(Left + X-FMouseDownPt.x, Top + Y-FMouseDownPt.y-5, Width, Height);
end;
end;
function TMapLabel.GetBrushColor: TColor;
begin
case FType of
lcSUBJ : result := clRed ; //subject
lcCOMP : result := clYellow; //comps or sales
lcRENT : result := colorLabelRental; //rentals
lcLIST : result := colorLabelListing ; //listings
lcCUST : result := clWhite; //custom
else result := clBlack; // unknown
end;
end;
procedure TMapLabel.MouseUp(Button: TMouseButton; Shift: TShiftState; X,Y: Integer);
var
Pt : TPoint;
begin
FMouseDown := False;
FPointPos := CLientToParent (FDispPts[0]);
if FPointerRotated or FPointerMoved then
begin
Pt.X := FDispPts[0].X;
Pt.Y := FDispPts[0].Y + 5;
FPointOut := CLientToParent (Pt);
end
else
FPointOut := FPointPos;
FRotating := False;
Repaint;
FoffestYFix := 5;
if Assigned(FMapLabelMoved) then
FMapLabelMoved(self);
end;
procedure TMapLabel.Paint;
var
idx: Integer;
FontHandle: HFont;
begin
with Canvas do
begin
Pen.Color := clBlack;
Pen.Width := 1;
Brush.Color := FColor;
Brush.Style := bsSolid;
//Draw Label itself
if (FPointerRotated) then
Polygon(FDispPts)
else
Polygon(FPts);
//Draw Rotation Handle
if FRotating then
Brush.Color := clRed
else
Brush.Color := clBlack;
if FPointerRotated then
Polygon(FDispRHdl)
else
Polygon(FRotateHdl);
// Canvas.Brush.color := clBlack;
// Canvas.FrameRect(ClientRect);
//Draw Text
Pen.Color := clBlack;
Pen.Width := 1;
Brush.Color := FColor;
Brush.Style := bsSolid;
if not FPointerRotated then
begin
Canvas.Font.Style := [fsBold];
Canvas.TextOut(FTextRect.Left+4, FTextRect.Top+4, FName);
end
else
begin
FontHandle := 0;
idx := 0;
Font.Name := 'ARIAL';
Font.Style := [fsBold];
Brush.Style := bsClear;
saveFont.Assign(Canvas.Font);
try
if (FAngle >= 0) and (FAngle <= 90) then
begin
FontHandle := RotateFont(Font, FAngle);
idx := 0;
end
else if (FAngle > 90) and (FAngle <= 180) then
begin
FontHandle := RotateFont(Font, FAngle + 180);
idx := 1;
end
else if (FAngle > 180) and (FAngle <= 270) then
begin
FontHandle := RotateFont(Font, FAngle - 180);
idx := 1;
end
else if (FAngle > 270) and (FAngle <= 360) then
begin
FontHandle := RotateFont(Font, FAngle);
idx := 0;
end;
Canvas.Font.Handle := FontHandle;
Canvas.TextOut(FDispTxPts[idx].x, FDispTxPts[idx].y, FName);
finally
// Canvas.Font.Assign(saveFont);
end;
end;
end;
end;
procedure TMapLabel.Rotate(Deg: Integer);
var
i: Integer;
BRect: TRect;
OPt: TPoint;
begin
//Rotate the Polygon points
for i := 0 to 4 do begin
FDispPts[i] := FPts[i];
FDispPts[i] := OffsetPt(FDispPts[i], 0,-FoffestY);
FDispPts[i] := RotatePt(FDispPts[i], Deg);
FDispPts[i] := OffsetPt(FDispPts[i], 0,FoffestY);
end;
//Rotate TextOut Points
for i := 0 to 1 do begin
FDispTxPts[i] := FPtTxOut[i];
FDispTxPts[i] := OffsetPt(FDispTxPts[i], 0,-FoffestY);
FDispTxPts[i] := RotatePt(FDispTxPts[i], Deg);
FDispTxPts[i] := OffsetPt(FDispTxPts[i], 0,FoffestY);
end;
//Rotate Rotation handle
for i := 0 to 3 do begin
FDispRHdl[i] := FRotateHdl[i];
FDispRHdl[i] := OffsetPt(FDispRHdl[i], 0,-FoffestY);
FDispRHdl[i] := RotatePt(FDispRHdl[i], Deg);
FDispRHdl[i] := OffsetPt(FDispRHdl[i], 0,FoffestY);
end;
BRect := PtArrayBoundsRect(FDispPts);
OPt := BRect.TopLeft;
OffsetRect(BRect, FPointPos.x, FPointPos.y - FoffestY + FoffestYFix );
BRect.right := BRect.right + 1;
BRect.Bottom := BRect.Bottom + 1;
for i := 0 to 4 do
FDispPts[i] := Point(FDispPts[i].x-OPt.x, FDispPts[i].y-Opt.y);
for i := 0 to 1 do
FDispTxPts[i] := Point(FDispTxPts[i].x-OPt.x, FDispTxPts[i].y-Opt.y);
for i := 0 to 3 do
FDispRHdl[i] := Point(FDispRHdl[i].x-OPt.x, FDispRHdl[i].y-Opt.y);
BoundsRect := BRect;
FAngle := Deg;
Visible := True;
RePaint;
end;
function TMapLabel.ClickInRotationHandle(X, Y: Integer): Boolean;
var
RRgn: THandle;
RPts: Array[0..3] of TPoint;
i: Integer;
begin
for i := 0 to 3 do
begin
if not FPointerRotated then
RPts[i] := FRotateHdl[i]
else
RPts[i] := FDispRHdl[i];
end;
RRgn := CreatePolygonRgn(RPts, 4, WINDING);
try
result := PtinRegion(RRgn, X, Y);
finally
if RRgn <> 0 then DeleteObject(RRgn);
end;
end;
procedure TMapLabel.Setup(AName: String; labelType: Integer; TipPt: TPoint; GRect: TGeoRect);
var
Size: TSize;
w,h,i, dx,dy: Integer;
begin
FName := AName;
FLabelGeoRect := GRect;
dx := FPointPos.X - TipPt.X;
dy := FPointPos.Y - TipPt.Y;
FPointPos := TipPt;
FPointOut := TipPt;
FType := labelType;
// FAnchorPt := APt;
FColor := GetBrushColor;
//set the size of the text area
Size := Canvas.TextExtent(FName);
w := Max(FMinWidth, Size.cx + 4);
h := Size.cy + 8;
FTextRect := Rect(0,0,w,h);
FoffestY := (FTextRect.Bottom - FTextRect.Top) div 2;
if not FPointerRotated then
begin
SetBounds(TipPt.X, TipPt.Y- (h div 2), 20 + w+1, h+2);
FAnchorPt := Point (0, h div 2 );
OffsetRect(FTextRect, FAnchorPt.X + 20, FAnchorPt.Y - (h div 2));
FPts[0] := FAnchorPt;
FPts[1] := Point(FTextRect.left, FTextRect.bottom);
FPts[2] := Point(FTextRect.right, FTextRect.bottom);
FPts[3] := Point(FTextRect.right, FTextRect.top);
FPts[4] := Point(FTextRect.left, FTextRect.top);
FPtTxOut[0] := Point(FTextRect.left, FTextRect.top + 4);
FPtTxOut[1] := Point(FTextRect.left + Size.cx + h div 2, FTextRect.bottom-4);
FRotateHdl[0] := Point(FTextRect.Right, FTextRect.Top + 5);
FRotateHdl[1] := Point(FTextRect.Right-6, FTextRect.Top + 5);
FRotateHdl[2] := Point(FTextRect.Right-6, FTextRect.Bottom - 5);
FRotateHdl[3] := Point(FTextRect.Right, FTextRect.Bottom - 5);
for i := 0 to 4 do FDispPts[i] := FPts[i];
for i := 0 to 1 do FDispTxPts[i] := FPtTxOut[i];
for i := 0 to 3 do FDispRHdl[i] := FRotateHdl[i];
if not FEditMode then
FAngle := MapLabelOrientation(TipPt,Rect(0,0,532,816));
if FAngle <> 0 then
begin
Rotate (FAngle);
FPointerRotated := true;
Repaint;
end;
end
else
SetBounds(Left - dx, Top - dy, Width, Height);
end;
{ TMapPinList }
function TMapPinList.First: TGraphicControl;
begin
result := TGraphicControl(inherited First);
end;
function TMapPinList.Get(Index: Integer): TGraphicControl;
begin
result := TGraphicControl(inherited Get(index));
end;
function TMapPinList.IndexOf(Item: TGraphicControl): Integer;
begin
result := inherited IndexOf(Item);
end;
function TMapPinList.Last: TGraphicControl;
begin
result := TGraphicControl(inherited Last);
end;
procedure TMapPinList.Put(Index: Integer; Item: TGraphicControl);
begin
inherited Put(Index, item);
end;
function TMapPinList.Remove(Item: TGraphicControl): Integer;
begin
result := inherited Remove(Item);
end;
end.
|
PROGRAM WRITELINE;
BEGIN
WRITELN ( 'Hello. Welcome to my pascal compiler.' ) ;
END.
|
unit ViewModel.UserList;
interface
uses
Model.Interfaces;
function CreateUserListViewModelClass: IUserListViewModelInterface;
implementation
uses
Model.User,
Model.FormDeclarations,
Model.ProSu.Interfaces,
Model.ProSu.InterfaceActions,
Model.ProSu.Provider,
Model.ProSu.Subscriber;
type
TUserListViewModel = class(TInterfacedObject, IUserListViewModelInterface)
private
fModel: IUserModelInterface;
fProvider : IProviderInterface;
fSubscriberToEdit : ISubscriberInterface;
function GetModel: IUserModelInterface;
procedure SetModel(const newModel: IUserModelInterface);
function GetProvider: IProviderInterface;
function GetSubscriberToEdit: ISubscriberInterface;
procedure SendNotification(const actions : TInterfaceActions);
procedure SendErrorNotification (const errorType: TInterfaceErrors; const errorMessage: string);
procedure NotificationFromProvider(const notifyClass : INotificationClass);
public
property Model: IUserModelInterface read GetModel write SetModel;
property Provider: IProviderInterface read GetProvider;
property SubscriberToEdit: ISubscriberInterface read GetSubscriberToEdit;
constructor Create;
end;
{ TUserViewModel }
constructor TUserListViewModel.Create;
begin
fProvider:=CreateProSuProviderClass;
fModel := CreateUserModelClass;
end;
function TUserListViewModel.GetModel: IUserModelInterface;
begin
result:=fModel;
end;
function TUserListViewModel.GetProvider: IProviderInterface;
begin
result:=fProvider;
end;
function TUserListViewModel.GetSubscriberToEdit: ISubscriberInterface;
begin
if not Assigned(fSubscriberToEdit) then
fSubscriberToEdit := CreateProSuSubscriberClass;
Result := fSubscriberToEdit;
end;
procedure TUserListViewModel.NotificationFromProvider(
const notifyClass: INotificationClass);
begin
end;
procedure TUserListViewModel.SendErrorNotification(
const errorType: TInterfaceErrors; const errorMessage: string);
var
tmpErrorNotificationClass: TErrorNotificationClass;
begin
tmpErrorNotificationClass:=TErrorNotificationClass.Create;
try
tmpErrorNotificationClass.Actions:=errorType;
tmpErrorNotificationClass.ActionMessage:=errorMessage;
fProvider.NotifySubscribers(tmpErrorNotificationClass);
finally
tmpErrorNotificationClass.Free;
end;
end;
procedure TUserListViewModel.SendNotification(const actions: TInterfaceActions);
var
tmpNotification : TNotificationClass;
begin
tmpNotification := TNotificationClass.Create;
try
tmpNotification.Actions := actions;
fProvider.NotifySubscribers(tmpNotification);
finally
tmpNotification.Free;
end;
end;
procedure TUserListViewModel.SetModel(const newModel: IUserModelInterface);
begin
fModel:=newModel;
end;
function CreateUserListViewModelClass: IUserListViewModelInterface;
begin
result:=TUserListViewModel.Create;
end;
end.
|
unit BMP;
uses Memory;
const
TYPE_OFFSET = 0;
SIZE_OFFSET = 2;
PIXELS_OFFSET = 10;
WIDTH_OFFSET = 18;
HEIGHT_OFFSET = 22;
BIT_COUNT_OFFSET = 28;
SIZEIMAGE_OFFSET = 34;
type
Pixel = class
public Red : byte;
public Green : byte;
public Blue : byte;
constructor (r : byte; g : byte; b : byte);
begin
self.Red := r;
self.Green := g;
self.Blue := b;
end;
function getBytes : array of byte;
begin
Result := new byte[3];
Result[0] := Blue;
Result[1] := Green;
Result[2] := Red;
end;
procedure SetRed(Red: byte);
begin
self.Red := Red;
end;
procedure SetGreen(Green: byte);
begin
self.Green := Green;
end;
procedure SetBlue(Blue: byte);
begin
self.Blue := Blue;
end;
end;
var
offsetToPixels: cardinal;
totalPixelsBytesCount: cardinal;
width: cardinal;
height: cardinal;
sizeimage: cardinal;
additional : integer;
{type BMPHeader = packed record
0bfType : WORD;//2
2bfSize : cardinal;//4
6bfReserved1 : WORD;//2
8bfReserved2 : WORD;//2
10bfOffBits : cardinal;//4
14biSize : cardinal;//4
18biWidth : cardinal//4
22biHeight : cardinal;//4
26biPlanes : WORD;//2
28biBitCount : WORD;//2
end;
}
function BuildPixels(pixelsArray : array of byte) : List<List<Pixel>>;
var
counter : integer;
l : List<List<Pixel>>;
lm : List<Pixel>;
p : Pixel;
portion : array of byte;
begin
lm := new List<Pixel>();
l := new List<List<Pixel>>();
portion := new byte[(width*3)+additional];
for i : integer := 1 to height do
begin
System.Array.Copy(pixelsArray, (i-1)*portion.Length, portion, 0, portion.Length);
counter := 0;
lm := new List<Pixel>();
while(counter < width*3) do
begin
p := new Pixel(portion[counter+2], portion[counter+1], portion[counter]);
lm.Add(p);
counter += 3;
end;
l.Add(lm);
end;
Result := l;
end;
procedure SetPixelsByteArray(var RowData: array of byte; PixelsArray: array of byte);
begin
if((RowData.Length-offsetToPixels) < PixelsArray.Length) then
begin
var newRowData : array of byte;
newRowData := new byte[PixelsArray.Length+offsetToPixels];
System.Array.Copy(RowData, 0, newRowData, 0, RowData.Length);
RowData := newRowData;
Memory.SetCardinalFromPointer(@RowData[WIDTH_OFFSET], width);
Memory.SetCardinalFromPointer(@RowData[HEIGHT_OFFSET], height);
Memory.SetWordFromPointer(@RowData[SIZEIMAGE_OFFSET], PixelsArray.Length);
end;
for i : cardinal := 0 to totalPixelsBytesCount-1 do
RowData[offsetToPixels+i] := PixelsArray[i];
end;
procedure SavePixels(var RowData : array of byte; pixels : List<List<Pixel>>);
var
res : array of byte;
currentPixel : array of byte;
counter : integer;
begin
res := new byte[((width*3)+additional)*height];
foreach ps : List<Pixel> in pixels do
begin
foreach p : Pixel in ps do
begin
currentPixel := p.getBytes();
res[counter] := currentPixel[0];
res[counter+1] := currentPixel[1];
res[counter+2] := currentPixel[2];
counter += 3;
end;
counter += additional;
end;
SetPixelsByteArray(RowData, res);
end;
function CheckBMPType(RowData: array of byte): WORD;
begin
Result := GetWordFromPointer(@RowData[TYPE_OFFSET]);
end;
function GetBitcount(RowData : array of byte) : WORD;
begin
Result := GetWordFromPointer(@RowData[BIT_COUNT_OFFSET]);
end;
function GetSizeimage(RowData : array of byte) : cardinal;
begin
Result := GetWordFromPointer(@RowData[SIZEIMAGE_OFFSET]);
sizeimage := Result;
end;
function GetPixelsByteArray(RowData: array of byte): array of byte;
var
ret: array of byte;
begin
offsetToPixels := GetCardinalFromPointer(@RowData[PIXELS_OFFSET]);
totalPixelsBytesCount := Length(RowData) - offsetToPixels;
SetLength(ret, totalPixelsBytesCount);
for i: cardinal := offsetToPixels to Length(RowData) - 1 do
ret[i - offsetToPixels] := RowData[i];
Result := ret;
end;
procedure GetPictureData(RowData : array of byte);
begin
width := GetCardinalFromPointer(@RowData[WIDTH_OFFSET]);
height := GetCardinalFromPointer(@RowData[HEIGHT_OFFSET]);
additional := width mod 4;
end;
function ConcatPixels(first : List<List<Pixel>>; second : List<List<Pixel>>; third : List<List<Pixel>>; orig : List<List<Pixel>>) : List<List<Pixel>>;
var
newPixels : List<List<Pixel>>;
tmpList : List<Pixel>;
begin
newPixels := new List<List<Pixel>>;
for i : integer := 0 to (height*2)-1 do
begin
tmpList := new List<Pixel>();
newPixels.Add(tmpList);
for j : integer := 0 to (width*2)-1 do
tmpList.Add(new Pixel(0, 0, 0));
end;
for i : integer := 0 to height-1 do
for j : integer := 0 to width-1 do
newPixels[i][j] := first[i][j];
for i : integer := 0 to height-1 do
for j : integer := 0 to width-1 do
newPixels[i][j+width] := second[i][j];
for i : integer := 0 to height-1 do
for j : integer := 0 to width-1 do
newPixels[i+height][j] := third[i][j];
for i : integer := 0 to height-1 do
for j : integer := 0 to width-1 do
newPixels[i+height][j+width] := orig[i][j];
Result := newPixels;
end;
begin
end. |
{***************************************************************}
{ Copyright (c) 2013 год . }
{ Тетенев Леонид Петрович, ltetenev@yandex.ru }
{ }
{***************************************************************}
unit RecordClients;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, RecordEdit, FIBDatabase, pFIBDatabase, FIBQuery, pFIBQuery, pFIBStoredProc,
Vcl.PlatformDefaultStyleActnCtrls, Vcl.Menus, Vcl.ActnPopup, Vcl.ExtCtrls, DlgExecute, RegSmartDlg, AddActions,
Vcl.ActnList, Vcl.ToolWin, Vcl.ActnMan, Vcl.ActnCtrls, GridDlg, Vcl.ComCtrls, DlgParams;
type
TfrRecordClients = class(TfrRecordEdit)
A_NewFirm: TAction;
A_EditFirm: TAction;
IBTr_Clients: TpFIBTransaction;
procedure A_EditFirmExecute(Sender: TObject);
procedure A_NewFirmExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure SmartDlgShowDialog(Dlg: TComponent; Info: TPropertyItem; const EditRect: TRect);
procedure SmartDlgSetEditText(Dlg: TObject; CurrItem: TPropertyItem; IsChange: Boolean);
procedure FormCreate(Sender: TObject);
procedure A_SaveExecute(Sender: TObject); override;
private
{ Private declarations }
ClientIsChange: Boolean;
public
{ Public declarations }
procedure FillDialogMenu; override;
end;
implementation
{$R *.dfm}
uses
CustomForm, ConstList, ClientsList, Prima, ClientsListBox, ClientDM, SqlTools;
procedure TfrRecordClients.A_EditFirmExecute(Sender: TObject);
var
CurrItem: TPropertyItem;
FieldName: String;
begin
inherited;
if not ( A_EditFirm.Visible and A_EditFirm.Enabled ) then
Exit;
CurrItem := SmartDlg.SelectedInfo;
if Assigned( CurrItem ) then
FieldName := CurrItem.FieldName
else
FieldName := '';
try
SmartDlg.SetSelectedRow( 0 );
Application.ProcessMessages;
if not ( OwnerForm is TfrClienstList ) then
Exit;
( OwnerForm as TfrClienstList ).A_EditFirmExecute( A_EditFirm );
finally
if FieldName <> '' then
SmartDlg.SetRowSelected( FieldName );
end;
end;
procedure TfrRecordClients.A_NewFirmExecute(Sender: TObject);
var
CurrItem: TPropertyItem;
FieldName: String;
begin
inherited;
if not ( A_NewFirm.Visible and A_NewFirm.Enabled ) then
Exit;
CurrItem := SmartDlg.SelectedInfo;
if Assigned( CurrItem ) then
FieldName := CurrItem.FieldName
else
FieldName := '';
try
SmartDlg.SetSelectedRow( 0 );
Application.ProcessMessages;
if not ( OwnerForm is TfrClienstList ) then
Exit;
( OwnerForm as TfrClienstList ).A_NewFirmExecute( A_NewFirm );
finally
if FieldName <> '' then
SmartDlg.SetRowSelected( FieldName );
end;
end;
procedure TfrRecordClients.A_SaveExecute(Sender: TObject);
begin
try
inherited;
finally
if ClientIsChange then begin
if OwnerForm is TfrClienstList then
( OwnerForm as TfrClienstList ).Q_Clients.FullRefresh;
end;
end;
end;
procedure TfrRecordClients.FillDialogMenu;
begin
inherited;
A_EditFirm.Visible := ( OwnerForm as TfrClienstList ).A_EditFirm.Visible;
A_NewFirm.Visible := ( OwnerForm as TfrClienstList ).A_NewFirm.Visible;
With frPrima do begin
AddInMainMenu( nil, ppDialog, A_Between, [ A_NewFirm, A_EditFirm, A_Sp ]);
AddActListInBar( aTbSmartDLG, A_SetBetween, [ A_NewFirm, A_EditFirm, A_Sp ]);
end;
end;
procedure TfrRecordClients.FormCreate(Sender: TObject);
begin
inherited;
ClientIsChange := False;
end;
procedure TfrRecordClients.FormShow(Sender: TObject);
var
CurrItem: TPropertyItem;
begin
inherited;
CurrItem := SmartDlg.RowsList.PropByHostFieldName( 'FIRM_LIST_SHORT' );
A_EditFirm.Enabled := Assigned( CurrItem ) and ( CurrItem.RowValue <> '' );
end;
procedure TfrRecordClients.SmartDlgSetEditText(Dlg: TObject; CurrItem: TPropertyItem; IsChange: Boolean);
const
sqlMails =
'select LIST_OF_CLIENT from GET_CLIENT_OF_MAIL_LINK( :CURR_CLIENT_ID, :E_MAIL_LIST )';
var
ResValues: TArrayVariant;
Item: TPropertyItem;
begin
inherited;
if not AnsiSameText( CurrItem.FieldName, 'E_MAIL_LIST' ) then
Exit;
if not IBTr_Clients.InTransaction then
IBTr_Clients.StartTransaction;
if GetQueryResult( sqlMails, [ dlgFillRows.PrimaryKeyValue, Trim( CurrItem.RowValue )], IBTr_Clients, ResValues ) then begin
Item := SmartDlg.RowsList.PropByHostFieldNameAsReadOnly( 'CLIENTS_LINK' );
if Assigned( Item ) then begin
if not VarIsNull( ResValues[ 0 ]) then
Item.RowValue := ResValues[ 0 ]
else
Item.RowValue := '';
end;
end;
SmartDlg.Refresh;
end;
procedure TfrRecordClients.SmartDlgShowDialog(Dlg: TComponent; Info: TPropertyItem; const EditRect: TRect);
var
NewClientID: Integer;
MailItem: TPropertyItem;
EList: String;
begin
inherited;
if not AnsiSameText( Info.FieldName, 'CLIENTS_LINK' ) then
Exit;
if Info.RowValue = '' then
Exit;
NewClientID := TfrClientsListBox.ShowClientsLinkMail( Self, IBTr_Clients, Info.Title, Info.RowValue, dlgFillRows.PrimaryKeyValue );
Application.ProcessMessages;
if NewClientID <> dlgFillRows.PrimaryKeyValue then begin
MailItem := SmartDlg.RowsList.PropByHostFieldNameAsReadOnly( 'E_MAIL_LIST' );
if not Assigned( MailItem ) then
Exit;
EList := MailItem.RowValue;
dlgFillRows.PrimaryKeyValue := NewClientID;
dlgFillRows.ActionType := sdEdit;
Self.Caption := TfrClienstList( OwnerForm ).A_EditClient.Caption;
dlgFillRows.FillDlgParams( DlgIdent, [ NewClientID ]);
SmartDlg.Refresh;
Application.ProcessMessages;
SmartDlg.SetRowSelected( 'E_MAIL_LIST' );
MailItem.RowValue := EList;
MailItem.OldValue := MailItem.RowValue;
SmartDlg.Editor.Text := EList;
ClientIsChange := True;
end;
end;
end.
|
unit DIOTA.IotaAPICommands;
interface
type
IIOTAAPICommand = interface
['{976C0E47-F554-4EB3-BCDF-1F8C84B56569}']
function GetCommand: String;
end;
TIOTAAPICommands = class
private
class function GetGET_NODE_INFO: IIOTAAPICommand; static;
class function GetGET_NEIGHBORS: IIOTAAPICommand; static;
class function GetADD_NEIGHBORS: IIOTAAPICommand; static;
class function GetREMOVE_NEIGHBORS: IIOTAAPICommand; static;
class function GetGET_TIPS: IIOTAAPICommand; static;
class function GetFIND_TRANSACTIONS: IIOTAAPICommand; static;
class function GetGET_TRYTES: IIOTAAPICommand; static;
class function GetGET_INCLUSIONS_STATES: IIOTAAPICommand; static;
class function GetGET_BALANCES: IIOTAAPICommand; static;
class function GetGET_TRANSACTIONS_TO_APPROVE: IIOTAAPICommand; static;
class function GetATTACH_TO_TANGLE: IIOTAAPICommand; static;
class function GetINTERRUPT_ATTACHING_TO_TANGLE: IIOTAAPICommand; static;
class function GetBROADCAST_TRANSACTIONS: IIOTAAPICommand; static;
class function GetSTORE_TRANSACTIONS: IIOTAAPICommand; static;
class function GetCHECK_CONSISTENCY: IIOTAAPICommand; static;
class function GetWERE_ADDRESSES_SPENT_FROM: IIOTAAPICommand; static;
public
class property GET_NODE_INFO: IIOTAAPICommand read GetGET_NODE_INFO;
class property GET_NEIGHBORS: IIOTAAPICommand read GetGET_NEIGHBORS;
class property ADD_NEIGHBORS: IIOTAAPICommand read GetADD_NEIGHBORS;
class property REMOVE_NEIGHBORS: IIOTAAPICommand read GetREMOVE_NEIGHBORS;
class property GET_TIPS: IIOTAAPICommand read GetGET_TIPS;
class property FIND_TRANSACTIONS: IIOTAAPICommand read GetFIND_TRANSACTIONS;
class property GET_TRYTES: IIOTAAPICommand read GetGET_TRYTES;
class property GET_INCLUSIONS_STATES: IIOTAAPICommand read GetGET_INCLUSIONS_STATES;
class property GET_BALANCES: IIOTAAPICommand read GetGET_BALANCES;
class property GET_TRANSACTIONS_TO_APPROVE: IIOTAAPICommand read GetGET_TRANSACTIONS_TO_APPROVE;
class property ATTACH_TO_TANGLE: IIOTAAPICommand read GetATTACH_TO_TANGLE;
class property INTERRUPT_ATTACHING_TO_TANGLE: IIOTAAPICommand read GetINTERRUPT_ATTACHING_TO_TANGLE;
class property BROADCAST_TRANSACTIONS: IIOTAAPICommand read GetBROADCAST_TRANSACTIONS;
class property STORE_TRANSACTIONS: IIOTAAPICommand read GetSTORE_TRANSACTIONS;
class property CHECK_CONSISTENCY: IIOTAAPICommand read GetCHECK_CONSISTENCY;
class property WERE_ADDRESSES_SPENT_FROM: IIOTAAPICommand read GetWERE_ADDRESSES_SPENT_FROM;
end;
implementation
type
TIOTAAPICommand = class(TInterfacedObject, IIOTAAPICommand)
private
FCommand: String;
public
constructor Create(command: String);
function GetCommand: String;
end;
{ TIOTAAPICommands }
class function TIOTAAPICommands.GetADD_NEIGHBORS: IIOTAAPICommand;
begin
Result := TIOTAAPICommand.Create('addNeighbors');
end;
class function TIOTAAPICommands.GetATTACH_TO_TANGLE: IIOTAAPICommand;
begin
Result := TIOTAAPICommand.Create('attachToTangle');
end;
class function TIOTAAPICommands.GetBROADCAST_TRANSACTIONS: IIOTAAPICommand;
begin
Result := TIOTAAPICommand.Create('broadcastTransactions');
end;
class function TIOTAAPICommands.GetCHECK_CONSISTENCY: IIOTAAPICommand;
begin
Result := TIOTAAPICommand.Create('checkConsistency');
end;
class function TIOTAAPICommands.GetFIND_TRANSACTIONS: IIOTAAPICommand;
begin
Result := TIOTAAPICommand.Create('findTransactions');
end;
class function TIOTAAPICommands.GetGET_BALANCES: IIOTAAPICommand;
begin
Result := TIOTAAPICommand.Create('getBalances');
end;
class function TIOTAAPICommands.GetGET_INCLUSIONS_STATES: IIOTAAPICommand;
begin
Result := TIOTAAPICommand.Create('getInclusionStates');
end;
class function TIOTAAPICommands.GetGET_NEIGHBORS: IIOTAAPICommand;
begin
Result := TIOTAAPICommand.Create('getNeighbors');
end;
class function TIOTAAPICommands.GetGET_NODE_INFO: IIOTAAPICommand;
begin
Result := TIOTAAPICommand.Create('getNodeInfo');
end;
class function TIOTAAPICommands.GetGET_TIPS: IIOTAAPICommand;
begin
Result := TIOTAAPICommand.Create('getTips');
end;
class function TIOTAAPICommands.GetGET_TRANSACTIONS_TO_APPROVE: IIOTAAPICommand;
begin
Result := TIOTAAPICommand.Create('getTransactionsToApprove');
end;
class function TIOTAAPICommands.GetGET_TRYTES: IIOTAAPICommand;
begin
Result := TIOTAAPICommand.Create('getTrytes');
end;
class function TIOTAAPICommands.GetINTERRUPT_ATTACHING_TO_TANGLE: IIOTAAPICommand;
begin
Result := TIOTAAPICommand.Create('interruptAttachingToTangle');
end;
class function TIOTAAPICommands.GetREMOVE_NEIGHBORS: IIOTAAPICommand;
begin
Result := TIOTAAPICommand.Create('removeNeighbors');
end;
class function TIOTAAPICommands.GetSTORE_TRANSACTIONS: IIOTAAPICommand;
begin
Result := TIOTAAPICommand.Create('storeTransactions');
end;
class function TIOTAAPICommands.GetWERE_ADDRESSES_SPENT_FROM: IIOTAAPICommand;
begin
Result := TIOTAAPICommand.Create('wereAddressesSpentFrom');
end;
{ TIOTAAPICommand }
constructor TIOTAAPICommand.Create(command: String);
begin
FCommand := command;
end;
function TIOTAAPICommand.GetCommand: String;
begin
Result := FCommand;
end;
end.
|
unit CnMatrixWord;
interface
uses
SysUtils, Classes, Windows, Grids;
type
TCnSearchDirection = (sdUp, sdUpLeft, sdLeft, sdLeftDown, sdDown, sdDownRight, sdRight, sdRightUp);
TCnSearchDirections = set of TCnSearchDirection;
TCnSearchResult = array of TPoint;
TCnMatrixWord = class(TObject)
private
FWidth: Integer;
FHeight: Integer;
FChars: TStrings;
FSearchDirections: TCnSearchDirections;
procedure SetSearchDirections(const Value: TCnSearchDirections);
function GetChars(X, Y: Integer): Char;
function GetHeight: Integer;
function GetWidth: Integer;
procedure ReCalc;
public
constructor Create;
destructor Destroy; override;
function Search(const Str: string; out ResultPoint: TPoint; out Direction: TCnSearchDirection): Boolean;
procedure LoadFromStrings(Strings: TStrings);
procedure LoadFromFile(const AFile: string);
procedure DumpToGrid(AGrid: TStringGrid);
property Chars[X, Y: Integer]: Char read GetChars;
property SearchDirections: TCnSearchDirections read FSearchDirections write SetSearchDirections;
property Width: Integer read GetWidth;
property Height: Integer read GetHeight;
end;
implementation
{ TCnMatrixWord }
constructor TCnMatrixWord.Create;
begin
FChars := TStringList.Create;
FSearchDirections := [sdUp, sdUpLeft, sdLeft, sdLeftDown, sdDown, sdDownRight, sdRight, sdRightUp];
end;
destructor TCnMatrixWord.Destroy;
begin
FChars.Free;
end;
procedure TCnMatrixWord.DumpToGrid(AGrid: TStringGrid);
var
Col, Row, L: Integer;
S: string;
begin
AGrid.ColCount := FWidth;
AGrid.RowCount := FHeight;
for Row := 0 to AGrid.RowCount - 1 do
for Col := 0 to AGrid.ColCount - 1 do
AGrid.Cells[Col, Row] := '';
for Row := 0 to AGrid.RowCount - 1 do
begin
S := FChars[Row];
L := Length(S) - 1;
for Col := 0 to AGrid.ColCount - 1 do
if Col <= L then
AGrid.Cells[Col, Row] := S[Col + 1];
end;
end;
function TCnMatrixWord.GetChars(X, Y: Integer): Char;
var
S: string;
begin
// 第 Y 行的第 X 个字符,X Y 均从 1 开始
if (Y < 1) or (Y > FChars.Count) then
raise Exception.Create('Y is out of bounds ' + IntToStr(Y));
S := FChars[Y - 1];
if (X < 1) or (X > Length(S)) then
raise Exception.Create('X is out of bounds ' + IntToStr(X));
Result := S[X];
end;
function TCnMatrixWord.GetHeight: Integer;
begin
Result := FHeight;
end;
function TCnMatrixWord.GetWidth: Integer;
begin
Result := FWidth;
end;
procedure TCnMatrixWord.LoadFromFile(const AFile: string);
begin
if FileExists(AFile) then
begin
FChars.LoadFromFile(AFile);
ReCalc;
end;
end;
procedure TCnMatrixWord.LoadFromStrings(Strings: TStrings);
begin
if Strings <> nil then
begin
FChars.Assign(Strings);
ReCalc;
end;
end;
procedure TCnMatrixWord.ReCalc;
var
I: Integer;
begin
FHeight := FChars.Count;
FWidth := 0;
for I := 0 to FChars.Count - 1 do
if Length(FChars[I]) > FWidth then
FWidth := Length(FChars[I]);
end;
function TCnMatrixWord.Search(const Str: string; out ResultPoint: TPoint;
out Direction: TCnSearchDirection): Boolean;
var
L: Integer;
C: Char;
F: Boolean;
function GetNextChar(OrigX, OrigY, Offset: Integer; Dir: TCnSearchDirection): Char;
begin
case Dir of // 第 Y 行的第 X 个字符偏 I
sdUp: Result := GetChars(OrigX, OrigY - Offset);
sdUpLeft: Result := GetChars(OrigX - Offset, OrigY - Offset);
sdLeft: Result := GetChars(OrigX - Offset, OrigY);
sdLeftDown: Result := GetChars(OrigX - Offset, OrigY + Offset);
sdDown: Result := GetChars(OrigX, OrigY + Offset);
sdDownRight: Result := GetChars(OrigX + Offset, OrigY + Offset);
sdRight: Result := GetChars(OrigX + Offset, OrigY);
sdRightUp: Result := GetChars(OrigX + Offset, OrigY - Offset);
else
Result := #0;
end;
end;
function SearchInDirection(Dir: TCnSearchDirection): Boolean;
var
I, X, Y: Integer;
begin
Result := False;
for X := 1 to FWidth do
begin
for Y := 1 to FHeight do
begin
try
C := GetChars(X, Y);
if C = Str[1] then
begin
F := True;
for I := 2 to L do
begin
try
C := GetNextChar(X, Y, I - 1, Dir);
if C <> Str[I] then
begin
F := False;
Break;
end;
except
F := False;
Break;
end;
end;
if F then
begin
Result := True;
ResultPoint.x := X;
ResultPoint.y := Y;
Direction := Dir;
end;
end;
except
Continue;
end;
end;
end;
end;
begin
Result := False;
L := Length(Str);
if L < 1 then
Exit;
if (sdUp in FSearchDirections) and SearchInDirection(sdUp) then
Result := True;
if (sdUpLeft in FSearchDirections) and SearchInDirection(sdUpLeft) then
Result := True;
if (sdLeft in FSearchDirections) and SearchInDirection(sdLeft) then
Result := True;
if (sdLeftDown in FSearchDirections) and SearchInDirection(sdLeftDown) then
Result := True;
if (sdDown in FSearchDirections) and SearchInDirection(sdDown) then
Result := True;
if (sdDownRight in FSearchDirections) and SearchInDirection(sdDownRight) then
Result := True;
if (sdRight in FSearchDirections) and SearchInDirection(sdRight) then
Result := True;
if (sdRightUp in FSearchDirections) and SearchInDirection(sdRightUp) then
Result := True;
end;
procedure TCnMatrixWord.SetSearchDirections(
const Value: TCnSearchDirections);
begin
FSearchDirections := Value;
end;
end.
|
{**************************************************************************************}
{ }
{ CCR.PrefsIniFile: CreateUserPreferencesIniFile function }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 }
{ (the "License"); you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT }
{ WARRANTY OF ANY KIND, either express or implied. See the License for the specific }
{ language governing rights and limitations under the License. }
{ }
{ The Initial Developer of the Original Code is Chris Rolliston. Portions created by }
{ Chris Rolliston are Copyright (C) 2013-15 Chris Rolliston. All Rights Reserved. }
{ }
{**************************************************************************************}
unit CCR.PrefsIniFile;
interface
uses
System.SysUtils, System.IniFiles;
{$SCOPEDENUMS ON}
type
TWinLocation = (IniFile, Registry);
function CreateUserPreferencesIniFile(AWinLocation: TWinLocation = TWinLocation.Registry): TCustomIniFile;
implementation
{$IFDEF ANDROID}
uses CCR.PrefsIniFile.Android;
function CreateUserPreferencesIniFile(AWinLocation: TWinLocation): TCustomIniFile;
begin
Result := TAndroidPreferencesIniFile.Create;
end;
{$ENDIF}
{$IFDEF MACOS}
uses CCR.PrefsIniFile.Apple;
function CreateUserPreferencesIniFile(AWinLocation: TWinLocation): TCustomIniFile;
begin
Result := TApplePreferencesIniFile.Create;
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
uses Winapi.Windows, System.Win.Registry;
function CreateUserPreferencesIniFile(AWinLocation: TWinLocation = TWinLocation.Registry): TCustomIniFile;
var
CompanyName, ProductName, Path: string;
{$IFDEF MSWINDOWS}
Handle, Len: DWORD;
Data: TBytes;
CP: PWordArray;
CharPtr: PChar;
{$ENDIF}
begin
Path := GetModuleName(0);
ProductName := ChangeFileExt(ExtractFileName(Path), '');
{$IFDEF MSWINDOWS}
SetLength(Data, GetFileVersionInfoSize(PChar(Path), Handle));
if GetFileVersionInfo(PChar(Path), Handle, Length(Data), Data) and
VerQueryValue(Data, 'VarFileInfo\Translation', Pointer(CP), Len) then
begin
FmtStr(Path, 'StringFileInfo\%.4x%.4x\', [CP[0], CP[1]]);
if VerQueryValue(Data, PChar(Path + 'CompanyName'), Pointer(CharPtr), Len) then
SetString(CompanyName, CharPtr, Len - 1);
if VerQueryValue(Data, PChar(Path + 'ProductName'), Pointer(CharPtr), Len) then
SetString(ProductName, CharPtr, Len - 1);
end;
{$ENDIF}
if CompanyName = '' then
Path := ProductName
else
Path := CompanyName + PathDelim + ProductName;
{$IF DECLARED(TRegistryIniFile)}
if AWinLocation = TWinLocation.Registry then
begin
Result := TRegistryIniFile.Create('Software\' + Path);
Exit;
end;
{$IFEND}
Path := IncludeTrailingPathDelimiter(GetHomePath) + Path;
ForceDirectories(Path);
Result := TMemIniFile.Create(Path + PathDelim + 'Preferences.ini', TEncoding.UTF8);
end;
{$ENDIF}
end. |
unit dumpjavamethods;
{$mode delphi}
interface
uses
Classes, SysUtils, And_jni, AndroidWidget;
type
{Draft Component code by "Lazarus Android Module Wizard" [5/1/2014 21:10:39]}
{https://github.com/jmpessoa/lazandroidmodulewizard}
{jControl template}
jDumpJavaMethods = class(jControl)
private
FfullJavaClassName: string;
FObjReferenceName: string;
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Init; override;
function jCreate( _fullJavaClassName: string): jObject;
procedure jFree();
function GetMethodFullSignatureList(): string;
function GetMethodImplementationList(): string;
procedure SetStripFullTypeName(_stripFullTypeName: boolean);
function GetStripFullTypeName(): boolean;
procedure SetFullJavaClassName(_fullJavaClassName: string);
function GetFullJavaClassName(): string;
procedure SetObjReferenceName(_objReferenceName: string);
function GetObjReferenceName(): string;
procedure SetDelimiter(_delimiter: string);
function GetDelimiter(): string;
function GetMethodHeaderList(): string;
function GetMethodHeaderListSize(): integer;
function GetMethodHeaderByIndex(_index: integer): string;
procedure MaskMethodHeaderByIndex(_index: integer);
procedure UnMaskMethodHeaderByIndex(_index: integer);
function GetNoMaskedMethodHeaderList(): string;
function Extract(): string; overload;
function Extract(_fullJavaClassName: string; _delimiter: string): string; overload;
function GetNoMaskedMethodImplementationByIndex(_index: integer): string;
function GetNoMaskedMethodImplementationListSize(): integer;
function GetNoMaskedMethodImplementationList(): string;
published
property FullJavaClassName: string read GetFullJavaClassName write SetFullJavaClassName;
property ObjReferenceName: string read GetObjReferenceName write SetObjReferenceName;
end;
function jDumpJavaMethods_jCreate(env: PJNIEnv; this: JObject;_Self: int64; _fullJavaClassName: string): jObject;
procedure jDumpJavaMethods_jFree(env: PJNIEnv; _jdumpjavamethods: JObject);
function jDumpJavaMethods_GetMethodFullSignatureList(env: PJNIEnv; _jdumpjavamethods: JObject): string;
function jDumpJavaMethods_GetMethodImplementationList(env: PJNIEnv; _jdumpjavamethods: JObject): string;
procedure jDumpJavaMethods_SetStripFullTypeName(env: PJNIEnv; _jdumpjavamethods: JObject; _stripFullTypeName: boolean);
function jDumpJavaMethods_GetStripFullTypeName(env: PJNIEnv; _jdumpjavamethods: JObject): boolean;
procedure jDumpJavaMethods_SetFullJavaClassName(env: PJNIEnv; _jdumpjavamethods: JObject; _fullJavaClassName: string);
function jDumpJavaMethods_GetFullJavaClassName(env: PJNIEnv; _jdumpjavamethods: JObject): string;
procedure jDumpJavaMethods_SetObjReferenceName(env: PJNIEnv; _jdumpjavamethods: JObject; _objReferenceName: string);
function jDumpJavaMethods_GetObjReferenceName(env: PJNIEnv; _jdumpjavamethods: JObject): string;
procedure jDumpJavaMethods_SetDelimiter(env: PJNIEnv; _jdumpjavamethods: JObject; _delimiter: string);
function jDumpJavaMethods_GetDelimiter(env: PJNIEnv; _jdumpjavamethods: JObject): string;
function jDumpJavaMethods_GetMethodHeaderList(env: PJNIEnv; _jdumpjavamethods: JObject): string;
function jDumpJavaMethods_GetMethodHeaderListSize(env: PJNIEnv; _jdumpjavamethods: JObject): integer;
function jDumpJavaMethods_GetMethodHeaderByIndex(env: PJNIEnv; _jdumpjavamethods: JObject; _index: integer): string;
procedure jDumpJavaMethods_MaskMethodHeaderByIndex(env: PJNIEnv; _jdumpjavamethods: JObject; _index: integer);
procedure jDumpJavaMethods_UnMaskMethodHeaderByIndex(env: PJNIEnv; _jdumpjavamethods: JObject; _index: integer);
function jDumpJavaMethods_GetNoMaskedMethodHeaderList(env: PJNIEnv; _jdumpjavamethods: JObject): string;
function jDumpJavaMethods_Extract(env: PJNIEnv; _jdumpjavamethods: JObject): string; overload;
function jDumpJavaMethods_Extract(env: PJNIEnv; _jdumpjavamethods: JObject; _fullJavaClassName: string; _delimiter: string): string; overload;
function jDumpJavaMethods_GetNoMaskedMethodImplementationByIndex(env: PJNIEnv; _jdumpjavamethods: JObject; _index: integer): string;
function jDumpJavaMethods_GetNoMaskedMethodImplementationListSize(env: PJNIEnv; _jdumpjavamethods: JObject): integer;
function jDumpJavaMethods_GetNoMaskedMethodImplementationList(env: PJNIEnv; _jdumpjavamethods: JObject): string;
implementation
{--------- jDumpJavaMethods --------------}
constructor jDumpJavaMethods.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
//your code here....
FfullJavaClassName:= 'android.media.MediaPlayer';
end;
destructor jDumpJavaMethods.Destroy;
begin
if not (csDesigning in ComponentState) then
begin
if FjObject <> nil then
begin
jFree();
FjObject:= nil;
end;
end;
//you others free code here...'
inherited Destroy;
end;
procedure jDumpJavaMethods.Init;
begin
if FInitialized then Exit;
inherited Init;
//your code here: set/initialize create params....
if FfullJavaClassName = '' then FfullJavaClassName:= 'android.media.MediaPlayer';
FjObject:= jCreate(FfullJavaClassName);
if FjObject = nil then exit;
FInitialized:= True;
if FObjReferenceName <> '' then //others initializations...
SetObjReferenceName(FObjReferenceName);
end;
function jDumpJavaMethods.jCreate( _fullJavaClassName: string): jObject;
begin
Result:= jDumpJavaMethods_jCreate(gApp.jni.jEnv, gApp.jni.jThis , int64(Self) ,_fullJavaClassName);
end;
procedure jDumpJavaMethods.jFree();
begin
//in designing component state: set value here...
if FInitialized then
jDumpJavaMethods_jFree(gApp.jni.jEnv, FjObject);
end;
function jDumpJavaMethods.GetMethodFullSignatureList(): string;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jDumpJavaMethods_GetMethodFullSignatureList(gApp.jni.jEnv, FjObject);
end;
function jDumpJavaMethods.GetMethodImplementationList(): string;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jDumpJavaMethods_GetMethodImplementationList(gApp.jni.jEnv, FjObject);
end;
procedure jDumpJavaMethods.SetStripFullTypeName(_stripFullTypeName: boolean);
begin
//in designing component state: set value here...
if FInitialized then
jDumpJavaMethods_SetStripFullTypeName(gApp.jni.jEnv, FjObject, _stripFullTypeName);
end;
function jDumpJavaMethods.GetStripFullTypeName(): boolean;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jDumpJavaMethods_GetStripFullTypeName(gApp.jni.jEnv, FjObject);
end;
procedure jDumpJavaMethods.SetFullJavaClassName(_fullJavaClassName: string);
begin
//in designing component state: set value here...
FfullJavaClassName:= _fullJavaClassName;
if FInitialized then
jDumpJavaMethods_SetFullJavaClassName(gApp.jni.jEnv, FjObject, _fullJavaClassName);
end;
function jDumpJavaMethods.GetFullJavaClassName(): string;
begin
//in designing component state: result value here...
Result:= FfullJavaClassName;
if FInitialized then
Result:= jDumpJavaMethods_GetFullJavaClassName(gApp.jni.jEnv, FjObject);
end;
procedure jDumpJavaMethods.SetObjReferenceName(_objReferenceName: string);
begin
//in designing component state: set value here...
FObjReferenceName:= _objReferenceName;
if FInitialized then
jDumpJavaMethods_SetObjReferenceName(gApp.jni.jEnv, FjObject, _objReferenceName);
end;
function jDumpJavaMethods.GetObjReferenceName(): string;
begin
//in designing component state: result value here...
Result:= FObjReferenceName;
if FInitialized then
Result:= jDumpJavaMethods_GetObjReferenceName(gApp.jni.jEnv, FjObject);
end;
procedure jDumpJavaMethods.SetDelimiter(_delimiter: string);
begin
//in designing component state: set value here...
if FInitialized then
jDumpJavaMethods_SetDelimiter(gApp.jni.jEnv, FjObject, _delimiter);
end;
function jDumpJavaMethods.GetDelimiter(): string;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jDumpJavaMethods_GetDelimiter(gApp.jni.jEnv, FjObject);
end;
function jDumpJavaMethods.GetMethodHeaderList(): string;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jDumpJavaMethods_GetMethodHeaderList(gApp.jni.jEnv, FjObject);
end;
function jDumpJavaMethods.GetMethodHeaderListSize(): integer;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jDumpJavaMethods_GetMethodHeaderListSize(gApp.jni.jEnv, FjObject);
end;
function jDumpJavaMethods.GetMethodHeaderByIndex(_index: integer): string;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jDumpJavaMethods_GetMethodHeaderByIndex(gApp.jni.jEnv, FjObject, _index);
end;
procedure jDumpJavaMethods.MaskMethodHeaderByIndex(_index: integer);
begin
//in designing component state: set value here...
if FInitialized then
jDumpJavaMethods_MaskMethodHeaderByIndex(gApp.jni.jEnv, FjObject, _index);
end;
procedure jDumpJavaMethods.UnMaskMethodHeaderByIndex(_index: integer);
begin
//in designing component state: set value here...
if FInitialized then
jDumpJavaMethods_UnMaskMethodHeaderByIndex(gApp.jni.jEnv, FjObject, _index);
end;
function jDumpJavaMethods.GetNoMaskedMethodHeaderList(): string;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jDumpJavaMethods_GetNoMaskedMethodHeaderList(gApp.jni.jEnv, FjObject);
end;
function jDumpJavaMethods.Extract(): string;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jDumpJavaMethods_Extract(gApp.jni.jEnv, FjObject);
end;
function jDumpJavaMethods.Extract(_fullJavaClassName: string; _delimiter: string): string;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jDumpJavaMethods_Extract(gApp.jni.jEnv, FjObject, _fullJavaClassName ,_delimiter);
end;
function jDumpJavaMethods.GetNoMaskedMethodImplementationByIndex(_index: integer): string;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jDumpJavaMethods_GetNoMaskedMethodImplementationByIndex(gApp.jni.jEnv, FjObject, _index);
end;
function jDumpJavaMethods.GetNoMaskedMethodImplementationListSize(): integer;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jDumpJavaMethods_GetNoMaskedMethodImplementationListSize(gApp.jni.jEnv, FjObject);
end;
function jDumpJavaMethods.GetNoMaskedMethodImplementationList(): string;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jDumpJavaMethods_GetNoMaskedMethodImplementationList(gApp.jni.jEnv, FjObject);
end;
{-------- jDumpJavaMethods_JNI_Bridge ----------}
function jDumpJavaMethods_jCreate(env: PJNIEnv; this: JObject;_Self: int64; _fullJavaClassName: string): jObject;
var
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].j:= _Self;
jParams[1].l:= env^.NewStringUTF(env, PChar(_fullJavaClassName));
jCls:= Get_gjClass(env);
jMethod:= env^.GetMethodID(env, jCls, 'jDumpJavaMethods_jCreate', '(JLjava/lang/String;)Ljava/lang/Object;');
Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams);
Result:= env^.NewGlobalRef(env, Result);
env^.DeleteLocalRef(env,jParams[1].l);
end;
(*
//Please, you need insert:
public java.lang.Object jDumpJavaMethods_jCreate(long _Self, String _fullJavaClassName) {
return (java.lang.Object)(new jDumpJavaMethods(this,_Self,_fullJavaClassName));
}
//to end of "public class Controls" in "Controls.java"
*)
procedure jDumpJavaMethods_jFree(env: PJNIEnv; _jdumpjavamethods: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jdumpjavamethods);
jMethod:= env^.GetMethodID(env, jCls, 'jFree', '()V');
env^.CallVoidMethod(env, _jdumpjavamethods, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
function jDumpJavaMethods_GetMethodFullSignatureList(env: PJNIEnv; _jdumpjavamethods: JObject): string;
var
jStr: JString;
jBoo: JBoolean;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jdumpjavamethods);
jMethod:= env^.GetMethodID(env, jCls, 'GetMethodFullSignatureList', '()Ljava/lang/String;');
jStr:= env^.CallObjectMethod(env, _jdumpjavamethods, jMethod);
case jStr = nil of
True : Result:= '';
False: begin
jBoo:= JNI_False;
Result:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
env^.DeleteLocalRef(env, jCls);
end;
function jDumpJavaMethods_GetMethodImplementationList(env: PJNIEnv; _jdumpjavamethods: JObject): string;
var
jStr: JString;
jBoo: JBoolean;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jdumpjavamethods);
jMethod:= env^.GetMethodID(env, jCls, 'GetMethodImplementationList', '()Ljava/lang/String;');
jStr:= env^.CallObjectMethod(env, _jdumpjavamethods, jMethod);
case jStr = nil of
True : Result:= '';
False: begin
jBoo:= JNI_False;
Result:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
env^.DeleteLocalRef(env, jCls);
end;
procedure jDumpJavaMethods_SetStripFullTypeName(env: PJNIEnv; _jdumpjavamethods: JObject; _stripFullTypeName: boolean);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].z:= JBool(_stripFullTypeName);
jCls:= env^.GetObjectClass(env, _jdumpjavamethods);
jMethod:= env^.GetMethodID(env, jCls, 'SetStripFullTypeName', '(Z)V');
env^.CallVoidMethodA(env, _jdumpjavamethods, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
function jDumpJavaMethods_GetStripFullTypeName(env: PJNIEnv; _jdumpjavamethods: JObject): boolean;
var
jBoo: JBoolean;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jdumpjavamethods);
jMethod:= env^.GetMethodID(env, jCls, 'GetStripFullTypeName', '()Z');
jBoo:= env^.CallBooleanMethod(env, _jdumpjavamethods, jMethod);
Result:= boolean(jBoo);
env^.DeleteLocalRef(env, jCls);
end;
procedure jDumpJavaMethods_SetFullJavaClassName(env: PJNIEnv; _jdumpjavamethods: JObject; _fullJavaClassName: string);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_fullJavaClassName));
jCls:= env^.GetObjectClass(env, _jdumpjavamethods);
jMethod:= env^.GetMethodID(env, jCls, 'SetFullJavaClassName', '(Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jdumpjavamethods, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
function jDumpJavaMethods_GetFullJavaClassName(env: PJNIEnv; _jdumpjavamethods: JObject): string;
var
jStr: JString;
jBoo: JBoolean;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jdumpjavamethods);
jMethod:= env^.GetMethodID(env, jCls, 'GetFullJavaClassName', '()Ljava/lang/String;');
jStr:= env^.CallObjectMethod(env, _jdumpjavamethods, jMethod);
case jStr = nil of
True : Result:= '';
False: begin
jBoo:= JNI_False;
Result:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
env^.DeleteLocalRef(env, jCls);
end;
procedure jDumpJavaMethods_SetObjReferenceName(env: PJNIEnv; _jdumpjavamethods: JObject; _objReferenceName: string);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_objReferenceName));
jCls:= env^.GetObjectClass(env, _jdumpjavamethods);
jMethod:= env^.GetMethodID(env, jCls, 'SetObjReferenceName', '(Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jdumpjavamethods, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
function jDumpJavaMethods_GetObjReferenceName(env: PJNIEnv; _jdumpjavamethods: JObject): string;
var
jStr: JString;
jBoo: JBoolean;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jdumpjavamethods);
jMethod:= env^.GetMethodID(env, jCls, 'GetObjReferenceName', '()Ljava/lang/String;');
jStr:= env^.CallObjectMethod(env, _jdumpjavamethods, jMethod);
case jStr = nil of
True : Result:= '';
False: begin
jBoo:= JNI_False;
Result:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
env^.DeleteLocalRef(env, jCls);
end;
procedure jDumpJavaMethods_SetDelimiter(env: PJNIEnv; _jdumpjavamethods: JObject; _delimiter: string);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_delimiter));
jCls:= env^.GetObjectClass(env, _jdumpjavamethods);
jMethod:= env^.GetMethodID(env, jCls, 'SetDelimiter', '(Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jdumpjavamethods, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
function jDumpJavaMethods_GetDelimiter(env: PJNIEnv; _jdumpjavamethods: JObject): string;
var
jStr: JString;
jBoo: JBoolean;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jdumpjavamethods);
jMethod:= env^.GetMethodID(env, jCls, 'GetDelimiter', '()Ljava/lang/String;');
jStr:= env^.CallObjectMethod(env, _jdumpjavamethods, jMethod);
case jStr = nil of
True : Result:= '';
False: begin
jBoo:= JNI_False;
Result:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
env^.DeleteLocalRef(env, jCls);
end;
function jDumpJavaMethods_GetMethodHeaderList(env: PJNIEnv; _jdumpjavamethods: JObject): string;
var
jStr: JString;
jBoo: JBoolean;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jdumpjavamethods);
jMethod:= env^.GetMethodID(env, jCls, 'GetMethodHeaderList', '()Ljava/lang/String;');
jStr:= env^.CallObjectMethod(env, _jdumpjavamethods, jMethod);
case jStr = nil of
True : Result:= '';
False: begin
jBoo:= JNI_False;
Result:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
env^.DeleteLocalRef(env, jCls);
end;
function jDumpJavaMethods_GetMethodHeaderListSize(env: PJNIEnv; _jdumpjavamethods: JObject): integer;
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jdumpjavamethods);
jMethod:= env^.GetMethodID(env, jCls, 'GetMethodHeaderListSize', '()I');
Result:= env^.CallIntMethod(env, _jdumpjavamethods, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
function jDumpJavaMethods_GetMethodHeaderByIndex(env: PJNIEnv; _jdumpjavamethods: JObject; _index: integer): string;
var
jStr: JString;
jBoo: JBoolean;
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _index;
jCls:= env^.GetObjectClass(env, _jdumpjavamethods);
jMethod:= env^.GetMethodID(env, jCls, 'GetMethodHeaderByIndex', '(I)Ljava/lang/String;');
jStr:= env^.CallObjectMethodA(env, _jdumpjavamethods, jMethod, @jParams);
case jStr = nil of
True : Result:= '';
False: begin
jBoo:= JNI_False;
Result:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
env^.DeleteLocalRef(env, jCls);
end;
procedure jDumpJavaMethods_MaskMethodHeaderByIndex(env: PJNIEnv; _jdumpjavamethods: JObject; _index: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _index;
jCls:= env^.GetObjectClass(env, _jdumpjavamethods);
jMethod:= env^.GetMethodID(env, jCls, 'MaskMethodHeaderByIndex', '(I)V');
env^.CallVoidMethodA(env, _jdumpjavamethods, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jDumpJavaMethods_UnMaskMethodHeaderByIndex(env: PJNIEnv; _jdumpjavamethods: JObject; _index: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _index;
jCls:= env^.GetObjectClass(env, _jdumpjavamethods);
jMethod:= env^.GetMethodID(env, jCls, 'UnMaskMethodHeaderByIndex', '(I)V');
env^.CallVoidMethodA(env, _jdumpjavamethods, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
function jDumpJavaMethods_GetNoMaskedMethodHeaderList(env: PJNIEnv; _jdumpjavamethods: JObject): string;
var
jStr: JString;
jBoo: JBoolean;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jdumpjavamethods);
jMethod:= env^.GetMethodID(env, jCls, 'GetNoMaskedMethodHeaderList', '()Ljava/lang/String;');
jStr:= env^.CallObjectMethod(env, _jdumpjavamethods, jMethod);
case jStr = nil of
True : Result:= '';
False: begin
jBoo:= JNI_False;
Result:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
env^.DeleteLocalRef(env, jCls);
end;
function jDumpJavaMethods_Extract(env: PJNIEnv; _jdumpjavamethods: JObject): string;
var
jStr: JString;
jBoo: JBoolean;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jdumpjavamethods);
jMethod:= env^.GetMethodID(env, jCls, 'Extract', '()Ljava/lang/String;');
jStr:= env^.CallObjectMethod(env, _jdumpjavamethods, jMethod);
case jStr = nil of
True : Result:= '';
False: begin
jBoo:= JNI_False;
Result:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
env^.DeleteLocalRef(env, jCls);
end;
function jDumpJavaMethods_Extract(env: PJNIEnv; _jdumpjavamethods: JObject; _fullJavaClassName: string; _delimiter: string): string;
var
jStr: JString;
jBoo: JBoolean;
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_fullJavaClassName));
jParams[1].l:= env^.NewStringUTF(env, PChar(_delimiter));
jCls:= env^.GetObjectClass(env, _jdumpjavamethods);
jMethod:= env^.GetMethodID(env, jCls, 'Extract', '(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;');
jStr:= env^.CallObjectMethodA(env, _jdumpjavamethods, jMethod, @jParams);
case jStr = nil of
True : Result:= '';
False: begin
jBoo:= JNI_False;
Result:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env,jParams[1].l);
env^.DeleteLocalRef(env, jCls);
end;
function jDumpJavaMethods_GetNoMaskedMethodImplementationByIndex(env: PJNIEnv; _jdumpjavamethods: JObject; _index: integer): string;
var
jStr: JString;
jBoo: JBoolean;
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _index;
jCls:= env^.GetObjectClass(env, _jdumpjavamethods);
jMethod:= env^.GetMethodID(env, jCls, 'GetNoMaskedMethodImplementationByIndex', '(I)Ljava/lang/String;');
jStr:= env^.CallObjectMethodA(env, _jdumpjavamethods, jMethod, @jParams);
case jStr = nil of
True : Result:= '';
False: begin
jBoo:= JNI_False;
Result:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
env^.DeleteLocalRef(env, jCls);
end;
function jDumpJavaMethods_GetNoMaskedMethodImplementationListSize(env: PJNIEnv; _jdumpjavamethods: JObject): integer;
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jdumpjavamethods);
jMethod:= env^.GetMethodID(env, jCls, 'GetNoMaskedMethodImplementationListSize', '()I');
Result:= env^.CallIntMethod(env, _jdumpjavamethods, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
function jDumpJavaMethods_GetNoMaskedMethodImplementationList(env: PJNIEnv; _jdumpjavamethods: JObject): string;
var
jStr: JString;
jBoo: JBoolean;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jdumpjavamethods);
jMethod:= env^.GetMethodID(env, jCls, 'GetNoMaskedMethodImplementationList', '()Ljava/lang/String;');
jStr:= env^.CallObjectMethod(env, _jdumpjavamethods, jMethod);
case jStr = nil of
True : Result:= '';
False: begin
jBoo:= JNI_False;
Result:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
env^.DeleteLocalRef(env, jCls);
end;
end.
|
PROGRAM CalcularFactorial (INPUT, OUTPUT);
(* Función que calcula el factorial de n (n!) de forma recursiva. *)
FUNCTION Factorial (CONST N: INTEGER): INTEGER;
BEGIN
IF N > 1 THEN
Factorial := N * (Factorial (N - 1))
ELSE
Factorial := N
END;
VAR
Base: INTEGER;
BEGIN
Write ('Valor de N: '); ReadLn (Base);
WriteLn ('N! = ', Factorial (Base));
Write ('Pulse [Intro] para finalizar...')
END. |
program xy (input, output) ;
const
UNTEN = 1; { Array-Untergrenze }
OBEN = 10; { Array-Obergrenze }
type
tIndex = UNTEN..OBEN;
tFeld = array[tIndex] of integer;
var
myarray : tFeld;
i : integer;
Zahl : integer;
function FeldMaxA (
inFeld : tFeld;
inUnten,
inOben : tIndex) : integer;
{ Getting the recursive Max in an array }
var
lokMax : integer;
begin
if inUnten = inOben then
FeldMaxA := inFeld[inUnten]
else
begin
lokmax := FeldMaxA(inFeld, inUnten, inOben - 1);
if lokmax > inFeld[oben] then
FeldMaxA := lokmax
else
FeldMaxA := inFeld[Oben]
end
end ;
function FeldMaxB (
var inFeld : tFeld;
inUnten,
inOben : tIndex) : integer;
{ bestimmt rekursiv das Maximum in einem Feld
mit den Grenzen inUnten und inOben }
var
Mitte : tIndex;
MaxL,
MaxR : integer;
begin
if inUnten = inOben then
FeldMaxB := inFeld[inUnten]
else
begin
Mitte := (inUnten + inOben) div 2;
MaxL := FeldMaxB (inFeld,inUnten,Mitte);
MaxR := FeldMaxB (inFeld,Mitte+1,inOben);
if MaxL > MaxR then
FeldMaxB := MaxL
else
FeldMaxB := MaxR
end
end; { FeldMaxA }
begin
for i:=1 to OBEN do
begin
writeln('Zahl eingeben: ');
readln(Zahl);
myarray[i] := Zahl
end ;
writeln('Maximum is: ', FeldMaxB(myarray, UNTEN, OBEN));
end.
|
unit IdTestCoderUUE;
interface
uses
IdTest,
IdObjs,
IdSys,
IdGlobal,
IdCoderUUE;
type
TIdTestCoderUUE = class(TIdTest)
published
procedure Test;
end;
implementation
procedure TIdTestCoderUUE.Test;
var
aEnc:TIdEncoderUUE;
aStr:string;
aDec:TIdDecoderUUE;
const
cPlain='Cat';
cEncoded='#0V%T';
begin
//todo test large strings
//todo test streams
aEnc:=TIdEncoderUUE.Create;
try
aStr:=aEnc.Encode(cPlain);
Assert(aStr=cEncoded,aStr);
finally
Sys.FreeAndNil(aEnc);
end;
aDec:=TIdDecoderUUE.Create;
try
aStr:=aDec.DecodeString(cEncoded);
Assert(aStr=cPlain);
finally
Sys.FreeAndNil(aDec);
end;
end;
initialization
TIdTest.RegisterTest(TIdTestCoderUUE);
end.
|
unit Module.SmartHND;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls,
CMW.Utils, FWEventLog, Module.WinProcesses, Module.Autoruns, Module.WinEvents, Module.Ports,
CMW.ModuleStruct, CMW.OSInfo, Module.Applications, Module.Cleaner, Module.Tasks, Module.HDD, Module.WinServices, Module.Executting,
CMW.ModuleProp, Subs, Vcl.Grids, Vcl.ValEdit, Module.WinFirewall, Module.Regeditor, Module.ContextMenu;
type
TFormSmartHND = class(TForm)
procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
end;
TTweakMachine = class
private
FListView:TListView;
FListLog:TListView;
FInitDir:string;
FOnDblClick:TNotifyEvent;
procedure SetInitDir(Value:string);
procedure OnDblClick(Sender:TObject);
function Initialize(aInitDir:string):Boolean;
function Execute(FileName:TFileName):DWORD;
public
constructor Create(aInitDir:string; aListView, aLogView:TListView);
procedure Update;
procedure Log(Value:string);
property InitDir:string read FInitDir write SetInitDir;
property ListView:TListView read FListView write FListView;
property LogView:TListView read FListLog write FListLog;
property OnDblClicked:TNotifyEvent read FOnDblClick write FOnDblClick;
end;
TSmartHandler = class
DeleteItems:TListView;
ScanItems:TListView;
StartTime:Cardinal;
Stop:Boolean;
StopTime:Cardinal;
ImPathsState:TGetState;
TweaksState:TGetState;
FOldCounterState:Integer;
FProcessingCounter:Integer;
private
FForm:TForm;
FNowWowRedirection:Boolean;
FWOWSwitchState:Boolean;
FProgressBarState:TProgressBar;
FCurrentElement:string;
FOnSetCurElement:TOnSetCurElement;
FTweakMachine:TTweakMachine;
procedure SetCurElement(Value:string);
procedure SetState(Value:TGlobalState);
function FProcessing:Boolean;
public
{0:Автозапуск} AutorunsUnit:TAutorunUnit;
{1:Приложения} ApplicationsUnit:TApplicationUnit;
{2:Очистка} CleanerUnit:TCleanerUnit;
{3:Планировщик} TasksUnit:TTasksUnit;
{4:Хранилище} HDDUnit:THDDUnit;
{5:Службы} ServicesUnit:TServicesUnit;
{6:События} EventsUnit:TEventsUnit;
{7:Процессы} ProcessesUnit:TProcessesUnit;
{8:Порты} PortsUnit:TPortsUnit;
{9:Выполнение} ExecuteUnit:TExecuteUnit;
{10:Брандмауэр} FirewallUnit:TFirewallUnit;
{11:Реестр} RegeditUnit:TRegUnit;
{12:Конт. меню} ContextMenuUnit:TContextMenuUnit;
function WOWSwitch:Boolean;
procedure GlobalStop;
procedure GlobalStart;
procedure AccessState(LV:TListView);
procedure Cancel;
procedure GetTweaks(LV:TListView);
procedure Run;
procedure AddToProcessing;
procedure OpenHostsFile;
constructor Create;
property NowWowRedirection:Boolean read FNowWowRedirection;
property TweakMachine:TTweakMachine read FTweakMachine;
property CurrentElement:string read FCurrentElement write SetCurElement;
property OnSetCurElement:TOnSetCurElement read FOnSetCurElement write FOnSetCurElement;
property Processing:Boolean read FProcessing;
property ProgressBarState:TProgressBar read FProgressBarState write FProgressBarState;
property EngineForm:TForm read FForm write FForm;
end;
var
FormSmartHND: TFormSmartHND;
implementation
{$R *.dfm}
uses CMW.Main, Winapi.ShellAPI, System.IniFiles, System.Win.Registry;
//-----------------------------TSmartHandler--------------------------------------
procedure TSmartHandler.OpenHostsFile;
begin
ShellExecute(Application.Handle, 'open', 'notepad.exe', PChar(Info.HostsFileName), nil, SW_NORMAL);
end;
procedure TSmartHandler.AddToProcessing;
begin
FProcessingCounter:=FProcessingCounter + 1;
SetState(gsNone);
end;
function TSmartHandler.WOWSwitch:Boolean;
begin
if AppBits = x64 then
begin
MessageBox(Application.Handle, 'Смена режима не даст результатов т.к. версия приложения и ОС одинакова.', 'Внимание', MB_OK or MB_ICONWARNING);
Exit(False);
end;
if @Wow64EnableWow64FsRedirection = nil then
begin
MessageBox(Application.Handle, 'Смена режима недоступна. Неудалось получить адрес функции "Wow64EnableWow64FsRedirection" из Kernel32.dll.', 'Внимание', MB_OK or MB_ICONWARNING);
Exit(False);
end;
FWOWSwitchState:=not FWOWSwitchState;
if not FWOWSwitchState then
begin
FNowWowRedirection:=False;
Wow64EnableWow64FsRedirection(True);
Exit(False);
end
else
begin
FNowWowRedirection:=True;
Wow64EnableWow64FsRedirection(False);
Exit(True);
end;
end;
procedure TSmartHandler.GlobalStart;
begin
Exit; {
ApplicationsUnit.Resume;
AutorunsUnit.Resume;
CleanerUnit.Resume;
TasksUnit.Resume;
HDDUnit.Resume;
ServicesUnit.Resume;
EventsUnit.Resume;
ProcessesUnit.Resume;
PortsUnit.Resume;
ExecuteUnit.Resume;
FirewallUnit.Resume;
RegeditUnit.Resume;
ContextMenuUnit.Resume}
Application.ProcessMessages;
end;
procedure TSmartHandler.GlobalStop;
begin
Stop:=True;
ApplicationsUnit.Stop;
AutorunsUnit.Stop;
CleanerUnit.Stop;
TasksUnit.Stop;
HDDUnit.Stop;
ServicesUnit.Stop;
EventsUnit.Stop;
ProcessesUnit.DisableMonitor;
ProcessesUnit.Stop;
PortsUnit.Stop;
ExecuteUnit.Stop;
FirewallUnit.Stop;
RegeditUnit.Stop;
ContextMenuUnit.Stop;
end;
function TSmartHandler.FProcessing:Boolean;
begin
Result:=FProcessingCounter > 0;
end;
procedure TSmartHandler.SetState(Value:TGlobalState);
begin
if not Assigned(FProgressBarState) then Exit;
case Value of
gsProcess: FProcessingCounter:=FProcessingCounter + 1;
gsFinished: FProcessingCounter:=FProcessingCounter - 1;
gsStopped: FProcessingCounter:=FProcessingCounter - 1;
gsError: FProcessingCounter:=FProcessingCounter - 1;
end;
if FProcessingCounter > 0 then
begin
if FProgressBarState.Position <> 10 then
begin
FProgressBarState.Style:=pbstMarquee;
FProgressBarState.Position:=10;
end;
end
else
if FProcessingCounter = 0 then
begin
FProgressBarState.Style:=pbstNormal;
FProgressBarState.Position:=100;
FProgressBarState.State:=pbsNormal;
end
else
begin
FProgressBarState.Style:=pbstNormal;
FProgressBarState.Position:=50;
FProgressBarState.State:=pbsError;
end;
end;
procedure TSmartHandler.SetCurElement(Value:string);
begin
if Value = FCurrentElement then Exit;
if Assigned(FOnSetCurElement) then OnSetCurElement(Value);
FCurrentElement:=Value;
end;
procedure TSmartHandler.AccessState(LV:TListView);
var RALvl:Byte;
begin
LV.Clear;
LV.Groups.Clear;
LV.GroupView:=TRue;
//---------------------Реестр--------------------------------------------------
RALvl:=Info.RollAccessLevel;
with LV.Items.Add do
begin
Caption:=LangText(26, 'Чтение HKCU');
SubItems.Add(BoolStr(RALvl > 0, 'Да', 'Нет'));
GroupID:=GetGroup(LV, LangText(32, 'Реестр'), True);
end;
with LV.Items.Add do
begin
Caption:=LangText(27, 'Запись HKCU');
SubItems.Add(BoolStr(RALvl > 1, 'Да', 'Нет'));
GroupID:=GetGroup(LV, LangText(32, 'Реестр'), True);
end;
with LV.Items.Add do
begin
Caption:=LangText(28, 'Полный доступ HKCU');
SubItems.Add(BoolStr(RALvl > 2, 'Да', 'Нет'));
GroupID:=GetGroup(LV, LangText(32, 'Реестр'), True);
end;
with LV.Items.Add do
begin
Caption:=LangText(29, 'Чтение HKLM');
SubItems.Add(BoolStr(RALvl > 3, 'Да', 'Нет'));
GroupID:=GetGroup(LV, LangText(32, 'Реестр'), True);
end;
with LV.Items.Add do
begin
Caption:=LangText(30, 'Запись HKLM');
SubItems.Add(BoolStr(RALvl > 4, 'Да', 'Нет'));
GroupID:=GetGroup(LV, LangText(32, 'Реестр'), True);
end;
with LV.Items.Add do
begin
Caption:=LangText(31, 'Полный доступ HKLM');
SubItems.Add(BoolStr(RALvl > 5, 'Да', 'Нет'));
GroupID:=GetGroup(LV, LangText(32, 'Реестр'), True);
end;
//-------------Права администратора runas /trustlevel:0x20000 "D:\Debug\CWM.exe"
with LV.Items.Add do
begin
Caption:=LangText(-1, 'Права администратора у пользователя');
SubItems.Add(BoolStr(Info.UserIsAdmin, 'Да', 'Нет'));
GroupID:=GetGroup(LV, LangText(-1, 'Общие права'), True);
end;
//-------------Права администратора
with LV.Items.Add do
begin
Caption:=LangText(-1, 'Права администратора у программы');
SubItems.Add(BoolStr(IsProgAdmin, 'Да', 'Нет'));
GroupID:=GetGroup(LV, LangText(-1, 'Общие права'), True);
end;
//-------------Права администратора
with LV.Items.Add do
begin
Caption:=LangText(-1, 'Перенаправление сред из-за не соответствия разрядности');
SubItems.Add(BoolStr(IsWow64, 'Да', 'Нет'));
GroupID:=GetGroup(LV, LangText(36, 'Другое'), True);
end;
end;
constructor TSmartHandler.Create;
var IconN:TIcon;
begin
inherited;
FProcessingCounter:=0;
FOldCounterState:=0;
//Clr data of class
FWOWSwitchState:=False;
//end clr
AutorunsUnit:=TAutorunUnit.Create;
with AutorunsUnit do
begin
Name:='AutorunsUnit';
ListView:=FormMain.ListViewAR;
LabelCount:=FormMain.LabelCountAutorun;
HandleInform:=SetCurElement;
DisableIcon:=TIcon.Create;
LoadIcons:=True;
StateProc:=SetState;
Grouping:=True;
CurrentOSLink:=Info;
FormMain.ImageListFiles32.GetIcon(11, DisableIcon);
Initialize;
end;
ApplicationsUnit:=TApplicationUnit.Create;
with ApplicationsUnit do
begin
Name:='ApplicationsUnit';
ListView:=FormMain.ListViewWinApps;
LabelCount:=FormMain.LabelCountInstall;
HandleInform:=SetCurElement;
StateProc:=SetState;
LoadIcons:=True;
DisableIcon:=TIcon.Create;
Grouping:=True;
CurrentOSLink:=Info;
FormMain.ImageListToolBar.GetIcon(22, DisableIcon);
Initialize;
end;
CleanerUnit:=TCleanerUnit.Create;
with CleanerUnit do
begin
Name:='CleanerUnit';
ListView:=FormMain.ListViewDelete;
ParamList:=FormMain.ListViewParam;
LabelCount:=FormMain.LabelCountClr;
HandleInform:=SetCurElement;
StateProc:=SetState;
LoadIcons:=True;
DisableIcon:=TIcon.Create;
Grouping:=True;
CurrentOSLink:=Info;
ScanFiles:=True;
FormMain.ImageListFiles32.GetIcon(10, DisableIcon);
Initialize;
end;
TasksUnit:=TTasksUnit.Create;
with TasksUnit do
begin
Name:='TasksUnit';
ListView:=FormMain.ListViewSchedule;
LabelCount:=FormMain.LabelCountTask;
HandleInform:=SetCurElement;
StateProc:=SetState;
LoadIcons:=True;
DisableIcon:=TIcon.Create;
CurrentOSLink:=Info;
Grouping:=True;
FormMain.ImageListFiles.GetIcon(16, DisableIcon);
IconN:=TIcon.Create;
FormMain.ImageListFiles.GetIcon(16, IconN);
ImageList.AddIcon(IconN);
FormMain.ImageListFiles.GetIcon(11, IconN);
ImageList.AddIcon(IconN);
FormMain.ImageListFiles.GetIcon(18, IconN);
ImageList.AddIcon(IconN);
FormMain.ImageListFiles.GetIcon(19, IconN);
ImageList.AddIcon(IconN);
IconN.Free;
Initialize;
end;
HDDUnit:=THDDUnit.Create;
with HDDUnit do
begin
Name:='HDDUnit';
ListView:=FormMain.ListViewHDD;
LabelCount:=FormMain.LabelCountHDD;
HandleInform:=SetCurElement;
StateProc:=SetState;
LoadIcons:=True;
Grouping:=True;
CurrentOSLink:=Info;
GetAttrNames:=True;
Initialize;
end;
ServicesUnit:=TServicesUnit.Create;
with ServicesUnit do
begin
Name:='ServicesUnit';
ListView:=FormMain.ListViewSrvs;
LabelCount:=FormMain.LabelCountService;
HandleInform:=SetCurElement;
StateProc:=SetState;
LoadIcons:=True;
Grouping:=True;
CurrentOSLink:=Info;
SrvIcon:=TIcon.Create;
FormMain.ImageListFiles.GetIcon(21, SrvIcon);
DrvIcon:=TIcon.Create;
FormMain.ImageListFiles.GetIcon(23, DrvIcon);
Initialize;
end;
EventsUnit:=TEventsUnit.Create;
with EventsUnit do
begin
Name:='EventsUnit';
ListView:=FormMain.ListViewEvents;
LabelCount:=FormMain.LabelCountEvent;
HandleInform:=SetCurElement;
StateProc:=SetState;
LoadIcons:=True;
Grouping:=True;
CurrentOSLink:=Info;
DisableIcon:=TIcon.Create;
FormMain.ImageListFiles.GetIcon(15, DisableIcon);
IconN:=TIcon.Create;
FormMain.ImageListFiles.GetIcon(26, IconN);//info 0
ImageList.AddIcon(IconN);
FormMain.ImageListFiles.GetIcon(27, IconN);//warn 1
ImageList.AddIcon(IconN);
FormMain.ImageListFiles.GetIcon(28, IconN);//error 2
ImageList.AddIcon(IconN);
FormMain.ImageListFiles.GetIcon(29, IconN);//secur 3
ImageList.AddIcon(IconN);
FormMain.ImageListFiles.GetIcon(30, IconN);//apps 4
ImageList.AddIcon(IconN);
FormMain.ImageListFiles.GetIcon(31, IconN);//sys 5
ImageList.AddIcon(IconN);
FormMain.ImageListFiles.GetIcon(32, IconN);//sucs 6
ImageList.AddIcon(IconN);
FormMain.ImageListFiles.GetIcon(33, IconN);//fail 7
ImageList.AddIcon(IconN);
Initialize;
end;
ProcessesUnit:=TProcessesUnit.Create;
with ProcessesUnit do
begin
Name:='ProcessesUnit';
ListView:=FormMain.ListViewProc;
TreeView:=FormMain.TreeViewPID;
WinList:=FormMain.ListViewWindows;
LabelCount:=FormMain.LabelCountProc;
HandleInform:=SetCurElement;
StateProc:=SetState;
LoadIcons:=True;
CurrentOSLink:=Info;
Grouping:=False;
OnlyVisableWnd:=True;
OnlyMainWnd:=True;
DisableIcon:=TIcon.Create;
FormMain.ImageListFiles.GetIcon(34, DisableIcon);
RootIcon:=TIcon.Create;
FormMain.ImageListFiles.GetIcon(35, RootIcon);
DefaultIcon:=TIcon.Create;
FormMain.ImageListFiles.GetIcon(20, DefaultIcon);
Initialize;
end;
PortsUnit:=TPortsUnit.Create;
with PortsUnit do
begin
Name:='PortsUnit';
ListView:=FormMain.ListViewPorts;
LabelCount:=FormMain.LabelCountPorts;
HandleInform:=SetCurElement;
StateProc:=SetState;
LoadIcons:=True;
CurrentOSLink:=Info;
Grouping:=True;
IconN:=TIcon.Create;
FormMain.ImageListFiles.GetIcon(24, IconN);
FImageList.AddIcon(IconN);
FormMain.ImageListFiles.GetIcon(25, IconN);
FImageList.AddIcon(IconN);
Initialize;
end;
ExecuteUnit:=TExecuteUnit.Create;
with ExecuteUnit do
begin
Name:='ExecuteUnit';
ListView:=FormMain.ListViewImPaths;
//LabelCount:=FormMain.LabelCount;
HandleInform:=SetCurElement;
StateProc:=SetState;
LoadIcons:=True;
CurrentOSLink:=Info;
Grouping:=True;
DisableIcon:=TIcon.Create;
FormMain.ImageListFiles.GetIcon(0, DisableIcon);
DirIcon:=TIcon.Create;
FormMain.ImageListFiles.GetIcon(1, DirIcon);
Initialize;
end;
FirewallUnit:=TFirewallUnit.Create;
with FirewallUnit do
begin
Name:='FirewallUnit';
ListView:=FormMain.ListViewFW;
//LabelCount:=FormMain.LabelCount;
HandleInform:=SetCurElement;
StateProc:=SetState;
LoadIcons:=True;
CurrentOSLink:=Info;
Grouping:=False;
DisableIcon:=TIcon.Create;
FormMain.ImageListFiles.GetIcon(20, DisableIcon);
ServiceIcon:=TIcon.Create;
FormMain.ImageListFiles.GetIcon(21, ServiceIcon);
Initialize;
end;
RegeditUnit:=TRegUnit.Create;
with RegeditUnit do
begin
Name:='RegeditUnit';
ListView:=FormMain.ListViewReg;
TreeView:=FormMain.TreeViewReg;
TreeView.Images:=FormMain.ImageListClearUnit;
//LabelCount:=FormMain.LabelCount;
HandleInform:=SetCurElement;
StateProc:=SetState;
LoadIcons:=True;
CurrentOSLink:=Info;
Grouping:=False;
IconDir:=TIcon.Create;
FormMain.ImageListFiles.GetIcon(1, IconDir);
IconStr:=TIcon.Create;
FormMain.ImageListFiles.GetIcon(36, IconStr);
IconInt:=TIcon.Create;
FormMain.ImageListFiles.GetIcon(37, IconInt);
IconBin:=TIcon.Create;
FormMain.ImageListFiles.GetIcon(37, IconBin);
//DisableIcon:=TIcon.Create;
//FormMain.ImageListFiles.GetIcon(20, DisableIcon);
//ServiceIcon:=TIcon.Create;
//FormMain.ImageListFiles.GetIcon(21, ServiceIcon);
Initialize;
end;
ContextMenuUnit:=TContextMenuUnit.Create;
with ContextMenuUnit do
begin
Name:='ContextMenuUnit';
ListView:=FormMain.ListViewContext;
//LabelCount:=FormMain.LabelCount;
HandleInform:=SetCurElement;
StateProc:=SetState;
LoadIcons:=True;
CurrentOSLink:=Info;
Grouping:=False;
DisableIcon:=TIcon.Create;
FormMain.ImageListFiles.GetIcon(20, DisableIcon);
//ServiceIcon:=TIcon.Create;
//FormMain.ImageListFiles.GetIcon(21, ServiceIcon);
Initialize;
end;
FreeAndNil(IconN);
Stop:=False;
StopTime:=0;
ImPathsState:=gsIsNotGetted;
FTweakMachine:=TTweakMachine.Create(CurrentDir+'data\fixs', FormMain.ListViewTweaks, FormMain.ListViewTweakLog);
FormMain.ListViewTweaks.OnDblClick:=FTweakMachine.OnDblClick;
end;
procedure TSmartHandler.Cancel;
begin
StopTime:=GetTickCount;
with FormMain do
begin
TimerTick.Enabled:=False;
end;
//Отмена сканирования
end;
procedure TSmartHandler.Run;
//var i:Integer;
begin
if Processing then Exit;
Stop:=False;
//Подготовка
CurrentElement:=LangText(9, 'Подготовка к сканированию...');
StartTime:=GetTickCount;
//Начало сканирования ---------------------------------------------------------
try
except
begin
StopTime:=GetTickCount;
with FormMain do
begin
CurrentElement:=LangText(8, 'Сканирование завершено не удачно.');
end;
Exit;
end;
end;
//Сканирование завершено ------------------------------------------------------
SmartHandler.Cancel;
end;
//------------------------------------------------------------------------------
procedure TSmartHandler.GetTweaks(LV:TListView);
begin
if (TweaksState = gsGetting) or (TweaksState = gsCantGet) then Exit;
TweaksState:=gsGetting;
CurrentElement:='Получение доступных исправлений и решений...';
LV.Clear;
LV.Checkboxes:=True;
LV.Groups.Clear;
LV.Items.BeginUpdate;
TweakMachine.Update;
CurrentElement:='Исправления и решения получены.';
LV.Items.EndUpdate;
LV.ViewStyle:=vsReport;
TweaksState:=gsIsGetted;
end;
///////////////////////
///
///
//------------------------TweakMachine------------------------------------------
// 0 - все норм
// 1 - не существует файл
// 2 - не открывается файл
// 3 - неверное кол-во действий
// 4 - неверное кол-во времени задержки
// 5 - не совпадает кол-во действий
// 6 - ошибка при выполнени команд
function TTweakMachine.Execute(FileName:TFileName):DWORD;
var FixFile:TIniFile;
Acts, i:Word;
TimeWait:Word;
CMDType:string;
cmd:string;
function QUERY(ActNo:Word):Boolean;
var QUERYSTR:string;
DATASTR:string;
Root:string;
p:Word;
Roll:TRegistry;
//12345678901234567
//QUERYREGPATHEXIST
//QUERYREGKEYEXIST
//QUERYREGKEYVALUE
begin
Result:=False;
if FixFile.ReadString('Act'+IntToStr(ActNo), 'QUERY', '') = '' then Exit(True);
DATASTR:=FixFile.ReadString('Act'+IntToStr(ActNo), 'QUERY', '');
p:=Pos('(', DATASTR);
QUERYSTR:=Copy(DATASTR, 1, p - 1);
DATASTR:=Copy(DATASTR, p+1, Length(DATASTR) - Length(QUERYSTR) - 2);
p:=Pos('\', DATASTR);
Root:=Copy(DATASTR, 1, p - 1);
DATASTR:=Copy(DATASTR, p+1, Length(DATASTR) - Length(Root) - 1);
if QUERYSTR = 'QUERYREGPATHEXIST' then
begin
Roll:=TRegistry.Create(KEY_READ);
Roll.RootKey:=StrKeyToRoot(Root);
Result:=Roll.OpenKey(DATASTR, False);
Roll.Free;
Exit;
end;
//Проверка запроса
end;
procedure ShowMSG(ActNo:Word);
begin
if QUERY(ActNo) then
begin
if FixFile.ReadString('Act'+IntToStr(i), 'MessageWithTrue', '') <> '' then
ShowMessage(FixFile.ReadString('Act'+IntToStr(i), 'MessageWithTrue', ''))
end
else
begin
if FixFile.ReadString('Act'+IntToStr(i), 'MessageWithFalse', '') <> '' then
ShowMessage(FixFile.ReadString('Act'+IntToStr(i), 'MessageWithFalse', ''));
end;
end;
begin
Result:=0;
LogView.Clear;
if not FileExists(FileName) then Exit(1);
try
FixFile:=TIniFile.Create(FileName);
except
Exit(2);
end;
if FixFile.ReadInteger('info', 'Actions', 0) <= 0 then Exit(3);
if FixFile.ReadInteger('info', 'TimeWait', 0) < 0 then Exit(4);
Acts:=FixFile.ReadInteger('info', 'Actions', 1);
TimeWait:=FixFile.ReadInteger('info', 'TimeWait', 1);
for i:= 1 to Acts do if FixFile.ReadString('Act'+IntToStr(i), 'Type', 'none') = 'none' then Exit(5);
//Проверка и загрузка окончена
Log('Проверка и загрузка окончена успешно, идет выполнение...');
for i:= 1 to Acts do
begin
Log('Действие №'+IntToStr(i)+': '+FixFile.ReadString('Act'+IntToStr(i), 'Info', 'нет описание действия'));
CMDType:=FixFile.ReadString('Act'+IntToStr(i), 'Type', 'none');
if CMDType = 'none' then
begin
Log('Тип команды №'+IntToStr(i)+' не указан!');
Exit(6);
end;
cmd:=FixFile.ReadString('Act'+IntToStr(i), 'Command', '');
if CMDType = 'cmd' then WinExec(cmd, SW_HIDE) else
if CMDType = 'cmdt' then WinExec(cmd, SW_NORMAL) else
if CMDType = 'msg' then ShowMSG(i) else
begin
Log('Тип команды №'+IntToStr(i)+' не распознан!');
Exit(6);
end;
if TimeWait > 0 then Log('Ожидание указанной паузы выполнения ('+IntToStr(TimeWait)+' сек.)');
Wait(TimeWait);
end;
Log('Код исправления выполнен успешно.');
end;
procedure TTweakMachine.OnDblClick(Sender:TObject);
var FN:string;
MPos:TPoint;
begin
if not (Sender is TListView) then Exit;
with (Sender as TListView) do
begin
if SelCount <= 0 then Exit;
MPos:=ScreenToClient(Mouse.CursorPos);
if (GetItemAt(MPos.X, MPos.Y) = nil) then Exit;
if Selected = nil then Exit;
try
FN:=Selected.SubItems[3];
except
Exit;
end;
if MessageBox(Application.Handle, PChar('Вы действительно хотите выполнить код исправления'#13#10' "'+Selected.Caption+'"'), 'Внимание', MB_ICONWARNING or MB_YESNO) <> ID_YES then EXIT;
end;
case Execute(FN) of
1:Log('Исправление на выполнено: не существует файл');
2:Log('Исправление на выполнено: не открывается файл');
3:Log('Исправление на выполнено: неверное кол-во действий');
4:Log('Исправление на выполнено: неверное кол-во времени задержки');
5:Log('Исправление на выполнено: не совпадает кол-во действий');
6:Log('Исправление на выполнено: ошибка при выполнении команд');
end;
end;
procedure TTweakMachine.Log(Value:string);
begin
LogView.Items.Add.Caption:=Value;
end;
procedure TTweakMachine.SetInitDir(Value:string);
begin
if not Initialize(Value) then Exception.Create('Не могу сменить каталог TweakMachine на "'+Value+'"');
end;
procedure TTweakMachine.Update;
var FixFile:TIniFile;
FixFiles:TStrings;
LI:TListItem;
i:Integer;
begin
FixFiles:=TStringList.Create;
ScanDir(FInitDir, '*.fix', FixFiles);
FListView.Clear;
if FixFiles.Count <= 0 then Exit;
FListView.Items.BeginUpdate;
for i:= 0 to FixFiles.Count - 1 do
with FListView.Items do
begin
if not FileExists(FixFiles[i]) then Continue;
try
try
FixFile:=TIniFile.Create(FixFiles[i]);
LI:=Add;
LI.Caption:=FixFile.ReadString('info', 'Name', 'не изветсно');
LI.SubItems.Add(FixFile.ReadString('info', 'Problem', 'не известно'));
LI.SubItems.Add(FixFile.ReadString('info', 'Desc', 'не известно'));
LI.SubItems.Add(FixFile.ReadString('info', 'Actions', 'не известно'));
LI.SubItems.Add(FixFiles[i]);
LI.ImageIndex:=17;
LI.GroupID:=GetGroup(FListView, FixFile.ReadString('info', 'GroupName', 'Нет группы'), False);
finally
FreeAndNil(FixFile);
end;
except
CMW.Utils.Log(['Except with - FixFile:=TIniFile.Create(FixFiles[i]);']);
end;
Application.ProcessMessages;
if Stopping then Exit;
end;
FListView.Items.EndUpdate;
end;
function TTweakMachine.Initialize(aInitDir:string):Boolean;
begin
if not System.SysUtils.DirectoryExists(aInitDir) then Exit(False);
ListView.Clear;
FInitDir:=aInitDir;
Result:=True;
end;
constructor TTweakMachine.Create(aInitDir:string; aListView, aLogView:TListView);
begin
inherited Create;
if Assigned(aListView) then FListView:=aListView else FListView:=TListView.Create(nil);
if Assigned(aLogView) then FListLog:=aLogView else FListLog:=TListView.Create(nil);
if not Initialize(aInitDir) then Exception.Create('Не могу инициализировать TweakMachine в "'+aInitDir+'"');
end;
procedure TFormSmartHND.FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_ESCAPE: Close;
end;
end;
end.
|
unit TSTOBCellImpl;
interface
Uses Windows, SysUtils, {$If CompilerVersion < 18.5}HsStreamEx,{$IfEnd}
HsInterfaceEx, TSTOBCellIntf;
Type
TBCellSubItem = Class(TInterfacedObjectEx, IBCellSubItem)
Private
FString1 : String;
FString2 : String;
FPadding : TBytes;
Protected
Procedure Created(); OverRide;
Function GetString1() : AnsiString;
Procedure SetString1(Const AString1 : AnsiString);
Function GetString2() : AnsiString;
Procedure SetString2(Const AString2 : AnsiString);
Function GetPadding() : TBytes;
Procedure Clear();
Procedure Assign(ASource : IInterface); ReIntroduce;
Property String1 : AnsiString Read GetString1 Write SetString1;
Property String2 : AnsiString Read GetString2 Write SetString2;
Property Padding : TBytes Read GetPadding;
End;
TBCellSubItems = Class(TInterfaceListEx, IBCellSubItems)
Protected
Function GetItemClass() : TInterfacedObjectExClass; OverRide;
Function Get(Index : Integer) : IBCellSubItem; OverLoad;
Procedure Put(Index : Integer; Const Item : IBCellSubItem); OverLoad;
Function Add() : IBCellSubItem; ReIntroduce; OverLoad;
Function Add(Const AItem : IBCellSubItem) : Integer; OverLoad;
Procedure Assign(ASource : IInterface); ReIntroduce;
End;
TBCellSubItemsClass = Class Of TBCellSubItems;
TBCellItem = Class(TInterfacedObjectEx, IBCellItem)
Private
FRgbFileName : String;
FxDiffs : Double;
FSubItems : IBCellSubItems;
Protected
Procedure Created(); OverRide;
Function GetSubItemClass() : TBCellSubItemsClass; Virtual;
Function GetRgbFileName() : AnsiString; Virtual;
Procedure SetRgbFileName(Const ARgbFileName : AnsiString);
Function GetxDiffs() : Double; Virtual;
Procedure SetxDiffs(Const AxDiffs : Double); Virtual;
Function GetNbSubItems() : Word; Virtual;
Function GetSubItems() : IBCellSubItems;
Procedure Clear();
Procedure Assign(ASource : IInterface); ReIntroduce;
Public
Destructor Destroy(); OverRide;
End;
TBCellItems = Class(TInterfaceListEx, IBCellItems)
Protected
Function GetItemClass() : TInterfacedObjectExClass; OverRide;
Function Get(Index : Integer) : IBCellItem; OverLoad;
Procedure Put(Index : Integer; Const Item : IBCellItem); OverLoad;
Function Add() : IBCellItem; ReIntroduce; OverLoad;
Function Add(Const AItem : IBCellItem) : Integer; OverLoad;
Procedure Assign(ASource : IInterface); ReIntroduce;
End;
TBCellItemsClass = Class Of TBCellItems;
TTSTOBCellFile = Class(TInterfacedObjectEx, ITSTOBCellFile)
Private
FFileSig : AnsiString;
FItems : IBCellItems;
Protected
Procedure Created(); OverRide;
Function GetItemClass() : TBCellItemsClass; Virtual;
Function GetFileSig() : AnsiString; Virtual;
Procedure SetFileSig(Const AFileSig : AnsiString); Virtual;
Function GetNbItem() : Word; Virtual;
Function GetItems() : IBCellItems;
Procedure Clear();
Procedure Assign(ASource : IInterface); ReIntroduce;
Public
Destructor Destroy(); OverRide;
End;
implementation
Uses RTLConsts;
Procedure TBCellSubItem.Created();
Begin
InHerited Created();
Clear();
End;
Procedure TBCellSubItem.Clear();
Begin
SetLength(FPadding, 28);
ZeroMemory(@FPadding[0], Length(FPadding));
FString1 := '';
FString2 := '';
End;
Procedure TBCellSubItem.Assign(ASource : IInterface);
Var lSrc : IBCellSubItem;
Begin
If Supports(ASource, IBCellSubItem, lSrc) Then
Begin
FString1 := lSrc.String1;
FString2 := lSrc.String2;
FPadding := lSrc.Padding;
End
Else
Raise EConvertError.CreateResFmt(@SAssignError, ['Unsupported Interface', ClassName]);
End;
Function TBCellSubItem.GetString1() : AnsiString;
Begin
Result := FString1;
End;
Procedure TBCellSubItem.SetString1(Const AString1 : AnsiString);
Begin
FString1 := AString1;
End;
Function TBCellSubItem.GetString2() : AnsiString;
Begin
Result := FString2;
End;
Procedure TBCellSubItem.SetString2(Const AString2 : AnsiString);
Begin
FString2 := AString2;
End;
Function TBCellSubItem.GetPadding() : TBytes;
Begin
Result := FPadding;
End;
Function TBCellSubItems.GetItemClass() : TInterfacedObjectExClass;
Begin
Result := TBCellSubItem;
End;
Function TBCellSubItems.Get(Index : Integer) : IBCellSubItem;
Begin
Result := InHerited Items[Index] As IBCellSubItem;
End;
Procedure TBCellSubItems.Put(Index : Integer; Const Item : IBCellSubItem);
Begin
InHerited Items[Index] := Item;
End;
Function TBCellSubItems.Add() : IBCellSubItem;
Begin
Result := InHerited Add() As IBCellSubItem;
End;
Function TBCellSubItems.Add(Const AItem : IBCellSubItem) : Integer;
Begin
Result := InHerited Add(AItem);
End;
Procedure TBCellSubItems.Assign(ASource : IInterface);
Var lSrc : IBCellSubItems;
X : Integer;
Begin
If Supports(ASource, IBCellSubItems, lSrc) Then
Begin
Clear();
For X := 0 To lSrc.Count - 1 Do
Add().Assign(lSrc[X]);
End
Else
Raise EConvertError.CreateResFmt(@SAssignError, ['Unsupported Interface', ClassName]);
End;
Procedure TBCellItem.Created();
Begin
InHerited Created();
Clear();
End;
Destructor TBCellItem.Destroy();
Begin
FSubItems := Nil;
InHerited Destroy();
End;
Function TBCellItem.GetSubItemClass() : TBCellSubItemsClass;
Begin
Result := TBCellSubItems;
End;
Procedure TBCellItem.Clear();
Begin
FRgbFileName := '';
FxDiffs := 0;
FSubItems := GetSubItemClass().Create();
End;
Procedure TBCellItem.Assign(ASource : IInterface);
Var lSrc : IBCellItem;
Begin
If Supports(ASource, IBCellItem, lSrc) Then
Begin
FRgbFileName := lSrc.RgbFileName;
FxDiffs := lSrc.xDiffs;
FSubItems.Assign(lSrc.SubItems);
End
Else
Raise EConvertError.CreateResFmt(@SAssignError, ['Unsupported Interface', ClassName]);
End;
Function TBCellItem.GetRgbFileName() : AnsiString;
Begin
Result := FRgbFileName;
End;
Procedure TBCellItem.SetRgbFileName(Const ARgbFileName : AnsiString);
Begin
FRgbFileName := ARgbFileName;
End;
Function TBCellItem.GetxDiffs() : Double;
Begin
Result := FxDiffs;
End;
Procedure TBCellItem.SetxDiffs(Const AxDiffs : Double);
Begin
FxDiffs := AxDiffs;
End;
Function TBCellItem.GetNbSubItems() : Word;
Begin
Result := FSubItems.Count;
End;
Function TBCellItem.GetSubItems() : IBCellSubItems;
Begin
Result := FSubItems;
End;
Function TBCellItems.GetItemClass() : TInterfacedObjectExClass;
Begin
Result := TBCellItem;
End;
Function TBCellItems.Get(Index : Integer) : IBCellItem;
Begin
Result := InHerited Items[Index] As IBCellItem;
End;
Procedure TBCellItems.Put(Index : Integer; Const Item : IBCellItem);
Begin
InHerited Items[Index] := Item;
End;
Function TBCellItems.Add() : IBCellItem;
Begin
Result := InHerited Add() As IBCellItem;
End;
Function TBCellItems.Add(Const AItem : IBCellItem) : Integer;
Begin
Result := InHerited Add(AItem);
End;
Procedure TBCellItems.Assign(ASource : IInterface);
Var lSrc : IBCellItems;
X : Integer;
Begin
If Supports(ASource, IBCellItems, lSrc) Then
Begin
Clear();
For X := 0 To lSrc.Count - 1 Do
Add().Assign(lSrc[X]);
End
Else
Raise EConvertError.CreateResFmt(@SAssignError, ['Unsupported Interface', ClassName]);
End;
Procedure TTSTOBCellFile.Created();
Begin
InHerited Created();
Clear();
End;
Destructor TTSTOBCellFile.Destroy();
Begin
FItems := Nil;
InHerited Destroy();
End;
Function TTSTOBCellFile.GetItemClass() : TBCellItemsClass;
Begin
Result := TBCellItems;
End;
Procedure TTSTOBCellFile.Clear();
Begin
FFileSig := '';
FItems := GetItemClass().Create();
End;
Procedure TTSTOBCellFile.Assign(ASource : IInterface);
Var lSrc : ITSTOBCellFile;
Begin
If Supports(ASource, ITSTOBCellFile, lSrc) Then
Begin
FFileSig := lSrc.FileSig;
FItems.Assign(lSrc.Items);
End
Else
Raise EConvertError.CreateResFmt(@SAssignError, ['Unsupported Interface', ClassName]);
End;
Function TTSTOBCellFile.GetFileSig() : AnsiString;
Begin
Result := AnsiString(Copy(FFileSig, 1, Length(FFileSig) - 1));
End;
Procedure TTSTOBCellFile.SetFileSig(Const AFileSig : AnsiString);
Begin
FFileSig := AFileSig + #1;
End;
Function TTSTOBCellFile.GetNbItem() : Word;
Begin
Result := FItems.Count;
End;
Function TTSTOBCellFile.GetItems() : IBCellItems;
Begin
Result := FItems;
End;
end.
|
unit UMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
OleCtrls, ExtDialogs, StdCtrls, ExtCtrls, Buttons, ComCtrls,
Menus, PDG2Lib_TLB, ImgList, ToolWin,IniFiles,WinObjs;
type
TBookDefine = class
private
FBookmarks : TStringList;
public
isValid : boolean;
BookName : string;
URL : string;
PageNo : integer;
Zoom : single;
formX,formY,formW,formH : integer;
viewX,viewY : integer;
isFullScreen : boolean;
// Bookmarks contain bookmark Names and page numbers(in objects)
property Bookmarks : TStringList read FBookmarks;
constructor Create;
Destructor Destroy;override;
procedure readConfig(ini : TCustomIniFile);
procedure writeConfig(ini : TCustomIniFile);
procedure viewBook;
procedure saveBook;
function isURLValid(const URL:string):boolean;
function addBookmark(const bookmarkName:string;bookmarkPage:integer):boolean;
end;
TfmViewer = class(TForm)
pnBottom: TPanel;
pnStatus: TPanel;
pnCurSize: TPanel;
pnPageNo: TPanel;
pmZoom: TPopupMenu;
N111: TMenuItem;
N121: TMenuItem;
N131: TMenuItem;
N141: TMenuItem;
N151: TMenuItem;
N161: TMenuItem;
N171: TMenuItem;
N181: TMenuItem;
Viewer: TT_Pdg01;
pnOriginSize: TPanel;
pnZoom: TPanel;
pnXY: TPanel;
pmFunc: TPopupMenu;
mnPrev: TMenuItem;
mnNext: TMenuItem;
mnGotoPage: TMenuItem;
mnZoom: TMenuItem;
N1: TMenuItem;
mnFullScreen: TMenuItem;
mnRefresh: TMenuItem;
OpenDialog1: TOpenDialog;
mnFitWidth: TMenuItem;
mnFitHeight: TMenuItem;
mnSpecify: TMenuItem;
mnFitWidth1: TMenuItem;
mnFitHeight1: TMenuItem;
N2: TMenuItem;
pnTools: TToolBar;
btnOpen: TToolButton;
btnNewBook: TToolButton;
ToolButton3: TToolButton;
btnPrev: TToolButton;
ToolButton5: TToolButton;
btnNext: TToolButton;
ToolButton7: TToolButton;
btnFullScreen: TToolButton;
btnRefresh: TToolButton;
ImageList1: TImageList;
pmBooks: TPopupMenu;
btnBookMan: TToolButton;
ToolButton1: TToolButton;
btnAbout: TToolButton;
btnNewBookmark: TToolButton;
btnGotoBookmark: TToolButton;
ToolButton6: TToolButton;
btnBookmarkMan: TToolButton;
pmBookmarks: TPopupMenu;
N3: TMenuItem;
muNewBookmark: TMenuItem;
muBookmarks: TMenuItem;
procedure btnOpenClick(Sender: TObject);
procedure btnPrevClick(Sender: TObject);
procedure btnNextClick(Sender: TObject);
procedure pnPageNoClick(Sender: TObject);
procedure pnZoomClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure FormCreate(Sender: TObject);
procedure btnFullScreenClick(Sender: TObject);
procedure SetTheZoom(Sender: TObject);
procedure pnZoomDblClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure ViewerScroll(Sender: TObject; x, y: Integer);
procedure mnFullScreenClick(Sender: TObject);
procedure btnRefreshClick(Sender: TObject);
procedure pmFuncPopup(Sender: TObject);
procedure mnFitWidthClick(Sender: TObject);
procedure mnFitHeightClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnNewBookClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnBookManClick(Sender: TObject);
procedure btnAboutClick(Sender: TObject);
procedure CMDIALOGKEY(var Message:TMessage); message CM_DIALOGKEY;
procedure btnNewBookmarkClick(Sender: TObject);
procedure btnBookmarkManClick(Sender: TObject);
procedure ViewerMouseAction(Sender: TObject; flag: Integer; Button,
Shift: Smallint; x, y: Integer);
procedure ViewerProgress(Sender: TObject; filelength, curpos: Integer);
procedure ViewerInitDrawing(Sender: TObject; URL: Integer);
private
{ Private declarations }
FisFullScreen: boolean;
oldLeft,oldTop,oldWidth,oldHeight : integer;
fullscreenX,fullscreenY,fullscreenW,fullscreenH : integer;
iniFile : TIniFile;
bookNames : TStrings;
curBook : TBookDefine;
viewWin : WWindow;
procedure SetIsFullScreen(const Value: boolean);
procedure WMGETMINMAXINFO(var message : TWMGETMINMAXINFO);message WM_GETMINMAXINFO;
procedure decZoom;
procedure incZoom;
procedure zoomTo(rate:single);
procedure updateViewPoint;
procedure goUp;
procedure goDown;
function handleKey(keycode:word;shift :TShiftState =[]):word;
procedure fitWidth;
procedure fitHeight;
procedure switchScreen;
procedure getAllBooks;
procedure RestructBooks;
procedure openBook(sender : TObject);
procedure saveBook;
procedure openBookmark(sender : TObject);
procedure addBookMenu(const bookName:string);
procedure addBookmarkMenu(const bookmarkName:string;bookmarkPage:integer);
procedure refreshView;
procedure clearBookmarks;
procedure RestructBookmarks;
function getcurPageNo: integer;
procedure AfterLoadANewPage;
public
{ Public declarations }
procedure gotoPage(pageNo:integer);
property curPageNo : integer read getcurPageNo write gotoPage;
property isFullScreen : boolean read FisFullScreen write SetIsFullScreen;
procedure gotoBookmark(bookmarkIndex : integer);
end;
var
fmViewer: TfmViewer;
resourcestring
SNewBookMark = 'New Bookmark';
SBookmarkName = 'Bookmark Name';
implementation
{$R *.DFM}
uses CompUtils,InpIntDlg, UBookMan,HYLAbout, UBookmarkMan;
{ TBookDefine }
procedure TBookDefine.readConfig(ini: TCustomIniFile);
var
bookmarkName,bookmarkEntry : string;
bookmarkCount,i : integer;
bookmarkPage : integer;
begin
assert(fmViewer<>nil);
assert(ini<>nil);
URL := ini.ReadString(BookName,'URL','');
PageNo := ini.ReadInteger(BookName,'PageNo',1);
formX := ini.ReadInteger(BookName,'X',fmViewer.left);
formY := ini.ReadInteger(BookName,'Y',fmViewer.top);
formW := ini.ReadInteger(BookName,'W',fmViewer.Width);
formH := ini.ReadInteger(BookName,'H',fmViewer.Height);
viewX := ini.ReadInteger(BookName,'VX',fmViewer.Viewer.ViewPoint_x);
viewY := ini.ReadInteger(BookName,'VY',fmViewer.Viewer.ViewPoint_y);
Zoom := ini.ReadFloat(BookName,'Zoom',1);
isFullScreen := ini.ReadBool(BookName,'Full',false);
if not (isFullScreen) and ( (formW>Screen.Width) or (formH>Screen.Height)) then
isFullScreen := true;
// read bookmarks
FBookmarks.Clear;
bookmarkCount:=ini.ReadInteger(BookName,'Bookmarks',0);
for i:=1 to bookmarkCount do
begin
bookmarkEntry:=IntToStr(i);
bookmarkName:=ini.ReadString(BookName,bookmarkEntry+'.desc','');
bookmarkPage:=ini.ReadInteger(BookName,bookmarkEntry+'.page',-1);
if (bookmarkName<>'') {and (bookmarkPage>=0)} then
FBookmarks.AddObject(bookmarkName,TObject(bookmarkPage));
end;
end;
procedure TBookDefine.viewBook;
begin
assert(fmViewer<>nil);
fmViewer.clearBookmarks;
//if isURLValid(URL) then
begin
fmViewer.Caption := Application.Title + ' ' + BookName;
if isFullScreen then
fmViewer.isFullScreen:=true else
fmViewer.SetBounds(formX,formY,formW,formH);
fmViewer.Viewer.URL := URL;
//fmViewer.Viewer.GotoPageNum(PageNo);
fmViewer.gotoPage(PageNo);
fmViewer.zoomTo(Zoom);
fmViewer.Viewer.MoveTo(viewX,viewY);
isValid := true;
fmViewer.RestructBookmarks;
end;
end;
procedure TBookDefine.saveBook;
begin
assert(fmViewer<>nil);
if fmViewer.Viewer.IsPageValid>0 then
begin
URL := fmViewer.Viewer.URL;
PageNo := fmViewer.curPageNo;
end;
zoom := fmViewer.Viewer.zoom;
formX := fmViewer.Left;
formY := fmViewer.Top;
formW := fmViewer.Width;
formH := fmViewer.Height;
viewX := fmViewer.Viewer.ViewPoint_x;
viewY := fmViewer.Viewer.ViewPoint_y;
isFullScreen := fmViewer.isFullScreen;
end;
procedure TBookDefine.writeConfig(ini: TCustomIniFile);
var
bookmarkName,bookmarkEntry : string;
bookmarkCount,i : integer;
bookmarkPage : integer;
begin
assert(fmViewer<>nil);
assert(ini<>nil);
ini.writeString(BookName,'URL',URL);
ini.writeInteger(BookName,'PageNo',PageNo);
ini.writeInteger(BookName,'X',formX);
ini.writeInteger(BookName,'Y',formY);
ini.writeInteger(BookName,'W',formW);
ini.writeInteger(BookName,'H',formH);
ini.writeFloat(BookName,'Zoom',Zoom);
ini.WriteInteger(BookName,'VX',viewX);
ini.WriteInteger(BookName,'VY',viewY);
ini.WriteBool(BookName,'Full',isFullScreen);
// write bookmarks
bookmarkCount:=FBookmarks.Count;
ini.WriteInteger(BookName,'Bookmarks',bookmarkCount);
for i:=1 to bookmarkCount do
begin
bookmarkEntry:=IntToStr(i);
bookmarkName:=FBookmarks[i-1];
bookmarkPage:=integer(FBookmarks.Objects[i-1]);
ini.WriteString(BookName,bookmarkEntry+'.desc',bookmarkName);
ini.WriteInteger(BookName,bookmarkEntry+'.page',bookmarkPage);
end;
end;
function TBookDefine.isURLValid(const URL:string):boolean;
begin
result := URL<>'';
if result then
result := FileExists(URL);
end;
const
moveSteps = 32;
constructor TBookDefine.Create;
begin
inherited;
FBookmarks := TStringList.create;
end;
destructor TBookDefine.Destroy;
begin
FBookmarks.free;
inherited;
end;
function TBookDefine.addBookmark(const bookmarkName:string;
bookmarkPage:integer):boolean;
begin
if (bookmarkName<>'') {and (bookmarkPage>=0)} then
begin
FBookmarks.AddObject(bookmarkName,TObject(bookmarkPage));
result := true;
end else
result := false;
end;
{ TfmViewer }
procedure TfmViewer.btnOpenClick(Sender: TObject);
begin
if OpenDialog1.Execute then
begin
saveBook;
curBook.isValid := false;
Viewer.URL := OpenDialog1.FileName;
Caption := Application.Title + ' '+ OpenDialog1.FileName;
clearBookmarks;
end;
end;
procedure TfmViewer.btnPrevClick(Sender: TObject);
begin
Viewer.GotoPreviousPage;
end;
procedure TfmViewer.btnNextClick(Sender: TObject);
begin
Viewer.GotoNextPage;
end;
procedure TfmViewer.pnPageNoClick(Sender: TObject);
var
newPage : Integer;
begin
newPage := curPageNo;
if InputInteger('Goto Page','Page No(<0 is cont):',newPage) then
//Viewer.GotoPageNum(newPage);
gotoPage(newPage);
end;
procedure TfmViewer.pnZoomClick(Sender: TObject);
begin
Popup(pmZoom);
end;
procedure TfmViewer.WMGETMINMAXINFO(var message: TWMGETMINMAXINFO);
begin
inherited ;
with message.MinMaxInfo^.ptMaxTrackSize do
begin
x:=2 * screen.width;
y:=2 * screen.height;
end;
end;
procedure TfmViewer.FormActivate(Sender: TObject);
begin
viewWin.Handle := Viewer.Handle;
end;
procedure TfmViewer.FormKeyPress(Sender: TObject; var Key: Char);
begin
case key of
#27 : isFullScreen := false; // ESC
#9 : isFullScreen := not isFullScreen; // TAB
'-','_' : decZoom;
'=','+' : incZoom;
end;
end;
procedure TfmViewer.SetIsFullScreen(const Value: boolean);
begin
if (FisFullScreen <> Value) then
begin
FisFullScreen := value;
if (FisFullScreen) then
begin
oldLeft:=left;
oldTop:=top;
oldWidth:=width;
oldHeight:=height;
setBounds(fullscreenX,fullscreenY,fullscreenW,fullscreenH);
end else
setBounds(oldLeft,oldTop,oldWidth,oldHeight);
end;
end;
procedure TfmViewer.FormCreate(Sender: TObject);
begin
FisFullScreen := false;
// prepare form size
oldLeft:=left;
oldTop:=top;
oldWidth:=width;
oldHeight:=height;
fullscreenX:=-(width-clientWidth) div 2;
fullscreenY:=-(height-clientHeight)-pnTools.Height;
fullscreenW:=Screen.width+(width-clientWidth);
fullscreenH:= (height-clientHeight) // caption height
+ pnTools.Height + Screen.Height + pnBottom.Height;
bookNames := TStringList.create;
iniFile := TIniFile.create(ChangeFileExt(Application.ExeName,'.ini'));
curBook := TBookDefine.create;
curBook.isValid := false;
getAllBooks;
viewWin := WWindow.Create(0);
end;
procedure TfmViewer.btnFullScreenClick(Sender: TObject);
begin
isFullScreen := true;
end;
procedure TfmViewer.SetTheZoom(Sender: TObject);
begin
zoomTo(1/TComponent(Sender).tag);
end;
procedure TfmViewer.decZoom;
begin
if Viewer.Zoom>0.01 then
zoomTo(Viewer.Zoom*0.8);
end;
procedure TfmViewer.incZoom;
begin
if Viewer.Zoom<8 then
zoomTo(Viewer.Zoom/0.8);
end;
procedure TfmViewer.zoomTo(rate: single);
begin
Viewer.SetZoom2(rate);
Viewer.Refresh;
end;
procedure TfmViewer.pnZoomDblClick(Sender: TObject);
var
zoom : integer;
begin
zoom := round(100 * Viewer.Zoom);
if InputInteger('Input Zoom Rate','Zoom Rate(%)',zoom,1,800) then
zoomTo(zoom/100);
end;
procedure TfmViewer.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
handleKey(key,shift);
end;
procedure TfmViewer.ViewerScroll(Sender: TObject; x, y: Integer);
begin
updateViewPoint;
end;
procedure TfmViewer.updateViewPoint;
begin
pnXY.Caption := format('x:%d,y:%d',[Viewer.ViewPoint_X,Viewer.ViewPoint_Y]);
end;
procedure TfmViewer.goDown;
var
X,Y,Y1: integer;
DC : WDC;
begin
X := Viewer.ViewPoint_X;
Y := Viewer.ViewPoint_Y;
if (Y+Viewer.Height+10)<Viewer.PageHeight then
begin
Viewer.MoveTo(X,Y+Viewer.Height-10);
Y1 := Y+Viewer.Height - Viewer.ViewPoint_Y;
DC := viewWin.GetDCObj(false);
try
DC.Canvas.Pen.Color := clRed;
DC.Canvas.MoveTo(0,Y1+10);
DC.Canvas.LineTo(Viewer.Width,Y1+10);
finally
DC.free;
end;
end else
begin
Viewer.GotoNextPage;
Viewer.MoveTo(X,0);
end;
end;
procedure TfmViewer.goUp;
var
X,Y : integer;
begin
X := Viewer.ViewPoint_X;
Y := Viewer.ViewPoint_Y;
if Y>=Viewer.Height then
begin
Viewer.MoveTo(X,Y - Viewer.Height);
end else
if Y>=10 then
Viewer.MoveTo(X,0) else
if Viewer.PageNum>1 then
begin
Viewer.GotoPreviousPage;
Viewer.MoveTo(X,Viewer.PageHeight - Viewer.Height);
end else
Viewer.MoveTo(X,0);
end;
function TfmViewer.handleKey(keycode:word;shift :TShiftState =[]):word;
begin
case keycode of
VK_PRIOR : goUp;
VK_NEXT : goDown;
VK_left : viewer.MoveStep(-moveSteps,0);
VK_right : viewer.MoveStep(moveSteps,0);
VK_up : if ssCtrl in shift then
btnPrevClick(self) else
viewer.MoveStep(0,-moveSteps);
VK_down : if ssCtrl in shift then
btnNextClick(self) else
viewer.MoveStep(0,moveSteps);
VK_Return : refreshView;
VK_F1 : btnAboutClick(nil);
VK_F2 : btnOpenClick(nil);
VK_F3 : btnNewBookClick(nil);
VK_F4 : if shift=[] then
switchScreen;
VK_F5 : fitWidth;
VK_F6 : fitHeight;
VK_F7 : btnNewBookmarkClick(nil);
else
begin
result := keycode;
exit;
end;
end;
result:= 0;
end;
procedure TfmViewer.mnFullScreenClick(Sender: TObject);
begin
switchScreen;
end;
procedure TfmViewer.btnRefreshClick(Sender: TObject);
begin
//Viewer.Refresh;
refreshView;
end;
procedure TfmViewer.pmFuncPopup(Sender: TObject);
begin
mnFullScreen.Checked := isFullScreen;
end;
procedure TfmViewer.mnFitWidthClick(Sender: TObject);
begin
FitWidth;
end;
procedure TfmViewer.mnFitHeightClick(Sender: TObject);
begin
FitHeight;
end;
procedure TfmViewer.fitHeight;
var
oriH : integer;
begin
if Viewer.IsPageValid>0 then
begin
oriH := Viewer.OrgPageHeight;
if (oriH>0) and (Viewer.Height>0) then
begin
ZoomTo(Viewer.Height/oriH);
end;
end;
end;
procedure TfmViewer.fitWidth;
var
oriW : integer;
begin
if Viewer.IsPageValid>0 then
begin
oriW := Viewer.OrgPageWidth;
if (oriW>0) and (Viewer.Width>0) then
begin
ZoomTo(Viewer.Width/oriW);
end;
end;
end;
procedure TfmViewer.switchScreen;
begin
isFullScreen := not isFullScreen;
end;
procedure TfmViewer.getAllBooks;
begin
iniFile.ReadSections(bookNames);
RestructBooks;
end;
procedure TfmViewer.FormDestroy(Sender: TObject);
begin
//saveBook;
curBook.free;
iniFile.free;
bookNames.free;
viewWin.free;
end;
procedure TfmViewer.openBook(sender: TObject);
begin
saveBook;
curBook.BookName := TMenuItem(sender).caption;
curBook.readConfig(iniFile);
curBook.viewBook;
end;
procedure TfmViewer.saveBook;
begin
assert(curBook<>nil);
assert(iniFile<>nil);
if curBook.isValid then
begin
curBook.saveBook;
curBook.writeConfig(IniFile);
IniFile.UpdateFile;
end;
end;
procedure TfmViewer.btnNewBookClick(Sender: TObject);
var
bookName : string;
begin
bookName := '';
if (Viewer.IsPageValid>0) and InputQuery('New Book','Book Name',bookName) then
begin
if BookName<>'' then
begin
saveBook;
curBook.BookName := BookName;
curBook.isValid := true;
bookNames.Add(bookName);
addBookMenu(bookName);
end;
end;
end;
procedure TfmViewer.addBookMenu(const bookName:string);
var
newItem : TMenuItem;
begin
newItem := TMenuItem.Create(pmBooks);
newItem.Caption := bookName;
newItem.OnClick := openBook;
pmBooks.Items.add(newItem);
end;
procedure TfmViewer.FormClose(Sender: TObject; var Action: TCloseAction);
begin
saveBook;
end;
procedure TfmViewer.refreshView;
var
x,y : integer;
begin
x := Viewer.ViewPoint_x;
y := Viewer.ViewPoint_y;
Viewer.Refresh;
Viewer.MoveTo(x,y);
end;
procedure TfmViewer.btnBookManClick(Sender: TObject);
begin
dlgBookMan.execute(bookNames,iniFile);
RestructBooks;
end;
procedure TfmViewer.btnAboutClick(Sender: TObject);
begin
StartAbout(0);
end;
procedure TfmViewer.CMDIALOGKEY(var Message: TMessage);
begin
handleKey(Message.WParam,KeyDataToShiftState(Message.LParam));
inherited;
end;
procedure TfmViewer.clearBookmarks;
begin
pmBookmarks.Items.Clear;
end;
procedure TfmViewer.RestructBookmarks;
var
bookmarkName,bookmarkEntry : string;
bookmarkCount,i : integer;
bookmarkPage : integer;
begin
bookmarkCount:=curBook.Bookmarks.Count;
for i:=1 to bookmarkCount do
begin
bookmarkEntry:=IntToStr(i);
bookmarkName:=curBook.Bookmarks[i-1];
bookmarkPage:=integer(curBook.Bookmarks.Objects[i-1]);
addBookmarkMenu(bookmarkName,bookmarkPage);
end;
end;
procedure TfmViewer.addBookmarkMenu(const bookmarkName: string;
bookmarkPage: integer);
var
newItem : TMenuItem;
begin
newItem := TMenuItem.Create(pmBookmarks);
newItem.Caption := bookmarkName;
newItem.tag := bookmarkPage;
newItem.OnClick := openBookmark;
pmBookmarks.Items.add(newItem);
end;
procedure TfmViewer.openBookmark(sender: TObject);
var
page : integer;
begin
page := TMenuItem(sender).tag;
//Viewer.GotoPageNum(page);
gotoPage(page);
end;
procedure TfmViewer.btnNewBookmarkClick(Sender: TObject);
var
bookmarkName : string;
bookmarkPage : integer;
begin
if curBook.isValid and (Viewer.IsPageValid>0)
and InputQuery(SNewBookMark,SBookmarkName,bookmarkName) then
begin
bookmarkPage:=curPageNo;
if curBook.addBookmark(bookmarkName,bookmarkPage) then
addBookmarkMenu(bookmarkName,bookmarkPage);
end;
end;
procedure TfmViewer.btnBookmarkManClick(Sender: TObject);
begin
if curBook.isValid then
begin
if dlgBookmarkMan.execute(curBook.Bookmarks) then
begin
clearBookmarks;
RestructBookmarks;
end;
end;
end;
procedure TfmViewer.RestructBooks;
var
i : integer;
begin
pmBooks.Items.clear;
for i:=0 to bookNames.count-1 do
begin
addBookMenu(bookNames[i]);
end;
end;
procedure TfmViewer.gotoBookmark(bookmarkIndex: integer);
begin
if (bookmarkIndex>=0) and (bookmarkIndex<curBook.Bookmarks.count) then
GotoPage(Integer(curBook.Bookmarks.objects[bookmarkIndex]));
end;
procedure TfmViewer.gotoPage(pageNo: integer);
begin
if pageNo>=0 then
Viewer.GotoContentNum(pageNo) else
Viewer.GotoDirNum(-pageNo);
end;
function TfmViewer.getcurPageNo: integer;
begin
if Viewer.isDir>0 then
result := -Viewer.PageNum else
result := Viewer.PageNum;
end;
procedure TfmViewer.ViewerMouseAction(Sender: TObject; flag: Integer;
Button, Shift: Smallint; x, y: Integer);
begin
if Button=Ord(VK_RBUTTON) then
begin
Popup(pmFunc);
end;
end;
procedure TfmViewer.ViewerProgress(Sender: TObject; filelength,
curpos: Integer);
begin
{
if Viewer.isDir>0 then
pnPageNo.caption := 'cont:'+IntToStr(Viewer.pagenum) else
pnPageNo.caption := IntToStr(Viewer.pagenum);
pnStatus.caption := 'Transfering...';
}
if filelength<>0 then
pnStatus.caption := Format('%d%%',[CurPos*100 div filelength]) else
pnStatus.caption := '';
end;
procedure TfmViewer.ViewerInitDrawing(Sender: TObject; URL: Integer);
begin
AfterLoadANewPage;
end;
procedure TfmViewer.AfterLoadANewPage;
begin
if Viewer.IsPageValid>0 then
pnStatus.caption := 'Complete' else
pnStatus.caption := 'Bad page';
pnZoom.Caption := format('%.1f%%',[Viewer.Zoom*100]);
pnOriginSize.caption := format('%d * %d',
[Viewer.OrgPageWidth,Viewer.OrgPageHeight]);
pnCurSize.Caption := format('%d * %d',
[Viewer.PageWidth,Viewer.PageHeight]);
updateViewPoint;
end;
end.
|
unit ClienteServidor;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, Datasnap.DBClient, Data.DB, System.Threading;
type
ESalvarArquivosError = class(System.SysUtils.Exception);
TServidor = class
private
FPath: String;
public
constructor Create;
//Tipo do par�metro n�o pode ser alterado
function SalvarArquivos(AData: OleVariant): Boolean;
end;
TfClienteServidor = class(TForm)
ProgressBar: TProgressBar;
btEnviarSemErros: TButton;
btEnviarComErros: TButton;
btEnviarParalelo: TButton;
procedure FormCreate(Sender: TObject);
procedure btEnviarSemErrosClick(Sender: TObject);
procedure btEnviarComErrosClick(Sender: TObject);
procedure btEnviarParaleloClick(Sender: TObject);
private
FPath: String;
FServidor: TServidor;
procedure RollBackOperation();
function InitDataset: TClientDataset;
public
end;
var
fClienteServidor: TfClienteServidor;
const
QTD_ARQUIVOS_ENVIAR = 100;
implementation
uses
IOUtils;
{$R *.dfm}
procedure TfClienteServidor.btEnviarComErrosClick(Sender: TObject);
var
cds: TClientDataset;
i: Integer;
begin
try
cds := InitDataset;
ProgressBar.Max := QTD_ARQUIVOS_ENVIAR;
for i := 0 to QTD_ARQUIVOS_ENVIAR do
begin
cds.Append;
cds.FieldByName('Arquivo').AsString := FPath;
cds.Post;
ProgressBar.Position := i;
{$REGION Simula��o de erro, n�o alterar}
if i = (QTD_ARQUIVOS_ENVIAR/2) then
FServidor.SalvarArquivos(NULL);
{$ENDREGION}
end;
FServidor.SalvarArquivos(cds.Data);
except
on E:Exception do
begin
RollBackOperation;
raise Exception.Create('Erro ao enviar os arquivos!'+#13#10+E.Message);
end;
end;
end;
procedure TfClienteServidor.btEnviarParaleloClick(Sender: TObject);
var
cds: TClientDataset;
i: Integer;
LArrayOfTaks: array [0..QTD_ARQUIVOS_ENVIAR] of ITask;
begin
cds := InitDataset;
ProgressBar.Max := QTD_ARQUIVOS_ENVIAR;
for i := 0 to QTD_ARQUIVOS_ENVIAR do
begin
LArrayOfTaks[i] := TTask.Create(
procedure
begin
TThread.Synchronize(nil,
procedure
begin
cds.Append;
cds.FieldByName('Arquivo').AsString := FPath;
cds.Post;
end);
end
);
LArrayOfTaks[i].Start;
ProgressBar.Position := ProgressBar.Position + 1;
end;
TTask.WaitForAll(LArrayOfTaks);
FServidor.SalvarArquivos(cds.Data);
end;
procedure TfClienteServidor.btEnviarSemErrosClick(Sender: TObject);
var
cds: TClientDataset;
i: Integer;
begin
cds := InitDataset;
ProgressBar.Max := QTD_ARQUIVOS_ENVIAR;
for i := 0 to QTD_ARQUIVOS_ENVIAR do
begin
cds.Append;
cds.FieldByName('Arquivo').AsString := FPath;
cds.Post;
ProgressBar.Position := ProgressBar.Position + 1;
end;
FServidor.SalvarArquivos(cds.Data);
end;
procedure TfClienteServidor.FormCreate(Sender: TObject);
begin
inherited;
ProgressBar.Position := 0;
FPath := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'pdf.pdf';
FServidor := TServidor.Create;
end;
function TfClienteServidor.InitDataset: TClientDataset;
begin
Result := TClientDataset.Create(nil);
Result.FieldDefs.Add('Arquivo', ftBlob);
Result.CreateDataSet;
end;
{ TServidor }
constructor TServidor.Create;
begin
FPath := ExtractFilePath(ParamStr(0)) + 'Servidor\';
end;
procedure TfClienteServidor.RollBackOperation;
var
i: integer;
Arq: TSearchRec;
begin
I := FindFirst(FPath+'*.*', faAnyFile, Arq);
while I = 0 do
begin
DeleteFile(FPath + Arq.Name);
I := FindNext(Arq);
end;
end;
function TServidor.SalvarArquivos(AData: OleVariant): Boolean;
var
cds: TClientDataSet;
FileName: string;
LMemoryStream: TMemoryStream;
begin
Result := False;
LMemoryStream := TMemoryStream.Create;
try
cds := TClientDataset.Create(nil);
try
cds.Data := AData;
{$REGION Simula��o de erro, n�o alterar}
if cds.RecordCount = 0 then
Exit;
{$ENDREGION}
cds.First;
while not cds.Eof do
begin
LMemoryStream.LoadFromFile(cds.FieldByName('Arquivo').AsString);
FileName := FPath + cds.RecNo.ToString + '.pdf';
if TFile.Exists(FileName) then
TFile.Delete(FileName);
LMemoryStream.SaveToFile(FileName);
cds.Next;
end;
Result := True;
finally
cds.Free;
LMemoryStream.Free;
end;
except
on E:Exception do
begin
E.ThrowOuterException(ESalvarArquivosError.Create('Erro ao salvar os arquivos!'+#13#10+E.Message));
end;
end;
end;
end.
|
unit fMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, GameModules, Menus, ActnList, Buttons;
type
TGameAction = ( gaNone, gaRestart, gaKeyUp, gaKeyDown, gaKeyLeft, gaKeyRight );
TActionConfig = record
Keys : array[TGameAction] of Byte;
end;
TfrmMain = class(TForm)
pnlInfo: TPanel;
pnlGame: TPanel;
imgMap: TImage;
MainMenu1: TMainMenu;
Game1: TMenuItem;
Help1: TMenuItem;
mnNewGame: TMenuItem;
mnAbout: TMenuItem;
mnConfigure: TMenuItem;
mnExit: TMenuItem;
lblScore: TStaticText;
StaticText2: TStaticText;
ActionList1: TActionList;
actNewGame: TAction;
actConfig: TAction;
actExit: TAction;
actAbout: TAction;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
SpeedButton3: TSpeedButton;
SpeedButton4: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure actNewGameExecute(Sender: TObject);
procedure actConfigExecute(Sender: TObject);
procedure actExitExecute(Sender: TObject);
procedure actAboutExecute(Sender: TObject);
private
FGame : TGameController;
FKeyActions : array[0..127] of TGameAction;
FActionStack : Integer;
procedure UpdateScore(Score: Integer);
procedure PlayAction(Action: TGameAction);
public
FActCfg : TActionConfig;
procedure SetupActionKeys(const ActCfg: TActionConfig);
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
uses
fConfig;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
ClientWidth := 800;
ClientHeight := 600;
FGame := TGameController.Create(imgMap.Canvas, imgMap.Height);
FGame.DrawBackground;
FGame.DrawTiles;
with FActCfg do
begin
Keys[gaKeyUp] := VK_UP;
Keys[gaKeyDown] := VK_DOWN;
Keys[gaKeyLeft] := VK_LEFT;
Keys[gaKeyRight] := VK_RIGHT;
end;
SetupActionKeys(FActCfg);
end;
procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TfrmMain.UpdateScore(Score: Integer);
begin
lblScore.Caption := Format('%d', [Score]);
FGame.DrawTiles;
end;
procedure TfrmMain.FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if(Key<127)then
begin
PlayAction(FKeyActions[Key]);
end;
end;
procedure TfrmMain.SetupActionKeys(const ActCfg: TActionConfig);
var
ga : TGameAction;
begin
FActCfg := ActCfg;
FillChar(FKeyActions, SizeOf(FKeyActions), gaNone);
for ga:=gaKeyUp to High(TGameAction) do
begin
FKeyActions[ActCfg.Keys[ga]] := ga;
end;
end;
procedure TfrmMain.PlayAction(Action: TGameAction);
begin
if (FActionStack>1) then
Exit;
Inc(FActionStack);
case Action of
gaKeyUp :
FGame.MoveTiles(maUp);
gaKeyDown :
FGame.MoveTiles(maDown);
gaKeyLeft :
FGame.MoveTiles(maLeft);
gaKeyRight :
FGame.MoveTiles(maRight);
else
begin
Dec(FActionStack);
Exit;
end;
end;
UpdateScore(FGame.Score);
Dec(FActionStack);
end;
procedure TfrmMain.actNewGameExecute(Sender: TObject);
begin
FGame.RestartGame;
UpdateScore(FGame.Score);
end;
procedure TfrmMain.actConfigExecute(Sender: TObject);
begin
frmConfig.ConfigAction;
end;
procedure TfrmMain.actExitExecute(Sender: TObject);
begin
Close;
end;
procedure TfrmMain.actAboutExecute(Sender: TObject);
begin
MessageBox(Handle, 'By eGust', 'About', 0);
end;
end.
|
unit SendDebt;
interface
uses
AncestorEditDialog, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters,
Vcl.Menus, cxControls, cxContainer, cxEdit, Vcl.ComCtrls, dxCore, cxDateUtils,
dsdGuides, cxDropDownEdit, cxCalendar, cxMaskEdit, cxButtonEdit, cxTextEdit,
cxCurrencyEdit, Vcl.Controls, cxLabel, dsdDB, dsdAction, System.Classes,
Vcl.ActnList, cxPropertiesStore, dsdAddOn, Vcl.StdCtrls, cxButtons,
dxSkinsCore, dxSkinsDefaultPainters, cxCheckBox;
type
TSendDebtForm = class(TAncestorEditDialogForm)
cxLabel1: TcxLabel;
Код: TcxLabel;
ceInvNumber: TcxCurrencyEdit;
cxLabel2: TcxLabel;
cxLabel5: TcxLabel;
cePaidKindFrom: TcxButtonEdit;
ceInfoMoneyFrom: TcxButtonEdit;
ceOperDate: TcxDateEdit;
PaidKindFromGuides: TdsdGuides;
InfoMoneyFromGuides: TdsdGuides;
ceJuridicalFrom: TcxButtonEdit;
cxLabel6: TcxLabel;
GuidesFiller: TGuidesFiller;
ceContractFrom: TcxButtonEdit;
cxLabel8: TcxLabel;
cxLabel10: TcxLabel;
ceComment: TcxTextEdit;
ContractFromGuides: TdsdGuides;
cxLabel4: TcxLabel;
ceAmount: TcxCurrencyEdit;
ContractJuridicalFromGuides: TdsdGuides;
cxLabel3: TcxLabel;
ceJuridicalTo: TcxButtonEdit;
ContractToGuides: TdsdGuides;
cxLabel7: TcxLabel;
ceInfoMoneyTo: TcxButtonEdit;
InfoMoneyToGuides: TdsdGuides;
cxLabel9: TcxLabel;
cxLabel11: TcxLabel;
cePaidKindTo: TcxButtonEdit;
ceContractTo: TcxButtonEdit;
PaidKindToGuides: TdsdGuides;
ContractJuridicalToGuides: TdsdGuides;
cePartnerFrom: TcxButtonEdit;
cxLabel12: TcxLabel;
PartnerFromGuides: TdsdGuides;
cePartnerTo: TcxButtonEdit;
cxLabel13: TcxLabel;
PartnerToGuides: TdsdGuides;
ceBranchFrom: TcxButtonEdit;
cxLabel14: TcxLabel;
BranchFromGuides: TdsdGuides;
ceBranchTo: TcxButtonEdit;
cxLabel15: TcxLabel;
BranchToGuides: TdsdGuides;
cxLabel16: TcxLabel;
ceCurrencyValueFrom: TcxCurrencyEdit;
ceParValueFrom: TcxCurrencyEdit;
cxLabel17: TcxLabel;
ceCurrencyFrom: TcxButtonEdit;
cxLabel18: TcxLabel;
GuidesCurrencyFrom: TdsdGuides;
cxLabel19: TcxLabel;
ceAmountCurrencyFrom: TcxCurrencyEdit;
cxLabel20: TcxLabel;
ceCurrencyValueTo: TcxCurrencyEdit;
ceParValueTo: TcxCurrencyEdit;
cxLabel21: TcxLabel;
cxLabel22: TcxLabel;
ceCurrencyTo: TcxButtonEdit;
GuidesCurrencyTo: TdsdGuides;
ceAmountCurrencyTo: TcxCurrencyEdit;
cxLabel23: TcxLabel;
cbisCopy: TcxCheckBox;
RefreshDispatcher: TRefreshDispatcher;
spGet_AmountCurr: TdsdStoredProc;
actRefreshAmountCurr: TdsdDataSetRefresh;
actCheckRight: TdsdExecStoredProc;
spCheckRight: TdsdStoredProc;
OpenChoiceFormContractFrom: TOpenChoiceForm;
macCheckRight_From: TMultiAction;
OpenChoiceFormContractTo: TOpenChoiceForm;
macCheckRight_To: TMultiAction;
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.dfm}
initialization
RegisterClass(TSendDebtForm);
end.
|
unit uBase;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
Windows,
fgl,
uModbus;
type
{ TBase }
{
Базовый класс библиотеки
Содержит методы работы с кодами ошибок
Все классы должны быть унаследованы от него
}
TBase = class(TInterfacedObject)
type
TErrors = specialize TFpgMap<Integer, String>;
protected
fLastError: dword;
fErrors: TErrors;
public
constructor Create;
destructor Destroy; override;
// Установить ошибку
procedure SetLastError(const aError: dword);
// Возвращает код ошибки, одновременно сбрасывая его в памяти
function GetLastError: dword;
// Возвращает описание ошибки, в т.ч. системной
function GetErrorDesc(const aError: dword): String;
end;
{ TPriorityItem }
{
Базовый класс-элемент кучи
}
TPriorityItem = class(TBase, IPriorityItem)
private
fPriority: TPriority;
protected
function GetPriority: TPriority;
procedure SetPriority(const aPriority: TPriority);
public
constructor Create;
public
property Priority: TPriority read GetPriority write SetPriority;
end;
{ THeap }
{
Куча для реализации очереди с приоритетами
LeftChild = Root * 2 + 1
RightChild = LeftChild + 1
Parent = (New - 1) div 2
}
THeap = class(TBase)
private
fItems: array of IPriorityItem;
fSize: Word;
fCapacity: Word;
private
procedure Swap(aIndex1, aIndex2: Integer);
protected
procedure ReBuild(const aParent: Word); virtual;
public
constructor Create(const aCapacity: Word); reintroduce;
procedure AfterConstruction; override;
destructor Destroy; override;
public
function IsEmpty: Boolean;
procedure Delete(out aItem: IPriorityItem);
procedure Insert(const aItem: IPriorityItem);
end;
{ TThreadSafeWrapper }
{
Потокобезопасный доступ к типу данных T (простой тип данных, массив,
класс) через критическую секцию
}
generic TThreadSafeWrapper<T> = class(TBase)
private
fLock: TRtlCriticalSection;
protected
fT: T;
public
constructor Create;
destructor Destroy; override;
function Lock: T;
procedure Unlock;
end;
{ TThreadSafePriorityQueue }
TThreadSafePriorityQueueSpec = specialize TThreadSafeWrapper<THeap>;
TThreadSafePriorityQueue = class(TThreadSafePriorityQueueSpec)
protected
fPushEvent: THandle;
public
constructor Create(const aCapacity: Word);
reintroduce; virtual;
destructor Destroy; override;
public
function Push(const aItem: IPriorityItem): Boolean;
function Pop(out aItem: IPriorityItem): Boolean;
end;
{ TClipboard - буфер обмена}
TBufferSpec = specialize TThreadSafeWrapper<TBuffer>;
TClipboard = class(TBufferSpec)
private
// Количество записанных в буфер обмена байт
fCount: Longint;
protected
function GetCount: Longint;
procedure SetCount(const aCount: Longint);
function GetBuffer: PBuffer;
public
property Count: Longint read GetCount write SetCount;
property Buffer: PBuffer read GetBuffer;
end;
{ TCrc16 }
TCrc16 = class
const
CrcTable: array [Byte] of Word = {$REGION CRC16 TABLE}
($0000, $C0C1, $C181, $0140, $C301, $03C0, $0280, $C241, $C601, $06C0,
$0780, $C741, $0500, $C5C1, $C481, $0440, $CC01, $0CC0, $0D80, $CD41,
$0F00, $CFC1, $CE81, $0E40, $0A00, $CAC1, $CB81, $0B40, $C901, $09C0,
$0880, $C841, $D801, $18C0, $1980, $D941, $1B00, $DBC1, $DA81, $1A40,
$1E00, $DEC1, $DF81, $1F40, $DD01, $1DC0, $1C80, $DC41, $1400, $D4C1,
$D581, $1540, $D701, $17C0, $1680, $D641, $D201, $12C0, $1380, $D341,
$1100, $D1C1, $D081, $1040, $F001, $30C0, $3180, $F141, $3300, $F3C1,
$F281, $3240, $3600, $F6C1, $F781, $3740, $F501, $35C0, $3480, $F441,
$3C00, $FCC1, $FD81, $3D40, $FF01, $3FC0, $3E80, $FE41, $FA01, $3AC0,
$3B80, $FB41, $3900, $F9C1, $F881, $3840, $2800, $E8C1, $E981, $2940,
$EB01, $2BC0, $2A80, $EA41, $EE01, $2EC0, $2F80, $EF41, $2D00, $EDC1,
$EC81, $2C40, $E401, $24C0, $2580, $E541, $2700, $E7C1, $E681, $2640,
$2200, $E2C1, $E381, $2340, $E101, $21C0, $2080, $E041, $A001, $60C0,
$6180, $A141, $6300, $A3C1, $A281, $6240, $6600, $A6C1, $A781, $6740,
$A501, $65C0, $6480, $A441, $6C00, $ACC1, $AD81, $6D40, $AF01, $6FC0,
$6E80, $AE41, $AA01, $6AC0, $6B80, $AB41, $6900, $A9C1, $A881, $6840,
$7800, $B8C1, $B981, $7940, $BB01, $7BC0, $7A80, $BA41, $BE01, $7EC0,
$7F80, $BF41, $7D00, $BDC1, $BC81, $7C40, $B401, $74C0, $7580, $B541,
$7700, $B7C1, $B681, $7640, $7200, $B2C1, $B381, $7340, $B101, $71C0,
$7080, $B041, $5000, $90C1, $9181, $5140, $9301, $53C0, $5280, $9241,
$9601, $56C0, $5780, $9741, $5500, $95C1, $9481, $5440, $9C01, $5CC0,
$5D80, $9D41, $5F00, $9FC1, $9E81, $5E40, $5A00, $9AC1, $9B81, $5B40,
$9901, $59C0, $5880, $9841, $8801, $48C0, $4980, $8941, $4B00, $8BC1,
$8A81, $4A40, $4E00, $8EC1, $8F81, $4F40, $8D01, $4DC0, $4C80, $8C41,
$4400, $84C1, $8581, $4540, $8701, $47C0, $4680, $8641, $8201, $42C0,
$4380, $8341, $4100, $81C1, $8081, $4040);
{$ENDREGION CRC16 TABLE}
public
class procedure CalcCrc16(const aBuffer: PBuffer; const aCount: Longint;
var aCrc16: Word);
end;
implementation
{ TThreadSafePriorityQueue }
constructor TThreadSafePriorityQueue.Create(const aCapacity: Word);
begin
inherited Create;
fT := THeap.Create(aCapacity);
fPushEvent := CreateEvent(nil, False, False, '');
end;
destructor TThreadSafePriorityQueue.Destroy;
begin
CloseHandle(fPushEvent);
inherited Destroy;
FreeAndNil(fT);
end;
function TThreadSafePriorityQueue.Push(const aItem: IPriorityItem): Boolean;
var
Heap: THeap;
begin
Result := False;
Heap := Lock;
try
Heap.Insert(aItem);
if Heap.GetLastError = 0 then
begin
// Сигнализировать поток о помещении в очередь очередного элемента
SetEvent(fPushEvent);
Result := True;
end;
finally
Unlock;
end;
end;
function TThreadSafePriorityQueue.Pop(out aItem: IPriorityItem): Boolean;
var
Heap: THeap;
begin
Result := False;
Heap := Lock;
try
Heap.Delete(aItem);
if Heap.GetLastError = 0 then
Result := True;
finally
Unlock;
end;
end;
{ TBase }
constructor TBase.Create;
begin
inherited Create;
fErrors := TErrors.Create;
end;
destructor TBase.Destroy;
begin
FreeAndNil(fErrors);
inherited Destroy;
end;
procedure TBase.SetLastError(const aError: dword);
begin
fLastError := aError;
end;
function TBase.GetLastError: dword;
begin
Result := fLastError;
if fLastError = 0 then
Result := GetLastError;
fLastError := 0;
end;
function TBase.GetErrorDesc(const aError: dword): String;
begin
if aError <> 0 then
Result := fErrors.KeyData[aError]
else
Result := SysErrorMessage(Windows.GetLastError);
end;
{$REGION HEAP}
{ TPriorityItem }
constructor TPriorityItem.Create;
begin
inherited Create;
fPriority := TPriority.prLow;
end;
function TPriorityItem.GetPriority: TPriority;
begin
Result := fPriority;
end;
procedure TPriorityItem.SetPriority(const aPriority: TPriority);
begin
fPriority := aPriority;
end;
const
ERROR_HEAP_FULL = 1;
ERROR_HEAP_EMPTY = 2;
resourcestring
sERROR_HEAP_FULL = 'Куча заполнена';
sERROR_HEAP_EMPTY = 'Куча пуста';
{ THeap }
constructor THeap.Create(const aCapacity: Word);
begin
inherited Create;
fSize := 0;
// Емкость кучи
fCapacity := aCapacity;
SetLength(fItems, aCapacity);
end;
procedure THeap.AfterConstruction;
begin
inherited AfterConstruction;
fErrors.Add(ERROR_HEAP_FULL, sERROR_HEAP_FULL);
fErrors.Add(ERROR_HEAP_EMPTY, sERROR_HEAP_EMPTY);
end;
destructor THeap.Destroy;
begin
fItems := nil;
inherited Destroy;
end;
function THeap.IsEmpty: Boolean;
begin
//Определяет,пуста ли куча.
//Предусловие:нет.
//Постусловие:если куча пуста,возвращает значение true;
//в противном случае возвращает значение false
Result := fSize = 0;
end;
procedure THeap.Insert(const aItem: IPriorityItem);
var
Place, Parent: Integer;
begin
// Вставляет новый элемент за последним узлом кучи
// и перемещает его вверх по дереву на соответствующую позицию.
// Куча считается полной, если она содержит максимальное кол-во элементов.
// Проверка места в кучи
if fSize >= fCapacity then
begin
fLastError := ERROR_HEAP_FULL;
Exit;
end;
//Размещаем новый элемент в конце кучи
fItems[fSize] := aItem;
//Перемещаем новый элемент на подходящую позицию
Place := fSize;
Parent := (Place - 1) div 2;
while (Parent >= 0) and (fItems[Place].Priority > fItems[Parent].Priority) do
begin
//Меняем местами элементы
Swap(Place, Parent);
Place := Parent;
Parent := (Place - 1) div 2;
end;
Inc(fSize, 1);
end;
procedure THeap.Delete(out aItem: IPriorityItem);
begin
// Проверка кучи
if IsEmpty then
begin
fLastError := ERROR_HEAP_EMPTY;
Exit;
end;
//Извлекает и удаляет элемент из корня кучи.
//Данный элемент имеет наибольшее значение ключа.
// ! Указатель перемещаем, если не использовать fItems[0] := nil,
// ! происходит утечка памяти
aItem := fItems[0];
fItems[0] := nil;
// Меняет местами последний элемент кучи с корнем
// и перемещает его вниз подереву,пока не будет обнаружена подходящая позиция.
fItems[0] := fItems[fSize - 1];
fItems[fSize - 1] := nil;
Dec(fSize, 1);
Rebuild(0);
end;
procedure THeap.ReBuild(const aParent: Word);
var
Child, RightChild: Word;
begin
// Если корень не является листом,
// и ключ корня меньше ключей его дочерних узлов
//Индекс левого дочернего узла корня
Child := aParent * 2 + 1;
// ... если он существует
if (Child < fSize) then
begin
//Корень не является листом, поэтому имеет левый дочерний узел
//Индекс правого дочернего узла
RightChild := Child + 1;
// ... если он существует
// ... найти наибольший элемент между дочерними узлами
if (RightChild < fSize) and (fItems[RightChild].Priority >
fItems[Child].Priority) then
// Индекс наибольшего дочернего узла корня
Child := RightChild;
// Если ключ корня меньше ключа его наибольшего узла
if (fItems[aParent].Priority < fItems[Child].Priority) then
begin
// Меняем местами элементы
Swap(Child, aParent);
// Преобразовываем новое поддерево в кучу
Rebuild(Child);
end;
end;
end;
procedure THeap.Swap(aIndex1, aIndex2: Integer);
var
Temp: IPriorityItem;
begin
Temp := fItems[aIndex1];
fItems[aIndex1] := fItems[aIndex2];
fItems[aIndex2] := Temp;
end;
{$ENDREGION HEAP}
{ TThreadSafeWrapper }
constructor TThreadSafeWrapper.Create;
begin
inherited Create;
InitCriticalSection(fLock);
end;
destructor TThreadSafeWrapper.Destroy;
begin
Lock;
try
inherited Destroy;
finally
Unlock;
DoneCriticalSection(fLock);
end;
end;
function TThreadSafeWrapper.Lock: T;
begin
Result := fT;
System.EnterCriticalSection(fLock);
end;
procedure TThreadSafeWrapper.Unlock;
begin
System.LeaveCriticalSection(fLock);
end;
{ TClipboard }
function TClipboard.GetCount: Longint;
begin
Result := Windows.InterlockedCompareExchange(fCount, 0, 0);
end;
procedure TClipboard.SetCount(const aCount: Longint);
begin
Windows.InterLockedExchange(fCount, aCount);
end;
function TClipboard.GetBuffer: PBuffer;
begin
Result := @fT;
end;
{ TCrc16 }
class procedure TCrc16.CalcCrc16(const aBuffer: PBuffer; const aCount: Longint;
var aCrc16: Word);
var
Index: Byte;
I: Integer;
begin
for I := 0 to aCount - 1 do
begin
Index := aBuffer^[I] xor aCrc16;
aCrc16 := aCrc16 shr 8 xor CRCTable[Index];
end;
end;
end.
|
{*******************************************************************************
*
* (C) COPYRIGHT AUTHORS, 2006 - 2021
*
* TITLE: scmsup.pas
*
* VERSION: 5.51
*
* DATE: 17 May 2021
*
* SCM support routines for drivers load/unload.
* ObjFPC variant
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
* ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
* PARTICULAR PURPOSE.
*
*******************************************************************************}
unit scmsup;
{$mode objfpc}{$H+}
interface
uses
Windows, jwawinsvc, Classes, SysUtils;
function scmOpenManager(DesiredAccess: DWORD; var schSCManager: THANDLE;
var lpStatus: DWORD): boolean;
function scmCloseManager(var schSCManager: THANDLE; var lpStatus: DWORD): boolean;
function scmInstallDriver(SchSCManager: SC_HANDLE; Name: LPCTSTR;
DisplayName: LPCTSTR; StartType: DWORD; ErrorControl: DWORD;
DriverBinary: LPCTSTR; var lpStatus: DWORD): boolean;
function scmRemoveDriver(SchSCManager: SC_HANDLE; DriverName: LPCTSTR;
var lpStatus: DWORD): boolean;
function scmStartDriver(SchSCManager: SC_HANDLE; DriverName: LPCTSTR;
var lpStatus: DWORD): boolean;
function scmStopDriver(SchSCManager: SC_HANDLE; DriverName: LPCTSTR;
var lpStatus: DWORD): boolean;
implementation
{*
* scmOpenManager
*
* Purpose:
*
* Open handle for local SCM database.
*
*}
function scmOpenManager(DesiredAccess: DWORD; var schSCManager: THANDLE;
var lpStatus: DWORD): boolean;
begin
schSCManager := OpenSCManager(nil, nil, DesiredAccess);
lpStatus := GetLastError();
Result := (lpStatus = ERROR_SUCCESS);
end;
{*
* scmCloseManager
*
* Purpose:
*
* Close handle for local SCM database.
*
*}
function scmCloseManager(var schSCManager: THANDLE; var lpStatus: DWORD): boolean;
begin
if (schSCManager <> 0) then
begin
if (CloseServiceHandle(schSCManager)) then
schSCManager := 0;
lpStatus := GetLastError();
end
else
begin
lpStatus := ERROR_INVALID_PARAMETER;
end;
Result := (lpStatus = ERROR_SUCCESS);
end;
{*
* scmInstallDriver
*
* Purpose:
*
* Create SCM service entry describing kernel driver.
*
*}
function scmInstallDriver(SchSCManager: SC_HANDLE; Name: LPCTSTR;
DisplayName: LPCTSTR; StartType: DWORD; ErrorControl: DWORD;
DriverBinary: LPCTSTR; var lpStatus: DWORD): boolean;
var
schService: SC_HANDLE;
begin
schService := CreateService(SchSCManager, // SCManager database
Name, // name of service
DisplayName, // name to display
SERVICE_ALL_ACCESS, // desired access
SERVICE_KERNEL_DRIVER, // service type
StartType, // start type
ErrorControl, // error control type
DriverBinary, // service's binary
nil, // no load ordering group
nil, // no tag identifier
nil, // no dependencies
nil, // LocalSystem account
nil // no password
);
lpStatus := GetLastError();
if (schService <> 0) then
CloseServiceHandle(schService);
Result := (lpStatus = ERROR_SUCCESS);
end;
{*
* scmStartDriver
*
* Purpose:
*
* Start service, resulting in SCM drvier load.
*
*}
function scmStartDriver(SchSCManager: SC_HANDLE; DriverName: LPCTSTR;
var lpStatus: DWORD): boolean;
var
bResult: boolean;
schService: SC_HANDLE;
begin
schService := OpenService(SchSCManager, DriverName, SERVICE_ALL_ACCESS);
lpStatus := GetLastError();
if (schService <> 0) then
begin
bResult := StartService(schService, 0, nil);
lpStatus := GetLastError();
if (lpStatus = ERROR_SERVICE_ALREADY_RUNNING) then
begin
bResult := True;
lpStatus := ERROR_SUCCESS;
end;
CloseServiceHandle(schService);
end;
Result := (bResult <> False);
end;
{*
* scmStopDriver
*
* Purpose:
*
* Command SCM to stop service, resulting in driver unload.
*
*}
function scmStopDriver(SchSCManager: SC_HANDLE; DriverName: LPCTSTR;
var lpStatus: DWORD): boolean;
var
bResult: boolean;
schService: SC_HANDLE;
iRetryCount: integer;
serviceStatus: SERVICE_STATUS;
begin
schService := OpenService(SchSCManager, DriverName, SERVICE_ALL_ACCESS);
lpStatus := GetLastError();
if (schService <> 0) then
begin
for iRetryCount := 5 downto 0 do
begin
SetLastError(ERROR_SUCCESS);
ZeroMemory(@serviceStatus, sizeof(serviceStatus));
bResult := ControlService(schService, SERVICE_CONTROL_STOP, serviceStatus);
lpStatus := GetLastError();
if (bResult <> False) then
break;
if (lpStatus <> ERROR_DEPENDENT_SERVICES_RUNNING) then
break;
Sleep(1000);
end;
CloseServiceHandle(schService);
end;
Result := (bResult <> False);
end;
{*
* scmRemoveDriver
*
* Purpose:
*
* Remove service entry from SCM database.
*
*}
function scmRemoveDriver(SchSCManager: SC_HANDLE; DriverName: LPCTSTR;
var lpStatus: DWORD): boolean;
var
bResult: boolean;
schService: SC_HANDLE;
begin
schService := OpenService(SchSCManager, DriverName, SERVICE_ALL_ACCESS);
lpStatus := GetLastError();
if (schService <> 0) then
begin
bResult := DeleteService(schService);
lpStatus := GetLastError();
CloseServiceHandle(schService);
end;
Result := (bResult <> False);
end;
{*
* scmUnloadDeviceDriver
*
* Purpose:
*
* Combines scmStopDriver and scmRemoveDriver.
*
*}
function scmUnloadDeviceDriver(DriverName: LPCTSTR; var lpStatus: DWORD): boolean;
var
schSCManager: SC_HANDLE;
begin
Result := False;
lpStatus := ERROR_SUCCESS;
if (DriverName <> nil) then
begin
schSCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
if (schSCManager <> 0) then
begin
scmStopDriver(schSCManager, DriverName, lpStatus);
Result := scmRemoveDriver(schSCManager, DriverName, lpStatus);
CloseServiceHandle(schSCManager);
end;
end
else
begin
lpStatus := ERROR_INVALID_PARAMETER;
end;
end;
{*
* scmOpenDevice
*
* Purpose:
*
* Open driver device by symbolic link.
*
*}
function scmOpenDevice(DriverName: LPCTSTR; var lpDeviceHandle: THANDLE;
var lpStatus: DWORD): boolean;
var
DeviceName: string;
begin
if (DriverName <> nil) then
begin
try
DeviceName := Format('\\.\%s:', [DriverName]);
except
Result := False;
lpStatus := ERROR_INTERNAL_ERROR;
exit;
end;
lpDeviceHandle := CreateFile(PChar(DeviceName), GENERIC_READ or
GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
Result := (lpDeviceHandle <> INVALID_HANDLE_VALUE);
end
else
begin
Result := False;
lpStatus := ERROR_INVALID_PARAMETER;
end;
end;
{*
* scmLoadDeviceDriver
*
* Purpose:
*
* Unload if already exists, Create, Load and Open driver instance.
*
*}
function scmLoadDeviceDriver(DriverName: LPCTSTR; DisplayName: LPCTSTR;
DriverPath: LPCTSTR; StartType: DWORD; ErrorControlType: DWORD;
ForceReload: boolean; var lpDeviceHandle: THANDLE; var lpStatus: DWORD): boolean;
var
schSCManager: SC_HANDLE;
begin
Result := False;
lpStatus := ERROR_INVALID_PARAMETER;
lpDeviceHandle := 0;
if (DriverName = nil) then
exit;
schSCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
if (schSCManager <> 0) then
begin
if (ForceReload) then
scmRemoveDriver(schSCManager, DriverName, lpStatus);
if (scmInstallDriver(schSCManager, DriverName, DisplayName,
StartType, ErrorControlType, DriverPath, lpStatus)) then
begin
if (scmStartDriver(schSCManager, DriverName, lpStatus)) then
begin
Result := scmOpenDevice(DriverName, lpDeviceHandle, lpStatus);
end;
end;
CloseServiceHandle(schSCManager);
end
else
begin
lpStatus := GetLastError();
end;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Generics.Collections, StdCtrls, Generics.Defaults;
type
TPerson = class
private
FFirstname: string;
FLastname: string;
FAge: Integer;
public
function ToString: string; override;
property Firstname: string read FFirstname write FFirstname;
property Lastname: string read FLastname write FLastname;
property Age: Integer read FAge write FAge;
constructor Create(const Firstname, Lastname : string; Age : Integer); virtual;
end;
TPersonComparer = class(TInterfacedObject, IComparer<TPerson>)
public
function Compare(const Left, Right: TPerson): Integer;
end;
TForm1 = class(TForm)
Button1: TButton;
ListBox1: TListBox;
Button2: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
FPersonList : TObjectList<TPerson>;
procedure LoadListbox;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
LoadListbox;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
FPersonList.Sort(TPersonComparer.Create);
LoadListbox;
end;
procedure TForm1.LoadListbox;
var
Person: TPerson;
begin
ListBox1.Clear;
for Person in FPersonList do
ListBox1.Items.Add(Person.ToString);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FPersonList := TObjectList<TPerson>.Create(True);
FPersonList.Add(TPerson.Create('Fred', 'Flintstone', 40));
FPersonList.Add(TPerson.Create('Wilma', 'Flintstone', 38));
FPersonList.Add(TPerson.Create('Pebbles', 'Flintstone', 1));
FPersonList.Add(TPerson.Create('Barney', 'Rubble', 38));
FPersonList.Add(TPerson.Create('Betty', 'Rubble', 40));
FPersonList.Add(TPerson.Create('Bam Bam', 'Rubble', 2));
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FPersonList.Free;
end;
{ TPerson }
constructor TPerson.Create(const Firstname, Lastname : string; Age : Integer);
begin
self.Lastname := Lastname;
self.Firstname := Firstname;
self.Age := Age;
end;
function TPerson.ToString: string;
begin
Result := Format('%s %s : Age %d', [Firstname, Lastname, Age]);
end;
{ TPersonComparer }
function TPersonComparer.Compare(const Left, Right: TPerson): Integer;
begin
Result := CompareText(Left.Lastname + Left.Firstname, Right.Lastname + Right.Firstname);
end;
end.
|
unit TelegraPh;
interface
uses
TelegraPh.Types,
TelegAPI.Bot.Impl;
type
TTelegraPh = class(TTelegramBotBase)
protected
procedure DoInitApiCore; override;
public
function createAccount(const ShortName: string; const AuthorName: string =
''; const AuthorUrl: string = ''): IphAccount;
function editAccountInfo(const AccessToken: string; const ShortName: string
= ''; const AuthorName: string = ''; const AuthorUrl: string = ''): IphAccount;
function getAccountInfo(const AccessToken: string): IphAccount;
function revokeAccessToken(const AccessToken: string): IphAccount;
function createPage(const AccessToken: string; const title: string; const
author_name: string = ''; const author_url: string = ''; const content:
TphContent = nil; const return_content: Boolean = False): IphPage;
function editPage(const AccessToken: string; const path: string; const title:
string; const content: TphContent; const author_name: string = ''; const
author_url: string = ''; const return_content: Boolean = False): IphPage;
function getPage(const path: string; const return_content: Boolean = False): IphPage;
function getPageList(const access_token: string; const offset: Integer = 0;
const limit: Integer = 50): IphPageList;
function getViews(const path: string; const year: Integer = 0; const month:
Integer = 0; const day: Integer = 0; const hour: Integer = 0): IphPageViews;
published
property UrlAPI;
end;
implementation
uses
TelegAPI.Utils.Json,
System.SysUtils,
System.JSON;
{ TTelegraPh }
function TTelegraPh.createAccount(const ShortName, AuthorName, AuthorUrl: string):
IphAccount;
begin
Result := TphAccount.Create(//
GetRequest.SetMethod('createAccount')//
.AddParameter('short_name', ShortName, '', True)//
.AddParameter('author_name', AuthorName, '', False)//
.AddParameter('author_url', AuthorUrl, '', False)//
.Execute);
end;
function TTelegraPh.createPage(const AccessToken, title, author_name, author_url:
string; const content: TphContent; const return_content: Boolean): IphPage;
begin
Result := TphPage.Create(//
GetRequest.SetMethod('createPage')//
.AddParameter('access_token', AccessToken, '', True)//
.AddParameter('title', title, '', True)//
.AddParameter('author_name', author_name, '', False)//
.AddParameter('author_url', author_url, '', False)//
.AddParameter('content', content.ToJson, TphContent(nil).ToJson, False)//
.AddParameter('return_content', return_content, False, False)//
.Execute);
end;
procedure TTelegraPh.DoInitApiCore;
begin
inherited;
UrlAPI := 'https://api.telegra.ph/';
GetRequest.DataExtractor :=
function(AInput: string): string
var
LJSON: TJSONObject;
begin
Result := '';
if AInput.IsEmpty or AInput.StartsWith('<html') then
Exit;
LJSON := TJSONObject.ParseJSONValue(AInput) as TJSONObject;
try
if LJSON.GetValue('ok') is TJSONFalse then
Logger.Error((LJSON.GetValue('error') as TJSONString).Value)
else
Result := LJSON.GetValue('result').ToString;
finally
LJSON.Free;
end;
end;
end;
function TTelegraPh.editAccountInfo(const AccessToken, ShortName, AuthorName,
AuthorUrl: string): IphAccount;
begin
Result := TphAccount.Create(//
GetRequest.SetMethod('editAccountInfo')//
.AddParameter('access_token', AccessToken, '', True)//
.AddParameter('short_name', ShortName, '', False)//
.AddParameter('author_name', AuthorName, '', False)//
.AddParameter('author_url', AuthorUrl, '', False)//
.Execute);
end;
function TTelegraPh.editPage(const AccessToken, Path, title: string; const
content: TphContent; const author_name, author_url: string; const
return_content: Boolean): IphPage;
begin
Result := TphPage.Create(//
GetRequest.SetMethod('editPage')//
.AddParameter('access_token', AccessToken, '', True)//
.AddParameter('path', Path, '', True)//
.AddParameter('title', title, '', True)//
.AddParameter('content', content.ToJson, TphContent(nil).ToJson, True)//
.AddParameter('author_name', author_name, '', False)//
.AddParameter('author_url', author_url, '', False)//
.AddParameter('return_content', return_content, False, False)//
.Execute);
end;
function TTelegraPh.getAccountInfo(const AccessToken: string): IphAccount;
begin
Result := TphAccount.Create(//
GetRequest.SetMethod('getAccountInfo')//
.AddParameter('access_token', AccessToken, '', True)//
.AddParameter('fields',
'["short_name","author_name","author_url", "auth_url", "page_count"]', '', False)//
.Execute);
end;
function TTelegraPh.getPage(const path: string; const return_content: Boolean): IphPage;
begin
Result := TphPage.Create(//
GetRequest.SetMethod('getPage')//
.AddParameter('path', path, '', True)//
.AddParameter('return_content', return_content, False, False)//
.Execute);
end;
function TTelegraPh.getPageList(const access_token: string; const offset, limit:
Integer): IphPageList;
begin
Result := TphPageList.Create(//
GetRequest.SetMethod('getPageList')//
.AddParameter('access_token', access_token, '', True)//
.AddParameter('offset', offset, 0, False)//
.AddParameter('limit', limit, 50, False)//
.Execute);
end;
function TTelegraPh.getViews(const path: string; const year, month, day, hour:
Integer): IphPageViews;
begin
Result := TphPageViews.Create(//
GetRequest.SetMethod('getViews')//
.AddParameter('path', path, '', True)//
.AddParameter('year', year, 0, False)//
.AddParameter('month', month, 0, False)//
.AddParameter('day', day, 0, false)//
.AddParameter('hour', hour, 0, False)//
.Execute);
end;
function TTelegraPh.revokeAccessToken(const AccessToken: string): IphAccount;
begin
Result := TphAccount.Create(//
GetRequest.SetMethod('revokeAccessToken')//
.AddParameter('access_token', AccessToken, '', True)//
.Execute);
end;
end.
|
unit oraclejdbcconnection;
{$mode delphi}
interface
uses
Classes, SysUtils, And_jni, AndroidWidget;
type
{Draft Component code by "LAMW: Lazarus Android Module Wizard" [3/29/2019 22:52:11]}
{https://github.com/jmpessoa/lazandroidmodulewizard}
{jControl template}
jOracleJDBCConnection = class(jControl)
private
FDriver: string;
FUrl: string;
FUserName: string;
FPassword: string;
FLanguage: TSpeechLanguage;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Init; override;
function jCreate(): jObject;
procedure jFree();
function Open(): boolean;
function ExecuteQuery(_sqlQuery: string): string;
function ExecuteUpdate(_sqlExecute: string): boolean;
procedure Close();
procedure SetDriver(_driver: string);
procedure SetUrl(_url: string);
procedure SetUserName(_username: string);
procedure SetPassword(_password: string);
procedure SetLanguage(_language: TSpeechLanguage);
property Driver: string read FDriver write SetDriver;
property Url: string read FUrl write SetUrl;
property UserName: string read FUserName write SetUserName;
property Password: string read FPassword write SetPassword;
property Language: TSpeechLanguage read FLanguage write SetLanguage;
published
end;
function jOracleJDBCConnection_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject;
procedure jOracleJDBCConnection_jFree(env: PJNIEnv; _joraclejdbcconnection: JObject);
function jOracleJDBCConnection_Open(env: PJNIEnv; _joraclejdbcconnection: JObject): boolean;
function jOracleJDBCConnection_ExecuteQuery(env: PJNIEnv; _joraclejdbcconnection: JObject; _sqlQuery: string): string;
function jOracleJDBCConnection_ExecuteUpdate(env: PJNIEnv; _joraclejdbcconnection: JObject; _sqlExecute: string): boolean;
procedure jOracleJDBCConnection_Close(env: PJNIEnv; _joraclejdbcconnection: JObject);
procedure jOracleJDBCConnection_SetDriver(env: PJNIEnv; _joraclejdbcconnection: JObject; _driver: string);
procedure jOracleJDBCConnection_SetUrl(env: PJNIEnv; _joraclejdbcconnection: JObject; _url: string);
procedure jOracleJDBCConnection_SetUserName(env: PJNIEnv; _joraclejdbcconnection: JObject; _username: string);
procedure jOracleJDBCConnection_SetPassword(env: PJNIEnv; _joraclejdbcconnection: JObject; _password: string);
procedure jOracleJDBCConnection_SetLanguage(env: PJNIEnv; _jmssqljdbcconnection: JObject; _language: integer);
implementation
{--------- jOracleJDBCConnection --------------}
constructor jOracleJDBCConnection.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
//your code here....
FLanguage:= slEnglish;
end;
destructor jOracleJDBCConnection.Destroy;
begin
if not (csDesigning in ComponentState) then
begin
if FjObject <> nil then
begin
jFree();
FjObject:= nil;
end;
end;
//you others free code here...'
inherited Destroy;
end;
procedure jOracleJDBCConnection.Init;
begin
if FInitialized then Exit;
inherited Init; //set default ViewParent/FjPRLayout as jForm.View!
//your code here: set/initialize create params....
FjObject := jCreate(); if FjObject = nil then exit;
FInitialized:= True;
end;
function jOracleJDBCConnection.jCreate(): jObject;
begin
Result:= jOracleJDBCConnection_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis);
end;
procedure jOracleJDBCConnection.jFree();
begin
//in designing component state: set value here...
if FInitialized then
jOracleJDBCConnection_jFree(gApp.jni.jEnv, FjObject);
end;
function jOracleJDBCConnection.Open(): boolean;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jOracleJDBCConnection_Open(gApp.jni.jEnv, FjObject);
end;
function jOracleJDBCConnection.ExecuteQuery(_sqlQuery: string): string;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jOracleJDBCConnection_ExecuteQuery(gApp.jni.jEnv, FjObject, _sqlQuery);
end;
function jOracleJDBCConnection.ExecuteUpdate(_sqlExecute: string): boolean;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jOracleJDBCConnection_ExecuteUpdate(gApp.jni.jEnv, FjObject, _sqlExecute);
end;
procedure jOracleJDBCConnection.Close();
begin
//in designing component state: set value here...
if FInitialized then
jOracleJDBCConnection_Close(gApp.jni.jEnv, FjObject);
end;
procedure jOracleJDBCConnection.SetDriver(_driver: string);
begin
//in designing component state: set value here...
if FInitialized then
jOracleJDBCConnection_SetDriver(gApp.jni.jEnv, FjObject, _driver);
end;
procedure jOracleJDBCConnection.SetUrl(_url: string);
begin
//in designing component state: set value here...
if FInitialized then
jOracleJDBCConnection_SetUrl(gApp.jni.jEnv, FjObject, _url);
end;
procedure jOracleJDBCConnection.SetUserName(_username: string);
begin
//in designing component state: set value here...
if FInitialized then
jOracleJDBCConnection_SetUserName(gApp.jni.jEnv, FjObject, _username);
end;
procedure jOracleJDBCConnection.SetPassword(_password: string);
begin
//in designing component state: set value here...
if FInitialized then
jOracleJDBCConnection_SetPassword(gApp.jni.jEnv, FjObject, _password);
end;
procedure jOracleJDBCConnection.SetLanguage(_language: TSpeechLanguage);
begin
//in designing component state: set value here...
FLanguage:= _language;
if FInitialized then
jOracleJDBCConnection_SetLanguage(gApp.jni.jEnv, FjObject, Ord(_language));
end;
{-------- jOracleJDBCConnection_JNI_Bridge ----------}
function jOracleJDBCConnection_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject;
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].j:= _Self;
jCls:= Get_gjClass(env);
jMethod:= env^.GetMethodID(env, jCls, 'jOracleJDBCConnection_jCreate', '(J)Ljava/lang/Object;');
Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams);
Result:= env^.NewGlobalRef(env, Result);
end;
procedure jOracleJDBCConnection_jFree(env: PJNIEnv; _joraclejdbcconnection: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _joraclejdbcconnection);
jMethod:= env^.GetMethodID(env, jCls, 'jFree', '()V');
env^.CallVoidMethod(env, _joraclejdbcconnection, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
function jOracleJDBCConnection_Open(env: PJNIEnv; _joraclejdbcconnection: JObject): boolean;
var
jBoo: JBoolean;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _joraclejdbcconnection);
jMethod:= env^.GetMethodID(env, jCls, 'Open', '()Z');
jBoo:= env^.CallBooleanMethod(env, _joraclejdbcconnection, jMethod);
Result:= boolean(jBoo);
env^.DeleteLocalRef(env, jCls);
end;
function jOracleJDBCConnection_ExecuteQuery(env: PJNIEnv; _joraclejdbcconnection: JObject; _sqlQuery: string): string;
var
jStr: JString;
jBoo: JBoolean;
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_sqlQuery));
jCls:= env^.GetObjectClass(env, _joraclejdbcconnection);
jMethod:= env^.GetMethodID(env, jCls, 'ExecuteQuery', '(Ljava/lang/String;)Ljava/lang/String;');
jStr:= env^.CallObjectMethodA(env, _joraclejdbcconnection, jMethod, @jParams);
case jStr = nil of
True : Result:= '';
False: begin
jBoo:= JNI_False;
Result:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
function jOracleJDBCConnection_ExecuteUpdate(env: PJNIEnv; _joraclejdbcconnection: JObject; _sqlExecute: string): boolean;
var
jBoo: JBoolean;
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_sqlExecute));
jCls:= env^.GetObjectClass(env, _joraclejdbcconnection);
jMethod:= env^.GetMethodID(env, jCls, 'ExecuteUpdate', '(Ljava/lang/String;)Z');
jBoo:= env^.CallBooleanMethodA(env, _joraclejdbcconnection, jMethod, @jParams);
Result:= boolean(jBoo);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jOracleJDBCConnection_Close(env: PJNIEnv; _joraclejdbcconnection: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _joraclejdbcconnection);
jMethod:= env^.GetMethodID(env, jCls, 'Close', '()V');
env^.CallVoidMethod(env, _joraclejdbcconnection, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jOracleJDBCConnection_SetDriver(env: PJNIEnv; _joraclejdbcconnection: JObject; _driver: string);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_driver));
jCls:= env^.GetObjectClass(env, _joraclejdbcconnection);
jMethod:= env^.GetMethodID(env, jCls, 'SetDriver', '(Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _joraclejdbcconnection, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jOracleJDBCConnection_SetUrl(env: PJNIEnv; _joraclejdbcconnection: JObject; _url: string);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_url));
jCls:= env^.GetObjectClass(env, _joraclejdbcconnection);
jMethod:= env^.GetMethodID(env, jCls, 'SetUrl', '(Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _joraclejdbcconnection, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jOracleJDBCConnection_SetUserName(env: PJNIEnv; _joraclejdbcconnection: JObject; _username: string);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_username));
jCls:= env^.GetObjectClass(env, _joraclejdbcconnection);
jMethod:= env^.GetMethodID(env, jCls, 'SetUserName', '(Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _joraclejdbcconnection, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jOracleJDBCConnection_SetPassword(env: PJNIEnv; _joraclejdbcconnection: JObject; _password: string);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_password));
jCls:= env^.GetObjectClass(env, _joraclejdbcconnection);
jMethod:= env^.GetMethodID(env, jCls, 'SetPassword', '(Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _joraclejdbcconnection, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jOracleJDBCConnection_SetLanguage(env: PJNIEnv; _jmssqljdbcconnection: JObject; _language: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _language;
jCls:= env^.GetObjectClass(env, _jmssqljdbcconnection);
jMethod:= env^.GetMethodID(env, jCls, 'SetLanguage', '(I)V');
env^.CallVoidMethodA(env, _jmssqljdbcconnection, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
end.
|
{$ifdef DEBUG}
{$D+,L+,Y+,R+,I+,C+,S+,V+,Q+}
{$endif}
unit EProcs;
interface
uses Seznam, Graph;
type
TExitProc = procedure;
PExitProcO = ^TExitProcO;
TExitProcO = object(TSeznamClen)
proc : TExitProc;
procedure CallProc;
constructor Init(iproc : TExitProc; ityp : TClenTyp);
end;
var epchain : TSeznam;
{Hex prevadeni asi nejfunguje jak by melo tzn. prevadi spatne.}
const HexDigits : array [0..15] of char = ('0','1','2','3','4','5','6',
'7','8','9','A','B','C','D',
'E','F');
function HexDump(x : word) : string;
implementation
var oldexitproc : pointer;
function HexDump(x : word) : string;
var pom : string[4];
begin
pom[0] := #4;
pom[1] := HexDigits[Hi(x) shr 4];
pom[2] := HexDigits[Hi(x) and $f];
pom[3] := HexDigits[Lo(x) shr 4];
pom[4] := HexDigits[Lo(x) and $f];
HexDump := pom;
end;
procedure ExitProcHandler; far; {tato procedura se vyvola pri ukonceni programu}
var i, poc : word;
begin
ExitProc := oldexitproc;
poc := epchain.PocetObj;
if poc > 0 then
for i := 1 to poc do
PExitProcO(epchain.Pozice(i))^.CallProc;
epchain.Done;
{$ifdef CZ_EXIT_TEXT} {vypis duvodu ukonceni}
if (ExitCode = 0) and (ErrorAddr = nil) then
writeln('Normalni ukonceni.')
else
if (ErrorAddr = nil) then
writeln('Ukonceni procedurou Halt(',ExitCode,')')
else
writeln('Ukonceni chybou za behu s chybovym kodem ',ExitCode,
' na adrese ',HexDump(Seg(ErrorAddr)),':',HexDump(Ofs(ErrorAddr)));
ExitCode := 0; {aby se nevypisovala pripadna chybova zprava dvakrat}
ErrorAddr := nil;
{$endif}
end;
procedure TExitProcO.CallProc;
begin
proc;
end;
constructor TExitProcO.Init(iproc : TExitProc; ityp : TClenTyp);
begin
inherited Init(ityp, nil);
proc := iproc;
end;
begin
epchain.Init(256,Static,nil);
oldexitproc := ExitProc;
ExitProc := @ExitProcHandler;
end. |
{
Author: Fredrik Nordbakke - FNProgramvare © 1997
E-mail: fredrik.nordbakke@ostfoldnett.no
WWW: http://www.prodat.no/fnp/delphi.html
}
unit FnpComboColor;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TSortBy = (ccsUnsorted, ccsColor, ccsText);
TFnpComboColor = class(TCustomComboBox)
private
{ Private declarations }
FColorWidth: Integer;
FSortBy: TSortBy;
FVersion: String;
function GetSelectedColor: TColor;
function GetSelectedColorText: String;
procedure SetColorWidth(Value: Integer);
procedure SetSelectedColor(Value: TColor);
procedure SetSelectedColorText(Value: String);
procedure SetSortBy(Value: TSortBy);
procedure DrawItem(Index: Integer; Rect: TRect;
State: TOwnerDrawState); override;
procedure SetVersion(Value: String);
protected
{ Protected declarations }
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
procedure AddColor(ColorText: String; Color: TColor);
property SelectedColor:TColor read GetSelectedColor write SetSelectedColor;
property SelectedColorText:String read GetSelectedColorText write SetSelectedColorText;
published
{ Published declarations }
property Color;
property Ctl3D;
property DragMode;
property DragCursor;
property DropDownCount;
property Enabled;
property Font;
property ItemHeight;
property Items;
property MaxLength;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Text;
property Visible;
property OnChange;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnDropDown;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnStartDrag;
property ColorWidth: Integer read FColorWidth write SetColorWidth default 18;
property SortBy: TSortBy read FSortBy write SetSortBy default ccsUnsorted;
property Version: String read FVersion write SetVersion stored False;
end;
procedure Register;
implementation
constructor TFnpComboColor.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FColorWidth := 18;
FSortBy := ccsUnsorted;
Style := csOwnerDrawFixed;
FVersion := '1.00.00';
end;
procedure TFnpComboColor.AddColor(ColorText: String; Color: TColor);
var
X: Integer;
begin
if (FSortBy = ccsUnsorted) or (Items.Count = 0) then
Items.AddObject(ColorText, Pointer(Color))
else if FSortBy = ccsColor then
begin
for X := 0 to Items.Count - 1 do
begin
if TColor(Items.Objects[X]) > Color then
begin
Break;
end;
end;
Items.InsertObject(X , ColorText, Pointer(Color));
end
else
begin
for X := 0 to Items.Count - 1 do
begin
if AnsiLowerCase(Items[X]) > AnsiLowerCase(ColorText) then
begin
Break;
end;
end;
Items.InsertObject(X , ColorText, Pointer(Color));
end;
end;
function TFnpComboColor.GetSelectedColor: TColor;
begin
if ItemIndex = -1 then
Result := -1
else
Result := TColor(Items.Objects[ItemIndex]);
end;
function TFnpComboColor.GetSelectedColorText: String;
begin
if ItemIndex = -1 then
Result := ''
else
Result := Items[ItemIndex];
end;
procedure TFnpComboColor.SetColorWidth(Value: Integer);
begin
if (FColorWidth <> Value) and (Value > 4) then
begin
FColorWidth := Value;
if not (csDesigning in ComponentState) then
Invalidate;
end;
end;
procedure TFnpComboColor.SetSelectedColor(Value: TColor);
var
X: Integer;
begin
for X := 0 to Items.Count - 1 do
begin
if TColor(Items.Objects[X]) = Value then
begin
ItemIndex := X;
Break;
end;
end;
end;
procedure TFnpComboColor.SetSelectedColorText(Value: String);
var
X: Integer;
begin
for X := 0 to Items.Count - 1 do
begin
if Items[X] = Value then
begin
ItemIndex := X;
Break;
end;
end;
end;
procedure TFnpComboColor.SetSortBy(Value: TSortBy);
var
C: TColor;
X: Integer;
Y: Integer;
begin
if FSortBy <> Value then
FSortBy := Value;
{ Use a "Buble Sort". Not the fastest algorithm, but it works fine here! }
if FSortBy <> ccsUnsorted then
begin
C := SelectedColor;
X := 0;
while X < Items.Count - 1 do
begin
Y := Items.Count -1;
while Y > X do
begin
if FSortBy = ccsColor then
begin
if TColor(Items.Objects[Y]) < TColor(Items.Objects[Y - 1]) then
Items.Exchange(Y, Y - 1);
end
else
begin
if AnsiLowerCase(Items[Y]) < AnsiLowerCase(Items[Y - 1]) then
Items.Exchange(Y, Y - 1);
end;
Y := Y - 1;
end;
X := X + 1;
end;
SelectedColor := C;
end
end;
procedure TFnpComboColor.DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
ColorR: TRect;
TextR: TRect;
OldColor: TColor;
begin
ColorR.Left := Rect.Left + 1;
ColorR.Top := Rect.Top + 1;
ColorR.Right := Rect.Left + FColorWidth - 1;
ColorR.Bottom := Rect.Top + ItemHeight - 1;
TextR.Left := Rect.Left + FColorWidth + 4;
TextR.Top := Rect.Top + 1;
TextR.Right := Rect.Right;
TextR.Bottom := Rect.Bottom - 1;
with Canvas do
begin
FillRect(Rect); { clear the rectangle }
OldColor := Brush.Color;
Brush.Color := TColor(Items.Objects[Index]);
Rectangle(ColorR.Left, ColorR.Top, ColorR.Right, ColorR.Bottom);
Brush.Color := OldColor;
DrawText(Handle, PChar(Items[Index]), -1, TextR, DT_VCENTER or DT_SINGLELINE);
end;
end;
procedure TFnpComboColor.SetVersion(Value: String);
begin
{ This property is read only! }
end;
procedure Register;
begin
RegisterComponents('Samples', [TFnpComboColor]);
end;
end.
|
unit LoggerIntf;
interface
type
ILogger = interface(IInvokable)
procedure LogMessage(const AMessage: string);
end;
implementation
end.
|
unit FORecord;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,ActnList;
const
DefaultCaptionFormat = '%s - %s';
type
TFileOpenRecord = class;
TKSFileAction = class(TAction)
private
function getFileOpenRecord(Target : TComponent): TFileOpenRecord;
public
function HandlesTarget(Target: TObject): Boolean; override;
procedure UpdateTarget(Target: TObject); override;
end;
TKSFileNew = class(TKSFileAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
TKSFileOpen = class(TKSFileAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
TKSFileSave = class(TKSFileAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
TKSFileSaveAs = class(TKSFileAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
TKSFileClose = class(TKSFileAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
TFileProcMethod = procedure (FORecord : TFileOpenRecord;
const FileName : string) of object;
TFileOpenRecord = class(TComponent)
private
FFileNamed: boolean;
FModified: boolean;
FDefaultFileName: string;
FFileName: string;
FOnFileOpen: TFileProcMethod;
FOnFileSave: TFileProcMethod;
FOnFileNew: TNotifyEvent;
FOpenDialog: TOpenDialog;
FSaveDialog: TSaveDialog;
FQuerySaveStr: string;
FOnFileClose: TNotifyEvent;
FBeforeFileOperate: TNotifyEvent;
FAfterFileOperate: TNotifyEvent;
FAutoChangeFormCaption: Boolean;
FOnFileNameChanged: TNotifyEvent;
FCaptionFormat: string;
FOnStatusChanged: TNotifyEvent;
FClosing : Boolean;
{ Private declarations }
procedure SetFileName(const Value: string);
// when user click "yes" or "no" return true, click "cancel" is false
procedure SetOpenDialog(const Value: TOpenDialog);
procedure SetSaveDialog(const Value: TSaveDialog);
procedure DoBeforeFileOpt;
procedure DoAfterFileOpt;
procedure SetCaptionFormat(const Value: string);
procedure SetModified(const Value: boolean);
procedure SetDefaultFileName(const Value: string);
protected
{ Protected declarations }
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure Loaded; override;
public
{ Public declarations }
constructor Create(AOwner : TComponent); override;
// in menu item-click handlers , call these procedures
procedure OnNewClick(sender : TObject);
procedure OnOpenClick(sender : TObject);
procedure OnSaveClick(sender : TObject);
procedure OnSaveAsClick(sender : TObject);
procedure OnCloseClick(sender : TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
function QuerySave:boolean;
procedure UpdateFormCaption;
// the property
property FileName : string Read FFileName Write SetFileName;
property Modified : boolean read FModified write SetModified;
procedure FileModified; // simple set Modified:=true
property FileNamed : boolean read FFileNamed;
published
{ Published declarations }
property OpenDialog : TOpenDialog read FOpenDialog write SetOpenDialog;
property SaveDialog : TSaveDialog read FSaveDialog write SetSaveDialog;
property DefaultFileName : string read FDefaultFileName write SetDefaultFileName;
property QuerySaveStr : string read FQuerySaveStr write FQuerySaveStr;
property AutoChangeFormCaption : Boolean read FAutoChangeFormCaption write FAutoChangeFormCaption default True;
property CaptionFormat : string read FCaptionFormat write SetCaptionFormat;
property OnFileNew : TNotifyEvent read FOnFileNew write FOnFileNew;
property OnFileOpen : TFileProcMethod read FOnFileOpen write FOnFileOpen;
property OnFileSave : TFileProcMethod read FOnFileSave write FOnFileSave;
property OnFileClose : TNotifyEvent read FOnFileClose write FOnFileClose;
property BeforeFileOperate : TNotifyEvent read FBeforeFileOperate write FBeforeFileOperate;
property AfterFileOperate : TNotifyEvent read FAfterFileOperate write FAfterFileOperate;
property OnFileNameChanged : TNotifyEvent read FOnFileNameChanged write FOnFileNameChanged;
property OnStatusChanged : TNotifyEvent read FOnStatusChanged write FOnStatusChanged;
end;
implementation
{ TFileOpenRecord }
constructor TFileOpenRecord.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FModified := false;
FFileNamed := false;
FDefaultFileName := 'Nonamed';
FQuerySaveStr := 'Do you want to save file ';
FFileName := DefaultFileName;
FAutoChangeFormCaption := True;
FCaptionFormat := DefaultCaptionFormat;
FClosing := false;
end;
procedure TFileOpenRecord.DoAfterFileOpt;
begin
Modified := false;
if assigned(FAfterFileOperate) then
FAfterFileOperate(self);
end;
procedure TFileOpenRecord.DoBeforeFileOpt;
begin
if assigned(FBeforeFileOperate) then
FBeforeFileOperate(self);
end;
procedure TFileOpenRecord.FileModified;
begin
Modified := true;
end;
procedure TFileOpenRecord.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
if not FClosing then
begin
CanClose := QuerySave;
end;
end;
procedure TFileOpenRecord.Loaded;
begin
UpdateFormCaption;
end;
procedure TFileOpenRecord.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation=opRemove) then
if AComponent=FOpenDialog then FOpenDialog:=nil else
if AComponent=FSaveDialog then FSaveDialog:=nil;
end;
procedure TFileOpenRecord.OnCloseClick(sender: TObject);
begin
try
FClosing := True;
DoBeforeFileOpt;
if not QuerySave then
abort else
if Assigned(FOnFileClose) then FOnFileClose(self);
DoAfterFileOpt;
finally
FClosing := False;
end;
end;
procedure TFileOpenRecord.OnNewClick(sender: TObject);
begin
DoBeforeFileOpt;
if QuerySave then
begin
//Modified := false;
FileName := DefaultFileName;
FFileNamed := false;
if Assigned(FOnFileNew) then FOnFileNew(self);
DoAfterFileOpt;
end;
end;
procedure TFileOpenRecord.OnOpenClick(sender: TObject);
begin
DoBeforeFileOpt;
if Assigned(FOpenDialog)
and Assigned(FOnFileOpen) then
if FOpenDialog.execute and QuerySave then
begin
//Modified := false;
//FFileNamed := true;
FileName := FOpenDialog.filename;
FOnFileOpen(self,Filename);
DoAfterFileOpt;
end;
end;
procedure TFileOpenRecord.OnSaveAsClick(sender: TObject);
begin
DoBeforeFileOpt;
if Assigned(FSaveDialog)
and Assigned(FOnFileSave) then
begin
FSaveDialog.Filename := filename;
if FSaveDialog.execute then
begin
//Modified := false;
FFileNamed := true;
FileName := FSaveDialog.filename;
OnFileSave(self,FileName);
DoAfterFileOpt;
end;
end;
end;
procedure TFileOpenRecord.OnSaveClick(sender: TObject);
begin
DoBeforeFileOpt;
if not FFileNamed then
OnSaveAsClick(sender)
else
begin
if Assigned(FOnFileSave) then FOnFileSave(self,Filename);
DoAfterFileOpt;
end;
end;
function TFileOpenRecord.QuerySave: boolean;
var
Choice : word;
begin
if Modified then
begin
choice:=MessageDlg(FQuerySaveStr+filename+' ?',mtInformation,
[mbYes,mbNo,mbCancel],0);
if choice=mrYes then OnSaveClick(self);
result := choice<>mrCancel;
end else
result := true;
end;
procedure TFileOpenRecord.SetCaptionFormat(const Value: string);
begin
FCaptionFormat := Value;
UpdateFormCaption;
end;
procedure TFileOpenRecord.SetDefaultFileName(const Value: string);
begin
if DefaultFileName <> Value then
begin
FDefaultFileName := Value;
if not FFileNamed then
FFileName := Value; // ±£³ÖδÃüÃû״̬
end;
end;
procedure TFileOpenRecord.SetFileName(const Value: string);
begin
if FileName <> Value then
begin
FFileName := Value;
if Assigned(FOnFileNameChanged) then
FOnFileNameChanged(Self);
UpdateFormCaption;
end;
FFileNamed := True;
end;
procedure TFileOpenRecord.SetModified(const Value: boolean);
begin
if Modified <> Value then
begin
FModified := Value;
if Assigned(FOnStatusChanged) then
FOnStatusChanged(Self);
end;
end;
procedure TFileOpenRecord.SetOpenDialog(const Value: TOpenDialog);
begin
if FOpenDialog <> Value then
begin
FOpenDialog := Value;
if FOpenDialog <>nil then
FOpenDialog.FreeNotification(self);
end;
end;
procedure TFileOpenRecord.SetSaveDialog(const Value: TSaveDialog);
begin
if FSaveDialog <> Value then
begin
FSaveDialog := Value;
if FSaveDialog<>nil then
FSaveDialog.FreeNotification(self);
end;
end;
procedure TFileOpenRecord.UpdateFormCaption;
begin
if (Owner is TCustomForm) and not (csDesigning in ComponentState) then
TCustomForm(Owner).Caption := Format(CaptionFormat,[Application.Title,FileName]);
end;
{ TKSFileAction }
function TKSFileAction.getFileOpenRecord(
Target: TComponent): TFileOpenRecord;
var
i : integer;
begin
result := nil;
for i:=0 to Target.ComponentCount-1 do
if Target.Components[i] is TFileOpenRecord then
begin
result := TFileOpenRecord(Target.Components[i]);
break;
end;
end;
function TKSFileAction.HandlesTarget(Target: TObject): Boolean;
begin
if (Target is TCustomForm) or (Target is TDataModule) then
result := getFileOpenRecord(TComponent(Target))<>nil else
result := false;
end;
procedure TKSFileAction.UpdateTarget(Target: TObject);
begin
end;
{ TKSFileNew }
procedure TKSFileNew.ExecuteTarget(Target: TObject);
var
fo : TFileOpenRecord;
begin
fo := getFileOpenRecord(TComponent(Target));
if fo<>nil then fo.OnNewClick(nil);
end;
{ TKSFileOpen }
procedure TKSFileOpen.ExecuteTarget(Target: TObject);
var
fo : TFileOpenRecord;
begin
fo := getFileOpenRecord(TComponent(Target));
if fo<>nil then fo.OnOpenClick(nil);
end;
{ TKSFileSave }
procedure TKSFileSave.ExecuteTarget(Target: TObject);
var
fo : TFileOpenRecord;
begin
fo := getFileOpenRecord(TComponent(Target));
if fo<>nil then fo.OnSaveClick(nil);
end;
{ TKSFileSaveAs }
procedure TKSFileSaveAs.ExecuteTarget(Target: TObject);
var
fo : TFileOpenRecord;
begin
fo := getFileOpenRecord(TComponent(Target));
if fo<>nil then fo.OnSaveAsClick(nil);
end;
{ TKSFileClose }
procedure TKSFileClose.ExecuteTarget(Target: TObject);
var
fo : TFileOpenRecord;
begin
fo := getFileOpenRecord(TComponent(Target));
if fo<>nil then fo.OnCloseClick(nil);
end;
end.
|
unit SSL_Client;
{$I ..\..\Base\SBDemo.inc}
interface
uses
Classes, SysUtils, DB,
Windows, Messages, Graphics, Controls, Forms, Dialogs,
DBCtrls, ExtCtrls, Grids, DBGrids, StdCtrls, ToolWin, ComCtrls,
Buttons, Spin, DemoFrame, MemDS, DBAccess, Uni, UniProvider,
UniDacVcl, ScBridge, ScCryptoAPIStorage, CRSSLIOHandler, CRVio,
{$IFNDEF CLR}
OracleUniProvider,
SQLServerUniProvider,
InterBaseUniProvider,
MySQLUniProvider,
PostgreSQLUniProvider
{$ELSE}
System.ComponentModel,
Devart.UniDac.Oracle.OracleUniProvider,
Devart.UniDac.SQLServer.SQLServerUniProvider,
Devart.UniDac.InterBase.InterBaseUniProvider,
Devart.UniDac.MySQL.MySQLUniProvider,
Devart.UniDac.PostgreSQL.PostgreSQLUniProvider
{$ENDIF}
;
type
TSSLClientFrame = class(TDemoFrame)
Panel1: TPanel;
Panel4: TPanel;
Panel2: TPanel;
Panel6: TPanel;
Panel5: TPanel;
Label2: TLabel;
btConnectDB: TSpeedButton;
btDisconnectDB: TSpeedButton;
DBGrid: TDBGrid;
UniConnection: TUniConnection;
UniTable: TUniTable;
DataSource: TDataSource;
Label10: TLabel;
edDBHost: TEdit;
Label11: TLabel;
Label12: TLabel;
edDBUserName: TEdit;
Label13: TLabel;
edDBPassword: TEdit;
Label14: TLabel;
seDBPort: TSpinEdit;
cbDBDatabase: TComboBox;
Panel7: TPanel;
lbTableName: TLabel;
cbTableName: TComboBox;
Panel9: TPanel;
btOpen: TSpeedButton;
btClose: TSpeedButton;
Panel8: TPanel;
CRSSLIOHandler: TCRSSLIOHandler;
ScCryptoAPIStorage: TScCryptoAPIStorage;
DBNavigator: TDBNavigator;
Panel3: TPanel;
Label1: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
edCACertName: TEdit;
edKeyName: TEdit;
cbRandomization: TCheckBox;
cbSSL: TCheckBox;
sbCACertName: TSpeedButton;
edCertName: TEdit;
sbCertName: TSpeedButton;
sbKeyName: TSpeedButton;
OpenDialog: TOpenDialog;
Label6: TLabel;
cbProvider: TComboBox;
procedure btConnectDBClick(Sender: TObject);
procedure btDisconnectDBClick(Sender: TObject);
procedure UniConnectionAfterConnect(Sender: TObject);
procedure UniTableAfterClose(DataSet: TDataSet);
procedure UniTableAfterOpen(DataSet: TDataSet);
procedure btOpenClick(Sender: TObject);
procedure btCloseClick(Sender: TObject);
procedure cbTableNameDropDown(Sender: TObject);
procedure cbTableNameChange(Sender: TObject);
procedure cbDBDatabaseDropDown(Sender: TObject);
procedure cbDBDatabaseChange(Sender: TObject);
procedure UniConnectionBeforeConnect(Sender: TObject);
procedure edDBHostChange(Sender: TObject);
procedure sbCACertNameClick(Sender: TObject);
procedure sbKeyNameClick(Sender: TObject);
procedure sbCertNameClick(Sender: TObject);
private
procedure CheckRandomize;
{$IFDEF MSWINDOWS}
function LoadState: boolean;
function SaveState: boolean;
function KeyPath: string;
{$ENDIF}
public
destructor Destroy; override;
procedure Initialize; override;
procedure Finalize; override;
end;
var
SSLClientFrame: TSSLClientFrame;
implementation
{$IFNDEF FPC}
{$IFDEF CLR}
{$R *.nfm}
{$ELSE}
{$R *.dfm}
{$ENDIF}
{$ENDIF}
uses
{$IFDEF MSWINDOWS}
Registry,
{$ENDIF}
ScConsts, ScSSHUtils, SSLDacDemoForm,
MyClassesUni, PgClassesUni;
const
CertFilter = 'All formats |*.pem;*.crt;*.cer|PEM format (*.pem;*.crt)|*.pem;*.crt|DER format (*.cer)|*.cer|All files (*.*)|*.*';
KeyFilter = 'All formats |*.key;*.ssl;*.pem;*.ietf;*.pub;*.ietfpub|OpenSSL format (*.ssl)|*.ssl|PKCS8 format (*.pem)|*.pem|IETF format (*.ietf)|*.ietf|Public key (*.pub)|*.pub|Public IETF key (*.ietfpub)|*.ietfpub|All files (*.*)|*.*';
destructor TSSLClientFrame.Destroy;
begin
UniConnection.Close;
inherited;
end;
procedure TSSLClientFrame.Initialize;
begin
inherited;
{$IFDEF MSWINDOWS}
LoadState;
{$ENDIF}
UniProviders.GetProviderNames(cbProvider.Items);
end;
procedure TSSLClientFrame.Finalize;
begin
{$IFDEF MSWINDOWS}
SaveState;
{$ENDIF}
inherited;
end;
procedure TSSLClientFrame.CheckRandomize;
begin
if not SSLDacForm.Randomized and not cbRandomization.Checked then begin
SSLDacForm.Randomize;
if not SSLDacForm.Randomized and not cbRandomization.Checked then
raise Exception.Create('Data for the random generator has not been generated');
end;
end;
procedure TSSLClientFrame.btConnectDBClick(Sender: TObject);
begin
UniConnection.Connect;
end;
procedure TSSLClientFrame.btDisconnectDBClick(Sender: TObject);
begin
UniConnection.Disconnect;
end;
procedure TSSLClientFrame.edDBHostChange(Sender: TObject);
begin
UniConnection.Disconnect;
end;
procedure TSSLClientFrame.UniConnectionAfterConnect(Sender: TObject);
begin
btConnectDB.Enabled := not UniConnection.Connected;
btDisconnectDB.Enabled := UniConnection.Connected;
btOpen.Enabled := UniConnection.Connected and (cbTableName.Text <> '');
cbTableName.Enabled := UniConnection.Connected;
end;
procedure TSSLClientFrame.UniTableAfterOpen(DataSet: TDataSet);
begin
btOpen.Enabled := False;
btClose.Enabled := True;
end;
procedure TSSLClientFrame.UniTableAfterClose(DataSet: TDataSet);
begin
btOpen.Enabled := not btConnectDB.Enabled and (cbTableName.Text <> '');
btClose.Enabled := False;
end;
procedure TSSLClientFrame.btOpenClick(Sender: TObject);
begin
UniTable.Open;
end;
procedure TSSLClientFrame.btCloseClick(Sender: TObject);
begin
UniTable.Close;
end;
procedure TSSLClientFrame.cbTableNameDropDown(Sender: TObject);
begin
if UniConnection.Connected then
UniConnection.GetTableNames(cbTableName.Items)
else
cbTableName.Items.Clear;
end;
procedure TSSLClientFrame.cbTableNameChange(Sender: TObject);
begin
UniTable.TableName := cbTableName.Text;
btOpen.Enabled := UniConnection.Connected and (cbTableName.Text <> '');
end;
{$IFDEF MSWINDOWS}
function TSSLClientFrame.SaveState: boolean;
var
Registry: TRegistry;
begin
Registry := TRegistry.Create(KEY_READ OR KEY_WRITE);
try
with Registry do begin
OpenKey(KeyPath + '\' + TSSLClientFrame.ClassName, True);
WriteString('CACertName', edCACertName.Text);
WriteString('ClientCertName', edCertName.Text);
WriteString('CertPrivateKeyName', edKeyName.Text);
WriteString('Provider', cbProvider.Text);
WriteString('DBHost', edDBHost.Text);
WriteInteger('DBPort', seDBPort.Value);
WriteString('DBUserName', edDBUserName.Text);
WriteString('DBDatabase', cbDBDatabase.Text);
WriteBool('Silent randomization', cbRandomization.Checked);
WriteBool('Use SSL', cbSSL.Checked);
end;
finally
Registry.Free;
end;
Result := True;
end;
function TSSLClientFrame.LoadState: boolean;
var
Registry: TRegistry;
begin
Result := False;
Registry := TRegistry.Create(KEY_READ OR KEY_WRITE);
try
with Registry do begin
if OpenKey(KeyPath + '\' + TSSLClientFrame.ClassName, False) then begin
if ValueExists('CACertName') then
edCACertName.Text := ReadString('CACertName');
if ValueExists('ClientCertName') then
edCertName.Text := ReadString('ClientCertName');
if ValueExists('CertPrivateKeyName') then
edKeyName.Text := ReadString('CertPrivateKeyName');
if ValueExists('Provider') then
cbProvider.Text := ReadString('Provider');
if ValueExists('DBHost') then
edDBHost.Text := ReadString('DBHost');
if ValueExists('DBPort') then
seDBPort.Value := ReadInteger('DBPort');
if ValueExists('DBUserName') then
edDBUserName.Text := ReadString('DBUserName');
if ValueExists('DBDatabase') then
cbDBDatabase.Text := ReadString('DBDatabase');
if ValueExists('Silent randomization') then
cbRandomization.Checked := ReadBool('Silent randomization');
if ValueExists('Use SSL') then
cbSSL.Checked := ReadBool('Use SSL');
Result := True;
end;
end;
finally
Registry.Free;
end;
end;
function TSSLClientFrame.KeyPath: string;
begin
Result := '\SOFTWARE\Devart\SecureBridge\Demos';
end;
{$ENDIF}
procedure TSSLClientFrame.cbDBDatabaseDropDown(Sender: TObject);
begin
UniConnection.GetDatabaseNames(cbDBDatabase.Items)
end;
procedure TSSLClientFrame.cbDBDatabaseChange(Sender: TObject);
begin
UniTable.Close;
UniConnection.Database := cbDBDatabase.Text;
cbTableName.Text := '';
end;
procedure TSSLClientFrame.UniConnectionBeforeConnect(Sender: TObject);
var
Cert: TScCertificate;
begin
if cbSSL.Checked then begin
ScCryptoAPIStorage.Certificates.Clear;
Cert := TScCertificate.Create(ScCryptoAPIStorage.Certificates);
Cert.CertName := CRSSLIOHandler.CACertName;
Cert.ImportFrom(edCACertName.Text);
Cert := TScCertificate.Create(ScCryptoAPIStorage.Certificates);
Cert.CertName := CRSSLIOHandler.CertName;
Cert.ImportFrom(edCertName.Text);
Cert.Key.ImportFrom(edKeyName.Text);
CheckRandomize;
UniConnection.IOHandler := CRSSLIOHandler;
UniConnection.SpecificOptions.Values['PostgreSQL.SSLMode'] := 'smRequire'; // for Pg
UniConnection.SpecificOptions.Values['MySQL.Protocol'] := 'mpSSL'; // for MySQL
end
else begin
UniConnection.IOHandler := nil;
UniConnection.SpecificOptions.Values['PostgreSQL.SSLMode'] := 'smDisable'; // for Pg
UniConnection.SpecificOptions.Values['MySQL.Protocol'] := 'mpDefault'; // for MySQL
end;
UniConnection.ProviderName := cbProvider.Text;
UniConnection.Server := edDBHost.Text;
UniConnection.Port := seDBPort.Value;
UniConnection.Username := edDBUserName.Text;
UniConnection.Password := edDBPassword.Text;
UniConnection.Database := cbDBDatabase.Text;
end;
procedure TSSLClientFrame.sbCACertNameClick(Sender: TObject);
begin
OpenDialog.Filter := CertFilter;
OpenDialog.Title := 'Import certificate';
if OpenDialog.Execute then
edCACertName.Text := OpenDialog.FileName;
end;
procedure TSSLClientFrame.sbCertNameClick(Sender: TObject);
begin
OpenDialog.Filter := CertFilter;
OpenDialog.Title := 'Import certificate';
if OpenDialog.Execute then
edCertName.Text := OpenDialog.FileName;
end;
procedure TSSLClientFrame.sbKeyNameClick(Sender: TObject);
begin
OpenDialog.Filter := KeyFilter;
OpenDialog.Title := 'Import key';
if OpenDialog.Execute then
edKeyName.Text := OpenDialog.FileName;
end;
end.
|
unit Objeto;
interface
type
TObjeto = class
public
function Equals(Objeto :TObjeto) :Boolean; virtual; abstract;
end;
implementation
{ TObjeto }
end.
|
unit NumericInterpolation;
interface
uses
SysUtils;
type
TNumericInterpolation = class sealed
public
class function LinearlyInterpolateY(
const LowerX, LowerY: Double;
const UpperX, UpperY: Double;
const Arg: Double
): Double; static;
end;
implementation
{ TNumericInterpolation }
class function TNumericInterpolation.LinearlyInterpolateY(
const LowerX, LowerY: Double;
const UpperX, UpperY: DOuble;
const Arg: Double
): Double;
begin
Result :=
LowerY +
((UpperY - LowerY) / (UpperX - LowerX)) *
(Arg - LowerX);
end;
end.
|
(*
O problema da identificacao de uma celebridade.
Rita e' uma colunista e esta' fazendo a cobertura de uma festa. Seu trabalho
e' identificar uma celebridade, caso ela exista. Uma celebridade e' uma pessoa
que e' conhecida por todas as demais pessoas da festa, mas que nao conhece
ninguem. Rita faz a seguinte pergunta aos convidados: "voce conhece aquela
pessoa ali?". Considere que todas as pessoas vao responder a pergunta de
forma sincera. Escreva um programa que ajuda a tarefa de Rita identificar
uma celebridade da festa.
Uma pessoa P é identificada como uma celebridade em uma festa se:
C1: todos conhecem P
C2: nao conhece ninguem
1) representacao do fato de Pi conhecer Pj em uma matriz:
m[i,j] = 0 se Pi nao conhece Pj
m[i,j] = 1 de Pi conhece Pj
Escrever um procedimento que leia uma sequencia de pares e preencher a matriz. Não esqueça de inicializar a matriz com zeros.
Exemplo (considerando 5 pessoas):
3 4
5 1
5 4
2 1
2 4
1 4
matriz 0 0 0 1 0
1 0 0 1 0
0 0 0 1 0
0 0 0 0 0
1 0 0 1 0
-----------------------------------
Solucao 4: usando 2 indices (p1, p2)
1 2 3 4 5
p1 p2
Utiliza a mesma ideia da Solucao 2, mas considerando as pessoas dos indices ini e fim. Se p1 conhece p2, incrementa p1 (ou seja, p1 nao pode ser celebridade).
*)
|
unit AqDrop.DB.FD.MSSQL;
interface
{$I '..\Core\AqDrop.Core.Defines.Inc'}
uses
{$IFNDEF AQMOBILE}
{$IF CompilerVersion >= 26}
FireDAC.Phys.MSSQL,
{$ELSE}
uADPhysMSSQL,
{$ENDIF}
{$ENDIF}
AqDrop.DB.Adapter,
AqDrop.DB.FD;
type
TAqFDMSSQLAdapter = class(TAqFDAdapter)
strict protected
class function GetDefaultSolver: TAqDBSQLSolverClass; override;
end;
TAqFDMSSQLConnection = class(TAqFDCustomConnection)
strict protected
function GetParameterValueByIndex(const pIndex: Int32): string; override;
procedure SetParameterValueByIndex(const pIndex: Int32; const pValue: string); override;
class function GetDefaultAdapter: TAqDBAdapterClass; override;
public
constructor Create; override;
property HostName: string index $80 read GetParameterValueByIndex write SetParameterValueByIndex;
property DataBase: string index $81 read GetParameterValueByIndex write SetParameterValueByIndex;
property UserName: string index $82 read GetParameterValueByIndex write SetParameterValueByIndex;
property Password: string index $83 read GetParameterValueByIndex write SetParameterValueByIndex;
end;
implementation
uses
AqDrop.Core.Exceptions,
AqDrop.DB.Types,
AqDrop.DB.MSSQL;
{ TAqFDMSSQLAdapter }
class function TAqFDMSSQLAdapter.GetDefaultSolver: TAqDBSQLSolverClass;
begin
Result := TAqDBMSSQLSQLSolver;
end;
{ TAqFDMSSQLConnection }
constructor TAqFDMSSQLConnection.Create;
begin
inherited;
DriverName := 'MSSQL';
end;
class function TAqFDMSSQLConnection.GetDefaultAdapter: TAqDBAdapterClass;
begin
Result := TAqFDMSSQLAdapter;
end;
function TAqFDMSSQLConnection.GetParameterValueByIndex(const pIndex: Int32): string;
begin
case pIndex of
$80:
Result := Params.Values['Server'];
$81:
Result := Params.Values['Database'];
$82:
Result := Params.Values['User_Name'];
$83:
Result := Params.Values['Password'];
else
Result := inherited;
end;
end;
procedure TAqFDMSSQLConnection.SetParameterValueByIndex(const pIndex: Int32; const pValue: string);
begin
case pIndex of
$80:
Params.Values['Server'] := pValue;
$81:
Params.Values['Database'] := pValue;
$82:
Params.Values['User_Name'] := pValue;
$83:
Params.Values['Password'] := pValue;
else
inherited;
end;
end;
end.
|
unit dmBD;
interface
uses
SysUtils, Classes, IBDatabase, DB, dmThreadDataModule;
type
TSCDatabase = (scdUsuario, scdComun, scdDatos);
TBDDatos = (bddDiaria, bddSemanal);
TBD = class(TThreadDataModule)
IBDatabaseComun: TIBDatabase;
IBTransactionComun: TIBTransaction;
IBDatabaseUsuario: TIBDatabase;
IBTransactionUsuario: TIBTransaction;
IBDatabaseDatos: TIBDatabase;
IBTransactionDatos: TIBTransaction;
private
class var
MainBD: TBD;
BDsPath: string;
var
FBDDatos: TBDDatos;
procedure SetBDDatos(const Value: TBDDatos);
function GetDatabasePath(const tipo: TSCDatabase; BDDatos: TBDDatos): TFileName;
procedure OnInternalBDDatosChange;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetDatabase(const tipo: TSCDatabase): TIBDatabase;
function GetNewDatabase(const AOwner: TComponent; const tipo: TSCDatabase; BDDatos: TBDDatos): TIBDatabase;
function GetTipoDatabase(const database: TIBDatabase): TSCDatabase;
procedure ConfigureDatabase(const database: TIBDatabase; const BDDatos: TBDDatos);
property BDDatos: TBDDatos read FBDDatos write SetBDDatos;
// constructor Create(AOwner: TComponent; const databaseName: string); overload;
end;
function BD: TBD;
procedure GlobalInitialization;
implementation
{$R *.dfm}
uses Forms, UtilDB, UtilThread, BusCommunication;
{constructor TBD.Create(AOwner: TComponent; const databaseName: string);
var path: string;
begin
inherited Create(AOwner);
path := ExtractFileDir(Application.ExeName);
if (FileExists(path + '\' + databaseName)) then
path := path + '\' + databaseName;
end;}
type
MessageInternalBDDatosChange = class(TBusMessage);
function BD: TBD;
begin
result := TBD(DataModuleManager.GetDataModule('BD'));
end;
procedure TBD.ConfigureDatabase(const database: TIBDatabase; const BDDatos: TBDDatos);
begin
database.DatabaseName := GetDatabasePath(GetTipoDatabase(database), BDDatos);
end;
constructor TBD.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
if MainBD = nil then begin
MainBD := Self;
BDsPath := ExtractFilePath(Application.ExeName);
FBDDatos := bddDiaria;
end
else begin
FBDDatos := MainBD.BDDatos;
Bus.RegisterEvent(MessageInternalBDDatosChange, OnInternalBDDatosChange);
end;
IBDatabaseComun.DatabaseName := GetDatabasePath(scdComun, FBDDatos);
IBDatabaseUsuario.DatabaseName := GetDatabasePath(scdUsuario, FBDDatos);
IBDatabaseDatos.DatabaseName := GetDatabasePath(scdDatos, FBDDatos);
OpenDatabase(IBDatabaseComun);
OpenDatabase(IBDatabaseUsuario);
OpenDatabase(IBDatabaseDatos);
end;
destructor TBD.Destroy;
begin
if MainBD <> Self then
Bus.UnregisterEvent(MessageInternalBDDatosChange, OnInternalBDDatosChange);
inherited;
end;
function TBD.GetDatabase(const tipo: TSCDatabase): TIBDatabase;
begin
case tipo of
scdUsuario: result := IBDatabaseUsuario;
scdComun: result := IBDatabaseComun;
else result := IBDatabaseDatos;
end;
end;
function TBD.GetDatabasePath(const tipo: TSCDatabase;
BDDatos: TBDDatos): TFileName;
function GetDBIdentifier: string;
begin
case tipo of
scdUsuario: result := 'U';
scdComun: result := 'C';
scdDatos:
if BDDatos = bddDiaria then
result := 'DD'
else
result := 'DS';
end;
end;
begin
result := BDsPath + 'SC' + GetDBIdentifier + '.dat';
end;
function TBD.GetNewDatabase(const AOwner: TComponent; const tipo: TSCDatabase;
BDDatos: TBDDatos): TIBDatabase;
begin
result := TIBDatabase.Create(AOwner);
result.DefaultTransaction := TIBTransaction.Create(result);
result.DatabaseName := GetDatabasePath(tipo, BDDatos);
OpenDatabase(result);
end;
function TBD.GetTipoDatabase(const database: TIBDatabase): TSCDatabase;
var dbName: TIBFileName;
begin
dbName := database.Name;
if dbName = IBDatabaseDatos.Name then
result := scdDatos
else
if dbName = IBDatabaseComun.Name then
result := scdComun
else
if dbName = IBDatabaseUsuario.Name then
result := scdUsuario
else
raise Exception.Create('database not found: ' + dbName);
end;
procedure TBD.OnInternalBDDatosChange;
begin
SetBDDatos(MainBD.BDDatos);
end;
procedure TBD.SetBDDatos(const Value: TBDDatos);
begin
if FBDDatos <> Value then begin
FBDDatos := Value;
IBDatabaseDatos.Close;
IBDatabaseDatos.DatabaseName := GetDatabasePath(scdDatos, FBDDatos);
OpenDatabase(IBDatabaseDatos);
if MainBD = Self then
Bus.SendEvent(MessageInternalBDDatosChange);
end;
end;
procedure GlobalInitialization;
begin
DataModuleManager.RegisterAutoCreateDataModule('BD', TBD);
end;
end.
|
// ******************************************************************
//
// Program Name : AT Library
// Platform(s) : Android, iOS, Linux, MacOS, Windows
// Framework : Console, FMX, VCL
//
// Filename : AT.Validate.pas
// Date Created : 11-Apr-2017
// Author : Matthew Vesperman
//
// Description:
//
// Data validation routines.
//
// Revision History:
//
// v1.00 : Initial version
//
// ******************************************************************
//
// COPYRIGHT © 2017 - PRESENT Angelic Technology
// ALL RIGHTS RESERVED WORLDWIDE
//
// ******************************************************************
/// <summary>
/// Contains data validation routines.
/// </summary>
unit AT.Validate;
interface
uses
System.Classes, System.Types;
const
cRegExBoolFalse = '^[Ff]([Aa][Ll][Ss][Ee])?|[Nn][Oo]?|0$';
cRegExBoolTrue = '^[Tt]([Rr][Uu][Ee])?|[Yy]([Ee][Ss])?|1$';
cRegExEmail = '^[a-zA-Z0-9.!#$%&''*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:' +
'[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:' +
'[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$';
cRegExHostName = '^(localhost|[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,10})' +
'(:[0-9]{1,5})?(\/.*)?$';
cRegExIPV4 = '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}' +
'([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$';
cRegExURL = '^(ftp:\/\/|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}' +
'[a-z0-9]+)*\.[a-z]{2,10}(:[0-9]{1,5})?(\/.*)?$';
type
/// <summary>
/// Contains class functions to check and validate data.
/// </summary>
TATValidate = class
public
/// <summary>
/// Determine if Value is a boolean value.
/// </summary>
/// <param name="Value">
/// The string to check.
/// </param>
/// <returns>
/// Returns TRUE if Value is a boolean value. Can be
/// F[alse]|N[o]|0|T[rue]|Y[es]|1. Case insensitive.
/// </returns>
/// <remarks>
/// Calls TATValidate.IsStrBooleanFalse and TATValidate.IsStrBooleanTrue
/// to check string.
/// </remarks>
class function IsStrBoolean(const Value: String): Boolean;
/// <summary>
/// Determine if Value is a boolean false value.
/// </summary>
/// <param name="Value">
/// The string to check.
/// </param>
/// <returns>
/// Returns TRUE if Value is a boolean false value. Can be
/// F[alse]|N[o]|0. Case insensitive.
/// </returns>
/// <remarks>
/// <para>
/// Regular Expression: '^[Ff]([Aa][Ll][Ss][Ee])?|[Nn][Oo]?|0$'
/// </para>
/// <para>
/// Calls TATValidate.MatchesRegEx to check string.
/// </para>
/// </remarks>
class function IsStrBooleanFalse(const Value: String): Boolean;
/// <summary>
/// Determine if Value is a boolean true value.
/// </summary>
/// <param name="Value">
/// The string to check.
/// </param>
/// <returns>
/// Returns TRUE if Value is a boolean true value. Can be T[rue]|Y[es]|1.
/// Case insensitive.
/// </returns>
/// <remarks>
/// <para>
/// Regular Expression: '^[Tt]([Rr][Uu][Ee])?|[Yy]([Ee][Ss])?|1$'
/// </para>
/// <para>
/// Calls TATValidate.MatchesRegEx to check string.
/// </para>
/// </remarks>
class function IsStrBooleanTrue(const Value: String): Boolean;
/// <summary>
/// Determine if Value is a currency (money) value.
/// </summary>
/// <param name="Value">
/// The string to check.
/// </param>
/// <returns>
/// Returns TRUE if Value is a currency (money) value.
/// </returns>
class function IsStrCurrency(const Value: String): Boolean;
/// <summary>
/// Determine if Value is a date value.
/// </summary>
/// <param name="Value">
/// The string to check.
/// </param>
/// <returns>
/// Returns TRUE if Value is a date value.
/// </returns>
class function IsStrDate(const Value: String): Boolean;
/// <summary>
/// Determine is Value is a date/time value.
/// </summary>
/// <param name="Value">
/// The string to check.
/// </param>
/// <returns>
/// Returns TRUE is Value is a date/time value.
/// </returns>
class function IsStrDateTime(const Value: String): Boolean;
/// <summary>
/// Determine if Value is a Real (floating-point) value.
/// </summary>
/// <param name="Value">
/// The string to check.
/// </param>
/// <returns>
/// Returns TRUE if Value is a Real (floating-point) value.
/// </returns>
class function IsStrFloat(const Value: String): Boolean;
/// <summary>
/// Determine if Value is a Int64 value.
/// </summary>
/// <param name="Value">
/// The string to check.
/// </param>
/// <returns>
/// Returns TRUE if Value is a Int64 value.
/// </returns>
class function IsStrInt64(const Value: String): Boolean;
/// <summary>
/// Determine if Value is a Integer value.
/// </summary>
/// <param name="Value">
/// The string to check.
/// </param>
/// <returns>
/// Returns TRUE if Value is a Integer value.
/// </returns>
class function IsStrInteger(const Value: String): Boolean;
/// <summary>
/// Determine if Value is a time value.
/// </summary>
/// <param name="Value">
/// The string to check.
/// </param>
/// <returns>
/// Returns TRUE if Value is a time value.
/// </returns>
class function IsStrTime(const Value: String): Boolean;
/// <summary>
/// Determine if Value is a UInt value.
/// </summary>
/// <param name="Value">
/// The string to check.
/// </param>
/// <returns>
/// Returns TRUE if Value is a UInt value.
/// </returns>
class function IsStrUInt(const Value: String): Boolean;
/// <summary>
/// Determine if Value is a UInt64 value.
/// </summary>
/// <param name="Value">
/// The string to check.
/// </param>
/// <returns>
/// Returns TRUE if Value is a UInt64 value.
/// </returns>
class function IsStrUInt64(const Value: String): Boolean;
/// <summary>
/// Determines if Value is a valid email address.
/// </summary>
/// <param name="Value">
/// The string to validate as an email address.
/// </param>
/// <returns>
/// TRUE if Value is a valid email address, FALSE otherwise.
/// </returns>
/// <remarks>
/// <para>
/// Regular Expression:
/// '^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$'
/// </para>
/// <para>
/// Calls TATValidate.MatchesRegEx to check string.
/// </para>
/// </remarks>
class function IsValidEmail(const Value: String): Boolean;
/// <summary>
/// Determines if Value is a valid hostname.
/// </summary>
/// <param name="Value">
/// The string to validate as a hostname.
/// </param>
/// <returns>
/// TRUE if Value is a valid hostname, FALSE otherwise.
/// </returns>
/// <remarks>
/// <para>
/// Regular Expression:
/// '^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,10}?$'
/// </para>
/// <para>
/// If Value is NOT 'localhost' then this method calls
/// TATValidate.MatchesRegEx to check string.
/// </para>
/// </remarks>
class function IsValidHostName(const Value: String): Boolean;
/// <summary>
/// Determines if Value is a valid IPV4 address.
/// </summary>
/// <param name="Value">
/// The string to validate as a IPV4 address.
/// </param>
/// <returns>
/// TRUE if Value is a valid IPV4 address, FALSE otherwise.
/// </returns>
/// <remarks>
/// <para>
/// Regular Expression:
/// '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'
/// </para>
/// <para>
/// Calls TATValidate.MatchesRegEx to check string.
/// </para>
/// </remarks>
class function IsValidIPV4Address(const Value: String): Boolean;
/// <summary>
/// Determines if Value is a valid url.
/// </summary>
/// <param name="Value">
/// The string to validate as a url.
/// </param>
/// <returns>
/// TRUE if Value is a valid url, FALSE otherwise.
/// </returns>
/// <remarks>
/// <para>
/// Regular Expression:
/// '^(ftp:\/\/|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,10}(:[0-9]{1,5})?(\/.*)?$'
/// </para>
/// <para>
/// Validates ftp, http, https prefixes as well as prefix-less urls.
/// </para>
/// <para>
/// Calls TATValidate.MatchesRegEx to check string.
/// </para>
/// </remarks>
class function IsValidURL(const Value: String): Boolean;
/// <summary>
/// Determines if Value is a valid string according to ARegEx,
/// </summary>
/// <param name="Value">
/// The string value to validate.
/// </param>
/// <param name="ARegEx">
/// The regular expression to use for validation.
/// </param>
/// <returns>
/// TRUE if Value matches the regular expression passed in ARegEx.
/// </returns>
class function MatchesRegEx(const Value, ARegEx: String): Boolean;
end;
//FUNCTIONS - These are maintained for backwards compatability...
/// <summary>
/// Determine if Value is a boolean value.
/// </summary>
/// <param name="Value">
/// The string to check.
/// </param>
/// <returns>
/// Returns TRUE if Value is a boolean value. Can be
/// F[alse]|N[o]|0|T[rue]|Y[es]|1. Case insensitive.
/// </returns>
/// <remarks>
/// <para>
/// Calls TATValidate.IsStrBoolean to check string.
/// </para>
/// <para>
/// Maintained for backwards compatability. Use TATValidate.IsStrBoolean
/// instead.
/// </para>
/// </remarks>
function IsStrBoolean(const Value: String): Boolean;
/// <summary>
/// Determine if Value is a boolean false value.
/// </summary>
/// <param name="Value">
/// The string to check.
/// </param>
/// <returns>
/// Returns TRUE if Value is a boolean false value. Can be F[alse]|N[o]|0.
/// Case insensitive.
/// </returns>
/// <remarks>
/// <para>
/// Calls TATValidate.IsStrBooleanFalse to check string.
/// </para>
/// <para>
/// Maintained for backwards compatability. Use
/// TATValidate.IsStrBooleanFalse instead.
/// </para>
/// </remarks>
function IsStrBooleanFalse(const Value: String): Boolean;
/// <summary>
/// Determine if Value is a boolean true value.
/// </summary>
/// <param name="Value">
/// The string to check.
/// </param>
/// <returns>
/// Returns TRUE if Value is a boolean true value. Can be T[rue]|Y[es]|1.
/// Case insensitive.
/// </returns>
/// <remarks>
/// <para>
/// Calls TATValidate.IsStrBooleanTrue to check string.
/// </para>
/// <para>
/// Maintained for backwards compatability. Use TATValidate.IsBooleanTrue
/// instead.
/// </para>
/// </remarks>
function IsStrBooleanTrue(const Value: String): Boolean;
/// <summary>
/// Determine if Value is a currency (money) value.
/// </summary>
/// <param name="Value">
/// The string to check.
/// </param>
/// <returns>
/// Returns TRUE if Value is a currency (money) value.
/// </returns>
/// <remarks>
/// <para>
/// Calls TATValidate.IsStrCurrency to check string.
/// </para>
/// <para>
/// Maintained for backwards compatability. Use TATValidate.IsStrCurrency
/// instead.
/// </para>
/// </remarks>
function IsStrCurrency(const Value: String): Boolean;
/// <summary>
/// Determine if Value is a date value.
/// </summary>
/// <param name="Value">
/// The string to check.
/// </param>
/// <returns>
/// Returns TRUE if Value is a date value.
/// </returns>
/// <remarks>
/// <para>
/// Calls TATValidate.IsStrDate to check string.
/// </para>
/// <para>
/// Maintained for backwards compatability. Use TATValidate.IsStrDate
/// instead.
/// </para>
/// </remarks>
function IsStrDate(const Value: String): Boolean;
/// <summary>
/// Determine is Value is a date/time value.
/// </summary>
/// <param name="Value">
/// The string to check.
/// </param>
/// <returns>
/// Returns TRUE is Value is a date/time value.
/// </returns>
/// <remarks>
/// <para>
/// Calls TATValidate.IsStrDateTime to check string.
/// </para>
/// <para>
/// Maintained for backwards compatability. Use TATValidate.IsStrDateTime
/// instead.
/// </para>
/// </remarks>
function IsStrDateTime(const Value: String): Boolean;
/// <summary>
/// Determine if Value is a Integer value.
/// </summary>
/// <param name="Value">
/// The string to check.
/// </param>
/// <returns>
/// Returns TRUE if Value is a Integer value.
/// </returns>
/// <remarks>
/// <para>
/// Calls TATValidate.IsStrIneger to check string.
/// </para>
/// <para>
/// Maintained for backwards compatability. Use TATValidate.IsStrInteger
/// instead.
/// </para>
/// </remarks>
function IsStrInteger(const Value: String): Boolean;
/// <summary>
/// Determine if Value is a Real (floating-point) value.
/// </summary>
/// <param name="Value">
/// The string to check.
/// </param>
/// <returns>
/// Returns TRUE if Value is a Real (floating-point) value.
/// </returns>
/// <remarks>
/// <para>
/// Calls TATValidate.IsStrFloat to check value.
/// </para>
/// <para>
/// Maintained for backwards compatability. Use TATValidate.IsStrFloat
/// instead.
/// </para>
/// </remarks>
function IsStrReal(const Value: String): Boolean;
/// <summary>
/// Determine if AStr is a time value.
/// </summary>
/// <param name="AStr">
/// The string to check.
/// </param>
/// <returns>
/// Returns TRUE if AStr is a time value.
/// </returns>
/// <remarks>
/// <para>
/// Calls TATValidate.IsStrTime to check string.
/// </para>
/// <para>
/// Maintained for backwards compatability. Use TATValidate.IsStrTime
/// instead.
/// </para>
/// </remarks>
function IsStrTime(const AStr: String): Boolean;
/// <summary>
/// Determines if Value is a valid email address.
/// </summary>
/// <param name="Value">
/// The string to validate as an email address.
/// </param>
/// <returns>
/// TRUE if Value is a valid email address, FALSE otherwise.
/// </returns>
/// <remarks>
/// <para>
/// Calls TATValidate.IsValidEmail to check string.
/// </para>
/// <para>
/// Maintained for backwards compatability. Use TATValidate.IsValidEmail
/// instead.
/// </para>
/// </remarks>
function IsValidEmail(const Value: String): Boolean;
/// <summary>
/// Determines if Value is a valid string according to ARegEx,
/// </summary>
/// <param name="Value">
/// The string value to validate.
/// </param>
/// <param name="ARegEx">
/// The regular expression to use for validation.
/// </param>
/// <returns>
/// TRUE if Value matches the regular expression passed in ARegEx.
/// </returns>
/// <remarks>
/// <para>
/// Calls TATValidate.MatchesRegEx to validate string.
/// </para>
/// <para>
/// Maintained for backwards compatability. Use TATValidate.MatchesRegEx
/// instead.
/// </para>
/// </remarks>
function MatchesRegEx(const Value, ARegEx: String): Boolean;
implementation
uses
System.SysUtils, System.RegularExpressions, AT.Strings.Replace;
function IsStrBoolean(const Value: String): Boolean;
begin
Result := TATValidate.IsStrBoolean(Value);
end;
function IsStrBooleanFalse(const Value: String): Boolean;
begin
Result := TATValidate.IsStrBooleanFalse(Value);
end;
function IsStrBooleanTrue(const Value: String): Boolean;
begin
Result := TATValidate.IsStrBooleanTrue(Value);
end;
function IsStrCurrency(const Value: String): Boolean;
begin
Result := TATValidate.IsStrCurrency(Value);
end;
function IsStrDate(const Value: String): Boolean;
begin
Result := TATValidate.IsStrDate(Value);
end;
function IsStrDateTime(const Value: String): Boolean;
begin
Result := TATValidate.IsStrDateTime(Value);
end;
function IsStrInteger(const Value: String): Boolean;
begin
Result := TATValidate.IsStrInteger(Value);
end;
function IsStrReal(const Value: String): Boolean;
begin
Result := TATValidate.IsStrFloat(Value);
end;
function IsStrTime(const AStr: string): Boolean;
var
ADT: TDateTime;
begin
Result := TryStrToTime(AStr, ADT);
end;
function IsValidEmail(const Value: String): Boolean;
begin
Result := TATValidate.IsValidEmail(Value);
end;
function MatchesRegEx(const Value, ARegEx: String): Boolean;
begin
Result := TATValidate.MatchesRegEx(Value, ARegEx);
end;
class function TATValidate.IsStrBoolean(const Value: String): Boolean;
begin
Result := (
TATValidate.IsStrBooleanFalse(Value) OR
TATValidate.IsStrBooleanTrue(Value)
);
end;
class function TATValidate.IsStrBooleanFalse(const Value: String): Boolean;
begin
Result := TATValidate.MatchesRegEx(Value, cRegExBoolFalse);
end;
class function TATValidate.IsStrBooleanTrue(const Value: String): Boolean;
begin
Result := TATValidate.MatchesRegEx(Value, cRegExBoolTrue);
end;
class function TATValidate.IsStrCurrency(const Value: String): Boolean;
var
ACurr: Currency;
AFmt: TFormatSettings;
begin
AFmt := TFormatSettings.Create;
Result := TryStrToCurr(Value, ACurr, AFmt);
end;
class function TATValidate.IsStrDate(const Value: String): Boolean;
var
sTemp: String;
ADT: TDateTime;
AFmt: TFormatSettings;
begin
sTemp := StrReplaceMonthNames(Value);
AFmt := TFormatSettings.Create;
Result := TryStrToDate(sTemp, ADT, AFmt);
end;
class function TATValidate.IsStrDateTime(const Value: String): Boolean;
var
sTemp: String;
ADT: TDateTime;
AFmt: TFormatSettings;
begin
sTemp := StrReplaceMonthNames(Value);
AFmt := TFormatSettings.Create;
Result := TryStrToDateTime(sTemp, ADT, AFmt);
end;
class function TATValidate.IsStrFloat(const Value: String): Boolean;
var
AFloat: Extended;
AFmt: TFormatSettings;
begin
AFmt := TFormatSettings.Create;
Result := TryStrToFloat(Value, AFloat, AFmt);
end;
class function TATValidate.IsStrInt64(const Value: String): Boolean;
var
AInt: Int64;
begin
Result := TryStrToInt64(Value, AInt);
end;
class function TATValidate.IsStrInteger(const Value: String): Boolean;
var
AInt: Integer;
begin
Result := TryStrToInt(Value, AInt);
end;
class function TATValidate.IsStrTime(const Value: String): Boolean;
var
sTemp: String;
ADT: TDateTime;
AFmt: TFormatSettings;
begin
sTemp := StrReplaceMonthNames(Value);
AFmt := TFormatSettings.Create;
Result := TryStrToTime(sTemp, ADT, AFmt);
end;
class function TATValidate.IsStrUInt(const Value: String): Boolean;
var
AInt: Cardinal;
begin
Result := TryStrToUInt(Value, AInt);
end;
class function TATValidate.IsStrUInt64(const Value: String): Boolean;
var
AInt: UInt64;
begin
Result := TryStrToUInt64(Value, AInt);
end;
class function TATValidate.IsValidEmail(const Value: String): Boolean;
begin
Result := TATValidate.MatchesRegEx(Value, cRegExEmail);
end;
class function TATValidate.IsValidHostName(const Value: String): Boolean;
begin
Result := SameText(Value, 'localhost');
if (Result) then
Exit(Result);
Result := TATValidate.MatchesRegEx(Value, cRegExHostName);
end;
class function TATValidate.IsValidIPV4Address(const Value: String): Boolean;
begin
Result := TATValidate.MatchesRegEx(Value, cRegExIPV4);
end;
class function TATValidate.IsValidURL(const Value: String): Boolean;
begin
Result := TATValidate.MatchesRegEx(Value, cRegExURL);
end;
class function TATValidate.MatchesRegEx(const Value, ARegEx: String): Boolean;
begin
Result := TRegEx.IsMatch(Value, ARegEx);
end;
end.
|
unit qCDKmodbusTypes;
interface
uses Classes,qCDKclasses;
type
TModbusFunction=type byte;
const
// константы исключений
mexcIllegalFunction=1; mexcIllegalDataAddress=2; mexcIllegalDataValue=3;
mexcSlaveDeviceFailure=4; mexcAknowledge=5; mexcSlaveDeviceBusy=6;
mexcSlaveDeviceProgramFailure=7; mexcMemoryParityError=8;
mexcGatewayPathUnavailable=10; mexcGatewayTargetNoResponse=11;
ModbusExceptionsInfos:array[0..9]of TIdentMapEntry=(
(Value: mexcIllegalFunction; Name: 'принятый код функции не может быть обработан'),
(Value: mexcIllegalDataAddress; Name: 'адрес данных, указанный в запросе, недоступен'),
(Value: mexcIllegalDataValue; Name: 'значение, содержащееся в поле данных запроса, является недопустимой величиной'),
(Value: mexcSlaveDeviceFailure; Name: 'невосстанавливаемая ошибка имела место, пока ведомое устройство пыталось выполнить затребованное действие'),
(Value: mexcAknowledge; Name: 'ведомое устройство приняло запрос и обрабатывает его, но это требует много времени; этот ответ предохраняет ведущее устройство от генерации ошибки таймаута'),
(Value: mexcSlaveDeviceBusy; Name: 'ведомое устройство занято обработкой команды; ведущее устройство должно повторить запрос позже, когда ведомое освободится'),
(Value: mexcSlaveDeviceProgramFailure; Name: 'ведомое устройство не может выполнить программную функцию, заданную в запросе; данное исключение возвращается на неуспешные программные запросы с функциями 0x0D или 0x0E;'+' ведущее устройство должно запросить диагностическую информацию или информацию об ошибках'),
(Value: mexcMemoryParityError; Name: 'ведомое устройство при чтении расширенной памяти обнаружило ошибку контроля чётности; ведущее устройство может повторить запрос, но обычно в таких случаях требуется ремонт'),
(Value: mexcGatewayPathUnavailable; Name: 'путь к шлюзу недоступен'),
(Value: mexcGatewayTargetNoResponse; Name: 'шлюз доступен, но устройство не отвечает')
);
////////// константы для Modbus-функций
mfReadCoils=$01; mfReadDiscreteInputs=$02;
mfReadHoldingRegisters=$03; mfReadInputRegisters=$04;
mfWriteSingleCoil=$05; mfWriteSingleRegister=$06;
mfReadExceptionStatus=$07; // mfDiagnostics:TModbusFunction=$08;
// mfProgram484:TModbusFunction=$09; mfPoll484=$0A;
mfFetchCommEventCounter=$0B; mfFetchCommEventLog=$0C;
// mfProgrammController:TModbusFunction=$0D; mfPollController=$0E;
mfWriteMultipleCoils=$0F; mfWriteMultipleRegisters=$10;
// mfReportSlaveID=$11;
// mfProgram884M84:TModbusFunction=$12; mfResetCommLink:TModbusFunction=$13;
mfReadFileRecord=$14; mfWriteFileRecord=$15;
mfMaskWriteRegister=$16; mfReadWriteMultipleRegisters=$17;
// mfReadFIFOQueue=$18;
mfReadScopeRecords=$41; // только для устройств БЭМП
ModbusFuncsInfos:array[0..15]of TIdentMapEntry=(
(Value: mfReadCoils; Name: 'чтение дискретных параметров'),
(Value: mfReadDiscreteInputs; Name: 'чтение дискретных входов'),
(Value: mfReadHoldingRegisters; Name: 'чтение аналоговых параметров'),
(Value: mfReadInputRegisters; Name: 'чтение аналоговых входов'),
(Value: mfWriteSingleCoil; Name: 'запись дискретного параметра'),
(Value: mfWriteSingleRegister; Name: 'запись аналогового параметра'),
(Value: mfReadExceptionStatus; Name: 'чтение сигналов состояния'),
// (Value: mfDiagnostics; Name: 'диагностика'),
// (Value: mfProgram484; Name: 'программирование 484-контроллера'),
// (Value: mfPoll484; Name: 'проверка состояния программирования 484-контроллера'),
(Value: mfFetchCommEventCounter; Name: 'чтение счётчика коммуникационных событий'),
(Value: mfFetchCommEventLog; Name: 'чтение журнала коммуникационных событий'),
// (Value: mfProgrammController; Name: 'программирование контроллера'),
// (Value: mfPollController; Name: 'проверка состояния программирования контроллера'),
(Value: mfWriteMultipleCoils; Name: 'запись дискретных параметров'),
(Value: mfWriteMultipleRegisters; Name: 'запись аналоговых параметров'),
// (Value: mfReportSlaveID; Name: 'чтение информации об устройстве'),
// (Value: mfProgram884M84; Name: 'программирование 884M84-контроллера'),
// (Value: mfResetCommLink; Name: 'сброс коммуникационного канала'),
(Value: mfReadFileRecord; Name: 'чтение файловых дампов'),
(Value: mfWriteFileRecord; Name: 'запись файловых дампов'),
(Value: mfMaskWriteRegister; Name: 'запись в аналоговый регистр с использованием масок "И" и "ИЛИ"'),
(Value: mfReadWriteMultipleRegisters; Name: 'одновременное чтение и запись аналоговых параметров'),
// (Value: mfReadFIFOQueue; Name: 'чтение данных из очереди'),
(Value: mfReadScopeRecords; Name: 'чтение дампов осциллограмм в устройствах БЭМП')
);
////////// константы ошибок, дополняют список в qCDKclasses
meSuccess=ceSuccess; // нет ошибки
// meMismatch=8; // несовпадение запроса и ответа
meModbusException=-100; // modbus-исключение
meUnknownFunctionCode=-101; // неизвестная функция
meDeviceAddress=-102; // ожидается адрес устройства
meFunctionCode=-103; // ожидается код функции
meElementReadStartAddress=-104; // ожидается начальный адрес первого элемента на чтение
meElementReadCount=-105; // ожидается количество элементов на чтение
meElementReadByteCount=-106; // ожидается количество байт на чтение
meElementReadValues=-107; // ожидается верное количество читаемых значений
meElementWriteAddress=-108; // ожидается адрес записываемого элемента
meElementWriteValue=-109; // ожидается записываемое значение
meElementWriteStartAddress=-110; // ожидается начальный адрес первого элемента на запись
meElementWriteCount=-111; // ожидается количество элементов на запись
meElementWriteByteCount=-112; // ожидается количество байт на запись
meElementWriteValues=-113; // ожидается верное количество записываемых значений
meFileRequestSize=-114; // ожидается размер всех запросов для файла
meFileSubRequestType=-115; // ожидается тип подзапроса для файла
meFileSubRequestFileNumber=-116; // ожидается номер файла в подзапросе
meFileSubRequestAddress=-117; // ожидается номер записи для файла в подзапросе
meFileSubRequestLength=-118; // ожидается длина записи для файле в подзапросе
meElementWriteMaskAnd=-119; // ожидается маска логического И на запись
meElementWriteMaskOr=-120; // ожидается маска логического ИЛИ на запись
meExceptionCode=-121; // ожидается код исключения
lwModbusErrorsCount=22;
ModbusErrorsInfos:array[0..lwModbusErrorsCount-1]of TIdentMapEntry=(
(Value:meModbusException; Name:'-100 - modbus-исключение'),
(Value:meUnknownFunctionCode; Name:'-101 - неизвестная функция'),
(Value:meDeviceAddress; Name:'-102 - ожидается адрес устройства'),
(Value:meFunctionCode; Name:'-103 - ожидается код функции'),
(Value:meElementReadStartAddress; Name:'-104 - ожидается начальный адрес первого элемента на чтение'),
(Value:meElementReadCount; Name:'-105 - ожидается количество элементов на чтение'),
(Value:meElementReadByteCount; Name:'-106 - ожидается количество байт на чтение'),
(Value:meElementReadValues; Name:'-107 - ожидается верное количество читаемых значений'),
(Value:meElementWriteAddress; Name:'-108 - ожидается адрес записываемого элемента'),
(Value:meElementWriteValue; Name:'-109 - ожидается записываемое значение'),
(Value:meElementWriteStartAddress; Name:'-110 - ожидается начальный адрес первого элемента на запись'),
(Value:meElementWriteCount; Name:'-111 - ожидается количество элементов на запись'),
(Value:meElementWriteByteCount; Name:'-112 - ожидается количество байт на запись'),
(Value:meElementWriteValues; Name:'-113 - ожидается верное количество записываемых значений'),
(Value:meFileRequestSize; Name:'-114 - ожидается размер всех запросов для файла'),
(Value:meFileSubRequestType; Name:'-115 - ожидается тип подзапроса для файла'),
(Value:meFileSubRequestFileNumber; Name:'-116 - ожидается номер файла в подзапросе'),
(Value:meFileSubRequestAddress; Name:'-117 - ожидается номер записи для файла в подзапросе'),
(Value:meFileSubRequestLength; Name:'-118 - ожидается длина записи для файле в подзапросе'),
(Value:meElementWriteMaskAnd; Name:'-119 - ожидается маска логического И на запись'),
(Value:meElementWriteMaskOr; Name:'-120 - ожидается маска логического ИЛИ на запись'),
(Value:meExceptionCode; Name:'-121 - ожидается код исключения')
);
implementation
uses SysUtils;
{$BOOLEVAL OFF}
{$RANGECHECKS OFF}
{$OVERFLOWCHECKS OFF}
(*class function TModbus.GetVersion(iNewVersion:Integer=0):AnsiString;
{$WRITEABLECONST ON}
const fVersion:integer=$0101;
{$WRITEABLECONST OFF}
begin
Result:='0x'+IntToHex(fVersion,8);
if iNewVersion<>0then fVersion:=iNewVersion;
end;*)
end.
|
unit DailySum;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
TDailySum = class
private
FLunch1Sums: array of integer;
FLunch2Sums: array of integer;
FDinner1Sums: array of integer;
FDinner2Sums: array of integer;
FDinner3Sums: array of integer;
procedure IncSum(var SumArray: array of integer; MealIndex: integer);
function GetSum(var SumArray: array of integer; MealIndex: integer): integer;
procedure FillArrayWithZeroes(Target: array of integer);
public
constructor Create(NrOfMeals: integer);
procedure IncLunch1Sum(MealIndex: integer);
procedure IncLunch2Sum(MealIndex: integer);
procedure IncDinner1Sum(MealIndex: integer);
procedure IncDinner2Sum(MealIndex: integer);
procedure IncDinner3Sum(MealIndex: integer);
function GetLunch1Sum(MealIndex: integer): integer;
function GetLunch2Sum(MealIndex: integer): integer;
function GetDinner1Sum(MealIndex: integer): integer;
function GetDinner2Sum(MealIndex: integer): integer;
function GetDinner3Sum(MealIndex: integer): integer;
end;
implementation
constructor TDailySum.Create(NrOfMeals: integer);
begin
SetLength(FLunch1Sums, NrOfMeals);
FillArrayWithZeroes(FLunch1Sums);
SetLength(FLunch2Sums, NrOfMeals);
FillArrayWithZeroes(FLunch2Sums);
SetLength(FDinner1Sums, NrOfMeals);
FillArrayWithZeroes(FDinner1Sums);
SetLength(FDinner2Sums, NrOfMeals);
FillArrayWithZeroes(FDinner2Sums);
SetLength(FDinner3Sums, NrOfMeals);
FillArrayWithZeroes(FDinner3Sums);
end;
procedure TDailySum.FillArrayWithZeroes(Target: array of integer);
var
Index: integer;
begin
for Index := 0 to Length(Target) do
begin
Target[Index] := 0;
end;
end;
procedure TDailySum.IncSum(var SumArray: array of integer; MealIndex: integer);
begin
SumArray[MealIndex] := SumArray[MealIndex] +1;
end;
procedure TDailySum.IncLunch1Sum(MealIndex: integer);
begin
IncSum(FLunch1Sums, MealIndex);
end;
procedure TDailySum.IncLunch2Sum(MealIndex: integer);
begin
IncSum(FLunch2Sums, MealIndex);
end;
procedure TDailySum.IncDinner1Sum(MealIndex: integer);
begin
IncSum(FDinner1Sums, MealIndex);
end;
procedure TDailySum.IncDinner2Sum(MealIndex: integer);
begin
IncSum(FDinner2Sums, MealIndex);
end;
procedure TDailySum.IncDinner3Sum(MealIndex: integer);
begin
IncSum(FDinner3Sums, MealIndex);
end;
function TDailySum.GetSum(var SumArray: array of integer; MealIndex: integer): integer;
begin
GetSum := SumArray[MealIndex];
end;
function TDailySum.GetLunch1Sum(MealIndex: integer): integer;
begin
GetLunch1Sum := GetSum(FLunch1Sums, MealIndex);
end;
function TDailySum.GetLunch2Sum(MealIndex: integer): integer;
begin
GetLunch2Sum := GetSum(FLunch2Sums, MealIndex);
end;
function TDailySum.GetDinner1Sum(MealIndex: integer): integer;
begin
GetDinner1Sum := GetSum(FDinner1Sums, MealIndex);
end;
function TDailySum.GetDinner2Sum(MealIndex: integer): integer;
begin
GetDinner2Sum := GetSum(FDinner2Sums, MealIndex);
end;
function TDailySum.GetDinner3Sum(MealIndex: integer): integer;
begin
GetDinner3Sum := GetSum(FDinner3Sums, MealIndex);
end;
end.
|
unit BiomeDecorator_u;
interface
uses RandomMCT, generation_obsh, WorldGenerator_u;
type BiomeDecorator=class(TObject)
protected
biome:TObject;
clayGen,sandGen,gravelAsSandGen,dirtGen,gravelGen,
coalGen,ironGen,goldGen,redstoneGen,diamondGen,
lapisGen,plantYellowGen,plantRedGen,mushroomBrownGen,
mushroomRedGen,field_40720_u,reedGen,cactusGen,
waterlilyGen,tallGrassGen,deadBushGen,pumpkinGen,
liquidsWaterGen,liquidsLavaGen:WorldGenerator;
procedure genStandardOre1(i:integer; generator:WorldGenerator; map:region; xreg,yreg,j,k:integer);
procedure genStandardOre2(i:integer; generator:WorldGenerator; map:region; xreg,yreg,j,k:integer);
procedure generateOres(map:region; xreg,yreg:integer);
procedure decorate_do(map:region; xreg,yreg:integer);
procedure make_fall(map:region; xreg,yreg:integer);
public
decoRNG:rnd;
chunk_X,chunk_Z:integer;
waterlilyPerChunk,treesPerChunk,flowersPerChunk,grassPerChunk,
reedsPerChunk,deadBushPerChunk,mushroomsPerChunk,
cactiPerChunk,sandPerChunk,sandPerChunk2,clayPerChunk,
field_40718_J:integer;
generateFluid:boolean;
constructor Create(biomegen:TObject); virtual;
destructor Destroy; override;
procedure decorate(map:region; xreg,yreg:integer; rand:rnd; i,j:integer);
end;
implementation
uses WorldGenClay_u, WorldGenSand_u, WorldGenMinable_u,
WorldGenFlowers_u, WorldGenBigMushroom_u, WorldGenReed_u,
WorldGenCactus_u, MapGenWaterlily_u, WorldGenTallGrass_u,
WorldGenDeadBush_u, WorldGenPumpkin_u, WorldGenLiquids_u,
generation_spec, BiomeGenBase_u;
constructor BiomeDecorator.Create(biomegen:TObject);
begin
clayGen:=WorldGenClay.Create(4);
sandGen:=WorldGenSand.Create(7, 12);
gravelAsSandGen:=WorldGenSand.Create(6, 13);
dirtGen:=WorldGenMinable.Create(3, 32);
gravelGen:=WorldGenMinable.Create(13, 32);
coalGen:=WorldGenMinable.Create(16, 16);
ironGen:=WorldGenMinable.Create(15, 8);
goldGen:=WorldGenMinable.Create(14, 8);
redstoneGen:=WorldGenMinable.Create(73, 7);
diamondGen:=WorldGenMinable.Create(56, 7);
lapisGen:=WorldGenMinable.Create(21, 6);
plantYellowGen:=WorldGenFlowers.Create(37);
plantRedGen:=WorldGenFlowers.Create(38);
mushroomBrownGen:=WorldGenFlowers.Create(39);
mushroomRedGen:=WorldGenFlowers.Create(40);
field_40720_u:=WorldGenBigMushroom.Create;
reedGen:=WorldGenReed.Create;
cactusGen:=WorldGenCactus.Create;
waterlilyGen:=MapGenWaterlily.Create;
tallGrassGen:=WorldGenTallGrass.Create(31,1);
deadBushGen:=WorldGenDeadBush.Create(32);
pumpkinGen:=WorldGenPumpkin.Create;
liquidsWaterGen:=WorldGenLiquids.Create(8);
liquidsLavaGen:=WorldGenLiquids.Create(10);
waterlilyPerChunk:= 0;
treesPerChunk:= 0;
flowersPerChunk:= 2;
grassPerChunk:= 1;
deadBushPerChunk:= 0;
mushroomsPerChunk:= 0;
reedsPerChunk:= 0;
cactiPerChunk:= 0;
sandPerChunk:= 1;
sandPerChunk2:= 3;
clayPerChunk:= 1;
field_40718_J:= 0;
generateFluid:= true;
biome:= biomegen;
end;
destructor BiomeDecorator.Destroy;
begin
clayGen.Free;
sandGen.Free;
gravelAsSandGen.Free;
dirtGen.Free;
gravelGen.Free;
coalGen.Free;
ironGen.Free;
goldGen.Free;
redstoneGen.Free;
diamondGen.Free;
lapisGen.Free;
plantYellowGen.Free;
plantRedGen.Free;
mushroomBrownGen.Free;
mushroomRedGen.Free;
field_40720_u.Free;
reedGen.Free;
cactusGen.Free;
waterlilyGen.Free;
tallGrassGen.Free;
deadBushGen.Free;
pumpkinGen.Free;
liquidsWaterGen.Free;
liquidsLavaGen.Free;
end;
procedure BiomeDecorator.decorate(map:region; xreg,yreg:integer; rand:rnd; i,j:integer);
begin
chunk_X:=i;
chunk_Z:=j;
decoRNG:=rand;
decorate_do(map,xreg,yreg);
end;
procedure BiomeDecorator.decorate_do(map:region; xreg,yreg:integer);
var trees:WorldGenerator;
t,l:integer;
xx,yy,zz:integer;
begin
generateores(map,xreg,yreg);
make_fall(map,xreg,yreg);
for t:=0 to sandPerChunk2-1 do
begin
xx:=chunk_X + decoRNG.nextInt(16) + 8;
zz:=chunk_Z + decoRNG.nextInt(16) + 8;
yy:=get_top_solid(map,xreg,yreg,xx,zz);
sandGen.generate(map,xreg,yreg,decoRNG,xx,yy,zz);
end;
for t:=0 to clayPerChunk-1 do
begin
xx:=chunk_X + decoRNG.nextInt(16) + 8;
zz:=chunk_Z + decoRNG.nextInt(16) + 8;
yy:=get_top_solid(map,xreg,yreg,xx,zz);
clayGen.generate(map,xreg,yreg,decoRNG,xx,yy,zz);
end;
for t:=0 to sandPerChunk-1 do
begin
xx:=chunk_X + decoRNG.nextInt(16) + 8;
zz:=chunk_Z + decoRNG.nextInt(16) + 8;
yy:=get_top_solid(map,xreg,yreg,xx,zz);
sandGen.generate(map,xreg,yreg,decoRNG,xx,yy,zz);
end;
l:=treesPerChunk;
if(decoRNG.nextInt(10) = 0) then inc(l);
for t:=0 to l-1 do
begin
xx:= chunk_X + decoRNG.nextInt(16) + 8;
zz:= chunk_Z + decoRNG.nextInt(16) + 8;
yy:=get_heightmap(map,xreg,yreg,xx,zz);
trees:=BiomeGenBase(biome).getRandomWorldGenForTrees(decoRNG);
trees.func_517_a(1, 1, 1);
trees.generate(map,xreg,yreg, decoRNG, xx, yy, zz);
end;
for t:=0 to field_40718_J-1 do
begin
xx:=chunk_X + decoRNG.nextInt(16) + 8;
zz:=chunk_Z + decoRNG.nextInt(16) + 8;
yy:=get_heightmap(map,xreg,yreg,xx,zz);
field_40720_u.generate(map,xreg,yreg,decoRNG,xx,yy,zz);
end;
for t:=0 to flowersPerChunk-1 do
begin
xx:=chunk_X + decoRNG.nextInt(16) + 8;
yy:=decoRNG.nextInt(128);
zz:=chunk_Z + decoRNG.nextInt(16) + 8;
plantYellowGen.generate(map,xreg,yreg,decoRNG,xx,yy,zz);
if(decoRNG.nextInt(4) = 0) then
begin
xx:=chunk_X + decoRNG.nextInt(16) + 8;
yy:=decoRNG.nextInt(128);
zz:=chunk_Z + decoRNG.nextInt(16) + 8;
plantRedGen.generate(map,xreg,yreg,decoRNG,xx,yy,zz);
end;
end;
for t:=0 to grassPerChunk-1 do
begin
xx:=chunk_X + decoRNG.nextInt(16) + 8;
yy:=decoRNG.nextInt(128);
zz:=chunk_Z + decoRNG.nextInt(16) + 8;
tallGrassGen.generate(map,xreg,yreg,decoRNG,xx,yy,zz);
end;
for t:=0 to deadBushPerChunk-1 do
begin
xx:=chunk_X + decoRNG.nextInt(16) + 8;
yy:=decoRNG.nextInt(128);
zz:=chunk_Z + decoRNG.nextInt(16) + 8;
deadBushGen.generate(map,xreg,yreg,decoRNG,xx,yy,zz);
end;
for t:=0 to waterlilyPerChunk-1 do
begin
xx:=chunk_X + decoRNG.nextInt(16) + 8;
zz:=chunk_Z + decoRNG.nextInt(16) + 8;
yy:=decoRNG.nextInt(128);
while (yy > 0)and(get_Block_Id(map,xreg,yreg,xx, yy - 1, zz) = 0) do
dec(yy);
waterlilyGen.generate(map,xreg,yreg,decoRNG,xx,yy,zz);
end;
for t:=0 to mushroomsPerChunk-1 do
begin
if decoRNG.nextInt(4) = 0 then
begin
xx:=chunk_X + decoRNG.nextInt(16) + 8;
yy:=get_heightmap(map,xreg,yreg,xx,zz);
zz:=chunk_Z + decoRNG.nextInt(16) + 8;
mushroomBrownGen.generate(map,xreg,yreg,decoRNG,xx,yy,zz);
end;
if decoRNG.nextInt(8) = 0 then
begin
xx:=chunk_X + decoRNG.nextInt(16) + 8;
yy:=get_heightmap(map,xreg,yreg,xx,zz);
zz:=chunk_Z + decoRNG.nextInt(16) + 8;
mushroomRedGen.generate(map,xreg,yreg,decoRNG,xx,yy,zz);
end;
end;
if(decoRNG.nextInt(4) = 0) then
begin
xx:=chunk_X + decoRNG.nextInt(16) + 8;
yy:=decoRNG.nextInt(128);
zz:=chunk_Z + decoRNG.nextInt(16) + 8;
mushroomBrownGen.generate(map,xreg,yreg,decoRNG,xx,yy,zz);
end;
if decoRNG.nextInt(8) = 0 then
begin
xx:=chunk_X + decoRNG.nextInt(16) + 8;
yy:=decoRNG.nextInt(128);
zz:=chunk_Z + decoRNG.nextInt(16) + 8;
mushroomRedGen.generate(map,xreg,yreg,decoRNG,xx,yy,zz);
end;
for t:=0 to reedsPerChunk-1 do
begin
xx:=chunk_X + decoRNG.nextInt(16) + 8;
yy:=decoRNG.nextInt(128);
zz:=chunk_Z + decoRNG.nextInt(16) + 8;
reedGen.generate(map,xreg,yreg,decoRNG,xx,yy,zz);
end;
for t:=0 to 9 do
begin
xx:=chunk_X + decoRNG.nextInt(16) + 8;
yy:=decoRNG.nextInt(128);
zz:=chunk_Z + decoRNG.nextInt(16) + 8;
reedGen.generate(map,xreg,yreg,decoRNG,xx,yy,zz);
end;
if(decoRNG.nextInt(32) = 0) then
begin
xx:=chunk_X + decoRNG.nextInt(16) + 8;
yy:=decoRNG.nextInt(128);
zz:=chunk_Z + decoRNG.nextInt(16) + 8;
pumpkinGen.generate(map,xreg,yreg,decoRNG,xx,yy,zz);
end;
for t:=0 to cactiPerChunk-1 do
begin
xx:=chunk_X + decoRNG.nextInt(16) + 8;
yy:=decoRNG.nextInt(128);
zz:=chunk_Z + decoRNG.nextInt(16) + 8;
cactusGen.generate(map,xreg,yreg,decoRNG,xx,yy,zz);
end;
if(generateFluid) then
begin
for t:=0 to 49 do
begin
xx:=chunk_X + decoRNG.nextInt(16) + 8;
yy:=decoRNG.nextInt(decoRNG.nextInt(128 - 8) + 8);
zz:=chunk_Z + decoRNG.nextInt(16) + 8;
liquidsWaterGen.generate(map,xreg,yreg,decoRNG,xx,yy,zz);
end;
for t:=0 to 19 do
begin
xx:=chunk_X + decoRNG.nextInt(16) + 8;
yy:=decoRNG.nextInt(decoRNG.nextInt(decoRNG.nextInt(128 - 16) + 8) + 8);
zz:=chunk_Z + decoRNG.nextInt(16) + 8;
liquidsLavaGen.generate(map,xreg,yreg,decoRNG,xx,yy,zz);
end;
end;
end;
procedure BiomeDecorator.make_fall(map:region; xreg,yreg:integer);
var tempxot,tempxdo,tempyot,tempydo:integer;
chxot,chxdo,chyot,chydo:integer;
x,y,z,tx,ty,t,t1,tt:integer;
b:boolean;
begin
//schitaem koordinati nachalnih i konechnih chankov v regione
if xreg<0 then
begin
tempxot:=(xreg+1)*32-32;
tempxdo:=(xreg+1)*32+3;
end
else
begin
tempxot:=xreg*32;
tempxdo:=(xreg*32)+35;
end;
if yreg<0 then
begin
tempyot:=(yreg+1)*32-32;
tempydo:=(yreg+1)*32+3;
end
else
begin
tempyot:=yreg*32;
tempydo:=(yreg*32)+35;
end;
dec(tempxot,2);
dec(tempxdo,2);
dec(tempyot,2);
dec(tempydo,2);
chxot:=chunk_X div 16;
chyot:=chunk_Z div 16;
if chxot=tempxdo then chxdo:=chxot-tempxot
else chxdo:=chxot+1-tempxot;
if chyot=tempydo then chydo:=chyot-tempyot
else chydo:=chyot+1-tempyot;
chxot:=chxot-tempxot;
chyot:=chyot-tempyot;
for tx:=chxot to chxdo do
for ty:=chyot to chydo do
for x:=0 to 15 do
for z:=0 to 15 do
for y:=2 to 127 do
begin
t:=map[tx][ty].blocks[y+(z*128+(x*2048))];
case t of
12,13:begin
if (map[tx][ty].blocks[y-1+(z*128+(x*2048))] in trans_bl) then
begin
t1:=y-2;
tt:=map[tx][ty].blocks[t1+(z*128+(x*2048))];
while (t1>0)and(tt in trans_bl) do
begin
dec(t1);
tt:=map[tx][ty].blocks[t1+(z*128+(x*2048))];
end;
if t1=0 then map[tx][ty].blocks[y+(z*128+(x*2048))]:=0
else
begin
map[tx][ty].blocks[t1+1+(z*128+(x*2048))]:=map[tx][ty].blocks[y+(z*128+(x*2048))];
map[tx][ty].blocks[y+(z*128+(x*2048))]:=0;
end;
end;
end;
9:begin
b:=false;
//levo
if (x=0) then
begin
if tx<>0 then t1:=map[tx-1][ty].blocks[y+(z*128+(15*2048))]
else t1:=1;
end
else
t1:=map[tx][ty].blocks[y+(z*128+((x-1)*2048))];
if t1=0 then b:=true;
//pravo
if b=false then
begin
if x=15 then
begin
if tx<>35 then t1:=map[tx+1][ty].blocks[y+(z*128)]
else t1:=1;
end
else
t1:=map[tx][ty].blocks[y+(z*128+((x+1)*2048))];
if t1=0 then b:=true;
end;
//pered
if b=false then
begin
if z=15 then
begin
if ty<>35 then t1:=map[tx][ty+1].blocks[y+(x*2048)]
else t1:=1;
end
else
t1:=map[tx][ty].blocks[y+((z+1)*128+(x*2048))];
if t1=0 then b:=true;
end;
//zad
if b=false then
begin
if z=0 then
begin
if ty<>0 then t1:=map[tx][ty-1].blocks[y+(x*2048)]
else t1:=1;
end
else
t1:=map[tx][ty].blocks[y+((z-1)*128+(x*2048))];
if t1=0 then b:=true;
end;
//niz
if map[tx][ty].blocks[y-1+(z*128+(x*2048))]=0 then b:=true;
if b=true then map[tx][ty].blocks[y+(z*128+(x*2048))]:=8;
end;
end;
end;
end;
procedure BiomeDecorator.genStandardOre1(i:integer; generator:WorldGenerator; map:region; xreg,yreg,j,k:integer);
var l,i1,j1,k1:integer;
begin
for l:=0 to i-1 do
begin
i1:= chunk_X + decoRNG.nextInt(16);
j1:= decoRNG.nextInt(k - j) + j;
k1:= chunk_Z + decoRNG.nextInt(16);
generator.generate(map,xreg,yreg, decoRNG, i1, j1, k1);
end;
end;
procedure BiomeDecorator.genStandardOre2(i:integer; generator:WorldGenerator; map:region; xreg,yreg,j,k:integer);
var l,i1,j1,k1:integer;
begin
for l:=0 to i-1 do
begin
i1:= chunk_X + decoRNG.nextInt(16);
j1:= decoRNG.nextInt(k) + decoRNG.nextInt(k) + (j - k);
k1:= chunk_Z + decoRNG.nextInt(16);
generator.generate(map,xreg,yreg, decoRNG, i1, j1, k1);
end;
end;
procedure BiomeDecorator.generateOres(map:region; xreg,yreg:integer);
begin
genStandardOre1(20, dirtGen,map,xreg,yreg, 0, 128);
genStandardOre1(10, gravelGen,map,xreg,yreg, 0, 128);
genStandardOre1(20, coalGen,map,xreg,yreg, 0, 128);
genStandardOre1(20, ironGen,map,xreg,yreg, 0, 128 div 2);
genStandardOre1(2, goldGen,map,xreg,yreg, 0, 128 div 4);
genStandardOre1(8, redstoneGen,map,xreg,yreg, 0, 128 div 8);
genStandardOre1(1, diamondGen,map,xreg,yreg, 0, 128 div 8);
genStandardOre2(1, lapisGen,map,xreg,yreg, 128 div 8, 128 div 8);
end;
end.
|
unit uLoadValue;
interface
uses
Forms,
SysUtils,
Dialogs,
Classes,
IniFiles,
Controls, windows;
type
TConfigValue = class
private
ini: TiniFile;
//DB 정보=======================================
FDbCon: Boolean;
configFile: string;
FvarServerIP: string;
FvarServerPort: string;
FvarDbIP: string; //DBIP
FvarDbname: string;
FvarDbuser: string;
FvarDbpass: string;
FvarDbprotocol: string;
//로그인 정보=======================================
FvarLoginId: string;
FvarLoginPass: string;
FvarAutoLogin: string;
Fvarweb: string;
FvarScheduleDate: string;
FvarScheduleOpen: string;
FSMSLogin: string;
//병원 정보=======================================
FvarsaupName: string;
FvarDaepyo: string;
FvarJumin: string;
FvarsaupNo: string;
FvarMyunhu: string;
FvarYoyang: string;
FvarZip: string;
FvarAdd1: string;
FvarAdd2: string;
FvarTel1: string;
FvarTel2: string;
FvarFax1: string;
FvarFax2: string;
FvarEmail: string;
Fvarilsu: string;
FvarGubun: string;
FvarSimjibu: string;
FvarDocNo: string;
FvarChubang: string;
FvarPrintsu: string;
FvarBunup: string;
FvarDaeheng: string;
FvarRmode: string;
FvarChungname: string;
FvarChungJumin: string;
FvarJagyukID: string;
FvarJagyukpass: string;
FvarsmsId: string;
FvarSmspass: string;
FvarChartRule: string;
FvarChartNew: string;
FvarSangMode: string;
FvarJinryoSave: string;
//약속환경설정==================================
Fp_startTime: string;
Fp_finishtime: string;
Fp_SmsContent: string;
Fp_BeforSms: integer;
Fp_SmsBeforTime: string;
Fp_timeinterval: integer;
Fp_rowinterval: integer;
Fp_columncount: integer;
//기타 정보
Fvarpicpath: string;
FvarImageUse: string;
FvarImageKind: string;
FvarImageDBSaveMode: string;
FvarImageDBPORT:string;
FvarImageDBIP:string;
FvarImageDBPATH:string;
FvarpanoScale:string;
FvarImageUser: string;
FvarImageIp: string;
FvarImagePass: string;
FvarImageDb: string;
FvarImageProtocol: string;
FvarLoadChamgo: string;
FvarCidIp: string;
FvarCidPort: string;
FvarCidUse: string;
FDetailLoadInfo: string; //환자 정보로드할 때 세부 정보 볼건지(1) 말건지 (0외 기타)
FInputBohum: string; //환자 정보로드할 때 세부 정보 볼건지(1) 말건지 (0외 기타)
FBohumApplyDate: string; //환자 정보로드할 때 세부 정보 볼건지(1) 말건지 (0외 기타)
FLoadSogepan:string;
FLoadGajokpan:string;
FvarLoadDur: string;
FvarDaegipath:string;
FvarScreenKind:string;
FvarScreenwidth:string;
FvarScreenheight:string;
FvarMonitorKind:string;
FvarAdvText:string;
FvarAdvFont:string;
FvarAdvSize:string;
FvarAdvSpeed:string;
FvarAdvStep:string;
FvarAdvFontColor:string;
FvarAdvBackColor:string;
FvarDpKind:string;
FvarLoadFileName: string;
public
constructor Create();
destructor Destroy();
property varDaegipath:string read FvarDaegipath;
property varScreenKind:string read FvarScreenKind;
property varScreenwidth:string read FvarScreenwidth;
property varScreenheight:string read FvarScreenheight;
property varMonitorKind:string read FvarMonitorKind;
property varAdvText:string read FvarAdvText;
property varAdvFont:string read FvarAdvFont;
property varAdvSize:string read FvarAdvSize;
property varAdvSpeed:string read FvarAdvSpeed;
property varAdvStep:string read FvarAdvStep;
property varAdvFontColor:string read FvarAdvFontColor;
property varAdvBackColor:string read FvarAdvBackColor;
property varDpKind:string read FvarDpKind;
property varLoadFileName: string read FvarLoadFileName;
//DB 정보=======================================
property DbCon: Boolean read FDbCon write FDbCon;
property RunDir: string read configFile;
property varServerPort: string read FvarServerPort;
property varServerIP: string read FvarServerIP;
property varDbIp: string read FvarDbIP;
property varDbname: string read FvarDbname;
property varDbuser: string read FvarDbuser;
property varDbpass: string read FvarDbpass;
property varDbprotocol: string read FvarDbprotocol;
//Login 정보=======================================
property varLoginId: string read FvarLoginId;
property varLoginPass: string read FvarLoginPass;
property varAutoLogin: string read FvarAutoLogin;
property varWEb: string read Fvarweb;
property VarSMSLogin: string read FSMSLogin;
property VarScheduleDate: string read FvarScheduleDate;
property VarScheduleOpen: string read FvarScheduleOpen;
//병원 정보=======================================
property varsaupname: string read Fvarsaupname;
// 0101 회사명
property varDaepyo: string read FvarDaepyo;
// 0102 대표자명
property varJumin: string read FvarJumin;
// 0103 주민번호
property varsaupNo: string read FvarsaupNo;
// 0104 사업자번호
property varMyunhu: string read FvarMyunhu;
// 0105 면허번호
property varYoyang: string read FvarYoyang;
// 0106 요양기관기호
property varZip: string read FvarZip;
// 0107 우편번호
property varAdd1: string read FvarAdd1;
// 0108 기본주소
property varAdd2: string read FvarAdd2;
// 0109 확장주소
property varTel1: string read FvarTel1;
// 0110 전화번호1
property varTel2: string read FvarTel2;
// 0111 전화번호2
property varFax1: string read FvarFax1;
// 0112 팩스번호1
property varFax2: string read FvarFax2;
// 0113 팩스번호2
property varEmail: string read FvarEmail;
// 0114 이메일
property varilsu: string read Fvarilsu;
// 0115 초재진산정일수
property varGubun: string read FvarGubun;
// 0116 병의원 구분
property varSimjibu: string read FvarSimjibu;
// 0117 심평원지부코드
property varDocNo: string read FvarDocNo;
// 0118 등록된 의사 수
property varChubang: string read FvarChubang;
// 0119 처방전 사용기간
property varPrintsu: string read FvarPrintsu;
// 0120 처방전인쇄-약국용, 환자보관용
property varBunup: string read FvarBunup;
// 0121 의약분업적용
property varDaeheng: string read FvarDaeheng;
// 0122 청구대행단체
property varRmode: string read FvarRmode;
// 0123 영수증발급모드
property varChungname: string read FvarChungname;
// 0124 보험청구 작성자명
property varChungJumin: string read FvarChungJumin;
// 0125 보험청구 작성자주민번호
property varJagyukID: string read FvarJagyukID;
// 0126 자격확인 아이디
property varJagyukpass: string read FvarJagyukpass;
// 0127 자격확인 패스워드
property varsmsId: string read FvarsmsId;
// 0128 SMS로그인 아이디
property varSmspass: string read FvarSmspass;
// 0129 SMS패스워드
property varChartRule: string read FvarChartRule;
// 0130 차트번호 규칙
property varChartNew: string read FvarChartNew;
// 0131 차트번호 새로시작번호
property varSangMode: string read FvarSangMode;
// 0132 상병모드(?) 구분
property varJinryoSave: string read FvarJinryoSave;
// 0133 Sunap테이블에 저장할지 말지
//약속환경 정보=======================================
property p_startTime: string read Fp_startTime;
property p_finishtime: string read Fp_finishtime;
property p_timeinterval: integer read Fp_timeinterval;
property p_rowinterval: integer read Fp_rowinterval;
property p_columncount: integer read Fp_columncount;
property p_SmsContent: string read Fp_SmsContent;
property p_BeforSms: integer read Fp_BeforSms;
property p_SmsBeforTime: string read Fp_SmsBeforTime;
//기타 정보============================================================
property varpicpath: string read Fvarpicpath;
property varImageKind : string read FvarImageKind;
property varImageDbSaveMode : string read FvarImageDbSaveMode;
property varImageDbPath : string read FvarImageDbPath;
property varImageDbPort : string read FvarImageDbPort;
property varImageDbIp : string read FvarImageDbIp;
property varpanoScale: string read FvarpanoScale ;
property varLoadChamgo : string read FvarLoadChamgo;
property varImageIp : string read FvarImageIp;
property varImageUse: string read FvarImageUse;
property varImageUser: string read FvarImageUser;
property varImagePass: string read FvarImagePass;
property varImageDB: string read FvarImageDB;
property varImageProtocol: string read FvarImageProtocol;
property varCidIp: string read FvarCidIp;
property varCidPort: string read FvarCidPort;
property varCidUse: string read FvarCidUse;
property DetailLoadInfo: string read FDetailLoadInfo;
property InputBohum: string read FInputBohum;
property BohumApplyDate: string read FBohumApplyDate;
property LoadSogepan: string read FLoadSogepan;
property LoadGajokPan: string read FLoadGajokPan;
property varLoadDur: string read FvarLoadDur;
procedure LoadGlobalData_ini;
procedure LoadGlobalData_db;
// procedure RestoreForm(const Frm: TForm; const sName: string = '');
// procedure SaveForm(const Frm: Tform; const sName: string = '');
end;
implementation
uses udm, uFunctions;
const
POSFMT = '%d,%d,%d,%d';
constructor TConfigValue.Create();
begin
inherited Create();
end;
destructor TConfigValue.Destroy();
begin
inherited Destroy();
end;
procedure TConfigValue.LoadGlobalData_ini;
var
forminit: Tinifile;
begin
//Load GlobalSet
//Db Password는 Open한다...
// configFile := GetConfigDir + 'db.ini';
configFile := extractFilePath(paramStr(0)) + 'db.ini';
FormInit := TIniFile.Create(runDir);
FvarServerPort := FormInit.ReadString('DATABASE', 'SERVERPORT', '9887');
FvarServerIP := FormInit.ReadString('DATABASE', 'SERVERIP', '127.0.0.1');
FvarDbIP := FormInit.ReadString('DATABASE', 'dbip', '127.0.0.1\MADANG');
FvarDbname := FormInit.ReadString('DATABASE', 'dbname', 'MADANG');
FvarDbuser := FormInit.ReadString('DATABASE', 'dbuser', 'SA');
FvarDbpass := FormInit.ReadString('DATABASE', 'dbpass', '2002');
FvarDbprotocol := FormInit.ReadString('DATABASE', 'dbprotocol', 'MSSQL');
FvarLoginId := FormInit.ReadString('LOGIN', 'ID', '1');
FvarLoginPass := FormInit.ReadString('LOGIN', 'PASS', '1');
FvarAutoLogin := FormInit.ReadString('LOGIN', 'IDSAVE', '1');
FvarWeb := FormInit.ReadString('LOGIN', 'WEB', '1');
FSMSLogin := FormInit.ReadString('LOGIN', 'SMS', '0');
FvarScheDuleDate := FormInit.ReadString('SCHEDULE', 'DATE', '2010-01-01');
FvarScheDuleOpen := FormInit.ReadString('SCHEDULE', 'VIEW', '0');
FvarSaupNo := FormInit.ReadString('BASEINFO', 'COMPCODE', '');
fVarSaupName := FormInit.ReadString('BASEINFO', 'COMPNAME', '');
fDetailLoadInfo := FormInit.ReadString('BASEINFO', 'DETAILLOAD', '');
fInputBohum := FormInit.ReadString('BASEINFO', 'INPUTBOHUM', '1');
fLoadGajokPan := FormInit.ReadString('ETC', 'GAJOKPAN', '1');
fLoadSogePan := FormInit.ReadString('ETC', 'SOGEPAN', '1');
//FvarLoadDur := FormInit.ReadString('ETC', 'LOADDUR', '');
FvarPicPath := FormInit.ReadString('BASEINFO', 'DICAPATH', '');
FvarCidUse := FormInit.ReadString('BASEINFO', 'CIDUSE', '');
FvarJagyukID := FormInit.ReadString('ETC', 'CERTPOSITION', '0');
FvarLoadChamgo := FormInit.ReadString('ETC', 'CHAMGOLOAD', '0');
FvarDaegipath:= FormInit.ReadString('DAEDI', 'Daegipath', '');
FvarScreenKind:= FormInit.ReadString('DAEDI', 'ScreenKind', '0');
FvarScreenwidth:= FormInit.ReadString('DAEDI', 'Screenwidth', '1024');
FvarScreenheight:= FormInit.ReadString('DAEDI', 'Screenheight', '768');
FvarMonitorKind:= FormInit.ReadString('DAEDI', 'MonitorKind', '1');
FvarAdvText:= FormInit.ReadString('DAEDI', 'AdvText', '이지케어는 치과병원의 필수 도구 입니다');
FvarAdvFont:= FormInit.ReadString('DAEDI', 'AdvFont', '굴림체');
FvarAdvSize:= FormInit.ReadString('DAEDI', 'AdvSize', '63');
FvarAdvSpeed:= FormInit.ReadString('DAEDI', 'AdvSpeed', '1');
FvarAdvStep:= FormInit.ReadString('DAEDI', 'AdvStep', '1');
FvarAdvFontColor:= FormInit.ReadString('DAEDI', 'AdvFontColor', 'clWhite');
FvarAdvBackColor:= FormInit.ReadString('DAEDI', 'AdvBackColor', 'clBlue');
FvarDpKind:= FormInit.ReadString('DAEDI', 'DpKind', '1');
FvarLoadFileName:= FormInit.ReadString('DAEDI', 'LoadFileName', 'image.lst');
FormInit.Free;
end;
procedure TConfigValue.LoadGlobalData_db;
{var
varProperty: array[0..30] of string = ('Fvarsaupname'
, 'FvarDaepyo'
, 'FvarJumin'
, 'FvarsaupNo'
, 'FvarMyunhu'
, 'FvarYoyang'
, 'FvarZip'
, 'FvarAdd1'
, 'FvarAdd2'
, 'FvarTel1'
, 'FvarTel2'
, 'FvarFax1'
, 'FvarFax2'
, 'FvarEmail'
, 'Fvarilsu'
, 'FvarGubun'
, 'FvarSimjibu'
, 'FvarDocNo'
, 'FvarChubang'
, 'FvarPrintsu'
, 'FvarBunup'
, 'FvarDaeheng'
, 'FvarRmode'
, 'FvarChungname'
, 'FvarChungJumin'
, 'FvarJagyukID'
, 'FvarJagyukpass'
, 'FvarsmsId'
, 'FvarSmspass'
, 'FvarChartRule'
, 'FvarChartNew');
}
begin
//DB에 접속 후 환경설정 정보를 가져오며,
//초기에 DB를 연결시켜놓는 역할을 한다.
//Load GlobalSet
with dm_f.Sqlwork do
begin
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0101'; //회사명
open;
FvarsaupName := FieldByName('val').AsString;
//fVarSaupName := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0102'; //대표자명
open;
FvarDaepyo := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0103'; //주민번호
open;
FvarJumin := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0104'; //사업자번호
open;
FvarsaupNo := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0105'; //면허번호
open;
FvarMyunhu := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0106'; //요양기관기호
open;
FvarYoyang := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0107'; //우편번호
open;
FvarZip := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0108'; //주소1
open;
FvarAdd1 := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0109'; //주소2
open;
FvarAdd2 := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0110'; //전화1
open;
FvarTel1 := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0111'; //전화2
open;
FvarTel2 := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0112'; //팩스1
open;
FvarFax1 := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0113'; //팩스2
open;
FvarFax2 := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0114'; //이메일
open;
FvarEmail := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0115'; //초재진 산정 일수
open;
Fvarilsu := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0116'; //병의원 구분
open;
FvarGubun := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0117'; //심평원 지부
open;
FvarSimjibu := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0118'; //의사수
open;
FvarDocNo := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0119'; //처방전 사용기간
open;
FvarChubang := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0120'; //처방전 인쇄/약국-환자용
open;
FvarPrintsu := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0121'; //의약분업예외
open;
FvarBunup := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0122'; //청구대행단체
open;
FvarDaeheng := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0123'; //영수증 발급 모드
open;
FvarRmode := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0124'; //청구자 성명
open;
FvarChungname := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0125'; //청구자 주민번호
open;
FvarChungJumin := FieldByName('val').AsString;
{Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0126'; //자격확인 아이디
open;
FvarJagyukID := FieldByName('val').AsString;
}
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0127'; //자격확인 패스워드
open;
FvarJagyukpass := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0128'; //SMS아이디
open;
FvarsmsId := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0129'; //SMS패스워드
open;
FvarSmspass := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0130'; //차트번호 규칙
open;
FvarChartRule := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0131'; //새로운 차트번호
open;
FvarChartNew := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0132'; //SangMode
open;
FvarSangMode := FieldByName('val').AsString;
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0133'; //Sunap table에 저장여부e
open;
FvarJinryoSave := FieldByName('val').AsString;
close;
sql.Clear;
sql.add('select * from ma_config');
sql.add('where code=:code');
paramByName('code').asString := '0201';
open;
if not isempty then
Fp_startTime := fieldByName('val').asString
else
Fp_startTime := '09:00';
close;
sql.Clear;
sql.add('select * from ma_config');
sql.add('where code=:code');
paramByName('code').asString := '0202';
open;
if not isempty then
Fp_finishtime := fieldByName('val').asString
else
Fp_finishtime := '19:00';
close;
sql.Clear;
sql.add('select * from ma_config');
sql.add('where code=:code');
paramByName('code').asString := '0203';
open;
if not isempty then
begin
if fieldByName('val').asString ='' then
Fp_timeinterval := 30
else
Fp_timeinterval := fieldByName('val').asInteger;
end
else
begin
Fp_timeinterval := 30;
end;
close;
sql.Clear;
sql.add('select * from ma_config');
sql.add('where code=:code');
paramByName('code').asString := '0204';
open;
if not isempty then
begin
if fieldByName('val').asString <>'' then
Fp_rowinterval := fieldByName('val').asInteger
else
Fp_rowinterval := 50;
end
else
Fp_rowinterval := 50;
close;
sql.Clear;
sql.add('select * from ma_config');
sql.add('where code=:code');
paramByName('code').asString := '0205';
open;
if not isempty then
begin
if fieldByName('val').asString <> '' then
Fp_columncount := fieldByName('val').asInteger
else
Fp_columncount := 5;
end
else
begin
Fp_columncount := 5;
end;
close;
sql.Clear;
sql.add('select * from ma_config');
sql.add('where code=:code');
paramByName('code').asString := '0206';
open;
if not isempty then
Fp_smsContent := fieldByName('val').asString
else
Fp_smsContent := '';
close;
sql.Clear;
sql.add('select * from ma_config');
sql.add('where code=:code');
paramByName('code').asString := '0207';
open;
if not isempty then
begin
if fieldByName('val').asString <> '' then
Fp_beforSms := fieldByName('val').asinteger
else
Fp_beForSMS := 1;
end
else
Fp_beForSMS := 1;
close;
sql.Clear;
sql.add('select * from ma_config');
sql.add('where code=:code');
paramByName('code').asString := '0208';
open;
if not isempty then
Fp_smsBeforTime := fieldByName('val').asString
else
Fp_smsBeforTime := '110000';
close;
sql.Clear;
sql.add('select * from ma_config');
sql.add('where code=:code');
paramByName('code').asString := '0132';
open;
if not isempty then
FBohumApplyDate := fieldByName('val').asString
else
FBohumApplyDate := '1900-01-01';
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0401'; //타 영상뷰어 사용
open;
if not isempty then
FvarImageUse := FieldByName('val').AsString
else
FvarImageUse:='0';
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0402'; //영상뷰어 종류
open;
if not isempty then
FvarImageKind := FieldByName('val').AsString
else
FvarImageKind :='0';
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0403'; //영상뷰어 IP Path
open;
if not isempty then
FvarImageIP := FieldByName('val').AsString
else
FvarImageIP :='127.0.0.1';
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0404'; //영상뷰어 DB Name
open;
if not isempty then
FvarImageDB := FieldByName('val').AsString
else
FvarImageDB :='madang';
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0405'; //영상뷰어 User
open;
if not isempty then
FvarImageUser := FieldByName('val').AsString
else
FvarImageUser :='sa';
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0406'; //영상뷰어 Pass
open;
if not isempty then
FvarImagePass := FieldByName('val').AsString
else
FvarImagePass :='2002';
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0407'; //영상뷰어 Protocol
open;
if not isempty then
FvarImageProtocol := FieldByName('val').AsString
else
FvarImageProtocol :='mssql';
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0408'; //영상뷰어 저장 방법
open;
if not isempty then
FvarImageDBSaveMode := FieldByName('val').AsString
else
FvarImageDBSaveMode :='0';
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0409'; //타영상 이미지DB경로 및 이름
open;
if not isempty then
FvarImageDBPath := FieldByName('val').AsString
else
FvarImageDBPath :='';
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0410'; //마당DB서버 IP
open;
if not isempty then
FvarImageDBIP := FieldByName('val').AsString
else
FvarImageDBIP :='127.0.0.1';
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0411'; //마당DB서버 PORT
open;
if not isempty then
FvarImageDBPORT := FieldByName('val').AsString
else
FvarImageDBPORT :='9001';
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0412'; //파노라마초기비율
open;
if not isempty then
FvarpanoScale := FieldByName('val').AsString
else
FvarpanoScale :='38';
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0501'; //CID IP
open;
if not isempty then
FvarCidIp := FieldByName('val').AsString
else
FvarCidIp :='127.0.0.1';
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0502'; //CID Port
open;
if not isempty then
FvarCidPort := FieldByName('val').AsString
else
FvarCidPort :='9000';
{ Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0301'; //환자의 참고사항을 사진에 불러오기
open;
if not isEmpty then
FvarLoadChamgo := FieldByName('val').AsString
else
FvarLoadChamgo :='0';
}
Close;
Sql.Clear;
Sql.Add('Select * from ma_config');
Sql.Add('Where Code=:Code');
ParamByName('CODE').AsString := '0302'; //DUr실행
open;
if not isEmpty then
FvarLoadDur := FieldByName('val').AsString
else
FvarLoadChamgo :='0';
// FvarLoadDur := FormInit.ReadString('ETC', 'LOADDUR', '');
end;
end;
{
procedure TConfigValue.SaveForm(const Frm: Tform; const sName: string = '');
var
R: TRect;
begin
configFile := GetConfigDir + 'db.ini';
ini := TIniFile.Create(ConfigFile);
try
with frm do
if sName = '' then // 저장할 키 값을 지정하지 않은 경우.
begin
case GetWinShowState(frm.Handle) of
SW_SHOWMAXIMIZED, SW_SHOWMINIMIZED:
begin
R := GetWinPos(frm.Handle);
ini.WriteString(PRGSECTION, Name,
Format(POSFMT, [R.Left, R.Top, R.Right,
R.Bottom]));
end;
else // 보통크기일 때는 현재 좌표 저장
ini.WriteString(PRGSECTION, Name, Format(POSFMT, [Left,
Top, Width, Height]));
end;
end
else
ini.WriteString(PRGSECTION, sName, Format(POSFMT, [Left,
Top, Width, Height]))
finally
ini.Free;
end;
end;
procedure TConfigValue.RestoreForm(const Frm: TForm; const sName: string = '');
var
s: TStringList;
pos: string;
begin
configFile := GetConfigDir + 'db.ini';
ini := TIniFile.Create(ConfigFile);
s := TStringList.Create;
try
if sName = '' then
pos := ini.ReadString(PRGSECTION, frm.name, '')
else
pos := ini.ReadString(PRGSECTION, sName, '');
if pos <> '' then
with frm do
begin
s.CommaText := pos;
SetBounds(StrToInt(s[0]), StrToInt(s[1]), StrToInt(s[2]),
StrToInt(s[3]));
end;
finally
ini.Free;
s.Free;
end;
end;
}
end.
|
{******************************************************************************}
{ }
{ Indy (Internet Direct) - Internet Protocols Simplified }
{ }
{ https://www.indyproject.org/ }
{ https://gitter.im/IndySockets/Indy }
{ }
{******************************************************************************}
{ }
{ This file is part of the Indy (Internet Direct) project, and is offered }
{ under the dual-licensing agreement described on the Indy website. }
{ (https://www.indyproject.org/license/) }
{ }
{ Copyright: }
{ (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. }
{ }
{******************************************************************************}
{ }
{ Originally written by: Fabian S. Biehn }
{ fbiehn@aagon.com (German & English) }
{ }
{ Contributers: }
{ Here could be your name }
{ }
{******************************************************************************}
// This File is auto generated!
// Any change to this file should be made in the
// corresponding unit in the folder "intermediate"!
// Generation date: 28.10.2020 15:24:13
unit IdOpenSSLHeaders_kdferr;
interface
// Headers for OpenSSL 1.1.1
// kdferr.h
{$i IdCompilerDefines.inc}
uses
Classes,
IdCTypes,
IdGlobal,
IdOpenSSLConsts;
const
(*
* KDF function codes.
*)
KDF_F_PKEY_HKDF_CTRL_STR = 103;
KDF_F_PKEY_HKDF_DERIVE = 102;
KDF_F_PKEY_HKDF_INIT = 108;
KDF_F_PKEY_SCRYPT_CTRL_STR = 104;
KDF_F_PKEY_SCRYPT_CTRL_UINT64 = 105;
KDF_F_PKEY_SCRYPT_DERIVE = 109;
KDF_F_PKEY_SCRYPT_INIT = 106;
KDF_F_PKEY_SCRYPT_SET_MEMBUF = 107;
KDF_F_PKEY_TLS1_PRF_CTRL_STR = 100;
KDF_F_PKEY_TLS1_PRF_DERIVE = 101;
KDF_F_PKEY_TLS1_PRF_INIT = 110;
KDF_F_TLS1_PRF_ALG = 111;
(*
* KDF reason codes.
*)
KDF_R_INVALID_DIGEST = 100;
KDF_R_MISSING_ITERATION_COUNT = 109;
KDF_R_MISSING_KEY = 104;
KDF_R_MISSING_MESSAGE_DIGEST = 105;
KDF_R_MISSING_PARAMETER = 101;
KDF_R_MISSING_PASS = 110;
KDF_R_MISSING_SALT = 111;
KDF_R_MISSING_SECRET = 107;
KDF_R_MISSING_SEED = 106;
KDF_R_UNKNOWN_PARAMETER_TYPE = 103;
KDF_R_VALUE_ERROR = 108;
KDF_R_VALUE_MISSING = 102;
procedure Load(const ADllHandle: TIdLibHandle; const AFailed: TStringList);
procedure UnLoad;
var
ERR_load_KDF_strings: function: TIdC_INT cdecl = nil;
implementation
procedure Load(const ADllHandle: TIdLibHandle; const AFailed: TStringList);
function LoadFunction(const AMethodName: string; const AFailed: TStringList): Pointer;
begin
Result := LoadLibFunction(ADllHandle, AMethodName);
if not Assigned(Result) then
AFailed.Add(AMethodName);
end;
begin
ERR_load_KDF_strings := LoadFunction('ERR_load_KDF_strings', AFailed);
end;
procedure UnLoad;
begin
ERR_load_KDF_strings := nil;
end;
end.
|
unit ServicoEmissorNFCe;
interface
uses
Parametros,
Venda,
Empresa,
ACBrNFeNotasFiscais,
ACBrDANFCeFortesFr,
ContNrs, DateTimeUtilitario, Classes, AcbrNfe, pcnConversao, pcnNFe,
pcnRetInutNFe, pcnRetConsSitNFe, pcnCCeNFe, ACBrNFeWebServices,
pcnEventoNFe, pcnConversaoNFe, pcnProcNFe, funcoes;
type
TServicoEmissorNFCe = class
private
FACBrNFe :TACBrNFe;
FACBrNFeDANFe :TACBrNFeDANFCeFortes;
FParametros :TParametros;
private
procedure GerarNFCe(Venda :TVenda);
procedure GerarIdentificacao(Configuracoes :TParametros;
Venda :TVenda;
NFCe :NotaFiscal);
procedure GerarEmitente(Empresa :TEmpresa;
NFCe :NotaFiscal);
procedure GerarDestinatario(Venda :TVenda; NFCe :NotaFiscal);
procedure GerarDadosProdutos(Venda :TVenda; NFCe :NotaFiscal);
procedure GerarValoresTotais(Venda :TVenda; NFCe :NotaFiscal);
procedure GerarTransportador(Venda :TVenda; NFCe :NotaFiscal);
procedure GerarPagamentos (Venda :TVenda; NFCe :NotaFiscal);
procedure Salva_retorno_envio(codigo_pedido, numero_lote :integer);
procedure Salva_retorno_cancelamento(Justificativa :String);
public
constructor Create(Configuracoes :TParametros);
destructor Destroy; override;
public
procedure Emitir(Venda :TVenda; NumeroLote :Integer);
procedure CancelarNFCe(XML: TStringStream; Justificativa :String);
end;
implementation
uses
SysUtils, DateUtils,
ParametrosNFCe,
endereco,
Item,
Produto, Movimento,
Token, EspecificacaoMovimentosPorCodigoPedido,
ParametrosDANFE, NcmIBPT, ItemVenda, Dialogs, Repositorio, FabricaRepositorio, NFCe, uModulo, StrUtils, Math, EspecificacaoFiltraNFCe,
Cliente, MaskUtils;
{ TServicoEmissorNFCe }
procedure TServicoEmissorNFCe.CancelarNFCe(XML: TStringStream; Justificativa :String);
var
DhEvento :TDateTime;
begin
if (Justificativa = '') then
Justificativa := 'CANCELAMENTO DE NF-E';
self.FACBrNFe.NotasFiscais.Clear;
self.FACBrNFe.NotasFiscais.LoadFromStream(XML);
self.FACBrNFe.EventoNFe.Evento.Clear;
with self.FACBrNFe.EventoNFe.Evento.Add do
begin
infEvento.chNFe := FACBrNFe.NotasFiscais.Items[0].NFe.procNFe.chNFe;
infEvento.CNPJ := FACBrNFe.NotasFiscais.Items[0].NFe.Emit.CNPJCPF;
infEvento.dhEvento := now;
infEvento.tpEvento := teCancelamento;
infEvento.detEvento.xJust := Justificativa;
infEvento.detEvento.nProt := FACBrNFe.NotasFiscais.Items[0].NFe.procNFe.nProt;
end;
if self.FACBrNFe.EnviarEvento(1) then
self.Salva_retorno_cancelamento( Justificativa );
end;
constructor TServicoEmissorNFCe.Create(Configuracoes: TParametros);
begin
FParametros := Configuracoes;
{ ACBrNFe (Configurações do WebService) }
FACBrNFe := TACBrNFe.Create(nil);
FACBrNFe.Configuracoes.WebServices.IntervaloTentativas := Configuracoes.NFCe.IntervaloTentativas;
FACBrNFe.Configuracoes.WebServices.Tentativas := Configuracoes.NFCe.Tentativas;
FACBrNFe.Configuracoes.WebServices.UF := Configuracoes.Empresa.estado;
FACbrNFe.Configuracoes.WebServices.Ambiente := TpcnTipoAmbiente( IfThen( copy(Configuracoes.NFCe.Ambiente,1,1) = 'P',0,1) );
FACBrNFe.Configuracoes.WebServices.Visualizar := false; // Mensagens
FACBrNFe.Configuracoes.Geral.FormaEmissao := TpcnTipoEmissao(Configuracoes.NFCe.FormaEmissao);
FACBrNFe.Configuracoes.Geral.ModeloDF := moNFCe;
FACBrNFe.Configuracoes.Geral.VersaoDF := TPcnVersaoDF(Configuracoes.NFCe.VersaoDF);
FACBrNFe.Configuracoes.Geral.IncluirQRCodeXMLNFCe := (FACbrNFe.Configuracoes.WebServices.Ambiente = taHomologacao);
try
FACBrNFe.Configuracoes.Geral.IdCSC := FParametros.NFCe.ID_TOKEN;
FACBrNFe.Configuracoes.Geral.CSC := FParametros.NFCe.TOKEN;
except
end;
FACBrNFe.Configuracoes.Geral.Salvar := false;
try
FAcbrNfe.Configuracoes.Certificados.NumeroSerie := FParametros.NFCe.Certificado;
FAcbrNfe.Configuracoes.Certificados.Senha := FParametros.NFCe.Senha;
except
end;
{ DANFE (Configurações da Impressão do DANFE)}
FACBrNFeDANFe := TACBrNFeDANFCeFortes.Create(nil);
FACBrNFeDANFe.TipoDANFE := tiNFCe;
FACBrNFeDANFe.ACBrNFe := self.FACBrNFe;
FACBrNFeDANFe.MostrarPreview := FParametros.NFCe.DANFE.VisualizarImpressao;
FACBrNFeDANFe.ViaConsumidor := FParametros.NFCe.DANFE.ViaConsumidor;
FACBrNFeDANFe.ImprimirItens := FParametros.NFCe.DANFE.ImprimirItens;
// FACBrNFeDANFe.ImprimirDANFE;
// FACBrNFeDANFe.ImprimirDANFEResumido();
FACBrNFeDANFe.ProdutosPorPagina := 30;
FACBrNFeDANFe.Sistema := 'Smart Chef';
{if not TStringUtilitario.EstaVazia(CaminhoLogo) then
FACBrNFeDANFE.Logo := CaminhoLogo;}
end;
destructor TServicoEmissorNFCe.Destroy;
begin
FreeAndNil(FACBrNFe);
FParametros := nil;
inherited;
end;
procedure TServicoEmissorNFCe.Emitir(Venda: TVenda; NumeroLote :Integer);
const
IMPRIMIR = true;
SINCRONO = true;
begin
try
GerarNFCe(Venda);
try
FACBrNFe.Enviar(NumeroLote, IMPRIMIR, SINCRONO);
Except
On E: Exception do begin
dm.GetValorGenerator('gen_lote_nfce','-1');
dm.GetValorGenerator('gen_nrnota_nfce','-1');
raise Exception.Create(e.Message);
end;
end;
Salva_retorno_envio(Venda.Codigo_pedido, NumeroLote);
Except
On E: Exception do begin
raise Exception.Create(e.Message);
end;
end;
end;
procedure TServicoEmissorNFCe.GerarDadosProdutos(Venda: TVenda;
NFCe: NotaFiscal);
var
nX :Integer;
total_itens, percent_correspondente :Real;
begin
//total_itens := ((Venda.Total + Venda.Desconto) - Venda.Tx_servico) - Venda.Couvert;
for nX := 0 to (Venda.Itens.Count-1) do begin
with NFCe.NFe.Det.Add do begin
{ Dados do Produto }
Prod.nItem := (nX+1);
Prod.cProd := IntToStr(Venda.Itens.Items[nX].Produto.codigo);
Prod.cEAN := '';//Venda.Itens.Items[nX].Produto.Codbar;
Prod.xProd := Venda.Itens.Items[nX].Produto.descricao;
Prod.NCM := Venda.Itens.Items[nX].Produto.NcmIBPT.ncm_ibpt;
Prod.EXTIPI := '';
Prod.CFOP := IfThen(Venda.Itens.Items[nX].Produto.tributacao = 'FF', '5405', '5102');
Prod.uCom := 'UN';//Venda.Itens.Items[nX].Produto.getUnidade;
Prod.qCom := Venda.Itens.Items[nX].Quantidade;
Prod.vUnCom := Venda.Itens.Items[nX].ValorUnitario;
Prod.vProd := Venda.Itens.Items[nX].Total;
Prod.cEANTrib := '';//Venda.Itens.Items[nX].Produto.Codbar;
Prod.uTrib := 'UN';//Venda.Itens.Items[nX].Produto.getUnidade;
Prod.qTrib := Venda.Itens.Items[nX].Quantidade;
Prod.vUnTrib := Venda.Itens.Items[nX].ValorUnitario;
Prod.vOutro := 0;
Prod.vFrete := 0;
Prod.vSeg := 0;
if Venda.Desconto > 0 then begin
percent_correspondente := (Venda.Itens.Items[nX].Total * 100) / Venda.Total;
Prod.vDesc := (percent_correspondente * Venda.Desconto)/100;
end
else
Prod.vDesc := 0;
{ Imposto }
with Imposto do begin
{ ICMS }
vTotTrib := Venda.Itens.Items[nX].ValorImpostos;
with ICMS do begin
with ICMS do begin
if Venda.Itens.Items[nX].Produto.tributacao = 'FF' then
CSOSN := csosn500
else
CSOSN := csosn102;
ICMS.orig := oeNacional;
ICMS.modBC := dbiValorOperacao;
ICMS.vBC := 0;//Venda.Itens[nX].CST00.Base;
ICMS.pICMS := 0;//Venda.Itens[nX].CST00.Aliquota;
ICMS.vICMS := 0;//Venda.Itens[nX].CST00.Valor;
ICMS.modBCST := dbisMargemValorAgregado;
ICMS.pMVAST := 0;
ICMS.pRedBCST:= 0;
ICMS.vBCST := 0;
ICMS.pICMSST := 0;
ICMS.vICMSST := 0;
ICMS.pRedBC := 0;
end;
end;
end; //with do imposto
end;
end;
end;
procedure TServicoEmissorNFCe.GerarDestinatario(Venda :TVenda; NFCe: NotaFiscal);
var endereco :TEndereco;
repositorio :TRepositorio;
begin
try
endereco := nil;
repositorio := nil;
NFCe.NFe.Dest.xNome := IfThen((Venda.Cpf_cliente = '')or(length(Venda.Cpf_cliente)<10), 'CONSUMIDOR', Venda.nome_cliente);
NFCe.NFe.Dest.CNPJCPF := IfThen( not (length(Venda.Cpf_cliente) in [11,14]), '', Venda.Cpf_cliente);
NFCe.NFe.Dest.indIEDest := inNaoContribuinte;
if assigned(Venda.Cliente) and
((assigned(Venda.Cliente.Enderecos) and (Venda.Cliente.Enderecos.count > 0)) or (venda.Codigo_endereco > 0)) then begin
if venda.Codigo_endereco > 0 then begin
repositorio := TFabricaRepositorio.GetRepositorio(TEndereco.ClassName);
endereco := TEndereco( repositorio.Get( venda.Codigo_endereco ) );
end
else
endereco := TEndereco(Venda.Cliente.Enderecos.Items[0]);
NFCe.NFe.Dest.EnderDest.xLgr := endereco.logradouro;
NFCe.NFe.Dest.EnderDest.nro := endereco.numero;
NFCe.NFe.Dest.EnderDest.xCpl := endereco.referencia;
NFCe.NFe.Dest.EnderDest.xBairro := endereco.bairro;
NFCe.NFe.Dest.EnderDest.cMun := endereco.codigo_cidade;
NFCe.NFe.Dest.EnderDest.xMun := endereco.cidade;
NFCe.NFe.Dest.EnderDest.UF := endereco.uf;
NFCe.NFe.Dest.EnderDest.CEP := StrToIntDef(endereco.cep,0);
NFCe.NFe.Dest.EnderDest.cPais := 1058;
NFCe.NFe.Dest.EnderDest.xPais := 'Brasil';
NFCe.NFe.Dest.EnderDest.fone := endereco.fone;
end;
finally
FreeAndNil(repositorio);
FreeAndNil(endereco);
end;
end;
procedure TServicoEmissorNFCe.GerarEmitente(Empresa: TEmpresa; NFCe: NotaFiscal);
begin
NFCe.NFe.Emit.CNPJCPF := Empresa.Cnpj;
NFCe.NFe.Emit.IE := Empresa.IE;
NFCe.NFe.Emit.xNome := Empresa.Razao_social;
NFCe.NFe.Emit.xFant := Empresa.Nome_Fantasia;
{ Endereco }
NFCe.NFe.Emit.EnderEmit.fone := Empresa.Telefone;
NFCe.NFe.Emit.EnderEmit.CEP := Empresa.Cep;
NFCe.NFe.Emit.EnderEmit.xLgr := Empresa.rua;
NFCe.NFe.Emit.EnderEmit.nro := Empresa.numero;
NFCe.NFe.Emit.EnderEmit.xCpl := Empresa.complemento;
NFCe.NFe.Emit.EnderEmit.xBairro := Empresa.bairro;
NFCe.NFe.Emit.EnderEmit.cMun := Empresa.cod_municipio;
NFCe.NFe.Emit.EnderEmit.xMun := Empresa.cidade;
NFCe.NFe.Emit.EnderEmit.UF := Empresa.estado;
NFCe.NFe.Emit.EnderEmit.cPais := 1058;
NFCe.NFe.Emit.EnderEmit.xPais := 'BRASIL';
NFCe.NFe.Emit.CRT := TpcnCRT(Empresa.Regime); // VERIFICAR SE PEGA CORRETO, SE VERIFICAR PAGAR TODOS ESSE COMENTARIOS crtRegimeNormal;// (1-crtSimplesNacional, 2-crtSimplesExcessoReceita, 3-crtRegimeNormal)
end;
procedure TServicoEmissorNFCe.GerarIdentificacao(
Configuracoes: TParametros; Venda: TVenda; NFCe: NotaFiscal);
begin
NFCe.NFe.Ide.cNF := Venda.NumeroNFe;
NFCe.NFe.Ide.natOp := 'VENDA';
NFCe.NFe.Ide.indPag := ipVista;
NFCe.NFe.Ide.modelo := 65;
NFCe.NFe.Ide.serie := 1;
NFCe.NFe.Ide.nNF := Venda.NumeroNFe;
NFCe.NFe.Ide.dEmi := Now;
NFCe.NFe.Ide.dSaiEnt := Now;
NFCe.NFe.Ide.hSaiEnt := Now;
NFCe.NFe.Ide.tpNF := tnSaida;
NFCe.NFe.Ide.tpEmis := teNormal; //TpcnTipoEmissao(Configuracoes.NFCe.FormaEmissao); SEGUNDA_CONFIGURACAO
NFCe.NFe.Ide.tpAmb := TpcnTipoAmbiente( IfThen( copy(Configuracoes.NFCe.Ambiente,1,1) = 'P',0,1) );
NFCe.NFe.Ide.cUF := UF_TO_CODUF(Configuracoes.Empresa.estado);
NFCe.NFe.Ide.cMunFG := Configuracoes.Empresa.cod_municipio;
NFCe.NFe.Ide.finNFe := fnNormal;
NFCe.NFe.Ide.tpImp := tiNFCe;
NFCe.NFe.Ide.indFinal := cfConsumidorFinal;
NFCe.NFe.Ide.indPres := pcPresencial;
end;
procedure TServicoEmissorNFCe.GerarNFCe(Venda: TVenda);
var
NFCe :ACBrNFeNotasFiscais.NotaFiscal;
begin
FACBrNFe.NotasFiscais.Clear;
NFCe := FACBrNFe.NotasFiscais.Add;
GerarIdentificacao (FParametros, Venda, NFCe);
GerarEmitente (FParametros.Empresa, NFCe);
GerarDestinatario (Venda, NFCe);
GerarDadosProdutos (Venda, NFCe);
GerarValoresTotais (Venda, NFCe);
GerarTransportador (Venda, NFCe);
GerarPagamentos (Venda, NFCe);
end;
procedure TServicoEmissorNFCe.GerarPagamentos(Venda: TVenda; NFCe: NotaFiscal);
var Especificacao :TEspecificacaoMovimentosPorCodigoPedido;
repositorio :TREpositorio;
Movimentos :TObjectList;
i :integer;
descontou_tx :boolean;
descontou_servicos :Boolean;
begin
Especificacao := nil;
repositorio := nil;
Movimentos := nil;
descontou_tx := false;
descontou_servicos := false;
try
Especificacao := TEspecificacaoMovimentosPorCodigoPedido.Create(Venda.Codigo_pedido);
repositorio := TFabricaRepositorio.GetRepositorio(TMovimento.ClassName);
Movimentos := repositorio.GetListaPorEspecificacao( Especificacao, 'codigo_pedido = '+inttostr(Venda.Codigo_pedido));
if (Venda.Couvert + Venda.Tx_servico + Venda.Taxa_entrega) <= 0 then
descontou_tx := true;
for i := 0 to Movimentos.Count -1 do begin
with NFCe.NFe.pag.Add do begin
case TMovimento(Movimentos[i]).tipo_moeda of
1 : tPag := fpDinheiro;
2 : tPag := fpCheque;
3 : tPag := fpCartaoCredito;
4 : tPag := fpCartaoDebito;
end;
//if tPag in [fpCartaoCredito, fpCartaoDebito] then
tpIntegra := tiNaoInformado;
vPag := TMovimento(Movimentos[i]).valor_pago;
if not descontou_tx and (vPag >= (Venda.Couvert + Venda.Tx_servico + Venda.Taxa_entrega)) then begin
vPag := vPag - (Venda.Couvert + Venda.Tx_servico + Venda.Taxa_entrega);
descontou_tx := true;
end;
if not descontou_servicos and (vPag > Venda.Total_em_servicos) then begin
vPag := vPag - Venda.Total_em_servicos;
descontou_servicos := true;
end;
end;
end;
Finally
FreeAndNil(Especificacao);
FreeAndNil(repositorio);
FreeAndNil(Movimentos);
end;
end;
procedure TServicoEmissorNFCe.GerarTransportador(Venda: TVenda;
NFCe: NotaFiscal);
begin
// NFC-e não pode ter frete
NFCe.NFe.Transp.modFrete := mfSemFrete;
end;
procedure TServicoEmissorNFCe.GerarValoresTotais(Venda: TVenda;
NFCe: NotaFiscal);
begin
NFCe.NFe.Total.ICMSTot.vBC := 0;
NFCe.NFe.Total.ICMSTot.vICMS := Venda.Icms;
NFCe.NFe.Total.ICMSTot.vBCST := Venda.BaseSt;
NFCe.NFe.Total.ICMSTot.vST := Venda.St;
NFCe.NFe.Total.ICMSTot.vProd := Venda.TotalBruto;
NFCe.NFe.Total.ICMSTot.vFrete := Venda.Frete;
NFCe.NFe.Total.ICMSTot.vSeg := Venda.Seguro;
NFCe.NFe.Total.ICMSTot.vDesc := Venda.Desconto;
NFCe.NFe.Total.ICMSTot.vII := 0; //Venda.ImpostoImportacao;
NFCe.NFe.Total.ICMSTot.vIPI := 0; //Venda.Ipi;
NFCe.NFe.Total.ICMSTot.vPIS := Venda.Pis;
NFCe.NFe.Total.ICMSTot.vCOFINS := Venda.Cofins;
NFCe.NFe.Total.ICMSTot.vOutro := 0; //Venda.OutrasDespesas;
NFCe.NFe.Total.ICMSTot.vNF := Venda.Total - Venda.Desconto;
NFCe.NFe.Total.ICMSTot.vTotTrib := Venda.TotalTributos;
end;
procedure TServicoEmissorNFCe.Salva_retorno_cancelamento(Justificativa :String);
var StringStream :TStringStream;
repositorio :TRepositorio;
Especificacao :TEspecificacaoFiltraNFCe;
NFCe :TNFCe;
begin
NFCe := nil;
Especificacao := nil;
repositorio := nil;
try
try
repositorio := TFabricaRepositorio.GetRepositorio(TNFCe.ClassName);
Especificacao := TEspecificacaoFiltraNFCe.Create(Date, Date, FACBrNFe.NotasFiscais.Items[0].NFe.Ide.nNF);
NFCe := TNFCe( repositorio.GetPorEspecificacao( Especificacao ) );
StringStream := TStringStream.Create( UTF8Encode(self.FACBrNFe.WebServices.EnvEvento.RetWS) );
NFCe.XML.LoadFromStream(StringStream);
if self.FACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.cStat <> 135 then
raise Exception.Create('Falha ao enviar.'+#13#10+self.FACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.xMotivo);
NFCe.status := IntToStr( self.FACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.cStat );
NFCe.Motivo := self.FACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.xMotivo;//'Cancelamento da NFC-e homologado';
NFCe.protocolo := self.FACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.nProt;
NFCe.dh_recebimento := self.FACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.dhRegEvento;
NFCe.justificativa := Justificativa;
repositorio.Salvar( NFCe );
Except
On E: Exception do begin
raise Exception.Create(e.Message);
end;
end;
Finally
freeAndNil(repositorio);
freeAndNil(Especificacao);
freeAndNil(NFCe);
end;
end;
procedure TServicoEmissorNFCe.Salva_retorno_envio(codigo_pedido, numero_lote: integer);
var NFCe :TNFCe;
repositorio :TRepositorio;
StringStream: TStringStream;
begin
NFCe := nil;
repositorio := nil;
try
repositorio := TFabricaRepositorio.GetRepositorio(TNFCE.ClassName);
NFCe := TNFCE.Create;
NFCe.nr_nota := FACBrNFe.NotasFiscais.Items[0].NFe.Ide.nNF;
NFCe.codigo_pedido := codigo_pedido;
NFCe.serie := IntToStr(FACBrNFe.NotasFiscais.Items[0].NFe.Ide.serie);
NFCe.chave := FACBrNFe.NotasFiscais.Items[0].NFe.procNFe.chNFe;
NFCe.protocolo := FACBrNFe.NotasFiscais.Items[0].NFe.procNFe.nProt;
NFCe.dh_recebimento := FACBrNFe.NotasFiscais.Items[0].NFe.procNFe.dhRecbto;
NFCe.status := intToStr( FACBrNFe.NotasFiscais.Items[0].NFe.procNFe.cStat );
NFCe.motivo := FACBrNFe.NotasFiscais.Items[0].NFe.procNFe.xMotivo;
StringStream := TStringStream.Create( FACBrNFe.NotasFiscais.Items[0].XML );
NFCe.XML.LoadFromStream(StringStream);
repositorio.Salvar( NFCe );
Except
On E: Exception do begin
raise Exception.Create(e.Message);
end;
end;
end;
end.
|
unit Globals;
interface
uses Registry, Forms, FormMinder, Editor;
procedure InitialiseGlobals;
procedure ReadSettings( Editor : TveEditor );
procedure SaveSettings( Editor : TveEditor );
function GetRegIniFile : TRegIniFile;
function GetFormMinder : TFormMinder;
//const HKEY_CURRENT_USER_KEY = 'Software\VeeCAD\1.0';
const HKEY_CURRENT_USER_KEY = 'Software\RKL\VeeCAD\2';
{
procedure ReadCustomOutlineEditorSettings( Editor : TveCustomOutlineEditor );
procedure SaveCustomOutlineEditorSettings( Editor : TveCustomOutlineEditor );
var
CustomEditorCellGrey : TColor;
}
implementation
uses SysUtils, Cursors, Graphics, Painter, Windows;
{
function GetIniFileName : string;
var
Extension : string;
begin
result := ParamStr( 0 );
Extension := ExtractFileExt( result );
Delete( result, length(result) - length(Extension) +2, 255 );
result := result + 'ini';
end;
}
function GetRegIniFile : TRegIniFile;
begin
result := TRegIniFile.Create( HKEY_CURRENT_USER_KEY );
end;
var Minder : TFormMinder;
function GetFormMinder : TFormMinder;
begin
result := Minder;
end;
procedure InitialiseGlobals;
begin
end;
procedure ReadSettings( Editor : TveEditor );
var
RegIniFile : TRegIniFile;
LeadStyle : string;
begin
CursorMinder.HKEY_CURRENT_USER_KEY := HKEY_CURRENT_USER_KEY;
CursorMinder.LoadSettings;
RegIniFile := GetRegIniFile;
try
Editor.ComponentLineWidth :=
RegIniFile.ReadInteger( 'General', 'ComponentLineWidth',
// two pixels wide default line width
2 );
Editor.PixelsPerCell :=
RegIniFile.ReadInteger( 'General', 'PixelsPerCell',
// default 13 pixels per cell at 96 dpi or equivalent at other dpi.
(Screen.PixelsPerInch * 13) div 96 );
// default is colors for "Lime" Color Scheme with Red selection.
Editor.BodyColor :=
RegIniFile.ReadInteger( 'Color', 'Body', $001F99 );
Editor.PinColor :=
RegIniFile.ReadInteger( 'Color', 'Pin', $21B300 );
Editor.StripColor :=
RegIniFile.ReadInteger( 'Color', 'Strip', $9FD7FF );
Editor.BoardColor :=
RegIniFile.ReadInteger( 'Color', 'Board', $FFFFFF );
Editor.SelectionColor :=
RegIniFile.ReadInteger( 'Color', 'Selection', $0000FF );
Editor.NodeColors[0] :=
RegIniFile.ReadInteger( 'Color', 'Net1', $C9C9C9 );
Editor.NodeColors[1] :=
RegIniFile.ReadInteger( 'Color', 'Net2', $CAC829 );
Editor.NodeColors[2] :=
RegIniFile.ReadInteger( 'Color', 'Net3', $0091FF );
Editor.NodeColors[3] :=
RegIniFile.ReadInteger( 'Color', 'Net4', $56D768 );
Editor.NodeColors[4] :=
RegIniFile.ReadInteger( 'Color', 'Net5', $FF5978 );
Editor.NodeColors[5] :=
RegIniFile.ReadInteger( 'Color', 'Net6', $23E5E2 );
Editor.ConnectionErrorsVisible :=
RegIniFile.ReadBool( 'Overlay', 'ConnectionErrors', False );
Editor.NetTraceVisible :=
RegIniFile.ReadBool( 'Overlay', 'NetTrace', False );
LeadStyle := RegIniFile.ReadString( 'General', 'LeadStyle', '' );
if LeadStyle = 'Line' then begin
Editor.LeadStyle := lsLine;
end
else begin // LeadStyle = 'Hollow' , also default case
Editor.LeadStyle := lsHollow;
end;
// hot keys
Editor.SelectModeShortCut := RegIniFile.ReadInteger( 'Keys', 'Select', VK_ESCAPE );
Editor.BreakModeShortCut := RegIniFile.ReadInteger( 'Keys', 'Break', VK_F2 );
Editor.LinkModeShortCut := RegIniFile.ReadInteger( 'Keys', 'Link', VK_F3 );
Editor.WireModeShortCut := RegIniFile.ReadInteger( 'Keys', 'Wire', VK_F4 );
Editor.TextModeShortCut := RegIniFile.ReadInteger( 'Keys', 'Text', VK_F5 );
Editor.RedrawShortCut := RegIniFile.ReadInteger( 'Keys', 'Redraw', VK_F6 );
finally
RegIniFile.Free;
end;
end;
procedure SaveSettings( Editor : TveEditor );
var
RegIniFile : TRegIniFile;
const
LeadStyle2Str : array[TLeadStyle] of string = ( 'Hollow', 'Line' );
begin
RegIniFile := GetRegIniFile;
try
RegIniFile.WriteInteger( 'General', 'ComponentLineWidth',
Editor.ComponentLineWidth );
RegIniFile.WriteInteger( 'General', 'PixelsPerCell', Editor.PixelsPerCell );
RegIniFile.WriteString( 'Color', 'Body', Format('$%6.6X', [Editor.BodyColor]) );
RegIniFile.WriteString( 'Color', 'Pin', Format('$%6.6X', [Editor.PinColor]) );
RegIniFile.WriteString( 'Color', 'Strip', Format('$%6.6X', [Editor.StripColor]) );
RegIniFile.WriteString( 'Color', 'Board', Format('$%6.6X', [Editor.BoardColor]) );
RegIniFile.WriteString( 'Color', 'Selection', Format('$%6.6X', [Editor.SelectionColor]) );
RegIniFile.WriteString( 'Color', 'Net1', Format('$%6.6X', [Editor.NodeColors[0]] ));
RegIniFile.WriteString( 'Color', 'Net2', Format('$%6.6X', [Editor.NodeColors[1]] ));
RegIniFile.WriteString( 'Color', 'Net3', Format('$%6.6X', [Editor.NodeColors[2]] ));
RegIniFile.WriteString( 'Color', 'Net4', Format('$%6.6X', [Editor.NodeColors[3]] ));
RegIniFile.WriteString( 'Color', 'Net5', Format('$%6.6X', [Editor.NodeColors[4]] ));
RegIniFile.WriteString( 'Color', 'Net6', Format('$%6.6X', [Editor.NodeColors[5]] ));
RegIniFile.WriteBool( 'Overlay', 'ConnectionErrors', Editor.ConnectionErrorsVisible );
RegIniFile.WriteBool( 'Overlay', 'NetTrace', Editor.NetTraceVisible );
RegIniFile.WriteString( 'General', 'LeadStyle', LeadStyle2Str[Editor.LeadStyle] );
finally
RegIniFile.Free;
end;
end;
initialization
Minder := TFormMinder.Create( HKEY_CURRENT_USER_KEY );
finalization
Minder.Free;
end.
|
unit IdTestMD5Hash;
interface
uses
IdTest;
type
TIdTestMD5Hash = class(TIdTest)
published
procedure TestRFC;
end;
implementation
uses IdHashMessageDigest, IdObjs, IdSys;
{ TIdTestMD5Header }
//tests specified by http://www.faqs.org/rfcs/rfc1321.html
procedure TIdTestMD5Hash.TestRFC;
var LH : TIdHashMessageDigest5;
LStrm : TIdStream;
s : String;
begin
LH := TIdHashMessageDigest5.Create;
try
LStrm := TIdMemoryStream.Create;
try
s := TIdHashMessageDigest5.AsHex(LH.HashValue(LStrm));
Assert(Sys.LowerCase(s)='d41d8cd98f00b204e9800998ecf8427e','test "" Failed');
finally
Sys.FreeAndNil(LStrm);
end;
finally
Sys.FreeAndNil(LH);
end;
LH := TIdHashMessageDigest5.Create;
try
LStrm := TIdStringStream.Create('a');
try
LStrm.Position := 0;
s := TIdHashMessageDigest5.AsHex(LH.HashValue(LStrm));
Assert(Sys.LowerCase(s)='0cc175b9c0f1b6a831c399e269772661','test "a" Failed');
finally
Sys.FreeAndNil(LStrm);
end;
finally
Sys.FreeAndNil(LH);
end;
LH := TIdHashMessageDigest5.Create;
try
LStrm := TIdStringStream.Create('abc');
try
LStrm.Position := 0;
s := TIdHashMessageDigest5.AsHex(LH.HashValue(LStrm));
Assert(Sys.LowerCase(s)='900150983cd24fb0d6963f7d28e17f72','test "abc" Failed');
finally
Sys.FreeAndNil(LStrm);
end;
finally
Sys.FreeAndNil(LH);
end;
LH := TIdHashMessageDigest5.Create;
try
LStrm := TIdStringStream.Create('message digest');
try
LStrm.Position := 0;
s := TIdHashMessageDigest5.AsHex(LH.HashValue(LStrm));
Assert(Sys.LowerCase(s)='f96b697d7cb7938d525a2f31aaf161d0','test "abc" Failed');
finally
Sys.FreeAndNil(LStrm);
end;
finally
Sys.FreeAndNil(LH);
end;
LH := TIdHashMessageDigest5.Create;
try
LStrm := TIdStringStream.Create('abcdefghijklmnopqrstuvwxyz');
try
LStrm.Position := 0;
s := TIdHashMessageDigest5.AsHex(LH.HashValue(LStrm));
Assert(Sys.LowerCase(s)='c3fcd3d76192e4007dfb496cca67e13b','test "abcdefghijklmnopqrstuvwxyz" Failed');
finally
Sys.FreeAndNil(LStrm);
end;
finally
Sys.FreeAndNil(LH);
end;
LH := TIdHashMessageDigest5.Create;
try
LStrm := TIdStringStream.Create('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789');
try
LStrm.Position := 0;
s := TIdHashMessageDigest5.AsHex(LH.HashValue(LStrm));
Assert(Sys.LowerCase(s)='d174ab98d277d9f5a5611c2c9f419d9f','test "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" Failed');
finally
Sys.FreeAndNil(LStrm);
end;
finally
Sys.FreeAndNil(LH);
end;
LH := TIdHashMessageDigest5.Create;
try
LStrm := TIdStringStream.Create('12345678901234567890123456789012345678901234567890123456789012345678901234567890');
try
LStrm.Position := 0;
s := TIdHashMessageDigest5.AsHex(LH.HashValue(LStrm));
Assert(Sys.LowerCase(s)='57edf4a22be3c955ac49da2e2107b67a','test "12345678901234567890123456789012345678901234567890123456789012345678901234567890" Failed');
finally
Sys.FreeAndNil(LStrm);
end;
finally
Sys.FreeAndNil(LH);
end;
end;
initialization
TIdTest.RegisterTest(TIdTestMD5Hash);
end.
|
unit main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, AbilityManager, Menus, Db, DBTables, DBCtrls, Grids,
DBGrids, ComWriUtils;
type
TForm1 = class(TForm)
AbilityProvider1: TAbilityProvider;
AbilityProvider2: TAbilityProvider;
MainMenu1: TMainMenu;
Read1: TMenuItem;
Write1: TMenuItem;
btnRead: TBitBtn;
Edit1: TEdit;
CheckBox1: TCheckBox;
btnWrite: TBitBtn;
dapUser: TDBAuthorityProvider;
Query1: TQuery;
Table1: TTable;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
DBText1: TDBText;
Label1: TLabel;
Label2: TLabel;
amRead: TSimpleAbilityManager;
amWrite: TGroupAbilityManager;
DBText2: TDBText;
cbActive: TCheckBox;
Edit2: TEdit;
Label3: TLabel;
BitBtn1: TBitBtn;
AbilityProvider3: TAbilityProvider;
SimpleAbilityManager1: TSimpleAbilityManager;
procedure DataSource1DataChange(Sender: TObject; Field: TField);
procedure amReadEnableChanged(Sender: TObject);
procedure dapUserAuthorityChanged(Sender: TObject);
procedure cbActiveClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Edit2Change(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.DataSource1DataChange(Sender: TObject; Field: TField);
begin
if dapUser<>nil
then dapUser.UserID := table1.fields[0].asString;
end;
procedure TForm1.amReadEnableChanged(Sender: TObject);
begin
if edit1=nil then exit;
if amRead.enabled
then Edit1.passwordchar:=#0
else Edit1.passwordchar:='*';
end;
procedure TForm1.dapUserAuthorityChanged(Sender: TObject);
begin
cbActive.checked := dapUser.active;
end;
procedure TForm1.cbActiveClick(Sender: TObject);
begin
dapUser.active := cbActive.checked;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
cbActive.checked := dapUser.active;
end;
procedure TForm1.Edit2Change(Sender: TObject);
begin
dapUser.DefaultAuthorityString := Edit2.text;
end;
end.
|
ALGORITHME: JeudeNim_Algo_2Joueurs
//But: Créer le Jeu de Nim pour qu'il soit jouable par 2 personnes.
//Principe:
//Entrée: Le nombre d'alumettes retirées.
//Sortie: La quantitée d'allumettes restante.
VAR
TotalAllumettes, AllumettesRetirees : entier;
DEBUT
TotalAllumettes <- 21;
AllumettesRetirees <- 0;
TANTQUE TotalAllumettes > 1 FAIRE
ECRIRE "Retirez un nombre d'allumettes entre 1 et 3.";
LIRE AllumettesRetirees;
SI AllumettesRetirees > 0 ET AllumettesRetirees < 4 ALORS;
TotalAllumettes <- TotalAllumettes - AllumettesRetirees;
ECRIRE "Il reste ", TotalAllumettes, " Allumettes, joueur suivant.";
SINON
ECRIRE "Le nombre doit etre compris entre 1 et 3."
FINSI
FINTANTQUE
ECRIRE "Vous avez perdu !"
FIN.
===================================================================================
ALGORITHME JeudeNim_Algo_Ordi
//But: Créer le jeu de Nim avec un joueur et un ordinateur.
//Principe:
//Entrée: Le nombre d'alumettes retirées.
//Sortie: La quantitée d'allumettes restante.
CONST
TotalAllumettes <- 21 : entier;
Fin <- 1 : entier;
AlluMax <- 3 : entier;
AlluMin <- 1 : entier;
VAR
AllumettesRestantes, RetraitAllumettes : entier;
DEBUT
AllumettesRestantes <- TotalAllumettes;
RetraitAllumettes <- 0;
FIN. |
unit TextFileStream;
interface
uses Classes;
type
TTextFileStream = class(TFileStream)
public
function Eof: Boolean;
function ReadLn: string;
procedure WriteString(const s: string);
procedure WriteLn(const s: string); overload;
procedure WriteLn; overload;
end;
const
LineEnd = #13#10;
implementation
function TTextFileStream.Eof: Boolean;
begin
result := (Position >= Size);
end;
function TTextFileStream.ReadLn: string;
const
BlkSize = 128;
var
c: char;
i: Integer;
begin
SetLength(Result, BlkSize);
i := 0;
while not Eof do begin
Read(c, SizeOf(c));
if c = #13 then begin
Read(c, SizeOf(c));
if c <> #10 then begin
Seek(SizeOf(c), soFromCurrent);
end;
break;
end;
if c = #10 then begin
break;
end;
Inc(i);
if i > BlkSize then
SetLength(Result, Length(Result) + BlkSize);
Result[i] := c;
end;
SetLength(Result, i);
end;
procedure TTextFileStream.WriteString(const s: string);
var
i: integer;
begin
for i := 1 to Length(s) do begin
Write(s[i], SizeOf(s[i]));
end;
end;
procedure TTextFileStream.WriteLn;
begin
Write(LineEnd, Length(LineEnd));
end;
procedure TTextFileStream.WriteLn(const s: string);
begin
WriteString(s);
WriteLn;
end;
end. |
unit DelphiUiLib.Reflection.Numeric;
{
This module provides facilities for representating numeric types
(such as enumerations and bit masks) as user-friendly text.
}
interface
uses
DelphiApi.Reflection, System.Rtti;
type
TNumericKind = (nkBool, nkDec, nkDecSigned, nkBytes, nkHex, nkEnum, nkBitwise);
TFlagReflection = record
Presents: Boolean;
Flag: TFlagName;
end;
TNumericReflection = record
TypeName: String;
SDKTypeName: String;
Kind: TNumericKind;
Value: UInt64;
Text: String;
IsKnown: Boolean; // for enumerations
KnownFlags: TArray<TFlagReflection>; // for bitwise
SubEnums: TArray<String>; // for bitwise
UnknownBits: UInt64; // for bitwise
end;
// Enumerate known flags of a type
function EnumerateFlagAttributes(AType: Pointer): TArray<TFlagName>;
// Internal use
procedure FillOrdinalReflection(
var Reflection: TNumericReflection;
[opt] const Attributes: TArray<TCustomAttribute>
);
// Represent a numeric value by RTTI type
function GetNumericReflectionRtti(
RttiType: TRttiType;
const Instance;
[opt] const InstanceAttributes: TArray<TCustomAttribute> = nil
): TNumericReflection;
// Represent a numeric value by TypeInfo
function GetNumericReflection(
AType: Pointer;
const Instance; InstanceAttributes: TArray<TCustomAttribute> = nil
): TNumericReflection;
type
TNumeric = class abstract
// Represent a numeric value via a generic metod
class function Represent<T>(
const Instance: T;
[opt] const InstanceAttributes: TArray<TCustomAttribute> = nil
): TNumericReflection; static;
end;
implementation
uses
System.TypInfo, System.SysUtils, DelphiUiLib.Reflection.Strings,
DelphiUiLib.Strings;
{$BOOLEVAL OFF}
{$IFOPT R+}{$DEFINE R+}{$ENDIF}
{$IFOPT Q+}{$DEFINE Q+}{$ENDIF}
function EnumerateFlagAttributes;
var
RttiType: TRttiType;
a: TCustomAttribute;
Count: Integer;
begin
RttiType := TRttiContext.Create.GetType(AType);
// Count flag-derived attributes
Count := 0;
for a in RttiType.GetAttributes do
if a is FlagNameAttribute then
Inc(Count);
SetLength(Result, Count);
// Collect flag names and values
Count := 0;
for a in RttiType.GetAttributes do
if a is FlagNameAttribute then
begin
Result[Count] := FlagNameAttribute(a).Flag;
Inc(Count);
end;
end;
function IsBooleanType(AType: Pointer): Boolean;
begin
Result := (AType = TypeInfo(Boolean)) or (AType = TypeInfo(ByteBool)) or
(AType = TypeInfo(WordBool)) or (AType = TypeInfo(LongBool));
end;
procedure FillBooleanReflection(
var Reflection: TNumericReflection;
[opt] const Attributes: TArray<TCustomAttribute>
);
var
a: TCustomAttribute;
BoolKind: TBooleanKind;
begin
BoolKind := bkTrueFalse;
// Find known attributes
for a in Attributes do
if a is BooleanKindAttribute then
begin
BoolKind := BooleanKindAttribute(a).Kind;
Break;
end;
Reflection.Kind := nkBool;
// Select corresponding representation
with Reflection do
case BoolKind of
bkEnabledDisabled: Text := EnabledDisabledToString(LongBool(Value));
bkAllowedDisallowed: Text := AllowedDisallowedToString(LongBool(Value));
bkYesNo: Text := YesNoToString(LongBool(Value));
else
Text := TrueFalseToString(LongBool(Value));
end;
end;
function GetEnumNameEx(
Enum: TRttiEnumerationType;
Value: Cardinal;
[opt] Naming: NamingStyleAttribute
): String;
begin
Result := GetEnumName(Enum.Handle, Integer(Value));
// Prettify
if Assigned(Naming) then
case Naming.NamingStyle of
nsCamelCase:
Result := PrettifyCamelCase(Result, Naming.Prefix, Naming.Suffix);
nsSnakeCase:
Result := PrettifySnakeCase(Result, Naming.Prefix, Naming.Suffix);
end;
end;
procedure FillEnumReflection(
var Reflection: TNumericReflection;
RttiEnum: TRttiEnumerationType;
[opt] const Attributes: TArray<TCustomAttribute>
);
var
a: TCustomAttribute;
Naming: NamingStyleAttribute;
Range: RangeAttribute;
Mask: ValidMaskAttribute;
begin
Naming := nil;
Range := nil;
Mask := nil;
// Find known attributes
for a in Attributes do
if a is NamingStyleAttribute then
Naming := NamingStyleAttribute(a)
else if a is RangeAttribute then
Range := RangeAttribute(a)
else if a is ValidMaskAttribute then
Mask := ValidMaskAttribute(a);
with Reflection do
begin
// To emit RTTI, enumerations must start with 0.
// We use a custom attribute to further restrict the range.
Kind := nkEnum;
IsKnown := (not Assigned(Range) or Range.Check(Cardinal(Value))) and
(not Assigned(Mask) or Mask.Check(Cardinal(Value))) and
(Value <= NativeUInt(Cardinal(RttiEnum.MaxValue)));
if IsKnown then
Text := GetEnumNameEx(RttiEnum, Cardinal(Value), Naming)
else
Text := IntToStr(Value) + ' (out of bound)';
end;
end;
procedure FillBitwiseReflection(
var Reflection: TNumericReflection;
[opt] const Attributes: TArray<TCustomAttribute>
);
var
a: TCustomAttribute;
SubEnum: SubEnumAttribute;
IgnoreSubEnums, IgnoreUnnamed: Boolean;
HexDigits: Integer;
Strings: array of String;
i, Count: Integer;
begin
Reflection.Kind := nkBitwise;
Reflection.UnknownBits := Reflection.Value;
Reflection.KnownFlags := nil;
Reflection.SubEnums := nil;
IgnoreUnnamed := False;
IgnoreSubEnums := False;
HexDigits := 0;
for a in Attributes do
begin
// Process bit flag names
if a is FlagNameAttribute then
begin
SetLength(Reflection.KnownFlags, Length(Reflection.KnownFlags) + 1);
with Reflection.KnownFlags[High(Reflection.KnownFlags)] do
begin
Flag := FlagNameAttribute(a).Flag;
Presents := (Reflection.UnknownBits and Flag.Value) = Flag.Value;
if Presents then
Reflection.UnknownBits := Reflection.UnknownBits and not Flag.Value;
end;
end
else
// Process sub-enumeration that are embedded into bit masks
if a is SubEnumAttribute then
begin
SubEnum := SubEnumAttribute(a);
if (Reflection.Value and SubEnum.Mask) = SubEnum.Flag.Value then
begin
SetLength(Reflection.SubEnums, Length(Reflection.SubEnums) + 1);
Reflection.SubEnums[High(Reflection.SubEnums)] := SubEnum.Flag.Name;
// Exclude the whole sub-enum mask
Reflection.UnknownBits := Reflection.UnknownBits and not SubEnum.Mask;
end;
end
else if a is IgnoreUnnamedAttribute then
IgnoreUnnamed := True
else if a is IgnoreSubEnumsAttribute then
IgnoreSubEnums := True
else if a is HexAttribute then
HexDigits := HexAttribute(a).Digits;
end;
Count := 0;
SetLength(Strings, Length(Reflection.KnownFlags) +
Length(Reflection.SubEnums) + 1);
// Collect present flags
for i := 0 to High(Reflection.KnownFlags) do
if Reflection.KnownFlags[i].Presents then
begin
Strings[Count] := Reflection.KnownFlags[i].Flag.Name;
Inc(Count);
end;
// Collect sub-enumerations
if not IgnoreSubEnums then
for i := 0 to High(Reflection.SubEnums) do
begin
Strings[Count] := Reflection.SubEnums[i];
Inc(Count);
end;
// Include unknown bits
if not IgnoreUnnamed and (Reflection.UnknownBits <> 0) then
begin
Strings[Count] := IntToHexEx(Reflection.UnknownBits, HexDigits);
Inc(Count);
end;
if Count = 0 then
Reflection.Text := '(none)'
else
Reflection.Text := String.Join(', ', Strings, 0, Count);
end;
procedure FillOrdinalReflection;
var
a: TCustomAttribute;
Bytes: Boolean;
Hex: HexAttribute;
BitwiseType: Boolean;
begin
Hex := nil;
Bytes := False;
BitwiseType := False;
// Find known attributes
for a in Attributes do
begin
if (a is FlagNameAttribute) or (a is SubEnumAttribute) then
begin
BitwiseType := True;
Break;
end;
Bytes := Bytes or (a is BytesAttribute);
if a is HexAttribute then
Hex := HexAttribute(a);
end;
// Convert
if BitwiseType then
begin
Reflection.Kind := nkBitwise;
FillBitwiseReflection(Reflection, Attributes);
end
else if Assigned(Hex) then
begin
Reflection.Kind := nkHex;
Reflection.Text := IntToHexEx(Reflection.Value, Hex.Digits);
end
else if Bytes then
begin
Reflection.Kind := nkBytes;
Reflection.Text := BytesToString(Reflection.Value);
end
else
begin
Reflection.Kind := nkDec;
Reflection.Text := IntToStrEx(Reflection.Value);
end;
end;
function GetNumericReflectionRtti;
var
Attributes: TArray<TCustomAttribute>;
a: TCustomAttribute;
begin
// Capture the data
if RttiType is TRttiInt64Type then
Result.Value := UInt64(Instance)
else if RttiType is TRttiOrdinalType then
case TRttiOrdinalType(RttiType).OrdType of
otSLong, otULong: Result.Value := Cardinal(Instance);
otSWord, otUWord: Result.Value := Word(Instance);
otSByte, otUByte: Result.Value := Byte(Instance);
end
else
Assert(False, 'Not a numeric type');
// Save type name
Result.TypeName := RttiType.Name;
Result.SDKTypeName := '';
// Save SDK type name
for a in RttiType.GetAttributes do
if a is SDKNameAttribute then
begin
Result.SDKTypeName := SDKNameAttribute(a).Name;
Break;
end;
// Combine available attributes
Attributes := Concat(RttiType.GetAttributes, InstanceAttributes);
// Fill information according to the type
if IsBooleanType(RttiType.Handle) then
FillBooleanReflection(Result, Attributes)
else if RttiType is TRttiEnumerationType then
FillEnumReflection(Result, RttiType as TRttiEnumerationType, Attributes)
else
FillOrdinalReflection(Result, Attributes);
end;
function GetNumericReflection;
var
RttiContext: TRttiContext;
RttiType: TRttiType;
begin
RttiContext := TRttiContext.Create;
RttiType := RttiContext.GetType(AType);
Result := GetNumericReflectionRtti(RttiType, Instance, InstanceAttributes);
end;
class function TNumeric.Represent<T>;
var
AsByte: Byte absolute Instance;
AsWord: Word absolute Instance;
AsCardinal: Cardinal absolute Instance;
AsUInt64: UInt64 absolute Instance;
begin
if not Assigned(TypeInfo(T)) then
begin
// Handle enumerations with no TypeInfo
case SizeOf(T) of
SizeOf(Byte): Result.Value := AsByte;
SizeOf(Word): Result.Value := AsWord;
SizeOf(Cardinal): Result.Value := AsCardinal;
SizeOf(UInt64): Result.Value := AsUInt64;
else
Assert(False, 'Not a numeric type');
end;
FillOrdinalReflection(Result, InstanceAttributes);
end
else
Result := GetNumericReflection(TypeInfo(T), Instance, InstanceAttributes);
end;
end.
|
{ $HDR$}
{**********************************************************************}
{ Unit archived using Team Coherence }
{ Team Coherence is Copyright 2002 by Quality Software Components }
{ }
{ For further information / comments, visit our WEB site at }
{ http://www.TeamCoherence.com }
{**********************************************************************}
{}
{ $Log: 18012: MakeCanonicalIPv6AddressBox.pas }
{
{ Rev 1.4 2003.07.11 4:07:44 PM czhower
{ Removed deprecated BXBoxster reference.
}
{
{ Rev 1.3 6/24/2003 01:13:46 PM JPMugaas
{ Updates for minor API change.
}
{
{ Rev 1.2 2003.04.13 9:36:14 PM czhower
}
{
Rev 1.1 4/12/2003 11:24:28 PM BGooijen
}
unit MakeCanonicalIPv6AddressBox;
interface
{$I IdCompilerDefines.inc}
uses
SysUtils, Classes, BXBubble, Forms;
type
TdmodMakeCanonicalIPv6Address = class(TDataModule)
MakeCanonicalIPv6Address: TBXBubble;
procedure MakeCanonicalIPv6AddressTest(Sender: TBXBubble);
private
public
end;
var
dmodMakeCanonicalIPv6Address: TdmodMakeCanonicalIPv6Address;
implementation
{$R *.dfm}
uses
IdCoreGlobal;
procedure TdmodMakeCanonicalIPv6Address.MakeCanonicalIPv6AddressTest(Sender: TBXBubble);
var
i:integer;
LTest:string;
LResult:string;
LTestResult:string;
begin
with MakeCanonicalIPv6Address do begin
with TStringList.Create do try
LoadFromFile(DataDir + 'MakeCanonicalIPv6Address.dat');
for i := 0 to (Count div 2) - 1 do begin
LTest:=Strings[i*2];
Status('Testing "'+LTest+'"');
LResult:=Strings[i*2+1];
LTestResult:=IdCoreGlobal.MakeCanonicalIPv6Address(LTest);
Check(LResult=LTestResult,'MakeCanonicalIPv6Address failed on "'+LTest+'", expected "'+LResult+'", got "'+LTestResult+'"');
end;
finally Free; end;
end;
end;
end.
|
unit DirFindMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, ActnList, Menus, ImgList, DirFindNodes, ShlObj,
System.Actions, System.ImageList;
type
TfDirFindMain = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
cbIgnoreCase: TCheckBox;
cbMultiLine: TCheckBox;
cbFolder: TComboBox;
btnSelectFolder: TButton;
cbFiles: TComboBox;
cbPattern: TComboBox;
btnStart: TButton;
txtProgress: TEdit;
tvMatches: TTreeView;
Label4: TLabel;
cbNotFiles: TComboBox;
PopupMenu1: TPopupMenu;
ImageList1: TImageList;
ActionList1: TActionList;
aCopy: TAction;
aRefresh: TAction;
aTerminate: TAction;
aDelete: TAction;
aReplace: TAction;
aTerminateAll: TAction;
aDeleteAll: TAction;
CopyLocation1: TMenuItem;
N1: TMenuItem;
Refresh1: TMenuItem;
Abort1: TMenuItem;
Remove1: TMenuItem;
N2: TMenuItem;
Replace1: TMenuItem;
N3: TMenuItem;
Abortall1: TMenuItem;
Removeall1: TMenuItem;
Expand1: TMenuItem;
cbRegExp: TCheckBox;
btnSearchSection: TButton;
Label5: TLabel;
rbCountFiles: TRadioButton;
rbCountMatches: TRadioButton;
rbCountSubMatches: TRadioButton;
procedure btnSelectFolderClick(Sender: TObject);
procedure btnStartClick(Sender: TObject);
procedure tvMatchesCreateNodeClass(Sender: TCustomTreeView;
var NodeClass: TTreeNodeClass);
procedure tvMatchesContextPopup(Sender: TObject; MousePos: TPoint;
var Handled: Boolean);
procedure aRefreshExecute(Sender: TObject);
procedure aTerminateExecute(Sender: TObject);
procedure aDeleteExecute(Sender: TObject);
procedure tvMatchesDblClick(Sender: TObject);
procedure aCopyExecute(Sender: TObject);
procedure tvMatchesKeyPress(Sender: TObject; var Key: Char);
procedure tvMatchesEnter(Sender: TObject);
procedure tvMatchesExit(Sender: TObject);
procedure tvMatchesChange(Sender: TObject; Node: TTreeNode);
procedure aTerminateAllExecute(Sender: TObject);
procedure aDeleteAllExecute(Sender: TObject);
procedure aReplaceExecute(Sender: TObject);
procedure Expand1Click(Sender: TObject);
private
FPopupNode:TTreeNode;
FFinderProgress:TDirFinderNode;
cm2:IContextMenu2;
function PopupFinder: TDirFinderNode;
procedure DoFinderProgress(Sender: TObject; const PrgTxt: string);
procedure DoStoreValues(Sender: TObject);
protected
procedure DoCreate; override;
procedure DoClose(var Action: TCloseAction); override;
procedure WndProc(var Message: TMessage); override;
procedure DoShow; override;
end;
var
fDirFindMain: TfDirFindMain;
implementation
{$WARN UNIT_PLATFORM OFF}
uses ActiveX, ComObj, FileCtrl, ClipBrd, DirFindReplace, DirFindWorker;
{$R *.dfm}
const
AppName='DirFind';
function IniStr(Key,Default,Ini:string):string;
begin
SetLength(Result,1024);
SetLength(Result,GetPrivateProfileString(AppName,PChar(Key),PChar(Default),PChar(Result),1024,PChar(Ini)));
end;
procedure SetIniStr(Key,Value,Ini:string);
begin
WritePrivateProfileString(AppName,PChar(Key),PChar(Value),PChar(Ini));
end;
procedure TfDirFindMain.DoCreate;
var
d:string;
i:integer;
begin
inherited;
OleInitialize(nil);//CoInitialize(nil);
FPopupNode:=nil;
FFinderProgress:=nil;
cm2:=nil;
try
d:=GetEnvironmentVariable('APPDATA');
if d='' then d:=ExtractFilePath(Application.ExeName) else d:=d+'\DirFind\';
cbFolder.Items.LoadFromFile(d+'DirFind_Folders.txt');
cbFiles.Items.LoadFromFile(d+'DirFind_Files.txt');
cbNotFiles.Items.LoadFromFile(d+'DirFind_FilesNot.txt');
cbPattern.Items.LoadFromFile(d+'DirFind_Patterns.txt');
except
//silent
end;
cbFolder.Sorted:=true;
cbFiles.Sorted:=true;
cbNotFiles.Sorted:=true;
cbPattern.Sorted:=true;
d:=d+'DirFind.ini';
cbFolder.Text:=IniStr('Folder','',d);
cbFiles.Text:=IniStr('Files','',d);
cbNotFiles.Text:=IniStr('FilesNot','',d);
cbPattern.Text:=IniStr('Pattern','',d);
cbRegExp.Checked:=IniStr('RegExp','0',d)='1';
cbIgnoreCase.Checked:=IniStr('IgnoreCase','1',d)='1';
cbMultiLine.Checked:=IniStr('MultiLine','0',d)='1';
i:=StrToIntDef(IniStr('CountMatches','0',d),0);
case i of
0:rbCountFiles.Checked:=true;
1:rbCountMatches.Checked:=true;
2:rbCountSubMatches.Checked:=true;
end;
IndentLevelTabSize:=StrToInt(IniStr('TabSize','4',d));
end;
procedure TfDirFindMain.DoClose(var Action: TCloseAction);
var
d:string;
i:integer;
const
BoolStr:array[boolean] of string=('0','1');
begin
inherited;
d:=GetEnvironmentVariable('APPDATA');
if d='' then d:=ExtractFilePath(Application.ExeName) else
begin
d:=d+'\DirFind\';
CreateDir(d);
end;
cbFolder.Items.SaveToFile(d+'DirFind_Folders.txt');
cbFiles.Items.SaveToFile(d+'DirFind_Files.txt');
cbNotFiles.Items.SaveToFile(d+'DirFind_FilesNot.txt');
cbPattern.Items.SaveToFile(d+'DirFind_Patterns.txt');
d:=d+'DirFind.ini';
SetIniStr('Folder',cbFolder.Text,d);
SetIniStr('Files',cbFiles.Text,d);
SetIniStr('FilesNot',cbNotFiles.Text,d);
SetIniStr('Pattern',cbPattern.Text,d);
SetIniStr('RegExp',BoolStr[cbRegExp.Checked],d);
SetIniStr('IgnoreCase',BoolStr[cbIgnoreCase.Checked],d);
SetIniStr('MultiLine',BoolStr[cbMultiLine.Checked],d);
if rbCountFiles.Checked then i:=0 else
if rbCountMatches.Checked then i:=1 else
if rbCountSubMatches.Checked then i:=2 else
i:=0;//default
SetIniStr('CountMatches',IntToStr(i),d);
end;
procedure TfDirFindMain.btnSelectFolderClick(Sender: TObject);
var
d:string;
begin
d:=cbFolder.Text;
if SelectDirectory('Select directory to search in','',d) then cbFolder.Text:=d;
end;
function RegExSafe(const x:string):string;
var
i,j,l:integer;
begin
l:=Length(x);
SetLength(Result,l*2);
i:=0;
j:=0;
while i<l do
begin
inc(i);
inc(j);
if AnsiChar(x[i]) in ['\','.','*','+','?','$','^','[',']','(',')','{','}'] then
begin
Result[j]:='\';
inc(j);
end;
Result[j]:=x[i];
end;
SetLength(Result,j);
end;
procedure TfDirFindMain.btnStartClick(Sender: TObject);
var
n:TDirFinderNode;
p:string;
i:integer;
begin
if (txtProgress.Focused or (Sender=btnSearchSection)) and (txtProgress.SelLength<>0) then
if cbRegExp.Checked then
cbPattern.Text:=RegExSafe(txtProgress.SelText)
else
cbPattern.Text:=txtProgress.SelText;
cbPattern.SelectAll;
if cbRegExp.Checked then
p:=cbPattern.Text
else
p:=RegExSafe(cbPattern.Text);
if rbCountFiles.Checked then i:=0 else
if rbCountMatches.Checked then i:=1 else
if rbCountSubMatches.Checked then i:=2 else
i:=0;//default
DirFindNextNodeClass:=TDirFinderNode;
n:=tvMatches.Items.Add(nil,'') as TDirFinderNode;
n.Start(
cbFolder.Text,
cbFiles.Text,
cbNotFiles.Text,
p,
cbIgnoreCase.Checked,
cbMultiLine.Checked,
TDirFinderCountMatches(i),
DoStoreValues);
tvMatches.Selected:=n;
end;
procedure TfDirFindMain.tvMatchesCreateNodeClass(Sender: TCustomTreeView;
var NodeClass: TTreeNodeClass);
begin
NodeClass:=DirFindNextNodeClass;
end;
procedure TfDirFindMain.tvMatchesContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean);
const
startCmd=20;//keep somewhere above total count of items in popupmenu
var
fn:string;
Malloc:IMalloc;
DesktopFolder,SourceFolder:IShellFolder;
eaten,flags:cardinal;
id:PItemIDList;
cm:IContextMenu;
w:WideString;
i:integer;
ici:TCMInvokeCommandInfo;
p:TPoint;
mi,mi1:TMenuItem;
begin
FPopupNode:=tvMatches.GetNodeAt(MousePos.X,MousePos.Y);
if (FPopupNode<>nil) and
((FPopupNode is TDirFindFolderNode) or
(FPopupNode is TDirFindMatchNode)) then
begin
try
fn:='';//counter warning
if FPopupNode is TDirFindFolderNode then
fn:=(FPopupNode as TDirFindFolderNode).FolderPath;
if FPopupNode is TDirFindMatchNode then
fn:=(FPopupNode as TDirFindMatchNode).FilePath;
p:=tvMatches.ClientToScreen(MousePos);
mi:=TMenuItem.Create(nil);
mi1:=TMenuItem.Create(nil);//forces sub-menu
mi1.Visible:=false;
mi.Caption:='Context menu';
mi.Add(mi1);
try
OleCheck(SHGetMalloc(Malloc));
OleCheck(SHGetDesktopFolder(DesktopFolder));
flags:=0;
w:=ExtractFilePath(fn);
OleCheck(DesktopFolder.ParseDisplayName(0,nil,PWideChar(w),eaten,id,flags));
try
OleCheck(DesktopFolder.BindToObject(id,nil,IShellFolder,SourceFolder));
finally
Malloc.Free(id);
end;
w:=ExtractFileName(fn);
OleCheck(SourceFolder.ParseDisplayName(0,nil,PWideChar(w),eaten,id,flags));
try
OleCheck(SourceFolder.GetUIObjectOf(0,1,id,IContextMenu,nil,cm));
finally
Malloc.Free(id);
end;
cm.QueryContextMenu(mi.Handle,0,startCmd,$7FFF,
CMF_EXPLORE or CMF_NODEFAULT);
PopupMenu1.Items.Insert(2,mi);
cm2:=cm as IContextMenu2;
i:=integer(TrackPopupMenu(
PopupMenu1.Handle,
TPM_RETURNCMD or TPM_LEFTALIGN or TPM_LEFTBUTTON or TPM_RIGHTBUTTON,
p.X,p.Y,0,Handle,nil));
if i<>0 then
if not PopupMenu1.DispatchCommand(i) then
begin
dec(i,startCmd);
ici.cbSize:=SizeOf(TCMInvokeCommandInfo);
ici.fMask:=0;
ici.hwnd:=Handle;
ici.lpVerb:=pointer(i);
ici.lpParameters:=nil;
ici.lpDirectory:=nil;
ici.nShow:=SW_SHOWNORMAL;
ici.dwHotKey:=0;
ici.hIcon:=0;
cm.InvokeCommand(ici);
end;
finally
cm2:=nil;
cm:=nil;
mi.Free;
DesktopFolder:=nil;
Malloc:=nil;
end;
Handled:=true;
except
//silent
end;
end;
end;
procedure TfDirFindMain.WndProc(var Message: TMessage);
begin
if cm2<>nil then
case Message.Msg of
WM_INITMENUPOPUP,
WM_DRAWITEM,
WM_MENUCHAR,
WM_MEASUREITEM:
begin
cm2.HandleMenuMsg(Message.Msg,Message.WParam,Message.LParam);
Message.Result:=0;
end;
end;
inherited;
end;
function TfDirFindMain.PopupFinder: TDirFinderNode;
begin
while (FPopupNode<>nil) and (FPopupNode.Parent<>nil) do FPopupNode:=FPopupNode.Parent;
if FPopupNode<>nil then Result:=FPopupNode as TDirFinderNode else
raise EAbort.Create('Nothing selected');//Result:=nil?
end;
procedure TfDirFindMain.aRefreshExecute(Sender: TObject);
begin
PopupFinder.Refresh;
end;
procedure TfDirFindMain.aTerminateExecute(Sender: TObject);
begin
PopupFinder.Abort;
end;
procedure TfDirFindMain.aDeleteExecute(Sender: TObject);
var
n:TDirFinderNode;
begin
n:=PopupFinder;
if FFinderProgress<>nil then FFinderProgress.OnProgress:=nil;
FFinderProgress:=nil;
txtProgress.Text:='';
Caption:=AppName;
Application.Title:=AppName;
n.Delete;
FPopupNode:=tvMatches.Selected;//for next press of [delete]
if tvMatches.Focused and (tvMatches.Selected=nil) then cbPattern.SetFocus;
end;
procedure TfDirFindMain.tvMatchesDblClick(Sender: TObject);
var
tn:TTreeNode;
begin
tn:=tvMatches.Selected;
if (tn<>nil) and (tn is TDirFindTreeNode) then
(tn as TDirFindTreeNode).DoDblClick;
end;
procedure TfDirFindMain.aCopyExecute(Sender: TObject);
begin
if FPopupNode<>nil then
if FPopupNode is TDirFinderNode then
Clipboard.AsText:=(FPopupNode as TDirFinderNode).AllFilePaths
else
if FPopupNode is TDirFindTreeNode then
Clipboard.AsText:=(FPopupNode as TDirFindTreeNode).ProgressText//?
else
Clipboard.AsText:=FPopupNode.Text;
end;
procedure TfDirFindMain.tvMatchesKeyPress(Sender: TObject; var Key: Char);
begin
if Key=#13 then tvMatchesDblClick(Sender);
end;
procedure TfDirFindMain.tvMatchesEnter(Sender: TObject);
begin
aDelete.Enabled:=true;
aDeleteAll.Enabled:=true;
aCopy.Enabled:=true;
end;
procedure TfDirFindMain.tvMatchesExit(Sender: TObject);
begin
aDelete.Enabled:=false;
aDeleteAll.Enabled:=false;
aCopy.Enabled:=false;
end;
procedure TfDirFindMain.tvMatchesChange(Sender: TObject; Node: TTreeNode);
var
tn:TTreeNode;
begin
FPopupNode:=Node;
tn:=Node;
if tn=nil then txtProgress.Text:='' else
if tn is TDirFindTreeNode then
txtProgress.Text:=(tn as TDirFindTreeNode).ProgressText
else
txtProgress.Text:=tn.Text;
if FFinderProgress<>nil then
begin
FFinderProgress.OnProgress:=nil;
FFinderProgress:=nil;
end;
if tn<>nil then
if tn is TDirFindFolderNode then (tn as TDirFindFolderNode).SetPrioFolder else
if tn is TDirFinderNode then
begin
FFinderProgress:=(tn as TDirFinderNode);
FFinderProgress.OnProgress:=DoFinderProgress;
end;
while (tn<>nil) and not(tn is TDirFinderNode) do tn:=tn.Parent;
if tn<>nil then
begin
Caption:=AppName+' - '+(tn as TDirFinderNode).RootPath+' - '+(tn as TDirFinderNode).Pattern;
Application.Title:=Caption;
end;
end;
procedure TfDirFindMain.DoFinderProgress(Sender:TObject;const PrgTxt:string);
begin
txtProgress.Text:=PrgTxt;
end;
procedure TfDirFindMain.aTerminateAllExecute(Sender: TObject);
var
tn:TTreeNode;
begin
tn:=tvMatches.Items.GetFirstNode;
while (tn<>nil) do
begin
if tn is TDirFinderNode then (tn as TDirFinderNode).Abort;
tn:=tn.getNextSibling;
end;
end;
procedure TfDirFindMain.aDeleteAllExecute(Sender: TObject);
begin
if FFinderProgress<>nil then FFinderProgress.OnProgress:=nil;
FFinderProgress:=nil;
txtProgress.Text:='';
Caption:=AppName;
Application.Title:=AppName;
tvMatches.Items.BeginUpdate;
try
tvMatches.Items.Clear;
finally
tvMatches.Items.EndUpdate;
end;
if tvMatches.Focused then cbPattern.SetFocus;
end;
procedure TfDirFindMain.aReplaceExecute(Sender: TObject);
var
tn:TDirFinderNode;
begin
tn:=PopupFinder;
if tn.IsFinding then raise Exception.Create('Matching job is still running. Wait for it to complete first.');
fDirFindReplace.lblPattern.Caption:=tn.Pattern;
if fDirFindReplace.ShowModal=mrOk then
MessageBox(Handle,PChar('Performed replace, '+
IntToStr(tn.ReplaceAll(fDirFindReplace.txtReplaceWith.Text))+' file(s) changed.'),
AppName,MB_OK or MB_ICONINFORMATION);
end;
procedure TfDirFindMain.Expand1Click(Sender: TObject);
begin
if FPopupNode<>nil then
if FPopupNode.HasChildren then
FPopupNode.Expand(false)
else
if FPopupNode is TDirFindTreeNode then
(FPopupNode as TDirFindTreeNode).DoDblClick;
end;
procedure TfDirFindMain.DoShow;
var
i,j,l:integer;
s:string;
b:boolean;
begin
inherited;
j:=0;
i:=ParamCount;
if i>0 then
begin
s:=ParamStr(1);
if Copy(s,1,1)='/' then
begin
b:=true;
j:=2;
l:=Length(s);
while j<=l do
begin
case s[j] of
'-':b:=false;
'+':b:=true;
'r','R':cbRegExp.Checked:=b;
'c','C':cbIgnoreCase.Checked:=b;
'm','M':cbMultiLine.Checked:=b;
'f','F':rbCountFiles.Checked:=true;
'a','A':rbCountMatches.Checked:=true;
's','S':rbCountSubMatches.Checked:=true;
else raise Exception.Create('Unknown command line option at position '+
IntToStr(j)+':"'+s+'"');
end;
inc(j);
end;
j:=1;
dec(i);
end;
end;
case i of
1:
begin
cbFolder.Text:=ParamStr(j+1);
cbPattern.SetFocus;
end;
2:
begin
cbFolder.Text:=ParamStr(j+1);
cbFiles.Text:='';//?
cbPattern.Text:=ParamStr(j+2);
btnStart.Click;
end;
3:
begin
cbFolder.Text:=ParamStr(j+1);
cbFiles.Text:=ParamStr(j+2);
cbPattern.Text:=ParamStr(j+3);
btnStart.Click;
end;
4:
begin
cbFolder.Text:=ParamStr(j+1);
cbFiles.Text:=ParamStr(j+2);
cbNotFiles.Text:=ParamStr(j+3);
cbPattern.Text:=ParamStr(j+4);
btnStart.Click;
end;
end;
end;
procedure TfDirFindMain.DoStoreValues(Sender: TObject);
var
n:TDirFinderNode;
procedure DoStore(cb:TComboBox;const Value:string);
begin
//assert cb.Items.Sorted
if (Value<>'') and (cb.Items.IndexOf(Value)=-1) then
cb.Items.Add(Value);
end;
begin
n:=(Sender as TDirFinderNode);
DoStore(cbFolder,n.RootPath);
DoStore(cbFiles,n.FindFiles);
DoStore(cbNotFiles,n.FindNotFiles);
DoStore(cbPattern,n.Pattern);
end;
end.
|
unit uHTMLResEmb;
{$IFDEF FPC}
{$mode objfpc}
{$H+}
//{$modeswitch typehelpers}
{$ENDIF}
interface
uses
{$IFDEF DARWIN}
cwstring,
{$ENDIF}
Classes,
DOM,
uUtil;
type
{ THTMLProcessor }
THTMLProcessor = class(TObject)
private
FDocPath: string;
FHeader: string;
FHTMLBroken: Boolean;
FEmbedCSS: Boolean;
FEmbedJavaScript: Boolean;
FEmbedImages: Boolean;
FXMLSourceDocument: TXMLDocument;
FDeleteList: TDOMNodes;
procedure PreventSelfClosingTag(ANode: TDOMNode);
procedure DeleteNodes;
function StoreAndRemoveHeader(AInput: TStringList): string;
procedure RestoreHeader(AInput: TStringList);
function NumericEntity(AEntity: DOMString): TDOMNode;
// Node-Handling by type
procedure StyleNode(ANode: TDOMNode);
procedure LinkNode(ANode: TDOMNode);
procedure ScriptNode(ANode: TDOMNode);
procedure ImageNode(ANode: TDOMNode);
// Node loop
procedure SelectNode(var ANode: TDOMNode);
procedure ProcessAllNodes;
public
constructor Create(ADocPath: string; AEmbedCSS, AEmbedJavaScript, AEmbedImages: Boolean);
destructor Destroy; override;
function ProcessHTML(AInput: TStringList; out ProcessingMessage: string): Boolean;
end;
implementation
uses
sysutils,
uXMLWriter;
{ ---------------------------------------------------------------------
THTMLProcessor
---------------------------------------------------------------------}
// private
procedure THTMLProcessor.PreventSelfClosingTag(ANode: TDOMNode);
begin
// ToDo: Exclude these tags in the future
//'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input',
//'keygen', 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr'
if (ANode.ChildNodes.Count = 0) then
ANode.AppendChild(FXMLSourceDocument.CreateTextNode(''));
end;
procedure THTMLProcessor.DeleteNodes;
var
i: Integer;
Parent: TDOMNode;
begin
for i := 0 to FDeleteList.Count-1 do
begin
Parent := FDeleteList[i].ParentNode;
if (Parent <> nil) then
begin
Parent.RemoveChild(FDeleteList[i]);
PreventSelfClosingTag(Parent);
end;
end;
end;
function THTMLProcessor.StoreAndRemoveHeader(AInput: TStringList): string;
var
Document: string;
XMLDeclStart, DocTypeStart, p: Integer;
begin
Document := AInput.Text;
XMLDeclStart := Pos('<?xml', Document);
DocTypeStart := Pos('<!DOCTYPE', Document);
// Is an error in the document but handled nevertheless
if (XMLDeclStart > DocTypeStart) then
begin
p := XMLDeclStart + 6;
while p < Length(Document) do
if (Document[p..p+1] = '?>') then
begin
FHeader := Copy(Document, 1, p+1);
Delete(Document, 1, p+1);
Break;
end
else
Inc(p);
end
// No XML declaration, only DOCTYPE
else if (DocTypeStart > XMLDeclStart) then
begin
p := DocTypeStart + 9;
while p < Length(Document) do
if (Document[p] = '>') then
begin
FHeader := Copy(Document, 1, p);
Delete(Document, 1, p);
Break;
end
else
Inc(p);
end;
// No XML and DOCTYPE declarations
Result := Document;
end;
procedure THTMLProcessor.RestoreHeader(AInput: TStringList);
begin
// AInput will always contain these lines at the beginning (see ProcessHTML):
// <?xml version="1.0" encoding="utf-8"?>
// <!DOCTYPE html SYSTEM " ">
// The first line will be deleted and the second (now first)
// line will be replaced with the original header content (if available).
AInput.Delete(0);
if (FHeader <> '') then
AInput[0] := FHeader
else
AInput.Delete(0);
end;
function THTMLProcessor.NumericEntity(AEntity: DOMString): TDOMNode;
begin
Result := FXMLSourceDocument.CreateNumericEntity(AEntity);
end;
procedure THTMLProcessor.StyleNode(ANode: TDOMNode);
var
StyleNodeContent: String;
begin
// Wrap node content in CDATA section (enables special characters like '>' in CSS)
// If RepairBrokenHTML was called, the special characters of already existing CDATA section
// have been escaped, so wrapping them again (ANodeTextContent) can create nested CDATA
// sections but thats not a problem for the browser/document.
// This is only done with broken HTML (see SelectNode()), so the original code isn't touched.
StyleNodeContent :=
'*/' +
NL +
ANode.TextContent +
NL +
'/* ';
while (ANode.ChildNodes.Count > 0) do
ANode.RemoveChild(ANode.ChildNodes[0]);
with ANode do
begin
AppendChild(FXMLSourceDocument.CreateTextNode(NL));
AppendChild(FXMLSourceDocument.CreateTextNode('/*'));
AppendChild(FXMLSourceDocument.CreateCDATASection(StyleNodeContent));
AppendChild(FXMLSourceDocument.CreateTextNode('*/'));
AppendChild(FXMLSourceDocument.CreateTextNode(NL));
end;
end;
procedure THTMLProcessor.LinkNode(ANode: TDOMNode);
var
Href, Rel: DOMString;
StylesheetFileName: string;
FileContent, StylesheetTagContent: String;
NewStyleNode: TDOMElement;
begin
Href := TDOMElement(ANode).GetAttribute('href');
if (HRef = '') then
Exit;
Rel := TDOMElement(ANode).GetAttribute('rel');
if ((Rel = '') or (Rel <> 'stylesheet')) then
Exit;
if Href[1..7] = 'file://' then
begin
{$IFDEF WINDOWS} // 'file:///c:/'
StylesheetFileName := Href[9..MaxInt];
{$ELSE}
StylesheetFileName := Href[8..MaxInt];
{$ENDIF}
end
else
StylesheetFileName := GetAbsolutePath(Href, FDocPath);
try
FileContent := GetFileContentAsString(StylesheetFileName);
StylesheetTagContent :=
'*/' +
NL +
FileContent +
NL +
'/* ';
except
WriteLn(StdErr, 'Warning: couldn''t embed ' + StylesheetFileName);
Exit;
end;
NewStyleNode := FXMLSourceDocument.CreateElement('style');
with NewStyleNode do
begin
SetAttribute('type', 'text/css');
AppendChild(FXMLSourceDocument.CreateTextNode(NL));
AppendChild(FXMLSourceDocument.CreateTextNode('/*'));
AppendChild(FXMLSourceDocument.CreateCDATASection(StylesheetTagContent));
AppendChild(FXMLSourceDocument.CreateTextNode('*/'));
AppendChild(FXMLSourceDocument.CreateTextNode(NL));
end;
with ANode do
begin
AppendSibling(FXMLSourceDocument.CreateTextNode(NL));
AppendSibling(NewStyleNode);
AppendSibling(FXMLSourceDocument.CreateTextNode(NL));
end;
FDeleteList.Add(ANode);
end;
procedure THTMLProcessor.ScriptNode(ANode: TDOMNode);
var
Src: DOMString;
ScriptFileName: string;
FileContent, ScriptNodeContent: String;
begin
Src := TDOMElement(ANode).GetAttribute('src');
// Wrap node content in CDATA section (enables special characters like '>' in JavaScript)
// If RepairBrokenHTML was called, the special characters of already existing CDATA section
// have been escaped, so wrapping them again (ANodeTextContent) can create nested CDATA
// sections but thats not a problem for the browser/document.
if (Src = '') then
begin
// This is only done with broken HTML (see SelectNode()), so the original code isn't touched.
if (FHTMLBroken) then
begin
ScriptNodeContent :=
NL +
'/*<!--*/' +
NL +
ANode.TextContent +
NL +
'/*-->*/' +
NL +
'//';
while (ANode.ChildNodes.Count > 0) do
ANode.RemoveChild(ANode.ChildNodes[0]);
with ANode do
begin
AppendChild(FXMLSourceDocument.CreateTextNode(NL));
AppendChild(FXMLSourceDocument.CreateTextNode('/*'));
AppendChild(FXMLSourceDocument.CreateCDATASection(ScriptNodeContent));
AppendChild(FXMLSourceDocument.CreateTextNode('*/'));
AppendChild(FXMLSourceDocument.CreateTextNode(NL));
end;
end;
Exit;
end;
if Src[1..7] = 'file://' then
begin
{$IFDEF WINDOWS} // 'file:///c:/'
ScriptFileName := Src[9..MaxInt];
{$ELSE}
ScriptFileName := Src[8..MaxInt];
{$ENDIF}
end
else
ScriptFileName := GetAbsolutePath(Src, FDocPath);
try
FileContent := GetFileContentAsString(ScriptFileName);
ScriptNodeContent :=
NL +
'/*<!--*/' +
NL +
WideStringReplace(FileContent, '</script>', '<\/script>', [rfIgnoreCase, rfReplaceAll]) +
NL +
'/*-->*/' +
NL +
'//';
except
WriteLn(StdErr, 'Warning: couldn''t embed ' + ScriptFileName);
Exit;
end;
ANode.Attributes.RemoveNamedItem('src');
ANode.AppendChild(FXMLSourceDocument.CreateTextNode('//'));
ANode.AppendChild(FXMLSourceDocument.CreateCDATASection(ScriptNodeContent));
ANode.AppendChild(FXMLSourceDocument.CreateTextNode(NL));
end;
procedure THTMLProcessor.ImageNode(ANode: TDOMNode);
var
Src: DOMString;
ImageFileName: string;
Base64Success: Boolean;
Base64Image: DOMString;
begin
Src := TDOMElement(ANode).GetAttribute('src');
if (Src = '') then
Exit;
if Src[1..7] = 'file://' then
begin
{$IFDEF WINDOWS} // 'file:///c:/'
ImageFileName := Src[9..MaxInt];
{$ELSE}
ImageFileName := Src[8..MaxInt];
{$ENDIF}
end
else
ImageFileName := GetAbsolutePath(Src, FDocPath);
Base64Success := False;
Base64Image := GetImageAsBase64String(ImageFileName, Base64Success);
if not(Base64Success) then
WriteLn(StdErr, 'Warning: couldn''t embed ' + ImageFileName)
else
TDOMElement(ANode).SetAttribute('src', Base64Image);
end;
// Node selection by tag name
procedure THTMLProcessor.SelectNode(var ANode: TDOMNode);
var
NodeName: DOMString;
begin
NodeName := WideLowerCase(ANode.NodeName);
if ((NodeName = 'style') and FHTMLBroken) then
StyleNode(ANode)
else if (FEmbedCSS and (NodeName = 'link')) then
LinkNode(ANode)
else if (FEmbedJavaScript and (NodeName = 'script')) then
ScriptNode(ANode)
else if (FEmbedImages and (NodeName = 'img')) then
ImageNode(ANode)
else if (ANode.NodeType = ELEMENT_NODE) then
PreventSelfClosingTag(ANode);
end;
procedure THTMLProcessor.ProcessAllNodes;
procedure VisitNodes(SourceNode: TDOMNode);
begin
if (SourceNode = nil) then
Exit;
SelectNode(SourceNode);
SourceNode := SourceNode.FirstChild;
while (SourceNode <> nil) do
begin
VisitNodes(SourceNode);
SourceNode := SourceNode.NextSibling;
end;
end;
begin
VisitNodes(FXMLSourceDocument.DocumentElement);
end;
constructor THTMLProcessor.Create(ADocPath: string; AEmbedCSS, AEmbedJavaScript, AEmbedImages: Boolean);
begin
FDocPath := ADocPath;
FHTMLBroken := False;
FEmbedCSS := AEmbedCSS;
FEmbedJavaScript := AEmbedJavaScript;
FEmbedImages := AEmbedImages;
FDeleteList := TDOMNodes.Create(False);
end;
// public
destructor THTMLProcessor.Destroy;
begin
FDeleteList.Free;
inherited Destroy;
end;
function THTMLProcessor.ProcessHTML(AInput: TStringList; out ProcessingMessage: string): Boolean;
var
Buffer: TStringStream;
DocumentStringContent: WideString;
FirstErrMsg, SecondErrMsg: string;
HeadElement, Title: TDOMNode;
begin
Result := False;
if (AInput.Count = 0) then
Exit;
FirstErrMsg := '';
SecondErrMsg := '';
ProcessingMessage := '';
DocumentStringContent := StoreAndRemoveHeader(AInput);
Buffer := TStringStream.Create('');
FXMLSourceDocument := nil;
try
// Initial parsing
try
// Hack: this incomplete DOCTYPE is sufficient to make the FPC XML parser accept any HTML entities like
ParseXMLDocument('<!DOCTYPE html SYSTEM " " >' + NL + DocumentStringContent, FXMLSourceDocument, nil, True);
except
FirstErrMsg := Exception(ExceptObject).Message;
FHTMLBroken := True;
// Retry and auto repair broken HTML. Unfortunately this removes CDATA sections
// but they will be restored in StyleNode() and ScriptNode().
DocumentStringContent := RepairBrokenHTML(DocumentStringContent, SecondErrMsg);
// Try again
ParseXMLDocument('<!DOCTYPE html SYSTEM " " >' + NL + DocumentStringContent, FXMLSourceDocument, nil, True);
end;
if (FirstErrMsg <> '') then
ProcessingMessage := FirstErrMsg;
HeadElement := FXMLSourceDocument.DocumentElement.FindNode('head');
// Fix self closing title element
if (HeadElement <> nil) then
begin
Title := HeadElement.FindNode('title');
if (Title <> nil) then
PreventSelfClosingTag(Title);
end;
ProcessAllNodes;
DeleteNodes;
// Write final result
WriteXMLFile(FXMLSourceDocument, Buffer);
Buffer.Position := 0;
AInput.Clear;
AInput.LoadFromStream(Buffer);
RestoreHeader(AInput);
Result := True;
except
Buffer.Free;
if (FXMLSourceDocument <> nil) then
FXMLSourceDocument.Free;
if (SecondErrMsg <> '') then
ProcessingMessage := FirstErrMsg + NL + SecondErrMsg + NL + Exception(ExceptObject).Message
else
ProcessingMessage := FirstErrMsg + NL + Exception(ExceptObject).Message;
raise Exception.Create(ProcessingMessage);
end;
end;
end.
|
{******************************************************************************}
{ }
{ WiRL: RESTful Library for Delphi }
{ }
{ Copyright (c) 2015-2019 WiRL Team }
{ }
{ https://github.com/delphi-blocks/WiRL }
{ }
{******************************************************************************}
unit WiRL.Diagnostics.Manager;
interface
uses
System.Classes, System.SysUtils, System.StrUtils, System.Generics.Collections,
System.SyncObjs, System.Diagnostics,
WiRL.Core.JSON,
WiRL.Core.Classes,
WiRL.Core.Singleton,
WiRL.Core.Context,
WiRL.Core.Auth.Context,
WiRL.Core.Engine,
WiRL.Core.Application;
type
TWiRLDiagnosticInfo = class
private
FRequestCount: Integer;
FLastRequestTime: TDateTime;
FCriticalSection: TCriticalSection;
FBasePath: string;
FTotalExecutionTime: Int64;
function GetAverageTimePerRequest: Double;
public
constructor Create;
destructor Destroy; override;
procedure AcquireRequest(AExecutionTimeInMilliseconds: Integer = 0); virtual;
function ToJSON: TJSONObject; virtual;
property BasePath: string read FBasePath write FBasePath;
property RequestCount: Integer read FRequestCount;
property LastRequestTime: TDateTime read FLastRequestTime;
property TotalExecutionTime: Int64 read FTotalExecutionTime;
property AverageTimePerRequest: Double read GetAverageTimePerRequest;
end;
TWiRLDiagnosticAppInfo = class(TWiRLDiagnosticInfo)
end;
TWiRLDiagnosticEngineInfo = class(TWiRLDiagnosticInfo)
private
FLastSessionEnd: TDateTime;
FActiveSessionCount: Integer;
FSessionCount: Integer;
FLastSessionStart: TDateTime;
public
constructor Create;
procedure AcquireNewSession();
procedure AcquireEndSession();
function ToJSON: TJSONObject; override;
property ActiveSessionCount: Integer read FActiveSessionCount;
property SessionCount: Integer read FSessionCount;
property LastSessionStart: TDateTime read FLastSessionStart;
property LastSessionEnd: TDateTime read FLastSessionEnd;
end;
TWiRLDiagnosticsManager = class(TNonInterfacedObject, IWiRLHandleListener, IWiRLHandleRequestEventListener)
private
type TDiagnosticsManagerSingleton = TWiRLSingleton<TWiRLDiagnosticsManager>;
private
class var FEngine: TWiRLEngine;
FEngineInfo: TWiRLDiagnosticEngineInfo;
FAppDictionary: TObjectDictionary<string, TWiRLDiagnosticAppInfo>;
FCriticalSection: TCriticalSection;
protected
class function GetInstance: TWiRLDiagnosticsManager; static; inline;
function GetAppInfo(const App: string; const ADoSomething: TProc<TWiRLDiagnosticAppInfo>): Boolean; overload;
public
public
constructor Create;
destructor Destroy; override;
class procedure SetEngine(AEngine: TWiRLEngine);
function ToJSON: TJSONObject; virtual;
procedure RetrieveAppInfo(const App: string; const ADoSomething: TProc<TWiRLDiagnosticAppInfo>);
// IWiRLTokenEventListener
procedure OnTokenStart(const AToken: string);
procedure OnTokenEnd(const AToken: string);
// IWiRLHandleRequestEventListener
procedure BeforeHandleRequest(const ASender: TWiRLEngine; const AApplication: TWiRLApplication);
procedure AfterHandleRequest(const ASender: TWiRLEngine; const AApplication: TWiRLApplication; const AStopWatch: TStopWatch);
class property Instance: TWiRLDiagnosticsManager read GetInstance;
end;
implementation
uses
System.Math, System.DateUtils,
WiRL.Core.Utils;
{ TWiRLDiagnosticsManager }
procedure TWiRLDiagnosticsManager.AfterHandleRequest(const ASender: TWiRLEngine;
const AApplication: TWiRLApplication; const AStopWatch: TStopWatch);
var
LStopWatch: TStopwatch;
begin
LStopWatch := AStopWatch;
GetAppInfo(AApplication.Name,
procedure (AAppInfo: TWiRLDiagnosticAppInfo)
begin
AAppInfo.AcquireRequest(LStopWatch.ElapsedMilliseconds);
FCriticalSection.Enter;
try
FEngineInfo.AcquireRequest(LStopWatch.ElapsedMilliseconds);
finally
FCriticalSection.Leave;
end
end
);
end;
procedure TWiRLDiagnosticsManager.BeforeHandleRequest(const ASender: TWiRLEngine;
const AApplication: TWiRLApplication);
begin
end;
constructor TWiRLDiagnosticsManager.Create;
begin
TDiagnosticsManagerSingleton.CheckInstance(Self);
FAppDictionary := TObjectDictionary<string, TWiRLDiagnosticAppInfo>.Create([doOwnsValues]);
FCriticalSection := TCriticalSection.Create;
FEngineInfo := TWiRLDiagnosticEngineInfo.Create;
inherited Create;
FEngine.AddSubscriber(Self);
end;
destructor TWiRLDiagnosticsManager.Destroy;
begin
FEngine.RemoveSubscriber(Self);
FEngineInfo.Free;
FCriticalSection.Free;
FAppDictionary.Free;
inherited;
end;
function TWiRLDiagnosticsManager.GetAppInfo(const App: string;
const ADoSomething: TProc<TWiRLDiagnosticAppInfo>): Boolean;
var
LInfo: TWiRLDiagnosticAppInfo;
LWiRLApp: TWiRLApplication;
begin
Result := False;
FCriticalSection.Enter;
try
if FEngine.Applications.TryGetValue(App, LWiRLApp) then // real application
begin
if not LWiRLApp.SystemApp then // skip system app
begin
if not FAppDictionary.TryGetValue(App, LInfo) then // find or create
begin
LInfo := TWiRLDiagnosticAppInfo.Create;
LInfo.BasePath := LWiRLApp.BasePath;
FAppDictionary.Add(App, LInfo);
end;
if Assigned(ADoSomething) then
ADoSomething(LInfo);
end;
end;
finally
FCriticalSection.Leave;
end;
end;
class function TWiRLDiagnosticsManager.GetInstance: TWiRLDiagnosticsManager;
begin
Result := TDiagnosticsManagerSingleton.Instance;
end;
procedure TWiRLDiagnosticsManager.OnTokenEnd(const AToken: string);
begin
inherited;
FCriticalSection.Enter;
try
FEngineInfo.AcquireEndSession;
finally
FCriticalSection.Leave;
end;
end;
procedure TWiRLDiagnosticsManager.OnTokenStart(const AToken: string);
begin
inherited;
FCriticalSection.Enter;
try
FEngineInfo.AcquireNewSession;
finally
FCriticalSection.Leave;
end;
end;
procedure TWiRLDiagnosticsManager.RetrieveAppInfo(const App: string;
const ADoSomething: TProc<TWiRLDiagnosticAppInfo>);
begin
GetAppInfo(App, ADoSomething);
end;
class procedure TWiRLDiagnosticsManager.SetEngine(AEngine: TWiRLEngine);
begin
FEngine := AEngine;
end;
function TWiRLDiagnosticsManager.ToJSON: TJSONObject;
var
LObj: TJSONObject;
LPair: TPair<string, TWiRLDiagnosticAppInfo>;
LAppArray: TJSONArray;
begin
LObj := TJSONObject.Create;
FCriticalSection.Enter;
try
LObj.AddPair('engine',
TJSONObject.Create(
TJSONPair.Create(
FEngineInfo.BasePath, FEngineInfo.ToJSON
)
)
);
LAppArray := TJSONArray.Create;
for LPair in FAppDictionary do
LAppArray.Add(TJsonObject.Create(TJSONPair.Create(LPair.Key, LPair.Value.ToJSON)));
LObj.AddPair('apps', LAppArray);
finally
FCriticalSection.Leave;
end;
Result := LObj;
end;
{ TAppInfo }
procedure TWiRLDiagnosticInfo.AcquireRequest(AExecutionTimeInMilliseconds:
Integer = 0);
begin
FCriticalSection.Enter;
try
Inc(FRequestCount);
FTotalExecutionTime := FTotalExecutionTime + AExecutionTimeInMilliseconds;
FLastRequestTime := Now;
finally
FCriticalSection.Leave;
end;
end;
constructor TWiRLDiagnosticInfo.Create;
begin
inherited Create;
FRequestCount := 0;
FLastRequestTime := 0;
FCriticalSection := TCriticalSection.Create;
end;
destructor TWiRLDiagnosticInfo.Destroy;
begin
FCriticalSection.Free;
inherited;
end;
function TWiRLDiagnosticInfo.GetAverageTimePerRequest: Double;
begin
if FRequestCount = 0 then
Result := 0
else
Result := RoundTo(FTotalExecutionTime / FRequestCount, -2);
end;
function TWiRLDiagnosticInfo.ToJSON: TJSONObject;
begin
Result := TJSONObject.Create;
Result.AddPair('BasePath', BasePath);
Result.AddPair('RequestCount', TJSONNumber.Create(FRequestCount));
Result.AddPair('LastRequestTime', DateToISO8601(FLastRequestTime));
Result.AddPair('TotalExecutionTime', TJSONNumber.Create(FTotalExecutionTime));
Result.AddPair('AverageTimePerRequest', TJSONNumber.Create(AverageTimePerRequest));
end;
{ TEngineInfo }
procedure TWiRLDiagnosticEngineInfo.AcquireEndSession;
begin
FCriticalSection.Enter;
try
FLastSessionEnd := Now;
Dec(FActiveSessionCount);
finally
FCriticalSection.Leave;
end;
end;
procedure TWiRLDiagnosticEngineInfo.AcquireNewSession;
begin
FCriticalSection.Enter;
try
Inc(FSessionCount);
Inc(FActiveSessionCount);
FLastSessionStart := Now;
finally
FCriticalSection.Leave;
end;
end;
constructor TWiRLDiagnosticEngineInfo.Create;
begin
inherited Create;
FLastSessionEnd := 0;
FSessionCount := 0;
FLastSessionStart := 0;
FActiveSessionCount := 0;
end;
function TWiRLDiagnosticEngineInfo.ToJSON: TJSONObject;
begin
Result := inherited ToJSON;
Result.AddPair('SessionCount', TJSONNumber.Create(FSessionCount));
Result.AddPair('ActiveSessionCount', TJSONNumber.Create(FActiveSessionCount));
Result.AddPair('LastSessionStart', DateToISO8601(FLastSessionStart));
Result.AddPair('LastSessionEnd', DateToISO8601(FLastSessionEnd));
end;
end.
|
// Copyright 2014 Agustin Seifert
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
unit EasyAttributes.ValueAttribute;
interface
uses
Rtti;
type
TRawValueAttribute = class(TCustomAttribute)
private
FValue: TValue;
function GetRawValue: TValue;
procedure SetRawValue(const AValue: TValue);
protected
property Value: TValue read GetRawValue write SetRawValue;
end;
TValueAttribute<T> = class(TRawValueAttribute)
private
function GetValue: T;
procedure SetValue(const AValue: T);
public
constructor Create(AValue: T); reintroduce;
property Value: T read GetValue write SetValue;
end;
TBooleanAttribute = class(TValueAttribute<boolean>);
TStringAttribute = class(TValueAttribute<string>);
TInt64Attribute = class(TValueAttribute<Int64>);
TIntegerAttribute = class(TValueAttribute<integer>);
TClassAttribute = class(TValueAttribute<TClass>);
TValueAttributeHelper = class helper for TCustomAttribute
function Value: TValue; overload;
function Value<T>: T; overload;
function TryValue(out Value: TValue): boolean; overload;
function TryValue<T>(out Value: T): boolean; overload;
end;
implementation
uses
EasyAttributes.ValueAttributeReader;
{ TValueAttribute }
constructor TValueAttribute<T>.Create(AValue: T);
begin
Value := AValue;
end;
function TValueAttribute<T>.GetValue: T;
begin
Result := GetRawValue.AsType<T>;
end;
procedure TValueAttribute<T>.SetValue(const AValue: T);
begin
SetRawValue(TValue.From<T>(AValue));
end;
{ TRawValueAttribute }
function TRawValueAttribute.GetRawValue: TValue;
begin
Result := FValue;
end;
procedure TRawValueAttribute.SetRawValue(const AValue: TValue);
begin
FValue := AValue;
end;
{ TValueAttributeHelper }
function TValueAttributeHelper.TryValue(out Value: TValue): boolean;
begin
Result := TBaseAttributeReader.TryValue(Self, Value);
end;
function TValueAttributeHelper.TryValue<T>(out Value: T): boolean;
begin
Result := TBaseAttributeReader.TryValue<T>(Self, Value);
end;
function TValueAttributeHelper.Value: TValue;
begin
Result := TBaseAttributeReader.Value(Self);
end;
function TValueAttributeHelper.Value<T>: T;
begin
Result := TBaseAttributeReader.Value<T>(Self);
end;
end.
|
unit uMySQLDao;
interface
uses FireDAC.Comp.Client, System.SysUtils, uDtM, Data.DB, Vcl.Dialogs,
System.Classes;
type
TMySQLDao = Class(TObject)
private
protected
FdQry: TFDQuery;
function ReturnDataSet(SQL: String): TFDQuery;
function ExecSQL(SQL: String): Integer;
public
constructor Create;
destructor Destroy; override;
end;
implementation
{ TMySQLDao }
constructor TMySQLDao.Create;
begin
inherited Create;
FdQry := TFDQuery.Create(nil);
FdQry.Connection := DtM.FDConnection;
end;
destructor TMySQLDao.Destroy;
begin
try
if Assigned(FdQry) then
FreeAndNil(FdQry);
except
on e: exception do
raise exception.Create(e.Message);
end;
end;
function TMySQLDao.ExecSQL(SQL: String): Integer;
begin
Result := 0;
try
DtM.FDConnection.StartTransaction;
FdQry.SQL.Text := SQL;
FdQry.ExecSQL;
Result := FdQry.RowsAffected;
DtM.FDConnection.Commit;
except
DtM.FDConnection.Rollback;
end;
end;
function TMySQLDao.ReturnDataSet(SQL: String): TFDQuery;
begin
FdQry.SQL.Text := SQL;
FdQry.Active := True;
Result := FdQry;
end;
end.
|
(*
Copyright (c) 2011-2014, Stefan Glienke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of this library nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*)
unit DSharp.Core.XmlSerialization.XmlReader;
interface
uses
DSharp.Core.XmlSerialization,
Rtti,
XMLIntf;
type
TXmlReader = class(TInterfacedObject, IXmlReader)
private
fAttributeIndex: Integer;
fCurrentNode: IXMLNode;
fDocument: IXMLDocument;
fElementNode: IXMLNode;
fIndex: Integer;
fRoot: TObject;
function GetXml: string;
procedure SetXml(const Value: string);
procedure CreateObject(var value: TValue);
procedure ReadAttribute(const instance: TObject);
procedure ReadElement(const instance: TObject);
procedure ReadEnumerable(const instance: TObject);
procedure ReadEvent(var value: TValue);
procedure ReadInterface(const instance: IInterface);
procedure ReadProperty(const instance: TObject; const prop: TRttiProperty);
procedure ReadObject(const instance: TObject);
public
constructor Create; overload;
constructor Create(const filename: string); overload;
function IsStartElement: Boolean; overload;
function IsStartElement(const name: string): Boolean; overload;
function MoveToElement: Boolean;
function MoveToFirstAttribute: Boolean;
function MoveToNextAttribute: Boolean;
procedure ReadStartElement; overload;
procedure ReadStartElement(const name: string); overload;
procedure ReadEndElement; overload;
procedure ReadValue(var value: TValue);
property Xml: string read GetXml write SetXml;
end;
implementation
uses
DSharp.Core.Reflection,
SysUtils,
TypInfo,
Variants,
XMLDoc,
XSBuiltIns;
function XMLTimeToTime(const XMLTime: string): TDateTime;
begin
Result := Frac(XMLTimeToDateTime(FormatDateTime('yyyy-mm-dd''T', 0) + XMLTime));
end;
{ TXmlReader }
constructor TXmlReader.Create;
begin
inherited Create;
fDocument := TXMLDocument.Create(nil);
fDocument.Active := True;
end;
constructor TXmlReader.Create(const filename: string);
begin
Create;
if filename <> '' then
fDocument.LoadFromFile(filename);
end;
procedure TXmlReader.CreateObject(var value: TValue);
var
rttiType: TRttiType;
method: TRttiMethod;
begin
if FindType(fCurrentNode.NodeName, rttiType)
and rttiType.TryGetStandardConstructor(method) then
begin
value := method.Invoke(rttiType.AsInstance.MetaclassType, []);
if not Assigned(fRoot) then
fRoot := value.AsObject;
end;
end;
function TXmlReader.GetXml: string;
begin
Result := FormatXMLData(fDocument.XML.Text);
end;
function TXmlReader.IsStartElement: Boolean;
begin
if Assigned(fCurrentNode) then
Result := fCurrentNode.ChildNodes.Count > fIndex
else
Result := Assigned(fDocument.DocumentElement);
end;
function TXmlReader.IsStartElement(const name: string): Boolean;
begin
if Assigned(fCurrentNode) then
Result := (fCurrentNode.ChildNodes.Count > fIndex)
and SameText(fCurrentNode.ChildNodes[fIndex].NodeName, name)
else
Result := SameText(fDocument.DocumentElement.NodeName, name);
end;
function TXmlReader.MoveToElement: Boolean;
begin
Result := Assigned(fElementNode);
if Result then
begin
fAttributeIndex := -1;
fCurrentNode := fElementNode;
fElementNode := nil;
end;
end;
function TXmlReader.MoveToFirstAttribute: Boolean;
begin
Result := fCurrentNode.AttributeNodes.Count > 0;
if Result then
begin
fAttributeIndex := 0;
fElementNode := fCurrentNode;
fCurrentNode := fCurrentNode.AttributeNodes.First;
end;
end;
function TXmlReader.MoveToNextAttribute: Boolean;
begin
if not Assigned(fElementNode) then
Result := MoveToFirstAttribute
else
begin
Result := fAttributeIndex < fElementNode.AttributeNodes.Count - 1;
if Result then
begin
Inc(fAttributeIndex);
fCurrentNode := fElementNode.AttributeNodes.Nodes[fAttributeIndex];
end;
end;
end;
procedure TXmlReader.ReadAttribute(const instance: TObject);
var
prop: TRttiProperty;
attrAttribute: XmlAttributeAttribute;
begin
for prop in instance.GetProperties do
begin
if prop.TryGetCustomAttribute<XmlAttributeAttribute>(attrAttribute)
and SameText(attrAttribute.AttributeName, fCurrentNode.NodeName) then
begin
ReadProperty(instance, prop);
Break;
end;
end;
end;
procedure TXmlReader.ReadElement(const instance: TObject);
var
prop: TRttiProperty;
elemAttribute: XmlElementAttribute;
begin
for prop in instance.GetProperties do
begin
if prop.TryGetCustomAttribute<XmlElementAttribute>(elemAttribute) then
begin
if SameText(elemAttribute.ElementName, fCurrentNode.NodeName) then
begin
ReadProperty(instance, prop);
Break;
end;
Continue;
end;
if prop.IsDefined<XmlAttributeAttribute> then
Continue;
if prop.Visibility < mvPublished then
Continue;
if SameText(prop.Name, fCurrentNode.NodeName) then
begin
ReadProperty(instance, prop);
Break;
end;
end;
end;
procedure TXmlReader.ReadEndElement;
begin
fIndex := fCurrentNode.ParentNode.ChildNodes.IndexOf(fCurrentNode) + 1;
fCurrentNode := fCurrentNode.ParentNode;
end;
procedure TXmlReader.ReadEnumerable(const instance: TObject);
var
rttiType: TRttiType;
method: TRttiMethod;
value: TValue;
begin
if instance.TryGetMethod('Clear', method) then
method.Invoke(instance, []);
if instance.HasMethod('GetEnumerator')
and instance.TryGetMethod('Add', method) then
begin
rttiType := method.GetParameters[0].ParamType;
while IsStartElement(rttiType.Name)
or (rttiType.IsPublicType and IsStartElement(rttiType.QualifiedName)) do
begin
ReadStartElement;
TValue.Make(nil, rttiType.Handle, value);
ReadValue(value);
method.Invoke(instance, [value]);
ReadEndElement;
end;
end;
end;
procedure TXmlReader.ReadEvent(var value: TValue);
type
PMethod = ^TMethod;
var
event: PMethod;
method: TRttiMethod;
begin
event := value.GetReferenceToRawData;
if fRoot.TryGetMethod(VarToStrDef(fCurrentNode.NodeValue, ''), method) then
begin
event.Data := fRoot;
event.Code := method.CodeAddress;
end;
end;
procedure TXmlReader.ReadInterface(const instance: IInterface);
begin
ReadObject(instance as TObject);
end;
procedure TXmlReader.ReadObject(const instance: TObject);
begin
ReadEnumerable(instance);
if MoveToFirstAttribute then
repeat
ReadAttribute(instance);
until not MoveToNextAttribute;
MoveToElement;
while IsStartElement do
begin
ReadStartElement;
ReadElement(instance);
ReadEndElement;
end;
end;
procedure TXmlReader.ReadProperty(const instance: TObject;
const prop: TRttiProperty);
var
value: TValue;
begin
if prop.IsReadable then
value := prop.GetValue(instance);
ReadValue(value);
if prop.IsWritable and not (prop.PropertyType.IsInstance or prop.PropertyType.IsInterface) then
prop.SetValue(instance, value);
end;
procedure TXmlReader.ReadStartElement;
begin
if Assigned(fCurrentNode) then
fCurrentNode := fCurrentNode.ChildNodes[fIndex]
else
fCurrentNode := fDocument.DocumentElement;
fIndex := 0;
end;
procedure TXmlReader.ReadStartElement(const name: string);
begin
if IsStartElement(name) then
ReadStartElement
else
raise EXmlException.CreateFmt('Element "%s" not found', [name]);
end;
procedure TXmlReader.ReadValue(var value: TValue);
begin
if value.IsEmpty then
CreateObject(value);
case value.Kind of
tkInteger, tkInt64:
value := TValue.FromOrdinal(value.TypeInfo, StrToInt64(fCurrentNode.NodeValue));
tkChar, tkString, tkWChar, tkLString, tkWString, tkUString:
value := TValue.From<string>(VarToStrDef(fCurrentNode.NodeValue, ''));
tkEnumeration:
value := TValue.FromOrdinal(value.TypeInfo,
GetEnumValue(value.TypeInfo, fCurrentNode.NodeValue));
tkFloat:
begin
if value.IsDate then
value := TValue.From<TDate>(StrToDate(fCurrentNode.NodeValue, XmlFormatSettings))
else if value.IsDateTime then
value := TValue.From<TDateTime>(XMLTimeToDateTime(fCurrentNode.NodeValue))
else if value.IsTime then
value := TValue.From<TTime>(XMLTimeToTime(fCurrentNode.NodeValue))
else
value := StrToFloat(fCurrentNode.NodeValue, XmlFormatSettings);
end;
tkSet:
TValue.Make(StringToSet(value.TypeInfo, fCurrentNode.NodeValue),
value.TypeInfo, value);
tkClass:
ReadObject(value.AsObject);
tkMethod:
ReadEvent(value);
tkInterface:
ReadInterface(value.AsInterface);
end;
end;
procedure TXmlReader.SetXml(const Value: string);
begin
fDocument.XML.Text := Value;
fDocument.Active := True;
fCurrentNode := nil;
fIndex := 0;
end;
end.
|
type
BEMCheckBox.BEMCheckBox.BEMCheckBoxGroup = class(NSObject)
private
property checkBoxes: not nullable NSHashTable; public;
property selectedCheckBox: nullable BEMCheckBox.BEMCheckBox.BEMCheckBox; public;
property mustHaveSelection: BOOL; public;
[NonSwiftOnly]
class method groupWithCheckBoxes(checkBoxes: NSArray<BEMCheckBox.BEMCheckBox.BEMCheckBox>): not nullable instancetype; public;
begin
end;
[Alias]
[SwiftOnly]
class method &group(checkBoxes: NSArray<BEMCheckBox.BEMCheckBox.BEMCheckBox>): not nullable instancetype; public;
begin
end;
[InitFromClassFactoryMethod]
[Alias]
[SwiftOnly]
class constructor withCheckBoxes(checkBoxes: NSArray<BEMCheckBox.BEMCheckBox.BEMCheckBox>): not nullable instancetype; public;
begin
end;
[NonSwiftOnly]
method addCheckBoxToGroup(checkBox: not nullable BEMCheckBox.BEMCheckBox.BEMCheckBox); public;
begin
end;
[Alias]
[SwiftOnly]
method addCheckBox(checkBox: not nullable BEMCheckBox.BEMCheckBox.BEMCheckBox); public;
begin
end;
[NonSwiftOnly]
method removeCheckBoxFromGroup(checkBox: not nullable BEMCheckBox.BEMCheckBox.BEMCheckBox); public;
begin
end;
[Alias]
[SwiftOnly]
method removeCheckBox(checkBox: not nullable BEMCheckBox.BEMCheckBox.BEMCheckBox); public;
begin
end;
end;
BEMCheckBox.BEMCheckBox.BEMBoxType = enum ([NonSwiftOnly] BEMBoxTypeCircle = 0, [NonSwiftOnly] Circle = 0, [SwiftOnly] circle = 0, [NonSwiftOnly] BEMBoxTypeSquare = 1, [NonSwiftOnly] Square = 1, [SwiftOnly] square = 1);
BEMCheckBox.BEMCheckBox.BEMCheckBox = class(UIControl, ICAAnimationDelegate)
private
property &delegate: not nullable BEMCheckBox.BEMCheckBox.IBEMCheckBoxDelegate; public;
property &on: BOOL; public;
property lineWidth: CGFloat; public;
property cornerRadius: CGFloat; public;
property animationDuration: CGFloat; public;
property hideBox: BOOL; public;
property onTintColor: not nullable UIColor; public;
property onFillColor: not nullable UIColor; public;
property offFillColor: not nullable UIColor; public;
property onCheckColor: not nullable UIColor; public;
property tintColor: not nullable UIColor; public;
property &group: nullable BEMCheckBox.BEMCheckBox.BEMCheckBoxGroup; public;
property boxType: BEMCheckBox.BEMCheckBox.BEMBoxType; public;
property onAnimationType: BEMAnimationType; public;
property offAnimationType: BEMAnimationType; public;
property minimumTouchSize: CGSize; public;
method setOn(&on: BOOL) animated(animated: BOOL); public;
begin
end;
method reload; public;
begin
end;
property onFill: not nullable UIColor; public;
property offFill: not nullable UIColor; public;
property onCheck: not nullable UIColor; public;
property minimumTouch: CGSize; public;
end;
BEMAnimationType = BEMCheckBox.BEMCheckBox.__enum_BEMAnimationType;
BEMCheckBox.BEMCheckBox.__enum_BEMAnimationType = enum ([NonSwiftOnly] BEMAnimationTypeStroke = 0, [NonSwiftOnly] Stroke = 0, [SwiftOnly] stroke = 0, [NonSwiftOnly] BEMAnimationTypeFill = 1, [NonSwiftOnly] Fill = 1, [SwiftOnly] fill = 1, [NonSwiftOnly] BEMAnimationTypeBounce = 2, [NonSwiftOnly] Bounce = 2, [SwiftOnly] bounce = 2, [NonSwiftOnly] BEMAnimationTypeFlat = 3, [NonSwiftOnly] Flat = 3, [SwiftOnly] flat = 3, [NonSwiftOnly] BEMAnimationTypeOneStroke = 4, [NonSwiftOnly] OneStroke = 4, [SwiftOnly] oneStroke = 4, [NonSwiftOnly] BEMAnimationTypeFade = 5, [NonSwiftOnly] Fade = 5, [SwiftOnly] fade = 5);
BEMCheckBox.BEMCheckBox.IBEMCheckBoxDelegate = interface(INSObject)
[NonSwiftOnly]
method didTapCheckBox(checkBox: not nullable BEMCheckBox.BEMCheckBox.BEMCheckBox); public;
[Alias]
[SwiftOnly]
method didTap(checkBox: not nullable BEMCheckBox.BEMCheckBox.BEMCheckBox); public;
[NonSwiftOnly]
method animationDidStopForCheckBox(checkBox: not nullable BEMCheckBox.BEMCheckBox.BEMCheckBox); public;
[Alias]
[SwiftOnly]
method animationDidStop(checkBox: not nullable BEMCheckBox.BEMCheckBox.BEMCheckBox); public;
end;
BEMCheckBoxDelegate = BEMCheckBox.BEMCheckBox.IBEMCheckBoxDelegate;
end.
|
unit Example1;
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
TFormExample1 = class(TForm)
ButtonReader: TButton;
Memo1: TMemo;
Path: TLabeledEdit;
procedure ButtonReaderClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormExample1: TFormExample1;
implementation
{$R *.dfm}
uses ofxreader;
procedure TFormExample1.ButtonReaderClick(Sender: TObject);
var OFXReader1: TOFXReader;
i: Integer;
begin
try
OFXReader1 := TOFXReader.Create(nil);
OFXReader1.OFXFile := Path.Text;
try
OFXReader1.Import;
except on E: Exception do
raise Exception.Create('Error Message: ' + E.Message);
end;
Memo1.Clear;
Memo1.Lines.Add('Bank: ' + OFXReader1.BankID);
Memo1.Lines.Add('Branch: ' + OFXReader1.BranchID);
Memo1.Lines.Add('Account: ' + OFXReader1.AccountID);
Memo1.Lines.Add('----------------');
Memo1.Lines.Add('# | '+
'Transaction identify | ' +
'Document | ' +
'Date | ' +
'Type | '+
'Value | '+
'Description ');
Memo1.Lines.Add('----------------');
for i := 0 to OFXReader1.Count-1 do
begin
Memo1.Lines.Add(IntToStr(i) + ' ' +
OFXReader1.Get(i).ID + ' ' +
OFXReader1.Get(i).Document + ' ' +
DateToStr(OFXReader1.Get(i).MovDate) + ' ' +
OFXReader1.Get(i).MovType + ' ' +
OFXReader1.Get(i).Value + ' ' +
OFXReader1.Get(i).Description);
end;
Memo1.Lines.Add('----------------');
Memo1.Lines.Add('Final balance: ' + OFXReader1.FinalBalance);
finally
FreeAndNil(OFXReader1);
end;
end;
end.
|
unit DatePrecision;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
TDatePrecision = (dpUnknown, dpHour, dpDay, dpMonth, dpQuarter, dpHalf, dpYear);
var
TDatePrecisionCodeSync_Code_0: string = 'unknown';
TDatePrecisionCodeSync_Code_1: string = 'hour';
TDatePrecisionCodeSync_Code_2: string = 'day';
TDatePrecisionCodeSync_Code_3: string = 'month';
TDatePrecisionCodeSync_Code_4: string = 'quarter';
TDatePrecisionCodeSync_Code_5: string = 'half';
TDatePrecisionCodeSync_Code_6: string = 'year';
function CodeToDatePrecision(AValue: string): TDatePrecision;
function DatePrecisionToCode(AValue: TDatePrecision): string;
implementation
uses
Variants;
function CodeToDatePrecision(AValue: string): TDatePrecision;
begin
if SameText(TDatePrecisionCodeSync_Code_0, AValue) then begin
Result := dpUnknown;
end else if SameText(TDatePrecisionCodeSync_Code_1, AValue) then begin
Result := dpHour;
end else if SameText(TDatePrecisionCodeSync_Code_2, AValue) then begin
Result := dpDay;
end else if SameText(TDatePrecisionCodeSync_Code_3, AValue) then begin
Result := dpMonth;
end else if SameText(TDatePrecisionCodeSync_Code_4, AValue) then begin
Result := dpQuarter;
end else if SameText(TDatePrecisionCodeSync_Code_5, AValue) then begin
Result := dpHalf;
end else if SameText(TDatePrecisionCodeSync_Code_6, AValue) then begin
Result := dpYear;
end else
raise Exception.CreateFmt(
'CodeToDatePrecision(AValue: string): Unable to find valid DatePrecision for Code, [%s]',
[VarToStr(AValue)]);
end;
function DatePrecisionToCode(AValue: TDatePrecision): string;
begin
case AValue of
dpUnknown:
Result := TDatePrecisionCodeSync_Code_0;
dpHour:
Result := TDatePrecisionCodeSync_Code_1;
dpDay:
Result := TDatePrecisionCodeSync_Code_2;
dpMonth:
Result := TDatePrecisionCodeSync_Code_3;
dpQuarter:
Result := TDatePrecisionCodeSync_Code_4;
dpHalf:
Result := TDatePrecisionCodeSync_Code_5;
dpYear:
Result := TDatePrecisionCodeSync_Code_6;
end;
end;
end.
|
program StringGridTest;
{$mode objfpc}{$H+}
uses
SysUtils,
MUIClass.Base,
MUIClass.Window,
MUIClass.StringGrid,
MUIClass.Gadget,
MUIClass.Group,
MUIClass.Area;
type
// My Window (mainly because we need the Event attached to an Object)
TMyWindow = class(TMUIWindow)
procedure ButtonClick(Sender: TObject);
procedure ListClick(Sender: TObject);
procedure SetSizeClick(Sender: TObject);
procedure SetClick(Sender: TObject);
end;
var
Win: TMyWindow; // Window
HeadGroup, FootGroup: TMUIGroup;
SetCols, SetRows, WCols, WRows, WText: TMUIString;
SG: TMUIStringGrid; // A StringGrid
// Event called, when Button is pressed
procedure TMyWindow.SetSizeClick(Sender: TObject);
begin
SG.Quiet := True;
SG.NumColumns := SetCols.IntegerValue;
SG.NumRows := SetRows.IntegerValue;
SG.Quiet := False;
end;
procedure TMyWindow.ButtonClick(Sender: TObject);
var
x,y: Integer;
begin
SG.Quiet := True;
for y := 0 to SG.NumRows - 1 do
begin
for x := 0 to SG.NumColumns - 1 do
SG.Cells[x, y] := IntToStr(x) +' ; ' + IntToStr(y);
end;
SG.Quiet := False;
end;
procedure TMyWindow.SetClick(Sender: TObject);
begin
SG.Cells[WCols.IntegerValue, WRows.IntegerValue] := WText.Contents;
end;
procedure TMyWindow.ListClick(Sender: TObject);
begin
WCols.IntegerValue := SG.ClickColumn;
WRows.IntegerValue := SG.Row;
WText.Contents := SG.Cells[SG.ClickColumn, SG.Row];
end;
begin
// Create a Window, with a title bar text
Win := TMyWindow.Create;
Win.Title := 'Test Window';
HeadGroup := TMUIGroup.Create;
HeadGroup.Horiz := True;
HeadGroup.Parent := Win;
SetCols := TMUIString.Create;
SetCols.Accept := '0123456789';
SetCols.IntegerValue := 3;
SetCols.Parent := HeadGroup;
SetRows := TMUIString.Create;
SetRows.Accept := '0123456789';
SetRows.IntegerValue := 5;
SetRows.Parent := HeadGroup;
With TMUIButton.Create('Set Grid Size') do
begin
OnClick := @Win.SetSizeClick;
Parent := HeadGroup;
end;
SG := TMUIStringGrid.Create;
SG.NumColumns := 3;
SG.NumRows := 5;
SG.ShowLines := True;
SG.ShowTitle := True;
SG.Cells[0,2] := 'Test 0,2';
SG.Cells[1,4] := 'Test 1,4';
SG.Cells[2,0] := 'Test 2,0';
SG.Titles[0] := 'Title 1';
SG.Titles[1] := 'Title a';
SG.Titles[2] := 'Title %';
{$ifdef AROS}
SG.OnDoubleClick := @Win.ListClick;
{$else}
SG.OnClick := @Win.ListClick;
{$endif}
SG.Parent := Win;
FootGroup := TMUIGroup.Create;
FootGroup.Horiz := True;
FootGroup.Parent := Win;
WCols := TMUIString.Create;
WCols.Accept := '0123456789';
WCols.IntegerValue := 0;
WCols.Parent := FootGroup;
WRows := TMUIString.Create;
WRows.Accept := '0123456789';
WRows.IntegerValue := 0;
WRows.Parent := FootGroup;
WText := TMUIString.Create;
WText.Parent := FootGroup;
with TMUIButton.Create('Set') do
begin
OnClick := @Win.SetClick;
Parent := FootGroup;
end;
// Create a Button with some text
with TMUIButton.Create('Fill all') do
begin
OnClick := @Win.ButtonClick; // Connect the Click Event
Parent := FootGroup; // Insert Button in the Window
end;
// will actually start everything,
// Create MUI object, connect them together
// from the Parent relation we builded with Pascal Classes
// Open the Window and run the Message Loop
// destroy everything after the Window is closed again.
MUIApp.Run;
end.
|
unit main;
interface
uses
Windows, Messages;
function ImgLoadFromRes(Wnd:HWND; Memory:Pointer; Size: Integer; Left,Top:integer;Width,Height:Cardinal; Stretch,IsBkg:boolean):Longint; stdcall;
function ImgLoad(Wnd:HWND; FileName:PChar; Left,Top:integer;Width,Height:Cardinal; Stretch,IsBkg:boolean):Longint; stdcall;
procedure ImgSetPosition(img:Longint; NewLeft, NewTop, NewWidth, NewHeight:integer); stdcall;
procedure ImgGetPosition(img:Longint; var Left, Top, Width, Height:integer); stdcall;
procedure ImgSetVisiblePart(img:Longint; NewLeft, NewTop, NewWidth, NewHeight : integer); stdcall;
procedure ImgGetVisiblePart(img:Longint; var Left, Top, Width, Height : integer); stdcall;
procedure ImgSetTransparent(img:Longint; Value:integer); stdcall;
function ImgGetTransparent(img:Longint):integer; stdcall;
procedure ImgRelease(img:Longint); stdcall;
procedure ImgSetVisibility(img:Longint; Visible:boolean); stdcall;
function ImgGetVisibility(img:Longint):boolean; stdcall;
procedure ImgApplyChanges(h:HWND); stdcall;
procedure CreateFormFromImage(h:HWND; FileName:PChar); stdcall;
procedure SetMinimizeAnimation(Value: Boolean); stdcall;
function GetMinimizeAnimation: Boolean; stdcall;
function WndProc(Wnd : HWND; Msg : UINT; wParam : Integer; lParam: Integer):Longint; stdcall;
procedure DestroyImages;
implementation
uses
for_png, addfunc;
procedure SetMinimizeAnimation(Value: Boolean); stdcall;
var
Info: TAnimationInfo;
begin
Info.cbSize := SizeOf(Info);
Info.iMinAnimate := integer(Value);
SystemParametersInfo(SPI_SETANIMATION, SizeOf(Info), @Info, 0);
end;
function GetMinimizeAnimation: Boolean; stdcall;
var
Info: TAnimationInfo;
begin
Info.cbSize := SizeOf(TAnimationInfo);
if SystemParametersInfo(SPI_GETANIMATION, SizeOf(Info), @Info, 0) then
Result := Info.iMinAnimate <> 0 else
Result := False;
end;
procedure ImgApplyChanges(h:HWND); stdcall;
var
k:integer;
r:TRect;
begin
k:=GetWndInd(h);
if k=-1 then Exit;
if IsRectEmpty(AWnd[k].UpdateBkgRect) and IsRectEmpty(AWnd[k].UpdateRect) then Exit;
UnionRect(r,AWnd[k].UpdateBkgRect,AWnd[k].UpdateRect);
if not IsRectEmpty(AWnd[k].UpdateRect) then begin
SetFullImage(k,False,@AWnd[k].UpdateRect);
SetRectEmpty(AWnd[k].UpdateRect);
end;
if not IsRectEmpty(AWnd[k].UpdateBkgRect) then begin
SetFullImage(k,True,@AWnd[k].UpdateBkgRect);
SetRectEmpty(AWnd[k].UpdateBkgRect);
end;
// DrawFormToDCMem(k,@r);
// EnumChildWindows(h,@RefreshChildWnd,Longint(@r));
AWnd[k].RefreshBtn:=True;
InvalidateRect(h,@r,False);
UpdateWindow(h);
end;
function WndProc(Wnd : HWND; Msg : UINT; wParam : Integer; lParam: Integer):Longint; stdcall;
var
k:integer;
r:TRect;
DC:HDC;
ps:TPaintStruct;
begin
k:=GetWndInd(Wnd);
if k=-1 then begin
Result:=CallWindowProc(Pointer(GetWindowLong(Wnd,GWL_WNDPROC)),Wnd,Msg,wParam,lParam);
Exit;
end;
case Msg of
WM_ERASEBKGND: {if Longint(AWnd[k].hDCMem)=wParam then Result:=CallWindowProc(Pointer(AWnd[k].OldProc),Wnd,Msg,wParam,lParam) else} Result:=1;
WM_PAINT: begin
Result:=0;
if (HDC(wParam)=0) then begin
DC:=BeginPaint(Wnd,ps);
//if not AWnd[k].RefreshBtn then DrawFormToDCMem(k,@ps.rcPaint) else AWnd[k].RefreshBtn:=False;
DrawFormToDCMem(k,@ps.rcPaint);
if AWnd[k].RefreshBtn then begin
EnumChildWindows(Wnd,@RefreshChildWnd,Longint(@ps.rcPaint));
AWnd[k].RefreshBtn:=False;
end;
BitBlt(DC,ps.rcPaint.Left,ps.rcPaint.Top,ps.rcPaint.Right-ps.rcPaint.Left,ps.rcPaint.Bottom-ps.rcPaint.Top,AWnd[k].hDCMem,ps.rcPaint.Left,ps.rcPaint.Top,SRCCOPY);
EndPaint(Wnd,ps);
end else begin
GetClientRect(Wnd,r);
BitBlt(HDC(wParam),0,0,r.Right,r.Bottom,AWnd[k].hDCMem,0,0,SRCCOPY);
end;
end;
WM_DESTROY: begin
while AWnd[k].PLastImg<>nil do DeleteImage(k,AWnd[k].PLastImg);
DeleteWnd(k);
Result:=CallWindowProc(Pointer(GetWindowLong(Wnd,GWL_WNDPROC)),Wnd,Msg,wParam,lParam);
end;
else Result:=CallWindowProc(Pointer(AWnd[k].OldProc),Wnd,Msg,wParam,lParam);
end;
end;
function ImgGetVisibility(img:Longint):boolean; stdcall;
var
cimg:PImg;
begin
Result:=False;
cimg:=GetImg(img);
if cimg=nil then Exit;
Result:=cimg^.Visible;
end;
procedure ImgSetVisibility(img:Longint; Visible:boolean); stdcall;
var
wr,r:TRect;
cimg:PImg;
begin
cimg:=GetImg(img);
if cimg=nil then Exit;
if Visible<>cimg^.Visible then begin
cimg^.Visible:=Visible;
SetRect(r,cimg^.Left,cimg^.Top,cimg^.Left+integer(cimg^.Width),cimg^.Top+integer(cimg^.Height));
GetClientRect(AWnd[cimg^.WndInd].Wnd,wr);
if cimg^.IsBkg then begin
UnionRect(AWnd[cimg^.WndInd].UpdateBkgRect,AWnd[cimg^.WndInd].UpdateBkgRect,r);
IntersectRect(AWnd[cimg^.WndInd].UpdateBkgRect,wr,AWnd[cimg^.WndInd].UpdateBkgRect);
end else begin
UnionRect(AWnd[cimg^.WndInd].UpdateRect,AWnd[cimg^.WndInd].UpdateRect,r);
IntersectRect(AWnd[cimg^.WndInd].UpdateRect,wr,AWnd[cimg^.WndInd].UpdateRect);
end;
end;
end;
procedure ImgRelease(img:Longint); stdcall;
var
wndind:integer;
h:HWND;
wr,r:TRect;
IsBkg:boolean;
cimg:PImg;
begin
cimg:=GetImg(img);
if cimg=nil then Exit;
wndind:=cimg^.WndInd;
IsBkg:=cimg^.IsBkg;
SetRect(r,cimg^.Left,cimg^.Top,cimg^.Left+integer(cimg^.Width),cimg^.Top+integer(cimg^.Height));
DeleteImage(wndind,cimg);
if AWnd[wndind].PFirstImg=nil then begin
h:=AWnd[wndind].Wnd;
DeleteWnd(wndind);
EnumChildWindows(h,@RefreshChildWnd,Longint(@r));
InvalidateRect(h,@r,True);
UpdateWindow(h);
end else begin
GetClientRect(AWnd[wndind].Wnd,wr);
if IsBkg then begin
UnionRect(AWnd[wndind].UpdateBkgRect,AWnd[wndind].UpdateBkgRect,r);
IntersectRect(AWnd[wndind].UpdateBkgRect,wr,AWnd[wndind].UpdateBkgRect);
end else begin
UnionRect(AWnd[wndind].UpdateRect,AWnd[wndind].UpdateRect,r);
IntersectRect(AWnd[wndind].UpdateRect,wr,AWnd[wndind].UpdateRect);
end;
end;
end;
procedure ImgGetVisiblePart(img:Longint; var Left, Top, Width, Height : integer); stdcall;
var
cimg:PImg;
begin
cimg:=GetImg(img);
if cimg=nil then Exit;
Left:=cimg^.VisibleRect.Left;
Top:=cimg^.VisibleRect.Top;
Width:=cimg^.VisibleRect.Right;
Height:=cimg^.VisibleRect.Bottom;
end;
procedure ImgSetVisiblePart(img:Longint; NewLeft, NewTop, NewWidth, NewHeight : integer); stdcall;
var
cimg:PImg;
wr,r:TRect;
begin
cimg:=GetImg(img);
if cimg=nil then Exit;
SetRect(cimg^.VisibleRect,NewLeft,NewTop,NewWidth,NewHeight);
SetRect(r,cimg^.Left,cimg^.Top,cimg^.Left+integer(cimg^.Width),cimg^.Top+integer(cimg^.Height));
GetClientRect(AWnd[cimg^.WndInd].Wnd,wr);
if cimg^.IsBkg then begin
UnionRect(AWnd[cimg^.WndInd].UpdateBkgRect,AWnd[cimg^.WndInd].UpdateBkgRect,r);
IntersectRect(AWnd[cimg^.WndInd].UpdateBkgRect,AWnd[cimg^.WndInd].UpdateBkgRect,wr);
end else begin
UnionRect(AWnd[cimg^.WndInd].UpdateRect,AWnd[cimg^.WndInd].UpdateRect,r);
IntersectRect(AWnd[cimg^.WndInd].UpdateRect,AWnd[cimg^.WndInd].UpdateRect,wr);
end;
end;
procedure ImgGetPosition(img:Longint; var Left, Top, Width, Height:integer); stdcall;
var
cimg:PImg;
begin
cimg:=GetImg(img);
if cimg=nil then Exit;
Left:=cimg^.Left;
Top:=cimg^.Top;
Width:=cimg^.Width;
Height:=cimg^.Height;
end;
procedure ImgSetPosition(img:Longint; NewLeft, NewTop, NewWidth, NewHeight:integer); stdcall;
var
wr,r,r2:TRect;
cimg:PImg;
begin
cimg:=GetImg(img);
if cimg=nil then Exit;
SetRect(r,cimg^.Left,cimg^.Top,cimg^.Left+integer(cimg^.Width),cimg^.Top+integer(cimg^.Height));
cimg^.Left:=NewLeft;
cimg^.Top:=NewTop;
if cimg^.Stretch then begin
cimg^.Width:=NewWidth;
cimg^.Height:=NewHeight;
end;
SetRect(r2,cimg^.Left,cimg^.Top,cimg^.Left+integer(cimg^.Width),cimg^.Top+integer(cimg^.Height));
GetClientRect(AWnd[cimg^.WndInd].Wnd,wr);
if cimg^.IsBkg then begin
UnionRect(AWnd[cimg^.WndInd].UpdateBkgRect,AWnd[cimg^.WndInd].UpdateBkgRect,r);
UnionRect(AWnd[cimg^.WndInd].UpdateBkgRect,AWnd[cimg^.WndInd].UpdateBkgRect,r2);
IntersectRect(AWnd[cimg^.WndInd].UpdateBkgRect,AWnd[cimg^.WndInd].UpdateBkgRect,wr);
end else begin
UnionRect(AWnd[cimg^.WndInd].UpdateRect,AWnd[cimg^.WndInd].UpdateRect,r);
UnionRect(AWnd[cimg^.WndInd].UpdateRect,AWnd[cimg^.WndInd].UpdateRect,r2);
IntersectRect(AWnd[cimg^.WndInd].UpdateRect,AWnd[cimg^.WndInd].UpdateRect,wr);
end;
end;
procedure ImgSetTransparent(img:Longint; Value:integer); stdcall;
var
cimg:PImg;
wr,r:TRect;
begin
cimg:=GetImg(img);
if cimg=nil then Exit;
if Value<0 then Value:=0;
if Value>255 then Value:=255;
if cimg^.Transparent<>Value then begin
cimg^.Transparent:=Value;
SetRect(r,cimg^.Left,cimg^.Top,cimg^.Left+integer(cimg^.Width),cimg^.Top+integer(cimg^.Height));
GetClientRect(AWnd[cimg^.WndInd].Wnd,wr);
if cimg^.IsBkg then begin
UnionRect(AWnd[cimg^.WndInd].UpdateBkgRect,AWnd[cimg^.WndInd].UpdateBkgRect,r);
IntersectRect(AWnd[cimg^.WndInd].UpdateBkgRect,AWnd[cimg^.WndInd].UpdateBkgRect,wr);
end else begin
UnionRect(AWnd[cimg^.WndInd].UpdateRect,AWnd[cimg^.WndInd].UpdateRect,r);
IntersectRect(AWnd[cimg^.WndInd].UpdateRect,AWnd[cimg^.WndInd].UpdateRect,wr);
end;
end;
end;
function ImgGetTransparent(img:Longint):integer; stdcall;
var
cimg:PImg;
begin
Result:=-1;
cimg:=GetImg(img);
if cimg=nil then Exit;
Result:=cimg^.Transparent;
end;
function ImgLoadFromRes(Wnd:HWND; Memory:Pointer; Size: Integer; Left,Top:integer;Width,Height:Cardinal; Stretch,IsBkg:boolean):Longint; stdcall;
var
k:integer;
r:TRect;
cimg:PImg;
begin
Result:=0;
if not gdipStart then Exit;
k:=GetWndInd(Wnd);
if k=-1 then k:=AddWnd(Wnd);
cimg:=AddImageFromRes(k,Memory,Size,Left,Top,Width,Height,Stretch,IsBkg);
if cimg<>nil then begin
Result:=Longint(cimg);
SetRect(r,Left,Top,Left+integer(cimg^.Width),Top+integer(cimg^.Height));
if IsBkg then UnionRect(AWnd[k].UpdateBkgRect,AWnd[k].UpdateBkgRect,r)
else UnionRect(AWnd[k].UpdateRect,AWnd[k].UpdateRect,r);
end;
end;
function ImgLoad(Wnd:HWND; FileName:PChar; Left,Top:integer;Width,Height:Cardinal; Stretch,IsBkg:boolean):Longint; stdcall;
var
k:integer;
r:TRect;
cimg:PImg;
begin
Result:=0;
if not gdipStart then Exit;
k:=GetWndInd(Wnd);
if k=-1 then k:=AddWnd(Wnd);
cimg:=AddImage(k,FileName,Left,Top,Width,Height,Stretch,IsBkg);
if cimg<>nil then begin
Result:=Longint(cimg);
SetRect(r,Left,Top,Left+integer(cimg^.Width),Top+integer(cimg^.Height));
if IsBkg then UnionRect(AWnd[k].UpdateBkgRect,AWnd[k].UpdateBkgRect,r)
else UnionRect(AWnd[k].UpdateRect,AWnd[k].UpdateRect,r);
end;
end;
procedure DestroyImages;
begin
while Length(AWnd)>0 do begin
while AWnd[High(AWnd)].PLastImg<>nil do DeleteImage(High(AWnd),AWnd[High(AWnd)].PLastImg);
DeleteWnd(High(AWnd));
end;
end;
procedure CreateFormFromImage(h:HWND; FileName:PChar); stdcall;
type
TGPImage = packed record
Height,
Width :Cardinal;
Graphics,
Image :Pointer;
mDC,
DC :HDC;
tempBitmap :BITMAPINFO;
mainBitmap,
oldBitmap :HBITMAP;
end;
var
gpImg : TGPImage;
pvBits : Pointer;
winSize : Size;
srcPoint : TPoint;
BF : BLENDFUNCTION;
ns : integer;
rt : TREct;
deskw,
deskh,
fLeft,
fTop : integer;
begin
if not gdipStart then Exit;
gpImg.Image:=nil;
GdipLoadImageFromFile(StringToPWideChar(FileName,ns),gpImg.Image);
GdipGetImageHeight(gpImg.Image,gpImg.Height);
GdipGetImageWidth(gpImg.Image,gpImg.Width);
SystemParametersInfo(SPI_GETWORKAREA,0,@rt,0);
deskw:=rt.Right-rt.Left;
deskh:=rt.Bottom-rt.Top;
fLeft:=(deskw div 2)-(integer(gpImg.Width) div 2);
fTop:=(deskh div 2)-(integer(gpImg.Height) div 2);
MoveWindow(h,fLeft,fTop,gpImg.Width,gpImg.Height,False);
SetWindowLong(h,GWL_EXSTYLE,GetWindowLong(h,GWL_EXSTYLE) or WS_EX_LAYERED);
gpImg.DC:=GetDC(h);
gpImg.mDC:=CreateCompatibleDC(gpImg.DC);
ZeroMemory(@gpImg.tempBitmap, SizeOf(BITMAPINFO));
with gpImg.tempBitmap.bmiHeader do begin
biSize:=SizeOf(BITMAPINFOHEADER);
biBitCount:=32;
biWidth:=gpImg.Width;
biHeight:=gpImg.Height;
biPlanes:=1;
biCompression:=BI_RGB;
biSizeImage:=biWidth * biHeight * (biBitCount div 8);
end;
gpImg.mainBitmap:=CreateDIBSection(gpImg.mDC,gpImg.tempBitmap,DIB_RGB_COLORS,pvBits,0,0);
gpImg.oldBitmap:=SelectObject(gpImg.mDC,gpImg.mainBitmap);
GdipCreateFromHDC(gpImg.mDC,gpImg.Graphics);
GdipDrawImageRectI(gpImg.Graphics,gpImg.Image,0,0,gpImg.Width,gpImg.Height);
srcPoint.X:=0;
srcPoint.Y:=0;
winSize.cx:=gpImg.Width;
winSize.cy:=gpImg.Height;
with BF do begin
AlphaFormat:=AC_SRC_ALPHA;
BlendFlags:=0;
BlendOp:=AC_SRC_OVER;
SourceConstantAlpha:=255;
end;
UpdateLayeredWindow(h, gpImg.DC, nil, @winSize, gpImg.mDC, @srcPoint, 0, @BF, ULW_ALPHA);
GdipDisposeImage(gpImg.Image);
GdipDeleteGraphics(gpImg.Graphics);
SelectObject(gpImg.mDC, gpImg.oldBitmap);
DeleteObject(gpImg.mainBitmap);
DeleteObject(gpImg.oldBitmap);
DeleteDC(gpImg.mDC);
ReleaseDC(h,gpImg.DC);
end;
end.
|
Program TestObjects;
CONSTANT
a = 7;
b = 8;
Type
DrawingObject = Object
x, y : INTEGER;
height, width : INTEGER; // replaced 'single' by 'integer' for now
end;
Var
Rectangle : DrawingObject;
x, y : INTEGER;
FUNCTION MyFunc(o1: DrawingObject; size: INTEGER; temp: INTEGER;): INTEGER;
VAR
MyFunc : INTEGER;
yo : INTEGER;
BEGIN
yo := o1.x;
yo := yo + o1.y;
// yo should be 11
WRITELN(yo);
MyFunc := temp + size - 8;
END;
begin
Rectangle.x:= 50; // the fields specific to the variable "Rectangle"
Rectangle.y:= 100;
y := MyFunc(Rectangle, a, b);
WRITELN(y);
end;
|
unit XDOM;
// Modified By HYL For Supporting GB Encoding
// XDOM 2.2.7
// Extended Document Object Model 2.2.7
// Delphi 3 Implementation
//
// Copyright (c) 2000 by Dieter Köhler
// ("http://www.philo.de/homepage.htm")
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
interface
uses
Math, SysUtils, Classes;
type
EDomException = class(Exception);
EIndex_Size_Err = class(EdomException);
EDomstring_Size_Err = class(EdomException);
EHierarchy_Request_Err = class(EdomException);
EWrong_Document_Err = class(EdomException);
EInvalid_Character_Err = class(EdomException);
ENo_Data_Allowed_Err = class(EdomException);
ENo_Modification_Allowed_Err = class(EdomException);
ENot_Found_Err = class(EdomException);
ENot_Supported_Err = class(EdomException);
EInuse_Attribute_Err = class(EdomException);
EInvalid_State_Err = class(EdomException);
ESyntax_Err = class(EdomException);
EInvalid_Modification_Err = class(EdomException);
ENamespace_Err = class(EdomException);
EInvalid_Access_Err = class(EdomException);
EInuse_Node_Err = class(EdomException);
EInuse_AttributeDefinition_Err = class(EdomException);
ENo_External_Entity_Allowed_Err = class(EdomException);
EIllegal_Entity_Reference_Err = class(EdomException);
EUnknown_Document_Format_Err = class(EdomException);
EParserException = class(Exception);
EParserMissingWhiteSpace_Err = class(EParserException);
EParserMissingQuotationMark_Err = class(EParserException);
EParserMissingEqualitySign_Err = class(EParserException);
EParserDoubleEqualitySign_Err = class(EParserException);
EParserInvalidElementName_Err = class(EParserException);
EParserInvalidAttributeName_Err = class(EParserException);
EParserInvalidAttributeValue_Err = class(EParserException);
EParserDoubleAttributeName_Err = class(EParserException);
EParserInvalidEntityName_Err = class(EParserException);
EParserInvalidProcessingInstruction_Err = class(EParserException);
EParserInvalidXmlDeclaration_Err = class(EParserException);
EParserInvalidCharRef_Err = class(EParserException);
EParserMissingStartTag_Err = class(EParserException);
EParserInvalidEndTag_Err = class(EParserException);
EParserInvalidCharacter_Err = class(EParserException);
EParserNotInRoot_Err = class(EParserException);
EParserDoubleRootElement_Err = class(EParserException);
EParserRootNotFound_Err = class(EParserException);
EParserWrongOrder_Err = class(EParserException);
EParserInvalidDoctype_Err = class(EParserException);
EParserInvalidTextDeclaration_Err = class(EParserException);
EParserDoubleDoctype_Err = class(EParserInvalidDoctype_Err);
EParserInvalidEntityDeclaration_Err = class(EParserInvalidDoctype_Err);
EParserInvalidElementDeclaration_Err = class(EParserInvalidDoctype_Err);
EParserInvalidAttributeDeclaration_Err = class(EParserInvalidDoctype_Err);
EParserInvalidNotationDeclaration_Err = class(EParserInvalidDoctype_Err);
EParserInvalidConditionalSection_Err = class(EParserInvalidDoctype_Err);
const
XmlStrError1En = 'ERROR in line %d';
XmlStrError1De = 'FEHLER in Zeile %d';
XmlStrError2En = 'ERROR in line %d-%d';
XmlStrError2De = 'FEHLER in Zeile %d-%d';
XmlStrFatalError1En = 'FATAL ERROR in line %d';
XmlStrFatalError1De = 'KRITISCHER FEHLER in Zeile %d';
XmlStrFatalError2En = 'FATAL ERROR in line %d-%d';
XmlStrFatalError2De = 'KRITISCHER FEHLER in Zeile %d-%d';
XmlStrErrorDefaultEn = 'Invalid source-code';
XmlStrErrorDefaultDe = 'Ungültiger Quellcode';
XmlStrInvalidElementNameEn = 'Invalid element name';
XmlStrInvalidElementNameDe = 'Ungültiger Element-Name';
XmlStrDoubleRootElementEn ='Double root element';
XmlStrDoubleRootElementDe ='Doppeltes Wurzel-Element';
XmlStrRootNotFoundEn ='Declared root element not found';
XmlStrRootNotFoundDe ='Deklariertes Wurzel-Element nicht gefunden';
XmlStrDoubleDoctypeEn ='Double document type declaration';
XmlStrDoubleDoctypeDe ='Doppelte Dokument-Typ-Deklaration';
XmlStrInvalidAttributeNameEn = 'Invalid attribute name';
XmlStrInvalidAttributeNameDe = 'Ungültiger Attribut-Name';
XmlStrInvalidAttributeValueEn = 'Invalid attribute value';
XmlStrInvalidAttributeValueDe = 'Ungültiger Attribut-Wert';
XmlStrDoubleAttributeNameEn = 'Double attributename in one element';
XmlStrDoubleAttributeNameDe = 'Doppelter Attributname in einem Element';
XmlStrInvalidEntityNameEn = 'Invalid entity name';
XmlStrInvalidEntityNameDe = 'Ungültiger Entity-Name';
XmlStrInvalidProcessingInstructionEn = 'Invalid processing instruction target';
XmlStrInvalidProcessingInstructionDe = 'Ungültiges Processing-Instruction-Ziel';
XmlStrInvalidXmlDeclarationEn = 'Invalid XML declaration';
XmlStrInvalidXmlDeclarationDe = 'Ungültige XML-Deklaration';
XmlStrInvalidCharRefEn = 'Invalid character reference';
XmlStrInvalidCharRefDe = 'Ungültige Zeichen-Referenz';
XmlStrMissingQuotationmarksEn = 'Missing quotation marks';
XmlStrMissingQuotationmarksDe = 'Fehlende Anführungszeichen';
XmlStrMissingEqualitySignEn = 'Missing equality sign';
XmlStrMissingEqualitySignDe = 'Fehlendes Gleichheitszeichen';
XmlStrDoubleEqualitySignEn = 'Double equality sign';
XmlStrDoubleEqualitySignDe = 'Doppeltes Gleichheitszeichen';
XmlStrMissingWhiteSpaceEn = 'Missing white-space';
XmlStrMissingWhiteSpaceDe = 'Fehlender Leerraum';
XmlStrMissingStartTagEn = 'End-tag without start-tag';
XmlStrMissingStartTagDe = 'End-Tag ohne Start-Tag';
XmlStrInvalidEndTagEn = 'Invalid end-tag';
XmlStrInvalidEndTagDe = 'Ungültiges End-Tag';
XmlStrInvalidCharacterEn = 'Invalid character';
XmlStrInvalidCharacterDe = 'Ungültiges Zeichen';
XmlStrNotInRootEn = 'Character(s) outside the root-element';
XmlStrNotInRootDe = 'Zeichen außerhalb des Wurzel-Elements';
XmlStrInvalidDoctypeEn = 'Invalid doctype declaration';
XmlStrInvalidDoctypeDe = 'Ungültige Dokumenttyp-Deklaration';
xmlStrWrongOrderEn = 'Wrong order';
xmlStrWrongOrderDe = 'Falsche Reihenfolge';
xmlStrInvalidEntityDeclarationEn = 'Invalid entity declaration';
xmlStrInvalidEntityDeclarationDe = 'Ungültige Entity-Deklaration';
xmlStrInvalidElementDeclarationEn = 'Invalid element declaration';
xmlStrInvalidElementDeclarationDe = 'Ungültige Element-Deklaration';
XmlStrInvalidAttributeDeclarationEn = 'Invalid attribute declaration';
XmlStrInvalidAttributeDeclarationDe = 'Ungültige Attribut-Deklaration';
XmlStrInvalidNotationDeclarationEn = 'Invalid notation declaration';
XmlStrInvalidNotationDeclarationDe = 'Ungültige Notations-Deklaration';
XmlStrInvalidConditionalSectionEn = 'Invalid conditional section';
XmlStrInvalidConditionalSectionDe = 'Ungültiger bedingter Abschnitt';
XmlStrInvalidTextDeclarationEn = 'Invalid text declaration';
XmlStrInvalidTextDeclarationDe = 'Ungültige Text-Deklaration';
XmlStrDoubleEntityDeclWarningEn = 'Warning: Double entity declaration';
XmlStrDoubleEntityDeclWarningDe = 'Warnung: Doppelte Entity-Deklaration';
XmlStrDoubleNotationDeclWarningEn = 'Warning: Double notation declaration';
XmlStrDoubleNotationDeclWarningDe = 'Warnung: Doppelte Notation-Deklaration';
type
TDomNodeType = (ntUnknown,
ntElement_Node,
ntAttribute_Node,
ntText_Node,
ntCDATA_Section_Node,
ntEntity_Reference_Node,
ntEntity_Node,
ntProcessing_Instruction_Node,
ntXml_Declaration_Node,
ntComment_Node,
ntDocument_Node,
ntDocument_Type_Node,
ntDocument_Fragment_Node,
ntNotation_Node,
ntConditional_Section_Node,
ntParameter_Entity_Reference_Node,
ntParameter_Entity_Node,
ntEntity_Declaration_Node,
ntParameter_Entity_Declaration_Node,
ntElement_Type_Declaration_Node,
ntSequence_Particle_Node,
ntChoice_Particle_Node,
ntPcdata_Choice_Particle_Node,
ntElement_Particle_Node,
ntAttribute_List_Node,
ntAttribute_Definition_Node,
ntNametoken_Node,
ntText_Declaration_Node,
ntNotation_Declaration_Node,
ntExternal_Parsed_Entity_Node,
ntExternal_Parameter_Entity_Node,
ntExternal_Subset_Node,
ntInternal_Subset_Node);
// If you change this: show_all (see below) may
// have to be changed, too!
TDomNodeTypeSet = set of TDomNodeType;
TdomPieceType = (xmlProcessingInstruction,xmlXmlDeclaration,
xmlTextDeclaration,xmlComment,xmlCDATA,xmlPCDATA,
xmlDoctype,xmlStartTag,xmlEndTag,xmlEmptyElementTag,
xmlCharRef,xmlEntityRef,xmlParameterEntityRef,
xmlEntityDecl,xmlElementDecl,xmlAttributeDecl,
xmlNotationDecl,xmlCondSection,xmlCharacterError);
TdomContentspecType = (ctEmpty,ctAny,ctMixed,ctChildren);
TdomEncodingType = (etUTF8,etUTF16BE,etUTF16LE,etMBCS); // modified by HYL
TdomFilterResult = (filter_accept,filter_reject,filter_skip);
TdomWhatToShow = set of TDomNodeType;
const
show_all: TdomWhatToShow = [ntElement_Node .. ntInternal_Subset_Node];
type
TDomNode = class;
TDomElement = class;
TDomDocument = class;
TdomDocumentType = class;
TdomEntity = class;
TdomParameterEntity = class;
TdomEntityDeclaration = class;
TdomParameterEntityDeclaration = class;
TdomNotation = class;
TdomNotationDeclaration = class;
TdomNodeList = class;
TdomAttrList = class;
TdomAttrDefinition = class;
TdomMediaList = class;
TXmlSourceCodePiece = class;
TdomDocumentClass = class of TdomDocument;
PdomDocumentFormat = ^TdomDocumentFormat;
TdomDocumentFormat = record
DocumentClass: TdomDocumentClass;
NamespaceUri: wideString;
QualifiedName: wideString;
next: PdomDocumentFormat;
end;
TdomCustomStr = class
private
FActualLen: Integer;
FCapacity: Integer;
FContent: WideString;
public
constructor create;
procedure addWideChar(const Ch: WideChar); virtual;
procedure addWideString(const s: WideString);
procedure reset;
function value: WideString; virtual;
property length: integer read FActualLen;
end;
TDomImplementation = class (TComponent)
private
FCreatedDocuments: TdomNodeList;
FCreatedDocumentTypes: TdomNodeList;
FCreatedDocumentsListing: TList;
FCreatedDocumentTypesListing: TList;
function getDocuments: TdomNodeList; virtual;
function getDocumentTypes: TdomNodeList; virtual;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
procedure Clear; virtual;
procedure FreeDocument(const doc: TdomDocument); virtual;
procedure FreeDocumentType(const docType: TdomDocumentType); virtual;
function hasFeature(const feature,
version: WideString): boolean; virtual;
function createDocument(const name: WideString;
doctype: TdomDocumentType): TdomDocument; virtual;
function createDocumentNS(const namespaceURI,
qualifiedName: WideString;
doctype: TdomDocumentType): TdomDocument; virtual;
function createDocumentType(const name,
publicId,
systemId: WideString): TdomDocumentType; virtual;
function createDocumentTypeNS(const qualifiedName,
publicId,
systemId: WideString): TdomDocumentType; virtual;
function GetDocumentClass(const aNamespaceUri,
aQualifiedName: wideString): TdomDocumentClass; virtual;
class procedure RegisterDocumentFormat(const aNamespaceUri,
aQualifiedName: wideString;
aDocumentClass: TdomDocumentClass); virtual;
function SupportsDocumentFormat(const aNamespaceUri,
aQualifiedName: wideString): boolean; virtual;
class procedure UnregisterDocumentClass(const aDocumentClass: TdomDocumentClass); virtual;
property documents: TdomNodeList read getDocuments;
property documentTypes: TdomNodeList read getDocumentTypes;
end;
TdomNodeFilter = class
public
function acceptNode(const node: TdomNode): TdomFilterResult; virtual; abstract;
end;
TdomTreeWalker = class
private
FRoot: TdomNode;
FCurrentNode: TdomNode;
FExpandEntityReferences: boolean;
FWhatToShow: TdomWhatToShow;
FFilter: TdomNodeFilter;
function GetCurrentNode: TdomNode; virtual;
procedure SetCurrentNode(const Node: TdomNode); virtual;
function GetExpandEntityReferences: boolean; virtual;
function GetFilter: TdomNodeFilter; virtual;
function GetRoot: TdomNode; virtual;
function GetWhatToShow: TdomWhatToShow; virtual;
function FindNextSibling(const OldNode: TdomNode): TdomNode; virtual;
function FindPreviousSibling(const OldNode: TdomNode): TdomNode; virtual;
function FindParentNode(const OldNode: TdomNode): TdomNode; virtual;
function FindFirstChild(const OldNode: TdomNode): TdomNode; virtual;
function FindLastChild(const OldNode: TdomNode): TdomNode; virtual;
function FindNextNode(OldNode: TdomNode): TdomNode; virtual;
function FindPreviousNode(const OldNode: TdomNode): TdomNode; virtual;
public
constructor create(const Root: TdomNode;
const WhatToShow: TdomWhatToShow;
const NodeFilter: TdomNodeFilter;
const EntityReferenceExpansion: boolean); virtual;
function parentNode: TdomNode; virtual;
function firstChild: TdomNode; virtual;
function lastChild: TdomNode; virtual;
function previousSibling: TdomNode; virtual;
function nextSibling: TdomNode; virtual;
function NextNode: TdomNode; virtual;
function PreviousNode: TdomNode; virtual;
property currentNode: TdomNode read GetCurrentNode write SetCurrentNode;
property expandEntityReferences: boolean read GetExpandEntityReferences;
property filter: TdomNodeFilter read GetFilter;
property root: TdomNode read GetRoot;
property whatToShow: TdomWhatToShow read GetWhatToShow;
end;
TdomPosition = (posBefore,posAfter);
TdomNodeIterator = class
private
FRoot: TdomNode;
FReferenceNode: TdomNode;
FPosition: TdomPosition; // Position of the Iterator relativ to FReferenceNode
FWhatToShow: TdomWhatToShow;
FExpandEntityReferences: boolean;
FFilter: TdomNodeFilter;
FInvalid: boolean;
procedure FindNewReferenceNode(const nodeToRemove: TdomNode); virtual; // To be called if the current FReferneceNode is being removed
function GetExpandEntityReferences: boolean; virtual;
function GetFilter: TdomNodeFilter; virtual;
function GetRoot: TdomNode; virtual;
function GetWhatToShow: TdomWhatToShow; virtual;
function FindNextNode(OldNode: TdomNode): TdomNode; virtual;
function FindPreviousNode(const OldNode: TdomNode): TdomNode; virtual;
public
constructor create(const Root: TdomNode;
const WhatToShow: TdomWhatToShow;
const NodeFilter: TdomNodeFilter;
const EntityReferenceExpansion: boolean); virtual;
procedure detach; virtual;
function NextNode: TdomNode; virtual;
function PreviousNode: TdomNode; virtual;
property expandEntityReferences: boolean read GetExpandEntityReferences;
property filter: TdomNodeFilter read GetFilter;
property root: TdomNode read GetRoot;
property whatToShow: TdomWhatToShow read GetWhatToShow;
end;
TdomNodeList = class
private
FNodeList: TList;
function GetLength: integer; virtual;
protected
function IndexOf(const Node: TdomNode): integer; virtual;
public
function Item(const index: integer): TdomNode; virtual;
constructor Create(const NodeList: TList);
property Length: integer read GetLength;
end;
TdomElementsNodeList = class(TdomNodeList)
private
FQueryName: WideString;
FStartElement: TdomNode;
function GetLength: integer; override;
public
function IndexOf(const Node: TdomNode): integer; override;
function Item(const index: integer): TdomNode; override;
constructor Create(const QueryName: WideString;
const StartElement: TdomNode); virtual;
end;
TdomElementsNodeListNS = class(TdomNodeList)
private
FQueryNamespaceURI: WideString;
FQueryLocalName: WideString;
FStartElement: TdomNode;
function GetLength: integer; override;
public
function IndexOf(const Node: TdomNode): integer; override;
function Item(const index: integer): TdomNode; override;
constructor Create(const QueryNamespaceURI,
QueryLocalName: WideString;
const StartElement: TdomNode); virtual;
end;
TdomSpecialNodeList = class(TdomNodeList)
private
FAllowedNodeTypes: TDomNodeTypeSet;
function GetLength: integer; override;
protected
function GetNamedIndex(const Name: WideString): integer; virtual;
function GetNamedItem(const Name: WideString): TdomNode; virtual;
public
function IndexOf(const Node: TdomNode): integer; override;
function Item(const index: integer): TdomNode; override;
constructor Create(const NodeList: TList;
const AllowedNTs: TDomNodeTypeSet); virtual;
end;
TdomNamedNodeMap = class(TdomNodeList)
private
FOwner: TdomNode; // The owner document.
FOwnerNode: TdomNode; // The node to whom the map is attached to.
FNamespaceAware: boolean;
FAllowedNodeTypes: TDomNodeTypeSet;
function getOwnerNode: TdomNode; virtual;
function getNamespaceAware: boolean; virtual;
procedure setNamespaceAware(const value: boolean); virtual;
protected
function RemoveItem(const Arg: TdomNode): TdomNode; virtual;
function GetNamedIndex(const Name: WideString): integer; virtual;
public
constructor Create(const AOwner,
AOwnerNode: TdomNode;
const NodeList: TList;
const AllowedNTs: TDomNodeTypeSet); virtual;
function GetNamedItem(const Name: WideString): TdomNode; virtual;
function SetNamedItem(const Arg: TdomNode): TdomNode; virtual;
function RemoveNamedItem(const Name: WideString): TdomNode; virtual;
function GetNamedItemNS(const namespaceURI,
LocalName: WideString): TdomNode; virtual;
function SetNamedItemNS(const Arg: TdomNode): TdomNode; virtual;
function RemoveNamedItemNS(const namespaceURI,
LocalName: WideString): TdomNode; virtual;
published
property ownerNode: TdomNode read GetOwnerNode;
property namespaceAware: boolean read GetNamespaceAware write SetNamespaceAware;
end;
TdomEntitiesNamedNodeMap = class(TdomNamedNodeMap)
private
procedure ResolveAfterAddition(const addedEntity: TdomEntity); virtual;
procedure ResolveAfterRemoval(const removedEntity: TdomEntity); virtual;
public
function SetNamedItem(const Arg: TdomNode): TdomNode; override;
function RemoveNamedItem(const Name: WideString): TdomNode; override;
function SetNamedItemNS(const Arg: TdomNode): TdomNode; override;
function RemoveNamedItemNS(const namespaceURI,
LocalName: WideString): TdomNode; override;
end;
TdomNode = class
private
FNodeName: WideString;
FNodeValue: WideString;
FNamespaceURI: WideString;
FNodeType: TdomNodeType;
FNodeList: TdomNodeList;
FNodeListing: TList;
FDocument: TdomDocument;
FParentNode: TdomNode;
FIsReadonly: boolean;
FAllowedChildTypes: set of TDomNodeType;
procedure makeChildrenReadonly; virtual;
function RefersToExternalEntity: boolean; virtual;
function HasEntRef(const EntName: widestring): boolean; virtual;
procedure addEntRefSubtree(const EntName: widestring); virtual;
procedure removeEntRefSubtree(const EntName: widestring); virtual;
function GetNodeName: WideString; virtual;
function GetNodeValue: WideString; virtual;
procedure SetNodeValue(const Value: WideString); virtual;
function GetNodeType: TdomNodeType; virtual;
function GetAttributes: TdomNamedNodeMap; virtual;
function GetParentNode: TdomNode; virtual;
function GetChildNodes: TdomNodeList; virtual;
function GetFirstChild: TdomNode; virtual;
function GetLastChild: TdomNode; virtual;
function GetPreviousSibling: TdomNode; virtual;
function GetNextSibling: TdomNode; virtual;
function GetDocument: TdomDocument; virtual;
function GetCode: WideString; virtual;
function GetLocalName: WideString; virtual;
function GetNamespaceURI: WideString; virtual;
function GetPrefix: WideString; virtual;
procedure SetPrefix(const value: WideString); virtual;
public
constructor Create(const AOwner: TdomDocument);
destructor Destroy; override;
procedure Clear; virtual;
function InsertBefore(const newChild,
refChild: TdomNode): TdomNode; virtual;
function ReplaceChild(const newChild,
oldChild: TdomNode): TdomNode; virtual;
function RemoveChild(const oldChild: TdomNode): TdomNode; virtual;
function AppendChild(const newChild: TdomNode): TdomNode; virtual;
function HasChildNodes: boolean; virtual;
function CloneNode(const deep: boolean): TdomNode; virtual;
function IsAncestor(const AncestorNode: TdomNode): boolean; virtual;
procedure GetLiteralAsNodes(const RefNode: TdomNode); virtual;
procedure normalize; virtual;
function supports(const feature,
version: WideString): boolean; virtual;
published
property Attributes: TdomNamedNodeMap read GetAttributes;
property ChildNodes: TdomNodeList read GetChildNodes;
property Code: WideString read GetCode;
property FirstChild: TdomNode read GetFirstChild;
property LastChild: TdomNode read GetLastChild;
property LocalName: WideString read GetLocalName;
property NamespaceURI: WideString read GetNamespaceURI;
property NextSibling: TdomNode read GetNextSibling;
property NodeName: WideString read GetNodeName;
property NodeType: TdomNodeType read GetNodeType;
property NodeValue: WideString read GetNodeValue write SetNodeValue;
property OwnerDocument: TdomDocument read GetDocument;
property ParentNode: TdomNode read GetParentNode;
property PreviousSibling: TdomNode read GetPreviousSibling;
property Prefix: WideString read GetPrefix write SetPrefix;
end;
TdomCharacterData = class (TdomNode)
private
function GetData: WideString; virtual;
procedure SetData(const Value: WideString); virtual;
function GetLength: integer; virtual;
public
constructor Create(const AOwner: TdomDocument); virtual;
function SubstringData(const offset,
count: integer):WideString; virtual;
procedure AppendData(const arg: WideString); virtual;
procedure InsertData(const offset: integer;
const arg: WideString); virtual;
procedure DeleteData(const offset,
count: integer); virtual;
procedure ReplaceData(const offset,
count: integer;
const arg: WideString); virtual;
published
property Data: WideString read GetData write SetData;
property length: integer read GetLength;
end;
TdomAttr = class (TdomNode)
private
FOwnerElement: TdomElement;
FSpecified: boolean;
function GetName: WideString; virtual;
function GetSpecified: boolean; virtual;
function GetNodeValue: WideString; override;
procedure SetNodeValue(const Value: WideString); override;
function GetValue: WideString; virtual;
procedure SetValue(const Value: WideString); virtual;
function GetOwnerElement: TdomElement; virtual;
function GetParentNode: TdomNode; override;
function GetPreviousSibling: TdomNode; override;
function GetNextSibling: TdomNode; override;
function GetCode: WideString; override;
public
constructor Create(const AOwner: TdomDocument;
const NamespaceURI,
Name: WideString;
const Spcfd: boolean); virtual;
procedure normalize; override;
published
property Name: WideString read GetName;
property Specified: boolean read GetSpecified default false;
property Value: WideString read GetValue write SetValue;
property OwnerElement: TdomElement read GetOwnerElement;
end;
TdomElement = class (TdomNode)
private
FCreatedElementsNodeLists: TList;
FCreatedElementsNodeListNSs: TList;
FAttributeListing: TList;
FAttributeList: TdomNamedNodeMap;
procedure SetNodeValue(const Value: WideString); override;
function GetCode: WideString; override;
public
constructor Create(const AOwner: TdomDocument;
const NamespaceURI,
TagName: WideString); virtual;
destructor Destroy; override;
function GetTagName: WideString; virtual;
function GetAttributes: TdomNamedNodeMap; override;
function GetAttribute(const Name: WideString): WideString; virtual;
function SetAttribute(const Name,
Value: WideString): TdomAttr; virtual;
function RemoveAttribute(const Name: WideString): TdomAttr; virtual;
function GetAttributeNode(const Name: WideString): TdomAttr; virtual;
function SetAttributeNode(const NewAttr: TdomAttr): TdomAttr; virtual;
function RemoveAttributeNode(const OldAttr: TdomAttr): TdomAttr; virtual;
function GetElementsByTagName(const Name: WideString): TdomNodeList; virtual;
function GetAttributeNS(const namespaceURI,
localName: WideString): WideString; virtual;
function SetAttributeNS(const namespaceURI,
qualifiedName,
value: WideString): TdomAttr; virtual;
function RemoveAttributeNS(const namespaceURI,
localName: WideString): TdomAttr; virtual;
function GetAttributeNodeNS(const namespaceURI,
localName: WideString): TdomAttr; virtual;
function SetAttributeNodeNS(const NewAttr: TdomAttr): TdomAttr; virtual;
function GetElementsByTagNameNS(const namespaceURI,
localName: WideString): TdomNodeList; virtual;
function hasAttribute(const name: WideString): boolean; virtual;
function hasAttributeNS(const namespaceURI,
localName: WideString): boolean; virtual;
procedure normalize; override;
published
property TagName: WideString read GetTagName;
end;
TdomText = class (TdomCharacterData)
private
function GetCode: WideString; override;
public
constructor Create(const AOwner: TdomDocument); override;
function SplitText(const offset: integer): TdomText; virtual;
end;
TdomComment = class (TdomCharacterData)
private
function GetCode: WideString; override;
public
constructor Create(const AOwner: TdomDocument); override;
end;
TdomProcessingInstruction = class (TdomNode)
private
function GetTarget: WideString; virtual;
function GetData: WideString; virtual;
procedure SetData(const Value: WideString); virtual;
function GetCode: WideString; override;
public
constructor Create(const AOwner: TdomDocument;
const Targ: WideString); virtual;
published
property Target: WideString read GetTarget;
property Data: WideString read GetData write SetData;
end;
TdomXmlDeclaration = class (TdomNode)
private
FStandalone: WideString;
FEncodingDecl: WideString;
FVersionNumber: WideString;
function GetVersionNumber: WideString; virtual;
function GetEncodingDecl: WideString; virtual;
procedure SetEncodingDecl(const Value: WideSTring); virtual;
function GetStandalone: WideString; virtual;
procedure SetStandalone(const Value: WideSTring); virtual;
function GetCode: WideString; override;
public
constructor Create(const AOwner: TdomDocument;
const Version,
EncDl,
SdDl: WideString); virtual;
published
property VersionNumber: WideString read GetVersionNumber;
property EncodingDecl: WideString read GetEncodingDecl write SetEncodingDecl;
property SDDecl: WideString read GetStandalone write SetStandalone;
end;
TdomCDATASection = class (TdomText)
private
function GetCode: WideString; override;
public
constructor Create(const AOwner: TdomDocument); override;
end;
TdomCustomDocumentType = class (TdomNode)
private
FParameterEntitiesListing: TList;
FAttributeListsListing: TList;
FParameterEntitiesList: TdomNamedNodeMap;
FAttributeListsList: TdomNamedNodeMap;
function GetParameterEntities: TdomNamedNodeMap; virtual;
function GetAttributeLists: TdomNamedNodeMap; virtual;
procedure SetNodeValue(const Value: WideString); override;
public
constructor Create(const AOwner: TdomDocument);
destructor Destroy; override;
published
property AttributeLists: TdomNamedNodeMap read GetAttributeLists;
property ParameterEntities: TdomNamedNodeMap read GetParameterEntities;
end;
TdomExternalSubset = class (TdomCustomDocumentType)
public
constructor Create(const AOwner: TdomDocument); virtual;
function CloneNode(const deep: boolean): TdomNode; override;
end;
TdomInternalSubset = class (TdomCustomDocumentType)
public
constructor Create(const AOwner: TdomDocument); virtual;
end;
TdomConditionalSection = class(TdomCustomDocumentType)
private
FIncluded: TdomNode;
function GetIncluded: TdomNode; virtual;
function GetCode: WideString; override;
protected
function SetIncluded(const node: TdomNode): TdomNode; virtual;
public
constructor Create(const AOwner: TdomDocument;
const IncludeStmt: WideString); virtual;
published
property Included: TdomNode read GetIncluded;
end;
TdomDocumentType = class (TdomCustomDocumentType)
private
FPublicId: WideString;
FSystemId: WideString;
FEntitiesListing: TList;
FEntitiesList: TdomEntitiesNamedNodeMap;
FNotationsListing: TList;
FNotationsList: TdomNamedNodeMap;
function analyzeEntityValue(const EntityValue: wideString): widestring; virtual;
function GetEntities: TdomEntitiesNamedNodeMap; virtual;
function GetName: WideString; virtual;
function GetNotations: TdomNamedNodeMap; virtual;
function GetPublicId: WideString; virtual;
function GetSystemId: WideString; virtual;
function GetExternalSubsetNode: TdomExternalSubset; virtual;
function GetInternalSubsetNode: TdomInternalSubset; virtual;
function GetInternalSubset: WideString; virtual;
function GetCode: WideString; override;
public
constructor Create(const AOwner: TdomDocument;
const Name,
PubId,
SysId: WideString); virtual;
destructor destroy; override;
published
property Entities: TdomEntitiesNamedNodeMap read GetEntities;
property ExternalSubsetNode: TdomExternalSubset read GetExternalSubsetNode;
property InternalSubset: WideString read GetInternalSubset;
property InternalSubsetNode: TdomInternalSubset read GetInternalSubsetNode;
property Name: WideString read GetName;
property Notations: TdomNamedNodeMap read GetNotations;
property PublicId: WideString read GetPublicId;
property SystemId: WideString read GetSystemId;
end;
TdomNotation = class (TdomNode)
private
FPublicId: WideString;
FSystemId: WideString;
function GetPublicId: WideString; virtual;
function GetSystemId: WideString; virtual;
procedure SetNodeValue(const Value: WideString); override;
function GetCode: WideString; override;
public
constructor Create(const AOwner: TdomDocument;
const Name,
PubId,
SysId: WideString); virtual;
published
property PublicId: WideString read GetPublicId;
property SystemId: WideString read GetSystemId;
end;
TdomNotationDeclaration = class (TdomNode)
private
FPublicId: WideString;
FSystemId: WideString;
function GetPublicId: WideString; virtual;
function GetSystemId: WideString; virtual;
procedure SetNodeValue(const Value: WideString); override;
function GetCode: WideString; override;
public
constructor Create(const AOwner: TdomDocument;
const Name,
PubId,
SysId: WideString); virtual;
published
property PublicId: WideString read GetPublicId;
property SystemId: WideString read GetSystemId;
end;
TdomCustomDeclaration = class (TdomNode)
private
function GetValue: WideString; virtual;
procedure SetValue(const Value: WideString); virtual;
procedure SetNodeValue(const Value: WideString); override;
public
constructor Create(const AOwner: TdomDocument;
const Name: WideString);
published
property Value: WideString read GetValue write SetValue;
end;
TdomElementTypeDeclaration = class (TdomCustomDeclaration)
private
FContentspec: TdomContentspecType;
function GetContentspec: TdomContentspecType; virtual;
function GetCode: WideString; override;
public
constructor Create(const AOwner: TdomDocument;
const Name: WideString;
const Contspec: TdomContentspecType); virtual;
function AppendChild(const newChild: TdomNode): TdomNode; override;
function InsertBefore(const newChild,
refChild: TdomNode): TdomNode; override;
published
property Contentspec: TdomContentspecType read GetContentspec;
end;
TdomAttrList = class(TdomCustomDeclaration)
private
FAttDefListing: TList;
FAttDefList: TdomNamedNodeMap;
function GetAttributeDefinitions: TdomNamedNodeMap; virtual;
function GetCode: WideString; override;
public
constructor Create(const AOwner: TdomDocument;
const Name: WideString); virtual;
destructor Destroy; override;
function RemoveAttributeDefinition(const Name: WideString): TdomAttrDefinition; virtual;
function GetAttributeDefinitionNode(const Name: WideString): TdomAttrDefinition; virtual;
function SetAttributeDefinitionNode(const NewAttDef: TdomAttrDefinition): boolean; virtual;
function RemoveAttributeDefinitionNode(const OldAttDef: TdomAttrDefinition): TdomAttrDefinition; virtual;
published
property AttributeDefinitions: TdomNamedNodeMap read GetAttributeDefinitions;
end;
TdomAttrDefinition = class(TdomNode)
private
FAttributeType: WideString;
FDefaultDeclaration: WideString;
FParentAttributeList: TdomAttrList;
function GetAttributeType: WideString; virtual;
function GetDefaultDeclaration: WideString; virtual;
function GetName: WideString; virtual;
function GetParentAttributeList: TdomAttrList; virtual;
procedure SetNodeValue(const Value: WideString); override;
function GetCode: WideString; override;
public
constructor Create(const AOwner: TdomDocument;
const Name,
AttType,
DefaultDecl,
AttValue: WideString); virtual;
published
property AttributeType: WideString read GetAttributeType;
property DefaultDeclaration: WideString read GetDefaultDeclaration;
property Name: WideString read GetName;
property ParentAttributeList: TdomAttrList read GetParentAttributeList;
end;
TdomNametoken = class (TdomNode)
private
function GetCode: WideString; override;
public
constructor Create(const AOwner: TdomDocument;
const Name: WideString); virtual;
procedure SetNodeValue(const Value: WideString); override;
end;
TdomParticle = class (TdomNode)
private
FFrequency: WideString;
function GetFrequency: WideString; virtual;
procedure SetFrequency(const freq: WideString); virtual;
procedure SetNodeValue(const Value: WideString); override;
public
constructor Create(const AOwner: TdomDocument;
const Freq: WideString);
published
property Frequency: WideString read GetFrequency;
end;
TdomSequenceParticle = class (TdomParticle)
private
function GetCode: WideString; override;
public
constructor Create(const AOwner: TdomDocument;
const Freq: WideString); virtual;
end;
TdomChoiceParticle = class (TdomParticle)
private
function getCode: WideString; override;
public
constructor create(const AOwner: TdomDocument;
const Freq: WideString); virtual;
end;
TdomPcdataChoiceParticle = class (TdomParticle)
private
function getCode: WideString; override;
procedure SetFrequency(const freq: WideString); override;
public
constructor create(const AOwner: TdomDocument;
const Freq: WideString); virtual;
end;
TdomElementParticle = class (TdomParticle)
private
function GetCode: WideString; override;
public
constructor Create(const AOwner: TdomDocument;
const Name,
Freq: WideString); virtual;
end;
TdomCustomEntity = class (TdomCustomDeclaration)
private
FPublicId: WideString;
FSystemId: WideString;
FIsInternalEntity: boolean;
function GetIsInternalEntity: boolean; virtual;
function GetPublicId: WideString; virtual;
function GetSystemId: WideString; virtual;
procedure SetValue(const Value: WideString); override;
public
constructor Create(const AOwner: TdomDocument;
const Name,
PubId,
SysId: WideString);
function InsertBefore(const newChild,
refChild: TdomNode): TdomNode; override;
function ReplaceChild(const newChild,
oldChild: TdomNode): TdomNode; override;
function AppendChild(const newChild: TdomNode): TdomNode; override;
published
property PublicId: WideString read GetPublicId;
property SystemId: WideString read GetSystemId;
property IsInternalEntity: boolean read GetIsInternalEntity;
end;
TdomExternalParsedEntity = class (TdomNode)
public
constructor Create(const AOwner: TdomDocument); virtual;
end;
TdomExternalParameterEntity = class (TdomNode)
public
constructor Create(const AOwner: TdomDocument); virtual;
end;
TdomEntity = class (TdomCustomEntity)
private
FNotationName: WideString;
function GetNotationName: WideString; virtual;
public
constructor Create(const AOwner: TdomDocument;
const Name,
PubId,
SysId,
NotaName: WideString); virtual;
function CloneNode(const deep: boolean): TdomNode; override;
property NotationName: WideString read GetNotationName;
end;
TdomParameterEntity = class (TdomCustomEntity)
public
constructor Create(const AOwner: TdomDocument;
const Name,
PubId,
SysId: WideString); virtual;
end;
TdomEntityDeclaration = class (TdomCustomEntity)
private
FNotationName: WideString;
FExtParsedEnt: TdomExternalParsedEntity;
function GetExtParsedEnt: TdomExternalParsedEntity; virtual;
procedure SetExtParsedEnt(const Value: TdomExternalParsedEntity); virtual;
function GetNotationName: WideString; virtual;
function GetCode: WideString; override;
public
constructor Create(const AOwner: TdomDocument;
const Name,
EntityValue,
PubId,
SysId,
NotaName: WideString); virtual;
property ExtParsedEnt: TdomExternalParsedEntity read GetExtParsedEnt write SetExtParsedEnt;
property NotationName: WideString read GetNotationName;
end;
TdomParameterEntityDeclaration = class (TdomCustomEntity)
private
FExtParamEnt: TdomExternalParameterEntity;
function GetCode: WideString; override;
function GetExtParamEnt: TdomExternalParameterEntity; virtual;
procedure SetExtParamEnt(const Value: TdomExternalParameterEntity); virtual;
public
constructor Create(const AOwner: TdomDocument;
const Name,
EntityValue,
PubId,
SysId: WideString); virtual;
property ExtParamEnt: TdomExternalParameterEntity read GetExtParamEnt write SetExtParamEnt;
end;
TdomReference = class (TdomNode)
private
function GetDeclaration: TdomCustomEntity; virtual;
procedure SetNodeValue(const Value: WideString); override;
function GetNodeValue: WideString; override;
public
constructor Create(const AOwner: TdomDocument;
const Name: WideString); virtual;
published
property Declaration: TdomCustomEntity read GetDeclaration;
end;
TdomEntityReference = class (TdomReference)
private
function GetCode: WideString; override;
public
constructor Create(const AOwner: TdomDocument;
const Name: WideString); override;
function CloneNode(const deep: boolean): TdomNode; override;
end;
TdomParameterEntityReference = class (TdomReference)
private
function GetCode: WideString; override;
public
constructor Create(const AOwner: TdomDocument;
const Name: WideString); override;
end;
TdomTextDeclaration = class (TdomNode)
private
FEncodingDecl: WideString;
FVersionNumber: WideString;
function GetVersionNumber: WideString; virtual;
function GetEncodingDecl: WideString; virtual;
procedure SetEncodingDecl(const Value: WideSTring); virtual;
function GetCode: WideString; override;
public
constructor Create(const AOwner: TdomDocument;
const Version,
EncDl: WideString); virtual;
published
property VersionNumber: WideString read GetVersionNumber;
property EncodingDecl: WideString read GetEncodingDecl write SetEncodingDecl;
end;
TdomDocumentFragment = class (TdomNode)
private
procedure SetNodeValue(const Value: WideString); override;
public
constructor Create(const AOwner: TdomDocument); virtual;
end;
TdomDocument = class (TdomNode)
private
FCreatedNodes: TList;
FCreatedNodeIterators: TList;
FCreatedTreeWalkers: TList;
FCreatedElementsNodeLists: TList;
FCreatedElementsNodeListNSs: TList;
FFilename: TFilename;
function ExpandEntRef(const Node: TdomEntityReference): boolean; virtual;
function GetFilename: TFilename; virtual;
procedure SetFilename(const Value: TFilename); virtual;
procedure FindNewReferenceNodes(const NodeToRemove: TdomNode); virtual;
function GetCodeAsString: String; virtual;
function GetCodeAsWideString: WideString; virtual;
function GetDoctype: TdomDocumentType; virtual;
function GetDocumentElement: TdomElement; virtual;
function GetXmlDeclaration: TdomXmlDeclaration; virtual;
procedure SetNodeValue(const Value: WideString); override;
function GetCode: WideString; override;
protected
function IsHTML: boolean; virtual;
function DuplicateNode(Node: TdomNode): TdomNode; virtual;
procedure InitDoc(const TagName: wideString); virtual;
procedure InitDocNS(const NamespaceURI,
QualifiedName: WideString); virtual;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Clear; override;
procedure ClearInvalidNodeIterators; virtual;
function CreateElement(const TagName: WideString): TdomElement; virtual;
function CreateElementNS(const NamespaceURI,
QualifiedName: WideString): TdomElement; virtual;
function CreateDocumentFragment: TdomDocumentFragment; virtual;
function CreateText(const Data: WideString): TdomText; virtual;
function CreateComment(const Data: WideString): TdomComment; virtual;
function CreateConditionalSection(const IncludeStmt: WideString): TdomConditionalSection; virtual;
function CreateCDATASection(const Data: WideString): TdomCDATASection; virtual;
function CreateProcessingInstruction(const Targ,
Data : WideString): TdomProcessingInstruction; virtual;
function CreateXmlDeclaration(const Version,
EncDl,
SdDl: WideString): TdomXmlDeclaration; virtual;
function CreateAttribute(const Name: WideString): TdomAttr; virtual;
function CreateAttributeNS(const NamespaceURI,
QualifiedName: WideString): TdomAttr; virtual;
function CreateEntityReference(const Name: WideString): TdomEntityReference; virtual;
function CreateParameterEntityReference(const Name: WideString): TdomParameterEntityReference; virtual;
function CreateDocumentType(const Name,
PubId,
SysId: WideString): TdomDocumentType; virtual;
function CreateNotation(const Name,
PubId,
SysId: WideString): TdomNotation; virtual;
function CreateNotationDeclaration(const Name,
PubId,
SysId: WideString): TdomNotationDeclaration; virtual;
function CreateEntity(const Name,
PubId,
SysId,
NotaName: WideString): TdomEntity; virtual;
function CreateParameterEntity(const Name,
PubId,
SysId: WideString): TdomParameterEntity; virtual;
function CreateEntityDeclaration(const Name,
EntityValue,
PubId,
SysId,
NotaName: WideString): TdomEntityDeclaration; virtual;
function CreateParameterEntityDeclaration(const Name,
EntityValue,
PubId,
SysId: WideString): TdomParameterEntityDeclaration; virtual;
function CreateElementTypeDeclaration(const Name: WideString;
const Contspec: TdomContentspecType): TdomElementTypeDeclaration; virtual;
function CreateSequenceParticle(const Freq: WideString): TdomSequenceParticle; virtual;
function CreateChoiceParticle(const Freq: WideString): TdomChoiceParticle; virtual;
function CreatePcdataChoiceParticle: TdomPcdataChoiceParticle; virtual;
function CreateElementParticle(const Name,
Freq: WideString): TdomElementParticle; virtual;
function CreateAttributeList(const Name: WideString): TdomAttrList; virtual;
function CreateAttributeDefinition(const Name,
AttType,
DefaultDecl,
AttValue: WideString) : TdomAttrDefinition; virtual;
function CreateNametoken(const Name: WideString): TdomNametoken; virtual;
function CreateTextDeclaration(const Version,
EncDl: WideString): TdomTextDeclaration; virtual;
function CreateExternalParsedEntity: TdomExternalParsedEntity; virtual;
function CreateExternalParameterEntity: TdomExternalParameterEntity; virtual;
function CreateExternalSubset: TdomExternalSubset; virtual;
function CreateInternalSubset: TdomInternalSubset; virtual;
procedure FreeAllNodes(const Node: TdomNode); virtual;
procedure FreeTreeWalker(const TreeWalker: TdomTreeWalker); virtual;
function GetElementsById(const elementId: WideString): TdomElement; virtual;
function GetElementsByTagName(const TagName: WideString): TdomNodeList; virtual;
function GetElementsByTagNameNS(const namespaceURI,
localName: WideString): TdomNodeList; virtual;
function ImportNode(const importedNode: TdomNode;
const deep: boolean): TdomNode; virtual;
function InsertBefore(const newChild,
refChild: TdomNode): TdomNode; override;
function ReplaceChild(const newChild,
oldChild: TdomNode): TdomNode; override;
function AppendChild(const newChild: TdomNode): TdomNode; override;
function CreateNodeIterator(const root: TdomNode;
whatToShow: TdomWhatToShow;
nodeFilter: TdomNodeFilter;
entityReferenceExpansion: boolean): TdomNodeIterator; virtual;
function CreateTreeWalker(const root: TdomNode;
whatToShow: TdomWhatToShow;
nodeFilter: TdomNodeFilter;
entityReferenceExpansion: boolean): TdomTreeWalker; virtual;
property CodeAsString: string read GetCodeAsString;
property CodeAsWideString: WideString read GetCodeAsWideString;
property Doctype: TdomDocumentType read GetDoctype;
property DocumentElement: TdomElement read GetDocumentElement;
property Filename: TFilename read GetFilename write SetFilename;
property XmlDeclaration: TdomXmlDeclaration read GetXmlDeclaration;
end;
TdomStyleSheet = class
private
function GetStyleSheetType: WideString; virtual; abstract;
function GetDisabled: boolean; virtual; abstract;
procedure SetDisabled(const value: boolean); virtual; abstract;
function GetOwnerNode: TdomNode; virtual; abstract;
function GetParentStyleSheet: TdomStyleSheet; virtual; abstract;
function GetHref: WideString; virtual; abstract;
function GetTitle: WideString; virtual; abstract;
function GetMedia: TdomMediaList; virtual; abstract;
public
property StyleSheetType: WideString read GetStyleSheetType;
property Disabled: boolean read GetDisabled write SetDisabled;
property OwnerNode: TdomNode read GetOwnerNode;
property ParentStyleSheet: TdomStyleSheet read GetParentStyleSheet;
property Href: WideString read GetHref;
property Title: WideString read GetTitle;
property Media: TdomMediaList read GetMedia;
end;
TdomMediaList = class
private
function GetCssText: WideString; virtual; abstract;
procedure SetCssText(const value: WideString); virtual; abstract;
function GetLength: integer; virtual; abstract;
public
function Item(const index: integer): TdomStyleSheet; virtual; abstract;
procedure Delete(const oldMedium: WideString); virtual; abstract;
procedure Append(const newMedium: WideString); virtual; abstract;
property Length: integer read GetLength;
property CssText: WideString read GetCssText write SetCssText;
end;
TdomStyleSheetList = class
private
function GetLength: integer; virtual; abstract;
public
function Item(const index: integer): TdomStyleSheet; virtual; abstract;
property Length: integer read GetLength;
end;
TdomDocumentStyle = class
private
function GetStyleSheets: TdomStyleSheetList; virtual; abstract;
public
property StyleSheets: TdomStyleSheetList read GetStyleSheets;
end;
TXmlSourceCode = class (TList)
private
procedure calculatePieceOffset(const startItem: integer); virtual;
function getNameOfFirstTag: wideString; virtual;
public
function Add(Item: Pointer): Integer;
procedure Clear; override; //virtual;
procedure ClearAndFree; virtual;
procedure Delete(Index: Integer);
procedure Exchange(Index1, Index2: Integer);
function GetPieceAtPos(pos: integer): TXmlSourceCodePiece;
procedure Insert(Index: Integer; Item: Pointer);
procedure Move(CurIndex, NewIndex: Integer);
procedure Pack;
function Remove(Item: Pointer): Integer;
procedure Sort(Compare: TListSortCompare);
property NameOfFirstTag: wideString read getNameOfFirstTag;
end;
TXmlSourceCodePiece = class
private
FPieceType: TdomPieceType;
Ftext: wideString;
FOffset: integer;
FOwner: TXmlSourceCode;
public
constructor Create(const pt: TdomPieceType); virtual;
property pieceType: TdomPieceType read FPieceType;
property text: WideString read Ftext write Ftext;
property offset: integer read FOffset;
property ownerSourceCode: TXmlSourceCode read FOwner;
end;
{Parser}
TXmlParserLanguage = (de,en);
type
TXmlMemoryStream = class(TMemoryStream)
public
procedure SetPointer(Ptr: Pointer; Size: Longint);
end;
TXmlInputSource = class
private
FStream: TStream;
FEncoding: TdomEncodingType;
FPublicId: wideString;
FSystemId: wideString;
public
constructor create(const Stream: TStream;
const PublicId,
SystemId: wideString;
defaultEncoding : TdomEncodingType); virtual;
property Encoding: TdomEncodingType read FEncoding;
property PublicId: wideString read FPublicId;
property Stream: TStream read FStream;
property SystemId: wideString read FSystemId;
end;
TXmlParserError = class
private
FErrorType: ShortString;
FStartLine: integer;
FEndLine: integer;
FLanguage: TXmlParserLanguage;
FSourceCodeText: WideString;
function GetErrorStr: WideString;
function GetErrorType: ShortString;
function GetStartLine: integer;
function GetEndLine: integer;
public
constructor Create(const ErrorType: ShortString;
const StartLine,
EndLine: integer;
const SourceCodeText: WideString;
const lang: TXmlParserLanguage); virtual;
property ErrorStr: WideString read GetErrorStr;
property ErrorType: ShortString read GetErrorType;
property StartLine: integer read GetStartLine;
property EndLine: integer read GetEndLine;
end;
TCustomParser = class (TComponent)
private
FLineNumber: longint;
FErrorList: TList;
FErrorStrings: TStringList;
FLanguage: TXmlParserLanguage;
FDOMImpl: TDomImplementation;
FIntSubset: WideString; // Only for buffer storage while parsing a document
FUseSpecifiedDocumentSC: boolean; // Internally used flag which indicates to write to FDocumentSC, FExternalSubsetSC or FInternalSubsetSC.
FDocumentSC: TXmlSourceCode;
FExternalSubsetSC: TXmlSourceCode;
FInternalSubsetSC: TXmlSourceCode;
FDefaultEncoding: TdomEncodingType;
procedure SetDomImpl(const impl: TDomImplementation); virtual;
function GetDomImpl: TDomImplementation; virtual;
procedure SetLanguage(const Lang: TXmlParserLanguage); virtual;
function GetLanguage: TXmlParserLanguage; virtual;
function GetErrorList: TList; virtual;
function GetErrorStrings: TStringList; virtual;
procedure ClearErrorList; virtual;
procedure XMLAnalyseAttrSequence(const Source: WideString;
const Element: TdomElement;
const FirstLineNumber,
LastLineNumber: integer); virtual;
function WriteXmlDeclaration(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomXmlDeclaration; virtual;
function WriteTextDeclaration(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomTextDeclaration; virtual;
function WriteProcessingInstruction(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomNode; virtual;
function WriteComment(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomComment; virtual;
function WriteCDATA(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomCDATASection; virtual;
function WritePCDATA(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomText; virtual;
function WriteStartTag(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomElement; virtual;
function WriteEndTag(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode): TdomElement; virtual;
function WriteCharRef(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomText; virtual;
function WriteEntityRef(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomEntityReference; virtual;
function WriteDoctype(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode): TdomDocumentType; virtual;
function WriteParameterEntityRef(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomParameterEntityReference; virtual;
function WriteEntityDeclaration(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomCustomEntity; virtual;
function WriteElementDeclaration(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomElementTypeDeclaration; virtual;
function WriteAttributeDeclaration(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomAttrList; virtual;
function WriteNotationDeclaration(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomNotationDeclaration; virtual;
function WriteConditionalSection(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomConditionalSection; virtual;
procedure InsertMixedContent(const RefNode: TdomNode;
const ContentSpec: WideString;
const readonly: boolean); virtual;
procedure InsertChildrenContent(const RefNode: TdomNode;
const ContentSpec: WideString;
const readonly: boolean); virtual;
procedure InsertNotationTypeContent(const RefNode: TdomNode;
const ContentSpec: WideString;
const readonly: boolean); virtual;
procedure InsertEnumerationContent(const RefNode: TdomNode;
const ContentSpec: WideString;
const readonly: boolean); virtual;
procedure FindNextAttDef(const Decl: WideString;
var Name,
AttType,
Bracket,
DefaultDecl,
AttValue,
Rest: WideString); virtual;
procedure DocToXmlSourceCode(const InputSource :TXmlInputSource;
const Source: TXmlSourceCode);
procedure ExtDtdToXmlSourceCode(const InputSource :TXmlInputSource;
const Source: TXmlSourceCode);
procedure IntDtdToXmlSourceCode(const InputSource :TXmlInputSource;
const Source: TXmlSourceCode);
protected
function NormalizeLineBreaks(const source :WideString): WideString; virtual;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
property DOMImpl: TDomImplementation read GetDomImpl write SetDomImpl;
property Language: TXmlParserLanguage read GetLanguage write SetLanguage default en;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
procedure DocMemoryToDom(const Ptr: Pointer;
const Size: Longint;
const RefNode: TdomNode;
const readonly: boolean); virtual;
procedure DocSourceCodeToDom(const DocSourceCode: TXmlSourceCode;
const RefNode: TdomNode;
const readonly: boolean); virtual;
procedure DocStreamToDom(const Stream: TStream;
const RefNode: TdomNode;
const readonly: boolean); virtual;
procedure DocStringToDom(const Str: string;
const RefNode: TdomNode;
const readonly: boolean); virtual;
procedure DocWideStringToDom( Str: WideString;
const RefNode: TdomNode;
const readonly: boolean); virtual;
procedure ExtDtdMemoryToDom(const Ptr: Pointer;
const Size: Longint;
const RefNode: TdomNode;
const readonly: boolean); virtual;
procedure ExtDtdSourceCodeToDom(const ExtDtdSourceCode: TXmlSourceCode;
const RefNode: TdomNode;
const readonly: boolean); virtual;
procedure ExtDtdStreamToDom(const Stream: TStream;
const RefNode: TdomNode;
const readonly: boolean); virtual;
procedure ExtDtdStringToDom(const Str: string;
const RefNode: TdomNode;
const readonly: boolean); virtual;
procedure ExtDtdWideStringToDom( Str: WideString;
const RefNode: TdomNode;
const readonly: boolean); virtual;
procedure IntDtdMemoryToDom(const Ptr: Pointer;
const Size: Longint;
const RefNode: TdomNode;
const readonly: boolean); virtual;
procedure IntDtdSourceCodeToDom(const IntDtdSourceCode: TXmlSourceCode;
const RefNode: TdomNode;
const readonly: boolean); virtual;
procedure IntDtdStreamToDom(const Stream: TStream;
const RefNode: TdomNode;
const readonly: boolean); virtual;
procedure IntDtdStringToDom(const Str: string;
const RefNode: TdomNode;
const readonly: boolean); virtual;
procedure IntDtdWideStringToDom( Str: WideString;
const RefNode: TdomNode;
const readonly: boolean); virtual;
property ErrorList: TList read GetErrorList;
property ErrorStrings: TStringList read GetErrorStrings;
property DocumentSC: TXmlSourceCode read FDocumentSC write FDocumentSC;
property ExternalSubsetSC: TXmlSourceCode read FExternalSubsetSC write FExternalSubsetSC;
property InternalSubsetSC: TXmlSourceCode read FInternalSubsetSC write FInternalSubsetSC;
// add by hyl
property DefaultEncoding : TdomEncodingType read FDefaultEncoding write FDefaultEncoding default etMBCS;
end;
TParserEvent = procedure( Sender: TObject;
const PublicId,
SystemId: WideString;
var extSubset: WideString) of object;
TXmlToDomParser = class (TCustomParser)
private
FOnExternalSubset: TParserEvent;
public
function FileToDom(const filename: TFileName): TdomDocument; virtual;
published
property OnExternalSubset: TParserEvent read FOnExternalSubset write FOnExternalSubset;
property DOMImpl;
property Language;
end;
function XMLExtractPrefix(const qualifiedName: wideString): wideString;
function XMLExtractLocalName(const qualifiedName: wideString): wideString;
function IsXmlChar(const S: WideChar): boolean;
function IsXmlWhiteSpace(const S: WideChar): boolean;
function IsXmlLetter(const S: WideChar): boolean;
function IsXmlBaseChar(const S: WideChar): boolean;
function IsXmlIdeographic(const S: WideChar): boolean;
function IsXmlCombiningChar(const S: WideChar): boolean;
function IsXmlDigit(const S: WideChar): boolean;
function IsXmlExtender(const S: WideChar): boolean;
function IsXmlNameChar(const S: WideChar): boolean;
function IsXmlPubidChar(const S: WideChar): boolean;
function IsXmlS(const S: WideString): boolean;
function IsXmlName(const S: WideString): boolean;
function IsXmlNames(const S: WideString): boolean;
function IsXmlNmtoken(const S: WideString): boolean;
function IsXmlNmtokens(const S: WideString): boolean;
function IsXmlCharRef(const S: WideString): boolean;
function IsXmlEntityRef(const S: WideString): boolean;
function IsXmlPEReference(const S: WideString): boolean;
function IsXmlReference(const S: WideString): boolean;
function IsXmlEntityValue(const S: WideString): boolean;
function IsXmlAttValue(const S: WideString): boolean;
function IsXmlSystemLiteral(const S: WideString): boolean;
function IsXmlPubidLiteral(const S: WideString): boolean;
function IsXmlCharData(const S: WideString): boolean;
function IsXmlPITarget(const S: WideString): boolean;
function IsXmlVersionNum(const S: WideString): boolean;
function IsXmlEncName(const S: WideString): boolean;
function IsXmlStringType(const S: WideString): boolean;
function IsXmlTokenizedType(const S: WideString): boolean;
function IsXmlNCNameChar(const s: WideChar): boolean;
function IsXmlNCName(const S: WideString): boolean;
function IsXmlDefaultAttName(const S: WideString): boolean;
function IsXmlPrefixedAttName(const S: WideString): boolean;
function IsXmlNSAttName(const S: WideString): boolean;
function IsXmlLocalPart(const S: WideString): boolean;
function IsXmlPrefix(const S: WideString): boolean;
function IsXmlQName(const S: WideString): boolean;
function XmlIntToCharRef(const value: integer): wideString;
function XmlCharRefToInt(const S: WideString): integer;
function XmlCharRefToStr(const S: WideString): WideString;
function XmlStrToCharRef(const S: WideString): WideString;
function UTF8ToUTF16BEStr(const s: string): WideString;
function UTF16BEToUTF8Str(const ws: WideString): string;
function Utf16HighSurrogate(const value: integer): WideChar;
function Utf16LowSurrogate(const value: integer): WideChar;
function Utf16SurrogateToInt(const highSurrogate, lowSurrogate: WideChar): integer;
function IsUtf16HighSurrogate(const S: WideChar): boolean;
function IsUtf16LowSurrogate(const S: WideChar): boolean;
procedure Register;
procedure XMLAnalysePCDATA(Source: widestring;
var Lines: TStringList);
procedure XMLAnalyseTag(const Source: WideString;
var TagName,
AttribSequence: WideString);
procedure XMLAnalyseEntityDef( Source: WideString;
var EntityValue,
SystemLiteral,
PubidLiteral,
NDataName: WideString;
var Error: boolean);
procedure XMLAnalyseNotationDecl(const Decl: WideString;
var SystemLiteral,
PubidLiteral: WideString;
var Error: boolean);
procedure XMLIsolateQuote( Source: WideString;
var content,
rest: WideString;
var QuoteType: WideChar;
var Error: boolean);
function XMLTrunc(const Source: WideString): WideString;
procedure XMLTruncAngularBrackets(const Source: WideString;
var content: WideString;
var Error: boolean);
procedure XMLTruncRoundBrackets(const Source: WideString;
var content: WideString;
var Error: boolean);
function XMLAnalysePubSysId(const PublicId,
SystemId,
NotaName: WideString): WideString;
var
domDocumentFormatList: PdomDocumentFormat = nil;
// add by hyl
function ReadWideCharFromMBCSStream(Stream:TStream):WideChar;
// end add
implementation
// add by hyl
function ReadWideCharFromMBCSStream(Stream:TStream):WideChar;
var
achar : char;
astr : string;
awidechar : array[0..1] of widechar;
begin
Stream.ReadBuffer(achar,1);
if ord(achar)>=$80 then
begin
astr := achar;
Stream.ReadBuffer(achar,1);
astr := astr + achar;
StringToWideChar(astr,@awidechar,sizeof(awidechar));
result:= awidechar[0];
end else
begin
result:=wideChar(ord(achar));
end;
end;
// end add
procedure Register;
begin
RegisterComponents('XML',[TDomImplementation,TXmlToDomParser]);
end;
procedure XMLAnalysePCDATA(Source: widestring;
var Lines: TStringList);
{'Source': Die PCDATA-Sequenz, die analysiert werden soll.
'Lines': Gibt den Inhalt von PCDATA in einzelnen Zeilen
zurück, so daß in einer Zeile entweder nur Leerraum
steht oder überhaupt kein Leerraum.}
var
i: integer;
Line: string;
begin
i:= 0;
Lines.clear;
while (i<length(Source)) do
begin
{No White-space?}
Line:= '';
while (i<length(Source)) do
begin
inc(i);
if IsXmlWhiteSpace(Source[i]) then begin dec(i); break; end;
Line:= concat(Line,Source[i]);
end;
if Line <> '' then Lines.Add(Line);
{White-space?}
Line:= '';
while (i<length(Source)) do
begin
inc(i);
if not IsXmlWhiteSpace(Source[i]) then begin dec(i); break; end;
Line:= concat(Line,Source[i]);
end;
if Line <> '' then Lines.Add(Line);
end;
end;
procedure XmlAnalyseTag(const Source: WideString;
var TagName,
AttribSequence: Widestring);
// 'Source': The tag, to be analyzed.
// 'TagName': Returns the namen of the tag.
// 'AttribSequence': Returns the Attributes, if existing.
var
i,j,sourceLength : integer;
begin
sourceLength:= length(Source); // buffer storage to increase performance
// Evaluate TagName:
i:= 1;
while i <= sourceLength do begin
if IsXmlWhiteSpace(Source[i]) then break;
inc(i);
end;
TagName:= copy(Source,1,i-1);
// Evaluate Attributes:
while i < sourceLength do begin
inc(i);
if not IsXmlWhiteSpace(Source[i]) then break;
end;
j:= length(Source);
while j > i do begin
if not IsXmlWhiteSpace(Source[j]) then break;
dec(j);
end;
AttribSequence:= copy(Source,i,j-i+1);
end;
procedure XMLAnalyseEntityDef( Source: WideString;
var EntityValue,
SystemLiteral,
PubidLiteral,
NDataName: WideString;
var Error: boolean);
// 'Source': The entity definition to be analyzed.
// 'EntityValue','SystemLiteral','PubidLiteral','NDataName':
// Return the respective values, if declared.
// 'Error': Returns 'true', if the entity definition is not well-formed.
var
i : integer;
SingleQuote,DoubleQuote,QuoteType: WideChar;
rest, intro, SystemLit, PubidLit, dummy: WideString;
begin
EntityValue:= '';
SystemLiteral:= '';
SystemLit:= '';
PubidLiteral:= '';
PubidLit:= '';
NDataName:= '';
intro:= '';
Error:= false;
if Length(Source) < 2 then begin Error:= true; exit; end;
SingleQuote:= chr(39); // Code of '.
DoubleQuote:= chr(34); // Code of ".
// Remove leading white space:
i:= 1;
while (i<=length(Source)) do begin
if not IsXmlWhiteSpace(Source[i]) then break;
inc(i);
end;
if i >= Length(Source) then begin Error:= true; exit; end;
dummy:= copy(Source,i,Length(Source)-i+1);
Source:= dummy; // Necessary, because of Delphi's problem when copying WideStrings.
if (Source[1] = SingleQuote) or (Source[1] = DoubleQuote) then begin
XMLIsolateQuote(Source,EntityValue,rest,QuoteType,Error);
if Error then exit;
if rest <> '' then begin Error:= true; exit; end;
if not IsXmlEntityValue(concat(WideString(QuoteType),EntityValue,WideString(QuoteType)))
then begin Error:= true; exit; end;
end else begin
intro:= copy(Source,1,6);
if (intro = 'SYSTEM') or (intro = 'PUBLIC') then begin
Dummy:= copy(Source,7,Length(Source)-6);
Source:= dummy; // Necessary, because of Delphi's problem when copying WideStrings.
if Source = '' then begin Error:= true; exit; end;
if not IsXmlWhiteSpace(Source[1]) then begin Error:= true; exit; end;
if (intro = 'SYSTEM') then begin
XMLIsolateQuote(Source,SystemLit,Source,QuoteType,Error);
if Error then exit;
if not IsXmlSystemLiteral(concat(WideString(QuoteType),SystemLit,WideString(QuoteType)))
then begin Error:= true; exit; end;
end else begin
XMLIsolateQuote(Source,PubidLit,Source,QuoteType,Error);
if Error then exit;
if not IsXmlPubidLiteral(concat(WideString(QuoteType),PubidLit,WideString(QuoteType)))
then begin Error:= true; exit; end;
XMLIsolateQuote(Source,SystemLit,Source,QuoteType,Error);
if Error then exit;
if not IsXmlSystemLiteral(concat(WideString(QuoteType),SystemLit,WideString(QuoteType)))
then begin Error:= true; exit; end;
end;
if Source <> '' then begin
if copy(Source,1,5) = 'NDATA' then begin
dummy:= copy(Source,6,Length(Source)-5);
Source:= XmlTrunc(dummy); // Necessary, because of Delphi's problem when copying WideStrings.
if IsXmlName(Source)
then NDataName:= Source
else begin Error:= true; exit; end;
end else begin Error:= true; exit; end;
end;
end else begin Error:= true; exit; end;
SystemLiteral:= SystemLit;
PubidLiteral:= PubidLit;
end; {if (Source[1] ... }
end;
procedure XMLAnalyseNotationDecl(const Decl: WideString;
var SystemLiteral,
PubidLiteral: WideString;
var Error: boolean);
// 'Source': The notation declaration to be analyzed.
// 'SystemLiteral','PubidLiteral','NDataName':
// Return the respective values, if declared.
// 'Error': Returns 'true', if the notation declaration is not well-formed.
var
QuoteType: WideChar;
intro, SystemLit, PubidLit, dummy, Source: WideString;
begin
SystemLiteral:= '';
SystemLit:= '';
PubidLiteral:= '';
PubidLit:= '';
intro:= '';
Error:= false;
if Length(Decl) < 2 then begin Error:= true; exit; end;
Source:= XMLTrunc(Decl);
intro:= copy(Source,1,6);
if (intro<>'SYSTEM') and (intro<>'PUBLIC') then begin Error:= true; exit; end;
Dummy:= copy(Source,7,Length(Source)-6);
Source:= dummy; // Necessary, because of Delphi's problem when copying WideStrings.
if Source = '' then begin Error:= true; exit; end;
if not IsXmlWhiteSpace(Source[1]) then begin Error:= true; exit; end;
if (intro = 'SYSTEM') then begin
XMLIsolateQuote(Source,SystemLit,dummy,QuoteType,Error);
if Error then exit;
if dummy <> '' then begin Error:= true; exit; end;
if not IsXmlSystemLiteral(concat(WideString(QuoteType),SystemLit,WideString(QuoteType)))
then begin Error:= true; exit; end;
end else begin
XMLIsolateQuote(Source,PubidLit,dummy,QuoteType,Error);
Source:= dummy;
if Error then exit;
if not IsXmlPubidLiteral(concat(WideString(QuoteType),PubidLit,WideString(QuoteType)))
then begin Error:= true; exit; end;
if Source <> '' then begin
if not IsXmlSystemLiteral(Source) then begin Error:= true; exit; end;
SystemLit:= copy(Source,2,length(Source)-2);
end;
end;
SystemLiteral:= SystemLit;
PubidLiteral:= PubidLit;
end;
function XMLTrunc(const Source: WideString): WideString;
// This function removes all white space at the beginning
// or end of 'Source'.
var
i: integer;
begin
Result:= '';
i:= 1;
while (i <= length(Source)) do begin
if not IsXmlWhiteSpace(Source[i]) then break;
inc(i);
end;
if i > Length(Source) then exit;
Result:= copy(Source,i,Length(Source)-i+1);
i:= length(Result);
while i > 0 do begin
if not IsXmlWhiteSpace(Result[i]) then break;
dec(i);
end;
if i = 0
then Result:= ''
else Result:= copy(Result,1,i);
end;
procedure XMLTruncAngularBrackets(const Source: WideString;
var content: WideString;
var Error: boolean);
{Die Prozedur entfernt evtl. vorhandenen White-Space am Anfang und
Ende von 'Source', prüft dann, ob der verbleibende WideString durch
eckige KLammern -- '[' und ']' -- eingerahmt wird. Ist dies der Fall,
wird der Klammer-Inhalt in 'content' zurückgegeben und 'Error' wird
auf 'false' gesetzt. Ist dies nicht der Fall, gibt 'content' einen leeren
WideString ('') zurück und 'Error' wird auf 'true' gesetzt.}
var
BracketStr: WideString;
begin
content:= '';
BracketStr:= XMLTrunc(Source);
if length(BracketStr) < 2 then begin Error:= true; exit; end;
if (BracketStr[1] <> '[') or (BracketStr[length(BracketStr)] <> ']')
then Error:= true
else begin
content:= copy(BracketStr,2,Length(BracketStr)-2);
Error:= false;
end;
end;
procedure XMLTruncRoundBrackets(const Source: WideString;
var content: WideString;
var Error: boolean);
{Die Prozedur entfernt evtl. vorhandenen White-Space am Anfang und Ende
von 'Source', prüft dann, ob der verbleibende WideString durch runde
KLammern -- '(' und ')' -- eingerahmt wird. Ist dies der Fall, wird vom
Klammer-Inhalt erneut evtl. vorhandener Leerraum am Anfang und Ende
entfernt und das Ergebnis in 'content' zurückgegeben sowie 'Error' auf
'false' gesetzt. Ist dies nicht der Fall, gibt 'content' einen leeren
WideString ('') zurück und 'Error' wird auf 'true' gesetzt.}
var
BracketStr: WideString;
begin
content:= '';
BracketStr:= XMLTrunc(Source);
if length(BracketStr) < 2 then begin Error:= true; exit; end;
if (BracketStr[1] <> '(') or (BracketStr[length(BracketStr)] <> ')')
then Error:= true
else begin
content:= XMLTrunc(copy(BracketStr,2,Length(BracketStr)-2));
Error:= false;
end;
end;
procedure XMLIsolateQuote( Source: WideString;
var content,
rest: WideString;
var QuoteType: WideChar;
var Error: boolean);
{Analysiert einen WideString ('Source'): Führender White-Space wird
abgeschnitten, danach wird ein in einfache oder doppelte Anführungs-
zeichen gesetzter Text (der auch leer sein kann) erwartet, dessen Inhalt
in 'content' zurückgegeben wird. 'QuoteType' gibt den Wert der
Anführungszeichen zurück (#39; für einfache und #34; für doppelte
Anführungszeichen). Wird nach dem Entfernen des führenden White-Spaces
kein Anführungszeichen gefunden oder fehlt das korrespondierende
Schlußzeichen, wird die Routine abgebrochen und 'Error = true' zurück-
gegeben. Anschließend wird überprüft, ob dirket nach dem Schlußzeichen
etwas anderes als White-Space folgt (bzw. der WideString zuende ist).
Falls etwas anderes folgt, wird 'Error = true' zurückgegeben. Falls
nicht, wird bis zum nächsten Nicht-White-Space-Zeichen gesucht und der
Rest des WideStrings in 'rest' zurückgegeben. Für alle Fälle, in denen
'Error = true' zurückgegebn wird, werden 'content' und 'rest' als leer
('') und 'QuoteType' als #0; zurückgegeben.}
var
i,quotepos: integer;
SingleQuote,DoubleQuote: WideChar;
dummy: WideString;
begin
content:= '';
rest:= '';
QuoteType:= #0;
if Length(Source) < 2 then begin Error:= true; exit; end;
SingleQuote:= #39; {Code für ein einfaches Anführungszeichen (').}
DoubleQuote:= #34; {Code für ein doppeltes Anführungszeichen (").}
Error:= false;
{White-space am Anfang entfernen:}
i:= 1;
while (i <= length(Source)) do begin
if not IsXmlWhiteSpace(Source[i]) then break;
inc(i);
end;
if i >= Length(Source) then begin Error:= true; exit; end;
Dummy:= copy(Source,i,Length(Source)-i+1);
Source:= dummy; {Diese umständliche Zuweisung ist wegen Delphi-Problem von WideStrings bei copy nötig}
if (Source[1] <> SingleQuote) and (Source[1] <> DoubleQuote)
then begin Error:= true; exit; end;
QuoteType:= Source[1];
Dummy:= Copy(Source,2,Length(Source)-1);
Source:= dummy; {Diese umständliche Zuweisung ist wegen Delphi-Problem von WideStrings bei copy nötig}
QuotePos:= Pos(WideString(QuoteType),Source);
if QuotePos = 0 then begin Error:= true; exit; end;
if Length(Source) > QuotePos then
if not IsXmlWhiteSpace(Source[QuotePos+1])
then begin QuoteType:= #0; Error:= true; exit; end;
content:= Copy(Source,1,QuotePos-1);
{White-Space nach dem Anführungszeichen-Abschnitt entfernen:}
i:= QuotePos + 1;
while (i <= length(Source)) do begin
if not IsXmlWhiteSpace(Source[i]) then break;
inc(i);
end;
if i <= Length(Source) then rest:= copy(Source,i,Length(Source)-i+1);
end;
function XMLAnalysePubSysId(const PublicId,
SystemId,
NotaName: WideString): WideString;
var
sQuote,dQuote,SystemIdContent,PublicIdContent: WideString;
begin
sQuote:= #$0027;
dQuote:= '"';
Result:= '';
if not IsXmlName(NotaName)
then EConvertError.CreateFmt('%S is not a valid NotaName value.',[NotaName]);;
if IsXMLSystemLiteral(concat(dQuote,SystemId,dQuote))
then SystemIdContent:= concat(dQuote,SystemId,dQuote)
else if IsXMLSystemLiteral(concat(sQuote,SystemId,sQuote))
then SystemIdContent:= concat(sQuote,SystemId,sQuote)
else EConvertError.CreateFmt('%S is not a valid SystemId value.',[SystemId]);;
if IsXMLPubidLiteral(concat(dQuote,PublicId,dQuote))
then PublicIdContent:= concat(dQuote,PublicId,dQuote)
else if IsXMLPubidLiteral(concat(sQuote,PublicId,sQuote))
then PublicIdContent:= concat(sQuote,PublicId,sQuote)
else EConvertError.CreateFmt('%S is not a valid PublicId value.',[PublicId]);;
if PublicId = '' then begin
if SystemId = '' then begin
Result:= concat(Result,WideString(' SYSTEM "" '));
end else begin
Result:= concat(Result,WideString(' SYSTEM '),SystemIdContent,WideString(' '));
end;
end else begin
if SystemId = '' then begin
Result:= concat(Result,WideString(' PUBLIC '),PublicIdContent,WideString(' '));
end else begin
Result:= concat(Result,WideString(' PUBLIC '),PublicIdContent,WideString(' '),SystemIdContent,WideString(' '));
end;
end; {if ...}
if NotaName <> ''
then Result:= concat(Result,WideString('NDATA '),NotaName,WideString(' '));
end;
function HasCircularReference(const Entity: TdomNode): boolean;
{Result = 'false': Es liegt keine zirkuläre Referenz vor.
Result = 'true': Es liegt eine zirkuläre Referenz vor.}
var
EntityList1,EntityList2,EntityList3: TList;
EntityDec: TdomCustomEntity;
i,j: integer;
begin
Result:= false;
if not assigned(Entity) then exit;
if not ( (Entity.nodetype = ntEntity_Node)
or (Entity.nodetype = ntParameter_Entity_Node) ) then exit;
EntityList1:= TList.create;
EntityList2:= TList.create;
EntityList3:= TList.create;
try
EntityList1.clear;
EntityList2.clear;
EntityList3.clear;
EntityList1.Add(Entity);
while EntityList1.Count > 0 do begin
for i:= 0 to EntityList1.Count -1 do begin
for j:= 0 to TdomNode(EntityList1[i]).ChildNodes.Length -1 do
case TdomNode(EntityList1[i]).ChildNodes.item(j).NodeType of
ntEntity_Reference_Node,ntParameter_Entity_Reference_Node: begin
EntityDec:= (TdomNode(EntityList1[i]).ChildNodes.item(j) as TdomReference).Declaration;
if assigned(EntityDec) then begin
if EntityList3.IndexOf(EntityDec) > -1 then begin
Result:= true;
exit;
end;
if EntityList2.IndexOf(EntityDec) = -1
then EntityList2.Add(EntityDec);
end; {if assigned ...}
end; {ntEntity_Reference_Node}
end; {case ...}
end; {for i:= 0 ...}
EntityList1.clear;
for i:= 0 to EntityList2.Count -1 do begin
EntityList1.add(EntityList2[i]);
EntityList3.Add(EntityList2[i]);
end;
EntityList2.clear;
end; {while ...}
finally
EntityList1.free;
EntityList2.free;
EntityList3.free;
end;
end;
function XMLExtractPrefix(const qualifiedName: wideString): wideString;
var
colonpos: integer;
prefix,localpart: WideString;
begin
prefix:= '';
colonpos:= pos(':',qualifiedName);
if colonpos = 0
then localpart:= qualifiedName
else begin
prefix:= copy(qualifiedName,1,length(qualifiedName)-colonpos);
localpart:= copy(qualifiedName,colonpos+1,length(qualifiedName)-colonpos);
if not IsXmlPrefix(prefix)
then raise EInvalid_Character_Err.create('Invalid character error.');
end;
if not IsXmlLocalPart(localpart)
then raise EInvalid_Character_Err.create('Invalid character error.');
result:= prefix;
end;
function XMLExtractLocalName(const qualifiedName: wideString): wideString;
var
colonpos: integer;
prefix,localpart: WideString;
begin
colonpos:= pos(':',qualifiedName);
if colonpos = 0
then localpart:= qualifiedName
else begin
prefix:= copy(qualifiedName,1,length(qualifiedName)-colonpos);
localpart:= copy(qualifiedName,colonpos+1,length(qualifiedName)-colonpos);
if not IsXmlPrefix(prefix)
then raise EInvalid_Character_Err.create('Invalid character error.');
end;
if not IsXmlLocalPart(localpart)
then raise EInvalid_Character_Err.create('Invalid character error.');
result:= localpart;
end;
function IsXmlChar(const S: WideChar): boolean;
begin
Case Word(S) of
$0009,$000A,$000D,$0020..$D7FF,$E000..$FFFD, // Unicode below $FFFF
$D800..$DBFF, // High surrogate of Unicode character [$10000..$10FFFF]
$DC00..$DFFF: // Low surrogate of Unicode character [$10000..$10FFFF]
result:= true;
else
result:= false;
end;
end;
function IsXmlWhiteSpace(const S: WideChar): boolean;
begin
Case Word(S) of
$0009,$000A,$000D,$0020:
result:= true;
else
result:= false;
end;
end;
function IsXmlLetter(const S: WideChar): boolean;
begin
Result:= IsXmlIdeographic(S) or IsXmlBaseChar(S);
end;
function IsXmlBaseChar(const S: WideChar): boolean;
begin
Case Word(S) of
$0041..$005a,$0061..$007a,$00c0..$00d6,$00d8..$00f6,$00f8..$00ff,
$0100..$0131,$0134..$013E,$0141..$0148,$014a..$017e,$0180..$01c3,
$01cd..$01f0,$01f4..$01f5,$01fa..$0217,$0250..$02a8,$02bb..$02c1,
$0386,$0388..$038a,$038c,$038e..$03a1,$03a3..$03ce,$03D0..$03D6,
$03DA,$03DC,$03DE,$03E0,$03E2..$03F3,$0401..$040C,$040E..$044F,
$0451..$045C,$045E..$0481,$0490..$04C4,$04C7..$04C8,$04CB..$04CC,
$04D0..$04EB,$04EE..$04F5,$04F8..$04F9,$0531..$0556,$0559,
$0561..$0586,$05D0..$05EA,$05F0..$05F2,$0621..$063A,$0641..$064A,
$0671..$06B7,$06BA..$06BE,$06C0..$06CE,$06D0..$06D3,$06D5,
$06E5..$06E6,$0905..$0939,$093D,$0958..$0961,$0985..$098C,
$098F..$0990,$0993..$09A8,$09AA..$09B0,$09B2,$09B6..$09B9,
$09DC..$09DD,$09DF..$09E1,$09F0..$09F1,$0A05..$0A0A,$0A0F..$0A10,
$0A13..$0A28,$0A2A..$0A30,$0A32..$0A33,$0A35..$0A36,$0A38..$0A39,
$0A59..$0A5C,$0A5E,$0A72..$0A74,$0A85..$0A8B,$0A8D,$0A8F..$0A91,
$0A93..$0AA8,$0AAA..$0AB0,$0AB2..$0AB3,$0AB5..$0AB9,$0ABD,$0AE0,
$0B05..$0B0C,$0B0F..$0B10,$0B13..$0B28,$0B2A..$0B30,$0B32..$0B33,
$0B36..$0B39,$0B3D,$0B5C..$0B5D,$0B5F..$0B61,$0B85..$0B8A,
$0B8E..$0B90,$0B92..$0B95,$0B99..$0B9A,$0B9C,$0B9E..$0B9F,
$0BA3..$0BA4,$0BA8..$0BAA,$0BAE..$0BB5,$0BB7..$0BB9,$0C05..$0C0C,
$0C0E..$0C10,$0C12..$0C28,$0C2A..$0C33,$0C35..$0C39,$0C60..$0C61,
$0C85..$0C8C,$0C8E..$0C90,$0C92..$0CA8,$0CAA..$0CB3,$0CB5..$0CB9,
$0CDE,$0CE0..$0CE1,$0D05..$0D0C,$0D0E..$0D10,$0D12..$0D28,
$0D2A..$0D39,$0D60..$0D61,$0E01..$0E2E,$0E30,$0E32..$0E33,
$0E40..$0E45,$0E81..$0E82,$0E84,$0E87..$0E88,$0E8A,$0E8D,
$0E94..$0E97,$0E99..$0E9F,$0EA1..$0EA3,$0EA5,$0EA7,$0EAA..$0EAB,
$0EAD..$0EAE,$0EB0,$0EB2..$0EB3,$0EBD,$0EC0..$0EC4,$0F40..$0F47,
$0F49..$0F69,$10A0..$10C5,$10D0..$10F6,$1100,$1102..$1103,
$1105..$1107,$1109,$110B..$110C,$110E..$1112,$113C,$113E,$1140,
$114C,$114E,$1150,$1154..$1155,$1159,$115F..$1161,$1163,$1165,
$1167,$1169,$116D..$116E,$1172..$1173,$1175,$119E,$11A8,$11AB,
$11AE..$11AF,$11B7..$11B8,$11BA,$11BC..$11C2,$11EB,$11F0,$11F9,
$1E00..$1E9B,$1EA0..$1EF9,$1F00..$1F15,$1F18..$1F1D,$1F20..$1F45,
$1F48..$1F4D,$1F50..$1F57,$1F59,$1F5B,$1F5D,$1F5F..$1F7D,
$1F80..$1FB4,$1FB6..$1FBC,$1FBE,$1FC2..$1FC4,$1FC6..$1FCC,
$1FD0..$1FD3,$1FD6..$1FDB,$1FE0..$1FEC,$1FF2..$1FF4,$1FF6..$1FFC,
$2126,$212A..$212B,$212E,$2180..$2182,$3041..$3094,$30A1..$30FA,
$3105..$312C,$AC00..$d7a3:
result:= true;
else
result:= false;
end;
end;
function IsXmlIdeographic(const S: WideChar): boolean;
begin
Case Word(S) of
$4E00..$9FA5,$3007,$3021..$3029:
result:= true;
else
result:= false;
end;
end;
function IsXmlCombiningChar(const S: WideChar): boolean;
begin
Case Word(S) of
$0300..$0345,$0360..$0361,$0483..$0486,$0591..$05A1,$05A3..$05B9,
$05BB..$05BD,$05BF,$05C1..$05C2,$05C4,$064B..$0652,$0670,
$06D6..$06DC,$06DD..$06DF,$06E0..$06E4,$06E7..$06E8,$06EA..$06ED,
$0901..$0903,$093C,$093E..$094C,$094D,$0951..$0954,$0962..$0963,
$0981..$0983,$09BC,$09BE,$09BF,$09C0..$09C4,$09C7..$09C8,
$09CB..$09CD,$09D7,$09E2..$09E3,$0A02,$0A3C,$0A3E,$0A3F,
$0A40..$0A42,$0A47..$0A48,$0A4B..$0A4D,$0A70..$0A71,$0A81..$0A83,
$0ABC,$0ABE..$0AC5,$0AC7..$0AC9,$0ACB..$0ACD,$0B01..$0B03,$0B3C,
$0B3E..$0B43,$0B47..$0B48,$0B4B..$0B4D,$0B56..$0B57,$0B82..$0B83,
$0BBE..$0BC2,$0BC6..$0BC8,$0BCA..$0BCD,$0BD7,$0C01..$0C03,
$0C3E..$0C44,$0C46..$0C48,$0C4A..$0C4D,$0C55..$0C56,$0C82..$0C83,
$0CBE..$0CC4,$0CC6..$0CC8,$0CCA..$0CCD,$0CD5..$0CD6,$0D02..$0D03,
$0D3E..$0D43,$0D46..$0D48,$0D4A..$0D4D,$0D57,$0E31,$0E34..$0E3A,
$0E47..$0E4E,$0EB1,$0EB4..$0EB9,$0EBB..$0EBC,$0EC8..$0ECD,
$0F18..$0F19,$0F35,$0F37,$0F39,$0F3E,$0F3F,$0F71..$0F84,
$0F86..$0F8B,$0F90..$0F95,$0F97,$0F99..$0FAD,$0FB1..$0FB7,$0FB9,
$20D0..$20DC,$20E1,$302A..$302F,$3099,$309A:
result:= true;
else
result:= false;
end;
end;
function IsXmlDigit(const S: WideChar): boolean;
begin
Case Word(S) of
$0030..$0039,$0660..$0669,$06F0..$06F9,$0966..$096F,$09E6..$09EF,
$0A66..$0A6F,$0AE6..$0AEF,$0B66..$0B6F,$0BE7..$0BEF,$0C66..$0C6F,
$0CE6..$0CEF,$0D66..$0D6F,$0E50..$0E59,$0ED0..$0ED9,$0F20..$0F29:
result:= true;
else
result:= false;
end;
end;
function IsXmlExtender(const S: WideChar): boolean;
begin
Case Word(S) of
$00B7,$02D0,$02D1,$0387,$0640,$0E46,$0EC6,$3005,$3031..$3035,
$309D..$309E,$30FC..$30FE:
result:= true;
else
result:= false;
end;
end;
function IsXmlNameChar(const S: WideChar): boolean;
begin
if IsXmlLetter(S) or IsXmlDigit(S) or IsXmlCombiningChar(S)
or IsXmlExtender(S) or (S='.') or (S='-') or (S='_') or (S=':')
then Result:= true
else Result:= false;
end;
function IsXmlPubidChar(const S: WideChar): boolean;
begin
if (S=#$20) or (S=#$D) or (S=#$A) or
((S>='a') and (S<='z')) or
((S>='A') and (S<='Z')) or
((S>='0') and (S<='9')) or
(S='-') or (S=#$27) or (S='(') or (S=')') or (S='+') or (S=',') or
(S='.') or (S='/') or (S=':') or (S='=') or (S='?') or (S=';') or
(S='!') or (S='*') or (S='#') or (S='@') or (S='$') or (S='_') or
(S='%')
then Result:= true
else Result:= false;
end;
function IsXmlS(const S: WideString): boolean;
var
i: integer;
begin
Result:= true;
if Length(S) = 0 then begin Result:= false; exit; end;
for i:= 1 to length(S) do
if not IsXmlWhiteSpace((PWideChar(S)+i-1)^)
then begin Result:= false; exit; end;
end;
function IsXmlName(const S: WideString): boolean;
var
i: integer;
begin
Result:= true;
if Length(S) = 0 then begin Result:= false; exit; end;
if not ( IsXmlLetter(PWideChar(S)^)
or (PWideChar(S)^ = '_')
or (PWideChar(S)^ = ':') )
then begin Result:= false; exit; end;
for i:= 2 to length(S) do
if not IsXmlNameChar((PWideChar(S)+i-1)^)
then begin Result:= false; exit; end;
end;
function IsXmlNames(const S: WideString): boolean;
var
i,j: integer;
piece: WideString;
begin
Result:= true;
if Length(S) = 0 then begin Result:= false; exit; end;
if IsXmlWhiteSpace(S[length(S)]) then begin Result:= false; exit; end;
i:= 0;
j:= 1;
while i < length(S) do begin
inc(i);
if IsXmlWhiteSpace(S[i]) or (i = length(S)) then begin
if i = length(S)
then piece:= XmlTrunc(copy(S,j,i+1-j))
else begin
piece:= XmlTrunc(copy(S,j,i-j));
j:= i+1;
while IsXmlWhiteSpace(S[j]) do inc(j);
i:= j;
end;
if not IsXmlName(piece) then begin Result:= false; exit; end;
end; {if ...}
end; {while ...}
end;
function IsXmlNmtoken(const S: WideString): boolean;
var
i: integer;
begin
Result:= true;
if Length(S) = 0 then begin Result:= false; exit; end;
for i:= 1 to length(S) do
if not IsXmlNameChar((PWideChar(S)+i-1)^)
then begin Result:= false; exit; end;
end;
function IsXmlNmtokens(const S: WideString): boolean;
var
i,j: integer;
piece: WideString;
begin
Result:= true;
if Length(S) = 0 then begin Result:= false; exit; end;
if IsXmlWhiteSpace(S[length(S)]) then begin Result:= false; exit; end;
i:= 0;
j:= 1;
while i < length(S) do begin
inc(i);
if IsXmlWhiteSpace(S[i]) or (i = length(S)) then begin
if i = length(S)
then piece:= XmlTrunc(copy(S,j,i+1-j))
else begin
piece:= XmlTrunc(copy(S,j,i-j));
j:= i+1;
while IsXmlWhiteSpace(S[j]) do inc(j);
i:= j;
end;
if not IsXmlNmtoken(piece) then begin Result:= false; exit; end;
end; {if ...}
end; {while ...}
end;
function IsXmlCharRef(const S: WideString): boolean;
var
i: integer;
SChar: widechar;
begin
Result:= true;
if copy(S,length(S),1) <> ';' then begin result:= false; exit; end;
if copy(S,1,3) = '&#x' then begin
if Length(S) < 5 then begin Result:= false; exit; end;
for i:= 4 to length(S)-1 do begin
SChar:= WideChar((PWideChar(S)+i-1)^);
if not ( (SChar >= '0') and (SChar <= '9') )
and not ( (SChar >= 'a') and (SChar <= 'f') )
and not ( (SChar >= 'A') and (SChar <= 'F') )
then begin Result:= false; exit; end;
end;
end else begin
if Length(S) < 4 then begin Result:= false; exit; end;
if copy(S,1,2) <> '&#' then begin Result:= false; exit; end;
for i:= 3 to length(S)-1 do begin
SChar:= WideChar((PWideChar(S)+i-1)^);
if not ( (SChar >= '0') and (SChar <= '9') )
then begin Result:= false; exit; end;
end;
end;
end;
function IsXmlEntityRef(const S: WideString): boolean;
begin
if pos('&',S) <> 1 then begin result:= false; exit; end;
if copy(S,length(S),1) <> ';' then begin result:= false; exit; end;
Result:= IsXmlName(copy(S,2,length(S)-2));
end;
function IsXmlPEReference(const S: WideString): boolean;
begin
if pos('%',S) <> 1 then begin result:= false; exit; end;
if copy(S,length(S),1) <> ';' then begin result:= false; exit; end;
Result:= IsXmlName(copy(S,2,length(S)-2));
end;
function IsXmlReference(const S: WideString): boolean;
begin
if IsXmlEntityRef(s) or IsXmlCharRef(s)
then result:= true
else result:= false;
end;
function IsXmlEntityValue(const S: WideString): boolean;
var
i,j,indexpos: integer;
SChar, SChar2, ForbittenQuote, sQuote, dQuote: widechar;
begin
sQuote:= #$0027;
dQuote:= '"';
Result:= true;
if Length(S) < 2 then begin Result:= false; exit; end;
if (S[length(S)] = sQuote) and (S[1] = sQuote) {single quotes}
then ForbittenQuote:= sQuote
else if (S[length(S)] = dQuote) and (S[1] = dQuote) {double quotes}
then ForbittenQuote:= dQuote
else begin Result:= false; exit; end;
i:= 2;
while i < length(S) do begin
SChar:= WideChar((PWideChar(S)+i-1)^);
if IsUtf16LowSurrogate(sChar) then begin Result:= false; exit; end;
if IsUtf16HighSurrogate(SChar) then begin
if i+1 = length(s) then begin Result:= false; exit; end;
inc(i);
SChar:= WideChar((PWideChar(S)+i-1)^);
if not IsUtf16LowSurrogate(SChar) then begin Result:= false; exit; end;
end;
if not IsXmlChar(sChar) then begin Result:= false; exit; end;
if SChar = ForbittenQuote then begin Result:= false; exit; end;
if SChar = '%' then begin {PEReference?}
indexpos:= -1;
for j:= i+1 to length(S)-1 do begin
SChar2:= WideChar((PWideChar(S)+j-1)^);
if SChar2 = ';' then begin indexpos:= j; break; end;
end;
if indexpos = -1 then begin Result:= false; exit; end;
if not IsXmlPEReference(copy(S,i,j-i+1)) then begin Result:= false; exit; end;
i:= j;
end;
if SChar = '&' then begin {Reference?}
indexpos:= -1;
for j:= i+1 to length(S)-1 do begin
SChar2:= WideChar((PWideChar(S)+j-1)^);
if SChar2 = ';' then begin indexpos:= j; break; end;
end;
if indexpos = -1 then begin Result:= false; exit; end;
if not IsXmlReference(copy(S,i,j-i+1)) then begin Result:= false; exit; end;
i:= j;
end;
inc(i);
end;
end;
function IsXmlAttValue(const S: WideString): boolean;
var
i,j,indexpos: integer;
SChar, SChar2, ForbittenQuote, sQuote, dQuote: widechar;
begin
sQuote:= #$0027;
dQuote:= '"';
Result:= true;
if Length(S) < 2 then begin Result:= false; exit; end;
if (S[length(S)] = sQuote) and (S[1] = sQuote) {single quotes}
then ForbittenQuote:= sQuote
else if (S[length(S)] = dQuote) and (S[1] = dQuote) {double quotes}
then ForbittenQuote:= dQuote
else begin Result:= false; exit; end;
i:= 2;
while i < length(S) do begin
SChar:= WideChar((PWideChar(S)+i-1)^);
if IsUtf16LowSurrogate(sChar) then begin Result:= false; exit; end;
if IsUtf16HighSurrogate(SChar) then begin
if i+1 = length(s) then begin Result:= false; exit; end;
inc(i);
SChar:= WideChar((PWideChar(S)+i-1)^);
if not IsUtf16LowSurrogate(SChar) then begin Result:= false; exit; end;
end;
if not IsXmlChar(sChar) then begin Result:= false; exit; end;
if SChar = ForbittenQuote then begin Result:= false; exit; end;
if SChar = '<' then begin Result:= false; exit; end;
if SChar = '&' then begin {Reference?}
indexpos:= -1;
for j:= i+1 to length(S)-1 do begin
SChar2:= WideChar((PWideChar(S)+j-1)^);
if SChar2 = ';' then begin indexpos:= j; break; end;
end;
if indexpos = -1 then begin Result:= false; exit; end;
if not IsXmlReference(copy(S,i,j-i+1)) then begin Result:= false; exit; end;
i:= j;
end;
inc(i);
end;
end;
function IsXmlSystemLiteral(const S: WideString): boolean;
var
i: integer;
SChar, ForbittenQuote, sQuote, dQuote: widechar;
begin
Result:= true;
sQuote:= #$0027;
dQuote:= '"';
if Length(S) < 2 then begin Result:= false; exit; end;
if (S[length(S)] = sQuote) and (S[1] = sQuote) {single quotes}
then ForbittenQuote:= sQuote
else if (S[length(S)] = dQuote) and (S[1] = dQuote) {double quotes}
then ForbittenQuote:= dQuote
else begin Result:= false; exit; end;
i:= 1;
while i < length(S)-1 do begin
inc(i);
SChar:= WideChar((PWideChar(S)+i-1)^);
if IsUtf16LowSurrogate(sChar) then begin Result:= false; exit; end;
if IsUtf16HighSurrogate(SChar) then begin
if i+1 = length(s) then begin Result:= false; exit; end;
inc(i);
SChar:= WideChar((PWideChar(S)+i-1)^);
if not IsUtf16LowSurrogate(SChar) then begin Result:= false; exit; end;
end;
if not IsXmlChar(sChar) then begin Result:= false; exit; end;
if SChar = ForbittenQuote then begin Result:= false; exit; end;
end;
end;
function IsXmlPubidLiteral(const S: WideString): boolean;
var
i: integer;
SChar, ForbittenQuote,sQuote, dQuote: widechar;
begin
Result:= true;
sQuote:= #$0027;
dQuote:= '"';
if Length(S) < 2 then begin Result:= false; exit; end;
if (S[length(S)] = sQuote) and (S[1] = sQuote) {single quotes}
then ForbittenQuote:= sQuote
else if (S[length(S)] = dQuote) and (S[1] = dQuote) {double quotes}
then ForbittenQuote:= dQuote
else begin Result:= false; exit; end;
i:= 1;
while i < length(S)-1 do begin
inc(i);
SChar:= WideChar((PWideChar(S)+i-1)^);
if IsUtf16LowSurrogate(sChar) then begin Result:= false; exit; end;
if IsUtf16HighSurrogate(SChar) then begin
if i+1 = length(s) then begin Result:= false; exit; end;
inc(i);
SChar:= WideChar((PWideChar(S)+i-1)^);
if not IsUtf16LowSurrogate(SChar) then begin Result:= false; exit; end;
end;
if not IsXmlChar(sChar) then begin Result:= false; exit; end;
if SChar = ForbittenQuote then begin Result:= false; exit; end;
if not IsXmlPubidChar(SChar) then begin Result:= false; exit; end;
end;
end;
function IsXmlCharData(const S: WideString): boolean;
var
i: integer;
SChar: wideChar;
begin
Result:= true;
if pos(']]>',S) > 0 then begin result:= false; exit; end;
i:= 0;
while i < length(S)-1 do begin
inc(i);
SChar:= S[i];
if IsUtf16LowSurrogate(sChar) then begin Result:= false; exit; end;
if IsUtf16HighSurrogate(SChar) then begin
if i = length(s) then begin Result:= false; exit; end;
inc(i);
SChar:= S[i];
if not IsUtf16LowSurrogate(SChar) then begin Result:= false; exit; end;
end;
if not IsXmlChar(sChar) then begin Result:= false; exit; end;
if SChar = '<' then begin Result:= false; exit; end;
if SChar = '&' then begin Result:= false; exit; end;
end;
end;
function IsXmlPITarget(const S: WideString): boolean;
begin
Result:= IsXmlName(S);
if length(S) = 3 then
if ((S[1] = 'X') or (S[1] = 'x')) and
((S[2] = 'M') or (S[2] = 'm')) and
((S[3] = 'L') or (S[3] = 'l'))
then Result:= false;
end;
function IsXmlVersionNum(const S: WideString): boolean;
var
SChar: widechar;
i: integer;
begin
Result:= true;
if Length(S) = 0 then begin Result:= false; exit; end;
for i:=1 to length(S) do begin
SChar:= S[i];
if not ( ((SChar >= 'a') and (SChar <= 'z')) or
((SChar >= 'A') and (SChar <= 'Z')) or
((SChar >= '0') and (SChar <= '9')) or
(SChar = '_') or (SChar = '.') or
(SChar = ':') or (SChar = '-') )
then Result:= false; exit;
end;
end;
function IsXmlEncName(const S: WideString): boolean;
var
SChar: widechar;
i: integer;
begin
Result:= true;
if Length(S) = 0 then begin Result:= false; exit; end;
SChar:= S[1];
if not ( ((SChar >= 'a') and (SChar <= 'z')) or
((SChar >= 'A') and (SChar <= 'Z')) )
then Result:= false; exit;
for i:=2 to length(S) do begin
SChar:= S[i];
if not ( ((SChar >= 'a') and (SChar <= 'z')) or
((SChar >= 'A') and (SChar <= 'Z')) or
((SChar >= '0') and (SChar <= '9')) or
(SChar = '.') or (SChar = '_') or (SChar = '-') )
then Result:= false; exit;
end;
end;
function IsXmlStringType(const S: WideString): boolean;
begin
if S = 'CDATA'
then Result:= true
else Result:= false;
end;
function IsXmlTokenizedType(const S: WideString): boolean;
begin
if (S='ID') or (S='IDREF') or (S='IDREFS') or (S='ENTITY') or
(S='ENTITIES') or (S='NMTOKEN') or (S='NMTOKENS')
then Result:= true
else Result:= false;
end;
function IsXmlNCNameChar(const s: WideChar): boolean;
begin
if IsXmlLetter(S) or IsXmlDigit(S) or IsXmlCombiningChar(S)
or IsXmlExtender(S) or (S='.') or (S='-') or (S='_')
then Result:= true
else Result:= false;
end;
function IsXmlNCName(const S: WideString): boolean;
var
i: integer;
begin
Result:= true;
if Length(S) = 0 then begin Result:= false; exit; end;
if not ( IsXmlLetter(PWideChar(S)^)
or (PWideChar(S)^ = '_') )
then begin Result:= false; exit; end;
for i:= 2 to length(S) do
if not IsXmlNCNameChar(S[i])
then begin Result:= false; exit; end;
end;
function IsXmlDefaultAttName(const S: WideString): boolean;
begin
if S='xmls'
then Result:= true
else Result:= false;
end;
function IsXmlPrefixedAttName(const S: WideString): boolean;
var
piece: WideString;
begin
if copy(S,1,6) = 'xmlns:' then begin
piece:= copy(S,7,length(S)-6);
Result:= IsXmlNCName(piece);
end else Result:= false;
end;
function IsXmlNSAttName(const S: WideString): boolean;
begin
Result:= (IsXmlPrefixedAttName(S) or IsXmlDefaultAttName(S));
end;
function IsXmlLocalPart(const S: WideString): boolean;
begin
Result:= IsXmlNCName(S);
end;
function IsXmlPrefix(const S: WideString): boolean;
begin
Result:= IsXmlNCName(S);
end;
function IsXmlQName(const S: WideString): boolean;
var
colonpos: integer;
prefix,localpart: WideString;
begin
colonpos:= pos(':',S);
if colonpos = 0
then result:= IsXmlLocalPart(S)
else begin
prefix:= copy(S,1,length(S)-colonpos);
localpart:= copy(S,colonpos+1,length(S)-colonpos);
result:= IsXmlPrefix(prefix) and IsXmlLocalPart(localpart);
end;
end;
function XmlIntToCharRef(const value: integer): wideString;
begin
Result:= concat('&#',intToStr(value),';');
end;
function XmlCharRefToInt(const S: WideString): integer;
var
value: word;
begin
if not IsXmlCharRef(S)
then raise EConvertError.CreateFmt('%S is not a valid XmlCharRef value.',[S]);
if S[3] = 'x'
then Result:= StrToInt(concat('$',copy(S,4,length(S)-4))) // Hex
else Result:= StrToInt(copy(S,3,length(S)-3)); // Dec
if Result > $10FFFF
then raise EConvertError.CreateFmt('%S is not a valid XmlCharRef value.',[S]);
if Result < $10000 then begin
Value:= Result;
if not IsXmlChar(WideChar(value))
then raise EConvertError.CreateFmt('%S is not a valid XmlCharRef value.',[S]);
end;
end;
function XmlCharRefToStr(const S: WideString): WideString;
var
value: integer;
smallValue: word;
begin
value:= XmlCharRefToInt(S);
if value < $10000 then begin
smallValue:= value;
Result:= WideString(WideChar(smallValue));
end else
Result:= concat(WideString(Utf16HighSurrogate(value)),
WideString(Utf16LowSurrogate(value)));
end;
function XmlStrToCharRef(const S: WideString): WideString;
var
SChar,LowSur: widechar;
i: integer;
begin
Result:= '';
i:= 0;
while i < length(S)-1 do begin
inc(i);
SChar:= S[i];
if not isXmlChar(SChar)
then raise EConvertError.CreateFmt('String contains invalid character %S.',[S]);
if isUtf16LowSurrogate(SChar)
then raise EConvertError.CreateFmt('Low surrogate %S without high surrogate.',[S]);
if IsUtf16HighSurrogate(SChar) then begin
if i+1 = length(s)
then raise EConvertError.CreateFmt('High surrogate %S without low surrogate at end of string.',[S]);
inc(i);
lowSur:= S[i];
if not IsUtf16LowSurrogate(lowSur)
then raise EConvertError.CreateFmt('High surrogate %S without low surrogate.',[S]);
Result:= concat(result,XmlIntToCharRef(Utf16SurrogateToInt(SChar,lowSur)));
end else begin
Result:= concat(result,XmlIntToCharRef(ord(SChar)));
end;
end; {for ...}
end;
function UTF8ToUTF16BEStr(const s: string): WideString;
// Converts a UTF-8 string into a UTF-16 WideString;
// The widestring starts with a Byte Order Mark.
// No special conversions (e.g. on line breaks) and
// no XML-char checking are done.
// - This function was provided by Ernst van der Pols -
const
MaxCode: array[1..6] of integer = ($7F,$7FF,$FFFF,$1FFFFF,$3FFFFFF,$7FFFFFFF);
var
i, j, CharSize, mask, ucs4: integer;
c, first: char;
begin
SetLength(Result,Length(s)+1); // assume no or little above-ASCII-chars
j:=1; // keep track of actual length
Result[j]:=WideChar($FEFF); // start with BOM
i:=0;
while i<length(s) do
begin
Inc(i); c:=s[i];
if ord(c)>=$80 then // UTF-8 sequence
begin
CharSize:=1;
first:=c; mask:=$40; ucs4:=ord(c);
if (ord(c) and $C0<>$C0) then
raise EConvertError.CreateFmt('Invalid UTF-8 sequence %2.2X',[ord(c)]);
while (mask and ord(first)<>0) do
begin
// read next character of stream
if i=length(s) then
raise EConvertError.CreateFmt('Aborted UTF-8 sequence "%s"',[Copy(s,i-CharSize,CharSize)]);
Inc(i); c:=s[i];
if (ord(c) and $C0<>$80) then
raise EConvertError.CreateFmt('Invalid UTF-8 sequence $%2.2X',[ord(c)]);
ucs4:=(ucs4 shl 6) or (ord(c) and $3F); // add bits to result
Inc(CharSize); // increase sequence length
mask:=mask shr 1; // adjust mask
end;
if (CharSize>6) then // no 0 bit in sequence header 'first'
raise EConvertError.CreateFmt('Invalid UTF-8 sequence "%s"',[Copy(s,i-CharSize,CharSize)]);
ucs4:=ucs4 and MaxCode[CharSize]; // dispose of header bits
// check for invalid sequence as suggested by RFC2279
if ((CharSize>1) and (ucs4<=MaxCode[CharSize-1])) then
raise EConvertError.CreateFmt('Invalid UTF-8 encoding "%s"',[Copy(s,i-CharSize,CharSize)]);
// convert non-ASCII UCS-4 to UTF-16 if possible
case ucs4 of
$00000080..$0000D7FF,$0000E000..$0000FFFD:
begin
Inc(j); Result[j]:=WideChar(ord(c));
end;
$0000D800..$0000DFFF,$0000FFFE,$0000FFFF:
raise EConvertError.CreateFmt('Invalid UCS-4 character $%8.8X',[ucs4]);
$00010000..$0010FFFF:
begin
// add high surrogate to content as if it was processed earlier
Inc(j); Result[j]:=Utf16HighSurrogate(ucs4); // assign high surrogate
Inc(j); Result[j]:=Utf16LowSurrogate(ucs4); // assign low surrogate
end;
else // out of UTF-16 range
raise EConvertError.CreateFmt('Cannot convert $%8.8X to UTF-16',[ucs4]);
end;
end
else // ASCII char
begin
Inc(j); Result[j]:=WideChar(ord(c));
end;
end;
SetLength(Result,j); // set to correct length
end;
function UTF16BEToUTF8Str(const ws: WideString): string;
// Converts a UTF-16BE widestring into a UTF-8 encoded string
// (and expands LF to CR+LF). The implementation is optimized
// for code that contains mainly ASCII characters (<=#$7F) and
// little above ASCII-chars. The buffer for the Result is set
// to the widestrings-length. With each non-ASCII character the
// Result-buffer is expanded (by the Insert-function), which leads
// to performance problems when one processes e.g. mainly Japanese
// documents.
// - This function was provided by Ernst van der Pols -
var i, j: integer;
ucs4: integer;
wc: WideChar;
s: string;
function UCS4CodeToUTF8String(code: integer): string;
const
MaxCode: array[0..5] of integer = ($7F,$7FF,$FFFF,$1FFFFF,$3FFFFFF,$7FFFFFFF);
FirstOctet: array[0..5] of byte = (0,$C0,$E0,$F0,$F8,$FC);
var
mo, i: integer;
begin
mo:=0; // get number of octets
while ((code>MaxCode[mo]) and (mo<5)) do Inc(mo);
SetLength(Result,mo+1); // set result to correct length
for i:=mo+1 downto 2 do // fill octets from rear end
begin
Result[i]:=char($80 or (code and $3F));
code:=code shr 6;
end; // fill first octet
Result[1]:=char(FirstOctet[mo] or code);
end;
begin
SetLength(Result,Length(ws)); // assume no above-ASCII-chars
j:=0; // keep track of actual length
i:=0;
if ws[1] = #$feff then inc(i); // Test for BOM
while i<length(ws) do
begin
Inc(i);
wc:=ws[i];
case word(wc) of
$0020..$007F,$0009,$000D: // plain ASCII
begin
Inc(j);
Result[j]:=Char(wc);
end;
$000A: // LF --> CR+LF
begin
Inc(j); Result[j]:=Chr(13);
Inc(j); System.Insert(Chr(10),Result,j);
end;
$D800..$DBFF: // high surrogate
begin
inc(i);
if (i<length(ws)) and (word(ws[i])>=$DC00) and (word(ws[i])<=$DFFF) then
begin
ucs4:=Utf16SurrogateToInt(wc,ws[i]);
s:=UCS4CodeToUTF8String(ucs4);
System.Insert(s,Result,j+1);
Inc(j,Length(s));
end
else
raise EConvertError.CreateFmt('High surrogate %4.4X without low surrogate.',[word(wc)]);
end;
$DC00..$DFFF: // low surrogate
begin
inc(i);
if (i<length(ws)) and (word(ws[i])>=$D800) and (word(ws[i])<=$DBFF) then
begin
ucs4:=Utf16SurrogateToInt(ws[i],wc);
s:=UCS4CodeToUTF8String(ucs4);
System.Insert(s,Result,j+1);
Inc(j,Length(s));
end
else
raise EConvertError.CreateFmt('Low surrogate %4.4X without high surrogate.',[word(wc)]);
end;
$0080..$D7FF,$E000..$FFFD:
begin
s:=UCS4CodeToUTF8String(word(wc));
System.Insert(s,Result,j+1);
Inc(j,Length(s));
end;
end;
end;
if Length(ws)<>j then
SetLength(Result,j); // set to correct length
end;
function Utf16HighSurrogate(const value: integer): WideChar;
var
value2: word;
begin
value2:= ($D7C0 + ( value shr 10 ));
Result:= WideChar(value2);
end;
function Utf16LowSurrogate(const value: integer): WideChar;
var
value2: word;
begin
value2:= ($DC00 XOR (value AND $3FF));
Result:= WideChar(value2);
end;
function Utf16SurrogateToInt(const highSurrogate, lowSurrogate: WideChar): integer;
begin
Result:= ( (word(highSurrogate) - $D7C0) shl 10 )
+ ( word(lowSurrogate) XOR $DC00 );
end;
function IsUtf16HighSurrogate(const S: WideChar): boolean;
begin
Case Word(S) of
$D800..$DBFF: result:= true;
else
result:= false;
end;
end;
function IsUtf16LowSurrogate(const S: WideChar): boolean;
begin
Case Word(S) of
$DC00..$DFFF: result:= true;
else
result:= false;
end;
end;
//++++++++++++++++++++++++++ TdomCustomStr +++++++++++++++++++++++++++++
constructor TdomCustomStr.create;
begin
reset;
end;
procedure TdomCustomStr.addWideChar(const Ch: WideChar);
begin
if FActualLen = FCapacity then begin // Grow
FCapacity:= FCapacity + FCapacity div 4;
SetLength(FContent,FCapacity);
end;
Inc(FActualLen);
FContent[FActualLen]:= Ch;
end;
procedure TdomCustomStr.AddWideString(const s: WideString);
var
i,l: integer;
begin
l:= system.length(s);
while FActualLen+l > FCapacity do begin // Grow
FCapacity:= FCapacity + FCapacity div 4;
SetLength(Fcontent,FCapacity);
end;
Inc(FActualLen,l);
for i:= 1 to l do
FContent[FActualLen-l+i]:= WideChar(s[i]);
end;
procedure TdomCustomStr.reset;
begin
FCapacity:= 64;
SetLength(FContent,FCapacity);
FActualLen:= 0;
end;
function TdomCustomStr.value: WideString;
begin
Result:= Copy(FContent,1,FActualLen);
end;
//+++++++++++++++++++++++ TdomImplementation ++++++++++++++++++++++++++
constructor TdomImplementation.Create(aOwner: TComponent);
begin
inherited create(aOwner);
FCreatedDocumentsListing:= TList.create;
FCreatedDocuments:= TdomNodeList.create(FCreatedDocumentsListing);
FCreatedDocumentTypesListing:= TList.create;
FCreatedDocumentTypes:= TdomNodeList.create(FCreatedDocumentTypesListing);
end;
destructor TdomImplementation.Destroy;
begin
clear;
FCreatedDocumentsListing.free;
FCreatedDocuments.free;
FCreatedDocumentTypesListing.free;
FCreatedDocumentTypes.free;
inherited destroy;
end;
procedure TdomImplementation.clear;
var
i: integer;
begin
for i:= 0 to FCreatedDocumentsListing.count-1 do begin
TdomDocument(FCreatedDocumentsListing[i]).clear; // destroys all child nodes, nodeIterators and treeWalkers
TdomDocument(FCreatedDocumentsListing[i]).free;
FCreatedDocumentsListing[i]:= nil;
end;
FCreatedDocumentsListing.pack;
FCreatedDocumentsListing.Capacity:= FCreatedDocumentsListing.Count;
for i:= 0 to FCreatedDocumentTypesListing.count-1 do begin
TdomDocumentType(FCreatedDocumentTypesListing[i]).free;
FCreatedDocumentTypesListing[i]:= nil;
end;
FCreatedDocumentTypesListing.pack;
FCreatedDocumentTypesListing.Capacity:= FCreatedDocumentTypesListing.Count;
end;
procedure TdomImplementation.FreeDocument(const doc: TdomDocument);
var
index: integer;
begin
index:= FCreatedDocumentsListing.IndexOf(doc);
if index = -1
then raise ENot_Found_Err.create('Document not found error.');
// destroys all child nodes, nodeIterators and treeWalkers:
doc.clear;
// free the document itself:
FCreatedDocumentsListing.Delete(index);
doc.free;
end;
procedure TdomImplementation.FreeDocumentType(const docType: TdomDocumentType);
var
index: integer;
begin
index:= FCreatedDocumentTypesListing.IndexOf(docType);
if index = -1
then raise ENot_Found_Err.create('DocumentType not found error.');
FCreatedDocumentTypesListing.delete(index);
docType.free;
end;
function TdomImplementation.getDocuments: TdomNodeList;
begin
Result:= FCreatedDocuments;
end;
function TdomImplementation.getDocumentTypes: TdomNodeList;
begin
Result:= FCreatedDocumentTypes;
end;
function TdomImplementation.HasFeature(const feature,
version: WideString): boolean;
var
VersionStr: string;
begin
Result:= false;
VersionStr:= WideCharToString(PWideChar(feature));
if (WideCharToString(PWideChar(version))='1.0')
or (WideCharToString(PWideChar(version))='')
then begin
if (CompareText(VersionStr,'XML')=0)
then Result:= true;
end else begin
if (WideCharToString(PWideChar(version))='2.0')
then begin
if (CompareText(VersionStr,'XML')=0)
then Result:= true;
if (CompareText(VersionStr,'TRAVERSAL')=0)
then Result:= true;
end; {if ...}
end; {if ... else ...}
end;
function TdomImplementation.createDocument(const name: WideString;
doctype: TdomDocumentType): TdomDocument;
begin
if assigned(doctype) then
if documentTypes.IndexOf(doctype) = -1
then raise EWrong_Document_Err.create('Wrong document error.');
if not IsXmlName(name)
then raise EInvalid_Character_Err.create('Invalid character error.');
if SupportsDocumentFormat('',name)
then Result:= GetDocumentClass('',name).create
else Result:= TdomDocument.Create;
FCreatedDocumentsListing.add(Result);
if assigned(doctype) then begin
FCreatedDocumentTypes.FNodeList.Remove(doctype);
doctype.FDocument:= Result;
Result.AppendChild(doctype);
end;
Result.InitDoc(name);
end;
function TdomImplementation.createDocumentNS(const namespaceURI,
qualifiedName: WideString;
doctype: TdomDocumentType): TdomDocument;
var
prfx: WideString;
begin
if assigned(doctype) then
if documentTypes.IndexOf(doctype) = -1
then raise EWrong_Document_Err.create('Wrong document error.');
if not IsXmlName(QualifiedName)
then raise EInvalid_Character_Err.create('Invalid character error.');
if not IsXmlQName(QualifiedName)
then raise ENamespace_Err.create('Namespace error.');
prfx:= XMLExtractPrefix(QualifiedName);
if ( ((prfx = 'xmlns') or (QualifiedName = 'xmlns'))
and not (NamespaceURI ='http://www.w3.org/2000/xmlns/') )
then raise ENamespace_Err.create('Namespace error.');
if (NamespaceURI = '') and (prfx <> '')
then raise ENamespace_Err.create('Namespace error.');
if (prfx = 'xml') and (NamespaceURI <> 'http://www.w3.org/XML/1998/namespace')
then raise ENamespace_Err.create('Namespace error.');
if SupportsDocumentFormat(namespaceURI,qualifiedName)
then Result:= GetDocumentClass(namespaceURI,qualifiedName).create
else Result:= TdomDocument.Create;
FCreatedDocuments.FNodeList.add(Result);
if assigned(doctype) then begin
FCreatedDocumentTypes.FNodeList.Remove(doctype);
doctype.FDocument:= Result;
Result.AppendChild(doctype);
end;
Result.InitDocNS(namespaceURI,qualifiedName);
end;
function TdomImplementation.createDocumentType(const name,
publicId,
systemId: WideString): TdomDocumentType;
begin
if not IsXmlName(name)
then raise EInvalid_Character_Err.create('Invalid character error.');
Result:= TdomDocumentType.Create(nil,name,publicId,systemId);
FCreatedDocumentTypes.FNodeList.add(Result);
end;
function TdomImplementation.createDocumentTypeNS(const qualifiedName,
publicId,
systemId: WideString): TdomDocumentType;
begin
if not IsXmlName(QualifiedName)
then raise EInvalid_Character_Err.create('Invalid character error.');
if not IsXmlQName(QualifiedName)
then raise ENamespace_Err.create('Namespace error.');
Result:= TdomDocumentType.Create(nil,qualifiedName,publicId,systemId);
FCreatedDocumentTypes.FNodeList.add(Result);
end;
function TdomImplementation.GetDocumentClass(const aNamespaceUri,
aQualifiedName: wideString): TdomDocumentClass;
var
aDocFormat: PdomDocumentFormat;
begin
aDocFormat := domDocumentFormatList;
while aDocFormat <> nil do
with aDocFormat^ do begin
if (aNamespaceUri = NamespaceUri) and (aQualifiedName = QualifiedName) then begin
Result:= DocumentClass;
exit;
end else aDocFormat := next;
end;
raise EUnknown_Document_Format_Err.create('Unknown document format yet');
end;
class procedure TdomImplementation.RegisterDocumentFormat(const aNamespaceUri,
aQualifiedName: wideString;
aDocumentClass: TdomDocumentClass);
var
newRec: PdomDocumentFormat;
begin
new(newRec);
with newRec^ do begin
documentClass:= aDocumentClass;
NamespaceUri:= aNamespaceUri;
QualifiedName:= aQualifiedName;
next:= domDocumentFormatList;
end;
domDocumentFormatList:= newRec;
end;
function TdomImplementation.SupportsDocumentFormat(const aNamespaceUri,
aQualifiedName: wideString): boolean;
var
aDocFormat: PdomDocumentFormat;
begin
Result:= false;
aDocFormat := domDocumentFormatList;
while aDocFormat <> nil do
with aDocFormat^ do begin
if (aNamespaceUri = NamespaceUri) and (aQualifiedName = QualifiedName) then begin
Result:= true;
exit;
end else aDocFormat := next;
end;
end;
class procedure TdomImplementation.UnregisterDocumentClass(const aDocumentClass: TdomDocumentClass);
var
aDocFormat,oldRec,previous: PdomDocumentFormat;
begin
previous:= nil;
aDocFormat := domDocumentFormatList;
while aDocFormat <> nil do
with aDocFormat^ do begin
if aDocumentClass = DocumentClass then begin
oldRec:= aDocFormat;
if assigned(previous)
then previous.next:= next
else domDocumentFormatList := next;
previous:= aDocFormat;
aDocFormat := next;
Dispose(oldRec);
end else begin
previous:= aDocFormat;
aDocFormat := next;
end;
end; {with ...}
end;
//++++++++++++++++++++++++++++ TdomTreeWalker +++++++++++++++++++++++++++++++
constructor TdomTreeWalker.create(const Root: TdomNode;
const WhatToShow: TdomWhatToShow;
const NodeFilter: TdomNodeFilter;
const EntityReferenceExpansion: boolean);
begin
if not assigned(Root)
then raise ENot_Supported_Err.create('Not supported error.');
inherited create;
FWhatToShow:= WhatToShow;
FFilter:= NodeFilter;
FExpandEntityReferences:= EntityReferenceExpansion;
FRoot:= Root;
FCurrentNode:= Root;
end;
function TdomTreeWalker.GetCurrentNode: TdomNode;
begin
Result:= FCurrentNode;
end;
procedure TdomTreeWalker.SetCurrentNode(const Node: TdomNode);
begin
if not assigned(Node)
then raise ENot_Supported_Err.create('Not supported error.');
FCurrentNode:= Node;
end;
function TdomTreeWalker.GetExpandEntityReferences: boolean;
begin
Result:= FExpandEntityReferences;
end;
function TdomTreeWalker.GetFilter: TdomNodeFilter;
begin
Result:= FFilter;
end;
function TdomTreeWalker.GetRoot: TdomNode;
begin
Result:= FRoot;
end;
function TdomTreeWalker.GetWhatToShow: TdomWhatToShow;
begin
Result:= FWhatToShow;
end;
function TdomTreeWalker.FindNextSibling(const OldNode: TdomNode): TdomNode;
var
accept: TdomFilterResult;
newNode: TdomNode;
begin
Result:= nil;
if oldNode = root then exit;
newNode:= oldNode.NextSibling;
if assigned(newNode) then begin
if newNode.NodeType in FWhatToShow then begin
if assigned(FFilter)
then accept:= FFilter.acceptNode(newNode)
else accept:= filter_accept;
end else accept:= filter_skip;
case accept of
filter_reject:
Result:= FindNextSibling(newNode);
filter_skip:
begin
Result:= FindFirstChild(newNode);
if not assigned(result)
then Result:= FindNextSibling(newNode);
end;
filter_accept:
Result:= newNode;
end; {case ...}
end else begin
if not assigned(oldNode.parentNode)
then begin result:= nil; exit; end; // TreeWalker.root not found!
if oldNode.parentNode.NodeType in FWhatToShow then begin
if assigned(FFilter)
then accept:= FFilter.acceptNode(oldNode.parentNode)
else accept:= filter_accept;
end else accept:= filter_skip;
case accept of
filter_reject, filter_skip:
Result:= FindNextSibling(oldNode.parentNode);
filter_accept:
Result:= nil;
end; {case ...}
end;
end;
function TdomTreeWalker.FindPreviousSibling(const OldNode: TdomNode): TdomNode;
var
accept: TdomFilterResult;
newNode: TdomNode;
begin
Result:= nil;
if OldNode = root then exit;
newNode:= oldNode.PreviousSibling;
if assigned(newNode) then begin
if newNode.NodeType in FWhatToShow then begin
if assigned(FFilter)
then accept:= FFilter.acceptNode(newNode)
else accept:= filter_accept;
end else accept:= filter_skip;
case accept of
filter_reject:
Result:= FindPreviousSibling(newNode);
filter_skip:
begin
Result:= FindLastChild(newNode);
if not assigned(result)
then Result:= FindPreviousSibling(newNode);
end;
filter_accept:
Result:= newNode;
end; {case ...}
end else begin
if not assigned(oldNode.parentNode)
then begin result:= nil; exit; end; // TreeWalker.root not found!
if oldNode.parentNode.NodeType in FWhatToShow then begin
if assigned(FFilter)
then accept:= FFilter.acceptNode(oldNode.parentNode)
else accept:= filter_accept;
end else accept:= filter_skip;
case accept of
filter_reject, filter_skip:
Result:= FindPreviousSibling(oldNode.parentNode);
filter_accept:
Result:= nil;
end; {case ...}
end;
end;
function TdomTreeWalker.FindParentNode(const OldNode: TdomNode): TdomNode;
var
accept: TdomFilterResult;
begin
Result:= nil;
if OldNode = root then exit;
Result:= OldNode.ParentNode;
if not assigned(Result)
then begin result:= nil; exit; end; // TreeWalker.root not found!
if Result.NodeType in FWhatToShow then begin
if assigned(FFilter)
then accept:= FFilter.acceptNode(Result)
else accept:= filter_accept;
end else accept:= filter_skip;
case accept of
filter_reject, filter_skip:
Result:= FindParentNode(Result);
end;
end;
function TdomTreeWalker.FindFirstChild(const OldNode: TdomNode): TdomNode;
var
newNode: TdomNode;
accept: TdomFilterResult;
begin
Result:= nil;
newNode:= OldNode.FirstChild;
if assigned(newNode) then begin
if newNode.NodeType in FWhatToShow then begin
if assigned(FFilter)
then accept:= FFilter.acceptNode(newNode)
else accept:= filter_accept;
end else accept:= filter_skip;
case accept of
filter_reject:
Result:= FindNextSibling(newNode);
filter_skip:
begin
Result:= FindFirstChild(newNode);
if not assigned(result)
then Result:= FindNextSibling(newNode);
end;
filter_accept:
Result:= newNode;
end; {case ...}
end;
end;
function TdomTreeWalker.FindLastChild(const OldNode: TdomNode): TdomNode;
var
newNode: TdomNode;
accept: TdomFilterResult;
begin
Result:= nil;
newNode:= OldNode.LastChild;
if assigned(newNode) then begin
if newNode.NodeType in FWhatToShow then begin
if assigned(FFilter)
then accept:= FFilter.acceptNode(newNode)
else accept:= filter_accept;
end else accept:= filter_skip;
case accept of
filter_reject:
Result:= FindPreviousSibling(newNode);
filter_skip:
begin
Result:= FindLastChild(newNode);
if not assigned(result)
then Result:= FindPreviousSibling(newNode);
end;
filter_accept:
Result:= newNode;
end; {case ...}
end;
end;
function TdomTreeWalker.FindNextNode(OldNode: TdomNode): TdomNode;
var
newNode: TdomNode;
begin
Result:= FindFirstChild(oldNode);
if OldNode = root then exit;
if not assigned(Result)
then Result:= FindNextSibling(oldNode);
while not assigned(Result) do begin
newNode:= FindParentNode(oldNode);
if not assigned(newNode) then exit; // No next node.
Result:= FindNextSibling(newNode);
oldNode:= newNode;
end;
end;
function TdomTreeWalker.FindPreviousNode(const OldNode: TdomNode): TdomNode;
var
newNode: TdomNode;
begin
Result:= nil;
if OldNode = root then exit;
Result:= FindPreviousSibling(oldNode);
if assigned(Result) then begin
newNode:= FindLastChild(Result);
if assigned(newNode) then result:= newNode;
end else
result:= FindParentNode(oldNode);
end;
function TdomTreeWalker.parentNode: TdomNode;
begin
Result:= FindParentNode(FCurrentNode);
if assigned(Result) then FCurrentNode:= Result;
end;
function TdomTreeWalker.firstChild: TdomNode;
begin
Result:= FindFirstChild(FCurrentNode);
if assigned(Result) then FCurrentNode:= Result;
end;
function TdomTreeWalker.lastChild: TdomNode;
begin
Result:= FindLastChild(FCurrentNode);
if assigned(Result) then FCurrentNode:= Result;
end;
function TdomTreeWalker.previousSibling: TdomNode;
begin
Result:= FindPreviousSibling(FCurrentNode);
if assigned(Result) then FCurrentNode:= Result;
end;
function TdomTreeWalker.nextSibling: TdomNode;
begin
Result:= FindNextSibling(FCurrentNode);
if assigned(Result) then FCurrentNode:= Result;
end;
function TdomTreeWalker.previousNode: TdomNode;
begin
Result:= FindPreviousNode(FCurrentNode);
if assigned(Result) then FCurrentNode:= Result;
end;
function TdomTreeWalker.nextNode: TdomNode;
begin
Result:= FindNextNode(FCurrentNode);
if assigned(Result) then FCurrentNode:= Result;
end;
//++++++++++++++++++++++++++++ TdomNodeIterator +++++++++++++++++++++++++++++++
constructor TdomNodeIterator.create(const Root: TdomNode;
const WhatToShow: TdomWhatToShow;
const nodeFilter: TdomNodeFilter;
const EntityReferenceExpansion: boolean);
begin
if not assigned(Root)
then raise ENot_Supported_Err.create('Not supported error.');
inherited create;
FRoot:= root;
FWhatToShow:= WhatToShow;
FFilter:= NodeFilter;
FReferenceNode:= Root;
FInvalid:= false;
FPosition:= posBefore;
end;
procedure TdomNodeIterator.FindNewReferenceNode(const nodeToRemove: TdomNode);
var
newRefNode: TdomNode;
newPosition: TdomPosition;
begin
newRefNode:= nil;
newPosition:= FPosition;
case FPosition of
posBefore: begin
newRefNode:= nodeToRemove.NextSibling;
if not assigned(newRefNode) then begin
newRefNode:= FindPreviousNode(nodeToRemove);
newPosition:= posAfter;
end;
end;
posAfter: begin
newRefNode:= nodeToRemove.NextSibling;
if not assigned(newRefNode) then begin
newRefNode:= FindPreviousNode(nodeToRemove);
newPosition:= posBefore;
end;
end;
end; {case ...}
if assigned(newRefNode) then begin
FReferenceNode:= newRefNode;
FPosition:= newPosition;
end;
end;
function TdomNodeIterator.GetExpandEntityReferences: boolean;
begin
Result:= FExpandEntityReferences;
end;
function TdomNodeIterator.GetFilter: TdomNodeFilter;
begin
Result:= FFilter;
end;
function TdomNodeIterator.GetRoot: TdomNode;
begin
Result:= FRoot;
end;
function TdomNodeIterator.GetWhatToShow: TdomWhatToShow;
begin
Result:= FWhatToShow;
end;
procedure TdomNodeIterator.detach;
begin
FReferenceNode:= nil;
FInvalid:= true;
end;
function TdomNodeIterator.FindNextNode(OldNode: TdomNode): TdomNode;
var
newNode: TdomNode;
begin
with OldNode do
if HasChildNodes
then result:= FirstChild
else result:= NextSibling;
while not assigned(Result) do begin
newNode:= oldNode.ParentNode;
if not assigned(newNode) then exit; // No next node.
Result:= newNode.NextSibling;
oldNode:= newNode;
end;
end;
function TdomNodeIterator.FindPreviousNode(const OldNode: TdomNode): TdomNode;
var
newNode: TdomNode;
begin
with OldNode do begin
result:= PreviousSibling;
if assigned(result) then begin
newNode:= result;
while assigned(newNode) do begin
result:= newNode;
newNode:= newNode.LastChild;
end;
end else result:= ParentNode;
end;
end;
function TdomNodeIterator.NextNode: TdomNode;
var
accept: TdomFilterResult;
newNode: TdomNode;
begin
newNode:= nil;
if FInvalid
then raise EInvalid_State_Err.create('Invalid state error.');
case FPosition of
posBefore: begin
FPosition:= posAfter;
newNode:= FReferenceNode;
end;
posAfter: begin
newNode:= FindNextNode(FReferenceNode);
end;
end;
repeat
accept:= filter_accept;
if assigned(newNode) then begin
if newNode.NodeType in FWhatToShow then begin
if assigned(FFilter)
then accept:= FFilter.acceptNode(newNode);
end else accept:= filter_skip;
if not (accept = filter_accept)
then newNode:= FindNextNode(newNode);
end;
until accept = filter_accept;
if assigned(newNode) then
if not (newNode.IsAncestor(root) or (newNode = root)) then
if (FReferenceNode.IsAncestor(root) or (FReferenceNode = root)) then newNode:= nil;
if assigned(newNode) then FReferenceNode:= newNode;
Result:= newNode;
end;
function TdomNodeIterator.PreviousNode: TdomNode;
var
accept: TdomFilterResult;
newNode: TdomNode;
begin
newNode:= nil;
if FInvalid
then raise EInvalid_State_Err.create('Invalid state error.');
case FPosition of
posBefore: begin
newNode:= FindPreviousNode(FReferenceNode);
end;
posAfter: begin
FPosition:= posBefore;
newNode:= FReferenceNode;
end;
end;
repeat
accept:= filter_accept;
if assigned(newNode) then begin
if newNode.NodeType in FWhatToShow then begin
if assigned(FFilter)
then accept:= FFilter.acceptNode(newNode);
end else accept:= filter_skip;
if not (accept = filter_accept)
then newNode:= FindPreviousNode(newNode);
end;
until accept = filter_accept;
if assigned(newNode) then
if not (newNode.IsAncestor(root) or (newNode = root)) then
if (FReferenceNode.IsAncestor(root) or (FReferenceNode = root)) then newNode:= nil;
if assigned(newNode) then FReferenceNode:= newNode;
Result:= newNode;
end;
//++++++++++++++++++++++++++++ TdomNodeList +++++++++++++++++++++++++++++++
constructor TdomNodeList.Create(const NodeList: TList);
begin
inherited create;
FNodeList:= NodeList;
end;
function TdomNodeList.GetLength: integer;
begin
Result:= FNodeList.count;
end;
function TdomNodeList.IndexOf(const Node: TdomNode): integer;
begin
Result:= FNodeList.IndexOf(Node);
end;
function TdomNodeList.Item(const index: integer): TdomNode;
begin
if (index < 0) or (index + 1 > FNodeList.count)
then Result:= nil
else Result:= TdomNode(FNodeList.Items[index]);
end;
//++++++++++++++++++++++++ TdomElementsNodeList ++++++++++++++++++++++++++
constructor TdomElementsNodeList.Create(const QueryName: WideString;
const StartElement: TdomNode);
begin
inherited Create(nil);
FQueryName:= QueryName;
FStartElement:= StartElement;
end;
function TdomElementsNodeList.GetLength: integer;
var
AktNode,NewNode: TdomNode;
Level: integer;
begin
Result:= 0;
if not assigned(FStartElement) then exit;
Level:= 0;
AktNode:= FStartElement;
if AktNode.NodeType = ntElement_Node then
if (AktNode.NodeName = FQueryName) or (FQueryName = '*') then
inc(Result);
repeat
if AktNode.HasChildNodes
then begin NewNode:= AktNode.FirstChild; inc(Level); end
else NewNode:= AktNode.NextSibling;
while not assigned(NewNode) do begin
dec(Level);
if Level < 1 then break;
AktNode:= AktNode.ParentNode;
NewNode:= AktNode.NextSibling;
end;
if Level < 1 then break;
AktNode:= NewNode;
if AktNode.NodeType = ntElement_Node then
if (AktNode.NodeName = FQueryName) or (FQueryName = '*') then
inc(Result);
until Level < 1;
end;
function TdomElementsNodeList.IndexOf(const Node: TdomNode): integer;
var
AktNode,NewNode: TdomNode;
Level,i: integer;
begin
Result:= -1;
if not assigned(FStartElement) then exit;
if not (Node is TdomNode) then exit;
if Node.NodeType <> ntElement_Node then exit;
i:= -1;
Level:= 0;
AktNode:= FStartElement;
repeat
if AktNode.HasChildNodes
then begin NewNode:= AktNode.FirstChild; inc(Level); end
else NewNode:= AktNode.NextSibling;
while not assigned(NewNode) do begin
dec(Level);
if Level < 1 then break;
AktNode:= AktNode.ParentNode;
NewNode:= AktNode.NextSibling;
end;
if Level < 1 then break;
AktNode:= NewNode;
if AktNode.NodeType = ntElement_Node then
if (AktNode.NodeName = FQueryName) or (FQueryName = '*') then begin
inc(i);
if AktNode = Node then begin Result:= i; break; end;
end;
until Level < 1;
end;
function TdomElementsNodeList.Item(const index: integer): TdomNode;
var
AktNode,NewNode: TdomNode;
Level,i: integer;
begin
Result:= nil;
if not assigned(FStartElement) then exit;
if (index < 0) then exit;
i:= -1;
Level:= 0;
AktNode:= FStartElement;
repeat
if AktNode.HasChildNodes
then begin NewNode:= AktNode.FirstChild; inc(Level); end
else NewNode:= AktNode.NextSibling;
while not assigned(NewNode) do begin
dec(Level);
if Level < 1 then break;
AktNode:= AktNode.ParentNode;
NewNode:= AktNode.NextSibling;
end;
if Level < 1 then break;
AktNode:= NewNode;
if AktNode.NodeType = ntElement_Node then
if (AktNode.NodeName = FQueryName) or (FQueryName = '*') then begin
inc(i);
if i = index then begin Result:= AktNode; break; end;
end;
until Level < 1;
end;
//+++++++++++++++++++++TdomElementsNodeListNS ++++++++++++++++++++++++++
constructor TdomElementsNodeListNS.Create(const QueryNamespaceURI,
QueryLocalName: WideString;
const StartElement: TdomNode);
begin
inherited Create(nil);
FQueryNamespaceURI:= QueryNamespaceURI;
FQueryLocalName:= QueryLocalName;
FStartElement:= StartElement;
end;
function TdomElementsNodeListNS.GetLength: integer;
var
AktNode,NewNode: TdomNode;
Level: integer;
begin
Result:= 0;
if not assigned(FStartElement) then exit;
Level:= 0;
AktNode:= FStartElement;
repeat
if AktNode.HasChildNodes
then begin NewNode:= AktNode.FirstChild; inc(Level); end
else NewNode:= AktNode.NextSibling;
while not assigned(NewNode) do begin
dec(Level);
if Level < 1 then break;
AktNode:= AktNode.ParentNode;
NewNode:= AktNode.NextSibling;
end;
if Level < 1 then break;
AktNode:= NewNode;
if AktNode.NodeType = ntElement_Node then
if ((AktNode.namespaceURI = FQueryNamespaceURI) or (FQueryNamespaceURI = '*'))
and ((AktNode.localName = FQueryLocalName) or (FQueryLocalName = '*'))
then inc(Result);
until Level < 1;
end;
function TdomElementsNodeListNS.IndexOf(const Node: TdomNode): integer;
var
AktNode,NewNode: TdomNode;
Level,i: integer;
begin
Result:= -1;
if not assigned(FStartElement) then exit;
if not (Node is TdomNode) then exit;
if Node.NodeType <> ntElement_Node then exit;
i:= -1;
Level:= 0;
AktNode:= FStartElement;
repeat
if AktNode.HasChildNodes
then begin NewNode:= AktNode.FirstChild; inc(Level); end
else NewNode:= AktNode.NextSibling;
while not assigned(NewNode) do begin
dec(Level);
if Level < 1 then break;
AktNode:= AktNode.ParentNode;
NewNode:= AktNode.NextSibling;
end;
if Level < 1 then break;
AktNode:= NewNode;
if AktNode.NodeType = ntElement_Node then
if ((AktNode.namespaceURI = FQueryNamespaceURI) or (FQueryNamespaceURI = '*'))
and ((AktNode.localName = FQueryLocalName) or (FQueryLocalName = '*'))
then begin
inc(i);
if AktNode = Node then begin Result:= i; break; end;
end;
until Level < 1;
end;
function TdomElementsNodeListNS.Item(const index: integer): TdomNode;
var
AktNode,NewNode: TdomNode;
Level,i: integer;
begin
Result:= nil;
if not assigned(FStartElement) then exit;
if (index < 0) then exit;
i:= -1;
Level:= 0;
AktNode:= FStartElement;
repeat
if AktNode.HasChildNodes
then begin NewNode:= AktNode.FirstChild; inc(Level); end
else NewNode:= AktNode.NextSibling;
while not assigned(NewNode) do begin
dec(Level);
if Level < 1 then break;
AktNode:= AktNode.ParentNode;
NewNode:= AktNode.NextSibling;
end;
if Level < 1 then break;
AktNode:= NewNode;
if AktNode.NodeType = ntElement_Node then
if ((AktNode.namespaceURI = FQueryNamespaceURI) or (FQueryNamespaceURI = '*'))
and ((AktNode.localName = FQueryLocalName) or (FQueryLocalName = '*'))
then begin
inc(i);
if i = index then begin Result:= AktNode; break; end;
end;
until Level < 1;
end;
//++++++++++++++++++++++++ TdomSpecialNodeList ++++++++++++++++++++++++++
constructor TdomSpecialNodeList.Create(const NodeList: TList;
const AllowedNTs: TDomNodeTypeSet);
begin
inherited Create(NodeList);
FAllowedNodeTypes:= AllowedNTs;
end;
function TdomSpecialNodeList.GetLength: integer;
var
i: integer;
begin
Result:= 0;
for i:= 0 to FNodeList.count-1 do
if TdomNode(FNodeList[i]).NodeType in FAllowedNodeTypes
then inc(Result);
end;
function TdomSpecialNodeList.IndexOf(const Node: TdomNode): integer;
var
i: integer;
begin
Result:= -1;
if not (Node.NodeType in FAllowedNodeTypes) then exit;
for i:= 0 to FNodeList.count-1 do begin
if TdomNode(FNodeList[i]).NodeType in FAllowedNodeTypes
then inc(Result);
if TdomNode(FNodeList[i]) = Node
then begin Result:= i; break; end;
end;
end;
function TdomSpecialNodeList.Item(const index: integer): TdomNode;
var
i,j: integer;
begin
Result:= nil;
j:= -1;
if (index < 0) or (index > FNodeList.count-1) then exit;
for i:= 0 to FNodeList.count-1 do begin
if TdomNode(FNodeList[i]).NodeType in FAllowedNodeTypes
then inc(j);
if j = index then begin Result:= TdomNode(FNodeList[i]); break; end;
end;
end;
function TdomSpecialNodeList.GetNamedIndex(const Name: WideString): integer;
var
i,j: integer;
begin
result:= -1;
j:= -1;
for i:= 0 to FNodeList.count-1 do
if TdomNode(FNodeList[i]).NodeType in FAllowedNodeTypes then begin
inc(j);
if (TdomNode(FNodeList[i]).NodeName = Name)
then begin Result:= j; break; end;
end;
end;
function TdomSpecialNodeList.GetNamedItem(const Name: WideString): TdomNode;
var
i: integer;
begin
result:= nil;
for i:= 0 to FNodeList.count-1 do
if (TdomNode(FNodeList[i]).NodeName = Name)
and (TdomNode(FNodeList[i]).NodeType in FAllowedNodeTypes) then begin
Result:= TdomNode(FNodeList[i]);
break;
end;
end;
//+++++++++++++++++++++++++ TdomNamedNodeMap +++++++++++++++++++++++++++++
constructor TdomNamedNodeMap.Create(const AOwner,
AOwnerNode: TdomNode;
const NodeList: TList;
const AllowedNTs: TDomNodeTypeSet);
begin
inherited create(NodeList);
FOwner:= AOwner;
FOwnerNode:= AOwnerNode;
FAllowedNodeTypes:= AllowedNTs;
FNamespaceAware:= false;
end;
function TdomNamedNodeMap.getOwnerNode: TdomNode;
begin
Result:= FOwnerNode;
end;
function TdomNamedNodeMap.getNamespaceAware: boolean;
begin
Result:= FNamespaceAware;
end;
procedure TdomNamedNodeMap.setNamespaceAware(const value: boolean);
begin
if FNodeList.count > 0
then raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
FNamespaceAware:= value;
end;
function TdomNamedNodeMap.RemoveItem(const Arg: TdomNode): TdomNode;
begin
if FNodeList.IndexOf(Arg) = -1
then raise ENot_Found_Err.create('Node not found error.');
Result:= Arg;
FNodeList.Remove(Arg);
Result.FParentNode:= nil;
end;
function TdomNamedNodeMap.GetNamedIndex(const Name: WideString): integer;
var
i: integer;
begin
if FNamespaceAware then raise ENamespace_Err.create('Namespace error.');
result:= -1;
for i:= 0 to FNodeList.count-1 do
if (TdomNode(FNodeList[i]).NodeName = Name)
and (TdomNode(FNodeList[i]).NodeType in FAllowedNodeTypes) then begin
Result:= i;
break;
end;
end;
function TdomNamedNodeMap.GetNamedItem(const Name: WideString): TdomNode;
var
i: integer;
begin
if FNamespaceAware then raise ENamespace_Err.create('Namespace error.');
result:= nil;
for i:= 0 to FNodeList.count-1 do
if (TdomNode(FNodeList[i]).NodeName = Name)
and (TdomNode(FNodeList[i]).NodeType in FAllowedNodeTypes) then begin
Result:= TdomNode(FNodeList[i]);
break;
end;
end;
function TdomNamedNodeMap.SetNamedItem(const Arg: TdomNode): TdomNode;
begin
if FNamespaceAware then raise ENamespace_Err.create('Namespace error.');
if FOwner.OwnerDocument <> Arg.OwnerDocument
then raise EWrong_Document_Err.create('Wrong document error.');
if not (Arg.NodeType in FAllowedNodeTypes)
then raise EHierarchy_Request_Err.create('Hierarchy request error.');
if assigned(arg.parentNode)
then raise EInuse_Node_Err.create('Inuse node error.');
if arg.NodeType = ntAttribute_Node
then if assigned((arg as TdomAttr).OwnerElement)
then if (arg as TdomAttr).OwnerElement <> FOwnerNode
then raise EInuse_Attribute_Err.create('Inuse attribute error.');
if assigned(GetNamedItem(Arg.NodeName))
then Result:= RemoveNamedItem(Arg.NodeName)
else Result:= nil;
FNodeList.Add(Arg);
arg.FParentNode:= nil;
if (arg.NodeType = ntAttribute_Node)
and (FOwnerNode.NodeType = ntElement_Node)
then (arg as TdomAttr).FownerElement:= TdomElement(FOwnerNode);
end;
function TdomNamedNodeMap.RemoveNamedItem(const Name: WideString): TdomNode;
begin
if FNamespaceAware then raise ENamespace_Err.create('Namespace error.');
Result:= GetNamedItem(Name);
if not assigned(Result)
then raise ENot_Found_Err.create('Node not found error.');
FNodeList.Remove(Result);
if Result.NodeType = ntAttribute_Node
then (Result as TdomAttr).FownerElement:= nil;
end;
function TdomNamedNodeMap.GetNamedItemNS(const namespaceURI,
localName: WideString): TdomNode;
var
i: integer;
begin
if not FNamespaceAware then raise ENamespace_Err.create('Namespace error.');
result:= nil;
for i:= 0 to FNodeList.count-1 do
if (TdomNode(FNodeList[i]).namespaceURI = namespaceURI)
and (TdomNode(FNodeList[i]).localName = localName)
and (TdomNode(FNodeList[i]).NodeType in FAllowedNodeTypes) then begin
Result:= TdomNode(FNodeList[i]);
break;
end;
end;
function TdomNamedNodeMap.SetNamedItemNS(const arg: TdomNode): TdomNode;
begin
if not FNamespaceAware then raise ENamespace_Err.create('Namespace error.');
if FOwner.OwnerDocument <> Arg.OwnerDocument
then raise EWrong_Document_Err.create('Wrong document error.');
if not (Arg.NodeType in FAllowedNodeTypes)
then raise EHierarchy_Request_Err.create('Hierarchy request error.');
if assigned(arg.parentNode)
then raise EInuse_Node_Err.create('Inuse node error.');
if arg.NodeType = ntAttribute_Node
then if assigned((arg as TdomAttr).OwnerElement)
then if (arg as TdomAttr).OwnerElement <> FOwnerNode
then raise EInuse_Attribute_Err.create('Inuse attribute error.');
if assigned(GetNamedItem(Arg.NodeName))
then Result:= RemoveNamedItem(Arg.NodeName)
else Result:= nil;
FNodeList.Add(Arg);
if (arg.NodeType = ntAttribute_Node)
and (FOwnerNode.NodeType = ntElement_Node)
then (arg as TdomAttr).FownerElement:= TdomElement(FOwnerNode);
end;
function TdomNamedNodeMap.RemoveNamedItemNS(const namespaceURI,
localName: WideString): TdomNode;
begin
if not FNamespaceAware then raise ENamespace_Err.create('Namespace error.');
Result:= GetNamedItemNS(namespaceURI,localName);
if not assigned(Result)
then raise ENot_Found_Err.create('Node not found error.');
FNodeList.Remove(Result);
if Result.NodeType = ntAttribute_Node
then (Result as TdomAttr).FownerElement:= nil;
end;
//+++++++++++++++++++++++++ TdomEntitiesNamedNodeMap +++++++++++++++++++++++++++++
procedure TdomEntitiesNamedNodeMap.ResolveAfterAddition(const addedEntity: TdomEntity);
var
EntityName: wideString;
i: integer;
oldChild: TdomNode;
begin
if not assigned(addedEntity) then exit;
EntityName:= addedEntity.NodeName;
for i:= 0 to pred(FNodeList.Count) do
if TdomNode(FNodeList[i]).NodeName <> EntityName
then addedEntity.addEntRefSubtree(TdomNode(FNodeList[i]).NodeName);
// Test for circular reference:
with addedEntity do begin
if HasEntRef(nodeName) then begin
while HasChildNodes do begin
FirstChild.FIsReadonly:= false;
oldChild:= RemoveChild(FirstChild);
OwnerDocument.FreeAllNodes(oldChild);
end; {while ...}
raise EParserInvalidEntityDeclaration_Err.create('Invalid entity declaration error.');
end; {if ...}
end; {with ...}
for i:= 0 to pred(FNodeList.Count) do
TdomEntity(FNodeList[i]).addEntRefSubtree(EntityName);
end;
procedure TdomEntitiesNamedNodeMap.ResolveAfterRemoval(const removedEntity: TdomEntity);
var
EntityName: wideString;
i: integer;
begin
if not assigned(removedEntity) then exit;
EntityName:= removedEntity.NodeName;
for i:= 0 to pred(FNodeList.Count) do
TdomEntity(FNodeList[i]).removeEntRefSubtree(EntityName);
end;
function TdomEntitiesNamedNodeMap.SetNamedItem(const Arg: TdomNode): TdomNode;
begin
result:= inherited SetNamedItem(Arg);
try
ResolveAfterAddition(Arg as TdomEntity);
except
RemoveNamedItem(Arg.nodeName);
raise;
end;
end;
function TdomEntitiesNamedNodeMap.RemoveNamedItem(const Name: WideString): TdomNode;
begin
result:= inherited RemoveNamedItem(Name);
if assigned(result)
then ResolveAfterRemoval(result as TdomEntity);
end;
function TdomEntitiesNamedNodeMap.SetNamedItemNS(const Arg: TdomNode): TdomNode;
begin
result:= inherited SetNamedItemNS(Arg);
ResolveAfterAddition(Arg as TdomEntity);
end;
function TdomEntitiesNamedNodeMap.RemoveNamedItemNS(const namespaceURI,
LocalName: WideString): TdomNode;
begin
result:= inherited RemoveNamedItemNS(namespaceURI,LocalName);
if assigned(result)
then ResolveAfterRemoval(result as TdomEntity);
end;
//++++++++++++++++++++++++++++++ TdomNode +++++++++++++++++++++++++++++++++
constructor TdomNode.Create(const AOwner: TdomDocument);
begin
inherited create;
FDocument:= AOwner;
FParentNode:= nil;
FNodeListing:= TList.create;
FNodeList:= TdomNodeList.create(FNodeListing);
FNodeName:= '';
FNodeValue:= '';
FNamespaceURI:= '';
FNodeType:= ntUnknown;
FIsReadonly:= false;
FAllowedChildTypes:= [ntElement_Node,
ntText_Node,
ntCDATA_Section_Node,
ntEntity_Reference_Node,
ntParameter_Entity_Reference_Node,
ntProcessing_Instruction_Node,
ntXml_Declaration_Node,
ntComment_Node,
ntDocument_Type_Node,
ntConditional_Section_Node,
ntDocument_Fragment_Node,
ntElement_Type_Declaration_Node,
ntAttribute_List_Node,
ntEntity_Declaration_Node,
ntParameter_Entity_Declaration_Node,
ntNotation_Node,
ntNotation_Declaration_Node,
ntExternal_Subset_Node,
ntInternal_Subset_Node];
end;
destructor TdomNode.Destroy;
begin
FNodeListing.free;
FNodeList.free;
inherited destroy;
end;
procedure TdomNode.Clear;
var
i: integer;
List1: TList;
begin
if FIsReadonly
then raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
List1:= TList.create;
List1.clear;
try
for i:= 0 to ChildNodes.Length -1 do
if not ChildNodes.item(i).FIsReadonly then
List1.Add(ChildNodes.item(i));
for i:= 0 to List1.count -1 do begin
RemoveChild(TdomNode(List1[i]));
OwnerDocument.FreeAllNodes(TdomNode(List1[i]));
end;
finally
List1.free;
end;
end;
procedure TdomNode.makeChildrenReadonly;
var
i: integer;
begin
with childnodes do
for i:= 0 to pred(length) do
with item(i) do begin
item(i).FisReadonly:= true;
item(i).makeChildrenReadonly;
end;
end;
function TdomNode.RefersToExternalEntity: boolean;
var
i: integer;
node: TdomNode;
begin
result:= false;
for i:= 0 to pred(childnodes.length) do begin
node:= childnodes.item(i);
if node.nodeType = ntEntity_Reference_Node then
if not TdomEntity(node).IsInternalEntity
then result:= true
else if node.RefersToExternalEntity then begin result:= true; exit; end;
end; {for ...}
end;
function TdomNode.HasEntRef(const EntName: widestring): boolean;
var
i: integer;
begin
result:= false;
for i:= 0 to pred(childnodes.length) do
with childnodes.item(i) do
if (nodeType = ntEntity_Reference_Node)
and (nodeName = EntName)
then result:= true
else if HasEntRef(EntName) then begin result:= true; exit; end;
end;
procedure TdomNode.addEntRefSubtree(const EntName: widestring);
var
i: integer;
begin
for i:= 0 to pred(childnodes.length) do begin
if (childnodes.item(i).nodeType = ntEntity_Reference_Node)
and (childnodes.item(i).nodeName = EntName) then begin
OwnerDocument.ExpandEntRef(childnodes.item(i) as TdomEntityReference);
end; {if ...}
childnodes.item(i).addEntRefSubtree(EntName);
end; {for ...}
end;
procedure TdomNode.removeEntRefSubtree(const EntName: widestring);
var
i: integer;
oldChild: TdomNode;
begin
for i:= 0 to pred(childnodes.length) do
with childnodes.item(i) do
if (nodeType = ntEntity_Reference_Node)
and (nodeName = EntName)
then begin
while HasChildNodes do begin
FirstChild.FIsReadonly:= false;
oldChild:= RemoveChild(FirstChild);
OwnerDocument.FreeAllNodes(oldChild);
end;
end else removeEntRefSubtree(EntName);
end;
function TdomNode.GetNodeName: WideString;
begin
Result:= FNodeName;
end;
function TdomNode.GetNodeValue: WideString;
begin
Result:= FNodeValue;
end;
procedure TdomNode.SetNodeValue(const Value: WideString);
begin
FNodeValue:= Value;
end;
function TdomNode.GetNodeType: TdomNodeType;
begin
Result:= FNodeType;
end;
function TdomNode.GetAttributes: TdomNamedNodeMap;
begin
Result:= nil;
end;
function TdomNode.GetParentNode: TdomNode;
begin
Result:= FParentNode;
end;
function TdomNode.GetDocument: TdomDocument;
begin
Result:= FDocument;
end;
function TdomNode.GetCode: WideString;
var
i: integer;
begin
Result:= '';
for i:= 0 to ChildNodes.Length -1 do
Result:= concat(Result,ChildNodes.item(i).Code);
end;
function TdomNode.GetLocalName: WideString;
var
colonpos: integer;
begin
Result:= '';
if (FNodeType in [ntElement_Node,ntAttribute_Node])
and IsXmlQName(FNodeName) then begin
colonpos:= pos(':',FNodeName);
result:= copy(FNodeName,colonpos+1,length(FNodeName)-colonpos);
end;
end;
function TdomNode.GetNamespaceURI: WideString;
begin
Result:= FNamespaceURI;
end;
function TdomNode.GetPrefix: WideString;
var
colonpos: integer;
begin
Result:= '';
if (FNodeType in [ntElement_Node,ntAttribute_Node])
and IsXmlQName(FNodeName) then begin
colonpos:= pos(':',FNodeName);
result:= copy(FNodeName,1,length(FNodeName)-colonpos);
end;
end;
procedure TdomNode.SetPrefix(const value: WideString);
begin
if not IsXmlQName(NodeName)
then raise EInvalid_Character_Err.create('Invalid character error.');
if not IsXmlName(value)
then raise EInvalid_Character_Err.create('Invalid character error.');
if not IsXmlPrefix(value)
then raise ENamespace_Err.create('Namespace error.');
if NamespaceURI = ''
then raise ENamespace_Err.create('Namespace error.');
if (value = 'xml')
and not(NamespaceURI = 'http://www.w3.org/XML/1998/namespace')
then raise ENamespace_Err.create('Namespace error.');
if (value = 'xmlns')
and not (NamespaceURI ='http://www.w3.org/2000/xmlns/')
then raise ENamespace_Err.create('Namespace error.');
if (NodeName = 'xmlns') and (self.NodeType = ntAttribute_Node)
then raise ENamespace_Err.create('Namespace error.');
FNodeName:= concat(value,':',localName);
end;
function TdomNode.GetChildNodes: TdomNodeList;
begin
Result:= FNodeList;
end;
function TdomNode.GetFirstChild: TdomNode;
begin
if FNodeListing.count = 0
then Result:= nil
else Result:= TdomNode(FNodeListing.First);
end;
function TdomNode.GetLastChild: TdomNode;
begin
if FNodeListing.count = 0
then Result:= nil
else Result:= TdomNode(FNodeListing.Last);
end;
function TdomNode.GetPreviousSibling: TdomNode;
begin
if assigned(ParentNode)
then Result:= ParentNode.ChildNodes.Item(ParentNode.ChildNodes.IndexOf(Self)-1)
else Result:= nil;
end;
function TdomNode.GetNextSibling: TdomNode;
begin
if assigned(ParentNode)
then Result:= ParentNode.ChildNodes.Item(ParentNode.ChildNodes.IndexOf(Self)+1)
else Result:= nil;
end;
function TdomNode.InsertBefore(const newChild,
refChild: TdomNode): TdomNode;
begin
if not (newChild.NodeType in FAllowedChildTypes)
then raise EHierarchy_Request_Err.create('Hierarchy request error.');
if OwnerDocument <> newChild.OwnerDocument
then raise EWrong_Document_Err.create('Wrong document error.');
{Auf Zirkularität prüfen:}
if IsAncestor(newChild)
then raise EHierarchy_Request_Err.create('Hierarchy request error.');
if FIsReadonly
then raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
if assigned(newChild.ParentNode)
then if newChild.ParentNode.FIsReadonly
then raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
if assigned(refChild) then
if FNodeListing.IndexOf(refChild) = -1
then raise ENot_Found_Err.create('Node not found error.');
Result:= newChild;
{refChild kann übrigens nie ein TdomDocumentFragment sein (die
folgende While-Schleife bricht in solch einem Fall mit einer
'ENot_Found_Err'-Fehlermeldung ab), da ein solches nie in
FNodeListing eingefügt werden kann, da bei einem
entsprechenden Versuch immer nur die Child-Nodes des
TdomDocumentFragment eingfügt werden würden.}
if NewChild is TdomDocumentFragment
then while NewChild.HasChildNodes do
InsertBefore(newChild.ChildNodes.Item(0),refChild)
else begin
if newChild = refChild then exit;
if assigned(newChild.parentNode) then newChild.parentNode.RemoveChild(newChild);
if assigned(refChild)
then FNodeListing.Insert(FNodeListing.IndexOf(refChild),newChild)
else FNodeListing.Add(newChild);
NewChild.FParentNode:= self;
end;
end;
function TdomNode.ReplaceChild(const newChild,
oldChild: TdomNode): TdomNode;
var
refChild: TdomNode;
begin
if not (newChild.NodeType in FAllowedChildTypes)
then raise EHierarchy_Request_Err.create('Hierarchy request error.');
if OwnerDocument <> newChild.OwnerDocument
then raise EWrong_Document_Err.create('Wrong document error.');
{Auf Zirkularität prüfen:}
if IsAncestor(newChild)
then raise EHierarchy_Request_Err.create('Hierarchy request error.');
if FIsReadonly
then raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
if assigned(newChild.ParentNode)
then if newChild.ParentNode.FIsReadonly
then raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
if FNodeListing.IndexOf(oldChild) = -1
then raise ENot_Found_Err.create('Node not found error.');
Result:= oldChild;
if newChild = oldChild then exit;
if assigned(newChild.parentNode) then newChild.parentNode.RemoveChild(newChild);
refChild:= oldChild.NextSibling;
RemoveChild(oldChild);
if assigned(refChild)
then InsertBefore(newChild,refChild)
else AppendChild(newChild);
end;
function TdomNode.RemoveChild(const oldChild: TdomNode): TdomNode;
begin
if FIsReadonly
then raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
if FNodeListing.IndexOf(oldChild) = -1
then raise ENot_Found_Err.create('Node not found error.');
OwnerDocument.FindNewReferenceNodes(oldChild);
Result:= oldChild;
FNodeListing.Remove(oldChild);
OldChild.FParentNode:= nil;
end;
function TdomNode.AppendChild(const newChild: TdomNode): TdomNode;
begin
if not (newChild.NodeType in FAllowedChildTypes)
then raise EHierarchy_Request_Err.create('Hierarchy request error.');
if OwnerDocument <> newChild.OwnerDocument
then raise EWrong_Document_Err.create('Wrong document error.');
{Auf Zirkularität prüfen:}
if IsAncestor(newChild)
then raise EHierarchy_Request_Err.create('Hierarchy request error.');
if FIsReadonly
then raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
if assigned(newChild.ParentNode)
then if newChild.ParentNode.FIsReadonly
then raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
Result:= newChild;
if NewChild is TdomDocumentFragment then
while NewChild.HasChildNodes do
AppendChild(newChild.ChildNodes.Item(0))
else begin
if assigned(newChild.parentNode) then newChild.parentNode.RemoveChild(newChild);
FNodeListing.Add(newChild);
NewChild.FParentNode:= self;
end;
end;
function TdomNode.HasChildNodes: boolean;
begin
if FNodeListing.count = 0
then result:= false
else result:= true;
end;
function TdomNode.CloneNode(const deep: boolean): TdomNode;
var
newChildNode: TdomNode;
i: integer;
begin
Result:= OwnerDocument.DuplicateNode(self);
if deep then for i:= 0 to ChildNodes.Length-1 do
begin
newChildNode:= ChildNodes.Item(i).CloneNode(true);
Result.AppendChild(newChildNode);
end;
end;
function TdomNode.IsAncestor(const AncestorNode: TdomNode): boolean;
var
NewAncestor: TdomNode;
List1: TList;
begin
Result:= false;
NewAncestor:= ParentNode;
List1:= TList.create;
List1.clear;
try
while assigned(NewAncestor) do begin
{Ciculation test:}
if List1.IndexOf(NewAncestor) > -1
then raise EHierarchy_Request_Err.create('Hierarchy request error.');
List1.Add(NewAncestor);
if NewAncestor = AncestorNode then begin Result:= true; break; end;
NewAncestor:= NewAncestor.ParentNode;
end;
finally
List1.free;
end;
end;
procedure TdomNode.GetLiteralAsNodes(const RefNode: TdomNode);
var
i: integer;
newNode: TdomNode;
EntDecl: TdomCustomEntity;
begin
{Auf Zirkularität prüfen:}
if self = RefNode
then raise EHierarchy_Request_Err.create('Hierarchy request error.');
for i:= 0 to ChildNodes.Length -1 do
case ChildNodes.item(i).NodeType of
ntEntity_Reference_Node,ntParameter_Entity_Reference_Node: begin
{xxx auf Zirkularität prüfen! xxx}
EntDecl:= (ChildNodes.item(i) as TdomReference).Declaration;
if not assigned(EntDecl)
then raise ENot_Found_Err.create('Entity declaration not found error.');
if EntDecl.IsInternalEntity then EntDecl.GetLiteralAsNodes(RefNode);
end;
else
begin
newNode:= OwnerDocument.DuplicateNode(ChildNodes.item(i));
RefNode.AppendChild(newNode);
ChildNodes.item(i).GetLiteralAsNodes(newNode);
end;
end; {case ...}
end;
procedure TdomNode.normalize;
var
i: integer;
begin
for i:= 0 to ChildNodes.Length-1 do
ChildNodes.Item(i).normalize;
end;
function TdomNode.supports(const feature,
version: WideString): boolean;
var
VersionStr: string;
begin
Result:= false;
VersionStr:= WideCharToString(PWideChar(feature));
if (WideCharToString(PWideChar(version))='1.0')
or (WideCharToString(PWideChar(version))='')
then begin
if (CompareText(VersionStr,'XML')=0)
then Result:= true;
end else begin
if (WideCharToString(PWideChar(version))='2.0')
then begin
if (CompareText(VersionStr,'XML')=0)
then Result:= true;
end; {if ...}
end; {if ... else ...}
end;
//+++++++++++++++++++++++++ TdomCharacterData ++++++++++++++++++++++++++++
constructor TdomCharacterData.create(const AOwner: TdomDocument);
begin
FAllowedChildTypes:= [];
inherited create(AOwner);
end;
function TdomCharacterData.GetData: WideString;
begin
Result:= NodeValue;
end;
procedure TdomCharacterData.SetData(const Value: WideString);
begin
NodeValue:= Value;
end;
function TdomCharacterData.GetLength: integer;
begin
Result:= System.Length(Data);
end;
function TdomCharacterData.SubstringData(const offset,
count: integer):WideString;
var
len: integer;
begin
if(offset < 0) or (offset > Length) or (count < 0)
then raise EIndex_Size_Err.create('Index size error.');
{Sicherstellen, daß mit count und offset die Länge des WideStrings
nicht überschritten wird:}
len:= Length-Offset;
if count < len then len:= count;
SetString(Result,PWideChar(Data)+Offset,len);
end;
procedure TdomCharacterData.AppendData(const arg: WideString);
begin
Data:= concat(Data,Arg);
end;
procedure TdomCharacterData.InsertData(const offset: integer;
const arg: WideString);
begin
ReplaceData(offset,0,arg);
end;
procedure TdomCharacterData.DeleteData(const offset,
count: integer);
begin
ReplaceData(offset,count,'');
end;
procedure TdomCharacterData.ReplaceData(const offset,
count: integer;
const arg: WideString);
var
len: integer;
Data1,Data2:WideString;
begin
if(offset < 0) or (offset > Length) or (count < 0)
then raise EIndex_Size_Err.create('Index size error.');
{Sicherstellen, daß mit count und offset die Länge des WideStrings
nicht überschritten wird:}
len:= Length-Offset;
if count < len then len:= count;
Data1:= SubstringData(0,offset);
Data2:= SubstringData(offset+len,Length-offset-len);
Data:= concat(Data1,arg,Data2);
end;
//+++++++++++++++++++++++++++ TdomAttr ++++++++++++++++++++++++++++++
constructor TdomAttr.Create(const AOwner: TdomDocument;
const NamespaceURI,
Name: WideString;
const Spcfd: boolean);
var
colonpos: integer;
prefix: WideString;
begin
if not IsXmlName(Name)
then raise EInvalid_Character_Err.create('Invalid character error.');
if (NamespaceURI <> '') then begin
if not IsXmlQName(Name) then raise ENamespace_Err.create('Namespace error.');
colonpos:= pos(':',Name);
if colonpos > 0 then begin
prefix:= copy(Name,1,length(Name)-colonpos);
if (prefix = 'xml') and (NamespaceURI <> 'http://www.w3.org/XML/1998/namespace')
then raise ENamespace_Err.create('Namespace error.');
if (prefix = 'xmlns') and (NamespaceURI <> '')
then raise ENamespace_Err.create('Namespace error.');
end;
end;
inherited Create(AOwner);
FNodeName:= Name;
FNodeValue:= '';
FNodeType:= ntAttribute_Node;
FOwnerElement:= nil;
FSpecified:= Spcfd;
FAllowedChildTypes:= [ntText_Node,
ntEntity_Reference_Node,
ntDocument_Fragment_Node];
end;
procedure TdomAttr.normalize;
var
PrevNode, CurrentNode: TdomNode;
i: integer;
begin
{normalize text:}
PrevNode:=nil;
i:=ChildNodes.Length;
while i>0 do
begin
Dec(i);
CurrentNode:=ChildNodes.Item(i);
if (CurrentNode.NodeType = ntText_Node) then
begin
if (Assigned(PrevNode)) and (PrevNode.NodeType = ntText_Node) then
begin
(CurrentNode as TdomText).AppendData((PrevNode as TdomText).Data);
removeChild(PrevNode);
PrevNode.OwnerDocument.FreeAllNodes(PrevNode);
end;
end
else // no text node, then normalize
CurrentNode.normalize;
PrevNode:=CurrentNode;
end;
end;
function TdomAttr.GetName: WideString;
begin
Result:= NodeName;
end;
function TdomAttr.GetSpecified: boolean;
begin
Result:= FSpecified;
end;
function TdomAttr.GetNodeValue: WideString;
begin
Result:= GetValue;
end;
procedure TdomAttr.SetNodeValue(const Value: WideString);
begin
raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
end;
function TdomAttr.GetValue: WideString;
var
i: integer;
EntityDec: TdomCustomEntity;
begin
Result:='';
for i:= 0 to ChildNodes.Length -1 do
case ChildNodes.item(i).NodeType of
ntText_Node:
Result:= Concat(Result,(ChildNodes.item(i) as TdomText).Data);
ntEntity_Reference_Node: begin
EntityDec:= (ChildNodes.item(i) as TdomEntityReference).Declaration;
if assigned(EntityDec)
then Result:= Concat(Result,EntityDec.Value);
end;
end;
end;
procedure TdomAttr.SetValue(const Value: WideString);
var
ValueNode: TdomNode;
begin
clear;
if Value <> '' then begin
ValueNode:= OwnerDocument.CreateText(Value);
AppendChild(ValueNode);
end;
end;
function TdomAttr.GetOwnerElement: TdomElement;
begin
Result:= FOwnerElement;
end;
function TdomAttr.GetParentNode: TdomNode;
begin
Result:= nil;
end;
function TdomAttr.GetPreviousSibling: TdomNode;
begin
Result:= nil;
end;
function TdomAttr.GetNextSibling: TdomNode;
begin
Result:= nil;
end;
function TdomAttr.GetCode: WideString;
begin
if specified
then Result:= concat(NodeName,WideString('="'),inherited GetCode,WideString('"'))
else Result:= '';
end;
//++++++++++++++++++++++++++++ TdomElement ++++++++++++++++++++++++++++++++
constructor TdomElement.Create(const AOwner: TdomDocument;
const NamespaceURI,
TagName: WideString);
begin
if not IsXmlName(TagName)
then raise EInvalid_Character_Err.create('Invalid character error.');
inherited Create(AOwner);
FNodeName:= TagName;
FNodeValue:= '';
FNodeType:= ntElement_Node;
FAttributeListing:= TList.create;
FCreatedElementsNodeLists:= TList.create;
FCreatedElementsNodeListNSs:= TList.create;
FAttributeList:= TdomNamedNodeMap.create(AOwner,self,FAttributeListing,[ntAttribute_Node]);
FAllowedChildTypes:= [ntElement_Node,
ntText_Node,
ntCDATA_Section_Node,
ntEntity_Reference_Node,
ntProcessing_Instruction_Node,
ntComment_Node,
ntDocument_Fragment_Node];
end;
destructor TdomElement.Destroy;
var
i: integer;
begin
FAttributeList.free;
FAttributeListing.free;
for i := 0 to FCreatedElementsNodeLists.Count - 1 do
TdomElementsNodeList(FCreatedElementsNodeLists[i]).free;
for i := 0 to FCreatedElementsNodeListNSs.Count - 1 do
TdomElementsNodeListNS(FCreatedElementsNodeListNSs[i]).free;
FCreatedElementsNodeLists.free;
FCreatedElementsNodeListNSs.free;
inherited Destroy;
end;
procedure TdomElement.SetNodeValue(const Value: WideString);
begin
raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
end;
function TdomElement.GetCode: WideString;
var
i: integer;
begin
Result:= concat(WideString('<'),NodeName);
for i:= 0 to Attributes.length -1 do
if (Attributes.Item(i) as TdomAttr).specified
then Result:= concat(Result,WideString(' '),Attributes.Item(i).code);
Result:= concat(Result,WideString('>'),inherited GetCode,WideString('</'),NodeName,WideString('>'));
end;
function TdomElement.GetTagName: WideString;
begin
Result:= NodeName;
end;
function TdomElement.GetAttributes: TdomNamedNodeMap;
begin
Result:= FAttributeList;
end;
function TdomElement.GetAttribute(const Name: WideString): WideString;
begin
if Attributes.NamespaceAware
then raise ENamespace_Err.create('Namespace error.');
if not assigned(GetAttributeNode(Name))
then Result:= ''
else Result:= (Attributes.GetNamedItem(Name) as TdomAttr).Value;
end;
function TdomElement.SetAttribute(const Name,
Value: WideString): TdomAttr;
var
Attr: TdomAttr;
begin
if Attributes.NamespaceAware
then raise ENamespace_Err.create('Namespace error.');
Attr:= GetAttributeNode(Name);
if assigned(Attr) then begin
Attr.Value:= Value;
Result:= nil;
end else begin
Result:= OwnerDocument.CreateAttribute(Name);
Result.Value:= Value;
SetAttributeNode(Result);
end;
end;
function TdomElement.RemoveAttribute(const Name: WideString): TdomAttr;
begin
if Attributes.NamespaceAware
then raise ENamespace_Err.create('Namespace error.');
if not assigned(GetAttributeNode(Name))
then ENot_Found_Err.create('Node not found error.');
Result:= RemoveAttributeNode(GetAttributeNode(Name));
end;
function TdomElement.GetAttributeNode(const Name: WideString): TdomAttr;
begin
if Attributes.NamespaceAware
then raise ENamespace_Err.create('Namespace error.');
Result:= TdomAttr(Attributes.GetNamedItem(Name));
end;
function TdomElement.SetAttributeNode(const NewAttr: TdomAttr): TdomAttr;
var
OldAttr: TdomAttr;
begin
if Attributes.NamespaceAware
then raise ENamespace_Err.create('Namespace error.');
if OwnerDocument <> NewAttr.OwnerDocument
then raise EWrong_Document_Err.create('Wrong document error.');
if assigned(NewAttr.parentNode) and not (NewAttr.OwnerElement = self)
then raise EInuse_Attribute_Err.create('Inuse attribute error.');
Result:= nil;
if not (NewAttr.OwnerElement = self) then begin
OldAttr:= (Attributes.GetNamedItem(NewAttr.Name) as TdomAttr);
if assigned(OldAttr) then Result:= RemoveAttributeNode(OldAttr);
Attributes.SetNamedItem(NewAttr);
end;
end;
function TdomElement.RemoveAttributeNode(const OldAttr: TdomAttr): TdomAttr;
begin
if Attributes.indexof(OldAttr) = -1
then raise ENot_Found_Err.create('Node not found error.');
Attributes.RemoveItem(OldAttr);
OldAttr.FOwnerElement:= nil;
Result:= OldAttr;
end;
function TdomElement.GetElementsByTagName(const Name: WideString): TdomNodeList;
var
i: integer;
begin
for i:= 0 to FCreatedElementsNodeLists.Count - 1 do
if TdomElementsNodeList(FCreatedElementsNodeLists[i]).FQueryName = Name
then begin Result:= TdomElementsNodeList(FCreatedElementsNodeLists[i]); exit; end;
Result:= TdomElementsNodeList.Create(Name,self);
FCreatedElementsNodeLists.add(Result);
end;
function TdomElement.GetAttributeNS(const namespaceURI,
localName: WideString): WideString;
begin
if not Attributes.NamespaceAware
then raise ENamespace_Err.create('Namespace error.');
if not assigned(GetAttributeNodeNS(namespaceURI,localName))
then Result:= ''
else Result:= (Attributes.GetNamedItemNS(namespaceURI,localName) as TdomAttr).Value;
end;
function TdomElement.SetAttributeNS(const namespaceURI,
qualifiedName,
value: WideString): TdomAttr;
var
Attr: TdomAttr;
prfx, localname: Widestring;
begin
if not Attributes.NamespaceAware
then raise ENamespace_Err.create('Namespace error.');
if not IsXmlName(QualifiedName)
then raise EInvalid_Character_Err.create('Invalid character error.');
if not IsXmlQName(QualifiedName)
then raise ENamespace_Err.create('Namespace error.');
prfx:= XMLExtractPrefix(QualifiedName);
if ( ((prfx = 'xmlns') or (QualifiedName = 'xmlns'))
and not (NamespaceURI ='http://www.w3.org/2000/xmlns/') )
then raise ENamespace_Err.create('Namespace error.');
if (NamespaceURI = '') and (prfx <> '')
then raise ENamespace_Err.create('Namespace error.');
if (prfx = 'xml') and (NamespaceURI <> 'http://www.w3.org/XML/1998/namespace')
then raise ENamespace_Err.create('Namespace error.');
localname:= XMLExtractLocalName(qualifiedName);
Attr:= GetAttributeNodeNS(namespaceURI,localName);
if assigned(Attr) then begin
Attr.FNodeName:= qualifiedName;
Attr.Value:= Value;
Result:= nil;
end else begin
Result:= OwnerDocument.CreateAttributeNS(namespaceURI,qualifiedName);
Result.Value:= Value;
SetAttributeNodeNS(Result);
end;
end;
function TdomElement.RemoveAttributeNS(const namespaceURI,
localName: WideString): TdomAttr;
begin
if not Attributes.NamespaceAware
then raise ENamespace_Err.create('Namespace error.');
if not assigned(GetAttributeNodeNS(namespaceURI,localName))
then ENot_Found_Err.create('Node not found error.');
Result:= RemoveAttributeNode(GetAttributeNodeNS(namespaceURI,localName));
end;
function TdomElement.GetAttributeNodeNS(const namespaceURI,
localName: WideString): TdomAttr;
begin
if not Attributes.NamespaceAware
then raise ENamespace_Err.create('Namespace error.');
Result:= TdomAttr(Attributes.GetNamedItemNS(namespaceURI,localName));
end;
function TdomElement.SetAttributeNodeNS(const NewAttr: TdomAttr): TdomAttr;
var
OldAttr: TdomAttr;
begin
if not Attributes.NamespaceAware
then raise ENamespace_Err.create('Namespace error.');
if OwnerDocument <> NewAttr.OwnerDocument
then raise EWrong_Document_Err.create('Wrong document error.');
if assigned(NewAttr.parentNode) and not (NewAttr.OwnerElement = self)
then raise EInuse_Attribute_Err.create('Inuse attribute error.');
Result:= nil;
if not (NewAttr.OwnerElement = self) then begin
OldAttr:= (Attributes.GetNamedItemNS(NewAttr.namespaceURI,NewAttr.localName) as TdomAttr);
if assigned(OldAttr) then Result:= RemoveAttributeNode(OldAttr);
Attributes.SetNamedItemNS(NewAttr);
end;
end;
function TdomElement.GetElementsByTagNameNS(const namespaceURI,
localName: WideString): TdomNodeList;
var
i: integer;
nl: TdomElementsNodeListNS;
begin
for i:= 0 to FCreatedElementsNodeListNSs.Count - 1 do begin
nl:= TdomElementsNodeListNS(FCreatedElementsNodeListNSs[i]);
if (nl.FQueryNamespaceURI = namespaceURI) and (nl.FQueryLocalName = localName)
then begin Result:= nl; exit; end;
end;
Result:= TdomElementsNodeListNS.Create(namespaceURI,localName,self);
FCreatedElementsNodeListNSs.add(Result);
end;
function TdomElement.hasAttribute(const name: WideString): boolean;
begin
Result:= assigned(Attributes.GetNamedItem(Name));
end;
function TdomElement.hasAttributeNS(const namespaceURI,
localName: WideString): boolean;
begin
Result:= assigned(Attributes.GetNamedItemNS(namespaceURI,localName));
end;
procedure TdomElement.normalize;
var
PrevNode, CurrentNode: TdomNode;
i: integer;
begin
{normalize text:}
PrevNode:=nil;
i:=ChildNodes.Length;
while i>0 do
begin
Dec(i);
CurrentNode:=ChildNodes.Item(i);
if (CurrentNode.NodeType = ntText_Node) then
begin
if (Assigned(PrevNode)) and (PrevNode.NodeType = ntText_Node) then
begin
(CurrentNode as TdomText).AppendData((PrevNode as TdomText).Data);
removeChild(PrevNode);
PrevNode.OwnerDocument.FreeAllNodes(PrevNode);
end;
end
else // no text node, then normalize
CurrentNode.normalize;
PrevNode:=CurrentNode;
end;
{normalize attributes:}
for i:= 0 to attributes.Length-1 do
attributes.item(i).normalize;
end;
//+++++++++++++++++++++++++++++ TdomText +++++++++++++++++++++++++++++++++
constructor TdomText.create(const AOwner: TdomDocument);
begin
inherited Create(AOwner);
FNodeName:= '#text';
FNodeValue:= '';
FNodeType:= ntText_Node;
end;
function TdomText.GetCode: WideString;
var
i,l: integer;
content: TdomCustomStr;
begin
content:= TdomCustomStr.create;
try
l:= system.length(FNodeValue);
for i:= 1 to l do
case Word((PWideChar(FNodeValue[i]))) of
60: content.addWideString(WideString('<'));
62: content.addWideString(WideString('>'));
38: content.addWideString(WideString('&'));
39: content.addWideString(WideString('''));
34: content.addWideString(WideString('"'));
else
content.addWideChar(WideChar(FNodeValue[i]));
end;
Result:= content.value;
finally
content.free;
end;
end;
function TdomText.SplitText(const offset: integer): TdomText;
begin
if(offset < 0) or (offset > Length)
then raise EIndex_Size_Err.create('Index size error.');
Result:= OwnerDocument.CreateText(SubstringData(offset,length-offset));
DeleteData(offset,length-offset);
if assigned(ParentNode) then ParentNode.InsertBefore(Result,self.NextSibling);
end;
//++++++++++++++++++++++++++++ TdomComment +++++++++++++++++++++++++++++++
constructor TdomComment.Create(const AOwner: TdomDocument);
begin
inherited Create(AOwner);
FNodeName:= '#comment';
FNodeValue:= '';
FNodeType:= ntComment_Node;
end;
function TdomComment.GetCode: WideString;
begin
Result:= concat(WideString('<!--'),FNodeValue,WideString('-->'));
end;
//+++++++++++++++++++++ TdomProcessingInstruction +++++++++++++++++++++++++
constructor TdomProcessingInstruction.Create(const AOwner: TdomDocument;
const Targ: WideString);
begin
if not IsXmlPITarget(Targ)
then raise EInvalid_Character_Err.create('Invalid character error.');
inherited Create(AOwner);
FNodeName:= Targ;
FNodeValue:= '';
FNodeType:= ntProcessing_Instruction_Node;
FAllowedChildTypes:= [];
end;
function TdomProcessingInstruction.GetTarget: WideString;
begin
Result:= FNodeName;
end;
function TdomProcessingInstruction.GetData: WideString;
begin
Result:= FNodeValue;
end;
procedure TdomProcessingInstruction.SetData(const Value: WideString);
begin
FNodeValue:= Value;
end;
function TdomProcessingInstruction.GetCode: WideString;
begin
Result:= concat(WideString('<?'),NodeName,WideString(' '),NodeValue,WideString('?>'));
end;
//++++++++++++++++++++++++ TdomXmlDeclaration ++++++++++++++++++++++++++
constructor TdomXmlDeclaration.Create(const AOwner: TdomDocument;
const Version,
EncDl,
SdDl: WideString);
begin
if not (IsXmlEncName(EncDl) or (EncDl = ''))
then raise EInvalid_Character_Err.create('Invalid character error.');
if not ((SdDl = 'yes') or (SdDl = 'no') or (SdDl = ''))
then raise EInvalid_Character_Err.create('Invalid character error.');
if not IsXmlVersionNum(Version)
then raise EInvalid_Character_Err.create('Invalid character error.');
inherited Create(AOwner);
FVersionNumber:= Version;
FEncodingDecl:= EncDl;
FStandalone:= SdDl;
FNodeName:= '#xml-declaration';
FNodeValue:= '';
FNodeType:= ntXml_Declaration_Node;
FAllowedChildTypes:= [];
end;
function TdomXmlDeclaration.GetVersionNumber: WideString;
begin
Result:= FVersionNumber;
end;
function TdomXmlDeclaration.GetEncodingDecl: WideString;
begin
Result:= FEncodingDecl;
end;
procedure TdomXmlDeclaration.SetEncodingDecl(const Value: WideString);
begin
if not (IsXmlEncName(Value) or (Value = ''))
then raise EInvalid_Character_Err.create('Invalid character error.');
FEncodingDecl:= Value;
end;
function TdomXmlDeclaration.GetStandalone: WideString;
begin
Result:= FStandalone;
end;
procedure TdomXmlDeclaration.SetStandalone(const Value: WideString);
begin
if not ((Value = 'yes') or (Value = 'no') or (Value = ''))
then raise EInvalid_Character_Err.create('Invalid character error.');
FStandalone:= Value;
end;
function TdomXmlDeclaration.GetCode: WideString;
begin
Result:= concat(WideString('<?xml version="'),VersionNumber,WideString('"'));
if EncodingDecl <> ''
then Result:= concat(Result,WideString(' encoding="'),EncodingDecl,WideString('"'));
if SDDecl <> ''
then Result:= concat(Result,WideString(' standalone="'),SDDecl,WideString('"'));
Result:= concat(Result,WideString('?>'));
end;
//++++++++++++++++++++++++++ TdomCDATASection +++++++++++++++++++++++++++++
constructor TdomCDATASection.Create(const AOwner: TdomDocument);
begin
inherited Create(AOwner);
FNodeName:= '#cdata-section';
FNodeValue:= '';
FNodeType:= ntCDATA_Section_Node;
end;
function TdomCDATASection.GetCode: WideString;
begin
Result:= concat(WideString('<![CDATA['),FNodeValue,WideString(']]>'));
end;
//++++++++++++++++++++++ TdomCustomDocumentType ++++++++++++++++++++++++
constructor TdomCustomDocumentType.Create(const AOwner: TdomDocument);
begin
inherited Create(AOwner);
FNodeValue:= '';
FParameterEntitiesListing:= TList.create;
FAttributeListsListing:= TList.create;
FParameterEntitiesList:= TdomNamedNodeMap.create(AOwner,self,FParameterEntitiesListing,[ntParameter_Entity_Node]);
FAttributeListsList:= TdomNamedNodeMap.create(AOwner,self,FAttributeListsListing,[ntAttribute_List_Node]);
FAllowedChildTypes:= [];
end;
destructor TdomCustomDocumentType.Destroy;
begin
FParameterEntitiesListing.free;
FAttributeListsListing.free;
FParameterEntitiesList.free;
FAttributeListsList.free;
inherited Destroy;
end;
procedure TdomCustomDocumentType.SetNodeValue(const Value: WideString);
begin
raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
end;
function TdomCustomDocumentType.GetParameterEntities: TdomNamedNodeMap;
begin
Result:= FParameterEntitiesList;
end;
function TdomCustomDocumentType.GetAttributeLists: TdomNamedNodeMap;
begin
Result:= FAttributeListsList;
end;
//++++++++++++++++++++++++++ TdomDocumentType +++++++++++++++++++++++++++++
constructor TdomDocumentType.Create(const AOwner: TdomDocument;
const Name,
PubId,
SysId: WideString);
begin
inherited Create(AOwner);
FNodeName:= Name;
FPublicId:= PubId;
FSystemId:= SysId;
FNodeType:= ntDocument_Type_Node;
FAllowedChildTypes:= [ntExternal_Subset_Node,
ntInternal_Subset_Node];
self.AppendChild(AOwner.CreateInternalSubset);
self.AppendChild(AOwner.CreateExternalSubset);
FEntitiesListing:= TList.create;
FEntitiesList:= TdomEntitiesNamedNodeMap.create(AOwner,self,FEntitiesListing,[ntEntity_Node]);
FNotationsListing:= TList.create;
FNotationsList:= TdomNamedNodeMap.create(AOwner,self,FNotationsListing,[ntNotation_Node]);
FIsReadonly:= true;
end;
destructor TdomDocumentType.Destroy;
begin
FEntitiesListing.free;
FEntitiesList.free;
FNotationsListing.free;
FNotationsList.free;
inherited Destroy;
end;
function TdomDocumentType.analyzeEntityValue(const EntityValue: wideString): widestring;
var
i,j: integer;
RefEndFound: boolean;
ReplaceText,EntName: wideString;
Entity: TdomNode;
begin
Result:= EntityValue;
i:= 0;
while i < length(Result) do begin
inc(i);
if result[i] = '%' then begin
j:= 0;
RefEndFound:= false;
while i+j < length(result) do begin
inc(j);
if result[i+j] = ';' then begin
RefEndFound:= true;
EntName:= copy(result,i+1,j-1);
Entity:= ParameterEntities.GetNamedItem(EntName);
if assigned(Entity)
then ReplaceText:= Entity.nodevalue
else raise EParserInvalidEntityDeclaration_Err.create('Invalid entity declaration error.');
delete(result,i,j+1);
insert(ReplaceText,Result,i);
i:= i-1;
break;
end; {if ...}
end; {while ...}
if not RefEndFound
then raise EParserInvalidEntityDeclaration_Err.create('Invalid entity declaration error.');
end else if result[i] = '&' then begin
j:= 0;
RefEndFound:= false;
while i+j < length(result) do begin
inc(j);
if result[i+j] = ';' then begin
RefEndFound:= true;
if result[i+1] = '#' then begin
ReplaceText:= XmlCharRefToStr(copy(result,i,j+1));
delete(result,i,j+1);
insert(ReplaceText,Result,i);
i:= i+length(ReplaceText)-1;
end; {if ...}
break;
end; {if ...}
end; {while ...}
if not RefEndFound
then raise EParserInvalidEntityDeclaration_Err.create('Invalid entity declaration error.');
end; {if ... else ...}
end; {while ...}
end;
function TdomDocumentType.GetCode: WideString;
var
IntSubs: WideString;
begin
Result:= concat(WideString('<!DOCTYPE '),NodeName,WideString(' '));
if (PublicId <> '') or (SystemId <> '')
then Result:= concat(Result,XMLAnalysePubSysId(PublicId,SystemId,''));
IntSubs:= InternalSubset; // To increase performance buffer store the internal subset.
if length(IntSubs) > 0
then Result:= concat(Result,WideString('['),IntSubs,
WideString(WideChar(10)),WideString(']'));
Result:= concat(result,WideString('>'));
end;
function TdomDocumentType.GetEntities: TdomEntitiesNamedNodeMap;
begin
Result:= FEntitiesList;
end;
function TdomDocumentType.GetExternalSubsetNode: TdomExternalSubset;
var
Child: TdomNode;
begin
Result:= nil;
Child:= GetFirstChild;
while assigned(Child) do begin
if Child.NodeType = ntExternal_Subset_Node then begin
Result:= (Child as TdomExternalSubset);
break;
end;
Child:= Child.NextSibling;
end;
end;
function TdomDocumentType.GetInternalSubsetNode: TdomInternalSubset;
var
Child: TdomNode;
begin
Result:= nil;
Child:= GetFirstChild;
while assigned(Child) do begin
if Child.NodeType = ntInternal_Subset_Node then begin
Result:= (Child as TdomInternalSubset);
break;
end;
Child:= Child.NextSibling;
end;
end;
function TdomDocumentType.GetInternalSubset: WideString;
var
i: integer;
S: WideString;
begin
Result:= '';
for i:= 0 to InternalSubsetNode.childnodes.length-1 do begin
S:= InternalSubsetNode.ChildNodes.Item(i).code;
if S <> '' then Result:= concat(Result,WideString(WideChar(10)),S);
end;
end;
function TdomDocumentType.GetName: WideString;
begin
Result:= NodeName;
end;
function TdomDocumentType.GetNotations: TdomNamedNodeMap;
begin
Result:= FNotationsList;
end;
function TdomDocumentType.GetPublicId: WideString;
begin
Result:= FPublicId;
end;
function TdomDocumentType.GetSystemId: WideString;
begin
Result:= FSystemId;
end;
//+++++++++++++++++++++++ TdomExternalSubset ++++++++++++++++++++++++++
constructor TdomExternalSubset.Create(const AOwner: TdomDocument);
begin
inherited create(AOwner);
FNodeName:= '#external-subset';
FNodeType:= ntExternal_Subset_Node;
FAllowedChildTypes:= [ntParameter_Entity_Reference_Node,
ntElement_Type_Declaration_Node,
ntAttribute_List_Node,
ntEntity_Declaration_Node,
ntText_Declaration_Node,
ntParameter_Entity_Declaration_Node,
ntNotation_Declaration_Node,
ntProcessing_Instruction_Node,
ntComment_Node,
ntConditional_Section_Node];
end;
function TdomExternalSubset.CloneNode(const deep: boolean): TdomNode;
begin
result:= inherited cloneNode(deep);
makeChildrenReadonly;
end;
//+++++++++++++++++++++++ TdomInternalSubset ++++++++++++++++++++++++++
constructor TdomInternalSubset.Create(const AOwner: TdomDocument);
begin
inherited create(AOwner);
FNodeName:= '#internal-subset';
FNodeType:= ntInternal_Subset_Node;
FAllowedChildTypes:= [ntParameter_Entity_Reference_Node,
ntElement_Type_Declaration_Node,
ntAttribute_List_Node,
ntEntity_Declaration_Node,
ntParameter_Entity_Declaration_Node,
ntNotation_Declaration_Node,
ntProcessing_Instruction_Node,
ntComment_Node];
end;
//+++++++++++++++++++++ TdomConditionalSection ++++++++++++++++++++++++
constructor TdomConditionalSection.Create(const AOwner: TdomDocument;
const IncludeStmt: WideString);
var
IncludeNode: TdomNode;
begin
if not ( IsXmlPEReference(IncludeStmt)
or (IncludeStmt = 'INCLUDE')
or (IncludeStmt = 'IGNORE') ) then raise EInvalid_Character_Err.create('Invalid character error.');
inherited create(AOwner);
FNodeName:= '#conditional-section';
FNodeType:= ntConditional_Section_Node;
if (IncludeStmt = 'INCLUDE') or (IncludeStmt = 'IGNORE')
then IncludeNode:= OwnerDocument.CreateText(IncludeStmt)
else IncludeNode:= OwnerDocument.CreateParameterEntityReference(copy(IncludeStmt,2,length(IncludeStmt)-2));
SetIncluded(IncludeNode);
FAllowedChildTypes:= [ntParameter_Entity_Reference_Node,
ntElement_Type_Declaration_Node,
ntAttribute_List_Node,
ntEntity_Declaration_Node,
ntParameter_Entity_Declaration_Node,
ntNotation_Declaration_Node,
ntProcessing_Instruction_Node,
ntComment_Node,
ntConditional_Section_Node];
end;
function TdomConditionalSection.GetIncluded: TdomNode;
begin
Result:= FIncluded;
end;
function TdomConditionalSection.GetCode: WideString;
var
i: integer;
S: WideString;
begin
Result:= concat(WideString('<![ '),Included.Code,WideString(' ['),WideString(WideChar(10)));
for i:= 0 to childnodes.length-1 do begin
S:= ChildNodes.Item(i).code;
if S <> '' then Result:= concat(Result,S,WideString(WideChar(10)));
end;
Result:= concat(Result,WideString(']]>'));
end;
function TdomConditionalSection.SetIncluded(const Node: TdomNode): TdomNode;
var
Error: boolean;
begin
case Node.NodeType of
ntText_Node:
if (Node.NodeValue = 'INCLUDE') or (Node.NodeValue = 'IGNORE')
then error:= false
else error:= true;
ntParameter_Entity_Reference_Node:
error:= false;
else
error:= true;
end; {case ...}
if Error then raise EInvalid_Character_Err.create('Invalid character error.');
Result:= FIncluded;
FIncluded:= Node;
end;
//++++++++++++++++++++++++++ TdomNotation ++++++++++++++++++++++++++++++
constructor TdomNotation.Create(const AOwner: TdomDocument;
const Name,
PubId,
SysId: WideString);
var
sQuote, dQuote: WideString;
begin
sQuote:= #$0027;
dQuote:= '"';
if not IsXmlName(Name)
then raise EInvalid_Character_Err.create('Invalid character error.');
if ( not ( IsXMLSystemLiteral(concat(dQuote,SystemId,dQuote)) or
IsXMLSystemLiteral(concat(sQuote,SysId,sQuote)) ) )
and ( not ( IsXMLPubidLiteral(concat(dQuote,PublicId,dQuote)) or
IsXMLPubidLiteral(concat(sQuote,PubId,sQuote)) ) )
then raise EInvalid_Character_Err.create('Invalid character error.');
inherited Create(AOwner);
FNodeName:= Name;
FNodeValue:= '';
FPublicId:= PubId;
FSystemId:= SysId;
FNodeType:= ntNotation_Node;
FAllowedChildTypes:= [];
end;
procedure TdomNotation.SetNodeValue(const Value: WideString);
begin
raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
end;
function TdomNotation.GetCode: WideString;
begin
Result:= '';
end;
function TdomNotation.GetPublicId: WideString;
begin
Result:= FPublicId;
end;
function TdomNotation.GetSystemId: WideString;
begin
Result:= FSystemId;
end;
//++++++++++++++++++++ TdomNotationDeclaration +++++++++++++++++++++++++
constructor TdomNotationDeclaration.Create(const AOwner: TdomDocument;
const Name,
PubId,
SysId: WideString);
var
sQuote, dQuote: WideString;
begin
sQuote:= #$0027;
dQuote:= '"';
if not IsXmlName(Name)
then raise EInvalid_Character_Err.create('Invalid character error.');
if ( not ( IsXMLSystemLiteral(concat(dQuote,SystemId,dQuote)) or
IsXMLSystemLiteral(concat(sQuote,SysId,sQuote)) ) )
and ( not ( IsXMLPubidLiteral(concat(dQuote,PublicId,dQuote)) or
IsXMLPubidLiteral(concat(sQuote,PubId,sQuote)) ) )
then raise EInvalid_Character_Err.create('Invalid character error.');
inherited Create(AOwner);
FNodeName:= Name;
FNodeValue:= '';
FPublicId:= PubId;
FSystemId:= SysId;
FNodeType:= ntNotation_Declaration_Node;
FAllowedChildTypes:= [];
end;
procedure TdomNotationDeclaration.SetNodeValue(const Value: WideString);
begin
raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
end;
function TdomNotationDeclaration.GetCode: WideString;
begin
Result:= concat(WideString('<!NOTATION '),NodeName,WideString(' '),XMLAnalysePubSysId(PublicId,SystemId,''),WideString('>'));
end;
function TdomNotationDeclaration.GetPublicId: WideString;
begin
Result:= FPublicId;
end;
function TdomNotationDeclaration.GetSystemId: WideString;
begin
Result:= FSystemId;
end;
//++++++++++++++++++++++ TdomCustomDeclaration +++++++++++++++++++++++++
constructor TdomCustomDeclaration.Create(const AOwner: TdomDocument;
const Name: WideString);
begin
if not IsXmlName(Name)
then raise EInvalid_Character_Err.create('Invalid character error.');
inherited Create(AOwner);
FNodeName:= Name;
FAllowedChildTypes:= [ntElement_Node,
ntProcessing_Instruction_Node,
ntComment_Node,
ntText_Node,
ntCDATA_Section_Node,
ntEntity_Reference_Node,
ntParameter_Entity_Reference_Node,
ntDocument_Fragment_Node];
end;
function TdomCustomDeclaration.GetValue: WideString;
var
i: integer;
begin
Result:='';
for i:= 0 to ChildNodes.Length -1 do
Result:= concat(Result,ChildNodes.item(i).code);
end;
procedure TdomCustomDeclaration.SetValue(const Value: WideString);
var
ValueNode: TdomNode;
begin
clear;
if Value <> '' then begin
ValueNode:= OwnerDocument.CreateText(Value);
AppendChild(ValueNode);
end;
end;
procedure TdomCustomDeclaration.SetNodeValue(const Value: WideString);
begin
raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
end;
//++++++++++++++++++ TdomElementTypeDeclaration ++++++++++++++++++++++++
constructor TdomElementTypeDeclaration.Create(const AOwner: TdomDocument;
const Name: WideString;
const Contspec: TdomContentspecType);
begin
inherited create(AOwner,Name);
FNodeType:= ntElement_Type_Declaration_Node;
FContentspec:= Contspec;
case Contspec of
ctEmpty,ctAny: FAllowedChildTypes:= [];
ctMixed: FAllowedChildTypes:= [ntPcdata_Choice_Particle_Node];
ctChildren: FAllowedChildTypes:= [ntSequence_Particle_Node,
ntChoice_Particle_Node,
ntElement_Particle_Node];
end;
end;
function TdomElementTypeDeclaration.GetContentspec: TdomContentspecType;
begin
Result:= FContentspec;
end;
function TdomElementTypeDeclaration.GetCode: WideString;
begin
if (contentspec <> ctEmpty) and (contentspec <> ctAny) and not hasChildNodes
then raise ENot_Supported_Err.create('Not supported error.');
Result:= concat(WideString('<!ELEMENT '),NodeName,WideString(' '));
case ContentSpec of
ctEmpty: Result:= concat(Result,WideString('EMPTY '));
ctAny: Result:= concat(Result,WideString('ANY '));
ctMixed, ctChildren: Result:= concat(Result,ChildNodes.Item(0).Code);
end; {case ...}
Result:= concat(Result,WideString('>'));
end;
function TdomElementTypeDeclaration.AppendChild(const newChild: TdomNode): TdomNode;
begin
if (contentspec = ctEmpty) or (contentspec = ctAny)
or (hasChildNodes and (FirstChild <> newChild))
then raise ENot_Supported_Err.create('Not supported error.');
result:= inherited AppendChild(newChild);
end;
function TdomElementTypeDeclaration.InsertBefore(const newChild,
refChild: TdomNode): TdomNode;
begin
if (contentspec = ctEmpty) or (contentspec = ctAny)
or (hasChildNodes and (FirstChild <> newChild))
then raise ENot_Supported_Err.create('Not supported error.');
result:= inherited InsertBefore(newChild,refChild);
end;
//++++++++++++++++++++++ TdomAttrList +++++++++++++++++++++++++++++
constructor TdomAttrList.Create(const AOwner: TdomDocument;
const Name: WideString);
begin
inherited Create(AOwner,Name);
FNodeType:= ntAttribute_List_Node;
FAttDefListing:= TList.create;
FAttDefList:= TdomNamedNodeMap.create(AOwner,self,FAttDefListing,[ntAttribute_Definition_Node]);
FAllowedChildTypes:= [];
end;
destructor TdomAttrList.Destroy;
begin
FAttDefList.free;
FAttDefListing.free;
inherited Destroy;
end;
function TdomAttrList.GetAttributeDefinitions: TdomNamedNodeMap;
begin
Result:= FAttDefList;
end;
function TdomAttrList.GetCode: WideString;
var
i: integer;
begin
Result:= concat(WideString('<!ATTLIST '),NodeName);
if AttributeDefinitions.length > 0 then Result:= concat(Result,WideString(WideChar(10)));
for i:= 0 to AttributeDefinitions.length -1 do begin
Result:= concat(Result,WideString(WideChar(9)),AttributeDefinitions.item(i).Code);
if i < AttributeDefinitions.length -1 then Result:= concat(Result,WideString(WideChar(10)));
end;
Result:= concat(Result,WideString('>'));
end;
function TdomAttrList.RemoveAttributeDefinition(const Name: WideString): TdomAttrDefinition;
begin
if not assigned(GetAttributeDefinitionNode(Name))
then ENot_Found_Err.create('Node not found error.');
Result:= RemoveAttributeDefinitionNode(GetAttributeDefinitionNode(Name));
end;
function TdomAttrList.GetAttributeDefinitionNode(const Name: WideString): TdomAttrDefinition;
begin
Result:= TdomAttrDefinition(AttributeDefinitions.GetNamedItem(Name));
end;
function TdomAttrList.SetAttributeDefinitionNode(const NewAttDef: TdomAttrDefinition): boolean;
begin
if OwnerDocument <> NewAttDef.OwnerDocument
then raise EWrong_Document_Err.create('Wrong document error.');
if assigned(NewAttDef.parentNode) and not (NewAttDef.ParentAttributeList = self)
then raise EInuse_AttributeDefinition_Err.create('Inuse attribute definition error.');
Result:= true;
if not (NewAttDef.ParentAttributeList = self) then
if assigned((AttributeDefinitions.GetNamedItem(NewAttDef.NodeName) as TdomAttrDefinition))
then Result:= false
else begin
AttributeDefinitions.SetNamedItem(NewAttDef);
NewAttDef.FParentAttributeList:= self;
end;
end;
function TdomAttrList.RemoveAttributeDefinitionNode(const OldAttDef: TdomAttrDefinition): TdomAttrDefinition;
begin
if AttributeDefinitions.indexof(OldAttDef) = -1
then raise ENot_Found_Err.create('Node not found error.');
AttributeDefinitions.RemoveItem(OldAttDef);
OldAttDef.FParentAttributeList:= nil;
Result:= OldAttDef;
end;
//++++++++++++++++++++ TdomAttrDefinition +++++++++++++++++++++++++
constructor TdomAttrDefinition.Create(const AOwner: TdomDocument;
const Name,
AttType,
DefaultDecl,
AttValue: WideString);
var
sQuote, dQuote: WideString;
begin
sQuote:= #$0027;
dQuote:= '"';
if not IsXmlName(Name)
then raise EInvalid_Character_Err.create('Invalid character error.');
if not ( (AttType='') or (AttType='NOTATION') or
IsXmlStringType(AttType) or IsXmlTokenizedType(AttType) )
then raise EInvalid_Character_Err.create('Invalid character error.');
if not ( (DefaultDecl = '#REQUIRED') or (DefaultDecl = '#IMPLIED') or
(DefaultDecl = '#FIXED') or (DefaultDecl = '') )
then raise EInvalid_Character_Err.create('Invalid character error.');
if ((DefaultDecl = '#REQUIRED') or (DefaultDecl = '#IMPLIED'))
and (AttValue <> '')
then raise EInvalid_Character_Err.create('Invalid character error.');
if ((DefaultDecl = '#FIXED') or (DefaultDecl = ''))
and (AttValue = '')
then raise EInvalid_Character_Err.create('Invalid character error.');
if not ( IsXMLAttValue(concat(dQuote,AttValue,dQuote)) or
IsXMLAttValue(concat(sQuote,AttValue,sQuote)) )
then raise EInvalid_Character_Err.create('Invalid character error.');
inherited create(AOwner);
FNodeName:= Name;
FAttributeType:= AttType;
FDefaultDeclaration:= DefaultDecl;
FNodeValue:= AttValue;
FNodeType:= ntAttribute_Definition_Node;
FParentAttributeList:= nil;
FAllowedChildTypes:= [];
if AttType = '' then FAllowedChildTypes:= [ntNametoken_Node];
if AttType = 'NOTATION' then FAllowedChildTypes:= [ntElement_Particle_Node];
end;
function TdomAttrDefinition.GetAttributeType: WideString;
begin
Result:= FAttributeType;
end;
function TdomAttrDefinition.GetDefaultDeclaration: WideString;
begin
Result:= FDefaultDeclaration;
end;
function TdomAttrDefinition.GetName: WideString;
begin
Result:= NodeName;
end;
function TdomAttrDefinition.GetParentAttributeList: TdomAttrList;
begin
Result:= FParentAttributeList;
end;
procedure TdomAttrDefinition.SetNodeValue(const Value: WideString);
begin
raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
end;
function TdomAttrDefinition.GetCode: WideString;
var
i: integer;
sQuote, dQuote: WideString;
begin
sQuote:= #$0027;
dQuote:= '"';
Result:= concat(Name,WideString(WideChar(9)));
if AttributeType <> '' then Result:= concat(Result,AttributeType,WideString(WideChar(9)));
if HasChildNodes then begin
Result:= concat(Result,WideString('('));
for i:= 0 to ChildNodes.Length -1 do begin
if i > 0 then Result:= concat(Result,WideString(' | '));
Result:= concat(Result,ChildNodes.item(i).code);
end;
Result:= concat(Result,WideString(')'));
end;
if DefaultDeclaration <> ''
then Result:= concat(Result,WideString(WideChar(9)),DefaultDeclaration);
if (DefaultDeclaration = '') or (DefaultDeclaration = '#FIXED') then
if Pos(dQuote,NodeValue) > 0
then Result:= concat(Result,WideString(WideChar(9)),sQuote,NodeValue,sQuote)
else Result:= concat(Result,WideString(WideChar(9)),dQuote,NodeValue,dQuote);
end;
//++++++++++++++++++++++++ TdomNametoken +++++++++++++++++++++++++++++++
constructor TdomNametoken.Create(const AOwner: TdomDocument;
const Name: WideString);
begin
if not IsXmlNmtoken(Name)
then raise EInvalid_Character_Err.create('Invalid character error.');
inherited create(AOwner);
FNodeName:= Name;
FNodeType:= ntNametoken_Node;
FAllowedChildTypes:= [];
end;
function TdomNametoken.GetCode: WideString;
begin
Result:= NodeName;
end;
procedure TdomNametoken.SetNodeValue(const Value: WideString);
begin
raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
end;
//+++++++++++++++++++++++++ TdomParticle +++++++++++++++++++++++++++++++
constructor TdomParticle.Create(const AOwner: TdomDocument;
const Freq: WideString);
begin
if not ( (Freq = '') or (Freq = '?') or (Freq = '*') or (Freq = '+') )
then raise EInvalid_Character_Err.create('Invalid character error.');
inherited create(AOwner);
FNodeType:= ntUnknown;
FAllowedChildTypes:= [];
FFrequency:= Freq;
end;
function TdomParticle.GetFrequency: WideString;
begin
Result:= FFrequency;
end;
procedure TdomParticle.SetFrequency(const freq: WideString);
begin
if not ( (Freq = '') or (Freq = '?') or (Freq = '*') or (Freq = '+') )
then raise EInvalid_Character_Err.create('Invalid character error.');
FFrequency:= Freq;
end;
procedure TdomParticle.SetNodeValue(const Value: WideString);
begin
raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
end;
//++++++++++++++++++++++ TdomSequenceParticle ++++++++++++++++++++++++++
constructor TdomSequenceParticle.Create(const AOwner: TdomDocument;
const Freq: WideString);
begin
inherited create(AOwner,Freq);
FNodeName:= '#sequence-particle';
FNodeType:= ntSequence_Particle_Node;
FAllowedChildTypes:= [ntSequence_Particle_Node,
ntChoice_Particle_Node,
ntElement_Particle_Node];
end;
function TdomSequenceParticle.GetCode: WideString;
var
i: integer;
begin
if not HasChildNodes
then raise ENot_Supported_Err.create('Not supported error.');
Result:= '(';
for i:= 0 to childnodes.length-1 do begin
if i > 0 then Result:= concat(Result,WideString(', '));
Result:= concat(Result,ChildNodes.item(i).code);
end;
Result:= concat(Result,WideString(')'),Frequency);
end;
//++++++++++++++++++++++ TdomChoiceParticle ++++++++++++++++++++++++++++
constructor TdomChoiceParticle.create(const AOwner: TdomDocument;
const Freq: WideString);
begin
inherited create(AOwner,Freq);
FNodeName:= '#choice-particle';
FNodeType:= ntChoice_Particle_Node;
FAllowedChildTypes:= [ntSequence_Particle_Node,
ntChoice_Particle_Node,
ntElement_Particle_Node];
end;
function TdomChoiceParticle.getCode: WideString;
var
i: integer;
begin
if not HasChildNodes
then raise ENot_Supported_Err.create('Not supported error.');
Result:= '(';
for i:= 0 to childnodes.length-1 do begin
if i > 0 then Result:= concat(Result,WideString(' | '));
Result:= concat(Result,ChildNodes.item(i).code);
end;
Result:= concat(Result,WideString(')'),Frequency);
end;
//+++++++++++++++++++ TdomPcdataChoiceParticle +++++++++++++++++++++++++
constructor TdomPcdataChoiceParticle.create(const AOwner: TdomDocument;
const Freq: WideString);
begin
if Freq <> '*'
then raise EInvalid_Character_Err.create('Invalid character error.');
inherited create(AOwner,Freq);
FNodeName:= '#pcdata-choice-particle';
FNodeType:= ntPcdata_Choice_Particle_Node;
FAllowedChildTypes:= [ntElement_Particle_Node];
end;
function TdomPcdataChoiceParticle.getCode: WideString;
var
i: integer;
begin
Result:= '( #PCDATA';
for i:= 0 to childnodes.length-1 do begin
Result:= concat(Result,WideString(' | '),ChildNodes.item(i).code);
end;
Result:= concat(Result,WideString(' )'),Frequency);
end;
procedure TdomPcdataChoiceParticle.SetFrequency(const freq: WideString);
begin
if Freq <> '*'
then raise EInvalid_Character_Err.create('Invalid character error.');
FFrequency:= Freq;
end;
//++++++++++++++++++++++ TdomElementParticle +++++++++++++++++++++++++++
constructor TdomElementParticle.Create(const AOwner: TdomDocument;
const Name,
Freq: WideString);
begin
if not IsXmlName(Name)
then raise EInvalid_Character_Err.create('Invalid character error.');
inherited create(AOwner,Freq);
FNodeName:= Name;
FNodeType:= ntElement_Particle_Node;
FAllowedChildTypes:= [];
end;
function TdomElementParticle.GetCode: WideString;
begin
Result:= concat(NodeName,Frequency);
end;
//++++++++++++++++++++++++ TdomCustomEntity ++++++++++++++++++++++++++++
constructor TdomCustomEntity.Create(const AOwner: TdomDocument;
const Name,
PubId,
SysId: WideString);
var
sQuote, dQuote: WideString;
begin
sQuote:= #$0027;
dQuote:= '"';
if not ( IsXMLSystemLiteral(concat(dQuote,SysId,dQuote)) or
IsXMLSystemLiteral(concat(sQuote,SysId,sQuote)) )
then raise EInvalid_Character_Err.create('Invalid character error.');
if not ( IsXMLPubidLiteral(concat(dQuote,PubId,dQuote)) or
IsXMLPubidLiteral(concat(sQuote,PubId,sQuote)) )
then raise EInvalid_Character_Err.create('Invalid character error.');
inherited Create(AOwner,Name);
FPublicId:= PubId;
FSystemId:= SysId;
if (PubId = '') and (SysId = '')
then FIsInternalEntity:= true
else FIsInternalEntity:= false;
end;
procedure TdomCustomEntity.SetValue(const Value: WideString);
begin
if (PublicId <> '') or (SystemId <> '')
then raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
inherited SetValue(Value);
end;
function TdomCustomEntity.InsertBefore(const newChild,
refChild: TdomNode): TdomNode;
begin
if (PublicId <> '') or (SystemId <> '')
then raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
Result:= inherited InsertBefore(newChild,refChild);
end;
function TdomCustomEntity.ReplaceChild(const newChild,
oldChild: TdomNode): TdomNode;
begin
if (PublicId <> '') or (SystemId <> '')
then raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
Result:= inherited ReplaceChild(newChild,oldChild);
end;
function TdomCustomEntity.AppendChild(const newChild: TdomNode): TdomNode;
begin
if (PublicId <> '') or (SystemId <> '')
then raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
Result:= inherited AppendChild(newChild);
end;
function TdomCustomEntity.GetPublicId: WideString;
begin
Result:= FPublicId;
end;
function TdomCustomEntity.GetSystemId: WideString;
begin
Result:= FSystemId;
end;
function TdomCustomEntity.GetIsInternalEntity: boolean;
begin
Result:= FIsInternalEntity;
end;
//+++++++++++++++++++++ TdomExternalParsedEntity +++++++++++++++++++++++
constructor TdomExternalParsedEntity.Create(const AOwner: TdomDocument);
begin
inherited Create(AOwner);
FNodeName:= '#external-parsed-entity';
FNodeType:= ntExternal_Parsed_Entity_Node;
FAllowedChildTypes:= [ntElement_Node,
ntText_Node,
ntCDATA_Section_Node,
ntEntity_Reference_Node,
ntProcessing_Instruction_Node,
ntComment_Node,
ntDocument_Fragment_Node];
end;
//+++++++++++++++++++ TdomExternalParameterEntity ++++++++++++++++++++++
constructor TdomExternalParameterEntity.Create(const AOwner: TdomDocument);
begin
inherited Create(AOwner);
FNodeName:= '#external-parameter-entity';
FNodeType:= ntExternal_Parameter_Entity_Node;
FAllowedChildTypes:= [ntParameter_Entity_Reference_Node,
ntElement_Type_Declaration_Node,
ntAttribute_List_Node,
ntEntity_Declaration_Node,
ntParameter_Entity_Declaration_Node,
ntNotation_Declaration_Node,
ntProcessing_Instruction_Node,
ntComment_Node,
ntConditional_Section_Node];
end;
//+++++++++++++++++++++++++++ TdomEntity +++++++++++++++++++++++++++++++++
constructor TdomEntity.Create(const AOwner: TdomDocument;
const Name,
PubId,
SysId,
NotaName: WideString);
begin
inherited Create(AOwner,Name,PubId,SysId);
FNotationName:= notaName;
FNodeType:= ntEntity_Node;
end;
function TdomEntity.CloneNode(const deep: boolean): TdomNode;
begin
result:= inherited cloneNode(deep);
makeChildrenReadonly;
end;
function TdomEntity.GetNotationName: WideString;
begin
Result:= FNotationName;
end;
//++++++++++++++++++++++ TdomParameterEntity +++++++++++++++++++++++++++
constructor TdomParameterEntity.Create(const AOwner: TdomDocument;
const Name,
PubId,
SysId: WideString);
begin
inherited Create(AOwner,Name,PubId,SysId);
FNodeType:= ntParameter_Entity_Node;
end;
//++++++++++++++++++++++ TdomEntityDeclaration +++++++++++++++++++++++++
constructor TdomEntityDeclaration.Create(const AOwner: TdomDocument;
const Name,
EntityValue,
PubId,
SysId,
NotaName: WideString);
var
sQuote, dQuote: WideString;
begin
sQuote:= #$0027;
dQuote:= '"';
if not (IsXMLName(NotaName) or (NotaName = '') )
then raise EInvalid_Character_Err.create('Invalid character error.');
if (EntityValue <> '') then begin
if not ( IsXmlEntityValue(concat(dQuote,SystemId,dQuote)) or
IsXmlEntityValue(concat(sQuote,SysId,sQuote)) )
then raise EInvalid_Character_Err.create('Invalid character error.');
if not ( (PubId = '') and (SysId = '') and (NotaName = '') )
then raise EInvalid_Character_Err.create('Invalid character error.');
end;
inherited Create(AOwner,Name,PubId,SysId);
FNotationName:= notaName;
FNodeType:= ntEntity_Declaration_Node;
FNodeValue:= EntityValue;
FExtParsedEnt:= nil;
FAllowedChildTypes:= [];
end;
function TdomEntityDeclaration.GetExtParsedEnt: TdomExternalParsedEntity;
begin
Result:= FExtParsedEnt;
end;
procedure TdomEntityDeclaration.SetExtParsedEnt(const Value: TdomExternalParsedEntity);
begin
if IsInternalEntity and assigned(Value)
then raise ENo_External_Entity_Allowed_Err.create('No external entity allowed error.');
FExtParsedEnt:= Value;
end;
function TdomEntityDeclaration.GetNotationName: WideString;
begin
Result:= FNotationName;
end;
function TdomEntityDeclaration.GetCode: WideString;
var
sQuote, dQuote: WideString;
begin
sQuote:= #$0027;
dQuote:= '"';
Result:= concat(WideString('<!ENTITY '),NodeName,WideString(' '));
if (PublicId = '') and (SystemId = '') then begin
if Pos(dQuote,NodeValue) > 0
then Result:= concat(Result,WideString(WideChar(9)),sQuote,NodeValue,sQuote)
else Result:= concat(Result,WideString(WideChar(9)),dQuote,NodeValue,dQuote);
end else Result:= concat(Result,XMLAnalysePubSysId(PublicId,SystemId,NotationName));
Result:= concat(Result,WideString('>'));
end;
//+++++++++++++++++ TdomParameterEntityDeclaration +++++++++++++++++++++
constructor TdomParameterEntityDeclaration.Create(const AOwner: TdomDocument;
const Name,
EntityValue,
PubId,
SysId: WideString);
var
sQuote, dQuote: WideString;
begin
sQuote:= #$0027;
dQuote:= '"';
if (EntityValue <> '') then begin
if not ( IsXmlEntityValue(concat(dQuote,SystemId,dQuote)) or
IsXmlEntityValue(concat(sQuote,SysId,sQuote)) )
then raise EInvalid_Character_Err.create('Invalid character error.');
if not ( (PubId = '') and (SysId = '') )
then raise EInvalid_Character_Err.create('Invalid character error.');
end;
inherited Create(AOwner,Name,PubId,SysId);
FNodeType:= ntParameter_Entity_Declaration_Node;
FNodeValue:= EntityValue;
FExtParamEnt:= nil;
FAllowedChildTypes:= [];
end;
function TdomParameterEntityDeclaration.GetCode: WideString;
var
sQuote, dQuote: WideString;
begin
sQuote:= #$0027;
dQuote:= '"';
Result:= concat(WideString('<!ENTITY % '),NodeName,WideString(' '));
if (PublicId = '') and (SystemId = '') then begin
if Pos(dQuote,NodeValue) > 0
then Result:= concat(Result,WideString(WideChar(9)),sQuote,NodeValue,sQuote)
else Result:= concat(Result,WideString(WideChar(9)),dQuote,NodeValue,dQuote);
end else Result:= concat(Result,XMLAnalysePubSysId(PublicId,SystemId,''));
Result:= concat(Result,WideString('>'));
end;
function TdomParameterEntityDeclaration.GetExtParamEnt: TdomExternalParameterEntity;
begin
Result:= FExtParamEnt;
end;
procedure TdomParameterEntityDeclaration.SetExtParamEnt(const Value: TdomExternalParameterEntity);
begin
if IsInternalEntity and assigned(Value)
then raise ENo_External_Entity_Allowed_Err.create('No external entity allowed error.');
FExtParamEnt:= Value;
end;
//++++++++++++++++++++++++++ TdomReference ++++++++++++++++++++++++++++
constructor TdomReference.Create(const AOwner: TdomDocument;
const Name: WideString);
begin
if not IsXmlName(Name)
then raise EInvalid_Character_Err.create('Invalid character error.');
inherited Create(AOwner);
FNodeName:= Name;
FNodeValue:= '';
FNodeType:= ntUnknown;
FAllowedChildTypes:= [];
end;
procedure TdomReference.SetNodeValue(const Value: WideString);
begin
raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
end;
function TdomReference.GetNodeValue: WideString;
begin
if assigned(Declaration)
then Result:= Declaration.value
else Result:='';
end;
function TdomReference.GetDeclaration: TdomCustomEntity;
begin
Result:= nil;
if assigned(OwnerDocument.Doctype) then begin
if self.NodeType = ntEntity_Reference_Node
then Result:= (OwnerDocument.Doctype.Entities.GetNamedItem(NodeName) as TdomEntity);
if self.NodeType = ntParameter_Entity_Reference_Node
then Result:= (OwnerDocument.Doctype.ParameterEntities.GetNamedItem(NodeName) as TdomParameterEntity);
end;
end;
//++++++++++++++++++++++++ TdomEntityReference +++++++++++++++++++++++++
constructor TdomEntityReference.Create(const AOwner: TdomDocument;
const Name: WideString);
begin
inherited Create(AOwner,Name);
FNodeType:= ntEntity_Reference_Node;
FAllowedChildTypes:= [ntElement_Node,
ntText_Node,
ntCDATA_Section_Node,
ntEntity_Reference_Node,
ntProcessing_Instruction_Node,
ntComment_Node,
ntDocument_Fragment_Node];
end;
function TdomEntityReference.GetCode: WideString;
begin
Result:= concat(WideString('&'),NodeName,WideString(';'))
end;
function TdomEntityReference.CloneNode(const deep: boolean): TdomNode;
begin
result:= inherited cloneNode(deep);
makeChildrenReadonly;
end;
//+++++++++++++++++++ TdomParameterEntityReference +++++++++++++++++++++
constructor TdomParameterEntityReference.Create(const AOwner: TdomDocument;
const Name: WideString);
begin
inherited Create(AOwner,Name);
FNodeType:= ntParameter_Entity_Reference_Node;
FAllowedChildTypes:= [ntParameter_Entity_Reference_Node,
ntElement_Type_Declaration_Node,
ntAttribute_List_Node,
ntEntity_Declaration_Node,
ntParameter_Entity_Declaration_Node,
ntNotation_Declaration_Node,
ntProcessing_Instruction_Node,
ntComment_Node];
end;
function TdomParameterEntityReference.GetCode: WideString;
begin
Result:= concat(WideString('%'),NodeName,WideString(';'))
end;
//+++++++++++++++++++++++ TdomTextDeclaration ++++++++++++++++++++++++++
constructor TdomTextDeclaration.Create(const AOwner: TdomDocument;
const Version,
EncDl: WideString);
begin
if not IsXmlEncName(EncDl)
then raise EInvalid_Character_Err.create('Invalid character error.');
if not (IsXmlVersionNum(Version) or (Version = ''))
then raise EInvalid_Character_Err.create('Invalid character error.');
inherited Create(AOwner);
FVersionNumber:= Version;
FEncodingDecl:= EncDl;
FNodeName:= '#text-declaration';
FNodeValue:= '';
FNodeType:= ntText_Declaration_Node;
FAllowedChildTypes:= [];
end;
function TdomTextDeclaration.GetVersionNumber: WideString;
begin
Result:= FVersionNumber;
end;
function TdomTextDeclaration.GetEncodingDecl: WideString;
begin
Result:= FEncodingDecl;
end;
procedure TdomTextDeclaration.SetEncodingDecl(const Value: WideSTring);
begin
if not (IsXmlEncName(Value) or (Value = ''))
then raise EInvalid_Character_Err.create('Invalid character error.');
FEncodingDecl:= Value;
end;
function TdomTextDeclaration.GetCode: WideString;
begin
Result:= '<?xml';
if VersionNumber <> ''
then Result:= concat(Result,WideString(' version="'),VersionNumber,WideString('"'));
Result:= concat(Result,WideString(' encoding="'),EncodingDecl,WideString('"'));
Result:= concat(Result,WideString('?>'));
end;
//++++++++++++++++++++++++ TdomDocumentFragment +++++++++++++++++++++++++++
constructor TdomDocumentFragment.Create(const AOwner: TdomDocument);
begin
inherited Create(AOwner);
FNodeName:= '#document-fragment';
FNodeValue:= '';
FNodeType:= ntDocument_Fragment_Node;
end;
procedure TdomDocumentFragment.SetNodeValue(const Value: WideString);
begin
raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
end;
//++++++++++++++++++++++++++++ TdomDocument +++++++++++++++++++++++++++++++
constructor TdomDocument.Create;
begin
inherited Create(self);
FNodeName:= '#document';
FNodeValue:= '';
FNodeType:= ntDocument_Node;
FFilename:= '';
FCreatedNodes:= TList.create;
FCreatedNodeIterators:= TList.create;
FCreatedTreeWalkers:= TList.create;
FCreatedElementsNodeLists:= TList.create;
FCreatedElementsNodeListNSs:= TList.create;
FAllowedChildTypes:= [ntElement_Node,
ntProcessing_Instruction_Node,
ntComment_Node,
ntDocument_Type_Node,
ntDocument_Fragment_Node,
ntXml_Declaration_Node];
end;
destructor TdomDocument.Destroy;
begin
clear;
FCreatedNodes.Free;
FCreatedNodeIterators.Free;
FCreatedTreeWalkers.Free;
FCreatedElementsNodeLists.free;
FCreatedElementsNodeListNSs.free;
inherited destroy;
end;
function TdomDocument.ExpandEntRef(const Node: TdomEntityReference): boolean;
var
oldChild,newChildNode: TdomNode;
newText: TdomText;
RefEntity: TdomEntity;
i: integer;
previousStatus: boolean;
begin
result:= false;
if Node.OwnerDocument <> Self
then raise EWrong_Document_Err.create('Wrong document error.');
if not (Node.NodeType in [ntEntity_Node,ntEntity_Reference_Node])
then raise ENot_Supported_Err.create('Not supported error.');
with Node do begin
while HasChildNodes do begin
FirstChild.FIsReadonly:= false;
oldChild:= RemoveChild(FirstChild);
FreeAllNodes(oldChild);
result:= true;
end;
if nodeName = 'lt' then begin
newText:= OwnerDocument.CreateText(#60);
AppendChild(newText);
result:= true;
end else
if nodeName = 'gt' then begin
newText:= OwnerDocument.CreateText(#62);
AppendChild(newText);
result:= true;
end else
if nodeName = 'amp' then begin
newText:= OwnerDocument.CreateText(#38);
AppendChild(newText);
result:= true;
end else
if nodeName = 'apos' then begin
newText:= OwnerDocument.CreateText(#39);
AppendChild(newText);
result:= true;
end else
if nodeName = 'quot' then begin
newText:= OwnerDocument.CreateText(#34);
AppendChild(newText);
result:= true;
end else
if assigned(Doctype) then begin
RefEntity:= TdomEntity(Doctype.entities.GetNamedItem(nodeName));
if assigned(RefEntity) then begin
if RefEntity.NotationName <> ''
then raise EIllegal_Entity_Reference_Err.Create('Illegal entity reference error.');
previousStatus:= Node.FIsReadonly;
Node.FIsReadonly:= false;
try
for i:= 0 to RefEntity.ChildNodes.Length-1 do begin
newChildNode:= RefEntity.ChildNodes.Item(i).CloneNode(true);
Node.AppendChild(newChildNode);
end; {for ...}
finally
Node.FIsReadonly:= previousStatus;
end;
result:= true;
end; {if ...}
end; {if ...}
node.makeChildrenReadonly;
end; {with ...}
end;
procedure TdomDocument.SetNodeValue(const Value: WideString);
begin
raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
end;
function TdomDocument.GetCode: WideString;
var
i: integer;
begin
Result:= '';
for i:= 0 to ChildNodes.Length -1 do
Result:= concat(Result,ChildNodes.item(i).Code,WideString(WideChar(10)));
end;
function TdomDocument.GetCodeAsString: String;
begin
if assigned(XmlDeclaration)
then XmlDeclaration.EncodingDecl:='UTF-8';
Result:=UTF16BEToUTF8Str(Code);
end;
function TdomDocument.GetCodeAsWideString: WideString;
begin
if assigned(XmlDeclaration)
then XmlDeclaration.EncodingDecl:= 'UTF-16';
Result:= concat(wideString(#$feff),Code);
end;
function TdomDocument.GetFilename: TFilename;
begin
Result:= FFilename;
end;
procedure TdomDocument.SetFilename(const Value: TFilename);
begin
FFilename:= Value;
end;
procedure TdomDocument.FindNewReferenceNodes(const NodeToRemove: TdomNode);
var
i: integer;
refNode, refRoot: TdomNode;
begin
for i:= 0 to FCreatedNodeIterators.count-1 do begin
refNode:= TdomNodeIterator(FCreatedNodeIterators[i]).FReferenceNode;
if (refNode = NodeToRemove) or refNode.IsAncestor(NodeToRemove) then begin
refRoot:= TdomNodeIterator(FCreatedNodeIterators[i]).root;
if NodeToRemove.IsAncestor(refRoot)
then TdomNodeIterator(FCreatedNodeIterators[i]).FindNewReferenceNode(NodeToRemove);
end;
end;
end;
procedure TdomDocument.clear;
var
i : integer;
begin
FNodeListing.clear;
for i := 0 to FCreatedNodes.Count - 1 do
TdomNode(FCreatedNodes[i]).free;
FCreatedNodes.Clear;
for i := 0 to FCreatedNodeIterators.Count - 1 do
TdomNodeIterator(FCreatedNodeIterators[i]).free;
FCreatedNodeIterators.Clear;
for i := 0 to FCreatedTreeWalkers.Count - 1 do
TdomTreeWalker(FCreatedTreeWalkers[i]).Free;
FCreatedTreeWalkers.Clear;
for i := 0 to FCreatedElementsNodeLists.Count - 1 do
TdomElementsNodeList(FCreatedElementsNodeLists[i]).free;
FCreatedElementsNodeLists.Clear;
for i := 0 to FCreatedElementsNodeListNSs.Count - 1 do
TdomElementsNodeListNS(FCreatedElementsNodeListNSs[i]).free;
FCreatedElementsNodeListNSs.Clear;
end;
procedure TdomDocument.ClearInvalidNodeIterators;
var
i: integer;
begin
for i:= 0 to FCreatedNodeIterators.count-1 do
if TdomNodeIterator(FCreatedNodeIterators[i]).FInvalid then begin
TdomNodeIterator(FCreatedNodeIterators[i]).free;
FCreatedNodeIterators[i]:= nil;
end;
FCreatedNodeIterators.pack;
FCreatedNodeIterators.Capacity:= FCreatedNodeIterators.Count;
end;
function TdomDocument.IsHTML: boolean;
{Returns 'True', if the document is HTML.}
var
Root: TdomElement;
NameStr: string;
begin
Result:= false;
Root:= GetDocumentElement;
if assigned(Root) then begin
NameStr:= WideCharToString(PWideChar(Root.TagName));
if CompareText(NameStr,'HTML') = 0 then result:= true;
end;
end;
function TdomDocument.DuplicateNode(Node: TdomNode): TdomNode;
{Creates a new node of the same type and properties than 'Node', except
that the new node has no parent and no child nodes.}
var
i: integer;
newChild: TdomNode;
begin
Result:= nil;
case Node.NodeType of
ntUnknown:
raise ENot_Supported_Err.create('Not supported error.');
ntElement_Node:
begin
Result:= CreateElement((Node as TdomElement).NodeName);
Result.FNodeValue:= FNodeValue;
{duplicate attributes:} {xxx nur specified duplizieren! xxx}
for i:= 0 to (Node as TdomElement).Attributes.Length-1 do begin
NewChild:= DuplicateNode((Node as TdomElement).Attributes.Item(i));
(Result as TdomElement).SetAttributeNode((NewChild as TdomAttr));
end;
end;
ntAttribute_Node:
begin
Result:= CreateAttribute((Node as TdomAttr).NodeName);
Result.FNodeValue:= FNodeValue;
{duplicate the text of the attribute node:}
for i:= 0 to Node.ChildNodes.Length-1 do begin
newChild:= DuplicateNode(Node.ChildNodes.Item(i));
Result.AppendChild(newChild);
end;
end;
ntText_Node:
Result:= CreateText((Node as TdomText).Data);
ntCDATA_Section_Node:
Result:= CreateCDATASection((Node as TdomCDATASection).Data);
ntEntity_Reference_Node:
begin
Result:= CreateEntityReference((Node as TdomEntityReference).NodeName);
Result.FNodeValue:= FNodeValue;
end;
ntParameter_Entity_Reference_Node:
begin
Result:= CreateParameterEntityReference((Node as TdomParameterEntityReference).NodeName);
Result.FNodeValue:= FNodeValue;
end;
ntEntity_Node:
Result:= CreateEntity((Node as TdomEntity).NodeName,
(Node as TdomEntity).PublicId,
(Node as TdomEntity).SystemId,
(Node as TdomEntity).NotationName);
ntParameter_Entity_Node:
Result:= CreateParameterEntity((Node as TdomParameterEntity).NodeName,
(Node as TdomParameterEntity).PublicId,
(Node as TdomParameterEntity).SystemId);
ntEntity_Declaration_Node:
Result:= CreateEntityDeclaration((Node as TdomEntityDeclaration).NodeName,
(Node as TdomEntityDeclaration).NodeValue,
(Node as TdomEntityDeclaration).PublicId,
(Node as TdomEntityDeclaration).SystemId,
(Node as TdomEntityDeclaration).NotationName);
ntParameter_Entity_Declaration_Node:
Result:= CreateParameterEntityDeclaration((Node as TdomParameterEntityDeclaration).NodeName,
(Node as TdomParameterEntityDeclaration).NodeValue,
(Node as TdomParameterEntityDeclaration).PublicId,
(Node as TdomParameterEntityDeclaration).SystemId);
ntProcessing_Instruction_Node:
Result:= CreateProcessingInstruction((Node as TdomProcessingInstruction).Target,
(Node as TdomProcessingInstruction).Data);
ntXml_Declaration_Node:
Result:= CreateXmlDeclaration((Node as TdomXmlDeclaration).VersionNumber,
(Node as TdomXmlDeclaration).EncodingDecl,
(Node as TdomXmlDeclaration).SdDecl);
ntComment_Node:
Result:= CreateComment((Node as TdomComment).Data);
ntConditional_Section_Node:
case (Node as TdomConditionalSection).Included.NodeType of
ntText_Node:
Result:= CreateConditionalSection(((Node as TdomConditionalSection).Included as TdomText).NodeValue);
ntParameter_Entity_Reference_Node:
Result:= CreateConditionalSection(((Node as TdomConditionalSection).Included as TdomParameterEntityReference).NodeName);
end;
ntDocument_Node:
Result:= TdomDocument.Create;
ntDocument_Type_Node:
Result:= CreateDocumentType((Node as TdomDocumentType).NodeName,
(Node as TdomDocumentType).PublicId,
(Node as TdomDocumentType).SystemId);
ntDocument_Fragment_Node:
Result:= CreateDocumentFragment;
ntNotation_Node:
Result:= CreateNotation((Node as TdomNotation).NodeName,
(Node as TdomNotation).PublicId,
(Node as TdomNotation).SystemId);
ntNotation_Declaration_Node:
Result:= CreateNotationDeclaration((Node as TdomNotationDeclaration).NodeName,
(Node as TdomNotationDeclaration).PublicId,
(Node as TdomNotationDeclaration).SystemId);
ntElement_Type_Declaration_Node:
Result:= CreateElementTypeDeclaration((Node as TdomElementTypeDeclaration).NodeName,
(Node as TdomElementTypeDeclaration).contentspec);
ntSequence_Particle_Node:
Result:= CreateSequenceParticle((Node as TdomSequenceParticle).Frequency);
ntPcdata_Choice_Particle_Node:
Result:= CreatePcdataChoiceParticle;
ntChoice_Particle_Node:
Result:= CreateChoiceParticle((Node as TdomChoiceParticle).Frequency);
ntElement_Particle_Node:
Result:= CreateElementParticle((Node as TdomChoiceParticle).NodeName,
(Node as TdomChoiceParticle).Frequency);
ntAttribute_List_Node: begin
Result:= CreateAttributeList((Node as TdomAttrList).NodeName);
{duplicate attribute definitions:}
for i:= 0 to (Node as TdomAttrList).AttributeDefinitions.Length-1 do begin
NewChild:= DuplicateNode((Node as TdomAttrList).AttributeDefinitions.Item(i));
(Result as TdomAttrList).SetAttributeDefinitionNode((NewChild as TdomAttrDefinition));
end;
end;
ntAttribute_Definition_Node: begin
Result:= CreateAttributeDefinition((Node as TdomAttrDefinition).NodeName,
(Node as TdomAttrDefinition).AttributeType,
(Node as TdomAttrDefinition).DefaultDeclaration,
(Node as TdomAttrDefinition).NodeValue);
{duplicate the children of the attribute definition node:}
for i:= 0 to Node.ChildNodes.Length-1 do begin
newChild:= DuplicateNode(Node.ChildNodes.Item(i));
Result.AppendChild(newChild);
end;
end;
ntNametoken_Node:
Result:= CreateNametoken((Node as TdomNametoken).NodeName);
ntText_Declaration_Node:
Result:= CreateTextDeclaration((Node as TdomTextDeclaration).VersionNumber,
(Node as TdomTextDeclaration).EncodingDecl);
ntExternal_Parsed_Entity_Node:
Result:= CreateExternalParsedEntity;
ntExternal_Parameter_Entity_Node:
Result:= CreateExternalParameterEntity;
ntExternal_Subset_Node:
Result:= CreateExternalSubset;
ntInternal_Subset_Node:
Result:= CreateInternalSubset;
end;
end;
procedure TdomDocument.InitDoc(const TagName: wideString);
begin
if not IsXmlName(TagName)
then raise EInvalid_Character_Err.create('Invalid character error.');
if assigned (DocumentElement)
then raise EHierarchy_Request_Err.create('Hierarchy request error.');
AppendChild(CreateElement(TagName));
end;
procedure TdomDocument.InitDocNS(const NamespaceURI,
QualifiedName: WideString);
var
prfx: WideString;
begin
if not IsXmlName(QualifiedName)
then raise EInvalid_Character_Err.create('Invalid character error.');
if not IsXmlQName(QualifiedName)
then raise ENamespace_Err.create('Namespace error.');
prfx:= XMLExtractPrefix(QualifiedName);
if ( ((prfx = 'xmlns') or (QualifiedName = 'xmlns'))
and not (NamespaceURI ='http://www.w3.org/2000/xmlns/') )
then raise ENamespace_Err.create('Namespace error.');
if (NamespaceURI = '') and (prfx <> '')
then raise ENamespace_Err.create('Namespace error.');
if (prfx = 'xml') and (NamespaceURI <> 'http://www.w3.org/XML/1998/namespace')
then raise ENamespace_Err.create('Namespace error.');
if assigned (DocumentElement)
then raise EHierarchy_Request_Err.create('Hierarchy request error.');
AppendChild(CreateElementNS(namespaceURI,qualifiedName));
end;
function TdomDocument.GetDoctype: TdomDocumentType;
var
Child: TdomNode;
begin
Result:= nil;
Child:= GetFirstChild;
while assigned(Child) do begin
if Child.NodeType = ntDocument_Type_Node then begin
Result:= (Child as TdomDocumentType);
break;
end;
Child:= Child.NextSibling;
end;
end;
function TdomDocument.GetDocumentElement: TdomElement;
var
Child: TdomNode;
begin
Result:= nil;
Child:= GetFirstChild;
while assigned(Child) do begin
if Child.NodeType = ntElement_Node then begin
Result:= (Child as TdomElement);
break;
end;
Child:= Child.NextSibling;
end;
end;
function TdomDocument.GetXmlDeclaration: TdomXmlDeclaration;
begin
Result:= nil;
if HasChildNodes then
if FirstChild.NodeType = ntXml_Declaration_Node
then Result:= (FirstChild as TdomXmlDeclaration);
end;
function TdomDocument.CreateElement(const TagName: WideString): TdomElement;
begin
Result:= TdomElement.Create(self,'',Tagname);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateElementNS(const NamespaceURI,
QualifiedName: WideString): TdomElement;
var
prfx: Widestring;
begin
if not IsXmlName(QualifiedName)
then raise EInvalid_Character_Err.create('Invalid character error.');
if not IsXmlQName(QualifiedName)
then raise ENamespace_Err.create('Namespace error.');
prfx:= XMLExtractPrefix(QualifiedName);
if ( ((prfx = 'xmlns') or (QualifiedName = 'xmlns'))
and not (NamespaceURI ='http://www.w3.org/2000/xmlns/') )
then raise ENamespace_Err.create('Namespace error.');
if (NamespaceURI = '') and (prfx <> '')
then raise ENamespace_Err.create('Namespace error.');
if (prfx = 'xml') and (NamespaceURI <> 'http://www.w3.org/XML/1998/namespace')
then raise ENamespace_Err.create('Namespace error.');
Result:= TdomElement.Create(self,NamespaceURI,QualifiedName);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateDocumentFragment: TdomDocumentFragment;
begin
Result:= TdomDocumentFragment.Create(self);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateText(const Data: WideString): TdomText;
begin
Result:= TdomText.Create(self);
Result.Data:= Data;
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateComment(const Data: WideString): TdomComment;
begin
Result:= TdomComment.Create(self);
Result.Data:= Data;
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateConditionalSection(const IncludeStmt: WideString): TdomConditionalSection;
begin
Result:= TdomConditionalSection.Create(self,IncludeStmt);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateCDATASection(const Data: WideString): TdomCDATASection;
begin
Result:= TdomCDATASection.Create(self);
Result.Data:= Data;
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateProcessingInstruction(const Targ,
Data : WideString): TdomProcessingInstruction;
begin
Result:= TdomProcessingInstruction.Create(self,Targ);
Result.Data:= Data;
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateXmlDeclaration(const Version,
EncDl,
SdDl: WideString): TdomXmlDeclaration;
begin
Result:= TdomXmlDeclaration.Create(self,Version,EncDl,SdDl);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateAttribute(const Name: WideString): TdomAttr;
begin
Result:= TdomAttr.Create(self,'',Name,true);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateAttributeNS(const NamespaceURI,
QualifiedName: WideString): TdomAttr;
var
prfx: WideString;
begin
if not IsXmlName(QualifiedName)
then raise EInvalid_Character_Err.create('Invalid character error.');
if not IsXmlQName(QualifiedName)
then raise ENamespace_Err.create('Namespace error.');
prfx:= XMLExtractPrefix(QualifiedName);
if ( ((prfx = 'xmlns') or (QualifiedName = 'xmlns'))
and not (NamespaceURI ='http://www.w3.org/2000/xmlns/') )
then raise ENamespace_Err.create('Namespace error.');
if (NamespaceURI = '') and (prfx <> '')
then raise ENamespace_Err.create('Namespace error.');
if (prfx = 'xml') and (NamespaceURI <> 'http://www.w3.org/XML/1998/namespace')
then raise ENamespace_Err.create('Namespace error.');
Result:= TdomAttr.Create(self,NamespaceURI,QualifiedName,true);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateEntityReference(const Name: WideString): TdomEntityReference;
begin
Result:= TdomEntityReference.Create(self,Name);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateParameterEntityReference(const Name: WideString): TdomParameterEntityReference;
begin
Result:= TdomParameterEntityReference.Create(self,Name);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateDocumentType(const Name,
PubId,
SysId: WideString): TdomDocumentType;
begin
Result:= TdomDocumentType.Create(self,Name,PubId,SysId);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateNotation(const Name,
PubId,
SysId: WideString): TdomNotation;
begin
Result:= TdomNotation.Create(self,Name,PubId,SysId);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateNotationDeclaration(const Name,
PubId,
SysId: WideString): TdomNotationDeclaration;
begin
Result:= TdomNotationDeclaration.Create(self,Name,PubId,SysId);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateEntity(const Name,
PubId,
SysId,
NotaName: WideString): TdomEntity;
begin
Result:= TdomEntity.Create(self,Name,PubId,SysId,NotaName);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateParameterEntity(const Name,
PubId,
SysId: WideString): TdomParameterEntity;
begin
Result:= TdomParameterEntity.Create(self,Name,PubId,SysId);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateEntityDeclaration(const Name,
EntityValue,
PubId,
SysId,
NotaName: WideString): TdomEntityDeclaration;
begin
Result:= TdomEntityDeclaration.Create(self,Name,EntityValue,PubId,SysId,NotaName);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateParameterEntityDeclaration(const Name,
EntityValue,
PubId,
SysId: WideString): TdomParameterEntityDeclaration;
begin
Result:= TdomParameterEntityDeclaration.Create(self,Name,EntityValue,PubId,SysId);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateElementTypeDeclaration(const Name: WideString;
const Contspec: TdomContentspecType): TdomElementTypeDeclaration;
begin
Result:= TdomElementTypeDeclaration.Create(self,Name,Contspec);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateSequenceParticle(const Freq: WideString): TdomSequenceParticle;
begin
Result:= TdomSequenceParticle.Create(self,Freq);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateChoiceParticle(const Freq: WideString): TdomChoiceParticle;
begin
Result:= TdomChoiceParticle.Create(self,Freq);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreatePcdataChoiceParticle: TdomPcdataChoiceParticle;
begin
Result:= TdomPcdataChoiceParticle.Create(self,'*');
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateElementParticle(const Name,
Freq: WideString): TdomElementParticle;
begin
Result:= TdomElementParticle.Create(self,Name,Freq);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateAttributeList(const Name: WideString): TdomAttrList;
begin
Result:= TdomAttrList.Create(self,Name);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateAttributeDefinition(const Name,
AttType,
DefaultDecl,
AttValue: WideString) : TdomAttrDefinition;
begin
Result:= TdomAttrDefinition.Create(self,Name,AttType,DefaultDecl,AttValue);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateNametoken(const Name: WideString): TdomNametoken;
begin
Result:= TdomNametoken.Create(self,Name);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateTextDeclaration(const Version,
EncDl: WideString): TdomTextDeclaration;
begin
Result:= TdomTextDeclaration.Create(self,Version,EncDl);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateExternalParsedEntity: TdomExternalParsedEntity;
begin
Result:= TdomExternalParsedEntity.Create(self);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateExternalParameterEntity: TdomExternalParameterEntity;
begin
Result:= TdomExternalParameterEntity.Create(self);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateExternalSubset: TdomExternalSubset;
begin
Result:= TdomExternalSubset.Create(self);
FCreatedNodes.add(Result);
end;
function TdomDocument.CreateInternalSubset: TdomInternalSubset;
begin
Result:= TdomInternalSubset.Create(self);
FCreatedNodes.add(Result);
end;
procedure TdomDocument.FreeAllNodes(const Node: TdomNode);
var
index: integer;
oldChild: TdomNode;
oldAttr: TdomAttr;
oldAttrDef: TdomAttrDefinition;
begin
if not assigned(Node) then exit;
if Node.OwnerDocument <> Self
then raise EWrong_Document_Err.create('Wrong document error.');
if Node = Self
then raise ENo_Modification_Allowed_Err.create('No modification allowed error.');
if assigned(Node.ParentNode)
then raise EInuse_Node_Err.create('Inuse node error.');
if Node.NodeType = ntAttribute_Node then
if assigned((Node as TdomAttr).OwnerElement)
then raise EInuse_Attribute_Err.create('Inuse attribute error.');
if Node.NodeType = ntAttribute_Definition_Node then
if assigned((Node as TdomAttrDefinition).ParentAttributeList)
then raise EInuse_AttributeDefinition_Err.create('Inuse attribute definition error.');
while node.HasChildNodes do begin
node.FirstChild.FIsReadonly:= false;
oldChild:= node.RemoveChild(node.FirstChild);
node.OwnerDocument.FreeAllNodes(oldChild);
end;
case Node.NodeType of
ntElement_Node:
while Node.Attributes.Length > 0 do begin
oldAttr:= (node.Attributes.item(0) as TdomAttr);
oldAttr.FIsReadonly:= false;
(Node as TdomElement).RemoveAttributeNode(oldAttr);
node.OwnerDocument.FreeAllNodes(oldAttr);
end;
ntAttribute_List_Node:
while (Node as TdomAttrList).AttributeDefinitions.Length > 0 do begin
oldAttrDef:= ((Node as TdomAttrList).AttributeDefinitions.item(0) as TdomAttrDefinition);
oldAttrDef.FIsReadonly:= false;
(Node as TdomAttrList).RemoveAttributeDefinitionNode(oldAttrDef);
node.OwnerDocument.FreeAllNodes(oldAttrDef);
end;
end; {case ...}
index:= FCreatedNodes.IndexOf(Node);
Node.free;
FCreatedNodes.Delete(index);
end;
procedure TdomDocument.FreeTreeWalker(const TreeWalker: TdomTreeWalker);
var
TreeWalkerIndex: integer;
begin
if not assigned(TreeWalker) then exit;
TreeWalkerIndex:= FCreatedTreeWalkers.IndexOf(TreeWalker);
if TreeWalkerIndex = -1
then raise EWrong_Document_Err.create('Wrong document error.');
TdomTreeWalker(FCreatedTreeWalkers[TreeWalkerIndex]).free;
FCreatedTreeWalkers.Delete(TreeWalkerIndex);
end;
function TdomDocument.GetElementsById(const elementId: WideString): TdomElement;
begin
result:= nil;
end;
function TdomDocument.GetElementsByTagName(const TagName: WideString): TdomNodeList;
var
i: integer;
begin
for i:= 0 to FCreatedElementsNodeLists.Count - 1 do
if TdomElementsNodeList(FCreatedElementsNodeLists[i]).FQueryName = TagName
then begin Result:= TdomElementsNodeList(FCreatedElementsNodeLists[i]); exit; end;
Result:= TdomElementsNodeList.Create(TagName,self);
FCreatedElementsNodeLists.add(Result);
end;
function TdomDocument.GetElementsByTagNameNS(const namespaceURI,
localName: WideString): TdomNodeList;
var
i: integer;
nl: TdomElementsNodeListNS;
begin
for i:= 0 to FCreatedElementsNodeListNSs.Count - 1 do begin
nl:= TdomElementsNodeListNS(FCreatedElementsNodeListNSs[i]);
if (nl.FQueryNamespaceURI = namespaceURI) and (nl.FQueryLocalName = localName)
then begin Result:= nl; exit; end;
end;
Result:= TdomElementsNodeListNS.Create(namespaceURI,localName,self);
FCreatedElementsNodeListNSs.add(Result);
end;
function TdomDocument.ImportNode(const importedNode: TdomNode;
const deep: boolean): TdomNode;
var
newChildNode: TdomNode;
i: integer;
begin
if (importedNode.NodeType in [ntDocument_Node,ntDocument_Type_Node])
then raise ENot_Supported_Err.create('Not supported error.');
Result:= DuplicateNode(importedNode);
if deep then for i:= 0 to importedNode.ChildNodes.Length-1 do
begin
newChildNode:= ImportNode(importedNode.ChildNodes.Item(i),true);
Result.AppendChild(newChildNode);
end;
end;
function TdomDocument.InsertBefore(const newChild,
refChild: TdomNode): TdomNode;
begin
case newChild.NodeType of
ntElement_Node: begin
if assigned(DocType) then begin
if DocType.NodeName <> newChild.NodeName
then raise EInvalid_Character_Err.create('Invalid character error.');
if ChildNodes.IndexOf(DocType) >= ChildNodes.IndexOf(refChild)
then raise EHierarchy_Request_Err.create('Hierarchy request error.');
end;
if assigned(DocumentElement)
then raise EHierarchy_Request_Err.create('Hierarchy request error.');
Result:= inherited InsertBefore(newChild,refChild);
end;
ntDocument_Type_Node: begin
if assigned(DocumentElement) then begin
if DocumentElement.NodeName <> newChild.NodeName
then raise EInvalid_Character_Err.create('Invalid character error.');
if ChildNodes.IndexOf(DocumentElement) < ChildNodes.IndexOf(refChild)
then raise EHierarchy_Request_Err.create('Hierarchy request error.');
end;
if assigned(DocType)
then raise EHierarchy_Request_Err.create('Hierarchy request error.');
Result:= inherited InsertBefore(newChild,refChild);
end;
ntXml_Declaration_Node:
if (FirstChild = refChild) and (refChild.nodeType <> ntXml_Declaration_Node)
then Result:= inherited InsertBefore(newChild,refChild)
else raise EHierarchy_Request_Err.create('Hierarchy request error.');
ntProcessing_Instruction_Node,ntComment_Node,ntDocument_Fragment_Node:
Result:= inherited InsertBefore(newChild,refChild);
else
raise EHierarchy_Request_Err.create('Hierarchy request error.');
end;
end;
function TdomDocument.ReplaceChild(const newChild,
oldChild: TdomNode): TdomNode;
begin
case newChild.NodeType of
ntElement_Node: begin
if assigned(DocumentElement) and (DocumentElement <> oldChild)
then raise EHierarchy_Request_Err.create('Hierarchy request error.');
if assigned(DocType) then
if DocType.NodeName <> newChild.NodeName
then raise EInvalid_Character_Err.create('Invalid character error.');
Result:= inherited ReplaceChild(newChild,oldChild);
end;
ntDocument_Type_Node: begin
if assigned(DocType) and (DocType <> oldChild)
then raise EHierarchy_Request_Err.create('Hierarchy request error.');
if assigned(DocumentElement)
then if DocumentElement.NodeName <> newChild.NodeName
then raise EInvalid_Character_Err.create('Invalid character error.');
Result:= inherited ReplaceChild(newChild,oldChild);
end;
ntXml_Declaration_Node:
if (FirstChild = oldChild)
then Result:= inherited ReplaceChild(newChild,oldChild)
else raise EHierarchy_Request_Err.create('Hierarchy request error.');
ntProcessing_Instruction_Node,ntComment_Node,
ntDocument_Fragment_Node:
Result:= inherited ReplaceChild(newChild,oldChild);
else
raise EHierarchy_Request_Err.create('Hierarchy request error.');
end;
end;
function TdomDocument.AppendChild(const newChild: TdomNode): TdomNode;
begin
case newChild.NodeType of
ntElement_Node: begin
if assigned(DocumentElement)
then raise EHierarchy_Request_Err.create('Hierarchy request error.');
Result:= inherited AppendChild(newChild);
end;
ntDocument_Type_Node: begin
if assigned(Doctype) or assigned(DocumentElement)
then raise EHierarchy_Request_Err.create('Hierarchy request error.');
Result:= inherited AppendChild(newChild);
end;
ntXml_Declaration_Node:
if HasChildNodes
then raise EHierarchy_Request_Err.create('Hierarchy request error.')
else Result:= inherited AppendChild(newChild);
ntProcessing_Instruction_Node,ntComment_Node,
ntDocument_Fragment_Node:
Result:= inherited AppendChild(newChild);
else
raise EHierarchy_Request_Err.create('Hierarchy request error.');
end;
end;
function TdomDocument.CreateNodeIterator(const root: TdomNode;
whatToShow: TdomWhatToShow;
nodeFilter: TdomNodeFilter;
entityReferenceExpansion: boolean): TdomNodeIterator;
begin
Result:= TdomNodeIterator.Create(root,whatToShow,nodeFilter,entityReferenceExpansion);
FCreatedNodeIterators.add(Result);
end;
function TdomDocument.CreateTreeWalker(const root: TdomNode;
whatToShow: TdomWhatToShow;
nodeFilter: TdomNodeFilter;
entityReferenceExpansion: boolean): TdomTreeWalker;
begin;
Result:= TdomTreeWalker.Create(root,whatToShow,nodeFilter,entityReferenceExpansion);
FCreatedTreeWalkers.add(Result);
end;
// +++++++++++++++++++++++++++ TXmlSourceCode ++++++++++++++++++++++++++
procedure TXmlSourceCode.calculatePieceOffset(const startItem: integer);
var
os, i: integer;
begin
if (startItem < count) and (startItem >= 0) then begin
if startItem = 0
then os:= 0
else begin
if not assigned(Items[startItem-1])
then begin
pack;
exit;
end else with TXmlSourceCodePiece(Items[startItem-1]) do
os:= FOffset + length(FText);
end;
for i:= startItem to count -1 do
if not assigned(Items[i])
then begin
pack;
exit;
end else with TXmlSourceCodePiece(Items[i]) do begin
FOffset:= os;
os:= os + length(FText);
end;
end; {if ...}
end;
function TXmlSourceCode.getNameOfFirstTag: wideString;
var
i,j,k: integer;
begin
Result:= '';
for i:= 0 to count -1 do
if assigned(Items[i]) then
with TXmlSourceCodePiece(Items[i]) do
if (pieceType = xmlStartTag) or (pieceType = xmlEmptyElementTag) then begin
if pieceType = xmlStartTag
then k:= length(text)-1
else k:= length(text)-2;
j:= 1;
while j < k do begin
inc(j);
if IsXmlWhiteSpace(text[j]) then break;
Result:= concat(Result,WideString(WideChar(text[j])));
end;
exit;
end;
end;
function TXmlSourceCode.Add(Item: Pointer): Integer;
begin
if assigned(Item) then begin
if not assigned(TXmlSourceCodePiece(Item).FOwner)
then TXmlSourceCodePiece(Item).FOwner:= self
else Error('Inuse source code piece error.',-1);
end else Error('Item not assigned error.',-1);
Result:= inherited Add(Item);
calculatePieceOffset(Result);
end;
procedure TXmlSourceCode.Clear;
var
i: integer;
begin
for i:= 0 to count -1 do
if assigned(Items[i]) then
with TXmlSourceCodePiece(Items[i]) do begin
FOffset:= 0;
FOwner:= nil;
end;
inherited clear;
end;
procedure TXmlSourceCode.ClearAndFree;
var
i: integer;
begin
for i:= 0 to count -1 do
if assigned(Items[i]) then TXmlSourceCodePiece(Items[i]).free;
inherited clear;
end;
procedure TXmlSourceCode.Delete(Index: Integer);
begin
if assigned(Items[index]) then
with TXmlSourceCodePiece(Items[index]) do begin
FOffset:= 0;
FOwner:= nil;
end;
inherited delete(index);
calculatePieceOffset(Index);
end;
procedure TXmlSourceCode.Exchange(Index1, Index2: Integer);
var
nr: integer;
begin
nr:= MinIntValue([Index1,Index2]);
inherited Exchange(Index1,Index2);
calculatePieceOffset(nr);
end;
function TXmlSourceCode.GetPieceAtPos(pos: integer): TXmlSourceCodePiece;
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// xxx This search is not optimized. Anybody out there, who xxx
// xxx wants to do it? Please email me: service@philo.de. xxx
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
var
i: integer;
begin
Result:= nil;
if pos < 1 then exit;
for i:= 0 to count -1 do
if not assigned(Items[i]) then begin
pack;
Result:= GetPieceAtPos(pos);
end else with TXmlSourceCodePiece(Items[i]) do begin
if (FOffset + length(FText)) >= pos then begin
Result:= TXmlSourceCodePiece(Items[i]);
exit;
end;
end;
end;
procedure TXmlSourceCode.Insert(Index: Integer; Item: Pointer);
begin
if assigned(Item) then begin
if not assigned(TXmlSourceCodePiece(Item).FOwner)
then TXmlSourceCodePiece(Item).FOwner:= self
else Error('Inuse source code piece error.',-1);
end else Error('Item not assigned error.',-1);
inherited Insert(Index,item);
calculatePieceOffset(index);
end;
procedure TXmlSourceCode.Move(CurIndex, NewIndex: Integer);
var
nr: integer;
begin
nr:= MinIntValue([CurIndex,NewIndex]);
inherited Move(CurIndex, NewIndex);
calculatePieceOffset(nr);
end;
procedure TXmlSourceCode.Pack;
begin
inherited pack;
calculatePieceOffset(0);
end;
function TXmlSourceCode.Remove(Item: Pointer): Integer;
var
nr: integer;
begin
nr:= IndexOf(Item);
result:= inherited Remove(Item);
if assigned(Items[nr]) then
with TXmlSourceCodePiece(Item) do begin
FOffset:= 0;
FOwner:= nil;
end;
calculatePieceOffset(nr);
end;
procedure TXmlSourceCode.Sort(Compare: TListSortCompare);
begin
inherited Sort(Compare);
calculatePieceOffset(0);
end;
// ++++++++++++++++++++++++ TXmlSourceCodePiece ++++++++++++++++++++++++
constructor TXmlSourceCodePiece.Create(const pt: TdomPieceType);
begin
FPieceType:= pt;
Ftext:= '';
FOffset:= 0;
FOwner:= nil;
end;
// ++++++++++++++++++++++++++ TXmlInputSource ++++++++++++++++++++++++++
constructor TXmlInputSource.create(const Stream: TStream;
const PublicId,
SystemId: wideString;
defaultEncoding : TdomEncodingType);
var
Str1: WideChar;
begin
FStream:= Stream;
FPublicId:= PublicId;
FSystemId:= SystemId;
// Determine the encoding type:
FStream.seek(0,soFromBeginning);
FStream.ReadBuffer(Str1,2);
if ord(str1) = $feff then begin
FEncoding:= etUTF16BE
end else begin
if ord(str1) = $fffe then begin
FEncoding:= etUTF16LE
end else begin
//FEncoding:= etUTF8;
FEncoding:=defaultEncoding; // modified by hyl
FStream.seek(0,soFromBeginning);
end;
end;
end;
// ++++++++++++++++++++++++++ TXmlParserError ++++++++++++++++++++++++++
constructor TXmlParserError.Create(const ErrorType: ShortString;
const StartLine,
EndLine: integer;
const SourceCodeText: WideString;
const lang: TXmlParserLanguage);
begin
FErrorType:= ErrorType;
FStartLine:= StartLine;
FEndLine:= EndLine;
FSourceCodeText:= SourceCodeText;
FLanguage:= lang;
inherited create;
end;
function TXmlParserError.GetErrorStr: WideString;
var
ErrorStr1,ErrorStr,XmlStrDefault: string;
XmlStrInvalidElementName,XmlStrDoubleRootElement,
XmlStrRootNotFound,XmlStrDoubleDoctype,
XmlStrInvalidAttributeName,XmlStrInvalidAttributeValue,
XmlStrDoubleAttributeName,XmlStrInvalidEntityName,XmlStrInvalidProcessingInstruction,
XmlStrInvalidXmlDeclaration,XmlStrInvalidCharRef,
XmlStrMissingQuotationmarks,XmlStrMissingEqualitySign,
XmlStrDoubleEqualitySign,XmlStrMissingWhiteSpace,
XmlStrMissingStartTag,XmlStrInvalidEndTag,
XmlStrInvalidCharacter,XmlStrNotInRoot,
XmlStrInvalidDoctype,XmlStrWrongOrder,
XmlStrInvalidEntityDeclaration,XmlStrInvalidElementDeclaration,
XmlStrInvalidAttributeDeclaration,XmlStrInvalidNotationDeclaration,
XmlStrInvalidConditionalSection,xmlStrInvalidTextDeclaration,
XmlStrDoubleEntityDeclWarning,XmlStrDoubleNotationDeclWarning: string;
XmlStrError1,XmlStrError2,XmlStrFatalError1,XmlStrFatalError2: string;
begin
Result:= '';
ErrorStr:= '';
if FLanguage = de then begin
XmlStrDefault:= XmlStrErrorDefaultDe;
XmlStrError1:= XmlStrError1De;
XmlStrError2:= XmlStrError2De;
XmlStrFatalError1:= XmlStrFatalError1De;
XmlStrFatalError2:= XmlStrFatalError2De;
XmlStrInvalidElementName:= XmlStrInvalidElementNameDe;
XmlStrDoubleRootElement:= XmlStrDoubleRootElementDe;
XmlStrRootNotFound:= XmlStrRootNotFoundDe;
XmlStrDoubleDoctype:= XmlStrDoubleDoctypeDe;
XmlStrInvalidAttributeName:= XmlStrInvalidAttributeNameDe;
XmlStrInvalidAttributeValue:= XmlStrInvalidAttributeValueDe;
XmlStrDoubleAttributeName:= XmlStrDoubleAttributeNameDe;
XmlStrInvalidEntityName:= XmlStrInvalidEntityNameDe;
XmlStrInvalidProcessingInstruction:= XmlStrInvalidProcessingInstructionDe;
XmlStrInvalidXmlDeclaration:= XmlStrInvalidXmlDeclarationDe;
XmlStrInvalidCharRef:= XmlStrInvalidCharRefDe;
XmlStrMissingQuotationmarks:= XmlStrMissingQuotationmarksDe;
XmlStrMissingEqualitySign:= XmlStrMissingEqualitySignDe;
XmlStrDoubleEqualitySign:= XmlStrDoubleEqualitySignDe;
XmlStrMissingWhiteSpace:= XmlStrMissingWhiteSpaceDe;
XmlStrMissingStartTag:= XmlStrMissingStartTagDe;
XmlStrInvalidEndTag:= XmlStrInvalidEndTagDe;
XmlStrInvalidCharacter:= XmlStrInvalidCharacterDe;
XmlStrNotInRoot:= XmlStrNotInRootDe;
XmlStrInvalidDoctype:= XmlStrInvalidDoctypeDe;
XmlStrWrongOrder:= XmlStrWrongOrderDe;
XmlStrInvalidEntityDeclaration:= XmlStrInvalidEntityDeclarationDe;
XmlStrInvalidElementDeclaration:= XmlStrInvalidElementDeclarationDe;
XmlStrInvalidAttributeDeclaration:= XmlStrInvalidAttributeDeclarationDe;
XmlStrInvalidNotationDeclaration:= XmlStrInvalidNotationDeclarationDe;
XmlStrInvalidConditionalSection:= XmlStrInvalidConditionalSectionDe;
XmlStrInvalidTextDeclaration:= XmlStrInvalidTextDeclarationDe;
XmlStrDoubleEntityDeclWarning:= XmlStrDoubleEntityDeclWarningDe;
XmlStrDoubleNotationDeclWarning:= XmlStrDoubleNotationDeclWarningDe;
end else begin
XmlStrDefault:= XmlStrErrorDefaultEn;
XmlStrError1:= XmlStrError1En;
XmlStrError2:= XmlStrError2En;
XmlStrFatalError1:= XmlStrFatalError1En;
XmlStrFatalError2:= XmlStrFatalError2En;
XmlStrInvalidElementName:= XmlStrInvalidElementNameEn;
XmlStrDoubleRootElement:= XmlStrDoubleRootElementEn;
XmlStrRootNotFound:= XmlStrRootNotFoundEn;
XmlStrDoubleDoctype:= XmlStrDoubleDoctypeEn;
XmlStrInvalidAttributeName:= XmlStrInvalidAttributeNameEn;
XmlStrInvalidAttributeValue:= XmlStrInvalidAttributeValueEn;
XmlStrDoubleAttributeName:= XmlStrDoubleAttributeNameEn;
XmlStrInvalidEntityName:= XmlStrInvalidEntityNameEn;
XmlStrInvalidProcessingInstruction:= XmlStrInvalidProcessingInstructionEn;
XmlStrInvalidXmlDeclaration:= XmlStrInvalidXmlDeclarationEn;
XmlStrInvalidCharRef:= XmlStrInvalidCharRefEn;
XmlStrMissingQuotationmarks:= XmlStrMissingQuotationmarksEn;
XmlStrMissingEqualitySign:= XmlStrMissingEqualitySignEn;
XmlStrDoubleEqualitySign:= XmlStrDoubleEqualitySignEn;
XmlStrMissingWhiteSpace:= XmlStrMissingWhiteSpaceEn;
XmlStrMissingStartTag:= XmlStrMissingStartTagEn;
XmlStrInvalidEndTag:= XmlStrInvalidEndTagEn;
XmlStrInvalidCharacter:= XmlStrInvalidCharacterEn;
XmlStrNotInRoot:= XmlStrNotInRootEn;
XmlStrInvalidDoctype:= XmlStrInvalidDoctypeEn;
XmlStrWrongOrder:= XmlStrWrongOrderEn;
XmlStrInvalidEntityDeclaration:= XmlStrInvalidEntityDeclarationEn;
XmlStrInvalidElementDeclaration:= XmlStrInvalidElementDeclarationEn;
XmlStrInvalidAttributeDeclaration:= XmlStrInvalidAttributeDeclarationEn;
XmlStrInvalidNotationDeclaration:= XmlStrInvalidNotationDeclarationEn;
XmlStrInvalidConditionalSection:= XmlStrInvalidConditionalSectionEn;
XmlStrInvalidTextDeclaration:= XmlStrInvalidTextDeclarationEn;
XmlStrDoubleEntityDeclWarning:= XmlStrDoubleEntityDeclWarningEn;
XmlStrDoubleNotationDeclWarning:= XmlStrDoubleNotationDeclWarningEn;
end;
if FErrorType = 'EParserRootNotFound_Err' {Gültigkeitsbeschränkung verletzt}
then begin
if FStartLine = FEndLine
then FmtStr(ErrorStr1,XmlStrError1,[FStartLine])
else FmtStr(ErrorStr1,XmlStrError2,[FStartLine,FEndLine]);
end else begin{Wohlgeformtheitsbeschränkung verletzt}
if FStartLine = FEndLine
then FmtStr(ErrorStr1,XmlStrFatalError1,[FStartLine])
else FmtStr(ErrorStr1,XmlStrFatalError2,[FStartLine,FEndLine]);
end;
ErrorStr:= concat(ErrorStr1,' -- ',XmlStrDefault);
if FErrorType = 'EParserInvalidElementName_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrInvalidElementName);
if FErrorType = 'EParserDoubleRootElement_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrDoubleRootElement);
if FErrorType = 'EParserRootNotFound_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrRootNotFound);
if FErrorType = 'EParserDoubleDoctype_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrDoubleDoctype);
if FErrorType = 'EParserInvalidAttributeName_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrInvalidAttributeName);
if FErrorType = 'EParserInvalidAttributeValue_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrInvalidAttributeValue);
if FErrorType = 'EParserDoubleAttributeName_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrDoubleAttributeName);
if FErrorType = 'EParserInvalidEntityName_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrInvalidEntityName);
if FErrorType = 'EParserInvalidProcessingInstruction_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrInvalidProcessingInstruction);
if FErrorType = 'EParserInvalidXmlDeclaration_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrInvalidXmlDeclaration);
if FErrorType = 'EParserInvalidCharRef_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrInvalidCharRef);
if FErrorType = 'EParserMissingQuotationMark_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrMissingQuotationmarks);
if FErrorType = 'EParserMissingEqualitySign_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrMissingEqualitySign);
if FErrorType = 'EParserDoubleEqualitySign_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrDoubleEqualitySign);
if FErrorType = 'EParserMissingWhiteSpace_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrMissingWhiteSpace);
if FErrorType = 'EParserMissingStartTag_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrMissingStartTag);
if FErrorType = 'EParserInvalidEndTag_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrInvalidEndTag);
if FErrorType = 'EParserInvalidCharacter_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrInvalidCharacter);
if FErrorType = 'EParserNotInRoot_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrNotInRoot);
if FErrorType = 'EParserInvalidDoctype_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrInvalidDoctype);
if FErrorType = 'EParserWrongOrder_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrWrongOrder);
if FErrorType = 'EParserInvalidEntityDeclaration_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrInvalidEntityDeclaration);
if FErrorType = 'EParserInvalidElementDeclaration_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrInvalidElementDeclaration);
if FErrorType = 'EParserInvalidAttributeDeclaration_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrInvalidAttributeDeclaration);
if FErrorType = 'EParserInvalidNotationDeclaration_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrInvalidNotationDeclaration);
if FErrorType = 'EParserInvalidConditionalSection_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrInvalidConditionalSection);
if FErrorType = 'EParserInvalidTextDeclaration_Err'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrInvalidTextDeclaration);
if FErrorType = 'Double_Entity_Decl_Warning'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrDoubleEntityDeclWarning);
if FErrorType = 'Double_Notation_Decl_Warning'
then ErrorStr:= concat(ErrorStr1,' -- ',XmlStrDoubleNotationDeclWarning);
if FSourceCodeText = ''
then Result:= concat(ErrorStr,'.')
else Result:= concat(ErrorStr,': ',FSourceCodeText);
end;
function TXmlParserError.GetErrorType: ShortString;
begin
Result:= FErrorType;
end;
function TXmlParserError.GetStartLine: integer;
begin
Result:= FStartLine;
end;
function TXmlParserError.GetEndLine: integer;
begin
Result:= FEndLine;
end;
// ++++++++++++++++++++++++++ TXmlMemoryStream +++++++++++++++++++++++++
procedure TXmlMemoryStream.SetPointer(Ptr: Pointer; Size: Longint);
begin
inherited SetPointer(Ptr,Size);
end;
// +++++++++++++++++++++++++++ TCustomParser ++++++++++++++++++++++++++
constructor TCustomParser.Create(aOwner: TComponent);
begin
Inherited Create(aOwner);
FLineNumber:= 0;
FErrorList:= TList.create;
FErrorStrings:= TStringList.create;
FLanguage:= en;
FIntSubset:= '';
FDOMImpl:= nil;
FDocumentSC:= nil;
FUseSpecifiedDocumentSC:= true;
FDefaultEncoding:=etMBCS;
end;
destructor TCustomParser.Destroy;
begin
ClearErrorList;
FErrorList.free;
FErrorStrings.free;
inherited Destroy;
end;
procedure TCustomParser.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent,Operation);
if (Operation = opRemove) and (AComponent = FDomImpl)
then FDomImpl:= nil;
end;
procedure TCustomParser.SetDomImpl(const impl: TDomImplementation);
begin
FDOMImpl:= impl;
if impl <> nil then impl.FreeNotification(Self);
end;
function TCustomParser.GetDomImpl: TDomImplementation;
begin
Result:= FDOMImpl;
end;
procedure TCustomParser.SetLanguage(const Lang: TXmlParserLanguage);
begin
FLanguage:= Lang;
end;
function TCustomParser.GetLanguage: TXmlParserLanguage;
begin
Result:= FLanguage;
end;
function TCustomParser.GetErrorList: TList;
begin
Result:= FErrorList;
end;
function TCustomParser.GetErrorStrings: TStringList;
var
i: integer;
begin
FErrorStrings.clear;
for i:= 0 to FErrorList.count -1 do
FErrorStrings.Add(TXmlParserError(FErrorList[i]).ErrorStr);
Result:= FErrorStrings;
end;
procedure TCustomParser.ClearErrorList;
{Löscht alle Objekte von FErrorList.}
var
i: integer;
begin
for i := 0 to (FErrorList.Count - 1) do
TdomNode(FErrorList[i]).Free;
FErrorList.Clear;
end;
function TCustomParser.NormalizeLineBreaks(const source :WideString): WideString;
const
CR: WideChar = #13;
LF: WideChar = #10;
CRLF: WideString = #13#10;
var
nPos: integer;
begin
Result:= source;
// CR+LF --> LF
repeat
nPos := Pos(CRLF, Result);
if nPos > 0 then
Delete(Result, nPos, 1);
until nPos = 0;
// CR --> LF
repeat
nPos := Pos(CR, Result);
if nPos > 0 then
Result[nPos] := LF;
until nPos = 0;
end;
procedure TCustomParser.XMLAnalyseAttrSequence(const Source: WideString;
const Element: TdomElement;
const FirstLineNumber,
LastLineNumber: integer);
// 'Source': The attribute sequence to be analyzed.
// 'Element': The TdomElement node to which the attributes as
// TdomAttr nodes will be added.
const
SingleQuote: WideChar = #39; // code of '
DoubleQuote: WideChar = #34; // code of "
var
i,j : integer;
name,value,v,text,CharacRef: WideString;
QuoteType: WideChar;
IsEntity,EqualSign,WhiteSpace: boolean;
Attri: TdomAttr;
begin
WhiteSpace:= true;
QuoteType:= 'x';
i:= 0;
while (i<length(Source)) do
begin
if not WhiteSpace
then raise EParserMissingWhiteSpace_Err.create('Missing white-space error.');
if i < length(Source) then begin
Name:= '';
while (i<length(Source)) do
begin
if IsXmlWhiteSpace(Source[i+1]) or (Source[i+1] = '=') then break;
inc(i);
Name:= concat(Name,WideString(Source[i]));
end;
EqualSign:= false;
while (i<length(Source)) do
begin
inc(i);
if not (IsXmlWhiteSpace(Source[i]) or (Source[i] = '=')) then
begin
if ((Source[i] = SingleQuote) or (Source[i] = DoubleQuote)) then begin
if not EqualSign
then raise EParserMissingEqualitySign_Err.create('Missing equality sign error.');
QuoteType:= Source[i];
break;
end else raise EParserMissingQuotationMark_Err.create('Missing quotation mark error.');
end else
if Source[i] = '=' then
if EqualSign
then raise EParserDoubleEqualitySign_Err.create('Double equality sign error.')
else EqualSign:= true;
end;
Value:='';
while (i<length(Source)) do
begin
inc(i);
if Source[i] = QuoteType then break;
Value:= concat(Value,WideString(Source[i]));
end;
{Ungültiger Attributname?:}
if not IsXmlName(Name)
then raise EParserInvalidAttributeName_Err.create('Invalid attribute name error.');
{Fehlendes Schlußzeichen?:}
if Source[i] <> QuoteType
then raise EParserMissingQuotationMark_Err.create('Missing quotation mark error.');
{Attributname zweimal vergeben?:}
if assigned(Element.Attributes.GetNamedItem(Name))
then raise EParserDoubleAttributeName_Err.create('Double attribute name error.');
if pos('&',Value) = 0 then begin
{Ungültiger Attributwert?:}
if not IsXmlCharData(Value)
then raise EParserInvalidAttributeValue_Err.create('Invalid attribute value error.');
Element.SetAttribute(Name,Value)
end else begin
Attri:= Element.OwnerDocument.CreateAttribute(Name);
Element.SetAttributeNode(Attri);
IsEntity:= false;
text:= '';
for j:= 1 to Length(value) do begin
if IsEntity then begin
if Value[j] = ';' then begin
if text[1] = '#' then begin {CharRef}
try
CharacRef:= concat(WideString('&'),text,WideString(';'));
v:= XmlCharRefToStr(CharacRef);
if Attri.LastChild is TdomText
then (Attri.LastChild as TdomText).appendData(v)
else Attri.AppendChild(Element.OwnerDocument.CreateText(v));
except
on EConvertError do
raise EParserInvalidCharRef_Err.create('Invalid character reference error.');
end; {try}
end else begin
if not IsXmlName(text)
then raise EParserInvalidAttributeValue_Err.create('Invalid attribute value error.');
Attri.AppendChild(Element.OwnerDocument.CreateEntityReference(text));
end;
text:= '';
IsEntity:= false;
end else Text:= concat(text,WideString(Value[j]));
end else begin
if Value[j] = '&' then begin
if text <> '' then begin
{Ungültiger Attributwert?:}
if not IsXmlCharData(text)
then raise EParserInvalidAttributeValue_Err.create('Invalid attribute value error.');
Attri.AppendChild(Element.OwnerDocument.CreateText(text));
end;
text:= '';
IsEntity:= true;
end else Text:= concat(text,WideString(Value[j]));
end; {if ...}
end; {for ...}
{Ungültiger Attributwert?:}
if IsEntity
then raise EParserInvalidAttributeValue_Err.create('Invalid attribute value error.');
if text <> '' then Attri.AppendChild(Element.OwnerDocument.CreateText(text));
end; {if ...}
end; {if i < length(Source)}
{White-space?}
WhiteSpace:= false;
while (i<length(Source)) do
begin
inc(i);
if not IsXmlWhiteSpace(Source[i])
then begin dec(i); break; end
else WhiteSpace:= true;
end;
end; {while (i<length(Source))}
end;
function TCustomParser.WriteXmlDeclaration(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomXmlDeclaration;
var
version,encoding,standalone,TargetName,AttribSequence: Widestring;
VersionAttr,EncodingAttr,StandaloneAttr: TdomAttr;
VersionIndex,EncodingIndex,StandaloneIndex: integer;
NewElement: TdomElement;
begin
Result:= nil;
XMLAnalyseTag(content,TargetName,AttribSequence);
if TargetName <> 'xml'
then raise EParserInvalidXmlDeclaration_Err.create('Invalid xml-declaration error.');
if RefNode.HasChildNodes
then raise EParserWrongOrder_Err.create('Wrong order error.');
NewElement:= RefNode.OwnerDocument.CreateElement('dummy');
try
XMLAnalyseAttrSequence(AttribSequence,NewElement,FirstLineNumber,LastLineNumber);
with NewElement.Attributes do begin
VersionAttr:= (GetNamedItem('version') as TdomAttr);
EncodingAttr:= (GetNamedItem('encoding') as TdomAttr);
StandaloneAttr:= (GetNamedItem('standalone') as TdomAttr);
VersionIndex:= GetNamedIndex('version');
EncodingIndex:= GetNamedIndex('encoding');
StandaloneIndex:= GetNamedIndex('standalone');
if (VersionIndex <> 0)
or (EncodingIndex > 1)
or ((Length > 1) and (EncodingIndex = -1) and (StandaloneIndex = -1))
or ((Length > 2) and ((EncodingIndex = -1) or (StandaloneIndex = -1)))
or (Length > 3)
or (not assigned(VersionAttr))
then raise EParserInvalidXmlDeclaration_Err.create('Invalid xml-declaration error.');
end; {with ...}
version:= VersionAttr.Value;
if assigned(EncodingAttr)
then encoding:= EncodingAttr.Value
else encoding:= '';
if assigned(standaloneAttr)
then standalone:= StandaloneAttr.Value
else Standalone:= '';
try
Result:= RefNode.OwnerDocument.CreateXmlDeclaration(version,encoding,Standalone);
try
RefNode.AppendChild(Result);
Result.FIsReadonly:= readonly;
except
if assigned(Result.ParentNode)
then Result.ParentNode.RemoveChild(Result);
RefNode.OwnerDocument.FreeAllNodes(Result);
raise;
end; {try ...}
except
raise EParserInvalidXmlDeclaration_Err.create('Invalid xml-declaration error.');
end; {try ...}
finally
RefNode.OwnerDocument.FreeAllNodes(NewElement);
end; {try ...}
end;
function TCustomParser.WriteTextDeclaration(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomTextDeclaration;
var
version,encoding,TargetName,AttribSequence: Widestring;
VersionAttr,EncodingAttr: TdomAttr;
VersionIndex,EncodingIndex: integer;
NewElement: TdomElement;
begin
Result:= nil;
XMLAnalyseTag(content,TargetName,AttribSequence);
if TargetName <> 'xml'
then raise EParserInvalidTextDeclaration_Err.create('Invalid text-declaration error.');
if RefNode.HasChildNodes
then raise EParserWrongOrder_Err.create('Wrong order error.');
NewElement:= RefNode.OwnerDocument.CreateElement('dummy');
try
XMLAnalyseAttrSequence(AttribSequence,NewElement,FirstLineNumber,LastLineNumber);
with NewElement.Attributes do begin
VersionAttr:= (GetNamedItem('version') as TdomAttr);
EncodingAttr:= (GetNamedItem('encoding') as TdomAttr);
VersionIndex:= GetNamedIndex('version');
EncodingIndex:= GetNamedIndex('encoding');
if (assigned(VersionAttr) and ((VersionIndex <> 0) or (EncodingIndex <> 1) or (Length > 2)))
or ( (not assigned(VersionAttr)) and ( (EncodingIndex <> 0) or (Length > 1)))
then raise EParserInvalidTextDeclaration_Err.create('Invalid text-declaration error.');
end; {with ...}
if assigned(VersionAttr)
then version:= VersionAttr.Value
else version:= '';
encoding:= EncodingAttr.Value;
try
Result:= RefNode.OwnerDocument.CreateTextDeclaration(version,encoding);
try
RefNode.AppendChild(Result);
Result.FIsReadonly:= readonly;
except
if assigned(Result.ParentNode)
then Result.ParentNode.RemoveChild(Result);
RefNode.OwnerDocument.FreeAllNodes(Result);
raise;
end; {try ...}
except
raise EParserInvalidTextDeclaration_Err.create('Invalid text-declaration error.');
end; {try ...}
finally
RefNode.OwnerDocument.FreeAllNodes(NewElement);
end; {try ...}
end;
function TCustomParser.WriteProcessingInstruction(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomNode;
var
TargetName,AttribSequence: Widestring;
begin
XMLAnalyseTag(content,TargetName,AttribSequence);
if TargetName = 'xml'
then raise EParserInvalidProcessingInstruction_Err.create('Invalid processing instruction error.');
try
Result:= RefNode.OwnerDocument.CreateProcessingInstruction(TargetName,AttribSequence);
try
RefNode.AppendChild(Result);
Result.FIsReadonly:= readonly;
except
if assigned(Result.ParentNode)
then Result.ParentNode.RemoveChild(Result);
RefNode.OwnerDocument.FreeAllNodes(Result);
raise;
end;
except
raise EParserInvalidProcessingInstruction_Err.create('Invalid processing instruction error.');
end;
end;
function TCustomParser.WriteComment(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomComment;
begin
try
Result:= RefNode.OwnerDocument.CreateComment(content);
try
RefNode.AppendChild(Result);
Result.FIsReadonly:= readonly;
except
if assigned(Result.ParentNode)
then Result.ParentNode.RemoveChild(Result);
RefNode.OwnerDocument.FreeAllNodes(Result);
raise;
end; {try ...}
except
raise EParserInvalidCharacter_Err.create('Invalid character error.');
end; {try ...}
end;
function TCustomParser.WriteCDATA(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomCDATASection;
begin
try
Result:= RefNode.OwnerDocument.CreateCDATASection(content);
try
RefNode.AppendChild(Result);
Result.FIsReadonly:= readonly;
except
if assigned(Result.ParentNode)
then Result.ParentNode.RemoveChild(Result);
RefNode.OwnerDocument.FreeAllNodes(Result);
raise;
end; {try ...}
except
raise EParserInvalidCharacter_Err.create('Invalid character error.');
end; {try ...}
end;
function TCustomParser.WritePCDATA(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomText;
begin
result:= nil;
if RefNode.NodeType = ntDocument_Node then
if IsXmlS(content)
then exit
else raise EParserInvalidCharacter_Err.create('Invalid character error.');
if RefNode.LastChild is TdomText
then (RefNode.LastChild as TdomText).appendData(content)
else begin
try
Result:= RefNode.OwnerDocument.CreateText(content);
try
RefNode.AppendChild(Result);
Result.FIsReadonly:= readonly;
except
if assigned(Result.ParentNode)
then Result.ParentNode.RemoveChild(Result);
RefNode.OwnerDocument.FreeAllNodes(Result);
raise;
end; {try ...}
except
raise EParserInvalidCharacter_Err.create('Invalid character error.');
end; {try ...}
end;
end;
function TCustomParser.WriteStartTag(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomElement;
var
TagName,AttribSequence: Widestring;
begin
XMLAnalyseTag(content,TagName,AttribSequence);
if not IsXmlName(TagName) then
raise EParserInvalidElementName_Err.create('Invalid element name error.');
if (RefNode.NodeType = ntDocument_Node) then
if assigned((RefNode as TdomDocument).DocumentElement)
then raise EParserDoubleRootElement_Err.create('Double root element error.');
try
Result:= RefNode.OwnerDocument.CreateElement(TagName);
try
XMLAnalyseAttrSequence(AttribSequence,Result,FirstLineNumber,LastLineNumber);
RefNode.AppendChild(Result);
Result.FIsReadonly:= readonly;
except
if assigned(Result.ParentNode)
then Result.ParentNode.RemoveChild(Result);
RefNode.OwnerDocument.FreeAllNodes(Result);
raise;
end; {try ...}
except
raise EParserMissingStartTag_Err.create('Invalid start tag error.');
end; {try ...}
end;
function TCustomParser.WriteEndTag(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode): TdomElement;
var
TagName,AttribSequence: Widestring;
begin
if not (RefNode.nodeType = ntElement_Node)
then raise EParserMissingStartTag_Err.create('Missing start tag error.');
XMLAnalyseTag(content,TagName,AttribSequence);
if AttribSequence <> ''
then raise EParserInvalidEndTag_Err.create('Invalid end tag error.');
if TagName <> RefNode.NodeName
then raise EParserMissingStartTag_Err.create('Missing start tag error.');
Result:= (RefNode as TdomElement);
end;
function TCustomParser.WriteCharRef(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomText;
var
value: wideString;
begin
Result:= nil;
try
Value:= XmlCharRefToStr(content);
except
on EConvertError do
raise EParserInvalidCharRef_Err.create('Invalid character reference error.');
end;
if RefNode.LastChild is TdomText
then (RefNode.LastChild as TdomText).appendData(value)
else begin
try
Result:= RefNode.OwnerDocument.CreateText(value);
try
RefNode.AppendChild(Result);
Result.FIsReadonly:= readonly;
except
if assigned(Result.ParentNode)
then Result.ParentNode.RemoveChild(Result);
RefNode.OwnerDocument.FreeAllNodes(Result);
raise;
end; {try ...}
except
raise EParserInvalidCharacter_Err.create('Invalid character error.');
end; {try ...}
end;
end;
function TCustomParser.WriteEntityRef(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomEntityReference;
var
EntityName: WideString;
begin
EntityName:= copy(content,2,length(content)-2);
try
Result:= RefNode.OwnerDocument.CreateEntityReference(EntityName);
try
RefNode.AppendChild(Result);
Result.FIsReadonly:= readonly;
except
if assigned(Result.ParentNode)
then Result.ParentNode.RemoveChild(Result);
RefNode.OwnerDocument.FreeAllNodes(Result);
raise;
end; {try ...}
except
raise EParserInvalidEntityName_Err.create('Invalid entity name error.');
end; {try ...}
end;
function TCustomParser.WriteDoctype(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode): TdomDocumentType;
var
DeclAnfg: integer;
ExternalId,intro,name,SystemLiteral,PubidLiteral: WideString;
NakedContent,data,dummy1,dummy2: WideString;
Error, dummy: boolean;
begin
if (RefNode.NodeType <> ntDocument_Node)
or assigned((RefNode as TdomDocument).DocumentElement)
then raise EParserWrongOrder_Err.create('Wrong order declaration error.');
if assigned((RefNode as TdomDocument).Doctype)
then raise EParserDoubleDoctype_Err.create('Double doctype declaration error.');
if (copy(content,1,9) <> '<!DOCTYPE')
or (content[length(content)] <> '>')
or (not isXmlWhiteSpace(content[10]))
then raise EParserInvalidDoctype_Err.create('invalid doctype declaration error.');
NakedContent:= XmlTrunc(copy(content,11,length(content)-11));
DeclAnfg:= Pos(WideString('['),NakedContent);
if DeclAnfg = 0 then begin
intro:= NakedContent;
Data:= '';
end else begin
intro:= copy(NakedContent,1,DeclAnfg-1);
dummy1:= copy(NakedContent,DeclAnfg,length(NakedContent)-DeclAnfg+1);
XMLTruncAngularBrackets(dummy1,data,error); {Diese umständliche Zuweisung ist wegen Delphi-Problem von WideStrings bei copy nötig}
if error then raise EParserInvalidDoctype_Err.create('invalid doctype declaration error.');
end; {if ...}
XMLAnalyseTag(intro,Name,ExternalId);
if not IsXmlName(Name)
then raise EParserInvalidDoctype_Err.create('invalid doctype declaration error.');
dummy1:= XmlTrunc(ExternalId);
ExternalId:= dummy1; {Diese umständliche Zuweisung ist wegen der Verwendung von WideStrings nötig}
if ExternalId <> '' then begin
XMLAnalyseEntityDef(ExternalId,dummy1,SystemLiteral,PubidLiteral,dummy2,Error);
if Error or (dummy1 <> '') or (dummy2 <> '')
then raise EParserInvalidDoctype_Err.create('invalid doctype declaration error.');
end; {if ...}
try
Result:= RefNode.OwnerDocument.CreateDocumentType(Name,PubidLiteral,SystemLiteral);
FIntSubset:= Data;
except
raise EParserInvalidDoctype_Err.create('invalid doctype declaration error.');
end; {try ...}
try
dummy:= Result.FIsReadonly;
Result.FIsReadonly:= false;
RefNode.AppendChild(Result);
Result.FIsReadonly:= dummy;
except
if assigned(Result.ParentNode)
then Result.ParentNode.RemoveChild(Result);
RefNode.OwnerDocument.FreeAllNodes(Result);
raise EParserInvalidDoctype_Err.create('invalid doctype declaration error.');
end; {try ...}
end;
function TCustomParser.WriteParameterEntityRef(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomParameterEntityReference;
var
EntityName: WideString;
ParEnt: TdomNode;
PreviousFlagValue: boolean;
begin
EntityName:= copy(content,2,length(content)-2);
try
Result:= RefNode.OwnerDocument.CreateParameterEntityReference(EntityName);
try
RefNode.AppendChild(Result);
ParEnt:= RefNode.OwnerDocument.Doctype.ParameterEntities.GetNamedItem(EntityName);
if not assigned(ParEnt)
then raise EParserInvalidEntityName_Err.create('Invalid entity name error.');
PreviousFlagValue:= FUseSpecifiedDocumentSC;
FUseSpecifiedDocumentSC:= false;
IntDtdWideStringToDom(concat(' ',ParEnt.FNodeValue,' '),Result,true); // xxx problems with external subset
FUseSpecifiedDocumentSC:= PreviousFlagValue;
Result.FIsReadonly:= readonly;
except
if assigned(Result.ParentNode)
then Result.ParentNode.RemoveChild(Result);
RefNode.OwnerDocument.FreeAllNodes(Result);
raise;
end; {try ...}
except
raise EParserInvalidEntityName_Err.create('Invalid entity name error.');
end; {try ...}
end;
function TCustomParser.WriteEntityDeclaration(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomCustomEntity;
var
DeclCorpus,DeclName,EntityDef,EntityValue,SystemLiteral,PubidLiteral,NDataName: WideString;
DeclTypus: TDomNodeType;
dummy,analyzedEV: WideString;
Error: boolean;
newEntity: TdomEntity;
newParameterEntity: TdomParameterEntity;
begin
result:= nil;
newEntity:= nil;
if (copy(content,1,8) <> '<!ENTITY')
or (content[length(content)] <> '>')
or (length(content) < 14)
or (not IsXmlWhiteSpace(content[9]))
then raise EParserInvalidEntityDeclaration_Err.create('Invalid entity declaration error.');
DeclCorpus:= XMLTrunc(copy(content,10,length(content)-10));
if DeclCorpus[1] = '%' then begin
if not IsXmlWhiteSpace(DeclCorpus[2])
then raise EParserInvalidEntityDeclaration_Err.create('Invalid entity declaration error.');
dummy:= XMLTrunc(copy(DeclCorpus,2,length(DeclCorpus)-1));
DeclCorpus:= dummy;
DeclTypus:= ntParameter_Entity_Declaration_Node;
end else DeclTypus:= ntEntity_Declaration_Node;
XMLAnalyseTag(DeclCorpus,DeclName,EntityDef);
if not IsXmlName(DeclName)
then raise EParserInvalidEntityDeclaration_Err.create('Invalid entity declaration error.');
XMLAnalyseEntityDef(EntityDef,EntityValue,SystemLiteral,PubidLiteral,NDataName,Error);
if Error then raise EParserInvalidEntityDeclaration_Err.create('Invalid entity declaration error.');
if (DeclTypus = ntParameter_Entity_Declaration_Node) and (NDataName <> '')
then raise EParserInvalidEntityDeclaration_Err.create('Invalid entity declaration error.');
try
if (DeclTypus = ntEntity_Declaration_Node) then begin
Result:= RefNode.OwnerDocument.CreateEntityDeclaration(DeclName,EntityValue,PubidLiteral,SystemLiteral,NDataName);
try
with RefNode.OwnerDocument do begin
if assigned(Doctype.Entities.GetNamedItem(DeclName)) then
FErrorList.Add(TXmlParserError.Create('Double_Entity_Decl_Warning',LastLineNumber,LastLineNumber,DeclName,Language))
else begin
newEntity:= CreateEntity(DeclName,PubidLiteral,SystemLiteral,NDataName);
If Result.IsInternalEntity
then DocWideStringToDom(EntityValue,newEntity,true);
Doctype.Entities.SetNamedItem(newEntity);
end;
end;
RefNode.AppendChild(Result);
Result.FIsReadonly:= readonly;
except
if assigned(newEntity)
then RefNode.OwnerDocument.FreeAllNodes(newEntity);
raise;
end; {try ...}
end else begin
Result:= RefNode.OwnerDocument.CreateParameterEntityDeclaration(DeclName,EntityValue,PubidLiteral,SystemLiteral);
with RefNode.OwnerDocument do begin
if assigned(Doctype.ParameterEntities.GetNamedItem(DeclName)) then
FErrorList.Add(TXmlParserError.Create('Double_Entity_Decl_Warning',LastLineNumber,LastLineNumber,DeclName,Language))
else begin
newParameterEntity:= CreateParameterEntity(DeclName,PubidLiteral,SystemLiteral);
Doctype.ParameterEntities.SetNamedItem(newParameterEntity);
If Result.IsInternalEntity then begin
analyzedEV:= RefNode.OwnerDocument.Doctype.analyzeEntityValue(EntityValue);
newParameterEntity.FNodeValue:= analyzedEV;
end;
end;
end;
RefNode.AppendChild(Result);
end;
except
if assigned(result) then begin
if assigned(Result.ParentNode)
then Result.ParentNode.RemoveChild(Result);
refNode.OwnerDocument.FreeAllNodes(Result);
end;
raise EParserInvalidEntityDeclaration_Err.create('Invalid entity declaration error.');
end; {try ...}
end;
function TCustomParser.WriteElementDeclaration(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomElementTypeDeclaration;
var
DeclCorpus,DeclName,ContentSpec: WideString;
dummy: WideString;
ContspecType: TdomContentspecType;
begin
if length(content) < 16
then raise EParserInvalidElementDeclaration_Err.create('Invalid element declaration error.');
if (copy(content,1,9) <> '<!ELEMENT')
or (content[length(content)] <> '>')
or (not IsXmlWhiteSpace(content[10]))
then raise EParserInvalidElementDeclaration_Err.create('Invalid element declaration error.');
DeclCorpus:= XMLTrunc(copy(content,11,length(content)-11));
XMLAnalyseTag(DeclCorpus,DeclName,ContentSpec);
if not IsXmlName(DeclName)
then raise EParserInvalidElementDeclaration_Err.create('Invalid element declaration error.');
dummy:= XMLTrunc(ContentSpec);
ContentSpec:= dummy;
ContspecType:= ctChildren;
if ContentSpec = 'EMPTY'
then ContspecType:= ctEmpty
else if ContentSpec = 'ANY'
then ContspecType:= ctAny
else if pos('#PCDATA',ContentSpec) > 0
then ContspecType:= ctMixed;
try
Result:= RefNode.OwnerDocument.CreateElementTypeDeclaration(DeclName,ContspecType);
try
RefNode.AppendChild(Result);
except
if assigned(Result.ParentNode)
then Result.ParentNode.RemoveChild(Result);
RefNode.OwnerDocument.FreeAllNodes(Result);
raise;
end; {try ...}
except
raise EParserInvalidElementDeclaration_Err.create('Invalid element declaration error.');
end; {try ...}
try
case ContspecType of
ctMixed: InsertMixedContent(Result,ContentSpec,readonly);
ctChildren: InsertChildrenContent(Result,ContentSpec,readonly);
end; {case ...}
except
RefNode.RemoveChild(Result);
RefNode.OwnerDocument.FreeAllNodes(Result);
raise EParserInvalidElementDeclaration_Err.create('Invalid element declaration error.');
end; {try ...}
Result.FIsReadonly:= readonly;
end;
function TCustomParser.WriteAttributeDeclaration(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomAttrList;
var
DeclCorpus,DeclName,ContentSpec: WideString;
dummy,AttDefName,AttType,Bracket,DefaultDecl,AttValue,Rest: WideString;
newAttDef: TdomAttrDefinition;
SucessfullyWriten: boolean;
begin
if length(Content) < 12
then raise EParserInvalidAttributeDeclaration_Err.create('Invalid attribute declaration error.');
if (copy(Content,1,9) <> '<!ATTLIST')
or (Content[length(Content)] <> '>')
or (not IsXmlWhiteSpace(Content[10]))
then raise EParserInvalidAttributeDeclaration_Err.create('Invalid attribute declaration error.');
DeclCorpus:= XMLTrunc(copy(Content,11,length(Content)-11));
XMLAnalyseTag(DeclCorpus,DeclName,ContentSpec);
if not IsXmlName(DeclName)
then raise EParserInvalidAttributeDeclaration_Err.create('Invalid attribute declaration error.');
try
Result:= RefNode.OwnerDocument.CreateAttributeList(DeclName);
try
RefNode.AppendChild(Result);
except
if assigned(Result.ParentNode)
then Result.ParentNode.RemoveChild(Result);
RefNode.OwnerDocument.FreeAllNodes(Result);
raise;
end; {try ...}
except
raise EParserInvalidAttributeDeclaration_Err.create('Invalid attribute declaration error.');
end; {try ...}
dummy:= XMLTrunc(ContentSpec);
ContentSpec:= dummy;
while ContentSpec <> '' do begin
FindNextAttDef(ContentSpec,AttDefName,AttType,Bracket,
DefaultDecl,AttValue,Rest);
try
newAttDef:= RefNode.OwnerDocument.CreateAttributeDefinition(AttDefName,AttType,DefaultDecl,AttValue);
try
if Bracket <> ''
then if AttType = 'NOTATION'
then InsertNotationTypeContent(newAttDef,Bracket,readonly)
else InsertEnumerationContent(newAttDef,Bracket,readonly);
except
RefNode.OwnerDocument.FreeAllNodes(newAttDef);
raise;
end; {try ...}
except
raise EParserInvalidAttributeDeclaration_Err.create('Invalid attribute declaration error.');
end; {try ...}
SucessfullyWriten:= Result.SetAttributeDefinitionNode(newAttDef);
if not SucessfullyWriten then RefNode.OwnerDocument.FreeAllNodes(newAttDef); {Schon Attribute mit demselben Namen vorhanden, dann nicht einfügen, sondern wieder löschen.}
ContentSpec:= Rest;
end; {while ...}
Result.FIsReadonly:= readonly;
end;
function TCustomParser.WriteNotationDeclaration(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomNotationDeclaration;
var
DeclCorpus,DeclName,ContentSpec,SystemLiteral,PubidLiteral: WideString;
Error: boolean;
newNotation: TdomNotation;
begin
newNotation:= nil;
if length(Content) < 22
then raise EParserInvalidNotationDeclaration_Err.create('Invalid notation declaration error.');
if (copy(Content,1,10) <> '<!NOTATION')
or (Content[length(Content)] <> '>')
or (not IsXmlWhiteSpace(Content[11]))
then raise EParserInvalidNotationDeclaration_Err.create('Invalid notation declaration error.');
DeclCorpus:= XMLTrunc(copy(Content,12,length(Content)-12));
XMLAnalyseTag(DeclCorpus,DeclName,ContentSpec);
if not IsXmlName(DeclName)
then raise EParserInvalidNotationDeclaration_Err.create('Invalid notation declaration error.');
XMLAnalyseNotationDecl(ContentSpec,SystemLiteral,PubidLiteral,Error);
if Error then raise EParserInvalidNotationDeclaration_Err.create('Invalid notation declaration error.');
try
Result:= RefNode.OwnerDocument.CreateNotationDeclaration(DeclName,PubidLiteral,SystemLiteral);
try
with RefNode.OwnerDocument do begin
if assigned(Doctype.Notations.GetNamedItem(DeclName)) then
FErrorList.Add(TXmlParserError.Create('Double_Notation_Decl_Warning',LastLineNumber,LastLineNumber,DeclName,Language))
else begin
newNotation:= CreateNotation(DeclName,PubidLiteral,SystemLiteral);
Doctype.Notations.SetNamedItem(newNotation);
end;
end;
RefNode.AppendChild(Result);
Result.FIsReadonly:= readonly;
except
if assigned(Result.ParentNode)
then Result.ParentNode.RemoveChild(Result);
RefNode.OwnerDocument.FreeAllNodes(Result);
if assigned(newNotation.ParentNode) then
RefNode.OwnerDocument.Doctype.Notations.removeItem(newNotation);
if assigned(newNotation)
then RefNode.OwnerDocument.FreeAllNodes(newNotation);
raise;
end; {try ...}
except
raise EParserInvalidNotationDeclaration_Err.create('Invalid notation declaration error.');
end; {try ...}
end;
function TCustomParser.WriteConditionalSection(const Content: WideString;
const FirstLineNumber,
LastLineNumber: integer;
const RefNode: TdomNode;
const readonly: boolean): TdomConditionalSection;
var
declaration: WideString;
IncludeStmt: WideString;
i,nr1,nr2: longint;
begin
nr1:= 0;
nr2:= 0;
for i:= 1 to length(content) do begin
if content[i] = '[' then begin
if nr1 = 0 then nr1:= i else nr2:= i;
end;
if nr2 > 0 then break;
end;
if nr2 = 0 then raise EParserInvalidConditionalSection_Err.create('invalid conditional section error.');
if (copy(content,1,3) <> '<![') then raise EParserInvalidConditionalSection_Err.create('invalid conditional section error.');
if (copy(content,length(content)-2,3) <> ']]>') then raise EParserInvalidConditionalSection_Err.create('invalid conditional section error.');
IncludeStmt:= XmlTrunc(copy(content,4,nr2-4));
if not ( IsXmlPEReference(IncludeStmt)
or (IncludeStmt = 'INCLUDE')
or (IncludeStmt = 'IGNORE') ) then raise EParserInvalidConditionalSection_Err.create('invalid conditional section error.');
declaration:= XmlTrunc(copy(content,nr2+1,length(content)-nr2-3));
try
Result:= RefNode.OwnerDocument.CreateConditionalSection(IncludeStmt);
except
raise EParserInvalidConditionalSection_Err.create('invalid conditional section error.');
end; {try ...}
try
if (IncludeStmt = 'INCLUDE') and (declaration <> '')
then ExtDtdWideStringToDom(declaration,Result,readonly);
except
RefNode.OwnerDocument.FreeAllNodes(Result);
raise;
end; {try ...}
try
RefNode.AppendChild(Result);
Result.FIsReadonly:= readonly;
except
if assigned(Result.ParentNode)
then Result.ParentNode.RemoveChild(Result);
RefNode.OwnerDocument.FreeAllNodes(Result);
raise EParserInvalidConditionalSection_Err.create('invalid conditional section error.');
end; {try ...}
end;
procedure TCustomParser.InsertMixedContent(const RefNode: TdomNode;
const ContentSpec: WideString;
const readonly: boolean);
var
freq, dummy, content,piece: WideString;
separator: integer;
Error: boolean;
newNode: TdomNode;
begin
content:= XMLTrunc(ContentSpec);
Freq:= '';
if (content[length(content)] = '*') then begin
Freq:= '*';
dummy:= copy(content,1,length(content)-1);
content:= dummy;
end;
XMLTruncRoundBrackets(content,dummy,Error);
if Error or (dummy = '')
then raise EParserException.create('Parser error.');
content:= dummy;
newNode:= RefNode.AppendChild(RefNode.OwnerDocument.CreatePcdataChoiceParticle);
newNode.FIsReadonly:= readonly;
if content = '#PCDATA' then exit;
if freq = '' then raise EParserException.create('Parser error.');
separator:= pos(WideString('|'),content);
if separator = 0 then raise EParserException.create('Parser error.');
dummy:= XMLTrunc(copy(content,separator+1,length(content)-separator));
content:= dummy;
while content <> '' do begin
separator:= pos(WideString('|'),content);
if separator = 0 then begin
piece:= content;
content:= '';
end else begin
piece:= XMLTrunc(copy(content,1,separator-1));
dummy:= XMLTrunc(copy(content,separator+1,length(content)-separator));
content:= dummy;
if content = '' then raise EParserException.create('Parser error.');
end; {if ...}
if not IsXmlName(piece) then raise EParserException.create('Parser error.');
newNode.AppendChild(newNode.OwnerDocument.CreateElementParticle(piece,''));
newNode.FIsReadonly:= readonly;
end; {while ...}
end;
procedure TCustomParser.InsertChildrenContent(const RefNode: TdomNode;
const ContentSpec: WideString;
const readonly: boolean);
var
piece,dummy,content,freq: WideString;
SeparatorChar: WideChar;
j,i,bracketNr: integer;
newNode: TdomNode;
Error: boolean;
begin
content:= XMLTrunc(ContentSpec);
Freq:= '';
if (content[length(content)] = '?') or
(content[length(content)] = '*') or
(content[length(content)] = '+') then begin
Freq:= content[length(content)];
dummy:= copy(content,1,length(content)-1);
content:= dummy;
end;
XMLTruncRoundBrackets(content,dummy,Error);
if Error or (dummy = '')
then raise EParserException.create('Parser error.');
content:= dummy;
bracketNr:= 0;
SeparatorChar:= ',';
for i:= 1 to length(content) do begin
if (content[i] = ',') and (bracketNr = 0) then begin
SeparatorChar:= ',';
break;
end; {if ...}
if (content[i] = '|') and (bracketNr = 0) then begin
SeparatorChar:= '|';
break;
end; {if ...}
if content[i] = '(' then inc(bracketNr);
if content[i] = ')' then begin
if bracketNr = 0 then raise EParserException.create('Parser error.');
dec(bracketNr);
end;
end; {for ...}
if SeparatorChar = ','
then newNode:= RefNode.AppendChild(RefNode.OwnerDocument.CreateSequenceParticle(Freq))
else newNode:= RefNode.AppendChild(RefNode.OwnerDocument.CreateChoiceParticle(Freq));
newNode.FIsReadonly:= readonly;
bracketNr:= 0;
i:= 0;
j:= 1;
while i < length(content) do begin
inc(i);
if content[i] = '(' then inc(bracketNr);
if content[i] = ')' then begin
if bracketNr = 0 then raise EParserException.create('Parser error.');
dec(bracketNr);
end;
if ((content[i] = SeparatorChar) and (bracketNr = 0)) or
(i = length(content)) then begin
if bracketNr > 0 then raise EParserException.create('Parser error.');
if i = length(content)
then piece:= XmlTrunc(copy(content,j,i+1-j))
else piece:= XmlTrunc(copy(content,j,i-j));
j:= i+1;
if piece[1] = '(' then begin
InsertChildrenContent(NewNode,piece,readonly);
end else begin
Freq:= '';
if (piece[length(piece)] = '?') or
(piece[length(piece)] = '*') or
(piece[length(piece)] = '+') then begin
Freq:= piece[length(piece)];
dummy:= copy(piece,1,length(piece)-1);
piece:= dummy;
end;
if not IsXmlName(piece)
then raise EParserException.create('Parser error.');
NewNode.AppendChild(RefNode.OwnerDocument.CreateElementParticle(piece,Freq));
newNode.FIsReadonly:= readonly;
end; {if ...}
end; {if ...}
end; {while ...}
end;
procedure TCustomParser.InsertNotationTypeContent(const RefNode: TdomNode;
const ContentSpec: WideString;
const readonly: boolean);
var
dummy,content,piece: WideString;
separator: integer;
Error: boolean;
newNode: TdomNode;
begin
XMLTruncRoundBrackets(ContentSpec,content,Error);
if Error then raise EParserException.create('Parser error.');
while content <> '' do begin
separator:= pos(WideString('|'),content);
if separator = 0 then begin
piece:= content;
content:= '';
end else begin
piece:= XMLTrunc(copy(content,1,separator-1));
dummy:= XMLTrunc(copy(content,separator+1,length(content)-separator));
content:= dummy;
if content = '' then raise EParserException.create('Parser error.');
end; {if ...}
if not IsXmlName(piece) then raise EParserException.create('Parser error.');
newNode:= RefNode.AppendChild(RefNode.OwnerDocument.CreateElementParticle(piece,''));
newNode.FIsReadonly:= readonly;
end; {while ...}
end;
procedure TCustomParser.InsertEnumerationContent(const RefNode: TdomNode;
const ContentSpec: WideString;
const readonly: boolean);
var
dummy,content,piece: WideString;
separator: integer;
Error: boolean;
newNode: TdomNode;
begin
XMLTruncRoundBrackets(ContentSpec,content,Error);
if Error then raise EParserException.create('Parser error.');
while content <> '' do begin
separator:= pos(WideString('|'),content);
if separator = 0 then begin
piece:= content;
content:= '';
end else begin
piece:= XMLTrunc(copy(content,1,separator-1));
dummy:= XMLTrunc(copy(content,separator+1,length(content)-separator));
content:= dummy;
if content = '' then raise EParserException.create('Parser error.');
end; {if ...}
if not IsXmlNmtoken(piece) then raise EParserException.create('Parser error.');
newNode:= RefNode.AppendChild(RefNode.OwnerDocument.CreateNametoken(piece));
newNode.FIsReadonly:= readonly;
end; {while ...}
end;
procedure TCustomParser.FindNextAttDef(const Decl: WideString;
var Name,
AttType,
Bracket,
DefaultDecl,
AttValue,
Rest: WideString);
var
i,j: integer;
FindBracket, FindDefaultDecl, FindAttValue: boolean;
QuoteType: WideChar;
begin
Name:= '';
AttType:= '';
Bracket:= '';
DefaultDecl:= '';
AttValue:= '';
Rest:= '';
FindBracket:= false;
FindDefaultDecl:= false;
FindAttValue:= false;
if Length(Decl) = 0
then raise EParserInvalidAttributeDeclaration_Err.create('Invalid attribute declaration error.');
i:= 1;
{White-space?}
while IsXmlWhiteSpace(Decl[i]) do begin
inc(i);
if i > length(Decl)
then raise EParserInvalidAttributeDeclaration_Err.create('Invalid attribute declaration error.');
end;
j:= i;
{Name?}
while not IsXmlWhiteSpace(Decl[i]) do begin
inc(i);
if i > length(Decl)
then raise EParserInvalidAttributeDeclaration_Err.create('Invalid attribute declaration error.');
end;
Name:= copy(Decl,j,i-j);
{White-space?}
while IsXmlWhiteSpace(Decl[i]) do begin
inc(i);
if i > length(Decl)
then raise EParserInvalidAttributeDeclaration_Err.create('Invalid attribute declaration error.');
end;
j:= i;
if Decl[j] = '(' then FindBracket:= true;
{AttType?}
if not FindBracket then begin
while not IsXmlWhiteSpace(Decl[i]) do begin
inc(i);
if i > length(Decl)
then raise EParserInvalidAttributeDeclaration_Err.create('Invalid attribute declaration error.');
end;
AttType:= copy(Decl,j,i-j);
if AttType = 'NOTATION' then FindBracket:= true;
{White-space?}
while IsXmlWhiteSpace(Decl[i]) do begin
inc(i);
if i > length(Decl)
then raise EParserInvalidAttributeDeclaration_Err.create('Invalid attribute declaration error.');
end;
j:= i;
end; {if ...}
{Bracket?}
if FindBracket then begin
if Decl[j] <> '('
then raise EParserInvalidAttributeDeclaration_Err.create('Invalid attribute declaration error.');
while not (Decl[i] = ')') do begin
inc(i);
if i >= length(Decl)
then raise EParserInvalidAttributeDeclaration_Err.create('Invalid attribute declaration error.');
end;
Bracket:= copy(Decl,j,i-j+1);
{White-space?}
inc(i);
if not IsXmlWhiteSpace(Decl[i])
then raise EParserInvalidAttributeDeclaration_Err.create('Invalid attribute declaration error.');
while IsXmlWhiteSpace(Decl[i]) do begin
inc(i);
if i > length(Decl)
then raise EParserInvalidAttributeDeclaration_Err.create('Invalid attribute declaration error.');
end;
j:= i;
end; {if ...}
if Decl[j] = '#'
then FindDefaultDecl:= true
else FindAttValue:= true;
{DefaultDecl?}
if FindDefaultDecl then begin
while not IsXmlWhiteSpace(Decl[i]) do begin
inc(i);
if i > length(Decl) then break;
end; {while ...}
DefaultDecl:= copy(Decl,j,i-j);
if DefaultDecl = '#FIXED' then begin
FindAttValue:= true;
{White-space?}
if i > length(Decl)
then raise EParserInvalidAttributeDeclaration_Err.create('Invalid attribute declaration error.');
while IsXmlWhiteSpace(Decl[i]) do begin
inc(i);
if i > length(Decl)
then raise EParserInvalidAttributeDeclaration_Err.create('Invalid attribute declaration error.');
end; {while ...}
j:= i;
end; {if ...}
end; {if ...}
{AttValue?}
if FindAttValue then begin
if i = length(Decl)
then raise EParserInvalidAttributeDeclaration_Err.create('Invalid attribute declaration error.');
QuoteType:= Decl[i];
if not ( (QuoteType = '"') or (QuoteType = #$0027))
then raise EParserInvalidAttributeDeclaration_Err.create('Invalid attribute declaration error.');
inc(i);
while not (Decl[i] = QuoteType) do begin
inc(i);
if i > length(Decl)
then raise EParserInvalidAttributeDeclaration_Err.create('Invalid attribute declaration error.');
end; {while ...}
AttValue:= copy(Decl,j+1,i-j-1);
inc(i);
end; {if ...}
Rest:= copy(Decl,i,length(Decl)-i+1);
end;
procedure TCustomParser.DocToXmlSourceCode(const InputSource :TXmlInputSource;
const Source: TXmlSourceCode);
const
SingleQuote: WideChar = #39; // code of '
DoubleQuote: WideChar = #34; // code of "
MaxCode: array[1..6] of integer = ($7F,$7FF,$FFFF,$1FFFFF,$3FFFFFF,$7FFFFFFF);
var
str0: Char;
str1: WideChar;
subEndMarker,SubStartMarker: WideString;
SingleQuoteOpen,DoubleQuoteOpen,BracketOpened: boolean;
StreamSize: longint;
PieceType: TdomPieceType;
newSourceCodePiece: TXmlSourceCodePiece;
content: TdomCustomStr;
CharSize, ucs4, mask: integer;
first: char;
begin
subEndMarker:= '';
subStartMarker:= '';
BracketOpened:= false;
Source.clearAndFree;
content:= TdomCustomStr.create;
with inputSource do begin
try
StreamSize:= Stream.Size; // buffer storage to increase performance
while Stream.Position < StreamSize do begin
SingleQuoteOpen:= false;
DoubleQuoteOpen:= false;
content.reset;
PieceType:= xmlPCData;
while Stream.Position < StreamSize do begin
case Encoding of
etUTF8: begin
Stream.ReadBuffer(str0,1);
if ord(str0)>=$80 then // UTF-8 sequence
begin
try
CharSize:=1;
first:=str0; mask:=$40; ucs4:=ord(str0);
if (ord(str0) and $C0<>$C0) then
raise EConvertError.CreateFmt('Invalid UTF-8 sequence at position %d',[Stream.Position-1]);
while (mask and ord(first)<>0) do
begin
// read next character of stream
if Stream.Position=StreamSize then
raise EConvertError.CreateFmt('Aborted UTF-8 sequence at position %d',[Stream.Position]);
Stream.ReadBuffer(str0,1);
if (ord(str0) and $C0<>$80) then
raise EConvertError.CreateFmt('Invalid UTF-8 sequence at position %d',[Stream.Position-1]);
ucs4:=(ucs4 shl 6) or (ord(str0) and $3F); // add bits to result
Inc(CharSize); // increase sequence length
mask:=mask shr 1; // adjust mask
end;
if (CharSize>6) then // no 0 bit in sequence header 'first'
raise EConvertError.CreateFmt('Invalid UTF-8 sequence at position %d',[Stream.Position-1]);
ucs4:=ucs4 and MaxCode[CharSize]; // dispose of header bits
// check for invalid sequence as suggested by RFC2279
if ((CharSize>1) and (ucs4<=MaxCode[CharSize-1])) then
raise EConvertError.CreateFmt('Invalid UTF-8 encoding at position %d',[Stream.Position-1]);
if (ucs4>=$10000) then
begin
// add high surrogate to content as if it was processed earlier
Content.addWideChar(Utf16HighSurrogate(ucs4));
// assign low surrogate to str1
str1:=Utf16LowSurrogate(ucs4);
end
else
str1:= WideChar(ord(ucs4));
except
on E: EConvertError do begin
content.AddWideChar(WideChar(ord(str0)));
PieceType:= xmlCharacterError;
end; {on ...}
end; {try ...}
if PieceType = xmlCharacterError then break;
end
else
str1:= WideChar(ord(str0));
end;
etMBCS : str1:=ReadWideCharFromMBCSStream(Stream);
etUTF16BE: begin
Stream.ReadBuffer(str1,2);
end;
etUTF16LE: begin
Stream.ReadBuffer(str1,2);
str1:= wideChar(Swap(ord(str1)));
end;
end; {case ...}
if not IsXmlChar(str1) then begin
content.AddWideChar(str1);
PieceType:= xmlCharacterError;
break;
end;
case PieceType of
xmlPCData: begin
if (str1 = '<') or (str1 = '&') then begin
if content.length = 0 then begin
if str1 = '<' then begin
PieceType:= xmlStartTag;
end else
if str1 = '&' then PieceType:= xmlEntityRef;
content.AddWideChar(Str1);
end else begin {if length(content) = 0}
case Encoding of
etUTF8,etMBCS: Stream.Seek(-1,soFromCurrent);
etUTF16BE,etUTF16LE: Stream.Seek(-2,soFromCurrent);
end; {case ...}
break;
end; {if length(content) = 0}
end else {if (str1 = '<') ...}
content.AddWideChar(str1);
end;
xmlEntityRef: begin
content.AddWideChar(str1);
if str1 = ';' then begin
if content.value[2] = wideChar('#')
then PieceType:= xmlCharRef;
break;
end;
end;
xmlStartTag: begin
content.AddWideChar(str1);
case content.length of
2: if content.value = '<?' then PieceType:= xmlProcessingInstruction;
4: if content.value = '<!--' then PieceType:= xmlComment;
9: if content.value = '<![CDATA[' then begin
PieceType:= xmlCDATA;
end else
if content.value = '<!DOCTYPE' then begin
PieceType:= xmlDoctype;
subEndMarker:= '';
subStartMarker:= '';
BracketOpened:= false;
end;
end;
{Count quotation marks:}
if (str1 = SingleQuote) and (not DoubleQuoteOpen) then begin
SingleQuoteOpen:= not SingleQuoteOpen;
end else if (str1 = DoubleQuote) and (not SingleQuoteOpen) then begin
DoubleQuoteOpen:= not DoubleQuoteOpen;
end else if str1 = '>' then begin
if (not DoubleQuoteOpen) and (not SingleQuoteOpen) then begin
if (Copy(content.value,1,2) = '</')
then PieceType:= xmlEndTag
else begin if (Copy(content.value,content.length-1,2) = '/>')
then PieceType:= xmlEmptyElementTag;
end;
break;
end;
end;
end;
xmlProcessingInstruction: begin
content.AddWideChar(str1);
if str1 = '>' then
if content.value[content.length-1] = '?' then begin
if (content.length > 5) then
if IsXmlWhiteSpace(content.value[6]) then
if (Copy(content.value,1,5) = '<?xml')
then PieceType:= xmlXmlDeclaration;
break;
end;
end;
xmlComment: begin
content.AddWideChar(str1);
if str1 = '>' then
if content.value[content.length-1] = '-' then
if content.value[content.length-2] = '-' then
if content.length > 6 then break;
end;
xmlCDATA: begin
content.AddWideChar(str1);
if str1 = '>' then
if content.value[content.length-1] = ']' then
if content.value[content.length-2] = ']' then break;
end;
xmlDoctype: begin
content.AddWideChar(str1);
if (SubEndMarker = '') then begin
if (str1 = SingleQuote) and (not DoubleQuoteOpen) then begin
if SingleQuoteOpen
then SingleQuoteOpen:= false
else SingleQuoteOpen:= true;
end else if (str1 = DoubleQuote) and (not SingleQuoteOpen) then begin
if DoubleQuoteOpen
then DoubleQuoteOpen:= false
else DoubleQuoteOpen:= true;
end;
if BracketOpened then begin
if not (SingleQuoteOpen or DoubleQuoteOpen) then begin
if str1 = '<' then begin
SubStartMarker:= '<';
end else if (str1 = '!') and (SubStartMarker = '<') then begin
SubStartMarker:= '<!';
end else if (str1 = '?') and (SubStartMarker = '<') then begin
SubStartMarker:= '';
SubEndMarker:= '?>';
end else if (str1 = '-') and (SubStartMarker = '<!')then begin
SubStartMarker:= '<!-';
end else if (str1 = '-') and (SubStartMarker = '<!-')then begin
SubStartMarker:= '';
SubEndMarker:= '-->';
end else if SubStartMarker <> '' then begin
SubStartMarker:= '';
end;
if (str1 = ']')
and (not SingleQuoteOpen)
and (not DoubleQuoteOpen)
then BracketOpened:= false;
end; {if not ...}
end else begin {if BracketOpened ... }
if (str1 = '[')
and (not SingleQuoteOpen)
and (not DoubleQuoteOpen) then BracketOpened:= true;
end; {if BracketOpened ... else ...}
end else begin; {if (SubEndMarker = '') ...}
if (Copy(content.value,content.length-Length(SubEndMarker)+1,Length(SubEndMarker))
= SubEndMarker)
then SubEndMarker:= '';
end; {if (SubEndMarker = '') ... else ...}
if (not DoubleQuoteOpen)
and (not SingleQuoteOpen)
and (not BracketOpened)
and (SubEndMarker = '')
and (str1 = '>')
then break;
end; {xmlDoctype: ...}
end; {case ...}
end; {while ...}
newSourceCodePiece:= TXmlSourceCodePiece.create(PieceType);
newSourceCodePiece.text:= NormalizeLineBreaks(content.value);
Source.Add(newSourceCodePiece);
end; {while ...}
finally
content.free;
end;
end; {with inputSource ...}
end;
procedure TCustomParser.ExtDtdToXmlSourceCode(const InputSource: TXmlInputSource;
const Source: TXmlSourceCode);
const
SingleQuote: WideChar = #39; // code of '
DoubleQuote: WideChar = #34; // code of "
MaxCode: array[1..6] of integer = ($7F,$7FF,$FFFF,$1FFFFF,$3FFFFFF,$7FFFFFFF);
var
str0: Char;
str1: WideChar;
subEndMarker,SubStartMarker: WideString;
SingleQuoteOpen,DoubleQuoteOpen,commentActive: boolean;
StreamSize,condSectCounter: longint;
PieceType: TdomPieceType;
newSourceCodePiece: TXmlSourceCodePiece;
content: TdomCustomStr;
CharSize, ucs4, mask: integer;
first: char;
begin
subEndMarker:= '';
subStartMarker:= '';
commentActive:= false;
condSectCounter:= 0;
Source.clearAndFree;
content:= TdomCustomStr.create;
with InputSource do begin
try
StreamSize:= Stream.Size; // buffer storage to increase performance
while Stream.Position < StreamSize do begin
SingleQuoteOpen:= false;
DoubleQuoteOpen:= false;
Content.reset;
PieceType:= xmlPCData;
while Stream.Position < StreamSize do begin
case Encoding of
etUTF8: begin
Stream.ReadBuffer(str0,1);
if ord(str0)>=$80 then // UTF-8 sequence
begin
try
CharSize:=1;
first:=str0; mask:=$40; ucs4:=ord(str0);
if (ord(str0) and $C0<>$C0) then
raise EConvertError.CreateFmt('Invalid UTF-8 sequence at position %d',[Stream.Position-1]);
while (mask and ord(first)<>0) do
begin
// read next character of stream
if Stream.Position=StreamSize then
raise EConvertError.CreateFmt('Aborted UTF-8 sequence at position %d',[Stream.Position]);
Stream.ReadBuffer(str0,1);
if (ord(str0) and $C0<>$80) then
raise EConvertError.CreateFmt('Invalid UTF-8 sequence at position %d',[Stream.Position-1]);
ucs4:=(ucs4 shl 6) or (ord(str0) and $3F); // add bits to result
Inc(CharSize); // increase sequence length
mask:=mask shr 1; // adjust mask
end;
if (CharSize>6) then // no 0 bit in sequence header 'first'
raise EConvertError.CreateFmt('Invalid UTF-8 sequence at position %d',[Stream.Position-1]);
ucs4:=ucs4 and MaxCode[CharSize]; // dispose of header bits
// check for invalid sequence as suggested by RFC2279
if ((CharSize>1) and (ucs4<=MaxCode[CharSize-1])) then
raise EConvertError.CreateFmt('Invalid UTF-8 encoding at position %d',[Stream.Position-1]);
if (ucs4>=$10000) then
begin
// add high surrogate to content as if it was processed earlier
Content.addWideChar(Utf16HighSurrogate(ucs4));
// assign low surrogate to str1
str1:=Utf16LowSurrogate(ucs4);
end
else
str1:= WideChar(ord(ucs4));
except
on E: EConvertError do begin
content.AddWideChar(WideChar(ord(str0)));
PieceType:= xmlCharacterError;
end; {on ...}
end; {try ...}
if PieceType = xmlCharacterError then break;
end
else
str1:= WideChar(ord(str0));
end;
// add by hyl
etMBCS : str1:=ReadWideCharFromMBCSStream(Stream);
// end add
etUTF16BE: begin
Stream.ReadBuffer(str1,2);
end;
etUTF16LE: begin
Stream.ReadBuffer(str1,2);
str1:= wideChar(Swap(ord(str1)));
end;
end; {case ...}
if not IsXmlChar(str1) then begin
content.addWideChar(str1);
PieceType:= xmlCharacterError;
break;
end;
if PieceType = xmlPCData then begin
if str1 = '<' then begin
PieceType:= xmlStartTag;
end else
if str1 = '%' then begin
PieceType:= xmlParameterEntityRef;
end else
if not IsXmlWhiteSpace(str1) then begin;
content.addWideChar(str1);
PieceType:= xmlCharacterError;
break;
end;
end; {if ...}
case PieceType of
xmlParameterEntityRef: begin
content.addWideChar(str1);
if str1 = ';' then break;
end;
xmlStartTag: begin
content.addWideChar(str1);
case content.length of
2: if content.value = '<?' then PieceType:= xmlProcessingInstruction;
3: if content.value = '<![' then begin
PieceType:= xmlCondSection;
condSectCounter:= 1;
commentActive:= false;
end;
4: if content.value = '<!--' then PieceType:= xmlComment;
8: if content.value = '<!ENTITY' then PieceType:= xmlEntityDecl;
9: if content.value = '<!ELEMENT' then PieceType:= xmlElementDecl
else if content.value = '<!ATTLIST' then PieceType:= xmlAttributeDecl;
10: if content.value = '<!NOTATION' then PieceType:= xmlNotationDecl;
end;
end;
xmlProcessingInstruction: begin
content.addWideChar(str1);
if str1 = '>' then
if content.value[content.length-1] = '?' then begin
if (content.length > 5) then
if IsXmlWhiteSpace(content.value[6]) then
if (Copy(content.value,1,5) = '<?xml')
then PieceType:= xmlTextDeclaration;
break;
end;
end;
xmlCondSection: begin
content.addWideChar(str1);
if str1 = '[' then begin
if content.value[content.length-1] = '!' then
if content.value[content.length-2] = '<' then
if not commentActive then inc(condSectCounter);
end else if str1 = '>' then begin
if content.value[content.length-1] = ']' then
if content.value[content.length-2] = ']' then
if not commentActive then dec(condSectCounter);
end;
if commentActive then begin
if str1 = '>' then
if content.value[content.length-1] = '-' then
if content.value[content.length-2] = '-' then
if not ( (content.value[content.length-3] = '!')
and (content.value[content.length-4] = '<') ) then
if not ( (content.value[content.length-3] = '-')
and (content.value[content.length-4] = '!')
and (content.value[content.length-5] = '<') )
then commentActive:= false;
end else begin
if str1 = '-' then
if content.value[content.length-1] = '-' then
if content.value[content.length-2] = '!' then
if content.value[content.length-3] = '<'
then commentActive:= true;
end;
if condSectCounter = 0 then break;
end;
xmlComment: begin
content.addWideChar(str1);
if str1 = '>' then
if content.value[content.length-1] = '-' then
if content.value[content.length-2] = '-' then
if content.length > 6 then break;
end;
xmlEntityDecl,xmlNotationDecl: begin
content.addWideChar(str1);
if (str1 = SingleQuote) and (not DoubleQuoteOpen) then begin
if SingleQuoteOpen
then SingleQuoteOpen:= false
else SingleQuoteOpen:= true;
end else if (str1 = DoubleQuote) and (not SingleQuoteOpen) then begin
if DoubleQuoteOpen
then DoubleQuoteOpen:= false
else DoubleQuoteOpen:= true;
end;
if (not DoubleQuoteOpen)
and (not SingleQuoteOpen)
and (str1 = '>')
then break;
end;
xmlElementDecl,xmlAttributeDecl: begin
content.addWideChar(str1);
if str1 = '>' then break;
end;
end; {case ...}
end; {while ...}
newSourceCodePiece:= TXmlSourceCodePiece.create(PieceType);
newSourceCodePiece.text:= NormalizeLineBreaks(content.value);
Source.Add(newSourceCodePiece);
end; {while ...}
finally
content.free;
end;
end; {with InputSource ...}
end;
procedure TCustomParser.IntDtdToXmlSourceCode(const InputSource: TXmlInputSource;
const Source: TXmlSourceCode);
const
SingleQuote: WideChar = #39; // code of '
DoubleQuote: WideChar = #34; // code of "
MaxCode: array[1..6] of integer = ($7F,$7FF,$FFFF,$1FFFFF,$3FFFFFF,$7FFFFFFF);
var
str0: Char;
str1: WideChar;
subEndMarker,SubStartMarker: WideString;
SingleQuoteOpen,DoubleQuoteOpen: boolean;
StreamSize: longint;
PieceType: TdomPieceType;
newSourceCodePiece: TXmlSourceCodePiece;
content: TdomCustomStr;
CharSize, ucs4, mask: integer;
first: char;
begin
subEndMarker:= '';
subStartMarker:= '';
Source.clearAndFree;
content:= TdomCustomStr.create;
with InputSource do begin
try
StreamSize:= Stream.Size; // buffer storage to increase performance
while Stream.Position < StreamSize do begin
SingleQuoteOpen:= false;
DoubleQuoteOpen:= false;
Content.reset;
PieceType:= xmlPCData;
while Stream.Position < StreamSize do begin
case Encoding of
etUTF8: begin
Stream.ReadBuffer(str0,1);
if ord(str0)>=$80 then // UTF-8 sequence
begin
try
CharSize:=1;
first:=str0; mask:=$40; ucs4:=ord(str0);
if (ord(str0) and $C0<>$C0) then
raise EConvertError.CreateFmt('Invalid UTF-8 sequence at position %d',[Stream.Position-1]);
while (mask and ord(first)<>0) do
begin
// read next character of stream
if Stream.Position=StreamSize then
raise EConvertError.CreateFmt('Aborted UTF-8 sequence at position %d',[Stream.Position]);
Stream.ReadBuffer(str0,1);
if (ord(str0) and $C0<>$80) then
raise EConvertError.CreateFmt('Invalid UTF-8 sequence at position %d',[Stream.Position-1]);
ucs4:=(ucs4 shl 6) or (ord(str0) and $3F); // add bits to result
Inc(CharSize); // increase sequence length
mask:=mask shr 1; // adjust mask
end;
if (CharSize>6) then // no 0 bit in sequence header 'first'
raise EConvertError.CreateFmt('Invalid UTF-8 sequence at position %d',[Stream.Position-1]);
ucs4:=ucs4 and MaxCode[CharSize]; // dispose of header bits
// check for invalid sequence as suggested by RFC2279
if ((CharSize>1) and (ucs4<=MaxCode[CharSize-1])) then
raise EConvertError.CreateFmt('Invalid UTF-8 encoding at position %d',[Stream.Position-1]);
if (ucs4>=$10000) then
begin
// add high surrogate to content as if it was processed earlier
Content.addWideChar(Utf16HighSurrogate(ucs4));
// assign low surrogate to str1
str1:=Utf16LowSurrogate(ucs4);
end
else
str1:= WideChar(ord(ucs4));
except
on E: EConvertError do begin
content.AddWideChar(WideChar(ord(str0)));
PieceType:= xmlCharacterError;
end; {on ...}
end; {try ...}
if PieceType = xmlCharacterError then break;
end
else
str1:= WideChar(ord(str0));
end;
// begin add
etMBCS : str1:=ReadWideCharFromMBCSStream(Stream);
// end add
etUTF16BE: begin
Stream.ReadBuffer(str1,2);
end;
etUTF16LE: begin
Stream.ReadBuffer(str1,2);
str1:= wideChar(Swap(ord(str1)));
end;
end; {case ...}
if not IsXmlChar(str1) then begin
content.addWideChar(str1);
PieceType:= xmlCharacterError;
break;
end;
if PieceType = xmlPCData then begin
if str1 = '<' then begin
PieceType:= xmlStartTag;
end else
if str1 = '%' then begin
PieceType:= xmlParameterEntityRef;
end else
if not IsXmlWhiteSpace(str1) then begin;
content.addWideChar(str1);
PieceType:= xmlCharacterError;
break;
end;
end; {if ...}
case PieceType of
xmlParameterEntityRef: begin
content.addWideChar(str1);
if str1 = ';' then break;
end;
xmlStartTag: begin
content.addWideChar(str1);
case content.length of
2: if content.value = '<?' then PieceType:= xmlProcessingInstruction;
4: if content.value = '<!--' then PieceType:= xmlComment;
8: if content.value = '<!ENTITY' then PieceType:= xmlEntityDecl;
9: if content.value = '<!ELEMENT' then PieceType:= xmlElementDecl
else if content.value = '<!ATTLIST' then PieceType:= xmlAttributeDecl;
10: if content.value = '<!NOTATION' then PieceType:= xmlNotationDecl;
end;
end;
xmlProcessingInstruction: begin
content.addWideChar(str1);
if str1 = '>' then
if content.value[content.Length-1] = '?' then break;
end;
xmlComment: begin
content.addWideChar(str1);
if str1 = '>' then
if content.value[content.Length-1] = '-' then
if content.value[content.Length-2] = '-' then
if content.length > 6 then break;
end;
xmlEntityDecl,xmlNotationDecl: begin
content.addWideChar(str1);
if (str1 = SingleQuote) and (not DoubleQuoteOpen) then begin
if SingleQuoteOpen
then SingleQuoteOpen:= false
else SingleQuoteOpen:= true;
end else if (str1 = DoubleQuote) and (not SingleQuoteOpen) then begin
if DoubleQuoteOpen
then DoubleQuoteOpen:= false
else DoubleQuoteOpen:= true;
end;
if (not DoubleQuoteOpen)
and (not SingleQuoteOpen)
and (str1 = '>')
then break;
end;
xmlElementDecl,xmlAttributeDecl: begin
content.addWideChar(str1);
if str1 = '>' then break;
end;
end; {case ...}
end; {while ...}
newSourceCodePiece:= TXmlSourceCodePiece.create(PieceType);
newSourceCodePiece.text:= NormalizeLineBreaks(content.value);
Source.Add(newSourceCodePiece);
end; {while ...}
finally
content.free;
end;
end; {with InputSource ...}
end;
procedure TCustomParser.DocSourceCodeToDom(const DocSourceCode: TXmlSourceCode;
const RefNode: TdomNode;
const readonly: boolean);
var
i: integer;
FirstLineNumber,LastLineNumber: integer; {xxx später löschen! xxx}
content: WideString;
LastNode: TdomNode;
begin
FirstLineNumber:= 0;
LastLineNumber:= 0;
FIntSubset:= ''; // Clear buffer storage for internal subset of the DTD
ClearErrorList;
FLineNumber:= 1;
LastNode:= RefNode;
try
for i:= 0 to DocSourceCode.Count -1 do begin
content:= TXmlSourceCodePiece(DocSourceCode[i]).text;
case TXmlSourceCodePiece(DocSourceCode[i]).pieceType of
xmlXmlDeclaration: WriteXmlDeclaration(copy(content,3,length(content)-4),FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlProcessingInstruction: WriteProcessingInstruction(copy(content,3,length(content)-4),FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlCDATA: WriteCDATA(copy(content,10,length(content)-12),FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlPCDATA: WritePCDATA(content,FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlStartTag: LastNode:= WriteStartTag(copy(content,2,length(content)-2),FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlEndTag: begin
if LastNode = RefNode then raise EParserMissingStartTag_Err.create('Missing start tag error.');
WriteEndTag(copy(content,3,length(content)-3),FirstLineNumber,LastLineNumber,LastNode);
LastNode:= LastNode.ParentNode;
end;
xmlEmptyElementTag: WriteStartTag(copy(content,2,length(content)-3),FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlCharRef: WriteCharRef(content,FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlEntityRef: WriteEntityRef(content,FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlComment: WriteComment(copy(content,5,length(content)-7),FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlDoctype: WriteDoctype(content,FirstLineNumber,LastLineNumber,LastNode);
xmlCharacterError: raise EParserInvalidCharacter_Err.create('Invalid character error.');
end; {case}
end; {for ...}
except
on E: EParserException do
begin
FErrorList.Add(TXmlParserError.Create(E.ClassName,LastLineNumber,LastLineNumber,Content,Language));
raise;
end;
end; {try}
end;
procedure TCustomParser.DocStreamToDom(const Stream: TStream;
const RefNode: TdomNode;
const readonly: boolean);
var
DocSourceCode: TXmlSourceCode;
sourceCodeCreated: boolean;
InputSource: TXmlInputSource;
begin
if FUseSpecifiedDocumentSC and assigned(FDocumentSC) then begin
DocSourceCode:= FDocumentSC;
sourceCodeCreated:= false;
end else begin
DocSourceCode:= TXmlSourceCode.create;
sourceCodeCreated:= true;
end;
InputSource:= TXmlInputSource.create(Stream,'','',FDefaultEncoding);
try
DocToXmlSourceCode(InputSource,DocSourceCode);
DocSourceCodeToDom(DocSourceCode,RefNode,readonly);
finally
InputSource.free;
if sourceCodeCreated then begin
DocSourceCode.ClearAndFree;
DocSourceCode.Free;
end;
end; {try}
end;
procedure TCustomParser.DocMemoryToDom(const Ptr: Pointer;
const Size: Longint;
const RefNode: TdomNode;
const readonly: boolean);
var
MStream: TXmlMemoryStream;
begin
if not assigned(RefNode) then exit;
MStream:= TXmlMemoryStream.create;
try
MStream.SetPointer(Ptr,Size);
DocStreamToDom(MStream,RefNode,readonly);
finally
MStream.free;
end; {try}
end;
procedure TCustomParser.DocStringToDom(const Str: string;
const RefNode: TdomNode;
const readonly: boolean);
var
Ptr: PChar;
Size: Longint;
begin
Ptr:= Pointer(Str);
Size:= length(Str);
if Size = 0 then exit;
DocMemoryToDom(Ptr,Size,RefNode,readonly);
end;
procedure TCustomParser.DocWideStringToDom( Str: WideString;
const RefNode: TdomNode;
const readonly: boolean);
var
Ptr: Pointer;
Size: Longint;
begin
if Str = '' then exit;
if Str[1] <> #$feff
then Str:= concat(wideString(#$feff),Str);
Ptr:= Pointer(Str);
Size:= length(Str)*2;
DocMemoryToDom(Ptr,Size,RefNode,readonly);
end;
procedure TCustomParser.ExtDtdSourceCodeToDom(const ExtDtdSourceCode: TXmlSourceCode;
const RefNode: TdomNode;
const readonly: boolean);
var
i: integer;
FirstLineNumber,LastLineNumber: integer; {xxx später löschen! xxx}
content: WideString;
LastNode: TdomNode;
begin
FirstLineNumber:= 0;
LastLineNumber:= 0;
FIntSubset:= ''; // Clear buffer storage for internal subset of the DTD
ClearErrorList;
FLineNumber:= 1;
LastNode:= RefNode;
try
for i:= 0 to ExtDtdSourceCode.Count -1 do begin
content:= TXmlSourceCodePiece(ExtDtdSourceCode[i]).text;
case TXmlSourceCodePiece(ExtDtdSourceCode[i]).pieceType of
xmlTextDeclaration: WriteTextDeclaration(copy(content,3,length(content)-4),FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlProcessingInstruction: WriteProcessingInstruction(copy(content,3,length(content)-4),FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlParameterEntityRef: WriteParameterEntityRef(content,FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlComment: WriteComment(copy(content,5,length(content)-7),FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlEntityDecl: WriteEntityDeclaration(content,FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlElementDecl: WriteElementDeclaration(content,FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlAttributeDecl: WriteAttributeDeclaration(content,FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlNotationDecl: WriteNotationDeclaration(content,FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlCondSection: WriteConditionalSection(content,FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlCharacterError: raise EParserInvalidCharacter_Err.create('Invalid character error.');
end; {case}
end; {for ...}
except
on E: EParserException do
begin
FErrorList.Add(TXmlParserError.Create(E.ClassName,LastLineNumber,LastLineNumber,Content,Language));
raise;
end;
end; {try}
end;
procedure TCustomParser.ExtDtdStreamToDom(const Stream: TStream;
const RefNode: TdomNode;
const readonly: boolean);
var
ExtDtdSourceCode: TXmlSourceCode;
sourceCodeCreated: boolean;
InputSource: TXmlInputSource;
begin
if FUseSpecifiedDocumentSC and assigned(FExternalSubsetSC) then begin
ExtDtdSourceCode:= FExternalSubsetSC;
sourceCodeCreated:= false;
end else begin
ExtDtdSourceCode:= TXmlSourceCode.create;
sourceCodeCreated:= true;
end;
InputSource:= TXmlInputSource.create(Stream,'','',FDefaultEncoding);
try
ExtDtdToXmlSourceCode(InputSource,ExtDtdSourceCode);
ExtDtdSourceCodeToDom(ExtDtdSourceCode,RefNode,readonly);
finally
InputSource.free;
if sourceCodeCreated then begin
ExtDtdSourceCode.ClearAndFree;
ExtDtdSourceCode.Free;
end;
end; {try}
end;
procedure TCustomParser.ExtDtdMemoryToDom(const Ptr: Pointer;
const Size: Longint;
const RefNode: TdomNode;
const readonly: boolean);
var
MStream: TXmlMemoryStream;
begin
if not assigned(RefNode) then exit;
MStream:= TXmlMemoryStream.create;
try
MStream.SetPointer(Ptr,Size);
ExtDtdStreamToDom(MStream,RefNode,readonly);
finally
MStream.free;
end; {try}
end;
procedure TCustomParser.ExtDtdStringToDom(const Str: string;
const RefNode: TdomNode;
const readonly: boolean);
var
Ptr: PChar;
Size: Longint;
begin
if Str = '' then exit;
Ptr:= Pointer(Str);
Size:= length(Str);
ExtDtdMemoryToDom(Ptr,Size,RefNode,readonly);
end;
procedure TCustomParser.ExtDtdWideStringToDom( Str: WideString;
const RefNode: TdomNode;
const readonly: boolean);
var
Ptr: Pointer;
Size: Longint;
begin
if Str = '' then exit;
if Str[1] <> #$feff
then Str:= concat(wideString(#$feff),Str);
Ptr:= Pointer(Str);
Size:= length(Str)*2;
ExtDtdMemoryToDom(Ptr,Size,RefNode,readonly);
end;
procedure TCustomParser.IntDtdSourceCodeToDom(const IntDtdSourceCode: TXmlSourceCode;
const RefNode: TdomNode;
const readonly: boolean);
var
i: integer;
FirstLineNumber,LastLineNumber: integer; {xxx später löschen! xxx}
content: WideString;
LastNode: TdomNode;
begin
FirstLineNumber:= 0;
LastLineNumber:= 0;
FIntSubset:= ''; // Clear buffer storage for internal subset of the DTD
ClearErrorList;
FLineNumber:= 1;
LastNode:= RefNode;
try
for i:= 0 to IntDtdSourceCode.Count -1 do begin
content:= TXmlSourceCodePiece(IntDtdSourceCode[i]).text;
case TXmlSourceCodePiece(IntDtdSourceCode[i]).pieceType of
xmlProcessingInstruction: WriteProcessingInstruction(copy(content,3,length(content)-4),FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlParameterEntityRef: WriteParameterEntityRef(content,FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlComment: WriteComment(copy(content,5,length(content)-7),FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlEntityDecl: WriteEntityDeclaration(content,FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlElementDecl: WriteElementDeclaration(content,FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlAttributeDecl: WriteAttributeDeclaration(content,FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlNotationDecl: WriteNotationDeclaration(content,FirstLineNumber,LastLineNumber,LastNode,readonly);
xmlCharacterError: raise EParserInvalidCharacter_Err.create('Invalid character error.');
end; {case}
end; {for ...}
except
on E: EParserException do
begin
FErrorList.Add(TXmlParserError.Create(E.ClassName,LastLineNumber,LastLineNumber,Content,Language));
raise;
end;
end; {try}
end;
procedure TCustomParser.IntDtdStreamToDom(const Stream: TStream;
const RefNode: TdomNode;
const readonly: boolean);
var
IntDtdSourceCode: TXmlSourceCode;
sourceCodeCreated: boolean;
InputSource: TXmlInputSource;
begin
if FUseSpecifiedDocumentSC and assigned(FInternalSubsetSC) then begin
IntDtdSourceCode:= FInternalSubsetSC;
sourceCodeCreated:= false;
end else begin
IntDtdSourceCode:= TXmlSourceCode.create;
sourceCodeCreated:= true;
end;
InputSource:= TXmlInputSource.create(Stream,'','',FDefaultEncoding);
try
IntDtdToXmlSourceCode(InputSource,IntDtdSourceCode);
IntDtdSourceCodeToDom(IntDtdSourceCode,RefNode,readonly);
finally
InputSource.free;
if sourceCodeCreated then begin
IntDtdSourceCode.ClearAndFree;
IntDtdSourceCode.Free;
end;
end; {try}
end;
procedure TCustomParser.IntDtdMemoryToDom(const Ptr: Pointer;
const Size: Longint;
const RefNode: TdomNode;
const readonly: boolean);
var
MStream: TXmlMemoryStream;
begin
if not assigned(RefNode) then exit;
MStream:= TXmlMemoryStream.create;
try
MStream.SetPointer(Ptr,Size);
IntDtdStreamToDom(MStream,RefNode,readonly);
finally
MStream.free;
end; {try}
end;
procedure TCustomParser.IntDtdStringToDom(const Str: string;
const RefNode: TdomNode;
const readonly: boolean);
var
Ptr: PChar;
Size: Longint;
begin
Ptr:= Pointer(Str);
Size:= length(Str);
if Size = 0 then exit;
IntDtdMemoryToDom(Ptr,Size,RefNode,readonly);
end;
procedure TCustomParser.IntDtdWideStringToDom( Str: WideString;
const RefNode: TdomNode;
const readonly: boolean);
var
Ptr: Pointer;
Size: Longint;
begin
if Str = '' then exit;
if Str[1] <> #$feff
then Str:= concat(wideString(#$feff),Str);
Ptr:= Pointer(Str);
Size:= length(Str)*2;
IntDtdMemoryToDom(Ptr,Size,RefNode,readonly);
end;
// ++++++++++++++++++++++++++++ TXmlToDomParser ++++++++++++++++++++++++
function TXmlToDomParser.FileToDom(const filename: TFileName): TdomDocument;
var
DocSourceCode: TXmlSourceCode;
sourceCodeCreated: boolean;
MStream: TMemoryStream;
ExtDtd,RootName: WideString;
InputSource: TXmlInputSource;
begin
Result:= nil;
InputSource:= nil;
if assigned(FDocumentSC) then FDocumentSC.clearAndFree;
if assigned(FExternalSubsetSC) then FExternalSubsetSC.clearAndFree;
if assigned(FInternalSubsetSC) then FInternalSubsetSC.clearAndFree;
if not assigned(FDOMImpl) then raise EAccessViolation.Create('DOMImplementation not specified.');
if Filename = '' then raise EAccessViolation.Create('Filename not specified.');
MStream:= TMemoryStream.create;
try
MStream.LoadFromFile(Filename);
InputSource:= TXmlInputSource.create(MStream,'','',FDefaultEncoding);
if assigned(FDocumentSC) then begin
DocSourceCode:= FDocumentSC;
sourceCodeCreated:= false;
end else begin
DocSourceCode:= TXmlSourceCode.create;
sourceCodeCreated:= true;
end;
try
DocToXmlSourceCode(InputSource,DocSourceCode);
RootName:= DocSourceCode.NameOfFirstTag;
if not IsXmlName(RootName) then begin
FErrorList.Add(TXmlParserError.Create('EParserRootNotFound_Err',0,0,'',Language));
raise EParserRootNotFound_Err.create('Root not found error.');
end;
Result:= FDomImpl.createDocument(RootName,nil);
Result.Clear; // Delete the dummy node
Result.Filename:= Filename;
try
DocSourceCodeToDom(DocSourceCode,Result,false);
except
DOMImpl.FreeDocument(Result);
raise;
end;
finally
if sourceCodeCreated then begin
DocSourceCode.ClearAndFree;
DocSourceCode.Free;
end;
end; {try}
try
// Parse the DTD:
if assigned(Result.Doctype) then
with Result.Doctype do begin
FEntitiesListing.clear;
IntDtdWideStringToDom(FIntSubset,InternalSubsetNode,false);
if (PublicId <> '') or (SystemId <> '') then begin
if assigned(OnExternalSubset)
then OnExternalSubset(self,PublicId,SystemId,ExtDtd);
ExtDtdWideStringToDom(ExtDtd,ExternalSubsetNode,true);
end; {if ...}
end; {with ...}
except
DOMImpl.FreeDocument(Result);
raise;
end;
finally
InputSource.free;
MStream.free;
end; {try}
end;
end.
|
unit ChainOfResponsibility.Handlers.DogHandler;
interface
uses
ChainOfResponsibility.AbstractClasses.AbstractHandler;
type
TDogHandler = class(TAbstractHandler)
public
function Handle(ARequest: TObject): TObject; override;
end;
implementation
uses
ChainOfResponsibility.Util.StringClass;
{ TDogHandler }
function TDogHandler.Handle(ARequest: TObject): TObject;
begin
if TString(ARequest).Str = 'MeatBall' then
Result := TString.New('Dog: I will eat the ' + TString(ARequest).Str)
else
Result := inherited Handle(ARequest);
end;
end.
|
unit MatriculaGerenciador;
{$MODE OBJFPC}
interface
uses Classes,fgl ,SysUtils,MatriculaModel;
type
TMyList = specialize TFPGObjectList<TMatriculaModel>;
TMatriculaGerenciador = class
public
FLista : TMyList;
ler:string;
public
constructor Create;
destructor Destroy; override;
procedure gerenciar;
procedure cadastrar;
procedure listar;
procedure editar;
procedure excluir;
end;
implementation
constructor TMatriculaGerenciador.Create;
begin
inherited Create;
FLista := TMyList.Create;
end;
procedure TMatriculaGerenciador.excluir;
var codigo:integer;
var index:integer;
var encontrou:boolean;
begin
try
Writeln('Digite o codigo da Matricula que deseja deletar');
Readln(codigo);
encontrou:=False;
for index:=0 to FLista.Count-1 do
begin
if(FLista.Items[index].FCodigo = codigo) then
begin
FLista.Delete(index);
encontrou := True;
end;
end;
if(encontrou = True) then
begin
WriteLn('Matricula excluida com sucesso');
end
else WriteLn('Nao foi encontrada uma Matricula com o codigo especificado');
finally
end;
end;
destructor TMatriculaGerenciador.Destroy;
begin
FLista.Free;
inherited Destroy;
end;
procedure TMatriculaGerenciador.editar;
var codigo:integer;
var index:integer;
var encontrou:boolean;
begin
try
Writeln('Digite o codigo da Matricula que deseja editar');
Readln(codigo);
encontrou:=False;
for index:=0 to FLista.Count-1 do
begin
if(FLista.Items[index].FCodigo = codigo) then
begin
WriteLn('Digite o novo codigo da Matricula');
Readln(FLista.Items[index].FCodigo);
WriteLn('Digite o novo nome do Aluno');
Readln(FLista.Items[index].alun.FNome);
WriteLn('Digite a novo periodo');
Readln(FLista.Items[index].FPeriodo);
encontrou := True;
end;
end;
if(encontrou = True) then
begin
WriteLn('Matricula atualizada com sucesso');
end
else WriteLn('Nao foi encontrada uma Matricula com o codigo especificado');
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end;
procedure TMatriculaGerenciador.gerenciar;
var opcao:integer;
begin
repeat
Writeln('Escolha uma opção');
Writeln('1 - Cadastrar Matricula');
Writeln('2 - Listar Matriculas');
Writeln('3 - Editar Matriculas');
Writeln('4 - Excluir Matriculas');
Writeln('0 - Sair');
Readln(opcao);
case opcao of
1:cadastrar;
2:listar;
3:editar;
4:excluir;
end;
until opcao = 0;
end;
procedure TMatriculaGerenciador.cadastrar;
var tempModel : TMatriculaModel;
begin
try
tempModel := TMatriculaModel.Create;
WriteLn('Digite o codigo da Matricula');
Readln(tempModel.FCodigo);
WriteLn('Digite o nome do Aluno');
Readln(tempModel.alun.FNome);
WriteLn('Digite o periodo');
Readln(tempModel.FPeriodo);
//adicionar na lista
FLista.Add(tempModel);
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end;
procedure TMatriculaGerenciador.listar;
var temp : TMatriculaModel;
begin
Writeln('Lista de Matriculas Cadastradas:');
for temp in FLista do
begin
Writeln('----------------------');
Writeln('C�digo: ',temp.getFCodigo);
Writeln('Nome: ',temp.alun.getFNome);
Writeln('Periodo: ',temp.getFPeriodo);
Writeln('----------------------');
end;
end;
end.
|
unit WvN.Pascal.CReader;
interface
uses
Windows,
WvN.Pascal.Model, System.Threading;
type
TOnProgress = reference to procedure(progress:double;const text:string);
function c_FunctionToPas(const aUnit:TPascalUnit; const c:string;var aRoutine:TRoutine):boolean;
procedure c_to_pas(const aCCode:string; var t:string;aName:string;aOnProgress:TOnProgress; var result:TPascalUnit);
function FixComments(const aCCode:string):string;
implementation
uses
IoUTils,
SysUtils,
System.RegularExpressions,
Classes;
const
PARSED_MARKER = ' ';
PARSED_MARKER_STR = PARSED_MARKER+PARSED_MARKER+PARSED_MARKER;
const
NonFunctions:array[0..12] of string = ('if','enum','struct','for','else','while','switch','case','class','namespace','do','const','delete');
type
TConversionRec = record
C:string;
Pascal:string;
end;
const
FundamentalTypes : array[0..45] of TConversionRec = (
(C:'int' ; Pascal:'Integer'),
(C:'short' ; Pascal:'Byte'),
(C:'char' ; Pascal:'Byte'),
(C:'float' ; Pascal:'Single'),
(C:'double' ; Pascal:'Double'),
(C:'unsigned char' ; Pascal:'Byte'),
(C:'signed char' ; Pascal:'ShortInt'),
(C:'unsigned short'; Pascal:'UInt16'),
(C:'signed short' ; Pascal:'Int16'),
(C:'signed long' ; Pascal:'Int32'),
(C:'unsigned long' ; Pascal:'UInt32'),
(C:'uint' ; Pascal:'Cardinal'),
(C:'signed int' ; Pascal:'Int32'),
(C:'unsigned int' ; Pascal:'UInt32'),
(C:'uint8' ; Pascal:'Byte'),
(C:'uint16' ; Pascal:'UInt16'),
(C:'uint32' ; Pascal:'UInt32'),
(C:'uint64' ; Pascal:'UInt64'),
(C:'int8' ; Pascal:'Shortint'),
(C:'int16' ; Pascal:'Int16'),
(C:'int32' ; Pascal:'Integer'),
(C:'int64' ; Pascal:'Int64'),
(C:'uint8_t' ; Pascal:'Byte'),
(C:'uint16_t' ; Pascal:'Uint16'),
(C:'uint32_t' ; Pascal:'Uint32'),
(C:'uint64_t' ; Pascal:'Uint64'),
(C:'int8_t' ; Pascal:'Shortint'),
(C:'int16_t' ; Pascal:'Int16'),
(C:'int32_t' ; Pascal:'Integer'),
(C:'int64_t' ; Pascal:'Int64'),
(C:'long long' ; Pascal:'Int64'),
(C:'unsigned long long'; Pascal:'UInt64'),
(C:'long int' ; Pascal:'LongInt'),
(C:'long double' ; Pascal:'Extended'),
(C:'__int64' ; Pascal:'Int64'),
(C:'void' ; Pascal:''),
(C:'void*' ; Pascal:'Pointer'),
(C:'char*' ; Pascal:'PAnsiChar'),
(C:'char *' ; Pascal:'PAnsiChar'),
(C:'wchar_t' ; Pascal:'WideChar'),
(C:'wchar_t*' ; Pascal:'PWideChar'),
(C:'wchar_t *' ; Pascal:'PWideChar'),
(C:'BOOL' ; Pascal:'Boolean'),
(C:'UBYTE' ; Pascal:'Byte'),
(C:'UWORD' ; Pascal:'Word'),
(C:'ULONG' ; Pascal:'Cardinal')
);
const
rxID = '[a-zA-Z_\$][\w_]*(\s*\*)?';
rxT = '(\*\s*)?(static\s+)?(unsigned\s+|signed\s+)?(long\s+)?[a-zA-Z_\$][\w_\<\>]*\s*(\*\s*)?';
rxType = rxT;
rxMultiLinecomment = '(?<comment>\s*)?';
rxStringLiteral = '[a-zA-Z_]?\"(\\.|[^\\"\n])*\"';
rxHexadecimal = '0[xX]([a-fA-F0-9]+)((u|U)|((u|U)?(l|L|ll|LL))|((l|L|ll|LL)(u|U)))?';
rxNum = '(?:[^a-zA-Z])[\+\-]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?';
rxChar = 'L?\''([^\\n]|(\(.|\n)))*?\''';
rxMethodDef=
'^'+ // only do this trick from the start.. otherwise we might accidently match somewhere else
rxMultiLineComment+ // preserve multiline comments..
'(?<comment3>(\/\/([^\n]*)\n)*)?'+ // preserve single line comments
'(?:\s*)' + // to preseve indents of original code
'(?<template>template\s*\<typename \w+\>\s*)?'+ // template
'(?<auto>(auto))?'+
'(?<static>(const|static|auto|extern|register|Static|local|LOCAL))?' + // text 'static' or 'local'
'\s*'+
'(?<inline>inline)?' + // text 'inline'
'((?<virtual>virtual)\s+)?'+
'\s*'+
'(?<returntype>'+rxType+')' + // constructors don't have a return type
'\s+'+
// some special modifiers.. not sure how to convert this to Delphi though, so let's leave those for now
'((?<pascal>__pascal)\s+)?'+
'((?<fastcall>__fastcall)\s+)?'+
'((?<classname>'+rxID+')\:\:)?'+ // support classname::method() kind of signature
'(?<destructor>\~)?'+ // constructor looks like MyClass::~MyClass()
'(?<funcname>'+rxID+')\s*'+ // the function name itself
'('+ // parameters are not always provided, so the whole parameter section including the brackets is optional
'\(\s*(?<parameters>[^\)]*?)\s*\)'+
')?'+
'\s*'+
'(?<comment2>\/\*[^*]*\*\/)?'+ // preserve comments
'\s*';
rxMethodHeader=rxMethodDef + '\{';
rxMethod = rxMethodHeader + '(?<code>.*)?\}';
rxClassDef = '^(?<indent>\s*)class\s+(?<classname>'+rxId+')\s*\:?\s*(?<public>public)?\s*(?<parentclass>'+rxType+')?\s*\{';
type
TLoc=(None,InStringQ1,InStringQ2,InLineComment,InMultiLineComment);
function IsFunction(const aCCode:string):boolean;
var s:string;
begin
for s in NonFunctions do
if aCCode.StartsWith(s) then
Exit(False);
Result := True;
end;
procedure ReplaceMatch(const c: string; const m: TMatch; aReplace: Char);
begin
c.Remove(m.Index, m.Length);
c.Insert(m.Index, StringOfChar(aReplace, m.Length));
end;
function Clear(const aCCode, aSearch:string; aReplace:char):string;
var m:TMatch;c:string;
begin
c := aCCode;
for m in TRegEx.Matches(aCCode, aSearch) do
ReplaceMatch(c, m, aReplace);
Result := c;
end;
function ClearComments(const aCCode:string):string;
begin
Result := Clear(aCCode,rxMultiLinecomment,' ')
end;
function FixComments(const aCCode:string):string;
var
loc:TLoc;
line:string;
l,i: Integer;
IsFirstMulti: Boolean;
sl:TStringList;
begin
Loc := None;
IsFirstMulti := True;
sl := TStringList.Create;
sl.Text := aCCode;
for l := 0 to sl.Count-1 do
begin
line := sl[l];
for I := 1 to line.Length do
begin
case loc of
None: begin
if line[I]='''' then Loc := InStringQ1;
if line[I]='"' then Loc := InStringQ2;
if I < line.Length-1 then
if line[I] = '/' then
if line[I + 1] = '/' then
Loc := InLineComment;
if I < line.Length-1 then
if line[I] = '/' then
if line[I + 1] = '*' then
begin
Loc := InMultiLineComment;
line[I+1] := '/';
sl[l] := line;
IsFirstMulti := True;
end;
end;
InStringQ1 : if (I>1) and (line[I-1]<>'\') and (line[I]='''') then Loc := None;
InStringQ2 : if (I>1) and (line[I-1]<>'\') and (line[I]='"' ) then Loc := None;
InMultiLineComment: if (I>1) and (line[I-1] = '*') and (line[I]='/' ) then
begin
Delete(line,i-1,2);
// we're turning multi-line comments into // comments.
// that means that we need to move content behind it to
// the next line.
Insert('//@@@@@@@@',line,i-1);
sl[l] := line;
loc := None;
end;
end;
end;
case loc of
InStringQ1 : Loc := None;
InStringQ2 : Loc := None;
InLineComment: Loc := None;
InMultiLineComment :
begin
if not IsFirstMulti then
sl[l] := '//' + sl[l] ;
IsFirstMulti := False;
end;
end;
end;
Result := sl.Text.Replace('@@@@@@@@','');
sl.Free;
end;
function StripComments(const aCCode:string):string;
var
loc:TLoc;
i,j: Integer;
begin
Loc := None;
setlength(result,length(aCCode));
I := 1; J:=1;
while I<=aCCode.length do
begin
case loc of
None:
begin
if I < aCCode.Length-1 then
if aCCode[I] = '/' then
if aCCode[I + 1] = '/' then
Loc := InLineComment;
if I < aCCode.Length then
if aCCode[I] = '/' then
if aCCode[I + 1] = '*' then
Loc := InMultiLineComment;
end;
InLineComment:
if CharInSet(aCCode[I], [#13, #10]) then
Loc := None;
InMultiLineComment:
if I > 1 then
if aCCode[I - 1] = '*' then
if aCCode[I] = '/' then
loc := None;
end;
if loc = None then
begin
Result[J] := aCCode[I];
Inc(J);
end;
inc(I);
end;
Setlength(Result,J);
end;
function ReplaceOutsideCommentsAndStrings(aCCode,aSearch,aReplace:string):string;
var
loc:TLoc;
i,j: Integer;
found: Boolean;
begin
Loc := None;
I := 1;
while I<=aCCode.length do
begin
case loc of
None:
begin
if aCCode[I]='''' then
Loc := InStringQ1;
if aCCode[I]='"' then
Loc := InStringQ2;
if I < aCCode.Length-1 then
if aCCode[I] = '/' then
if aCCode[I + 1] = '/' then
Loc := InLineComment;
if I < aCCode.Length then
if aCCode[I] = '/' then
if aCCode[I + 1] = '*' then
Loc := InMultiLineComment;
end;
InStringQ1:
if I>1 then
if aCCode[I]='''' then
if aCCode[I-1]<>'\' then
Loc := None;
InStringQ2:
if I>1 then
if aCCode[I]='"' then
if aCCode[I-1]<>'\' then
Loc := TLoc.None;
InLineComment:
if CharInSet(aCCode[I], [#13, #10]) then
Loc := None;
InMultiLineComment:
if I > 1 then
if aCCode[I - 1] = '*' then
if aCCode[I] = '/' then
loc := None;
end;
if loc = None then
begin
found := true;
if i+aSearch.Length-1<=length(ACCode) then
begin
for j := 1 to length(aSearch) do
begin
if aCCode[j+i-1]<>aSearch[J] then
begin
found:=False;
break;
end;
end;
end
else
found := false;
if found then
begin
Result := Result + aReplace;
inc(I,length(aSearch));
Continue;
end
end;
Result := Result + aCCode[I];
inc(I);
end;
end;
procedure ScanUntilMatchingChar(c1: Char; c2: Char; const aCCode: string; var Res: string);overload;
var
loc:TLoc;
level: Integer;
i: Integer;
begin
level := 1;
Loc := None;
for I := 1 to aCCode.Length do
begin
case loc of
None:
begin
if aCCode[I]='''' then
Loc := InStringQ1;
if aCCode[I]='"' then
Loc := InStringQ2;
if I < aCCode.Length-1 then
if aCCode[I] = '/' then
if aCCode[I + 1] = '/' then
Loc := InLineComment;
if I < aCCode.Length then
if aCCode[I] = '/' then
if aCCode[I + 1] = '*' then
Loc := InMultiLineComment;
end;
InStringQ1:
if I>1 then
if aCCode[I]='''' then
if aCCode[I-1]<>'\' then
Loc := None;
InStringQ2:
if I>1 then
if aCCode[I]='"' then
if aCCode[I-1]<>'\' then
Loc := TLoc.None;
InLineComment:
if CharInSet(aCCode[I], [#13, #10]) then
Loc := None;
InMultiLineComment:
if I > 1 then
if aCCode[I - 1] = '*' then
if aCCode[I] = '/' then
loc := None;
end;
if Loc=none then
begin
if aCCode[I] = c1 then
inc(level);
if aCCode[I] = c2 then
dec(level);
if level = 0 then
begin
// ok, we're back at level 0, so we've found the closing bracket.
Res := trim(copy(aCCode, 0, 2 + I - length(aCCode)));
Break;
end;
end;
end;
end;
procedure ScanUntilMatchingChar(c1: Char; c2: Char; const aCCode: string; aMatch: TMatch; var Res: string);overload;
var
loc:TLoc;
level: Integer;
i: Integer;
begin
level := 0;
Loc := None;
I := aMatch.Index + aMatch.Length - 1;
while I<=aCCode.length do
begin
case loc of
None:
begin
if aCCode[I]='''' then
Loc := InStringQ1;
if aCCode[I]='"' then
Loc := InStringQ2;
if I < aCCode.Length-1 then
if aCCode[I] = '/' then
if aCCode[I + 1] = '/' then
Loc := InLineComment;
if I < aCCode.Length then
if aCCode[I] = '/' then
if aCCode[I + 1] = '*' then
Loc := InMultiLineComment;
end;
InStringQ1:
if I>1 then
if aCCode[I]='''' then
if aCCode[I-1]<>'\' then
Loc := None;
InStringQ2:
if I>1 then
if aCCode[I]='"' then
if aCCode[I-1]<>'\' then
Loc := TLoc.None;
InLineComment:
if CharInSet(aCCode[I], [#13, #10]) then
Loc := None;
InMultiLineComment:
if I > 1 then
if aCCode[I - 1] = '*' then
if aCCode[I] = '/' then
loc := None;
end;
if Loc=none then
begin
if aCCode[I] = c1 then
inc(level);
if aCCode[I] = c2 then
dec(level);
if level = 0 then
begin
// ok, we're back at level 0, so we've found the closing bracket.
Res := trim(copy(aCCode, aMatch.Index, 2 + I - aMatch.Index));
Break;
end;
end;
inc(I);
end;
end;
function RemoveRoutines(const c:string;aOnProgress:TOnProgress=nil):string;
var
m: TMatch;
mc:TMatchCollection;
n: Integer;
Routine: string;
rt:TRoutine;
Newcode:string;
u:TPascalUnit;
const
minv = 0.8;
scale = 0.4;
begin
// search for functions by pattern..
NewCode := c;
mc := TRegEx.Matches(NewCode, '^(?<indent>\s*)(static\s+)?(inline\s+)?(?<return_type>'+rxId+')\s*(?<classname>'+rxID+'::)?(?<funcname>'+rxID+')\s*\(\s*(?<params>[^\)]*)\s*\)[^{|^;]*\{' ,
[roMultiLine]);
u := TPascalUnit.Create(nil);
try
for n := mc.Count-1 downto 0 do
begin
m := mc[n];
// sometimes we accidentially ran into somethign that looks like a function
if not IsFunction(m.Value.Trim) then
Continue;
// we've found a function signature.
// now let's scan until we've found the final closing bracket
// there can be nested brackets
Routine := '';
ScanUntilMatchingChar('{','}',c,m,Routine);
if Routine<>'' then
begin
if c_FunctionToPas(u ,Routine,rt) then
begin
try
if rt <> nil then
Delete(NewCode, m.Index, length(Routine));
if Assigned(aOnProgress) then
if rt<>nil then
aOnProgress(minv+scale*n/mc.count,rt.Name);
finally
// rt.Free;
end;
end;
end;
end;
Result := NewCode;
finally
u.Free;
end;
end;
function RemoveStructs(const c:string):string;
var
m: TMatch;
mc:TMatchCollection;
n: Integer;
aRoutine: string;
Newcode:string;
begin
// search for functions by pattern..
NewCode := c;
mc := TRegEx.Matches(NewCode, 'struct\s+(?<packed>PACKED)?\s*(?<name>'+rxId+')[^{]*\{' , [roMultiLine]);
for n := mc.Count-1 downto 0 do
begin
m := mc[n];
// we've found a function signature.
// now let's scan until we've found the final closing bracket
// there can be nested brackets
aRoutine := '';
ScanUntilMatchingChar('{','}',c,m,aRoutine);
if aRoutine<>'' then
Delete(NewCode, m.Index, length(aRoutine));
end;
Result := NewCode;
end;
function convertType(const s:string):string;
var
I: Integer;
begin
// let's rule out the most common ones first
for I := 0 to high(FundamentalTypes) do
if SameText(S, FundamentalTypes[I].C) then
begin
Result := FundamentalTypes[I].Pascal;
Exit;
end;
Result := esc(S);
end;
procedure setV(var s:string;const m:TMatch;const v:string);
begin
s := s.Replace('<' + v + '>', m.Groups[v].Value);
end;
function FixTernary(const c:string):string;
var m:TMatch;s:string;
begin
Result := '';
// fix ternary if
for m in TRegEx.Matches(c, '(?<pre>)(?<condition>\w+\s*[\>\<=!\/\*\+\-]\s*\w+)\s*\?\s*(?<if_true>.*):\s*(?<if_false>[^\)])([\)]?)(?<post>)',[ roSingleLine ]) do
begin
s := '<pre>ifthen(<condition> , <if_true> , <if_false>)<post>';
setV(s,m,'pre');
setV(s,m,'post');
setV(s,m,'condition');
setV(s,m,'if_true');
setV(s,m,'if_false');
Result := Result + s;
end;
if Result='' then
Result := c;
end;
procedure FindDefines(const Defines:TStringList; const c:string);
var m:TMatch; d,s:string; i:integer; sl:TStringList;
begin
Defines.Clear;
sl := TStringList.Create;
try
sl.Text := StripComments(c);;
for i := 0 to sl.Count-1 do
begin
s := sl[i].Trim;
m := TRegEx.Match(s,'^(\s*)\#define\s+(?<def>'+rxID+')\s*$' ,[ roMultiLine ]);
if m.Success then
begin
d := m.Groups['def'].Value;
Defines.Add( d );
end;
end;
finally
sl.Free
end;
end;
type
TMacro=record
Identifier:string;
Parameters,Replacements:TArray<string>;
end;
function ApplyMacro(const aCCode:string; const aMacro:TMacro):string;
var
loc:TLoc;
i,j: Integer;
begin
if Length(aMacro.Replacements)<1 then
Exit(aCCode);
Result := ReplaceOutsideCommentsAndStrings(aCCode,aMacro.Identifier, aMacro.Replacements[0]);
Exit;
Loc := None;
I := 0;
J := 1;
while I<=aCCode.length do
begin
case loc of
None:
begin
if aCCode[I]='''' then
Loc := InStringQ1;
if aCCode[I]='"' then
Loc := InStringQ2;
if I < aCCode.Length-1 then
if aCCode[I] = '/' then
if aCCode[I + 1] = '/' then
Loc := InLineComment;
if I < aCCode.Length then
if aCCode[I] = '/' then
if aCCode[I + 1] = '*' then
Loc := InMultiLineComment;
end;
InStringQ1:
if I>1 then
if aCCode[I]='''' then
if aCCode[I-1]<>'\' then
Loc := None;
InStringQ2:
if I>1 then
if aCCode[I]='"' then
if aCCode[I-1]<>'\' then
Loc := None;
InLineComment:
if CharInSet(aCCode[I], [#13, #10]) then
Loc := None;
InMultiLineComment:
if I > 1 then
if aCCode[I - 1] = '*' then
if aCCode[I] = '/' then
loc := None;
end;
if Loc=none then
begin
// increase J if we found a match
if aCCode[I] = aMacro.Identifier[J+1] then
inc(J)
else
J := 0;
if J>=aMacro.Identifier.Length then
begin
// found identifier!
// ReplaceOutsideCommentsAndStrings()
end;
end
else
j := 0;
inc(I);
end;
end;
function c_inlinevardef(const c:string;out pas:string):boolean;
var m: TMatch;
begin
pas := '';
Result := false;
if c='' then
begin
pas := '';
Exit(False)
end;
if c.Trim.StartsWith('return') then
Exit;
// "int test = 5 * 5 + xxx;"
// varname : test
// vartype : int
// expr : 5 * 5 + xxx
m := TRegEx.Match(c,'^(?<indent>\s*)(?<vartype>'+rxType+')\s+(\*)?(?<varname>'+rxID+')\s*=\s*(?<expr>.*)\s*;',[roSingleLine]);
if m.Success then
begin
Result := True;
pas := '<indent><varname> := <expr>;';
setV(pas,m,'indent');
setV(pas,m,'varname');
setV(pas,m,'vartype');
setV(pas,m,'expr');
Exit;
end;
// char dest[20]="Hello";
m := TRegEx.Match(c,'^(?<indent>\s*)char\s+(?<varname>'+rxID+')\s*\[\s*(?<arraysize>[^\]^\s]+)\s*\]\s*=\s*(?<expr>[^;]*)\s*;',[roSingleLine]);
if m.Success then
begin
Result := True;
pas := '<indent><varname> := <expr>;';
setV(pas,m,'indent');
setV(pas,m,'varname');
setV(pas,m,'expr');
// if m.Groups['comment'].Value<>'' then
// pas := pas + ' // '+ m.Groups['comment'].Value;
Exit;
end;
// int var[4] = xx; // foo
m := TRegEx.Match(c,'^(?<indent>\s*)((?<vartype>\w*)\s+)?(?<varname>'+rxID+')\s*\[\s*(?<arraysize>[^\]^\s]+)\s*\]\s*=\s*(?<expr>[^;]+)\s*;\s*(?<comment>\/\*.*\*\/)?',[roSingleLine]);
if m.Success then
begin
Result := True;
pas := '<indent><varname>[<arraysize>] := <expr>;';
setV(pas,m,'indent');
setV(pas,m,'varname');
setV(pas,m,'arraysize');
setV(pas,m,'expr');
// if m.Groups['comment'].Value<>'' then
// pas := pas + ' // '+ m.Groups['comment'].Value;
Exit;
end;
// type dest[20]="Hello";
m := TRegEx.Match(c,'^(?<indent>\s*)((?<vartype>\w*)\s+)?(?<varname>'+rxID+')\s*\[\s*(?<arraysize>[^\]^\s]+)\s*\]\s*=\s*(?<expr>[^;]*)\s*;',[roSingleLine]);
if m.Success then
begin
Result := True;
pas := '<indent><varname>[<arraysize>] := <expr>;';
setV(pas,m,'indent');
setV(pas,m,'varname');
setV(pas,m,'arraysize');
setV(pas,m,'expr');
// if m.Groups['comment'].Value<>'' then
// pas := pas + ' // '+ m.Groups['comment'].Value;
Exit;
end;
// "int test;"
// "int *test;"
// vartype : int
// varname : test
m := TRegEx.Match(c,'^(?<indent>\s*)(?<vartype>'+rxType+')\s+[\*]?(?<varname>'+rxID+')\s*;',[roSingleLine]);
if m.Success then
begin
pas := '';
if m.Groups['vartype'].Value='return' then
Exit;
Exit(true);
end;
// "int test[4];"
// vartype : int
// varname : test
// arraysize : 4
m := TRegEx.Match(c,'(?<indent>\s*)(?<vartype>'+rxType+')\s+(?<varname>'+rxID+')\s*\[\s*(?<arraysize>[^\]]*)\s*\]\s*;',[roSingleLine]);
if m.Success then
begin
pas := '';
Exit(true);
end;
// const int base = 4344
m := TRegEx.Match(c, '^\s*(?<const>const)\s+(struct\s+)?(?<vartype>' + rxType + ')\s+(?<varname>' + rxID + ')\s*=\s*(?<expression>.*)\s*;\s*$');
if m.Success then
begin
pas := '';
Exit(true);
end;
// const int base = 4344
m := TRegEx.Match(c, '^\s*(?<const>const)\s+(struct\s+)?(?<vartype>' + rxType + ')\s+(?<varname>' + rxID + ')\s*=\s*(?<expression>.*)\s*;\s*\/\/(?<comment>.*)$');
if m.Success then
begin
pas := '';
Exit(true);
end;
// UBYTE a,b,inst,note,eff,dat;
m := TRegEx.Match(c,'^(?<indent>\s*)(?<vartype>'+rxType+')\s+(?<vars>(('+rxID+')\s*\,\s*)+\s*(?<varname>'+rxID+'))\s*;',[roSingleLine]);
if m.Success then
begin
pas := '';
Exit(true);
end;
// int i, test=0;
// output:
// test := 0;
m := TRegEx.Match(c,'^(?<indent>\s*)(?<vartype>'+rxType+')\s+(?<vars>(('+rxID+')\s*\,\s*)+\s*(?<varname>'+rxID+'))\s*(=\s*(?<expr>[^;]*));',[roSingleLine]);
if m.Success then
begin
pas := '<indent><varname> := <expr>;';
setV(pas,m,'indent');
setV(pas,m,'varname');
setV(pas,m,'vartype');
setV(pas,m,'expr');
Exit(true);
end;
end;
procedure DeleteArrayIndex(var X: TArray<string>; Index: Integer);
begin
if Index > High(X) then Exit;
if Index < Low(X) then Exit;
if Index = High(X) then
begin
SetLength(X, Length(X) - 1);
Exit;
end;
Finalize(X[Index]);
System.Move(X[Index +1], X[Index],
(Length(X) - Index -1) * SizeOf(string) + 1);
SetLength(X, Length(X) - 1);
end;
procedure FixTypeCasts(var Result: string);
begin
// remove unnecessary casts:
// convert float(123)
// to 123
Result := TRegEx.Replace(Result, 'float\s*\(\s*(?<val>' + rxNum + ')\s*\)', '\1');
// convert float(varname)
// to varname
Result := TRegEx.Replace(Result, 'float\s*\(\s*(?<val>' + rxID + ')\s*\)', '\1');
// convert float(<expression>)
// to (<expression>)
Result := TRegEx.Replace(Result, 'float\s*\(\s*(?<val>[^)]*)\s*\)', '(\1)');
end;
procedure FixSwitchCaseStatementsSimple(var Result: string);
begin
// old method, based on search/replacing switch and case stuff..
// didn't find errors with this approach, but it doesn't finish the job:
// - it doesn't remove break statements,
// - it won't enclose multiple statements into code blocks
// convert case XXX :
// to XXX:
Result := TRegEx.Replace(Result, '^(\s*)case\s*(?<val>[^\:]*)\s*:', '\1\2: ', [roMultiLine]);
// convert switch( expression )
// to case expression do
Result := TRegEx.Replace(Result, '^(\s*)switch\s*\((?<cond>[^)]*)\s*\)\s*{', '\1case \2 of', [roMultiLine]);
// convert default: command = 0;
// to else command = 0;
Result := TRegEx.Replace(Result, '^(\s*)default\s*\:', '\1else', [roMultiLine]);
end;
procedure FixCaseStatementsFull(const c:TCode; var aAllCCode: string);
var
matchSwitch,
matchCase : TMatch;
SwitchStatementStr, ex, cond: string;
cs : TSwitch;
cc : TCase;
begin
// new method, with more detailed interpretation:
repeat
// matchSwitch := TRegEx.Match(aAllCCode, '^(?<indent>\s*)switch\s*\((?<cond>.*)\s*\)\s*\{', [roMultiLine]);
matchSwitch := TRegEx.Match(aAllCCode, '^(?<indent>\s*)switch\s*\(', [roMultiLine]);
if not matchSwitch.Success then
Break;
cs := TSwitch.Create(c);
cs.Indent := length(matchSwitch.Groups['indent'].Value.Replace(sLineBreak,''));
// cs.Switch := matchSwitch.Groups['cond'].Value;
ScanUntilMatchingChar('(',')', aAllCCode, matchSwitch, cond);
delete(cond,high(cond),1);
cs.Switch := cond.Substring(cond.IndexOf('(')+1) ;
ScanUntilMatchingChar('{', '}', aAllCCode, matchSwitch, SwitchStatementStr);
SwitchStatementStr := Copy(aAllCCode, matchSwitch.Length+ matchSwitch.index, Pos('}',aAllCCode,matchSwitch.Index) - (matchSwitch.Length+ matchSwitch.index));
cs.Name := cs.Switch.Trim;
cs.Sourceinfo.Position := matchSwitch.Index;
cs.Sourceinfo.Length := SwitchStatementStr.Length;
for matchCase in TRegEx.Matches(SwitchStatementStr, '(case\s+(?<case>[_\w\'']+))?(default)?\s*:\s*(?<code>.+?)(?=break|case|default)', [roSingleLine]) do
begin
cc := TCase.Create(cs);
cc.Sourceinfo.Position := cs.Sourceinfo.Position + matchCase.Index;
cc.Sourceinfo.Length := matchCase.Value.Length;
cc.Id := matchCase.Groups['case'].Value;
if cc.Id = '' then
cc.Id := 'else';
cc.Name := cc.Id;
cc.Code := TCode.Create(cc,matchCase.Groups['code'].Value.Trim.Split([';']) );
cs.Cases := cs.Cases + [cc];
end;
ex := copy(SwitchStatementStr, matchCase.index + matchCase.length, Maxint).Trim;
if ex.startsWith(';') then ex := ex.Substring(2).trim;
if ex.startsWith('break;') then ex := ex.Substring(6).trim;
ex := ex.trim;
if ex<>'' then
begin
matchCase := TRegEx.Match(ex, '(case\s+(?<case>[_\w\'']+))?(default)?\s*:\s*(?<code>[^}]*)', [roSingleLine]);
if matchCase.Success then
begin
cc := TCase.Create(cs);
cc.Id := matchCase.Groups['case'].Value;
if cc.Id = '' then
cc.Id := 'else';
cc.Name := 'case_'+cc.Id;
cc.Code := TCode.Create(cc,matchCase.Groups['code'].Value.Trim.Split([';']));
cs.Cases := cs.Cases + [cc];
end;
end;
cs.Renderinfo.Position := matchSwitch.Index+1;
Delete(aAllCCode, matchSwitch.Index+1, SwitchStatementStr.Length+4);
Insert(cs.ToPascal, aAllCCode, matchSwitch.Index);
cs.Renderinfo.Length := aAllCCode.Length - cs.Renderinfo.Position-1;
until not matchSwitch.Success;
end;
procedure ReplaceFunctionName(var aCCode:string; aFunctionName,aReplacementName:string );
begin
aCCode := TRegEx.Replace(aCCode,aFunctionName+'\s*\(\s*([^\)]*)\s*\)',aReplacementName+'(\1)',[ roMultiLine ]);
end;
function ConvertForLoop(var l: string; m: TMatch):string;
var
loop: TLoop;
Local_m: TMatch;
begin
// convert for-loop
for Local_m in TRegEx.Matches(l, '^(?<indent>\s*)' + 'for\s*\(\s*' + '(?<vartype>int(?:\s+))?' + '(?<varname>\w+)' + '\s*\=\s*' + '(?<min>[^\;]*)' + '\s*;\s*' + '(?<varname2>\w+)' + '\s*' + '(?<op><[\=]{0,1})' + '\s*' + '(?<max>.*)' + '\s*\;\s*' + '(?<varname3>' + '\w+\+\+|' + '\w+\-\-|' + '\+\+\w+|' + '\-\-\w+)' + '\s*\)\s*' + '(?<code>.*)', [roSingleLine]) do
begin
loop := TLoop.Create(nil);
try
loop.IndexerVar := TVariable.Create(loop, Local_m.Groups['varname'].Value, ConvertType(Local_m.Groups['vartype'].Value));
loop.StartVal := Local_m.Groups['min'].Value;
loop.EndVal := Local_m.Groups['max'].Value;
if loop.StartVal > loop.EndVal then
loop.Dir := down
else
loop.Dir := up;
if Local_m.Groups['varname3'].Value.Contains('--') then
loop.Dir := down;
if Local_m.Groups['op'].Value = '<' then
loop.Op := LT;
if Local_m.Groups['op'].Value = '>' then
loop.Op := GT;
if Local_m.Groups['op'].Value = '>=' then
loop.Op := GT_EQ;
if Local_m.Groups['op'].Value = '<=' then
loop.Op := LT_EQ;
if Local_m.Groups['op'].Value = '==' then
loop.Op := EQ;
l := Local_m.Groups['indent'].Value + loop.toPascal + ' ' + Local_m.Groups['code'].Value;
finally
loop.Free;
end;
end;
end;
procedure ConvertCLinesToPas(const code:TCode);
var m:TMatch; l:string;
c,I: Integer;
s,ps,tmp: string;
linesAr:TArray<string>;
expr: string;
Result:string;
begin
c := 0;
// replace lines that contain a variable declaration.
// when it also contains an assignment, leave the assignment,
// otherwise remove the line
setlength(linesAr,code.lines.count);
for I := 0 to code.lines.Count-1 do
begin
if not c_inlinevardef(code.lines[I],ps) then
begin
linesAr[c] := code.lines[I];
inc(c);
end
else
begin
if ps<>'' then
begin
linesAr[c] := ps;
inc(c);
end;
end;
end;
// strip emtpy lines at then end
i := length(linesAr)-1;
while (i>=0) and (linesAr[i].Trim='') do
begin
setlength(linesAr,i);
dec(i);
end;
setlength(linesAr,c);
code.lines.Clear;
code.lines.InsertRange(0,linesAr);
if code.Lines.Count > 0 then
begin
l := code.Lines[code.Lines.Count-1];
code.lines[code.Lines.Count-1] := TRegEx.Replace(l,'^(\s*)return\s*;\s*','\1Exit;',[roSingleLine]) ;
l := code.Lines[code.Lines.Count-1];
code.lines[code.Lines.Count-1] := TRegEx.Replace(l,'^(\s*)Exit\s*\((?<expr>[^\)])\)\s*;\s*','\1Result := \2;',[roSingleLine]) ;
l := code.Lines[code.Lines.Count-1];
code.lines[code.Lines.Count-1] := TRegEx.Replace(l,'^(\s*)return\s*(?<expr>[^;]+)\s*;\s*','\1Result := \2;',[roSingleLine]) ;
end;
for I := 0 to code.Lines.Count-1 do
begin
l := code.lines[I];
l := TRegEx.Replace(l,'^(\s*)return\s*(?<expr>[^;]+)\s*;?$','\1Exit(\2);');
// fix special operators
for m in TRegEx.Matches(l, '^(?<indent>\s*)(?<varname>.*)\s*(?<op>[\+\-\*\/\%\&\^\~])\s*\=\s*(?<expr>.*);') do
begin
s :='<indent><varname> := <varname> <op> <expr>;';
setV(s,m,'indent');
setV(s,m,'varname');
setV(s,m,'op');
expr := FixTernary(m.Groups['expr'].Value);
if not TRegEx.Match(expr,'^[a-zA-Z0-9\-\>\.\$\_]+$').Success then
expr := '('+expr+')';
s := s.Replace('<expr>', expr );
s := s.Replace('^','xor');
s := s.Replace(' xor',' xor');
s := s.Replace('%','mod');
s := s.Replace('&','and');
s := s.Replace('~','not');
s := s.Replace(' not',' not');
s := s.Replace(' and',' and');
s := s.Replace(' mod',' mod');
s := s.Replace(' +',' +');
s := s.Replace(' -',' -');
s := s.Replace('|','or');
l := s;
end;
// convert : printf("Usage: %s filename\n", argv[0], x, 565)
// to : writeln(format('Usage: %s filename',[argv[0], x, 565]))
l := TRegEx.Replace(l, 'printf\s*\(\s*\"(?<format_str>.*)\\n\"\s*,\s*(?<params>.*)\s*\)\s*;','writeln(format(''\1'',[\2]));');
// convert : printf("Usage: %s filename\n", argv[0], x, 565)
// to : write(format('Usage: %s filename\n',[argv[0], x, 565]))
l := TRegEx.Replace(l, 'printf\s*\(\s*\"(?<format_str>.*)\"\s*,\s*(?<params>.*)\s*\)\s*;','write(format(''\1'',[\2]));');
for m in TRegEx.Matches(l,'(?<indent>\s*)printf\s*\(\s*\"(?<format_str>.*(?<cr>\\n)?)\"\s*,\s*(?<params>.*)\s*\)\s*;') do
begin
s := '(Format(''<format_str>'',[<params>]));';
tmp := m.Groups['format_str'].Value.Trim;
if tmp.EndsWith('\n') then
begin
setlength(tmp,length(tmp)-2);
s := 'Writeln'+s;
end
else
s := 'Write'+s;
s := '<indent>'+s;
s := s.Replace('<format_str>', tmp );
setV(s,m,'indent');
setV(s,m,'params');
l := s;
end;
// convert parameterless printf statements to write/writeln
for m in TRegEx.Matches(l,'(?<indent>\s*)printf\s*\(\s*\"(?<format_str>.*(?<cr>\\n)?)\"\s*\)\s*;') do
begin
s := '(''<format_str>'');';
tmp := m.Groups['format_str'].Value.Trim;
if tmp.EndsWith('\n') then
begin
setlength(tmp,length(tmp)-2);
s := 'Writeln'+s;
end
else
s := 'Write'+s;
s := s.Replace('<format_str>', tmp );
s := '<indent>'+s;
setV(s,m,'indent');
l := s;
end;
for m in TRegEx.Matches(l,'(?<indent>\s*)scanf\(\s*\"(?<format_str>.*(?<cr>\\n)?)\"\s*,\s*(?<params>.*)\s*\)\s*;') do
begin
s := '<indent>Readln(<params>);';
setV(s,m,'indent');
setV(s,m,'params');
s := s.Replace('&','');
l := s;
end;
// replace
// cout << xxx << "cccvbcvbvc" << endl;
// Write(xxx,'cccvbcvbvc',endl);
if l.Trim.StartsWith('cout') then
begin
s := 'Write(';
for m in TRegEx.Matches(l, '\<\<\s*(?<str>["]?[^\<]+["]?)',[ roSingleLine ]) do
begin
if s<>'Write(' then
s := s + ',';
s := s + m.Groups['str'].Value.Replace('"','''');
end;
s := s +')';
s := copy(l,1,pos('cout',l)) + s;
l := s;
end;
if c_inlinevardef(s,ps) then
s := ps;
ConvertForLoop(l, m);
code.lines[I] := l;
end;
Result := string.join(sLineBreak,Code.lines.ToArray);
FixTypeCasts(Result);
FixCaseStatementsFull(code, Result);
// let's try to deal with crappy C string handling.
// this is probably where C sucks the most :)
// convert strcpy( xxxx, 123 );
// to xxxx := 123;
Result := TRegEx.Replace(Result,'(?<indent>\s*)strcpy\s*\(\s*(?<arg1>[^,^(]*)\s*\,\s*(?<arg2>[^)]*)\s*\)\s*\;','\1\2 := \3;',[ roMultiLine ]);
// convert strcat(xxx,yyy);
// to xxx := xxx + yyy;
Result := TRegEx.Replace(Result,'(?<indent>\s*)strcat\s*\(\s*(?<arg1>[^,^(]*)\s*\,\s*(?<arg2>[^)]*)\s*\)\s*\;','\1\2 := \2 + \3;',[ roMultiLine ]);
// convert strlen(xxx)
// to Length(xxx)
Result := TRegEx.Replace(Result,'strlen\(\s*(?<index>[^\)]+)\s*\)','Length(\1)',[ roMultiLine ]);
// Convert argv[1]
// to ParamStr(1)
// we'll make sure that it's not a part of another string for example
Result := TRegEx.Replace(Result,'(\s*|[^a-z^A-Z^0-9^_]*)argc(\s*|[^a-z^A-Z^0-9^_]*)','\1ParamCount\2',[ roMultiLine ]);
// Convert argv[1]
// to ParamStr(1)
Result := TRegEx.Replace(Result,'argv\[\s*(?<index>[^\]]+)\s*\]','ParamStr(\1)',[ roMultiLine ]);
// Convert puts(foo)
// to WriteLn(foo)
Result := TRegEx.Replace(Result,'puts\(\s*(?<index>[^\)]+)\s*\)','WriteLn(\1)',[ roMultiLine ]);
// replace "end; else" with "end else"
Result := TRegEx.Replace(Result, 'end;(\w+)else\w+','end\1else');
// replace i++ with PostInc(i)
Result := TRegEx.Replace(Result, '(\w+)\+\+','PostInc(\1)');
// replace ++i with PreInc(i)
Result := TRegEx.Replace(Result, '\+\+(\w+)','PreInc(\1)');
// replace i-- with PostDec(i)
Result := TRegEx.Replace(Result, '(\w+)\-\-','PostDec(\1)');
// replace --i with PreDec(i)
Result := TRegEx.Replace(Result, '\-\-(\w+)','PreDec(\1)');
// replace "hallo" with 'hallo'
Result := TRegEx.Replace(Result, '\"(.*)\"','''\1''');
// replace '\0' with #0
Result := Result.Replace('''\0''','#0');
// replace (d?:0:1) with (ifthen(d,0,1))
Result := TRegEx.Replace(Result,'\((?<condition>.*)\s*\?\s*(?<if_true>.*):\s*(?<if_false>.*)\s*\)','( ifthen(\1, \2, \3) )' );
// return statements that are not on their own line are not converted. Let's fix that:
Result := TRegEx.Replace(Result,'^(\s*)if\s*\((?<condition>[^\)]+)\s*\)\s*return\s*;','\1if \2 then Exit;',[ roMultiLine ]);
// return statements that are not on their own line are not converted. Let's fix that:
Result := TRegEx.Replace(Result,'^(\s*)if\s*\((?<condition>[^\)]+)\s*\)\s*return\s*([^;]*)\s*;','\1if \2 then Exit(\3);',[ roMultiLine ]);
// convert single line if statement
// convert if(XXX) YYY;
// to if XXX then YYY;
Result := TRegEx.Replace(Result,'^(?<indent>\s*)if\s*\(\s*(?<expr>[^\)]*)\s*\)\s*(?<then>[^\;]*)\s*\;','\1if \2 then \3;',[ roMultiLine ]);
// convert if(XXX)
// to if XXX then
Result := TRegEx.Replace(Result,'^(?<indent>\s*)if\s*\(\s*(?<expr>.*)\s*\)(?<trail>\s*)','\1if \2 then \3',[ roMultiLine ]);
// convert while(XXX)
// to while XXX do
Result := TRegEx.Replace(Result,'^(?<indent>\s*)while\s*\(\s*(?<expr>.*)\s*\)(?<trail>\s*)','\1while \2 do \3',[ roMultiLine ]);
// int main(){
//do {
//x = 2 * x;
//y--;
//}
//while (x < y);
//
//}
Result := TRegEx.Replace(Result,'^(?<indent>\s*)do\s*\{(?<body>[^\}]*)\}\s*(while)\s*\((?<expr>[^)]*)\s*\)\s*;','\1repeat \2 until not(\4);',[ roMultiLine ]);
// convert atoi to StrToInt
ReplaceFunctionName(Result,'atoi','StrToInt');
// convert putchar("\n") to Write(sLineBreak)
ReplaceFunctionName(Result,'putchar','Write');
ReplaceFunctionName(Result,'memcpy','Windows.CopyMemory');
// well.. we've exchausted all the tricks we've got on our sleeve
// let's just do some simplistic substitutions to convert whatever's left
// not very accurate, but it works in the majority of the situations
//Result := Result.Replace(' = ', ' := ' , [rfReplaceAll]);
Result := Result.Replace('==' , '=' , [rfReplaceAll]);
Result := Result.Replace('!=' , '<>' , [rfReplaceAll]);
// replace ! that's not in a string. Else "Hello, World!" becomes "Hello, World not "
Result := ReplaceOutsideCommentsAndStrings(Result,'!',' not ');
Result := Result.Replace('&&' , ' and ', [rfReplaceAll]);
Result := Result.Replace('||' , ' or ' , [rfReplaceAll]);
Result := ReplaceOutsideCommentsAndStrings(Result,'^',' xor ');
Result := Result.Replace('>>' , ' shr ', [rfReplaceAll]);
Result := Result.Replace('<<' , ' shl ', [rfReplaceAll]);
Result := Result.Replace('->' , '^.' , [rfReplaceAll]);
Result := Result.Replace('::' , '.' , [rfReplaceAll]);
Result := ReplaceOutsideCommentsAndStrings(Result,'{','begin ');
Result := ReplaceOutsideCommentsAndStrings(Result,'}','end; '+sLineBreak);
Result := Result.Replace('(*','( *'); // (* could appear in C code
Result := Result.Replace('/*' , '(*');
Result := Result.Replace('*/' , '*)' + sLineBreak);
Result := TRegEx.Replace(Result,'\s\|\s',' or ',[ roMultiLine ]);
Result := TRegEx.Replace(Result,'\s\&\s',' and ',[ roMultiLine ]);
Result := TRegex.Replace(Result,'atan\s*\(' , 'arctan(',[roMultiLine ]);
// convert conditional defines #ifdef XXX to {$ifdef XXX}
Result := TRegEx.Replace(Result,'^(\s*)\#ifdef\s+(.*)$','\1{$IFDEF \2}',[ roMultiLine ]);
Result := TRegEx.Replace(Result,'^(\s*)\#ifndef\s+('+rxID+')\s*$','\1{$IFNDEF \2}',[ roMultiLine ]);
Result := TRegEx.Replace(Result,'^(\s*)\#if\s+(.*)$' ,'\1{$IF \2}',[ roMultiLine ]);
Result := TRegEx.Replace(Result,'^(\s*)\#else\s*$' ,'\1{$ELSE}',[ roMultiLine ]);
Result := TRegEx.Replace(Result,'^(\s*)\#endif\s*$' ,'\1{$ENDIF}',[ roMultiLine ]);
Result := TRegEx.Replace(Result,'^(\s*)\#define\s+('+rxID+')\s*$' ,'\1{$DEFINE \2}',[ roMultiLine ]);
// fprintf with newline and parameters
// fprintf(stderr, "[*.PAT loader] highnote to high (sh.high_frequency=%d highnote=%d sizeof(ins->note)=%d\n", sh.high_frequency, highnote, (int)sizeof(ins->note));
// WriteLn(format('[*.PAT loader] highnote to high (sh.high_frequency=%d highnote=%d sizeof(ins->note)=%d',[sh.high_frequency, highnote, (int)sizeof(ins->note)]);
Result := TRegEx.Replace(Result,'^(?<indent>\s*)fprintf\s*\(\s*(?<output>\w[\w\d_]*),\s*[''"](?<formatstr>[^''"]*)(?<newline>\\n)[''"]\s*,\s*(?<params>.*)\);', '\1WriteLn(Format(''\3'',[\5]));',[ roMultiLine ]);
// fprintf without newline and parameters
// fprintf(stderr, "[*.PAT loader] highnote to high (sh.high_frequency=%d highnote=%d sizeof(ins->note)=%d", sh.high_frequency, highnote, (int)sizeof(ins->note));
// Write(format('[*.PAT loader] highnote to high (sh.high_frequency=%d highnote=%d sizeof(ins->note)=%d',[sh.high_frequency, highnote, (int)sizeof(ins->note)]);
Result := TRegEx.Replace(Result,'^(?<indent>\s*)fprintf\s*\(\s*(?<output>\w[\w\d_]*),\s*[''"](?<formatstr>[^''"]*)[''"]\s*,\s*(?<params>.*)\);', '\1Write(Format(''\3'',[\5]));',[ roMultiLine ]);
// fprintf with newline
// fprintf(stderr, "[*.PAT loader] highnote to high (sh.high_frequency=%d highnote=%d sizeof(ins->note)=%d\n", sh.high_frequency, highnote, (int)sizeof(ins->note));
// WriteLn(format('[*.PAT loader] highnote to high (sh.high_frequency=%d highnote=%d sizeof(ins->note)=%d',[sh.high_frequency, highnote, (int)sizeof(ins->note)]);
Result := TRegEx.Replace(Result,'^(?<indent>\s*)fprintf\s*\(\s*(?<output>\w[\w\d_]*),\s*[''"](?<formatstr>[^''"]*)(?<newline>\\n)[''"]\s*\);', '\1WriteLn(''\3'');',[ roMultiLine ]);
// fprintf without newline
// fprintf(stderr, "[*.PAT loader] highnote to high (sh.high_frequency=%d highnote=%d sizeof(ins->note)=%d", sh.high_frequency, highnote, (int)sizeof(ins->note));
// Write(format('[*.PAT loader] highnote to high (sh.high_frequency=%d highnote=%d sizeof(ins->note)=%d',[sh.high_frequency, highnote, (int)sizeof(ins->note)]);
Result := TRegEx.Replace(Result,'^(?<indent>\s*)fprintf\s*\(\s*(?<output>\w[\w\d_]*),\s*[''"](?<formatstr>[^''"]*)[''"]\s*\);', '\1Write(''\3'');',[ roMultiLine ]);
// pointers
// convert (*xxx) to @xxx
Result := TRegEx.Replace(Result,'\(\*(\s*'+rxID+')\)' ,'@\1',[ roMultiLine ]);
// convert XXX[534] = 34gfdjeklrtj354;
// to XXX[534] := 34gfdjeklrtj354;
// convert XXX[534].xxx = 34gfdjeklrtj354;
// to XXX[534].xxx := 34gfdjeklrtj354;
Result := TRegEx.Replace(Result,'^(\s*)(\w[\w\[\]_\d\.]*)\s*\=\s*(.*)$' ,'\1\2 := \3',[ roMultiLine ]);
// convert hex
Result := TRegEx.Replace(Result,rxHexadecimal ,'\$\1',[ roMultiLine ]);
// convert null to nil
Result := TRegEx.Replace(Result,'NULL' ,'nil',[ roMultiLine ]);
Result := TRegEx.Replace(Result,'(\d+)U','\1',[ roMultiLine ]);
Result := TRegEx.Replace(Result,'^(\s*)(return);','\1Exit;',[ roMultiLine ]);
// convert null to nil
Result := Result.Replace('Writeln('''')','Writeln');
Result := Result.Replace('(int32_t)','');
Result := Result.Replace('(int64_t)','');
Result := Result.Replace('\n''','''+sLineBreak');
Result := Result.Replace('''''+','');
Result := Result.Replace(' +''''','');
Result := Result.Replace('Write(sLineBreak)','WriteLn');
Result := TRegEx.Replace(Result,'else(\s*);(\s*)' ,'else\1\2',[ roMultiLine ]);
Result := TRegEx.Replace(Result,';(\s*)else(\s*)' ,'\1else\2',[ roMultiLine ]);
Result := Result.TrimRight;
Code.Lines.Clear;
Code.Lines.InsertRange(0,Result.Split([sLineBreak]));
end;
function GetVariablesFromLine(const Line: string; aVariableList: TVariableList):boolean;
var
m: TMatch;
i: Integer;
s: String;
lType: string;
lvarName: string;
begin
if Line.Trim='' then
Exit(False);
// int test4_TT
m := TRegEx.Match(Line,'^\s*(struct\s+)?(?<vartype>' + rxType + ')\s+(?<varname>' + rxID + ')\s*;\s*$');
if m.Success then
begin
if m.Groups['vartype'].Value <> 'return' then
begin
TVariable.Create(aVariableList, m.Groups['varname'].Value, convertType(m.Groups['vartype'].Value),TDir.inout);
exit(true);
end;
end;
// int test = 5*5+xxx
m := TRegEx.Match(Line, '^\s*(struct\s+)?(?<vartype>' + rxType + ')\s+(?<varname>' + rxID + ')\s*=\s*(?<expression>.*)\s*;\s*$');
if m.Success then
begin
if m.Groups['vartype'].Value <> 'return' then
begin
TVariable.Create(aVariableList, m.Groups['varname'].Value, convertType(m.Groups['vartype'].Value),TDir.inout);
exit(true);
end;
end;
// const int base = 508887777
m := TRegEx.Match(Line, '^\s*(?<const>const)\s+(struct\s+)?(?<vartype>' + rxType + ')\s+(?<varname>' + rxID + ')\s*=\s*(?<expression>.*)\s*;\s*(?<comment>.*)\s*;\s*$');
if m.Success then
begin
TVariable.Create( aVariableList, m.Groups['varname'].Value, convertType(m.Groups['vartype'].Value), TDir.in, False, True, m.Groups['expression'].Value, m.Groups['comment'].Value.Trim.TrimLeft(['/']).Trim);
exit(true);
end;
// int test;
// int *test;
// int **test;
m := TRegEx.Match(Line, '^(?<indent>\s*)(struct\s+)?(?<vartype>' + rxType + ')\s+(?<pointer>[\*]{0,2})?(?<varname>' + rxID + ')\s*;');
if m.Success then
begin
if m.Groups['vartype'].Value <> 'return' then
begin
TVariable.Create(aVariableList, m.Groups['varname'].Value,
m.Groups['pointer'].Value.Replace('*','^') + ConvertType(m.Groups['vartype'].Value),
TDir.inout);
exit(true);
end;
end;
// catch loop variable (for int i=0;i<10;i++)
m := TRegEx.Match(Line, '^(?<indent>\s*)for\s*\(\s*(?<vartype>int(?:\s+))(?<varname>' + rxId + ')\s*\=\s*(?<min>[^\;])\s*;\s*(?<varname2>' + rxID + ')\s*(?<op><[\=]{0,1})\s*(?<max>.*)\s*\;\s*(?<varname3>\w+\+\+)\s*\)\s*(.*)', [roSingleLine]);
if m.Success then
begin
TVariable.Create(aVariableList, m.Groups['varname'].Value, convertType(m.Groups['vartype'].Value.Trim),TDir.inout);
exit(true);
end;
// int xxx[17][18]
m := TRegEx.Match(Line, '^\s*(?<vartype>' + rxType + ')\s+(?<varname>' + rxID + ')\s*\[\s*(?<arraysize1>.*)\s*\]\s*\[\s*(?<arraysize2>.*)\s*\]');
if m.Success then
begin
if TryStrToInt(m.Groups['arraysize1'].Value, i) then
if TryStrToInt(m.Groups['arraysize2'].Value, i) then
TVariable.Create(aVariableList, m.Groups['varname'].Value, format('array[0..%d,0..%d] of %s', [
StrToInt(m.Groups['arraysize1'].Value) - 1,
StrToInt(m.Groups['arraysize2'].Value) - 1,
convertType(m.Groups['vartype'].Value)]),TDir.inout);
exit(true);
end;
// int xxx[4]
m := TRegEx.Match(Line, '^\s*(?<vartype>' + rxType + ')\s+(?<varname>' + rxID + ')\s*\[\s*(?<arraysize>.*)\s*\]\s*');
if m.Success then
begin
if m.Groups['arraysize'].Value='' then
// int test[]
TVariable.Create(aVariableList, m.Groups['varname'].Value, format('array of %s', [convertType(m.Groups['vartype'].Value)]),TDir.inout)
else
if TryStrToInt(m.Groups['arraysize'].Value, i) then
// int test[4]
TVariable.Create(aVariableList, m.Groups['varname'].Value, format('array[0..%d] of %s', [StrToInt(m.Groups['arraysize'].Value) - 1, convertType(m.Groups['vartype'].Value)]),TDir.inout)
else
// char name[NAME_MAX+1]
TVariable.Create(aVariableList, m.Groups['varname'].Value, format('array[0..(%s)-1] of %s', [m.Groups['arraysize'].Value, convertType(m.Groups['vartype'].Value)]),TDir.inout);
exit(true);
end;
if line.Contains('void') then
Exit(False);
m := TRegEx.Match(Line,'^\s*(?<vartype>'+rxType+')\s+'
+'(?<vars>(('+rxID+')\s*'
+'(\[\s*(?<arraysize1>\d)\s*\])?\s*'
+'(\[\s*(?<arraysize2>\d)\s*\])?\s*'
+'\,\s*)+\s*('+rxID+'))\s*(=\s*[^;]*)?;',[roSingleLine]);
if m.Success then
begin
if m.Groups['vartype'].Value<>'return' then
for s in m.Groups['vars'].Value.Split([',']) do
begin
lType := convertType(m.Groups['vartype'].Value );
lvarName := s.Split(['['])[0];
if m.Groups['arraysize1'].Value <> '' then
begin
if m.Groups['arraysize2'].Value <> '' then
lType := Format('Array[0..%d,0..%d] of %s',[
StrToInt(m.Groups['arraysize1'].Value),
StrToInt(m.Groups['arraysize2'].Value),
lType
])
else
if m.Groups['arraysize1'].Value <> '' then
lType := Format('Array[0..%d] of %s',[
StrToInt(m.Groups['arraysize1'].Value),
lType
])
end;
TVariable.Create(aVariableList, lVarName, lType,TDir.inout) ;
end;
exit(true);
end;
// static const int lg_n = 6;
m := TRegEx.Match(Line, '^\s*(?<static>static)\s+(?<const>const)\s+(?<vartype>' + rxType + ')\s+(?<varname>' + rxID + ')\s*\=\s*(?<value>.*)\;$');
if m.Success then
begin
TVariable.Create(aVariableList, m.Groups['varname'].Value, convertType(m.Groups['vartype'].Value), TDir.&in, true, true, m.Groups['value'].Value );
exit(true);
end;
Exit(False);
end;
procedure getMethodParams(const s: String; var params:TVariableList);
var
p : string;
m : TMatch;
t,dir:string;
d:TDir;
begin
// parse the routine arguments
for p in s.Split([',']) do
for m in TRegEx.Matches(p, '\s*(?<direction>in\s+|out\s+|inout\s+|const\s+)?(?<type>'+rxType+')\s+(?<pointer>[\*\&]?)(?<varname>'+rxID+')\s*') do
begin
dir := m.Groups['direction'].Value.Trim;
if dir='inout' then d := TDir.inout else
if Dir='out' then d := TDir.out else
if Dir='in' then d := TDir.in else
if Dir='const' then d := TDir.in else
d := TDir.none;
if m.Groups['pointer'].Value='*' then
d := inout;
t := ConvertType( m.Groups['type'].Value );
if t.EndsWith('*') then
begin
d := inout;
t := t.TrimRight(['*']);
end;
TVariable.Create(
params,
m.Groups['varname'].Value,
t,
d,
False,
False);
end;
end;
function c_Array1DToPas(const u: TPascalElement; c:string;out pas:TArrayDef1D):Boolean;
var
m:TMatch;
i:integer;ns:string;
begin
Result := false;
pas := TArrayDef1D.Create(u);
for m in TRegEx.Matches(c,'\s*(?<eltype>'+rxType+')\s+(?<varname>'+rxID+')\s*\[(?<arraysize>.*)?\]\s*=\s*\{(?<elements>.*)\};',[roIgnoreCase, roSingleLine] ) do
begin
Result := True;
pas.itemType := convertType(m.Groups['eltype'].Value);
pas.rangeMin := '0';
// pas.rangeMax := StrToIntDef(m.Groups['arraysize'].Value,-1);
pas.Name := m.Groups['varname'].Value+ns;
pas.Items := m.Groups['elements'].Value.Replace(' ','').Replace(#9,'').Replace(sLineBreak,'').Split([',']);
// if the items look like a string, let's just make it an array of string instead of CHAR* or something crappy like that.
for I := Low(pas.Items) to high(pas.Items) do
if Length(pas.Items[I])>3 then // for something to be enclosed in quotes, we need at least a length of 2.. more than 3 because we don't want to convert chars to string
if pas.Items[0].Contains('"') then
pas.itemType := 'String';
for I := Low(pas.Items) to high(pas.Items) do
begin
pas.Items[I] := trim(pas.Items[I].Replace('"',''''));
end;
pas.rangeMax := IntToStr(length(pas.Items)-1);
Exit;
end;
end;
function c_Array2DToPas(const u: TPascalElement; c:string;out pas:TArrayDef2D):Boolean;
var
m,n:TMatch;
I,J:integer;
SubItems:string;
begin
Result := false;
for m in TRegEx.Matches(c,'\s*(?<modifier>\w+)*\s+(?<eltype>'+rxType+')\s+(?<varname>'+rxID+')\s*\[(?<arraysize1>.*)?\]\[(?<arraysize2>.*)?\]\s*=\s*\{(?<elements>.*)\};',[roIgnoreCase, roSingleLine] ) do
begin
pas := TArrayDef2D.Create(u);
Result := True;
pas.itemType := ConvertType(m.Groups['eltype'].Value);
pas.ranges[0].rangeMin := '0';
pas.ranges[1].rangeMin := '0';
pas.ranges[0].rangeMax := m.Groups['arraysize1'].Value;
pas.ranges[1].rangeMax := m.Groups['arraysize2'].Value;
pas.Name := m.Groups['varname'].Value;
J := 0;
for n in TRegEx.Matches(m.Groups['elements'].Value,'\{(?<el>[^\}]*)}') do
begin
SubItems := n.Groups['el'].Value.Replace(' ','').Replace(#9,'').Replace(sLineBreak,'');
setlength(Pas.Items,J+1);
Pas.Items[J] := subItems.Split([',']);
for I := Low(pas.Items[J]) to high(pas.Items[J]) do
pas.Items[J][I] := trim(pas.Items[J][I].Replace('"',''''));
// pas.ranges[1].rangeMax := IntToStr(length(pas.Items[J])-1);
inc(J);
end;
Exit;
end;
end;
procedure getLocalVars(const aCode:TCode; aVarList:TVariableList);
var l:string; vis:TVisibility; i:integer;
begin
vis := TVisibility.DefaultVisibility;
for l in aCode.Lines do
begin
if l.Trim = 'public:' then
vis := TVisibility.&Public;
if l.Trim = 'private:' then
vis := TVisibility.&Private;
// va := [];
GetVariablesFromLine(l, aVarList);
for I := 0 to aVarList.Count-1 do
TVariable(aVarList[I]).Visibility := vis;
end;
end;
procedure CleanComments(var comment: string);
var
a: TArray<string>;
s: string;
t: string;
begin
if Comment <> '' then
begin
Comment := comment.Trim.Replace('//','');
a := [];
for s in Comment.Split([sLineBreak]) do
begin
t := s.Trim;
if t.StartsWith('/*') then
t := t.Substring(3);
if t.EndsWith('*/') then
setlength(t, t.Length - 2);
if t.Trim <> '' then
a := a + [t];
end;
Comment := string.Join(sLineBreak, a);
end;
end;
function c_FunctionDefToPas(const c:string;var aRoutine:TRoutine):boolean;
var
m: TMatch;
ReturnType, FuncName, Parameters,
ClassName: string;
rt:TRoutineType;
params,
localvars:TVariableList;
code:TCode;
isStatic,isInline,isDestructor, isVirtual:boolean;
comment:string;
begin
Assert(not Assigned(aRoutine));
try
m := TRegEx.Match(c.Trim, rxMethodDef , [roSingleLine] );
except
on e:Exception do
Exit(false);
end;
if not m.Success then
Exit(False);
ReturnType := m.Groups['returntype'].Value.Trim;
if not IsFunction(c.Trim) then
Exit(False);
ReturnType := convertType( ReturnType );
if ReturnType.EndsWith('*') then
ReturnType := '^'+ReturnType.TrimRight(['*']);
ClassName := m.Groups['classname'].Value;
FuncName := m.Groups['funcname'].Value;
try
Parameters := m.Groups['parameters'].Value;
except
Parameters := '';
end;
isDestructor := m.Groups['destructor'].Value='~';
if SameText(ClassName,FuncName) then
begin
if isDestructor then
begin
rt := TRoutineType.&destructor;
FuncName := 'Destroy';
end
else
begin
rt := TRoutineType.&constructor;
FuncName := 'Create';
end;
end
else
if SameText(ReturnType,'void') then
rt := TRoutineType.&procedure
else
rt := TRoutineType.&function;
Params := TVariableList.Create(nil);
Params.Name := 'Params';
getMethodParams(Parameters,Params);
code := TCode.Create(nil, c.Split([';']) );
localvars := TVariableList.Create(nil);
localvars.Name := 'LocalVars';
getLocalVars(Code, localvars);
isInline := SameText(m.Groups['inline'].Value.Trim,'inline');
isStatic := SameText(m.Groups['static'].Value.Trim,'static');
isVirtual := SameText(m.Groups['virtual'].Value.Trim,'virtual');
Comment := m.Groups['comment'].value
+ m.Groups['comment3'].value;
CleanComments(comment);
aRoutine := TRoutine.Create(
nil,
FuncName,
ClassName,
rt,
ReturnType,
params,
localvars,
code,
false,
false,
isInline,
isStatic,
isVirtual,
comment
);
ConvertCLinesToPas(code);
exit(True);
end;
function c_FunctionToPas(const aUnit:TPascalUnit; const c:string;var aRoutine:TRoutine):boolean;
var
m: TMatch;
ReturnType, FuncName, ParameterStr,
CodeStr: string;
ClassName: string;
RoutineType:TRoutineType;
params,
localvars:TVariableList;
code:TCode;
isStatic,isInline,isDestructor, isVirtual:boolean;
comment:string;
classDef:TClassDef;
begin
try
m := TRegEx.Match(c.Trim, rxMethod , [roSingleLine] );
except
on e:Exception do
Exit(false);
end;
if not m.Success then
Exit(False);
ReturnType := m.Groups['returntype'].Value.Trim;
if ReturnType = 'typedef' then Exit(False);
if ReturnType = 'enum' then Exit(False);
if ReturnType = 'struct' then Exit(False);
if ReturnType = 'class' then Exit(False);
ReturnType := convertType( ReturnType );
if ReturnType.EndsWith('*') then
ReturnType := '^'+ReturnType.TrimRight(['*']);
ClassName := m.Groups['classname'].Value;
FuncName := m.Groups['funcname'].Value;
ParameterStr := m.Groups['parameters'].Value;
CodeStr := m.Groups['code'].Value;
isDestructor := m.Groups['destructor'].Value='~';
if SameText(ClassName,FuncName) then
begin
if isDestructor then
begin
RoutineType := TRoutineType.&destructor;
FuncName := 'Destroy';
end
else
begin
RoutineType := TRoutineType.&constructor;
FuncName := 'Create';
end;
end
else
if SameText(ReturnType,'void') then
RoutineType := TRoutineType.&procedure
else
RoutineType := TRoutineType.&function;
Code := TCode.Create(nil,CodeStr.Split([sLineBreak]));
Code.Sourceinfo.Position := m.Groups['code'].Index;
params := TVariableList.Create(nil);
params.Name := 'Params';
getMethodParams(ParameterStr,params);
localvars := TVariableList.Create(nil);
localvars.Name := 'Local vars';
getLocalVars(Code, localvars);
isInline := SameText(m.Groups['inline'].Value.Trim,'inline');
isStatic := SameText(m.Groups['static'].Value.Trim,'static');
isVirtual := SameText(m.Groups['virtual'].Value.Trim,'virtual');
Comment := m.Groups['comment'].value
+ m.Groups['comment3'].value;
CleanComments(comment);
if ClassName = '' then
ClassName := 'TGlobal';
classDef := aUnit.getClassByName(ClassName);
aRoutine := TRoutine.Create(
classDef,
FuncName,
ClassName,
RoutineType,
ReturnType,
params,
localvars,
code,
false,
false,
isInline,
isStatic,
isVirtual,
comment
);
ConvertCLinesToPas(code);
exit(True);
end;
function c_StructToPas(const aPascalUnit:TPascalUnit; c:string;var outClass:TClassDef):Boolean;
var
m:TMatch;
Name:string;
Code:TCode;
v:TVariableList;
begin
Result := false;
Code := TCode.Create(nil,[]);
try
for m in TRegEx.Matches(c,'struct\s+(?<packed>PACKED)?\s*(?<name>'+rxId+')[^{]*\{',[roMultiLine] ) do
begin
Result := True;
Name := m.Groups['name'].Value;
Code.Lines.Clear;
Code.Lines.InsertRange(0,c.Split([sLineBreak]));
v := TVariableList.Create(nil);
v.Name := 'Fields';
getLocalVars(Code,v);
if v.Count = 0 then
begin
v.Free;
exit(false);
end;
outClass := TClassDef.Create(aPascalUnit,Name,v,TClassKind.&record);
outClass.FIsPacked := m.Groups['packed'].Value='PACKED';
Exit(True);
end;
finally
Code.Free;
end;
end;
function c_return(const c:string;out pas:string):boolean;
var m: TMatch;
begin
pas := '';
Result := false;
for m in TRegEx.Matches(c,'\s*return\s+(?<expression>.*)') do
begin
Result := True;
Pas := 'exit( <expression> );';
setV(Pas,m,'expression');
end;
end;
procedure AddArrays1D(const u: TPascalUnit; const c: string);
var
m: TMatch;
ar: TArrayDef1D;
I: Integer;
level: Integer; aRoutine: string;
begin
// search for array definitions
for m in TRegEx.Matches(c, '(?<modifier>\w+\s+)*\s*(?<eltype>'+rxType+')\s+(?<varname>'+rxID+')\s*\[\s*(?<arraysize>[^\]]*)?\s*\]\s*=\s*\{', [roIgnoreCase]) do
begin
level := 0;
for I := m.Index + m.Length - 1 to c.Length do
begin
if c[I] = '{' then inc(level);
if c[I] = '}' then dec(level);
// ok, we're back at level 0, so we've found the closing bracket.
if level = 0 then
begin
aRoutine := trim(copy(c, m.Index, 2 + I - m.Index));
if c_Array1DToPas(u, aRoutine, ar) then
u.GlobalArrays1D := u.GlobalArrays1D + [ar];
ar.Sourceinfo.Position := m.Index;
ar.Sourceinfo.Length := I - m.Index + 1;
Break;
end;
end;
end;
end;
procedure AddArrays2D(var u: TPascalUnit; const c: string);
var
m: TMatch;
ar: TArrayDef2D;
I: Integer;
level: Integer; aRoutine: string;
begin
// search for array definitions
for m in TRegEx.Matches(c, '(?<modifier>\w+\s)*\s*(?<eltype>'+rxType+')\s+(?<varname>'+rxID+')\s*\[\s*(?<arraysize1>[^\]]*)?\s*\]\[\s*(?<arraysize2>[^\]]*)?\s*\]\s*=\s*\{', []) do
begin
level := 0;
for I := m.Index + m.Length - 1 to c.Length do
begin
if c[I] = '{' then inc(level);
if c[I] = '}' then dec(level);
// ok, we're back at level 0, so we've found the closing bracket.
if level = 0 then
begin
aRoutine := trim(copy(c, m.Index, 2 + I - m.Index));
ar := TArrayDef2D.Create(u);
if c_Array2DToPas(u, aRoutine, ar) then
u.GlobalArrays2D := u.GlobalArrays2D + [ar];
ar.Sourceinfo.Position := m.Index;
ar.Sourceinfo.Length := I - m.Index + 1;
Break;
end;
end;
end;
end;
function c_class_to_pas(u:TPascalUnit; c:string; out pas:TArray<TClassDef>):Boolean;
var mc:TMatchCollection; m,m2:TMatch; classDef:TArray<string>;i,j:integer;
vis:TVisibility;
cd:string;
rt:TRoutine;
def:TClassDef;
begin
Result := True;
mc := TRegEx.Matches(c, rxClassDef , [roMultiLine]);
if mc.Count = 0 then
Exit(False);
for m in mc do
begin
def := TClassDef.Create(u,m.Groups['classname'].Value,nil,TClassKind.&class);
pas := pas + [def];
def.FParentType := '';
cd := c.Substring( m.Index + m.Length, MaxInt).Trim;
cd := cd.TrimRight(['}']);
classDef := cd{m.Groups['classdef'].Value}.Split([sLineBreak]);
vis := TVisibility.DefaultVisibility;
for i := low(classDef) to High(classDef) do
begin
if classDef[I].Trim = 'public:' then
begin
vis := TVisibility.&Public;
Continue;
end;
if classDef[I].Trim = 'private:' then
begin
vis := TVisibility.&private;
Continue;
end;
GetVariablesFromLine(classDef[i], def.FMembers);
m2 := TRegEx.Match(classDef[i], rxMethodDef);
if m2.Success then
begin
rt := nil;
if c_FunctionDefToPas(classDef[i], rt) then
begin
if not def.AddRoutine(rt) then
rt.Free;
end;
end;
for J := 0 to def.FMembers.Count-1 do
TVariable(def.FMembers[J]).Visibility := vis;
end;
u.AddClass(def);
end;
end;
procedure AddClassDefs(var u: TPascalUnit; const aCCode: string;var t:string);
var
m: TMatch;
aRoutine: string;
cl: TArray<TClassDef>;
mc: TMatchCollection;
begin
// class Dx7Note {
// public:
// Dx7Note();
// void init(const char patch[156], int midinote, int velocity);
//
// // Note: this _adds_ to the buffer. Interesting question whether it's
// void compute(int32_t *buf, int32_t lfo_val, int32_t lfo_delay,
// const Controllers *ctrls);
//
// void keyup();
//
// // PG:add the update
// void update(const char patch[156], int midinote);
// void peekVoiceStatus(VoiceStatus &status);
// void transferSignal(Dx7Note &src);
// void oscSync();
//
// private:
// Env env_[6];
// FmOpParams params_[6];
// PitchEnv pitchenv_;
// int32_t basepitch_[6];
//
// int pitchmodsens_;
// };
// class xxx : public TForm
mc := TRegEx.Matches(aCCode, rxClassDef , [roMultiLine]);
for m in mc do
begin
// we've found a class signature.
// now let's scan until we've found the final closing bracket
// there can be nested brackets
ScanUntilMatchingChar('{','}',aCCode,m,aRoutine);
if aRoutine='' then
Continue;
aRoutine := trim(copy(aCCode, m.Index, length(aRoutine)));
if c_class_to_pas(u,aRoutine,cl) then
begin
// cl.Sourceinfo.Position := m.Index;
// cl.Sourceinfo.Length := aRoutine.Length;
end;
end;
end;
procedure AddFunctions(const aPascalUnit: TPascalUnit; const aCCode: string; var t:string;aOnProgress:TOnProgress=nil);
var
m: TMatch;
aRoutine,c: string;
rt: TRoutine;
cl: TClassDef;
mc: TMatchCollection;
I,Index:integer;
J: Integer;
const
minv = 0.3;
scale = 0.4;
begin
// search for functions by pattern..
rt := nil;
mc := TRegEx.Matches(aCCode, rxMethodHeader , [ roMultiLine ]);
for m in mc do
begin
// sometimes we accidentially ran into somethign that looks like a function
if not IsFunction(m.Value.Trim) then
Continue;
aRoutine := '';
ScanUntilMatchingChar('{', '}', aCCode, m, aRoutine);
//////////////////////////////
/// search backwards for multi-line comment
I := m.Index;
c := '';
while I>0 do
begin
case aCCode[I] of
#9,#13,#10,' ':
begin
dec(I);
Continue;
end;
'/':
// maybe found end of a multiline comment
begin
Dec(I);
if aCCode[I]='*' then
begin
// found end of multiline comment
while I>1 do
begin
if (aCCode[I]='*') and (aCCode[I-1]='/') then
I := 0
else
aRoutine := aCCode[I] + c;
Dec(I);
end;
end;
end;
else break;
end;
dec(I);
end;
//////////////////////////////
if aRoutine<>'' then
begin
if c_FunctionToPas(aPascalUnit,aRoutine,rt) then
begin
cl := aPascalUnit.getClassByName(rt.ClassName);
rt.Sourceinfo.Position := m.Index;
rt.Sourceinfo.Length := aRoutine.Length;
rt.code.Sourceinfo.Position := rt.Sourceinfo.Position;
// Convert switch statements
if rt.Code.Count > 0 then
for Index := 0 to rt.code.Count-1 do
begin
if rt.code[Index] is TSwitch then
begin
rt.code[Index].Sourceinfo.Position := rt.code[Index].Sourceinfo.Position + rt.Sourceinfo.Position;
for J := 0 to rt.Code[Index].Count-1 do
begin
rt.Code[Index][J].Sourceinfo.Position := rt.Code[Index][J].Sourceinfo.Position + rt.Code.Sourceinfo.Position;
end;
end;
end;
if rt.Comment = '' then
rt.Comment := c;
if assigned(aOnprogress) then
aOnProgress(minv+scale*I / mc.count,rt.ToDeclarationPascal);
if not cl.AddRoutine(rt) then
rt.Free;
end;
rt := nil;
end;
end;
// aCCode := RemoveRoutines(aCCode);
end;
procedure AddConsts(var u: TPascalUnit; const c: string; var t:string);
var
m: TMatch;
val:string;
WithoutRoutines:string;
code:TCode;
LType:String;
const
rx = '^\s*#define\s+(?<name>'+rxID+')\s+(?<expr>.*)\s*$';
rx3 = '^\s*const\s+(?<type>'+rxType+')\s+(?<name>'+rxID+')\s*\=\s*(?<expr>.*)\s*\;\s*$'; // const int kControllerPitchStep = 130;
rx4 = '^\s*const\s+(?<type>'+rxType+')\s+(?<name>'+rxID+')\s*\[\s*\]\s*\=\s*(?<expr>.*)\s*\;\s*$'; // const char filename[] = "XYZ.DAT";
begin
// search for const definitions
for m in TRegEx.Matches(c, rx, [roMultiLine]) do
begin
val := m.Groups['expr'].Value;
if val.Trim.StartsWith('#include') then
Continue;
val := val
.Replace('<<',' shl ')
.Replace('>>',' shr ')
.Replace(' ',' ')
.Replace('"','''')
;
LType := '';
if val.StartsWith('''') then
if val.Length=3 then
LType := 'Char'
else
LType := 'String';
TVariable.Create(u.GlobalVars, m.Groups['name'].Value,LType, TDir.&in, true, true, val);
end;
t := TRegEx.Replace(t,rx,PARSED_MARKER_STR,[roMultiLine] );
for m in TRegEx.Matches(c, rx3, [roMultiLine]) do
begin
val := m.Groups['expr'].Value;
LType := convertType(m.Groups['type'].Value);
if val.StartsWith('''') then
if val.Length=3 then
LType := 'Char'
else
LType := 'String';
TVariable.Create(u.GlobalVars, m.Groups['name'].Value,lType, TDir.&inout, true, true, val);
end;
t := TRegEx.Replace(t,rx3,PARSED_MARKER_STR,[roMultiLine] );
for m in TRegEx.Matches(c, rx4, [roMultiLine]) do
begin
val := m.Groups['expr'].Value;
val := val.Replace('"','''');
LType := convertType(m.Groups['type'].Value);
if val.StartsWith('''') then
LType := 'Char';
LType := 'TArray<'+LType+'>';
if LType='TArray<Char>' then
LType := 'String';
TVariable.Create(u.GlobalVars, m.Groups['name'].Value, LType, TDir.&inout, true, true, val);
end;
t := TRegEx.Replace(t,rx3,PARSED_MARKER_STR,[roMultiLine] );
WithoutRoutines := RemoveRoutines(c);
Code := TCode.Create(nil, WithoutRoutines.Split([sLineBreak]));
try
// vars := TVariableList.Create;
// vars.Name := 'vars';
getLocalVars( Code, u.GlobalVars );
finally
code.Free;
end;
end;
procedure AddStructs(var u: TPascalUnit; const c: string; aOnProgress:TOnProgress);
var
m: TMatch;
mc:TMatchCollection;
struct: TClassDef;
StructStr,name: string;
i: Integer;
const
minv = 0.75;
scale = 0.1;
begin
// search for struct definitions
mc := TRegEx.Matches(c, 'struct\s+(?<packed>PACKED)?\s*(?<name>'+rxID+')[^{^)]*\{', [roMultiLine]);
i := 0;
for m in mc do
begin
name := m.Groups['name'].Value;
if name.StartsWith('*') then
Continue;
if assigned(aOnprogress) then
aOnProgress(minV+scale*i/mc.count,'Struct:'+Name);
StructStr := '';
ScanUntilMatchingChar('{','}',c,m,StructStr);
if StructStr='' then
Continue;
if c_StructToPas(u,StructStr, struct) then
begin
struct.Sourceinfo.Position := m.Index;
struct.Sourceinfo.Length := StructStr.Length;
u.AddClass(struct);
end;
inc(i);
end;
end;
procedure ReplaceOutsideCommentsOrStrings(var v: string;cFrom,cTo:char);
var
inBlockComment: Boolean;
inLineComment: Boolean;
ix: Integer;
begin
inBlockComment := false;
inLineComment := false;
if length(v) > 2 then
for Ix := 1 to length(v) - 1 do
begin
if (v[Ix] = '/') and (v[Ix + 1] = '/') then inLineComment := True;
if CharInSet(v[iX],[#10,#13]) then inLineComment := False;
if (v[Ix] = '/') and (v[Ix + 1] = '*') then inBlockComment := True;
if (v[Ix] = '*') and (v[Ix + 1] = '/') then inBlockComment := False;
if (not inLineComment) and (not inBlockComment) then
if SameText(copy(v,ix,length(cFrom)) , cFrom) then
v[Ix] := cTo;
end;
end;
procedure ReplaceInBlockComments(var v: string;cFrom,cTo:char);
var
inComment: Boolean;
ix: Integer;
begin
inComment := false;
if length(v) > 2 then
for Ix := 1 to length(v) - 1 do
begin
if inComment then
if v[Ix] = cFrom then
v[Ix] := cTo
else if (v[Ix] = '*') and (v[Ix + 1] = '/') then
inComment := False;
if (v[Ix] = '/') and (v[Ix + 1] = '*') then
inComment := True;
end;
end;
procedure ReplaceInLineComments(var v: string;cFrom,cTo:char);
var
inComment: Boolean;
ix: Integer;
begin
inComment := false;
if length(v) > 2 then
for Ix := 1 to length(v) - 1 do
begin
if inComment then
if v[Ix] = cFrom then
v[Ix] := cTo
else if (v[Ix] = #13) or (v[Ix] = #10) then
inComment := False;
if (v[Ix] = '/') and (v[Ix + 1] = '/') then
inComment := True;
end;
end;
procedure ReplaceInComments(var v: string;cFrom,cTo:char);
begin
ReplaceInBlockComments(v,cFrom,cTo);
ReplaceInLineComments (v,cFrom,cTo);
end;
procedure AddEnums(var u: TPascalUnit; const c: string);
var
m,cm: TMatch; e:TEnumDef; Item:TEnumItem;
v,s: string; n:integer;
begin
// search for enum definitions
for m in TRegEx.Matches(c, '(?<typedef>typedef\s+)?enum\s*(?<name>'+rxType+')?\s*{(?<values>[^\}]*)}\s*(?<typedefname>'+rxType+')?', [roMultiLine]) do
begin
e := TEnumDef.Create(u);
if m.Groups['typedef'].Value<>'' then
e.Name := m.Groups['typedefname'].Value
else
e.Name := m.Groups['name'].Value;
e.SourceInfo.Position := m.Index-1;
e.SourceInfo.Length := m.Length;
n := 0;
v := m.Groups['values'].Value;
ReplaceInComments(v,',','.');
for s in v.Split([',']) do
begin
if s.Trim.IsEmpty then
Continue;
Item := Default(TEnumItem);
Item.Index := n;
if length(s.Split(['=']))>1 then
begin
Item.Value := StrToIntDef(s.Split(['='])[1],n);
Item.Name := s.Split(['='])[0].Trim.Replace(sLineBreak,' ');
n := Item.Value;
end
else
begin
Item.Value := n;
Item.Name := s.Trim;
end;
Item.Name := TRegEx.Replace(Item.Name,'/\*(?<comment>.*)?\*/','',[ ]).Trim;
cm := TRegEx.Match(s,'/\*(?<comment>.*)?\*/');
if cm.Success then
Item.Comment := cm.Groups['comment'].value;
if Item.Name.Trim<>'' then
e.Items := e.Items + [ Item ];
inc(n);
end;
u.Enums := u.Enums + [ e ];
end;
end;
procedure AddUnits(var Result: TPascalUnit; const aCCode: string; var t:string);
var
m: TMatch;
u: string;
const
rx = '^\s*#include\s*(?<inc>.*)\s*$';
begin
for m in TRegEx.Matches(aCCode, rx, [roMultiLine]) do
begin
u := m.Groups['inc'].Value;
u := TRegEx.Replace(u, '\/\/(.*)$', '{ \1 }');
u := TRegEx.Replace(u, '\/\*(.*)\*\/\s*', '');
u := u.Trim.Replace('/', '.')
.Replace('<', '')
.Replace('>', '')
.Replace('"', '')
.Replace('..', '')
;
if u.StartsWith('.') then
u := u.TrimLeft(['.']);
if ExtractFileExt(u) = '.h' then
u := ChangeFileExt(u, '');
if u='stdio' then Continue;
if u='stdlib' then Continue;
if u='string' then Continue;
Result.usesListIntf.AddUnit(u);
end;
t:=TRegEx.Replace(t,rx, PARSED_MARKER_STR,[roMultiLine]);
end;
procedure FixTypes(var s: string);
var m:TMatch;indent,t1,t2,v:string;
begin
s := s.Replace('std::string',
' string');
for m in tregex.Matches(s, '^(?<indent>\s*)(std::)?vector\<\s*(?<elType>'+rxType+')\s*\>\s*(?<val>'+rxID+')', [ roMultiLine ]) do
begin
indent := m.Groups['indent'].Value;
t1 := m.Groups['elType'].Value;
v := m.Groups['val'].Value;
t2 := convertType(t1);
if t1<>t2 then
begin
delete(s,m.Index, m.Length);
// t2 := 'TArray<'+t2+'>';
t2 := indent+t1+' '+v+'[]';
Insert(t2, s, m.Index);
end;
end;
s := s.Replace('std::vector',
' TArray');
s := s.Replace('(*','( *');
end;
procedure ApplyMacros(var s: string);
var u : TPascalUnit;t,fn:string; ul:TPascalElement; i:integer;
begin
// include header files
u := TPascalUnit.Create(nil);
try
AddUnits(u, s, t);
for i := 0 to u.usesListIntf.Count-1 do
begin
ul := u.usesListIntf[i];
fn := ul.Name;
if not TFile.Exists(fn) then
fn := ChangeFileExt(fn,'.h');
if not TFile.Exists(fn) then
fn := ChangeFileExt(fn,'.hpp');
if TFile.Exists(fn) then
s := s.Replace('#include '+ fn,TFile.ReadAllText(fn) )
end;
s := s.Replace('__DATE__',FormatDateTime('yyyy-mm-dd',now));
s := s.Replace('__TIME__',FormatDateTime('hh:nn:ss',now));
s := s.Replace('__FILE__',u.Name);
s := s.Replace('__LINE__','0' );
finally
u.Free
end;
end;
procedure c_to_pas(const aCCode:string; var t:string; aName:string;aOnProgress:TOnProgress; var Result:TPascalUnit);
var
s:string;
macro:TMacro;
begin
if not Assigned(Result) then
raise EArgumentNilException.Create('No Pascal unit provided');
if not Assigned(aOnProgress) then
raise EArgumentNilException.Create('No progress callback provided');
aOnProgress(0,'Converting');
FindDefines(result.Defines,aCCode);
Result.Name := aName;
Result.usesListIntf.&Unit := Result;
Result.usesListIntf.Name := 'Intf';
Result.usesListImpl.&Unit := Result;
Result.usesListImpl.Name := 'Impl';
s := aCCode;
ApplyMacros(s);
// s := ClearComments(s);
// s := TRegEx.Replace(s,',\s*\r\n',', '); // when there's a comma at the end of the line, remove the linebreak
FixTypes(s);
s := FixComments(s);
t := s;
macro.Identifier := 'EXPORTCALL';
macro.Replacements := ['__declspec(dllexport) __stdcall'];
ApplyMacro(s,macro);
aOnProgress(0.05,'Finding units...');
AddUnits(Result, s, t);
// aOnProgress(0.10,'Finding classes...');
AddClassDefs(Result,s,t);
aOnProgress(0.20,'Finding routines...');
AddFunctions(Result, aCCode, t,aOnProgress);
aOnProgress(0.60,'Finding enums...');
AddEnums(Result, s);
aOnProgress(0.65,'Finding 1D arrays...');
AddArrays1D(Result, s);
aOnProgress(0.70,'Finding 2D arrays...');
AddArrays2D(Result, s);
aOnProgress(0.75,'Finding structs...');
AddStructs(Result, s, aOnProgress);
// to find globally defined consts/variables,
// we first remove all detected routines and structs
aOnProgress(0.83,'Removing routines...');
s := RemoveRoutines(s, aOnProgress);
aOnProgress(0.84,'Removing structs...');
s := RemoveStructs(s);
aOnProgress(0.95,'Finding global declarations...');
AddConsts(Result, s, t);
aOnProgress(1.00,'Done.');
result.SetDefaultVisible;
end;
end.
|
unit NBasePerf;
interface
uses System.Generics.Collections, System.Classes, System.SysUtils;
type
TNPerfCounter = class
public
CounterName: String; // Performance name. any character
StartTime: TDateTime;
ElapsedMS: Single;
PerformCount: Int64; // Perform count. It is increased every AddCounter()
RecordCount: Int64; // item count. Max 9,223,372,036,854,775,808.
Dirty: Boolean;
procedure Start;
procedure Done(ARecord: Int64 = 1);
end;
TNPerf = class(TDictionary<String, TNPerfCounter>)
private
fThreadSafe: Boolean;
procedure _PrintDebug(AStrings: TStrings; ACounterName: String = '');
procedure _Start(ACounter: String);
procedure _Done(ACounter: String; ACountValue: Integer);
public
constructor Create;
destructor Destroy; override;
class procedure PrintDebug(AStrings: TStrings; ACounterName: String = '');
class procedure Start(ACounter: String);
class procedure Done(ACounter: String; ACountValue: Integer = 1);
class procedure SetThreadSafe(Value: Boolean);
end;
implementation
uses DateUtils, Math;
var
_GlobalPerf: TNPerf;
function GlobalPerf: TNPerf;
begin
if _GlobalPerf = nil then
_GlobalPerf := TNPerf.Create;
result := _GlobalPerf;
end;
{ TNPerf }
constructor TNPerf.Create;
begin
inherited Create;
end;
destructor TNPerf.Destroy;
begin
inherited;
end;
class procedure TNPerf.SetThreadSafe(Value: Boolean);
begin
GlobalPerf.fThreadSafe := Value;
end;
class procedure TNPerf.Start(ACounter: String);
begin
GlobalPerf._Start(ACounter);
end;
class procedure TNPerf.Done(ACounter: String; ACountValue: Integer = 1);
begin
GlobalPerf._Done(ACounter, ACountValue);
end;
class procedure TNPerf.PrintDebug(AStrings: TStrings; ACounterName: String);
begin
GlobalPerf._PrintDebug(AStrings, ACounterName);
end;
procedure TNPerf._PrintDebug(AStrings: TStrings; ACounterName: String = '');
var
k: String;
AStr1, AStr2: String;
begin
if fThreadSafe then
TMonitor.Enter(Self);
try
for k in Keys do begin
with Items[k] do begin
if (ACounterName = '') or SameText(CounterName, ACounterName) then begin
if RecordCount > 0 then
AStr1 := formatFloat('#,0', ElapsedMS / RecordCount)
else
AStr1 := '?';
if PerformCount > 0 then
AStr2 := formatFloat('#,0', ElapsedMS / PerformCount)
else
AStr2 := '?';
AStrings.Add(format('%s : Total performed=%s, elapsed=%s, record=%s. avg per record=%s(ms), avg per perform=%s(ms)',
[CounterName,
formatFloat('#,0', PerformCount),
formatFloat('#,0.000', ElapsedMS),
formatFloat('#,0', RecordCount),
AStr1, AStr2]));
end;
end;
end;
finally
if fThreadSafe then
TMonitor.Exit(Self);
end;
end;
procedure TNPerf._Start(ACounter: String);
var
p: TNPerfCounter;
begin
if Self = nil then
Exit;
if fThreadSafe then
TMonitor.Enter(Self);
try
if not TryGetValue(ACounter, p) then begin
p := TNPerfCounter.Create;
p.CounterName := ACounter;
Add(ACounter, p);
end
else if p.Dirty then
raise Exception.Create(format('Performance counter "%s" duplicated', [ACounter]));
p.Start;
finally
if fThreadSafe then
TMonitor.Exit(Self);
end;
end;
procedure TNPerf._Done(ACounter: String; ACountValue: Integer);
var
p: TNPerfCounter;
begin
if Self = nil then
Exit;
if fThreadSafe then
TMonitor.Enter(Self);
try
if not TryGetValue(ACounter, p) then begin
p := TNPerfCounter.Create;
p.CounterName := ACounter;
Add(ACounter, p);
end;
p.Dirty := false;
p.Done(ACountValue);
finally
if fThreadSafe then
TMonitor.Exit(Self);
end;
end;
{ TNPerfCounter }
procedure TNPerfCounter.Done(ARecord: Int64 = 1);
begin
ElapsedMS := ElapsedMS + MilliSecondsBetween(StartTime, now);
PerformCount := PerformCount + 1;
RecordCount := RecordCount + ARecord;
Dirty := false;
end;
procedure TNPerfCounter.Start;
begin
StartTime := Now;
Dirty := true;
end;
end.
|
{*****************************************************************************}
{ BindAPI }
{ Copyright (C) 2020 Paolo Morandotti }
{ Unit plBindAPI.AutoBinder }
{*****************************************************************************}
{ }
{Permission is hereby granted, free of charge, to any person obtaining }
{a copy of this software and associated documentation files (the "Software"), }
{to deal in the Software without restriction, including without limitation }
{the rights to use, copy, modify, merge, publish, distribute, sublicense, }
{and/or sell copies of the Software, and to permit persons to whom the }
{Software is furnished to do so, subject to the following conditions: }
{ }
{The above copyright notice and this permission notice shall be included in }
{all copies or substantial portions of the Software. }
{ }
{THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS }
{OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, }
{FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE }
{AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER }
{LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING }
{FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS }
{IN THE SOFTWARE. }
{*****************************************************************************}
unit plBindAPI.AutoBinder;
interface
uses
System.Classes, System.Rtti, System.Generics.Collections,
plBindAPI.Types, plBindAPI.Attributes, plBindAPI.CoreBinder;
type
TarAttributes = TArray<TCustomAttribute>;
TarFields = TArray<TRttiField>;
TarMethods = TArray<TRttiMethod>;
TarProperties = TArray<TRttiProperty>;
TListObjects = TList<TObject>;
TplAutoBinder = class(TInterfacedObject, IplAutoBinder)
private
FBinder: TPlBinder;
FIsDefault: Boolean; {Thread unsafe}
FLastBound: TListObjects;
procedure BindAll(ASource, aTarget: TObject);
function BindClass(ASource, aTarget: TObject): Boolean;
procedure BindClassAttributes(ASource, aTarget: TObject);
procedure BindField(ASource, aTarget: TObject; AnAttribute: FieldBindAttribute; AFieldNAme: string = '');
procedure BindFields(ASource, aTarget: TObject; AList: TarFields);
procedure BindMethod(ASource, aTarget: TObject; AnAttribute: MethodBindAttribute);
procedure BindMethods(ASource, aTarget: TObject; AList: TarMethods);
procedure BindProperty(ASource, aTarget: TObject; const SourceProperty: string; AnAttribute: PropertiesBindAttribute);
procedure BindProperties(ASource, aTarget: TObject; AList: TarProperties);
function CanBind(AnAttribute: CustomBindAttribute; ATarget: TObject): boolean;
function GetEnabled: Boolean;
function GetInterval: integer;
function FindCalculatingFuncion(AnOwner: TObject; const AFunctionName: string): TplBridgeFunction;
procedure SetEnabled(const Value: Boolean);
procedure SetInterval(const Value: integer);
procedure UnbindMethod(ASource: TObject; AnAttribute: MethodBindAttribute);
procedure UnbindMethods; overload;
public
constructor Create;
destructor Destroy; override;
public
property Enabled: Boolean read GetEnabled write SetEnabled;
property Interval: integer read GetInterval write SetInterval;
procedure Bind(ASource: TObject; const APropertySource: string; ATarget: TObject; const APropertyTarget: string; AFunction: TplBridgeFunction = nil);
procedure BindObject(ASource, aTarget: TObject);
function Count: integer;
procedure Start(const SleepInterval: Integer);
procedure Stop;
procedure UnbindMethods(ASource: TObject); overload;
procedure UnbindSource(ASource: TObject);
procedure UnbindTarget(ATarget: TObject);
procedure UpdateValues;
end;
implementation
uses
TypInfo, System.StrUtils;
{ TplAutoBinder }
procedure TplAutoBinder.Bind(ASource: TObject; const APropertySource: string;
ATarget: TObject; const APropertyTarget: string;
AFunction: TplBridgeFunction);
begin
FBinder.Bind(ASource, APropertySource, ATarget, APropertyTarget, AFunction);
end;
procedure TplAutoBinder.BindAll(ASource, aTarget: TObject);
var
rContext: TRttiContext;
rFields: TarFields;
rMethods: TarMethods;
rProperties: TarProperties;
rType: TRttiType;
begin
rContext := TRttiContext.Create;
rType := rContext.GetType(ASource.ClassType);
rFields := rType.GetFields;
rMethods := rType.GetMethods;
rProperties := rType.GetProperties;
BindProperties(ASource, aTarget, rProperties);
BindFields(ASource, aTarget, rFields);
BindMethods(ASource, aTarget, rMethods);
rContext.Free;
end;
function TplAutoBinder.BindClass(ASource, aTarget: TObject): boolean;
var
classBinder: ClassBindAttribute;
rContext: TRttiContext;
rType: TRttiType;
rAttr: TCustomAttribute;
rAttributes: TarAttributes;
begin
Result := False;
if not Assigned(aTarget) then
aTarget := Self;
rContext := TRttiContext.Create;
rType := rContext.GetType(ASource.ClassType);
rAttributes := rType.GetAttributes;
for rAttr in rAttributes do
if rAttr is ClassBindAttribute then
begin
classBinder := ClassBindAttribute(rAttr);
if (classBinder.IsEnabled) and
(classBinder.TargetClassName = aTarget.ClassName) then
begin
FLastBound.Add(ASource);
FIsDefault := ClassBindAttribute(rAttr).IsDefault;
Result := True;
Break;
end;
end;
rContext.Free;
end;
procedure TplAutoBinder.BindClassAttributes(ASource, aTarget: TObject);
var
rContext: TRttiContext;
rType: TRttiType;
rAttr: TCustomAttribute;
rAttributes: TarAttributes;
begin
rContext := TRttiContext.Create;
rType := rContext.GetType(ASource.ClassType);
rAttributes := rType.GetAttributes;
for rAttr in rAttributes do
if rAttr is FieldBindAttribute then
BindField(ASource, aTarget, FieldBindAttribute(rAttr))
else if rAttr is MethodBindAttribute then
BindMethod(ASource, aTarget, MethodBindAttribute(rAttr));
end;
procedure TplAutoBinder.BindFields(ASource, aTarget: TObject; AList: TarFields);
var
rField: TRttiField;
rAttr: TCustomAttribute;
begin
for rField in AList do
{ Search for the custom attribute and do some custom processing }
for rAttr in rField.GetAttributes() do
if (rAttr is FieldBindAttribute) and (rField.Visibility in [mvPublic, mvPublished]) then
BindField(ASource, aTarget, FieldBindAttribute(rAttr), rField.Name)
else if rAttr is MethodBindAttribute then
BindMethod( rField.GetValue(ASource).AsObject, aTarget, MethodBindAttribute(rAttr));
end;
procedure TplAutoBinder.BindField(ASource, aTarget: TObject;
AnAttribute: FieldBindAttribute; AFieldName: string = '');
var
calculateValue: TplBridgeFunction;
separator: string;
SourceObject: TObject;
SourcePath: string;
TargetObject: TObject;
TargetPath: string;
begin
if CanBind(AnAttribute, aTarget) then
begin
if AnAttribute.FunctionName <> '' then
calculateValue := FindCalculatingFuncion(aTarget, AnAttribute.FunctionName)
else
calculateValue := nil;
SourcePath := AnAttribute.SourcePath;
separator := IfThen(SourcePath <> '', '.', '');
if AFieldName <> '' then
SourcePath := AFieldName + separator + SourcePath;
TargetPath := AnAttribute.TargetPath;
SourceObject := FBinder.NormalizePath(ASource, SourcePath);
TargetObject := FBinder.NormalizePath(aTarget, TargetPath);
if (AnAttribute is BindFieldAttribute)
or (AnAttribute is BindFieldFromAttribute) then
Bind(TargetObject, TargetPath, SourceObject, SourcePath, calculateValue);
if (AnAttribute is BindFieldAttribute)
or (AnAttribute is BindFieldToAttribute) then
Bind(SourceObject, SourcePath, TargetObject, TargetPath, calculateValue);
end;
end;
procedure TplAutoBinder.BindMethod(ASource, aTarget: TObject;
AnAttribute: MethodBindAttribute);
begin
if CanBind(AnAttribute, aTarget) then
FBinder.BindMethod(ASource, AnAttribute.SourceMethodName, aTarget, AnAttribute.NewMethodName);
end;
procedure TplAutoBinder.BindMethods(ASource, aTarget: TObject; AList: TarMethods);
var
rMethod: TRttiMethod;
rAttr: TCustomAttribute;
begin
for rMethod in AList do
{ Search for the custom attribute and do some custom processing }
for rAttr in rMethod.GetAttributes() do
if rAttr is MethodBindAttribute then
BindMethod(ASource, aTarget, MethodBindAttribute(rAttr));
end;
procedure TplAutoBinder.BindObject(ASource, aTarget: TObject);
begin
if BindClass(ASource, aTarget) then
begin
BindClassAttributes(ASource, aTarget);
BindAll(ASource, aTarget);
end;
end;
procedure TplAutoBinder.BindProperties(ASource, aTarget: TObject; AList: TarProperties);
var
rProperty: TRttiProperty;
rAttr: TCustomAttribute;
begin
for rProperty in AList do
{ Search for the custom attribute and do some custom processing }
for rAttr in rProperty.GetAttributes() do
if rAttr is PropertiesBindAttribute then
BindProperty(ASource, aTarget, rProperty.Name, PropertiesBindAttribute(rAttr))
else if rAttr is MethodBindAttribute then
BindMethod(rProperty.GetValue(ASource).AsObject, aTarget, MethodBindAttribute(rAttr));
end;
procedure TplAutoBinder.BindProperty(ASource, aTarget: TObject;
const SourceProperty: string; AnAttribute: PropertiesBindAttribute);
var
SourceObject: TObject;
SourcePath: string;
TargetObject: TObject;
TargetPath: string;
calculateValue: TplBridgeFunction;
begin
if CanBind(AnAttribute, aTarget) then
begin
if AnAttribute.FunctionName <> '' then
calculateValue := FindCalculatingFuncion(aTarget, AnAttribute.FunctionName)
else
calculateValue := nil;
SourcePath := SourceProperty;
TargetPath := AnAttribute.TargetName;
SourceObject := FBinder.NormalizePath(ASource, SourcePath);
TargetObject := FBinder.NormalizePath(aTarget, TargetPath);
if (AnAttribute is BindPropertyAttribute)
or (AnAttribute is BindPropertyFromAttribute) then
Bind(TargetObject, TargetPath, SourceObject, SourcePath, calculateValue);
if (AnAttribute is BindPropertyAttribute)
or (AnAttribute is BindPropertyToAttribute) then
Bind(SourceObject, SourcePath, TargetObject, TargetPath, calculateValue);
end
end;
function TplAutoBinder.CanBind(AnAttribute: CustomBindAttribute; ATarget: TObject): boolean;
begin
Result := AnAttribute.IsEnabled and
(((AnAttribute.TargetClassName = '') and FIsDefault)or
(AnAttribute.TargetClassName = ATarget.ClassName));
end;
constructor TplAutoBinder.Create;
begin
inherited;
FBinder := TPlBinder.Create;
FLastBound := TListObjects.Create;
end;
destructor TplAutoBinder.Destroy;
begin
UnbindMethods;
FLastBound.Free;
FBinder.Free;
inherited;
end;
function TplAutoBinder.FindCalculatingFuncion(AnOwner: TObject;
const AFunctionName: string): TplBridgeFunction;
var
rContext: TRttiContext;
rType: TRttiType;
rMethod: TRTTIMethod;
methodPath: string;
recMethod: TMethod;
targetObject: TObject;
begin
methodPath := AFunctionName;
rContext := TRttiContext.Create;
TargetObject := FBinder.NormalizePath(AnOwner, methodPath);
{ Extract type information for ASource's type }
rType := rContext.GetType(targetObject.ClassType);
rMethod := rType.GetMethod(methodPath);
if Assigned(rMethod) then
begin
recMethod.Code := rMethod.CodeAddress;
recMethod.Data := pointer(targetObject); //(Self);
end;
Result := TplBridgeFunction(recMethod);
end;
function TplAutoBinder.Count: integer;
begin
Result := FBinder.Count;
end;
function TplAutoBinder.GetEnabled: Boolean;
begin
Result := FBinder.Enabled;
end;
function TplAutoBinder.GetInterval: integer;
begin
Result := FBinder.Interval;
end;
procedure TplAutoBinder.SetEnabled(const Value: Boolean);
begin
FBinder.Enabled := Value;
end;
procedure TplAutoBinder.SetInterval(const Value: integer);
begin
FBinder.Interval := Value;
end;
procedure TplAutoBinder.Start(const SleepInterval: Integer);
begin
FBinder.Start(SleepInterval);
end;
procedure TplAutoBinder.Stop;
begin
FBinder.Stop;
end;
procedure TplAutoBinder.UnbindMethod(ASource: TObject; AnAttribute: MethodBindAttribute);
var
propertyPath: string;
targetObject: TObject;
recMethod: TMethod ;
begin
if CanBind(AnAttribute, ASource) then
begin
propertyPath := AnAttribute.SourceMethodName;
targetObject := FBinder.NormalizePath(ASource, propertyPath);
recMethod.Code := nil;
recMethod.Data := nil;
SetMethodProp(targetObject, propertyPath, recMethod);
end;
end;
procedure TplAutoBinder.UnbindMethods(ASource: TObject);
var
rContext: TRttiContext;
rType: TRttiType;
rAttr: TCustomAttribute;
rAttributes: TarAttributes;
begin
rContext := TRttiContext.Create;
rType := rContext.GetType(ASource.ClassType);
rAttributes := rType.GetAttributes;
for rAttr in rAttributes do
if rAttr is MethodBindAttribute then
UnbindMethod(ASource, MethodBindAttribute(rAttr));
FLastBound.Remove(ASource);
rContext.Free;
end;
procedure TplAutoBinder.UnbindMethods;
var
target: TObject;
begin
for target in FLastBound do
try
UnbindMethods(target);
except
Continue;
end;
end;
procedure TplAutoBinder.UnbindSource(ASource: TObject);
begin
FBinder.DetachAsSource(ASource);
end;
procedure TplAutoBinder.UnbindTarget(ATarget: TObject);
begin
FBinder.DetachAsTarget(ATarget);
end;
procedure TplAutoBinder.UpdateValues;
begin
FBinder.UpdateValues;
end;
end.
|
unit ufrm_main;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.ImageList,
System.Actions,
System.UITypes,
Vcl.ImgList,
Vcl.ActnList,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ExtCtrls,
Vcl.Menus,
Vcl.StdCtrls,
cxGraphics,
cxControls,
cxLookAndFeels,
cxLookAndFeelPainters,
dxRibbonSkins,
dxSkinsCore,
dxSkinBlack,
dxSkinBlue,
dxSkinBlueprint,
dxSkinCaramel,
dxSkinCoffee,
dxSkinDarkRoom,
dxSkinDarkSide,
dxSkinDevExpressDarkStyle,
dxSkinDevExpressStyle,
dxSkinFoggy,
dxSkinGlassOceans,
dxSkinHighContrast,
dxSkiniMaginary,
dxSkinLilian,
dxSkinLiquidSky,
dxSkinLondonLiquidSky,
dxSkinMcSkin,
dxSkinMetropolis,
dxSkinMetropolisDark,
dxSkinMoneyTwins,
dxSkinOffice2007Black,
dxSkinOffice2007Blue,
dxSkinOffice2007Green,
dxSkinOffice2007Pink,
dxSkinOffice2007Silver,
dxSkinOffice2010Black,
dxSkinOffice2010Blue,
dxSkinOffice2010Silver,
dxSkinOffice2013DarkGray,
dxSkinOffice2013LightGray,
dxSkinOffice2013White,
dxSkinOffice2016Colorful,
dxSkinOffice2016Dark,
dxSkinPumpkin,
dxSkinSeven,
dxSkinSevenClassic,
dxSkinSharp,
dxSkinSharpPlus,
dxSkinSilver,
dxSkinSpringTime,
dxSkinStardust,
dxSkinSummer2008,
dxSkinTheAsphaltWorld,
dxSkinsDefaultPainters,
dxSkinValentine,
dxSkinVisualStudio2013Blue,
dxSkinVisualStudio2013Dark,
dxSkinVisualStudio2013Light,
dxSkinVS2010, dxSkinWhiteprint,
dxSkinXmas2008Blue,
dxSkinsdxRibbonPainter,
dxRibbonCustomizationForm,
cxContainer,
cxEdit,
dxSkinscxPCPainter,
dxSkinsdxBarPainter,
dxSkinsForm,
dxBar,
dxStatusBar,
dxRibbonStatusBar,
cxLabel,
dxGalleryControl,
dxRibbonBackstageViewGalleryControl,
dxRibbonBackstageView,
cxClasses,
dxRibbon,
dxBevel,
dxGDIPlusClasses,
cxLocalization,
cxImageList,
ACBrBase,
ufrm_main_default,
ufrm_login,
ufrm_client,
ufrm_contract,
ufrm_contract_user,
ufrm_enterprise,
ufrm_phonebook,
ufrm_report,
ufrm_supplier,
ufrm_voip_server,
ufrm_import_astpp,
ufrm_print_astpp,
ufrm_import_sippulse,
ufrm_did,
ufrm_provider, dxSkinTheBezier;
type
Tfrm_main = class(Tfrm_main_default)
Action_contract: TAction;
Action_contract_user: TAction;
Action_enterprise: TAction;
Action_client: TAction;
Action_supplier: TAction;
Action_phonebook: TAction;
Action_report: TAction;
dxBarLargeButton1: TdxBarLargeButton;
dxBarLargeButton2: TdxBarLargeButton;
dxBarLargeButton3: TdxBarLargeButton;
dxBarLargeButton4: TdxBarLargeButton;
dxBarLargeButton5: TdxBarLargeButton;
dxBarManager_1Bar2: TdxBar;
dxBarManager_1Bar3: TdxBar;
dxBarLargeButton6: TdxBarLargeButton;
dxBarLargeButton7: TdxBarLargeButton;
dxBarManager_1Bar4: TdxBar;
rbpopmenu_1: TdxRibbonPopupMenu;
dxBarButton1: TdxBarButton;
Action_voip_server: TAction;
dxBarLargeButton10: TdxBarLargeButton;
dxBarButton3: TdxBarButton;
dxBarLargeButtonContaTelefonica: TdxBarLargeButton;
Action_import_astpp: TAction;
dxBarSubItem1: TdxBarSubItem;
dxBarButton4: TdxBarButton;
Action_import_sippulse: TAction;
dxBarButton5: TdxBarButton;
dxBarSubItem2: TdxBarSubItem;
dxBarManager_1Bar5: TdxBar;
Action_invoice_unified: TAction;
Action_invoice_astpp: TAction;
Action_invoice_sippulse: TAction;
dxBarButton6: TdxBarButton;
dxBarButton7: TdxBarButton;
dxBarButton8: TdxBarButton;
dxBarLargeButton8: TdxBarLargeButton;
dxBarSubItem3: TdxBarSubItem;
dxBarButton2: TdxBarButton;
Action_provider: TAction;
Action_did: TAction;
dxBarButton9: TdxBarButton;
procedure FormCreate(Sender: TObject);
procedure Action_contractExecute(Sender: TObject);
procedure Action_contract_userExecute(Sender: TObject);
procedure Action_enterpriseExecute(Sender: TObject);
procedure Action_clientExecute(Sender: TObject);
procedure Action_supplierExecute(Sender: TObject);
procedure Action_phonebookExecute(Sender: TObject);
procedure Action_reportExecute(Sender: TObject);
procedure Action_voip_serverExecute(Sender: TObject);
procedure Action_import_astppExecute(Sender: TObject);
procedure Action_invoice_astppExecute(Sender: TObject);
procedure Action_import_sippulseExecute(Sender: TObject);
procedure Action_providerExecute(Sender: TObject);
procedure Action_didExecute(Sender: TObject);
private
public
end;
var
frm_main: Tfrm_main;
implementation
{$R *.dfm}
procedure Tfrm_main.Action_phonebookExecute(Sender: TObject);
begin
inherited;
if not Assigned(frm_phonebook) then begin
frm_phonebook := Tfrm_phonebook.Create(Self);
frm_phonebook.Height := Bevel_1.Height;
frm_phonebook.Width := Bevel_1.Width;
frm_phonebook.Show;
end else begin
frm_phonebook.WindowState := wsNormal;
frm_phonebook.Show;
end;
end;
procedure Tfrm_main.Action_providerExecute(Sender: TObject);
begin
inherited;
if not Assigned(frm_provider) then begin
frm_provider := Tfrm_provider.Create(Self);
frm_provider.Height := Bevel_1.Height;
frm_provider.Width := Bevel_1.Width;
frm_provider.Show;
end else begin
frm_provider.WindowState := wsNormal;
frm_provider.Show;
end;
end;
procedure Tfrm_main.Action_reportExecute(Sender: TObject);
begin
inherited;
if not Assigned(frm_report) then begin
frm_report := Tfrm_report.Create(Self);
frm_report.Height := Bevel_1.Height;
frm_report.Width := Bevel_1.Width;
frm_report.Show;
end else begin
frm_report.WindowState := wsNormal;
frm_report.Show;
end;
end;
procedure Tfrm_main.Action_clientExecute(Sender: TObject);
begin
inherited;
if not Assigned(frm_client) then begin
frm_client := Tfrm_client.Create(Self);
frm_client.Height := Bevel_1.Height;
frm_client.Width := Bevel_1.Width;
frm_client.Show;
end else begin
frm_client.WindowState := wsNormal;
frm_client.Show;
end;
end;
procedure Tfrm_main.Action_contractExecute(Sender: TObject);
begin
inherited;
if not Assigned(frm_contract) then begin
frm_contract := Tfrm_contract.Create(Self);
frm_contract.Height := Bevel_1.Height;
frm_contract.Width := Bevel_1.Width;
frm_contract.Show;
end else begin
frm_contract.WindowState := wsNormal;
frm_contract.Show;
end;
end;
procedure Tfrm_main.Action_contract_userExecute(Sender: TObject);
begin
inherited;
if not Assigned(frm_contract_user) then begin
frm_contract_user := Tfrm_contract_user.Create(Self);
frm_contract_user.Height := Bevel_1.Height;
frm_contract_user.Width := Bevel_1.Width;
frm_contract_user.Show;
end else begin
frm_contract_user.WindowState := wsNormal;
frm_contract_user.Show;
end;
end;
procedure Tfrm_main.Action_didExecute(Sender: TObject);
begin
inherited;
if not Assigned(frm_did) then begin
frm_did := Tfrm_did.Create(Self);
frm_did.Height := Bevel_1.Height;
frm_did.Width := Bevel_1.Width;
frm_did.Show;
end else begin
frm_did.WindowState := wsNormal;
frm_did.Show;
end;
end;
procedure Tfrm_main.Action_enterpriseExecute(Sender: TObject);
begin
inherited;
if not Assigned(frm_enterprise) then begin
frm_enterprise := Tfrm_enterprise.Create(Self);
frm_enterprise.Height := Bevel_1.Height;
frm_enterprise.Width := Bevel_1.Width;
frm_enterprise.Show;
end else begin
frm_enterprise.WindowState := wsNormal;
frm_enterprise.Show;
end;
end;
procedure Tfrm_main.Action_import_astppExecute(Sender: TObject);
begin
inherited;
if not Assigned(frm_import_astpp) then begin
frm_import_astpp := Tfrm_import_astpp.Create(Self);
frm_import_astpp.Height := Bevel_1.Height;
frm_import_astpp.Width := Bevel_1.Width;
frm_import_astpp.Show;
end else begin
frm_import_astpp.WindowState := wsNormal;
frm_import_astpp.Show;
end;
end;
procedure Tfrm_main.Action_import_sippulseExecute(Sender: TObject);
begin
inherited;
if not Assigned(frm_import_sippulse) then begin
frm_import_sippulse := Tfrm_import_sippulse.Create(Self);
frm_import_sippulse.Height := Bevel_1.Height;
frm_import_sippulse.Width := Bevel_1.Width;
frm_import_sippulse.Show;
end else begin
frm_import_sippulse.WindowState := wsNormal;
frm_import_sippulse.Show;
end;
end;
procedure Tfrm_main.Action_invoice_astppExecute(Sender: TObject);
begin
inherited;
if not Assigned(frm_print_astpp) then begin
frm_print_astpp := Tfrm_print_astpp.Create(Self);
frm_print_astpp.Height := Bevel_1.Height;
frm_print_astpp.Width := Bevel_1.Width;
frm_print_astpp.Show;
end else begin
frm_print_astpp.WindowState := wsNormal;
frm_print_astpp.Show;
end;
end;
procedure Tfrm_main.Action_supplierExecute(Sender: TObject);
begin
inherited;
if not Assigned(frm_supplier) then begin
frm_supplier := Tfrm_supplier.Create(Self);
frm_supplier.Height := Bevel_1.Height;
frm_supplier.Width := Bevel_1.Width;
frm_supplier.Show;
end else begin
frm_supplier.WindowState := wsNormal;
frm_supplier.Show;
end;
end;
procedure Tfrm_main.Action_voip_serverExecute(Sender: TObject);
begin
inherited;
if not Assigned(frm_voip_server) then begin
frm_voip_server := Tfrm_voip_server.Create(Self);
frm_voip_server.Height := Bevel_1.Height;
frm_voip_server.Width := Bevel_1.Width;
frm_voip_server.Show;
end else begin
frm_voip_server.WindowState := wsNormal;
frm_voip_server.Show;
end;
end;
procedure Tfrm_main.FormCreate(Sender: TObject);
begin
inherited;
modulo:='TELEFONIA';
frm_login := Tfrm_login.Create(Self);
frm_login.ShowModal;
if frm_login.ModalResult <> mrOk then begin
MessageDlg('Você não se autenticou. A aplicação será encerrada!', mtWarning, [mbOK], 0);
Application.Terminate;
end;
end;
end.
|
unit jclass_fields;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
jclass_items,
jclass_enum,
jclass_common_abstract,
fgl;
type
{ TJClassField }
TJClassField = class(TJClassItem)
public
procedure LoadFromStream(AStream: TStream); override;
end;
{ TJClassFields }
TJClassFields = class(specialize TFPGObjectList<TJClassField>)
private
FClassFile: TJClassFileAbstract;
public
procedure BuildDebugInfo(AIndent: string; AOutput: TStrings);
procedure LoadFromStream(AStream: TStream);
constructor Create(AClassFile: TJClassFileAbstract);
end;
implementation
{ TJClassFields }
procedure TJClassFields.BuildDebugInfo(AIndent: string; AOutput: TStrings);
var
i: integer;
begin
AOutput.Add('%sCount: %d', [AIndent, Count]);
for i := 0 to Count - 1 do
begin
AOutput.Add('%s %s', [AIndent, FClassFile.FindUtf8Constant(Items[i].NameIndex)]);
Items[i].BuildDebugInfo(AIndent + ' ', AOutput);
end;
end;
procedure TJClassFields.LoadFromStream(AStream: TStream);
var
item: TJClassField;
itemsCount: UInt16;
i: integer;
begin
itemsCount := FClassFile.ReadWord(AStream);
for i := 0 to itemsCount - 1 do
begin
item := TJClassField.Create(FClassFile);
try
item.LoadFromStream(AStream);
Add(item);
except
item.Free;
raise;
end;
end;
end;
constructor TJClassFields.Create(AClassFile: TJClassFileAbstract);
begin
inherited Create();
FClassFile := AClassFile;
end;
{ TJClassField }
procedure TJClassField.LoadFromStream(AStream: TStream);
begin
FAccessFlags := ReadWord(AStream);
FNameIndex := ReadWord(AStream);
FDescriptorIndex := ReadWord(AStream);
FAttributes.LoadFromStream(AStream, alFieldInfo);
end;
end.
|
unit U_DtmCadastroCurso;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, sqldb, db, FileUtil, U_Utils, U_DtmPrincipal,
U_Curso;
type
{ TDtmCadastroCurso }
TDtmCadastroCurso = class(TDataModule)
qryCurso: TSQLQuery;
qryPesquisa: TSQLQuery;
qryPesquisaCODIGO: TLongintField;
qryPesquisaNOME: TStringField;
private
public
function salvarCurso(pCurso:TCurso; pControle:TControle):boolean;
function getCurso(pCodigo:Integer):TCurso;
function deleteCurso(pCodigo:Integer):Boolean;
end;
var
DtmCadastroCurso: TDtmCadastroCurso;
implementation
{$R *.lfm}
{ TDtmCadastroCurso }
function TDtmCadastroCurso.salvarCurso(pCurso:TCurso; pControle: TControle): boolean;
begin
try
qryCurso.Close;
if (pControle = tpNovo) then
qryCurso.SQL.Text:='INSERT INTO CURSO (COD_CURSO, DES_CURSO) VALUES (:COD_CURSO, :DES_CURSO)'
else
qryCurso.SQL.Text:='UPDATE CURSO SET DES_CURSO = :DES_CURSO WHERE COD_CURSO = :COD_CURSO';
qryCurso.ParamByName('COD_CURSO').AsInteger:=pCurso.codigo;
qryCurso.ParamByName('DES_CURSO').AsString:=pCurso.descicao;
qryCurso.ExecSQL;
DtmPrincipal.FBTrans.CommitRetaining;
except
on E:exception do
begin
Result := False;
DtmPrincipal.FBTrans.RollbackRetaining;
MsgErro('Ocorreu um erro ao salvar o curso',E);
end;
end;
end;
function TDtmCadastroCurso.getCurso(pCodigo: Integer): TCurso;
var
curso : TCurso;
begin
try
qryCurso.Close;
qryCurso.SQL.Text:='SELECT COD_CURSO, DES_CURSO FROM CURSO WHERE COD_CURSO = :COD_CURSO';
qryCurso.ParamByName('COD_CURSO').AsInteger := pCodigo;
qryCurso.Open;
if not (qryCurso.IsEmpty) then
begin
curso := TCurso.Create;
curso.codigo := qryCurso.FieldByName('COD_CURSO').AsInteger;
curso.descicao := qryCurso.FieldByName('DES_CURSO').AsString;
Result := curso;
end
else
Result := nil;
except
on E:exception do
begin
Result := nil;
MsgErro('Ocorreu um erro ao pesquisar o curso',E);
end;
end;
end;
function TDtmCadastroCurso.deleteCurso(pCodigo: Integer): Boolean;
begin
try
qryCurso.Close;
qryCurso.SQL.Text:='DELETE FROM CURSO WHERE COD_CURSO = :COD_CURSO';
qryCurso.ParamByName('COD_CURSO').AsInteger := pCodigo;
qryCurso.ExecSQL;
DtmPrincipal.FBTrans.CommitRetaining;
Result := True;
except
on E:exception do
begin
Result := False;
DtmPrincipal.FBTrans.RollbackRetaining;
MsgErro('Ocorreu um erro ao deletar o curso.',E);
end;
end;
end;
end.
|
{ search-api
Copyright (c) 2019 mr-highball
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
}
unit search.query;
{$mode delphi}
interface
uses
Classes, SysUtils, search.types;
type
{ TQueryImpl }
(*
base implementation of IQuery
*)
TQueryImpl = class(TInterfacedObject,IQuery)
strict private
FCollection: TQueryCollection;
FParent: ISearchSettings;
strict protected
function GetCollection: TQueryCollection;
function GetOperations: TQueryOperations;
function GetParent: ISearchSettings;
//children override
function DoGetSupportedOperations: TQueryOperations;virtual;abstract;
public
//--------------------------------------------------------------------------
//properties
//--------------------------------------------------------------------------
property Collection : TQueryCollection read GetCollection;
property SupportedOperations : TQueryOperations read GetOperations;
property Parent : ISearchSettings read GetParent;
//--------------------------------------------------------------------------
//methods
//--------------------------------------------------------------------------
function Add(const AQuery: String;
const AOperation: TQueryOperation=qoAnd): IQuery;
function Clear: IQuery;
constructor Create(Const AParent: ISearchSettings);virtual;overload;
destructor destroy; override;
end;
implementation
{ TQueryImpl }
function TQueryImpl.Add(const AQuery: String;
const AOperation: TQueryOperation): IQuery;
var
LTerm: TQueryTerm;
begin
//initialize return and the query term
Result:=Self as IQuery;
LTerm.Text:=AQuery;
LTerm.Operation:=AOperation;
//we can exit if the term already exists
if FCollection.IndexOf(LTerm) > 0 then
Exit;
//add the term
FCollection.Add(LTerm);
end;
function TQueryImpl.Clear: IQuery;
begin
Result:=Self as IQuery;
FCollection.Clear;
end;
constructor TQueryImpl.Create(Const AParent: ISearchSettings);
begin
FCollection:=TQueryCollection.Create;
FParent:=AParent;
end;
destructor TQueryImpl.destroy;
begin
FCollection.Free;
FParent:=nil;
inherited destroy;
end;
function TQueryImpl.GetCollection: TQueryCollection;
begin
Result:=FCollection;
end;
function TQueryImpl.GetOperations: TQueryOperations;
begin
Result:=DoGetSupportedOperations;
end;
function TQueryImpl.GetParent: ISearchSettings;
begin
Result:=FParent;
end;
end.
|
unit ComboLists;
{
%ComboLists : 包含几个下拉框
}
(***** Code Written By Huang YanLai *****)
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls,LibMessages,ComWriUtils;
type
// %TCustomCodeValues : 包含一系列的Code-Value组(代码表)
TCustomCodeValues = class(TCompCommonAttrs)
private
FIsCodeSorted: boolean;
function GetCount: integer;
function GetCodes(index: integer): string;
function GetValues(index: integer): string;
procedure SetCodes(index: integer; const Value: string);
procedure SetValues(index: integer; const Value: string);
function GetNameCaseSen: boolean;
function GetValueCaseSen: boolean;
procedure SetNameCaseSen(const Value: boolean);
procedure SetValueCaseSen(const Value: boolean);
protected
FMap : TStringMap;
property NameCaseSen: boolean read GetNameCaseSen write SetNameCaseSen;
property ValueCaseSen:boolean read GetValueCaseSen write SetValueCaseSen;
property IsCodeSorted : boolean read FIsCodeSorted write FIsCodeSorted;
public
constructor Create(AOwner : TComponent); override;
Destructor Destroy;override;
property Codes[index : integer] : string read GetCodes write SetCodes;
property Values[index : integer] : string read GetValues write SetValues;
property Count : integer read GetCount;
function getValueByCode(const Code:string) : string;
function getCodeByValue(const value:string) : string;
function IndexOfCode(const Code:string) : integer;
function IndexOfValue(const value:string) : integer;
function FindNearestCode(const name:string) : integer;
function FindNearestValue(const Value:string) : integer;
end;
TCodeValues = class(TCustomCodeValues)
private
FItems: TStrings;
procedure SetItems(const Value: TStrings);
procedure ItemChanged(Sender : TObject);
procedure UpdateMap;
protected
procedure Loaded; override;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy;override;
property Map : TStringMap read FMap;
published
property Items : TStrings read FItems write SetItems;
end;
// %TCustomComboList : 下拉框显示TCustomCodeValues的Value值,返回实际Code
// #功能:直接输入代码;输入Value在下拉框中定位;过滤
TCustomComboList = class(TCustomComboBox)
private
{ Private declarations }
FValues : TCustomCodeValues;
FCanEdit: boolean;
FFiltered : boolean;
FTempList : TStringList;
procedure SetValues(const Value: TCustomCodeValues);
procedure UpdateItems;
procedure LMComAttrsChanged(var message : TMessage);message LM_ComAttrsChanged;
function getCode: string;
function getValue: string;
procedure SetCode(const Value: string);
procedure SetValue(const Value: string);
procedure SetCanEdit(const Value: boolean);
procedure FilterItems;
protected
{ Protected declarations }
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure KeyPress(var Key: Char); override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure FindThis;
function isCode(const s:string): boolean; virtual;
procedure DropDown; override;
procedure Change; override;
property Values : TCustomCodeValues read FValues write SetValues;
property CanEdit : boolean read FCanEdit write SetCanEdit default false;
property Filtered : boolean read FFiltered write FFiltered;
public
{ Public declarations }
constructor Create(AOwner : TComponent); override;
Destructor Destroy;override;
procedure Clear;
property Code : string read getCode write SetCode;
property Value : string read getValue write SetValue;
procedure GoNearestCode(const ACode:string);
procedure GoNearestValue(const AValue:string);
procedure RestoreItems;
published
{ Published declarations }
end;
// %TComboList : 下拉框显示TCustomCodeValues的Value值,返回实际Code
TComboList = class(TCustomComboList)
published
property Filtered;
property Values;
property Code;
property Value;
property CanEdit;
//property Style; {Must be published before Items}
property Anchors;
property BiDiMode;
property Color;
property Constraints;
property Ctl3D;
property DragCursor;
property DragKind;
property DragMode;
property DropDownCount;
property Enabled;
property Font;
property ImeMode;
property ImeName;
property ItemHeight;
//property Items;
//property MaxLength;
property ParentBiDiMode;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
//property Sorted;
property TabOrder;
property TabStop;
//property Text;
property Visible;
property OnChange;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnDrawItem;
property OnDropDown;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMeasureItem;
property OnStartDock;
property OnStartDrag;
end;
implementation
{ TCustomCodeValues }
constructor TCustomCodeValues.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FMap := TStringMap.Create(false,false);
end;
destructor TCustomCodeValues.Destroy;
begin
FMap.free;
inherited Destroy;
end;
function TCustomCodeValues.GetCount: integer;
begin
result := FMap.Count;
end;
function TCustomCodeValues.GetCodes(index: integer): string;
begin
result := FMap.Names[index];
end;
function TCustomCodeValues.GetValues(index: integer): string;
begin
result := FMap.Values[index];
end;
procedure TCustomCodeValues.SetCodes(index: integer; const Value: string);
begin
FMap.Names[index]:=value;
end;
procedure TCustomCodeValues.SetValues(index: integer; const Value: string);
begin
FMap.Values[index]:=value;
end;
function TCustomCodeValues.getCodeByValue(const Value:string): string;
var
i : integer;
begin
i:=Fmap.IndexOfValue(Value);
if i<0 then result:=''
else result:=Fmap.names[i];
end;
function TCustomCodeValues.getValueByCode(const Code:string): string;
var
i : integer;
begin
i := IndexOfCode(code);
if i<0 then result:=''
else result:=Fmap.Values[i];
end;
function TCustomCodeValues.IndexOfCode(const Code: string): integer;
begin
if FIsCodeSorted then
result:=Fmap.FindName(Code)
else result:=Fmap.IndexOfName(code);
end;
function TCustomCodeValues.IndexOfValue(const value: string): integer;
begin
result := Fmap.IndexOfValue(Value);
end;
function TCustomCodeValues.GetNameCaseSen: boolean;
begin
result := FMap.NameCaseSen;
end;
function TCustomCodeValues.GetValueCaseSen: boolean;
begin
result := FMap.ValueCaseSen;
end;
procedure TCustomCodeValues.SetNameCaseSen(const Value: boolean);
begin
FMap.NameCaseSen:=value;
end;
procedure TCustomCodeValues.SetValueCaseSen(const Value: boolean);
begin
FMap.ValueCaseSen:=value;
end;
function TCustomCodeValues.FindNearestCode(const name: string): integer;
begin
result := Fmap.FindNearestName(name);
end;
function TCustomCodeValues.FindNearestValue(const Value: string): integer;
begin
result := Fmap.FindNearestValue(Value);
end;
{ TCustomComboList }
constructor TCustomComboList.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Style := csDropDownList;
FCanEdit := false;
FTempList := TStringList.Create;
end;
destructor TCustomComboList.Destroy;
begin
FTempList.free;
inherited Destroy;
end;
procedure TCustomComboList.Clear;
begin
ItemIndex:=-1;
Change;
end;
function TCustomComboList.getCode: string;
begin
if ItemIndex=-1 then
result:=''
else
begin
assert(FValues<>nil);
//result := FValues.Codes[ItemIndex];
result := FValues.Codes[integer(items.objects[ItemIndex])];
end;
end;
function TCustomComboList.getValue: string;
begin
if ItemIndex=-1 then
result:=''
else result := Items[ItemIndex];
end;
procedure TCustomComboList.GoNearestCode(const ACode: string);
var
i : integer;
begin
RestoreItems;
if FValues<>nil then
begin
i := FValues.FindNearestCode(ACode);
ItemIndex:=i;
end
else ItemIndex:=-1;
Change;
end;
procedure TCustomComboList.GoNearestValue(const AValue: string);
var
i : integer;
begin
RestoreItems;
if FValues<>nil then
begin
i := FValues.FindNearestValue(AValue);
ItemIndex:=i;
end
else ItemIndex:=-1;
Change;
end;
procedure TCustomComboList.KeyPress(var Key: Char);
begin
inherited KeyPress(Key);
if CanEdit then
if Filtered and DroppedDown then FilterItems
else if not Filtered and (key=#13) then FindThis;
end;
procedure TCustomComboList.LMComAttrsChanged(var message: TMessage);
begin
if message.WParam=WParam(FValues) then
UpdateItems;
end;
procedure TCustomComboList.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent,Operation);
if (AComponent=FValues) and (Operation=opRemove) then
FValues:=nil;
end;
procedure TCustomComboList.SetCanEdit(const Value: boolean);
begin
if FCanEdit <> Value then
begin
FCanEdit := Value;
if FCanEdit then
Style := csDropDown
else Style := csDropDownList;
end;
end;
procedure TCustomComboList.SetCode(const Value: string);
var
i : integer;
begin
RestoreItems;
if FValues<>nil then
begin
i := FValues.IndexOfCode(Value);
ItemIndex:=i;
end
else ItemIndex:=-1;
Change;
end;
procedure TCustomComboList.SetValue(const Value: string);
var
i : integer;
begin
RestoreItems;
if FValues<>nil then
begin
i := FValues.IndexOfValue(Value);
ItemIndex:=i;
end
else ItemIndex:=-1;
Change;
end;
procedure TCustomComboList.SetValues(const Value: TCustomCodeValues);
begin
if SetCommonAttrsProp(self,TCompCommonAttrs(FValues),value) then
UpdateItems;
end;
procedure TCustomComboList.UpdateItems;
var
i : integer;
begin
Items.Clear;
if FValues<>nil then
for i:=0 to FValues.count-1 do
Items.AddObject(FValues.values[i],TObject(i));
end;
procedure TCustomComboList.FindThis;
begin
RestoreItems;
if items.count=0 then exit
else if text='' then
begin
itemIndex:=0;
Change;
end
else begin
if isCode(text) then GoNearestCode(text)
else GoNearestValue(text);
end;
end;
function TCustomComboList.isCode(const s: string): boolean;
begin
result := (s<>'') and (s[1] in ['0'..'9']);
end;
procedure TCustomComboList.KeyDown(var Key: Word; Shift: TShiftState);
begin
inherited KeyDown(Key,Shift);
if (key=VK_Delete) and (ssShift in Shift) then Clear
else if CanEdit and Filtered and DroppedDown and ((key=VK_Delete) or (key=VK_BACK)) then
FilterItems;
end;
procedure TCustomComboList.FilterItems;
var
s : string;
i : integer;
Save : integer;
begin
//ItemIndex:=-1;
if Values=nil then exit;
// save the SelStart
Save := SelStart;
s := text;
if s='' then RestoreItems //UpdateItems
else
begin
FtempList.BeginUpdate;
FtempList.Clear;
for i:=0 to values.count-1 do
begin
if pos(s,values.values[i])>0 then
FtempList.AddObject(values.values[i],TObject(i));
end;
FtempList.EndUpdate;
// 当用户选择一条记录时,不改变列表值
if not ((FtempList.count=1) and (FtempList[0]=s) and (Items.count>0)) then
Items.Assign(FtempList);
end;
// restore the SelStart
// 否则,Selstart=0,输入顺序反向
SelStart := save;
end;
procedure TCustomComboList.RestoreItems;
begin
if {Filtered and }(Values<>nil) and (Items.count<>Values.Count) then
UpdateItems;
end;
procedure TCustomComboList.DropDown;
begin
inherited DropDown;
if canEdit and Filtered then FilterItems
else RestoreItems;
end;
procedure TCustomComboList.Change;
begin
inherited Change;
//if DroppedDown and Filtered then FilterItems;
end;
{ TCodeValues }
constructor TCodeValues.Create(AOwner: TComponent);
begin
inherited;
FItems := TStringList.Create;
TStringList(FItems).OnChange := ItemChanged;
end;
destructor TCodeValues.Destroy;
begin
FreeAndNil(FItems);
inherited;
end;
procedure TCodeValues.ItemChanged(Sender: TObject);
begin
if not (csLoading in ComponentState) then
begin
UpdateMap;
end;
end;
procedure TCodeValues.Loaded;
begin
inherited;
UpdateMap;
end;
procedure TCodeValues.SetItems(const Value: TStrings);
begin
FItems.Assign(Value);
end;
procedure TCodeValues.UpdateMap;
var
I : Integer;
S : string;
Code, Value : string;
Index : Integer;
begin
Map.Clear;
for I:=0 to Items.Count-1 do
begin
S := Items[I];
Index := Pos('=',S);
if Index>0 then
begin
Value := Copy(S,1,Index-1);
Code:= Copy(S,Index+1,Length(S));
Map.Add(Code,Value);
end;
end;
end;
end.
|
{ $HDR$}
{**********************************************************************}
{ Unit archived using Team Coherence }
{ Team Coherence is Copyright 2002 by Quality Software Components }
{ }
{ For further information / comments, visit our WEB site at }
{ http://www.TeamCoherence.com }
{**********************************************************************}
{}
{ $Log: 13151: FormSettings.pas
{
{ Rev 1.0 2003-03-20 14:03:30 peter
}
{
{ Rev 1.0 2003-03-17 10:14:22 Supervisor
}
unit FormSettings;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Registry, StdCtrls;
type
TSaveValOpt = (svEdit, svMemo, svCheckBox, svRadioButton, svListBox,
svComboBox, svFontDialog);
TSaveValSet = set of TSaveValOpt;
TFormSettings = class(TComponent)
protected
FSavePos : boolean;
FSaveVals : boolean;
FLoadVals : boolean;
FKeyName : string;
FSaveOpt : TSaveValSet;
FRootCon : TWinControl;
DidLastSave : boolean;
procedure Loaded; override;
function StrToWS(const s: string): TWindowState;
function WSToStr(ws: TWindowState): string;
function GetKeyName: string;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure DoLoadValues(reg: TRegIniFile);
procedure DoSaveValues(reg: TRegIniFile);
procedure ReadFont(Name: string; f: TFont; reg: TRegIniFile);
procedure WriteFont(Name: string; f: TFont; reg: TRegIniFile);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure LoadSettings;
procedure SaveSettings;
published
property SavePosition: boolean read FSavePos write FSavePos;
property SaveValues: boolean read FSaveVals write FSaveVals;
property LoadValues: boolean read FLoadVals write FLoadVals;
property SaveValueOptions: TSaveValSet read FSaveOpt write FSaveOpt;
property KeyName: string read GetKeyName write FKeyName;
property RootControl: TWinControl read FRootCon write FRootCon;
end;
procedure Register;
implementation
const
WindowStr : array[1..3] of string = ('NORMAL', 'MAXIMIZED', 'MINIMIZED');
constructor TFormSettings.Create(AOwner: TComponent);
begin
inherited;
FreeNotification(AOwner);
FSavePos := True;
FSaveVals := False;
FLoadVals := False;
DidLastSave := False;
FSaveOpt := [svEdit, svMemo, svCheckBox, svRadioButton, svListBox,
svComboBox, svFontDialog];
end;
destructor TFormSettings.Destroy;
begin
inherited;
end;
procedure TFormSettings.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (not DidLastSave) and (csDestroying in ComponentState) then begin
DidLastSave := True;
// This still doesn't work! All the window handles are gone! -bpz
// SaveSettings;
end;
end;
procedure TFormSettings.Loaded;
begin
inherited;
LoadSettings;
end;
function TFormSettings.StrToWS(const s: string): TWindowState;
var
t : string;
begin
t := UpperCase(s);
Result := wsNormal;
if t = WindowStr[1] then Result := wsNormal;
if t = WindowStr[2] then Result := wsMaximized;
if t = WindowStr[3] then Result := wsMinimized;
end;
function TFormSettings.WSToStr(ws: TWindowState): string;
begin
case ws of
wsNormal : Result := WindowStr[1];
wsMaximized : Result := WindowStr[2];
wsMinimized : Result := WIndowStr[3];
else
Result := WindowStr[1];
end;
end;
function TFormSettings.GetKeyName: string;
begin
Result := FKeyName;
if (Result='') and (not (csDesigning in ComponentState))
and (Application<>nil) and (Owner<>nil) then
Result := 'Software\' + Application.Title + '\' + Owner.Name;
end;
procedure TFormSettings.LoadSettings;
var
f : TForm;
reg : TRegIniFile;
begin
if (Owner = nil) or (not (Owner is TForm)) then exit;
if csDesigning in ComponentState then exit;
f := Owner as TForm;
f.Position := poDesigned;
reg := TRegIniFile.Create(KeyName);
if SavePosition then begin
f.Left := reg.ReadInteger('Position', 'Left', f.Left);
f.Top := reg.ReadInteger('Position', 'Top', f.Top);
f.Width := reg.ReadInteger('Position', 'Width', f.Width);
f.Height := reg.ReadInteger('Position', 'Height', f.Height);
f.WindowState := StrToWS(reg.ReadString('Position', 'WindowState', 'Normal'));
end;
if LoadValues then
DoLoadValues(reg);
reg.Free;
end;
procedure TFormSettings.SaveSettings;
var
f : TForm;
reg : TRegIniFile;
begin
if (Owner = nil) or (not (Owner is TForm)) then exit;
if csDesigning in ComponentState then exit;
f := Owner as TForm;
f.Position := poDesigned;
reg := TRegIniFile.Create(KeyName);
if SavePosition then begin
if f.WindowState = wsNormal then begin
reg.WriteInteger('Position', 'Left', f.Left);
reg.WriteInteger('Position', 'Top', f.Top);
reg.WriteInteger('Position', 'Width', f.Width);
reg.WriteInteger('Position', 'Height', f.Height);
end;
reg.WriteString('Position', 'WindowState', WSToStr(f.WindowState));
end;
if SaveValues then
DoSaveValues(reg);
reg.Free;
end;
procedure TFormSettings.DoLoadValues(reg: TRegIniFile);
var
i : integer;
con : TWinControl;
c : TControl;
cp : TComponent;
begin
con := RootControl;
if con=nil then con := Owner as TForm;
Assert(con<>nil);
for i := 0 to con.ComponentCount-1 do begin
cp := con.Components[i];
if not (cp is TControl) then continue;
c := cp as TControl;
if c is TEdit then
TEdit(c).Text := reg.ReadString('Values', c.Name, TEdit(c).Text);
if c is TMemo then
TMemo(c).Text := reg.ReadString('Values', c.Name, TMemo(c).Text);
if c is TCheckBox then
TCheckBox(c).Checked := reg.ReadBool('Values', c.Name, TCheckBox(c).Checked);
if c is TRadioButton then
TRadioButton(c).Checked := reg.ReadBool('Values', c.Name, TRadioButton(c).Checked);
if c is TListBox then
TListBox(c).ItemIndex := reg.ReadInteger('Values', c.Name, TListBox(c).ItemIndex);
if c is TComboBox then
TComboBox(c).ItemIndex := reg.ReadInteger('Values', c.Name, TComboBox(c).ItemIndex);
end;
for i := 0 to con.ComponentCount-1 do begin
cp := con.Components[i];
if cp is TFontDialog then
ReadFont(cp.Name, TFontDialog(cp).Font, reg);
end;
end;
procedure TFormSettings.DoSaveValues(reg: TRegIniFile);
var
i : integer;
con : TWinControl;
c : TControl;
cp : TComponent;
begin
con := RootControl;
if con=nil then con := Owner as TForm;
Assert(con<>nil);
for i := 0 to con.ComponentCount-1 do begin
cp := con.Components[i];
if not (cp is TControl) then continue;
c := cp as TControl;
if c is TEdit then
reg.WriteString('Values', c.Name, TEdit(c).Text);
if c is TMemo then
reg.WriteString('Values', c.Name, TMemo(c).Text);
if c is TCheckBox then
reg.WriteBool('Values', c.Name, TCheckBox(c).Checked);
if c is TRadioButton then
reg.WriteBool('Values', c.Name, TRadioButton(c).Checked);
if c is TListBox then
reg.WriteInteger('Values', c.Name, TListBox(c).ItemIndex);
if c is TComboBox then
reg.WriteInteger('Values', c.Name, TComboBox(c).ItemIndex);
end;
for i := 0 to con.ComponentCount-1 do begin
cp := con.Components[i];
if cp is TFontDialog then
WriteFont(cp.Name, TFontDialog(cp).Font, reg);
end;
end;
procedure TFormSettings.ReadFont(Name: string; f: TFont; reg: TRegIniFile);
var
b : boolean;
begin
f.Name := reg.ReadString('Values', Name + '_Name', f.Name);
f.Size := reg.ReadInteger('Values', Name + '_Size', f.Size);
f.Color := reg.ReadInteger('Values', Name + '_Color', f.Color);
b := reg.ReadBool('Values', Name + '_Bold', fsBold in f.Style);
if b then f.Style := f.Style + [fsBold]
else f.Style := f.Style - [fsBold];
b := reg.ReadBool('Values', Name + '_Italic', fsItalic in f.Style);
if b then f.Style := f.Style + [fsItalic]
else f.Style := f.Style - [fsItalic];
b := reg.ReadBool('Values', Name + '_Underline', fsUnderline in f.Style);
if b then f.Style := f.Style + [fsUnderline]
else f.Style := f.Style - [fsUnderline];
b := reg.ReadBool('Values', Name + '_StrikeOut', fsStrikeOut in f.Style);
if b then f.Style := f.Style + [fsStrikeOut]
else f.Style := f.Style - [fsStrikeOut];
end;
procedure TFormSettings.WriteFont(Name: string; f: TFont; reg: TRegIniFile);
begin
reg.WriteString('Values', Name + '_Name', f.Name);
reg.WriteInteger('Values', Name + '_Size', f.Size);
reg.WriteInteger('Values', Name + '_Color', f.Color);
reg.WriteBool('Values', Name + '_Bold', fsBold in f.Style);
reg.WriteBool('Values', Name + '_Italic', fsItalic in f.Style);
reg.WriteBool('Values', Name + '_Underline', fsUnderline in f.Style);
reg.WriteBool('Values', Name + '_StrikeOut', fsStrikeOut in f.Style);
end;
procedure Register;
begin
RegisterComponents('Samples', [TFormSettings]);
end;
end.
|
namespace Beta;
extension method NSArray.distinctArrayWithKey(aKey: String): NSArray;
begin
var keyValues := new NSMutableSet;
result := new NSMutableArray;
for each item in self do begin
var keyForItem := item.valueForKey(aKey);
if assigned(keyForItem) and not keyValues.containsObject(keyForItem) then begin
NSMutableArray(result).addObject(item);
keyValues.addObject(keyForItem);
end;
end;
end;
end.
|
unit dmDescargarDatos;
interface
uses
Windows, SysUtils, Classes, DB, IBCustomDataSet, IBQuery, IBSQL, AbBrowse,
AbUnzper, IBDatabase, dmInternalPerCentServer, dmBD, UtilDB;
type
TDescargarDatos = class(TInternalPerCentServer)
private
function GetOIDValor: integer;
public
function Descargar(const BDDiario, BDSemanal, BDComun: TIBDatabase;
const Diario, Semanal: boolean): TFileName;
end;
implementation
uses AbUtils, forms, strUtils, dmInternalServer, AbZipTyp,
UserServerCalls, UtilString, dmConfiguracion, Contnrs,
dmDataComun;
{$R *.dfm}
function TDescargarDatos.Descargar(const BDDiario, BDSemanal, BDComun: TIBDatabase;
const Diario, Semanal: boolean): TFileName;
var datosCall: TDatosUserServerCall;
OIDCotizacionDiario, OIDCotizacionSemanal, OIDSesionDiario,
OIDSesionSemanal, OIDRentabilidadDiario, OIDRentabilidadSemanal,
OIDModificacionC, OIDModificacionD, OIDModificacionS, OIDMensaje, OIDFrase: integer;
function LastOID(const bd: TIBDatabase; const tableName: string): integer;
var OIDGenerator: TOIDGenerator;
begin
if not bd.DefaultTransaction.InTransaction then
bd.DefaultTransaction.StartTransaction;
OIDGenerator := TOIDGenerator.Create(bd, tableName);
try
result := OIDGenerator.LastOID;
finally
OIDGenerator.Free;
end;
end;
begin
if Canceled then
raise EAbort.Create('');
Application.ProcessMessages;
if Diario then begin
OIDCotizacionDiario := LastOID(BDDiario, 'COTIZACION');
OIDSesionDiario := LastOID(BDDiario, 'SESION');
OIDRentabilidadDiario := LastOID(BDDiario, 'SESION_RENTABILIDAD');
end
else begin
OIDCotizacionDiario := High(Integer);
OIDSesionDiario := High(Integer);
OIDRentabilidadDiario := High(Integer);
end;
if Canceled then
raise EAbort.Create('');
Application.ProcessMessages;
if Semanal then begin
OIDCotizacionSemanal := LastOID(BDSemanal, 'COTIZACION');
OIDSesionSemanal := LastOID(BDSemanal, 'SESION');
OIDRentabilidadSemanal := LastOID(BDSemanal, 'SESION_RENTABILIDAD');
end
else begin
OIDCotizacionSemanal := High(Integer);
OIDSesionSemanal := High(Integer);
OIDRentabilidadSemanal := High(Integer);
end;
if Canceled then
raise EAbort.Create('');
Application.ProcessMessages;
OIDMensaje := LastOID(BDComun, 'MENSAJE');
OIDFrase := LastOID(BDComun, 'FRASE');
with Configuracion.Sistema do begin
OIDModificacionC := ServidorModificacionComun;
OIDModificacionD := ServidorModificacionDiaria;
OIDModificacionS := ServidorModificacionSemanal;
end;
if Canceled then
raise EAbort.Create('');
Application.ProcessMessages;
datosCall := TDatosUserServerCall.Create(Self);
try
result := datosCall.Call(Diario, Semanal, GetOIDValor, OIDCotizacionDiario, OIDCotizacionSemanal,
OIDSesionDiario, OIDSesionSemanal, OIDRentabilidadDiario, OIDRentabilidadSemanal,
OIDModificacionC, OIDModificacionD, OIDModificacionS, OIDMensaje, OIDFrase, False);
finally
datosCall.Free;
end;
CancelPerCentOperation;
end;
function TDescargarDatos.GetOIDValor: integer;
var valorIterator: TDataValorIterator;
OIDValor: integer;
begin
valorIterator := DataComun.ValoresIterator;
try
valorIterator.first;
result := valorIterator.next^.OIDValor;
while valorIterator.hasNext do begin
OIDValor := valorIterator.next^.OIDValor;
if result < OIDValor then
result := OIDValor;
end;
finally
valorIterator.Free;
end;
end;
end.
|
unit History;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, StdCtrls, Buttons;
type
THistoryBox = class(TForm)
BitBtnClear: TBitBtn;
BitBtnOK: TBitBtn;
ListView: TListView;
procedure BitBtnClearClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
HistoryBox: THistoryBox;
implementation
{$R *.DFM}
uses
Registry;
procedure THistoryBox.BitBtnClearClick(Sender: TObject);
var
Reg: TRegistry;
begin
if Application.MessageBox('真要清除历史记录吗?', '黑白棋', MB_YESNO or MB_ICONQUESTION) = IDYES then
begin
Reg := TRegistry.Create;
Reg.DeleteKey('\Software\WC\黑白棋\历史记录');
Reg.Free;
ListView.Items.Clear
end
end;
end.
|
unit AT.FMX.ClockLabel;
interface
uses
System.SysUtils, System.Classes, FMX.Types, FMX.Controls, FMX.StdCtrls;
const
pidATPlatforms = pidWin32 OR pidWin64 OR pidOSX32 OR
pidiOSSimulator32 OR pidiOSSimulator64 OR
pidiOSDevice32 OR pidiOSDevice64 OR
pidAndroid32Arm OR pidAndroid64Arm OR
pidLinux64;
type
[ComponentPlatformsAttribute(pidATPlatforms)]
TATFMXClockLabel = class(TLabel)
strict private
FFormat: String;
FTimer: TTimer;
procedure OnTimer(Sender: TObject);
procedure SetFormat(const Value: String);
procedure UpdateLabel;
protected
property Text;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Format: String read FFormat write SetFormat;
end;
implementation
constructor TATFMXClockLabel.Create(AOwner: TComponent);
begin
inherited;
FFormat := 'c';
if (NOT (csDesigning IN ComponentState)) then
begin
FTimer := TTimer.Create(AOwner);
FTimer.OnTimer := OnTimer;
FTimer.Interval := 1000;
FTimer.Enabled := True;
end;
UpdateLabel;
end;
destructor TATFMXClockLabel.Destroy;
begin
FreeAndNil(FTimer);
inherited;
end;
procedure TATFMXClockLabel.OnTimer(Sender: TObject);
begin
UpdateLabel;
end;
procedure TATFMXClockLabel.SetFormat(const Value: String);
begin
FFormat := Value;
UpdateLabel;
end;
procedure TATFMXClockLabel.UpdateLabel;
begin
Text := FormatDateTime(FFormat, Now);
end;
end.
|
{ H-SNAKE - author: Jakub "Horuss" Czajkowski
language: Free Pascal
IDE: Dev Pascal 1.9.2
License: GNU GPL
}
PROGRAM h_snake;
USES crt;
TYPE
coordinates=record
x,y:byte;
end;
CONST
sizex=30; { size of gamearea }
sizey=15;
body='o';
h='O';
MAX=255; { max snake length }
VAR
length,tail,head,next,time,bonus_stop:byte; { MAX gives us chance to use byte }
snake:array[1..MAX] of coordinates; { snake == array of coordinate records, this snake is like queue implemented on array }
gamearea:array[1..sizex+2,1..sizey+2] of char;
food,bonus:coordinates;
crash,legal,eaten,ch_ok:boolean;
klawisz,direction,ch_menu,ch_level,ch_diff:char;
score:integer;
{ ********* DRAW LOGO ********** }
procedure logo;
begin
gotoxy(1,1);
textcolor(lightcyan);
writeln(' _ _ ___ _ _ _ _ __ ___ ');
writeln('| || | __ / __| | \| | /_\ | |/ / | __|');
writeln('| __ | |__| \__ \ | .` | / _ \ | < | _| ');
writeln('|_||_| |___/ |_|\_| /_/ \_\ |_|\_\ |___|');
writeln;
textcolor(white);
end;
{ ********* INITIATIN ********** }
procedure init; { clear score, draw snake on the starting position }
var i:byte;
begin
score:=0;
length:=5;
gotoxy(41,7);
write('Moving - Arrows');
gotoxy(41,8);
write('Exit - ESC');
gotoxy(41,9);
write('Pause - Spacebar');
gotoxy(41,11);
textcolor(yellow);
write('length: ',length:3);
gotoxy(41,13);
write('score:',score:6);
textcolor(white);
tail:=1;
head:=length;
direction:='r';
crash:=false;
for i:=1 to length do
begin
snake[i].x:=4+i-1;
snake[i].y:=8;
gotoxy(snake[i].x,8);
textcolor(red);
write(body);
end;
gotoxy(snake[length].x,snake[length].y);
textcolor(lightred);
write(h);
textcolor(white);
gotoxy(1,25);
end;
{ ********* SELECTING LEVEL ********** }
procedure select_level; { different level == different obstacles }
var i:byte;
begin
writeln;
writeln(' Choose level:');
writeln(' 1. Classic over all');
writeln(' 2. Double sharp');
writeln(' 3. Labirynth of madness');
ch_level:=readkey;
if (ch_level='1') or (ch_level='2') or (ch_level='3') then ch_ok:=true else ch_ok:=false; { is the choose valid }
if ch_level='2' then
begin
for i:=5 to 9 do
gamearea[5,i]:='|';
for i:=6 to 11 do
gamearea[i,5]:='-';
for i:=10 to 13 do
gamearea[15,i]:='|';
for i:=20 to 25 do
gamearea[i,5]:='-';
for i:=5 to 9 do
gamearea[26,i]:='|';
end;
if ch_level='3' then
begin
for i:=5 to 13 do
gamearea[6,i]:='|';
for i:=5 to 13 do
gamearea[27,i]:='|';
for i:=7 to 15 do
gamearea[i,9]:='-';
for i:=18 to 26 do
gamearea[i,9]:='-';
for i:=13 to 20 do
gamearea[i,4]:='-';
for i:=13 to 20 do
gamearea[i,14]:='-';
end;
end;
{ ********* SELECTING DIFFICULTY ********** }
procedure select_difficulty; { changing delay of each snake "step" }
begin
writeln;
writeln(' Choose difficulty:');
writeln(' 1. Easy - snake moves slowly.');
writeln(' 2. Normal - snake moves normally.');
writeln(' 3. Hard - snake moves fast.');
ch_diff:=readkey;
if (ch_diff='1') or (ch_diff='2') or (ch_diff='3') then ch_ok:=true else ch_ok:=false; { is the choose valid }
if ch_diff='1' then
begin
time:=200;
end;
if ch_diff='2' then
begin
time:=150;
end;
if ch_diff='3' then
begin
time:=70;
end;
end;
{ ********* PRZYGOTOWANIE PLANSZY ********** }
procedure walls; { one-time paint walls }
var i:byte;
begin
for i:=2 to sizex+1 do
begin
gamearea[i,1]:='-';
end;
for i:=2 to sizey+1 do
begin
gamearea[1,i]:='|';
end;
for i:=2 to sizey+1 do
begin
gamearea[sizex+2,i]:='|';
end;
for i:=2 to sizex+1 do
begin
gamearea[i,sizey+2]:='-';
end;
gamearea[1,sizey+2]:='+';
gamearea[sizex+2,1]:='+';
gamearea[1,1]:='+';
gamearea[sizex+2,sizey+2]:='+';
end;
{ ********* CLEARING ********** }
procedure gamearea_clear; { clearing after previous game }
var i,j:byte;
begin
for i:=2 to sizey+1 do
for j:=2 to sizex+1 do
gamearea[j,i]:=' ';
end;
{ ********* DRAWING GAMEAREA ********** }
procedure gamearea_draw; { painting gamearea: walls and obstacles }
var i,j:byte;
begin
gotoxy(1,6);
for i:=1 to sizey+2 do
begin
for j:=1 to sizex+2 do
begin
if (gamearea[j,i]='-') or (gamearea[j,i]='+') or (gamearea[j,i]='|') then
begin
textcolor(lightgray);
textbackground(lightgray);
write(gamearea[j,i]);
textcolor(white);
textbackground(black);
end
else
begin
write(gamearea[j,i]);
end;
end;
writeln;
end;
end;
{ ********* SCORE ********** }
procedure score_endgame; { after finishing shows your score }
begin
if ch_diff='2' then score:=score*2;
if ch_diff='3' then score:=score*4;
if ch_level='2' then score:=score+20;
if ch_level='3' then score:=score+50;
clrscr;
logo;
writeln;
textcolor(yellow);
writeln(' Your snake length: ',length:3);
writeln;
writeln(' Your score: ',score:6);
writeln;
writeln(' !!! CONGRATULATIONS !!!');
textcolor(white);
writeln;
writeln;
writeln(' Press ESC, to continue.');
repeat until readkey=#27;
end;
{ ********* COLLISION CHECK ********** }
procedure check; { checking collision with snake/walls/obstacles }
var i:byte;
begin
if tail<head then
begin
for i:=tail to head-2 do
if (snake[i].x=snake[head].x) and (snake[i].y=snake[head].y) then begin crash:=true end; { snake itself }
end
else
begin
for i:=tail to MAX do { snake itself if just passing the "snake" array }
if (snake[i].x=snake[head].x) and (snake[i].y=snake[head].y) then begin crash:=true; end;
for i:=2 to head-2 do
if (snake[i].x=snake[head].x) and (snake[i].y=snake[head].y) then begin crash:=true; end;
end;
if (gamearea[snake[head].x,snake[head].y-5]='|') or (gamearea[snake[head].x,snake[head].y-5]='-') then begin crash:=true;end; { wall/obstacle }
end;
{ ********* MOVE (1 step) ********** }
procedure move;
begin
if head<MAX then next:=head+1
else next:=1;
if keypressed then
begin
klawisz:=readkey;
if klawisz=#27 then begin crash:=true; end; {exit}
if klawisz=#32 then {pause}
begin
gotoxy(41,17);
write('PAUSE');
gotoxy(1,25);
repeat until readkey=#32;
gotoxy(41,17);
write(' ');
gotoxy(1,25);
end;
if klawisz = #0 then {arrow (sending 2 chars, first is #0)}
begin
legal:=false;
klawisz:=readkey;
case klawisz of
#75:
if direction<>'r' then
begin
snake[next].x:=snake[head].x-1;
snake[next].y:=snake[head].y;
direction:='l';
legal:=true;
end;
#80:
if direction<>'u' then
begin
snake[next].x:=snake[head].x;
snake[next].y:=snake[head].y+1;
direction:='d';
legal:=true;
end;
#77:
if direction<>'l' then
begin
snake[next].x:=snake[head].x+1;
snake[next].y:=snake[head].y;
direction:='r';
legal:=true;
end;
#72:
if direction<>'d' then
begin
snake[next].x:=snake[head].x;
snake[next].y:=snake[head].y-1;
direction:='u';
legal:=true;
end;
end;
if legal=true then
begin
if eaten=false then
begin
gotoxy(snake[tail].x,snake[tail].y);
write(' ');
snake[tail].x:=0; snake[tail].y:=0;
end;
gotoxy(snake[head].x,snake[head].y);
textcolor(red);
write(body);
textcolor(white);
if eaten=false then
begin
if tail<MAX then inc(tail) { going through snake array }
else tail:=1;
end;
if head<MAX then inc(head) { going through snake array }
else head:=1;
gotoxy(snake[head].x,snake[head].y);
textcolor(lightred);
write(h);
textcolor(white);
gotoxy(1,25);
delay(time);
end;
end;
end
else { if not keypressed, keeping old direction }
begin
if eaten=false then
begin
gotoxy(snake[tail].x,snake[tail].y);
write(' ');
snake[tail].x:=0; snake[tail].y:=0;
end;
gotoxy(snake[head].x,snake[head].y);
textcolor(red);
write(body);
textcolor(white);
case direction of
'l':
begin
snake[next].x:=snake[head].x-1;
snake[next].y:=snake[head].y;
end;
'd':
begin
snake[next].x:=snake[head].x;
snake[next].y:=snake[head].y+1;
end;
'r':
begin
snake[next].x:=snake[head].x+1;
snake[next].y:=snake[head].y;
end;
'u':
begin
snake[next].x:=snake[head].x;
snake[next].y:=snake[head].y-1;
end;
end;
if eaten=false then
begin
if tail<MAX then inc(tail) { going through snake array }
else tail:=1;
end;
if head<MAX then inc(head) { going through snake array }
else head:=1;
gotoxy(snake[head].x,snake[head].y);
textcolor(lightred);
write(h);
textcolor(white);
gotoxy(1,25);
delay(time);
end;
check; { after move, check the collisions }
end;
{ ********* ADDIND FOOD ********** }
procedure add_food;
var possible:boolean;
i:byte;
begin
repeat
begin
possible:=true;
food.x:=random(sizex)+2;
food.y:=random(sizey)+7;
if tail<head then
for i:=tail to head do
begin
if (food.x=snake[i].x) and (food.y=snake[i].y) then possible:=false; {checking if the food is "on" snake}
end
else
begin
for i:=tail to MAX do
if (food.x=snake[i].x) and (food.y=snake[i].y) then possible:=false;
for i:=1 to head do
if (food.x=snake[i].x) and (food.y=snake[i].y) then possible:=false;
end;
if (gamearea[food.x,food.y-5]='|') or (gamearea[food.x,food.y-5]='-') then possible:=false; {checking if the food is on wall/obstacle}
if (abs(food.x-snake[head].x)<3) and (abs(food.y-snake[head].y)<3) then possible:=false; {checking if the food is not too close to snakes head}
end;
until (possible=true);
gotoxy(food.x,food.y);
textcolor(lightgreen);
write('$');
textcolor(white);
gotoxy(1,25);
end;
{ ********* ADDING BONUS ********** }
procedure add_bonus;
var possible:boolean;
i:byte;
begin
repeat
begin
possible:=true;
bonus.x:=random(sizex)+2;
bonus.y:=random(sizey)+7;
if tail<head then
for i:=tail to head do
begin
if (bonus.x=snake[i].x) and (bonus.y=snake[i].y) then possible:=false; {checking if the bonus is on snake}
end
else
begin
for i:=tail to MAX do
if (bonus.x=snake[i].x) and (bonus.y=snake[i].y) then possible:=false;
for i:=1 to head do
if (bonus.x=snake[i].x) and (bonus.y=snake[i].y) then possible:=false;
end;
if (gamearea[bonus.x,bonus.y-5]='|') or (gamearea[bonus.x,bonus.y-5]='-') then possible:=false; {checking if the bonus is on wall/obstacle}
if (abs(bonus.x-snake[head].x)<3) and (abs(bonus.y-snake[head].y)<3) then possible:=false; {checking if the bonus is not too close to snakes head}
end;
until (possible=true);
gotoxy(bonus.x,bonus.y);
textcolor(cyan);
write('X');
textcolor(white);
gotoxy(1,25);
end;
{ ********* STARTING GAME ********** }
procedure play;
begin
clrscr;
logo;
gamearea_draw;
init;
add_food;
gotoxy(41,17);
textcolor(lightcyan);
write('Press any key, to continue');
gotoxy(1,25);
textcolor(white);
repeat until keypressed;
gotoxy(41,17);
write(' ');
repeat {main game loop}
begin
if length=MAX then
begin
gotoxy(41,17);
textcolor(lightred);
write('MAXIMUM LENGTH');
textcolor(white);
crash:=true;
end;
eaten:=false;
if (food.x=snake[head].x) and (food.y=snake[head].y) then
begin
eaten:=true;
inc(length);
if length=bonus_stop then
begin
gotoxy(41,15);
write(' ');
time:=time-50;
bonus_stop:=0;
end;
add_food;
if (random(8)=1) and (bonus.x=0) and (bonus.y=0) and (length-bonus_stop>0) then add_bonus;
gotoxy(50,11);
textcolor(yellow);
write(length:3);
score:=score+10;
gotoxy(47,13);
write(score:6);
textcolor(white);
end;
if (bonus.x=snake[head].x) and (bonus.y=snake[head].y) then
begin
bonus.x:=0;
bonus.y:=0;
time:=time+50;
gotoxy(41,15);
textcolor(lightgreen);
write('Bonus - you are slowed!');
textcolor(white);
bonus_stop:=length+2;
score:=score+20;
gotoxy(47,13);
textcolor(yellow);
write(score:6);
textcolor(white);
end;
move;
end;
until crash=true;
gotoxy(41,17);
textcolor(lightred);
write('GAME OVER. Press ESC, to exit.');
gotoxy(1,25);
textcolor(white);
repeat until readkey=#27;
score_endgame;
end;
{ ********* HELP FROM MENU ********** }
procedure help;
begin
clrscr;
logo;
writeln(' About the game:');
writeln(' Your task is to control the snake and eat food.');
writeln(' Avoid hitting yourself and the walls.');
textcolor(lightgreen);
write(' $');textcolor(white);writeln(' - food, increase length and your score by 10.');
textcolor(cyan);
write(' X');textcolor(white);writeln(' - bonus, reduces the speed of the snake for some time');
writeln(' and increase your score by 20.');
writeln(' Your score is also affected by selected level and difficulty.');
writeln;
writeln(' Controls:');
writeln(' Control snake using arrows.');
writeln(' Spacebar allows you to turn the pause on/off .');
writeln;
writeln;
writeln(' Press ESC, to return.');
repeat until readkey=#27;
end;
{ ********* ABOUT FROM MENU ********** }
procedure about;
begin
clrscr;
logo;
writeln(' Author: Jakub "Horuss" Czajkowski.');
writeln;
writeln(' Game created during course "Fundamentals of Computer Science" on');
writeln(' AGH University of Science and Technology in Cracow');
writeln;
writeln;
writeln(' Press ESC, to return.');
repeat until readkey=#27;
end;
{ ********* MENU ********** }
procedure menu;
begin
if ch_menu='1' then
begin
select_level;
if ch_ok=true then select_difficulty;
if ch_ok=true then play;
end;
if ch_menu='2' then help;
if ch_menu='3' then about;
end;
{ #################### PROGRAM ###################### }
BEGIN
textcolor(white);
clrscr;
randomize;
walls;
repeat
begin
gamearea_clear;
clrscr;
logo;
writeln(' MENU:');
writeln;
writeln(' 1. Play !');
writeln(' 2. Help');
writeln(' 3. About');
writeln(' ESC. Exit');
ch_menu:=readkey;
menu;
end;
until ch_menu=#27;
END.
|
program exer18;
var
media,n1,n2:real;
begin
read(n1,n2);
media := (n1 + n2)/2;
if (media >= 7) then
writeln('aprovado')
else if (media < 3) then
writeln('reprovado')
else
writeln('exame');
end.
//EXERCICIO:
//Escreva um programa em Pascal que leia as duas notas bimestrais
//de um aluno e determine a sua media. A partir da media, o programa
//deve imprimir a seguinte mensagem: APROVADO, REPROVADO ou EXAME.
//A media e' 7 para Aprovacao, menor que 3 para Reprovacao e as demais em Exame.
//Exemplos:
//3.1
//2.5
//REPROVADO
//3
//3
//EXAME
//10
//0
//EXAME
//6
//8
//APROVADO
//10
//10
//APROVADO
|
unit PPL.Rules;
interface
uses
System.SysUtils, System.Classes, IdBaseComponent, IdComponent,
IdTCPConnection, IdTCPClient, IdHTTP, System.Threading, Winapi.Windows,
System.Types;
type
TLog = reference to procedure(const ALog: string);
TFemMasc = record
public
class operator Add(a, b: TFemMasc): TFemMasc;
procedure Zerar();
public
Feminino: Integer;
Masculino: Integer;
Desconhecido: Integer;
Arquivos: Integer;
Linhas: Integer;
end;
TdmRules = class(TDataModule)
private
{ Private declarations }
procedure _(const AMensagem: string);
function AnalisarArquivos(const APath: string): IFuture<TFemMasc>;
public
GeraLog: TLog;
procedure LimparDiretorio();
procedure DownloadArquivos(const AArquivos: TArray<string>);
procedure DescompactarArquivos();
function CalcularFemMasc(): ITask;
end;
var
dmRules: TdmRules;
implementation
uses
idURI, System.IOUtils, System.Zip, System.Generics.Collections, Vcl.Dialogs, System.Diagnostics;
{ %CLASSGROUP 'Vcl.Controls.TControl' }
{$R *.dfm}
{ TDataModule1 }
function TdmRules.AnalisarArquivos(const APath: string): IFuture<TFemMasc>;
begin
Result := TTask.Future<TFemMasc>(
function: TFemMasc
var
tfArquivo: TextFile;
sLinha: string;
slLinha: TStringList;
begin
dmRules._(Format('Analisando: [%s]', [APath]));
slLinha := TStringList.Create();
slLinha.Delimiter := ';';
Result.Zerar;
Inc(Result.Arquivos);
AssignFile(tfArquivo, APath);
try
try
Reset(tfArquivo);
while not Eof(tfArquivo) do
begin
TTask.CurrentTask.CheckCanceled();
Inc(Result.Linhas);
ReadLn(tfArquivo, sLinha);
slLinha.DelimitedText := sLinha;
if (slLinha[30] = 'FEMININO') then
begin
Inc(Result.Feminino);
Continue;
end;
if (slLinha[30] = 'MASCULINO') then
begin
Inc(Result.Masculino);
Continue;
end;
Inc(Result.Desconhecido);
end;
except
on E: Exception do
begin
dmRules._(E.ClassName);
end;
end;
finally
CloseFile(tfArquivo);
slLinha.Free;
dmRules._('Pronto!');
end;
end);
end;
function TdmRules.CalcularFemMasc: ITask;
begin
Result := TTask.Create(
procedure
const
C_RESULT = #13#10'Arquivos: [%d]'#13#10'Linhas: [%d]'#13#10'Feminino: [%d]'#13#10'Masculino: [%d]'#13#10'Desconhecido: [%d]';
var
oFuture: IFuture<TFemMasc>;
oLista: TQueue<IFuture<TFemMasc>>;
sDiretorio: string;
sArquivo: string;
rSoma: TFemMasc;
oItem: IFuture<TFemMasc>;
oCrono : TStopWatch;
begin
oCrono := TStopwatch.StartNew;
dmRules._('Iniciando processo de análise!');
oLista := TQueue < IFuture < TFemMasc >>.Create();
try
for sDiretorio in TDirectory.GetDirectories(TDirectory.GetCurrentDirectory()) do
begin
for sArquivo in TDirectory.GetFiles(sDiretorio, '*.txt') do
begin
if TTask.CurrentTask.Status = TTaskStatus.Canceled then
begin
dmRules._('INTERROMPENDO O LANÇAMENTO DE TASKS');
Break;
end;
oFuture := Self.AnalisarArquivos(sArquivo);
oLista.Enqueue(oFuture);
end;
end;
rSoma.Zerar;
while oLista.Count > 0 do
begin
oItem := oLista.Dequeue();
if TTask.CurrentTask.Status = TTaskStatus.Canceled then
begin
dmRules._('CANCELANDO ...');
oItem.Cancel;
Continue;
end;
rSoma := rSoma + oFuture.Value;
end;
if TTask.CurrentTask.Status = TTaskStatus.Canceled then
begin
dmRules._('A TAREFA FOI CANCELADA!');
end
else
begin
dmRules._(Format(C_RESULT, [rSoma.Arquivos, rSoma.Linhas, rSoma.Feminino, rSoma.Masculino, rSoma.Desconhecido]));
end;
finally
oLista.Free;
dmRules._('Pronto!');
oCrono.Stop;
dmRules._(Format('*** Tempo de execução: [%d] segundos',[oCrono.Elapsed.Seconds]));
end
end);
end;
procedure TdmRules.DescompactarArquivos;
function Descompactar(const AArquivo: string): TProc;
begin
Result := procedure
var
oDescompressor: TZipFile;
sDir: string;
begin
dmRules._(Format('Descompactando o arquivo: [%s]', [AArquivo]));
oDescompressor := TZipFile.Create;
try
sDir := TPath.GetFileNameWithoutExtension(AArquivo);
oDescompressor.Open(AArquivo, zmRead);
oDescompressor.ExtractAll(TPath.Combine(TDirectory.GetCurrentDirectory(), sDir));
finally
oDescompressor.Close;
oDescompressor.Free;
dmRules._('Pronto!')
end;
end;
end;
var
sArquivo: string;
oTask : ITask;
oLista: TList<ITask>;
begin
oLista := TList<ITask>.Create();
for sArquivo in TDirectory.GetFiles(TDirectory.GetCurrentDirectory(), '*.zip') do
begin
oTask := TTask.Run(Descompactar(sArquivo));
oLista.Add(oTask);
end;
TThread.CreateAnonymousThread(
procedure
begin
TTask.WaitForAll(oLista.ToArray());
oLista.Free;
ShowMessage('Arquivos descompactados com sucesso!');
end
).Start;
end;
procedure TdmRules.DownloadArquivos(const AArquivos: TArray<string>);
function Download(const AURL: string): TProc;
begin
Result := procedure
var
sNomeArquivo: string;
oHTTP: TIdHTTP;
oFile: TStringStream;
begin
sNomeArquivo := TPath.GetFileName(AURL);
dmRules._('Baixando o arquivo: ' + sNomeArquivo);
oHTTP := TIdHTTP.Create();
oFile := TStringStream.Create();
try
oHTTP.Get(AURL, oFile);
oFile.SaveToFile('.\' + sNomeArquivo);
finally
dmRules._('Pronto!');
oHTTP.Free;
oFile.Free;
end;
end;
end;
var
aTrabalhadores: array of TProc;
aEmpreitada: ITask;
i: Integer;
begin
SetLength(aTrabalhadores, Length(AArquivos));
for i := 0 to High(AArquivos) do
begin
aTrabalhadores[i] := Download(AArquivos[i]);
end;
aEmpreitada := TParallel.Join(aTrabalhadores);
TThread.CreateAnonymousThread(
procedure
begin
aEmpreitada.Wait();
ShowMessage('Arquivos recuperados com sucesso!');
end
).Start;
end;
procedure TdmRules.LimparDiretorio;
function ExcluirItem(const AArquivo: string; const IsDirectory: Boolean): TProc;
begin
Result := procedure
begin
dmRules._(Format('Deletando o item: [%s]', [AArquivo]));
if IsDirectory then
begin
TDirectory.Delete(AArquivo, True);
end
else
begin
TFile.Delete(AArquivo);
end;
dmRules._('Pronto!');
end;
end;
var
sItem: string;
oLista : TList<ITask>;
begin
oLista := TList<ITask>.Create();
for sItem in TDirectory.GetFiles(TDirectory.GetCurrentDirectory(), '*.zip') do
begin
TThreadPool.Default.QueueWorkItem(ExcluirItem(sItem, False));
end;
for sItem in TDirectory.GetDirectories(TDirectory.GetCurrentDirectory()) do
begin
TThreadPool.Default.QueueWorkItem(ExcluirItem(sItem, True));
end;
end;
procedure TdmRules._(const AMensagem: string);
var
iThreadID: Cardinal;
begin
if Assigned(Self.GeraLog) then
begin
iThreadID := TThread.CurrentThread.ThreadID;
Self.GeraLog(Format('[%d] - %s', [iThreadID, AMensagem]));
end;
end;
{ TFemMasc }
class operator TFemMasc.Add(a, b: TFemMasc): TFemMasc;
begin
Result.Feminino := a.Feminino + b.Feminino;
Result.Masculino := a.Masculino + b.Masculino;
Result.Desconhecido := a.Desconhecido + b.Desconhecido;
Result.Arquivos := a.Arquivos + b.Arquivos;
Result.Linhas := a.Linhas + b.Linhas;
end;
procedure TFemMasc.Zerar;
begin
Self.Desconhecido := 0;
Self.Feminino := 0;
Self.Masculino := 0;
Self.Arquivos := 0;
Self.Linhas := 0;
end;
end.
|
unit U_Adapter.dto;
interface
type
TAdapter = class(TInterfacedObject)
private
fAdapterDescription : String;
fAdapterGateway : String;
fAdapterIndex : String;
fAdapterIPAddress : String;
fAdapterIPv6Address : String;
fAdapterPhysicalAddress : String;
fAdapterSubnetMask : String;
fAdapterType : String;
fLocalHost : String;
fNodeType : String;
fDeviveName: String;
fDeviceIndex: String;
fDeviveStatus: String;
public
constructor Create(); Overload;
constructor Create(
aAdapterDescription, aAdapterGateway, aAdapterIndex,
aAdapterIPAddress, aAdapterIPv6Address, aAdapterPhysicalAddress,
aAdapterSubnetMask, aAdapterType, aLocalHost, aNodeType,
aDeviveName, aDeviceIndex, aDeviveStatus : String); Overload;
property AdapterDescription : String read fAdapterDescription write fAdapterDescription;
property AdapterGateway : String read fAdapterGateway write fAdapterGateway;
property AdapterIndex : String read fAdapterIndex write fAdapterIndex;
property AdapterIPAddress : String read fAdapterIPAddress write fAdapterIPAddress;
property AdapterIPv6Address : String read fAdapterIPv6Address write fAdapterIPv6Address;
property AdapterPhysicalAddress : String read fAdapterPhysicalAddress write fAdapterPhysicalAddress;
property AdapterSubnetMask : String read fAdapterSubnetMask write fAdapterSubnetMask;
property AdapterType : String read fAdapterType write fAdapterType;
property LocalHost : String read fLocalHost write fLocalHost;
property NodeType : String read fNodeType write fNodeType;
property DeviceIndex : String read fDeviceIndex write fDeviceIndex;
property DeviveName : String read fDeviveName write fDeviveName;
property DeviveStatus : String read fDeviveStatus write fDeviveStatus;
end;
implementation
{ TAdapter }
constructor TAdapter.Create;
begin
inherited Create();
end;
constructor TAdapter.Create(
aAdapterDescription, aAdapterGateway, aAdapterIndex,
aAdapterIPAddress, aAdapterIPv6Address, aAdapterPhysicalAddress,
aAdapterSubnetMask, aAdapterType, aLocalHost, aNodeType,
aDeviveName, aDeviceIndex, aDeviveStatus : String);
begin
inherited Create();
Self.fAdapterDescription := aAdapterDescription;
Self.fAdapterGateway := aAdapterGateway;
Self.fAdapterIndex := aAdapterIndex;
Self.fAdapterIPAddress := aAdapterIPAddress;
Self.fAdapterIPv6Address := aAdapterIPv6Address;
Self.fAdapterPhysicalAddress := aAdapterPhysicalAddress;
Self.fAdapterSubnetMask := aAdapterSubnetMask;
Self.fAdapterType := aAdapterType;
Self.fLocalHost := aLocalHost;
Self.fNodeType := aNodeType;
Self.fDeviceIndex := aDeviceIndex;
Self.fDeviveName := aDeviveName;
Self.fDeviveStatus := aDeviveStatus;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.