text stringlengths 14 6.51M |
|---|
namespace QueueAndStack;
interface
uses
System.Windows.Forms,
System.Drawing,
OxygeneQueue, OxygeneStack;
type
MainForm = class(System.Windows.Forms.Form)
{$REGION Windows Form Designer generated fields}
private
CountStringsButton: System.Windows.Forms.Button;
PushIntegerButton: System.Windows.Forms.Button;
StringBox: System.Windows.Forms.TextBox;
ListBox: System.Windows.Forms.ListBox;
IntegerBox: System.Windows.Forms.TextBox;
PushStringButton: System.Windows.Forms.Button;
PopIntegerButton: System.Windows.Forms.Button;
label2: System.Windows.Forms.Label;
PopStringButton: System.Windows.Forms.Button;
label1: System.Windows.Forms.Label;
components: System.ComponentModel.Container := nil;
method CountStringsButton_Click(sender: System.Object; e: System.EventArgs);
method PushIntegerButton_Click(sender: System.Object; e: System.EventArgs);
method PopIntegerButton_Click(sender: System.Object; e: System.EventArgs);
method PopStringButton_Click(sender: System.Object; e: System.EventArgs);
method PushStringButton_Click(sender: System.Object; e: System.EventArgs);
method InitializeComponent;
{$ENDREGION}
protected
method Dispose(aDisposing: Boolean); override;
public
constructor;
class method Main;
private
var
StringStack: Stack<String> := new Stack<String>;
IntegerQueue: Queue<Integer> := new Queue<Integer>;
end;
implementation
{$REGION Construction and Disposition}
constructor MainForm;
begin
InitializeComponent();
end;
method MainForm.Dispose(aDisposing: boolean);
begin
if aDisposing then begin
if assigned(components) then
components.Dispose();
end;
inherited Dispose(aDisposing);
end;
{$ENDREGION}
{$REGION Windows Form Designer generated code}
method MainForm.InitializeComponent;
begin
self.label1 := new System.Windows.Forms.Label();
self.StringBox := new System.Windows.Forms.TextBox();
self.PopStringButton := new System.Windows.Forms.Button();
self.PopIntegerButton := new System.Windows.Forms.Button();
self.IntegerBox := new System.Windows.Forms.TextBox();
self.label2 := new System.Windows.Forms.Label();
self.PushIntegerButton := new System.Windows.Forms.Button();
self.PushStringButton := new System.Windows.Forms.Button();
self.ListBox := new System.Windows.Forms.ListBox();
self.CountStringsButton := new System.Windows.Forms.Button();
self.SuspendLayout();
//
// label1
//
self.label1.AutoSize := true;
self.label1.Location := new System.Drawing.Point(32, 67);
self.label1.Name := 'label1';
self.label1.Size := new System.Drawing.Size(34, 13);
self.label1.TabIndex := 0;
self.label1.Text := 'String';
//
// StringBox
//
self.StringBox.Location := new System.Drawing.Point(115, 64);
self.StringBox.Name := 'StringBox';
self.StringBox.Size := new System.Drawing.Size(83, 20);
self.StringBox.TabIndex := 1;
self.StringBox.Text := 'new string';
//
// PopStringButton
//
self.PopStringButton.Location := new System.Drawing.Point(326, 62);
self.PopStringButton.Name := 'PopStringButton';
self.PopStringButton.Size := new System.Drawing.Size(88, 23);
self.PopStringButton.TabIndex := 2;
self.PopStringButton.Text := 'Pop String';
self.PopStringButton.Click += new System.EventHandler(@self.PopStringButton_Click);
//
// PopIntegerButton
//
self.PopIntegerButton.Location := new System.Drawing.Point(326, 12);
self.PopIntegerButton.Name := 'PopIntegerButton';
self.PopIntegerButton.Size := new System.Drawing.Size(88, 23);
self.PopIntegerButton.TabIndex := 5;
self.PopIntegerButton.Text := 'Pop Integer';
self.PopIntegerButton.Click += new System.EventHandler(@self.PopIntegerButton_Click);
//
// IntegerBox
//
self.IntegerBox.Location := new System.Drawing.Point(115, 14);
self.IntegerBox.Name := 'IntegerBox';
self.IntegerBox.Size := new System.Drawing.Size(83, 20);
self.IntegerBox.TabIndex := 4;
self.IntegerBox.Text := '999';
self.IntegerBox.TextAlign := System.Windows.Forms.HorizontalAlignment.Right;
//
// label2
//
self.label2.AutoSize := true;
self.label2.Location := new System.Drawing.Point(26, 17);
self.label2.Name := 'label2';
self.label2.Size := new System.Drawing.Size(40, 13);
self.label2.TabIndex := 3;
self.label2.Text := 'Integer';
//
// PushIntegerButton
//
self.PushIntegerButton.Location := new System.Drawing.Point(222, 12);
self.PushIntegerButton.Name := 'PushIntegerButton';
self.PushIntegerButton.Size := new System.Drawing.Size(88, 23);
self.PushIntegerButton.TabIndex := 7;
self.PushIntegerButton.Text := 'Push Integer';
self.PushIntegerButton.Click += new System.EventHandler(@self.PushIntegerButton_Click);
//
// PushStringButton
//
self.PushStringButton.Location := new System.Drawing.Point(222, 62);
self.PushStringButton.Name := 'PushStringButton';
self.PushStringButton.Size := new System.Drawing.Size(88, 23);
self.PushStringButton.TabIndex := 6;
self.PushStringButton.Text := 'Push String';
self.PushStringButton.Click += new System.EventHandler(@self.PushStringButton_Click);
//
// ListBox
//
self.ListBox.FormattingEnabled := true;
self.ListBox.IntegralHeight := false;
self.ListBox.Location := new System.Drawing.Point(29, 91);
self.ListBox.Name := 'ListBox';
self.ListBox.Size := new System.Drawing.Size(384, 243);
self.ListBox.TabIndex := 8;
//
// CountStringsButton
//
self.CountStringsButton.Location := new System.Drawing.Point(29, 33);
self.CountStringsButton.Name := 'CountStringsButton';
self.CountStringsButton.Size := new System.Drawing.Size(75, 23);
self.CountStringsButton.TabIndex := 11;
self.CountStringsButton.Text := 'Counts';
self.CountStringsButton.Click += new System.EventHandler(@self.CountStringsButton_Click);
//
// MainForm
//
self.ClientSize := new System.Drawing.Size(429, 346);
self.Controls.Add(self.CountStringsButton);
self.Controls.Add(self.ListBox);
self.Controls.Add(self.PushIntegerButton);
self.Controls.Add(self.PushStringButton);
self.Controls.Add(self.PopIntegerButton);
self.Controls.Add(self.IntegerBox);
self.Controls.Add(self.label2);
self.Controls.Add(self.PopStringButton);
self.Controls.Add(self.StringBox);
self.Controls.Add(self.label1);
self.FormBorderStyle := System.Windows.Forms.FormBorderStyle.FixedDialog;
self.MaximizeBox := false;
self.Name := 'MainForm';
self.Text := 'QueueAndStack Sample';
self.AutoScaleMode := System.Windows.Forms.AutoScaleMode.Font;
self.ResumeLayout(false);
self.PerformLayout();
end;
{$ENDREGION}
{$REGION Application Entry Point}
[STAThread]
class method MainForm.Main;
begin
Application.EnableVisualStyles();
try
with lForm := new MainForm() do
Application.Run(lForm);
except
on E: Exception do begin
MessageBox.Show(E.Message);
end;
end;
end;
{$ENDREGION}
method MainForm.PushStringButton_Click(sender: System.Object; e: System.EventArgs);
begin
StringStack.Push(StringBox.Text);
StringBox.Text := '';
end;
method MainForm.PopStringButton_Click(sender: System.Object; e: System.EventArgs);
begin
ListBox.Items.Add(StringStack.Pop);
end;
method MainForm.PushIntegerButton_Click(sender: System.Object; e: System.EventArgs);
begin
IntegerQueue.Push(Int32.Parse(IntegerBox.Text));
IntegerBox.Text := '0';
end;
method MainForm.PopIntegerButton_Click(sender: System.Object; e: System.EventArgs);
begin
ListBox.Items.Add(IntegerQueue.Pop.ToString);
end;
method MainForm.CountStringsButton_Click(sender: System.Object; e: System.EventArgs);
begin
ListBox.Items.Add('StringStack Count = '+StringStack.Count.ToString);
ListBox.Items.Add('IntegerQueue Count = '+IntegerQueue.Count.ToString);
end;
end. |
unit uArrayListOfString;
interface
uses uArrayList;
{
Stores strs
}
type _Str = class(TObject)
public
str: String;
end;
function TStr(str: String): _Str;
{
Automatic dynamic string array
}
type ArrayListOfString = class(ArrayList)
public
procedure add(str: String); overload;
procedure put(str: String; index: integer); overload;
function remove(index: integer): String; overload;
procedure remove(str: String); overload;
function get(index: integer): String; overload;
function find(str: String): integer; overload;
end;
implementation
// _Str
function TStr(str: String): _Str;
begin
TStr :=_Str.Create();
TStr.str := str;
end;
// ArrayListOfString
procedure ArrayListOfString.add(str: String);
begin
inherited add(TStr(str));
end;
// ArrayListOfString
procedure ArrayListOfString.put(str: String; index: integer);
begin
inherited put(TStr(str), index);
end;
// ArrayListOfString
function ArrayListOfString.remove(index: integer): String;
begin
remove := (inherited remove(index) as _Str).str;
end;
// ArrayListOfString
procedure ArrayListOfString.remove(str: String);
var i: integer;
begin
for i := 0 to size() - 1 do begin
if (arr[i] as _Str).str = str then begin
remove(i);
break;
end;
end;
end;
// ArrayListOfString
function ArrayListOfString.get(index: integer): String;
begin
get := (inherited get(index) as _Str).str;
end;
// ArrayListOfString
function ArrayListOfString.find(str: String): integer;
var i: integer;
begin
find := -1;
for i := 0 to len - 1 do
if str = get(i) then begin
find := i;
break;
end;
end;
end.
|
unit Frame.Communication;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.Math,
System.JSON,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ExtCtrls,
Vcl.StdCtrls,
Vcl.Buttons,
Lib.JSONFormat,
Lib.VCL.HTTPGraphic,
Lib.HTTPConsts,
Lib.HTTPUtils,
Lib.HTTPContent;
type
TCommunicationFrame = class(TFrame)
TabPanel: TPanel;
ResponseTab: TSpeedButton;
LogTab: TSpeedButton;
CodeLabel: TLabel;
RequestTab: TSpeedButton;
ClearButton: TButton;
LogMemo: TMemo;
RequestMemo: TMemo;
ResponseMemo: TMemo;
ContentImage: TImage;
PictureScrollBox: TScrollBox;
procedure LogTabClick(Sender: TObject);
procedure RequestTabClick(Sender: TObject);
procedure ResponseTabClick(Sender: TObject);
procedure ClearButtonClick(Sender: TObject);
private
FAutoShowResponseContent: Boolean;
procedure ShowResponseResultCode(ResultCode: Integer);
public
constructor Create(AOwner: TComponent); override;
procedure Reset;
procedure ToLog(const Text: string);
procedure SetRequest(Request: TRequest);
procedure SetResponse(Response: TResponse);
procedure ShowLog;
procedure ShowResponse;
property AutoShowResponseContent: Boolean read FAutoShowResponseContent write FAutoShowResponseContent;
end;
implementation
{$R *.dfm}
function ContentIsText(const ContentType: string): Boolean;
begin
Result:=(ContentType='') or
ContentType.StartsWith('text/') or
ContentType.StartsWith('application/x-www-form-urlencoded') or
ContentType.StartsWith('application/javascript');
end;
function ContentIsJSON(const ContentType: string): Boolean;
begin
Result:=ContentType.StartsWith('application/json');
end;
procedure ShowContentText(Content: TContent; Strings: TStrings);
var
ContentType,ContentTypeCharset,jsText: string;
jsValue: TJSONValue;
Encoding: TEncoding;
begin
Strings.Clear;
ContentType:=Content.Headers.ContentType;
ContentTypeCharset:=Content.Headers.ContentTypeCharset.ToLower;
if ContentTypeCharset='utf-8' then
Encoding:=TEncoding.UTF8
else
Encoding:=TEncoding.ANSI;
try
if ContentIsText(ContentType) then
Strings.Text:=Encoding.GetString(Content.Content)
else
if ContentIsJSON(ContentType) then
begin
jsText:=Encoding.GetString(Content.Content);
jsValue:=TJSONObject.ParseJSONValue(jsText);
if Assigned(jsValue) then
Strings.Text:=ToJSON(jsValue,False)
else
Strings.Text:=jsText;
end else
Strings.Text:=Content.Description;
except
end;
end;
procedure ShowContentPicture(Content: TContent; Image: TImage);
begin
if Assigned(Content) and PictureLoadFromContent(Image.Picture,Content) then
begin
Image.Stretch:=
(Image.Picture.Height>Image.Height) or
(Image.Picture.Width>Image.Width);
Image.Hint:=HTTPExtractFileName(Content.ResourceName);
end else
Image.Picture.Assign(nil);
end;
{ TCommunicationFrame }
constructor TCommunicationFrame.Create(AOwner: TComponent);
begin
inherited;
FAutoShowResponseContent:=True;
end;
function GetResponseColor(Code: Integer): TColor;
begin
case Code of
HTTPCODE_SUCCESS: Exit(clGreen);
end;
Result:=clRed;
end;
procedure TCommunicationFrame.ShowResponseResultCode(ResultCode: Integer);
begin
CodeLabel.Caption:=' '+ResultCode.ToString+' ';
CodeLabel.Color:=GetResponseColor(ResultCode);
CodeLabel.Visible:=ResultCode<>0;
end;
procedure TCommunicationFrame.ToLog(const Text: string);
begin
LogMemo.Lines.Add(Text);
end;
procedure TCommunicationFrame.Reset;
begin
SetRequest(nil);
SetResponse(nil);
ShowLog;
end;
procedure TCommunicationFrame.SetRequest(Request: TRequest);
begin
if Request=nil then
begin
RequestMemo.Clear;
end else begin
ToLog(Request.Composes);
ShowContentText(Request,RequestMemo.Lines);
end;
end;
procedure TCommunicationFrame.SetResponse(Response: TResponse);
begin
if Response=nil then
begin
ResponseMemo.Clear;
ShowResponseResultCode(0);
ShowContentPicture(nil,ContentImage);
end else begin
ToLog(Response.Composes);
ShowContentPicture(Response,ContentImage);
if not Assigned(ContentImage.Picture.Graphic) then
PictureScrollBox.SendToBack;
ShowContentText(Response,ResponseMemo.Lines);
ShowResponseResultCode(Response.ResultCode);
if Length(Response.Content)=0 then ShowLog else
if FAutoShowResponseContent or ResponseTab.Down then ShowResponse;
end;
end;
procedure TCommunicationFrame.LogTabClick(Sender: TObject);
begin
LogMemo.BringToFront;
end;
procedure TCommunicationFrame.RequestTabClick(Sender: TObject);
begin
RequestMemo.BringToFront;
end;
procedure TCommunicationFrame.ResponseTabClick(Sender: TObject);
begin
ResponseMemo.BringToFront;
if Assigned(ContentImage.Picture.Graphic) then
PictureScrollBox.BringToFront;
end;
procedure TCommunicationFrame.ClearButtonClick(Sender: TObject);
begin
LogMemo.Clear;
SetRequest(nil);
SetResponse(nil);
end;
procedure TCommunicationFrame.ShowLog;
begin
LogTab.Click;
LogTab.Down:=True;
end;
procedure TCommunicationFrame.ShowResponse;
begin
ResponseTab.Click;
ResponseTab.Down:=True;
end;
end.
|
unit OTFEUnifiedTestApp_U;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
{$IFDEF LINUX}
This software is only intended for use under MS Windows
{$ENDIF}
{$WARN UNIT_PLATFORM OFF} // Useless warning about platform - we're already
// protecting against that!
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls,
Spin64, FileCtrl, ExtCtrls,
OTFE_U, OTFEUnified_U, ComCtrls;
type
TOTFEUnifiedTestApp_F = class(TForm)
pbClose: TButton;
pbVersion: TButton;
pbIsEncryptedVolFile: TButton;
edTestIfMtdVolFile: TEdit;
DriveComboBox1: TDriveComboBox;
OpenDialog1: TOpenDialog;
pbBrowse: TButton;
pbDisountVolume: TButton;
pbMountVolume: TButton;
pbDismountDrive: TButton;
pbClear: TButton;
rgActive: TRadioGroup;
ckDismountDriveEmergency: TCheckBox;
pbGetFileMountedForDrive: TButton;
pbGetDriveMountedForFile: TButton;
pbNumDrivesMounted: TButton;
pbRefresh: TButton;
pbGetDrivesMounted: TButton;
pbIsDriverInstalled: TButton;
pbDismountAll: TButton;
OTFEUnified1: TOTFEUnified;
RichEdit1: TRichEdit;
procedure pbCloseClick(Sender: TObject);
procedure pbVersionClick(Sender: TObject);
procedure pbIsEncryptedVolFileClick(Sender: TObject);
procedure pbBrowseClick(Sender: TObject);
procedure pbMountVolumeClick(Sender: TObject);
procedure pbDisountVolumeClick(Sender: TObject);
procedure pbDismountDriveClick(Sender: TObject);
procedure pbClearClick(Sender: TObject);
procedure rgActiveClick(Sender: TObject);
procedure pbGetFileMountedForDriveClick(Sender: TObject);
procedure pbGetDriveMountedForFileClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure pbNumDrivesMountedClick(Sender: TObject);
procedure pbRefreshClick(Sender: TObject);
procedure pbGetDrivesMountedClick(Sender: TObject);
procedure pbIsDriverInstalledClick(Sender: TObject);
procedure pbDismountAllClick(Sender: TObject);
private
procedure ReportWhetherActive();
procedure RefreshDriveComboBox();
public
{ Public declarations }
end;
var
OTFEUnifiedTestApp_F: TOTFEUnifiedTestApp_F;
implementation
{$R *.DFM}
uses ShellAPI;
procedure TOTFEUnifiedTestApp_F.ReportWhetherActive();
begin
if OTFEUnified1.Active then
begin
RichEdit1.lines.add('UnifiedDiskEncryption component ACTIVE');
rgActive.ItemIndex:=0;
end
else
begin
RichEdit1.lines.add('UnifiedDiskEncryption component NOT Active');
rgActive.ItemIndex:=1;
end;
end;
procedure TOTFEUnifiedTestApp_F.pbCloseClick(Sender: TObject);
begin
Close;
end;
procedure TOTFEUnifiedTestApp_F.pbVersionClick(Sender: TObject);
begin
RichEdit1.lines.add('Driver version: 0x'+inttohex(OTFEUnified1.Version(), 1));
end;
procedure TOTFEUnifiedTestApp_F.pbIsEncryptedVolFileClick(Sender: TObject);
var
filename: string;
output: string;
begin
filename := edTestIfMtdVolFile.text;
output := filename;
if OTFEUnified1.IsEncryptedVolFile(filename) then
begin
output := output + ' IS ';
end
else
begin
output := output + ' is NOT ';
end;
output := output + 'a UnifiedDiskEncryption volume file';
RichEdit1.lines.add(output);
end;
procedure TOTFEUnifiedTestApp_F.pbBrowseClick(Sender: TObject);
begin
OpenDialog1.Filename := edTestIfMtdVolFile.text;
if OpenDialog1.execute() then
begin
edTestIfMtdVolFile.text := OpenDialog1.FileName;
end;
end;
procedure TOTFEUnifiedTestApp_F.pbMountVolumeClick(Sender: TObject);
begin
if OTFEUnified1.Mount(edTestIfMtdVolFile.text)<>#0 then
begin
RichEdit1.lines.add(edTestIfMtdVolFile.text+' mounted OK');
end
else
begin
RichEdit1.lines.add(edTestIfMtdVolFile.text+' mount failed');
end;
RefreshDriveComboBox();
end;
procedure TOTFEUnifiedTestApp_F.pbDisountVolumeClick(Sender: TObject);
begin
if OTFEUnified1.Dismount(edTestIfMtdVolFile.text, ckDismountDriveEmergency.checked) then
begin
RichEdit1.lines.add(edTestIfMtdVolFile.text+' dismounted OK');
end
else
begin
RichEdit1.lines.add(edTestIfMtdVolFile.text+' dismount failed');
end;
RefreshDriveComboBox();
end;
procedure TOTFEUnifiedTestApp_F.pbDismountDriveClick(Sender: TObject);
var
output: string;
begin
output := DriveComboBox1.drive + ': ';
if OTFEUnified1.Dismount(DriveComboBox1.drive, ckDismountDriveEmergency.checked) then
begin
output := output + 'dismounted OK';
end
else
begin
output := output + 'dismount FAILED';
end;
RichEdit1.lines.add(output);
RefreshDriveComboBox();
end;
procedure TOTFEUnifiedTestApp_F.RefreshDriveComboBox();
var
origCase: TTextCase;
begin
origCase := DriveComboBox1.TextCase;
DriveComboBox1.TextCase := tcUpperCase;
DriveComboBox1.TextCase := tcLowerCase;
DriveComboBox1.TextCase := origCase;
end;
procedure TOTFEUnifiedTestApp_F.pbClearClick(Sender: TObject);
begin
RichEdit1.lines.Clear();
end;
procedure TOTFEUnifiedTestApp_F.rgActiveClick(Sender: TObject);
begin
try
OTFEUnified1.Active := (rgActive.ItemIndex=0);
finally
ReportWhetherActive();
end;
end;
procedure TOTFEUnifiedTestApp_F.pbGetFileMountedForDriveClick(Sender: TObject);
var
output: string;
begin
output := DriveComboBox1.drive +
': is UnifiedDiskEncryption volume file: "' +
OTFEUnified1.GetVolFileForDrive(DriveComboBox1.drive) +
'"';
RichEdit1.lines.add(output);
end;
procedure TOTFEUnifiedTestApp_F.pbGetDriveMountedForFileClick(Sender: TObject);
var
output: string;
begin
output := '"' +
edTestIfMtdVolFile.text +
'" is mounted as: '+
OTFEUnified1.GetDriveForVolFile(edTestIfMtdVolFile.text) +
':';
RichEdit1.lines.add(output);
end;
procedure TOTFEUnifiedTestApp_F.FormCreate(Sender: TObject);
begin
if Win32Platform = VER_PLATFORM_WIN32_NT then
begin
edTestIfMtdVolFile.text := 'c:\junk.pgd';
end
else
begin
edTestIfMtdVolFile.text := 'e:\VolumeFiles\ff.pgd';
end;
end;
procedure TOTFEUnifiedTestApp_F.pbNumDrivesMountedClick(Sender: TObject);
var
output: string;
begin
output := 'Number of UnifiedDiskEncryption volumes mounted: ';
output := output + inttostr(OTFEUnified1.CountDrivesMounted());
RichEdit1.lines.add(output);
end;
procedure TOTFEUnifiedTestApp_F.pbRefreshClick(Sender: TObject);
begin
RefreshDriveComboBox();
end;
procedure TOTFEUnifiedTestApp_F.pbGetDrivesMountedClick(Sender: TObject);
var
output: string;
begin
output := 'Number of UnifiedDiskEncryption volumes mounted: ';
output := output + OTFEUnified1.DrivesMounted();
RichEdit1.lines.add(output);
end;
procedure TOTFEUnifiedTestApp_F.pbIsDriverInstalledClick(Sender: TObject);
begin
if OTFEUnified1.IsDriverInstalled() then
begin
RichEdit1.lines.add('Driver installed');
end
else
begin
RichEdit1.lines.add('Driver NOT installed');
end;
end;
procedure TOTFEUnifiedTestApp_F.pbDismountAllClick(
Sender: TObject);
var
dismountFailedFor: string;
begin
dismountFailedFor := OTFEUnified1.DismountAll(ckDismountDriveEmergency.checked);
if dismountFailedFor='' then
begin
RichEdit1.lines.add('DismountAll OK');
end
else
begin
RichEdit1.lines.add('DismountAll failed for drives: '+dismountFailedFor);
end;
end;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
{$WARN UNIT_PLATFORM ON}
// -----------------------------------------------------------------------------
END.
|
unit rpVersionInfo; //версия 1.0 3/8/98 записана и проверена в Delphi 3.
(*Автор Rick Peterson, данный компонент распространяется свободно
и освобожден от платы за использование. В случае изменения
авторского кода просьба прислать измененный код. Сообщайте пожалуйста
обо всех найденных ошибках. Адрес для писем - rickpet@airmail.net. *)
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
TypInfo;
type
{$M+}
(* Видели директиву $M+??? Это заставляет Delphi включать в код RTTI-информацию для
перечислимых типов. В основном допускает работу с перечислимыми типами как
со строками с помощью GetEnumName *)
TVersionType = (vtCompanyName, vtFileDescription, vtFileVersion,
vtInternalName,
vtLegalCopyright, vtLegalTradeMark, vtOriginalFileName,
vtProductName, vtProductVersion, vtComments);
{$M-}
TrpVersionInfo = class(TComponent)
(* Данный компонент позволяет получать информацию о версии вашего приложения
во время его выполенния *)
private
FVersionInfo: array[0..ord(high(TVersionType))] of string;
protected
function GetCompanyName: string;
function GetFileDescription: string;
function GetFileVersion: string;
function GetInternalName: string;
function GetLegalCopyright: string;
function GetLegalTradeMark: string;
function GetOriginalFileName: string;
function GetProductName: string;
function GetProductVersion: string;
function GetComments: string;
function GetVersionInfo(VersionType: TVersionType): string; virtual;
procedure SetVersionInfo; virtual;
public
constructor Create(AOwner: TComponent); override;
published
(* Использовать это очень просто - Label1.Caption := VersionInfo1.FileVersion
Примечание: Все свойства - только для чтения, поэтому они недоступны в
Инспекторе Объектов *)
property CompanyName: string read GetCompanyName;
property FileDescription: string read GetFileDescription;
property FileVersion: string read GetFileVersion;
property InternalName: string read GetInternalName;
property LegalCopyright: string read GetLegalCopyright;
property LegalTradeMark: string read GetLegalTradeMark;
property OriginalFileName: string read GetOriginalFileName;
property ProductName: string read GetProductName;
property ProductVersion: string read GetProductVersion;
property Comments: string read GetComments;
end;
procedure Register;
implementation
constructor TrpVersionInfo.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
SetVersionInfo;
end;
function TrpVersionInfo.GetCompanyName: string;
begin
result := GeTVersionInfo(vtCompanyName);
end;
function TrpVersionInfo.GetFileDescription: string;
begin
result := GeTVersionInfo(vtFileDescription);
end;
function TrpVersionInfo.GetFileVersion: string;
begin
result := GeTVersionInfo(vtFileVersion);
end;
function TrpVersionInfo.GetInternalName: string;
begin
result := GeTVersionInfo(vtInternalName);
end;
function TrpVersionInfo.GetLegalCopyright: string;
begin
result := GeTVersionInfo(vtLegalCopyright);
end;
function TrpVersionInfo.GetLegalTradeMark: string;
begin
result := GeTVersionInfo(vtLegalTradeMark);
end;
function TrpVersionInfo.GetOriginalFileName: string;
begin
result := GeTVersionInfo(vtOriginalFileName);
end;
function TrpVersionInfo.GetProductName: string;
begin
result := GeTVersionInfo(vtProductName);
end;
function TrpVersionInfo.GetProductVersion: string;
begin
result := GeTVersionInfo(vtProductVersion);
end;
function TrpVersionInfo.GetComments: string;
begin
result := GeTVersionInfo(vtComments);
end;
function TrpVersionInfo.GeTVersionInfo(VersionType: TVersionType): string;
begin
result := FVersionInfo[ord(VersionType)];
end;
procedure TrpVersionInfo.SeTVersionInfo;
var
sAppName, sVersionType: string;
iAppSize, iLenOfValue, i: Cardinal;
pcBuf, pcValue: PWideChar;
begin
sAppName := Application.ExeName;
iAppSize := GetFileVersionInfoSize(PChar(sAppName), iAppSize);
if iAppSize > 0 then
begin
pcBuf := AllocMem(iAppSize);
GetFileVersionInfo(PChar(sAppName), 0, iAppSize, pcBuf);
for i := 0 to Ord(High(TVersionType)) do
begin
sVersionType := GetEnumName(TypeInfo(TVersionType), i);
sVersionType := Copy(sVersionType, 3, length(sVersionType));
if VerQueryValue(pcBuf, PChar('StringFileInfo\040904E4\' +
sVersionType), Pointer(pcValue), iLenOfValue) then
FVersionInfo[i] := pcValue;
end;
FreeMem(pcBuf, iAppSize);
end;
end;
procedure Register;
begin
RegisterComponents('FreeWare', [TrpVersionInfo]);
end;
end.
|
{
Role
Drawing shapes(Collaborate with ThDrawObject)
Display drawn shapes(Collaborate with ThItemList)
}
unit ThCanvasLayers;
interface
uses
System.Classes, System.SysUtils, System.Types, System.Math, System.Generics.Collections,
Vcl.Controls,
GR32, GR32_Layers, GR32_Polygons, GR32_VectorUtils,
ThTypes, ThClasses,
ThItemCollections,
ThDrawObject, ThItemStyle;
type
TThCustomLayer = class(TPositionedLayer)
end;
// Display drawn shapes
TThCustomViewLayer = class(TThCustomLayer)
private
FHitTest: Boolean;
function GetOffset: TFloatPoint;
function GetScale: TFloatPoint;
protected
FItemList: TThItemList;
procedure Paint(Buffer: TBitmap32); override;
function ViewportToLocal(APoint: TFloatPoint): TFloatPoint; overload;
function ViewportToLocal(AX, AY: TFloat): TFloatPoint; overload;
public
constructor Create(ALayerCollection: TLayerCollection); override;
destructor Destroy; override;
function DoHitTest(X, Y: Integer): Boolean; override;
procedure Clear;
property HitTest: Boolean read FHitTest write FHitTest;
property Scale: TFloatPoint read GetScale;
property Offset: TFloatPoint read GetOffset;
end;
// Drawing shapes
TThCustomDrawLayer = class(TThCustomViewLayer)
private
FMouseDowned: Boolean;
protected
FDrawMode: TThDrawMode;
[unsafe] FDrawObject: IThDrawObject; // 인터페이스 인스턴스 교체 시 자동해제 방지
procedure SetDrawMode(const Value: TThDrawMode); virtual;
procedure Paint(Buffer: TBitmap32); 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;
public
constructor Create(ALayerCollection: TLayerCollection); override;
property DrawMode: TThDrawMode read FDrawMode write SetDrawMode;
end;
// 자유롭게 그리기(펜과 지우개) 위한 레이어
TPenDrawLayer = class(TThCustomDrawLayer)
private
FPenDrawObj: TThPenDrawObject;
FEraDrawObj: TThObjectEraserObject;
protected
procedure SetDrawMode(const Value: TThDrawMode); override;
public
constructor Create(ALayerCollection: TLayerCollection); override;
destructor Destroy; override;
function DoHitTest(X, Y: Integer): Boolean; override;
property PenDrawObj: TThPenDrawObject read FPenDrawObj;
end;
// 도형을 추가해 그리는 레이어
TShapeDrawLayer = class(TThCustomDrawLayer)
private
FShapeId: string;
FShapeDrawObj: TThShapeDrawObject;
procedure SetShapetId(const Value: string);
protected
procedure SetDrawMode(const Value: TThDrawMode); override;
public
constructor Create(ALayerCollection: TLayerCollection); override;
destructor Destroy; override;
property ShapeId: string read FShapeId write SetShapetId;
// property Selection: TThShapeSelectObject read FSelectObj;
procedure DeleteSelectedItems;
end;
// 배경 레이어
TThBackgroundLayer = class(TBitmapLayer)
public
function DoHitTest(X, Y: Integer): Boolean; override;
end;
implementation
uses
ThUtils;
{ TThCustomViewLayer }
constructor TThCustomViewLayer.Create(ALayerCollection: TLayerCollection);
begin
inherited;
FItemList := TThItemList.Create;
Scaled := True;
end;
destructor TThCustomViewLayer.Destroy;
begin
FItemList.Clear;
FItemList.Free;
inherited;
end;
procedure TThCustomViewLayer.Clear;
begin
FItemList.Clear;
Update;
end;
function TThCustomViewLayer.DoHitTest(X, Y: Integer): Boolean;
begin
Result := FHitTest;
end;
function TThCustomViewLayer.GetOffset: TFloatPoint;
begin
LayerCollection.GetViewportShift(Result.X, Result.Y);
end;
function TThCustomViewLayer.GetScale: TFloatPoint;
begin
LayerCollection.GetViewportScale(Result.X, Result.Y);
end;
procedure TThCustomViewLayer.Paint(Buffer: TBitmap32);
var
I: Integer;
LScale, LOffset: TFloatPoint;
begin
inherited;
LScale := Scale;
LOffset := Offset;
Buffer.BeginUpdate;
for I := 0 to FItemList.Count - 1 do
FItemList[I].Draw(Buffer, LScale, LOffset);
Buffer.EndUpdate;
end;
function TThCustomViewLayer.ViewportToLocal(AX, AY: TFloat): TFloatPoint;
begin
Result := ViewportToLocal(FloatPoint(AX, AY));
end;
function TThCustomViewLayer.ViewportToLocal(APoint: TFloatPoint): TFloatPoint;
begin
Result := LayerCollection.ViewportToLocal(APoint, True)
end;
{ TThCustomDrawLayer }
constructor TThCustomDrawLayer.Create(ALayerCollection: TLayerCollection);
begin
inherited;
FMouseDowned := False;
MouseEvents := True;
end;
procedure TThCustomDrawLayer.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
if Button = mbLeft then
begin
FMouseDowned := True;
if Assigned(FDrawObject) then
FDrawObject.MouseDown(ViewportToLocal(X, Y), Shift);
Update;
end;
end;
procedure TThCustomDrawLayer.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
if Assigned(FDrawObject) then
begin
FDrawObject.MouseMove(ViewportToLocal(X, Y), Shift);
Update;
end;
end;
procedure TThCustomDrawLayer.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
var
Item: IThItem;
begin
if FMouseDowned then
begin
FMouseDowned := False;
Item := FDrawObject.ItemInstance;
if Assigned(Item) then
FItemList.Add(Item);
FDrawObject.MouseUp(ViewportToLocal(X, Y), Shift);
Update;
end;
end;
procedure TThCustomDrawLayer.Paint(Buffer: TBitmap32);
begin
inherited;
if FMouseDowned and Assigned(FDrawObject) then
FDrawObject.Draw(Buffer, Scale, Offset);
end;
procedure TThCustomDrawLayer.SetDrawMode(const Value: TThDrawMode);
begin
FDrawMode := Value;
end;
{ TPenLayer }
constructor TPenDrawLayer.Create(ALayerCollection: TLayerCollection);
begin
inherited;
FPenDrawObj := TThPenDrawObject.Create(TThPenStyle.Create);
FEraDrawObj := TThObjectEraserObject.Create(TThEraserStyle.Create, FItemList);
FDrawObject := FPenDrawObj;
FMouseDowned := False;
end;
destructor TPenDrawLayer.Destroy;
begin
FPenDrawObj.Free;
FEraDrawObj.Free;
inherited;
end;
function TPenDrawLayer.DoHitTest(X, Y: Integer): Boolean;
begin
Result := inherited;
if Result then
Result := Assigned(FDrawObject);
end;
procedure TPenDrawLayer.SetDrawMode(const Value: TThDrawMode);
begin
inherited;
case Value of
dmPen: FDrawObject := FPenDrawObj;
dmEraser: FDrawObject := FEraDrawObj;
end;
Update;
end;
{ TThShapeDrawLayer }
constructor TShapeDrawLayer.Create(ALayerCollection: TLayerCollection);
begin
inherited;
FShapeDrawObj := TThShapeDrawObject.Create(FItemList);
FDrawObject := FShapeDrawObj;
end;
procedure TShapeDrawLayer.DeleteSelectedItems;
begin
FShapeDrawObj.DeleteSelectedItems;
Update;
end;
destructor TShapeDrawLayer.Destroy;
begin
FShapeDrawObj.Free;
inherited;
end;
procedure TShapeDrawLayer.SetDrawMode(const Value: TThDrawMode);
begin
inherited;
if FDrawMode = dmSelect then
ShapeId := '';
end;
procedure TShapeDrawLayer.SetShapetId(const Value: string);
begin
FShapeId := Value;
FShapeDrawObj.ShapeId := FShapeId;
end;
{ TThBackgroundLayer }
function TThBackgroundLayer.DoHitTest(X, Y: Integer): Boolean;
begin
Result := False;
end;
end.
|
unit ThConsts;
interface
uses
System.UIConsts;
const
{$IFDEF RELEASE}
ItemDefaultOpacity = 0.8;
{$ELSE}
ItemDefaultOpacity = 1;
{$ENDIF}
ItemMinimumSize = 30;
ItemShapeDefaultColor = claGreen;
ItemLineThickness = 7;
ItemLineSelectionThickness = 15; // 선 선택 범위
ItemFocusMinimumSize = ItemMinimumSize * 0.5;
//{$DEFINE ON_HIGHLIGHT}
ItemHighlightSize = 3;
// ItemHighlightColor = $FFAAAAAA;
ItemHighlightColor = claGray;
ItemSelectionSize = 3;
ItemSelectionColor = claSkyblue;
ItemResizeSpotOverColor = claRed;
ItemResizeSpotOutColor = claWhite;
ItemResizeSpotDisableColor = claDarkgray;
ItemResizeSpotRadius = 6;
// Item factorys Unique id
ItemFactoryIDRectangle = 1100;
ItemFactoryIDLine = 1200;
ItemFactoryIDCircle = 1300;
ItemFactoryIDText = 2000;
ItemFactoryIDImageFile = 3000;
CanvasTrackAniCount: Single = 5;
CanvasTrackDuration: Single = 0.5;
CanvasZoomOutRate: Single = 0.9;
CanvasZoomInRate: Single = 1.1;
CanvasZoomScaleDefault: Single = 1;
CanvasZoomScaleMax: Single = 20;
CanvasZoomScaleMin: Single = 0.05;
//
// CanvasZoomOutRate: Single = 0.9;
// CanvasZoomInRate: Single = 1.1;
// CanvasZoomScaleDefault: Single = 0.1;
// CanvasZoomScaleMax: Single = 15;
// CanvasZoomScaleMin: Single = 0.001;
implementation
end.
|
(*
* Copyright (c) 2004
* HouSisong@gmail.com
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*)
//------------------------------------------------------------------------------
// 具现化的Single类型的声明
// Create by HouSisong, 2006.10.19
//------------------------------------------------------------------------------
unit DGL_Single;
interface
uses
SysUtils;
{$I DGLCfg.inc_h}
type
_ValueType = Single;
const
_NULL_Value:Single=0;
function _HashValue(const Key: _ValueType):Cardinal;{$ifdef _DGL_Inline} inline; {$endif}//Hash函数
{$I DGL.inc_h}
type
TSingleAlgorithms = _TAlgorithms;
ISingleIterator = _IIterator;
ISingleContainer = _IContainer;
ISingleSerialContainer = _ISerialContainer;
ISingleVector = _IVector;
ISingleList = _IList;
ISingleDeque = _IDeque;
ISingleStack = _IStack;
ISingleQueue = _IQueue;
ISinglePriorityQueue = _IPriorityQueue;
ISingleSet = _ISet;
ISingleMultiSet = _IMultiSet;
TSingleVector = _TVector;
TSingleDeque = _TDeque;
TSingleList = _TList;
ISingleVectorIterator = _IVectorIterator; //速度比_IIterator稍快一点:)
ISingleDequeIterator = _IDequeIterator; //速度比_IIterator稍快一点:)
ISingleListIterator = _IListIterator; //速度比_IIterator稍快一点:)
TSingleStack = _TStack;
TSingleQueue = _TQueue;
TSinglePriorityQueue = _TPriorityQueue;
ISingleMapIterator = _IMapIterator;
ISingleMap = _IMap;
ISingleMultiMap = _IMultiMap;
TSingleSet = _TSet;
TSingleMultiSet = _TMultiSet;
TSingleMap = _TMap;
TSingleMultiMap = _TMultiMap;
TSingleHashSet = _THashSet;
TSingleHashMultiSet = _THashMultiSet;
TSingleHashMap = _THashMap;
TSingleHashMultiMap = _THashMultiMap;
implementation
uses
HashFunctions;
function _HashValue(const Key :_ValueType):Cardinal; overload;
begin
result:=HashValue_Single(Key);
end;
{$I DGL.inc_pas}
end.
|
unit main;
interface
uses libFilmFile, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.StdCtrls, System.Classes;
type TForm1 = class(TForm)
StringGrid1: TStringGrid;
Button1: TButton;
Button2: TButton;
Edit1: TEdit;
Edit2: TEdit;
Button3: TButton;
Edit3: TEdit;
Button4: TButton;
Button5: TButton;
Label1: TLabel;
Edit4: TEdit;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
private
FilmFile: libFilmFile.TFilmFile;
public
procedure GridUpdate;
end;
var
Form1: TForm1;
implementation
uses
add_dialog, custom_output, plot;
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
add_dialog.Form2.SetFilmFile(FilmFile);
add_dialog.Form2.Show;
end;
procedure TForm1.GridUpdate;
var
FilmArray: libFilmFile.TFilmArray;
i: integer;
leastRatedFilm: TFilm;
begin
FilmArray := FilmFile.update;
leastRatedFilm.rating := 1000;
StringGrid1.RowCount := length(FilmArray) + 1;
for i := 0 to length(FilmArray) - 1 do begin
if FilmArray[i].rating < leastRatedFilm.rating then
leastRatedFilm := FilmArray[i];
StringGrid1.Cells[0, i + 1] := FilmArray[i].name;
StringGrid1.Cells[1, i + 1] := FilmArray[i].genre;
StringGrid1.Cells[2, i + 1] := FilmArray[i].mainActor;
StringGrid1.Cells[3, i + 1] := intToStr(FilmArray[i].year);
StringGrid1.Cells[4, i + 1] := intToStr(FilmArray[i].rating);
end;
if length(filmArray) = 0 then
leastRatedFilm.genre := 'Data unavailable';
Edit4.Text := leastRatedFilm.genre;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
if StringGrid1.Selection.Top = 0 then
raise Exception.Create('Wrong Selection!')
else begin
FilmFile.delete(StringGrid1.Selection.Top - 1);
GridUpdate;
end;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
Form3.SetFilmFile(filmFile);
Form3.SetParameters(Edit1.Text, genreFlt, strToInt(Edit2.Text));
Form3.Show();
end;
procedure TForm1.Button4Click(Sender: TObject);
begin
Form3.SetFilmFile(filmFile);
Form3.SetParameters(Edit3.Text);
Form3.Show();
end;
procedure TForm1.Button5Click(Sender: TObject);
begin
Form4.SetFilmFile(filmFile);
Form4.Show();
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FilmFile := libFilmFile.TFilmFile.Create('data.bin');
GridUpdate;
StringGrid1.Cells[0, 0] := 'Name';
StringGrid1.Cells[1, 0] := 'Genre';
StringGrid1.Cells[2, 0] := 'Main Actor';
StringGrid1.Cells[3, 0] := 'Year';
StringGrid1.Cells[4, 0] := 'Rating';
end;
end.
|
unit Xplat.Services;
interface
uses
System.Classes, System.IniFiles;
type
IPleaseWaitService = interface
['{86D7671B-A5A0-4ADB-A4F9-E609A8246DC1}']
procedure StartWait;
procedure StopWait;
end;
IIniFileService = interface(IInterface)
['{6024D9FD-3B3B-4B5A-B767-D87993B2E32D}']
function ReadBool(const Section, Ident: string; Default: Boolean): Boolean;
procedure WriteBool(const Section, Ident: string; Value: Boolean);
function ReadString(const Section, Ident, Default: string): string;
procedure WriteString(const Section, Ident, Value: String);
function ReadInteger(const Section, Ident: string; Default: Integer): Integer;
procedure WriteInteger(const Section, Ident: string; Value: Integer);
function ReadDate(const Section, Ident: string; Default: TDateTime): TDateTime;
procedure WriteDate(const Section, Ident: string; Value: TDateTime);
function ReadDateTime(const Section, Ident: string; Default: TDateTime): TDateTime;
procedure WriteDateTime(const Section, Ident: string; Value: TDateTime);
function ReadTime(const Section, Ident: string; Default: TDateTime): TDateTime;
procedure WriteTime(const Section, Ident: string; Value: TDateTime);
function ReadFloat(const Section, Ident: string; Default: Double): Double;
procedure WriteFloat(const Section, Ident: string; Value: Double);
procedure ReadSection(const Section: string; Strings: TStrings);
procedure ReadSections(Strings: TStrings);
procedure ReadSectionValues(const Section: string; Strings: TStrings);
procedure EraseSection(const Section: string);
procedure DeleteKey(const Section, Ident: String);
procedure UpdateFile;
end;
implementation
uses
FMX.Platform
{$IFDEF MACOS}
//Services common to Apple Mac and iOS platforms
, Apple.IniFiles
{$IFDEF IOS}
//iOS specific service implementations
, iOS.Services
{$ELSE}
//Mac specific service implementations
, Mac.Services
{$ENDIF}
{$ENDIF}
{$IFDEF ANDROID}
//Android specific service implementation
, Android.Services
{$ENDIF}
{$IFDEF MSWINDOWS}
//Windows specific service implementations
, Windows.Services
{$ENDIF}
;
end.
|
unit Amazon.Storage.Service;
interface
uses Amazon.Storage.Service.Intf, System.Classes, Amazon.Storage.Service.API, Amazon.Storage.Service.Config, System.SysUtils,
IdCustomHTTPServer, Data.Cloud.CloudAPI, Amazon.Storage.Service.Types, System.Math;
type
TAmazonRegion = Amazon.Storage.Service.API.TAmazonRegion;
TAmazonStorageServiceConfig = Amazon.Storage.Service.Config.TAmazonStorageServiceConfig;
TAmazonBucketResult = Amazon.Storage.Service.API.TAmazonBucketResult;
TAmazonObjectResult = Amazon.Storage.Service.API.TAmazonObjectResult;
TAmazonProtocol = Amazon.Storage.Service.Types.TAmazonProtocol;
TAmazonStorageService = class(TInterfacedObject, IAmazonStorageService)
private
FStorage: Amazon.Storage.Service.API.TAmazonStorageService;
FBucketName: string;
function Configuration: TAmazonStorageServiceConfig;
function GetFileContentType(const AFilePath: string): string;
function DownloadFile(const AFileName: string): TMemoryStream;
function ListBuckets: TStrings;
function GetBucket(const ABucketName: string): TAmazonBucketResult;
procedure CreateBucket(const ABucketName: string);
procedure DeleteBucket(const ABucketName: string);
procedure UploadFile(const AFilePath: string); overload;
procedure UploadFile(const AFilePath, AFileName: string); overload;
procedure UploadFile(const AFile: TMemoryStream; AFileName: string); overload;
procedure DeleteFile(const AFileName: string);
constructor Create(const ABucketName: string);
public
class function New(const ABucketName: string = ''): IAmazonStorageService;
destructor Destroy; override;
end;
implementation
uses Winapi.Windows;
procedure TAmazonStorageService.UploadFile(const AFilePath, AFileName: string);
var
LBinaryReader: TBinaryReader;
LFileContent: TBytes;
LFileInformation: TStringList;
LResponseInfo: TCloudResponseInfo;
begin
try
if not FileExists(AFilePath) then
raise Exception.Create('Não foi possível encontrar o arquivo no diretório informado!');
if FBucketName.Trim.IsEmpty then
raise Exception.Create('Não foi informado o bucket name de onde o arquivo deverá ficar salvo!');
LBinaryReader := TBinaryReader.Create(AFilePath);
try
LFileContent := LBinaryReader.ReadBytes(LBinaryReader.BaseStream.Size);
finally
LBinaryReader.Free;
end;
LFileInformation := TStringList.Create;
LResponseInfo := TCloudResponseInfo.Create;
try
LFileInformation.Add('Content-type=' + GetFileContentType(AFilePath));
if not FStorage.UploadObject(FBucketName, AFileName, LFileContent, False, LFileInformation, nil,
TAmazonACLType.amzbaPrivate, LResponseInfo) then
raise Exception.CreateFmt('%d - %s', [LResponseInfo.StatusCode, LResponseInfo.StatusMessage]);
finally
LResponseInfo.Free;
LFileInformation.Free;
end;
except
on E:Exception do
raise Exception.Create('Não foi possível fazer o upload do arquivo. O seguinte erro ocorreu: ' + sLineBreak + E.Message);
end;
end;
procedure TAmazonStorageService.UploadFile(const AFile: TMemoryStream; AFileName: string);
var
LFilePath: string;
LTempFolder: array[0..MAX_PATH] of Char;
begin
GetTempPath(MAX_PATH, @LTempFolder);
LFilePath := StrPas(LTempFolder) + FormatDateTime('hhmmss', Now) + Random(1000).ToString +
StringReplace(AFileName,'/','_',[rfReplaceAll, rfIgnoreCase]);
try
AFile.Position := 0;
AFile.SaveToFile(LFilePath);
Self.UploadFile(LFilePath, AFileName);
finally
if FileExists(LFilePath) then
DeleteFile(LFilePath);
end;
end;
procedure TAmazonStorageService.UploadFile(const AFilePath: string);
begin
Self.UploadFile(AFilePath, ExtractFileName(AFilePath));
end;
function TAmazonStorageService.Configuration: TAmazonStorageServiceConfig;
begin
Result := TAmazonStorageServiceConfig.GetInstance;
end;
constructor TAmazonStorageService.Create(const ABucketName: string);
begin
FStorage := TAmazonStorageServiceConfig.GetInstance.GetNewStorage;
FBucketName := ABucketName;
if ABucketName.Trim.IsEmpty then
FBucketName := Self.Configuration.MainBucketName;
end;
procedure TAmazonStorageService.CreateBucket(const ABucketName: string);
var
LResponseInfo: TCloudResponseInfo;
begin
LResponseInfo := TCloudResponseInfo.Create;
try
FStorage.CreateBucket(ABucketName, TAmazonACLType.amzbaPrivate, Self.Configuration.Region, LResponseInfo);
if LResponseInfo.StatusCode <> 200 then
raise Exception.CreateFmt('%d - %s', [LResponseInfo.StatusCode, LResponseInfo.StatusMessage]);
finally
LResponseInfo.Free;
end;
end;
procedure TAmazonStorageService.DeleteBucket(const ABucketName: string);
var
LResponseInfo: TCloudResponseInfo;
begin
LResponseInfo := TCloudResponseInfo.Create;
try
FStorage.DeleteBucket(ABucketName, LResponseInfo, Self.Configuration.Region);
if LResponseInfo.StatusCode <> 204 then
raise Exception.CreateFmt('%d - %s', [LResponseInfo.StatusCode, LResponseInfo.StatusMessage]);
finally
LResponseInfo.Free;
end;
end;
procedure TAmazonStorageService.DeleteFile(const AFileName: string);
begin
try
if FBucketName.Trim.IsEmpty then
raise Exception.Create('Não foi informado o bucket name de onde o arquivo se encontra!');
FStorage.DeleteObject(FBucketName, AFileName);
except
on E:Exception do
raise Exception.Create('Erro ao excluir o arquivo. O seguinte erro ocorreu: ' + sLineBreak + E.Message);
end;
end;
destructor TAmazonStorageService.Destroy;
begin
FStorage.ConnectionInfo.Free;
FStorage.Free;
inherited;
end;
function TAmazonStorageService.DownloadFile(const AFileName: string): TMemoryStream;
begin
Result := nil;
try
if FBucketName.Trim.IsEmpty then
raise Exception.Create('Não foi informado o bucket name de onde o arquivo se encontra!');
Result := TMemoryStream.Create;
FStorage.GetObject(FBucketName, AFileName, Result);
Result.Position := 0;
except
on E:Exception do
begin
if Assigned(Result) then
Result.Free;
raise Exception.Create('Erro ao fazer download do arquivo. O seguinte erro ocorreu: ' + sLineBreak + E.Message);
end;
end;
end;
function TAmazonStorageService.GetBucket(const ABucketName: string): TAmazonBucketResult;
var
LResponseInfo: TCloudResponseInfo;
begin
LResponseInfo := TCloudResponseInfo.Create;
try
Result := FStorage.GetBucket(ABucketName, nil, LResponseInfo);
if LResponseInfo.StatusCode <> 200 then
raise Exception.CreateFmt('%d - %s', [LResponseInfo.StatusCode, LResponseInfo.StatusMessage]);
finally
LResponseInfo.Free;
end;
end;
function TAmazonStorageService.GetFileContentType(const AFilePath: string): string;
var
LMIMETable: TIdThreadSafeMimeTable;
begin
LMIMETable := TIdThreadSafeMimeTable.Create(True);
try
Result := LMIMETable.GetFileMIMEType(AFilePath);
finally
LMIMETable.Free;
end;
end;
function TAmazonStorageService.ListBuckets: TStrings;
var
LResponseInfo: TCloudResponseInfo;
begin
LResponseInfo := TCloudResponseInfo.Create;
try
Result := FStorage.ListBuckets(LResponseInfo);
if LResponseInfo.StatusCode <> 200 then
raise Exception.CreateFmt('%d - %s', [LResponseInfo.StatusCode, LResponseInfo.StatusMessage]);
finally
LResponseInfo.Free;
end;
end;
class function TAmazonStorageService.New(const ABucketName: string = ''): IAmazonStorageService;
begin
Result := TAmazonStorageService.Create(ABucketName);
end;
end.
|
unit uPreSaleReceive;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Mask, DateBox, DBCtrls, DB, DBTables, Grids, DBGrids,
Buttons, DBCGrids, ComCtrls, ADODB, SuperComboADO, siComp, siLangRT,
PaiDeForms, Variants, uFrmPayPartial, uCCMercuryIntegration,
uFrmCreditPay, uPCCIntegration, cxStyles, cxCustomData, cxGraphics,
cxFilter, cxData, cxEdit, cxDBData, cxGridLevel, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxClasses, cxControls,
cxGridCustomView, cxGrid;
type
TPreSaleReceive = class(TFrmParentForms)
Panel1: TPanel;
Panel9: TPanel;
Panel3: TPanel;
spTestPayType: TADOStoredProc;
spquPayTypeMin: TADOStoredProc;
spquPayTypeMinDifDay: TIntegerField;
spquPayTypeMinTotalSale: TFloatField;
pgReceive: TPageControl;
tbSingle: TTabSheet;
tbMultiple: TTabSheet;
pnlPaymentType: TPanel;
Image1: TImage;
Image3: TImage;
Label4: TLabel;
pnlPayTitle: TPanel;
cmbPaymentType: TSuperComboADO;
pnlDepositDate: TPanel;
lblPreDate: TLabel;
Image6: TImage;
Image7: TImage;
spDep30: TSpeedButton;
spDep60: TSpeedButton;
spDep90: TSpeedButton;
pnlDateTitle: TPanel;
EditDepositDate: TDateBox;
Label8: TLabel;
EditTotalInvoice: TEdit;
pnlShowCash: TPanel;
lblCashTotal: TLabel;
EditTotalCash: TEdit;
lblPlus: TLabel;
lblReceived: TLabel;
EditReceived: TEdit;
lblMinus: TLabel;
spLine: TShape;
lblChange: TLabel;
EditChange: TEdit;
lblEqual: TLabel;
Label13: TLabel;
EditReceiveDate: TDateBox;
pnlShowAuthorization: TPanel;
Label1: TLabel;
EditAuthorization: TEdit;
pnlMultiParcela: TPanel;
pnlParc1: TPanel;
lblParc1: TLabel;
Label12: TLabel;
cmbPayType1: TSuperComboADO;
lblAuto1: TLabel;
EditAuto1: TEdit;
EditDep1: TDateBox;
lblDep1: TLabel;
Label16: TLabel;
EditValue1: TEdit;
pnlParc2: TPanel;
Label17: TLabel;
Label18: TLabel;
lblAuto2: TLabel;
lblDep2: TLabel;
Label22: TLabel;
cmbPayType2: TSuperComboADO;
EditAuto2: TEdit;
EditDep2: TDateBox;
EditValue2: TEdit;
pnlParc3: TPanel;
Label23: TLabel;
Label24: TLabel;
lblAuto3: TLabel;
lblDep3: TLabel;
Label28: TLabel;
cmbPayType3: TSuperComboADO;
EditAuto3: TEdit;
EditDep3: TDateBox;
EditValue3: TEdit;
pnlParc4: TPanel;
Label29: TLabel;
Label30: TLabel;
lblAuto4: TLabel;
lblDep4: TLabel;
Label33: TLabel;
cmbPayType4: TSuperComboADO;
EditAuto4: TEdit;
EditDep4: TDateBox;
EditValue4: TEdit;
pnlParc5: TPanel;
Label34: TLabel;
Label35: TLabel;
lblAuto5: TLabel;
lblDep5: TLabel;
Label38: TLabel;
cmbPayType5: TSuperComboADO;
EditAuto5: TEdit;
EditDep5: TDateBox;
EditValue5: TEdit;
cbxCloseLayaway: TCheckBox;
Image4: TImage;
Image5: TImage;
pnlLayway: TPanel;
lblPayment: TLabel;
lblLayaway: TLabel;
lbMenus: TLabel;
Shape1: TShape;
lbIqual: TLabel;
lbBalance: TLabel;
edPayment: TEdit;
edLayaway: TEdit;
edtBalance: TEdit;
spHelp: TSpeedButton;
btOK: TButton;
btCancel: TButton;
btnPartialPayment2: TSpeedButton;
lbPartialInfo2: TLabel;
pnlDelayPayments: TPanel;
lbPartialInfo: TLabel;
btnPartialPayment: TSpeedButton;
cbPayPlace1: TComboBox;
lbPayPlace1: TLabel;
lbPayPlace2: TLabel;
cbPayPlace2: TComboBox;
lbPayPlace3: TLabel;
cbPayPlace3: TComboBox;
lbPayPlace4: TLabel;
cbPayPlace4: TComboBox;
lbPayPlace5: TLabel;
cbPayPlace5: TComboBox;
lblCustomerCredit: TLabel;
lblCustomerCreditValue: TLabel;
pnlPaymentPlace: TPanel;
lbPaymentPlace: TLabel;
cbPaymentPlace: TComboBox;
spPreSaleDeleteSingleDelayPayment: TADOStoredProc;
pnlMultiButtons: TPanel;
btMulti2: TSpeedButton;
btMulti3: TSpeedButton;
btMulti4: TSpeedButton;
btMulti5: TSpeedButton;
pnlPayButton: TPanel;
spPayCash: TSpeedButton;
spPayVisa: TSpeedButton;
spPayMaster: TSpeedButton;
spPayAmerican: TSpeedButton;
spPayCheck: TSpeedButton;
pnlShowAccount: TPanel;
lbAccount: TLabel;
edtAccountCard: TEdit;
lbAccountCredit: TLabel;
lbAccountCreditValue: TLabel;
quAccountBalance: TADODataSet;
quAccountBalanceAmount: TBCDField;
pnlAccount1: TPanel;
lbAccount1: TLabel;
edtAccount1: TEdit;
pnlAccount2: TPanel;
lbAccount2: TLabel;
edtAccount2: TEdit;
pnlAccount3: TPanel;
lbAccount3: TLabel;
edtAccount3: TEdit;
pnlAccount4: TPanel;
lbAccount4: TLabel;
edtAccount4: TEdit;
pnlAccount5: TPanel;
lbAccount5: TLabel;
edtAccount5: TEdit;
quAccountBalanceExpirationDate: TDateTimeField;
pnlPaySuggestion: TPanel;
Image2: TImage;
Image8: TImage;
pnlPaymentSugg: TPanel;
grdBrowse: TcxGrid;
grdBrowseDB: TcxGridDBTableView;
grdBrowseDBImageIndex: TcxGridDBColumn;
grdBrowseDBMeioPag: TcxGridDBColumn;
grdBrowseDBAmount: TcxGridDBColumn;
grdBrowseDBOBS: TcxGridDBColumn;
grdBrowseLevel: TcxGridLevel;
quUpPayment: TADODataSet;
quUpPaymentIDPaymentCondition: TIntegerField;
quUpPaymentIDMeioPag: TIntegerField;
quUpPaymentMeioPag: TStringField;
quUpPaymentImageIndex: TIntegerField;
quUpPaymentAmount: TBCDField;
quUpPaymentOBS: TStringField;
dsUpPayment: TDataSource;
quUpPaymentEstimetedDate: TDateTimeField;
grdBrowseDBEstimetedDate: TcxGridDBColumn;
procedure btOKClick(Sender: TObject);
procedure btCancelClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure spPayCashClick(Sender: TObject);
procedure spPayVisaClick(Sender: TObject);
procedure cmbPaymentTypeSelectItem(Sender: TObject);
procedure spDep30Click(Sender: TObject);
procedure spPayMasterClick(Sender: TObject);
procedure spPayAmericanClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure EditReceivedChange(Sender: TObject);
procedure SelecionaParcela(Sender: TObject);
procedure cmbPayType1SelectItem(Sender: TObject);
procedure cmbPayType2SelectItem(Sender: TObject);
procedure cmbPayType3SelectItem(Sender: TObject);
procedure cmbPayType4SelectItem(Sender: TObject);
procedure cmbPayType5SelectItem(Sender: TObject);
procedure pgReceiveChange(Sender: TObject);
procedure RecalcTotals(Sender : TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure EditReceivedExit(Sender: TObject);
procedure edPaymentChange(Sender: TObject);
procedure edPaymentExit(Sender: TObject);
procedure spHelpClick(Sender: TObject);
procedure edPaymentKeyPress(Sender: TObject; var Key: Char);
procedure EditValue1KeyPress(Sender: TObject; var Key: Char);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnPartialPaymentClick(Sender: TObject);
procedure btnPartialPayment2Click(Sender: TObject);
procedure cbPaymentPlaceSelect(Sender: TObject);
procedure cbPayPlace1Change(Sender: TObject);
procedure cbPayPlace2Change(Sender: TObject);
procedure cbPayPlace3Change(Sender: TObject);
procedure cbPayPlace4Change(Sender: TObject);
procedure cbPayPlace5Change(Sender: TObject);
procedure spPayCheckClick(Sender: TObject);
procedure NeedSwipe(Sender: TObject; var SwipedTrack: WideString;
var Canceled: Boolean);
procedure edtAccountCardExit(Sender: TObject);
procedure edtAccountCardKeyPress(Sender: TObject; var Key: Char);
procedure edtAccountCardEnter(Sender: TObject);
private
MyPayType,
MyIDPreSale,
MyIDCliente,
IDInvoice : Integer;
sRefound,
sTotalRef,
sReceive,
sTotalRec,
sSetDateTo,
sPaymentPlaces,
sCadastrar,
sBonusInfo,
sBonusCodeValue : String;
MyTotInvoice,
TotParcela,
MyLayaway,
MyTotCash,
MyPayment : Currency;
MyquPreSaleInfo : TADOQuery;
MyquPreSaleItem : TADOStoredProc;
MyPaymentTypeID,
MyOtherComID,
MyIDTouristGroup : Integer;
MyDepositDate,
MyPreSaleDate : TDateTime;
MyIsLayaway : Boolean;
IsToPrintLayaway : Boolean;
IsLayawayToClose : Boolean;
MyIDCashRegMov : Integer;
OldTag : Integer;
MyquPreSaleValue : TADOStoredProc;
nParcela : Integer;
IsOnRecalc : Boolean;
fHasDeposit : Boolean;
fFormOfPayment : Integer;
FPaymentChange : Double;
FBonnusBuck : Currency;
FIDBonnus : Integer;
fConfirmEst : Boolean;
fPrintBoleto : Boolean;
fCustSAMax : Currency;
fCustDeliquent : Boolean;
FErrorMsg : String;
FrmPayPartial : TFrmPayPartial;
FrmCreditPay : TFrmCreditPay;
procedure PushError(ErrorType: Integer; sError: String);
function ValidSinglePaymentType : Boolean;
function ValidateMultiple(IsSaving : Boolean) : Boolean;
function ValidadeLocalPayment:Boolean;
function ValidateCustomer: Boolean;
function ValidadeStoreAccount(APayment : Currency):Boolean;
function AddPayment:Boolean;
function DoPay:Boolean;
function PrintDocument:Boolean;
procedure RefreshPaySugg;
procedure OpenPaySugg;
procedure ClosePaySugg;
procedure StartSingle;
procedure StartMultiple;
procedure PaintPanel(PanelTag : Integer; Color : Integer);
procedure AtuDepositState(PaymentTypeID : Integer);
procedure CreateParams( var Params: TCreateParams ); override;
function GetPayment:Double;
procedure CancelPreDatar;
function DeletePayment: Boolean;
function ShowCloseLayAway(TotLayAway: Currency): Boolean;
procedure SetComboPaymentPlaces(sComboPaymentPlaces: String; bVisible: Boolean);
function ValidateReceive: Boolean;
function PagamentoJaSelecionado(Tipo: Integer; IDMeioPag: String;
Parcela: Integer; RaiseMessage: Boolean): Boolean;
procedure cmbPayTypeSelectItem(Sender: TObject);
procedure cbPayPlaceChange(Sender: TObject);
function ShowCredit(var Amount: Double; Const Verify: Boolean) : Boolean;
function GetAccountCredit(Account : String; var Amount : Currency; var ExpDate : TDateTime):Boolean;
procedure ClearCredit;
function TipoPagamentoJaSelecionado(Tipo, Parcela: Integer;
RaiseMessage: Boolean): Boolean;
procedure RefreshCustomerCredit;
procedure RefreshAccountCredit;
procedure RefreshCustomerInfo;
//PCCharge
function DoPCCharge(var AAuth, ATroud, ALastDigits: String; Processor, MercantNum:String; AAmount: Currency; iPayType:Integer): Boolean;
function HasCreditCardProcessor(IDMeioPag: Integer; PayType:Integer):Boolean;
function CallProcessor(IDMeioPag: Integer; PayType: Integer; var AAuth, ATroud, ALastDigits: String; AAmount: Currency):Boolean;
procedure SucessFullSwipe(Sender: TObject; const ACardNumber,
ACardMember, ACardExpireDate: WideString);
//Mercury CC
function DoMercury(var AAuth, ATroud, ALastDigits: String; AAmount: Currency; iPayType : Integer): Boolean;
function MercuryResult(AmercuryWidget : TCCWidget): Boolean;
procedure DisablePriorPayments(ALastToDisable: Integer);
function PriorPaymentsSelected(ALastPayment: Integer): Boolean;
procedure NeedTroutD(Sender: TObject; var ATrouD, ARefNo, AAuthCode: WideString;
var ACanceled: Boolean);
procedure PreparePCC(APCCT: TPCCTransaction; AProcessor,
AMercantNum: String);
function PCCResult(APCCT: TPCCTransaction): Boolean;
function DoPCVoid(var AAuth, ATroud, ALastDigits: String; Processor, MercantNum: String): Boolean;
function PaymentIsLast(ALastPayment: Integer): Boolean;
function PriorPaymetValues(ALastPayment: Integer): Currency;
function GetBonusPayment:Integer;
procedure PrintBankBillet;
procedure RecalcInvoiceTotal;
function ProcessInvoiceBonus : Boolean;
function getPaymentCard(arg_processor, arg_paymentType: Integer): TCCWidget;
public
function processCardCreditIsPresent(arg_amount: Double; arg_widget:TCCWidget): boolean;
function processCardDebitIsPresent(arg_amount: Double; arg_widget: TCCWidget): boolean;
function processCardIsNotPresent(arg_amount: Double; arg_widget: TCCWidget): boolean;
function Start(quPreSaleInfo: TADOQuery;
quPreSaleValue: TADOStoredProc;
quPreSaleItem: TADOStoredProc;
IDCashRegMov: integer;
IsLayaway: Boolean;
IsToPrint: Boolean;
FormOfPayment: Integer;
BonnusBuck: Currency;
var Change: Double): Boolean;
end;
implementation
uses uDM, xBase, uPassword, uPrintReceipt, uMsgBox, uMsgConstant, uHandleError,
uNumericFunctions, uDateTimeFunctions, uCharFunctions, uDMGlobal, uSystemConst,
Math, uFrmPCCSwipeCard, ufrmPCCharge, ufrmPCVoid, ConvUtils, uBonusBucks,
uCreditCardFunction, uFrmPrintBoleto;
{$R *.DFM}
procedure TPreSaleReceive.PushError(ErrorType: Integer; sError: String);
begin
DM.SetError(ErrorType, Self.Name, sError);
end;
function TPreSaleReceive.GetBonusPayment:Integer;
var
myQuery : TADODataSet;
begin
myQuery := TADODataSet.Create(Self);
try
myQuery.Connection := DM.ADODBConnect;
myQuery.CommandText := 'Select IDMeioPag From MeioPag (NOLOCK) Where Tipo = 8 AND Desativado = 0 AND Hidden = 0';
myQuery.Open;
if myQuery.RecordCount > 0 then
Result := myQuery.FieldByName('IDMeioPag').AsInteger
else
Result := -1;
finally
FreeAndNil(myQuery);
end;
end;
function TPreSaleReceive.GetPayment:Double;
begin
if MyIsLayaway then
Result := MyPayment
else
Result := MyTotInvoice;
end;
function TPreSaleReceive.DoPay:Boolean;
var
cCash: Currency;
begin
DM.FTraceControl.TraceIn('TPreSaleReceive.DoPay');
Result := True;
try
if pnlShowCash.Visible then
cCash := MyStrToMoney(EditReceived.Text);
Result := DM.fPOS.PreSalePay(MyIDPreSale,
MyIDTouristGroup,
MyOtherComID,
MyIDCashRegMov,
DM.fStore.ID,
Now,
EditReceiveDate.Date,
cCash,
DM.FBonusSync.BonusValue,
DM.FBonusSync.BonusCode,
IDInvoice);
if not Result then
raise Exception.Create('error receiving');
except
on E: Exception do
begin
DM.FTraceControl.SetException(E.Message, 'TPreSaleReceive');
Result := False;
end;
end;
end;
function TPreSaleReceive.PrintDocument:Boolean;
var
iPrinType : Integer;
begin
try
if MyIsLayaway then
iPrinType := RECEIPT_TYPE_LAYAWAY_RECEIVE
else
iPrinType := RECEIPT_TYPE_HOLD;
if (DM.fPrintReceipt.PrintReceipt) then
with TPrintReceipt.Create(Self) do
Start(MyIDPreSale, iPrinType, MyStrToCurrency(EditChange.Text));
Result := True;
Except
on E: Exception do
begin
PushError(CRITICAL_ERROR, 'PreSaleReceive.PrintDocument.Exception' + #13#10 + E.Message);
Result := False;
end;
end;
end;
function TPreSaleReceive.AddPayment:Boolean;
function GetAuthorization(sAuthorization: String): String;
begin
if sAuthorization = '' Then
Result := Trim(EditAuthorization.Text)
else
Result := sAuthorization;
end;
var
Authorization : String;
sValue : String;
ExprireDate : TDateTime;
i : Integer;
fCustomerDoc : String;
begin
DM.FTraceControl.TraceIn('TPreSaleReceive.AddPayment');
Result := True;
fCustomerDoc := '';
try
btOK.Enabled := False;
btCancel.Enabled := False;
if MyStrToInt(cmbPaymentType.LookUpValue) = 1 then
ExprireDate := Int(EditReceiveDate.Date)
else
ExprireDate := Int(EditDepositDate.Date);
if pnlShowAuthorization.Visible then
Authorization := EditAuthorization.Text
else
Authorization := '';
// Grava nova parcela
if pgReceive.ActivePage = tbSingle then
begin
MyStrToMoney(EditReceived.Text);
if (DM.fPos.GetPayType(cmbPaymentType.LookUpValue) = PAYMENT_TYPE_CREDIT) and
(GetPayment >= 0) then
FrmCreditPay.DiscountCredit(GetPayment);
//Debito no gitf
if MyPayType = PAYMENT_TYPE_GIFTCARD then
fCustomerDoc := edtAccountCard.Text;
//Adicionar pagamento pre-datados caso tenha
if fHasDeposit then
begin
for i := 0 to FrmPayPartial.tvPartialPay.Items.Count-1 do
begin
if TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).IDCashRegMovClosed = -1 then
begin
Result := DM.fPOS.AddPayment(MyIDPreSale,
DM.fStore.ID,
DM.fUser.ID,
MyIDCliente,
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).IDPaymentType,
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).IDCashRegMov,
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).PreSaleDate,
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).ExpireDate,
IntToStr(i+1)+'/'+IntToStr(FrmPayPartial.tvPartialPay.Items.Count),
GetAuthorization(TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).Authorization),
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).Valor,
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).NumeroDoc,
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).DocCliente,
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).NomeCliente,
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).Telefone,
MyStrToInt(TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).Banco),
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).OBS,
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).PaymentPlace,
True); //Sempre que o pagamento foi criado pelo formulário de pre datado
// Ele será pre datado
//PollDisplay
DM.PollDisplayAddPayment(TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).IDPaymentType,
cmbPaymentType.Text,
TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).Valor);
end;
end;
end
else
if GetPayment <> 0 Then
begin
Result := DM.fPOS.AddPayment(MyIDPreSale,
DM.fStore.ID,
DM.fUser.ID,
MyIDCliente,
MyStrToInt(cmbPaymentType.LookUpValue),
MyIDCashRegMov,
EditReceiveDate.Date,
ExprireDate,
'1/1',
Authorization,
GetPayment,
'', fCustomerDoc, '', '', 0, '',
cbPaymentPlace.ItemIndex,
False);
//PollDisplay
DM.PollDisplayAddPayment(MyStrToInt(cmbPaymentType.LookUpValue),
cmbPaymentType.Text,
GetPayment);
end;
end
else
begin
// Usa o validate para incluir
Result := ValidateMultiple(True);
end;
if not Result then
raise Exception.Create('error paying');
except
on E: Exception do
begin
DM.FTraceControl.SetException(E.Message, 'TPreSaleReceive');
Result := False;
end;
end;
DM.FTraceControl.TraceOut;
end;
procedure TPreSaleReceive.CreateParams( var Params: TCreateParams );
begin
inherited CreateParams( Params );
Params.Style := WS_THICKFRAME or WS_POPUP;
end;
function TPreSaleReceive.Start( quPreSaleInfo: TADOQuery;
quPreSaleValue: TADOStoredProc;
quPreSaleItem: TADOStoredProc;
IDCashRegMov: integer;
IsLayaway: Boolean;
IsToPrint: Boolean;
FormOfPayment: Integer;
BonnusBuck: Currency;
var Change: Double): Boolean;
begin
DM.FTraceControl.TraceIn('TPreSaleReceive.Start');
try
MyIDCashRegMov := IDCashRegMov;
IsToPrintLayaway := IsToPrint;
MyIDPreSale := quPreSaleInfo.FieldByName('IDPreSale').AsInteger;
MyIDCliente := quPreSaleInfo.FieldByName('IDCustomer').AsInteger;
MyTotInvoice := MyRound(quPreSaleValue.FieldByName('TotalInvoice').AsFloat, 2);
MyPaymentTypeID := quPreSaleInfo.FieldByName('IDMeioPag').AsInteger;
MyDepositDate := quPreSaleInfo.FieldByName('DepositDate').AsDateTime;
MyPreSaleDate := quPreSaleInfo.FieldByName('PreSaleDate').AsDateTime;
MyOtherComID := quPreSaleInfo.FieldByName('OtherComissionID').AsInteger;
MyIDTouristGroup := quPreSaleInfo.FieldByName('IDTouristGroup').AsInteger;
MyquPreSaleInfo := quPreSaleInfo;
MyquPreSaleValue := quPreSaleValue;
MyquPreSaleItem := quPreSaleItem;
MyIsLayaway := IsLayaway;
EditReceiveDate.Date := Now;
cbxCloseLayaway.Checked := False;
cbxCloseLayaway.Visible := False;
fHasDeposit := False;
fFormOfPayment := FormOfPayment;
//Refresh nos totais
RecalcInvoiceTotal;
// Exibe Crédito acumulado do Cliente
RefreshCustomerCredit;
//Atualizo informacoes do cliente
RefreshCustomerInfo;
// Numero de Parcelas
nParcela := 1;
Left := 0;
Top := 102;
Height := Screen.Height - Top;
FBonnusBuck := BonnusBuck;
FIDBonnus := -1;
Result := (ShowModal = mrOK );
Change := FPaymentChange;
except
on E: Exception do
DM.FTraceControl.SaveTrace(DM.fUser.ID, E.Message, 'TPreSaleReceive');
end;
DM.FTraceControl.TraceOut;
end;
procedure TPreSaleReceive.btOKClick(Sender: TObject);
var
bCanExec : Boolean;
IDError : Integer;
ErrorMsg : String;
bCloseSale : boolean;
begin
DM.FTraceControl.TraceIn('TPreSaleReceive.btOKClick');
try
bCanExec := True;
//Faz todas as validaçoes aqui e depois chama a rotina correta
if ValidateReceive then
begin
//Close Sale
bCloseSale := not (MyIsLayaway) or ((MyRound(MyTotInvoice-(MyPayment + MyLayaway),2)=0) and (cbxCloseLayaway.Checked));
if bCloseSale then
begin
bCanExec := ProcessInvoiceBonus;
if not bCanExec then
Exit;
end;
try
DM.ADODBConnect.BeginTrans;
if not (MyIsLayaway) or (MyIsLayaway and (MyPayment <> 0)) then
begin
if MyIsLayaway Then
bCanexec := DeletePayment;
if bCanExec Then
bCanExec := AddPayment;
end;
//Close Payment
if bCanExec and bCloseSale then
bCanExec := DoPay;
finally
if bCanExec then
begin
DM.ADODBConnect.CommitTrans;
btCancel.Enabled := True;
PrintBankBillet;
btOK.Enabled := True;
ModalResult := mrOK;
end
else
begin
DM.ADODBConnect.RollbackTrans;
DM.FTraceControl.SaveTrace(DM.fUser.ID);
btCancel.Enabled := True;
btOK.Enabled := True;
if DM.fSystem.SrvParam[PARAM_APPLY_BONUS_ON_SALE] then
DM.BonusVoid(DM.FBonusSync.BonusCode, IDError, ErrorMsg);
MsgBox(MSG_INF_NOT_RECEIVE_HOLD, vbInformation + vbOkOnly);
ModalResult := mrNone;
end;
end;
end;
except
on E: Exception do
DM.FTraceControl.SaveTrace(DM.fUser.ID, E.Message, 'TPreSaleReceive');
end;
DM.FTraceControl.TraceOut;
end;
procedure TPreSaleReceive.btCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
CancelPreDatar;
end;
procedure TPreSaleReceive.FormShow(Sender: TObject);
begin
inherited;
WindowState := wsNormal;
// Seta Panel so do Cash
// pnlShowCash.Visible := False;
pnlShowCash.Visible := not IsLayawayToClose;
// Carrega valores iniciais do pagamento
EditTotalInvoice.Text := FloatToStrF(MyTotInvoice, ffCurrency, 20, 2);
lblMinus.Visible := MyTotInvoice > 0;
EditChange.Visible := lblMinus.Visible;
lblEqual.Visible := lblMinus.Visible;
lblChange.Visible := lblMinus.Visible;
spLine.Visible := lblMinus.Visible;
fPrintBoleto := False;
if MyTotInvoice < 0 then
begin
btOk.Caption := sRefound;
lblCashTotal.Caption := sTotalRef;
end
else
begin
lblCashTotal.Caption := sTotalRec;
btOk.Caption := sReceive;
end;
if FBonnusBuck <> 0 then
begin
FIDBonnus := GetBonusPayment;
if FIDBonnus <> -1 then
begin
StartMultiple;
cmbPayType1.LookUpValue := IntToStr(FIDBonnus);
cmbPayType1SelectItem(cmbPayType1);
EditValue1.Text := FormatFloat('#,##0.00', FBonnusBuck);
Exit;
end
else
MsgBox(MSG_CRT_NO_BONUS_PAYMENT_SET, vbSuperCritical + vbOkOnly);
end;
StartSingle;
end;
procedure TPreSaleReceive.spPayCashClick(Sender: TObject);
begin
cmbPaymentType.LookUpValue := IntToStr(PAY_TYPE_CASH);
cmbPaymentTypeSelectItem(nil);
if MyIsLayaway then
begin
if edPayment.CanFocus then
edPayment.SetFocus;
end
else
begin
if not pnlShowCash.Visible then
pnlShowCash.Visible := True;
if EditReceived.CanFocus then
EditReceived.SetFocus;
end;
end;
procedure TPreSaleReceive.spPayVisaClick(Sender: TObject);
begin
cmbPaymentType.LookUpValue := IntToStr(PAY_TYPE_VISA);
cmbPaymentTypeSelectItem(nil);
end;
procedure TPreSaleReceive.cmbPaymentTypeSelectItem(Sender: TObject);
var
FrmCreditPay: TFrmCreditPay;
CreditUse: Double;
sAuto, sRout, sLastDigits, FCoupon: String;
bError : Boolean;
cBonusValue : Currency;
iIDError : Integer;
sErrorStr : String;
BonusBucks: TBonusBucks;
begin
pnlDepositDate.Visible := False;
pnlShowCash.Visible := False;
pnlDelayPayments.Visible := False;
pnlShowAuthorization.Visible := False;
if cmbPaymentType.LookUpValue = '' then
Exit;
ClearCredit; // Limpa os créditos selecionados para utilização
MyTotCash := 0;
//Process Bonus
case MyStrToInt(cmbPaymentType.LookUpValue) of
PAY_TYPE_CASH:
begin
spPayCash.Down := True;
MyTotCash := MyTotInvoice;
if MyIsLayaway then
EditTotalCash.Text := FloatToStrF(MyPayment, ffCurrency, 20, 2)
else
EditTotalCash.Text := FloatToStrF(MyTotCash, ffCurrency, 20, 2);
end;
PAY_TYPE_VISA:
spPayVisa.Down := True;
PAY_TYPE_AMERICAN:
spPayAmerican.Down := True;
PAY_TYPE_MASTER:
spPayMaster.Down := True;
PAY_TYPE_CHECK:
spPayCheck.Down := True;
else
begin
// nao seleciona
spPayCash.Down := False;
spPayVisa.Down := False;
spPayAmerican.Down := False;
spPayMaster.Down := False;
spPayCheck.Down := False;
end;
end;
// Atualiza estado do Deposit Date
AtuDepositState(MyStrToInt(cmbPaymentType.LookUpValue));
//Verifica o Tipo de Pagamento
MyPayType := DM.fPOS.GetPayType(cmbPaymentType.LookUpValue);
if MyPayType = PAYMENT_TYPE_BONUSBUCK then
begin
FCoupon := UpperCase(InputBox(sBonusInfo, sBonusCodeValue, ''));
if (FCoupon <> '') then
begin
if (Length(FCoupon) <> 34) then
begin
MsgBox(MSG_CRT_BONUS_IS_NOT_VALID, vbCritical + vbOKOnly);
cmbPaymentType.LookUpValue := '';
Exit;
end;
if DM.BonusUse(FCoupon, cBonusValue, iIDError, sErrorStr) then
try
if MyIsLayaway then
MyPayment := cBonusValue
else
MyTotInvoice := cBonusValue;
AddPayment;
RecalcInvoiceTotal;
//Dou baixa do bonus no sistema
BonusBucks := TBonusBucks.Create(DM.ADODBConnect, DM.FBonusSync);
BonusBucks.SetUsed(MyIDPreSale, FCoupon);
cmbPaymentType.LookUpValue := '';
finally
btOK.Enabled := True;
btCancel.Enabled := True;
FreeAndNil(BonusBucks);
end
else
MsgBox(MSG_CRT_ERROR_USING_BONUS + sErrorStr, vbOKOnly + vbSuperCritical);
end;
Exit;
end;
if (MyStrToInt(cmbPaymentType.LookUpValue) > 0) and not ValidSinglePaymentType then
Exit;
if (MyPayType = PAYMENT_TYPE_CREDIT) and (GetPayment > 0) then
begin
CreditUse := GetPayment;
if not ShowCredit(CreditUse, True) then
begin
if CreditUse < GetPayment then
begin
pgReceive.ActivePage := tbMultiple;
pgReceiveChange(pgReceive);
cmbPayType1.LookUpValue := cmbPaymentType.LookUpValue;
EditValue1.Text := MyFloatToStr(CreditUse);
end
else
cmbPaymentType.LookUpValue := '';
Exit;
end;
end else if (MyPayType = PAYMENT_TYPE_CREDIT) and (GetPayment < 0) then
begin
if MyIDCliente = 1 then
begin
MsgBox(MSG_CRT_NO_CUSTUMER, vbCritical + vbOkOnly);
cmbPaymentType.LookUpValue := '';
end;
end;
if (MyPayType in [PAYMENT_TYPE_CARD, PAYMENT_TYPE_CHECK, PAYMENT_TYPE_OTHER, PAYMENT_TYPE_STOREACCOUNT]) then
begin
pnlDelayPayments.Visible := DM.fSystem.SrvParam[PARAM_DISPLAY_PRE_DATADO];
pnlShowAuthorization.Visible := (MyPayType in [PAYMENT_TYPE_CARD]);
EditAuthorization.Text := '';
if EditAuthorization.CanFocus then
EditAuthorization.SetFocus;
if pnlDelayPayments.Visible then
btnPartialPayment.Caption := sCadastrar + cmbPaymentType.Text;
end
else
begin
pnlShowAuthorization.Visible := False;
pnlDelayPayments.Visible := False;
end;
// Mostra o panel de Cash se pagamento for do tipo cash
pnlShowCash.Visible := (MyTotCash > 0);
if pnlShowCash.Visible then
if EditReceived.CanFocus then
EditReceived.SetFocus;
//Cancela Pre-Datado se trocar de tipo de pago
CancelPreDatar;
EditAuthorization.Text := '';
//Test Processor
if HasCreditCardProcessor(StrToInt(cmbPaymentType.LookUpValue), MyPayType) then
if CallProcessor(StrToInt(cmbPaymentType.LookUpValue), MyPayType, sAuto, sRout, sLastDigits, GetPayment) then
begin
EditAuthorization.Text := 'A:'+ sAuto + ' R:' + sRout + ' L:' + sLastDigits;
EditAuthorization.Enabled := False;
btCancel.Enabled := False;
tbMultiple.TabVisible := False;
cmbPaymentType.Enabled := False;
btnPartialPayment.Visible := False;
edPayment.Enabled := False;
pnlPayButton.Visible := False;
end
else
cmbPaymentType.LookUpValue := '';
if MyPayType = PAYMENT_TYPE_GIFTCARD then
begin
pnlShowAccount.Visible := True;
edtAccountCard.Clear;
edtAccountCard.SetFocus;
end
else
begin
pnlShowAccount.Visible := False;
lbAccountCredit.Visible := False;
lbAccountCreditValue.Visible := False;
end;
end;
procedure TPreSaleReceive.spDep30Click(Sender: TObject);
begin
EditDepositDate.Text := DateToStr(Int(EditReceiveDate.Date) +
MyStrToInt(RightStr(TSpeedButton(Sender).Caption, 1)));
end;
procedure TPreSaleReceive.spPayMasterClick(Sender: TObject);
begin
cmbPaymentType.LookUpValue := IntToStr(PAY_TYPE_MASTER);
cmbPaymentTypeSelectItem(nil);
end;
procedure TPreSaleReceive.spPayAmericanClick(Sender: TObject);
begin
cmbPaymentType.LookUpValue := IntToStr(PAY_TYPE_AMERICAN);
cmbPaymentTypeSelectItem(nil);
end;
procedure TPreSaleReceive.AtuDepositState(PaymentTypeID : Integer);
begin
// Desabilita tudo
spDep30.Down := False;
spDep60.Down := False;
spDep90.Down := False;
{
spDep30.Visible := False;
spDep60.Visible := False;
spDep90.Visible := False;
lblPreDate.Visible := False;
}
spDep30.Visible := cbPaymentPlace.ItemIndex in [PAYMENT_PLACE_OUTROS];
spDep60.Visible := cbPaymentPlace.ItemIndex in [PAYMENT_PLACE_OUTROS];
spDep90.Visible := cbPaymentPlace.ItemIndex in [PAYMENT_PLACE_OUTROS];
lblPreDate.Visible := cbPaymentPlace.ItemIndex in [PAYMENT_PLACE_OUTROS];
with spquPayTypeMin do
begin
if Active then
Close;
Parameters.ParambyName('@IDMeioPag').Value := PaymentTypeID;
Open;
First;
while not Eof do
begin
if (spquPayTypeMinDifDay.AsInteger > 0) and
(MyTotInvoice >= spquPayTypeMinTotalSale.AsFloat) then
begin
if not spDep30.Visible then
begin
spDep30.Caption := '+&' + Trim(spquPayTypeMinDifDay.AsString);
spDep30.Hint := sSetDateTo + DateToStr(Int(EditReceiveDate.Date) + spquPayTypeMinDifDay.AsInteger);
spDep30.Visible := True;
end
else if not spDep60.Visible then
begin
spDep60.Caption := '+&' + Trim(spquPayTypeMinDifDay.AsString);
spDep60.Hint := sSetDateTo + DateToStr(Int(EditReceiveDate.Date) + spquPayTypeMinDifDay.AsInteger);
spDep60.Visible := True;
end
else if not spDep90.Visible then
begin
spDep90.Caption := '+&' + Trim(spquPayTypeMinDifDay.AsString);
spDep90.Hint := sSetDateTo + DateToStr(Int(EditReceiveDate.Date) + spquPayTypeMinDifDay.AsInteger);
spDep90.Visible := True;
end;
end;
Next;
end;
Close;
// testa se mostra o panel de deposit date
pnlDepositDate.Visible := spDep30.Visible;
lblPreDate.Visible := (not spDep30.Visible) and (not Password.HasFuncRight(17));
if lblPreDate.Visible then
begin
EditDepositDate.Color := clSilver;
EditDepositDate.ReadOnly := True;
end
else
begin
EditDepositDate.Color := clWhite;
EditDepositDate.ReadOnly := False;
end;
end;
end;
procedure TPreSaleReceive.PaintPanel(PanelTag : Integer; Color : Integer);
begin
case PanelTag of
1: pnlPayTitle.Color := Color;
2: pnlDateTitle.Color := Color;
end;
end;
procedure TPreSaleReceive.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
ClosePaySugg;
end;
procedure TPreSaleReceive.EditReceivedChange(Sender: TObject);
var
Code: Integer;
Value: Real;
begin
// Muda o change automatico
if Trim(EditReceived.Text) = '' then
EditChange.Text := FloatToStrF(0, ffCurrency, 20, 2);
Value := MyStrToMoney(Trim(EditReceived.Text));
if pgReceive.ActivePage = tbSingle then
begin
EditChange.Text := FloatToStrF(Value-GetPayment, ffCurrency, 20, 2);
FPaymentChange := Value - GetPayment;
end
else
begin
EditChange.Text := FloatToStrF(Value-MyTotCash, ffCurrency, 20, 2);
FPaymentChange := Value-GetPayment;
end;
end;
procedure TPreSaleReceive.SelecionaParcela(Sender: TObject);
var
i, j : integer;
MyPanel : TPanel;
begin
// Numero de Parcelas
nParcela := TSpeedButton(Sender).Tag;
// Seleciona as parcelas que vao aparecer
with pnlMultiParcela do
begin
for i := 0 to (ControlCount - 1) do
begin
if not (Controls[i] is TPanel) then
Continue;
// Mostra as parcelas dependendo do numero selecionado
Controls[i].Visible := (Controls[i].Tag <= TSpeedButton(Sender).Tag);
// Apaga todos os valores dos campos
MyPanel := TPanel(Controls[i]);
try
IsOnRecalc := True;
for j := 0 to (MyPanel.ControlCount - 1) do
begin
if MyPanel.Controls[j] is TSuperComboADO then
begin
TSuperComboADO(MyPanel.Controls[j]).LookUpValue := '';
TSuperComboADO(MyPanel.Controls[j]).OnSelectItem(MyPanel.Controls[j]);
end
else if MyPanel.Controls[j] is TEdit then
TEdit(MyPanel.Controls[j]).Text := ''
else if MyPanel.Controls[j] is TDateBox then
TDateBox(MyPanel.Controls[j]).Date := Int(EditReceiveDate.Date)
else if MyPanel.Controls[j] is TPanel then
TPanel(MyPanel.Controls[j]).Visible := False;
end;
finally
IsOnRecalc := False;
end;
end;
end;
RecalcTotals(nil);
if FIDBonnus <> -1 then
begin
cmbPayType1.LookUpValue := IntToStr(FIDBonnus);
cmbPayType1SelectItem(cmbPayType1);
EditValue1.Text := FormatFloat('#,##0.00', FBonnusBuck);
end;
end;
function TPreSaleReceive.PriorPaymentsSelected(ALastPayment: Integer): Boolean;
var
I : Integer;
cmbPayType: TSuperComboADO;
begin
Result := True;
for I := 1 to ALastPayment do
begin
cmbPayType := TSuperComboADO(FindComponent('cmbPayType' + IntToStr(I)));
if cmbPayType.LookUpValue = '' then
begin
Result := False;
Break;
end;
end;
end;
function TPreSaleReceive.PaymentIsLast(ALastPayment: Integer): Boolean;
var
cmbPayType: TSuperComboADO;
begin
if ALastPayment = 5 then
Result := True
else
begin
cmbPayType := TSuperComboADO(FindComponent('cmbPayType' + IntToStr(ALastPayment + 1)));
Result := not TWinControl(cmbPayType.Parent).Visible;
end;
end;
procedure TPreSaleReceive.DisablePriorPayments(ALastToDisable: Integer);
var
I: Integer;
cmbPayType: TSuperComboADO;
lblAuto, lblDep: TLabel;
EditAuto, EditValue: TEdit;
cbPayPlace: TComboBox;
pnlAccount: TPanel;
EditDep: TDateBox;
begin
for I := 1 to ALastToDisable do
begin
cmbPayType := TSuperComboADO(FindComponent('cmbPayType' + IntToStr(I)));
lblAuto := TLabel(FindComponent('lblAuto' + IntToStr(I)));
EditAuto := TEdit(FindComponent('EditAuto' + IntToStr(I)));
pnlAccount := TPanel(FindComponent('pnlAccount' + IntToStr(I)));
EditDep := TDateBox(FindComponent('EditDep' + IntToStr(I)));
lblDep := TLabel(FindComponent('lblDep' + IntToStr(I)));
cbPayPlace := TComboBox(FindComponent('cbPayPlace' + IntToStr(I)));
EditValue := TEdit(FindComponent('EditValue' + IntToStr(I)));
EditAuto.Enabled := False;
btCancel.Enabled := False;
tbSingle.TabVisible := False;
cmbPayType.Enabled := False;
EditValue.Enabled := False;
pnlAccount.Visible := False;
end;
pnlMultiButtons.Visible := False;
end;
function TPresaleReceive.PriorPaymetValues(ALastPayment: Integer): Currency;
var
MyEditValue: TEdit;
I: Integer;
begin
Result := 0;
for I := 1 to ALastPayment - 1 do
begin
MyEditValue := TEdit(Self.FindComponent('EditValue' + Trim(IntToStr(I))));
Result := MyStrToCurrency(MyEditValue.text);
end;
end;
// Encapsula o SelectItem dos 5 TSuperComboADO de Tipo de Pagamento
// Do tab Multiple
procedure TPreSaleReceive.cmbPayTypeSelectItem(Sender: TObject);
var
iPayType : Integer;
cmbPayType: TSuperComboADO;
lblAuto, lblDep : TLabel;
pnlAccount : TPanel;
EditAuto, EditValue, edtGiftCard : TEdit;
cbPayPlace : TComboBox;
EditDep: TDateBox;
CreditUse : Double;
bProcessor: Boolean;
sAuto, sRout: String;
sLastDigits: String;
fAmount : Currency;
fExpDate : TDateTime;
begin
cmbPayType := TSuperComboADO(Sender);
if cmbPayType.LookUpValue = '' then
Exit;
if MyIsLayaway then
if MyStrToMoney(edPayment.Text) = 0 then
begin
MsgBox(MSG_CRT_NO_PAYMENT_ZERO, vbCritical);
cmbPayType.LookUpValue := '';
Exit;
end;
if (not PriorPaymentsSelected(cmbPayType.Tag)) then
begin
MsgBox('All prior payment types must be selected in order to complete this operation', vbCritical);
cmbPayType.LookUpValue := '';
Exit;
end;
lblAuto := TLabel(FindComponent('lblAuto' + IntToStr(cmbPayType.Tag)));
EditAuto := TEdit(FindComponent('EditAuto' + IntToStr(cmbPayType.Tag)));
EditDep := TDateBox(FindComponent('EditDep' + IntToStr(cmbPayType.Tag)));
lblDep := TLabel(FindComponent('lblDep' + IntToStr(cmbPayType.Tag)));
cbPayPlace := TComboBox(FindComponent('cbPayPlace' + IntToStr(cmbPayType.Tag)));
EditValue := TEdit(FindComponent('EditValue' + IntToStr(cmbPayType.Tag)));
pnlAccount := TPanel(FindComponent('pnlAccount' + IntToStr(cmbPayType.Tag)));
edtGiftCard := TEdit(FindComponent('edtAccount' + IntToStr(cmbPayType.Tag)));
if not TipoPagamentoJaSelecionado(PAYMENT_TYPE_CREDIT, -1, False) then
ClearCredit;
iPayType := DM.fPOS.GetPayType(cmbPayType.LookUpValue);
if iPayType <> PAYMENT_TYPE_CREDIT then
if PagamentoJaSelecionado(iPayType, cmbPayType.LookUpValue, cmbPayType.Tag, True) then
begin
cmbPayType.LookUpValue := '';
cmbPayType.Clear;
Exit;
end;
if (iPayType = PAYMENT_TYPE_CREDIT) and (MyStrToMoney(EditValue.Text) >= 0) then
begin
CreditUse := MyStrToMoney(EditValue.Text);
ShowCredit(CreditUse, False);
if CreditUse < MyStrToMoney(EditValue.Text) then
EditValue.Text := MyFloatToStr(CreditUse);
if CreditUse = 0 then
begin
cmbPayType.LookUpValue := '';
cmbPayType.Clear;
Exit;
end;
end else if (iPayType = PAYMENT_TYPE_CREDIT) and (MyStrToMoney(EditValue.Text) < 0) then
begin
if MyIDCliente = 1 then
begin
MsgBox(MSG_CRT_NO_CUSTUMER, vbCritical + vbOkOnly);
cmbPayType.LookUpValue := '';
cmbPayType.Clear;
Exit;
end;
end;
if ((iPayType = PAYMENT_TYPE_GIFTCARD) and (MyStrToMoney(EditValue.Text) >= 0)) and
(edtGiftCard.Text <> '') then
begin
if not GetAccountCredit(edtGiftCard.Text, fAmount, fExpDate) then
MsgBox(Format(MSG_CRT_NO_GIFT_ACCOUNT, [edtGiftCard.Text]), vbInformation + vbOkOnly);
if fAmount = 0 then
MsgBox(Format(MSG_CRT_GIFT_ACCOUNT_ZERO, [edtGiftCard.Text]), vbInformation + vbOkOnly);
if fExpDate < Trunc(Now) then
MsgBox(Format(MSG_CRT_GIFT_EXPIRED,[edtAccountCard.Text]), vbOKOnly + vbCritical);
if fAmount < MyStrToMoney(EditValue.Text) then
EditValue.Text := MyFloatToStr(fAmount);
end;
lblAuto.Visible := (iPayType in [PAYMENT_TYPE_CARD]);
EditAuto.Visible := lblAuto.Visible;
pnlAccount.Visible := (iPayType in [PAYMENT_TYPE_GIFTCARD]);
EditDep.Visible := (not (iPayType in [PAYMENT_TYPE_CASH, PAYMENT_TYPE_BONUSBUCK])) or (cbPayPlace.ItemIndex in [PAYMENT_PLACE_OUTROS]);
lblDep.Visible := EditDep.Visible;
RecalcTotals(EditValue);
//Test Processor
if HasCreditCardProcessor(StrToInt(cmbPayType.LookUpValue), iPayType) then
begin
if PaymentIsLast(cmbPayType.Tag) then
begin
if ((PriorPaymetValues(cmbPayType.Tag) + MyStrToCurrency(EditValue.Text)) < MyTotInvoice) then
begin
MsgBox('The last payment must complete the amount.', vbCritical);
cmbPayType.LookUpValue := '';
Exit;
end;
end;
if CallProcessor(StrToInt(cmbPayType.LookUpValue), iPayType, sAuto, sRout, sLastDigits, MyStrToCurrency(EditValue.Text)) then
begin
EditAuto.Text := 'A:'+ sAuto + ' R:' + sRout + ' L:' + sLastDigits;
DisablePriorPayments(cmbPayType.Tag);
if MyIsLayaway then
edPayment.Enabled := False;
end
else
cmbPayType.LookUpValue := '';
end;
end;
procedure TPreSaleReceive.cmbPayType1SelectItem(Sender: TObject);
var
iPayType : Integer;
begin
cmbPayTypeSelectItem(Sender);
iPayType := DM.fPOS.GetPayType(cmbPayType1.LookUpValue);
btnPartialPayment2.Visible := (not HasCreditCardProcessor(StrToIntDef(cmbPayType1.LookUpValue, 0), iPayType)) and (DM.fSystem.SrvParam[PARAM_DISPLAY_PRE_DATADO] AND (iPayType in [PAYMENT_TYPE_CARD, PAYMENT_TYPE_CHECK, PAYMENT_TYPE_OTHER, PAYMENT_TYPE_STOREACCOUNT]));
//Cancela pre-datado caso tenha
CancelPreDatar;
end;
procedure TPreSaleReceive.cmbPayType2SelectItem(Sender: TObject);
begin
cmbPayTypeSelectItem(Sender);
end;
procedure TPreSaleReceive.cmbPayType3SelectItem(Sender: TObject);
begin
cmbPayTypeSelectItem(Sender);
end;
procedure TPreSaleReceive.cmbPayType4SelectItem(Sender: TObject);
begin
cmbPayTypeSelectItem(Sender);
end;
procedure TPreSaleReceive.cmbPayType5SelectItem(Sender: TObject);
begin
cmbPayTypeSelectItem(Sender);
end;
procedure TPreSaleReceive.pgReceiveChange(Sender: TObject);
begin
// Ajusta qual modo vai aparecer
case pgReceive.ActivePage.TabIndex of
0: StartSingle;
1: StartMultiple;
end;
//Cancela Pre Datado Caso tenha
CancelPreDatar;
end;
procedure TPreSaleReceive.StartSingle;
begin
pgReceive.ActivePage := tbSingle;
spDep30.Down := False;
spDep60.Down := False;
spDep90.Down := False;
cmbPaymentType.LookUpValue := '';
cmbPaymentTypeSelectItem(nil);
EditDepositDate.Date := Int(EditReceiveDate.Date);
// Testa se vendedor fez algum Deposit Date pre setado
if ( MyPaymentTypeID > 0 ) then
begin
// Seleciona a forma de pagamento escolhida pelo vendedor
cmbPaymentType.LookUpValue := IntToStr(MyPaymentTypeID);
cmbPaymentTypeSelectItem(nil);
EditDepositDate.Date := MyDepositDate;
MsgBox(MSG_INF_INVOICE_HAS_SETUP, vbOKOnly + vbInformation);
end;
if not IsLayawayToClose then
begin
if pnlPaymentPlace.Visible then
begin
if cbPaymentPlace.CanFocus then
cbPaymentPlace.SetFocus;
end
else if cmbPaymentType.CanFocus then
cmbPaymentType.SetFocus;
end;
RefreshPaySugg;
end;
procedure TPreSaleReceive.StartMultiple;
begin
pgReceive.ActivePage := tbMultiple;
IsOnRecalc := False;
pnlShowCash.Visible := False;
btMulti2.Down := True;
SelecionaParcela(btMulti2);
end;
procedure TPreSaleReceive.RecalcTotals(Sender : TObject);
var
i : integer;
SubTotal : Double;
MyEditValue : TEdit;
MycmbPayType : TSuperComboADO;
fAmount : Currency;
begin
// Recalcula os totais para que sempre sobre a divisao do numero de parcelas
if IsOnRecalc then Exit;
if MyIsLayaway then
fAmount := MyStrToMoney(edPayment.Text)
else
fAmount := MyTotInvoice;
MyTotCash := 0;
SubTotal := 0;
// Desabilita o Loop do change to text do controle
IsOnRecalc := True;
with pnlMultiParcela do
begin
for i := 0 to (ControlCount - 1) do
begin
if not (Controls[i] is TPanel) then
Continue;
if not Controls[i].Visible then
Continue;
MyEditValue := TEdit(Self.FindComponent('EditValue' + Trim(IntToStr(Controls[i].Tag))));
MycmbPayType := TSuperComboADO(Self.FindComponent('cmbPayType' + Trim(IntToStr(Controls[i].Tag))));
if Sender = nil then
begin
// Entra quando for todas as parcelas
MyEditValue.Text := MyFloatToStr(MyRound(fAmount/nParcela, 2));
end
else
begin
// Entra quando estiver editando um field
if Controls[i].Tag > TSpeedButton(Sender).Tag then
begin
// Calcula dividido pelo resto dos outros campos
MyEditValue.Text := MyFloatToStr(MyRound((fAmount-SubTotal)/(nParcela-TSpeedButton(Sender).Tag), 2));
if MyStrToInt(MycmbPayType.LookUpValue) = 1 then
MyTotCash := MyTotCash + MyStrToMoney(MyEditValue.Text);
end
else
begin
SubTotal := SubTotal + MyStrToMoney(MyEditValue.Text);
if MyStrToInt(MycmbPayType.LookUpValue) = 1 then
MyTotCash := MyTotCash + MyStrToMoney(MyEditValue.Text);
end;
end;
end;
end;
if (MyTotCash > 0) then
begin
pnlShowCash.Visible := True;
EditTotalCash.Text := FloatToStrF(MyTotCash, ffCurrency, 20, 2);
EditReceived.Text := FormatFloat('###0.00', MyTotCash);
EditChange.Text := FloatToStrF(0, ffCurrency, 20, 2);
end
else
pnlShowCash.Visible := False;
IsOnRecalc := False;
end;
procedure TPreSaleReceive.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Shift = [ssAlt] then
begin
if UpperCase(Chr(Key)) = 'S' then
StartSingle
else if UpperCase(Chr(Key)) = 'M' then
StartMultiple;
end;
end;
function TPreSaleReceive.ValidateMultiple(IsSaving : Boolean) : Boolean;
function GetAuthorization(sAuthorization: String): String;
begin
if sAuthorization = '' Then
Result := Trim(EditAuto1.Text)
else
Result := sAuthorization;
end;
var
MyEditValue : TEdit;
MycmbPayType : TSuperComboADO;
MyEditAuto : TEdit;
MyEditDep : TDateBox;
MyEditGift : TEdit;
i, j : integer;
Authorization : String;
ExprireDate : TDateTime;
MycbPayPlace : TComboBox;
sCustomerDoc : String;
fAmount : Currency;
fExpDate : TDateTime;
begin
// Valida multiplas parcelas
Result := False;
Authorization := '';
sCustomerDoc := '';
with pnlMultiParcela do
begin
for i := 0 to (ControlCount - 1) do
begin
if not (Controls[i] is TPanel) then Continue;
if not Controls[i].Visible then Continue;
MyEditValue := TEdit(Self.FindComponent('EditValue' + Trim(IntToStr(Controls[i].Tag))));
MycmbPayType := TSuperComboADO(Self.FindComponent('cmbPayType' + Trim(IntToStr(Controls[i].Tag))));
MyEditAuto := TEdit(Self.FindComponent('EditAuto' + Trim(IntToStr(Controls[i].Tag))));
MyEditDep := TDateBox(Self.FindComponent('EditDep' + Trim(IntToStr(Controls[i].Tag))));
MycbPayPlace := TComboBox(Self.FindComponent('cbPayPlace' + Trim(IntToStr(Controls[i].Tag))));
MyEditGift := TEdit(Self.FindComponent('edtAccount' + Trim(IntToStr(Controls[i].Tag))));
sCustomerDoc := MyEditGift.Text;
if IsSaving then
begin
if MyStrToInt(MycmbPayType.LookUpValue) = 1 then
//if MyStrToInt(cmbPaymentType.LookUpValue) = 1 then ????? Isso num tá erado ?
ExprireDate := EditReceiveDate.Date
else
ExprireDate := MyEditDep.Date;
if MyEditAuto.Visible then
Authorization := MyEditAuto.Text
else
Authorization := '';
if (DM.fPos.GetPayType(MycmbPayType.LookUpValue) = PAYMENT_TYPE_CREDIT) and
(MyStrToMoney(MyEditValue.Text) > 0) then
FrmCreditPay.DiscountCredit(MyStrToMoney(MyEditValue.Text));
If fHasDeposit then
begin
for j := 0 to FrmPayPartial.tvPartialPay.Items.Count-1 do
begin
DM.fPOS.AddPayment(MyIDPreSale,
DM.fStore.ID,
DM.fUser.ID,
MyIDCliente,
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).IDPaymentType,
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).IDCashRegMov,
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).PreSaleDate,
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).ExpireDate,
IntToStr(i+1)+'/'+IntToStr(ControlCount-3) + ' - ' +IntToStr(j+1)+'/'+IntToStr(FrmPayPartial.tvPartialPay.Items.Count),
GetAuthorization(TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).Authorization),
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).Valor,
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).NumeroDoc,
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).DocCliente,
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).NomeCliente,
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).Telefone,
MyStrToInt(TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).Banco),
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).OBS,
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).PaymentPlace,
True); // Sempre que o pagamento for cadastrado no formulário pre-datado
// Ele será pre-datatado
//PollDisplay
DM.PollDisplayAddPayment(TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).IDPaymentType,
MycmbPayType.Text,
TPartialPay(FrmPayPartial.tvPartialPay.Items[J].Data).Valor);
end;
//Depois que efetuar o Pre-Datado tenho que limpar os valores
CancelPreDatar;
end
else
begin
DM.fPOS.AddPayment(MyIDPreSale,
DM.fStore.ID,
DM.fUser.ID,
MyIDCliente,
MyStrToInt(MycmbPayType.LookUpValue),
MyIDCashRegMov,
EditReceiveDate.Date,
ExprireDate,
IntToStr(i+1)+'/'+IntToStr(ControlCount-3),
Authorization,
MyStrToMoney(MyEditValue.Text),
'', sCustomerDoc, '', '', 0, '',
MycbPayPlace.ItemIndex,
False);
//PollDisplay
DM.PollDisplayAddPayment(MyStrToInt(MycmbPayType.LookUpValue),
MycmbPayType.Text,
MyStrToMoney(MyEditValue.Text));
end;
Continue; // Passa para o proximo campo
end;
//Testa PaymentPlace
if MycbPayPlace.Visible then
if MycbPayPlace.ItemIndex = PAYMENT_PLACE_EMPTY then
begin
MsgBox(MSG_INF_CHOOSE_PAYPLACE, vbInformation + vbOkOnly);
MycbPayPlace.SetFocus;
Exit;
end;
// Testa se authorization e valida
if MycmbPayType.LookUpValue = '' then
begin
MsgBox(MSG_CRT_NO_PAYMENT_TYPE, vbOKOnly + vbInformation);
if MyEditAuto.CanFocus then
MyEditAuto.SetFocus;
Exit;
end;
// Testa se valor e branco
if MyStrToMoney(MyEditValue.Text) = 0 then
begin
MsgBox(MSG_CRT_NO_AMOUNT, vbOKOnly + vbInformation);
if MyEditValue.CanFocus then
MyEditValue.SetFocus;
Exit;
end;
// Testa se authorization e valida
if MyEditAuto.Visible and (MyEditAuto.Text = '') then
begin
MsgBox(MSG_CRT_NO_AUTHORIZANUMBER, vbOKOnly + vbInformation);
if MyEditAuto.CanFocus then
MyEditAuto.SetFocus;
Exit;
end;
// Teste de Invoice com Special Price com Payment Type diferente de Cash
if (MyquPreSaleInfo.FieldByName('MediaID').AsInteger = MEDIA_TYPE_GUIDE) and
MyquPreSaleValue.FieldByName('TaxIsent').AsBoolean and
(MyStrToInt(MycmbPayType.LookUpValue) <> PAY_TYPE_CASH) then
begin
if Password.HasFuncRight(18) then
begin
if MsgBox(MSG_QST_INVOICE_ONLY_CASH, vbYesNo + vbQuestion) = vbNo then
Exit;
end
else
begin
if MycmbPayType.CanFocus then
MycmbPayType.SetFocus;
MsgBox(MSG_INF_INVOICE_REC_ONLY_CASH, vbOKOnly + vbInformation);
Exit;
end;
end;
if (DM.fPos.GetPayType(MycmbPayType.LookUpValue) = PAYMENT_TYPE_GIFTCARD) then
begin
if not GetAccountCredit(MyEditGift.Text, fAmount, fExpDate) then
begin
MsgBox(Format(MSG_CRT_NO_GIFT_ACCOUNT, [MyEditGift.Text]), vbInformation + vbOkOnly);
Exit;
end;
if fAmount <= 0 then
begin
MsgBox(Format(MSG_CRT_GIFT_ACCOUNT_ZERO, [MyEditGift.Text]), vbInformation + vbOkOnly);
MyEditValue.SetFocus;
Exit;
end;
if fExpDate < Trunc(Now) then
begin
MsgBox(Format(MSG_CRT_GIFT_EXPIRED,[edtAccountCard.Text]), vbOKOnly + vbCritical);
Exit;
end;
if fAmount < MyStrToMoney(MyEditValue.Text) then
begin
MsgBox(Format(MSG_CRT_NOT_GIFT_ACCOUN_BALANCE,[MyEditGift.Text, fAmount]), vbOKOnly + vbCritical);
MyEditValue.SetFocus;
Exit;
end;
end;
// teste de data valida
if MyEditDep.visible and not TestDate(MyEditDep.Text) then
begin
if MyEditDep.Visible then
MyEditDep.SetFocus;
MsgBox(MSG_CRT_NO_VALID_DATE, vbOKOnly + vbInformation);
Exit;
end;
//Testa se tem boleto para imprimir
if (not fPrintBoleto) and (DM.fSystem.SrvParam[PARAM_TAX_IN_COSTPRICE]) and (MyStrToMoney(MyEditValue.Text) > 0) then
fPrintBoleto := (MycmbPayType.GetFieldByName('PrintBankBillet') <> 0);
// Teste de pre date valido
// testa valor minimo para pagamento em cada tipo
if (MyEditDep.Visible) and (MyTotInvoice > 0) then
with spTestpayType do
begin
Parameters.ParambyName('@IDMeioPag').Value := MyStrToInt(MycmbPayType.LookUpValue);
//#Rod - Round
Parameters.ParambyName('@DifDay').Value := Int(MyEditDep.Date-Int(EditReceiveDate.Date));
Parameters.ParambyName('@Value').Value := MyTotInvoice;
ExecProc;
case Parameters.ParambyName('RETURN_VALUE').Value of
1: begin
if Password.HasFuncRight(17) then
begin
if MsgBox(MSG_QST_AMOUN_NOT_REACH_MIN, vbYesNo + vbQuestion) = vbNo then
begin
MyEditValue.SetFocus;
Exit;
end;
end
else
begin
MyEditDep.SetFocus;
MsgBox(MSG_INF_INVOICE_NOT_REACH_DATE, vbOKOnly + vbInformation);
Exit;
end;
end;
-1: begin
if Password.HasFuncRIght(17) then
begin
if MsgBox(MSG_QST_PAYTYPE_NOT_ALLOW_DATE, vbYesNo + vbQuestion) = vbNo then
begin
MyEditValue.SetFocus;
Exit;
end;
end
else
begin
MyEditDep.SetFocus;
MsgBox(MSG_INF_PAYTYPE_NOT_THIS_DATE, vbOKOnly + vbInformation);
Exit;
end;
end;
end;
end;
//Verificar se cliente e requerido
if (MycmbPayType.GetFieldByName('RequireCustomer')) and (MyIDCliente <= 1) then
begin
MsgBox(MSG_CRT_NO_CUSTUMER, vbInformation + vbOkOnly);
Result := False;
Exit;
end;
//Validar Store Account Balance
if (DM.fPos.GetPayType(MycmbPayType.LookUpValue) = PAYMENT_TYPE_STOREACCOUNT) then
if not ValidadeStoreAccount(MyStrToMoney(MyEditValue.Text)) then
Exit;
//Validar inadimplencia
if (MyIDCliente > 1) and (not Password.HasFuncRight(90)) then
begin
if fCustDeliquent and MycmbPayType.GetFieldByName('ValidateNonpayer') then
begin
MsgBox(MSG_CRT_CUSTOMER_NOTUSE_PAYMENT, vbInformation + vbOkOnly);
Result := False;
Exit;
end;
end;
end;
end;
Result := True;
end;
procedure TPreSaleReceive.EditReceivedExit(Sender: TObject);
begin
EditReceived.Text := FormatFloat('###0.00', MyStrToMoney(EditReceived.Text));
end;
function TPreSaleReceive.ValidSinglePaymentType : Boolean;
begin
Result := False;
try
// Valida o recebimento single
if cmbPaymentType.LookUpValue = '' then
begin
cmbPaymentType.SetFocus;
MsgBox(MSG_CRT_NO_PAYMENT_TYPE, vbOKOnly + vbCritical);
Exit;
end;
if not TestDate(EditDepositDate.Text) and pnlDepositDate.Visible then
begin
EditDepositdate.SetFocus;
MsgBox(MSG_CRT_NO_VALID_DATE, vbOKOnly + vbCritical);
Exit;
end;
// Testa Layaway
if MyIsLayaway then
if (MyPayment = 0) and edPayment.Visible then
begin
MsgBox(MSG_CRT_NO_PAYMENT_ZERO, vbCritical + vbOkOnly);
if edPayment.CanFocus then
edPayment.SetFocus;
exit;
end;
// Teste de Invoice com Special Price com Payment Type diferente de Cash
if (MyquPreSaleInfo.FieldByName('MediaID').AsInteger = MEDIA_TYPE_GUIDE) and
MyquPreSaleValue.FieldByName('TaxIsent').AsBoolean and
(MyStrToInt(cmbPaymentType.LookUpValue) <> PAY_TYPE_CASH) then
begin
if Password.HasFuncRight(18) then
begin
if MsgBox(MSG_QST_INVOICE_ONLY_CASH, vbYesNo + vbQuestion) = vbNo then
Exit;
end
else
begin
if cmbPaymentType.CanFocus then
cmbPaymentType.SetFocus;
MsgBox(MSG_INF_INVOICE_REC_ONLY_CASH, vbOKOnly + vbInformation);
Exit;
end;
end;
if MyTotInvoice > 0 then
begin
// testa valor minimo para pagamento em cada tipo
with spTestpayType do
begin
Parameters.ParambyName('@IDMeioPag').Value := MyStrToInt(cmbPaymentType.LookUpValue);
Parameters.ParambyName('@DifDay').Value := Int(EditDepositDate.Date-Int(EditReceiveDate.Date));
Parameters.ParambyName('@Value').Value := MyTotInvoice;
ExecProc;
case Parameters.ParambyName('RETURN_VALUE').Value of
1 : begin
if Password.HasFuncRight(17) then
begin
if MsgBox(MSG_QST_AMOUN_NOT_REACH_MIN, vbYesNo + vbQuestion) = vbNo then
Exit;
end
else
begin
if pnlDepositDate.Visible then
EditDepositDate.SetFocus;
MsgBox(MSG_INF_INVOICE_NOT_REACH_DATE, vbOKOnly + vbInformation);
Exit;
end;
end;
-1 : begin
if Password.HasFuncRight(17) then
begin
if MsgBox(MSG_QST_PAYTYPE_NOT_ALLOW_DATE, vbYesNo + vbQuestion) = vbNo then
Exit;
end
else
begin
if pnlDepositDate.Visible then
EditDepositDate.SetFocus;
MsgBox(MSG_INF_PAYTYPE_NOT_THIS_DATE, vbOKOnly + vbInformation);
Exit;
end;
end;
end;
end;
end;
if (DM.fSystem.SrvParam[PARAM_TAX_IN_COSTPRICE]) and (GetPayment > 0) and (not fPrintBoleto) then
fPrintBoleto := (cmbPaymentType.GetFieldByName('PrintBankBillet') <> 0);
if (DM.fPOS.GetPayType(cmbPaymentType.LookUpValue) = PAYMENT_TYPE_STOREACCOUNT) then
if not ValidadeStoreAccount(GetPayment) then
Exit;
if not ValidateCustomer then
Exit;
Result := True;
finally
if not Result then
cmbPaymentType.LookUpValue := '';
end;
end;
procedure TPreSaleReceive.edPaymentChange(Sender: TObject);
var
Code, I : Integer;
Value : Real;
cPayment : Currency;
bVisible : Boolean;
begin
// Muda o change automatico
if Trim(edPayment.Text) = '' then
MyPayment := 0
else
MyPayment := MyStrToMoney(edPayment.Text);
//Val(edPayment.Text, Value, Code);
//if Code = 0 then
// MyPayment := Value;
EditReceived.Text := edPayment.Text;
EditTotalCash.Text := FloatToStrF(MyPayment, ffCurrency, 20, 2);
Try
cPayment := MyStrToMoney(edPayment.Text);
Except
cPayment := 0
end;
cbxCloseLayaway.Visible := ShowCloseLayAway(cPayment + MyLayaway) and (not DM.fSystem.SrvParam[PARAM_INVOICE_SHOW_TAB_PAYMENTS]);
//Cancela Pre-Datado se trocar o valor ha pagar
// Apenas se a mudança não foi gerada pelo OnExit do próprio (Formatação)
if edPayment.Tag = 0 then
CancelPreDatar;
if pgReceive.ActivePage = tbMultiple then
begin
btMulti2.Down := True;
btMulti2.OnClick(btMulti2);
end;
end;
procedure TPreSaleReceive.edPaymentExit(Sender: TObject);
var
MyTotInvoiceCurrency: currency;
begin
if cmbPaymentType.Text = '' then
Exit;
// Formata, fazendo com que o OnChange não seja chamado
// (O Tag é tratado no OnChange)
edPayment.Tag := 1;
try
edPayment.Text := FormatFloat('###0.00', MyPayment);
finally
edPayment.Tag := 0;
end;
if MyPayment = 0 then
begin
MsgBox(MSG_CRT_NO_PAYMENT_ZERO, vbCritical + vbOkOnly);
if edPayment.CanFocus then
edPayment.SetFocus;
exit;
end;
MyTotInvoiceCurrency := MyRound(MyTotInvoice, 2);
if MyPayment > (MyTotInvoiceCurrency - MyLayaway) then
begin
MsgBox(MSG_CRT_NO_VALID_AMOUNT, vbCritical + vbOkOnly);
if edPayment.CanFocus then
edPayment.SetFocus;
Exit;
end;
end;
procedure TPreSaleReceive.spHelpClick(Sender: TObject);
begin
Application.HelpContext(1060);
end;
procedure TPreSaleReceive.edPaymentKeyPress(Sender: TObject;
var Key: Char);
begin
Key := ValidateCurrency(Key);
end;
procedure TPreSaleReceive.EditValue1KeyPress(Sender: TObject;
var Key: Char);
begin
Key := ValidateCurrency(Key);
end;
procedure TPreSaleReceive.FormCreate(Sender: TObject);
begin
inherited;
Case DMGlobal.IDLanguage of
LANG_ENGLISH :
begin
sRefound := '&Refund';
sTotalRef := 'Total Refund :';
sReceive := '&Receive';
sTotalRec := 'Cash Total :';
sSetDateTo := 'Set Date to ';
sPaymentPlaces := 'Store,Out,Other,';
sCadastrar := 'Register ';
sBonusInfo := 'Enter Bonus';
sBonusCodeValue:= 'Code : ';
end;
LANG_PORTUGUESE :
begin
sRefound := '&Reembolso';
sTotalRef := 'Total :';
sReceive := '&Receber';
sTotalRec := 'Total :';
sSetDateTo := 'Colocar data para ';
sPaymentPlaces := 'Loja,Contra-Entrega,Outros,';
sCadastrar := 'Cadastrar ';
sBonusInfo := 'Informar código do bonus';
sBonusCodeValue:= 'Código do bonus : ';
end;
LANG_SPANISH :
begin
sRefound := '&Reembolso';
sTotalRef := 'Total :';
sReceive := '&Reciber';
sTotalRec := 'Total :';
sSetDateTo := 'Colocar fecha para ';
sPaymentPlaces := 'Tienda,Contra-Entrega,Otros,';
sCadastrar := 'Registar ';
sBonusInfo := 'Informar código do bonus';
sBonusCodeValue:= 'Código do bonus : ';
end;
end;
FrmPayPartial := Nil;
FrmCreditPay := nil;
pnlDelayPayments.Visible := DM.fSystem.SrvParam[PARAM_DISPLAY_PRE_DATADO];
SetComboPaymentPlaces(sPaymentPlaces, DM.fSystem.SrvParam[PARAM_DISPLAY_PAYMENT_PLACE]);
fConfirmEst := DM.fSystem.SrvParam[PARAM_CONFIRM_BUDGET];
end;
procedure TPreSaleReceive.FormDestroy(Sender: TObject);
begin
inherited;
if FrmPayPartial <> nil then
FreeAndNil(FrmPayPartial);
if FrmCreditPay <> nil then
FreeAndNil(FrmCreditPay);
end;
procedure TPreSaleReceive.CancelPreDatar;
begin
fHasDeposit := false;
If FrmPayPartial <> nil then
FrmPayPartial.ClearPaymentList;
lbPartialInfo.Caption := '';
lbPartialInfo2.Caption := '';
end;
procedure TPreSaleReceive.btnPartialPaymentClick(Sender: TObject);
var
Amount : Currency;
begin
inherited;
if not ValidadeLocalPayment then
Exit;
if MyIsLayaway then
if MyPayment <> 0 then //Testa o pagamento se nao for zero, para nao adicionar parcelas zeradas
if (MyTotInvoice>0) and (MyStrToMoney(edPayment.Text)<=0) then
Exit;
If FrmPayPartial = nil then
FrmPayPartial := TFrmPayPartial.Create(Self);
if MyIsLayaway then
Amount := MyStrToMoney(edPayment.Text)
else
Amount := MyTotInvoice;
lbPartialInfo.Caption :=
FrmPayPartial.Start(StrToInt(cmbPaymentType.LookUpValue),
MyIDCliente,
MyIDPreSale,
MyIDCashRegMov,
Amount,
EditReceiveDate.Date,
EditAuthorization.Text,
fFormOfPayment,
cbPaymentPlace.ItemIndex);
fHasDeposit := FrmPayPartial.HasDeposit;
end;
procedure TPreSaleReceive.btnPartialPayment2Click(Sender: TObject);
begin
inherited;
if StrToCurr(EditValue1.Text) = 0 then
Exit;
if cbPayPlace1.Visible then
if cbPayPlace1.ItemIndex = PAYMENT_PLACE_EMPTY then
begin
MsgBox(MSG_INF_CHOOSE_PAYPLACE, vbInformation + vbOkOnly);
cbPayPlace1.SetFocus;
Exit;
end;
If FrmPayPartial = nil then
FrmPayPartial := TFrmPayPartial.Create(Self);
lbPartialInfo2.Caption :=
FrmPayPartial.Start(StrToInt(cmbPayType1.LookUpValue),
MyIDCliente,
MyIDPreSale,
MyIDCashRegMov,
MyStrToMoney(EditValue1.Text),
editReceiveDate.Date,
EditAuto1.Text,
fFormOfPayment,
cbPayPlace1.ItemIndex);
fHasDeposit := FrmPayPartial.HasDeposit;
end;
function TPreSaleReceive.DeletePayment: Boolean;
var
I : Integer;
begin
DM.FTraceControl.TraceIn('TPreSaleReceive.DeletePayment');
Result := True;
try
If (FrmPayPartial <> nil) Then
if (FrmPayPartial.tvPartialPay.Items.Count > 0) Then
for I := 0 to FrmPayPartial.tvPartialPay.Items.Count - 1 do
if TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).IDCashRegMovClosed = -1 then
with spPreSaleDeleteSingleDelayPayment do
begin
Parameters.ParamByName('@IDLancamento').Value := TPartialPay(FrmPayPartial.tvPartialPay.Items[I].Data).IDLancamento;
Parameters.ParamByName('@IDUser').Value := DM.fUser.ID;
ExecProc;
end;
except
on E: Exception do
DM.FTraceControl.SetException(E.Message, 'TPreSaleReceive');
end;
DM.FTraceControl.TraceOut;
end;
function TPreSaleReceive.ShowCloseLayAway(TotLayAway: Currency): Boolean;
begin
Result := MyRound(MyTotInvoice-TotLayAway,2)=0;
if DM.fSystem.SrvParam[PARAM_CONFIRM_DELIVERY_ON_SALE] then
Result := Result and MyquPreSaleInfo.FieldByName('DeliverConfirmation').AsBoolean;
end;
procedure TPreSaleReceive.SetComboPaymentPlaces(sComboPaymentPlaces: String; bVisible: Boolean);
var
I, J : Integer;
MyPanel : TPanel;
AssociatedLabel : TLabel;
begin
// Passa a lista de locais de pagamento para todos os respectivos ComboBox
cbPaymentPlace.Items.CommaText := sComboPaymentPlaces;
cbPaymentPlace.ItemIndex := PAYMENT_PLACE_LOJA;
pnlPaymentPlace.Visible := bVisible;
with pnlMultiParcela do
for I := 0 to (ControlCount - 1) do
begin
if not (Controls[I] is TPanel) then Continue;
MyPanel := TPanel(Controls[I]);
for J := 0 to (MyPanel.ControlCount - 1) do
if MyPanel.Controls[J] is TComboBox then
begin
TComboBox(MyPanel.Controls[J]).Visible := bVisible;
TComboBox(MyPanel.Controls[J]).Items.CommaText := sComboPaymentPlaces;
TComboBox(MyPanel.Controls[J]).ItemIndex := PAYMENT_PLACE_EMPTY;
AssociatedLabel := TLabel(Self.FindComponent('lbPayPlace' + Trim(IntToStr(MyPanel.Controls[J].Tag))));
if AssociatedLabel <> nil then
AssociatedLabel.Visible := bVisible;
end;
end;
end;
function TPreSaleReceive.ValidateReceive : Boolean;
var
fAmount : Currency;
fExpDate : TDateTime;
MyTotInvoiceCurrency: currency;
begin
DM.FTraceControl.TraceIn('TPreSaleReceive.ValidateReceive');
try
Result := False;
if not ValidadeLocalPayment then
Exit;
MyTotInvoiceCurrency := MyRound(MyTotInvoice, 2);
if MyIsLayaway then
if (DM.fSystem.SrvParam[PARAM_ENTER_LAYAWAY_FULL_AMOUNT]) and
(((MyPayment + MyLayaway) - MyTotInvoiceCurrency ) <> 0) then
begin
MsgBox(MSG_INF_TOTAL_SMALLER_PRE_SALE, vbOKOnly + vbInformation);
Exit;
end;
if not IsLayawayToClose then
begin
if pgReceive.ActivePage = tbSingle then
begin
if not ValidSinglePaymentType then
Exit;
if MyPayType = PAYMENT_TYPE_GIFTCARD then
begin
if not GetAccountCredit(edtAccountCard.Text, fAmount, fExpDate) then
begin
MsgBox(Format(MSG_CRT_NO_GIFT_ACCOUNT, [edtAccountCard.Text]), vbInformation + vbOkOnly);
Exit;
end;
if fAmount <= 0 then
begin
MsgBox(Format(MSG_CRT_GIFT_ACCOUNT_ZERO,[edtAccountCard.Text]), vbOKOnly + vbCritical);
Exit;
end;
if fExpDate < Trunc(Now) then
begin
MsgBox(Format(MSG_CRT_GIFT_EXPIRED,[edtAccountCard.Text]), vbOKOnly + vbCritical);
Exit;
end;
if fAmount < GetPayment then
begin
pgReceive.ActivePage := tbMultiple;
pgReceiveChange(pgReceive);
cmbPayType1.LookUpValue := cmbPaymentType.LookUpValue;
EditValue1.Text := MyFloatToStr(fAmount);
pnlAccount1.Visible := True;
edtAccount1.Text := edtAccountCard.Text;
Exit;
end;
end;
if pnlShowAuthorization.Visible and (EditAuthorization.Text = '') then
begin
EditAuthorization.SetFocus;
MsgBox(MSG_CRT_NO_AUTHORIZANUMBER, vbOKOnly + vbCritical);
Exit;
end;
end
else
begin
// Valida o recebimento Multiple
if not ValidateMultiple(False) then
Exit;
end;
if not TestDate(EditReceiveDate.Text) then
begin
MsgBox(MSG_CRT_INVAL_DATE_RECEIVE, vbCritical + vbOkOnly);
if EditReceiveDate.CanFocus then
EditReceiveDate.SetFocus;
Exit;
end;
// Testa o troco dado
// Teste se Received > Total PreSale
if MyIsLayaway then
begin
if (spPayCash.Down and (MyRound(MyPayment-MyStrToMoney(EditReceived.Text), 2)>0)) then
begin
if EditReceived.CanFocus then
EditReceived.SetFocus;
MsgBox(MSG_INF_TOTAL_SMALLER_PRE_SALE, vbOKOnly + vbInformation);
Exit;
end;
// Payment cannot be zero
if (MyPayment = 0) and edPayment.Visible then
begin
MsgBox(MSG_CRT_NO_PAYMENT_ZERO, vbCritical + vbOkOnly);
if edPayment.CanFocus then
edPayment.SetFocus;
exit;
end;
MyTotInvoiceCurrency := MyRound(MyTotInvoice, 2);
// Invalid Payment
if MyPayment > (MyTotInvoiceCurrency - MyLayaway) then
begin
MsgBox(MSG_CRT_NO_VALID_AMOUNT, vbCritical + vbOkOnly);
if edPayment.CanFocus then
edPayment.SetFocus;
Exit;
end;
end
else
begin
if ((MyTotCash > 0) and (MyRound(MyTotCash-MyStrToMoney(EditReceived.Text), 2)>0)) then
begin
if EditReceived.CanFocus then
EditReceived.SetFocus;
MsgBox(MSG_INF_TOTAL_SMALLER_PRE_SALE, vbOKOnly + vbInformation);
Exit;
end;
end;
end;
except
on E: Exception do
DM.FTraceControl.SaveTrace(DM.fUser.ID, E.Message, 'TPreSaleReceive');
end;
Result := True;
DM.FTraceControl.TraceOut;
end;
function TPreSaleReceive.PagamentoJaSelecionado(Tipo: Integer; IDMeioPag: String; Parcela: Integer;RaiseMessage: Boolean): Boolean;
var
i, j : Integer;
MyPanel: Tpanel;
Combo : TSuperComboADO;
begin
Result := False;
if Tipo = PAYMENT_TYPE_CARD then
Exit;
with pnlMultiParcela do
for i := 0 to (ControlCount - 1) do
begin
if Result then
Break;
if not (Controls[i] is TPanel) then
Continue;
MyPanel := TPanel(Controls[i]);
for j := 0 to (MyPanel.ControlCount - 1) do
if MyPanel.Controls[j] is TSuperComboADO then
begin
Combo := TSuperComboADO(MyPanel.Controls[j]);
if (Combo.LookUpValue <> '') and
(Combo.Tag <> Parcela) and
(Combo.LookUpValue = IDMeioPag) and
(Combo.Tag <= NParcela) Then
begin
if RaiseMessage then
MsgBox(MSG_INF_PAYTYPE_SELECTED, vbCritical);
Result := True;
Break;
end;
end
end;
end;
function TPreSaleReceive.TipoPagamentoJaSelecionado(Tipo: Integer; Parcela: Integer;RaiseMessage: Boolean): Boolean;
var
i, j : Integer;
MyPanel: Tpanel;
Combo : TSuperComboADO;
begin
Result := False;
// Não testa para Cartão de crédito
if Tipo in [PAYMENT_TYPE_CARD, PAYMENT_TYPE_GIFTCARD] then
Exit;
with pnlMultiParcela do
for i := 0 to (ControlCount - 1) do
begin
if Result then
Break;
if not (Controls[i] is TPanel) then
Continue;
MyPanel := TPanel(Controls[i]);
for j := 0 to (MyPanel.ControlCount - 1) do
if MyPanel.Controls[j] is TSuperComboADO then
begin
Combo := TSuperComboADO(MyPanel.Controls[j]);
if (Combo.LookUpValue <> '') and
(Combo.Tag <> Parcela) and
(DM.fPOS.GetPayType(Combo.LookUpValue) = Tipo) and
(Combo.Tag <= NParcela) Then
begin
if RaiseMessage then
MsgBox(MSG_INF_PAYTYPE_SELECTED, vbCritical);
Result := True;
Break;
end;
end
end;
end;
procedure TPreSaleReceive.cbPaymentPlaceSelect(Sender: TObject);
begin
inherited;
AtuDepositState(MyStrToInt(cmbPaymentType.LookUpValue));
end;
// Encapsula o change de cada um dos 5 PayPlaces
// do Tab Multiple
procedure TPreSaleReceive.cbPayPlaceChange(Sender: TObject);
var
iPayType: Integer;
EditDep : TDateBox;
lblDep : TLabel;
cbPayPlace : TComboBox;
cmbPayType : TSuperComboADO;
begin
EditDep := TDateBox(FindComponent('EditDep' + IntToStr(TComponent(Sender).Tag)));
lblDep := TLabel(FindComponent('lblDep' + IntToStr(TComponent(Sender).Tag)));
cbPayPlace := TComboBox(FindComponent('cbPayPlace' + IntToStr(TComponent(Sender).Tag)));
cmbPayType := TSuperComboADO(FindComponent('cmbPayType' + IntToStr(TComponent(Sender).Tag)));
iPayType := DM.fPOS.GetPayType(cmbPayType.LookUpValue);
EditDep.Visible := (iPayType <> PAYMENT_TYPE_CASH) or (cbPayPlace.ItemIndex in [PAYMENT_PLACE_OUTROS]);
lblDep.Visible := EditDep.Visible;
end;
procedure TPreSaleReceive.cbPayPlace1Change(Sender: TObject);
begin
inherited;
cbPayPlaceChange(Sender);
end;
procedure TPreSaleReceive.cbPayPlace2Change(Sender: TObject);
begin
inherited;
cbPayPlaceChange(Sender);
end;
procedure TPreSaleReceive.cbPayPlace3Change(Sender: TObject);
begin
inherited;
cbPayPlaceChange(Sender);
end;
procedure TPreSaleReceive.cbPayPlace4Change(Sender: TObject);
begin
inherited;
cbPayPlaceChange(Sender);
end;
procedure TPreSaleReceive.cbPayPlace5Change(Sender: TObject);
begin
inherited;
cbPayPlaceChange(Sender);
end;
function TPreSaleReceive.ShowCredit(var Amount: Double; Const Verify: Boolean) : Boolean;
var
VerifyAmount : Double;
begin
Result := True;
VerifyAmount := Amount;
if FrmCreditPay = nil then
FrmCreditPay := TFrmCreditPay.Create(Self)
else
FrmCreditPay.UnloadCredit;
// Se necessita verificar confere se o cliente possui crédito antes de abrir
if Verify then
Result := (VerifyAmount <= FrmCreditPay.GetTotalCredit(MyIDCliente, DM.fStore.ID, MyIDPreSale));
if not Result then
begin
MsgBox(MSG_INF_CREDIT_GREATER_INVOICE, vbCritical + vbOKOnly);
Exit;
end;
Result := FrmCreditPay.Start(MyIDCliente, MyIDPreSale, NOW, Amount);
if Result and (Verify and (VerifyAmount > Amount)) then
begin
Result := False;
MsgBox(MSG_INF_CREDIT_SMALLER_TOTAL, vbCritical + vbOKOnly);
end;
end;
procedure TPreSaleReceive.ClearCredit;
begin
if FrmCreditPay <> nil then
FrmCreditPay.UnloadCredit;
end;
procedure TPreSaleReceive.RefreshCustomerCredit;
var
dCredit : Double;
begin
if FrmCreditPay = nil then
FrmCreditPay := TFrmCreditPay.Create(Self);
dCredit := FrmCreditPay.GetTotalCredit(MyIDCliente, DM.fStore.ID, MyIDPreSale);
lblCustomerCreditValue.Caption := ' : ' + MyFloatToStr(dCredit);
lblCustomerCredit.Visible := dCredit > 0;
lblCustomerCreditValue.Visible := lblCustomerCredit.Visible;
end;
function TPreSaleReceive.ValidadeLocalPayment: Boolean;
begin
Result := True;
if pgReceive.ActivePage = tbSingle then
if pnlPaymentPlace.Visible then
if cbPaymentPlace.ItemIndex = PAYMENT_PLACE_EMPTY then
begin
MsgBox(MSG_INF_CHOOSE_PAYPLACE, vbInformation + vbOkOnly);
cbPaymentPlace.SetFocus;
Result := False;
end;
end;
procedure TPreSaleReceive.spPayCheckClick(Sender: TObject);
begin
cmbPaymentType.LookUpValue := IntToStr(PAY_TYPE_CHECK);
cmbPaymentTypeSelectItem(nil);
end;
procedure TPreSaleReceive.PreparePCC(APCCT: TPCCTransaction; AProcessor, AMercantNum : String);
begin
DM.FTraceControl.TraceIn('TPreSaleReceive.PreparePCC');
try
APCCT.Path := DM.fPCCharge.Path;
APCCT.User := DM.fPCCharge.User;
APCCT.TimeOut := DM.fPCCharge.TimeOut;
APCCT.Multi := IntToStr(Byte(DM.fPCCharge.MultTrans));
APCCT.LastValidDate := IntToStr(DM.fPCCharge.LastDate);
APCCT.PrintReceipts := IntToStr(DM.fPCCharge.PrintNum);
APCCT.Processor := AProcessor;
APCCT.Port := DM.fPCCharge.Port;
APCCT.IPAddress := DM.fPCCharge.Server;
APCCT.MerchantNumber := AMercantNum;
APCCT.OnNeedSwipe := nil;
APCCT.AfterSucessfullSwipe := nil;
APCCT.OnNeedTroutD := nil;
//PinPad
APCCT.PinTimeOut := StrToInt(DM.fPinPad.TimeOut);
APCCT.PinEncryptMethod := StrToInt(DM.fPinPad.EncryptMethod);
APCCT.PinDevice := StrToInt(DM.fPinPad.GetDevice);
APCCT.PinBaud := DM.fPinPad.Baud;
APCCT.PinDataBits := DM.fPinPad.DataBits;
APCCT.PinParity := DM.fPinPad.Parity;
APCCT.PinComm := DM.fPinPad.Comm;
except
on E: Exception do
begin
DM.FTraceControl.SaveTrace(DM.fUser.ID, E.Message, 'TPreSaleReceive');
end;
end;
DM.FTraceControl.TraceOut;
end;
function TPreSaleReceive.PCCResult(APCCT: TPCCTransaction) : Boolean;
var
sMsg: String;
begin
DM.FTraceControl.TraceIn('TPreSaleReceive.PCCResult');
Result := false;
sMsg := '';
try
case APCCT.TransactionReturn of
ttrSuccessfull:
begin
Result := True;
sMsg := Format('%S'#13#10#13#10'Auth: %S'#13#10'RefNumber: %S'#13#10'TroutD: %S', [APCCT.PCCResult, APCCT.Auth, APCCT.RefNumber, APCCT.TroutD]);
if APCCT.AVS <> '' then
sMsg := Format(sMsg + #13#10'AVS: %S', [APCCT.AVS]);
if APCCT.CVV2Ver <> '' then
sMsg := Format(sMsg + #13#10'CVV2: %S', [APCCT.CVV2Ver]);
Application.MessageBox(PChar(sMsg), 'Transaction result', MB_OK + MB_ICONINFORMATION);
end;
ttrNotSuccessfull:
begin
sMsg := Format('%S'#13#10#13#10'Reason: %S', [APCCT.PCCResult, APCCT.Auth]);
raise Exception.Create(sMsg);
end;
ttrError:
begin
sMsg := Format('%S'#13#10'Error: %D - %S', [APCCT.PCCResult, APCCT.ErrorCode, APCCT.ErrorDesc]);
raise Exception.Create(sMsg);
end;
ttrException:
begin
sMsg := Format(''#13#10'Error: %S', [APCCT.ErrorDesc]);
raise Exception.Create(sMsg);
end;
end;
except
on E: Exception do
begin
DM.FTraceControl.SaveTrace(DM.fUser.ID, E.Message, 'TPreSaleReceive');
Result := False;
Application.MessageBox(PChar(sMsg), 'Transaction result', MB_OK + MB_ICONINFORMATION);
end;
end;
DM.FTraceControl.TraceOut;
end;
function TPreSaleReceive.DoPCCharge(var AAuth, ATroud, ALastDigits: String;
Processor, MercantNum : String; AAmount: Currency; iPayType:Integer): Boolean;
var
PCCT: TPCCTransaction;
sMsg: String;
frmPCCharge : TfrmPCCharge;
MsgResult : Integer;
iAction : Integer;
begin
DM.FTraceControl.TraceIn('TPreSaleReceive.DoPCCharge');
Result := False;
PCCT := TPCCTransaction.Create(Self);
try
try
PreparePCC(PCCT, Processor, MercantNum);
if iPayType = PAYMENT_TYPE_CARD then
begin
MsgResult := MsgBox('Is the customer card present?_Total to be proccessed: '+FormatCurr('#,##0.00',AAmount), vbYesNoCancel);
if MsgResult = vbCancel then
Exit;
end
else
MsgResult := vbYes;
if (MsgResult = vbYes) then
begin
PCCT.OnNeedSwipe := NeedSwipe;
PCCT.AfterSucessfullSwipe := SucessFullSwipe;
if iPayType = PAYMENT_TYPE_CARD then
PCCT.RetailCreditOrAutorizationCardPresent(MyFormatCur(Abs(AAmount), '.'), IntToStr(MyIDPreSale), '', AAmount < 0)
else
begin
if (AAmount > 0) then
iAction := DEBIT_SALE
else
iAction := DEBIT_RETURN;
PCCT.RetailDebitCardPresent(MyFormatCur(Abs(AAmount), '.'), '0.00', IntToStr(MyIDPreSale), '', iAction);
end;
Result := PCCResult(PCCT);
end
else
begin
frmPCCharge := TfrmPCCharge.Create(Self);
try
Result := frmPCCharge.Start(PCCT, IntToStr(MyIDPreSale), AAmount);
finally
frmPCCharge.Free;
end;
end;
if Result then
begin
AAuth := PCCT.Auth;
ATroud := PCCT.TroutD;
ALastDigits := PCCT.LastDigits;
end;
//Result := PCCResult(PCCT, AAuth, ATroud, ALastDigits);
except
on E: Exception do
begin
DM.FTraceControl.SaveTrace(DM.fUser.ID, E.Message, 'TPreSaleReceive');
Result := False;
end;
end;
finally
PCCT.Free;
end;
DM.FTraceControl.TraceOut;
end;
function TPreSaleReceive.DoPCVoid(var AAuth, ATroud, ALastDigits: String;
Processor, MercantNum : String): Boolean;
var
PCCT: TPCCTransaction;
begin
Result := False;
PCCT := TPCCTransaction.Create(Self);
try
try
PreparePCC(PCCT, Processor, MercantNum);
PCCT.OnNeedTroutD := NeedTroutD;
PCCT.RetailVoidSale;
Result := PCCResult(PCCT);
if Result then
begin
AAuth := PCCT.Auth;
ATroud := PCCT.TroutD;
ALastDigits := PCCT.LastDigits;
end;
except
Result := False;
end;
finally
PCCT.Free;
end;
end;
procedure TPreSaleReceive.NeedSwipe(Sender: TObject;
var SwipedTrack: WideString; var Canceled: Boolean);
var
SC : TFrmPCCSwipeCard;
iIDMeioPag : Integer;
begin
DM.FTraceControl.TraceIn('TPreSaleReceive.NeedSwipe');
SC := TFrmPCCSwipeCard.Create(Self);
try
try
Canceled := not SC.Start(SwipedTrack, iIDMeioPag);
finally
SC.Free;
end;
except
on E: Exception do
begin
DM.FTraceControl.SaveTrace(DM.fUser.ID, E.Message, 'TPreSaleReceive');
end;
end;
DM.FTraceControl.TraceOut;
end;
procedure TPreSaleReceive.SucessFullSwipe(Sender: TObject; const ACardNumber,
ACardMember, ACardExpireDate: WideString);
var
sMsg: String;
begin
// Adicionar neste evento qualquer código que precise ser executado após
// uma tentativa bem sucedida de leitura do cartão
end;
procedure TPreSaleReceive.NeedTroutD(Sender: TObject; var ATrouD, ARefNo,
AAuthCode: WideString; var ACanceled: Boolean);
var
PCV: TfrmPCVoid;
begin
PCV := TfrmPCVoid.Create(Self);
try
ACanceled := not PCV.Start(GetPayment, ATrouD, ARefNo, AAuthCode, nil);
finally
PCV.Free;
end;
end;
function TPreSaleReceive.HasCreditCardProcessor(IDMeioPag: Integer; PayType:Integer): Boolean;
var
fProcessor : String;
fMercantNum : String;
fCardID : String;
iCopies: Integer;
begin
//DM.fPos.GetPayType(cmbPaymentType.LookUpValue)
Result := (PayType in [PAYMENT_TYPE_CARD, PAYMENT_TYPE_DEBIT]) and
(DM.fPCCharge.ProcessorType <> 0);
if Result then
begin
(*
if DM.fPCCharge.ProcessorType = PROCESSOR_PCCHARGE then
begin
DM.fPCCharge.GetProcessor(IDMeioPag, fProcessor, fMercantNum, iCopies, fCardID);
Result := ((Trim(fProcessor)<>'') and (Trim(fMercantNum)<>''));
end
else *) if DM.fPCCharge.ProcessorType = PROCESSOR_MERCURY then
Result := ((Trim(DM.fMRMercury.IpAddress)<>'') and (Trim(DM.fMRMercury.MerchantID)<>''));
if not Result then
begin
if (Trim(fProcessor) = '') then
MsgBox('Invalid "Processor"._Card not charged', vbSuperCritical + vbOkOnly)
else if (Trim(fMercantNum) = '') then
MsgBox('Invalid "Mercant Number"._Card not charged', vbSuperCritical + vbOkOnly);
end;
end;
end;
function TPreSaleReceive.CallProcessor(IDMeioPag : Integer; PayType: Integer;
var AAuth, ATroud, ALastDigits: String; AAmount: Currency): Boolean;
var
TrouD: String;
fProcessor : String;
fMercantNum : String;
fCardID : String;
Authorization : String;
ATransactResult: Boolean;
iCopies: Integer;
begin
DM.FTraceControl.TraceIn('TPreSaleReceive.CallProcessor');
Result := False;
ATransactResult := False;
try
AAuth := '';
ATroud := '';
(*
if DM.fPCCharge.ProcessorType = PROCESSOR_PCCHARGE then
begin
DM.fPCCharge.GetProcessor(IDMeioPag, fProcessor, fMercantNum, iCopies, fCardID);
if (fProcessor <> '') or (fMercantNum <> '') then
ATransactResult := DoPCCharge(Authorization, TrouD, ALastDigits, fProcessor, fMercantNum, AAmount, PayType);
end
else *)
if DM.fPCCharge.ProcessorType = PROCESSOR_MERCURY then
ATransactResult := DoMercury(Authorization, TrouD, ALastDigits, AAmount, PayType);
if not ATransactResult then
raise Exception.Create('Card not charged!!!_' + FErrorMsg)
else
begin
Result := True;
AAuth := Authorization;
ATroud := TrouD;
end;
except
on E: Exception do
begin
Result := False;
DM.FTraceControl.SaveTrace(DM.fUser.ID, E.Message, 'TPreSaleReceive');
MsgBox(E.Message, vbCritical);
end;
end;
DM.FTraceControl.TraceOut;
end;
function TPreSaleReceive.GetAccountCredit(Account: String;
var Amount: Currency; var ExpDate : TDateTime): Boolean;
begin
with quAccountBalance do
begin
Parameters.ParamByName('CardNumber').Value := Account;
try
Open;
Amount := quAccountBalanceAmount.AsCurrency;
if quAccountBalanceExpirationDate.IsNull then
ExpDate := Trunc(Now)
else
ExpDate := Trunc(quAccountBalanceExpirationDate.AsDateTime);
Result := not IsEmpty;
finally
Close;
end;
end;
end;
procedure TPreSaleReceive.RefreshAccountCredit;
var
fAmount : Currency;
fExpDate : TDateTime;
begin
if edtAccountCard.Text <> '' then
begin
lbAccountCredit.Visible := False;
lbAccountCreditValue.Visible := lbAccountCredit.Visible;
if not GetAccountCredit(edtAccountCard.Text, fAmount, fExpDate) then
begin
MsgBox(Format(MSG_CRT_NO_GIFT_ACCOUNT, [edtAccountCard.Text]), vbInformation + vbOkOnly);
Exit;
end;
if fAmount = 0 then
begin
MsgBox(Format(MSG_CRT_GIFT_ACCOUNT_ZERO, [edtAccountCard.Text]), vbInformation + vbOkOnly);
Exit;
end;
if fExpDate < Trunc(Now) then
begin
MsgBox(Format(MSG_CRT_GIFT_EXPIRED,[edtAccountCard.Text]), vbOKOnly + vbCritical);
Exit;
end;
lbAccountCreditValue.Caption := ' : ' + MyFloatToStr(fAmount);
lbAccountCredit.Visible := True;
lbAccountCreditValue.Visible := lbAccountCredit.Visible;
if (fAmount < GetPayment) and (fAmount <> 0) then
begin
pgReceive.ActivePage := tbMultiple;
pgReceiveChange(pgReceive);
cmbPayType1.LookUpValue := cmbPaymentType.LookUpValue;
EditValue1.Text := MyFloatToStr(fAmount);
pnlAccount1.Visible := True;
edtAccount1.Text := edtAccountCard.Text;
lblAuto1.Visible := False;
EditAuto1.Visible := False;
EditAuto1.Text := '';
cmbPayType1.SetFocus;
Exit;
end;
end;
end;
procedure TPreSaleReceive.edtAccountCardExit(Sender: TObject);
begin
inherited;
RefreshAccountCredit;
btOk.Default := True;
end;
procedure TPreSaleReceive.edtAccountCardKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key = #13 then
RefreshAccountCredit;
end;
procedure TPreSaleReceive.edtAccountCardEnter(Sender: TObject);
begin
inherited;
btOk.Default := False;
end;
procedure TPreSaleReceive.ClosePaySugg;
begin
with quUpPayment do
if Active then
Close;
end;
procedure TPreSaleReceive.OpenPaySugg;
begin
with quUpPayment do
if not Active then
begin
Parameters.ParamByName('IDPreSale').Value := MyIDPreSale;
Open;
end;
end;
procedure TPreSaleReceive.RefreshPaySugg;
begin
if fConfirmEst then
begin
ClosePaySugg;
OpenPaySugg;
pnlPaySuggestion.Visible := (not quUpPayment.IsEmpty);
end
else
pnlPaySuggestion.Visible := False;
end;
function TPreSaleReceive.ValidateCustomer: Boolean;
begin
Result := True;
if (cmbPaymentType.LookUpSource.DataSet.FieldByName('RequireCustomer').AsBoolean) and (MyIDCliente <= 1) then
begin
MsgBox(MSG_CRT_NO_CUSTUMER, vbInformation + vbOkOnly);
Result := False;
Exit;
end;
//Validar inadimplencia
if (MyIDCliente > 1) and (not Password.HasFuncRight(90)) then
begin
if fCustDeliquent and cmbPaymentType.GetFieldByName('ValidateNonpayer') then
begin
MsgBox(MSG_CRT_CUSTOMER_NOTUSE_PAYMENT, vbInformation + vbOkOnly);
Result := False;
Exit;
end;
end;
end;
function TPreSaleReceive.DoMercury(var AAuth, ATroud, ALastDigits: String;
AAmount: Currency; iPayType: Integer): Boolean;
var
FMercuryWidget : TCCWidget;
MsgResult : Integer;
begin
DM.FTraceControl.TraceIn('TFrmStoreAccount.DoMercury');
Result := False;
if iPayType = PAYMENT_TYPE_CARD then
FMercuryWidget := getPaymentCard(dm.fPCCharge.ProcessorType, iPayType)
else
FMercuryWidget := getPaymentCard(dm.fPCCharge.ProcessorType, iPayType);
try
if iPayType = PAYMENT_TYPE_CARD then
begin
MsgResult := MsgBox('Is the customer card present?_Total to be proccessed: '+FormatCurr('#,##0.00',AAmount), vbYesNoCancel);
if MsgResult = vbCancel then
Exit;
end
else
MsgResult := vbYes;
// antonio aug 10 2015 - call correct interface to process transaction with card present or not
if ( msgResult = vbYes ) then begin
if ( ipayType = PAYMENT_TYPE_CARD ) then begin
processCardCreditIsPresent(AAmount, fMercuryWidget)
end else begin
processCardDebitIsPresent(AAmount, fMercuryWidget);
end
end else begin
processCardIsNotPresent(AAmount, fMercuryWidget);
end;
finally
FreeAndNil(FMercuryWidget);
end;
DM.FTraceControl.TraceOut;
end;
function TPreSaleReceive.MercuryResult(AmercuryWidget: TCCWidget): Boolean;
var
sMsg: String;
begin
DM.FTraceControl.TraceIn(Self.ClassName + '.MercuryResult');
Result := False;
sMsg := '';
try
case AmercuryWidget.TransactionReturn of
ttrSuccessfull:
begin
Result := True;
sMsg := Format('%S'#13#10'Auth: %S'#13#10'RefNumber: %S'#13#10'RefDataD: %S', [AmercuryWidget.Msg, AmercuryWidget.ResultAuth, AmercuryWidget.ResultRefNo, AmercuryWidget.ResultAcqRefData]);
end;
ttrNotSuccessfull:
begin
sMsg := Format('%S'#13#10'Reason: %S', [AmercuryWidget.Msg, AmercuryWidget.ResultAuth]);
raise Exception.Create(sMsg);
end;
ttrError:
begin
sMsg := Format(#13#10'Error: %S', [AmercuryWidget.Msg]);
raise Exception.Create(sMsg);
end;
ttrException:
begin
sMsg := Format(''#13#10'Error: %S', [AmercuryWidget.Msg + ' ' + AmercuryWidget.ErrorMsg]);
raise Exception.Create(sMsg);
end;
end;
except
FErrorMsg := sMsg;
end;
DM.FTraceControl.TraceOut;
end;
procedure TPreSaleReceive.PrintBankBillet;
begin
if fPrintBoleto then
begin
with DM.quFreeSQL do
try
if Active then
Close;
SQL.Clear;
SQL.Add('SELECT L.IDLancamento');
SQL.Add('FROM Fin_Lancamento L (NOLOCK)');
SQL.Add('JOIN MeioPag MP (NOLOCK) ON (L.IDQuitacaoMeioPrevisto = MP.IDMeioPag)');
SQL.Add('WHERE L.IDPreSale = ' + IntToStr(MyIDPreSale));
SQL.Add('AND IsNull(MP.PrintBankBillet,0) = 1');
Open;
if not IsEmpty then
begin
First;
while not EOF do
begin
with TFrmPrintBoleto.Create(Self) do
Start(FieldByName('IDLancamento').AsInteger);
Next;
end;
end;
finally
Close;
end;
end;
end;
function TPreSaleReceive.ValidadeStoreAccount(APayment : Currency): Boolean;
var
fSABanlace : Currency;
begin
if (MyIDCliente <= 1) then
begin
MsgBox(MSG_CRT_NO_CUSTUMER, vbInformation + vbOkOnly);
Result := False;
Exit;
end;
if (GetPayment <= 0) then
begin
MsgBox(MSG_CRT_INVALID_AMOUNT, vbOKOnly + vbCritical);
Exit;
end;
//Validar Saldo
if (not Password.HasFuncRight(89)) then
begin
with DM.quFreeSQL do
try
if Active then
Close;
SQL.Clear;
SQL.Add('SELECT SUM(SA.Amount) as Amount');
SQL.Add('FROM Sal_StoreAccount SA (NOLOCK)');
SQL.Add('WHERE SA.IDStoreAccountUsed IS NULL');
SQL.Add('AND SA.IsUsed = 0');
SQL.Add('AND SA.IsReceiving = 0');
SQL.Add('AND SA.IDPessoa = ' + IntToStr(MyIDCliente));
Open;
fSABanlace := FieldByName('Amount').AsCurrency;
finally
Close;
end;
if fCustSAMax < (fSABanlace + APayment) then
begin
MsgBox(Format(MSG_CRT_AS_EXCEED_BALANCE, [FormatFloat('#,##0.00', (fSABanlace + APayment)), FormatFloat('#,##0.00', fCustSAMax)]), vbOKOnly + vbCritical);
Exit;
end;
end;
Result := True;
end;
procedure TPreSaleReceive.RefreshCustomerInfo;
begin
if (MyIDCliente > 1) then
with DM.quFreeSQL do
try
if Active then
Close;
SQL.Clear;
SQL.Add('SELECT P.StoreAccountLimit, P.Nonpayer');
SQL.Add('FROM Pessoa P (NOLOCK)');
SQL.Add('WHERE P.IDPessoa = ' + IntToStr(MyIDCliente));
Open;
fCustSAMax := FieldByName('StoreAccountLimit').AsCurrency;
fCustDeliquent := FieldByName('Nonpayer').AsBoolean;
finally
Close;
end;
end;
procedure TPreSaleReceive.RecalcInvoiceTotal;
var
cBonusPayment : Currency;
begin
if MyIsLayaway then
begin
// Calculo o total de layaway
MyLayaway := DM.fPOS.GetInvoicePayments(MyIDPreSale);
// Sugiro o valor restante a pagar
MyPayment := MyTotInvoice - MyLayaway;
edLayaway.text := FloatToStrF(MyLayaway, ffCurrency, 20, 2);
edtBalance.text := FloatToStrF(MyPayment, ffCurrency, 20, 2);
// Mostros os campos do Layaway se Balance nao for zero
lblPayment.Visible := (MyPayment<>0);
edPayment.Visible := lblPayment.Visible;
lbIqual.Visible := lblPayment.Visible;
// Mostros os campos do Layaway
lblLayaway.Visible := True;
edLayaway.Visible := True;
lbMenus.Visible := True;
lbBalance.Visible := True;
edtBalance.Visible := True;
IsLayawayToClose := ShowCloseLayAway(MyLayaway);
//Verifico se e para fechar o Layaway
if IsLayawayToClose then
begin
pnlPaymentType.Visible := False;
pnlShowCash.Visible := False;
lblPayment.Visible := False;
edPayment.Visible := False;
lbIqual.Visible := False;
cbxCloseLayaway.Visible := not DM.fSystem.SrvParam[PARAM_INVOICE_SHOW_TAB_PAYMENTS];
//cbxCloseLayaway.Enabled := False;
end
else
begin
cbxCloseLayaway.Visible := False;
if DM.fSystem.SrvParam[PARAM_ENTER_LAYAWAY_FULL_AMOUNT] then
edPayment.Text := FormatFloat('#,##0.00', MyPayment)
else
edPayment.Clear;
end;
end
else
begin
if DM.fSystem.SrvParam[PARAM_APPLY_BONUS_ON_SALE] then
begin
cBonusPayment := DM.fPOS.GetInvoicePayments(MyIDPreSale);
if (cBonusPayment <> 0) then
begin
MyTotInvoice := MyRound(MyquPreSaleValue.FieldByName('TotalInvoice').AsFloat, 2) - cBonusPayment;
EditTotalInvoice.Text := FloatToStrF(MyTotInvoice, ffCurrency, 20, 2);
end;
end;
// Sumo com os campos do layaway
lblPayment.Visible := False;
edPayment.Visible := False;
lblLayaway.Visible := False;
edPayment.Visible := False;
edLayaway.Visible := False;
lbMenus.Visible := False;
lbIqual.Visible := False;
lbBalance.Visible := False;
edtBalance.Visible := False;
end;
end;
function TPreSaleReceive.ProcessInvoiceBonus : Boolean;
var
BonusBucks: TBonusBucks;
cDiscountValue: Currency;
GetBonus : Boolean;
BonusCode : String;
IDError : Integer;
ErrorMsg : String;
sInvoiceNum : String;
begin
DM.FTraceControl.TraceIn('TPreSaleReceive.ProcessInvoiceBonus');
GetBonus := False;
Result := True;
try
try
BonusCode := '';
DM.FBonusSync.BonusCode := '';
DM.FBonusSync.BonusValue := 0;
if DM.fSystem.SrvParam[PARAM_APPLY_BONUS_ON_SALE] then
begin
BonusBucks := TBonusBucks.Create(DM.ADODBConnect, DM.FBonusSync);
BonusBucks.IDPreSaleCreated := MyIDPreSale;
cDiscountValue := BonusBucks.DiscountValue;
sInvoiceNum := MyquPreSaleInfo.FieldByName('SaleCode').AsString;
if cDiscountValue > 0 then
if not DM.BonusGenerate(MyTotInvoice, cDiscountValue, sInvoiceNum, Trunc(Now), BonusCode, IDError, ErrorMsg) then
begin
DM.FBonusSync.BonusValue := 0;
if (MsgBox(MSG_QST_PROCESS_BONUS + ErrorMsg, vbYesNo + vbQuestion) = vbNo) then
begin
Result := False;
Exit;
end;
end;
GetBonus := True;
end
else
cDiscountValue := 0;
if not Result then
raise Exception.Create('error receiving');
finally
if GetBonus then
FreeAndNil(BonusBucks);
end;
except
on E: Exception do
begin
DM.FTraceControl.SetException(E.Message, 'TPreSaleReceive');
Result := False;
end;
end;
DM.FTraceControl.TraceOut;
end;
function TPreSaleReceive.getPaymentCard(arg_processor,
arg_paymentType: Integer): TCCWidget;
begin
case (arg_paymentType) of
PAYMENT_TYPE_CARD: begin
result := TCCredit.Create();
end;
PAYMENT_TYPE_DEBIT: begin
result := TCDebit.Create();
end;
PAYMENT_TYPE_GIFTCARD: begin
result := TCPrePaid.Create();
end;
end;
end;
function TPreSaleReceive.processCardCreditIsPresent(arg_amount: Double; arg_widget: TCCWidget): Boolean;
begin
arg_widget.OnNeedSwipe := NeedSwipe;
arg_widget.AfterSucessfullSwipe := SucessFullSwipe;
arg_widget.Memo := 'MainRetail ' + DM.fSystem.VerBuild;
arg_widget.OperatorID := IntToStr(DM.fUser.ID);
arg_widget.InvoiceNo := IntToStr(MyIDPreSale);
arg_widget.RefNo := IntToStr(MyIDPreSale);
arg_widget.Purchase := arg_amount;
arg_widget.AcctNo := '';
arg_widget.ExpDate := '';
arg_widget.Track2 := '';
arg_widget.Tax := 0;
arg_widget.Address := '';
arg_widget.zip := '';
arg_widget.CustomerCode := '';
arg_widget.cvvData := '';
if ( arg_amount > 0 ) then begin
arg_widget.ProcessSale();
end else begin
arg_widget.ProcessReturn();
end;
end;
function TPreSaleReceive.processCardDebitIsPresent(arg_amount: Double; arg_widget: TCCWidget): Boolean;
begin
(*
arg_widget.fmPinPad.fbaudRate := dm.fpinPad.baud;
arg_widget.fmPinPad.FCommport := dm.fpinpad.comm;
arg_widget.ftimeout := strToInt(dm.fPinPad.TimeOut);
*)
if ( arg_amount > 0 ) then begin
arg_widget.processSale();
end else begin
arg_widget.ProcessReturn();
end;
end;
function TPreSaleReceive.processCardIsNotPresent(arg_amount: Double; arg_widget: TCCWidget): Boolean;
var sCardNumber, sMemberName, sExpireDate, sStreetAddress, sZipCode, sCVV2 : String;
begin
with TfrmPCCharge.Create(nil) do
try
Result := StartMercury(sCardNumber, sMemberName, sExpireDate, sStreetAddress, sZipCode, sCVV2);
if ( Result ) then begin
arg_widget.OnNeedSwipe := nil;
arg_widget.AfterSucessfullSwipe := nil;
arg_widget.OnNeedTroutD := nil;
arg_widget.Memo := 'MainRetail';
arg_widget.OperatorID := intToStr(dm.fUser.ID);
arg_widget.InvoiceNo := intToStr(MyIDPreSale);
arg_widget.RefNo := intToStr(myIdPresale);
arg_widget.Purchase := arg_amount;
arg_widget.tax := 0;
arg_widget.AcctNo := sCardNumber;
arg_widget.ExpDate := sExpireDate;
arg_widget.address := sStreetAddress;
arg_widget.zip := sZipCode;
arg_widget.cvvData := sCVV2;
arg_widget.CustomerCode := sMemberName;
arg_widget.Track2 := '';
if ( arg_amount > 0 ) then begin
arg_widget.ProcessSale()
end else begin
arg_widget.ProcessReturn();
end;
end
else
FErrorMsg := 'Canceled by user.';
finally
Free;
end;
end;
end.
|
unit MeshSmoothGaussianCommand;
interface
uses ControllerDataTypes, ActorActionCommandBase, Actor;
{$INCLUDE source/Global_Conditionals.inc}
type
TMeshSmoothGaussianCommand = class (TActorActionCommandBase)
public
constructor Create(var _Actor: TActor; var _Params: TCommandParams); override;
procedure Execute; override;
end;
implementation
uses StopWatch, MeshSmoothGaussian, GlobalVars, SysUtils;
constructor TMeshSmoothGaussianCommand.Create(var _Actor: TActor; var _Params: TCommandParams);
begin
FCommandName := 'Mesh Smooth Gaussian Method';
inherited Create(_Actor,_Params);
end;
procedure TMeshSmoothGaussianCommand.Execute;
var
MeshSmooth : TMeshSmoothGaussian;
{$ifdef SPEED_TEST}
StopWatch : TStopWatch;
{$endif}
begin
{$ifdef SPEED_TEST}
StopWatch := TStopWatch.Create(true);
{$endif}
MeshSmooth := TMeshSmoothGaussian.Create(FActor.Models[0]^.LOD[FActor.Models[0]^.CurrentLOD]);
MeshSmooth.Execute;
MeshSmooth.Free;
{$ifdef SPEED_TEST}
StopWatch.Stop;
GlobalVars.SpeedFile.Add('Mesh smooth Gaussian for LOD takes: ' + FloatToStr(StopWatch.ElapsedNanoseconds) + ' nanoseconds.');
StopWatch.Free;
{$endif}
end;
end.
|
(***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower Async Professional
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1991-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* EXSAPIP0.PAS 4.06 *}
{*********************************************************}
{**********************Description************************}
{* Demonstrates using the TApdSapiPhone component in a *}
{* more complex voice telephony application. *}
{*********************************************************}
unit ExSapiP0;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
AdTapi, AdSapiPh, OoMisc, AdSapiEn, Grids, StdCtrls, AdPort, Gauges;
type
TConversationState = (csPhone, csPhoneVerify, csDate, csTime,
csDateTimeVerify);
TForm1 = class(TForm)
ApdSapiEngine1: TApdSapiEngine;
ApdSapiPhone1: TApdSapiPhone;
Label1: TLabel;
ApdComPort1: TApdComPort;
btnAnswer: TButton;
StringGrid1: TStringGrid;
Label2: TLabel;
Memo1: TMemo;
Gauge1: TGauge;
Log: TLabel;
procedure btnAnswerClick(Sender: TObject);
procedure ApdSapiPhone1TapiConnect(Sender: TObject);
procedure Hangup;
procedure Conversation;
procedure FindPhoneEngines;
procedure ApdSapiPhone1AskForPhoneNumberFinish(Sender: TObject;
Reply: TApdSapiPhoneReply; Data, SpokenData: String);
procedure ApdSapiPhone1AskForYesNoFinish(Sender: TObject;
Reply: TApdSapiPhoneReply; Data: Boolean; SpokenData: String);
procedure ApdSapiPhone1AskForDateFinish(Sender: TObject;
Reply: TApdSapiPhoneReply; Data: TDateTime; SpokenData: String);
procedure ApdSapiPhone1AskForTimeFinish(Sender: TObject;
Reply: TApdSapiPhoneReply; Data: TDateTime; SpokenData: String);
procedure ApdSapiEngine1Interference(Sender: TObject;
InterferenceType: TApdSRInterferenceType);
procedure ApdSapiEngine1PhraseFinish(Sender: TObject;
const Phrase: String);
procedure ApdSapiEngine1VUMeter(Sender: TObject; Level: Integer);
procedure ApdSapiPhone1TapiDisconnect(Sender: TObject);
procedure ApdSapiEngine1SRError(Sender: TObject; Error: Cardinal;
const Details, Message: String);
procedure ApdSapiEngine1SRWarning(Sender: TObject; Error: Cardinal;
const Details, Message: String);
procedure ApdSapiEngine1SSError(Sender: TObject; Error: Cardinal;
const Details, Message: String);
procedure ApdSapiEngine1SSWarning(Sender: TObject; Error: Cardinal;
const Details, Message: String);
procedure FormCreate(Sender: TObject);
private
ConvState : TConversationState;
PhoneNumber : string;
TheDate : TDateTime;
TheTime : TDateTime;
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Hangup;
begin
ApdSapiEngine1.Speak ('Goodbye');
ApdSapiEngine1.WaitUntilDoneSpeaking;
ApdSapiPhone1.CancelCall;
ApdSapiPhone1.AutoAnswer;
end;
procedure TForm1.FindPhoneEngines;
procedure SetSSEngine;
var
i : Integer;
begin
for i := 0 to ApdSapiEngine1.SSVoices.Count - 1 do
if tfPhoneOptimized in ApdSapiEngine1.SSVoices.Features[i] then begin
ApdSapiEngine1.SSVoices.CurrentVoice := i;
Exit;
end;
raise Exception.Create ('No phone enabled speech synthesis engine was found');
end;
procedure SetSREngine;
var
i : Integer;
begin
for i := 0 to ApdSapiEngine1.SREngines.Count - 1 do
if sfPhoneOptimized in ApdSapiEngine1.SREngines.Features[i] then begin
ApdSapiEngine1.SREngines.CurrentEngine := i;
Exit;
end;
raise Exception.Create ('No phone enabled speech recognition engine was found');
end;
begin
SetSSEngine;
SetSREngine;
end;
procedure TForm1.Conversation;
function SplitPhoneNumber (PhoneNum : string) : string;
var
i : Integer;
begin
Result := '';
for i := 1 to Length (PhoneNum) do
if (PhoneNum[i] >= '0') and (PhoneNum[i] <= '9') then
Result := Result + PhoneNum[i] + ' ';
end;
begin
case ConvState of
csPhone :
begin
Memo1.Lines.Add ('Asking for phone number');
ApdSapiPhone1.AskForPhoneNumber ('Please tell me your phone number');
end;
csPhoneVerify :
begin
Memo1.Lines.Add ('Confirming phone number');
ApdSapiPhone1.AskForYesNo ('I heard ' + SplitPhoneNumber (PhoneNumber) +
'. Is this correct?');
end;
csDate :
begin
Memo1.Lines.Add ('Asking for date');
ApdSapiPhone1.AskForDate ('What date would you like?');
end;
csTime :
begin
Memo1.Lines.Add ('Asking for time');
ApdSapiPhone1.AskForTime ('What time would you like?');
end;
csDateTimeVerify :
begin
Memo1.Lines.Add ('Confirming Date and Time');
ApdSapiPhone1.AskForYesNo ('I heard ' +
FormatDateTime ('ddddd', TheDate) +
' at ' +
FormatDateTime ('t', TheTime) +
'. Is this correct?');
end;
end;
end;
procedure TForm1.btnAnswerClick(Sender: TObject);
begin
{ Make sure that phone enabled SAPI engines are being used }
FindPhoneEngines;
{ Wait for a call }
ApdSapiPhone1.AutoAnswer;
end;
procedure TForm1.ApdSapiPhone1TapiConnect(Sender: TObject);
begin
Memo1.Lines.Add ('Call received at ' + FormatDateTime ('ddddd t', Now));
ApdSapiEngine1.Speak ('Welcome to the Sapi phone demonstration');
ApdSapiEngine1.WaitUntilDoneSpeaking;
ConvState := csPhone;
Conversation;
end;
procedure TForm1.ApdSapiPhone1AskForPhoneNumberFinish(Sender: TObject;
Reply: TApdSapiPhoneReply; Data, SpokenData: String);
begin
case Reply of
prOk :
begin
PhoneNumber := Data;
StringGrid1.RowCount := StringGrid1.RowCount + 1;
if StringGrid1.RowCount < 2 then begin
StringGrid1.RowCount := StringGrid1.RowCount + 1;
end;
StringGrid1.Cells [0, 0] := 'Phone Number';
StringGrid1.Cells [1, 0] := 'Date';
StringGrid1.Cells [2, 0] := 'Time';
StringGrid1.Cells [3, 0] := 'OK';
StringGrid1.FixedRows := 1;
StringGrid1.Cells [0, StringGrid1.RowCount - 1] := PhoneNumber;
StringGrid1.Cells [3, StringGrid1.RowCount - 1] := 'No';
ConvState := csPhoneVerify;
Conversation;
end;
prCheck :
begin
PhoneNumber := Data;
ConvState := csPhoneVerify;
StringGrid1.Cells [0, 0] := 'Phone Number';
StringGrid1.Cells [1, 0] := 'Date';
StringGrid1.Cells [2, 0] := 'Time';
StringGrid1.FixedRows := 1;
StringGrid1.Cells [0, StringGrid1.RowCount - 1] := PhoneNumber;
StringGrid1.Cells [3, StringGrid1.RowCount - 1] := 'No';
Conversation;
end;
prHangup :
Hangup;
prBack :
begin
ConvState := csPhone;
Conversation;
end;
end;
end;
procedure TForm1.ApdSapiPhone1AskForYesNoFinish(Sender: TObject;
Reply: TApdSapiPhoneReply; Data: Boolean; SpokenData: String);
begin
case Reply of
prOk :
begin
if Data then
case ConvState of
csPhoneVerify :
ConvState := csDate;
csDateTimeVerify :
begin
ApdSapiEngine1.Speak ('thank you');
StringGrid1.Cells [3, StringGrid1.RowCount - 1] := 'Yes';
Hangup;
Exit;
end;
end
else
case ConvState of
csPhoneVerify :
ConvState := csPhone;
csDateTimeVerify :
ConvState := csDate;
end;
Conversation;
end;
prHangup :
Hangup;
prBack :
begin
case ConvState of
csPhoneVerify :
ConvState := csPhone;
csDateTimeVerify :
ConvState := csTime;
end;
Conversation
end;
end;
end;
procedure TForm1.ApdSapiPhone1AskForDateFinish(Sender: TObject;
Reply: TApdSapiPhoneReply; Data: TDateTime; SpokenData: String);
begin
case Reply of
prOk :
begin
TheDate := Data;
ConvState := csTime;
StringGrid1.Cells [1, StringGrid1.RowCount - 1] :=
FormatDateTime ('ddddd', TheDate);
Conversation;
end;
prCheck :
begin
TheDate := Data;
ConvState := csTime;
StringGrid1.Cells [1, StringGrid1.RowCount - 1] :=
FormatDateTime ('ddddd', TheDate);
Conversation;
end;
prHangup :
Hangup;
prBack :
begin
ConvState := csPhone;
Conversation;
end;
end;
end;
procedure TForm1.ApdSapiPhone1AskForTimeFinish(Sender: TObject;
Reply: TApdSapiPhoneReply; Data: TDateTime; SpokenData: String);
begin
case Reply of
prOk :
begin
TheTime := Data;
ConvState := csDateTimeVerify;
StringGrid1.Cells [2, StringGrid1.RowCount - 1] :=
FormatDateTime ('t', TheTime);
Conversation;
end;
prCheck :
begin
TheTime := Data;
ConvState := csDateTimeVerify;
StringGrid1.Cells [2, StringGrid1.RowCount - 1] :=
FormatDateTime ('t', TheTime);
Conversation;
end;
prHangup :
Hangup;
prBack :
begin
ConvState := csDate;
Conversation;
end;
end;
end;
procedure TForm1.ApdSapiEngine1Interference(Sender: TObject;
InterferenceType: TApdSRInterferenceType);
begin
case InterferenceType of
itAudioStarted :
Memo1.Lines.Add ('Audio Started');
itAudioStopped :
Memo1.Lines.Add ('Audio Stopped');
itDeviceOpened :
Memo1.Lines.Add ('Device Opened');
itDeviceClosed :
Memo1.Lines.Add ('Device Closed');
itNoise :
Memo1.Lines.Add ('Interference: Noise');
itTooLoud :
Memo1.Lines.Add ('Interference: Too Loud');
itTooQuiet :
Memo1.Lines.Add ('Interference: Too Quiet');
itUnknown :
Memo1.Lines.Add ('Interference: Unknown');
end;
end;
procedure TForm1.ApdSapiEngine1PhraseFinish(Sender: TObject;
const Phrase: String);
begin
Memo1.Lines.Add ('The user said ' + Phrase);
end;
procedure TForm1.ApdSapiEngine1VUMeter(Sender: TObject; Level: Integer);
begin
Gauge1.Progress := Level;
end;
procedure TForm1.ApdSapiPhone1TapiDisconnect(Sender: TObject);
begin
Memo1.Lines.Add ('Call disconnected at ' + FormatDateTime ('ddddd t', Now));
end;
procedure TForm1.ApdSapiEngine1SRError(Sender: TObject; Error: Cardinal;
const Details, Message: String);
begin
Memo1.Lines.Add ('Speech Recognition Error: ' + Message);
end;
procedure TForm1.ApdSapiEngine1SRWarning(Sender: TObject; Error: Cardinal;
const Details, Message: String);
begin
Memo1.Lines.Add ('Speech Recognition Warning: ' + Message);
end;
procedure TForm1.ApdSapiEngine1SSError(Sender: TObject; Error: Cardinal;
const Details, Message: String);
begin
Memo1.Lines.Add ('Speech Synthesis Error: ' + Message);
end;
procedure TForm1.ApdSapiEngine1SSWarning(Sender: TObject; Error: Cardinal;
const Details, Message: String);
begin
Memo1.Lines.Add ('Speech Synthesis Warning: ' + Message);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
if (not ApdSapiEngine1.IsSapi4Installed) then begin
ShowMessage ('SAPI 4 is not installed. AV will occur.');
end;
end;
end.
|
unit uCheckReportFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uBaseEditFrm, ExtCtrls, Menus,
cxCustomData,
cxEdit, DB, cxDBData, cxGridLevel, cxClasses, cxControls,
cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, StdCtrls, cxButtons, cxContainer, cxTextEdit,
cxMaskEdit, cxDropDownEdit, DBClient,
cxGridBandedTableView, cxGridDBBandedTableView, ActnList, ComCtrls,
cxGraphics, cxLookAndFeelPainters, cxStyles, cxFilter, cxData,
cxDataStorage, cxButtonEdit, cxLabel;
type
TFrm_CheckReport = class(TSTBaseEdit)
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
Label1: TLabel;
cbCheckDate: TcxComboBox;
btFind: TcxButton;
cxGrid1: TcxGrid;
dbgLevel1: TcxGridLevel;
cxButton1: TcxButton;
cxButton2: TcxButton;
cdsCheckList: TClientDataSet;
dsCheckList: TDataSource;
SaveDg: TSaveDialog;
cdsCheckDate: TClientDataSet;
Label5: TLabel;
bt_material: TcxTextEdit;
dbgList: TcxGridDBBandedTableView;
ActionList1: TActionList;
act_SetSizesCaption: TAction;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
cxGrid2: TcxGrid;
dbgList2: TcxGridDBBandedTableView;
cxGridLevel1: TcxGridLevel;
cdsCheckList2: TClientDataSet;
dsCheckList2: TDataSource;
Label2: TLabel;
cbOldCheckDate: TcxComboBox;
btOldFind: TcxButton;
cxButton4: TcxButton;
cdsOldCheckDate: TClientDataSet;
Label4: TLabel;
Image2: TImage;
Label6: TLabel;
cxLabel1: TcxLabel;
cxbtnWarehouse: TcxButtonEdit;
procedure cxButton1Click(Sender: TObject);
procedure cxButton2Click(Sender: TObject);
procedure btFindClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure bt_materialPropertiesChange(Sender: TObject);
procedure cxTextEdit1PropertiesChange(Sender: TObject);
procedure act_SetSizesCaptionExecute(Sender: TObject);
procedure dbgListKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure dbgListMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cxButton4Click(Sender: TObject);
procedure btOldFindClick(Sender: TObject);
procedure Label4Click(Sender: TObject);
procedure cxbtnWarehousePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
private
{ Private declarations }
FwarehouseID : string;
function CreateDBGridColumn(dsDetail : TDataSet;cxDetail:TcxGridDBBandedTableView;FFielCation_Tables:string):Boolean;
procedure SetMasterSizesGroup(fMaterialID: string; cxGridTV: TcxGridDBBandedTableView); //创建表格列
procedure CreateParams(var Params: TCreateParams); override;
public
{ Public declarations }
end;
var
Frm_CheckReport: TFrm_CheckReport;
procedure OpenCheckReport;
implementation
uses Pub_Fun,FrmCliDM,cxGridExportLink,Frm_TolZB,ADODB,uMaterDataSelectHelper;
{$R *.dfm}
procedure OpenCheckReport;
begin
try
if Frm_CheckReport=nil then
Application.CreateForm(TFrm_CheckReport,Frm_CheckReport);
Frm_CheckReport.ShowModal;
finally
Frm_CheckReport.Free;
end;
end;
procedure TFrm_CheckReport.cxButton1Click(Sender: TObject);
begin
inherited;
if PageControl1.ActivePageIndex=0 then
begin
if cdsCheckList.IsEmpty then Exit;
if SaveDg.Execute then
ExportGridToExcel(SaveDg.FileName, cxGrid1, True, true, True);
end;
if PageControl1.ActivePageIndex=1 then
begin
if cdsCheckList2.IsEmpty then Exit;
if SaveDg.Execute then
ExportGridToExcel(SaveDg.FileName, cxGrid2, True, true, True);
end;
end;
procedure TFrm_CheckReport.cxButton2Click(Sender: TObject);
begin
inherited;
Close;
end;
procedure TFrm_CheckReport.btFindClick(Sender: TObject);
var ErrMsg,CheckDateStr,CFMATERIALID,FType,FieldName : string;
i : Integer;
sqlstr,error :string;
begin
inherited;
CheckDateStr := trim(cbCheckDate.Text);
if CheckDateStr='' then
begin
ShowMsg(Handle,'盘点日期不能为空!',[]);
Abort;
end;
sqlstr := 'SELECT 1 FROM CT_IM_CHECKSAVESTORAGE WHERE FWarehouseID='+QuotedStr(userinfo.Warehouse_FID)+' and FCheckDateStr='+QuotedStr(CheckDateStr)+ ' and rownum=1';
if not CliDM.Get_ExistsSQL(sqlstr,error) then
begin
ShowMsg(Handle,'您选择的盘点日期当天还没有保存库存,分析结果将全部为盘盈!',[]);
end;
try
Screen.Cursor := crHourGlass;
btFind.Enabled := False;
if PageControl1.ActivePageIndex=0 then //差异分析
begin
try
cdsCheckList.DisableControls;
cdsCheckList.Filtered := False;
//if CliDM.Pub_CheckSaveStorage(4,CheckDateStr,cdsCheckList,ErrMsg) then
if CliDM.E_CheckSaveStorage(8,UserInfo.LoginUser_FID,FwarehouseID,CheckDateStr,cdsCheckList,ErrMsg) then
begin
CreateDBGridColumn(cdsCheckList,dbgList,Self.Name);
if cdsCheckList.FindField('Fnumber')<> nil then dbgList.GetColumnByFieldName('Fnumber').Visible := False;
if cdsCheckList.FindField('FMATERIALID')<> nil then dbgList.GetColumnByFieldName('FMATERIALID').Visible := False;
if cdsCheckList.FindField('StyleCode')<> nil then dbgList.GetColumnByFieldName('StyleCode').Caption := '商品编号';
if cdsCheckList.FindField('StyleName')<> nil then dbgList.GetColumnByFieldName('StyleName').Caption := '商品名称';
if cdsCheckList.FindField('ColorName')<> nil then dbgList.GetColumnByFieldName('ColorName').Caption := '颜色';
if cdsCheckList.FindField('CupName')<> nil then dbgList.GetColumnByFieldName('CupName').Caption := '内长';
if cdsCheckList.FindField('StoQty')<> nil then dbgList.GetColumnByFieldName('StoQty').Caption := '库存数量';
if cdsCheckList.FindField('CHECKQTY')<> nil then dbgList.GetColumnByFieldName('CHECKQTY').Caption := '盘点数量';
if cdsCheckList.FindField('SurPlusQTY')<> nil then dbgList.GetColumnByFieldName('SurPlusQTY').Caption := '盘盈数量';
if cdsCheckList.FindField('LossesQTY')<> nil then dbgList.GetColumnByFieldName('LossesQTY').Caption := '盘亏数量';
//20120209 增加吊牌价 差异额 分类、年份、季节栏位
if cdsCheckList.FindField('YearName')<> nil then dbgList.GetColumnByFieldName('YearName').Caption := '年份';
if cdsCheckList.FindField('SeasonName')<> nil then dbgList.GetColumnByFieldName('SeasonName').Caption := '季节';
if cdsCheckList.FindField('GenreName')<> nil then dbgList.GetColumnByFieldName('GenreName').Caption := '类别';
if cdsCheckList.FindField('CFUnityPrice')<> nil then dbgList.GetColumnByFieldName('CFUnityPrice').Caption := '吊牌价';
if cdsCheckList.FindField('DIFFSUMPRICE')<> nil then dbgList.GetColumnByFieldName('DIFFSUMPRICE').Caption := '盈亏金额';
cdsCheckList.First;
CFMATERIALID := cdsCheckList.fieldByName('FMATERIALID').AsString;
SetMasterSizesGroup(CFMATERIALID,dbgList);
for i :=0 to cdsCheckList.FieldCount-1 do
begin
FieldName := cdsCheckList.Fields[i].FieldName;
if UpperCase(FieldName)=UpperCase('StyleCode') then
begin
with dbgList.DataController.Summary.FooterSummaryItems.Add do
begin
ItemLink := dbgList.GetColumnByFieldName(FieldName);
Position := spFooter;
Kind := skCount;
Format := '0.00;-0.00';
end;
end;
if (UpperCase(FieldName) = UpperCase('StoQty'))
or (UpperCase(FieldName) = UpperCase('CHECKQTY'))
or (UpperCase(FieldName) = UpperCase('SurPlusQTY'))
or (UpperCase(FieldName) = UpperCase('LossesQTY'))
or (UpperCase(FieldName) = UpperCase('DIFFSUMPRICE'))
then
begin
with dbgList.DataController.Summary.FooterSummaryItems.Add do
begin
ItemLink := dbgList.GetColumnByFieldName(FieldName);
Position := spFooter;
Kind := skSum;
Format := '0.00;-0.00';
end;
end;
end;
if not cdsCheckList.IsEmpty then
begin
cdsCheckList.First;
while not cdsCheckList.Eof do
begin
for i := 1 to 30 do
begin
if cdsCheckList.FindField('DAmount_'+inttostr(i)) <> nil then
if cdsCheckList.FindField('DAmount_'+inttostr(i)).AsFloat=0 then
begin
if not(cdsCheckList.State in db.dsEditModes) then cdsCheckList.Edit;
cdsCheckList.FindField('DAmount_'+inttostr(i)).Value:=null;
end;
end;
cdsCheckList.Next;
end;
end;
end
else
begin
ShowMsg(Handle, ErrMsg,[]);
Abort;
end;
finally
cdsCheckList.EnableControls;
end;
end;
if PageControl1.ActivePageIndex=1 then //未盘清单
begin
try
//if CliDM.Pub_CheckSaveStorage(5,CheckDateStr,cdsCheckList2,ErrMsg) then
if CliDM.E_CheckSaveStorage(9,UserInfo.LoginUser_FID,FwarehouseID,CheckDateStr,cdsCheckList2,ErrMsg) then
begin
CreateDBGridColumn(cdsCheckList2,dbgList2,Self.Name+dbgList2.Name);
if cdsCheckList2.FieldByName('Fnumber')<> nil then
dbgList2.GetColumnByFieldName('Fnumber').Visible := False;
if cdsCheckList2.FieldByName('FMATERIALID')<> nil then
dbgList2.GetColumnByFieldName('FMATERIALID').Visible := False;
if cdsCheckList2.FieldByName('SumQty')<> nil then
dbgList2.GetColumnByFieldName('SumQty').Caption := '合计数量';
cdsCheckList2.First;
CFMATERIALID := cdsCheckList2.fieldByName('FMATERIALID').AsString;
SetMasterSizesGroup(CFMATERIALID,dbgList2);
end
else
begin
ShowMsg(Handle, ErrMsg,[]);
Abort;
end;
finally
end;
end;
finally
btFind.Enabled := True;
Screen.Cursor := crDefault;
end;
end;
procedure TFrm_CheckReport.FormCreate(Sender: TObject);
var ErrMsg,CheckDateStr: String;
begin
inherited;
{cbCheckDate.Properties.Items.Clear;
if CliDM.E_CheckSaveStorage(6,UserInfo.LoginUser_FID,FwarehouseID,CheckDateStr,cdsCheckDate,ErrMsg) then
if not cdsCheckDate.IsEmpty then
begin
cdsCheckDate.First;
while not cdsCheckDate.Eof do
begin
CheckDateStr := cdsCheckDate.Fields[0].AsString;
cbCheckDate.Properties.Items.Add(CheckDateStr);
cdsCheckDate.Next;
end;
cbCheckDate.ItemIndex := 0;
end;
//查看历史盘点报表
cbOldCheckDate.Properties.Items.Clear;
if CliDM.E_CheckSaveStorage(7,UserInfo.LoginUser_FID,FwarehouseID,CheckDateStr,cdsOldCheckDate,ErrMsg) then
if not cdsOldCheckDate.IsEmpty then
begin
cdsOldCheckDate.First;
while not cdsOldCheckDate.Eof do
begin
CheckDateStr := cdsOldCheckDate.Fields[0].AsString;
cbOldCheckDate.Properties.Items.Add(CheckDateStr);
cdsOldCheckDate.Next;
end;
cbOldCheckDate.ItemIndex := 0;
end; }
dbgList.Bands.Items[1].Width := UserInfo.MaxSizeCount * 35;
dbgList.Bands.Items[2].Width := UserInfo.MaxSizeCount * 35;
dbgList.Bands.Items[3].Width := UserInfo.MaxSizeCount * 35;
//LoadImage(UserInfo.ExePath+'\Img\POS_Edit_Top2.jpg',Image1);
end;
procedure TFrm_CheckReport.bt_materialPropertiesChange(Sender: TObject);
var FilterStr : string;
begin
inherited;
if cdsCheckList.FindField('Fnumber') <> nil then
begin
if Trim(bt_material.Text)='' then cdsCheckList.Filtered := False
else
begin
cdsCheckList.Filtered := False;
FilterStr := 'UPPER(Fnumber) like ' + QuotedStr('%'+Trim(UpperCase(bt_material.Text))+'%') ;
cdsCheckList.Filter := FilterStr;
cdsCheckList.Filtered := True;
end;
end;
end;
procedure TFrm_CheckReport.cxTextEdit1PropertiesChange(Sender: TObject);
var FilterStr : string;
begin
inherited;
if PageControl1.ActivePageIndex=0 then
begin
if cdsCheckList.FindField('Fnumber') <> nil then
begin
if Trim(bt_material.Text)='' then cdsCheckList.Filtered := False
else
begin
cdsCheckList.Filtered := False;
FilterStr := 'UPPER(Fnumber) like ' + QuotedStr('%'+Trim(UpperCase(bt_material.Text))+'%') ;
cdsCheckList.Filter := FilterStr;
cdsCheckList.Filtered := True;
end;
end;
end
else
begin
if cdsCheckList2.FindField('Fnumber') <> nil then
begin
if Trim(bt_material.Text)='' then cdsCheckList2.Filtered := False
else
begin
cdsCheckList2.Filtered := False;
FilterStr := 'UPPER(Fnumber) like ' + QuotedStr('%'+Trim(UpperCase(bt_material.Text))+'%') ;
cdsCheckList2.Filter := FilterStr;
cdsCheckList2.Filtered := True;
end;
end;
end;
end;
function TFrm_CheckReport.CreateDBGridColumn(dsDetail: TDataSet;
cxDetail: TcxGridDBBandedTableView; FFielCation_Tables: string): Boolean;
var i:Integer;
FieldName : string;
GridColumn : TcxGridDBBandedColumn;
begin
Result := True;
if not dsDetail.Active then
begin
Result := False;
Exit;
end;
//设置列
try
cxDetail.BeginUpdate;
cxDetail.ClearItems;
for i :=0 to dsDetail.FieldCount-1 do
begin
FieldName := dsDetail.Fields[i].FieldName;
GridColumn := cxDetail.CreateColumn;
with GridColumn do
begin
Caption := FieldName;
Name := FFielCation_Tables+'_'+ IntToStr(i);
DataBinding.FieldName := FieldName;
Width := 120; //列宽
Options.Sorting := True; //排序
Options.Filtering := True; //过滤
Options.Focusing := True; //鼠标停留
Options.Editing := False; //是否可以编辑
if UpperCase(FieldName)=UpperCase('FID') then Visible := False;
if UpperCase(Copy(FieldName,0,8))=UpperCase('FAmount_') then
begin
Position.BandIndex := 1;
Width := 50;
if StrToInt(Copy(FieldName,Length('FAmount_')+1,Length(FieldName)))>UserInfo.MaxSizeCount then Visible := False;
end;
if UpperCase(Copy(FieldName,0,9))=UpperCase('CHAmount_') then
begin
Position.BandIndex := 2;
Width := 50;
if StrToInt(Copy(FieldName,Length('CHAmount_')+1,Length(FieldName)))>UserInfo.MaxSizeCount then
Visible := False;
end;
if UpperCase(Copy(FieldName,0,8))=UpperCase('DAmount_') then
begin
Position.BandIndex := 3;
Width := 50;
if StrToInt(Copy(FieldName,Length('DAmount_')+1,Length(FieldName)))>UserInfo.MaxSizeCount then Visible := False;
end;
end;
if FieldName='商品编号' then
with cxDetail.DataController.Summary.FooterSummaryItems.Add do
begin
ItemLink := cxDetail.GetColumnByFieldName(FieldName);
Position := spFooter;
Kind := skCount;
end;
end;
finally
cxDetail.EndUpdate;
end;
end;
//设置尺码标题
procedure TFrm_CheckReport.SetMasterSizesGroup(fMaterialID: string;
cxGridTV: TcxGridDBBandedTableView);
var i,SizeCount,j :Integer;
sqlstr,FieldName : string;
begin
try
cxGridTV.BeginUpdate;
if cxGridTV.DataController.DataSource.DataSet.FindField('SizeGroupID')<>nil then
cxGridTV.GetColumnByFieldName('SizeGroupID').Visible := False;
sqlstr :=
' SELECT distinct B.FSEQ,C.FNAME_L2,T.FNUMBER '
+' from T_BD_Material A(nolock) '
+' LEFT OUTER JOIN ct_bas_sizegroupentry B(nolock) ON A.cfSizeGroupID collate Chinese_PRC_CS_AS_WS=B.fParentID collate Chinese_PRC_CS_AS_WS'
+' LEFT OUTER JOIN T_BD_AsstAttrValue C(nolock) on b.cfSizeID collate Chinese_PRC_CS_AS_WS=C.FID collate Chinese_PRC_CS_AS_WS'
+' left join t_Bd_Asstattrcompondingtype T on A.FASSISTATTR collate Chinese_PRC_CS_AS_WS=T.FID collate Chinese_PRC_CS_AS_WS'
+' WHERE A.FID collate Chinese_PRC_CS_AS_WS='+QuotedStr(fMaterialID)
+' ORDER BY B.FSEQ ';
with CliDM.qryTemp do
begin
Close;
sql.Clear;
sql.Add(sqlstr);
Open;
SizeCount := CliDM.qryTemp.RecordCount;
First;
for i:= 1 to UserInfo.MaxSizeCount do
begin
if cxGridTV.DataController.DataSource.DataSet.FindField('fAmount_'+inttostr(I))<>nil then
cxGridTV.GetColumnByFieldName('fAmount_'+inttostr(I)).Caption := ''; //库存数量
if cxGridTV.DataController.DataSource.DataSet.FindField('CHAmount_'+inttostr(I))<>nil then
cxGridTV.GetColumnByFieldName('CHAmount_'+inttostr(I)).Caption := ''; //盘点数量
if cxGridTV.DataController.DataSource.DataSet.FindField('DAmount_'+inttostr(I))<>nil then
cxGridTV.GetColumnByFieldName('DAmount_'+inttostr(I)).Caption := ''; //差异数量
if CliDM.qryTemp.Locate('FSEQ',I,[]) then
begin
if cxGridTV.DataController.DataSource.DataSet.FindField('fAmount_'+inttostr(I))<>nil then
begin
FieldName := 'fAmount_'+inttostr(I);
if (cxGridTV.GetColumnByFieldName(FieldName) <> nil) then
begin
cxGridTV.GetColumnByFieldName(FieldName).Caption := FieldByName('FNAME_L2').AsString;
end;
end;
if cxGridTV.DataController.DataSource.DataSet.FindField('CHAmount_'+inttostr(I))<>nil then
begin
FieldName := 'CHAmount_'+inttostr(I);
if (cxGridTV.GetColumnByFieldName(FieldName) <> nil) then
begin
cxGridTV.GetColumnByFieldName(FieldName).Caption := FieldByName('FNAME_L2').AsString;
end;
end;
if cxGridTV.DataController.DataSource.DataSet.FindField('DAmount_'+inttostr(I))<>nil then
begin
FieldName := 'DAmount_'+inttostr(I);
if (cxGridTV.GetColumnByFieldName(FieldName) <> nil) then
begin
cxGridTV.GetColumnByFieldName(FieldName).Caption := FieldByName('FNAME_L2').AsString;
end;
end;
end;
Next;
end;
end;
finally
cxGridTV.EndUpdate;
end;
end;
procedure TFrm_CheckReport.act_SetSizesCaptionExecute(Sender: TObject);
var CFMATERIALID : string;
begin
inherited;
if PageControl1.ActivePageIndex = 0 then
begin
if not cdsCheckList.Active then exit;
CFMATERIALID := cdsCheckList.fieldByName('FMATERIALID').AsString;
SetMasterSizesGroup(CFMATERIALID,dbgList);
end
else
begin
if not cdsCheckList2.Active then exit;
CFMATERIALID := cdsCheckList2.fieldByName('FMATERIALID').AsString;
SetMasterSizesGroup(CFMATERIALID,dbgList2);
end;
end;
procedure TFrm_CheckReport.dbgListKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if (Key = VK_RETURN) or (Key = 37) or (Key=38) then //回车 左键 上键
act_SetSizesCaption.Execute;
end;
procedure TFrm_CheckReport.dbgListMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited;
act_SetSizesCaption.Execute;
end;
procedure TFrm_CheckReport.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
Frm_CheckReport := nil;
end;
procedure TFrm_CheckReport.cxButton4Click(Sender: TObject);
var ErrMsg,CheckDateStr: String;
begin
inherited;
end;
procedure TFrm_CheckReport.btOldFindClick(Sender: TObject);
var ErrMsg,CheckDateStr,CFMATERIALID,FType,FieldName : string;
i : integer;
begin
inherited;
CheckDateStr := trim(cbOldCheckDate.Text);
if CheckDateStr='' then
begin
ShowMsg(Handle,'历史盘点日期不能为空!',[]);
cbOldCheckDate.SetFocus;
Abort;
end;
try
Screen.Cursor := crHourGlass;
cdsCheckList.DisableControls;
btOldFind.Enabled := False;
if PageControl1.ActivePageIndex=0 then //历史盘点差异分析
begin
cdsCheckList.Filtered := False;
// if CliDM.Pub_CheckSaveStorage(7,CheckDateStr,cdsCheckList,ErrMsg) then
if CliDM.E_CheckSaveStorage(7,UserInfo.LoginUser_FID,FwarehouseID,CheckDateStr,cdsCheckList,ErrMsg) then
begin
CreateDBGridColumn(cdsCheckList,dbgList,Self.Name);
if cdsCheckList.FindField('Fnumber')<> nil then dbgList.GetColumnByFieldName('Fnumber').Visible := False;
if cdsCheckList.FindField('FMATERIALID')<> nil then dbgList.GetColumnByFieldName('FMATERIALID').Visible := False;
if cdsCheckList.FindField('StyleCode')<> nil then dbgList.GetColumnByFieldName('StyleCode').Caption := '商品编号';
if cdsCheckList.FindField('StyleName')<> nil then dbgList.GetColumnByFieldName('StyleName').Caption := '商品名称';
if cdsCheckList.FindField('ColorName')<> nil then dbgList.GetColumnByFieldName('ColorName').Caption := '颜色';
if cdsCheckList.FindField('CupName')<> nil then dbgList.GetColumnByFieldName('CupName').Caption := '内长';
if cdsCheckList.FindField('StoQty')<> nil then dbgList.GetColumnByFieldName('StoQty').Caption := '库存数量';
if cdsCheckList.FindField('CHECKQTY')<> nil then dbgList.GetColumnByFieldName('CHECKQTY').Caption := '盘点数量';
if cdsCheckList.FindField('SurPlusQTY')<> nil then dbgList.GetColumnByFieldName('SurPlusQTY').Caption := '盘盈数量';
if cdsCheckList.FindField('LossesQTY')<> nil then dbgList.GetColumnByFieldName('LossesQTY').Caption := '盘亏数量';
//20120209 增加吊牌价 差异额 分类、年份、季节栏位
if cdsCheckList.FindField('YearName')<> nil then dbgList.GetColumnByFieldName('YearName').Caption := '年份';
if cdsCheckList.FindField('SeasonName')<> nil then dbgList.GetColumnByFieldName('SeasonName').Caption := '季节';
if cdsCheckList.FindField('GenreName')<> nil then dbgList.GetColumnByFieldName('GenreName').Caption := '类别';
if cdsCheckList.FindField('CFUnityPrice')<> nil then dbgList.GetColumnByFieldName('CFUnityPrice').Caption := '吊牌价';
if cdsCheckList.FindField('DIFFSUMPRICE')<> nil then dbgList.GetColumnByFieldName('DIFFSUMPRICE').Caption := '盈亏金额';
for i :=0 to cdsCheckList.FieldCount-1 do
begin
FieldName := cdsCheckList.Fields[i].FieldName;
if UpperCase(FieldName)=UpperCase('StyleCode') then
begin
with dbgList.DataController.Summary.FooterSummaryItems.Add do
begin
ItemLink := dbgList.GetColumnByFieldName(FieldName);
Position := spFooter;
Kind := skCount;
Format := '0.00;-0.00';
end;
end;
if (UpperCase(FieldName) = UpperCase('StoQty'))
or (UpperCase(FieldName) = UpperCase('CHECKQTY'))
or (UpperCase(FieldName) = UpperCase('SurPlusQTY'))
or (UpperCase(FieldName) = UpperCase('LossesQTY'))
or (UpperCase(FieldName) = UpperCase('DIFFSUMPRICE'))
then
begin
with dbgList.DataController.Summary.FooterSummaryItems.Add do
begin
ItemLink := dbgList.GetColumnByFieldName(FieldName);
Position := spFooter;
Kind := skSum;
Format := '0.00;-0.00';
end;
end;
end;
cdsCheckList.First;
CFMATERIALID := cdsCheckList.fieldByName('FMATERIALID').AsString;
SetMasterSizesGroup(CFMATERIALID,dbgList);
if not cdsCheckList.IsEmpty then
begin
cdsCheckList.First;
while not cdsCheckList.Eof do
begin
for i := 1 to 30 do
begin
if cdsCheckList.FindField('DAmount_'+inttostr(i)) <> nil then
if cdsCheckList.FindField('DAmount_'+inttostr(i)).AsFloat=0 then
begin
if not(cdsCheckList.State in db.dsEditModes) then cdsCheckList.Edit;
cdsCheckList.FindField('DAmount_'+inttostr(i)).Value:=null;
end;
end;
cdsCheckList.Next;
end;
end;
end
else
begin
ShowMsg(Handle, ErrMsg,[]);
Abort;
end;
end;
if PageControl1.ActivePageIndex=1 then //历史未盘商品
begin
//if CliDM.Pub_CheckSaveStorage(8,CheckDateStr,cdsCheckList2,ErrMsg) then
if CliDM.E_CheckSaveStorage(10,UserInfo.LoginUser_FID,FwarehouseID,CheckDateStr,cdsCheckList2,ErrMsg) then
begin
CreateDBGridColumn(cdsCheckList2,dbgList2,Self.Name+dbgList2.Name);
if cdsCheckList2.FieldByName('Fnumber')<> nil then
dbgList2.GetColumnByFieldName('Fnumber').Visible := False;
if cdsCheckList2.FieldByName('FMATERIALID')<> nil then
dbgList2.GetColumnByFieldName('FMATERIALID').Visible := False;
if cdsCheckList2.FieldByName('SumQty')<> nil then
dbgList2.GetColumnByFieldName('SumQty').Caption := '合计数量';
cdsCheckList2.First;
CFMATERIALID := cdsCheckList2.fieldByName('FMATERIALID').AsString;
SetMasterSizesGroup(CFMATERIALID,dbgList2);
end
else
begin
ShowMsg(Handle, ErrMsg,[]);
Abort;
end;
end;
finally
cdsCheckList.EnableControls;
btOldFind.Enabled := True;
Screen.Cursor := crDefault;
end;
end;
procedure TFrm_CheckReport.Label4Click(Sender: TObject);
begin
inherited;
if PageControl1.ActivePageIndex =0 then
begin
if dbgList.DataController.DataSource.DataSet.IsEmpty then
begin
ShowMessage('没有可以统计的数据项!');
Abort;
end;
Total_ZB(TcxGridDBTableView(dbgList),TAdoDataSet(cdsCheckList),self.Caption,1,self.Caption);
end
else
if PageControl1.ActivePageIndex =1 then
begin
if dbgList2.DataController.DataSource.DataSet.IsEmpty then
begin
ShowMessage('没有可以统计的数据项!');
Abort;
end;
Total_ZB(TcxGridDBTableView(dbgList2),TAdoDataSet(cdsCheckList2),self.Caption,1,self.Caption);
end;
end;
procedure TFrm_CheckReport.CreateParams(var Params: TCreateParams);
begin
Inherited CreateParams(Params);
Params.ExStyle := Params.ExStyle or WS_Ex_AppWindow;
end;
procedure TFrm_CheckReport.cxbtnWarehousePropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var ErrMsg,CheckDateStr: String;
begin
inherited;
FWareHouseID := '';
with Select_Warehouse('','',1) do
begin
if not IsEmpty then
begin
FWareHouseID :=fieldbyname('FID').AsString ;
cxbtnWarehouse.Text := fieldbyname('Fname_l2').AsString;
end;
end;
cbCheckDate.Properties.Items.Clear;
if CliDM.E_CheckSaveStorage(6,UserInfo.LoginUser_FID,FwarehouseID,CheckDateStr,cdsCheckDate,ErrMsg) then
if not cdsCheckDate.IsEmpty then
begin
cdsCheckDate.First;
while not cdsCheckDate.Eof do
begin
CheckDateStr := cdsCheckDate.Fields[0].AsString;
cbCheckDate.Properties.Items.Add(CheckDateStr);
cdsCheckDate.Next;
end;
cbCheckDate.ItemIndex := 0;
end;
//查看历史盘点报表
cbOldCheckDate.Properties.Items.Clear;
if CliDM.E_CheckSaveStorage(7,UserInfo.LoginUser_FID,FwarehouseID,CheckDateStr,cdsOldCheckDate,ErrMsg) then
if not cdsOldCheckDate.IsEmpty then
begin
cdsOldCheckDate.First;
while not cdsOldCheckDate.Eof do
begin
CheckDateStr := cdsOldCheckDate.Fields[0].AsString;
cbOldCheckDate.Properties.Items.Add(CheckDateStr);
cdsOldCheckDate.Next;
end;
cbOldCheckDate.ItemIndex := 0;
end;
end;
end.
|
//
// Generated by JavaToPas v1.5 20150831 - 132322
////////////////////////////////////////////////////////////////////////////////
unit android.graphics.drawable.GradientDrawable_Orientation;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes;
type
JGradientDrawable_Orientation = interface;
JGradientDrawable_OrientationClass = interface(JObjectClass)
['{FB619682-2AD7-406E-B97F-CBB97A59D381}']
function _GetBL_TR : JGradientDrawable_Orientation; cdecl; // A: $4019
function _GetBOTTOM_TOP : JGradientDrawable_Orientation; cdecl; // A: $4019
function _GetBR_TL : JGradientDrawable_Orientation; cdecl; // A: $4019
function _GetLEFT_RIGHT : JGradientDrawable_Orientation; cdecl; // A: $4019
function _GetRIGHT_LEFT : JGradientDrawable_Orientation; cdecl; // A: $4019
function _GetTL_BR : JGradientDrawable_Orientation; cdecl; // A: $4019
function _GetTOP_BOTTOM : JGradientDrawable_Orientation; cdecl; // A: $4019
function _GetTR_BL : JGradientDrawable_Orientation; cdecl; // A: $4019
function valueOf(&name : JString) : JGradientDrawable_Orientation; cdecl; // (Ljava/lang/String;)Landroid/graphics/drawable/GradientDrawable$Orientation; A: $9
function values : TJavaArray<JGradientDrawable_Orientation>; cdecl; // ()[Landroid/graphics/drawable/GradientDrawable$Orientation; A: $9
property BL_TR : JGradientDrawable_Orientation read _GetBL_TR; // Landroid/graphics/drawable/GradientDrawable$Orientation; A: $4019
property BOTTOM_TOP : JGradientDrawable_Orientation read _GetBOTTOM_TOP; // Landroid/graphics/drawable/GradientDrawable$Orientation; A: $4019
property BR_TL : JGradientDrawable_Orientation read _GetBR_TL; // Landroid/graphics/drawable/GradientDrawable$Orientation; A: $4019
property LEFT_RIGHT : JGradientDrawable_Orientation read _GetLEFT_RIGHT; // Landroid/graphics/drawable/GradientDrawable$Orientation; A: $4019
property RIGHT_LEFT : JGradientDrawable_Orientation read _GetRIGHT_LEFT; // Landroid/graphics/drawable/GradientDrawable$Orientation; A: $4019
property TL_BR : JGradientDrawable_Orientation read _GetTL_BR; // Landroid/graphics/drawable/GradientDrawable$Orientation; A: $4019
property TOP_BOTTOM : JGradientDrawable_Orientation read _GetTOP_BOTTOM; // Landroid/graphics/drawable/GradientDrawable$Orientation; A: $4019
property TR_BL : JGradientDrawable_Orientation read _GetTR_BL; // Landroid/graphics/drawable/GradientDrawable$Orientation; A: $4019
end;
[JavaSignature('android/graphics/drawable/GradientDrawable_Orientation')]
JGradientDrawable_Orientation = interface(JObject)
['{ED973A4B-8482-4A74-8294-46C5DCE128D1}']
end;
TJGradientDrawable_Orientation = class(TJavaGenericImport<JGradientDrawable_OrientationClass, JGradientDrawable_Orientation>)
end;
implementation
end.
|
program HowToModelShapeUsingRecord;
uses
SwinGame;
procedure Main();
var
c : Circle;
r : Rectangle;
t : Triangle;
l : LineSegment;
begin
OpenGraphicsWindow('Model Shape Using Record', 600, 100);
LoadDefaultColors();
ClearScreen(ColorWhite);
c := CircleAt(50, 50, 30);
r := RectangleFrom(300, 20, 100, 60);
t := TriangleFrom(450, 80, 550, 80, 500, 20);
l := LineFrom(100, 40, 250, 40);
DrawCircle(ColorBlue, c);
DrawRectangle(ColorGreen, r);
DrawTriangle(ColorPink, t);
DrawLine(ColorRed, l);
RefreshScreen();
Delay(5000);
ReleaseAllResources();
end;
begin
Main();
end. |
unit Personification_AddYearReport;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxLabel, cxTextEdit, cxMaskEdit,
cxSpinEdit, ExtCtrls, cxControls, cxContainer, cxEdit, cxProgressBar,
StdCtrls, cxButtons, ActnList, FIBQuery, pFIBQuery, pFIBStoredProc,
FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet, iBase,
zProc, zMessages, Unit_zGlobal_Consts, dxBar, dxBarExtItems, cxStyles,
cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxDBData,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel,
cxClasses, cxGridCustomView, cxGrid, cxGridBandedTableView, PackageLoad,
Dates, ZcxLocateBar, AccMGMT, cxCheckBox;
type
TFAddYearReport = class(TForm)
Panel1: TPanel;
DB: TpFIBDatabase;
DSet: TpFIBDataSet;
ReadTransaction: TpFIBTransaction;
StProc: TpFIBStoredProc;
WriteTransaction: TpFIBTransaction;
StProcReport: TpFIBStoredProc;
TransactionStProcReport: TpFIBTransaction;
Panel3: TPanel;
BarManager: TdxBarManager;
dxBarDockControl1: TdxBarDockControl;
PlusBtn: TdxBarLargeButton;
MinusBtn: TdxBarLargeButton;
PlusAllBtn: TdxBarLargeButton;
GridDBTableView1: TcxGridDBTableView;
GridLevel1: TcxGridLevel;
Grid: TcxGrid;
GridClTin: TcxGridDBColumn;
GridClFio: TcxGridDBColumn;
GridClBirthDate: TcxGridDBColumn;
Styles: TcxStyleRepository;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
cxStyle3: TcxStyle;
cxStyle4: TcxStyle;
cxStyle5: TcxStyle;
cxStyle6: TcxStyle;
cxStyle7: TcxStyle;
cxStyle8: TcxStyle;
cxStyle9: TcxStyle;
cxStyle10: TcxStyle;
cxStyle11: TcxStyle;
cxStyle12: TcxStyle;
cxStyle13: TcxStyle;
cxStyle14: TcxStyle;
cxStyle15: TcxStyle;
cxStyle16: TcxStyle;
cxStyle17: TcxStyle;
cxStyle18: TcxStyle;
cxStyle19: TcxStyle;
cxStyle20: TcxStyle;
cxStyle21: TcxStyle;
cxStyle22: TcxStyle;
cxStyle23: TcxStyle;
cxStyle24: TcxStyle;
cxStyle25: TcxStyle;
cxStyle26: TcxStyle;
cxStyle27: TcxStyle;
cxStyle28: TcxStyle;
cxStyle29: TcxStyle;
cxStyle30: TcxStyle;
GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet;
GridBandedTableViewStyleSheetDevExpress: TcxGridBandedTableViewStyleSheet;
DeleteAllBtn: TdxBarLargeButton;
RefreshBtn: TdxBarLargeButton;
DSource: TDataSource;
StProcDSet: TpFIBStoredProc;
GridClMonthBeg: TcxGridDBColumn;
GridClMonthEnd: TcxGridDBColumn;
GridClYearSet: TcxGridDBColumn;
DSetUpdateTransaction: TpFIBTransaction;
YearSpinEdit: TdxBarSpinEdit;
ProgressBar: TdxBarProgressItem;
ExitBtn: TdxBarLargeButton;
BarDockLocate: TdxBarDockControl;
FormBtn: TdxBarLargeButton;
StProcAll: TpFIBStoredProc;
StProcAllTransaction: TpFIBTransaction;
is_science_mark: TcxCheckBox;
procedure ActionCancelExecute(Sender: TObject);
procedure PlusBtnClick(Sender: TObject);
procedure GridDBTableView1FocusedRecordChanged(
Sender: TcxCustomGridTableView; APrevFocusedRecord,
AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure GridClYearSetPropertiesValidate(Sender: TObject;
var DisplayValue: Variant; var ErrorText: TCaption;
var Error: Boolean);
procedure GridClMonthEndPropertiesValidate(Sender: TObject;
var DisplayValue: Variant; var ErrorText: TCaption;
var Error: Boolean);
procedure GridClMonthBegPropertiesValidate(Sender: TObject;
var DisplayValue: Variant; var ErrorText: TCaption;
var Error: Boolean);
procedure MinusBtnClick(Sender: TObject);
procedure ExitBtnClick(Sender: TObject);
procedure ProgressBarClick(Sender: TObject);
procedure YearSpinEditCurChange(Sender: TObject);
procedure PlusAllBtnClick(Sender: TObject);
procedure DeleteAllBtnClick(Sender: TObject);
procedure FormBtnClick(Sender: TObject);
private
PDB_handle:TISC_DB_HANDLE;
PLanguageIndex:Byte;
PId_Report:Integer;
PIdUser:String;
PBarLocate:TZBarLocate;
public
constructor Create(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE);reintroduce;
property Id_report:integer read PId_Report write PId_Report;
end;
implementation
uses DateUtils;
{$R *.dfm}
constructor TFAddYearReport.Create(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE);
begin
inherited Create(AOwner);
PDB_handle := ADB_Handle;
PLanguageIndex := LanguageIndex;
//------------------------------------------------------------------------------
PlusBtn.Caption := InsertBtn_Caption[PLanguageIndex];
MinusBtn.Caption := DeleteBtn_Caption[PLanguageIndex];
RefreshBtn.Caption := RefreshBtn_Caption[PLanguageIndex];
ExitBtn.Caption := ExitBtn_Caption[PLanguageIndex];
DeleteAllBtn.Caption := DelAllBtn_Caption[PLanguageIndex];
PlusAllBtn.Caption := AddAllBtn_Caption[PLanguageIndex];
FormBtn.Caption := FormBtn_Caption[PLanguageIndex];
ProgressBar.Caption := ProgressBar_Caption[PLanguageIndex];
Caption := CreateReport_Caption[PLanguageIndex];
GridClTin.Caption := GridClTin_Caption[PLanguageIndex];
GridClFio.Caption := GridClFIO_Caption[PLanguageIndex];
GridClYearSet.Caption := GridClYear_Caption[PLanguageIndex];
GridClMonthBeg.Caption := GridClBegPeriod_Caption[PLanguageIndex];
GridClMonthEnd.Caption := GridClEndPeriod_Caption[PLanguageIndex];
GridClBirthDate.Caption := GridClBirthDate_Caption[PLanguageIndex];
YearSpinEdit.Caption := GridClYear_Caption[PLanguageIndex];
//------------------------------------------------------------------------------
PBarLocate:=TZBarLocate.Create(BarManager);
PBarLocate.DataSet := DSet;
PBarLocate.BorderStyle := bbsNone;
PBarLocate.AddLocateItem('TIN',
GridClTin.Caption,
[loCaseInsensitive,loPartialKey]);
PBarLocate.AddLocateItem('FIO',
GridClFIO.Caption,
[loCaseInsensitive,loPartialKey]);
PBarLocate.DigitalField := 'TIN';
PBarLocate.DockControl := BarDockLocate;
//------------------------------------------------------------------------------
DB.Handle := PDB_handle;
PIdUser:=IntToStr(GetUserId);
YearSpinEdit.Value := YearOf(Date)-1;
DSet.SQLs.SelectSQL.Text := 'SELECT * FROM Z_PERSONIFICATION_REESTR_S('+PIdUser+')';
DSet.SQLs.UpdateSQL.Text := 'execute procedure Z_PERSONIFICATION_REESTR_U('+PIdUser+',?TIN,?FIO,?BIRTH_DATE,?MONTH_BEG,?MONTH_END,?YEAR_SET)';
DSet.SQLs.RefreshSQL.Text := 'SELECT * FROM Z_PERSONIFICATION_REESTR_S_BY_K('+pIdUser+',?TIN)';
DSet.Open;
end;
procedure TFAddYearReport.ActionCancelExecute(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TFAddYearReport.PlusBtnClick(Sender: TObject);
var Man:Variant;
begin
Man:=LoadPeopleModal(Self,PDB_handle);
if VarArrayDimCount(Man)>0 then
begin
if not DSet.Locate('TIN',Man[5],[loCaseInsensitive]) then
try
StProcDSet.StoredProcName := 'Z_PERSONIFICATION_REESTR_I';
StProcDSet.Transaction.StartTransaction;
StProcDSet.Prepare;
StProcDSet.ParamByName('ID_USER').AsInteger := StrToInt(pIdUser);
StProcDSet.ParamByName('TIN').AsString := Man[5];
StProcDSet.ParamByName('BIRTH_DATE').AsDate := man[6];
StProcDSet.ParamByName('FIO').asString := VarToStrDef(Man[1],'')+' '+VarToStrDef(Man[2],'')+' '+VarToStrDef(Man[3],'');
StProcDSet.ExecProc;
StProcDSet.Transaction.Commit;
DSet.SQLs.InsertSQL.Text := 'execute procedure Z_EMPTY_PROC';
DSet.SQLs.RefreshSQL.Text := 'SELECT * FROM Z_PERSONIFICATION_REESTR_S_BY_K('+pIdUser+','+Man[5]+')';
DSet.Insert;
DSet.Post;
DSet.SQLs.RefreshSQL.Text := 'SELECT * FROM Z_PERSONIFICATION_REESTR_S_BY_K('+pIdUser+',?TIN)';
DSet.SQLs.InsertSQL.Text := '';
except
on e:Exception do
begin
ZShowMessage(Error_Caption[PLanguageIndex],e.Message,mtError,[mbOK]);
StProcDSet.Transaction.Rollback;
end;
end;
end;
end;
procedure TFAddYearReport.GridDBTableView1FocusedRecordChanged(
Sender: TcxCustomGridTableView; APrevFocusedRecord,
AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
begin
if DSetUpdateTransaction.InTransaction then DSetUpdateTransaction.Commit;
end;
procedure TFAddYearReport.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if ReadTransaction.InTransaction then ReadTransaction.Commit;
end;
procedure TFAddYearReport.GridClYearSetPropertiesValidate(Sender: TObject;
var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean);
begin
if DSetUpdateTransaction.InTransaction then
begin
DSet['YEAR_SET']:=DisplayValue;
DSet.Edit;
DSet.Post;
end;
end;
procedure TFAddYearReport.GridClMonthEndPropertiesValidate(Sender: TObject;
var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean);
begin
if DSetUpdateTransaction.InTransaction then
begin
DSet['MONTH_END']:=DisplayValue;
DSet.Edit;
DSet.Post;
end;
end;
procedure TFAddYearReport.GridClMonthBegPropertiesValidate(Sender: TObject;
var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean);
begin
if DSetUpdateTransaction.InTransaction then
begin
DSet['MONTH_BEG']:=DisplayValue;
DSet.Edit;
DSet.Post;
end;
end;
procedure TFAddYearReport.MinusBtnClick(Sender: TObject);
begin
if ZShowMessage(Caption_Delete[PLanguageIndex],DeleteRecordQuestion_Text[PLanguageIndex],mtConfirmation,[mbYes,mbNo])=mrYes
then
try
StProcDSet.StoredProcName := 'Z_PERSONIFICATION_REESTR_D';
StProcDSet.Transaction.StartTransaction;
StProcDSet.Prepare;
StProcDSet.ParamByName('ID_USER').AsInteger := StrToInt(pIdUser);
StProcDSet.ParamByName('TIN').AsString := DSet['TIN'];
StProcDSet.ExecProc;
StProcDSet.Transaction.Commit;
DSet.SQLs.DeleteSQL.Text := 'execute procedure Z_EMPTY_PROC';
DSet.Delete;
DSet.SQLs.RefreshSQL.Text := 'SELECT * FROM Z_PERSONIFICATION_REESTR_S_BY_K('+pIdUser+',?TIN)';
except
on e:Exception do
begin
ZShowMessage(Error_Caption[PLanguageIndex],e.Message,mtError,[mbOK]);
StProcDSet.Transaction.Rollback;
end;
end;
end;
procedure TFAddYearReport.ExitBtnClick(Sender: TObject);
begin
Close;
end;
procedure TFAddYearReport.ProgressBarClick(Sender: TObject);
begin
ShowMessage('1');
end;
procedure TFAddYearReport.YearSpinEditCurChange(Sender: TObject);
begin
YearSpinEdit.Text:=YearSpinEdit.CurText;
end;
procedure TFAddYearReport.PlusAllBtnClick(Sender: TObject);
begin
try
StProcAll.StoredProcName := 'Z_PERSONIFICATION_GET_SPISOK';
StProcAll.Transaction.StartTransaction;
StProcAll.Prepare;
StProcAll.ParamByName('ID_USER').AsInteger := StrToInt(pIdUser);
StProcAll.ParamByName('NUM_YEAR').AsInteger := StrToInt(YearSpinEdit.text);
StProcAll.ExecProc;
StProcAll.Transaction.Commit;
DSet.CloseOpen(True);
except
on e:Exception do
begin
ZShowMessage(Error_Caption[PLanguageIndex],e.Message,mtError,[mbOK]);
StProcAll.Transaction.Rollback;
end;
end;
end;
procedure TFAddYearReport.DeleteAllBtnClick(Sender: TObject);
begin
try
StProcAll.StoredProcName := 'Z_PERSONIFICATION_CLEAR_SPISOK';
StProcAll.Transaction.StartTransaction;
StProcAll.Prepare;
StProcAll.ParamByName('ID_USER').AsInteger := StrToInt(pIdUser);
StProcAll.ExecProc;
StProcAll.Transaction.Commit;
DSet.CloseOpen(True);
except
on e:Exception do
begin
ZShowMessage(Error_Caption[PLanguageIndex],e.Message,mtError,[mbOK]);
StProcAll.Transaction.Rollback;
end;
end;
end;
procedure TFAddYearReport.FormBtnClick(Sender: TObject);
var MR:TModalResult;
begin
MR:=mrNone;
try
self.Enabled:=False;
GridDBTableView1.OptionsCustomize.ColumnSorting := False;
GridDBTableView1.OptionsCustomize.ColumnSorting := False;
GridDBTableView1.DataController.DataSource := nil;
BarManager.BarByName('BarProgress').Visible := True;
try
StProcReport.StoredProcName := 'Z_PERSONIFICATION_REPORT_I';
StProcReport.Transaction.StartTransaction;
StProcReport.Prepare;
StProcReport.ExecProc;
Id_Report := StProcReport.ParamByName('ID').AsInteger;
StProcReport.Transaction.Commit;
ProgressBar.Max := DSet.RecordCount;
DSet.First;
StProc.StoredProcName := 'Z_PERSONIFACATION';
while not DSet.Eof do
begin
ProgressBar.Position := ProgressBar.Position+1;
Self.Update;
StProc.Transaction.StartTransaction;
StProc.Prepare;
StProc.ParamByName('KOD_SETUP_B').AsInteger := PeriodToKodSetup(DSet['YEAR_SET'],DSET['MONTH_BEG']);
StProc.ParamByName('KOD_SETUP_E').AsInteger := PeriodToKodSetup(DSet['YEAR_SET'],DSET['MONTH_END']);
StProc.ParamByName('ID_REPORT').AsInteger := Id_Report;
StProc.ParamByName('TIN').AsString := DSet['TIN'];
StProc.ParamByName('mark_science').AsInteger:= Integer(is_science_mark.Checked);
StProc.ExecProc;
StProc.Transaction.Commit;
DSet.Next;
end;
ReadTransaction.Commit;
MR:=mrYes;
except
on E:Exception do
begin
ZShowMessage(Error_Caption[PLanguageIndex],varToStrDef(DSet['TIN'],'')+#13+
varToStrDef(Dset['FIO'],'')+#13+
e.Message,mtError,[mbOk]);
if WriteTransaction.InTransaction then WriteTransaction.Rollback;
If TransactionStProcReport.InTransaction then TransactionStProcReport.Rollback;
if ReadTransaction.InTransaction then ReadTransaction.Rollback;
end;
end;
finally
self.Enabled:=True;
GridDBTableView1.OptionsCustomize.ColumnSorting := True;
GridDBTableView1.OptionsCustomize.ColumnSorting := True;
ModalResult:=MR;
GridDBTableView1.DataController.DataSource := DSource;
end;
end;
end.
|
(*
Fractal3D
based on Ivan Lee Herring source code
*)
unit fmain;
interface
uses
Winapi.Windows,
Winapi.Messages,
Winapi.MMSystem,
System.Types,
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Imaging.jpeg,
Vcl.Clipbrd,
Vcl.Printers,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.Buttons,
Vcl.ExtCtrls,
Vcl.Menus,
Vcl.ComCtrls,
Vcl.ExtDlgs,
Fractal;
type
TDrawingTool =
(dtEllipse, dtCSEllipse, dtPolygon,
dtVTriangle, dtTriangle, dtTSTriangle,
dtVPRectangle, dtVERectangle, dtVSRectangle,
dtVDRectangle, dtVTRectangle, dtVFRectangle, dtVNRectangle,
dtVMRectangle, dtVARectangle, dtVWRectangle, dtVCRectangle,
dtVBRectangle, dtVRectangle, dtRectangle, dtRoundRect,
dtLine, dtPBrush);
TMainForm = class(TForm)
MainMenu: TMainMenu;
FileOpenItem: TMenuItem;
FileSaveItem: TMenuItem;
FileSaveAsItem: TMenuItem;
FilePrintItem: TMenuItem;
FilePrintSetupItem: TMenuItem;
FileExitItem: TMenuItem;
EditCutItem: TMenuItem;
EditCopyItem: TMenuItem;
EditPasteItem: TMenuItem;
HelpContentsItem: TMenuItem;
HelpSearchItem: TMenuItem;
HelpHowToUseItem: TMenuItem;
HelpAboutItem: TMenuItem;
PrintDialog: TPrintDialog;
PrintSetupDialog: TPrinterSetupDialog;
SpeedBar: TPanel;
Options: TMenuItem;
Fractals1: TMenuItem;
Math1: TMenuItem;
ScrollBox1: TScrollBox;
Image2: TImage;
ImageSize1: TMenuItem;
BackgroundColor1: TMenuItem;
FV_IS640x480: TMenuItem;
FV_IS800x600: TMenuItem;
FV_IS1024x768: TMenuItem;
FV_IS2048x1536: TMenuItem;
FV_IS1280x960: TMenuItem;
FV_IS1600x1200: TMenuItem;
FV_IS1920x1440: TMenuItem;
FV_IS2400x1800: TMenuItem;
FV_IS3072x2304: TMenuItem;
Red1: TMenuItem;
Green1: TMenuItem;
Blue1: TMenuItem;
Black1: TMenuItem;
White1: TMenuItem;
Yellow1: TMenuItem;
HintPanel: TPanel;
OpenPictureDialog1: TOpenPictureDialog;
SavePictureDialog1: TSavePictureDialog;
N6: TMenuItem;
ImageDraw: TMenuItem;
ImageAnnotate: TMenuItem;
ImageSelectFont: TMenuItem;
FontDialog1: TFontDialog;
Aqua1: TMenuItem;
Fuchsia1: TMenuItem;
Gray1: TMenuItem;
LimeGreen1: TMenuItem;
Purple1: TMenuItem;
Teal1: TMenuItem;
Silver1: TMenuItem;
OliveGreen1: TMenuItem;
NavyBlue1: TMenuItem;
Maroon1: TMenuItem;
ImageDoneAlarm: TMenuItem;
PrintBig1: TMenuItem;
ForegroundColorSet1: TMenuItem;
LandformsSet: TMenuItem;
Win16Set: TMenuItem;
N5: TMenuItem;
RedRanger256: TMenuItem;
GreenGoblin256: TMenuItem;
BlueMeanie256: TMenuItem;
PurpleReigns256: TMenuItem;
YellowSnow256: TMenuItem;
AquaMarine256: TMenuItem;
SmogFog256: TMenuItem;
N7: TMenuItem;
ColorPicker256: TMenuItem;
FractalBlack1: TMenuItem;
PopupMenu1: TPopupMenu;
UnZoom1to1: TMenuItem;
PanThis: TMenuItem;
HiddenFX: TPanel;
MousePanel: TPanel;
ProgressBar1: TProgressBar;
ColorPicker16: TMenuItem;
RGB16: TMenuItem;
Mine1: TMenuItem;
Bomb1: TMenuItem;
Loaded16: TMenuItem;
Loaded256: TMenuItem;
LoadedToo56: TMenuItem;
ImageDoneVoices: TMenuItem;
EditCropItem: TMenuItem;
EditClearAllItem: TMenuItem;
ZoomToWindow: TMenuItem;
ZoomMouse: TMenuItem;
FV_IS2560x1920: TMenuItem;
FV_IS3200x2400: TMenuItem;
FV_IS4096x3072: TMenuItem;
FV_IS4000x3000: TMenuItem;
FV_IS3840x2880: TMenuItem;
EditPasteIntoItem: TMenuItem;
EditCopyAreaItem: TMenuItem;
ZoomOut1: TMenuItem;
N12: TMenuItem;
XYZ3D: TMenuItem;
ResizeImage: TMenuItem;
Panel1: TPanel;
OpenButton: TSpeedButton;
SaveButton: TSpeedButton;
SaveAsButton: TSpeedButton;
PrintButton: TSpeedButton;
PrintSetupButton: TSpeedButton;
Croparea: TSpeedButton;
CutButton: TSpeedButton;
CopyButton: TSpeedButton;
PasteButton: TSpeedButton;
PasteArea: TSpeedButton;
ImageDrawBtn: TSpeedButton;
IAnnotateBtn: TSpeedButton;
SelectFontBtn: TSpeedButton;
HelpContentsBtn: TSpeedButton;
TopicSearchBtn: TSpeedButton;
AboutButton: TSpeedButton;
ExitButton: TSpeedButton;
Preview1: TMenuItem;
MineColor: TPanel;
BombColor: TPanel;
ColorDialog1: TColorDialog;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormResize(Sender: TObject);
procedure SetImageSize;
procedure ShowHint(Sender: TObject);
procedure FileOpen(Sender: TObject);
procedure FileSave(Sender: TObject);
procedure FileSaveAs(Sender: TObject);
procedure PrintBig1Click(Sender: TObject);
procedure FilePrint(Sender: TObject);
procedure FilePrintSetup(Sender: TObject);
procedure FileExit(Sender: TObject);
procedure HelpContents(Sender: TObject);
procedure HelpSearch(Sender: TObject);
procedure HelpHowToUse(Sender: TObject);
procedure HelpAbout(Sender: TObject);
procedure Image2MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure Image2MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure Image2MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure ImageDrawClick(Sender: TObject);
procedure ImageAnnotateClick(Sender: TObject);
procedure ImageSelectFontClick(Sender: TObject);
procedure Fractals1Click(Sender: TObject);
procedure Math1Click(Sender: TObject);
procedure FalseSize;
procedure FV_IS640x480Click(Sender: TObject);
procedure FV_IS800x600Click(Sender: TObject);
procedure FV_IS1024x768Click(Sender: TObject);
procedure FV_IS1280x960Click(Sender: TObject);
procedure FV_IS1600x1200Click(Sender: TObject);
procedure FV_IS1920x1440Click(Sender: TObject);
procedure FV_IS2048x1536Click(Sender: TObject);
procedure FV_IS2400x1800Click(Sender: TObject);
procedure FV_IS3072x2304Click(Sender: TObject);
procedure FV_IS4096x3072Click(Sender: TObject);
procedure FV_IS4000x3000Click(Sender: TObject);
procedure FV_IS3840x2880Click(Sender: TObject);
procedure FV_IS3200x2400Click(Sender: TObject);
procedure FV_IS2560x1920Click(Sender: TObject);
procedure FalseColors;
procedure Black1Click(Sender: TObject);
procedure Maroon1Click(Sender: TObject);
procedure Green1Click(Sender: TObject);
procedure OliveGreen1Click(Sender: TObject);
procedure NavyBlue1Click(Sender: TObject);
procedure Purple1Click(Sender: TObject);
procedure Teal1Click(Sender: TObject);
procedure Gray1Click(Sender: TObject);
procedure Silver1Click(Sender: TObject);
procedure Red1Click(Sender: TObject);
procedure LimeGreen1Click(Sender: TObject);
procedure Yellow1Click(Sender: TObject);
procedure Blue1Click(Sender: TObject);
procedure Fuchsia1Click(Sender: TObject);
procedure Aqua1Click(Sender: TObject);
procedure White1Click(Sender: TObject);
procedure Mine1Click(Sender: TObject);
procedure Bomb1Click(Sender: TObject);
procedure FractalBlack1Click(Sender: TObject);
procedure False16;
procedure Win16SetClick(Sender: TObject);
procedure LandformsSetClick(Sender: TObject);
procedure ColorPicker16Click(Sender: TObject);
procedure RGB16Click(Sender: TObject);
procedure Loaded16Click(Sender: TObject);
procedure FalseSets;
procedure BlueMeanie256Click(Sender: TObject);
procedure AquaMarine256Click(Sender: TObject);
procedure GreenGoblin256Click(Sender: TObject);
procedure YellowSnow256Click(Sender: TObject);
procedure PurpleReigns256Click(Sender: TObject);
procedure RedRanger256Click(Sender: TObject);
procedure SmogFog256Click(Sender: TObject);
procedure ColorPicker256Click(Sender: TObject);
procedure Loaded256Click(Sender: TObject);
procedure LoadedToo56Click(Sender: TObject);
procedure ImageDoneVoicesClick(Sender: TObject);
procedure AlarmBtnClick(Sender: TObject);
procedure EditCut(Sender: TObject);
procedure EditCopy(Sender: TObject);
procedure EditPaste(Sender: TObject);
procedure EditPasteIntoItemClick(Sender: TObject);
procedure EditCropItemClick(Sender: TObject);
procedure EditCopyAreaItemClick(Sender: TObject);
procedure EditClearAllItemClick(Sender: TObject);
procedure UnZoom;
procedure UnZoom1to1Click(Sender: TObject);
procedure ZoomOut1Click(Sender: TObject);
procedure ZoomMachine;
procedure ZoomToWindowClick(Sender: TObject);
procedure ZoomMouseClick(Sender: TObject);
procedure ZoomMouseDo;
procedure Image2Progress(Sender: TObject; Stage: TProgressStage;
PercentDone: Byte; RedrawNow: Boolean; const R: TRect;
const Msg: string);
procedure XYZ3DClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure ResizeImageClick(Sender: TObject);
procedure Preview1Click(Sender: TObject);
procedure BombColorClick(Sender: TObject);
procedure MineColorClick(Sender: TObject);
procedure DoMiner;
procedure DoBomber;
public
Drawing: Boolean; // field to track whether button was pressed
Origin, MovePt: TPoint; // fields to store points
DrawingTool: TDrawingTool;
procedure DrawShape (TopLeft, BottomRight, Tri, Quad: TPoint; AMode: TPenMode);
procedure ChangeFileName;
procedure WriteDataFile;
procedure ReadDataFile;
procedure FileOpener;
procedure FileSaver;
procedure Set16Colors;
procedure SiliconSets;
procedure OverBit;
procedure ImageOverDone;
procedure PlaySound(WavFileName: string);
procedure EditCropper;
procedure DoImageDone;
procedure DoImageStart;
end;
var
MainForm: TMainForm;
BitmapF: TBitmap; { temporary variable to hold the bitmap }
//==================================================================
implementation
//==================================================================
uses
FUGlobal,
FAbout,
{FmxUtils,}
FMath,
FGMath,
FAnno,
FGStyle,
FMJPEG,
FMResize,
//FFractalPreviewForm, ?
FXYZ3D,
Fjul,
FGLfrm {FGlForm, FMathGL,};
{$R *.DFM}
{---------------------------------------------------------------------}
procedure TMainForm.FileExit(Sender: TObject);
begin
Close;
end;
procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
isReallyGone := True;
dtmGlForm.Close;
{ XYZGL.Close; }
{ MathGL.Close; }
MainFormX := MainForm.left;
MainFormY := MainForm.top;
DoSaver;
{ Nil out the array }
SetLength(ManMatrix, 0, 0);
{ kill bitmap(s) ? }
BitmapF.Free;
{ if (bBrushHasBitmap = True) then
begin
MainForm.Image2.Canvas.Brush.Bitmap := nil;
DIYSBitmap.Free;
end; }
end;
(* *********************************************************** *)
procedure TMainForm.FormCreate(Sender: TObject);
var
i: Integer;
begin
{ LOAD FRACTALS.F3D and SET these }
if FileExists(ExtractFilePath(ParamStr(0)) + 'fractal.pof') then
DoLoader
else
begin
// FractalFont := FontDialog1.Font;
StartedNameNumber := 'alle alle in free'; { F3197432-460875 }
Started := Date;
Colorreg := 3;
SystemInfoFormX := 113;
SystemInfoFormY := 113;
MessageX := 113;
MessageY := 113;
DIYStyleFormX := 560;
DIYStyleFormY := 460;
AnnotationFormX := 440;
AnnotationFormY := 440;
XYZ3DFormX := 488;
XYZ3DFormY := 0;
JPEGFormX := 44;
JPEGFormY := 44;
ResizeFormX := 44;
ResizeFormY := 44;
XYZGLX := 44;
XYZGLY := 44;
MathGLX := 44;
MathGLY := 44;
// some things do not exist until after created...
FractalDir := ExtractFilePath(ParamStr(0));
DemsDir := FractalDir;
FormulasDir := FractalDir;
IamDone := 0;
V1Color := clRed;
V2Color := clLime;
V3Color := clBlue;
V4Color := clYellow;
BombBackgroundColor := clAqua;
MineBackgroundColor := clPurple;
Color16Name := 'COLOR16FILE.1CP';
Color256Name := 'COLORFILE.2CP';
Color256TooName := 'COLORFILE.2CP';
for i := 0 to 15 do
ColorArray[i] := RGB(0, 0, 255 - (i * 12));
for i := 0 to 15 do
ColorArray[i + 16] := RGB(0, 255 - (i * 12), 255 - (i * 12));
for i := 0 to 15 do
ColorArray[i + 32] := RGB(0, 255 - (i * 12), 0);
for i := 0 to 15 do
ColorArray[i + 48] := RGB(255 - (i * 12), 255 - (i * 12), 0);
for i := 0 to 15 do
ColorArray[i + 64] := RGB(255 - (i * 12), 0, 255 - (i * 12));
for i := 0 to 15 do
ColorArray[i + 80] := RGB(255 - (i * 12), 0, 0);
for i := 0 to 15 do
ColorArray[i + 96] := RGB(255 - (i * 12), 255 - (i * 12), 255 - (i * 12));
for i := 0 to 15 do
ColorArray[i + 112] := RGB(0, 0, 255 - (i * 14));
for i := 0 to 15 do
ColorArray[i + 128] := RGB(0, 255 - (i * 14), 255 - (i * 14));
for i := 0 to 15 do
ColorArray[i + 144] := RGB(0, 255 - (i * 14), 0);
for i := 0 to 15 do
ColorArray[i + 160] := RGB(255 - (i * 14), 255 - (i * 14), 0);
for i := 0 to 15 do
ColorArray[i + 176] := RGB(255 - (i * 14), 0, 255 - (i * 14));
for i := 0 to 15 do
ColorArray[i + 192] := RGB(255 - (i * 14), 0, 0);
for i := 0 to 15 do
ColorArray[i + 208] := RGB(0, 255 - (i * 14), 0);
for i := 0 to 15 do
ColorArray[i + 224] := RGB(0, 255 - (i * 14), 255 - (i * 14));
for i := 0 to 15 do
ColorArray[i + 240] := RGB(255 - (i * 14), 0, 0);
Color256S := 2;
MainForm.AquaMarine256.Checked := True;
{ MainForm.SiliconSets; }
{ 2: } for i := 0 to 255 do
begin
Colors[0, i] := 0;
Colors[1, i] := 255 - i;
Colors[2, i] := 255 - i;
end;
FBackGroundColor := clBlue;
MainForm.Blue1.Checked := True;
{ MainForm.FalseColors; }
RGBArray[0, 0] := 0;
RGBArray[1, 0] := 0;
RGBArray[2, 0] := 128;
RGBArray[0, 1] := 0;
RGBArray[1, 1] := 0;
RGBArray[2, 1] := 255;
RGBArray[0, 2] := 0;
RGBArray[1, 2] := 128;
RGBArray[2, 2] := 128;
RGBArray[0, 3] := 0;
RGBArray[1, 3] := 255;
RGBArray[2, 3] := 255;
RGBArray[0, 4] := 255;
RGBArray[1, 4] := 255;
RGBArray[2, 4] := 0;
RGBArray[0, 5] := 128;
RGBArray[1, 5] := 128;
RGBArray[2, 5] := 0;
RGBArray[0, 6] := 0;
RGBArray[1, 6] := 255;
RGBArray[2, 6] := 0;
RGBArray[0, 7] := 0;
RGBArray[1, 7] := 128;
RGBArray[2, 7] := 0;
RGBArray[0, 8] := 128;
RGBArray[1, 8] := 128;
RGBArray[2, 8] := 128;
RGBArray[0, 9] := 255;
RGBArray[1, 9] := 0;
RGBArray[2, 9] := 255;
RGBArray[0, 10] := 128;
RGBArray[1, 10] := 0;
RGBArray[2, 10] := 128;
RGBArray[0, 11] := 192;
RGBArray[1, 11] := 192;
RGBArray[2, 11] := 192;
RGBArray[0, 12] := 255;
RGBArray[1, 12] := 0;
RGBArray[2, 12] := 0;
RGBArray[0, 13] := 128;
RGBArray[1, 13] := 0;
RGBArray[2, 13] := 0;
RGBArray[0, 14] := 255;
RGBArray[1, 14] := 255;
RGBArray[2, 14] := 255;
RGBArray[0, 15] := 0;
RGBArray[1, 15] := 0;
RGBArray[2, 15] := 0;
Colorset16 := 3; { MainForm.False16; }
MainForm.LandformsSet.Checked := True;
DoSaver;
end;
{ SET UP VARIABLES ALWAYS }
{
Left := MainFormX;
Top := MainFormY;
Height := 565;
Width := 679;
}
FYImageX := 640;
FYImageY := 480;
BombColor.Color := BombBackgroundColor;
MineColor.Color := MineBackgroundColor;
{ FontDialog1.Font:=FractalFont; }
ImageOverDone; { sets IamDone Voice or Noise }
{ MainForm.ImageOverDone; }{ sets iamdone ImageDoneAlarmb }
SetImageSize;
FalseColors;
False16;
FalseSets;
Application.OnHint := ShowHint;
Application.HelpFile := ExtractFilePath(ParamStr(0)) + 'FRACTAL3D.HLP';
OpenPictureDialog1.InitialDir := FractalDir;
SavePictureDialog1.InitialDir := FractalDir;
{ ForceCurrentDirectory := True; }
FractalFilename := 'F_000000000.BMP';
OpenPictureDialog1.FileName := FractalFilename;
OpenPictureDialog1.Title := 'Fractal File Selection';
LastKnownFunction := 0;
bRotatingImage := False;
bRotateImage := False;
Julia := False;
bJuliaBase := False;
bMan3d := False;
bJulia3d := False;
bFractalMaxed := False;
DoSanMarcosDragon := False;
Drawing := False;
Fractaling := False;
bPointing := False;
bBrushHasBitmap := False;
bVista := False;
iMadeMountains := -1;
bSaveTheMountains := False;
bMousing := False;
bLightning := False;
bVistaLive := False;
DIYAnnotate := False;
ITriangling := 0;
ImageZoomRatio := 0;
ImageZoomRatioEx := 0;
ZoomingOn := False;
bZoomMousing := False;
WasZooming := False;
isReallyGone := False;
DIYL.X := 0;
DIYL.Y := 0;
DIYZ := 0;
DIYE := 0;
DrawingTool_PBrush_Width := 10;
FXMax := 1.2;
FXMin := -2.0;
FYMax := 1.2;
FYMin := -1.2;
FHQ := -0.003483;
FVP := 0.268545;
max_iterations := 64;
Start_Col := 0;
Color_Option := 0;
BitmapF := TBitmap.Create; { construct the bitmap object }
BitmapF.PixelFormat := MyPixelFormat; { pf24bit; }
BitmapF.Width := FYImageX; { assign the initial width... }
BitmapF.Height := FYImageY; { ...and the initial height }
Image2.Picture.Graphic.assign(BitmapF);
{ VImage.Picture.Graphic.assign(BitmapF); }
{ REST ALL ZOOOOMS }
{ assign the bitmap to the image control }
SetLength(ManMatrix, FYImageX, FYImageY);
end;
procedure TMainForm.ShowHint(Sender: TObject);
begin
HintPanel.Caption := Application.Hint;
end;
procedure TMainForm.FormResize(Sender: TObject);
begin { }
Height := 565;
Width := 679;
end;
(* *********************************************************** *)
procedure TMainForm.SetImageSize;
begin
MainForm.FalseSize;
case FYImageX of
640: MainForm.FV_IS640x480.Checked := True;
800: MainForm.FV_IS800x600.Checked := True;
1024: MainForm.FV_IS1024x768.Checked := True;
1280: MainForm.FV_IS1280x960.Checked := True;
1600: MainForm.FV_IS1600x1200.Checked := True;
1920: MainForm.FV_IS1920x1440.Checked := True;
2048: MainForm.FV_IS2048x1536.Checked := True;
2400: MainForm.FV_IS2400x1800.Checked := True;
2560: MainForm.FV_IS2560x1920.Checked := True;
3072: MainForm.FV_IS3072x2304.Checked := True;
3200: MainForm.FV_IS3200x2400.Checked := True;
3840: MainForm.FV_IS3840x2880.Checked := True;
4000: MainForm.FV_IS4000x3000.Checked := True;
4096: MainForm.FV_IS4096x3072.Checked := True;
else
DoMessages(24);
end;
end;
procedure TMainForm.FormShow(Sender: TObject);
begin { }
{ Check Clipboard:
if available then enable clipboard items }
if Clipboard.HasFormat(CF_BITMAP) then
begin
PasteButton.Enabled := True;
PasteArea.Enabled := True;
EditPasteItem.Enabled := True;
EditPasteIntoItem.Enabled := True;
end
else
begin
PasteButton.Enabled := False;
PasteArea.Enabled := False;
EditPasteItem.Enabled := False;
EditPasteIntoItem.Enabled := False;
end;
end;
procedure TMainForm.FormActivate(Sender: TObject);
begin
{ Check Clipboard:
if available then enable clipboard items }
if Clipboard.HasFormat(CF_BITMAP) then
begin
PasteButton.Enabled := True;
PasteArea.Enabled := True;
EditPasteItem.Enabled := True;
EditPasteIntoItem.Enabled := True;
end
else
begin
PasteButton.Enabled := False;
PasteArea.Enabled := False;
EditPasteItem.Enabled := False;
EditPasteIntoItem.Enabled := False;
end;
end;
(* *********************************************************** *)
{ MovePt must be set to the endpoint of each intermediate line,
so you can use MovePt and Origin to erase that
line the next time a line is drawn: }
(* *********************************************************** *)
procedure TMainForm.Image2MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if (Cropping > 0) then
begin
DrawingTool := dtRectangle;
Drawing := True;
Image2.Canvas.MoveTo(X, Y);
Origin := Point(X, Y);
MovePt := Point(X, Y); { keep track of where this move was }
HintPanel.Caption := Format('Origin: (%d, %d)', [X, Y]);
end
else if (bZoomMousing) then
begin
DrawingTool := dtRectangle;
Drawing := True;
Image2.Canvas.MoveTo(X, Y);
Origin := Point(X, Y);
MovePt := Point(X, Y); { keep track of where this move was }
HintPanel.Caption := Format('Origin: (%d, %d)', [X, Y]);
end
else if (ImageDraw.Checked = True) then
begin
Drawing := True;
Image2.Canvas.MoveTo(X, Y);
Origin := Point(X, Y);
MovePt := Point(X, Y); { keep track of where this move was }
HintPanel.Caption := Format('Origin: (%d, %d)', [X, Y]);
end
else if (Fractaling = True) then
begin
{ Choose Box type, Click center and expand at correct ratio, or normal }
Drawing := True;
DrawingTool := dtRectangle;
Image2.Canvas.MoveTo(X, Y);
Origin := Point(X, Y);
MovePt := Point(X, Y); { keep track of where this move was }
HintPanel.Caption := Format('Origin: (%d, %d)', [X, Y]);
end
else
(* If ((bVistaLive= True) and (Drawing= True)) then begin
Image1.Canvas.MoveTo(X, Y);
{ Image1.Canvas.MoveTo(Origin.X, Origin.Y);
Origin := Point(X, Y);} {already going this Triangle}
MovePt := Point(X, Y); { keep track of where this move was }
HintPanel.Caption:= Format('Origin: (%d, %d)', [X, Y]);
end; *)
if ((bVistaLive = True) and (Drawing <> True)) then
begin
Drawing := True;
Image2.Canvas.MoveTo(X, Y);
Origin := Point(X, Y);
MovePt := Point(X, Y);
{ keep track of where this move was }
DIYXY.X := X;
DIYXY.Y := Y;
HintPanel.Caption := Format('Origin: (%d, %d)', [X, Y]);
end;
{ If (Drawing = True) then Image1.Canvas.Pen.Color:= clWhite; }
end;
{ Now you get a “rubber band” effect when you draw the line.
By changing the pen’s mode to pmNotXor, you have it
combine your line with the background pixels. When you
go to erase the line, you’re actually setting the pixels back
to the way they were. By changing the pen mode back to pmCopy
(its default value) after drawing the lines, you ensure that
the pen is ready to do its final drawing when you
release the mouse button. }
(* *********************************************************** *)
procedure TMainForm.Image2MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
var
Xs, Ys: string;
TXMin, TYMax: Extended;
begin
if Drawing then
begin
if ((DrawingTool = dtVRectangle) or (DrawingTool = dtVTriangle) or
(DrawingTool = dtTSTriangle) or (DrawingTool = dtTriangle)) then
begin
if (ITriangling = 2) then
begin
DrawShape(Origin, MovePt, DIYX3Y3, DIYX4Y4, pmNotXor);
MovePt := Point(X, Y);
DIYX4Y4.X := X;
DIYX4Y4.Y := Y;
DrawShape(Origin, MovePt, DIYX3Y3, DIYX4Y4, pmNotXor);
end
else if (ITriangling = 1) then
begin
DrawShape(Origin, MovePt, DIYX3Y3, DIYX4Y4, pmNotXor);
MovePt := Point(X, Y);
DIYX3Y3.X := X;
DIYX3Y3.Y := Y;
DIYX4Y4.X := X;
DIYX4Y4.Y := Y;
DrawShape(Origin, MovePt, DIYX3Y3, DIYX4Y4, pmNotXor);
end
else if (ITriangling = 0) then
begin
DrawShape(Origin, MovePt, DIYX3Y3, DIYX4Y4, pmNotXor);
MovePt := Point(X, Y);
DrawShape(Origin, MovePt, DIYX3Y3, DIYX4Y4, pmNotXor);
end;
end
else
begin
{ Fractal: Choose Box type, Click center and expand at correct ratio, or normal }
DrawShape(Origin, MovePt, DIYX3Y3, DIYX4Y4, pmNotXor);
MovePt := Point(X, Y);
DrawShape(Origin, MovePt, DIYX3Y3, DIYX4Y4, pmNotXor);
end;
end;
{ Procedure to display X,Y according to
graphic coordinate system }
{ Coords(X,Y);
Case of Active Translation
FX,FY
Origin in center of screen
Origin at bottom left
Scale - Zoom Resolution
... Output to:
Mouse panel: X,Y
Hint Panel: Origin.. first moused point
FX panel: Translated X,Y }
str(X, Xs);
str(Y, Ys);
MousePanel.Caption := ' X: ' + Xs + ', Y: ' + Ys;
{ MousePanel.Caption := Format(' Current: (%d, %d)', [X, Y]); }
if (Fractaling = True) then
begin
{ Choose Box type, Click center and expand at correct ratio, or normal }
bMousing := False;
TXMin := FXMin + (FXMax - FXMin) / (Image2.Width - 1) * X;
TYMax := FYMax - (FYMax - FYMin) / (Image2.Height - 1) * Y;
str(TXMin: 24: 20, Xs);
str(TYMax: 24: 20, Ys);
HiddenFX.Caption := 'FX: ' + Xs + ', FY: ' + Ys;
end
else if (bPointing = True) then
begin
bMousing := False;
{ FVP:= FXMin + (FXMax - FXMin)/(Image2.Width-1) * X ;
FHQ:= FYMax - (FYMax - FYMin)/(Image2.Height-1) * Y ; }
TXMin := FXMin + (FXMax - FXMin) / (Image2.Width - 1) * X;
TYMax := FYMax - (FYMax - FYMin) / (Image2.Height - 1) * Y;
str(TXMin: 24: 20, Xs);
str(TYMax: 24: 20, Ys);
HiddenFX.Caption := 'P: ' + Xs + ', Q: ' + Ys;
end
else if (bMousing = True) then
begin
str((X - (Image2.Width div 2)), Xs);
str(((Image2.Height div 2) - Y), Ys);
HiddenFX.Caption := 'X: ' + Xs + ', Y: ' + Ys;
end
else if (bLightning = True) then
begin
str((X - (Image2.Width div 2)), Xs);
str(((Image2.Height div 2) - Y), Ys);
HiddenFX.Caption := 'Lightning X: ' + Xs + ', Y: ' + Ys;
end;
end;
(* *********************************************************** *)
procedure TMainForm.Image2MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
FiTemp: Integer;
a, b, c, TXMin, TYMax, TXMax, TYMin: Extended;
Arect: TRect;
AnnoS: string;
{ F_File: file of TFont; }
begin
if ImageDraw.Checked then
begin
DrawShape(Origin, Point(X, Y), DIYX3Y3, DIYX4Y4, pmCopy);
{ draw the final shape }
Drawing := False;
{ clear the Drawing flag for this line, rectangle, etc..
Mouse down will start another line-rectangle
will keep drawing till Draw is unchecked
or Style form is closed }
end;
if Fractaling then
begin
{ Choose Box type, Click center and expand at correct ratio, or normal }
if (Origin.X > X) then
begin
FiTemp := Origin.X;
Origin.X := X;
X := FiTemp;
end;
if (Origin.Y > Y) then
begin
FiTemp := Origin.Y;
Origin.Y := Y;
Y := FiTemp;
end;
{ based on 0,0, upper left, then lower right
640,480 Numbers provide Ratio not image size just use 4,3 }
a := ((480 * (X - Origin.X)) / 640);
b := (((Y - Origin.Y) - a) / 2);
if (a > (Y - Origin.Y)) then
begin
a := Origin.Y - b;
c := Y + b;
end
else
begin
a := Origin.Y + b;
c := Y - b;
end;
Origin.Y := round(a);
Y := round(c);
with Image2.Canvas do
begin
CopyMode := cmDstInvert;
Arect := Rect(Origin.X, Origin.Y, X, Y);
CopyRect(Arect, Image2.Canvas, Arect);
CopyMode := cmSrcCopy; { restore the copy mode }
{ Message to Save?? as Temp File.BMP? }
Image2.Picture.SaveToFile('TempFile.BMP');
end;
TXMin := FXMin + (FXMax - FXMin) / (Image2.Width - 1) * Origin.X;
{ Origins }
TYMax := FYMax - (FYMax - FYMin) / (Image2.Height - 1) * Origin.Y;
TXMax := FXMin + (FXMax - FXMin) / (Image2.Width - 1) * X; { 639 }
TYMin := FYMax - (FYMax - FYMin) / (Image2.Height - 1) * Y; { 479 }
FXMin := TXMin;
FYMin := TYMin;
FXMax := TXMax;
FYMax := TYMax;
{ FXVPin }
FVP := FXMin + (FXMax - FXMin) / (Image2.Width - 1) *
(Origin.X + ((Origin.X - X) div 2));
{ FYHQIn }
FHQ := FYMax - (FYMax - FYMin) / (Image2.Height - 1) *
(Origin.Y + ((Origin.Y - Y) div 2));
Fractaling := False;
Drawing := False; { clear the Drawing flag }
LastKnownFunction := 69;
FractalForm.FractalSet;
end;
if bPointing then
begin { 639 }
{ Convert to Fractal Coordinates }
{ FXVPin := FXMin + (FXMax - FXMin)/639 * xpos ;
FYHQIn := FYMax - (FYMax - FYMin)/479 * ypos ; }
{ FXVPin } FVP := FXMin + (FXMax - FXMin) / (Image2.Width - 1) * X;
{ FYHQIn } FHQ := FYMax - (FYMax - FYMin) / (Image2.Height - 1) * Y;
bPointing := False;
Julia := False; { 479 }
LastKnownFunction := 69;
FractalForm.FractalSet;
{ Need to figure what the POINT needs to compute Q and P
FXVPin := FXMin + (FXMax - FXMin)/639 * xpos ;
FYHQIn := FYMax - (FYMax - FYMin)/479 * ypos ; }
end;
if bVistaLive then
begin
if (DrawingTool = dtVRectangle) then
begin
if (ITriangling = 2) then
begin
DIYX4Y4.X := X;
DIYX4Y4.Y := Y;
{ DIYX4Y4.X:=DIYXY.X;
DIYX4Y4.Y:=DIYXY.Y; }
Application.ProcessMessages;
str(DIYXY.X, AnnoS);
MathForm.DIYXEdit.Text := AnnoS;
str(DIYXY.Y, AnnoS);
MathForm.DIYYEdit.Text := AnnoS;
str(DIYX2Y2.X, AnnoS);
MathForm.DIYWxEdit.Text := AnnoS;
str(DIYX2Y2.Y, AnnoS);
MathForm.DIYHyEdit.Text := AnnoS;
DrawShape(Origin, Point(X, Y), DIYX3Y3, DIYX4Y4, pmCopy);
DrawShape(Point(X, Y), DIYXY, DIYX3Y3, DIYX4Y4, pmCopy);
ITriangling := 102;
DrawShape(Point(X, Y), DIYXY, DIYX3Y3, DIYX4Y4, pmCopy);
bVistaLive := False;
Drawing := False; { clear the Drawing flag }
end
else if (ITriangling = 1) then
begin
{ DIYX2Y2.X:= Origin.x;
DIYX2Y2.Y:=Origin.y; }
DIYX3Y3.X := X;
DIYX3Y3.Y := Y;
DIYX4Y4.X := X;
DIYX4Y4.Y := Y;
DrawShape(Origin, Point(X, Y), DIYX3Y3, DIYX4Y4, pmCopy);
Image2.Canvas.MoveTo(X, Y);
Origin := Point(X, Y);
MovePt := Point(X, Y);
{ DrawShape(Origin, MovePt, pmNotXor); }
inc(ITriangling);
Drawing := True; { Reset the Drawing flag }
{ DrawShape(Point(X, Y),DIYXY, pmCopy); }
end
else if (ITriangling = 0) then
begin
{ Capture the past points }
DIYXY.X := Origin.X;
DIYXY.Y := Origin.Y;
DIYX2Y2.X := X;
DIYX2Y2.Y := Y;
DrawShape(Origin, Point(X, Y), DIYX3Y3, DIYX4Y4, pmCopy);
Image2.Canvas.MoveTo(X, Y);
Origin := Point(X, Y);
MovePt := Point(X, Y);
{ DrawShape(Origin, Point(X, Y), pmNotXor); }
Application.ProcessMessages;
inc(ITriangling);
Drawing := True; { Reset the Drawing flag }
end;
end
else if ((DrawingTool = dtVTriangle) or (DrawingTool = dtTSTriangle) or
(DrawingTool = dtTriangle)) then
begin
if (ITriangling = 1) then
begin
DIYX3Y3.X := X;
DIYX3Y3.Y := Y;
Application.ProcessMessages;
str(DIYXY.X, AnnoS);
MathForm.DIYXEdit.Text := AnnoS;
str(DIYXY.Y, AnnoS);
MathForm.DIYYEdit.Text := AnnoS;
str(DIYX2Y2.X, AnnoS);
MathForm.DIYWxEdit.Text := AnnoS;
str(DIYX2Y2.Y, AnnoS);
MathForm.DIYHyEdit.Text := AnnoS;
DrawShape(Origin, Point(X, Y), DIYX3Y3, DIYX4Y4, pmCopy);
DrawShape(Point(X, Y), DIYXY, DIYX3Y3, DIYX4Y4, pmCopy);
ITriangling := 102;
DrawShape(Point(X, Y), DIYXY, DIYX3Y3, DIYX4Y4, pmCopy);
bVistaLive := False;
Drawing := False; { clear the Drawing flag }
end
else if (ITriangling = 0) then
begin
{ Capture the past points }
DIYXY.X := Origin.X;
DIYXY.Y := Origin.Y;
DIYX2Y2.X := X;
DIYX2Y2.Y := Y;
DIYX3Y3.X := X;
DIYX3Y3.Y := Y;
DrawShape(Origin, Point(X, Y), DIYX3Y3, DIYX4Y4, pmCopy);
Image2.Canvas.MoveTo(X, Y);
Origin := Point(X, Y);
MovePt := Point(X, Y);
{ DrawShape(Origin, Point(X, Y), pmNotXor); }
Application.ProcessMessages;
Drawing := True; { Reset the Drawing flag }
inc(ITriangling);
end;
end
else
begin { all other shapes }
{ Capture the data according to type }
DIYXY.X := Origin.X;
DIYXY.Y := Origin.Y;
DIYX2Y2.X := X;
DIYX2Y2.Y := Y;
str(Origin.X, AnnoS);
MathForm.DIYXEdit.Text := AnnoS;
str(Origin.Y, AnnoS);
MathForm.DIYYEdit.Text := AnnoS;
str(X, AnnoS);
MathForm.DIYWxEdit.Text := AnnoS;
str(Y, AnnoS);
MathForm.DIYHyEdit.Text := AnnoS;
bVistaLive := False;
Drawing := False; { clear the Drawing flag }
DrawShape(Origin, Point(X, Y), DIYX3Y3, DIYX4Y4, pmCopy);
end;
end;
if ((ImageAnnotate.Checked) or (DIYAnnotate)) then
begin
Image2.Canvas.TextOut(X, Y, AnnotationForm.AnnoEdit.Text);
ImageAnnotate.Checked := False;
DIYTextStorage := AnnotationForm.AnnoEdit.Text;
DIYXY.X := X;
DIYXY.Y := Y;
DIYAnnotate := False;
AnnotationForm.Hide;
{ Place-Record the Annotation AND the Font data
onto the Vista List }
begin
(* MathForm.SaveDialog1.Filename := FractalFont.Name + '*.vft';
MathForm.SaveDialog1.Filter := 'Vista Font(*.vft)|*.vft';
if MathForm.SaveDialog1.Execute then { Display Open dialog box }
begin
AssignFile(F_File, MathForm.SaveDialog1.Filename);
ReWrite(F_File);
if IoResult = 0 then
begin
Write(F_File, FractalFont);
CloseFile(F_File);
*)
MathForm.DIYMemo.Lines.Append('Annotation');
{ AnnoS := MathForm.SaveDialog1.Filename;
MathForm.DIYMemo.Lines.Append(AnnoS); }
MathForm.DIYMemo.Lines.Append(DIYTextStorage);
str(X, AnnoS);
MathForm.DIYMemo.Lines.Append('X: ' + AnnoS);
str(Y, AnnoS);
MathForm.DIYMemo.Lines.Append('Y: ' + AnnoS);
(* end;
if (IoResult <> 0) then
Application.Mess ageBox
('DID NOT Save Font', 'Font save Error', MB_OKCANCEL);
end;
*)
end;
Image2.Canvas.Refresh;
Application.ProcessMessages;
end;
if bLightning then
begin
DIYL.X := X;
DIYL.Y := Y;
str(X, AnnoS);
MathForm.DIYLxEdit.Text := AnnoS;
str(Y, AnnoS);
MathForm.DIYLyEdit.Text := AnnoS;
bLightning := False;
end;
if (Cropping > 0) then
begin
DrawingTool := dtLine;
Drawing := False;
MovePt := Point(X, Y);
EditCropper;
end;
if (bZoomMousing) then
begin
DrawingTool := dtLine;
Drawing := False;
MovePt := Point(X, Y);
ZoomMouseDo;
end;
if bRotatingImage then
bRotateImage := True;
{ in the Drawing...
bRotateImage:=False;
Repeat Application.ProcessMessages until (bRotateImage=True) }
end;
(* *********************************************************** *)
procedure TMainForm.DrawShape(TopLeft, BottomRight, Tri, Quad: TPoint;
AMode: TPenMode);
var
Code, ColdX, i: Integer;
TempColor: TColor;
dCounter, Ramper: Double;
begin
with Image2.Canvas do
begin
Pen.Mode := AMode;
case DrawingTool of
dtLine:
begin
Image2.Canvas.MoveTo(TopLeft.X, TopLeft.Y);
Image2.Canvas.LineTo(BottomRight.X, BottomRight.Y);
end;
dtVTriangle, dtTSTriangle, dtTriangle:
begin
if (ITriangling > 5) then
begin
Image2.Canvas.Polygon([DIYXY, DIYX2Y2, DIYX3Y3]);
end
else
begin
Image2.Canvas.MoveTo(TopLeft.X, TopLeft.Y);
Image2.Canvas.LineTo(BottomRight.X, BottomRight.Y);
end;
end;
dtVRectangle:
begin
if (ITriangling > 5) then
begin
Image2.Canvas.Polygon([DIYXY, DIYX2Y2, DIYX3Y3, DIYX4Y4]);
end
else
begin
Image2.Canvas.MoveTo(TopLeft.X, TopLeft.Y);
Image2.Canvas.LineTo(BottomRight.X, BottomRight.Y);
end;
end;
dtVDRectangle, dtVTRectangle, dtVFRectangle, dtVNRectangle, dtVMRectangle,
dtVARectangle, dtVWRectangle, dtVCRectangle, dtVSRectangle,
dtVBRectangle, dtRectangle:
Image2.Canvas.Rectangle(TopLeft.X, TopLeft.Y, BottomRight.X,
BottomRight.Y);
dtVPRectangle:
begin
if bVistaLive then
Image2.Canvas.Rectangle(TopLeft.X, TopLeft.Y, BottomRight.X,
BottomRight.Y)
else
begin
{ Pandora dCounter }
val(MathForm.DIYZEdit.Text, dCounter, Code);
Codefx(MathForm.DIYZEdit.Text, Code);
Ramper := (255 / (1 + abs(DIYXY.Y - DIYX2Y2.Y)));
for Code := DIYXY.Y to DIYX2Y2.Y do
begin
for ColdX := DIYXY.X to DIYX2Y2.X do
begin
if (random(abs(DIYXY.Y - DIYX2Y2.Y)) <=
random(round(Ramper * dCounter))) then
Pixels[ColdX, Code] := V1Color;
if (random(abs(DIYXY.Y - DIYX2Y2.Y)) <=
random(round(Ramper * (dCounter / 8)))) then
begin
Pixels[ColdX + 1, Code] := V2Color;
Pixels[ColdX, Code] := V3Color;
Pixels[ColdX, Code + 1] := V2Color;
Pixels[ColdX - 1, Code] := V2Color;
Pixels[ColdX, Code - 1] := V2Color;
end;
if (random(abs(DIYXY.Y - DIYX2Y2.Y)) <=
random(round(Ramper * dCounter))) then
Pixels[ColdX, Code] := V4Color;
end;
end;
end;
end;
dtVERectangle:
begin
if bVistaLive then
Image2.Canvas.Rectangle(TopLeft.X, TopLeft.Y, BottomRight.X,
BottomRight.Y)
else
begin
dCounter := 0;
Ramper := (255 / (1 + abs(DIYXY.Y - DIYX2Y2.Y)));
for i := DIYXY.Y to DIYX2Y2.Y do
begin
TempColor := RGB(Colors[0, round(dCounter)],
Colors[1, round(dCounter)], Colors[2, round(dCounter)]);
dCounter := dCounter + Ramper;
Pen.Color := TempColor;
MoveTo(DIYXY.X, i);
LineTo(DIYX2Y2.X, i);
end;
end;
end;
dtCSEllipse, dtEllipse:
Image2.Canvas.Ellipse(TopLeft.X, TopLeft.Y, BottomRight.X,
BottomRight.Y);
dtPBrush:
Image2.Canvas.Ellipse(TopLeft.X, TopLeft.Y,
(TopLeft.X + DrawingTool_PBrush_Width),
(TopLeft.Y + DrawingTool_PBrush_Width));
dtRoundRect:
Image2.Canvas.RoundRect(TopLeft.X, TopLeft.Y, BottomRight.X,
BottomRight.Y, (TopLeft.X - BottomRight.X) div 2,
(TopLeft.Y - BottomRight.Y) div 2);
end;
end;
end;
(* *********************************************************** *)
procedure TMainForm.ImageDrawClick(Sender: TObject);
begin
{ use this to activate painting
Use style to change bitmap }
if (ImageDraw.Checked) then
begin
ImageDraw.Checked := False;
DIYStyleForm.Hide;
Drawing := False; { clear the Drawing flag }
end
else
begin
ImageDraw.Checked := True;
DrawingTool := dtLine;
DIYStyleForm.Show;
Drawing := True; { clear the Drawing flag }
end;
{ ImageDraw.Checked := (Not ImageDraw.Checked);
If ImageDraw.Checked then DrawingTool := dtLine; }
end;
procedure TMainForm.ImageAnnotateClick(Sender: TObject);
begin
ImageAnnotate.Checked := (not ImageAnnotate.Checked);
if ImageAnnotate.Checked then
begin
{ Image2.Canvas.Font := FractalFont; }
AnnotationForm.Show;
end;
{
Writes a string on the canvas, starting at the point (X,Y),
and then updates the PenPos to the end of the string.
procedure TextOut(X, Y: Integer; const Text: string);
Description
Use TextOut to write a string onto the canvas.
The string will be written using the current value of Font.
Use the TextExtent method to determine the space occupied by
the text in the image. To write only the text that fits within
a clipping rectangle, use TextRect instead.
Writes a string inside a clipping rectangle.
procedure TextRect(Rect: TRect; X, Y: Integer; const Text: string);
Description
Use TextRect to write a string within a limited rectangular region.
Any portions of the string that fall outside the rectangle passed
in the Rect parameter are clipped and don't appear. The upper left
corner of the text is placed at the point (X, Y). }
end;
procedure TMainForm.ImageSelectFontClick(Sender: TObject);
begin
FontDialog1.Execute;
Image2.Canvas.Font := FontDialog1.Font;
HintPanel.Caption := FontDialog1.Font.Name;
end;
(* *********************************************************** *)
function NextFileNumber(F_image: string): string; { File Save }
var
WorkerName: string;
begin
WorkerName := ExtractFileName(F_image);
repeat
;
if FileExists(WorkerName) then
begin
inc(WorkerName[11]);
{ $3A is :, the Char after 9 }
if WorkerName[11] >= char($3A) then
begin
WorkerName[11] := char($30);
{ $30 = 0 }
inc(WorkerName[10]);
end;
if WorkerName[10] >= char($3A) then
begin
WorkerName[10] := char($30);
{ $30 = 0 }
inc(WorkerName[9]);
end;
end;
until (not FileExists(WorkerName) or (WorkerName[9] > char($39)));
{ $39 = 9 }
NextFileNumber := WorkerName;
end; { of NextFileNumber }
(* ********************************************************* *)
procedure TMainForm.ChangeFileName;
var
SFile, SinFile: string;
begin
if FileExists(FractalFilename) then
begin
SFile := FractalFilename;
SinFile := NextFileNumber(SFile);
FractalFilename := ExpandFileName(SinFile);
if (FileExists(FractalFilename)) then
DoMessages(27);
end;
end;
(* *********************************************************** *)
{ Image FILENAME MUST BE CHANGED PRIOR TO CALLING
to keep aligned with its Image file }
(* *********************************************************** *)
procedure TMainForm.WriteDataFile;
var
FractalFileRcd: string;
IterationalEx, Color_RangeEx, Gotto_ColEx: Extended;
F_File: file of Extended;
begin { Read and Write data files as ALL Extended values }
{ function ExtractFileName(const FileName: string): string;)
MyFilesExtension := ExtractFileExt(FractalFilename);
function ChangeFileExt(const FileName, Extension: string): string; }
if (CallMandelBrot = True) then
begin
IterationalEx := max_iterations * 1.0;
Color_RangeEx := Color_Option * 1.0;
Gotto_ColEx := Start_Col * 1.0;
FractalFileRcd := ChangeFileExt(FractalFilename, '.TMP');
AssignFile(F_File, FractalFileRcd);
ReWrite(F_File);
if IoResult = 0 then
begin
Write(F_File, FXMax);
Write(F_File, FXMin);
Write(F_File, FYMax);
Write(F_File, FYMin);
Write(F_File, FHQ);
Write(F_File, FVP);
Write(F_File, IterationalEx);
Write(F_File, Color_RangeEx);
Write(F_File, Gotto_ColEx);
{ MaximumElevation }
IterationalEx := MaximumElevation * 1.0;
Write(F_File, IterationalEx);
IterationalEx := MinimumElevation * 1.0;
Write(F_File, IterationalEx);
IterationalEx := ContourInterval * 1.0;
Write(F_File, IterationalEx);
IterationalEx := Fractalgorhythym * 1.0;
Write(F_File, IterationalEx);
IterationalEx := FileSizeX * 1.0;
Write(F_File, IterationalEx);
IterationalEx := FileSizeY * 1.0;
Write(F_File, IterationalEx);
CloseFile(F_File);
if (IoResult <> 0) then
DoMessages(39982);
end
else
DoMessages(39981);
end
else
begin
IterationalEx := max_iterations * 1.0;
Color_RangeEx := Color_Option * 1.0;
Gotto_ColEx := Start_Col * 1.0;
FractalFileRcd := ChangeFileExt(FractalFilename, '.RCD');
AssignFile(F_File, FractalFileRcd);
ReWrite(F_File);
Write(F_File, FXMax);
Write(F_File, FXMin);
Write(F_File, FYMax);
Write(F_File, FYMin);
Write(F_File, FHQ);
Write(F_File, FVP);
Write(F_File, IterationalEx);
Write(F_File, Color_RangeEx);
Write(F_File, Gotto_ColEx);
{ MaximumElevation }
IterationalEx := MaximumElevation * 1.0;
Write(F_File, IterationalEx);
IterationalEx := MinimumElevation * 1.0;
Write(F_File, IterationalEx);
IterationalEx := ContourInterval * 1.0;
Write(F_File, IterationalEx);
IterationalEx := Fractalgorhythym * 1.0;
Write(F_File, IterationalEx);
IterationalEx := FileSizeX * 1.0;
Write(F_File, IterationalEx);
IterationalEx := FileSizeY * 1.0;
Write(F_File, IterationalEx);
CloseFile(F_File);
if IoResult <> 0 then
DoMessages(30101);
end;
LastKnownFunction := 66;
FractalForm.FractalSet;
end;
(* *********************************************************** *)
procedure TMainForm.ReadDataFile;
var
FractalFileRcd: string;
IterationalEx1, IterationalEx, Color_RangeEx, Gotto_ColEx: Extended;
F_File: file of Extended;
begin { Try to read RCD file then TMP... failure }
FractalFileRcd := ChangeFileExt(FractalFilename, '.RCD');
if (FileExists(FractalFileRcd)) then
begin
AssignFile(F_File, FractalFileRcd);
Reset(F_File);
if IoResult <> 0 then
begin
DoMessages(30102);
end;
Read(F_File, FXMax);
Read(F_File, FXMin);
Read(F_File, FYMax);
Read(F_File, FYMin);
Read(F_File, FHQ);
Read(F_File, FVP);
Read(F_File, IterationalEx1);
Read(F_File, Color_RangeEx);
Read(F_File, Gotto_ColEx);
max_iterations := round(IterationalEx1);
Color_Option := round(Color_RangeEx);
Start_Col := round(Gotto_ColEx);
Read(F_File, IterationalEx);
MaximumElevation := round(IterationalEx);
Read(F_File, IterationalEx);
MinimumElevation := round(IterationalEx);
Read(F_File, IterationalEx);
ContourInterval := round(IterationalEx);
Read(F_File, IterationalEx);
Fractalgorhythym := round(IterationalEx);
Read(F_File, IterationalEx);
FileSizeX := round(IterationalEx);
Read(F_File, IterationalEx);
FileSizeY := round(IterationalEx);
CloseFile(F_File);
end
else
begin
FractalFileRcd := ChangeFileExt(FractalFilename, '.TMP');
if FileExists(FractalFileRcd) then
begin
AssignFile(F_File, FractalFileRcd);
Reset(F_File);
if IoResult <> 0 then
begin
DoMessages(39987);
exit;
end;
Read(F_File, FXMax);
Read(F_File, FXMin);
Read(F_File, FYMax);
Read(F_File, FYMin);
Read(F_File, FHQ);
Read(F_File, FVP);
Read(F_File, IterationalEx);
Read(F_File, Color_RangeEx);
Read(F_File, Gotto_ColEx);
max_iterations := round(IterationalEx1);
Color_Option := round(Color_RangeEx);
Start_Col := round(Gotto_ColEx);
Read(F_File, IterationalEx);
MaximumElevation := round(IterationalEx);
Read(F_File, IterationalEx);
MinimumElevation := round(IterationalEx);
Read(F_File, IterationalEx);
ContourInterval := round(IterationalEx);
Read(F_File, IterationalEx);
Fractalgorhythym := round(IterationalEx);
Read(F_File, IterationalEx);
FileSizeX := round(IterationalEx);
Read(F_File, IterationalEx);
FileSizeY := round(IterationalEx);
CloseFile(F_File);
Erase(F_File);
if IoResult <> 0 then
begin
DoMessages(39988);
end;
end
else
begin
DoMessages(39989);
end;
end;
LastKnownFunction := 99;
FractalForm.FractalSet;
end;
(* *********************************************************** *)
procedure TMainForm.FileOpen(Sender: TObject);
begin
{ if then }
OpenPictureDialog1.Title := 'Fractal File Selection';
OpenPictureDialog1.FileName := 'Fractals.BMP';
FileOpener;
end;
procedure TMainForm.FileOpener;
var { PixelString, }
MyFilesExtension: string;
{ Pixeli: Integer; }
begin
OpenPictureDialog1.InitialDir := FractalDir;
if OpenPictureDialog1.Execute then
begin
FractalDir := ExtractFilePath(OpenPictureDialog1.FileName);
MyFilesExtension := Uppercase(ExtractFileExt(OpenPictureDialog1.FileName));
if MyFilesExtension = '.BMP' then
begin
{ Add code to open OpenPictureDialog1.FileName }
FractalFilename := OpenPictureDialog1.FileName;
Image2.Picture.LoadFromFile(FractalFilename);
if (BitmapF.PixelFormat <> MyPixelFormat) then
begin
DoMessages(12);
{ if (PixelScanSize = 4) then Pixeli := 32 else
Pixeli := 24;
str(Pixeli, PixelString); }
end
else
begin
ReadDataFile; { of this }
MyFilesExtension := ChangeFileExt(FractalFilename, '.TMP');
if (not FileExists(MyFilesExtension)) then
ChangeFileName; { for next }
MyFilesExtension := ExtractFileName(FractalFilename);
if (MyFilesExtension[6] = 'P') then
Julia := True;
if Julia then
bPointing := True
else
Fractaling := True;
end;
end
else
DoMessages(30093);
end;
end;
procedure TMainForm.FileSave(Sender: TObject);
begin
FileSaver;
end;
procedure TMainForm.FileSaver;
begin
{ Add code to save current file under current name
SavePictureDialog1 }
Image2.Picture.SaveToFile(FractalFilename);
WriteDataFile;
end;
procedure TMainForm.FileSaveAs(Sender: TObject);
var
jp: TJpegImage; // Requires the "jpeg" unit added to "uses" clause.
MyFilesExtension: string;
begin
SavePictureDialog1.InitialDir := FractalDir;
if SavePictureDialog1.Execute then
begin
FractalDir := ExtractFilePath(SavePictureDialog1.FileName);
MyFilesExtension := Uppercase(ExtractFileExt(SavePictureDialog1.FileName));
if MyFilesExtension = '.BMP' then
begin
Image2.Picture.SaveToFile(SavePictureDialog1.FileName);
end
else if MyFilesExtension = '.JPG' then
begin
{ This example converts a bitmap image to a jpeg file
by using the Assign method. }
jp := TJpegImage.Create;
try
with jp do
begin
assign(Image2.Picture.Bitmap);
if JPEGForm.ShowModal = mrOK then
jp.SaveToFile(SavePictureDialog1.FileName);
end;
finally
jp.Free;
end;
end;
end;
end;
(* *********************************************************** *)
procedure TMainForm.PrintBig1Click(Sender: TObject);
begin
PrintBig1.Checked := (not PrintBig1.Checked);
end;
procedure TMainForm.FilePrint(Sender: TObject);
var
PrintRect: TRect;
begin
if PrintDialog.Execute then
begin
{ Add code to print current file }
with Printer do
begin
BeginDoc;
{ Image1.Picture.Bitmap or FBitmap
Check to see if enlarged print is available }
if ((PageWidth > (Image2.Picture.Bitmap.Width * 2)) and
(PageHeight > (Image2.Picture.Bitmap.Height * 2)) and PrintBig1.Checked)
then
begin
{ Rect(0, 0, Image.Width, Image.Height); }
PrintRect := Rect((PageWidth - (Image2.Picture.Bitmap.Width * 2)) div 2,
(PageHeight - (Image2.Picture.Bitmap.Height * 2)) div 2,
(((PageWidth - (Image2.Picture.Bitmap.Width * 2)) div 2) +
(Image2.Picture.Bitmap.Width * 2)),
(((PageHeight - (Image2.Picture.Bitmap.Height * 2)) div 2) +
(Image2.Picture.Bitmap.Height * 2)));
Canvas.StretchDraw(PrintRect, Image2.Picture.Bitmap);
end
else if (((PageWidth - Image2.Picture.Bitmap.Width) > 0) and
((PageHeight - Image2.Picture.Bitmap.Height) > 0)) then
Canvas.Draw((PageWidth - Image2.Picture.Bitmap.Width) div 2,
(PageHeight - Image2.Picture.Bitmap.Height) div 2,
Image2.Picture.Bitmap)
else { Reduce Image to fit page... }
if DoMessagesOK(10001) = mrYes then
begin
PrintRect := Rect((PageWidth - (Image2.Picture.Bitmap.Width div 2))
div 2, (PageHeight - (Image2.Picture.Bitmap.Height div 2)) div 2,
(((PageWidth - (Image2.Picture.Bitmap.Width div 2)) div 2) +
(Image2.Picture.Bitmap.Width div 2)),
(((PageHeight - (Image2.Picture.Bitmap.Height div 2)) div 2) +
(Image2.Picture.Bitmap.Height div 2)));
Canvas.StretchDraw(PrintRect, Image2.Picture.Bitmap);
end;
EndDoc;
end;
end;
end;
procedure TMainForm.FilePrintSetup(Sender: TObject);
begin
PrintSetupDialog.Execute;
end;
(* *********************************************************** *)
(* *********************************************************** *)
procedure TMainForm.HelpContents(Sender: TObject);
begin
{ Application.HelpCommand(HELP_CONTENTS, 0); }
Application.HelpContext(0);
end;
procedure TMainForm.HelpSearch(Sender: TObject);
const
EmptyString: PChar = '';
begin
Application.HelpCommand(HELP_PARTIALKEY, Longint(EmptyString));
end;
procedure TMainForm.HelpHowToUse(Sender: TObject);
begin
Application.HelpCommand(HELP_HELPONHELP, 0);
end;
procedure TMainForm.HelpAbout(Sender: TObject);
begin
{ Add code to show program's About Box }
AboutBox.Show;
{ With TAboutBox.Create(Self) Do Show; }
end;
(* *********************************************************** *)
procedure TMainForm.Preview1Click(Sender: TObject);
begin
FMJForm.Show;
{ FractalPreviewForm.Show; }
end;
procedure TMainForm.Fractals1Click(Sender: TObject);
begin
FractalForm.Show;
end;
procedure TMainForm.XYZ3DClick(Sender: TObject);
begin
XYZ3DForm.Show;
end;
procedure TMainForm.Math1Click(Sender: TObject);
begin
MathForm.Show;
end;
(* *********************************************************** *)
procedure TMainForm.FalseSize;
begin
FV_IS640x480.Checked := False;
FV_IS800x600.Checked := False;
FV_IS1024x768.Checked := False;
FV_IS1280x960.Checked := False;
FV_IS1600x1200.Checked := False;
FV_IS1920x1440.Checked := False;
FV_IS2048x1536.Checked := False;
FV_IS2400x1800.Checked := False;
FV_IS2560x1920.Checked := False;
FV_IS3072x2304.Checked := False;
FV_IS3200x2400.Checked := False;
FV_IS3840x2880.Checked := False;
FV_IS4000x3000.Checked := False;
FV_IS4096x3072.Checked := False;
end;
procedure TMainForm.FV_IS640x480Click(Sender: TObject);
begin
if (not FV_IS640x480.Checked) then
begin
FalseSize;
FV_IS640x480.Checked := (not FV_IS640x480.Checked);
FYImageX := 640;
FYImageY := 480;
OverBit;
end;
end;
procedure TMainForm.FV_IS800x600Click(Sender: TObject);
begin
if (not FV_IS800x600.Checked) then
begin
FalseSize;
FV_IS800x600.Checked := (not FV_IS800x600.Checked);
FYImageX := 800;
FYImageY := 600;
OverBit;
end;
end;
procedure TMainForm.FV_IS1024x768Click(Sender: TObject);
begin
if (not FV_IS1024x768.Checked) then
begin
FalseSize;
FV_IS1024x768.Checked := (not FV_IS1024x768.Checked);
FYImageX := 1024;
FYImageY := 768;
OverBit;
end;
end;
procedure TMainForm.FV_IS1280x960Click(Sender: TObject);
begin
if (not FV_IS1280x960.Checked) then
begin
FalseSize;
FV_IS1280x960.Checked := (not FV_IS1280x960.Checked);
FYImageX := 1280;
FYImageY := 960;
OverBit;
end;
end;
procedure TMainForm.FV_IS1600x1200Click(Sender: TObject);
begin
if (not FV_IS1600x1200.Checked) then
begin
FalseSize;
FV_IS1600x1200.Checked := (not FV_IS1600x1200.Checked);
FYImageX := 1600;
FYImageY := 1200;
OverBit;
end;
end;
procedure TMainForm.FV_IS1920x1440Click(Sender: TObject);
begin
if (not FV_IS1920x1440.Checked) then
begin
FalseSize;
FV_IS1920x1440.Checked := (not FV_IS1920x1440.Checked);
FYImageX := 1920;
FYImageY := 1440;
OverBit;
end;
end;
procedure TMainForm.FV_IS2048x1536Click(Sender: TObject);
begin
if (not FV_IS2048x1536.Checked) then
begin
FalseSize;
FV_IS2048x1536.Checked := (not FV_IS2048x1536.Checked);
FYImageX := 2048;
FYImageY := 1536;
OverBit;
end;
end;
procedure TMainForm.FV_IS2400x1800Click(Sender: TObject);
begin
if (not FV_IS2400x1800.Checked) then
begin
FalseSize;
FV_IS2400x1800.Checked := (not FV_IS2400x1800.Checked);
FYImageX := 2400;
FYImageY := 1800;
OverBit;
end;
end;
procedure TMainForm.FV_IS3072x2304Click(Sender: TObject);
begin
if (not FV_IS3072x2304.Checked) then
begin
FalseSize;
FV_IS3072x2304.Checked := (not FV_IS3072x2304.Checked);
FYImageX := 3072;
FYImageY := 2304;
OverBit;
end;
end;
procedure TMainForm.FV_IS4096x3072Click(Sender: TObject);
begin
if (not FV_IS4096x3072.Checked) then
begin
FalseSize;
FV_IS4096x3072.Checked := (not FV_IS4096x3072.Checked);
FYImageX := 4096;
FYImageY := 3072;
OverBit;
end;
end;
procedure TMainForm.FV_IS4000x3000Click(Sender: TObject);
begin
if (not FV_IS4000x3000.Checked) then
begin
FalseSize;
FV_IS4000x3000.Checked := (not FV_IS4000x3000.Checked);
FYImageX := 4000;
FYImageY := 3000;
OverBit;
end;
end;
procedure TMainForm.FV_IS3840x2880Click(Sender: TObject);
begin
if (not FV_IS3840x2880.Checked) then
begin
FalseSize;
FV_IS3840x2880.Checked := (not FV_IS3840x2880.Checked);
FYImageX := 3840;
FYImageY := 2880;
OverBit;
end;
end;
procedure TMainForm.FV_IS3200x2400Click(Sender: TObject);
begin
if (not FV_IS3200x2400.Checked) then
begin
FalseSize;
FV_IS3200x2400.Checked := (not FV_IS3200x2400.Checked);
FYImageX := 3200;
FYImageY := 2400;
OverBit;
end;
end;
procedure TMainForm.FV_IS2560x1920Click(Sender: TObject);
begin
if (not FV_IS2560x1920.Checked) then
begin
FalseSize;
FV_IS2560x1920.Checked := (not FV_IS2560x1920.Checked);
FYImageX := 2560;
FYImageY := 1920;
OverBit;
end;
end;
(* *********************************************************** *)
procedure TMainForm.FalseColors;
begin
Black1.Checked := False; { clBlack }
Maroon1.Checked := False; { clMaroon }
Green1.Checked := False; { clGreen }
OliveGreen1.Checked := False; { clOlive }
NavyBlue1.Checked := False; { clNavy }
Purple1.Checked := False; { clPurple }
Teal1.Checked := False; { clTeal }
Gray1.Checked := False; { clGray }
Silver1.Checked := False; { clSilver }
Red1.Checked := False; { clRed }
LimeGreen1.Checked := False; { clime }
Yellow1.Checked := False; { clYellow }
Blue1.Checked := False; { clBlue }
Fuchsia1.Checked := False; { clFuchsia }
Aqua1.Checked := False; { clAqua }
White1.Checked := False; { clWhite }
Bomb1.Checked := False;
Mine1.Checked := False;
if FBackGroundColor = clBlack then
Black1.Checked := True
else if FBackGroundColor = clWhite then
White1.Checked := True
else if FBackGroundColor = clAqua then
Aqua1.Checked := True
else if FBackGroundColor = clFuchsia then
Fuchsia1.Checked := True
else if FBackGroundColor = clBlue then
Blue1.Checked := True
else if FBackGroundColor = clYellow then
Yellow1.Checked := True
else if FBackGroundColor = clLime then
LimeGreen1.Checked := True
else if FBackGroundColor = clRed then
Red1.Checked := True
else if FBackGroundColor = clSilver then
Silver1.Checked := True
else if FBackGroundColor = clGray then
Gray1.Checked := True
else if FBackGroundColor = clTeal then
Teal1.Checked := True
else if FBackGroundColor = clPurple then
Purple1.Checked := True
else if FBackGroundColor = clNavy then
NavyBlue1.Checked := True
else if FBackGroundColor = clOlive then
OliveGreen1.Checked := True
else if FBackGroundColor = clGreen then
Green1.Checked := True
else if FBackGroundColor = clMaroon then
Maroon1.Checked := True
else if FBackGroundColor = MineBackgroundColor then
Mine1.Checked := True
else if FBackGroundColor = BombBackgroundColor then
Bomb1.Checked := True;
end;
procedure TMainForm.FractalBlack1Click(Sender: TObject);
begin
if (not FractalBlack1.Checked) then
begin
FractalBlack1.Checked := True;
bFractalMaxed := True;
end
else
begin
FractalBlack1.Checked := False;
bFractalMaxed := False;
end;
end;
procedure TMainForm.Black1Click(Sender: TObject);
begin
if (not Black1.Checked) then
begin
FBackGroundColor := clBlack;
FalseColors;
end;
end;
procedure TMainForm.Maroon1Click(Sender: TObject);
begin
if (not Maroon1.Checked) then
begin
FBackGroundColor := clMaroon;
FalseColors;
{ Maroon1.Checked:=(Not Maroon1.Checked); }
end;
end;
procedure TMainForm.Green1Click(Sender: TObject);
begin
if (not Green1.Checked) then
begin
FBackGroundColor := clGreen;
FalseColors;
{ Green1.Checked:=(Not Green1.Checked); }
end;
end;
procedure TMainForm.OliveGreen1Click(Sender: TObject);
begin
if (not OliveGreen1.Checked) then
begin
FBackGroundColor := clOlive;
FalseColors;
{ OliveGreen1.Checked:=(Not OliveGreen1.Checked); }
end;
end;
procedure TMainForm.NavyBlue1Click(Sender: TObject);
begin
if (not NavyBlue1.Checked) then
begin
FBackGroundColor := clNavy;
FalseColors;
{ NavyBlue1.Checked:=(Not NavyBlue1.Checked); }
end;
end;
procedure TMainForm.Purple1Click(Sender: TObject);
begin
if (not Purple1.Checked) then
begin
FBackGroundColor := clPurple;
FalseColors;
{ Purple1.Checked:=(Not Purple1.Checked); }
end;
end;
procedure TMainForm.Teal1Click(Sender: TObject);
begin
if (not Teal1.Checked) then
begin
FBackGroundColor := clTeal;
FalseColors;
{ Teal1.Checked:=(Not Teal1.Checked); }
end;
end;
procedure TMainForm.Gray1Click(Sender: TObject);
begin
if (not Gray1.Checked) then
begin
FBackGroundColor := clGray;
FalseColors;
{ Gray1.Checked:=(Not Gray1.Checked); }
end;
end;
procedure TMainForm.Silver1Click(Sender: TObject);
begin
if (not Silver1.Checked) then
begin
FBackGroundColor := clSilver;
FalseColors;
{ Silver1.Checked:=(Not Silver1.Checked); }
end;
end;
procedure TMainForm.Red1Click(Sender: TObject);
begin
if (not Red1.Checked) then
begin
FBackGroundColor := clRed;
FalseColors;
{ Red1.Checked:=(Not Red1.Checked); }
end;
end;
procedure TMainForm.LimeGreen1Click(Sender: TObject);
begin
if (not LimeGreen1.Checked) then
begin
FBackGroundColor := clLime;
FalseColors;
{ LimeGreen1.Checked:=(Not LimeGreen1.Checked); }
end;
end;
procedure TMainForm.Yellow1Click(Sender: TObject);
begin
if (not Yellow1.Checked) then
begin
FBackGroundColor := clYellow;
FalseColors;
{ Yellow1.Checked:=(Not Yellow1.Checked); }
end;
end;
procedure TMainForm.Blue1Click(Sender: TObject);
begin
if (not Blue1.Checked) then
begin
FBackGroundColor := clBlue;
FalseColors;
{ Blue1.Checked:=(Not Blue1.Checked); }
end;
end;
procedure TMainForm.Fuchsia1Click(Sender: TObject);
begin
if (not Fuchsia1.Checked) then
begin
FBackGroundColor := clFuchsia;
FalseColors;
{ Fuchsia1.Checked:=(Not Fuchsia1.Checked); }
end;
end;
procedure TMainForm.Aqua1Click(Sender: TObject);
begin
if (not Aqua1.Checked) then
begin
FBackGroundColor := clAqua;
FalseColors;
{ Aqua1.Checked:=(Not Aqua1.Checked); }
end;
end;
procedure TMainForm.White1Click(Sender: TObject);
begin
if (not White1.Checked) then
begin
FBackGroundColor := clWhite;
FalseColors;
{ White1.Checked:=(Not White1.Checked); }
end;
end;
procedure TMainForm.Mine1Click(Sender: TObject);
begin
if (not Mine1.Checked) then
begin
FBackGroundColor := MineBackgroundColor;
FalseColors;
end;
end;
procedure TMainForm.Bomb1Click(Sender: TObject);
begin
if (not Bomb1.Checked) then
begin
FBackGroundColor := BombBackgroundColor;
FalseColors;
end;
end;
procedure TMainForm.BombColorClick(Sender: TObject);
begin
{ BombBackgroundColor, MineBackgroundColor, }
ColorDialog1.Color := BombBackgroundColor;
if ColorDialog1.Execute then
begin
BombBackgroundColor := ColorDialog1.Color;
BombColor.Color := ColorDialog1.Color;
DoBomber;
end;
end;
procedure TMainForm.MineColorClick(Sender: TObject);
begin
{ BombBackgroundColor, MineBackgroundColor, }
ColorDialog1.Color := MineBackgroundColor;
if ColorDialog1.Execute then
begin
MineBackgroundColor := ColorDialog1.Color;
MineColor.Color := ColorDialog1.Color;
DoMiner;
end;
end;
procedure TMainForm.DoMiner;
begin { Make a bitmap and paint it background color
then assign it to the menu bitmap
save the bitmap as the MINE.BMP }
MainForm.Mine1.Bitmap.Canvas.Brush.Color := MineBackgroundColor;
MainForm.Mine1.Bitmap.Canvas.Pen.Color := MineBackgroundColor;
MainForm.Mine1.Bitmap.Canvas.Brush.Style := bsSolid;
MainForm.Mine1.Bitmap.Canvas.FillRect
(Rect(1, 1, (MainForm.Mine1.Bitmap.Width), (MainForm.Mine1.Bitmap.Height)));
MainForm.Mine1.Bitmap.Canvas.Draw(0, 0, MainForm.Mine1.Bitmap);
MainForm.Mine1.Bitmap.SaveToFile('MINE.BMP');
end;
procedure TMainForm.DoBomber;
begin
MainForm.Bomb1.Bitmap.Canvas.Brush.Color := BombBackgroundColor;
MainForm.Bomb1.Bitmap.Canvas.Pen.Color := BombBackgroundColor;
MainForm.Bomb1.Bitmap.Canvas.Brush.Style := bsSolid;
MainForm.Bomb1.Bitmap.Canvas.FillRect
(Rect(1, 1, (MainForm.Bomb1.Bitmap.Width), (MainForm.Bomb1.Bitmap.Height)));
MainForm.Bomb1.Bitmap.Canvas.Draw(0, 0, MainForm.Bomb1.Bitmap);
MainForm.Bomb1.Bitmap.SaveToFile('BOMB.BMP');
end;
(* *********************************************************** *)
procedure TMainForm.Set16Colors;
var
F_File: file of TColor;
TempColor: TColor;
i: Integer;
begin
case Colorset16 of
1:
begin { Win16 }
Win16Set.Checked := True;
RGBArray[0, 0] := 0;
RGBArray[1, 0] := 0;
RGBArray[2, 0] := 0;
RGBArray[0, 1] := 128;
RGBArray[1, 1] := 0;
RGBArray[2, 1] := 0;
RGBArray[0, 2] := 0;
RGBArray[1, 2] := 128;
RGBArray[2, 2] := 0;
RGBArray[0, 3] := 128;
RGBArray[1, 3] := 128;
RGBArray[2, 3] := 0;
RGBArray[0, 4] := 0;
RGBArray[1, 4] := 0;
RGBArray[2, 4] := 128;
RGBArray[0, 5] := 128;
RGBArray[1, 5] := 0;
RGBArray[2, 5] := 128;
RGBArray[0, 6] := 0;
RGBArray[1, 6] := 128;
RGBArray[2, 6] := 128;
RGBArray[0, 7] := 192;
RGBArray[1, 7] := 192;
RGBArray[2, 7] := 192;
RGBArray[0, 8] := 128;
RGBArray[1, 8] := 128;
RGBArray[2, 8] := 128;
RGBArray[0, 9] := 255;
RGBArray[1, 9] := 0;
RGBArray[2, 9] := 0;
RGBArray[0, 10] := 0;
RGBArray[1, 10] := 255;
RGBArray[2, 10] := 0;
RGBArray[0, 11] := 255;
RGBArray[1, 11] := 255;
RGBArray[2, 11] := 0;
RGBArray[0, 12] := 0;
RGBArray[1, 12] := 0;
RGBArray[2, 12] := 255;
RGBArray[0, 13] := 255;
RGBArray[1, 13] := 0;
RGBArray[2, 13] := 255;
RGBArray[0, 14] := 0;
RGBArray[1, 14] := 255;
RGBArray[2, 14] := 255;
RGBArray[0, 15] := 255;
RGBArray[1, 15] := 255;
RGBArray[2, 15] := 255;
end;
2:
begin { RGB }
RGB16.Checked := True;
RGBArray[0, 0] := 255;
RGBArray[1, 0] := 0;
RGBArray[2, 0] := 0;
RGBArray[0, 1] := 225;
RGBArray[1, 1] := 0;
RGBArray[2, 1] := 0;
RGBArray[0, 2] := 210;
RGBArray[1, 2] := 0;
RGBArray[2, 2] := 0;
RGBArray[0, 3] := 195;
RGBArray[1, 3] := 0;
RGBArray[2, 3] := 0;
RGBArray[0, 4] := 180;
RGBArray[1, 4] := 0;
RGBArray[2, 4] := 0;
RGBArray[0, 5] := 0;
RGBArray[1, 5] := 255;
RGBArray[2, 5] := 0;
RGBArray[0, 6] := 0;
RGBArray[1, 6] := 225;
RGBArray[2, 6] := 0;
RGBArray[0, 7] := 0;
RGBArray[1, 7] := 210;
RGBArray[2, 7] := 0;
RGBArray[0, 8] := 0;
RGBArray[1, 8] := 195;
RGBArray[2, 8] := 0;
RGBArray[0, 9] := 0;
RGBArray[1, 9] := 180;
RGBArray[2, 9] := 0;
RGBArray[0, 10] := 0;
RGBArray[1, 10] := 0;
RGBArray[2, 10] := 255;
RGBArray[0, 11] := 0;
RGBArray[1, 11] := 0;
RGBArray[2, 11] := 240;
RGBArray[0, 12] := 0;
RGBArray[1, 12] := 0;
RGBArray[2, 12] := 225;
RGBArray[0, 13] := 0;
RGBArray[1, 13] := 0;
RGBArray[2, 13] := 210;
RGBArray[0, 14] := 0;
RGBArray[1, 14] := 0;
RGBArray[2, 14] := 195;
RGBArray[0, 15] := 0;
RGBArray[1, 15] := 0;
RGBArray[2, 15] := 180;
end;
3:
begin { Landforms }
LandformsSet.Checked := True;
RGBArray[0, 0] := 0;
RGBArray[1, 0] := 0;
RGBArray[2, 0] := 128;
RGBArray[0, 1] := 0;
RGBArray[1, 1] := 0;
RGBArray[2, 1] := 255;
RGBArray[0, 2] := 0;
RGBArray[1, 2] := 128;
RGBArray[2, 2] := 128;
RGBArray[0, 3] := 0;
RGBArray[1, 3] := 255;
RGBArray[2, 3] := 255;
RGBArray[0, 4] := 255;
RGBArray[1, 4] := 255;
RGBArray[2, 4] := 0;
RGBArray[0, 5] := 128;
RGBArray[1, 5] := 128;
RGBArray[2, 5] := 0;
RGBArray[0, 6] := 0;
RGBArray[1, 6] := 255;
RGBArray[2, 6] := 0;
RGBArray[0, 7] := 0;
RGBArray[1, 7] := 128;
RGBArray[2, 7] := 0;
RGBArray[0, 8] := 128;
RGBArray[1, 8] := 128;
RGBArray[2, 8] := 128;
RGBArray[0, 9] := 255;
RGBArray[1, 9] := 0;
RGBArray[2, 9] := 255;
RGBArray[0, 10] := 128;
RGBArray[1, 10] := 0;
RGBArray[2, 10] := 128;
RGBArray[0, 11] := 192;
RGBArray[1, 11] := 192;
RGBArray[2, 11] := 192;
RGBArray[0, 12] := 255;
RGBArray[1, 12] := 0;
RGBArray[2, 12] := 0;
RGBArray[0, 13] := 128;
RGBArray[1, 13] := 0;
RGBArray[2, 13] := 0;
RGBArray[0, 14] := 255;
RGBArray[1, 14] := 255;
RGBArray[2, 14] := 255;
RGBArray[0, 15] := 0;
RGBArray[1, 15] := 0;
RGBArray[2, 15] := 0;
end;
4:
begin { Picker }
ColorPicker16.Checked := True;
RGBArray[0, 0] := 0;
RGBArray[1, 0] := 0;
RGBArray[2, 0] := 128;
RGBArray[0, 1] := 0;
RGBArray[1, 1] := 0;
RGBArray[2, 1] := 255;
RGBArray[0, 2] := 0;
RGBArray[1, 2] := 128;
RGBArray[2, 2] := 128;
RGBArray[0, 3] := 0;
RGBArray[1, 3] := 255;
RGBArray[2, 3] := 255;
RGBArray[0, 4] := 255;
RGBArray[1, 4] := 255;
RGBArray[2, 4] := 0;
RGBArray[0, 5] := 128;
RGBArray[1, 5] := 128;
RGBArray[2, 5] := 0;
RGBArray[0, 6] := 0;
RGBArray[1, 6] := 255;
RGBArray[2, 6] := 0;
RGBArray[0, 7] := 0;
RGBArray[1, 7] := 128;
RGBArray[2, 7] := 0;
RGBArray[0, 8] := 128;
RGBArray[1, 8] := 128;
RGBArray[2, 8] := 128;
RGBArray[0, 9] := 255;
RGBArray[1, 9] := 0;
RGBArray[2, 9] := 255;
RGBArray[0, 10] := 128;
RGBArray[1, 10] := 0;
RGBArray[2, 10] := 128;
RGBArray[0, 11] := 192;
RGBArray[1, 11] := 192;
RGBArray[2, 11] := 192;
RGBArray[0, 12] := 255;
RGBArray[1, 12] := 0;
RGBArray[2, 12] := 0;
RGBArray[0, 13] := 128;
RGBArray[1, 13] := 0;
RGBArray[2, 13] := 0;
RGBArray[0, 14] := 255;
RGBArray[1, 14] := 255;
RGBArray[2, 14] := 255;
RGBArray[0, 15] := 0;
RGBArray[1, 15] := 0;
RGBArray[2, 15] := 0;
end;
5:
begin { Loader }
Loaded16.Checked := True;
{ Load the Filename as the selected set??? }
if (FileExists(Color16Name)) then
begin
AssignFile(F_File, Color16Name);
Reset(F_File);
if IoResult <> 0 then
begin
DoMessages(30091);
end;
for i := 0 to 15 do
begin
Read(F_File, TempColor);
RGBArray[0, i] := GetRValue(TempColor);
RGBArray[1, i] := GetGValue(TempColor);
RGBArray[2, i] := GetBValue(TempColor);
end;
end
else
DoMessages(30092);
end;
end; { of case }
end;
procedure TMainForm.False16;
begin
Win16Set.Checked := False;
RGB16.Checked := False;
LandformsSet.Checked := False;
ColorPicker16.Checked := False;
Loaded16.Checked := False;
Set16Colors;
end;
procedure TMainForm.Win16SetClick(Sender: TObject);
begin
if (not Win16Set.Checked) then
begin
Colorset16 := 1;
False16;
end;
end;
procedure TMainForm.RGB16Click(Sender: TObject);
begin
if (not RGB16.Checked) then
begin
Colorset16 := 2;
False16;
end;
end;
procedure TMainForm.LandformsSetClick(Sender: TObject);
begin
if (not LandformsSet.Checked) then
begin
Colorset16 := 3;
False16;
end;
end;
procedure TMainForm.ColorPicker16Click(Sender: TObject);
begin
if (not ColorPicker16.Checked) then
begin
Colorset16 := 4;
False16;
end;
end;
procedure TMainForm.Loaded16Click(Sender: TObject);
begin
if (not Loaded16.Checked) then
begin
Colorset16 := 5;
False16;
end;
end;
(* *********************************************************** *)
procedure TMainForm.SiliconSets;
var
F_File: file of TColor;
i: Integer;
begin
case Color256S of
1:
begin
BlueMeanie256.Checked := True;
for i := 0 to 255 do
begin
Colors[0, i] := 0;
Colors[1, i] := 0;
Colors[2, i] := 255 - i;
end;
end;
2:
begin
AquaMarine256.Checked := True;
for i := 0 to 255 do
begin
Colors[0, i] := 0;
Colors[1, i] := 255 - i;
Colors[2, i] := 255 - i;
end;
end;
3:
begin
GreenGoblin256.Checked := True;
for i := 0 to 255 do
begin
Colors[0, i] := 0;
Colors[1, i] := 255 - i;
Colors[2, i] := 0;
end;
end;
4:
begin
YellowSnow256.Checked := True;
for i := 0 to 255 do
begin
Colors[0, i] := 255 - i;
Colors[1, i] := 255 - i;
Colors[2, i] := 0;
end;
end;
5:
begin
PurpleReigns256.Checked := True;
for i := 0 to 255 do
begin
Colors[0, i] := 255 - i;
Colors[1, i] := 0;
Colors[2, i] := 255 - i;
end;
end;
6:
begin
RedRanger256.Checked := True;
for i := 0 to 255 do
begin
Colors[0, i] := 255 - i;
Colors[1, i] := 0;
Colors[2, i] := 0;
end;
end;
7:
begin
SmogFog256.Checked := True;
for i := 0 to 255 do
begin
Colors[0, i] := 255 - i;
Colors[1, i] := 255 - i;
Colors[2, i] := 255 - i;
end;
end;
8:
begin
ColorPicker256.Checked := True;
for i := 0 to 255 do
begin
Colors[0, i] := GetRValue(ColorArray[i]);
Colors[1, i] := GetGValue(ColorArray[i]);
Colors[2, i] := GetBValue(ColorArray[i]);
end;
end;
9:
begin { Load filename set }
if (FileExists(Color256Name)) then
begin
Loaded256.Checked := True;
AssignFile(F_File, Color256Name);
Reset(F_File);
if IoResult <> 0 then
begin
DoMessages(30091);
end
else
begin
for i := 0 to 255 do
Read(F_File, ColorArray[i]);
CloseFile(F_File);
for i := 0 to 255 do
begin
Colors[0, i] := GetRValue(ColorArray[i]);
Colors[1, i] := GetGValue(ColorArray[i]);
Colors[2, i] := GetBValue(ColorArray[i]);
end;
end;
end
else
DoMessages(30092);
end;
10:
begin { Load filename set }
if (FileExists(Color256TooName)) then
begin
LoadedToo56.Checked := True;;
AssignFile(F_File, Color256TooName);
Reset(F_File);
if IoResult <> 0 then
begin
DoMessages(30091);
end
else
begin
for i := 0 to 255 do
Read(F_File, ColorArray[i]);
CloseFile(F_File);
for i := 0 to 255 do
begin
Colors[0, i] := GetRValue(ColorArray[i]);
Colors[1, i] := GetGValue(ColorArray[i]);
Colors[2, i] := GetBValue(ColorArray[i]);
end;
end;
end
else
DoMessages(30092);
end;
end; { of case }
end;
procedure TMainForm.FalseSets;
begin
BlueMeanie256.Checked := False;
AquaMarine256.Checked := False;
GreenGoblin256.Checked := False;
YellowSnow256.Checked := False;
PurpleReigns256.Checked := False;
RedRanger256.Checked := False;
SmogFog256.Checked := False;
ColorPicker256.Checked := False;
Loaded256.Checked := False;
LoadedToo56.Checked := False;
SiliconSets;
end;
procedure TMainForm.BlueMeanie256Click(Sender: TObject);
begin
if (not BlueMeanie256.Checked) then
begin
Color256S := 1;
FalseSets;
{ BlueMeanie256.Checked:=(Not BlueMeanie256.Checked); }
end;
end;
procedure TMainForm.AquaMarine256Click(Sender: TObject);
begin
if (not AquaMarine256.Checked) then
begin
Color256S := 2;
FalseSets;
{ AquaMarine256.Checked:=(Not AquaMarine256.Checked); }
end;
end;
procedure TMainForm.GreenGoblin256Click(Sender: TObject);
begin
if (not GreenGoblin256.Checked) then
begin
Color256S := 3;
FalseSets;
{ GreenGoblin256.Checked:=(Not GreenGoblin256.Checked); }
end;
end;
procedure TMainForm.YellowSnow256Click(Sender: TObject);
begin
if (not YellowSnow256.Checked) then
begin
Color256S := 4;
FalseSets;
{ YellowSnow256.Checked:=(Not YellowSnow256.Checked); }
end;
end;
procedure TMainForm.PurpleReigns256Click(Sender: TObject);
begin
if (not PurpleReigns256.Checked) then
begin
Color256S := 5;
FalseSets;
{ PurpleReigns256.Checked:=(Not PurpleReigns256.Checked); }
end;
end;
procedure TMainForm.RedRanger256Click(Sender: TObject);
begin
if (not RedRanger256.Checked) then
begin
Color256S := 6;
FalseSets;
{ RedRanger256.Checked:=(Not RedRanger256.Checked); }
end;
end;
procedure TMainForm.SmogFog256Click(Sender: TObject);
begin
if (not SmogFog256.Checked) then
begin
Color256S := 7;
FalseSets;
{ SmogFog256.Checked:=(Not SmogFog256.Checked); }
end;
end;
procedure TMainForm.ColorPicker256Click(Sender: TObject);
begin
if (not ColorPicker256.Checked) then
begin
Color256S := 8;
FalseSets;
{ ColorPicker256.Checked:=(Not ColorPicker256.Checked); }
end;
end;
procedure TMainForm.Loaded256Click(Sender: TObject);
begin
if (not Loaded256.Checked) then
begin
Color256S := 9;
FalseSets;
{ Loaded256.Checked:=(Not Loaded256.Checked); }
end;
end;
(* *********************************************************** *)
procedure TMainForm.LoadedToo56Click(Sender: TObject);
begin
if (not LoadedToo56.Checked) then
begin
Color256S := 10;
FalseSets;
{ LoadedToo56.Checked:=(Not LoadedToo56.Checked); }
end;
end;
(* *********************************************************** *)
procedure TMainForm.Image2Progress(Sender: TObject; Stage: TProgressStage;
PercentDone: Byte; RedrawNow: Boolean; const R: TRect; const Msg: string);
begin
if Stage = psRunning then
MainForm.Caption := 'Fractal 3D: Math Graphics working... ' +
Format('%d%%', [PercentDone])
else
MainForm.Caption := 'Fractal 3D: Math Graphics';
end;
procedure TMainForm.AlarmBtnClick(Sender: TObject);
begin { Set Alarm Boolean for access by Image Processors }
if (not ImageDoneAlarm.Checked) then
begin
ImageDoneAlarm.Checked := True;
ImageDoneVoices.Checked := False;
ImageDoneAlarmb := True;
IamDone := 1;
end
else
begin
ImageDoneAlarm.Checked := False;
ImageDoneVoices.Checked := False;
ImageDoneAlarmb := False;
IamDone := 0;
end;
end;
procedure TMainForm.ImageDoneVoicesClick(Sender: TObject);
begin { Set Alarm Boolean for access by Image Processors }
if (not ImageDoneVoices.Checked) then
begin
ImageDoneAlarm.Checked := False;
ImageDoneVoices.Checked := True;
ImageDoneAlarmb := True;
IamDone := 2;
end
else
begin
ImageDoneAlarm.Checked := False;
ImageDoneVoices.Checked := False;
ImageDoneAlarmb := False;
IamDone := 0;
end;
end;
procedure TMainForm.ImageOverDone;
begin
case IamDone of
0:
begin
ImageDoneAlarm.Checked := False;
ImageDoneVoices.Checked := False;
ImageDoneAlarmb := False;
end;
1:
begin
ImageDoneAlarm.Checked := True;
ImageDoneVoices.Checked := False;
ImageDoneAlarmb := True;
end;
2:
begin
ImageDoneAlarm.Checked := False;
ImageDoneVoices.Checked := True;
ImageDoneAlarmb := True;
end;
end; { case }
end;
procedure TMainForm.PlaySound(WavFileName: string);
var
s: array [0 .. 79] of char;
begin
{ Convert filename to a null-terminated string }
StrPCopy(s, WavFileName);
{ Play the sound asynchronously }
sndPlaySound(s, 0); { see mmsystem.hlp for other values }
end;
procedure TMainForm.EditCropItemClick(Sender: TObject);
begin { Crop off edges with mouse }
Cropping := 1;
end;
procedure TMainForm.EditCut(Sender: TObject);
begin { Add code to Cut out center }
Cropping := 2;
end;
procedure TMainForm.EditClearAllItemClick(Sender: TObject);
begin
{ erase the screen }
end;
procedure TMainForm.EditCopy(Sender: TObject);
begin { Add code to Copy ALL of Image }
Clipboard.assign(Image2.Picture);
end;
(* *********************************************************** *)
procedure TMainForm.EditCopyAreaItemClick(Sender: TObject);
begin
{ Copy the moused area, leave the image uncut }
Cropping := 3;
end;
(* *********************************************************** *)
procedure TMainForm.EditPaste(Sender: TObject);
begin { is there a bitmap on the Clipboard? }
if Clipboard.HasFormat(CF_BITMAP) then
begin
Image2.Picture.Bitmap.assign(Clipboard);
end;
end;
(* *********************************************************** *)
procedure TMainForm.EditPasteIntoItemClick(Sender: TObject);
begin { Mouse an area to paste the clipboard into }
Cropping := 4;
end;
(* *********************************************************** *)
procedure TMainForm.EditCropper;
var
AllRect, Arect: TRect;
CropImage: TBitmap;
begin
case Cropping of
1: { Crop off outside }
begin
CropImage := TBitmap.Create;
CropImage.PixelFormat := MyPixelFormat; { pf24bit; }
CropImage.Width := Origin.X - MovePt.X;
CropImage.Height := Origin.Y - MovePt.Y;
AllRect := Rect(0, 0, CropImage.Width - 1, CropImage.Height - 1);
Arect := Rect(Origin.X, Origin.Y, MovePt.X, MovePt.Y);
CropImage.Canvas.CopyMode := cmSrcCopy;
CropImage.Canvas.CopyRect(AllRect, Image2.Canvas, Arect);
Image2.Picture.Graphic := CropImage;
CropImage.Free;
end;
2: { Cut out center }
begin
CropImage := TBitmap.Create;
CropImage.PixelFormat := MyPixelFormat; { pf24bit; }
CropImage.Width := Origin.X - MovePt.X;
CropImage.Height := Origin.Y - MovePt.Y;
AllRect := Rect(0, 0, CropImage.Width - 1, CropImage.Height - 1);
Arect := Rect(Origin.X, Origin.Y, MovePt.X, MovePt.Y);
CropImage.Canvas.CopyMode := cmSrcCopy;
CropImage.Canvas.CopyRect(AllRect, Image2.Canvas, Arect);
Clipboard.assign(CropImage);
with Image2.Canvas do
begin
CopyMode := cmWhiteness; { copy everything as white }
{ get bitmap rectangle
Origin := Point(X, Y);
MovePt := Point(X, Y); }
Arect := Rect(Origin.X, Origin.Y, MovePt.X, MovePt.Y);
CopyRect(Arect, Image2.Canvas, Arect);
{ copy bitmap over itself }
CopyMode := cmSrcCopy; { restore normal mode }
end;
end;
3: { Copy area, leave alone }
begin
CropImage := TBitmap.Create;
CropImage.PixelFormat := MyPixelFormat; { pf24bit; }
CropImage.Width := Origin.X - MovePt.X;
CropImage.Height := Origin.Y - MovePt.Y;
AllRect := Rect(0, 0, CropImage.Width - 1, CropImage.Height - 1);
Arect := Rect(Origin.X, Origin.Y, MovePt.X, MovePt.Y);
CropImage.Canvas.CopyMode := cmSrcCopy;
CropImage.Canvas.CopyRect(AllRect, Image2.Canvas, Arect);
Clipboard.assign(CropImage);
{ Clip owns it... ? CropImage.Free; }
end;
4: { Paste into }
begin
CropImage := TBitmap.Create;
CropImage.assign(Clipboard);
Arect := Rect(Origin.X, Origin.Y, MovePt.X, MovePt.Y);
MainForm.Image2.Canvas.StretchDraw(Arect, CropImage);
CropImage.Free;
end;
end; { case }
Cropping := 0;
{ Check Clipboard:
if available then enable clipboard items }
if Clipboard.HasFormat(CF_BITMAP) then
begin
PasteButton.Enabled := True;
PasteArea.Enabled := True;
EditPasteItem.Enabled := True;
EditPasteIntoItem.Enabled := True;
end
else
begin
PasteButton.Enabled := False;
PasteArea.Enabled := False;
EditPasteItem.Enabled := False;
EditPasteIntoItem.Enabled := False;
end;
end;
(* *********************************************************** *)
{ (UnZoom) Change Zoom back to 1:1 }
procedure TMainForm.UnZoom1to1Click(Sender: TObject);
begin
UnZoom;
end;
procedure TMainForm.UnZoom;
begin { assign the bitmap to the image control }
if (ZoomingOn) then
begin { RESET All parameters }
Image2.Picture.Bitmap.Width := FYImageX;
Image2.Picture.Bitmap.Height := FYImageY;
Image2.Picture.Graphic.assign(BitmapF);
ZoomingOn := False;
{ ImageZoomRatio:=0;
ImageZoomRatioEx:=0;
ZoomOriginX:=0;
ZoomOriginY:=0;
ZoomImageX:= FYImageX;
ZoomImageY:= FYImageY; }
end;
end;
(* *********************************************************** *)
procedure TMainForm.ZoomMachine;
begin { Prepare to Zoom }
ZoomingOn := True;
ImageZoomRatio := 0;
ImageZoomRatioEx := 0;
ZoomImageX := FYImageX;
ZoomImageY := FYImageY;
ZoomOriginX := 0;
ZoomOriginY := 0;
BitmapF.assign(Image2.Picture.Bitmap);
end;
(* *********************************************************** *)
procedure TMainForm.ZoomOut1Click(Sender: TObject);
begin { Reduce Zoom Ratio }
if (not ZoomingOn) then
ZoomMachine;
{ ImageZoomRatio:=(ImageZoomRatio div 2);
ImageZoomRatioEx:=(ImageZoomRatioEx / 2);
ZoomImageX:=(ImageZoomRatio * ZoomImageX);
ZoomImageY:=(ImageZoomRatio * ZoomImageY);
ZoomOriginX:= (ZoomOriginX div 2);
ZoomOriginY:= (ZoomOriginY div 2);
}
{ Image1.Picture.Bitmap.Width := ZoomImageX;
Image1.Picture.Bitmap.Height := ZoomImageY; }
{ BitmapF :=Image1.Picture.Bitmap; }
end;
(* *********************************************************** *)
procedure TMainForm.ZoomMouseClick(Sender: TObject);
begin
if (not ZoomingOn) then
ZoomMachine;
bZoomMousing := True;
end;
(* *********************************************************** *)
procedure TMainForm.ZoomMouseDo;
var
FiTemp: Integer;
a, b, c: Extended;
begin
{ Select area - Make it correct - change bitmap }
if (Origin.X > MovePt.X) then
begin
FiTemp := Origin.X;
Origin.X := MovePt.X;
MovePt.X := FiTemp;
end;
if (Origin.Y > MovePt.Y) then
begin
FiTemp := Origin.Y;
Origin.Y := MovePt.Y;
MovePt.Y := FiTemp;
end;
{ based on 0,0, upper left, then lower right
640,480 Numbers provide Ratio not image size just use 4,3 }
a := ((480 * (MovePt.X - Origin.X)) / 640);
b := (((MovePt.Y - Origin.Y) - a) / 2);
if (a > (MovePt.Y - Origin.Y)) then
begin
a := Origin.Y - b;
c := MovePt.Y + b;
end
else
begin
a := Origin.Y + b;
c := MovePt.Y - b;
end;
Origin.Y := round(a);
MovePt.Y := round(c);
ZSARect := Rect(Origin.X, Origin.Y, MovePt.X, MovePt.Y);
ZDAllRect := Rect(0, 0, ScrollBox1.Width - 4 { Image1.Width } ,
ScrollBox1.Height - 4
{ Image1.Height } );
Image2.Picture.Bitmap.Width := ScrollBox1.Width - 4;
Image2.Picture.Bitmap.Height := ScrollBox1.Height - 4;
ZoomImageX := Image2.Picture.Bitmap.Width;
ZoomImageY := Image2.Picture.Bitmap.Height;
Image2.Picture.Bitmap.Canvas.CopyMode := cmSrcCopy;
{ procedure CopyRect(Dest: TRect; Canvas: TCanvas; Source: TRect); }
Image2.Picture.Bitmap.Canvas.CopyRect(ZDAllRect, BitmapF.Canvas, ZSARect);
bZoomMousing := False;
end;
(* *********************************************************** *)
procedure TMainForm.ZoomToWindowClick(Sender: TObject);
begin { If (not ZoomingOn) then ZoomMachine; }
if (not ZoomingOn) then
ZoomMachine;
{ Get window size,
ScrollBox1.Width
ScrollBox1.Height
change bitmap to closest ratio }
ZSARect := Rect(0, 0, Image2.Width - 1, Image2.Height - 1);
ZDAllRect := Rect(0, 0, ScrollBox1.Width - 4 { Image1.Width } ,
ScrollBox1.Height - 4
{ Image1.Height } );
Image2.Picture.Bitmap.Width := ScrollBox1.Width - 4;
Image2.Picture.Bitmap.Height := ScrollBox1.Height - 4;
ZoomImageX := Image2.Picture.Bitmap.Width;
ZoomImageY := Image2.Picture.Bitmap.Height;
Image2.Picture.Bitmap.Canvas.CopyMode := cmSrcCopy;
Image2.Picture.Bitmap.Canvas.CopyRect(ZDAllRect, BitmapF.Canvas, ZSARect);
end;
(* *********************************************************** *)
procedure TMainForm.DoImageStart;
var
TempColor: TColor;
{ Save_Cursor:TCursor; }
begin
Screen.Cursor := crHourglass; { Show hourglass cursor }
{ IF Zooming then Unzoom and remember settings }
if (ZoomingOn) then
begin
UnZoom;
WasZooming := True;
end;
{ Set up the Image, procedures set their own title
so that Vista does NOT have titles all over the place }
with MainForm.Image2.Canvas do
begin
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, FYImageX, FYImageY));
TempColor := RGB(255 - GetRValue(FBackGroundColor),
255 - GetGValue(FBackGroundColor), 255 - GetBValue(FBackGroundColor));
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
end;
end;
{ If ImageDoneAlarmb then DoImageDone; }
procedure TMainForm.DoImageDone;
var
PathS: string;
begin
if ImageDoneAlarmb then
begin
if ImageDoneAlarm.Checked then
begin
Beep;
end
else if ImageDoneVoices.Checked then
begin
PathS := ExtractFilePath(ParamStr(0)) + 'DONE.WAV';
PlaySound(PathS);
end;
end;
BitmapF.assign(Image2.Picture.Bitmap);
if WasZooming then
begin
Image2.Picture.Bitmap.Width := ZoomImageX;
Image2.Picture.Bitmap.Height := ZoomImageY;
Image2.Picture.Bitmap.Canvas.CopyMode := cmSrcCopy;
Image2.Picture.Bitmap.Canvas.CopyRect(ZDAllRect, BitmapF.Canvas, ZSARect);
{ ZSARect := Rect(0,0,
Image2.Width-1,Image2.Height-1);
ZDAllRect := Rect(0,0,
ScrollBox1.Width-4,ScrollBox1.Height-4); }
WasZooming := False;
ZoomingOn := True;
end;
Screen.Cursor := crDefault; { Always restore to normal }
end;
(* *********************************************************** *)
procedure TMainForm.ResizeImageClick(Sender: TObject);
var
a, b: Double;
ResizeX, ResizeY, Code: Integer;
Arect, AllRect: TRect;
begin
if (ResizeForm.ShowModal = mrOK) then
begin
val(ResizeForm.HeightEdit.Text, ResizeY, Code);
val(ResizeForm.WidthEdit.Text, ResizeX, Code);
a := ((3 * (ResizeX)) / 4);
b := (((ResizeY) - a));
if (a > (ResizeY)) then
a := ResizeY + b
else
a := ResizeY - b;
ResizeY := round(a);
AllRect := Rect(0, 0, Image2.Width - 1, Image2.Height - 1);
UnZoom;
BitmapF.assign(Image2.Picture.Bitmap);
Arect := Rect(0, 0, ResizeX - 1, ResizeY - 1);
SetStretchBltMode(Image2.Picture.Bitmap.Canvas.Handle, HALFTONE
{ STRETCH_DELETESCANS } );
{ BOOL SetBrushOrgEx(
HDC hdc, // handle of device context
int nXOrg, // x-coordinate of new origin
int nYOrg, // y-coordinate of new origin
LPPOINT lppt // points to previous brush origin
); } SetBrushOrgEx(Image2.Picture.Bitmap.Canvas.Handle, 0, 0, nil);
Image2.Picture.Bitmap.Canvas.CopyMode := cmSrcCopy;
{ procedure CopyRect(Dest: TRect; Canvas: TCanvas; Source: TRect); }
Image2.Picture.Bitmap.Canvas.CopyRect(Arect, BitmapF.Canvas, AllRect);
Image2.Picture.Bitmap.Width := ResizeX;
Image2.Picture.Bitmap.Height := ResizeY;
BitmapF.assign(Image2.Picture.Bitmap);
FYImageX := ResizeX;
FYImageY := ResizeY;
SetImageSize;
end;
end;
(* *********************************************************** *)
{ Change Image Size }
procedure TMainForm.OverBit;
begin
{ kill old bitmap(s) ? }
BitmapF.Free;
BitmapF := TBitmap.Create; { construct the bitmap object }
{ property PixelFormat: TPixelFormat;
type TPixelFormat = (pfDevice, pf1bit, pf4bit, pf8bit, pf15bit, pf16bit,
pf24bit, pf32bit, pfCustom); }
BitmapF.PixelFormat := MyPixelFormat; { pf24bit; }
BitmapF.Width := FYImageX; { assign the initial width... }
BitmapF.Height := FYImageY; { ...and the initial height }
Image2.Picture.Graphic := BitmapF;
{ VImage.Picture.Graphic := BitmapF; }
{ RESET ZOOM STUFF }
{ assign the bitmap to the image control }
ImageZoomRatio := 0;
ImageZoomRatioEx := 0;
ZoomingOn := False;
bZoomMousing := False;
WasZooming := False;
end;
(* *********************************************************** *)
(* *********************************************************** *)
(*
begin
Application.Initialize;
with TSplashScreen.Create(nil) do
try
ProgressBar1.Max := 100;
Show; // show a splash screen contain ProgressBar control
Update; // force display of Form5
Application.Title := 'Fractl3D';
Application.CreateForm(TMainForm, MainForm);
ProgressBar1.StepIt;
Application.CreateForm(TFractalForm, FractalForm);
ProgressBar1.StepIt;
Application.CreateForm(TMathForm, MathForm);
ProgressBar1.StepIt;
Application.CreateForm(TAnnotationForm, AnnotationForm);
Application.CreateForm(TDIYStyleForm, DIYStyleForm);
ProgressBar1.StepIt;
Application.CreateForm(TJPEGForm, JPEGForm);
Application.CreateForm(TResizeForm, ResizeForm);
ProgressBar1.StepIt;
Application.CreateForm(TSystemInfoForm, SystemInfoForm);
ProgressBar1.StepIt;
Application.CreateForm(TXYZ3DForm, XYZ3DForm);
Application.CreateForm(TAboutBox, AboutBox);
ProgressBar1.StepIt;
Application.CreateForm(TFMJForm, FMJForm);
ProgressBar1.StepIt;
Application.CreateForm(TXYZGL, XYZGL);
ProgressBar1.StepIt;
Application.CreateForm(TMathGL, MathGL);
ProgressBar1.StepIt;
finally
Free;
end;
Application.Run;
end. *)
(* *********************************************************** *)
end.
|
unit ADSchemaTypes;
interface
uses Windows, Classes;
type
{ Enum for error types }
ErrorTypeEnum = (
SuccessStatus,
LDAPError,
ADSchemaError);
{ Status model
*gets error number and forms output message }
ADSchemaStatus = class
strict private
pvErrorNumb : integer;
pvErrorType : ErrorTypeEnum;
pvErrorMsg : string;
function pvGetLDAPMsg(errorNumb : integer) : string;
function pvGetADSchemaMsg(errorNumb : integer) : string;
public
property StatusNumb : integer
read pvErrorNumb;
property StatusType : ErrorTypeEnum
read pvErrorType;
property StatusMsg : string
read pvErrorMsg;
{ Creates object and sets pvErrorMsg by erNumb and erType,
or leave it as it is }
constructor Create(erNumb : integer;
erType : ErrorTypeEnum;
erMsg : string); overload;
{ Creates and sets pvErrorMsg=0 and pvErrorMsg=Success }
constructor Create(); overload;
end;
{ Attribute model }
ADAttribute = class
strict private
AttributeName : string;
AttributeValues : TStringList;
function GetValuesCount() : integer;
function GetValue(index : integer) : string;
procedure SetValue(index : integer; value : string);
public
property Name : string
read AttributeName
write AttributeName;
property Values[index : integer] : string
read GetValue
write SetValue;
property ValuesCount : integer
read GetValuesCount;
function GetList() : TStringList;
function SearchValue(value : string) : integer;
procedure AddValue(value : string);
procedure DeleteValue(valueIndex : integer);
constructor Create(attrName : string; attrValues : array of string); overload;
constructor Create(attrName : string); overload;
destructor Destroy(); override;
end;
{ Entry model }
ADEntry = class
strict private
EntryName : string;
EntryAttributes : TList;
function GetAttributesCount() : integer;
function GetAttribute(index : integer) : ADAttribute;
//Because of memory risks
//procedure SetAttribute(index : integer; value : ADAttribute);
public
property Name : string
read EntryName
write EntryName;
property Attributes[index : integer] : ADAttribute
read GetAttribute;
//write SetAttribute;
property AttributesCount : integer
read GetAttributesCount;
function GetList() : TList;
function GetAttributeByName(attrName : string) : ADAttribute;
function AddAttribute(attribute : ADAttribute) : integer; overload;
function AddAttribute(attrName : string; attrValues : array of string) : integer; overload;
function AddAttribute(attrName : string) : integer; overload;
procedure DeleteAttribute(index : integer); overload;
procedure DeleteAttribute(name : string); overload;
constructor Create(entrName : string); overload;
constructor Create(entrName : string; attrs : array of ADAttribute); overload;
destructor Destroy(); override;
end;
{ Entries List model }
ADEntryList = class
strict private
Entries : TList;
function GetEntriesCount() : integer;
function GetEntry(index : integer) : ADEntry;
public
property Items[index : integer] : ADEntry
read GetEntry;
property EntriesCount : integer
read GetEntriesCount;
function GetList() : TList;
function AddEntry(entry : ADEntry) : integer; overload;
function AddEntry(entryName : string) : integer; overload;
function AddEntry(entryName : string;
attrs : array of ADAttribute) : integer; overload;
procedure DeleteEntry(index : integer); overload;
procedure DeleteEntry(name : string); overload;
constructor Create();
destructor Destroy(); override;
end;
implementation
{ --------------------------------------------------------
------------------- IMPLEMENTATION ---------------------
------------------- ADSchemaStatus ---------------------
-------------------------------------------------------- }
{ Public }
constructor ADSchemaStatus.Create(erNumb : integer;
erType : ErrorTypeEnum;
erMsg : string);
var
res : string;
begin
pvErrorNumb := erNumb;
pvErrorType := erType;
pvErrorMsg := erMsg;
case erType of
LDAPError: res := pvGetLDAPMsg(erNumb);
ADSchemaError: res := pvGetADSchemaMsg(erNumb);
end;
if res <> '' then
pvErrorMsg := erMsg + ' --- ' + res;
end;
{ Public }
constructor ADSchemaStatus.Create();
begin
pvErrorNumb := 0;
pvErrorType := SuccessStatus;
pvErrorMsg := 'Success';
end;
{ Private }
function ADSchemaStatus.pvGetLDAPMsg(errorNumb : integer) : string;
var
res : string;
begin
//Make case of all LDAP errors { TODO: make message for every error }
case errorNumb of
1 : res := 'LDAP_OPERATIONS_ERROR: Indicates an internal error. The server is unable to respond with a more specific error and is also unable to properly respond to a request.';
2 : res := 'LDAP_PROTOCOL_ERROR: Indicates that the server has received an invalid or malformed request from the client.';
end;
Insert('LDAP ERROR: ', res, 0);
result := res;
end;
{ Private }
function ADSchemaStatus.pvGetADSchemaMsg(errorNumb : integer) : string;
var
res : string;
begin
//Make case of all ADSchema errors
case errorNumb of
1 : res := 'Cant set Schema DN!';
2 : res := 'Cant parse search results!';
3 : res := 'There is no all needed attributes in Entry!';
4 : res := 'Invalid password or user is not in schema admin group!';
end;
Insert('ADSchema ERROR: ', res, 0);
result := res;
end;
{ --------------------------------------------------------
------------------- IMPLEMENTATION ---------------------
------------------- ADAttribute ------------------------
-------------------------------------------------------- }
{ Public }
constructor ADAttribute.Create(attrName : string; attrValues : array of string);
var
i : integer;
begin
AttributeName := attrName;
AttributeValues := TStringList.Create;
for i := 0 to Length(attrValues) - 1 do
AttributeValues.Add(attrValues[i]);
end;
{ Public }
constructor ADAttribute.Create(attrName : string);
begin
AttributeName := attrName;
AttributeValues := TStringList.Create;
end;
{ Public }
destructor ADAttribute.Destroy();
begin
if AttributeValues <> nil then
begin
AttributeValues.Free;
AttributeValues := nil;
end;
inherited;
end;
{ Public }
function ADAttribute.GetList() : TStringList;
begin
result := AttributeValues;
end;
{ Public }
function ADAttribute.SearchValue(value : string) : integer;
var
i : integer;
begin
result := -1;
if AttributeValues.Count > 0 then
begin
for i := 0 to AttributeValues.Count - 1 do
begin
if AttributeValues[i] = value then
begin
result := i;
Break;
end;
end;
end;
end;
{ Public }
procedure ADAttribute.AddValue(value : string);
begin
AttributeValues.Add(value);
end;
{ Public }
procedure ADAttribute.DeleteValue(valueIndex : integer);
begin
AttributeValues.Delete(valueIndex);
end;
{ Private }
function ADAttribute.GetValuesCount() : integer;
begin
result := AttributeValues.Count;
end;
{ Private }
function ADAttribute.GetValue(index : integer) : string;
begin
result := AttributeValues[index];
end;
{ Private }
procedure ADAttribute.SetValue(index : integer; value : string);
begin
AttributeValues[index] := value;
end;
{ --------------------------------------------------------
------------------- IMPLEMENTATION ---------------------
------------------- ADEntry ----------------------------
-------------------------------------------------------- }
{ Public }
constructor ADEntry.Create(entrName : string);
begin
EntryName := entrName;
EntryAttributes := TList.Create;
end;
{ Public }
constructor ADEntry.Create(entrName : string; attrs : array of ADAttribute);
var
i : integer;
begin
EntryName := entrName;
EntryAttributes := TList.Create;
for i := 0 to Length(attrs) - 1 do
EntryAttributes.Add(attrs[i]);
end;
{ Public }
destructor ADEntry.Destroy();
var
i : integer;
begin
if (EntryAttributes <> nil) then
begin
if EntryAttributes.Count > 0 then
begin
for i := 0 to EntryAttributes.Count - 1 do
ADAttribute(EntryAttributes[i]).Destroy;
EntryAttributes.Clear;
end;
EntryAttributes.Free;
EntryAttributes := nil;
end;
inherited;
end;
{ Public }
function ADEntry.GetList() : TList;
begin
result := EntryAttributes;
end;
{ Public }
function ADEntry.GetAttributeByName(attrName : string) : ADAttribute;
var
i : integer;
begin
if AttributesCount > 0 then
for i := 0 to AttributesCount - 1 do
if Attributes[i].Name = attrName then
begin
result := Attributes[i];
Exit;
end;
result := nil;
end;
{ Public }
function ADEntry.AddAttribute(attribute : ADAttribute) : integer;
begin
EntryAttributes.Add(attribute);
result := EntryAttributes.Count - 1;
end;
{ Public }
function ADEntry.AddAttribute(attrName : string; attrValues : array of string) : integer;
begin
EntryAttributes.Add(ADAttribute.Create(attrName, attrValues));
result := EntryAttributes.Count - 1;
end;
{ Public }
function ADEntry.AddAttribute(attrName : string) : integer;
begin
EntryAttributes.Add(ADAttribute.Create(attrName));
result := EntryAttributes.Count - 1;
end;
{ Public }
procedure ADEntry.DeleteAttribute(index : integer);
begin
ADAttribute(EntryAttributes[index]).Destroy;
EntryAttributes.Delete(index);
end;
{ Public }
procedure ADEntry.DeleteAttribute(name : string);
var
i : integer;
begin
for i := 0 to EntryAttributes.Count - 1 do
begin
if ADAttribute(EntryAttributes[i]).Name = name then
begin
ADAttribute(EntryAttributes[i]).Destroy;
EntryAttributes.Delete(i);
break;
end;
end;
end;
{ Private }
function ADEntry.GetAttributesCount() : integer;
begin
result := EntryAttributes.Count;
end;
{ Private }
function ADEntry.GetAttribute(index : integer) : ADAttribute;
begin
result := ADAttribute(EntryAttributes[index]);
end;
{ --------------------------------------------------------
------------------- IMPLEMENTATION ---------------------
------------------- ADEntryList ------------------------
-------------------------------------------------------- }
{ Public }
constructor ADEntryList.Create();
begin
Entries := TList.Create;
end;
{ Public }
destructor ADEntryList.Destroy();
var
i : integer;
begin
if Entries <> nil then
begin
if Entries.count > 0 then
begin
for i := 0 to Entries.Count - 1 do
begin
ADEntry(Entries[i]).Destroy;
end;
Entries.Clear;
end;
Entries.Free;
Entries := nil;
end;
inherited;
end;
{ Public }
function ADEntryList.GetList() : TList;
begin
result := Entries;
end;
{ Public }
function ADEntryList.AddEntry(entry : ADEntry) : integer;
begin
Entries.Add(entry);
result := Entries.Count - 1;
end;
{ Public }
function ADEntryList.AddEntry(entryName : string) : integer;
begin
Entries.Add(ADEntry.Create(entryName));
result := Entries.Count - 1;
end;
{ Public }
function ADEntryList.AddEntry(entryName : string; attrs : array of ADAttribute) : integer;
begin
Entries.Add(ADEntry.Create(entryName, attrs));
result := Entries.Count - 1;
end;
{ Public }
procedure ADEntryList.DeleteEntry(index : integer);
begin
ADEntry(Entries[index]).Destroy;
Entries.Delete(index);
end;
{ Public }
procedure ADEntryList.DeleteEntry(name : string);
var
i : integer;
begin
for i := 0 to Entries.Count - 1 do
begin
if ADEntry(Entries[i]).Name = name then
begin
ADEntry(Entries[i]).Destroy;
Entries.Delete(i);
break;
end;
end;
end;
{ Private }
function ADEntryList.GetEntriesCount() : integer;
begin
result := Entries.Count;
end;
{ Private }
function ADEntryList.GetEntry(index : integer) : ADEntry;
begin
result := ADEntry(Entries[index]);
end;
end.
|
uses UConst, UGeneticAlgorithm;
function read_txt(filename: string): array of array of real;
begin
foreach var (i, line) in ReadLines(filename).Numerate do
begin
Setlength (result, i);
result[i-1] := line.ToReals;
end;
end;
function mixing(ratio: array of real;
flows: array of array of real): array of real;
begin
result := ArrFill(flows.Length,0.0);
foreach var i in flows.Indices do
foreach var j in ratio.Indices do
result [i] += ratio [j] * flows[i][j];
end;
function calculate_octane_number(fractions: array of real;
Bi: array of real := UConst.Bi;
RON: array of real := UConst.RON): real;
begin
result := 0.0;
var B := ArrFill(Bi.Length, 0.0);
foreach var i in Bi.Indices do
for var j :=i+1 to Bi.High do
B[i] := Bi[i] * B[j]* fractions[i] * fractions[j];
foreach var i in fractions.Indices do
result += fractions[i] * RON[i];
result += B.Sum;
end;
function normalize (x: array of real): array of real;
begin
var s:= x.Sum;
result:= ArrFill (x.Length, 0.0);
foreach var i in x.Indices do
result [i]:= x[i]/s;
end;
function objective_func(ratio, actual_values: array of real):real;
begin
var data:= read_txt('data.txt');
var fractions:= mixing(normalize(ratio), data);
var ron:= calculate_octane_number(fractions);
result:=(actual_values[0]-ron)**2;
end;
begin
var data := read_txt('data.txt');
// var fractions := mixing(|0.15, 0.19, 0.33, 0.1, 0.115, 0.115|,data);
// var ron := calculate_octane_number(fractions);
// print($'Октановое число смешения = {ron:f}')
var bounds:=||1e-5,0.99|,|1e-5,0.99|,|1e-5,0.99|,|1e-5,0.99|,|1e-5,0.99|,
|1e-5,0.99||;
var res:= genetic_algorithm(bounds, objective_func, |92.0|);
var norm_ratio: array of array of real;
SetLength(norm_ratio, res.Length);
foreach var i in res.Indices do
norm_ratio [i]:= normalize(res[i][:^1]);
foreach var i in norm_ratio.Indices do
Println(calculate_octane_number(mixing(norm_ratio[i],data)));
norm_ratio.PrintLines
end.
|
unit ElphyFormat;
interface
{$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF}
uses classes,sysUtils,
util1,Gdos, debug0,
stmdef, stmObj,varConf1,blocInf0,
DataGeneFile,cyberK2,
acqDef2
;
{ Nouveau format de fichier de données.
Le fichier contiendra l'entête des fichiers d'objets Dac2 (ObjFile1), soit 18 octets.
Ensuite, une suite de blocs tous complètement indépendants, chaque bloc ayant le
format d'un objet, comme dans les fichiers d'objets ou de configuration.
C'est à dire:
BLOC=
- un mot de 4 octets représentant la taille totale du bloc (y compris ces 4 octets)
- un mot clé string de longueur quelconque identifiant le bloc
- les données du bloc
Donc, un programme pourra lire les blocs (ou objets) qui l'intéressent et ignorer
les autres.
Cas particulier:
- si la taille d'un bloc est -1, le bloc se termine à la fin du fichier
Ce sera le cas pour un bloc de données pour une acquisition continue, lorsque
le fichier n'aura pas été fermé correctement.
Il n'y a pas d'entête de fichier dans le sens Acquis1 ou Dac2.
Les blocs actuels sont les suivants:
TcommentBlock
TFileInfoBlock
TEpInfoBlock
TstimBlock
TacqBlock
TUtagBlock
TseqBlock
TRdataBlock
TReventBlock
Les données sont constituées d'un bloc Seq suivi par:
- un ou plusieurs blocs Rdata
- un ou plusieurs blocs Revt
Entre les blocs Rdata ou Revt peuvent s'intercaler d'autres blocs.
Les autres blocs sont des blocs d'information.
Il est possible de ranger des objets (vecteurs, matrices) dans le même fichier.
}
type
TElphyFileBlock=
class(typeUO)
constructor create;override;
end;
TcommentBlock=
class(TElphyFileBlock)
stCom:AnsiString;
class function STMClassName:AnsiString;override;
procedure BuildInfo(var conf:TblocConf;lecture,tout:boolean);override;
function getInfo:AnsiString;override;
end;
TFileInfoBlock=
class(TElphyFileBlock)
blocInfo:TblocInfo;
blocExterne:boolean;
constructor create;override;
destructor destroy;override;
class function STMClassName:AnsiString;override;
procedure setBloc(bloc:TblocInfo);
procedure BuildInfo(var conf:TblocConf;lecture,tout:boolean);override;
function getInfo:AnsiString;override;
end;
TEpInfoBlock=
class(TFileInfoBlock)
class function STMClassName:AnsiString;override;
function getInfo:AnsiString;override;
end;
TuserTagRecord=
record
SampleIndex:integer;
Stime:TdateTime;
code:byte;
ep:integer;
withObj: boolean;
end;
TUserTagBlock=
class(TElphyFileBlock)
Utag:TuserTagRecord;
stCom:AnsiString;
constructor create;override;
destructor destroy;override;
class function STMClassName:AnsiString;override;
procedure BuildInfo(var conf:TblocConf;lecture,tout:boolean);override;
function getInfo:AnsiString;override;
end;
{ Structure d'une séquence:
On part du principe qu'à 'acquisition, on a nbvoie multiplexées contenant
chacune nbpt échantillons.
En fait, on ne sauve pas tous les points, soit parce qu'on a décimé certaines voies (Ksampling0>1),
soit parce qu'on les a transformées en voies événements (Ksampling0=0) .
Il suffit de connaitre le facteur de downsampling pour chaque voie pour connaitre la
structure du fichier.
Ksampling0=1 signifie que tous les pts ont été sauvés
Ksampling0=n signifie que 1 point sur n a été sauvé
Ksampling0=0 signifie qu'aucun point n'a été sauvé
Pour les voies Tag avec tagMode=itc , la dernière voie est telle que Ksampling0=1
}
TseqRecord=
record
nbvoie:byte; {nbvoie à l'acquisition. Même si une voie n'est pas sauvée. Inclut la voie tag }
nbpt:integer; {nbpt nominal = cas ou Ksampling0=1 pour chaque voie}
tpData:typeTypeG; {type des échantillons, a été remplacé par Ktype0 }
uX:string[10]; {unités de temps}
Dxu,x0u:double; {Dxu par voie}
continu:boolean; {si vrai, le fichier est continu}
TagMode:TtagMode;
TagShift:byte;
DxuSpk,X0uSpk: double; { introduit pour CyberK, paramètres des waveforms uniquement }
nbSpk:integer; { '' }
DyuSpk,Y0uSpk: double; { '' }
unitXspk,unitYSpk:string[10]; { '' }
CyberTime: double; { temps du cyberK en secondes }
PCtime:longword; { temps PC en millisecondes }
DigEventCh: integer; { numéro de la voie Evt utilisant les compteurs NI }
DigEventDxu:double; { période échantillonnage correspondante }
DxEvent: double; { période échantillonnage des voies evt ordinaires. Par défaut, on avait Dxu / nbvoie . }
FormatOption: byte; { ajouté le 26 mars 2011 . =0 jusqu'à cette date.
1: les voies deviennent des vecteurs 100% indépendants }
end;
TAdcChannel=record
uY:string[10];
Dyu,Y0u:double;
end;
TadcChannels=array of TadcChannel;
TAdcChannel2=record
ChanType:byte; // 0: analog ou tag 1: Evt si tmItc , la dernière voie est la voie tag
tpNum: typetypeG; // number type
imin, imax: integer;
ux:string[10];
Dxu,x0u:double;
uY:string[10];
Dyu,Y0u:double;
end;
TadcChannels2=array of TadcChannel2;
TseqBlock=
class(TElphyFileBlock)
private
adcChannel:TAdcChannels; { description des canaux}
SamplePerChan0:array of integer; {0 signifie EVT}
Ktype0:array of typetypeG; { ajouté en juin 2008 }
Ksampling0:array of word; { facteurs de sous-échantillonnage: 1 par défaut }
adcChannel2:TAdcChannels2;
procedure CalculAgSampleCount;
procedure setDsize(nb:int64); {fixe les valeurs de SamplePerChan0 }
procedure setKtype(n:integer;tp:typetypeG);
function getKtype(n:integer):typetypeG;
procedure setKsampling(n:integer;w:word);
function getKsampling(n:integer):word;
public
{Paramètres sauvés dans le fichier}
seq:TseqRecord;
{Paramètres calculés }
SampleTot:integer;
chanMask:array of integer; {Le masque a la taille d'un agrégat. On range le numéro de voie (0 à nbvoie-1)
dans chaque élément. }
AgSampleCount:integer; {Taille d'agrégat calculée avec getAgSampleCount en nombre d'échantillons}
AgSize:integer; {Taille de l'agrégat en octets }
ppcm0:integer; {ppcm des Ksampling0 positifs}
Tmax:float; {Durée de la séquence en secondes ou ms, ajouté juillet 2009 , calculé avec SamplePerChan0 }
Offset2: array of integer; {Offsets dans le bloc Rdata}
constructor create;override;
class function STMClassName:AnsiString;override;
procedure setVarSizes(conf:TblocConf);
procedure BuildInfo(var conf:TblocConf;lecture,tout:boolean);override;
procedure completeLoadInfo;override;
{function loadFromStream(f:Tstream;size:longWord;Fdata:boolean):boolean;override;}
function getInfo:AnsiString;override;
procedure BuildMask(DataSz:int64);{construction de chanMask, calcul de SamplePerChan0}
function UnderSampled:boolean;
function AnalogChCount:integer;
function EvtChCount:integer;
procedure init0(Const seq1:TseqRecord ); // initialisation en format 0
procedure init1(Const seq1:TseqRecord ); // initialisation en format 1
function SamplePerChan(num : integer): integer;
procedure initChannel0(num: integer; Dy,y0: double; unitY: string);
procedure initChannel1(num: integer; ChanType1:byte; tp: typetypeG; i1, i2: integer;
Dx,x0:double; unitX:string; Dy,y0: double; unitY: string);
function getDyu(num: integer): double;
function getY0u(num: integer): double;
function getUnitY(num: integer): string;
function getDxu(num: integer): double;
function getX0u(num: integer): double;
function getUnitX(num: integer): string;
function getChanType(num: integer): integer;
function getImin(num: integer): integer;
function getImax(num: integer): integer;
function getOffset2(num: integer): integer;
property Ktype[n:integer]: typetypeG read getKtype write setKtype;
property Ksampling[n:integer]: word read getKsampling write setKsampling;
end;
TRdataRecord=record
MySize:word; {Taille du record}
SFirst:boolean; {si vrai , il y a eu une pause avant ce bloc}
Stime:TdateTime; {Date du PC à l'enregistrement}
Nindex:longword;
end;
TRdataBlock=
class(TElphyFileBlock)
private
off0:int64;
size0:longword; {offset et taille des données après loadObject}
rec:TRdataRecord;
public
function dataSize:longword;
function dataOffset:int64;
class function NindexOffset:integer; {Offset de Nindex à partir du début du bloc (position de "Block Size" }
class function STMClassName:AnsiString;override;
property NomIndex:longword read rec.NIndex;
property Stime: TdateTime read rec.Stime;
procedure BuildInfo(var conf:TblocConf;lecture,tout:boolean);override;
function loadFromStream(f:Tstream;size:LongWord;Fdata:boolean):boolean;override;
function getInfo:AnsiString;override;
end;
TRevent=record
date:integer;
code:byte;
end;
TReventBlock=
class(TRdataBlock)
public
scaling: TevtScaling;
expectedNbEv:integer;
nbVev:integer;
nbev:array of integer;
constructor create;override;
class function STMClassName:AnsiString;override;
function loadFromStream(f:Tstream;size:LongWord;Fdata:boolean):boolean;override;
function getInfo:AnsiString;override;
end;
TRspkBlock=
class(TReventBlock)
public
class function STMClassName:AnsiString;override;
end;
TRspkWaveBlock=
class(TRdataBlock)
public
scaling: TSpkWaveScaling;
Wavelen:integer; {Paramètres sauvés dans cet ordre }
Pretrig:integer;
nbVev:integer;
nbev:array of integer;
waveSize:integer; {=ElphySpkPacketFixedSize + nbptSpk*2; }
class function STMClassName:AnsiString;override;
function loadFromStream(f:Tstream;size:LongWord;Fdata:boolean):boolean;override;
function getInfo:AnsiString;override;
end;
TRsoundBlock=
class(TRdataBlock)
public
class function STMClassName:AnsiString;override;
end;
TRcyberTagBlock=
class(TRdataBlock)
public
class function STMClassName:AnsiString;override;
end;
TRpclBlock=
class(TRdataBlock)
public
nbPhoton:integer;
Funix:boolean;
class function STMClassName:AnsiString;override;
function loadFromStream(f:Tstream;size:LongWord;Fdata:boolean):boolean;override;
function getInfo:AnsiString;override;
end;
procedure WriteRdataHeader(f:TStream;size:integer;tm:TdateTime;first:boolean);
{size est la taille des données proprement dites}
procedure WriteReventHeader(f:TStream;size:integer;tm:TdateTime;first:boolean);
{size est la taille des données proprement dites}
procedure WriteRspkHeader(f:TStream;size:integer;tm:TdateTime;first:boolean;scale: TevtScaling);
{size est la taille des données proprement dites}
procedure WriteRSPKwaveHeader(f:TStream;size:integer;tm:TdateTime;first:boolean;scale: TSpkWaveScaling);
procedure WriteRcyberTagHeader(f:TStream;size:integer;tm:TdateTime;first:boolean);
procedure WriteRPCLHeader(f:TStream;size:integer;tm:TdateTime;first:boolean);
implementation
{********************** Méthodes de TElphyFileBlock *****************************}
constructor TElphyFileBlock.create;
begin
inherited; {on pourrait ne pas appeler inherited }
notPublished:=true;
end;
{********************** Méthodes de TcommentBlock *****************************}
class function TcommentBlock.STMClassName:AnsiString;
begin
result:='B_comment';
end;
procedure TcommentBlock.BuildInfo(var conf:TblocConf;lecture,tout:boolean);
begin
conf.setStringconf('STCOM',stCom);
end;
function TcommentBlock.getInfo:AnsiString;
begin
result:=inherited getInfo+
stCom+CRLF;
end;
{********************** Méthodes de TFileInfoBlock ****************************}
constructor TFileInfoBlock.create;
begin
inherited;
blocInfo:=TblocInfo.create(0);
end;
destructor TFileInfoBlock.destroy;
begin
if not BlocExterne then blocInfo.free;
inherited;
end;
class function TFileInfoBlock.STMClassName:AnsiString;
begin
result:='B_Finfo';
end;
procedure TFileInfoBlock.setBloc(bloc:TblocInfo);
begin
if assigned(blocInfo) and not BlocExterne then blocInfo.free;
blocInfo:=bloc;
blocExterne:=true;
end;
procedure TFileInfoBlock.BuildInfo(var conf:TblocConf;lecture,tout:boolean);
begin
conf.setDynConf('USR',blocInfo.buf,blocinfo.tailleBuf);
end;
function TFileInfoBlock.getInfo:AnsiString;
begin
if assigned(blocInfo) then
result:=inherited getInfo+
'Size: '+Istr(blocInfo.tailleBuf)+' bytes'+CRLF;
end;
{********************** Méthodes de TEpInfoBlock ****************************}
class function TEpInfoBlock.STMClassName:AnsiString;
begin
result:='B_Einfo';
end;
function TEpInfoBlock.getInfo:AnsiString;
begin
result:=inherited getInfo;
end;
{********************** Méthodes de TUserTagBlock ****************************}
constructor TUserTagBlock.create;
begin
inherited;
end;
destructor TUserTagBlock.destroy;
begin
inherited;
end;
class function TUserTagBlock.STMClassName:AnsiString;
begin
result:='B_UTag';
end;
procedure TUserTagBlock.BuildInfo(var conf:TblocConf;lecture,tout:boolean);
begin
conf.setVarConf('Utag',Utag,Sizeof(Utag));
conf.SetStringConf('Text=',stCom);
end;
function TUserTagBlock.getInfo:AnsiString;
begin
with Utag do
result:=inherited getInfo+
'SampleIndex='+Istr(SampleIndex)+crlf+
'Stime='+dateTimeToStr(Stime)+crlf+
'Code='+Istr(code)+crlf+
'Ep='+Istr(ep)+crlf+
'WithObj='+Bstr(WithObj)+crlf+
'Text='+stCom;
end;
{********************** Méthodes de TSeqBlock ****************************}
constructor TseqBlock.create;
var
i:integer;
begin
inherited;
end;
class function TseqBlock.STMClassName:AnsiString;
begin
result:='B_Ep';
end;
procedure TseqBlock.setVarSizes(conf:TblocConf);
begin
case seq.FormatOption of
0:begin
setLength(adcChannel,seq.nbvoie);
setLength(Ksampling0,seq.nbvoie);
setLength(SamplePerChan0,seq.nbvoie);
setLength(Ktype0,seq.nbvoie);
fillchar(Ktype0[0],seq.nbvoie,ord(G_smallint));
conf.ModifyVar('Adc',AdcChannel[0],seq.nbvoie*sizeof(TadcChannel));
conf.ModifyVar('Ksamp',Ksampling0[0],seq.nbvoie*sizeof(Ksampling0[0]));
conf.ModifyVar('Ktype',Ktype0[0],seq.nbvoie*sizeof(Ktype0[0]));
end;
1:begin
setLength(adcChannel2,seq.nbvoie);
conf.ModifyVar('Adc2',AdcChannel2[0],seq.nbvoie*sizeof(TadcChannel2));
end;
end;
end;
procedure TseqBlock.BuildInfo(var conf:TblocConf;lecture,tout:boolean);
begin
if lecture then
begin
fillchar(seq,sizeof(seq),0);
end;
{seq contient nbvoie. Juste après la lecture de seq, setVarSizes est appelée pour fixer la
taille des tableaux (adcChannel, etc...) }
conf.SetVarConf('Ep',seq,sizeof(seq),SetVarSizes); { onRead = SetVarSizes }
if lecture or (seq.FormatOption=0) then
begin
conf.setVarConf('Adc',AdcChannel[0],seq.nbvoie*sizeof(TadcChannel));
conf.setVarConf('Ksamp',Ksampling0[0],seq.nbvoie*sizeof(Ksampling0[1]));
conf.setVarConf('Ktype',Ktype0[0],seq.nbvoie*sizeof(Ktype0[0]));
end;
if lecture or (seq.FormatOption=1) then
begin
conf.setVarConf('Adc2',AdcChannel2[0],seq.nbvoie*sizeof(TadcChannel2));
end;
end;
procedure TseqBlock.completeLoadInfo;
begin
calculAgSampleCount;
end;
function TseqBlock.getInfo:AnsiString;
var
i:integer;
NumEv: integer;
begin
result:=inherited getInfo+
'Analog Channel count='+Istr(AnalogChCount)+CRLF+
'Evt Channel count='+Istr(EvtChCount)+CRLF+
'Samples per channel='+Istr(seq.nbpt)+CRLF+
'Data type='+TypeNameG[seq.tpData]+CRLF+
'UnitX='+seq.uX+CRLF+
'Dx='+Estr(seq.dxu,9)+CRLF+
'X0='+Estr(seq.x0u,9)+CRLF+
'Continuous='+Bstr(seq.continu)+CRLF+
'TagMode='+Istr(ord(seq.TagMode))+CRLF+
'TagShift='+Istr(seq.tagShift)+CRLF+CRLF;
NumEv:=0;
case seq.FormatOption of
0: for i:=0 to High(AdcChannel) do
with adcChannel[i] do
if Ksampling0[i]>0
then result:=result+Istr(i+1)+': ADC Dy='+Estr(dyu,9)+' y0='+Estr(y0u,9)+' ('+uY+')'
+' KS='+Istr(Ksampling0[i])+' type='+TypeNameG[Ktype0[i]]+CRLF
else
begin
inc(NumEv);
result:=result+Istr(i+1)+': EVT'+Istr(numEv)+CRLF;
end;
1: for i:=0 to High(AdcChannel2) do
with adcChannel2[i] do
if ChanType=0
then result:=result+Istr(i+1)+': ADC Dy='+Estr(dyu,9)+' y0='+Estr(y0u,9)+' ('+uY+')'
+' Dx='+Estr(Dxu,9)+' type='+TypeNameG[tpNum]+CRLF
else
begin
inc(NumEv);
result:=result+Istr(i+1)+': EVT'+Istr(numEv)+CRLF;
end;
end;
result:=result+crlf+
'CyberTime='+Estr(seq.cyberTime,3);
result:=result+crlf+
'PCTime='+Istr(seq.PCtime);
end;
procedure TseqBlock.CalculAgSampleCount; {taille d'un agrégat en nb d'échantillons}
var
i,n:integer;
begin
case seq.FormatOption of
0: begin
ppcm0:=1;
for i:=0 to seq.nbvoie-1 do
begin
if Ksampling0[i]>0
then ppcm0:=ppcm(ppcm0,Ksampling0[i]);
end; { on calcule le ppcm des Ksampling0>0 }
AgSampleCount:=0;
for i:=0 to seq.nbvoie-1 do { AgSampleCount est la somme des quotients ppcm/Ksampling0}
if Ksampling0[i]>0
then AgSampleCount:=AgSampleCount+ppcm0 div Ksampling0[i];
end;
1: begin
n:=0;
setLength(Offset2, length(AdcChannel2));
for i:=0 to high(AdcChannel2) do
with AdcChannel2[i] do
begin
offset2[i]:=n;
n:=n+ tailleTypeG[tpNum]*(Imax-Imin+1);
end;
end;
end;
end;
procedure TseqBlock.setDsize(nb:int64); {nb est la taille du bloc de données}
var
i,j,rest,vv:integer;
nbAg,it:int64;
tt:float;
begin
if seq.FormatOption<>0 then exit;
if AgSampleCount=0 then {setDsize fixe les valeurs de SamplePerChan0 }
begin {en tenant compte du fait que le dernier agrégat }
for i:=0 to seq.nbvoie-1 do {peut ne pas être complet}
SamplePerChan0[i]:=0;
exit;
end;
nbAg:=nb div AgSize; {nombre d'agrégats complets }
for i:=0 to seq.nbvoie-1 do
if Ksampling0[i]>0
then SamplePerChan0[i]:=nbAg*ppcm0 div Ksampling0[i]
else SamplePerChan0[i]:=0;
rest:=nb mod AgSize; {agrégat incomplet }
it:=0; { taille }
j:=0; { indice dans l'Ag }
while it<rest do
begin
vv:= chanMask[j];
if (vv>=0) and (vv <seq.nbvoie) then { condition inutile ?}
begin
inc(SamplePerChan0[vv]);
inc(it,TailleTypeG[Ktype0[vv]]);
inc(j);
end
else
begin
messageCentral('TseqBlock.setDsize error vv='+Istr(vv));
break;
end;
end;
Tmax:=0;
for i:=0 to seq.nbvoie-1 do
if Ksampling0[i]>0 then
begin
tt:=SamplePerChan0[i]*Ksampling0[i]*seq.Dxu;
if Ksampling0[i]=1 then
begin
Tmax:=tt;
exit;
end;
if tt>Tmax then Tmax:=tt;
end;
end;
procedure TseqBlock.BuildMask(dataSz:int64);
var
i,j,k:integer;
begin
if seq.FormatOption<>0 then exit;
CalculAgSampleCount;
setLength(chanMask,AgSampleCount);
AgSize:=0;
i:=0;
k:=0;
repeat
for j:=0 to seq.nbvoie-1 do
if (Ksampling0[j]<>0) and (i mod Ksampling0[j]=0) then
begin
chanMask[k]:=j;
AgSize:=AgSize+TailleTypeG[Ktype0[j]];
inc(k);
if k>=AgSampleCount then break;
end;
inc(i);
until k>=AgSampleCount;
setDsize(dataSz);
end;
function TseqBlock.UnderSampled:boolean;
var
i:integer;
begin
result:=false;
if seq.FormatOption<>0 then exit;
for i:=0 to seq.nbvoie-1 do
if Ksampling0[i]>1 then
begin
result:=true;
exit;
end;
end;
function TseqBlock.AnalogChCount:integer;
var
i:integer;
begin
result:=0;
case seq.FormatOption of
0: begin
for i:=0 to seq.nbvoie-1 do
if Ksampling0[i]>0 then inc(result);
if seq.TagMode=tmITC then dec(result); // on ne compte pas les voies digitales
end;
1: begin
for i:=0 to high(AdcChannel2) do
if AdcChannel2[i].ChanType=0 then inc(result);
end;
end;
end;
function TseqBlock.EvtChCount:integer;
var
i:integer;
begin
result:=0;
case seq.FormatOption of
0: for i:=0 to seq.nbvoie-1 do
if Ksampling0[i]=0 then inc(result);
1: for i:=0 to high(AdcChannel2) do
if AdcChannel2[i].ChanType=1 then inc(result);
end;
end;
procedure TseqBlock.init0(const seq1: TseqRecord);
begin
seq:=seq1;
seq.FormatOption:=0;
setLength(adcChannel,seq.nbvoie);
setLength(Ksampling0,seq.nbvoie);
setLength(samplePerChan0,seq.nbvoie);
setLength(Ktype0,seq.nbvoie);
fillchar(Ktype0[0],seq.nbvoie,ord(g_smallint));
end;
procedure TseqBlock.init1(const seq1: TseqRecord);
begin
seq:=seq1;
seq.FormatOption:=1;
setLength(adcChannel2,seq.nbvoie);
end;
function TseqBlock.SamplePerChan(num: integer): integer;
begin
case seq.FormatOption of
0: result:= SamplePerChan0[num];
1: with AdcChannel2[num] do result:= imax-imin+1;
end;
end;
procedure TseqBlock.initChannel0(num: integer; Dy, y0: double; unitY: string);
begin
with AdcChannel[num] do
begin
Dyu:= Dy;
Y0u:= Y0;
uy:=unitY;
end;
end;
procedure TseqBlock.initChannel1(num: integer; ChanType1:byte; tp: typetypeG; i1, i2: integer;
Dx,x0:double; unitX:string; Dy,y0: double; unitY: string);
begin
with AdcChannel2[num] do
begin
ChanType:=ChanType1;
tpNum:=tp;
imin:=i1;
imax:=i2;
Dxu:= Dx;
x0u:= x0;
ux:=unitX;
Dyu:= Dy;
Y0u:= Y0;
uy:=unitY;
end;
end;
function TseqBlock.getDxu(num: integer): double;
begin
case seq.FormatOption of
0: result:=seq.Dxu;
1: result:=AdcChannel2[num].Dxu;
end;
end;
function TseqBlock.getX0u(num: integer): double;
begin
case seq.FormatOption of
0: result:=seq.X0u;
1: result:=AdcChannel2[num].X0u;
end;
end;
function TseqBlock.getUnitX(num: integer): string;
begin
case seq.FormatOption of
0: result:=seq.ux;
1: result:=AdcChannel2[num].ux;
end;
end;
function TseqBlock.getDyu(num: integer): double;
begin
case seq.FormatOption of
0: result:=AdcChannel[num].Dyu;
1: result:=AdcChannel2[num].Dyu;
end;
end;
function TseqBlock.getY0u(num: integer): double;
begin
case seq.FormatOption of
0: result:=AdcChannel[num].Y0u;
1: result:=AdcChannel2[num].Y0u;
end;
end;
function TseqBlock.getUnitY(num: integer): string;
begin
case seq.FormatOption of
0: result:=AdcChannel[num].uy;
1: result:=AdcChannel2[num].uy;
end;
end;
procedure TseqBlock.setKtype(n:integer;tp:typetypeG);
begin
case seq.FormatOption of
0: Ktype0[n]:=tp;
1: AdcChannel2[n].tpNum:=tp;
end;
end;
function TseqBlock.getKtype(n:integer):typetypeG;
begin
case seq.FormatOption of
0: result:=Ktype0[n];
1: result:=AdcChannel2[n].tpNum;
end;
end;
procedure TseqBlock.setKsampling(n:integer;w:word);
begin
case seq.FormatOption of
0: Ksampling0[n]:= w;
end;
end;
function TseqBlock.getKsampling(n:integer):word;
begin
case seq.FormatOption of
0: result:=Ksampling0[n];
else result:=1;
end;
end;
function TseqBlock.getChanType(num: integer): integer;
begin
result:= AdcChannel2[num].ChanType;
end;
function TseqBlock.getImin(num: integer): integer;
begin
result:= AdcChannel2[num].Imin;
end;
function TseqBlock.getImax(num: integer): integer;
begin
result:= AdcChannel2[num].Imax;
end;
function TseqBlock.getOffset2(num: integer): integer;
begin
result:=Offset2[num];
end;
{********************** Méthodes de TRdataBlock ****************************}
function TRdataBlock.dataSize:longword;
begin
result:=size0;
end;
function TRdataBlock.dataOffset:int64;
begin
result:=off0;
end;
class function TRdataBlock.NindexOffset:integer;
begin
result:=5+length(stmClassName) + sizeof(word)+ sizeof(boolean)+ sizeof(TdateTime);
end;
class function TRdataBlock.STMClassName:AnsiString;
begin
result:='RDATA';
end;
procedure TRdataBlock.BuildInfo(var conf:TblocConf;lecture,tout:boolean);
begin
{Vide mais il est nécessaire de surcharger typeUO.buildinfo}
end;
function TRdataBlock.loadFromStream(f:Tstream;size:LongWord;Fdata:boolean):boolean;
var
sz:integer;
begin
fillchar(rec,sizeof(rec),0);
f.ReadBuffer(rec.mySize,sizeof(rec.mySize)); { lire mySize 2 octets }
if rec.MySize >sizeof(rec) { puis le reste de rec }
then rec.MySize :=sizeof(rec); { En procédant ainsi, on se réserve la possibilité }
f.ReadBuffer(rec.Sfirst,rec.mySize-2); { d'ajouter des champs dans rec }
off0:=f.position; { Position des données }
size0:=size-5-length(stmClassName)-rec.mySize; { Taille des données. On enlève les dix octets
d'entête : 'RDATA' + taille}
f.Position:=f.Position+size0;
end;
function TRdataBlock.getInfo:AnsiString;
begin
result:=inherited getInfo+
'Raw data offset: '+IntToStr(off0)+crlf+
'Raw data size: '+IntToStr(size0)+' bytes'+crlf+
'Date: '+ dateTimeToStr(rec.Stime)+crlf
;
end;
type
TRdataHeader=
record
BlockSize:integer;
st:String[5];
hrec:TRdataRecord;
end;
procedure WriteRawHeader(f:TStream;size:integer;tm:TdateTime;first:boolean;ident:shortstring;Const extra: pointer=nil;Const ExtraSize: integer=0);
var
hrec:TRdataRecord;
BlockSize:integer;
begin
BlockSize:=4 +
length(ident) +1 +
sizeof(hrec) +
size +
ExtraSize;
hrec.mySize:=sizeof(TRdataRecord) +extraSize;
hrec.Sfirst:=first;
hrec.Stime:=tm;
f.Write(blockSize,sizeof(blockSize));
f.Write(ident,length(ident)+1);
f.Write(hrec,sizeof(hrec));
if extra<>nil then f.Write(extra^,ExtraSize);
end;
procedure WriteRdataHeader(f:TStream;size:integer;tm:TdateTime;first:boolean);
begin
writeRawHeader(f,size,tm,first,'RDATA');
end;
{********************** Méthodes de TReventBlock ****************************}
constructor TReventBlock.create;
begin
inherited;
expectedNbEv:=-1;
end;
class function TReventBlock.STMClassName:AnsiString;
begin
result:='REVT';
end;
function TReventBlock.loadFromStream(f:Tstream;size:LongWord;Fdata:boolean):boolean;
var
sz:integer;
pos0: int64;
begin
pos0:= f.Position;
fillchar(rec,sizeof(rec),0);
f.readBuffer(rec.mySize,sizeof(rec.mySize)); // lire mySize
sz:=rec.MySize -2; // taille restante
if sz >= sizeof(rec)-2
then f.readBuffer(rec.Sfirst,sizeof(rec)-2); // le rec original sz:= sz-sizeof(rec)+2;
fillchar(scaling,sizeof(scaling),0);
if sz >= sizeof(rec)-2+sizeof(scaling)
then f.Read(scaling,sizeof(scaling)); // scaling optionnel
f.Position:=pos0+rec.MySize; // dans tous les cas, on saute rec.mySize octets
f.readBuffer(nbVev,sizeof(nbvEv));
if (expectedNbEv>=0) then nbVEv:=expectedNbEv;
if (nbVeV<0) or (nbVeV>256) then nbVeV:=1;
setLength(nbeV,nbVeV);
f.readBuffer(nbEv[0],nbvEv*sizeof(integer));
off0:=f.position;
size0:=size-5-length(stmClassName)-rec.mySize-sizeof(integer)*(nbVeV+1);
f.Position:=f.Position+size0;
end;
function TReventBlock.getInfo: AnsiString;
var
st:AnsiString;
i:integer;
tot:integer;
begin
result:=inherited getInfo;
if scaling.Dxu<>0 then
with scaling do
result:= result + 'Dx = '+Estr(Dxu,9)+crlf+
'x0 = '+Estr(x0u,9)+crlf+
'unitX= '+unitX +crlf;
st:='';
for i:=0 to high(nbEv) do
st:=st+Istr1(i+1,3)+': '+Istr(nbEv[i])+crlf;
result:=result +
'ChCount='+Istr(nbVeV)+crlf+
'Event counts='+crlf+
st;
tot:=0;
for i:=0 to high(nbEv) do
tot:= tot+nbEv[i];
result:=result+crlf+Istr(tot);
end;
procedure WriteReventHeader(f:TStream;size:integer;tm:TdateTime;first:boolean);
begin
writeRawHeader(f,size,tm,first,'REVT');
end;
{ TRspkBlock }
class function TRspkBlock.STMClassName: AnsiString;
begin
result:='RSPK';
end;
procedure WriteRSPKHeader(f:TStream;size:integer;tm:TdateTime;first:boolean;scale: TevtScaling);
begin
writeRawHeader(f,size,tm,first,'RSPK',@scale,sizeof(scale));
end;
{ TRspkWaveBlock }
function TRspkWaveBlock.loadFromStream(f: Tstream; size: LongWord; Fdata: boolean): boolean;
var
sz:integer;
pos0:int64;
begin
pos0:= f.Position;
fillchar(rec,sizeof(rec),0);
f.readBuffer(rec.mySize,sizeof(rec.mySize)); // lire mySize
sz:=rec.MySize -2; // taille restante
if sz >= sizeof(rec)-2
then f.readBuffer(rec.Sfirst,sizeof(rec)-2); // le rec original sz:= sz-sizeof(rec)+2;
fillchar(scaling,sizeof(scaling),0);
if sz >= sizeof(rec)-2+sizeof(scaling)
then f.Read(scaling,sizeof(scaling)); // scaling optionnel
f.Position:=pos0+rec.MySize; // dans tous les cas, on saute rec.mySize octets
f.readBuffer(WaveLen,sizeof(WaveLen));
f.readBuffer(Pretrig,sizeof(Pretrig));
f.readBuffer(nbVev,sizeof(nbvEv));
if (nbVeV>0) and (nbVeV<256) then
begin
setLength(nbeV,nbVeV);
f.readBuffer(nbEv[0],nbvEv*sizeof(integer));
end;
waveSize:=ElphySpkPacketFixedSize + WaveLen*2;
off0:=f.position;
size0:=size-5-length(stmClassName)-rec.mySize-sizeof(integer)*(nbVeV+3);
f.Position:=pos0+size;
end;
class function TRspkWaveBlock.STMClassName: AnsiString;
begin
result:='RspkWave';
end;
function TRspkWaveBlock.getInfo: AnsiString;
var
st:AnsiString;
i:integer;
begin
result:=inherited getInfo;
if scaling.Dxu<>0 then
with scaling do
result:= result + 'Dx = '+Estr(Dxu,9)+crlf +
'x0 = '+Estr(x0u,9)+crlf +
'unitX= '+unitX +crlf +
'Dy = '+Estr(Dyu,9)+crlf +
'y0 = '+Estr(y0u,9)+crlf +
'unitY = '+unitY +crlf +
'DxSource = '+Estr(DxuSource,9)+crlf+
'unitXsource= '+unitXsource +crlf;
st:='';
for i:=0 to high(nbEv) do
st:=st+Istr1(i+1,3)+': '+Istr(nbEv[i])+crlf;
result:= result+
'WaveLen = '+Istr(Wavelen)+crlf+
'Pretrig = '+Istr(Pretrig)+crlf+
'ChCount = '+Istr(nbVeV)+crlf+
'Event counts= '+crlf+
st;
end;
procedure WriteRSPKwaveHeader(f:TStream;size:integer;tm:TdateTime;first:boolean; scale: TSpkWaveScaling);
begin
writeRawHeader(f,size,tm,first,'RspkWave', @scale, sizeof(scale));
end;
{ Méthodes de TRsoundBlock }
class function TRsoundBlock.STMClassName: AnsiString;
begin
result:='RSOUND';
end;
{ TRcyberTag }
class function TRcyberTagBlock.STMClassName: AnsiString;
begin
result:='RCyberTag';
end;
procedure WriteRcyberTagHeader(f:TStream;size:integer;tm:TdateTime;first:boolean);
begin
writeRawHeader(f,size,tm,first,'RCyberTag');
end;
{ TRpclBlock }
function TRpclBlock.loadFromStream(f: Tstream; size: LongWord; Fdata: boolean): boolean;
var
sz:integer;
p:int64;
begin
p:=f.Position;
fillchar(rec,sizeof(rec),0);
f.readBuffer(rec.mySize,sizeof(rec.mySize));
if rec.MySize >sizeof(rec)
then rec.MySize :=sizeof(rec);
f.readBuffer(rec.Sfirst,rec.mySize-2);
f.readBuffer(nbPhoton,sizeof(nbPhoton));
off0:=f.position;
size0:=size-5-length(stmClassName)-rec.mySize-sizeof(nbPhoton);
f.Position:=p+size;
end;
class function TRpclBlock.STMClassName: AnsiString;
begin
result:='RPCL';
end;
function TRpclBlock.getInfo: AnsiString;
begin
result:=inherited getInfo+
'nbPhoton='+Istr(nbPhoton)+CRLF;
end;
procedure WriteRPCLHeader(f:TStream;size:integer;tm:TdateTime;first:boolean);
begin
writeRawHeader(f,size,tm,first,'RPCL');
end;
Initialization
AffDebug('Initialization ElphyFormat',0);
registerObject(TcommentBlock,sys);
registerObject(TUserTagBlock,sys);
registerObject(TfileInfoBlock,sys);
registerObject(TepInfoBlock,sys);
registerObject(TseqBlock,sys);
registerObject(TRdataBlock,sys);
registerObject(TReventBlock,sys);
registerObject(TRspkBlock,sys);
registerObject(TRspkWaveBlock,sys);
registerObject(TRsoundBlock,sys);
registerObject(TRcyberTagBlock,sys);
registerObject(TRpclBlock,sys);
end.
|
unit ParallelEd2k;
{ Contains ED2K hashing functions, multi- and singlethreaded. }
interface
uses SysUtils, Classes, Windows, md4, FileInfo, UniStrUtils;
//{$DEFINE HASH_STATS}
//Enable to gather hashing statistics
const
ED2K_CHUNK_SIZE = 9728000;
type
{ Generic hasher }
TEd2kHasher = class;
TLeadPartDoneEvent = procedure(Sender: TEd2kHasher; Hash: MD4Digest) of object;
TEd2kHasher = class
public { Results }
FileSize: int64;
Ed2k: MD4Digest;
Lead: MD4Digest;
{$IFDEF HASH_STATS}
public
TotalTime: cardinal;
ReadingTime: cardinal;
HashingTime: cardinal;
{$ENDIF}
protected
FOnLeadPartDone: TLeadPartDoneEvent;
public
Terminated: boolean;
procedure HashFile(Filename: UniString); virtual; abstract;
property OnLeadPartDone: TLeadPartDoneEvent read FOnLeadPartDone write FOnLeadPartDone;
end;
type {Single-threaded hasher}
TSimpleEd2kHasher = class(TEd2kHasher)
protected
buf: pointer;
Parts: array of MD4Digest;
public
constructor Create;
destructor Destroy; override;
procedure HashFile(filename: UniString); override;
end;
type {Multithreaded hasher}
THashThread = class;
TParallelEd2kHasher = class(TEd2kHasher)
protected
FWakeUp: THandle;
Workers: array of THashThread;
WorkerIdle: array of boolean;
WorkersIdle: integer;
procedure WakeUp;
function GetFreeWorker: integer;
function GetFreeMemoryBlock: integer;
procedure WaitAllWorkersFree;
function GetFreeWorkerCount: integer;
procedure WaitEvent;
protected
Parts: array of MD4Digest;
PartsDone: array of boolean;
MemoryBlocks: array of pointer;
MemoryBlocksFree: array of boolean;
protected
LeadPartReported: boolean;
public
constructor Create(MaxThreads: cardinal = 0);
destructor Destroy; override;
procedure HashFile(filename: UniString); override;
end;
THashThread = class(TThread)
protected
Parent: TParallelEd2kHasher;
WorkerIndex: integer;
FWakeUp: THandle;
Context: Md4Context;
{$IFDEF HASH_STATS}
HashingTime: cardinal;
{$ENDIF}
{Set these before waking the thread. All the data must be available.
It'll be released upon completion.}
JobData: pointer;
JobSize: integer;
PartIndex: integer;
MemBlockIndex: integer;
procedure HashJob;
public
constructor Create(AParent: TParallelEd2kHasher; AWorkerIndex: integer);
destructor Destroy; override;
procedure Execute; override;
procedure Terminate; reintroduce;
procedure WakeUp;
end;
const
ZeroSizeHash: MD4Digest = (
$d4, $1d, $8c, $d9, $8f, $00, $b2, $04,
$e9, $80, $09, $98, $ec, $f8, $42, $7e);
function GetFileSizeEx(hFile: THandle; lpFileSize: PInt64): longbool; stdcall; external kernel32;
implementation
constructor TSimpleEd2kHasher.Create;
begin
inherited Create;
GetMem(buf, ED2K_CHUNK_SIZE);
end;
destructor TSimpleEd2kHasher.Destroy;
begin
FreeMem(buf);
inherited Destroy;
end;
procedure TSimpleEd2kHasher.HashFile(filename: UniString);
var h: THandle;
BytesRead: cardinal;
PartIndex: integer;
Context: MD4Context;
{$IFDEF HASH_STATS}
total_tm, tm: cardinal;
{$ENDIF}
begin
{$IFDEF HASH_STATS}
total_tm := GetTickCount;
{$ENDIF}
h := CreateFileW(PWideChar(filename), GENERIC_READ, FILE_SHARE_READ, nil,
OPEN_EXISTING, 0, 0);
if h=INVALID_HANDLE_VALUE then
RaiseLastOsError;
if not GetFileSizeEx(h, @FileSize) then
RaiseLastOsError();
{ Empty file }
if FileSize=0 then begin
Ed2k := ZeroSizeHash;
Lead := ZeroSizeHash;
exit;
end;
{ Allocate parts.
ED2K always requires last chunk to be incomplete, even when it's size is zero.
LASTCHUN + K.......
LASTCHNK + ........
LASTCH..
}
SetLength(Parts, FileSize div ED2K_CHUNK_SIZE+1);
{ Process }
PartIndex := 0;
repeat
{$IFDEF HASH_STATS}
tm := GetTickCount;
{$ENDIF}
{ Read next chunk, maybe empty or incomplete }
if not ReadFile(h, buf^, ED2K_CHUNK_SIZE, BytesRead, nil) then
RaiseLastOsError;
{$IFDEF HASH_STATS}
ReadingTime := ReadingTime + GetTickCount-tm;
{$ENDIF}
{$IFDEF HASH_STATS}
tm := GetTickCount;
{$ENDIF}
MD4Init(Context);
MD4Update(Context, PAnsiChar(buf), BytesRead);
MD4Final(Context, Parts[PartIndex]);
{$IFDEF HASH_STATS}
HashingTime := HashingTime + GetTickCount-tm;
{$ENDIF}
if PartIndex=0 then
if Assigned(FOnLeadPartDone) then
FOnLeadPartDone(Self, Parts[0]);
Inc(PartIndex)
until (PartIndex >= Length(Parts)) or Terminated;
{ Finalize hash }
Lead := Parts[0];
if Length(Parts)=1 then begin
Ed2k := Parts[0];
exit;
end;
MD4Init(Context);
MD4Update(Context, @Parts[0], Length(Parts)*SizeOf(Md4Digest));
MD4Final(Context, Ed2k);
CloseHandle(h);
{$IFDEF HASH_STATS}
TotalTime := TotalTime + GetTickCount-total_tm;
{$ENDIF}
end;
////////////////////////////////////////////////////////////////////////////////
constructor TParallelEd2kHasher.Create(MaxThreads: cardinal = 0);
var sysinfo: SYSTEM_INFO;
i: integer;
begin
inherited Create;
{$IFDEF HASH_STATS}
TotalTime := 0;
HashingTime := 0;
ReadingTime := 0;
{$ENDIF}
FWakeUp := CreateEvent(nil, false, false, nil);
{ MD5 hashing is slow, so create as many processing threads as there are cores }
GetSystemInfo(&sysinfo);
if (MaxThreads>0) and (MaxThreads < sysinfo.dwNumberOfProcessors) then
sysinfo.dwNumberOfProcessors := MaxThreads;
SetLength(Workers, sysinfo.dwNumberOfProcessors);
{ Zero-initialize in case of premature destruction }
for i := 0 to Length(Workers) - 1 do
Workers[i] := nil;
{ This controls whether the thread is idle.
When a thread enters idle state, it sets it's idle cell to true, then wakes
main thread up.
After assigning work main thread sets this to false and wakes worker thread up. }
SetLength(WorkerIdle, Length(Workers));
for i := 0 to Length(WorkerIdle) - 1 do
WorkerIdle[i] := true;
{ We allocate all the memory blocks from the start to save on memory reallocations.
It's alright, if the computer has many cores it's likely to have enough memory. }
SetLength(MemoryBlocks, Length(Workers)+1); {one for loading}
for i := 0 to Length(MemoryBlocks)-1 do
MemoryBlocks[i] := nil;
for i := 0 to Length(MemoryBlocks)-1 do
GetMem(MemoryBlocks[i], ED2K_CHUNK_SIZE);
SetLength(MemoryBlocksFree, Length(MemoryBlocks));
for i := 0 to Length(MemoryBlocksFree)-1 do
MemoryBlocksFree[i] := true;
{ Create threads }
for i := 0 to Length(Workers) - 1 do
Workers[i] := THashThread.Create(Self, i);
end;
destructor TParallelEd2kHasher.Destroy;
var i: integer;
begin
{ Worker threads }
for i := 0 to Length(Workers) - 1 do
FreeAndNil(Workers[i]);
{ Memory blocks }
for i := 0 to Length(MemoryBlocks) - 1 do begin
FreeMem(MemoryBlocks[i]);
MemoryBlocks[i] := nil;
end;
CloseHandle(FWakeUp);
inherited;
end;
{ Wakes the main thread up to check for free workers }
procedure TParallelEd2kHasher.WakeUp;
begin
SetEvent(FWakeUp);
end;
{ Waits until there are worker threads available. Returns first available thread index. }
function TParallelEd2kHasher.GetFreeWorker: integer;
var i, hr: integer;
begin
repeat
for i := 0 to Length(Workers) - 1 do
if WorkerIdle[i] then begin
Result := i;
exit;
end;
hr := WaitForSingleObject(FWakeUp, INFINITE);
if hr <> WAIT_OBJECT_0 then
RaiseLastOsError();
until false;
end;
//Calculates free worker count.
//Call from the main thread only.
//This might raise in multithreaded environment, but only main thread can make this number go down.
function TParallelEd2kHasher.GetFreeWorkerCount: integer;
var i: integer;
begin
Result := 0;
for i := 0 to Length(Workers) - 1 do
if WorkerIdle[i] then
Inc(Result);
end;
//Sleeps until something happens (usually a thread signalling something)
procedure TParallelEd2kHasher.WaitEvent;
var hr: integer;
begin
hr := WaitForSingleObject(FWakeUp, INFINITE);
if hr <> WAIT_OBJECT_0 then
RaiseLastOsError();
end;
{ Waits until all workers become free }
//Deprecated, don't use: there could be different reasons for waking up,
//not only the worker being freed.
procedure TParallelEd2kHasher.WaitAllWorkersFree;
begin
repeat
if GetFreeWorkerCount>=Length(Workers) then exit;
WaitEvent;
until false;
end;
{ Searches for a first free memory block. This should always be available,
because we don't search for a next block until we gave out the preious one. }
function TParallelEd2kHasher.GetFreeMemoryBlock: integer;
var i: integer;
begin
for i := 0 to Length(MemoryBlocks) - 1 do
if MemoryBlocksFree[i] then begin
Result := i;
exit;
end;
raise Exception.Create('ED2K Hasher: No free pre-allocated blocks, unexpected failure.');
end;
procedure TParallelEd2kHasher.HashFile(filename: UniString);
var h: THandle;
BytesRead: cardinal;
PartIndex: integer;
MemBlockIndex: integer;
Worker: integer;
Context: MD4Context;
i: integer;
{$IFDEF HASH_STATS}
total_tm, tm: cardinal;
{$ENDIF}
begin
{$IFDEF HASH_STATS}
total_tm := GetTickCount;
for i := 0 to Length(Workers) - 1 do
Workers[i].HashingTime := 0;
{$ENDIF}
ResetEvent(FWakeUp);
Terminated := false;
h := CreateFileW(PWideChar(filename), GENERIC_READ, FILE_SHARE_READ, nil,
OPEN_EXISTING, 0, 0);
if h=INVALID_HANDLE_VALUE then
RaiseLastOsError;
if not GetFileSizeEx(h, @FileSize) then
RaiseLastOsError();
{ Empty file }
if FileSize=0 then begin
Ed2k := ZeroSizeHash;
Lead := ZeroSizeHash;
exit;
end;
{ Allocate parts.
ED2K always requires last chunk to be incomplete, even when it's size is zero.
LASTCHUN + K.......
LASTCHNK + ........
LASTCH..
}
SetLength(Parts, FileSize div ED2K_CHUNK_SIZE+1);
SetLength(PartsDone, Length(Parts));
for i := 0 to Length(PartsDone) - 1 do
PartsDone[i] := false;
{ Process }
PartIndex := 0;
LeadPartReported := false;
repeat
{ If we have calculated the lead part, maybe it's time to report it }
if (not LeadPartReported) and PartsDone[0] then begin
if Assigned(FOnLeadPartDone) then
FOnLeadPartDone(Self, Parts[0]);
LeadPartReported := true;
end;
{ Find free memory block }
MemBlockIndex := GetFreeMemoryBlock;
MemoryBlocksFree[MemBlockIndex] := false;
{$IFDEF HASH_STATS}
tm := GetTickCount;
{$ENDIF}
{ Read next chunk, maybe empty or incomplete }
if not ReadFile(h, MemoryBlocks[MemBlockIndex]^, ED2K_CHUNK_SIZE, BytesRead, nil) then
RaiseLastOsError;
{$IFDEF HASH_STATS}
ReadingTime := ReadingTime + GetTickCount-tm;
{$ENDIF}
{ Wait for worker to become available }
Worker := GetFreeWorker;
WorkerIdle[Worker] := false;
{ Assign a task }
Workers[Worker].JobData := MemoryBlocks[MemBlockIndex];
Workers[Worker].JobSize := BytesRead;
Workers[Worker].PartIndex := PartIndex;
Workers[Worker].MemBlockIndex := MemBlockIndex;
Workers[Worker].WakeUp;
Inc(PartIndex)
until (PartIndex >= Length(Parts)) or Terminated;
{ Wait for all workers to finish their jobs }
repeat
{ Lead part might be not done yet for small files }
if (not LeadPartReported) and PartsDone[0] then begin
if Assigned(FOnLeadPartDone) then
FOnLeadPartDone(Self, Parts[0]);
LeadPartReported := true;
end;
{ All workers free: exit }
if GetFreeWorkerCount>=Length(Workers) then break;
{ Sleep }
WaitEvent;
until false;
{ Finalize hash }
Lead := Parts[0];
if Length(Parts)=1 then begin
Ed2k := Parts[0];
exit;
end;
MD4Init(Context);
MD4Update(Context, @Parts[0], Length(Parts)*SizeOf(Md4Digest));
MD4Final(Context, Ed2k);
CloseHandle(h);
{$IFDEF HASH_STATS}
TotalTime := TotalTime + GetTickCount-total_tm;
for i := 0 to Length(Workers) - 1 do
HashingTime := HashingTime + Workers[i].HashingTime;
{$ENDIF}
end;
constructor THashThread.Create(AParent: TParallelEd2kHasher; AWorkerIndex: integer);
begin
inherited Create({Suspended:}true);
Parent := AParent;
WorkerIndex := AWorkerIndex;
FWakeUp := CreateEvent(nil, false, false, nil);
Resume;
end;
destructor THashThread.Destroy;
begin
Terminate;
WaitFor();
CloseHandle(FWakeUp);
inherited;
end;
procedure THashThread.Execute;
var hr: integer;
begin
while not Terminated do begin
hr := WaitForSingleObject(FWakeUp, INFINITE);
if hr<>WAIT_OBJECT_0 then
RaiseLastOsError();
if Terminated then exit;
if JobData<>nil then
HashJob;
end;
end;
procedure THashThread.Terminate;
begin
inherited Terminate;
WakeUp;
end;
procedure THashThread.WakeUp;
begin
SetEvent(FWakeUp);
end;
{ Work function. Hashes the assigned job, then resets it,
increments the completed job counter, adds itself to a free workers list
and notifies main thread. }
procedure THashThread.HashJob;
{$IFDEF HASH_STATS}
var tm: cardinal;
{$ENDIF}
begin
{$IFDEF HASH_STATS}
tm := GetTickCount;
{$ENDIF}
MD4Init(Context);
MD4Update(Context, PAnsiChar(JobData), JobSize);
MD4Final(Context, Parent.Parts[PartIndex]);
{$IFDEF HASH_STATS}
HashingTime := HashingTime + GetTickCount-tm;
{$ENDIF}
Parent.PartsDone[PartIndex] := true;
Parent.MemoryBlocksFree[MemBlockIndex] := true;
JobData := nil;
JobSize := 0;
PartIndex := -1;
MemBlockIndex := -1;
Parent.WorkerIdle[WorkerIndex] := true;
Parent.WakeUp;
end;
end.
|
unit UnitOpenGLShadowMapBlurShader;
{$ifdef fpc}
{$mode delphi}
{$ifdef cpui386}
{$define cpu386}
{$endif}
{$ifdef cpuamd64}
{$define cpux86_64}
{$endif}
{$ifdef cpu386}
{$define cpux86}
{$define cpu32}
{$asmmode intel}
{$endif}
{$ifdef cpux86_64}
{$define cpux64}
{$define cpu64}
{$asmmode intel}
{$endif}
{$ifdef FPC_LITTLE_ENDIAN}
{$define LITTLE_ENDIAN}
{$else}
{$ifdef FPC_BIG_ENDIAN}
{$define BIG_ENDIAN}
{$endif}
{$endif}
{-$pic off}
{$define caninline}
{$ifdef FPC_HAS_TYPE_EXTENDED}
{$define HAS_TYPE_EXTENDED}
{$else}
{$undef HAS_TYPE_EXTENDED}
{$endif}
{$ifdef FPC_HAS_TYPE_DOUBLE}
{$define HAS_TYPE_DOUBLE}
{$else}
{$undef HAS_TYPE_DOUBLE}
{$endif}
{$ifdef FPC_HAS_TYPE_SINGLE}
{$define HAS_TYPE_SINGLE}
{$else}
{$undef HAS_TYPE_SINGLE}
{$endif}
{$if declared(RawByteString)}
{$define HAS_TYPE_RAWBYTESTRING}
{$else}
{$undef HAS_TYPE_RAWBYTESTRING}
{$ifend}
{$if declared(UTF8String)}
{$define HAS_TYPE_UTF8STRING}
{$else}
{$undef HAS_TYPE_UTF8STRING}
{$ifend}
{$else}
{$realcompatibility off}
{$localsymbols on}
{$define LITTLE_ENDIAN}
{$ifndef cpu64}
{$define cpu32}
{$endif}
{$ifdef cpux64}
{$define cpux86_64}
{$define cpu64}
{$else}
{$ifdef cpu386}
{$define cpux86}
{$define cpu32}
{$endif}
{$endif}
{$define HAS_TYPE_EXTENDED}
{$define HAS_TYPE_DOUBLE}
{$ifdef conditionalexpressions}
{$if declared(RawByteString)}
{$define HAS_TYPE_RAWBYTESTRING}
{$else}
{$undef HAS_TYPE_RAWBYTESTRING}
{$ifend}
{$if declared(UTF8String)}
{$define HAS_TYPE_UTF8STRING}
{$else}
{$undef HAS_TYPE_UTF8STRING}
{$ifend}
{$else}
{$undef HAS_TYPE_RAWBYTESTRING}
{$undef HAS_TYPE_UTF8STRING}
{$endif}
{$endif}
{$ifdef win32}
{$define windows}
{$endif}
{$ifdef win64}
{$define windows}
{$endif}
{$ifdef wince}
{$define windows}
{$endif}
{$rangechecks off}
{$extendedsyntax on}
{$writeableconst on}
{$hints off}
{$booleval off}
{$typedaddress off}
{$stackframes off}
{$varstringchecks on}
{$typeinfo on}
{$overflowchecks off}
{$longstrings on}
{$openstrings on}
interface
uses {$ifdef fpcgl}gl,glext,{$else}dglOpenGL,{$endif}UnitOpenGLShader;
type TShadowMapBlurShader=class(TShader)
public
uTexture:glInt;
uDirection:glInt;
public
constructor Create;
destructor Destroy; override;
procedure BindAttributes; override;
procedure BindVariables; override;
end;
implementation
constructor TShadowMapBlurShader.Create;
var f,v:ansistring;
begin
v:='#version 330'+#13#10+
'out vec2 vTexCoord;'+#13#10+
'void main(){'+#13#10+
' vTexCoord = vec2((gl_VertexID >> 1) * 2.0, (gl_VertexID & 1) * 2.0);'+#13#10+
' gl_Position = vec4(((gl_VertexID >> 1) * 4.0) - 1.0, ((gl_VertexID & 1) * 4.0) - 1.0, 0.0, 1.0);'+#13#10+
'}'+#13#10;
f:='#version 330'+#13#10+
'in vec2 vTexCoord;'+#13#10+
'layout(location = 0) out vec4 oOutput;'+#13#10+
'uniform sampler2D uTexture;'+#13#10+
'uniform vec2 uDirection;'+#13#10+
'vec4 GaussianBlur(const in sampler2D pTexSource, const in vec2 pCenterUV, const in float pLOD, const in vec2 pPixelOffset){'+#13#10+
' return ((textureLod(pTexSource, pCenterUV + (pPixelOffset * 0.5949592424752924), pLOD) +'+#13#10+
' textureLod(pTexSource, pCenterUV - (pPixelOffset * 0.5949592424752924), pLOD)) * 0.3870341767000849)+'+#13#10+
' ((textureLod(pTexSource, pCenterUV + (pPixelOffset * 2.176069137573487), pLOD) +'+#13#10+
' textureLod(pTexSource, pCenterUV - (pPixelOffset * 2.176069137573487), pLOD)) * 0.11071876711891004);'+#13#10+
{ ' return ((textureLod(pTexSource, pCenterUV + (pPixelOffset * 0.6591712451751888), pLOD) +'+#13#10+
' textureLod(pTexSource, pCenterUV - (pPixelOffset * 0.6591712451751888), pLOD)) * 0.15176565679402804)+'+#13#10+
' ((textureLod(pTexSource, pCenterUV + (pPixelOffset * 2.4581680281192115), pLOD) +'+#13#10+
' textureLod(pTexSource, pCenterUV - (pPixelOffset * 2.4581680281192115), pLOD)) * 0.16695645822541735)+'+#13#10+
' ((textureLod(pTexSource, pCenterUV + (pPixelOffset * 4.425094078679077), pLOD) +'+#13#10+
' textureLod(pTexSource, pCenterUV - (pPixelOffset * 4.425094078679077), pLOD)) * 0.10520961571427603)+'+#13#10+
' ((textureLod(pTexSource, pCenterUV + (pPixelOffset * 6.39267736227941), pLOD) +'+#13#10+
' textureLod(pTexSource, pCenterUV - (pPixelOffset * 6.39267736227941), pLOD)) * 0.05091823661517932)+'+#13#10+
' ((textureLod(pTexSource, pCenterUV + (pPixelOffset * 8.361179642955081), pLOD) +'+#13#10+
' textureLod(pTexSource, pCenterUV - (pPixelOffset * 8.361179642955081), pLOD)) * 0.01892391240315673)+'+#13#10+
' ((textureLod(pTexSource, pCenterUV + (pPixelOffset * 10.330832149360727), pLOD) +'+#13#10+
' textureLod(pTexSource, pCenterUV - (pPixelOffset * 10.330832149360727), pLOD)) * 0.005400173381332095);'+#13#10+}
'}'+#13#10+
'void main(){'+#13#10+
' oOutput = GaussianBlur(uTexture, vTexCoord, 0.0, (vec2(1.0) / textureSize(uTexture, 0)) * uDirection);'+#13#10+
'}'+#13#10;
inherited Create(v,f);
end;
destructor TShadowMapBlurShader.Destroy;
begin
inherited Destroy;
end;
procedure TShadowMapBlurShader.BindAttributes;
begin
inherited BindAttributes;
end;
procedure TShadowMapBlurShader.BindVariables;
begin
inherited BindVariables;
uTexture:=glGetUniformLocation(ProgramHandle,pointer(pansichar('uTexture')));
uDirection:=glGetUniformLocation(ProgramHandle,pointer(pansichar('uDirection')));
end;
end.
|
unit uIBXCommonDB;
interface
uses uCommonDB, DB, IBDatabase, IBHeader, uIBXCommonDBErrors, IBQuery;
type
TIBXCommonDB = class(TCommonDB)
private
IBX_DB: TIBDatabase;
DefaultTransaction: TIBTransaction;
public
constructor Create;
destructor Destroy; override;
procedure SetHandle(const Handle); override;
procedure GetHandle(var Handle: Integer); override;
function GetTransaction: TCommonDBTransaction; override;
end;
TIBXDBTransaction = class(TCommonDBTransaction)
private
IBX_Transaction: TIBTransaction;
InProcess: Boolean;
Queries: array of TIBQuery;
WorkQuery: TIBQuery;
procedure FreeDataSets;
protected
function GetInTransaction: Boolean; override;
function GetNativeTransaction: TObject; override;
public
constructor Create(IBX_DB: TIBDatabase);
destructor Destroy; override;
procedure Start; override;
procedure Rollback; override;
procedure Commit; override;
procedure ExecQuery(SQL: string); override;
function QueryData(SQL: string): TDataSet; override;
procedure NewSQL(query: TDataSet; SQL: string); override;
procedure RemoveDataSet(query: TDataSet); override;
end;
function IBXCreateDBCenter(Handle: TISC_DB_Handle): TDBCenter;
implementation
uses SysUtils, Classes;
function IBXCreateDBCenter(Handle: TISC_DB_Handle): TDBCenter;
var
DB: TIBXCommonDB;
begin
DB := TIBXCommonDB.Create;
DB.SetHandle(Handle);
Result := TDBCenter.Create(DB);
end;
{*****************TIBXDBTransaction***************}
procedure TIBXDBTransaction.RemoveDataSet(query: TDataSet);
var
i, j: Integer;
begin
for i := 0 to High(Queries) do
if Queries[i] = query then
begin
query.Close;
for j := i + 1 to High(Queries) do
Queries[j - 1] := Queries[j];
SetLength(Queries, Length(Queries) - 1);
break;
end;
end;
function TIBXDBTransaction.GetNativeTransaction: TObject;
begin
Result := IBX_Transaction;
end;
procedure TIBXDBTransaction.NewSQL(query: TDataSet; SQL: string);
var
ibq: TIBQuery;
i: Integer;
begin
if not (query is TIBQuery) then
raise Exception.Create(E_IBXCommonDB_NewSQLNotIBQuery);
ibq := query as TIBQuery;
for i := 0 to High(Queries) do
if Queries[i] = ibq then
begin
ibq.Close;
ibq.SQL.Text := SQL;
ibq.Open;
Exit;
end;
raise Exception.Create(E_IBXCommonDB_NewSQLNotMine);
end;
function TIBXDBTransaction.GetInTransaction: Boolean;
begin
Result := InProcess;
end;
procedure TIBXDBTransaction.ExecQuery(SQL: string);
var
inTran: Boolean;
begin
inTran := InProcess;
if not inTran then Start;
WorkQuery.Close;
WorkQuery.SQL.Text := SQL;
WorkQuery.ExecSQL;
if not inTran then Commit;
end;
function TIBXDBTransaction.QueryData(SQL: string): TDataSet;
var
query: TIBQuery;
begin
if not InProcess then Start;
query := TIBQuery.Create(IBX_Transaction);
query.Transaction := IBX_Transaction;
SetLength(Queries, Length(Queries) + 1);
Queries[High(Queries)] := query;
query.SQL.Text := SQL;
query.Open;
Result := query;
end;
procedure TIBXDBTransaction.FreeDataSets;
var
i: Integer;
begin
for i := 0 to High(Queries) do
Queries[i].Free;
SetLength(Queries, 0);
end;
procedure TIBXDBTransaction.Start;
begin
if InProcess then
raise Exception.Create(E_IBXCommonDB_AlreadyStarted);
if not IBX_Transaction.Active then
IBX_Transaction.StartTransaction;
InProcess := True;
end;
procedure TIBXDBTransaction.Rollback;
begin
if not InProcess then
raise Exception.Create(E_IBXCommonDB_RollbackNotInTran);
IBX_Transaction.Rollback;
FreeDataSets;
InProcess := False;
end;
procedure TIBXDBTransaction.Commit;
begin
if not InProcess then
raise Exception.Create(E_IBXCommonDB_CommitNotInTran);
IBX_Transaction.Commit;
FreeDataSets;
InProcess := False;
end;
constructor TIBXDBTransaction.Create(IBX_DB: TIBDatabase);
begin
inherited Create;
IBX_Transaction := TIBTransaction.Create(IBX_DB);
IBX_Transaction.DefaultDatabase := IBX_DB;
with IBX_Transaction.Params do
begin
Add('read_committed');
Add('rec_version');
Add('nowait');
end;
SetLength(Queries, 0);
WorkQuery := TIBQuery.Create(IBX_Transaction);
WorkQuery.Transaction := IBX_Transaction;
InProcess := False;
end;
destructor TIBXDBTransaction.Destroy;
begin
WorkQuery.Free;
FreeDataSets;
IBX_Transaction.Free;
inherited Destroy;
end;
{********************TIBXCommonDB***********************}
function TIBXCommonDB.GetTransaction: TCommonDBTransaction;
begin
if IBX_DB = nil then
raise Exception.Create(E_IBXCommonDB_DBIsNil);
Result := TIBXDBTransaction.Create(IBX_DB);
end;
constructor TIBXCommonDB.Create;
begin
inherited Create;
IBX_DB := TIBDatabase.Create(nil);
DefaultTransaction := TIBTransaction.Create(IBX_DB);
IBX_DB.DefaultTransaction := DefaultTransaction;
DefaultTransaction.DefaultDatabase := IBX_DB;
end;
destructor TIBXCommonDB.Destroy;
begin
IBX_DB := nil;
DefaultTransaction.Free;
inherited Destroy;
end;
procedure TIBXCommonDB.SetHandle(const Handle);
begin
if IBX_DB = nil then
raise Exception.Create(E_IBXCommonDB_DBIsNil);
IBX_DB.SetHandle(TISC_DB_Handle(Handle));
end;
procedure TIBXCommonDB.GetHandle(var Handle: Integer);
begin
if IBX_DB = nil then
raise Exception.Create(E_IBXCommonDB_DBIsNil);
Handle := Integer(IBX_DB.Handle);
end;
end.
|
unit ProcessTemplateUnit;
interface
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
uses Classes, Generics.Collections, SysUtils, RbwParser,
Math
{$IFDEF FPC}
, SimpleTextWriter
{$ENDIF}
;
type
TParameter = record
ParameterName: string;
ParameterValue: double;
end;
TParameterDictionary = TDictionary<string, TParameter>;
EEnhanceTemplateError = class(Exception);
EPvalError = class(EEnhanceTemplateError);
EReadParamCountError = class(EPvalError);
EReadParamError = class(EPvalError);
ETemplateError = class(EEnhanceTemplateError);
EBadFileName = class(ETemplateError);
EBadDelimiter = class(ETemplateError);
EUnmatchedDelimiter = class(ETemplateError);
ENotEnoughPrecision = class(ETemplateError);
EBadParamName = class(ETemplateError);
ECompileError = class(ETemplateError);
TParameterProcessor = class(TObject)
private
FTemplateFileName: string;
FPvalFileName: string;
{$IFDEF FPC}
FTemplateFile: TSimpleStreamReader;
FPValFile: TSimpleStreamReader;
FModelOutputFile: TSimpleStreamWriter;
{$ELSE}
FTemplateFile: TStreamReader;
FPValFile: TStreamReader;
FModelOutputFile: TStreamWriter;
{$ENDIF}
FParameters: TParameterDictionary;
FParser: TRbwParser;
FParameterDelimiter: Char;
FFormulaDelimiter: Char;
procedure WriteUsage;
procedure WriteParameters;
procedure GetFileNames;
procedure OpenFiles;
procedure CloseFiles;
Procedure ReadPValFile;
procedure ReadAndProcessTemplateLines;
procedure ReadTemplateHeader;
procedure ProcessTemplateLine(ALine: string);
private
procedure ProcessTemplate;
public
Constructor Create;
destructor Destroy; override;
end;
procedure ProcessTemplate;
implementation
uses
StrUtils;
resourcestring
StrUnableToReadTheN = 'Unable to read the number of parameters from the PV' +
'AL file';
StrInThePVALFile = 'In the PVAL file, "%s" does not have exactly two value' +
's separated by commas or whitespace.';
StrInThePVALFileNoConvert = 'In the PVAL file, unable to convert "%0:s" to' +
' a number in "1:s".';
StrErrorReadingPVALF = 'Error reading PVAL file. Only %0:d read instead of' +
' %1:d.';
StrErrorReadingThePa = 'Error Reading the %s delimiter. Parameter d' +
'elimiters must be one character in length.';
StrErrorReadingTheFo = 'Error reading the formula delimiter from the templ' +
'ate file. The line for the formula delimiter must begin with "etf " follo' +
'wed by a single character.';
StrUnmatchedDelimiter = 'There is an unmatched %0:s delimiter in "%1:s".';
StrNotEnoughSpace = 'There was not enough space to replace %0:s with the p' +
'arameter value in "%1:s. The available space starts at position %2:d and ends at position %3:d.';
StrNoParameterNamed = 'No parameter named %s was defined in the PVAL file.';
StrDuplicateDelimiters = 'Both the parameter delimiter and formula delimit' +
'er are set to "%s". The two must be different from each other.';
StrConversionProblem = 'There was an error converting "%0:s" to a real number in the lined %1:s';
procedure ProcessTemplate;
var
Processor: TParameterProcessor;
begin
Processor := TParameterProcessor.Create;
try
Processor.ProcessTemplate;
finally
Processor.Free;
end;
end;
function MaxPrecisionFloatToStr(value: double; AvailableWidth: Integer): string;
var
Exponent: Integer;
ExponentStr: string;
ExponentLength: Integer;
DecimalPostion: Integer;
begin
result := FloatToStr(Value);
if Length(result) > AvailableWidth then
begin
Exponent := Trunc(Log10(Abs(Value)));
result := FloatToStrF(Value, ffGeneral, AvailableWidth,
Max(0, AvailableWidth-Exponent-1));
if Length(result) > AvailableWidth then
begin
DecimalPostion := Pos('.', result);
if (Pos('E', result) = 0) and
((DecimalPostion <= AvailableWidth) and (DecimalPostion > 0)) then
begin
result := Copy(result, 1, AvailableWidth);
end
else
begin
ExponentStr := 'E' + IntToStr(Exponent);
ExponentLength := Length(ExponentStr);
if ExponentLength < AvailableWidth then
begin
result := FloatToStrF(Value, ffExponent, AvailableWidth,
Max(0, AvailableWidth-Exponent-1));
result := Copy(result, 1, AvailableWidth-ExponentLength) + ExponentStr
end;
end;
end;
end;
end;
function PadLeft(AString: string; AvailableWidth: Integer): string;
begin
result := AString;
while Length(result) < AvailableWidth do
begin
result := ' ' + result;
end;
end;
function PadRight(AString: string; AvailableWidth: Integer): string;
begin
result := AString;
while Length(result) < AvailableWidth do
begin
result := result + ' ';
end;
end;
procedure TParameterProcessor.WriteUsage;
begin
WriteLn('Usage');
WriteLn(' EnhancedTemplateProcessor <template file name>');
WriteLn(' EnhancedTemplateProcessor <template file name> <PVAL file name>');
WriteLn('A PVAL is not required if formulas do not require parameter value substitution.');
WriteLn('File names that include white space must be enclosed in quotation marks');
end;
procedure TParameterProcessor.WriteParameters;
var
ParamIndex: Integer;
begin
WriteLn('File names on the command line');
for ParamIndex := 0 to ParamCount do
begin
WriteLn(ParamStr(ParamIndex));
end;
end;
procedure TParameterProcessor.CloseFiles;
begin
FTemplateFile.Free;
FPValFile.Free;
FModelOutputFile.Free;
end;
constructor TParameterProcessor.Create;
begin
FParser := TRbwParser.Create(nil);
FParameters := TParameterDictionary.Create;
FormatSettings.DecimalSeparator := '.';
end;
destructor TParameterProcessor.Destroy;
begin
FParameters.Free;
FParser.Free;
inherited;
end;
procedure TParameterProcessor.GetFileNames;
begin
FTemplateFileName := ParamStr(1);
FTemplateFileName := ExpandFileName(FTemplateFileName);
if ParamCount = 2 then
begin
FPvalFileName := ParamStr(2);
FPvalFileName := ExpandFileName(FPvalFileName);
end
else
begin
FPvalFileName := '';
end;
end;
procedure TParameterProcessor.OpenFiles;
begin
if ExtractFileExt(FTemplateFileName) = '' then
begin
raise EBadFileName.Create('Template files must have an extension');
end;
{$IFDEF FPC}
FTemplateFile := TSimpleStreamReader.Create(FTemplateFileName);
{$ELSE}
FTemplateFile := TStreamReader.Create(FTemplateFileName);
{$ENDIF}
if FPvalFileName <> '' then
begin
{$IFDEF FPC}
FPValFile := TSimpleStreamReader.Create(FPvalFileName);
{$ELSE}
FPValFile := TStreamReader.Create(FPvalFileName);
{$ENDIF}
end
else
begin
FPValFile := nil;
end;
{$IFDEF FPC}
FModelOutputFile := TSimpleStreamWriter.Create(
ChangeFileExt(FTemplateFileName, ''));
{$ELSE}
FModelOutputFile := TStreamWriter.Create(
ChangeFileExt(FTemplateFileName, ''));
{$ENDIF}
end;
procedure TParameterProcessor.ProcessTemplate;
begin
if (ParamCount = 0) then
begin
WriteUsage;
Exit;
end;
if (ParamCount > 2) then
begin
WriteUsage;
WriteParameters;
Exit;
end;
if ParamStr(1) = '?' then
begin
WriteUsage;
Exit;
end;
try
GetFileNames;
OpenFiles;
ReadPValFile;
ReadAndProcessTemplateLines;
finally
CloseFiles;
end;
end;
procedure TParameterProcessor.ProcessTemplateLine(ALine: string);
var
StartPosition: Integer;
EndPos: Integer;
OriginalLine: string;
ParameterName: string;
Parameter: TParameter;
ReplacementString: string;
AvailableLength: Integer;
AValue: double;
TemplateParameterName: string;
Formula: string;
StartFormula: Integer;
OriginalFormula: string;
function CountFormulaDelimiterBefore(APosition: Integer): integer;
var
FormulaDelimiterPosition: Integer;
begin
result := 0;
FormulaDelimiterPosition := Pos (FFormulaDelimiter, ALine);
while FormulaDelimiterPosition > 0 do
begin
Inc(result);
FormulaDelimiterPosition := PosEx (FFormulaDelimiter, ALine,
Succ(FormulaDelimiterPosition));
if FormulaDelimiterPosition > APosition then
begin
break;
end;
end;
end;
begin
OriginalLine := ALine;
if FParameterDelimiter <> ' ' then
begin
StartPosition := Pos (FParameterDelimiter, ALine);
while StartPosition > 0 do
begin
EndPos := PosEx(FParameterDelimiter, ALine, Succ(StartPosition));
if EndPos = 0 then
begin
raise EUnmatchedDelimiter.Create(Format(StrUnmatchedDelimiter,
['parameter', OriginalLine]));
end;
TemplateParameterName := Copy(ALine, Succ(StartPosition), EndPos-StartPosition-1);
ParameterName := UpperCase(Trim(TemplateParameterName));
if FParameters.TryGetValue(ParameterName, Parameter) then
begin
AvailableLength := EndPos-StartPosition+1;
ReplacementString := MaxPrecisionFloatToStr(Parameter.ParameterValue,
AvailableLength);
if Odd(CountFormulaDelimiterBefore(StartPosition)) then
begin
ReplacementString := PadRight(ReplacementString, AvailableLength);
end
else
begin
ReplacementString := PadLeft(ReplacementString, AvailableLength);
end;
if Length(ReplacementString) > AvailableLength then
begin
raise ENotEnoughPrecision.Create(Format(StrNotEnoughSpace,
[TemplateParameterName, OriginalLine, StartPosition, EndPos]));
end
else if not TryStrToFloat(Trim(ReplacementString), AValue) then
begin
raise EConvertError.Create(Format(StrConversionProblem,
[ReplacementString, OriginalLine]));
end;
ALine := Copy(ALine, 1, Pred(StartPosition)) + ReplacementString
+ Copy(ALine, Succ(EndPos), MaxInt);
StartPosition := Pos (FParameterDelimiter, ALine);
end
else
begin
raise EBadParamName.Create(Format(StrNoParameterNamed,
[Trim(TemplateParameterName)]));
end;
end;
end;
StartPosition := Pos (FFormulaDelimiter, ALine);
while StartPosition > 0 do
begin
EndPos := PosEx(FFormulaDelimiter, ALine, Succ(StartPosition));
if EndPos = 0 then
begin
raise EUnmatchedDelimiter.Create(Format(StrUnmatchedDelimiter,
['formula', OriginalLine]));
end;
Formula := Trim(Copy(ALine, Succ(StartPosition), EndPos-StartPosition-1));
OriginalFormula := Formula;
StartFormula := PosEx(Formula, ALine, Succ(StartPosition));
// The number should end where the formula begins.
AvailableLength := StartFormula - StartPosition;
try
FParser.Compile(Formula);
AValue := FParser.CurrentExpression.DoubleResult;
except on E: Exception do
begin
raise ECompileError.Create(Format('Unable to evaluate the formula "%0:s" in "%1:s." The error message was "%:2s"',
[OriginalFormula, OriginalLine, E.Message]));
end;
end;
ReplacementString := MaxPrecisionFloatToStr(AValue, AvailableLength);
ReplacementString := PadLeft(ReplacementString, AvailableLength);
if Length(ReplacementString) > AvailableLength then
begin
raise ENotEnoughPrecision.Create(Format(StrNotEnoughSpace,
[TemplateParameterName, OriginalLine, StartPosition, StartFormula]));
end
else if not TryStrToFloat(Trim(ReplacementString), AValue) then
begin
raise EConvertError.Create(Format(StrConversionProblem,
[ReplacementString, OriginalLine]));
end;
ALine := Copy(ALine, 1, Pred(StartPosition)) + ReplacementString
+ Copy(ALine, Succ(EndPos), MaxInt);
StartPosition := Pos (FFormulaDelimiter, ALine);
end;
FModelOutputFile.WriteLine(ALine);
end;
procedure TParameterProcessor.ReadAndProcessTemplateLines;
var
ALine: string;
begin
ReadTemplateHeader;
while not FTemplateFile.EndOfStream do
begin
ALine := FTemplateFile.ReadLine;
ProcessTemplateLine(ALine);
end;
end;
procedure TParameterProcessor.ReadPValFile;
var
ALine: string;
ParameterCount: Integer;
Splitter: TStringList;
AParameter: TParameter;
Value: Double;
ValueString: String;
DPos: Integer;
begin
if FPValFile <> nil then
begin
while Not FPValFile.EndOfStream do
begin
ALine := Trim(FPValFile.ReadLine);
if (Aline = '') or (Aline[1] = '#') then
begin
Continue;
end;
if TryStrToInt(Aline, ParameterCount) then
begin
FParameters.Capacity := ParameterCount;
break;
end
else
begin
raise EReadParamCountError.Create(StrUnableToReadTheN)
end;
end;
Splitter := TStringList.Create;
try
Splitter.StrictDelimiter := False;
while Not FPValFile.EndOfStream do
begin
ALine := Trim(FPValFile.ReadLine);
if (Aline = '') or (Aline[1] = '#') then
begin
Continue;
end;
Splitter.DelimitedText := ALine;
if Splitter.Count <> 2 then
begin
raise EReadParamError.Create(Format(StrInThePVALFile, [ALine]));
end;
AParameter.ParameterName := Splitter[0];
ValueString := Splitter[1];
DPos := Pos('D', ValueString);
if DPos >= 1 then
begin
ValueString[DPos] := 'E';
end;
DPos := Pos('d', ValueString);
if DPos >= 1 then
begin
ValueString[DPos] := 'e';
end;
if TryStrToFloat(ValueString, Value) then
begin
AParameter.ParameterValue := Value;
FParameters.Add(UpperCase(AParameter.ParameterName), AParameter);
if FParameters.Count = ParameterCount then
begin
break;
end;
end
else
begin
raise EReadParamError.Create(Format(StrInThePVALFileNoConvert,
[Splitter[1], ALine]));
end;
end;
finally
Splitter.Free;
end;
if FParameters.Count <> ParameterCount then
begin
raise EReadParamError.Create(Format(StrErrorReadingPVALF,
[FParameters.Count, ParameterCount]));
end;
end;
end;
procedure TParameterProcessor.ReadTemplateHeader;
var
ALine: string;
ID: string;
TemplateString: string;
procedure ReadFormulaDelimiter;
begin
if (ID = 'etf ') then
begin
TemplateString := Trim(Copy(ALine,5, MAXINT));
if Length(TemplateString) = 1 then
begin
FFormulaDelimiter := TemplateString[1];
end
else
begin
raise EBadDelimiter.Create(Format(StrErrorReadingThePa, ['formula']));
end;
end
else
begin
raise EBadDelimiter.Create(StrErrorReadingTheFo);
end;
end;
begin
ALine := FTemplateFile.ReadLine;
ID := Copy(ALine, 1, 4);
if (ID = 'ptf ') or (ID = 'jtf ') then
begin
TemplateString := Trim(Copy(ALine,5, MAXINT));
if Length(TemplateString) = 1 then
begin
FParameterDelimiter := TemplateString[1];
ALine := FTemplateFile.ReadLine;
ID := Copy(ALine, 1, 4);
ReadFormulaDelimiter;
end
else
begin
raise EBadDelimiter.Create(Format(StrErrorReadingThePa, ['parameter']));
end;
end
else
begin
FParameterDelimiter := ' ';
ReadFormulaDelimiter;
end;
if FParameterDelimiter = FFormulaDelimiter then
begin
raise EBadDelimiter.Create(Format(StrDuplicateDelimiters,
[FParameterDelimiter]));
end;
end;
end.
|
unit ufrmElectricPayment;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterBrowse, StdCtrls, ExtCtrls, ComCtrls, ActnList, cxGraphics,
cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, cxStyles,
cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB,
cxDBData, cxContainer, dxCore, cxDateUtils, Vcl.Menus, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxCurrencyEdit, cxDropDownEdit,
cxLookupEdit, cxDBLookupEdit, cxDBExtLookupComboBox, System.Actions,
ufraFooter4Button, cxButtons, cxTextEdit, cxMaskEdit, cxCalendar, cxLabel,
cxGridLevel, cxClasses, cxGridCustomView, cxGrid, cxPC;
type
TfrmElectricPayment = class(TfrmMasterBrowse)
pnlTop: TPanel;
lbl6: TLabel;
lbl1: TLabel;
lbl4: TLabel;
lbl5: TLabel;
lbl8: TLabel;
lbl11: TLabel;
lbl12: TLabel;
cbpCustomerCode: TcxExtLookupComboBox;
edtCustomerName: TEdit;
edtPaymentNo: TEdit;
edtDescription: TEdit;
edtAmountInvoice: TcxCurrencyEdit;
edtTotalPayment: TcxCurrencyEdit;
cbpInvoiceNo: TcxExtLookupComboBox;
lbl2: TLabel;
dtpRecv: TDateTimePicker;
lbl3: TLabel;
cbpBankAccount: TcxExtLookupComboBox;
edtBankAccount: TEdit;
btnShow: TcxButton;
cxcolNo: TcxGridDBColumn;
cxcolBankAccount: TcxGridDBColumn;
cxcolDocument: TcxGridDBColumn;
cxcolReceiptDate: TcxGridDBColumn;
cxcolAmount: TcxGridDBColumn;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure fraFooter4Button1btnCloseClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure cbpCustomerCodeChange(Sender: TObject);
procedure cbpInvoiceNoChange(Sender: TObject);
procedure cbpBankAccountChange(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btnShowClick(Sender: TObject);
procedure actAddExecute(Sender: TObject);
procedure actPrintExecute(Sender: TObject);
private
{ Private declarations }
JournalCode : string;
JournalID : Integer;
NoRekening : string;
PaymentId: Integer;
company_id, unit_id, customer_id, InvoiceId, InvoiceUnitId, RekCompanyId: Integer;
procedure SetInputComponents(Disable: Boolean);
procedure ClearAllControls;
procedure ShowDataElectricPayment;
procedure FillComboCustomer(aUnit_Id: Integer);
procedure FillComboInvoice(CustomerId: Integer);
procedure FillComboBankAccount(aCompany_Id: Integer);
public
{ Public declarations }
end;
var
frmElectricPayment: TfrmElectricPayment;
implementation
{$R *.dfm}
uses
uConn, uTSCommonDlg, uConstanta, udmReport, ufrmDialogPrintPreview;
var arrParam: TArr;
arrInvoiceUnitId, arrRekeningCompanyId, arrPaymentId: array of Integer;
arrAmountInvoice: array of Currency;
max_payment_no: Int64;
procedure TfrmElectricPayment.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action:= caFree;
end;
procedure TfrmElectricPayment.FormDestroy(Sender: TObject);
begin
inherited;
frmElectricPayment:= nil;
end;
procedure TfrmElectricPayment.fraFooter4Button1btnCloseClick(
Sender: TObject);
begin
inherited;
if fraFooter4Button1.btnAdd.Tag = 1 then
begin
fraFooter4Button1.btnAdd.Tag := 0;
fraFooter4Button1.btnAdd.Caption:= '&Add';
fraFooter4Button1.btnClose.Tag := 0;
fraFooter4Button1.btnClose.Caption:= 'Close';
fraFooter4Button1.btnUpdate.Enabled:= True;
btnShow.Enabled:= True;
SetInputComponents(True);
ClearAllControls;
end
else if fraFooter4Button1.btnUpdate.Tag = 1 then
begin
fraFooter4Button1.btnUpdate.Tag := 0;
fraFooter4Button1.btnUpdate.Caption:= '&Edit';
fraFooter4Button1.btnClose.Tag := 0;
fraFooter4Button1.btnClose.Caption:= 'Close';
fraFooter4Button1.btnAdd.Enabled:= True;
btnShow.Enabled:= True;
SetInputComponents(True);
ClearAllControls;
end
end;
procedure TfrmElectricPayment.FormShow(Sender: TObject);
var i: Integer;
begin
inherited;
// kode jurnal dibikin constanta
JournalCode := 'R007';
JournalID := 103;
dtpRecv.Date:= Now;
SetInputComponents(True);
end;
procedure TfrmElectricPayment.SetInputComponents(Disable: Boolean);
var i: Integer;
begin
with pnlTop do
begin
for i:= 0 to ControlCount-1 do
begin
if Disable and not (Controls[i] is TLabel) and not (Controls[i] is TcxButton) then
begin
Controls[i].Enabled:= False;
end
else if not Disable then
if not (Controls[i] is TcxButton) then
Controls[i].Enabled:= True
else
Controls[i].Enabled:= False;
end;
end;
end;
procedure TfrmElectricPayment.cbpCustomerCodeChange(Sender: TObject);
begin
inherited;
edtAmountInvoice.Value:= 0;
edtAmountInvoice.Clear;
// if cbpCustomerCode.Row > 0 then
// begin
// edtCustomerName.Text:= cbpCustomerCode.Cells[2, cbpCustomerCode.Row];
// FillComboInvoice(StrToInt(cbpCustomerCode.Cells[0,cbpCustomerCode.Row]));
// ShowDataElectricPayment;
// end
// else
begin
edtCustomerName.Text:= '';
end;
end;
procedure TfrmElectricPayment.cbpInvoiceNoChange(Sender: TObject);
begin
inherited;
// if cbpInvoiceNo.Row > 0 then
// begin
// if (cbpInvoiceNo.Cells[0, cbpInvoiceNo.Row] <> '') and
// (cbpInvoiceNo.Cells[0, cbpInvoiceNo.Row] <> 'Id') and (Length(arrAmountInvoice) > 0)then
// begin
// edtAmountInvoice.Value := arrAmountInvoice[cbpInvoiceNo.Row-1];
// InvoiceId := StrToInt(cbpInvoiceNo.Cells[0, cbpInvoiceNo.Row]);
// InvoiceUnitId := arrInvoiceUnitId[cbpInvoiceNo.Row-1];
// end
// else
// begin
// edtAmountInvoice.Value:= 0;
// edtAmountInvoice.Clear;
// end;
// end
// else
// begin
// edtAmountInvoice.Value:= 0;
// edtAmountInvoice.Clear;
// end;
end;
procedure TfrmElectricPayment.ClearAllControls;
begin
cbpCustomerCode.Clear;
edtCustomerName.Clear;
cbpInvoiceNo.Clear;
dtpRecv.Date:= Now;
edtPaymentNo.Clear;
edtDescription.Clear;
cbpBankAccount.Clear;
edtBankAccount.Clear;
edtAmountInvoice.Clear;
edtTotalPayment.Clear;
end;
procedure TfrmElectricPayment.cbpBankAccountChange(Sender: TObject);
begin
inherited;
//
// if cbpBankAccount.Row > 0 then
// begin
// edtBankAccount.Text:= cbpBankAccount.Cells[2, cbpBankAccount.Row];
// NoRekening:= cbpBankAccount.Cells[1, cbpBankAccount.Row];
// RekCompanyId:= arrRekeningCompanyId[cbpBankAccount.Row-1];
// end
// else
// begin
// edtBankAccount.Text:= '';
// end;
end;
procedure TfrmElectricPayment.ShowDataElectricPayment;
var
i: Integer;
sSQL: string;
begin
sSQL:= 'select c.cust_name, rkj.kdjur_code, rkj.kdjur_name, rkj.kdjur_comp_id,'
+ ' ep.elpay_document_no, ep.elpay_date, ep.elpay_description, ep.elpay_amount_payment,'
+ ' b.bank_name, ep.ELPAY_ID, r.rek_code'
+ ' from electric_payment ep'
+ ' left join electric_invoice ei on ep.elpay_elinv_id = ei.elinv_id'
+ ' left join electric_customer ec on ei.elinv_elcust_id = ec.elcust_id'
+ ' left join customer c on ec.elcust_cust_id = c.cust_id'
+ ' left join ref$kode_jurnal rkj on ep.elpay_kdjur_id = rkj.kdjur_id'
+ ' left join rekening r on ep.elpay_rek_code_bank = r.rek_code'
+ ' left join bank b on r.rek_code = b.bank_rek_code'
// + ' where ec.ELCUST_ID = '+ cbpCustomerCode.Cells[0,cbpCustomerCode.Row];
// strgGrid.ClearNormalCells;
// strgGrid.RowCount:= 2;
//
// with cOpenQuery(sSQL, False) do
// begin
// try
// if not IsEmpty then
// begin
// with strgGrid do
// begin
// ClearNormalCells;
// Last;
// RowCount:= RecordCount + 1;
// SetLength(arrPaymentId, RecordCount);
// i:= 1;
//
// First;
// while not Eof do
// begin
// Cells[0,i] := IntToStr(i);
// Alignments[0,i] := taCenter;
// Cells[1,i] := FieldByName('bank_name').AsString;
// Cells[2,i] := FieldByName('elpay_document_no').AsString;
// Cells[3,i] := FormatDateTime('dd mmmm yyyy', FieldByName('elpay_date').AsDateTime);
// Cells[4,i] := FormatCurr('#,##0.00', FieldByName('elpay_amount_payment').AsFloat);
// Alignments[4,i] := taRightJustify;
// arrPaymentId[i-1] := FieldByName('ELPAY_ID').AsInteger;
//
// Inc(i);
// Next;
// end;
// end;
//
// strgGridClickCell(Self,1,0);
//
// end
// else
// begin
// SetLength(arrPaymentId,0);
// end;
//
// finally
// Free;
// end;
// end;
end;
procedure TfrmElectricPayment.FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if (Key = Ord('P')) and (ssctrl in Shift) then
GetAndRunButton('btnDelete');
end;
procedure TfrmElectricPayment.btnShowClick(Sender: TObject);
begin
inherited;
// if Mastercompany.ID = 0 then
// begin
// CommonDlg.ShowError(ER_COMPANY_NOT_SPECIFIC);
// //frmMain.cbbCompCode.SetFocus;
// Exit;
// end
// else if MasterNewUnit.ID = 0 then
// begin
// CommonDlg.ShowError(ER_UNIT_NOT_SPECIFIC);
// //frmMain.cbbUnit.SetFocus;
// Exit;
// end;
//
// if cbpCustomerCode.Enabled then
// begin
// cbpCustomerCodeChange(Self);
// end
// else
// begin
// cbpCustomerCode.Enabled:= True;
// FillComboCustomer(MasterNewUnit.ID);
// cbpCustomerCode.SetFocus;
// edtCustomerName.Enabled:= True;
// end;
end;
procedure TfrmElectricPayment.FillComboBankAccount(aCompany_Id: Integer);
var
i : Integer;
sSQL: string;
begin
sSQL:= 'select b.BANK_ID, b.BANK_CODE, b.BANK_NAME, r.REK_CODE, r.REK_COMP_ID'
+ ' from bank b'
+ ' left join rekening r on b.bank_rek_code = r.rek_code'
+ ' where b.BANK_REK_CODE is not null'
+ ' and r.REK_COMP_ID = '+ IntToStr(aCompany_Id)
+ ' order by b.BANK_CODE asc';
// isi list combo box bank account
// with cbpBankAccount do
// begin
// ClearGridData;
// ColCount := 3;
//
// with cOpenQuery(sSQL, False) do
// begin
// try
// Last;
// if not IsEmpty then
// begin
// First;
// SetLength(arrRekeningCompanyId, RecordCount);
// i:= 0;
// RowCount := RecordCount + 1;
// AddRow(['Id', 'Rekening Code', 'Bank Name']);
//
// while not Eof do
// begin
// AddRow([FieldByName('BANK_ID').AsString,
// FieldByName('REK_CODE').AsString,
// FieldByName('BANK_NAME').AsString]);
// arrRekeningCompanyId[i]:= FieldByName('REK_COMP_ID').AsInteger;
//
// Inc(i);
// Next;
// end;
// end
// else
// begin
// SetLength(arrRekeningCompanyId, 0);
// RowCount := 2;
// AddRow(['Id', 'Rekening Code', 'Bank Name']);
// AddRow(['', ' ', ' ']);
// end;
//
// finally
// Free;
// end;
// end;
//
// FixedRows := 1;
// SizeGridToData;
// Text := '';
// end;
end;
procedure TfrmElectricPayment.FillComboInvoice(CustomerId: Integer);
var
i : Integer;
sSQL: string;
begin
// if (cbpCustomerCode.Cells[0,cbpCustomerCode.Row] <> '') and
// (cbpCustomerCode.Cells[0,cbpCustomerCode.Row] <> 'Id') then
// begin
// sSQL:= 'select ELINV_ID, ELINV_UNT_ID, ELINV_NUMBER,'
// + ' (ELINV_COST_ABODEMEN + ELINV_COST_USE +'
// + ' ELINV_TTBL + ELINV_PJU) AS total_invoice'
// + ' from electric_invoice'
// + ' where ELINV_IS_PAYMENT = 0'
// + ' and ELINV_ELCUST_ID = '+ cbpCustomerCode.Cells[0,cbpCustomerCode.Row];
//
// // isi list combo box electric invoice
// with cbpInvoiceNo do
// begin
// ClearGridData;
// ColCount := 2;
//
// with cOpenQuery(sSQL, False) do
// begin
// try
// if not IsEmpty then
// begin
// Last;
// ReadOnly:= False;
// First;
// SetLength(arrInvoiceUnitId, RecordCount);
// SetLength(arrAmountInvoice, RecordCount);
// i:= 0;
//
// RowCount := RecordCount + 1;
// AddRow(['Id', 'Invoice No']);
//
// while not Eof do
// begin
// arrInvoiceUnitId[i]:= FieldByName('ELINV_UNT_ID').AsInteger;
// arrAmountInvoice[i]:= FieldByName('total_invoice').AsCurrency;
// Inc(i);
//
// AddRow([FieldByName('ELINV_ID').AsString,
// FieldByName('ELINV_NUMBER').AsString]);
//
// Next;
// end;
// end
// else
// begin
// SetLength(arrInvoiceUnitId, 0);
// SetLength(arrAmountInvoice, 0);
// RowCount := 2;
// AddRow(['Id', 'Invoice No']);
// AddRow(['', ' ']);
// ReadOnly:= True;
// end;
//
// finally
// Free;
// end;
// end;
//
// FixedRows := 1;
// SizeGridToData;
// Text := '';
// end;
// end;
end;
procedure TfrmElectricPayment.FillComboCustomer(aUnit_Id: Integer);
var
sSQL: string;
begin
sSQL:= 'select ec.ELCUST_ID, c.CUST_ID, c.CUST_CODE, c.CUST_NAME'
+ ' from electric_customer ec'
+ ' left join customer c on ec.elcust_cust_id = c.cust_id'
+ ' where ec.ELCUST_UNT_ID = '+ IntToStr(aUnit_Id)
+ ' order by c.CUST_CODE asc';
// isi list combo box electric customer
// with cbpCustomerCode do
// begin
// ClearGridData;
// ColCount := 3;
//
// with cOpenQuery(sSQL, False) do
// begin
// try
// Last;
// if not IsEmpty then
// begin
// First;
// RowCount := RecordCount + 1;
// AddRow(['Id', 'Customer Code', 'Customer Name']);
//
// while not Eof do
// begin
// AddRow([FieldByName('ELCUST_ID').AsString,
// FieldByName('CUST_CODE').AsString,
// FieldByName('CUST_NAME').AsString]);
//
// Next;
// end;
// end
// else
// begin
// RowCount := 2;
// AddRow(['Id', 'Customer Code', 'Customer Name']);
// AddRow(['', ' ', ' ']);
// end;
//
// finally
// Free;
// end;
// end;
//
// FixedRows := 1;
// SizeGridToData;
// Text := '';
// end;
end;
procedure TfrmElectricPayment.actAddExecute(Sender: TObject);
begin
inherited;
//
// if Mastercompany.ID = 0 then begin
// CommonDlg.ShowError(ER_COMPANY_NOT_SPECIFIC);
// //frmMain.cbbCompCode.SetFocus;
// Exit;
// end
// else if MasterNewUnit.ID = 0 then begin
// CommonDlg.ShowError(ER_UNIT_NOT_SPECIFIC);
// //frmMain.cbbUnit.SetFocus;
// Exit;
// end;
//
// if not Assigned(ElectricPayment) then
// ElectricPayment:= TElectricPayment.Create;
//
// if fraFooter4Button1.btnAdd.Tag = 0 then begin
// fraFooter4Button1.btnAdd.Tag := 1;
// fraFooter4Button1.btnAdd.Caption:= '&Save';
// fraFooter4Button1.btnClose.Tag := 1;
// fraFooter4Button1.btnClose.Caption:= 'Abort';
// fraFooter4Button1.btnUpdate.Enabled:= False;
// SetInputComponents(False);
//
// strgGrid.ClearNormalCells;
// strgGrid.RowCount:= 2;
//
// FillComboCustomer(MasterNewUnit.ID);
//
// SetLength(arrParam,0);
// dataPaymentNo:= ElectricPayment.GetMaxPaymentNo(arrParam);
// if not dataPaymentNo.IsEmpty then begin
// if dataPaymentNo.FieldByName('max_no').Value <> Null then
// max_payment_no:= StrToInt(dataPaymentNo.FieldByName('max_no').AsString)
// else
// max_payment_no:= 0;
// end
// else
// max_payment_no:= 0;
//
// edtPaymentNo.Text:= StrPadLeft(IntToStr(max_payment_no + 1), 10, '0');
//
// FillComboBankAccount(Mastercompany.ID);
// end
// else begin
// if (Trim(cbpInvoiceNo.Cells[0, cbpInvoiceNo.Row]) = '') or
// (cbpInvoiceNo.Cells[0, cbpInvoiceNo.Row] = 'Id') then begin
// CommonDlg.ShowError('Invoice No cannot be empty.');
// cbpInvoiceNo.SetFocus;
// Exit;
// end;
//
// if (Trim(cbpCustomerCode.Cells[0, cbpCustomerCode.Row]) = '') or
// (cbpCustomerCode.Cells[0, cbpCustomerCode.Row] = 'Id') then begin
// CommonDlg.ShowError('Customer must be specific.');
// cbpCustomerCode.SetFocus;
// Exit;
// end;
//
// try
// ElectricPayment.BeginTransaction;
//
// // insert ke tabel electric_payment
// SetLength(arrParam,15);
// arrParam[0].tipe := ptInteger;
// if MasterNewUnit.ID < 1 then
// arrParam[0].data := 0
// else
// arrParam[0].data := MasterNewUnit.ID;
// arrParam[1].tipe := ptInteger;
// arrParam[1].data := StrToInt(cbpInvoiceNo.Cells[0, cbpInvoiceNo.Row]);
// arrParam[2].tipe := ptInteger;
// arrParam[2].data := arrInvoiceUnitId[cbpInvoiceNo.Row-1];
// arrParam[3].tipe := ptDateTime;
// arrParam[3].data := dtpRecv.Date;
// arrParam[4].tipe := ptString;
// arrParam[4].data := edtPaymentNo.Text;
// arrParam[5].tipe := ptInteger;
// arrParam[5].data := JournalID;
// arrParam[6].tipe := ptInteger;
// arrParam[6].data := Mastercompany.ID;
// arrParam[7].tipe := ptCurrency;
// arrParam[7].data := edtTotalPayment.Value;
// arrParam[8].tipe := ptString;
// arrParam[8].data := edtDescription.Text;
// arrParam[9].tipe := ptString;
// arrParam[9].data := cbpBankAccount.Cells[1, cbpBankAccount.Row];
// arrParam[10].tipe := ptInteger;
// arrParam[10].data := arrRekeningCompanyId[cbpBankAccount.Row-1];
// arrParam[11].tipe := ptString;
// arrParam[11].data := cbpBankAccount.Cells[1, cbpBankAccount.Row];
// arrParam[12].tipe := ptInteger;
// arrParam[12].data := arrRekeningCompanyId[cbpBankAccount.Row-1];
// arrParam[13].tipe := ptInteger;
// arrParam[13].data := FLoginId;
// arrParam[14].tipe := ptDateTime;
// arrParam[14].data := Date;
// ElectricPayment.AddElectricPayment(arrParam);
//
// // ubah status is_payment
// SetLength(arrParam,1);
// arrParam[0].tipe := ptInteger;
// arrParam[0].data := StrToInt(cbpInvoiceNo.Cells[0, cbpInvoiceNo.Row]);
// ElectricPayment.EditStatusIsPayment(arrParam);
//
// ElectricPayment.Commit;
// except
// ElectricPayment.Rollback;
// CommonDlg.ShowError('Cannot store to database.');
// end;
//
// fraFooter4Button1.btnAdd.Tag := 0;
// fraFooter4Button1.btnAdd.Caption:= '&Add';
// fraFooter4Button1.btnClose.Tag := 0;
// fraFooter4Button1.btnClose.Caption:= 'Close';
// fraFooter4Button1.btnUpdate.Enabled:= True;
// SetInputComponents(True);
// ClearAllControls;
// btnShow.Enabled:= True;
// end;
end;
procedure TfrmElectricPayment.actPrintExecute(Sender: TObject);
var ParamList: TStringList;
separatorTanggal: Char;
dataElectricPayment: TDataSet;
begin
inherited;
// if strgGrid.Cells[0,1] <> '' then
// begin
// if not Assigned(mySpell) then
// mySpell := TSpell.Create;
//
// separatorTanggal:= DateSeparator;
// DateSeparator:= '/';
//
// if not Assigned(ElectricPayment) then
// ElectricPayment:= TElectricPayment.Create;
//
// SetLength(arrParam,1);
// arrParam[0].tipe := ptInteger;
// arrParam[0].data := PaymentId;
// dataElectricPayment:= ElectricPayment.GetListPaymentByPaymentId(arrParam);
//
// ParamList := TStringList.Create;
// if not dataElectricPayment.IsEmpty then
// begin
// ParamList.Add(StrPadLeft(IntToStr(dataElectricPayment.FieldByName('kdjur_comp_id').AsInteger),2,'0')); //1
// ParamList.Add(UpperCase(mySpell.Spell(dataElectricPayment.FieldByName('elpay_amount_payment').AsString))); //2
// end
// else
// begin
// ParamList.Add(''); //1
// ParamList.Add(''); //2
// end;
// ParamList.Add(FLoginUsername); //3
// ParamList.Add(MasterNewUnit.Nama); //4
//
// if not Assigned(frmDialogPrintPreview) then
// frmDialogPrintPreview:= TfrmDialogPrintPreview.Create(Application);
//
// with frmDialogPrintPreview do
// begin
// ListParams:= ParamList;
// RecordSet := dataElectricPayment;
// FilePath := FFilePathReport + 'frElectricPayment.fr3';
// SetFormPropertyAndShowDialog(frmDialogPrintPreview);
// end;
//
// FreeAndNil(ParamList);
// FreeAndNil(mySpell);
// frmDialogPrintPreview.Free;
//
//
// DateSeparator:= separatorTanggal;
// end;
end;
end.
|
unit M_checks;
interface
uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons,
StdCtrls, SysUtils, _Strings, M_Global;
type
TChecksWindow = class(TForm)
BNGoto: TBitBtn;
CloseBtn: TBitBtn;
LBChecks: TListBox;
BNRecheck: TBitBtn;
CBOnTop: TCheckBox;
CBPin: TCheckBox;
Memo: TMemo;
procedure LBChecksClick(Sender: TObject);
procedure BNGotoClick(Sender: TObject);
procedure CloseBtnClick(Sender: TObject);
procedure BNRecheckClick(Sender: TObject);
procedure CBOnTopClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDblClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
ChecksWindow: TChecksWindow;
implementation
uses Mapper, M_MapUt, M_Util, M_Editor, Infedit2;
{$R *.DFM}
procedure TChecksWindow.LBChecksClick(Sender: TObject);
var TheLine : String;
begin
TheLine := LBChecks.Items[LBChecks.ItemIndex];
if (TheLine[1] = 'S') or
(TheLine[1] = 's') or
(TheLine[1] = 'W') or
(TheLine[1] = 'w') or
(TheLine[1] = 'O') then
BNGoto.Enabled := TRUE
else
BNGoto.Enabled := FALSE;
end;
procedure TChecksWindow.BNGotoClick(Sender: TObject);
var TheLine : String;
TheSector : TSector;
pars : TStringParser;
begin
TheLine := LBChecks.Items[LBChecks.ItemIndex];
pars := TStringParser.Create(TheLine);
CASE TheLine[1] OF
'S','s' : begin
if StrToInt(pars[2]) < MAP_SEC.Count then
begin
SC_HILITE := StrToInt(pars[2]);
WL_HILITE := 0;
VX_HILITE := 0;
if MAP_MODE = MM_SC then
DO_Fill_SectorEditor
else
DO_Switch_To_SC_Mode;
DO_Center_On_CurrentObject;
if TheLine[1] = 's' then
begin
INFSector := SC_HILITE;
INFWall := -1;
INFRemote := TRUE;
INFWindow2.Show;
INFWindow2.FormActivate(NIL);
end;
end
else
begin
Application.MessageBox('This sector doesn''t exist anymore !',
'Consistency Checks',
mb_Ok or mb_IconExclamation);
end;
end;
'W','w' : begin
if StrToInt(pars[4]) < MAP_SEC.Count then
begin
TheSector := TSector(MAP_SEC.Objects[StrToInt(pars[4])]);
if StrToInt(pars[2]) < TheSector.Wl.Count then
begin
SC_HILITE := StrToInt(pars[4]);
WL_HILITE := StrToInt(pars[2]);
VX_HILITE := 0;
if MAP_MODE = MM_WL then
DO_Fill_WallEditor
else
DO_Switch_To_WL_Mode;
DO_Center_On_CurrentObject;
if TheLine[1] = 'w' then
begin
INFSector := SC_HILITE;
INFWall := WL_HILITE;
INFRemote := TRUE;
INFWindow2.Show;
INFWindow2.FormActivate(NIL);
end;
end
else
begin
Application.MessageBox('This wall doesn''t exist anymore !',
'Consistency Checks',
mb_Ok or mb_IconExclamation);
end;
end
else
begin
Application.MessageBox('This sector doesn''t exist anymore !',
'Consistency Checks',
mb_Ok or mb_IconExclamation);
end;
end;
'O' : begin
if StrToInt(pars[2]) < MAP_OBJ.Count then
begin
OB_HILITE := StrToInt(pars[2]);
if MAP_MODE = MM_OB then
DO_Fill_ObjectEditor
else
DO_Switch_To_OB_Mode;
DO_Center_On_CurrentObject;
end
else
begin
Application.MessageBox('This object doesn''t exist anymore !',
'Consistency Checks',
mb_Ok or mb_IconExclamation);
end;
end;
END;
pars.Free;
BNGoto.Enabled := FALSE;
LBChecks.ItemIndex := -1;
if not CBPin.Checked then Close;
end;
procedure TChecksWindow.BNRecheckClick(Sender: TObject);
begin
DO_ConsistencyChecks;
end;
procedure TChecksWindow.CBOnTopClick(Sender: TObject);
begin
if CBOnTop.Checked then
FormStyle := fsStayOnTop
else
FormStyle := fsNormal;
end;
procedure TChecksWindow.CloseBtnClick(Sender: TObject);
begin
Close;
end;
procedure TChecksWindow.FormCreate(Sender: TObject);
begin
ChecksWindow.Left := Ini.ReadInteger('WINDOWS', 'Checks X', 0);
ChecksWindow.Top := Ini.ReadInteger('WINDOWS', 'Checks Y', 72);
ChecksWindow.CBPin.Checked := Ini.ReadBool('WINDOWS', 'Checks P', TRUE);
ChecksWindow.CBOnTop.Checked := Ini.ReadBool('WINDOWS', 'Checks T', FALSE);
end;
procedure TChecksWindow.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Ini.WriteInteger('WINDOWS', 'Checks X', ChecksWindow.Left);
Ini.WriteInteger('WINDOWS', 'Checks Y', ChecksWindow.Top);
Ini.WriteBool ('WINDOWS', 'Checks P', ChecksWindow.CBPin.Checked);
Ini.WriteBool ('WINDOWS', 'Checks T', ChecksWindow.CBOnTop.Checked);
end;
procedure TChecksWindow.FormDblClick(Sender: TObject);
begin
Memo.Clear;
Memo.Lines.AddStrings(LBChecks.Items);
Memo.SelectAll;
Memo.CopyToClipboard;
end;
end.
|
unit MainForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, CelikApi, Vcl.ExtCtrls;
type
TForm1 = class(TForm)
btnCitajLKEid: TButton;
btnCitajLKNorm: TButton;
Image1: TImage;
btnSacuvajFotografijuUFajl: TButton;
btnSacuvajPodatkeUFajl: TButton;
btnUcitajPodatkeIzFajla: TButton;
mmoPodaci: TMemo;
SaveDialog1: TSaveDialog;
OpenDialog1: TOpenDialog;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnCitajLKEidClick(Sender: TObject);
procedure btnCitajLKNormClick(Sender: TObject);
procedure btnSacuvajFotografijuUFajlClick(Sender: TObject);
procedure btnSacuvajPodatkeUFajlClick(Sender: TObject);
procedure btnUcitajPodatkeIzFajlaClick(Sender: TObject);
private
{ Private declarations }
VerzijaLK: Integer;
EidDocumentData: TEidDocumentData;
EidFixedPersonalData: TEidFixedPersonalData;
EidVariablePersonalData: TEidVariablePersonalData;
EidPortrait: TEidPortrait;
NormDocumentData: TNormDocumentData;
NormFixedPersonalData: TNormFixedPersonalData;
NormVariablePersonalData: TNormVariablePersonalData;
NormPortrait: TMemoryStream;
procedure IzbrisiPodatke();
procedure PrikaziPodatke();
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
Jpeg;
procedure TForm1.FormCreate(Sender: TObject);
begin
CelikApi.LoadDll();
EidStartup(2);
NormPortrait := TMemoryStream.Create;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
NormPortrait.Free;
EidCleanup;
CelikApi.UnloadDll();
end;
procedure TForm1.btnCitajLKEidClick(Sender: TObject);
begin
IzbrisiPodatke();
ZeroMemory(@EidDocumentData, SizeOf(TEidDocumentData));
ZeroMemory(@EidFixedPersonalData, SizeOf(TEidFixedPersonalData));
ZeroMemory(@EidVariablePersonalData, SizeOf(TEidVariablePersonalData));
ZeroMemory(@EidPortrait, SizeOf(TEidPortrait));
EidBeginRead('', @VerzijaLK);
EidReadDocumentData(@EidDocumentData);
EidReadFixedPersonalData(@EidFixedPersonalData);
EidReadVariablePersonalData(@EidVariablePersonalData);
EidReadPortrait(@EidPortrait);
EidEndRead();
EidToNormDocumentData(EidDocumentData, NormDocumentData);
EidToNormFixedPersonalData(EidFixedPersonalData, NormFixedPersonalData);
EidToNormVariablePersonalData(EidVariablePersonalData, NormVariablePersonalData);
EidToNormPortrait(EidPortrait, NormPortrait);
PrikaziPodatke();
end;
procedure TForm1.btnCitajLKNormClick(Sender: TObject);
begin
IzbrisiPodatke();
EidBeginRead('', @VerzijaLK);
NormReadDocumentData(NormDocumentData);
NormReadFixedPersonalData(NormFixedPersonalData);
NormReadVariablePersonalData(NormVariablePersonalData);
NormReadPortrait(NormPortrait);
EidEndRead;
PrikaziPodatke();
end;
procedure TForm1.btnSacuvajFotografijuUFajlClick(Sender: TObject);
begin
SaveDialog1.FileName := NormFixedPersonalData.Surname + '-' + NormFixedPersonalData.GivenName + '.jpg';
if (SaveDialog1.Execute) then
begin
NormPortrait.SaveToFile(SaveDialog1.FileName);
end;
end;
procedure TForm1.btnSacuvajPodatkeUFajlClick(Sender: TObject);
var
StrukturaLK: TFileStream;
begin
SaveDialog1.FileName := NormFixedPersonalData.Surname + '-' + NormFixedPersonalData.GivenName + '.dat';
if (SaveDialog1.Execute) then
begin
StrukturaLK := TFileStream.Create(SaveDialog1.FileName, fmCreate);
StrukturaLK.Write(EidDocumentData, sizeof(TEidDocumentData));
StrukturaLK.Write(EidFixedPersonalData, sizeof(TEidFixedPersonalData));
StrukturaLK.Write(EidVariablePersonalData, sizeof(TEidVariablePersonalData));
StrukturaLK.Write(EidPortrait, sizeof(TEidPortrait));
StrukturaLK.Free;
end;
end;
procedure TForm1.btnUcitajPodatkeIzFajlaClick(Sender: TObject);
var
StrukturaLK: TFileStream;
begin
IzbrisiPodatke();
OpenDialog1.FileName := NormFixedPersonalData.Surname + '-' + NormFixedPersonalData.GivenName + '.dat';
if (OpenDialog1.Execute) then
begin
StrukturaLK := TFileStream.Create(OpenDialog1.FileName, fmOpenRead);
StrukturaLK.Read(EidDocumentData, SizeOf(TEidDocumentData));
StrukturaLK.Read(EidFixedPersonalData, SizeOf(TEidFixedPersonalData));
StrukturaLK.Read(EidVariablePersonalData, SizeOf(TEidVariablePersonalData));
StrukturaLK.Read(EidPortrait, SizeOf(TEidPortrait));
StrukturaLK.Free;
EidToNormDocumentData(EidDocumentData, NormDocumentData);
EidToNormFixedPersonalData(EidFixedPersonalData, NormFixedPersonalData);
EidToNormVariablePersonalData(EidVariablePersonalData, NormVariablePersonalData);
EidToNormPortrait(EidPortrait, NormPortrait);
PrikaziPodatke();
end;
end;
procedure TForm1.IzbrisiPodatke();
begin
mmoPodaci.Clear;
Image1.Picture.Assign(nil);
end;
procedure TForm1.PrikaziPodatke();
var
PortraitJPG: TJPEGImage;
begin
IzbrisiPodatke();
mmoPodaci.Lines.Add('Verzija lične karte: ' + IntToStr(VerzijaLK));
mmoPodaci.Lines.Add('----- Podaci o dokumentu ----------------');
mmoPodaci.Lines.Add('Reg.no: ' + NormDocumentData.DocRegNo);
mmoPodaci.Lines.Add('Tip dokumenta: ' + NormDocumentData.DocumentType);
mmoPodaci.Lines.Add('Datum izdavanja: ' + NormDocumentData.IssuingDate);
mmoPodaci.Lines.Add('Datum isteka: ' + NormDocumentData.ExpiryDate);
mmoPodaci.Lines.Add('Izdaje: ' + NormDocumentData.IssuingAuthority);
mmoPodaci.Lines.Add('----- Podaci o osobi, nepromenljivi -----');
mmoPodaci.Lines.Add('Matični broj: ' + NormFixedPersonalData.PersonalNumber);
mmoPodaci.Lines.Add('Prezime: ' + NormFixedPersonalData.Surname);
mmoPodaci.Lines.Add('Ime: ' + NormFixedPersonalData.GivenName);
mmoPodaci.Lines.Add('Ime roditelja: ' + NormFixedPersonalData.ParentGivenName);
mmoPodaci.Lines.Add('Pol: ' + NormFixedPersonalData.Sex);
mmoPodaci.Lines.Add('Mesto rođenja: ' + NormFixedPersonalData.PlaceOfBirth);
mmoPodaci.Lines.Add('Država: ' + NormFixedPersonalData.StateOfBirth);
mmoPodaci.Lines.Add('Datum rođenja: ' + NormFixedPersonalData.DateOfBirth);
mmoPodaci.Lines.Add('Opština: ' + NormFixedPersonalData.CommunityOfBirth);
mmoPodaci.Lines.Add('----- Podaci o osobi, promenljivi -------');
mmoPodaci.Lines.Add('Prebivalište - oznaka države: ' + EidVariablePersonalData.state);
mmoPodaci.Lines.Add('Prebivalište - opština: ' + EidVariablePersonalData.community);
mmoPodaci.Lines.Add('Prebivalište - mesto: ' + EidVariablePersonalData.place);
mmoPodaci.Lines.Add('Prebivalište - ulica: ' + EidVariablePersonalData.street);
mmoPodaci.Lines.Add('Prebivalište - kućni broj: ' + EidVariablePersonalData.houseNumber);
mmoPodaci.Lines.Add('Prebivalište - slovo uz broj: ' + EidVariablePersonalData.houseLetter);
mmoPodaci.Lines.Add('Prebivalište - ulaz: ' + EidVariablePersonalData.entrance);
mmoPodaci.Lines.Add('Prebivalište - sprat: ' + EidVariablePersonalData.floor);
mmoPodaci.Lines.Add('Prebivalište - broj stana: ' + EidVariablePersonalData.apartmentNumber);
mmoPodaci.Lines.Add('Prebivalište - promena datuma: ' + EidVariablePersonalData.AddressDate);
mmoPodaci.Lines.Add('Prebivalište - adresna oznaka: ' + EidVariablePersonalData.AddressLabel);
if NormPortrait.Size > 0 then
begin
PortraitJPG := TJPEGImage.Create;
try
NormPortrait.Position := 0;
PortraitJPG.LoadFromStream(NormPortrait);
Image1.Picture.Assign(PortraitJPG);
finally
PortraitJPG.Free;
end;
end;
end;
end.
|
unit ServerDatabases;
interface
uses
Classes, LrProfiles, htDatabaseProfile;
type
TServerDatabaseProfile = class(TLrProfile)
private
FDatabases: ThtDatabaseProfileMgr;
//FServer: TLrProfileIdent;
protected
procedure SetDatabases(const Value: ThtDatabaseProfileMgr);
//procedure SetServer(const Value: TLrProfileIdent);
public
constructor Create(inCollection: TCollection); override;
destructor Destroy; override;
published
//property Server: TLrProfileIdent read FServer write SetServer;
property Databases: ThtDatabaseProfileMgr read FDatabases
write SetDatabases;
end;
//
TServerDatabaseProfileMgr = class(TLrProfileMgr)
protected
function GetDatabases(inIndex: Integer): TServerDatabaseProfile;
procedure SetDatabases(inIndex: Integer;
const Value: TServerDatabaseProfile);
public
constructor Create(const inFilename: string = ''); reintroduce;
function AddDatabase: TServerDatabaseProfile;
property Count: Integer read GetCount;
property Databases[inIndex: Integer]: TServerDatabaseProfile read
GetDatabases write SetDatabases; default;
end;
implementation
uses
Globals;
{ TServerDatabaseProfile }
constructor TServerDatabaseProfile.Create(inCollection: TCollection);
begin
inherited;
FDatabases := ThtDatabaseProfileMgr.Create;
FDatabases.SetSubComponent(true);
end;
destructor TServerDatabaseProfile.Destroy;
begin
FDatabases.Free;
inherited;
end;
procedure TServerDatabaseProfile.SetDatabases(
const Value: ThtDatabaseProfileMgr);
begin
FDatabases := Value;
end;
{
procedure TServerDatabaseProfile.SetServer(const Value: TLrProfileIdent);
begin
FServer := Value;
end;
}
{ TServerDatabaseProfileMgr }
constructor TServerDatabaseProfileMgr.Create(const inFilename: string);
begin
inherited Create(TServerDatabaseProfile, inFilename);
end;
function TServerDatabaseProfileMgr.GetDatabases(
inIndex: Integer): TServerDatabaseProfile;
begin
Result := TServerDatabaseProfile(Profiles[inIndex]);
end;
procedure TServerDatabaseProfileMgr.SetDatabases(inIndex: Integer;
const Value: TServerDatabaseProfile);
begin
Profiles[inIndex] := Value;
end;
function TServerDatabaseProfileMgr.AddDatabase: TServerDatabaseProfile;
begin
Result := TServerDatabaseProfile(Profiles.Add);
end;
end.
|
(*
Desciption: Calculate sqrt of a (Formular: x0 = a; x(n + 1) = (x(n) + a / x(n)) / 2 )
Programmer: Loc Pham
Date: 23/01/2016
Version: v1.0
*)
(* Program name *)
program HomeWork9;
(* Unit's inclusion *)
uses crt;
(* Const's declaration *)
const EPSILON = 0.0000000000000025;
(* Variable's declration *)
var number : real;
(* Function's declaration *)
function MySqrt(number: real) : real;
(* Local variables *)
var result, prevCalc, curCalc : real;
(* Funtion body *)
begin
if (number = 0) then
begin
result := 0;
end
else
begin
(* Initialize *)
prevCalc := number;
curCalc := (prevCalc + number / prevCalc) / 2;
while (abs(curCalc - prevCalc) >= EPSILON) do
begin
prevCalc := curCalc;
curCalc := (prevCalc + number / prevCalc) / 2;
end;
result := curCalc;
end;
MySqrt := result;
end;
(* Main program *)
begin
write('Enter number: ');
readln(number);
writeln('Sqrt is:', MySqrt(number));
end. |
{******************************************************************************}
{ }
{ Delphi OpenAPI 3.0 Generator }
{ Copyright (c) 2018-2021 Paolo Rossi }
{ https://github.com/paolo-rossi/delphi-openapi }
{ }
{******************************************************************************}
{ }
{ 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 OpenAPI.Neon.Serializers;
interface
uses
System.SysUtils, System.Generics.Defaults, System.Rtti, System.TypInfo, System.JSON,
Neon.Core.Attributes,
Neon.Core.Persistence,
Neon.Core.Types,
Neon.Core.Nullables,
Neon.Core.Serializers.RTL,
OpenAPI.Model.Any,
OpenAPI.Model.Base,
OpenAPI.Model.Classes,
OpenAPI.Model.Schema;
type
TOpenAPISerializer = class
class function GetNeonConfig: INeonConfiguration; static;
end;
TNullableStringSerializer = class(TCustomSerializer)
protected
class function GetTargetInfo: PTypeInfo; override;
class function CanHandle(AType: PTypeInfo): Boolean; override;
public
function Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; override;
function Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; override;
end;
TNullableBooleanSerializer = class(TCustomSerializer)
protected
class function GetTargetInfo: PTypeInfo; override;
class function CanHandle(AType: PTypeInfo): Boolean; override;
public
function Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; override;
function Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; override;
end;
TNullableIntegerSerializer = class(TCustomSerializer)
protected
class function GetTargetInfo: PTypeInfo; override;
class function CanHandle(AType: PTypeInfo): Boolean; override;
public
function Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; override;
function Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; override;
end;
TNullableInt64Serializer = class(TCustomSerializer)
protected
class function GetTargetInfo: PTypeInfo; override;
class function CanHandle(AType: PTypeInfo): Boolean; override;
public
function Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; override;
function Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; override;
end;
TNullableDoubleSerializer = class(TCustomSerializer)
protected
class function GetTargetInfo: PTypeInfo; override;
class function CanHandle(AType: PTypeInfo): Boolean; override;
public
function Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; override;
function Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; override;
end;
TNullableTDateTimeSerializer = class(TCustomSerializer)
protected
class function GetTargetInfo: PTypeInfo; override;
class function CanHandle(AType: PTypeInfo): Boolean; override;
public
function Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; override;
function Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; override;
end;
TOpenAPIAnySerializer = class(TCustomSerializer)
protected
class function GetTargetInfo: PTypeInfo; override;
class function CanHandle(AType: PTypeInfo): Boolean; override;
public
function Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; override;
function Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; override;
end;
TOpenAPIReferenceSerializer = class(TCustomSerializer)
protected
class function GetTargetInfo: PTypeInfo; override;
class function CanHandle(AType: PTypeInfo): Boolean; override;
public
function Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; override;
function Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; override;
end;
TOpenAPISchemaSerializer = class(TCustomSerializer)
protected
class function GetTargetInfo: PTypeInfo; override;
class function CanHandle(AType: PTypeInfo): Boolean; override;
public
function Serialize(const AValue: TValue; ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue; override;
function Deserialize(AValue: TJSONValue; const AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue; override;
end;
procedure RegisterOpenAPISerializers(ARegistry: TNeonSerializerRegistry);
implementation
uses
Neon.Core.Utils;
{ TNullableStringSerializer }
class function TNullableStringSerializer.CanHandle(AType: PTypeInfo): Boolean;
begin
if AType = GetTargetInfo then
Result := True
else
Result := False;
end;
function TNullableStringSerializer.Deserialize(AValue: TJSONValue; const AData:
TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue;
var
LNullValue: NullString;
begin
LNullValue := AValue.Value;
Result := TValue.From<NullString>(LNullValue);
end;
class function TNullableStringSerializer.GetTargetInfo: PTypeInfo;
begin
Result := TypeInfo(NullString);
end;
function TNullableStringSerializer.Serialize(const AValue: TValue; ANeonObject:
TNeonRttiObject; AContext: ISerializerContext): TJSONValue;
var
LValue: NullString;
begin
Result := nil;
LValue := AValue.AsType<NullString>;
if LValue.HasValue then
Result := TJSONString.Create(LValue.Value);
end;
{ TNullableBooleanSerializer }
class function TNullableBooleanSerializer.CanHandle(AType: PTypeInfo): Boolean;
begin
if AType = GetTargetInfo then
Result := True
else
Result := False;
end;
function TNullableBooleanSerializer.Deserialize(AValue: TJSONValue; const
AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue;
var
LNullValue: NullBoolean;
begin
LNullValue := (AValue as TJSONBool).AsBoolean;
Result := TValue.From<NullBoolean>(LNullValue);
end;
class function TNullableBooleanSerializer.GetTargetInfo: PTypeInfo;
begin
Result := TypeInfo(NullBoolean);
end;
function TNullableBooleanSerializer.Serialize(const AValue: TValue;
ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue;
var
LValue: NullBoolean;
begin
Result := nil;
LValue := AValue.AsType<NullBoolean>;
if LValue.HasValue then
Result := TJSONBool.Create(LValue.Value);
end;
{ TNullableIntegerSerializer }
class function TNullableIntegerSerializer.CanHandle(AType: PTypeInfo): Boolean;
begin
if AType = GetTargetInfo then
Result := True
else
Result := False;
end;
function TNullableIntegerSerializer.Deserialize(AValue: TJSONValue; const
AData: TValue; ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue;
var
LNullValue: NullInteger;
begin
LNullValue := (AValue as TJSONNumber).AsInt;
Result := TValue.From<NullInteger>(LNullValue);
end;
class function TNullableIntegerSerializer.GetTargetInfo: PTypeInfo;
begin
Result := TypeInfo(NullInteger);
end;
function TNullableIntegerSerializer.Serialize(const AValue: TValue;
ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue;
var
LValue: NullInteger;
begin
Result := nil;
LValue := AValue.AsType<NullInteger>;
if LValue.HasValue then
Result := TJSONNumber.Create(LValue.Value);
end;
{ TNullableInt64Serializer }
class function TNullableInt64Serializer.CanHandle(AType: PTypeInfo): Boolean;
begin
if AType = GetTargetInfo then
Result := True
else
Result := False;
end;
function TNullableInt64Serializer.Deserialize(AValue: TJSONValue; const AData: TValue;
ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue;
var
LNullValue: NullInt64;
begin
LNullValue := (AValue as TJSONNumber).AsInt64;
Result := TValue.From<NullInt64>(LNullValue);
end;
class function TNullableInt64Serializer.GetTargetInfo: PTypeInfo;
begin
Result := TypeInfo(NullInt64);
end;
function TNullableInt64Serializer.Serialize(const AValue: TValue; ANeonObject:
TNeonRttiObject; AContext: ISerializerContext): TJSONValue;
var
LValue: NullInt64;
begin
Result := nil;
LValue := AValue.AsType<NullInt64>;
if LValue.HasValue then
Result := TJSONNumber.Create(LValue.Value);
end;
{ TNullableDoubleSerializer }
class function TNullableDoubleSerializer.CanHandle(AType: PTypeInfo): Boolean;
begin
if AType = GetTargetInfo then
Result := True
else
Result := False;
end;
function TNullableDoubleSerializer.Deserialize(AValue: TJSONValue; const AData: TValue;
ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue;
var
LNullValue: NullDouble;
begin
LNullValue := (AValue as TJSONNumber).AsDouble;
Result := TValue.From<NullDouble>(LNullValue);
end;
class function TNullableDoubleSerializer.GetTargetInfo: PTypeInfo;
begin
Result := TypeInfo(NullDouble);
end;
function TNullableDoubleSerializer.Serialize(const AValue: TValue; ANeonObject:
TNeonRttiObject; AContext: ISerializerContext): TJSONValue;
var
LValue: NullDouble;
begin
Result := nil;
LValue := AValue.AsType<NullDouble>;
if LValue.HasValue then
Result := TJSONNumber.Create(LValue.Value);
end;
{ TNullableTDateTimeSerializer }
class function TNullableTDateTimeSerializer.CanHandle(AType: PTypeInfo): Boolean;
begin
if AType = GetTargetInfo then
Result := True
else
Result := False;
end;
function TNullableTDateTimeSerializer.Deserialize(AValue: TJSONValue; const AData: TValue;
ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue;
var
LNullValue: NullDateTime;
begin
LNullValue := TJSONUtils.JSONToDate(AValue.Value, AContext.GetConfiguration.GetUseUTCDate);
Result := TValue.From<NullDateTime>(LNullValue);
end;
class function TNullableTDateTimeSerializer.GetTargetInfo: PTypeInfo;
begin
Result := TypeInfo(NullDateTime);
end;
function TNullableTDateTimeSerializer.Serialize(const AValue: TValue;
ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue;
var
LValue: NullDateTime;
begin
Result := nil;
LValue := AValue.AsType<NullDateTime>;
if LValue.HasValue then
Result := TJSONString.Create(TJSONUtils.DateToJSON(LValue.Value, AContext.GetConfiguration.GetUseUTCDate));
end;
{ TOpenAPISerializer }
class function TOpenAPISerializer.GetNeonConfig: INeonConfiguration;
begin
Result := TNeonConfiguration.Create;
Result.SetMemberCase(TNeonCase.CamelCase)
.SetPrettyPrint(True)
.GetSerializers
//Neon Serializers
.RegisterSerializer(TJSONValueSerializer)
//Neon Serializers
.RegisterSerializer(TNullableStringSerializer)
.RegisterSerializer(TNullableBooleanSerializer)
.RegisterSerializer(TNullableIntegerSerializer)
.RegisterSerializer(TNullableInt64Serializer)
.RegisterSerializer(TNullableDoubleSerializer)
.RegisterSerializer(TNullableTDateTimeSerializer)
// OpenAPI Models
//.RegisterSerializer(TOpenAPIAnySerializer)
.RegisterSerializer(TOpenAPIReferenceSerializer)
.RegisterSerializer(TOpenAPISchemaSerializer)
;
end;
{ TOpenAPIAnySerializer }
class function TOpenAPIAnySerializer.CanHandle(AType: PTypeInfo): Boolean;
begin
if AType = GetTargetInfo then
Result := True
else
Result := False;
end;
function TOpenAPIAnySerializer.Deserialize(AValue: TJSONValue; const AData: TValue;
ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue;
begin
Result := nil;
end;
class function TOpenAPIAnySerializer.GetTargetInfo: PTypeInfo;
begin
Result := TypeInfo(TOpenAPIAny);
end;
function TOpenAPIAnySerializer.Serialize(const AValue: TValue;
ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue;
var
LValue: TOpenAPIAny;
begin
LValue := AValue.AsType<TOpenAPIAny>;
if LValue = nil then
Exit(nil);
if LValue.Value.IsEmpty then
Exit(nil);
Result := AContext.WriteDataMember(LValue.Value);
case ANeonObject.NeonInclude.Value of
IncludeIf.NotEmpty, IncludeIf.NotDefault:
begin
if (Result as TJSONObject).Count = 0 then
FreeAndNil(Result);
end;
end;
end;
{ TOpenAPIReferenceSerializer }
class function TOpenAPIReferenceSerializer.CanHandle(AType: PTypeInfo): Boolean;
begin
Result := TypeInfoIs(AType);
end;
function TOpenAPIReferenceSerializer.Deserialize(AValue: TJSONValue; const AData: TValue;
ANeonObject: TNeonRttiObject; AContext: IDeserializerContext): TValue;
begin
Result := nil;
end;
class function TOpenAPIReferenceSerializer.GetTargetInfo: PTypeInfo;
begin
Result := TOpenAPIModelReference.ClassInfo;
end;
function TOpenAPIReferenceSerializer.Serialize(const AValue: TValue;
ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue;
var
LRefObj: TOpenAPIModelReference;
LType: TRttiType;
begin
LRefObj := AValue.AsType<TOpenAPIModelReference>;
if LRefObj = nil then
Exit(nil);
if Assigned(LRefObj.Reference) and not (LRefObj.Reference.Ref.IsEmpty) then
Result := TJSONString.Create(LRefObj.Reference.Ref)
//AContext.WriteDataMember(LRefObj.Reference)
else
begin
LType := TRttiUtils.Context.GetType(AValue.TypeInfo);
Result := TJSONObject.Create;
AContext.WriteMembers(LType, AValue.AsObject, Result);
end;
case ANeonObject.NeonInclude.Value of
IncludeIf.NotEmpty, IncludeIf.NotDefault:
begin
if (Result as TJSONObject).Count = 0 then
FreeAndNil(Result);
end;
end;
end;
{ TOpenAPISchemaSerializer }
class function TOpenAPISchemaSerializer.CanHandle(AType: PTypeInfo): Boolean;
begin
Result := TypeInfoIs(AType);
end;
function TOpenAPISchemaSerializer.Deserialize(AValue: TJSONValue;
const AData: TValue; ANeonObject: TNeonRttiObject;
AContext: IDeserializerContext): TValue;
begin
end;
class function TOpenAPISchemaSerializer.GetTargetInfo: PTypeInfo;
begin
Result := TOpenAPISchema.ClassInfo;
end;
function TOpenAPISchemaSerializer.Serialize(const AValue: TValue;
ANeonObject: TNeonRttiObject; AContext: ISerializerContext): TJSONValue;
var
LSchema: TOpenAPISchema;
LType: TRttiType;
begin
LSchema := AValue.AsType<TOpenAPISchema>;
if LSchema = nil then
Exit(nil);
// It's also a reference object
if Assigned(LSchema.Reference) and not (LSchema.Reference.Ref.IsEmpty) then
begin
Result := AContext.WriteDataMember(LSchema.Reference);
Exit;
end;
if Assigned(LSchema.JSONObject) then
Result := LSchema.JSONObject.Clone as TJSONObject
else
begin
LType := TRttiUtils.Context.GetType(AValue.TypeInfo);
Result := TJSONObject.Create;
AContext.WriteMembers(LType, AValue.AsObject, Result);
end;
case ANeonObject.NeonInclude.Value of
IncludeIf.NotEmpty, IncludeIf.NotDefault:
begin
if (Result as TJSONObject).Count = 0 then
FreeAndNil(Result);
end;
end;
end;
procedure RegisterOpenAPISerializers(ARegistry: TNeonSerializerRegistry);
begin
//Neon Serializers
ARegistry.RegisterSerializer(TJSONValueSerializer);
ARegistry.RegisterSerializer(TNullableStringSerializer);
ARegistry.RegisterSerializer(TNullableBooleanSerializer);
ARegistry.RegisterSerializer(TNullableIntegerSerializer);
ARegistry.RegisterSerializer(TNullableInt64Serializer);
ARegistry.RegisterSerializer(TNullableDoubleSerializer);
ARegistry.RegisterSerializer(TNullableTDateTimeSerializer);
ARegistry.RegisterSerializer(TOpenAPIReferenceSerializer);
ARegistry.RegisterSerializer(TOpenAPISchemaSerializer);
end;
end.
|
unit gr_CountSheet_Filter;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxCheckBox, StdCtrls, cxButtons,
cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, cxControls,
cxGroupBox, cxSpinEdit, cxDropDownEdit, uCommonSp,
gr_uCommonProc, gr_uCommonLoader, gr_uCommonConsts, gr_uCommonTypes,
GlobalSpr,
IBase, Dates, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet, gr_uMessage,
cxLabel;
type UVVedFilter = record
Id_smeta:integer;
Kod_Smeta:integer;
Name_Smeta:String;
Id_department:integer;
Kod_department:string[10];
Name_Department:String;
Id_man:integer;
tn:integer;
FIO:string;
Kod_Setup:integer;
Kod:integer;
ModalResult:TModalResult;
end;
type
TUVVedViewFilter = class(TForm)
BoxSmeta: TcxGroupBox;
EditSmeta: TcxButtonEdit;
YesBtn: TcxButton;
CancelBtn: TcxButton;
BoxKodSetup: TcxGroupBox;
MonthesList: TcxComboBox;
YearSpinEdit: TcxSpinEdit;
CheckBoxKodSetup: TcxCheckBox;
CheckBoxKod: TcxCheckBox;
BoxKod: TcxGroupBox;
CheckBoxDepartment: TcxCheckBox;
BoxDepartment: TcxGroupBox;
EditDepartment: TcxButtonEdit;
CheckBoxSmeta: TcxCheckBox;
EditKod: TcxMaskEdit;
EdDepartmentEdit: TcxTextEdit;
EdNameSmeta: TcxTextEdit;
CheckBoxIdMan: TcxCheckBox;
BoxIdMan: TcxGroupBox;
EditMan: TcxButtonEdit;
EditName: TcxTextEdit;
procedure CheckBoxKodSetupClick(Sender: TObject);
procedure CheckBoxKodClick(Sender: TObject);
procedure CheckBoxDepartmentClick(Sender: TObject);
procedure CheckBoxSmetaClick(Sender: TObject);
procedure cxButtonEdit1PropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure EditSmetaPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure CancelBtnClick(Sender: TObject);
procedure YesBtnClick(Sender: TObject);
procedure CheckBoxIdManClick(Sender: TObject);
procedure EditManPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure EditManExit(Sender: TObject);
procedure EditDepartmentExit(Sender: TObject);
procedure EditSmetaExit(Sender: TObject);
private
PParameter:UVVedFilter;
pDbHandle:TISC_DB_HANDLE;
pLanguageIndex:byte;
pTypeView:TgrUVParam;
public
constructor Create(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:UVVedFilter;ATypeView:TgrUVParam);reintroduce;
property Parameter:UVVedFilter read PParameter;
end;
function ViewFilter(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:UVVedFilter;ATypeView:TgrUVParam):UVVedFilter;
implementation
{$R *.dfm}
function ViewFilter(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:UVVedFilter;ATypeView:TgrUVParam):UVVedFilter;
var Filter:TUVVedViewFilter;
begin
Result:=AParameter;
Filter := TUVVedViewFilter.Create(AOwner,ADB_Handle,AParameter,ATypeView);
if Filter.ShowModal=mrYes then
Result:=Filter.Parameter;
Result.ModalResult:=Filter.ModalResult;
Filter.Free;
end;
constructor TUVVedViewFilter.Create(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE;AParameter:UVVedFilter;ATypeView:TgrUVParam);
var curr_ks:integer;
begin
inherited Create(AOwner);
PParameter:=AParameter;
pLanguageIndex := IndexLanguage;
pDbHandle := ADB_Handle;
pTypeView := ATypeView;
//******************************************************************************
Caption := FilterBtn_Caption[pLanguageIndex];
CheckBoxDepartment.Properties.Caption := LabelDepartment_Caption[pLanguageIndex];
CheckBoxSmeta.Properties.Caption := LabelSmeta_Caption[pLanguageIndex];
CheckBoxKodSetup.Properties.Caption := LabelPeriod_Caption[pLanguageIndex];
CheckBoxIdMan.Properties.Caption := LabelStudent_Caption[pLanguageIndex];
CheckBoxKod.Properties.Caption := LabelKod_Caption[pLanguageIndex];
YesBtn.Caption := YesBtn_Caption[pLanguageIndex];
CancelBtn.Caption := CancelBtn_Caption[pLanguageIndex];
MonthesList.Properties.Items.Text := MonthesList_Text[pLanguageIndex];
//******************************************************************************
if PParameter.Kod_Setup=0 then
begin
curr_ks := grKodSetup(pDbHandle);
YearSpinEdit.Value:=YearMonthFromKodSetup(curr_ks);
MonthesList.ItemIndex:= YearMonthFromKodSetup(curr_ks,false)-1;
end
else
begin
YearSpinEdit.Value:=YearMonthFromKodSetup(PParameter.Kod_Setup);
MonthesList.ItemIndex:= YearMonthFromKodSetup(PParameter.Kod_Setup,false)-1;
CheckBoxKodSetup.Checked := True;
BoxKodSetup.Enabled := True;
end;
if pTypeView<>uvpFilter then
begin
CheckBoxKodSetup.Checked:=True;
CheckBoxKodSetup.Enabled:=false;
BoxKodSetup.Enabled := False;
end;
if PParameter.Kod<>0 then
begin
CheckBoxKod.Checked := True;
BoxKod.Enabled := True;
EditKod.Text := IntToStr(PParameter.Kod);
end;
if PParameter.Id_department<>0 then
begin
CheckBoxDepartment.Checked := True;
BoxDepartment.Enabled := True;
EditDepartment.Text := PParameter.Kod_department;
EdDepartmentEdit.Text := PParameter.Name_Department;
end;
if PParameter.Id_smeta<>0 then
begin
CheckBoxSmeta.Checked := True;
BoxSmeta.Enabled := True;
EditSmeta.Text := IntToStr(PParameter.Kod_Smeta);
EdNameSmeta.Text := PParameter.Name_Smeta;
end;
if PParameter.Id_man<>0 then
begin
CheckBoxIdMan.Checked := True;
BoxIdMan.Enabled := True;
EditMan.Text := IntToStr(PParameter.tn);
EditName.Text := PParameter.FIO;
end;
//******************************************************************************
end;
procedure TUVVedViewFilter.CheckBoxKodSetupClick(Sender: TObject);
begin
BoxKodSetup.Enabled := not BoxKodSetup.Enabled;
end;
procedure TUVVedViewFilter.CheckBoxKodClick(Sender: TObject);
begin
BoxKod.Enabled := not BoxKod.Enabled;
end;
procedure TUVVedViewFilter.CheckBoxDepartmentClick(Sender: TObject);
begin
BoxDepartment.Enabled := not BoxDepartment.Enabled;
if BoxDepartment.Enabled=False
then
begin
PParameter.Id_department:=0;
PParameter.Kod_department:='';
end
end;
procedure TUVVedViewFilter.CheckBoxSmetaClick(Sender: TObject);
begin
BoxSmeta.Enabled := not BoxSmeta.Enabled;
if BoxSmeta.Enabled=False
then
begin
PParameter.Id_smeta:=0;
PParameter.Kod_Smeta:=0;
end
end;
procedure TUVVedViewFilter.cxButtonEdit1PropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var sp: TSprav;
begin
try
sp := GetSprav('SpDepartment');
if sp <> nil then
begin
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(pDbHandle);
FieldValues['ShowStyle'] := 0;
FieldValues['Select'] := 1;
FieldValues['Actual_Date'] := Date;
FieldValues['Id_Property']:=4;
Post;
end;
end;
sp.Show;
except
on E:Exception do
begin
grShowMessage(ECaption[PlanguageIndex],e.Message,mtError,[mbOK]);
end;
end;
if sp.Output = nil then
ShowMessage('BUG: Output is NIL!!!')
else
if not sp.Output.IsEmpty then
begin
PParameter.Id_department :=sp.Output['ID_DEPARTMENT'];
PParameter.Name_Department:=varToStrDef(sp.Output['NAME_FULL'],'');
PParameter.Kod_department :=varToStrDef(sp.Output['DEPARTMENT_CODE'],'');
EdDepartmentEdit.Text :=varToStrDef(sp.Output['NAME_FULL'],'');
EditDepartment.Text :=varToStrDef(sp.Output['DEPARTMENT_CODE'],'');
end;
sp.Free;
end;
procedure TUVVedViewFilter.EditSmetaPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var Smeta:Variant;
begin
Smeta:=GetSmets(self,pDbHandle,Date,psmSmet);
if VarArrayDimCount(Smeta)> 0 then
If Smeta[0]<>NULL then
begin
PParameter.Id_smeta := Smeta[0];
PParameter.Kod_Smeta := Smeta[3];
PParameter.Name_Smeta := Smeta[2];
EdNameSmeta.Text := PParameter.Name_Smeta;
EditSmeta.Text := IntToStr(PParameter.Kod_Smeta);
end;
end;
procedure TUVVedViewFilter.CancelBtnClick(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TUVVedViewFilter.YesBtnClick(Sender: TObject);
begin
If ((PParameter.Id_smeta=0) or (not CheckBoxSmeta.Checked)) and
((PParameter.Id_department=0) or (not CheckBoxDepartment.Checked)) and
((PParameter.Id_man=0) or (not CheckBoxIdMan.Checked)) and
(not CheckBoxKodSetup.Checked) and
((EditKod.Text='') or (not CheckBoxKod.Checked)) then
grShowMessage(ECaption[pLanguageIndex],EnotInputData_Text[pLanguageIndex],mtWarning,[mbOK])
else
begin
if (not CheckBoxDepartment.Checked) then
PParameter.Id_department:=0;
if not CheckBoxSmeta.Checked then
PParameter.Id_smeta:=0;
if not CheckBoxIdMan.Checked then
PParameter.Id_man:=0;
if CheckBoxKodSetup.Checked then
PParameter.Kod_Setup := PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1)
else
PParameter.Kod_Setup:=0;
if (CheckBoxKod.Checked) and (EditKod.Text<>'') then
PParameter.Kod := StrToInt(EditKod.Text)
else
PParameter.Kod:=0;
ModalResult:=mrYes;
end;
end;
procedure TUVVedViewFilter.CheckBoxIdManClick(Sender: TObject);
begin
BoxIdMan.Enabled := not BoxIdMan.Enabled;
if BoxIdMan.Enabled=False
then PParameter.tn:=0;
end;
procedure TUVVedViewFilter.EditManPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var man:Variant;
AParameter: TgrSimpleParam;
begin
AParameter:=TgrSimpleParam.Create;
AParameter.Owner:=Self;
AParameter.DB_Handle:=PDbHandle;
man:=DoFunctionFromPackage(AParameter,Stud_StudentCards);
if VarArrayDimCount(man)> 0 then
if man[0]<>NULL then
begin
PParameter.Id_man:=man[0];
PParameter.Tn:=grifThen(VarIsNull(Man[1]),0,Man[1]);
PParameter.FIO:=man[2];
EditName.Text := PParameter.FIO;
EditMan.Text := IntToStr(PParameter.Tn);
end;
end;
procedure TUVVedViewFilter.EditManExit(Sender: TObject);
var man:Variant;
begin
if EditMan.Text<>'' then
begin
if StrToInt(EditMan.Text)=PParameter.Tn then Exit;
man:=grManByTn(StrToInt(EditMan.Text),pDbHandle);
if VarArrayDimCount(man)>0 then
begin
PParameter.Id_man:=man[0];
PParameter.Tn:=man[1];
PParameter.FIO:=man[2];
EditName.Text := PParameter.FIO;
end
else
EditMan.SetFocus;
end;
end;
procedure TUVVedViewFilter.EditDepartmentExit(Sender: TObject);
var Department:Variant;
begin
if EditDepartment.Text<>'' then
begin
if EditDepartment.Text=PParameter.Kod_department then Exit;
Department:=grDepartmentByKod(EditDepartment.Text,PDbHandle);
if VarArrayDimCount(Department)>0 then
begin
PParameter.Id_department:=Department[0];
PParameter.Kod_department:=Department[1];
PParameter.Name_Department:=Department[2];
EdDepartmentEdit.Text := PParameter.Name_Department;
end
else
EditDepartment.SetFocus;
end;
end;
procedure TUVVedViewFilter.EditSmetaExit(Sender: TObject);
var Smeta:Variant;
begin
if EditSmeta.Text<>'' then
begin
if StrToInt(EditSmeta.Text)=PParameter.Kod_Smeta then Exit;
Smeta:=grSmetaByKod(StrToInt(EditSmeta.Text),PDbHandle);
if VarArrayDimCount(Smeta)>0 then
begin
PParameter.Id_smeta:=Smeta[0];
PParameter.Kod_Smeta:=Smeta[1];
PParameter.Name_Smeta:=Smeta[2];
EdNameSmeta.Text := PParameter.Name_Smeta;
end
else
EditSmeta.SetFocus;
end;
end;
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* 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.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFX509Certificate;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
{$IFDEF DELPHI16_UP}
WinApi.Windows, System.Classes, System.SysUtils,
{$ELSE}
Windows, Classes, SysUtils,
{$ENDIF}
uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes;
type
TCEFX509CertificateRef = class(TCefBaseRefCountedRef, ICefX509Certificate)
protected
function GetSubject: ICefX509CertPrincipal;
function GetIssuer: ICefX509CertPrincipal;
function GetSerialNumber: ICefBinaryValue;
function GetValidStart: TCefTime;
function GetValidExpiry: TCefTime;
function GetDerEncoded: ICefBinaryValue;
function GetPemEncoded: ICefBinaryValue;
function GetIssuerChainSize: NativeUInt;
procedure GetDEREncodedIssuerChain(chainCount: NativeUInt; var chain : TCefBinaryValueArray);
procedure GetPEMEncodedIssuerChain(chainCount: NativeUInt; var chain : TCefBinaryValueArray);
public
class function UnWrap(data: Pointer): ICefX509Certificate;
end;
implementation
uses
uCEFMiscFunctions, uCEFLibFunctions, uCEFBinaryValue, uCEFX509CertPrincipal;
function TCEFX509CertificateRef.GetSubject: ICefX509CertPrincipal;
begin
Result := TCefX509CertPrincipalRef.UnWrap(PCefX509Certificate(FData).get_subject(FData));
end;
function TCEFX509CertificateRef.GetIssuer: ICefX509CertPrincipal;
begin
Result := TCefX509CertPrincipalRef.UnWrap(PCefX509Certificate(FData).get_issuer(FData));
end;
function TCEFX509CertificateRef.GetSerialNumber: ICefBinaryValue;
begin
Result := TCefBinaryValueRef.UnWrap(PCefX509Certificate(FData).get_serial_number(FData));
end;
function TCEFX509CertificateRef.GetValidStart: TCefTime;
begin
Result := PCefX509Certificate(FData).get_valid_start(FData);
end;
function TCEFX509CertificateRef.GetValidExpiry: TCefTime;
begin
Result := PCefX509Certificate(FData).get_valid_expiry(FData);
end;
function TCEFX509CertificateRef.GetDerEncoded: ICefBinaryValue;
begin
Result := TCefBinaryValueRef.UnWrap(PCefX509Certificate(FData).get_derencoded(FData));
end;
function TCEFX509CertificateRef.GetPemEncoded: ICefBinaryValue;
begin
Result := TCefBinaryValueRef.UnWrap(PCefX509Certificate(FData).get_pemencoded(FData));
end;
function TCEFX509CertificateRef.GetIssuerChainSize: NativeUInt;
begin
Result := PCefX509Certificate(FData).get_issuer_chain_size(FData);
end;
procedure TCEFX509CertificateRef.GetDEREncodedIssuerChain(chainCount: NativeUInt; var chain : TCefBinaryValueArray);
var
TempArray : array of PCefBinaryValue;
i : NativeUInt;
begin
TempArray := nil;
try
try
if (chainCount > 0) then
begin
SetLength(TempArray, chainCount);
i := 0;
while (i < chainCount) do
begin
TempArray[i] := nil;
inc(i);
end;
PCefX509Certificate(FData).get_derencoded_issuer_chain(FData, chainCount, TempArray[0]);
if (chainCount > 0) then
begin
SetLength(chain, chainCount);
i := 0;
while (i < chainCount) do
begin
chain[i] := TCefBinaryValueRef.UnWrap(TempArray[i]);
inc(i);
end;
end;
end;
except
on e : exception do
if CustomExceptionHandler('TCEFX509CertificateRef.GetDEREncodedIssuerChain', e) then raise;
end;
finally
if (TempArray <> nil) then
begin
Finalize(TempArray);
TempArray := nil;
end;
end;
end;
procedure TCEFX509CertificateRef.GetPEMEncodedIssuerChain(chainCount: NativeUInt; var chain : TCefBinaryValueArray);
var
TempArray : array of PCefBinaryValue;
i : NativeUInt;
begin
TempArray := nil;
try
try
if (chainCount > 0) then
begin
SetLength(TempArray, chainCount);
i := 0;
while (i < chainCount) do
begin
TempArray[i] := nil;
inc(i);
end;
PCefX509Certificate(FData).get_pemencoded_issuer_chain(FData, chainCount, TempArray[0]);
if (chainCount > 0) then
begin
SetLength(chain, chainCount);
i := 0;
while (i < chainCount) do
begin
chain[i] := TCefBinaryValueRef.UnWrap(TempArray[i]);
inc(i);
end;
end;
end;
except
on e : exception do
if CustomExceptionHandler('TCEFX509CertificateRef.GetPEMEncodedIssuerChain', e) then raise;
end;
finally
if (TempArray <> nil) then
begin
Finalize(TempArray);
TempArray := nil;
end;
end;
end;
class function TCEFX509CertificateRef.UnWrap(data: Pointer): ICefX509Certificate;
begin
if (data <> nil) then
Result := Create(data) as ICefX509Certificate
else
Result := nil;
end;
end.
|
namespace UINavigationController;
interface
uses
UIKit;
type
[IBObject]
SecondViewController = public class(UIViewController)
private
public
method init: id; override;
method viewDidLoad; override;
[IBAction] method buttonPressed(sender: id);
method otherButtonPressed;
end;
implementation
method SecondViewController.init: id;
begin
self := inherited initWithNibName("SecondViewController") bundle(nil);
if assigned(self) then begin
self.title := "Second View Controller";
end;
result := self;
end;
method SecondViewController.buttonPressed(sender: id);
begin
self.navigationController.popToRootViewControllerAnimated(true);
end;
method SecondViewController.otherButtonPressed;
begin
var message := new UIAlertView withTitle("Search") message("If this were a real application you would now be in the DO STUFF mode") &delegate(nil) cancelButtonTitle("OK") otherButtonTitles(nil);
message.show();
end;
method SecondViewController.viewDidLoad;
begin
inherited viewDidLoad;
var rightButton := new UIBarButtonItem withTitle("Do Stuff") style(UIBarButtonItemStyle.UIBarButtonItemStylePlain) &target(self) action(selector(otherButtonPressed));
self.navigationItem.rightBarButtonItem := rightButton;
end;
end.
|
(*
Category: SWAG Title: DIRECTORY HANDLING ROUTINES
Original name: 0047.PAS
Description: File Searching
Author: JOHN STEPHENSON
Date: 09-04-95 11:01
*)
{
RA> Does anyone have a procedure for search for wildcards on Harddisks?
RA> It needs to check multiple hard disks and all directories. I tried
RA> some TP built in functions (Fsearch, and another one) but one doesn't
RA> support wildcards and neither scan all dirs unless I do alot of fancy
RA> stuff...
Here's some code, written by another of the frequent contributors
here, which should help:
}
program Tree_Search; { by John Stephenson 1994 }
Uses DOS,CRT;
var files : word;
Function UpCaseStr(st: String): String;
var loop: byte;
Begin
for loop := 1 to length(st) do st[loop] := upcase(st[loop]);
upcasestr := st
end;
Procedure FileList(Path: PathStr; Var OutFile: Text; lookingfor: string);
Var
dir,fs: SearchRec;
final: String;
Begin
textattr := lightred; write(#13,'Scanning: ', path); clreol;
FindFirst(path+'*.*',directory,dir);
with dir do While DosError = 0 Do
Begin
if (name[1] <> '.') and (attr and directory = directory) then
FileList(Path+Name+'\',outfile,lookingfor);
FindNext(dir)
end;
FindFirst(path+lookingfor,anyfile-directory,fs);
with fs do While DosError = 0 do
Begin
inc(files); fillchar(final,sizeof(final),' ');
final := #13 + path + name;
final[0] := #60; textattr := lightcyan;
write(#13,final); textattr := lightblue;
write(size, ' bytes'); clreol; writeln;
FindNext(fs)
end
End;
Procedure Help;
begin
textattr := lightcyan; writeln('FDir v1.00b by John Stephenson');
textattr := lightgray;
writeln(#10'USAGE: FDir (path\)filename.ext');
halt
end;
var
lookingfor: string;
d: dirstr;
n: namestr;
e: extstr;
Begin
lookingfor := upcasestr(paramstr(1));
fsplit(lookingfor, d, n, e);
if d = '' then d := '\';
lookingfor := n + e;
if lookingfor = '' then help;
textattr := white; writeln('Searching for: ', lookingfor);
files := 0;
FileList(d,output,lookingfor); write(#13); clreol;
textattr := white; write(#10, files, ' files(s) found');
textattr := lightgray; writeln
End.
|
(*
Category: SWAG Title: BITWISE TRANSLATIONS ROUTINES
Original name: 0015.PAS
Description: RANDOM1.PAS
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:53
*)
{Another method to acComplish this (which only requires an order of n
itterations is to generate an Array initialized from 2 to 1000 and then
randomize that Array. For your 400 numbers, just take 400 values in the
new sequence (starting at the index of your lowest number). You can do
that as follows:
}
Const MaxNumber = 2000;
Type SeqArray = Array [1..MaxNumber] of Integer;
{================================================================}
Procedure RandomizeSeq (first, last: Integer; Var iseq: SeqArray);
{================================================================}
Var i, iran,
temp, imax : Integer;
r : Real;
{
Operation: A random number within the range 1..last is generated
on each pass and the upper limit of the random number generated is
decreased by 1. The value stored at the highest index of the last
pass is moved to the location of the last number selected.
Parameters:
first = lowest number in sequence.
last = highest number in sequence.
iseq = Sequence Array
}
begin
{ initialize sequence Array }
For i := first to last do iseq[i] := i;
Randomize;
{ randomize the sorted Array }
For imax := last downto first do begin
{ get a random number between 0 and 1 and scale up to
an Integer in the range of first to last }
r := random;
iran := Trunc(r*imax) + first;
{ replace With value at highest index }
temp := iseq[iran];
iseq[iran] := iseq[imax];
iseq[imax] := temp
end;
end;
{ Example of generating 20 random numbers from 2 to 100: }
Var i : Integer;
a : SeqArray;
begin
RandomizeSeq(2,100,a);
For i := 2 to 21 do Write(a[i]:3); Writeln;
end.
|
{Una empresa de transportes realiza envíos de cargas, se desea calcular y mostrar el importe
a pagar.
Los datos que se ingresan son PESO de la carga (número real) y CATEGORIA (dato codificado:
1 -común, 2 - especial, 3 – aéreo).
El precio se calcula a $2 por Kg para categoría común, $2.5 por Kg para categoría especial y $3
por Kg para categoría aérea.
Se cobra recargo por sobrepeso: 30% si sobrepasa los 15 Kg, 20% si pesa más de 10 Kg y hasta
15Kg inclusive, 10% más de 5Kg y hasta 10 Kg inclusive.}
Program TP1eje16;
Var
peso,precio:real;
categoria:char;
Begin
write('Ingrese el peso en kg de la carga: ');readln(peso);
write('Elija la categoria: 1- Comun / 2- Especial / 3- Aereo : ');readln(categoria);
Case categoria of
'1': precio:= peso * 2;
'2': precio:= peso * 2.5;
'3': precio:= peso * 3;
end;
If (peso > 15) then
precio:= precio * 1.3
Else
if (peso >= 10) then
precio:= precio * 1.2
Else
precio:= precio * 1.1;
writeln(' ');
writeln('El precio de su carga es: ',precio:2:0);
end.
|
namespace org.me.openglapplication;
//Multi-purpose activity that initiates OpenGL surface views
//Expects 2 values to be passed in Intent's extras:
// isTranslucent: Boolean
// openGLRendererClass: string
interface
uses
java.util,
android.os,
android.app,
android.content,
android.util,
android.view,
android.widget,
android.opengl,
android.graphics,
android.util;
type
OpenGLActivity = public class(Activity)
public
const IsTranslucent = 'isTranslucent';
const OpenGLRendererClass = 'openGLRendererClass';
method onCreate(savedInstanceState: Bundle); override;
end;
implementation
method OpenGLActivity.onCreate(savedInstanceState: Bundle);
begin
inherited;
if Intent.getBooleanExtra(IsTranslucent, False) then
//Title bar can't be re-added in code, but can be removed
//So the manifest sets a translucent theme with a title bar, and here we disable the title bar if necessary
requestWindowFeature(Window.FEATURE_NO_TITLE)
else
//Translucency can't be enabled in code, but it can be disabled
//So the manifest sets a translucent theme, and here we disable the theme if necessary
Theme := Android.R.style.Theme;
var view := new GLSurfaceView(Self);
//view.DebugFlags := GLSurfaceView.DEBUG_CHECK_GL_ERROR or GLSurfaceView.DEBUG_LOG_GL_CALLS;
if Intent.getBooleanExtra(IsTranslucent, False) then
begin
// We want an 8888 pixel format because that's required for a translucent window.
// And we want a depth buffer.
view.setEGLConfigChooser(8, 8, 8, 8, 16, 0);
// Use a surface format with an Alpha channel:
view.Holder.Format := PixelFormat.TRANSLUCENT;
end;
//Find which OpenGL renderer class was requested and instantiate it
var targetRendererClass := Intent.StringExtra[OpenGLRendererClass];
if length(targetRendererClass) > 0 then
begin
try
var cls := &Class.forName(targetRendererClass);
var con := cls.getDeclaredConstructor([typeOf(Context)]);
view.setEGLConfigChooser(8, 8, 8, 8, 16, 0);
view.Renderer := con.newInstance(Self) as GLSurfaceView.Renderer ;
except
on E: Throwable do
Log.e(MainActivity.Tag, 'Exception creating OpenGL renderer', E)
end;
ContentView := view
end
else
finish
end;
end.
|
unit DSA.Graph.Dijkstra;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DSA.Tree.IndexHeap,
DSA.Interfaces.DataStructure,
DSA.Interfaces.Comparer,
DSA.Graph.Edge,
DSA.List_Stack_Queue.ArrayList,
DSA.List_Stack_Queue.LinkedListStack;
type
generic TDijkstra<T> = class
private
type
TArr_bool = specialize TArray<boolean>;
TEdge_T = specialize TEdge<T>;
TMinIndexHeap = specialize TIndexHeap<T>;
TList_Edge = specialize TArrayList<TEdge_T>;
TArrEdge = specialize TArray<TEdge_T>;
TWeightGraph_T = specialize TWeightGraph<T>;
TCmp_T = specialize TComparer<T>;
TStack_Edge = specialize TLinkedListStack<TEdge_T>;
var
__g: TWeightGraph_T;
__s: integer; // 起始点
__distTo: array of T; // distTo[i]存储从起始点s到i的最短路径长度
__marked: TArr_bool; // 标记数组, 在算法运行过程中标记节点i是否被访问
__from: TArrEdge; // from[i]记录最短路径中, 到达i点的边是哪一条,可以用来恢复整个最短路径
public
constructor Create(g: TWeightGraph_T; s: integer);
destructor Destroy; override;
/// <summary> 返回从a点到b点的最短路径长度 </summary>
function ShortestPathTo(b: integer): T;
/// <summary> 判断从a点到b点是否联通 </summary>
function HasPathTo(b: integer): boolean;
/// <summary> 寻找从a到b的最短路径, 将整个路径经过的边存放在vec中 </summary>
function ShortestPath(b: integer): TList_Edge;
/// <summary> 打印出从a点到b点的路径 </summary>
procedure ShowPath(b: integer);
end;
procedure Main;
implementation
uses
DSA.Graph.SparseWeightedGraph,
DSA.Utils;
type
TSparseWeightedGraph_int = specialize TSparseWeightedGraph<integer>;
TDijkstra_int = specialize TDijkstra<integer>;
TReadGraphWeight_int = specialize TReadGraphWeight<integer>;
procedure Main;
var
g: TSparseWeightedGraph_int;
d: TDijkstra_int;
fileName: string;
i, v: integer;
begin
fileName := WEIGHT_GRAPH_FILE_NAME_5;
v := 5;
g := TSparseWeightedGraph_int.Create(v, False);
TReadGraphWeight_int.Execute(g, FILE_PATH + fileName);
WriteLn('Test Dijkstra:'); d := TDijkstra_int.Create(g, 0);
for i := 0 to v - 1 do
begin
if d.HasPathTo(i) then
begin
WriteLn('Shortest Path to ', i, ' : ', d.ShortestPathTo(i));
d.ShowPath(i);
end
else
begin
WriteLn('No Path to ', i);
end;
WriteLn('----------');
end;
end;
{ TDijkstra }
constructor TDijkstra.Create(g: TWeightGraph_T; s: integer);
var
ipq: TMinIndexHeap;
v, w, bool: integer;
e: TEdge_T;
cmp: TCmp_T;
begin
__s := s;
__g := g;
SetLength(__distTo, g.Vertex);
SetLength(__marked, g.Vertex);
SetLength(__from, g.Vertex);
cmp := TCmp_T.Default;
// 使用索引堆记录当前找到的到达每个顶点的最短距离
ipq := TMinIndexHeap.Create(g.Vertex, THeapkind.Min);
__distTo[s] := Default(T);
__from[s] := TEdge_T.Create(s, s, Default(T));
__marked[s] := True;
ipq.Insert(s, __distTo[s]);
while not ipq.IsEmpty do
begin
v := ipq.ExtractFirstIndex;
// distTo[v]就是s到v的最短距离
__marked[v] := True;
// 对v的所有相邻节点进行更新
for e in g.AdjIterator(v) do
begin
w := e.OtherVertex(v);
if not __marked[w] then
begin
// 如果w点以前没有访问过,
// 或者访问过, 但是通过当前的v点到w点距离更短, 则进行更新
bool := cmp.Compare(__distTo[v] + e.Weight, __distTo[w]);
if (__from[w] = nil) or (bool < 0) then
begin
__distTo[w] := __distTo[v] + e.Weight;
__from[w] := e;
if ipq.Contain(w) then
ipq.Change(w, __distTo[w])
else
ipq.Insert(w, __distTo[w]);
end;
end;
end;
end;
end;
destructor TDijkstra.Destroy;
begin
inherited Destroy;
end;
function TDijkstra.HasPathTo(b: integer): boolean;
begin
Assert((b >= 0) and (b < __g.Vertex));
Result := __marked[b];
end;
function TDijkstra.ShortestPath(b: integer): TList_Edge;
var
stack: TStack_Edge;
e: TEdge_T;
ret: TList_Edge;
begin
Assert((b >= 0) and (b < __g.Vertex));
Assert(HasPathTo(b));
// 通过from数组逆向查找到从s到w的路径, 存放到栈中
stack := TStack_Edge.Create;
e := __from[b];
while e.VertexA <> __s do
begin
stack.Push(e);
e := __from[e.VertexA];
end;
stack.Push(e);
ret := TList_Edge.Create;
// 从栈中依次取出元素, 获得顺序的从s到w的路径
while not stack.IsEmpty do
begin
e := stack.Pop;
ret.AddLast(e);
end;
Result := ret;
end;
function TDijkstra.ShortestPathTo(b: integer): T;
begin
Assert((b >= 0) and (b < __g.Vertex));
Assert(HasPathTo(b));
Result := __distTo[b];
end;
procedure TDijkstra.ShowPath(b: integer);
var
list: TList_Edge;
i: integer;
begin
Assert((b >= 0) and (b < __g.Vertex));
Assert(HasPathTo(b));
list := ShortestPath(b);
for i := 0 to list.GetSize - 1 do
begin
Write(list[i].VertexA, ' -> ');
if i = list.GetSize - 1 then
WriteLn(list[i].VertexB);
end;
end;
end.
|
// -------------------------------------------------------------
// Este programa mostra como criar um game de labirinto :~
// Autor : Luiz Reginaldo - Desenvolvedor do Pzim
// -------------------------------------------------------------
Program Pzim ;
var maze: array[1..25,1..80] of char;
i, j: integer ;
xDestino, yDestino: integer ;
x,y: integer;
flag:boolean;
//----------------------------------------------------------------
// Funcao usada para saber se a posicao está dentro do labirinto
//----------------------------------------------------------------
Function isDentroLabirinto( i, j: integer ): boolean ;
Begin
if (i <=0) or (i >= 25) or (j <= 1) or (j >= 80) then
isDentroLabirinto := false
else
isDentroLabirinto := true ;
End;
//--------------------------------------------------------------------
// Funcao usada para saber se a posicao denota uma borda do labirinto
//--------------------------------------------------------------------
Function isBorda( i, j: integer ): boolean ;
Begin
if (i <=0) or (i >= 25) or (j <=0) or (j >= 80) then
isBorda := true
else
isBorda := false ;
End;
//--------------------------------------------------------------------
// Funcao usada para saber o número de parede ao redor de uma posição
//--------------------------------------------------------------------
Function numParedes( i, j: integer ): integer ;
var x: integer;
Begin
if not isDentroLabirinto(i,j) then
numParedes := 0
else
Begin
x:= 4;
if not isDentroLabirinto(i+1,j) or (maze[i+1,j] <> 'P' ) then x:= x-1;
if not isDentroLabirinto(i-1,j) or (maze[i-1,j] <> 'P' ) then x:= x-1;
if not isDentroLabirinto(i,j-1) or (maze[i,j-1] <> 'P' ) then x:= x-1;
if not isDentroLabirinto(i,j+1) or (maze[i,j+1] <> 'P' ) then x:= x-1;
numParedes := x;
End;
End;
//--------------------------------------------------------------------
// Procedimento que monta o labirinto, a partir de uma heurística.
//--------------------------------------------------------------------
Procedure NovoLabirinto;
Const BAIXO = 0;
DIREITA=1;
CIMA=2;
ESQUERDA=3;
Var direcoesValidas: array[0..3] of integer;
podeConstruir:boolean;
visited, posPilha, numPosCandidatas, direcaoEscolhida,x {linha},y {coluna} : integer;
pilhaCaminhoSeguido: array[0..2000] of integer;
Begin
// Define todas as posicoes do labirinto como parede
for i:=1 to 25 do
for j:=1 to 80 do
Begin
maze[i][j] := 'P' ;
End;
// Define a posicao de onde o labirinto irá comecar a ser construido
randomize;
x := 3 ;
y := 3 ;
// Variáveis usadas na construcao do labirinto
posPilha := 0 ;
podeConstruir:= true;
// Enquanto o labirinto ainda puder ser construido, repete...
while (podeConstruir) do
Begin
numPosCandidatas := 0;
// Heuristica: as posicoes candidatas para próxima posicao
// na construcao do labirinto possuem uma parede entre a
// posicao atual e tem 4 paredes ao seu redor.
if (not isBorda(x,y)) and (numParedes(x,y-2)=4) then
Begin
direcoesValidas[numPosCandidatas] := BAIXO ;
numPosCandidatas:= numPosCandidatas+1;
End;
if (not isBorda(x,y)) and (numParedes(x+2,y)=4) then
Begin
direcoesValidas[numPosCandidatas] := DIREITA ;
numPosCandidatas:= numPosCandidatas+1;
End;
if (not isBorda(x,y)) and (numParedes(x,y+2)=4) then
Begin
direcoesValidas[numPosCandidatas] := CIMA ;
numPosCandidatas:= numPosCandidatas+1;
End;
if (not isBorda(x,y)) and (numParedes(x-2,y)=4) then
Begin
direcoesValidas[numPosCandidatas] := ESQUERDA ;
numPosCandidatas:= numPosCandidatas+1;
End;
// Se foi encontrada pelo menos uma posicao candidata,
// escolhe aleatoriamente uma dessas posicoes e move para lá.
if (numPosCandidatas <> 0) then
Begin
direcaoEscolhida := direcoesValidas[ random(numPosCandidatas) ] ;
case (direcaoEscolhida) of
// knock down walls and make new cell the current cell
BAIXO: Begin
maze[x][y-2] := 'B' ;
maze[x][y-1] := 'B' ;
y:= y-2 ;
End;
DIREITA: Begin
maze[x+2][y] := 'B' ;
maze[x+1][y] := 'B' ;
x:= x+2 ;
End;
CIMA: Begin
maze[x][y+2] := 'B' ;
maze[x][y+1] := 'B' ;
y:= y+2 ;
End;
ESQUERDA: Begin
maze[x-2][y] := 'B' ;
maze[x-1][y] := 'B' ;
x:= x-2 ;
End;
end;
// Agora, empilha a direcao escolhida
pilhaCaminhoSeguido[posPilha] := direcaoEscolhida ;
posPilha := posPilha + 1;
end // fim do if
// Agora, se não foi encontrada nenhuma posicao candidata,
// Atualiza a posicao atual a partir da direcao armazenada
// no topo da pilha que contem o caminho seguido
else
Begin
posPilha:= posPilha-1;
// Se a pilha está vazia, a construcao deve parar...
if( posPilha < 0 ) then
podeConstruir:= false
// Senão, atualiza a posicao atual, voltando...
else Begin
case (pilhaCaminhoSeguido[posPilha]) of
BAIXO: Begin y:= y+2 ; End;
DIREITA: Begin x:= x-2 ; End;
CIMA: Begin y:= y-2 ; End;
ESQUERDA: Begin x:= x+2 ; End;
end;
End;
End;
End;
End;
//---------------------------------------------------------
// Procedimento que desenha o Labirinto
//---------------------------------------------------------
Procedure DesenhaLabirinto;
Begin
textcolor( lightgray );
for i:= 1 to 25 do
Begin
for j:= 1 to 80 do
if( maze[i,j] = 'P' ) then
Begin
gotoxy(j,i);
write( #177 );
End;
End;
End;
//---------------------------------------------------------
// Método que desenha o personagem em uma nova posicao
//---------------------------------------------------------
Procedure MovePersonagem( posx, posy: integer) ;
begin
// Apaga posicao anterior
gotoxy(y, x);
textcolor(lightgray);
write( #219 );
// Desenha na nova posicao
gotoxy(posy, posx);
textcolor(lightgreen);
write( #219 );
x:= posx;
y:= posy;
end;
//---------------------------------------------------------
// Método que desenha a posicao de saida
//---------------------------------------------------------
Procedure DesenhaSaida ;
Begin
// Desenha saida
flag:= false;
while( flag = false ) do
Begin
xDestino:= random(24)+1 ;
yDestino:= 77;
if( maze[xDestino,yDestino] = 'B' ) then
Begin
textcolor(white);
gotoxy(yDestino, xDestino);
write( 'S' );
flag:= true ;
End;
End;
End;
//---------------------------------------------------------
// Método que imprime mensagem de fim de jogo
//---------------------------------------------------------
Procedure FimJogo;
Begin
delay(2000);
clrscr;
gotoxy( 20, 10 );
textcolor(WHITE);
write('Muito bem! Você conseguiu encontrar a saída!');
gotoxy( 25, 14 );
textcolor(WHITE);
write('Pressione [ENTER] para sair . . .');
End;
//---------------------------------------------------------
// Programa principal
//---------------------------------------------------------
Begin
clrscr;
NovoLabirinto;
DesenhaLabirinto;
DesenhaSaida;
// Mostra mensagem...
gotoxy(1,1);
textbackground(green);
write(' Pascalzim Maze - By Luiz Reginaldo - Pressione CTRL+C para sair ');
// Move para a posicao inicial do personagem
gotoxy(1,1);
textbackground(black);
MovePersonagem(3,3);
// Joga... Só pode mover para uma posicao com buraco!
while not( (x=xDestino)and(y=yDestino) ) do
Begin
if (keypressed) then
case upcase(readkey) of
#0: case (readkey) of
// seta para cima
#72: begin
if( maze[x-1][y] = 'B' ) then
Begin
MovePersonagem(x-1,y);
End;
end;
// seta para baixo
#80: begin
if( maze[x+1][y] = 'B' ) then
Begin
MovePersonagem(x+1,y);
End;
end;
// seta para esquerda
#77: begin
if( maze[x][y+1] = 'B' ) then
Begin
MovePersonagem(x,y+1);
End;
end ;
// seta para direita
#75: begin
if( maze[x][y-1] = 'B' ) then
Begin
MovePersonagem(x,y-1);
End;
end;
end;
end;
End;
// Imprime tela de fim de jogo
FimJogo;
End.
|
unit LightSourceComThreadUnit;
// ==================================================
// COM port I/O handler thread for Laser control unit
// ==================================================
// 02.10.18
// 22.03.22 COM port Baud rate now set by constructor
interface
uses
System.Classes, System.SysUtils, Windows, mmsystem, System.StrUtils ;
type
TLightSourceComThread = class(TThread)
private
{ Private declarations }
FComPort : Integer ; // Com port #
FComHandle : THandle ; // Com port handle
FComPortOpen : Boolean ; // Com port open flag
FBaudRate : DWord ; // Com port baud rate
ComFailed : Boolean ; // COM port communications failed flag
OverLapStructure : POVERLAPPED ;
procedure OpenCOMPort ;
procedure CloseCOMPort ;
function SendCommand( const Line : string ) : Boolean ;
function ReceiveBytes( var EndOfLine : Boolean ) : string ;
public
constructor Create( BaudRate : DWord ) ;
protected
procedure Execute; override;
end;
implementation
uses LightSourceUnit ;
const
// Com port control flags
dcb_Binary = $00000001;
dcb_ParityCheck = $00000002;
dcb_OutxCtsFlow = $00000004;
dcb_OutxDsrFlow = $00000008;
dcb_DtrControlMask = $00000030;
dcb_DtrControlDisable = $00000000;
dcb_DtrControlEnable = $00000010;
dcb_DtrControlHandshake = $00000020;
dcb_DsrSensivity = $00000040;
dcb_TXContinueOnXoff = $00000080;
dcb_OutX = $00000100;
dcb_InX = $00000200;
dcb_ErrorChar = $00000400;
dcb_NullStrip = $00000800;
dcb_RtsControlMask = $00003000;
dcb_RtsControlDisable = $00000000;
dcb_RtsControlEnable = $00001000;
dcb_RtsControlHandshake = $00002000;
dcb_RtsControlToggle = $00003000;
dcb_AbortOnError = $00004000;
dcb_Reserveds = $FFFF8000;
constructor TLightSourceComThread.Create( BaudRate : DWord ) ;
// ------------------
// Thread constructor
// ------------------
begin
// Create thread
inherited Create(False);
FBaudRate := BaudRate ;
end ;
procedure TLightSourceComThread.Execute;
// --------------------------------
// COM Port transmit/receive thread
// --------------------------------
var
EndOfLine : Boolean ;
Reply : string ;
begin
// Create command list
Reply := '' ;
// Initialization
OpenComPort ;
{ Place thread code here }
while not Terminated do begin
Synchronize( procedure
begin
// Send next command in list
if (LightSource.CommandList.Count > 0) then
begin
SendCommand(LightSource.CommandList[0]);
// outputdebugstring(pchar(format('Light Source tx: %s',[LightSource.CommandList[0]])));
LightSource.CommandList.Delete(0) ;
end;
// Wait for command completion reply from remote device
Reply := Reply + ReceiveBytes(EndOfLine) ;
if EndOfLine then
begin
if Reply <> '' then LightSource.ReplyList.Add(Reply);
// outputdebugstring(pchar(format('Light Source rx: %s',[Reply])));
Reply := '' ;
end ;
end );
sleep(1);
end;
// Close COM port
CloseComPort ;
end;
procedure TLightSourceComThread.OpenCOMPort ;
// ----------------------------------------
// Establish communications with COM port
// ----------------------------------------
var
DCB : TDCB ; { Device control block for COM port }
CommTimeouts : TCommTimeouts ;
begin
if FComPortOpen then Exit ;
Synchronize( procedure begin FComPort := LightSource.FControlPort end ) ;
ComFailed := True ;
if FComPort < 1 then Exit ;
{ Open com port }
FComHandle := CreateFile( PCHar(format('COM%d',[FComPort])),
GENERIC_READ or GENERIC_WRITE,
0,
Nil,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0) ;
if NativeInt(FComHandle) < 0 then
begin
FComPortOpen := False ;
// ShowMessage(format('OBIS: Unable to open serial port: COM%d',[FControlPort+1]));
Exit ;
end;
outputdebugstring(pchar(format('Light Source COM%d open on handle %d',[FComPort,FComHandle])));
{ Get current state of COM port and fill device control block }
GetCommState( FComHandle, DCB ) ;
{ Change settings to those required for CoolLED }
DCB.BaudRate := FBaudRate ; //Old value pre 22.3.22 CBR_9600 ;
DCB.ByteSize := 8 ;
DCB.Parity := NOPARITY ;
DCB.StopBits := ONESTOPBIT ;
// Settings required to activate remote mode of CoolLED
DCB.Flags := dcb_Binary or dcb_DtrControlEnable or dcb_RtsControlEnable ;
{ Update COM port }
SetCommState( FComHandle, DCB ) ;
{ Initialise Com port and set size of transmit/receive buffers }
SetupComm( FComHandle, 4096, 4096 ) ;
{ Set Com port timeouts }
GetCommTimeouts( FComHandle, CommTimeouts ) ;
CommTimeouts.ReadIntervalTimeout := $FFFFFFFF ;
CommTimeouts.ReadTotalTimeoutMultiplier := 0 ;
CommTimeouts.ReadTotalTimeoutConstant := 0 ;
CommTimeouts.WriteTotalTimeoutMultiplier := 0 ;
CommTimeouts.WriteTotalTimeoutConstant := 5000 ;
SetCommTimeouts( FComHandle, CommTimeouts ) ;
ClearCommBreak( FComHandle ) ;
FComPortOpen := True ;
ComFailed := False ;
end ;
procedure TLightSourceComThread.CloseCOMPort ;
// ----------------------
// Close serial COM port
// ----------------------
begin
if FComPortOpen then CloseHandle( FComHandle ) ;
FComPortOpen := False ;
end ;
function TLightSourceComThread.SendCommand(
const Line : string { Text to be sent to Com port }
) : Boolean ;
{ --------------------------------------
Write a line of ASCII text to Com port
--------------------------------------}
var
i : Integer ;
nWritten,nC : DWORD ;
xBuf : array[0..258] of ansichar ;
Overlapped : Pointer ;
OK : Boolean ;
begin
Result := False ;
if not FComPortOpen then Exit ;
if ComFailed then Exit ;
// outputdebugstring(pchar('tx: ' + Line));
{ Copy command line to be sent to xMit buffer and and a CR character }
nC := Length(Line) ;
for i := 1 to nC do xBuf[i-1] := ANSIChar(Line[i]) ;
xBuf[nC] := #13 ;
Inc(nC) ;
xBuf[nC] := #10 ;
Inc(nC) ;
Overlapped := Nil ;
OK := WriteFile( FComHandle, xBuf, nC, nWritten, Overlapped ) ;
if (not OK) or (nWRitten <> nC) then
begin
// ShowMessage( ' Error writing to COM port ' ) ;
Result := False ;
end
else Result := True ;
end ;
function TLightSourceComThread.ReceiveBytes(
var EndOfLine : Boolean
) : string ; { bytes received }
{ -------------------------------------------------------
Read bytes from COMort until a line has been received
-------------------------------------------------------}
var
Line : string ;
rBuf : array[0..255] of ansichar ;
ComState : TComStat ;
PComState : PComStat ;
NumBytesRead,ComError,NumRead : DWORD ;
begin
if not FComPortOpen then Exit ;
PComState := @ComState ;
Line := '' ;
rBuf[0] := ' ' ;
NumRead := 0 ;
EndOfLine := False ;
Result := '' ;
{ Find out if there are any characters in receive buffer }
ClearCommError( FComHandle, ComError, PComState ) ;
// Read characters until CR is encountered
while (NumRead < ComState.cbInQue) and {(RBuf[0] <> #10) and} (RBuf[0] <> #13) do
begin
ReadFile( FComHandle,rBuf,1,NumBytesRead,OverlapStructure ) ;
if (rBuf[0] <> #10) and (rBuf[0] <> #13) then Line := Line + String(rBuf[0])
else EndOfLine := True ;
//outputdebugstring(pwidechar(RBuf[0]));
Inc( NumRead ) ;
end ;
Result := Line ;
end ;
end.
|
unit cnFormMargin;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, umcmIntE, cxLookAndFeelPainters, cxContainer, cxEdit,
cxTextEdit, cxMaskEdit, cxSpinEdit, cxControls, cxGroupBox, cxButtons;
type
TFormPageMargin = class(TForm)
cxButton1: TcxButton;
cxButton2: TcxButton;
cxGroupBox1: TcxGroupBox;
Label1: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
cbForceMargin: TCheckBox;
rsLeft: TcxSpinEdit;
rsTop: TcxSpinEdit;
rsRight: TcxSpinEdit;
rsBottom: TcxSpinEdit;
procedure cxButton2Click(Sender: TObject);
procedure cxButton1Click(Sender: TObject);
private
{ Private declarations }
function GetForceMargin : boolean;
function GetMarginBottom : double;
function GetMarginLeft : double;
function GetMarginRight : double;
function GetMarginTop : double;
procedure SetForceMargin(Value : boolean);
procedure SetMarginBottom(Value : double);
procedure SetMarginLeft(Value : double);
procedure SetMarginRight(Value : double);
procedure SetMarginTop(Value : double);
public
{ Public declarations }
property ForceMargin : boolean
read GetForceMargin
write SetForceMargin;
property MarginBottom : double
read GetMarginBottom
write SetMarginBottom;
property MarginLeft : double
read GetMarginLeft
write SetMarginLeft;
property MarginRight : double
read GetMarginRight
write SetMarginRight;
property MarginTop : double
read GetMarginTop
write SetMarginTop;
end;
var
FormPageMargin: TFormPageMargin;
implementation
{$R *.dfm}
function TFormPageMargin.GetForceMargin : boolean;
begin
Result := cbForceMargin.Checked;
end; // TFormPageMargin.GetForceMargin.
procedure TFormPageMargin.SetForceMargin(Value : boolean);
begin
cbForceMargin.Checked := Value;
end; // TFormPageMargin.SetForceMargin.
function TFormPageMargin.GetMarginBottom : double;
begin
Result := rsBottom.Value;
end; // TFormPageMargin.GetMarginBottom.
function TFormPageMargin.GetMarginLeft : double;
begin
Result := rsLeft.Value;
end; // TFormPageMargin.GetMarginLeft.
function TFormPageMargin.GetMarginRight : double;
begin
Result := rsRight.Value;
end; // TFormPageMargin.GetMarginRight.
function TFormPageMargin.GetMarginTop : double;
begin
Result := rsTop.Value;
end; // TFormPageMargin.GetMarginTop.
procedure TFormPageMargin.SetMarginBottom(Value : double);
begin
rsBottom.Value := Value;
end; // TFormPageMargin.SetMarginBottom.
procedure TFormPageMargin.SetMarginLeft(Value : double);
begin
rsLeft.Value := Value;
end; // TFormPageMargin.SetMarginLeft.
procedure TFormPageMargin.SetMarginRight(Value : double);
begin
rsRight.Value := Value;
end; // TFormPageMargin.SetMarginRight.
procedure TFormPageMargin.SetMarginTop(Value : double);
begin
rsTop.Value := Value;
end; // TFormPageMargin.SetMarginTop.
procedure TFormPageMargin.cxButton2Click(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TFormPageMargin.cxButton1Click(Sender: TObject);
begin
ModalResult:=mrOk;
end;
end.
|
unit ExtStringGrid;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Grids;
type
TDeleteEvent = procedure( Sender : TObject ) of object;
TInsertEvent = procedure( Sender : TObject ) of object;
type
TExtStringGrid = class(TStringGrid)
private
{ Private declarations }
FOnDelete : TDeleteEvent;
FOnInsert : TInsertEvent;
protected
{ Protected declarations }
procedure KeyDown( var Key : word; Shift : TShiftState ); override;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function SaveToFile( NF : string ) : integer;
function LoadFromFile( NF : string ) : integer;
procedure DeleteVoidLines;
function VoidLine( ARow : integer ) : boolean;
published
{ Published declarations }
property OnDelete : TDeleteEvent read FOnDelete write FOnDelete;
property OnInsert : TInsertEvent read FOnInsert write FOnInsert;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Losev Controls', [TExtStringGrid]);
end;
constructor TExtStringGrid.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor TExtStringGrid.Destroy;
begin
inherited Destroy;
end;
procedure TExtStringGrid.KeyDown( var Key : word; Shift : TShiftState );
var
i, R : integer;
begin
if (goEditing in Options) then
case key of
VK_Insert :
if ( ssCtrl in Shift ) then begin
R:=Row;
RowCount:=RowCount+1;
for i:=RowCount-2 downto Row do MoveRow( i, i+1 );
Row:=R;
Col:=FixedCols;
Rows[Row].Clear;
FOnInsert( Self );
end
else
if ( ssAlt in Shift ) then begin
R:=Row+1;
RowCount:=RowCount+1;
for i:=RowCount-2 downto Row+1 do MoveRow( i, i+1 );
Row:=R;
Col:=FixedCols;
Rows[Row].Clear;
FOnInsert( Self );
end;
VK_Delete :
if ( ssCtrl in Shift ) then begin
if (RowCount>FixedRows+1) then begin
if (Row=RowCount-1) then R:=Row-1 else R:=Row;
DeleteRow( Row );
Row:=R;
end
else
Rows[Row].Clear;
FOnDelete( Self );
end;
end;
inherited KeyDown( Key, Shift );
end;
function TExtStringGrid.SaveToFile( NF : string ) : integer;
var
Err : integer;
i,j : integer;
f : textfile;
begin
{$I-}
AssignFile( f, NF );
ReWrite( f );
Err:=IOResult;
if Err=0 then begin
for i:=FixedRows to RowCount-1 do begin
for j:=FixedCols to ColCount-1 do begin
WriteLn( f, Cells[j,i] );
Err:=IOResult;
if Err>0 then break;
end;
if Err>0 then break;
end;
CloseFile( f );
if Err>0 then IOResult else Err:=IOResult;
end;
if Err>0 then begin
DeleteFile( NF );
IOResult;
end;
Result:=Err;
end;
function TExtStringGrid.LoadFromFile( NF : string ) : integer;
var
Err : integer;
j : integer;
f : textfile;
S : string;
begin
RowCount:=FixedRows+1;
{$I-}
AssignFile( f, NF );
ReSet( f );
Err:=IOResult;
if Err=0 then begin
while not Eof(f) do begin
for j:=FixedCols to ColCount-1 do begin
ReadLn( f, S ); Cells[j,RowCount-1]:=S;
Err:=IOResult;
if Err>0 then break;
end;
RowCount:=RowCount+1;
if Err>0 then break;
end;
CloseFile( f );
if Err>0 then IOResult else Err:=IOResult;
if RowCount>FixedRows+1 then DeleteRow( RowCount-1 );
end;
Row:=FixedRows;
Col:=FixedCols;
Result:=Err;
end;
function TExtStringGrid.VoidLine( ARow : integer ) : boolean;
var
i,j : integer;
begin
for i:=FixedCols to ColCount-1 do
for j:=1 to length( Cells[i,ARow] ) do
if Cells[i,ARow][j]>#32 then begin
VoidLine:=false;
Exit;
end;
VoidLine:=true;
end;
procedure TExtStringGrid.DeleteVoidLines;
var
i : integer;
begin
i:=FixedRows;
while (i<RowCount) and (RowCount>FixedCols+1) do
if VoidLine( i ) then DeleteRow( i ) else inc( i );
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Design time registration code for the Newton Manager.
}
unit VXS.NewtonRegister;
interface
uses
System.Classes, VXS.NGDManager;
procedure register;
//=========================================================
implementation
//=========================================================
procedure register;
begin
RegisterClasses([TVXNGDManager, TVXNGDDynamic, TVXNGDStatic]);
RegisterComponents('VXScene', [TVXNGDManager]);
end;
end.
|
//
// Generated by JavaToPas v1.5 20171018 - 171145
////////////////////////////////////////////////////////////////////////////////
unit java.sql.Timestamp;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes;
type
JTimestamp = interface;
JTimestampClass = interface(JObjectClass)
['{595F67B1-652A-4AF3-A5CE-7108D2A45285}']
function after(ts : JTimestamp) : boolean; cdecl; // (Ljava/sql/Timestamp;)Z A: $1
function before(ts : JTimestamp) : boolean; cdecl; // (Ljava/sql/Timestamp;)Z A: $1
function compareTo(o : JDate) : Integer; cdecl; overload; // (Ljava/util/Date;)I A: $1
function compareTo(ts : JTimestamp) : Integer; cdecl; overload; // (Ljava/sql/Timestamp;)I A: $1
function equals(ts : JObject) : boolean; cdecl; overload; // (Ljava/lang/Object;)Z A: $1
function equals(ts : JTimestamp) : boolean; cdecl; overload; // (Ljava/sql/Timestamp;)Z A: $1
function getNanos : Integer; cdecl; // ()I A: $1
function getTime : Int64; cdecl; // ()J A: $1
function hashCode : Integer; cdecl; // ()I A: $1
function init(time : Int64) : JTimestamp; cdecl; overload; // (J)V A: $1
function init(year : Integer; month : Integer; date : Integer; hour : Integer; minute : Integer; second : Integer; nano : Integer) : JTimestamp; deprecated; cdecl; overload;// (IIIIIII)V A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
function valueOf(s : JString) : JTimestamp; cdecl; // (Ljava/lang/String;)Ljava/sql/Timestamp; A: $9
procedure setNanos(n : Integer) ; cdecl; // (I)V A: $1
procedure setTime(time : Int64) ; cdecl; // (J)V A: $1
end;
[JavaSignature('java/sql/Timestamp')]
JTimestamp = interface(JObject)
['{5A18ABA8-2C26-4154-86EE-08A9D646D19C}']
function after(ts : JTimestamp) : boolean; cdecl; // (Ljava/sql/Timestamp;)Z A: $1
function before(ts : JTimestamp) : boolean; cdecl; // (Ljava/sql/Timestamp;)Z A: $1
function compareTo(o : JDate) : Integer; cdecl; overload; // (Ljava/util/Date;)I A: $1
function compareTo(ts : JTimestamp) : Integer; cdecl; overload; // (Ljava/sql/Timestamp;)I A: $1
function equals(ts : JObject) : boolean; cdecl; overload; // (Ljava/lang/Object;)Z A: $1
function equals(ts : JTimestamp) : boolean; cdecl; overload; // (Ljava/sql/Timestamp;)Z A: $1
function getNanos : Integer; cdecl; // ()I A: $1
function getTime : Int64; cdecl; // ()J A: $1
function hashCode : Integer; cdecl; // ()I A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure setNanos(n : Integer) ; cdecl; // (I)V A: $1
procedure setTime(time : Int64) ; cdecl; // (J)V A: $1
end;
TJTimestamp = class(TJavaGenericImport<JTimestampClass, JTimestamp>)
end;
implementation
end.
|
namespace RemotingSample.Server;
interface
uses
System.Reflection,
System.Runtime.Remoting,
System.Runtime.Remoting.Channels,
System.Runtime.Remoting.Channels.HTTP,
RemotingSample.Implementation;
type
ConsoleApp = class
class var
fChannel: HttpChannel;
public
class method Main;
end;
implementation
class method ConsoleApp.Main;
const
DefaultPort = 8033;
begin
// Initializes the server to listen for HTTP requests on a specific port
fChannel := new HttpChannel(DefaultPort);
ChannelServices.RegisterChannel(fChannel, false);
// Registers the TRemoteService service
RemotingConfiguration.RegisterWellKnownServiceType(
typeOf(RemoteService),
'RemoteService.soap',
WellKnownObjectMode.Singleton);
// Starts accepting requests
Console.WriteLine('HTTP channel created. Listening on port '+DefaultPort.ToString);
Console.ReadLine;
end;
end. |
Vie_algopermutation_LV_v1_20/11/17
Algorithme:Permutation_3_entiers
//But:Permuter trois entiers saisie par l'utilisateur
//Principe:On demande à l'utilisateur de saisir trois entiers et on va les permuters les uns avec les autres
//Entrée:3 entiers saisie
//Sortie:3 entiers dans un ordre inversé
VAR
Nb1,Nb2,Nb3,perm1,perm2:ENTIER
DEBUT
ECRIRE "Saisissez trois entiers"
LIRE Nb1,Nb2,Nb3
Perm1<--Nb1
Nb1<--Nb2
Nb2<--Nb3
Nb3<--Perm1
ECRIRE "Le nombre 1 vaut maintenant: ",Nb1," le nombre 2 vaut: ",Nb2," et le nombre 3 vaut: ",Nb3
FIN |
unit JS_HTML_Code;
interface
const
//subtitle word add HTML code
HTML_CODE_A_WORD =
'<li class="menu">' +
'<ul>' +
'<li class="button"><a href="#" class="green">%s<span></span></a></li>' +
'<li class="dropdown">' +
'</li></ul></li>';
JS_CODE_INIT1 = 'document.write("' +
'<body bgColor=black>' +
'<div style=''text-align: center; color: white; font-family: Tahoma; font-size: 20; margin-top: 40px;''>' +
'Загрузка...</div></body>");';
//CefRegisterExtension Javascript code
JS_CODE_INIT2 =
'var cef;'+
'if (!cef)'+
' cef = {};'+
'if (!cef.translation)'+
' cef.translation = {};' +
'(function() {'+
' cef.translation.translator = function() {'+
' native function GetTranslatorObject();'+
' return GetTranslatorObject();'+
' };'+
'})();';
//clear word list code
JS_CODE_CLEAR = 'clearWords();';
JS_CODE_APPEND_MASK = 'appendWord("%s", "%s");';
JS_CODE_REGISTER_EVENTS = 'registerEvents();';
JS_CODE_SHOW_WORD_BY_NUM = 'showWordByNum(%d);';
JS_CODE_APPEND_PHRASEWORD = 'addWord("%s");';
JS_CODE_ADD_TRANSLATE_ALL_BUTTON = 'addTranslateAllButton();';
JS_CODE_UI_SET_STATEPLAY = 'changeStatePlay();';
JS_CODE_UI_SET_STATEPAUSE = 'changeStatePause();';
JS_CODE_UI_SET_SLIDERPOS = 'setSliderPosition(%d);';
JS_CODE_UI_SET_VOLUME = 'setVolume(%d)';
JS_CODE_UI_SET_CURPOS = 'setCurPos("%s")';
JS_CODE_UI_SET_DURATION = 'setDuration("%s")';
JS_CODE_UI_SET_CURPOS2 = 'setCurPos2("%s")';
HTML_CODE_GOOGLE_BUTTON = '<div class="externallink google" goto="%s"><a href="%s">translate.google.ru</a></div> <BR>';
HTML_CODE_URBANDIC_BUTTON = '<div class="externallink urbandictionary" goto="%s"><a href="%s">urbandictionary.com</a></div> <BR> ';
HTML_CODE_WIKIPEDIA_BUTTON = '<div class="externallink wikies" goto="%s"><a href="%s">wikipedia.org</a></div> <BR> ';
HTML_CODE_WIKTIONARY_BUTTON = '<div class="externallink wikies" goto="%s"><a href="%s">wiktionary.org</a></div> <BR> ';
HTML_TRANSLATE_HEADER_MASK = 'Значение слова <a class="speech">%s</a>: <hr /> ';
HTML_CODE_WORD_NOT_FOUND = '<BR><i>Слово не найдено :(</i> ';
HTML_MB_WORD_FROM_MASK = '<BR>Возможно, производное от <b>%s</b> <BR>';
HTML_CODE_LOOK_INTERNET = '<BR><BR> Значение слова можно поискать в Интернете: <hr class="hr_gray">';
HTML_CODE_NOT_FOUND_LOOK_INTERNET = '<BR><BR> Попробуйте поискать в Интернете: <hr class="hr_gray">';
HTML_CODE_LOOK_GARBAGE = '<BR><BR> <b>Будь мужиком, следи за осанкой!</b> <hr class="hr_gray">';
HTML_CODE_GUTTENBERG_MASK = 'Место в <abbr title="wiktionary.org - TV/movie frequency list (2006)">частотном словаре</abbr>: <a class="guttenberg">%d</a>';
HTML_CODE_WORD_MASK = '<a class="view_word">%s</a>';
HTML_CODE_GOOGLE_OPINION = '<BR> <a class="google_opinion" word="%s">Ask Google</a> <BR>';
HTML_CODE_BING_OPINION = '<BR> <a class="bing_opinion" word="%s">ask Bing!</a> <BR>';
implementation
end.
|
unit uMain;
{
Copyright (c) 2015 Ugochukwu Mmaduekwe ugo4brain@gmail.com
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
}
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.ExtCtrls, Vcl.Samples.Spin,
Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, Vcl.Dialogs, uStringGenerator,
uStopWatch, uBase, uBase32, uBase64, uBase85, uBase91, uBase128, uBase256,
uBase1024, uBase4096, uZBase32, uBaseN;
function MillisecondstoTDateTime(Milliseconds: Extended): TDateTime;
procedure DisplayCalculations;
procedure CustomDisplayCalculations;
function returnBitsPerCharsandRatio(ItemIndex: Integer; out ratio: String;
isCustom: Boolean = False): String;
function AlphabetParse(InArray: array of String): String;
function AlphabetDisplay(ItemIndex: Integer; out CustomChar: String): String;
procedure SwapInputOuput;
function BaseDeriver(ItemIndex: Integer): Integer;
procedure ClearMemo;
procedure ValuestoDisplay;
procedure GenerateInputText;
function ComboOneChange(ItemIndex: Integer): String;
procedure ComboTwoChange;
function EncodeString(data: String; Encoding, BasetoUse: Integer;
PrefixPostfix: Boolean): String;
function DecodeToString(data: String; Encoding, BasetoUse: Integer;
PrefixPostfix: Boolean): String;
type
TForm1 = class(TForm)
GroupBox1: TGroupBox;
Memo1: TMemo;
Memo2: TMemo;
Label1: TLabel;
Label2: TLabel;
ComboBox1: TComboBox;
SpinEdit1: TSpinEdit;
Label3: TLabel;
CheckBox1: TCheckBox;
Button1: TButton;
ComboBox2: TComboBox;
Label4: TLabel;
Label5: TLabel;
SpinEdit2: TSpinEdit;
Edit1: TEdit;
Label6: TLabel;
Memo3: TMemo;
Alphabet: TLabel;
Edit2: TEdit;
Edit3: TEdit;
CheckBox2: TCheckBox;
Label7: TLabel;
Label8: TLabel;
ComboBox3: TComboBox;
Label9: TLabel;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Edit4: TEdit;
Edit5: TEdit;
Edit6: TEdit;
Label10: TLabel;
Label11: TLabel;
Label13: TLabel;
SpinEdit3: TSpinEdit;
Label12: TLabel;
CheckBox3: TCheckBox;
Button6: TButton;
procedure Button1Click(Sender: TObject);
procedure Memo1Change(Sender: TObject);
procedure Memo1KeyPress(Sender: TObject; var Key: Char);
procedure Memo2KeyPress(Sender: TObject; var Key: Char);
procedure FormCreate(Sender: TObject);
procedure ComboBox1Change(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Memo2Change(Sender: TObject);
procedure ComboBox2Change(Sender: TObject);
procedure Memo3KeyPress(Sender: TObject; var Key: Char);
procedure Button4Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function MillisecondstoTDateTime(Milliseconds: Extended): TDateTime;
begin
result := Milliseconds / (SecsPerDay * 1000.0);
end;
procedure DisplayCalculations;
var
ratioValue: String;
CustomChar: String;
begin
Form1.Edit2.Text := returnBitsPerCharsandRatio(Form1.ComboBox2.ItemIndex,
ratioValue);
Form1.Edit3.Text := ratioValue;
Form1.Memo3.Text := AlphabetDisplay(Form1.ComboBox2.ItemIndex, CustomChar);
Form1.Edit1.Text := CustomChar;
end;
procedure CustomDisplayCalculations;
var
ratioValue: String;
CustomChar: String;
begin
Form1.Edit2.Text := returnBitsPerCharsandRatio(Form1.ComboBox2.ItemIndex,
ratioValue, True);
Form1.Edit3.Text := ratioValue;
Form1.Edit1.Text := CustomChar;
end;
function returnBitsPerCharsandRatio(ItemIndex: Integer; out ratio: String;
isCustom: Boolean = False): String;
var
FormatSetting: TFormatSettings;
begin
result := '';
ratio := '';
FormatSetting := TFormatSettings.Create;
case ItemIndex of
0:
begin
Base(Length(uBase32.DefaultAlphabet), uBase32.DefaultAlphabet,
uBase32.DefaultSpecial);
result := InttoStr(BlockBitsCount) + '/' + InttoStr(BlockCharsCount);
ratio := FormatFloat('0.000000', (BlockBitsCount) / BlockCharsCount,
FormatSetting);
end;
1:
begin
Base(Length(uBase64.DefaultAlphabet), uBase64.DefaultAlphabet,
uBase64.DefaultSpecial);
result := InttoStr(BlockBitsCount) + '/' + InttoStr(BlockCharsCount);
ratio := FormatFloat('0.000000', (BlockBitsCount) / BlockCharsCount,
FormatSetting);
end;
2:
begin
Base(Length(uBase85.DefaultAlphabet), uBase85.DefaultAlphabet,
uBase85.DefaultSpecial);
result := InttoStr(BlockBitsCount) + '/' + InttoStr(BlockCharsCount);
ratio := FormatFloat('0.000000', (BlockBitsCount) / BlockCharsCount,
FormatSetting);
end;
3:
begin
Base(Length(uBase91.DefaultAlphabet), uBase91.DefaultAlphabet,
uBase91.DefaultSpecial);
result := InttoStr(BlockBitsCount) + '/' + InttoStr(BlockCharsCount);
ratio := FormatFloat('0.000000', (BlockBitsCount) / BlockCharsCount,
FormatSetting);
end;
4:
begin
Base(Length(uBase128.DefaultAlphabet), uBase128.DefaultAlphabet,
uBase128.DefaultSpecial);
result := InttoStr(BlockBitsCount) + '/' + InttoStr(BlockCharsCount);
ratio := FormatFloat('0.000000', (BlockBitsCount) / BlockCharsCount,
FormatSetting);
end;
5:
begin
Base(Length(uBase256.DefaultAlphabet), uBase256.DefaultAlphabet,
uBase256.DefaultSpecial);
result := InttoStr(BlockBitsCount) + '/' + InttoStr(BlockCharsCount);
ratio := FormatFloat('0.000000', (BlockBitsCount) / BlockCharsCount,
FormatSetting);
end;
6:
begin
Base(Length(uBase1024.DefaultAlphabet), uBase1024.DefaultAlphabet,
uBase1024.DefaultSpecial);
result := InttoStr(BlockBitsCount) + '/' + InttoStr(BlockCharsCount);
ratio := FormatFloat('0.000000', (BlockBitsCount) / BlockCharsCount,
FormatSetting);
end;
7:
begin
Base(Length(uBase4096.DefaultAlphabet), uBase4096.DefaultAlphabet,
uBase4096.DefaultSpecial);
result := InttoStr(BlockBitsCount) + '/' + InttoStr(BlockCharsCount);
ratio := FormatFloat('0.000000', (BlockBitsCount) / BlockCharsCount,
FormatSetting);
end;
8:
begin
Base(Length(uZBase32.DefaultAlphabet), uZBase32.DefaultAlphabet,
uZBase32.DefaultSpecial);
result := InttoStr(BlockBitsCount) + '/' + InttoStr(BlockCharsCount);
ratio := FormatFloat('0.000000', (BlockBitsCount) / BlockCharsCount,
FormatSetting);
end;
9:
begin
if not(isCustom) then
begin
Form1.Memo3.Text := GetAlphabet(Form1.SpinEdit2.Value);
end;
tempStr := Form1.Memo3.Text;
MakeCustomDefaultAlphabet(tempStr, OutDefaultAlphabet);
BaseN(OutDefaultAlphabet, Form1.SpinEdit3.Value,
Form1.CheckBox3.Checked);
result := InttoStr(BlockBitsCount) + '/' + InttoStr(BlockCharsCount);
ratio := FormatFloat('0.000000', (BlockBitsCount) / BlockCharsCount,
FormatSetting);
end;
end;
end;
function AlphabetParse(InArray: array of String): String;
begin
result := ArraytoString(InArray);
end;
procedure SwapInputOuput;
var
tempString: String;
begin
tempString := Form1.Memo1.Text;
Form1.Memo1.Text := Form1.Memo2.Text;;
Form1.Memo2.Text := tempString;
end;
function BaseDeriver(ItemIndex: Integer): Integer;
begin
result := 0;
case ItemIndex of
0:
begin
result := Length(uBase32.DefaultAlphabet);
end;
1:
begin
result := Length(uBase64.DefaultAlphabet);
end;
2:
begin
result := Length(uBase85.DefaultAlphabet);
end;
3:
begin
result := Length(uBase91.DefaultAlphabet);
end;
4:
begin
result := Length(uBase128.DefaultAlphabet);
end;
5:
begin
result := Length(uBase256.DefaultAlphabet);
end;
6:
begin
result := Length(uBase1024.DefaultAlphabet);
end;
7:
begin
result := Length(uBase4096.DefaultAlphabet);
end;
8:
begin
result := Length(uZBase32.DefaultAlphabet);
end;
9:
begin
result := 32;
end;
end;
end;
function ComboOneChange(ItemIndex: Integer): String;
begin
case ItemIndex of
0:
begin
result := 'Man is distinguished, not only by his reason, but by this singular passion from '
+ 'other animals, which is a lust of the mind, that by a perseverance of delight '
+ 'in the continued and indefatigable generation of knowledge, exceeds the short '
+ 'vehemence of any carnal pleasure.';
end;
1:
begin
result := 'Зарегистрируйтесь сейчас на Десятую Международную Конференцию по '
+ 'Unicode, которая состоится 10-12 марта 1997 года в Майнце в Германии. '
+ 'Конференция соберет широкий круг экспертов по вопросам глобального '
+ 'Интернета и Unicode, локализации и интернационализации, воплощению и '
+ 'применению Unicode в различных операционных системах и программных '
+ 'приложениях, шрифтах, верстке и многоязычных компьютерных системах.';
end;
2:
begin
result := 'Σὲ γνωρίζω ἀπὸ τὴν κόψη ' + 'τοῦ σπαθιοῦ τὴν τρομερή, ' +
'σὲ γνωρίζω ἀπὸ τὴν ὄψη ' + 'ποὺ μὲ βία μετράει τὴ γῆ. ' +
'᾿Απ᾿ τὰ κόκκαλα βγαλμένη ' + 'τῶν ῾Ελλήνων τὰ ἱερά ' +
'καὶ σὰν πρῶτα ἀνδρειωμένη ' + 'χαῖρε, ὦ χαῖρε, ᾿Ελευθεριά!';
end;
end;
end;
procedure ComboTwoChange;
begin
Form1.Memo2.Clear;
ValuestoDisplay;
Form1.SpinEdit2.Value := BaseDeriver(Form1.ComboBox2.ItemIndex);
Form1.Memo3.Text := GetAlphabet(Form1.SpinEdit2.Value);
DisplayCalculations;
if Form1.ComboBox2.ItemIndex = 2 then
Form1.CheckBox2.Enabled := True
else
begin
Form1.CheckBox2.Enabled := False;
Form1.CheckBox2.Checked := False;
end;
if Form1.ComboBox2.ItemIndex = 9 then
begin
Form1.SpinEdit2.Enabled := True;
Form1.SpinEdit3.Enabled := True;
Form1.SpinEdit3.Value := 64;
Form1.Button6.Enabled := True;
Form1.Memo3.ReadOnly := False;
end
else
begin
Form1.SpinEdit2.Enabled := False;
Form1.SpinEdit3.Enabled := False;
Form1.SpinEdit3.Value := 64;
Form1.Button6.Enabled := False;
Form1.Memo3.ReadOnly := True;
end;
end;
function AlphabetDisplay(ItemIndex: Integer; out CustomChar: String): String;
begin
result := '';
CustomChar := '';
case ItemIndex of
0:
begin
result := AlphabetParse(uBase32.DefaultAlphabet);
CustomChar := uBase32.DefaultSpecial;
end;
1:
begin
result := AlphabetParse(uBase64.DefaultAlphabet);
CustomChar := uBase64.DefaultSpecial;
end;
2:
begin
result := AlphabetParse(uBase85.DefaultAlphabet);
end;
3:
begin
result := AlphabetParse(uBase91.DefaultAlphabet);
CustomChar := uBase91.DefaultSpecial;
end;
4:
begin
result := AlphabetParse(uBase128.DefaultAlphabet);
CustomChar := uBase128.DefaultSpecial;
end;
5:
begin
result := AlphabetParse(uBase256.DefaultAlphabet);
CustomChar := uBase256.DefaultSpecial;
end;
6:
begin
result := AlphabetParse(uBase1024.DefaultAlphabet);
CustomChar := uBase1024.DefaultSpecial;
end;
7:
begin
result := AlphabetParse(uBase4096.DefaultAlphabet);
CustomChar := uBase4096.DefaultSpecial;
end;
8:
begin
result := AlphabetParse(uZBase32.DefaultAlphabet);
CustomChar := uZBase32.DefaultSpecial;
end;
9:
begin
result := AlphabetParse(uBaseN.OutDefaultAlphabet);
CustomChar := '';
end;
end;
end;
procedure ClearMemo;
begin
Form1.Memo1.Clear;
Form1.Memo2.Clear;
Form1.Memo3.Clear;
end;
procedure ValuestoDisplay;
begin
Form1.Edit4.Text := InttoStr(Length(Form1.Memo1.Text));
Form1.Edit5.Text := InttoStr(Length(Form1.Memo2.Text));
Form1.Edit6.Text := 'Not Measured';
end;
procedure GenerateInputText;
begin
Form1.Memo1.Text := GetRandom(Form1.SpinEdit1.Value, Form1.CheckBox1.Checked);
ValuestoDisplay;
end;
function EncodeString(data: String; Encoding, BasetoUse: Integer;
PrefixPostfix: Boolean): String;
begin
case Encoding of
0:
begin
case BasetoUse of
0:
begin
result := uBase32.Encode(TEncoding.ANSI.GetBytes(data));
end;
1:
begin
result := uBase64.Encode(TEncoding.ANSI.GetBytes(data));
end;
2:
begin
result := uBase85.Encode(TEncoding.ANSI.GetBytes(data),
PrefixPostfix);
end;
3:
begin
result := uBase91.Encode(TEncoding.ANSI.GetBytes(data));
end;
4:
begin
result := uBase128.Encode(TEncoding.ANSI.GetBytes(data));
end;
5:
begin
result := uBase256.Encode(TEncoding.ANSI.GetBytes(data));
end;
6:
begin
result := uBase1024.Encode(TEncoding.ANSI.GetBytes(data));
end;
7:
begin
result := uBase4096.Encode(TEncoding.ANSI.GetBytes(data));
end;
8:
begin
result := uZBase32.Encode(TEncoding.ANSI.GetBytes(data));
end;
9:
begin
result := uBaseN.Encode(TEncoding.ANSI.GetBytes(data),
Form1.SpinEdit3.Value, Form1.CheckBox3.Checked);
end;
else
begin
raise Exception.Create('Invalid Base Selection');
end;
end;
end;
1:
begin
case BasetoUse of
0:
begin
result := uBase32.Encode(TEncoding.ASCII.GetBytes(data));
end;
1:
begin
result := uBase64.Encode(TEncoding.ASCII.GetBytes(data));
end;
2:
begin
result := uBase85.Encode(TEncoding.ASCII.GetBytes(data),
PrefixPostfix);
end;
3:
begin
result := uBase91.Encode(TEncoding.ASCII.GetBytes(data));
end;
4:
begin
result := uBase128.Encode(TEncoding.ASCII.GetBytes(data));
end;
5:
begin
result := uBase256.Encode(TEncoding.ASCII.GetBytes(data));
end;
6:
begin
result := uBase1024.Encode(TEncoding.ASCII.GetBytes(data));
end;
7:
begin
result := uBase4096.Encode(TEncoding.ASCII.GetBytes(data));
end;
8:
begin
result := uZBase32.Encode(TEncoding.ASCII.GetBytes(data));
end;
9:
begin
result := uBaseN.Encode(TEncoding.ASCII.GetBytes(data),
Form1.SpinEdit3.Value, Form1.CheckBox3.Checked);
end;
else
begin
raise Exception.Create('Invalid Base Selection');
end;
end;
end;
2:
begin
case BasetoUse of
0:
begin
result := uBase32.Encode
(TEncoding.BigEndianUnicode.GetBytes(data));
end;
1:
begin
result := uBase64.Encode
(TEncoding.BigEndianUnicode.GetBytes(data));
end;
2:
begin
result := uBase85.Encode
(TEncoding.BigEndianUnicode.GetBytes(data), PrefixPostfix);
end;
3:
begin
result := uBase91.Encode
(TEncoding.BigEndianUnicode.GetBytes(data));
end;
4:
begin
result := uBase128.Encode
(TEncoding.BigEndianUnicode.GetBytes(data));
end;
5:
begin
result := uBase256.Encode
(TEncoding.BigEndianUnicode.GetBytes(data));
end;
6:
begin
result := uBase1024.Encode
(TEncoding.BigEndianUnicode.GetBytes(data));
end;
7:
begin
result := uBase4096.Encode
(TEncoding.BigEndianUnicode.GetBytes(data));
end;
8:
begin
result := uZBase32.Encode
(TEncoding.BigEndianUnicode.GetBytes(data));
end;
9:
begin
result := uBaseN.Encode(TEncoding.BigEndianUnicode.GetBytes(data),
Form1.SpinEdit3.Value, Form1.CheckBox3.Checked);
end;
else
begin
raise Exception.Create('Invalid Base Selection');
end;
end;
end;
3:
begin
case BasetoUse of
0:
begin
result := uBase32.Encode(TEncoding.Default.GetBytes(data));
end;
1:
begin
result := uBase64.Encode(TEncoding.Default.GetBytes(data));
end;
2:
begin
result := uBase85.Encode(TEncoding.Default.GetBytes(data),
PrefixPostfix);
end;
3:
begin
result := uBase91.Encode(TEncoding.Default.GetBytes(data));
end;
4:
begin
result := uBase128.Encode(TEncoding.Default.GetBytes(data));
end;
5:
begin
result := uBase256.Encode(TEncoding.Default.GetBytes(data));
end;
6:
begin
result := uBase1024.Encode(TEncoding.Default.GetBytes(data));
end;
7:
begin
result := uBase4096.Encode(TEncoding.Default.GetBytes(data));
end;
8:
begin
result := uZBase32.Encode(TEncoding.Default.GetBytes(data));
end;
9:
begin
result := uBaseN.Encode(TEncoding.Default.GetBytes(data),
Form1.SpinEdit3.Value, Form1.CheckBox3.Checked);
end;
else
begin
raise Exception.Create('Invalid Base Selection');
end;
end;
end;
4:
begin
case BasetoUse of
0:
begin
result := uBase32.Encode(TEncoding.Unicode.GetBytes(data));
end;
1:
begin
result := uBase64.Encode(TEncoding.Unicode.GetBytes(data));
end;
2:
begin
result := uBase85.Encode(TEncoding.Unicode.GetBytes(data),
PrefixPostfix);
end;
3:
begin
result := uBase91.Encode(TEncoding.Unicode.GetBytes(data));
end;
4:
begin
result := uBase128.Encode(TEncoding.Unicode.GetBytes(data));
end;
5:
begin
result := uBase256.Encode(TEncoding.Unicode.GetBytes(data));
end;
6:
begin
result := uBase1024.Encode(TEncoding.Unicode.GetBytes(data));
end;
7:
begin
result := uBase4096.Encode(TEncoding.Unicode.GetBytes(data));
end;
8:
begin
result := uZBase32.Encode(TEncoding.Unicode.GetBytes(data));
end;
9:
begin
result := uBaseN.Encode(TEncoding.Unicode.GetBytes(data),
Form1.SpinEdit3.Value, Form1.CheckBox3.Checked);
end;
else
begin
raise Exception.Create('Invalid Base Selection');
end;
end;
end;
5:
begin
case BasetoUse of
0:
begin
result := uBase32.Encode(TEncoding.UTF7.GetBytes(data));
end;
1:
begin
result := uBase64.Encode(TEncoding.UTF7.GetBytes(data));
end;
2:
begin
result := uBase85.Encode(TEncoding.UTF7.GetBytes(data),
PrefixPostfix);
end;
3:
begin
result := uBase91.Encode(TEncoding.UTF7.GetBytes(data));
end;
4:
begin
result := uBase128.Encode(TEncoding.UTF7.GetBytes(data));
end;
5:
begin
result := uBase256.Encode(TEncoding.UTF7.GetBytes(data));
end;
6:
begin
result := uBase1024.Encode(TEncoding.UTF7.GetBytes(data));
end;
7:
begin
result := uBase4096.Encode(TEncoding.UTF7.GetBytes(data));
end;
8:
begin
result := uZBase32.Encode(TEncoding.UTF7.GetBytes(data));
end;
9:
begin
result := uBaseN.Encode(TEncoding.UTF7.GetBytes(data),
Form1.SpinEdit3.Value, Form1.CheckBox3.Checked);
end;
else
begin
raise Exception.Create('Invalid Base Selection');
end;
end;
end;
6:
begin
case BasetoUse of
0:
begin
result := uBase32.Encode(TEncoding.UTF8.GetBytes(data));
end;
1:
begin
result := uBase64.Encode(TEncoding.UTF8.GetBytes(data));
end;
2:
begin
result := uBase85.Encode(TEncoding.UTF8.GetBytes(data),
PrefixPostfix);
end;
3:
begin
result := uBase91.Encode(TEncoding.UTF8.GetBytes(data));
end;
4:
begin
result := uBase128.Encode(TEncoding.UTF8.GetBytes(data));
end;
5:
begin
result := uBase256.Encode(TEncoding.UTF8.GetBytes(data));
end;
6:
begin
result := uBase1024.Encode(TEncoding.UTF8.GetBytes(data));
end;
7:
begin
result := uBase4096.Encode(TEncoding.UTF8.GetBytes(data));
end;
8:
begin
result := uZBase32.Encode(TEncoding.UTF8.GetBytes(data));
end;
9:
begin
result := uBaseN.Encode(TEncoding.UTF8.GetBytes(data),
Form1.SpinEdit3.Value, Form1.CheckBox3.Checked);
end;
else
begin
raise Exception.Create('Invalid Base Selection');
end;
end;
end;
else
begin
raise Exception.Create('Invalid Encoding Selection');
end;
end;
end;
function DecodeToString(data: String; Encoding, BasetoUse: Integer;
PrefixPostfix: Boolean): String;
begin
data := StringReplace(data, sLineBreak, '', [rfReplaceAll]);
case Encoding of
0:
begin
case BasetoUse of
0:
begin
result := TEncoding.ANSI.GetString(uBase32.Decode(data));
end;
1:
begin
result := TEncoding.ANSI.GetString(uBase64.Decode(data));
end;
2:
begin
result := TEncoding.ANSI.GetString
(uBase85.Decode(data, PrefixPostfix));
end;
3:
begin
result := TEncoding.ANSI.GetString(uBase91.Decode(data));
end;
4:
begin
result := TEncoding.ANSI.GetString(uBase128.Decode(data));
end;
5:
begin
result := TEncoding.ANSI.GetString(uBase256.Decode(data));
end;
6:
begin
result := TEncoding.ANSI.GetString(uBase1024.Decode(data));
end;
7:
begin
result := TEncoding.ANSI.GetString(uBase4096.Decode(data));
end;
8:
begin
result := TEncoding.ANSI.GetString(uZBase32.Decode(data));
end;
9:
begin
result := TEncoding.ANSI.GetString
(uBaseN.Decode((data), Form1.SpinEdit3.Value,
Form1.CheckBox3.Checked));
end;
else
begin
raise Exception.Create('Invalid Base Selection');
end;
end;
end;
1:
begin
case BasetoUse of
0:
begin
result := TEncoding.ASCII.GetString(uBase32.Decode(data));
end;
1:
begin
result := TEncoding.ASCII.GetString(uBase64.Decode(data));
end;
2:
begin
result := TEncoding.ASCII.GetString
(uBase85.Decode(data, PrefixPostfix));
end;
3:
begin
result := TEncoding.ASCII.GetString(uBase91.Decode(data));
end;
4:
begin
result := TEncoding.ASCII.GetString(uBase128.Decode(data));
end;
5:
begin
result := TEncoding.ASCII.GetString(uBase256.Decode(data));
end;
6:
begin
result := TEncoding.ASCII.GetString(uBase1024.Decode(data));
end;
7:
begin
result := TEncoding.ASCII.GetString(uBase4096.Decode(data));
end;
8:
begin
result := TEncoding.ASCII.GetString(uZBase32.Decode(data));
end;
9:
begin
result := TEncoding.ASCII.GetString
(uBaseN.Decode((data), Form1.SpinEdit3.Value,
Form1.CheckBox3.Checked));
end;
else
begin
raise Exception.Create('Invalid Base Selection');
end;
end;
end;
2:
begin
case BasetoUse of
0:
begin
result := TEncoding.BigEndianUnicode.GetString
(uBase32.Decode(data));
end;
1:
begin
result := TEncoding.BigEndianUnicode.GetString
(uBase64.Decode(data));
end;
2:
begin
result := TEncoding.BigEndianUnicode.GetString
(uBase85.Decode(data, PrefixPostfix));
end;
3:
begin
result := TEncoding.BigEndianUnicode.GetString
(uBase91.Decode(data));
end;
4:
begin
result := TEncoding.BigEndianUnicode.GetString
(uBase128.Decode(data));
end;
5:
begin
result := TEncoding.BigEndianUnicode.GetString
(uBase256.Decode(data));
end;
6:
begin
result := TEncoding.BigEndianUnicode.GetString
(uBase1024.Decode(data));
end;
7:
begin
result := TEncoding.BigEndianUnicode.GetString
(uBase4096.Decode(data));
end;
8:
begin
result := TEncoding.BigEndianUnicode.GetString
(uZBase32.Decode(data));
end;
9:
begin
result := TEncoding.BigEndianUnicode.GetString
(uBaseN.Decode((data), Form1.SpinEdit3.Value,
Form1.CheckBox3.Checked));
end;
else
begin
raise Exception.Create('Invalid Base Selection');
end;
end;
end;
3:
begin
case BasetoUse of
0:
begin
result := TEncoding.Default.GetString(uBase32.Decode(data));
end;
1:
begin
result := TEncoding.Default.GetString(uBase64.Decode(data));
end;
2:
begin
result := TEncoding.
Default.GetString(uBase85.Decode(data, PrefixPostfix));
end;
3:
begin
result := TEncoding.Default.GetString(uBase91.Decode(data));
end;
4:
begin
result := TEncoding.Default.GetString(uBase128.Decode(data));
end;
5:
begin
result := TEncoding.Default.GetString(uBase256.Decode(data));
end;
6:
begin
result := TEncoding.Default.GetString(uBase1024.Decode(data));
end;
7:
begin
result := TEncoding.Default.GetString(uBase4096.Decode(data));
end;
8:
begin
result := TEncoding.Default.GetString(uZBase32.Decode(data));
end;
9:
begin
result := TEncoding.
Default.GetString(uBaseN.Decode((data), Form1.SpinEdit3.Value,
Form1.CheckBox3.Checked));
end;
else
begin
raise Exception.Create('Invalid Base Selection');
end;
end;
end;
4:
begin
case BasetoUse of
0:
begin
result := TEncoding.Unicode.GetString(uBase32.Decode(data));
end;
1:
begin
result := TEncoding.Unicode.GetString(uBase64.Decode(data));
end;
2:
begin
result := TEncoding.Unicode.GetString
(uBase85.Decode(data, PrefixPostfix));
end;
3:
begin
result := TEncoding.Unicode.GetString(uBase91.Decode(data));
end;
4:
begin
result := TEncoding.Unicode.GetString(uBase128.Decode(data));
end;
5:
begin
result := TEncoding.Unicode.GetString(uBase256.Decode(data));
end;
6:
begin
result := TEncoding.Unicode.GetString(uBase1024.Decode(data));
end;
7:
begin
result := TEncoding.Unicode.GetString(uBase4096.Decode(data));
end;
8:
begin
result := TEncoding.Unicode.GetString(uZBase32.Decode(data));
end;
9:
begin
result := TEncoding.Unicode.GetString
(uBaseN.Decode((data), Form1.SpinEdit3.Value,
Form1.CheckBox3.Checked));
end;
else
begin
raise Exception.Create('Invalid Base Selection');
end;
end;
end;
5:
begin
case BasetoUse of
0:
begin
result := TEncoding.UTF7.GetString(uBase32.Decode(data));
end;
1:
begin
result := TEncoding.UTF7.GetString(uBase64.Decode(data));
end;
2:
begin
result := TEncoding.UTF7.GetString
(uBase85.Decode(data, PrefixPostfix));
end;
3:
begin
result := TEncoding.UTF7.GetString(uBase91.Decode(data));
end;
4:
begin
result := TEncoding.UTF7.GetString(uBase128.Decode(data));
end;
5:
begin
result := TEncoding.UTF7.GetString(uBase256.Decode(data));
end;
6:
begin
result := TEncoding.UTF7.GetString(uBase1024.Decode(data));
end;
7:
begin
result := TEncoding.UTF7.GetString(uBase4096.Decode(data));
end;
8:
begin
result := TEncoding.UTF7.GetString(uZBase32.Decode(data));
end;
9:
begin
result := TEncoding.UTF7.GetString
(uBaseN.Decode((data), Form1.SpinEdit3.Value,
Form1.CheckBox3.Checked));
end;
else
begin
raise Exception.Create('Invalid Base Selection');
end;
end;
end;
6:
begin
case BasetoUse of
0:
begin
result := TEncoding.UTF8.GetString(uBase32.Decode(data));
end;
1:
begin
result := TEncoding.UTF8.GetString(uBase64.Decode(data));
end;
2:
begin
result := TEncoding.UTF8.GetString
(uBase85.Decode(data, PrefixPostfix));
end;
3:
begin
result := TEncoding.UTF8.GetString(uBase91.Decode(data));
end;
4:
begin
result := TEncoding.UTF8.GetString(uBase128.Decode(data));
end;
5:
begin
result := TEncoding.UTF8.GetString(uBase256.Decode(data));
end;
6:
begin
result := TEncoding.UTF8.GetString(uBase1024.Decode(data));
end;
7:
begin
result := TEncoding.UTF8.GetString(uBase4096.Decode(data));
end;
8:
begin
result := TEncoding.UTF8.GetString(uZBase32.Decode(data));
end;
9:
begin
result := TEncoding.UTF8.GetString
(uBaseN.Decode((data), Form1.SpinEdit3.Value,
Form1.CheckBox3.Checked));
end;
else
begin
raise Exception.Create('Invalid Base Selection');
end;
end;
end;
else
begin
raise Exception.Create('Invalid Encoding Selection');
end;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
GenerateInputText;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
stopwatch: TStopwatch;
FormatSettings: TFormatSettings;
InString, Value: String;
elapsedMilliseconds: Int64;
begin
if Form1.SpinEdit2.Value = 0 then
begin
Form1.SpinEdit2.Value := 2;
end;
if Form1.SpinEdit3.Value = 0 then
begin
Form1.SpinEdit3.Value := 64;
end;
if (Length(Form1.Memo3.Text) < Form1.SpinEdit2.Value) or
(Length(Form1.Memo3.Text) > Form1.SpinEdit2.Value) then
begin
Form1.Memo3.Text := GetAlphabet(Form1.SpinEdit2.Value);
end;
tempStr := Form1.Memo3.Text;
CustomDisplayCalculations;
try
Form1.Memo2.Clear;
Form1.Edit5.Text := InttoStr(Length(Form1.Memo2.Text));
InString := Form1.Memo1.Text;
FormatSettings := TFormatSettings.Create;
stopwatch := TStopwatch.Create;
try
stopwatch.Start;
Value := EncodeString(InString, Form1.ComboBox3.ItemIndex,
Form1.ComboBox2.ItemIndex, Form1.CheckBox2.Checked);
stopwatch.Stop;
elapsedMilliseconds := stopwatch.elapsedMilliseconds;
finally
stopwatch.Free;
end;
Form1.Memo2.Text := Value;
Form1.Edit6.Text := FormatDateTime('hh:nn:ss:zzz',
MillisecondstoTDateTime(elapsedMilliseconds), FormatSettings);
except
on E: Exception do
Application.MessageBox(PChar(E.Message), 'Error', MB_OK);
end;
end;
procedure TForm1.Button3Click(Sender: TObject);
var
stopwatch: TStopwatch;
FormatSettings: TFormatSettings;
InString, Value: String;
elapsedMilliseconds: Int64;
begin
if Form1.SpinEdit2.Value = 0 then
begin
Form1.SpinEdit2.Value := 2;
end;
if Form1.SpinEdit3.Value = 0 then
begin
Form1.SpinEdit3.Value := 64;
end;
if (Length(Form1.Memo3.Text) < Form1.SpinEdit2.Value) or
(Length(Form1.Memo3.Text) > Form1.SpinEdit2.Value) then
begin
Form1.Memo3.Text := GetAlphabet(Form1.SpinEdit2.Value);
end;
tempStr := Form1.Memo3.Text;
CustomDisplayCalculations;
try
Form1.Memo2.Clear;
Form1.Edit5.Text := InttoStr(Length(Form1.Memo2.Text));
InString := Form1.Memo1.Text;
FormatSettings := TFormatSettings.Create;
stopwatch := TStopwatch.Create;
try
stopwatch.Start;
Value := DecodeToString(InString, Form1.ComboBox3.ItemIndex,
Form1.ComboBox2.ItemIndex, Form1.CheckBox2.Checked);
stopwatch.Stop;
elapsedMilliseconds := stopwatch.elapsedMilliseconds;
finally
stopwatch.Free;
end;
Form1.Memo2.Text := Value;
Form1.Edit6.Text := FormatDateTime('hh:nn:ss:zzz',
MillisecondstoTDateTime(elapsedMilliseconds), FormatSettings);
except
on E: Exception do
Application.MessageBox(PChar(E.Message), 'Error', MB_OK);
end;
end;
procedure TForm1.Button4Click(Sender: TObject);
begin
SwapInputOuput;
end;
procedure TForm1.Button6Click(Sender: TObject);
begin
if Form1.SpinEdit2.Value = 0 then
begin
Form1.SpinEdit2.Value := 2;
end;
if Form1.SpinEdit3.Value = 0 then
begin
Form1.SpinEdit3.Value := 64;
end;
Form1.Memo3.Text := GetAlphabet(Form1.SpinEdit2.Value);
DisplayCalculations;
end;
procedure TForm1.ComboBox1Change(Sender: TObject);
begin
Form1.Memo1.Text := ComboOneChange(Form1.ComboBox1.ItemIndex);
ValuestoDisplay;
Form1.Memo2.Clear;
end;
procedure TForm1.ComboBox2Change(Sender: TObject);
begin
ComboTwoChange;
ValuestoDisplay;
Form1.Memo1.Text := ComboOneChange(Form1.ComboBox1.ItemIndex);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
ClearMemo;
Form1.Memo1.Text := ComboOneChange(Form1.ComboBox1.ItemIndex);
Form1.SpinEdit2.Value := BaseDeriver(Form1.ComboBox2.ItemIndex);
DisplayCalculations;
end;
procedure TForm1.Memo1Change(Sender: TObject);
begin
ValuestoDisplay;
end;
procedure TForm1.Memo1KeyPress(Sender: TObject; var Key: Char);
begin
if Key = ^A then
Form1.Memo1.SelectAll;
end;
procedure TForm1.Memo2Change(Sender: TObject);
begin
ValuestoDisplay;
end;
procedure TForm1.Memo2KeyPress(Sender: TObject; var Key: Char);
begin
if Key = ^A then
Form1.Memo2.SelectAll;
end;
procedure TForm1.Memo3KeyPress(Sender: TObject; var Key: Char);
begin
if Key = ^A then
Form1.Memo3.SelectAll;
end;
end.
|
unit TestUInquilinoUnidadeController;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, UCondominioVO, SysUtils, Generics.Collections, DBXJSON, UPessoasVO,
UCondominioController, DBXCommon, DBClient, Classes, UController, UInquilinoUnidadeVO,
DB, UInquilinoUnidadeController, ConexaoBD, SQLExpr;
type
// Test methods for class TInquilinoUnidadeController
TestTInquilinoUnidadeController = class(TTestCase)
strict private
FInquilinoUnidadeController: TInquilinoUnidadeController;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestConsultarPorId;
end;
implementation
procedure TestTInquilinoUnidadeController.SetUp;
begin
FInquilinoUnidadeController := TInquilinoUnidadeController.Create;
end;
procedure TestTInquilinoUnidadeController.TearDown;
begin
FInquilinoUnidadeController.Free;
FInquilinoUnidadeController := nil;
end;
procedure TestTInquilinoUnidadeController.TestConsultarPorId;
var
ReturnValue: TInquilinoUnidadeVO;
// id: Integer;
begin
ReturnValue := FInquilinoUnidadeController.ConsultarPorId(8);
if(returnvalue <> nil) then
begin
check(true,'Inquilino pesquisado com sucesso!');
end
else
check(true,'Inquilino não encontrado!');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTInquilinoUnidadeController.Suite);
end.
|
unit URepositorioGrupoProduto;
interface
uses
UGrupoProduto
, UFamiliaProduto
, UEntidade
, URepositorioDB
, SqlExpr
, URepositorioFamiliaProduto
;
type
TRepositorioGRUPOPRODUTO = class (TRepositorioDB<TGrupoProduto>)
private
FRepositorioFamiliaProduto : TRepositorioFAMILIAPRODUTO;
public
constructor Create;
destructor Destroy; override;
procedure AtribuiDBParaEntidade(const coGrupoProduto : TGrupoProduto); override;
procedure AtribuiEntidadeParaDB(const coGrupoProduto : TGrupoProduto;
const coSQLQuery : TSQLQuery); override;
end;
implementation
uses
UDM
, SysUtils
;
{ TRepositoriogrupoProduto }
procedure TRepositorioGrupoProduto.AtribuiDBParaEntidade(const coGrupoProduto: TGrupoProduto);
begin
inherited;
with FSQLSelect do
begin
coGrupoProduto.NOMEGRUPO := FieldByName(FLD_GrupoProduto_NOMEGRUPO).AsString;
coGrupoProduto.FAMILIA_PRODUTO := TFamiliaProduto(
FRepositorioFamiliaProduto.Retorna(FieldByName(FLD_GRUPOPRODUTO_ID_FAMILIA_PRODUTO).AsInteger));
end;
end;
procedure TRepositorioGrupoProduto.AtribuiEntidadeParaDB(const coGrupoProduto: TGrupoProduto;
const coSQLQuery: TSQLQuery);
begin
inherited;
with coSQLQuery do
begin
ParamByName(FLD_GrupoProduto_NOMEGRUPO).AsString := coGrupoProduto.NOMEGRUPO;
ParamByName(FLD_GRUPOPRODUTO_ID_FAMILIA_PRODUTO).AsInteger := coGrupoProduto.FAMILIA_PRODUTO.ID;
end;
end;
constructor TRepositorioGrupoProduto.Create;
begin
inherited Create(TGrupoProduto, TBL_GrupoProduto, FLD_ENTIDADE_ID, STR_GrupoProduto);
FRepositorioFamiliaProduto := TRepositorioFAMILIAPRODUTO.Create;
end;
destructor TRepositorioGRUPOPRODUTO.Destroy;
begin
FreeAndNil(FRepositorioFamiliaProduto);
inherited;
end;
end.
|
unit &Assembler.Global;
interface
type
TNumberScale = (nsNo, nsBy2, nsBy4, nsBy8);
TAddrSize = (msByte = 1, msWord = 2, msDWord = 4);
TCmdPrefix = (cpRegSize = $66, // Overrides operand size (eax -> ax)
cpAddrSize = $67, // Overrides address size
cpWait = $9B, // wait
cpLock = $F0, // lock
cpRep = $F2, // rep
cpRepNZ = $F3); // repne
TRegIndex = (rEax, rEcx, rEdx, rEbx, rEsp, rEbp, rEsi, rEdi);
TReg64Index = (rRax, rRcx, rRdx, rRbx, rRsp, rRbp, rRsi, rRdi,
r8, r9, r10, r11, r12, r13, r14, r15);
TAddressingType = (atIndirAddr, // 00b
atBaseAddr8B, // 01b
atBaseAddr32B, // 10b (16B for 16-bit OS)
atRegisters); // 11b
// SIB – Scale Index Base
// If you specify the same index and base, one register is going to be used.
// TAddressingType.atRegisters doesn't need SIB byte.
TSIBInfo = packed record
Scale: TNumberScale; // 00b
Index: TRegIndex; // 000b
Base: TRegIndex; // 000b
end;
TRMInfo = packed record
IsBase: Boolean; // 0b
B1: Boolean; // 0b
B2: Boolean; // 0b
end;
// "/0" - opcode's expansion due to Reg field in ModR/M byte.
// "/r" - Registers are used in ModR/M.
// ref.x86asm.net
// o (register/opcode field) - RegFrom value (manually sets via TRegIndex)
TModRMInfo = packed record
Addr: TAddressingType; // 00b
FReg: TRegIndex; //000b
case Integer of // 000b
1: (SReg: TRegIndex);
2: (Memory: TRMInfo); // Integer = 101b
end;
TJumpType = (jtJo, jtJno,
jtJb, jtJnb,
jtJz, jtJnz,
jtJa, jtJna,
jtJs, jtJns,
jtJp, jtJnp,
jtJl, jtJnl,
jtJg, jtJng,
jtJmp);
TCondition = (cOverflow, cNotOverflow,
cBelow, cNotBelow,
cZero, cNotZero,
cAbove, cNotAbove,
cSign, cNotSign,
cParity, cNotParity,
cLess, cNotLess,
cNotGreater, cGreater);
const
REG_x32_COUNT = SizeOf(TRegIndex);
REG_x64_COUNT = SizeOf(TReg64Index);
implementation
end.
|
unit uUserButton;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, Registry, ActnList;
type
TfrmChangeUserAction = class(TForm)
OkButton: TBitBtn;
CancelButton: TBitBtn;
Label1: TLabel;
ActionsListBox: TListBox;
procedure OkButtonClick(Sender: TObject);
procedure ActionsListBoxDblClick(Sender: TObject);
private
Button: TButton;
ActList: TActionList;
public
constructor Create(AOwner: TComponent; Button: TButton; ActList: TActionList);
reintroduce;
end;
procedure LoadUserButton(Button: TButton; ActList: TActionList);
procedure SetUserButtonAction(Button: TButton; ActList: TActionList);
var
frmChangeUserAction: TfrmChangeUserAction;
implementation
constructor TfrmChangeUserAction.
Create(AOwner: TComponent; Button: TButton; ActList: TActionList);
var
i: Integer;
begin
inherited Create(AOwner);
Self.Button := Button;
Self.ActList := ActList;
for i := 0 to ActList.ActionCount - 1 do
if ActList.Actions[i] is TAction then
if ActList.Actions[i].Category = 'Exec' then
ActionsListBox.Items.Add((ActList.Actions[i] as TAction).Caption);
ActionsListBox.ItemIndex := 0;
end;
procedure SetUserButtonAction(Button: TButton; ActList: TActionList);
var
form: TfrmChangeUserAction;
begin
form := TfrmChangeUserAction.Create(nil, Button, ActList);
form.ShowModal;
form.Free;
end;
procedure LoadUserButton(Button: TButton; ActList: TActionList);
var
reg: TRegistry;
action: string;
i: Integer;
begin
reg := TRegistry.Create;
try
reg.RootKey := HKEY_CURRENT_USER;
if reg.OpenKey('\Software\ASUP\UserButtons\' + Button.Name, False) then
begin
try
action := reg.ReadString('Action');
with ActList do
for i := 0 to ActionCount - 1 do
if Actions[i].Name = action then
Button.Action := Actions[i];
except
end;
end;
reg.CloseKey;
finally
reg.Free;
end;
end;
{$R *.dfm}
procedure TfrmChangeUserAction.OkButtonClick(Sender: TObject);
var
i: Integer;
action: string;
reg: TRegistry;
begin
action := '';
for i := 0 to ActList.ActionCount - 1 do
if ActList.Actions[i] is TAction then
if ActList.Actions[i].Category = 'Exec' then
with ActList.Actions[i] as TAction do
if Caption = ActionsListBox.Items[ActionsListBox.ItemIndex] then
action := Name;
reg := TRegistry.Create;
try
reg.RootKey := HKEY_CURRENT_USER;
if reg.OpenKey('\Software\ASUP\UserButtons\' + Button.Name, True) then
begin
reg.WriteString('Action', action);
reg.CloseKey;
end
finally
reg.Free;
end;
Close;
end;
procedure TfrmChangeUserAction.ActionsListBoxDblClick(Sender: TObject);
begin
OkButton.Click;
end;
end.
|
unit uSintegraFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit,
DB, cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,
ExtCtrls, cxLookAndFeelPainters, StdCtrls, cxButtons, cxContainer,
cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, ComCtrls, DBClient;
const
REGISTRO_50 = '50';
type
TSintegra = class
private
FFileName: String;
FTextFile: TextFile;
FFirstDate: TDateTime;
FLastDate: TDateTime;
FAccord: String;
FNatureOperation: String;
FPurpose: String;
FCompanyCGC: String;
FCompanyIE: String;
FTotalReg50: Integer;
FTotalReg51: Integer;
FTotalReg54: Integer;
FTotalReg60: Integer;
FTotalReg70: Integer;
FTotalReg75: Integer;
FTotalReg90: Integer;
procedure LoadCompanyProperties;
procedure GenerateReg10;
procedure GenerateReg11;
procedure GenerateReg50;
procedure GenerateReg51;
procedure GenerateReg54;
procedure GenerateReg60;
procedure GenerateReg70;
procedure GenerateReg75;
procedure GenerateReg90;
function GetRegDate(ADate: TDateTime): String;
function BrancoF(s: String; n: Integer): String;
function Espacos(quantos: Integer): String;
public
constructor Create;
procedure GenerateFile;
function CanGenerateFile: Boolean;
property TextFile: TextFile read FTextFile write FTextFile;
property FirstDate: TDateTime read FFirstDate write FFirstDate;
property LastDate: TDateTime read FLastDate write FLastDate;
property Accord: String read FAccord write FAccord;
property NatureOperation: String read FNatureOperation write FNatureOperation;
property Purpose: String read FPurpose write FPurpose;
end;
TSintegraFrm = class(TForm)
pnlBottom: TPanel;
dsPurchase: TDataSource;
btnClose: TcxButton;
pnlFilter: TPanel;
edtFirstDate: TcxDateEdit;
edtLastDate: TcxDateEdit;
Label1: TLabel;
Label2: TLabel;
btnGo: TcxButton;
dsSale: TDataSource;
btnOk: TcxButton;
PageControl: TPageControl;
TabSheet: TTabSheet;
TabSheet1: TTabSheet;
grdPurchase: TcxGrid;
grdPurchaseDBTableView: TcxGridDBTableView;
grdPurchaseLevel: TcxGridLevel;
grdSale: TcxGrid;
grdSaleDBTableView: TcxGridDBTableView;
grdSaleLevel: TcxGridLevel;
TabSheet2: TTabSheet;
TabSheet3: TTabSheet;
cbxConvenio: TcxComboBox;
Label3: TLabel;
cbxNatOperacao: TcxComboBox;
Label4: TLabel;
cbxFinalidade: TcxComboBox;
Label5: TLabel;
grdProduto: TcxGrid;
grdProdutoDBTV: TcxGridDBTableView;
grdProdutoLevel: TcxGridLevel;
ds60R: TDataSource;
grdReducaoZ: TcxGrid;
grdReducaoZTableView: TcxGridDBTableView;
grdReducaoZLevel: TcxGridLevel;
dsReducaoZ: TDataSource;
grdPurchaseDBTableViewCodFornecedor: TcxGridDBColumn;
grdPurchaseDBTableViewCodProduto: TcxGridDBColumn;
grdPurchaseDBTableViewQtd: TcxGridDBColumn;
grdPurchaseDBTableViewValorTotal: TcxGridDBColumn;
grdPurchaseDBTableViewValorImposto: TcxGridDBColumn;
grdPurchaseDBTableViewPercImposto: TcxGridDBColumn;
grdPurchaseDBTableViewFrete: TcxGridDBColumn;
grdPurchaseDBTableViewOutrosCustos: TcxGridDBColumn;
grdPurchaseDBTableViewNovoCusto: TcxGridDBColumn;
grdPurchaseDBTableViewTipo: TcxGridDBColumn;
grdPurchaseDBTableViewNotaFiscal: TcxGridDBColumn;
grdPurchaseDBTableViewDataRegistro: TcxGridDBColumn;
grdPurchaseDBTableViewDataFatura: TcxGridDBColumn;
grdPurchaseDBTableViewCFOP: TcxGridDBColumn;
grdPurchaseDBTableViewCNPJ: TcxGridDBColumn;
grdPurchaseDBTableViewInscEstadual: TcxGridDBColumn;
grdPurchaseDBTableViewGrupoFornecido: TcxGridDBColumn;
grdPurchaseDBTableViewUF: TcxGridDBColumn;
grdPurchaseDBTableViewFornecedor: TcxGridDBColumn;
grdPurchaseDBTableViewProduto: TcxGridDBColumn;
grdPurchaseDBTableViewCF: TcxGridDBColumn;
grdSaleDBTableViewCodFornecedor: TcxGridDBColumn;
grdSaleDBTableViewCFOP: TcxGridDBColumn;
grdSaleDBTableViewCodProduto: TcxGridDBColumn;
grdSaleDBTableViewQtd: TcxGridDBColumn;
grdSaleDBTableViewValorTotal: TcxGridDBColumn;
grdSaleDBTableViewValorImposto: TcxGridDBColumn;
grdSaleDBTableViewPercImposto: TcxGridDBColumn;
grdSaleDBTableViewFrete: TcxGridDBColumn;
grdSaleDBTableViewOutrosCustos: TcxGridDBColumn;
grdSaleDBTableViewNovoCusto: TcxGridDBColumn;
grdSaleDBTableViewNotaFiscal: TcxGridDBColumn;
grdSaleDBTableViewDataRegistro: TcxGridDBColumn;
grdSaleDBTableViewDataFatura: TcxGridDBColumn;
grdSaleDBTableViewCPF: TcxGridDBColumn;
grdSaleDBTableViewInscEstadual: TcxGridDBColumn;
grdSaleDBTableViewGrupoFornecido: TcxGridDBColumn;
grdSaleDBTableViewUF: TcxGridDBColumn;
grdSaleDBTableViewCliente: TcxGridDBColumn;
grdSaleDBTableViewProduto: TcxGridDBColumn;
grdSaleDBTableViewCF: TcxGridDBColumn;
grdReducaoZTableViewNumeroECF: TcxGridDBColumn;
grdReducaoZTableViewNumeroSerie: TcxGridDBColumn;
grdReducaoZTableViewIDReducaoZ: TcxGridDBColumn;
grdReducaoZTableViewMovDate: TcxGridDBColumn;
grdReducaoZTableViewNumReducaoZ: TcxGridDBColumn;
grdReducaoZTableViewCOOInicial: TcxGridDBColumn;
grdReducaoZTableViewCOOFinal: TcxGridDBColumn;
grdReducaoZTableViewNumCancelamentos: TcxGridDBColumn;
grdReducaoZTableViewValCancelamentos: TcxGridDBColumn;
grdReducaoZTableViewValDescontos: TcxGridDBColumn;
grdReducaoZTableViewGTInicial: TcxGridDBColumn;
grdReducaoZTableViewGTFinal: TcxGridDBColumn;
grdReducaoZTableViewSubstituicaoTrib: TcxGridDBColumn;
grdReducaoZTableViewIsencao: TcxGridDBColumn;
grdProdutoDBTVCodigoProduto: TcxGridDBColumn;
grdProdutoDBTVProduto: TcxGridDBColumn;
grdProdutoDBTVQuantidade: TcxGridDBColumn;
grdProdutoDBTVValorTotal: TcxGridDBColumn;
grdProdutoDBTVPercImposto: TcxGridDBColumn;
grdProdutoDBTVUnidade: TcxGridDBColumn;
grdProdutoDBTVCF: TcxGridDBColumn;
grdReducaoZTableViewNaoTributavel: TcxGridDBColumn;
edtCFOP: TcxTextEdit;
Label6: TLabel;
pb: TProgressBar;
lbDisplay: TLabel;
procedure btnGoClick(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
private
procedure CarregarDados;
procedure CarregarEmpresa;
procedure CarregarCompras;
procedure CarregarNFCompras;
procedure CarregarProdCompras;
procedure CarregarNFVendas;
procedure EnableControls;
procedure DisableControls;
public
procedure Start;
end;
implementation
uses uDMSintegra, ADODB, DateUtils, uStringFunctions;
{$R *.dfm}
{ TSintegraFrm }
procedure TSintegraFrm.Start;
begin
edtFirstDate.Date := EncodeDate(YearOf(Now), MonthOf(Now), 1);
edtLastDate.Date := EncodeDate(YearOf(Now), MonthOf(Now), DaysInMonth(Now));
cbxConvenio.ItemIndex := 0;
cbxNatOperacao.ItemIndex := 2;
cbxFinalidade.ItemIndex := 0;
ShowModal;
end;
procedure TSintegraFrm.btnGoClick(Sender: TObject);
var
AFirstDate, ALastDate: TDateTime;
begin
AFirstDate := edtFirstDate.Date;
ALastDate := (edtLastDate.Date+1);
Screen.Cursor := crHourGlass;
try
with DMSintegra.quPurchase do
begin
if Active then
Close;
Parameters.ParamByName('FirstDate').Value := AFirstDate;
Parameters.ParamByName('LastDate').Value := ALastDate;
Open;
end;
with DMSintegra.quSale do
begin
if Active then
Close;
Parameters.ParamByName('FirstDate').Value := AFirstDate;
Parameters.ParamByName('LastDate').Value := ALastDate;
Open;
end;
with DMSintegra.cdsReducaoZ do
begin
if Active then
Close;
FetchParams;
Params.ParamByName('FirstDate').Value := AFirstDate;
Params.ParamByName('LastDate').Value := ALastDate;
Open;
end;
with DMSintegra.cdsTributacaoEcf do
begin
if Active then
Close;
FetchParams;
Params.ParamByName('FirstDate').Value := AFirstDate;
Params.ParamByName('LastDate').Value := ALastDate;
Open;
end;
with DMSintegra.qu60R do
begin
if Active then
Close;
Parameters.ParamByName('FirstDate').Value := AFirstDate;
Parameters.ParamByName('LastDate').Value := ALastDate;
Open;
end;
finally
btnOk.SetFocus;
Screen.Cursor := crDefault;
end;
end;
procedure TSintegraFrm.btnOkClick(Sender: TObject);
begin
Screen.Cursor := crHourGlass;
btnOk.Visible := False;
try
CarregarDados;
with TSintegra.Create do
try
if CanGenerateFile then
begin
DisableControls;
FirstDate := edtFirstDate.Date;
LastDate := edtLastDate.Date;
Accord := cbxConvenio.Text;
NatureOperation := cbxNatOperacao.Text;
Purpose := cbxFinalidade.Text;
GenerateFile;
ShowMessage('Arquivo Gerado com Sucesso !');
end;
finally
Free;
EnableControls;
end;
finally
Screen.Cursor := crDefault;
btnOk.Visible := True;
end;
end;
procedure TSintegraFrm.btnCloseClick(Sender: TObject);
begin
Close;
end;
procedure TSintegraFrm.CarregarCompras;
begin
DmSintegra.quPurchase.First;
pb.Visible := True;
pb.Position := 0;
pb.Max := DmSintegra.quPurchase.RecordCount;
lbDisplay.Caption := 'Gerando Compras ...';
Application.ProcessMessages;
try
while not DmSintegra.quPurchase.Eof do
begin
CarregarNFCompras;
CarregarProdCompras;
DmSintegra.quPurchase.Next;
lbDisplay.Caption := 'Gerando Compras ('+IntToStr(pb.Position)+ ' de ' + IntToStr(pb.Max) + ')...';
Application.ProcessMessages;
pb.StepIt;
end;
finally
pb.Visible := False;
lbDisplay.Caption := '';
end;
end;
procedure TSintegraFrm.CarregarNFVendas;
var
sCPF, sNF, sIE: String;
begin
with DMSintegra.quSale do
begin
First;
pb.Visible := True;
pb.Position := 0;
pb.Max := DmSintegra.quSale.RecordCount;
lbDisplay.Caption := 'Gerando Vendas ...';
while not Eof do
begin
sCPF := '00000000000000' + Trim(FieldByName('CPF').AsString);
sCPF := Copy(sCPF, Length(sCPF)-13, 14);
if FieldByName('InscEstadual').AsString = '' then
sIE := 'ISENTO'
else
sIE := Copy(FieldByName('InscEstadual').AsString, 1, 14);
sNF := StringReplace(FieldByName('NotaFiscal').AsString, '/', '', [rfReplaceAll]);
sNF := StringReplace(sNF, '-', '', [rfReplaceAll]);
sNF := StringReplace(sNF, '.', '', [rfReplaceAll]);
sNF := StringReplace(sNF, '(', '', [rfReplaceAll]);
sNF := StringReplace(sNF, ')', '', [rfReplaceAll]);
sNF := StringReplace(sNF, 'T', '', [rfReplaceAll]);
sNF := StringReplace(sNF, 'N', '', [rfReplaceAll]);
sNF := StringReplace(sNF, 'F', '', [rfReplaceAll]);
sNF := StringReplace(sNF, ' ', '', [rfReplaceAll]);
sNF := FormatFloat('000000', StrToFloat(sNF));
if DMSintegra.cdsSintegra.FindKey([REGISTRO_50, sCPF, StrToDate(Copy(FormatDateTime('ddddd', FieldByName('DataRegistro').AsDateTime), 1, 10)), sNF]) then
DMSintegra.cdsSintegra.Edit
else
begin
DMSintegra.cdsSintegra.Append;
DMSintegra.cdsSintegraALIQ.AsString := '00';
DMSintegra.cdsSintegraTIPO.AsString := REGISTRO_50;
DMSintegra.cdsSintegraCNPJ.AsString := sCPF;
DMSintegra.cdsSintegraIEST.AsString := sIE;
DMSintegra.cdsSintegraDATAREG.AsString := Copy(FormatDateTime('ddddd', FieldByName('DataRegistro').AsDateTime), 1, 10);
DMSintegra.cdsSintegraUF.AsString := FieldByName('Estado_UF').AsString;
DMSintegra.cdsSintegraRF.AsString := '01';
DMSintegra.cdsSintegraSERIE.AsString := '1 ';
DMSintegra.cdsSintegraDOC.AsString := sNF;
if (FieldByName('CFOP').AsString <> '') and (Length(FieldByName('CFOP').AsString) = 4) then
DMSintegra.cdsSintegraCFOP.AsString := FieldByName('CFOP').AsString
else
DMSintegra.cdsSintegraCFOP.AsString := edtCFOP.Text;
DMSintegra.cdsSintegraP_T.AsString := 'P';
DMSintegra.cdsSintegraS_N.AsString := 'N';
DMSintegra.cdsSintegraISENTO.AsString := FormatFloat('0.00', 0);
DMSintegra.cdsSintegraOUTRAS.AsString := FormatFloat('0.00', 0);
end;
DMSintegra.cdsSintegraCONTABIL.AsFloat := DMSintegra.cdsSintegraCONTABIL.AsFloat + FieldByName('ValorTotal').AsFloat;
DMSintegra.cdsSintegraBASE.AsFloat := DMSintegra.cdsSintegraBASE.AsFloat + FieldByName('ValorTotal').AsFloat;
DMSintegra.cdsSintegraIMPOSTO.AsFloat := DMSintegra.cdsSintegraIMPOSTO.AsFloat + FieldByName('ValorImposto').AsFloat;
if FieldByName('PercImposto').AsFloat <> 0 then
DMSintegra.cdsSintegraALIQ.asString := FormatFloat('00', FieldByName('PercImposto').AsFloat);
DMSintegra.cdsSintegra.Post;
pb.StepIt;
lbDisplay.Caption := 'Gerando Vendas ('+IntToStr(pb.Position)+ ' de ' + IntToStr(pb.Max) + ')...';
Application.ProcessMessages;
Next;
end;
pb.Visible := False;
lbDisplay.Caption := '';
end;
end;
procedure TSintegraFrm.CarregarNFCompras;
var
sNF: String;
begin
with DmSintegra.quPurchase do
begin
sNF := StringReplace(FieldByName('NotaFiscal').AsString, '/', '', [rfReplaceAll]);
sNF := StringReplace(sNF, '-', '', [rfReplaceAll]);
sNF := StringReplace(sNF, '.', '', [rfReplaceAll]);
sNF := FormatFloat('000000', StrToFloat(sNF));
if DMSintegra.cdsSintegra.FindKey([REGISTRO_50, FieldByName('CNPJ').AsString, FieldByName('DataRegistro').AsDateTime, sNF]) then
DMSintegra.cdsSintegra.Edit
else
begin
DMSintegra.cdsSintegra.Append;
DMSintegra.cdsSintegraTIPO.AsString := REGISTRO_50;
DMSintegra.cdsSintegraCNPJ.AsString := FieldByName('CNPJ').AsString;
DMSintegra.cdsSintegraIEST.AsString := FieldByName('InscEstadual').AsString;
DMSintegra.cdsSintegraDATAREG.AsDateTime := FieldByName('DataRegistro').AsDateTime;
DMSintegra.cdsSintegraUF.AsString := FieldByName('UF').AsString;
DMSintegra.cdsSintegraCFOP.AsString := FieldByName('CFOP').AsString;
DMSintegra.cdsSintegraCODFORNECEDOR.AsString := FieldByName('CodFornecedor').AsString;
DMSintegra.cdsSintegraDOC.AsString := sNF;
DMSintegra.cdsSintegraRF.AsString := '01';
DMSintegra.cdsSintegraSERIE.AsString := '1 ';
DMSintegra.cdsSintegraALIQ.AsString := '00';
DMSintegra.cdsSintegraP_T.AsString := 'T';
DMSintegra.cdsSintegraS_N.AsString := 'N';
end;
DMSintegra.cdsSintegraCONTABIL.AsFloat := DMSintegra.cdsSintegraCONTABIL.AsFloat + FieldByName('ValorTotal').AsFloat;
DMSintegra.cdsSintegraBASE.AsFloat := DMSintegra.cdsSintegraBASE.AsFloat + FieldByName('ValorTotal').AsFloat;
DMSintegra.cdsSintegraIMPOSTO.AsFloat := DMSintegra.cdsSintegraIMPOSTO.AsFloat + FieldByName('ValorImposto').AsFloat;
if FieldByName('CF').asString = '040' then
DMSintegra.cdsSintegraISENTO.AsFloat := DMSintegra.cdsSintegraISENTO.AsFloat + FieldByName('ValorTotal').AsFloat
else
DMSintegra.cdsSintegraOUTRAS.AsFloat := DMSintegra.cdsSintegraOUTRAS.AsFloat + FieldByName('ValorTotal').AsFloat;
DMSintegra.cdsSintegra.Post;
end;
end;
procedure TSintegraFrm.CarregarProdCompras;
begin
with DmSintegra.quPurchase do
begin
DMSintegra.cdsProdutoCompra.Append;
DMSintegra.cdsProdutoCompraNF.AsString := FormatFloat('000000', StrToFloat(DMSintegra.cdsSintegraDOC.AsString));
DMSintegra.cdsProdutoCompraCODFORNECEDOR.AsString := FieldByName('CodFornecedor').AsString;
if FieldByName('PercImposto').IsNull then
begin
DMSintegra.cdsProdutoCompraQUANTIDADE.AsString := FormatFloat('00000000000', FieldByName('Qtd').AsFloat * 1000);
DMSintegra.cdsProdutoCompraVALORTOTAL.AsString := FormatFloat('000000000000', FieldByName('ValorTotal').AsFloat * 100);
DMSintegra.cdsProdutoCompraALIQ.AsString := FormatFloat('0000', FieldByName('PercImposto').AsFloat * 100);
end
else
begin
DMSintegra.cdsProdutoCompraQUANTIDADE.AsString := FormatFloat('00000000000', FieldByName('Qtd').AsFloat * 1000);
DMSintegra.cdsProdutoCompraVALORTOTAL.AsString := FormatFloat('000000000000', FieldByName('ValorTotal').AsFloat * 100);
DMSintegra.cdsProdutoCompraALIQ.AsString := FormatFloat('0000', FieldByName('PercImposto').AsFloat * 100);
end;
DMSintegra.cdsProdutoCompraCODPRODUTO.AsString := FieldByName('CodProduto').AsString;
DMSintegra.cdsProdutoCompraDESCRICAO.AsString := FieldByName('PRODUTO').AsString;
DMSintegra.cdsProdutoCompraUNIDADE.AsString := FieldByName('TIPO').AsString;
DMSintegra.cdsProdutoCompraCFOP.AsString := FieldByName('CFOP').AsString;
DMSintegra.cdsProdutoCompraKSFI.AsString := FieldByName('CF').AsString;
DMSintegra.cdsProdutoCompraNRITEM.AsString := '000';
DMSintegra.cdsProdutoCompra.Post;
end;
end;
procedure TSintegraFrm.CarregarDados;
begin
DMSintegra.cdsSintegra.EmptyDataSet;
DMSintegra.cdsSintegra.IndexName := 'cdsSintegraIndex1';
CarregarEmpresa;
CarregarNFVendas;
CarregarCompras;
DMSintegra.cdsSintegra.IndexName := '';
DMSintegra.cdsSintegra.First;
end;
procedure TSintegraFrm.CarregarEmpresa;
begin
with DMSintegra.qryEmpresa do
begin
if Active then
Close;
Parameters.ParamByName('IDEmpresa').Value := DMSintegra.GetAppProperty('Settings', 'IDEmpresa');
Open;
end;
end;
procedure TSintegraFrm.DisableControls;
begin
dsPurchase.DataSet.DisableControls;
dsSale.DataSet.DisableControls;
ds60R.DataSet.DisableControls;
dsReducaoZ.DataSet.DisableControls;
end;
procedure TSintegraFrm.EnableControls;
begin
dsPurchase.DataSet.EnableControls;
dsSale.DataSet.EnableControls;
ds60R.DataSet.EnableControls;
dsReducaoZ.DataSet.EnableControls;
end;
{ TSintegra }
function TSintegra.BrancoF(s: String; n: Integer): String;
begin
s := s + Espacos(n);
result := Copy(s,1,n);
end;
function TSintegra.CanGenerateFile: Boolean;
begin
Result := True;
FFileName := DMSintegra.GetAppProperty('Settings', 'SintegraFileName');
if FileExists(FFileName) then
Result := MessageDlg('Arquivo ' + FFileName + ' já existe, Deseja substituir ?', mtConfirmation, [mbYes, mbNo], 0) = mrYes;
end;
constructor TSintegra.Create;
begin
FTotalReg50 := 0;
FTotalReg51 := 0;
FTotalReg54 := 0;
FTotalReg60 := 0;
FTotalReg70 := 0;
FTotalReg75 := 0;
FTotalReg90 := 0;
LoadCompanyProperties;
end;
function TSintegra.Espacos(quantos: Integer): String;
var
p: Integer;
retorna: String;
begin
retorna := '';
for p := 1 to quantos do begin
retorna := retorna + ' ';
end;
result := retorna;
end;
procedure TSintegra.GenerateFile;
begin
try
AssignFile(FTextFile, FFileName);
Rewrite(FTextFile);
GenerateReg10;
GenerateReg11;
GenerateReg50;
GenerateReg51;
GenerateReg54;
GenerateReg60;
GenerateReg70;
GenerateReg75;
GenerateReg90;
finally
CloseFile(FTextFile);
end;
end;
procedure TSintegra.GenerateReg10;
var
DET, sFAX: String;
begin
// Aqui montarei o registro 10
DET := '10';
DET := DET + FCompanyCGC;
DET := DET + FCompanyIE;
DET := DET + Copy(DMSintegra.qryEmpresaRazaoSocial.AsString + ' ', 1, 35);
DET := DET + Copy(DMSintegra.qryEmpresaCidade.AsString + ' ', 1, 30);
DET := DET + Trim(DMSintegra.qryEmpresaIDEstado.AsString);
sFAX := StringReplace(DMSintegra.qryEmpresaFax.AsString, '(', '', [rfReplaceAll]);
sFAX := StringReplace(sFAX, ')', '', [rfReplaceAll]);
sFAX := StringReplace(sFAX, '-', '', [rfReplaceAll]);
sFAX := StringReplace(sFAX, '.', '', [rfReplaceAll]);
sFAX := StringReplace(sFAX, '/', '', [rfReplaceAll]);
sFAX := FormatFloat('0000000000', StrToFloatDef(sFAX, 0));
DET := DET + sFAX;
DET := DET + GetRegDate(FFirstDate);
DET := DET + GetRegDate(FLastDate);
DET := DET + Copy(FAccord, 1, 1);
DET := DET + Copy(FNatureOperation, 1, 1);
DET := DET + Copy(FPurpose, 1, 1);
WriteLN(FTextFile, DET);
end;
procedure TSintegra.GenerateReg11;
var
DET, sTEL, sCEP: String;
begin
DET := '11';
DET := DET + BrancoF(DMSintegra.qryEmpresaEndereco.AsString, 34);
DET := DET + FormatFloat('00000', DMSintegra.qryEmpresaNumero.AsFloat);
DET := DET + BrancoF(DMSintegra.qryEmpresaCoplemento.AsString, 22);
DET := DET + BrancoF(DMSintegra.qryEmpresaBairro.AsString, 15);
sCEP := StringReplace(DMSintegra.qryEmpresaCEP.AsString, '-', '', [rfReplaceAll]);
sCEP := StringReplace(sCEP, '.', '', [rfReplaceAll]);
sCEP := FormatFloat('00000000', StrToFloatDef(sCEP, 0));
DET := DET + sCEP;
//DET := DET + BrancoF(DMSintegra.qryEmpresaContato.AsString, 28); //Bahia
DET := DET + BrancoF(DMSintegra.qryEmpresaContato.AsString, 28);
sTEL := StringReplace(DMSintegra.qryEmpresaTelefone.AsString, '(', '', [rfReplaceAll]);
sTEL := StringReplace(sTEL, ')', '', [rfReplaceAll]);
sTEL := StringReplace(sTEL, '-', '', [rfReplaceAll]);
sTEL := StringReplace(sTEL, '.', '', [rfReplaceAll]);
sTEL := StringReplace(sTEL, '/', '', [rfReplaceAll]);
sTEL := FormatFloat('000000000000', StrToFloatDef(sTEL, 0));
DET := DET + sTEL;
Writeln(FTextFile, DET);
end;
procedure TSintegra.GenerateReg50;
var
DET: String;
begin
DMSintegra.cdsSintegra.Filtered := False;
DMSintegra.cdsSintegra.Filter := 'TIPO = ' + QuotedStr('50');
DMSintegra.cdsSintegra.Filtered := True;
DMSintegra.cdsSintegra.First;
FTotalReg50 := 0;
while not DMSintegra.cdsSintegra.Eof do
begin
DET := DMSintegra.cdsSintegraTIPO.AsString;
DET := DET + DMSintegra.cdsSintegraCNPJ.AsString;
DET := DET + BrancoF(DMSintegra.cdsSintegraIEST.AsString, 14);
DET := DET + GetRegDate(DMSintegra.cdsSintegraDATAREG.value);
DET := DET + BrancoF(DMSintegra.cdsSintegraUF.AsString, 2);
DET := DET + DMSintegra.cdsSintegraRF.AsString;
DET := DET + BrancoF(DMSintegra.cdsSintegraSERIE.AsString, 3);
DET := DET + DMSintegra.cdsSintegraDOC.AsString;
DET := DET + DMSintegra.cdsSintegraCFOP.AsString;
DET := DET + 'P'; //P: Emissão Própria ou T: Emissão de terceiros
DET := DET + FormatFloat('0000000000000', ABS(Trunc(DMSintegra.cdsSintegraDATAREG.Value)));
DET := DET + FormatFloat('0000000000000', ABS(Trunc(DMSintegra.cdsSintegraBASE.Value)));
DET := DET + FormatFloat('0000000000000', ABS(Trunc(DMSintegra.cdsSintegraImposto.Value)));
DET := DET + FormatFloat('0000000000000', ABS(Trunc(DMSintegra.cdsSintegraISENTO.Value)));
DET := DET + FormatFloat('0000000000000', ABS(Trunc(DMSintegra.cdsSintegraOUTRAS.Value)));
DET := DET + FormatFloat('0000', ABS(StrToFloatDef(DMSintegra.cdsSintegraALIQ.AsString, 0)) * 100);
DET := DET + DMSintegra.cdsSintegraS_N.AsString;
WriteLN(FTextFile, DET);
FTotalReg50 := FTotalReg50 + 1;
DMSintegra.cdsSintegra.Next;
end;
DMSintegra.cdsSintegra.Filtered := False;
end;
procedure TSintegra.GenerateReg51;
var
DET: String;
begin
DMSintegra.cdsSintegra.Filtered := False;
DMSintegra.cdsSintegra.Filter := 'TIPO = ' + QuotedStr('51');
DMSintegra.cdsSintegra.Filtered := True;
DMSintegra.cdsSintegra.First;
FTotalReg51 := 0;
while not DMSintegra.cdsSintegra.Eof do
begin
DET := DMSintegra.cdsSintegraTIPO.AsString;
DET := DET + DMSintegra.cdsSintegraCNPJ.AsString;
DET := DET + BrancoF(DMSintegra.cdsSintegraIEST.AsString, 14);
DET := DET + GetRegDate(DMSintegra.cdsSintegraDATAREG.value);
DET := DET + DMSintegra.cdsSintegraUF.AsString;
DET := DET + DMSintegra.cdsSintegraRF.AsString;
DET := DET + BrancoF(DMSintegra.cdsSintegraSERIE.AsString, 3);
DET := DET + DMSintegra.cdsSintegraDOC.AsString;
DET := DET + DMSintegra.cdsSintegraCFOP.AsString;
DET := DET + 'T';
DET := DET + FormatFloat('0000000000000', DMSintegra.cdsSintegraDATAREG.Value);
DET := DET + FormatFloat('0000000000000', DMSintegra.cdsSintegraBASE.Value);
DET := DET + FormatFloat('0000000000000', DMSintegra.cdsSintegraImposto.Value);
DET := DET + FormatFloat('0000000000000', DMSintegra.cdsSintegraISENTO.Value);
DET := DET + FormatFloat('0000000000000', DMSintegra.cdsSintegraOUTRAS.Value);
DET := DET + FormatFloat('0000', StrToFloatDef(DMSintegra.cdsSintegraALIQ.AsString, 0) * 100);
DET := DET + DMSintegra.cdsSintegraS_N.AsString;
WriteLN(FTextFile, DET);
FTotalReg51 := FTotalReg51 + 1;
DMSintegra.cdsSintegra.Next;
end;
DMSintegra.cdsSintegra.Filtered := False;
end;
procedure TSintegra.GenerateReg54;
var
NrItem: Integer;
DET, DET54: String;
begin
FTotalReg54 := 0;
DMSintegra.cdsSintegra.First;
while not DMSintegra.cdsSintegra.Eof do
begin
NrItem := 0;
DET := DMSintegra.cdsSintegraTIPO.AsString;
DMSintegra.cdsProdutoCompra.FindNearest([DMSintegra.cdsSintegraDOC.AsString, DMSintegra.cdsSintegraCODFORNECEDOR.AsString]);
while not DMSintegra.cdsProdutoCompra.Eof do
begin
if DMSintegra.cdsProdutoCompraNF.AsString + Trim(DMSintegra.cdsProdutoCompraCODFORNECEDOR.AsString) <> DMSintegra.cdsSintegraDOC.AsString + Trim(DMSintegra.cdsSintegraCODFORNECEDOR.AsString) then
Break;
NrItem := NrItem + 1;
if DMSintegra.Virtual_Produtos.FindKey([DMSintegra.cdsProdutoCompraCODPRODUTO.AsString + ' ']) = False then
begin
DMSintegra.Virtual_Produtos.Append;
DMSintegra.Virtual_ProdutosCodigoProduto.AsString := DMSintegra.cdsProdutoCompraCODPRODUTO.AsString + ' ';
DMSintegra.Virtual_ProdutosDescricao.AsString := DMSintegra.cdsProdutoCompraDESCRICAO.AsString;
DMSintegra.Virtual_ProdutosAliquota.AsString := DMSintegra.cdsProdutoCompraALIQ.AsString;
DMSintegra.Virtual_ProdutosCF.AsString := DMSintegra.cdsProdutoCompraKSFI.AsString;
DMSintegra.Virtual_ProdutosUnidade.AsString := DMSintegra.cdsProdutoCompraUnidade.AsString;
if (DMSintegra.Virtual_ProdutosCF.AsString <> '000') and (DMSintegra.Virtual_ProdutosCF.AsString <> '040') and (DMSintegra.Virtual_ProdutosCF.AsString <> '090') then
DMSintegra.Virtual_ProdutosCF.AsString := '000';
DMSintegra.Virtual_Produtos.Post;
end;
DET54 := '54';
DET54 := DET54 + DMSintegra.cdsSintegraCNPJ.AsString;
DET54 := DET54 + DMSintegra.cdsSintegraRF.AsString;
DET54 := DET54 + '1 ';
DET54 := DET54 + DMSintegra.cdsProdutoCompraNF.AsString;
DET54 := DET54 + DMSintegra.cdsSintegraCFOP.AsString;
if DMSintegra.cdsProdutoCompraKSFI.AsString = '' then
DET54 := DET54 + '000'
else
DET54 := DET54 + DMSintegra.cdsProdutoCompraKSFI.AsString;
DET54 := DET54 + FormatFloat('000', NrItem);
DET54 := DET54 + Copy(DMSintegra.cdsProdutoCompraCodProduto.AsString + ' ', 1, 14);
DET54 := DET54 + DMSintegra.cdsProdutoCompraQuantidade.AsString;
DET54 := DET54 + DMSintegra.cdsProdutoCompraValorTotal.AsString;
DET54 := DET54 + '000000000000';
DET54 := DET54 + DMSintegra.cdsProdutoCompraValorTotal.AsString;
DET54 := DET54 + '000000000000';
DET54 := DET54 + '000000000000';
DET54 := DET54 + DMSintegra.cdsProdutoCompraAliq.AsString;
FTotalReg54 := FTotalReg54 + 1;
WriteLN(FTextFile, DET54);
DMSintegra.cdsProdutoCompra.Next;
end;
DMSintegra.cdsSintegra.Next;
end;
end;
procedure TSintegra.GenerateReg60;
var
YY, MM, DD: Word;
ConvData: TDate;
DET: String;
FTotal : Currency;
begin
// Aqui vamos gerar os ECF
FTotalReg60 := 0;
with DMSintegra do
begin
cdsReducaoZ.First;
while not cdsReducaoZ.Eof do
begin
ConvData := cdsReducaoZ.FieldByName('MovDate').AsDateTime;
DecodeDate(ConvData , YY, MM, DD);
DET := '60M';
DET := DET + FormatFloat('0000', YY) + FormatFloat('00', MM) + FormatFloat('00', DD);
DET := DET + cdsReducaoZ.FieldByName('NumeroSerie').AsString;
DET := DET + FormatFloat('000', cdsReducaoZ.FieldByName('NumeroECF').AsFloat);
DET := DET + '2C';
DET := DET + FormatFloat('000000', cdsReducaoZ.FieldByName('COOInicial').AsFloat);
DET := DET + FormatFloat('000000', cdsReducaoZ.FieldByName('COOFinal').AsFloat);
DET := DET + FormatFloat('000000', cdsReducaoZ.FieldByName('NumReducaoZ').AsFloat);
DET := DET + '001';
FTotal := (cdsReducaoZ.FieldByName('GTFinal').AsFloat - cdsReducaoZ.FieldByName('GTInicial').AsFloat);
DET := DET + FormatFloat('0000000000000000', FTotal * 100);
FTotal := cdsReducaoZ.FieldByName('GTFinal').AsFloat;
DET := DET + FormatFloat('0000000000000000', FTotal * 100);
DET := DET + ' ';
WriteLN(FTextFile, DET);
FTotalReg60 := FTotalReg60 + 1;
FTotal := cdsReducaoZ.FieldByName('SubstituicaoTrib').AsFloat;
if FTotal <> 0 then
begin
DET := '60A';
DET := DET + FormatFloat('0000', YY) + FormatFloat('00', MM) + FormatFloat('00', DD);
DET := DET + cdsReducaoZ.FieldByName('NumeroSerie').AsString;
DET := DET + 'F ';
DET := DET + FormatFloat('000000000000', FTotal * 100);
DET := DET + ' ';
WriteLN(FTextFile, DET);
FTotalReg60 := FTotalReg60 + 1;
end;
FTotal := cdsReducaoZ.FieldByName('Isencao').Value;
if FTotal <> 0 then
begin
DET := '60A';
DET := DET + FormatFloat('0000', YY) + FormatFloat('00', MM) + FormatFloat('00', DD);
DET := DET + cdsReducaoZ.FieldByName('NumeroSerie').AsString;
DET := DET + 'I ';
DET := DET + FormatFloat('000000000000', FTotal * 100);
DET := DET + ' ';
WriteLN(FTextFile, DET);
FTotalReg60 := FTotalReg60 + 1;
end;
FTotal := cdsReducaoZ.FieldByName('NaoTributavel').AsFloat;
if FTotal <> 0 then
begin
DET := '60A';
DET := DET + FormatFloat('0000', YY) + FormatFloat('00', MM) + FormatFloat('00', DD);
DET := DET + cdsReducaoZ.FieldByName('NumeroSerie').AsString;
DET := DET + 'N ';
DET := DET + FormatFloat('000000000000', FTotal * 100);
DET := DET + ' ';
WriteLN(FTextFile, DET);
FTotalReg60 := FTotalReg60 + 1;
end;
FTotal := cdsReducaoZ.FieldByName('ValDescontos').AsFloat;
if FTotal <> 0 then
begin
DET := '60A';
DET := DET + FormatFloat('0000', YY) + FormatFloat('00', MM) + FormatFloat('00', DD);
DET := DET + cdsReducaoZ.FieldByName('NumeroSerie').AsString;
DET := DET + 'CANC';
DET := DET + FormatFloat('000000000000', FTotal * 100);
DET := DET + ' ';
WriteLN(FTextFile, DET);
FTotalReg60 := FTotalReg60 + 1;
end;
FTotal := cdsReducaoZ.FieldByName('ValCancelamentos').AsFloat;
if FTotal <> 0 then
begin
DET := '60A';
DET := DET + FormatFloat('0000', YY) + FormatFloat('00', MM) + FormatFloat('00', DD);
DET := DET + cdsReducaoZ.FieldByName('NumeroSerie').AsString;
DET := DET + 'DESC';
DET := DET + FormatFloat('000000000000', FTotal * 100);
DET := DET + ' ';
WriteLN(FTextFile, DET);
FTotalReg60 := FTotalReg60 + 1;
end;
cdsTributacaoEcf.Filter := 'IDReducaoZ = ' + cdsReducaoZ.FieldByName('IDReducaoZ').AsString;
cdsTributacaoEcf.Filtered := True;
cdsTributacaoEcf.First;
while not cdsTributacaoEcf.Eof do
begin
DET := '60';
DET := DET + 'A';
DET := DET + FormatFloat('0000', YY) + FormatFloat('00', MM) + FormatFloat('00', DD);
DET := DET + cdsReducaoZ.FieldByName('NumeroSerie').AsString;
DET := DET + FormatFloat('0000', cdsTributacaoEcf.FieldByName('Aliquota').Value * 100 );
FTotal := cdsTributacaoEcf.FieldByName('BaseCalculo').AsFloat;
DET := DET + FormatFloat('000000000000', FTotal * 100);
DET := DET + ' ';
WriteLN(FTextFile, DET);
FTotalReg60 := FTotalReg60 + 1;
cdsTributacaoEcf.Next;
end;
cdsTributacaoEcf.Filter := '';
cdsTributacaoEcf.Filtered := False;
cdsReducaoZ.Next;
end;
end;
DMSintegra.qu60R.First;
while not DMSintegra.qu60R.Eof do
begin
if (DMSintegra.qu60RQuantidade.value > 0) and (DMSintegra.qu60RValorTotal.value > 0) then
begin
DET := '60';
DET := DET + 'R';
DET := DET + FormatFloat('00', MM) + FormatFloat('0000', YY);
DET := DET + Copy(DMSintegra.qu60RCodigoProduto.AsString + ' ', 1, 14);
DET := DET + FormatFloat('0000000000000', DMSintegra.qu60RQuantidade.Value * 1000);
FTotal := DMSintegra.qu60RValorTotal.Value;
DET := DET + FormatFloat('0000000000000000', FTotal * 100);
DET := DET + FormatFloat('0000000000000000', DMSintegra.qu60RValorTotal.Value * 100);
DET := DET + FormatFloat('0000', DMSintegra.qu60RPercImposto.Value * 100); // Pode ser 0700 1200 1800 2500 F I - F-SubsTrib I-Isento
DET := DET + ' '; // 54 espacos verificar ????
WriteLN(FTextFile, DET);
FTotalReg60 := FTotalReg60 + 1;
end;
DMSintegra.qu60R.Next;
end;
end;
procedure TSintegra.GenerateReg70;
var
DET: String;
begin
DMSintegra.cdsSintegra.Filtered := False;
DMSintegra.cdsSintegra.Filter := 'TIPO = ' + QuotedStr('70');
DMSintegra.cdsSintegra.Filtered := True;
DMSintegra.cdsSintegra.First;
FTotalReg70 := 0;
while not DMSintegra.cdsSintegra.Eof do
begin
DET := DMSintegra.cdsSintegraTIPO.AsString;
DET := DET + DMSintegra.cdsSintegraCNPJ.AsString;
DET := DET + BrancoF(DMSintegra.cdsSintegraIEST.AsString, 14);
DET := DET + GetRegDate(DMSintegra.cdsSintegraDATAREG.value);
DET := DET + DMSintegra.cdsSintegraUF.AsString;
DET := DET + DMSintegra.cdsSintegraRF.AsString;
DET := DET + BrancoF(DMSintegra.cdsSintegraSERIE.AsString, 3);
DET := DET + DMSintegra.cdsSintegraDOC.AsString;
DET := DET + DMSintegra.cdsSintegraCFOP.AsString;
DET := DET + 'T';
DET := DET + FormatFloat('0000000000000', DMSintegra.cdsSintegraDATAREG.Value);
DET := DET + FormatFloat('0000000000000', DMSintegra.cdsSintegraBASE.Value);
DET := DET + FormatFloat('0000000000000', DMSintegra.cdsSintegraImposto.Value);
DET := DET + FormatFloat('0000000000000', DMSintegra.cdsSintegraISENTO.Value);
DET := DET + FormatFloat('0000000000000', DMSintegra.cdsSintegraOUTRAS.Value);
DET := DET + FormatFloat('0000', StrToFloatDef(DMSintegra.cdsSintegraALIQ.AsString, 0) * 100);
DET := DET + DMSintegra.cdsSintegraS_N.AsString;
WriteLN(FTextFile, DET);
FTotalReg70 := FTotalReg70 + 1;
DMSintegra.cdsSintegra.Next;
end;
DMSintegra.cdsSintegra.Filtered := False;
end;
procedure TSintegra.GenerateReg75;
var
DET: String;
begin
// Registro com a listagem de produtos dos outros registros
FTotalReg75 := 0;
DMSintegra.qu60R.First;
while not DMSintegra.qu60R.Eof do
begin
if (DMSintegra.qu60RQuantidade.value > 0) and (DMSintegra.qu60RValorTotal.value > 0) then
begin
DET := '75';
DET := DET + GetRegDate(FFirstDate);
DET := DET + GetRegDate(FLastDate);
DET := DET + Copy(DMSintegra.qu60RCodigoProduto.AsString + ' ', 1, 14); // 14 posicoes
DET := DET + ' ';
DET := DET + Copy(DMSintegra.qu60RProduto.AsString + ' ',1,53);
DET := DET + Copy(DMSintegra.qu60RUnidade.AsString + ' ', 1, 6);
if (DMSintegra.qu60RCF.asString <> '000') and (DMSintegra.qu60RCF.asString <> '040') and (DMSintegra.qu60RCF.asString <> '090') then
DET := DET + DMSintegra.qu60RCF.asString else
DET := DET + '000';
DET := DET + '00';
if DMSintegra.qu60RCF.asString = '000' then
DET := DET + FormatFloat('0000', DMSintegra.qu60RPercImposto.Value * 100);
if DMSintegra.qu60RCF.asString = '040' then
DET := DET + 'I ';
if DMSintegra.qu60RCF.asString = '090' then
DET := DET + 'F ';
DET := DET + '000000';
DET := DET + '000000000000';
WriteLN(FTextFile, DET);
if DMSintegra.Virtual_Produtos.FindKey([copy(DMSintegra.qu60RCodigoProduto.AsString + ' ', 1, 20)]) = True then
DMSintegra.Virtual_Produtos.Delete;
FTotalReg75 := FTotalReg75 + 1;
end;
DMSintegra.qu60R.Next;
end;
DMSintegra.Virtual_Produtos.First;
while not DMSintegra.Virtual_Produtos.Eof do
begin
DET := '75';
DET := DET + GetRegDate(FFirstDate);
DET := DET + GetRegDate(FLastDate);
DET := DET + copy(DMSintegra.Virtual_ProdutosCodigoProduto.AsString + ' ', 1, 14); // 14 posicoes
DET := DET + ' ';
DET := DET + Copy(DMSintegra.Virtual_ProdutosDESCRICAO.AsString + ' ',1,53);
DET := DET + Copy(DMSintegra.Virtual_ProdutosUNIDADE.AsString + ' ', 1, 6);
DET := DET + DMSintegra.Virtual_ProdutosCF.AsString;
DET := DET + '00';
if DMSintegra.Virtual_ProdutosCF.AsString = '000' then
DET := DET + FormatFloat('0000', DMSintegra.Virtual_ProdutosAliquota.Value * 100);
if DMSintegra.Virtual_ProdutosCF.AsString = '040' then
DET := DET + 'I ';
if DMSintegra.Virtual_ProdutosCF.AsString = '090' then
DET := DET + 'F ';
DET := DET + '000000';
DET := DET + '0000000000';
WriteLN(FTextFile, DET);
FTotalReg75 := FTotalReg75 + 1;
DMSintegra.Virtual_Produtos.Next;
end;
end;
procedure TSintegra.GenerateReg90;
var
DET: String;
begin
// Totalizadores
FTotalReg90 := FTotalReg50 + FTotalReg51 + FTotalReg54 + FTotalReg70 + FTotalReg60 + FTotalReg75 + 2 + 1;
DET := '90';
DET := DET + FCompanyCGC;
DET := DET + FCompanyIE;
DET := DET + '50' + FormatFloat('00000000', FTotalReg50);
DET := DET + '51' + FormatFloat('00000000', FTotalReg51);
DET := DET + '54' + FormatFloat('00000000', FTotalReg54);
DET := DET + '60' + FormatFloat('00000000', FTotalReg60);
DET := DET + '70' + FormatFloat('00000000', FTotalReg70);
DET := DET + '75' + FormatFloat('00000000', FTotalReg75);
DET := DET + '99' + FormatFloat('00000000', FTotalReg90) + ' ' + '1';
Writeln(FTextFile, DET);
end;
function TSintegra.GetRegDate(ADate: TDateTime): String;
var
wDay, wMonth, wYear: Word;
begin
DecodeDate(ADate, wYear, wMonth, wDay);
Result := FormatFloat('0000', wYear) + FormatFloat('00', wMonth) + FormatFloat('00', wDay);
end;
procedure TSintegra.LoadCompanyProperties;
var
i: Integer;
sLetter: String;
begin
FCompanyCGC := '';
for i := 1 to Length(DMSintegra.qryEmpresaCGC.AsString) do
begin
sLetter := Copy(DMSintegra.qryEmpresaCGC.AsString, i, 1);
if (sLetter = '1') or (sLetter = '2') or (sLetter = '3') or (sLetter = '4') or (sLetter = '5') or
(sLetter = '6') or (sLetter = '7') or (sLetter = '8') or (sLetter = '9') or (sLetter = '0') then
FCompanyCGC := FCompanyCGC + sLetter;
end;
FCompanyCGC := Copy(FCompanyCGC + ' ', 1, 14);
FCompanyIE := '';
for i := 1 to length(DMSintegra.qryEmpresaInscricaoEstadual.AsString) do
begin
sLetter := Copy(DMSintegra.qryEmpresaInscricaoEstadual.AsString, i, 1);
if (sLetter = '1') or (sLetter = '2') or (sLetter = '3') or (sLetter = '4') or (sLetter = '5') or
(sLetter = '6') or (sLetter = '7') or (sLetter = '8') or (sLetter = '9') or (sLetter = '0') then
FCompanyIE := FCompanyIE + sLetter;
end;
if FCompanyIE = '' then
FCompanyIE := '00000000000000';
FCompanyIE := Copy(FCompanyIE + ' ', 1, 14);
end;
end.
|
unit ibSHException;
interface
uses
SysUtils, Classes,
SHDesignIntf,
ibSHDesignIntf, ibSHDBObject;
type
TibBTException = class(TibBTDBObject, IibSHException)
private
FText: string;
FNumber: Integer;
function GetText: string;
procedure SetText(Value: string);
function GetNumber: Integer;
procedure SetNumber(Value: Integer);
published
property Description;
property Text: string read GetText {write SetText};
property Number: Integer read GetNumber {write SetNumber};
end;
implementation
uses
ibSHConsts, ibSHSQLs;
{ TibBTException }
function TibBTException.GetText: string;
begin
Result := FText;
end;
procedure TibBTException.SetText(Value: string);
begin
FText := Value;
end;
function TibBTException.GetNumber: Integer;
begin
Result := FNumber;
end;
procedure TibBTException.SetNumber(Value: Integer);
begin
FNumber := Value;
end;
end.
|
// UTheBallStructures
{: Structures you can have in a TheBall game map.<p>
<b>History : </b><font size=-1><ul>
<li>28/10/02 - EG - Creation
</ul></font>
}
unit UTheBallStructures;
interface
uses Classes, SysUtils, GLScene, GLObjects, VectorGeometry, odeimport, GLBitmapFont,
GLGeomObjects, BaseClasses, GLColor;
type
TTheBallStructure = class;
// TTheBallStructures
//
TTheBallStructures = class (TList)
protected
{ Protected Declarations }
function GetItems(index : Integer) : TTheBallStructure;
procedure SetItems(index : Integer; val : TTheBallStructure);
public
{ Public Declarations }
property Items[index : Integer] : TTheBallStructure read GetItems write SetItems; default;
function StructureByName(const aName : String) : TTheBallStructure;
end;
// TTheBallStructure
//
TTheBallStructure = class (TPersistent)
private
{ Private Declarations }
FOwner : TTheBallStructures;
FName : String;
protected
{ Protected Declarations }
function ParentObject : TGLBaseSceneObject; dynamic;
public
{ Public Declarations }
constructor Create(aOwner : TTheBallStructures); virtual;
destructor Destroy; override;
property Owner : TTheBallStructures read FOwner;
property Name : String read FName;
procedure Parse(const vals : TStringList); dynamic;
procedure Instantiate; dynamic; abstract;
procedure Release; dynamic; abstract;
procedure Progress(const progressTime : TProgressTimes); virtual;
procedure SetTransparency(alpha : Single); dynamic;
end;
TTheBallStructureClass = class of TTheBallStructure;
// TTBTableText
//
TTBTableText = class (TTheBallStructure)
private
{ Private Declarations }
FFlatText : TGLFlatText;
FPosition : TAffineVector;
FOrientation : TAffineVector;
FSize : Single;
FColor : Integer;
FText : String;
protected
{ Protected Declarations }
public
{ Public Declarations }
constructor Create(aOwner : TTheBallStructures); override;
destructor Destroy; override;
procedure Parse(const vals : TStringList); override;
procedure Instantiate; override;
procedure Release; override;
end;
// TTBCubeArea
//
TTBCubeArea = class (TTheBallStructure)
private
{ Private Declarations }
FPosition : TAffineVector;
FSize : TAffineVector;
protected
{ Protected Declarations }
public
{ Public Declarations }
constructor Create(aOwner : TTheBallStructures); override;
destructor Destroy; override;
procedure Parse(const vals : TStringList); override;
procedure Instantiate; override;
procedure Release; override;
property Position : TAffineVector read FPosition;
property Size : TAffineVector read FSize;
end;
// TTBSpawnPoint
//
TTBSpawnPoint = class (TTBCubeArea)
end;
// TTBBallExit
//
TTBBallExit = class (TTBCubeArea)
private
{ Private Declarations }
FDummy : TGLDummyCube;
public
{ Public Declarations }
procedure Instantiate; override;
procedure Release; override;
procedure Progress(const progressTime : TProgressTimes); override;
end;
// TTBSpikes
//
TTBSpikes = class (TTBCubeArea)
private
{ Private Declarations }
FNB : Integer;
FDummy : TGLDummyCube;
public
{ Public Declarations }
procedure Parse(const vals : TStringList); override;
procedure Instantiate; override;
procedure Release; override;
procedure Progress(const progressTime : TProgressTimes); override;
end;
// TTBFire
//
TTBFire = class (TTBCubeArea)
private
{ Private Declarations }
FDisk : TGLDisk;
public
{ Public Declarations }
procedure Parse(const vals : TStringList); override;
procedure Instantiate; override;
procedure Release; override;
procedure Progress(const progressTime : TProgressTimes); override;
end;
// TTBSteam
//
TTBSteam = class (TTBCubeArea)
private
{ Private Declarations }
FPlane : TGLPlane;
FTimeOffset, FTimeOn, FTimeOff : Single;
FStrength : Single;
public
{ Public Declarations }
procedure Parse(const vals : TStringList); override;
procedure Instantiate; override;
procedure Release; override;
procedure Progress(const progressTime : TProgressTimes); override;
end;
// TTBTrigger
//
TTBTrigger = class (TTBCubeArea)
private
{ Private Declarations }
FActionStartTime : Double;
FDisk : TGLDisk;
FTarget, FAction, FSound : String;
public
{ Public Declarations }
procedure Parse(const vals : TStringList); override;
procedure Instantiate; override;
procedure Release; override;
procedure Progress(const progressTime : TProgressTimes); override;
end;
// TTBBlock
//
TTBBlock = class (TTBCubeArea)
private
{ Private Declarations }
FBlock : TGLCube;
FBlockGeom : PdxGeom;
protected
{ Protected Declarations }
public
{ Public Declarations }
constructor Create(aOwner : TTheBallStructures); override;
destructor Destroy; override;
procedure Parse(const vals : TStringList); override;
procedure Instantiate; override;
procedure Release; override;
procedure Progress(const progressTime : TProgressTimes); override;
end;
// TTBMarbleBlock
//
TTBMarbleBlock = class (TTBBlock)
public
{ Public Declarations }
procedure Instantiate; override;
end;
// TTBTransparentBlock
//
TTBTransparentBlock = class (TTBBlock)
private
{ Private Declarations }
FInitialAlpha : Single;
protected
{ Protected Declarations }
function ParentObject : TGLBaseSceneObject; override;
public
{ Public Declarations }
procedure SetTransparency(alpha : Single); override;
end;
// TTBGlassBlock
//
TTBGlassBlock = class (TTBTransparentBlock)
public
{ Public Declarations }
procedure Instantiate; override;
end;
procedure ParseTheBallMap(const mapData : String; strucList : TTheBallStructures;
var mapTitle : String);
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses FMain, GLTexture, dynodegl, GLParticleFX, GLSound, GLUtils;
// ParseTheBallMap
//
procedure ParseTheBallMap(const mapData : String; strucList : TTheBallStructures;
var mapTitle : String);
var
i, p : Integer;
line, className : String;
sl, vals : TStringList;
struc : TTheBallStructure;
begin
sl:=TStringList.Create;
vals:=TStringList.Create;
try
sl.Text:=mapData;
for i:=0 to sl.Count-1 do begin
line:=Trim(sl[i]);
if (line='') or (Copy(line, 1, 2)='//') then continue;
p:=Pos(':', line);
Assert(p>1);
className:='TTB'+Trim(Copy(line, 1, p-1));
if CompareText(className, 'TTBTitle')=0 then
mapTitle:=Trim(Copy(line, p+1, MaxInt))
else begin
struc:=TTheBallStructureClass(FindClass(className)).Create(strucList);
vals.CommaText:=Trim(Copy(line, p+1, MaxInt));
struc.Parse(vals);
strucList.Add(struc);
end;
end;
finally
vals.Free;
sl.Free;
end;
end;
// ------------------
// ------------------ TTheBallStructures ------------------
// ------------------
// GetItems
//
function TTheBallStructures.GetItems(index : Integer) : TTheBallStructure;
begin
Result:=TTheBallStructure(inherited Items[index]);
end;
// SetItems
//
procedure TTheBallStructures.SetItems(index : Integer; val : TTheBallStructure);
begin
inherited Items[index]:=val;
end;
// StructureByName
//
function TTheBallStructures.StructureByName(const aName : String) : TTheBallStructure;
var
i : Integer;
begin
Result:=nil;
for i:=0 to Count-1 do
if CompareText(aName, Items[i].Name)=0 then begin
Result:=Items[i];
Break;
end;
end;
// ------------------
// ------------------ TTheBallStructure ------------------
// ------------------
// Create
//
constructor TTheBallStructure.Create(aOwner : TTheBallStructures);
begin
inherited Create;
FOwner:=aOwner;
end;
// Destroy
//
destructor TTheBallStructure.Destroy;
begin
inherited Destroy;
end;
// ParentObject
//
function TTheBallStructure.ParentObject : TGLBaseSceneObject;
begin
Result:=Main.DCMap;
end;
// Parse
//
procedure TTheBallStructure.Parse(const vals : TStringList);
begin
FName:=vals.Values['Name'];
end;
// Progress
//
procedure TTheBallStructure.Progress(const progressTime : TProgressTimes);
begin
// nothing
end;
// SetTransparency
//
procedure TTheBallStructure.SetTransparency(alpha : Single);
begin
// nothing
end;
// ------------------
// ------------------ TTBTableText ------------------
// ------------------
// Create
//
constructor TTBTableText.Create(aOwner : TTheBallStructures);
begin
inherited;
end;
// Destroy
//
destructor TTBTableText.Destroy;
begin
inherited Destroy;
end;
// Parse
//
procedure TTBTableText.Parse(const vals : TStringList);
begin
inherited;
FPosition[0]:=StrToFloatDef(vals.Values['X'], 0);
FPosition[1]:=StrToFloatDef(vals.Values['Y'], 0.01);
FPosition[2]:=StrToFloatDef(vals.Values['Z'], 0);
FOrientation[0]:=StrToFloatDef(vals.Values['OX'], 1);
FOrientation[1]:=StrToFloatDef(vals.Values['OY'], 0);
FOrientation[2]:=StrToFloatDef(vals.Values['OZ'], 0);
NormalizeVector(FOrientation);
FSize:=StrToFloatDef(vals.Values['Size'], 1)*0.01;
FColor:=StrToIntDef(vals.Values['Color'], 0);
FText:=vals.Values['Text'];
end;
// Instantiate
//
procedure TTBTableText.Instantiate;
begin
FFlatText:=TGLFlatText(ParentObject.AddNewChild(TGLFlatText));
FFlatText.Position.AsAffineVector:=FPosition;
FFlatText.Direction.AsVector:=YHmgVector;
FFlatText.Up.AsAffineVector:=FOrientation;
FFlatText.Roll(180);
FFlatText.Scale.SetVector(FSize, FSize, FSize);
FFlatText.BitmapFont:=Main.WindowsBitmapFont;
FFlatText.Text:=FText;
FFlatText.ModulateColor.AsWinColor:=FColor;
end;
// Release
//
procedure TTBTableText.Release;
begin
FreeAndNil(FFlatText);
end;
// ------------------
// ------------------ TTBCubeArea ------------------
// ------------------
// Create
//
constructor TTBCubeArea.Create(aOwner : TTheBallStructures);
begin
inherited;
end;
// Destroy
//
destructor TTBCubeArea.Destroy;
begin
inherited Destroy;
end;
// Parse
//
procedure TTBCubeArea.Parse(const vals : TStringList);
begin
inherited;
FPosition[0]:=StrToFloatDef(vals.Values['X'], 0);
FPosition[1]:=StrToFloatDef(vals.Values['Y'], 0.5);
FPosition[2]:=StrToFloatDef(vals.Values['Z'], 0);
FSize[0]:=StrToFloatDef(vals.Values['SX'], 1);
FSize[1]:=StrToFloatDef(vals.Values['SY'], 1);
FSize[2]:=StrToFloatDef(vals.Values['SZ'], 1);
end;
// Instantiate
//
procedure TTBCubeArea.Instantiate;
begin
// nothing
end;
// Release
//
procedure TTBCubeArea.Release;
begin
// nothing
end;
// ------------------
// ------------------ TTBBallExit ------------------
// ------------------
// Instantiate
//
procedure TTBBallExit.Instantiate;
var
src : TGLSourcePFXEffect;
begin
FDummy:=TGLDummyCube(ParentObject.AddNewChild(TGLDummyCube));
FDummy.Position.AsAffineVector:=Position;
src:=GetOrCreateSourcePFX(FDummy);
src.Manager:=Main.PFXExit;
src.ParticleInterval:=0.02;
src.PositionDispersion:=VectorLength(FSize)*0.5;
src.VelocityDispersion:=VectorLength(FSize)*0.1;
end;
// Release
//
procedure TTBBallExit.Release;
begin
FreeAndNil(FDummy);
end;
// Progress
//
procedure TTBBallExit.Progress(const progressTime : TProgressTimes);
var
src : TGLSourcePFXEffect;
begin
if FDummy.DistanceTo(Main.DCBallAbsolute)<VectorLength(FSize)*0.7 then begin
if not Main.LevelWon then begin
src:=GetOrCreateSourcePFX(FDummy);
src.VelocityDispersion:=VectorLength(FSize)*2;
src.Burst(progressTime.newTime, 150);
end;
end;
end;
// ------------------
// ------------------ TTBSpikes ------------------
// ------------------
// Parse
//
procedure TTBSpikes.Parse(const vals : TStringList);
begin
inherited;
FNB:=StrToIntDef(vals.Values['NB'], 3);
end;
// Instantiate
//
procedure TTBSpikes.Instantiate;
var
i : Integer;
spike : TGLCone;
begin
FDummy:=TGLDummyCube(ParentObject.AddNewChild(TGLDummyCube));
FDummy.Position.AsAffineVector:=Position;
for i:=1 to FNB do begin
spike:=TGLCone(FDummy.AddNewChild(TGLCone));
spike.Height:=(Random*0.4+0.6)*FSize[1];
spike.Position.X:=(Random-0.5)*2*FSize[0];
spike.Position.Y:=spike.Height*0.5;
spike.Position.Z:=(Random-0.5)*2*FSize[2];
spike.Parts:=[coSides];
spike.BottomRadius:=0.1*VectorLength(FSize[0], FSize[1]);
spike.Stacks:=1;
spike.Slices:=Random(4)+6;
spike.Material.MaterialLibrary:=main.MaterialLibrary;
spike.Material.LibMaterialName:='chrome';
end;
end;
// Release
//
procedure TTBSpikes.Release;
begin
FreeAndNil(FDummy);
end;
// Progress
//
procedure TTBSpikes.Progress(const progressTime : TProgressTimes);
begin
if FDummy.DistanceTo(Main.DCBallAbsolute)<VectorLength(FSize)*0.7 then begin
if Main.deflateEnergy=0 then begin
Main.deflateEnergy:=3;
Main.deflateVector:=VectorNormalize(Main.DCBallAbsolute.AbsoluteToLocal(YVector));
if Main.ballBody<>nil then
dBodyAddForce(Main.ballBody, 0, 1500, 0);
end;
end;
end;
// ------------------
// ------------------ TTBFire ------------------
// ------------------
// Parse
//
procedure TTBFire.Parse(const vals : TStringList);
begin
inherited;
end;
// Instantiate
//
procedure TTBFire.Instantiate;
var
src : TGLSourcePFXEffect;
begin
FDisk:=TGLDisk(ParentObject.AddNewChild(TGLDisk));
FDisk.Direction.AsVector:=YHmgVector;
FDisk.Position.AsAffineVector:=Position;
FDisk.Loops:=1;
FDisk.Slices:=8;
FDisk.OuterRadius:=VectorLength(FSize)*0.4;
FDisk.Material.MaterialLibrary:=Main.MaterialLibrary;
FDisk.Material.LibMaterialName:='chrome';
src:=GetOrCreateSourcePFX(FDisk);
src.Manager:=Main.PFXFire;
src.ParticleInterval:=0.05;
src.PositionDispersion:=VectorLength(FSize)*0.2;
src.VelocityDispersion:=VectorLength(FSize)*0.1;
end;
// Release
//
procedure TTBFire.Release;
begin
FreeAndNil(FDisk);
end;
// Progress
//
procedure TTBFire.Progress(const progressTime : TProgressTimes);
var
src : TGLSourcePFXEffect;
begin
if FDisk.DistanceTo(Main.DCBallAbsolute)<VectorLength(FSize)*0.7 then begin
src:=GetOrCreateSourcePFX(Main.SPHBall);
if src.Manager=nil then begin
src.Manager:=Main.PFXFire;
src.ParticleInterval:=0.01;
src.PositionDispersion:=0.4;
src.VelocityDispersion:=0.1;
Main.burnOut:=3;
end;
end;
end;
// ------------------
// ------------------ TTBSteam ------------------
// ------------------
// Parse
//
procedure TTBSteam.Parse(const vals : TStringList);
begin
inherited;
FTimeOffset:=StrToFloatDef(vals.Values['TimeOffset'], 0);
FTimeOn:=StrToFloatDef(vals.Values['TimeOn'], 3);
FTimeOff:=StrToFloatDef(vals.Values['TimeOff'], 3);
FStrength:=StrToFloatDef(vals.Values['Strength'], 20);
end;
// Instantiate
//
procedure TTBSteam.Instantiate;
var
src : TGLSourcePFXEffect;
begin
FPlane:=TGLPlane(ParentObject.AddNewChild(TGLPlane));
FPlane.Direction.AsVector:=YHmgVector;
FPlane.Position.AsAffineVector:=Position;
FPlane.Width:=FSize[0];
FPlane.Height:=FSize[2];
FPlane.Material.MaterialLibrary:=Main.MaterialLibrary;
FPlane.Material.LibMaterialName:='chrome';
src:=GetOrCreateSourcePFX(FPlane);
src.Manager:=Main.PFXSteam;
src.ParticleInterval:=0.03;
src.PositionDispersion:=VectorLength(FSize)*0.2;
src.VelocityDispersion:=VectorLength(FSize)*0.7;
src.InitialVelocity.Y:=Sqrt(FStrength);
end;
// Release
//
procedure TTBSteam.Release;
begin
FreeAndNil(FPlane);
end;
// Progress
//
procedure TTBSteam.Progress(const progressTime : TProgressTimes);
var
t : Single;
src : TGLSourcePFXEffect;
v : TVector;
begin
src:=GetOrCreateSourcePFX(FPlane);
t:=Frac((progressTime.newTime+FTimeOffset)/(FTimeOn+FTimeOff))*(FTimeOn+FTimeOff);
if t<=FTimeOn then begin
src.ParticleInterval:=0.03;
v:=FPlane.AbsoluteToLocal(Main.DCBallAbsolute.Position.AsVector);
if (Abs(v[0])<FSize[0]) and (Abs(v[1])<FSize[2]) and (v[2]>=0) then begin
if v[2]<FStrength*0.3 then
Main.verticalForce:=Main.verticalForce+FStrength*(1-(v[2]/(FStrength*0.3)))*0.7;
end;
end else src.ParticleInterval:=0.5;
end;
// ------------------
// ------------------ TTBTrigger ------------------
// ------------------
// Parse
//
procedure TTBTrigger.Parse(const vals : TStringList);
begin
inherited;
FTarget:=vals.Values['Target'];
FAction:=vals.Values['Action'];
FSound:=vals.Values['Sound'];
end;
// Instantiate
//
procedure TTBTrigger.Instantiate;
begin
FActionStartTime:=-1;
FDisk:=TGLDisk(ParentObject.AddNewChild(TGLDisk));
FDisk.Direction.AsVector:=YHmgVector;
FDisk.Position.AsAffineVector:=Position;
FDisk.Loops:=1;
FDisk.Slices:=6;
FDisk.OuterRadius:=VectorLength(FSize)*0.4;
FDisk.Material.MaterialLibrary:=Main.MaterialLibrary;
FDisk.Material.LibMaterialName:='wood';
end;
// Release
//
procedure TTBTrigger.Release;
begin
FreeAndNil(FDisk);
end;
// Progress
//
procedure TTBTrigger.Progress(const progressTime : TProgressTimes);
var
trg : TTheBallStructure;
d : Single;
begin
if FActionStartTime=-1 then begin
if FDisk.DistanceTo(Main.DCBallAbsolute)<VectorLength(FSize)*0.7 then begin
FActionStartTime:=progressTime.newTime;
FDisk.Position.Y:=FDisk.Position.Y-0.05;
if (FSound<>'') and Main.GLSMBass.Active then begin
with GetOrCreateSoundEmitter(FDisk) do begin
Source.SoundLibrary:=Main.SoundLibrary;
Source.SoundName:=FSound;
Playing:=True;
end;
end;
end;
end;
if FActionStartTime>=0 then begin
trg:=Owner.StructureByName(FTarget);
if Assigned(trg) then begin
if CompareText(FAction, 'Vanish')=0 then begin
d:=FActionStartTime+3-progressTime.newTime;
if (d>=0) and (d<=3) then
trg.SetTransparency(Sqr(d)*0.5)
else begin
Owner.Items[Owner.IndexOf(trg)]:=nil;
trg.Release;
FActionStartTime:=-2;
end;
end;
end;
end;
end;
// ------------------
// ------------------ TTBBlock ------------------
// ------------------
// Create
//
constructor TTBBlock.Create(aOwner : TTheBallStructures);
begin
inherited;
end;
// Destroy
//
destructor TTBBlock.Destroy;
begin
Assert(FBlockGeom=nil);
Assert(FBlock=nil);
inherited Destroy;
end;
// Parse
//
procedure TTBBlock.Parse(const vals : TStringList);
begin
inherited;
end;
// Instantiate
//
procedure TTBBlock.Instantiate;
begin
FBlock:=TGLCube(ParentObject.AddNewChild(TGLCube));
FBlock.Position.AsAffineVector:=FPosition;
FBlock.CubeWidth:=FSize[0];
FBlock.CubeHeight:=FSize[1];
FBlock.CubeDepth:=FSize[2];
FBlock.Parts:=FBlock.Parts-[cpBottom];
FBlockGeom:=dCreateBox(Main.space, FSize[0], FSize[1], FSize[2]);
CopyPosFromGeomToGL(FBlockGeom, FBlock);
end;
// Release
//
procedure TTBBlock.Release;
begin
FreeAndNil(FBlock);
if Assigned(FBlockGeom) then begin
dGeomDestroy(FBlockGeom);
FBlockGeom:=nil;
end;
end;
// Progress
//
procedure TTBBlock.Progress(const progressTime : TProgressTimes);
begin
CopyPosFromGeomToGL(FBlockGeom, FBlock);
end;
// ------------------
// ------------------ TTBMarbleBlock ------------------
// ------------------
// Instantiate
//
procedure TTBMarbleBlock.Instantiate;
begin
inherited;
with FBlock.Material do begin
MaterialLibrary:=Main.MaterialLibrary;
LibMaterialName:='marbleblock';
end;
end;
// ------------------
// ------------------ TTBTransparentBlock ------------------
// ------------------
// Instantiate
//
function TTBTransparentBlock.ParentObject : TGLBaseSceneObject;
begin
Result:=Main.DCMapTransparent;
end;
// SetTransparency
//
procedure TTBTransparentBlock.SetTransparency(alpha : Single);
var
n : String;
begin
n:=FBlock.Material.LibMaterialName;
if n<>'' then begin
// clone material locally
FBlock.Material:=Main.MaterialLibrary.Materials.GetLibMaterialByName(n).Material;
FBlock.Material.FrontProperties.Emission.Color:=clrGray50;
end;
if FInitialAlpha=0 then
FInitialAlpha:=FBlock.Material.FrontProperties.Diffuse.Alpha;
FBlock.Material.FrontProperties.Diffuse.Alpha:=alpha*FInitialAlpha;
end;
// ------------------
// ------------------ TTBGlassBlock ------------------
// ------------------
// Instantiate
//
procedure TTBGlassBlock.Instantiate;
begin
inherited;
with FBlock.Material do begin
MaterialLibrary:=Main.MaterialLibrary;
LibMaterialName:='glassblock';
end;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// class registrations
RegisterClasses([TTBMarbleBlock, TTBSpawnPoint, TTBBallExit, TTBSpikes,
TTBFire, TTBGlassBlock, TTBTableText, TTBTrigger, TTBSteam]);
end.
|
unit Actor;
interface
{$INCLUDE source/Global_Conditionals.inc}
uses BasicMathsTypes, math3d, math, dglOpenGL, Model, ModelVxt, Palette, Graphics,
{$IFDEF VOXEL_SUPPORT}Voxel, HVA,{$ENDIF} Windows, GLConstants, ShaderBank, Histogram;
type
PActor = ^TActor;
TActor = class
private
// For the renderer
RequestUpdateWorld: boolean;
procedure QuickSwitchModels(_m1, _m2: integer);
procedure CommonAddActions;
public
// List
Next : PActor;
// Atributes
Models : array of PModel;
// physics cinematics.
PositionAcceleration : TVector3f;
RotationAcceleration : TVector3f;
PositionSpeed : TVector3f; // Move for the next frame.
RotationSpeed : TVector3f;
Position : TVector3f;
Rotation : TVector3f;
// User interface
IsSelected : boolean;
ColoursType : byte;
FactionColour: TColor;
// Editing Mode
CurrentModel : integer;
// Others
ShaderBank : PShaderBank;
// Constructors
constructor Create(_ShaderBank : PShaderBank);
destructor Destroy; override;
procedure Clear;
procedure Reset;
// I/O
procedure SaveToFile(const _Filename,_TexExt: string; _ModelID: integer);
// Execution
procedure Render();
procedure RenderVectorial();
procedure RotateActor;
procedure MoveActor;
procedure ProcessNextFrame;
{$IFDEF VOXEL_SUPPORT}
procedure RebuildActor;
procedure RebuildCurrentMeshes;
{$ENDIF}
procedure Refresh;
// Gets
function GetRequestUpdateWorld: boolean;
// Sets
procedure SetPosition(_x, _y, _z: single); overload;
procedure SetPosition(_Vector: TVector3f); overload;
procedure SetRotation(_x, _y, _z: single); overload;
procedure SetRotation(_Vector: TVector3f); overload;
procedure SetPositionSpeed(_x, _y, _z: single); overload;
procedure SetPositionSpeed(_Vector: TVector3f); overload;
procedure SetRotationSpeed(_x, _y, _z: single); overload;
procedure SetRotationSpeed(_Vector: TVector3f); overload;
procedure SetPositionAcceleration(_x, _y, _z: single); overload;
procedure SetPositionAcceleration(_Vector: TVector3f); overload;
procedure SetRotationAcceleration(_x, _y, _z: single); overload;
procedure SetRotationAcceleration(_Vector: TVector3f); overload;
procedure SetNormalsModeRendering;
procedure SetColourModeRendering;
procedure SetQuality(_value: integer);
// Adds
procedure Add(const _filename: string); overload;
procedure Add(const _Model: PModel); overload;
{$IFDEF VOXEL_SUPPORT}
procedure Add(const _Voxel: PVoxel; const _HVA: PHVA; const _Palette: PPalette; _Quality: integer = C_QUALITY_CUBED); overload;
procedure Add(const _VoxelSection: PVoxelSection; const _Palette: PPalette; _Quality: integer = C_QUALITY_CUBED); overload;
{$ENDIF}
procedure AddReadOnly(const _filename: string); overload;
procedure AddReadOnly(const _Model: PModel); overload;
{$IFDEF VOXEL_SUPPORT}
procedure AddReadOnly(const _Voxel: PVoxel; const _HVA: PHVA; const _Palette: PPalette; _Quality: integer = C_QUALITY_CUBED); overload;
procedure AddReadOnly(const _VoxelSection: PVoxelSection; const _Palette: PPalette; _Quality: integer = C_QUALITY_CUBED); overload;
{$ENDIF}
procedure Clone(const _filename: string); overload;
procedure Clone(const _Model: PModel); overload;
{$IFDEF VOXEL_SUPPORT}
procedure Clone(const _Voxel: PVoxel; const _HVA: PHVA; const _Palette: PPalette; _Quality: integer = C_QUALITY_CUBED); overload;
procedure Clone(const _VoxelSection: PVoxelSection; const _Palette: PPalette; _Quality: integer = C_QUALITY_CUBED); overload;
{$ENDIF}
// Removes
procedure Remove(var _Model : PModel);
// switches
procedure SwitchModels(_m1, _m2: integer);
// Palette related
procedure ChangeRemappable (_Colour : TColor); overload;
procedure ChangeRemappable (_r,_g,_b : byte); overload;
procedure ChangePalette (const _Filename: string);
// Textures
procedure ExportTextures(const _BaseDir, _Ext: string; _previewTextures: boolean);
procedure ExportHeightMap(const _BaseDir, _Ext : string; _previewTextures: boolean);
procedure SetTextureNumMipMaps(_NumMipMaps, _TextureType: integer);
// Transparency methods
procedure ForceTransparency(_level: single);
procedure ForceTransparencyOnMesh(_Level: single; _ModelID,_MeshID: integer);
procedure ForceTransparencyExceptOnAMesh(_Level: single; _ModelID,_MeshID: integer);
// Mesh Operations
procedure RemoveInvisibleFaces;
// Quality Assurance
function GetAspectRatioHistogram(): THistogram;
function GetSkewnessHistogram(): THistogram;
function GetSmoothnessHistogram(): THistogram;
// Mesh Plugins
procedure AddNormalsPlugin;
procedure RemoveNormalsPlugin;
// Assign
procedure AssignForBackup(const _Source: TActor);
end;
implementation
uses GlobalVars, HierarchyAnimation;
constructor TActor.Create(_ShaderBank : PShaderBank);
begin
Next := nil;
ShaderBank := _ShaderBank;
IsSelected := false;
SetLength(Models,0);
RequestUpdateWorld := false;
ColoursType := 1;
FactionColour := $000000FF;
Reset;
end;
destructor TActor.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TActor.Clear;
var
i : integer;
begin
for i := Low(Models) to High(Models) do
begin
if Models[i] <> nil then
begin
ModelBank.Delete(Models[i]);
end;
end;
SetLength(Models,0);
RequestUpdateWorld := true;
end;
procedure TActor.Reset;
begin
Rotation.X := 0;
Rotation.Y := 0;
Rotation.Z := 0;
Position.X := 0;
Position.Y := 0;
Position.Z := 0;
PositionSpeed := SetVector(0,0,0);
RotationSpeed := SetVector(0,0,0);
PositionAcceleration := SetVector(0,0,0);
RotationAcceleration := SetVector(0,0,0);
CurrentModel := 0;
end;
// I/O
procedure TActor.SaveToFile(const _Filename,_TexExt: string; _ModelID: integer);
begin
ModelBank.Save(Models[_ModelID],_Filename, _TexExt);
end;
procedure TActor.Render();
var
i : integer;
begin
glPushMatrix;
MoveActor;
RotateActor;
for i := Low(Models) to High(Models) do
begin
if Models[i] <> nil then
begin
Models[i]^.Render();
end;
end;
glPopMatrix;
end;
procedure TActor.RenderVectorial();
var
i : integer;
begin
glPushMatrix;
MoveActor;
RotateActor;
for i := Low(Models) to High(Models) do
begin
if Models[i] <> nil then
begin
Models[i]^.RenderVectorial();
end;
end;
glPopMatrix;
end;
procedure TActor.RotateActor;
begin
glRotatef(Rotation.X, 1, 0, 0);
glRotatef(Rotation.Y, 0, 1, 0);
glRotatef(Rotation.Z, 0, 0, 1);
end;
procedure TActor.MoveActor;
begin
glTranslatef(Position.X, Position.Y, Position.Z);
end;
procedure TActor.ProcessNextFrame;
var
Signal, i : integer;
begin
// Process acceleration.
Signal := Sign(PositionSpeed.X);
PositionSpeed.X := PositionSpeed.X + PositionAcceleration.X;
if Signal <> Sign(PositionSpeed.X) then
PositionSpeed.X := 0;
Signal := Sign(PositionSpeed.Y);
PositionSpeed.Y := PositionSpeed.Y + PositionAcceleration.Y;
if Signal <> Sign(PositionSpeed.Y) then
PositionSpeed.Y := 0;
Signal := Sign(PositionSpeed.Z);
PositionSpeed.Z := PositionSpeed.Z + PositionAcceleration.Z;
if Signal <> Sign(PositionSpeed.Z) then
PositionSpeed.Z := 0;
Signal := Sign(RotationSpeed.X);
RotationSpeed.X := RotationSpeed.X + RotationAcceleration.X;
if Signal <> Sign(RotationSpeed.X) then
RotationSpeed.X := 0;
Signal := Sign(RotationSpeed.Y);
RotationSpeed.Y := RotationSpeed.Y + RotationAcceleration.Y;
if Signal <> Sign(RotationSpeed.Y) then
RotationSpeed.Y := 0;
Signal := Sign(RotationSpeed.Z);
RotationSpeed.Z := RotationSpeed.Z + RotationAcceleration.Z;
if Signal <> Sign(RotationSpeed.Z) then
RotationSpeed.Z := 0;
// Process position and angle
Position.X := Position.X + PositionSpeed.X;
Position.Y := Position.Y + PositionSpeed.Y;
Position.Z := Position.Z + PositionSpeed.Z;
Rotation.X := CleanAngle(Rotation.X + RotationSpeed.X);
Rotation.Y := CleanAngle(Rotation.Y + RotationSpeed.Y);
Rotation.Z := CleanAngle(Rotation.Z + RotationSpeed.Z);
// Process included models.
for i := Low(Models) to High(Models) do
begin
if Models[i] <> nil then
begin
Models[i]^.ProcessNextFrame;
RequestUpdateWorld := RequestUpdateWorld or Models[i]^.RequestUpdateWorld;
end;
end;
// update request world update.
RequestUpdateWorld := RequestUpdateWorld or (PositionSpeed.X <> 0) or (PositionSpeed.Y <> 0) or (PositionSpeed.Z <> 0) or (RotationSpeed.X <> 0) or (RotationSpeed.Y <> 0) or (RotationSpeed.Z <> 0);
end;
{$IFDEF VOXEL_SUPPORT}
procedure TActor.RebuildActor;
var
i : integer;
begin
for i := Low(Models) to High(Models) do
begin
if Models[i] <> nil then
begin
if Models[i]^.ModelType = C_MT_VOXEL then
begin
(Models[i]^ as TModelVxt).RebuildModel;
end;
Models[i]^.ChangeRemappable(FactionColour);
end;
end;
if ColoursType = C_COLOURS_DISABLED then
SetNormalsModeRendering;
RequestUpdateWorld := true;
end;
procedure TActor.RebuildCurrentMeshes;
var
i : integer;
begin
for i := Low(Models) to High(Models) do
begin
if Models[i] <> nil then
begin
(Models[i]^ as TModelVxt).RebuildCurrentLOD;
end;
end;
RequestUpdateWorld := true;
end;
{$ENDIF}
procedure TActor.Refresh;
var
i : integer;
begin
for i := Low(Models) to High(Models) do
begin
if Models[i] <> nil then
begin
Models[i]^.RefreshModel;
end;
end;
RequestUpdateWorld := true;
end;
// Gets
function TActor.GetRequestUpdateWorld: boolean;
begin
Result := RequestUpdateWorld;
RequestUpdateWorld := false;
end;
// Sets
procedure TActor.SetPosition(_x, _y, _z: single);
begin
Position.X := _x;
Position.Y := _y;
Position.Z := _z;
RequestUpdateWorld := true;
end;
procedure TActor.SetPosition(_Vector: TVector3f);
begin
Position.X := _Vector.X;
Position.Y := _Vector.Y;
Position.Z := _Vector.Z;
RequestUpdateWorld := true;
end;
procedure TActor.SetRotation(_x, _y, _z: single);
begin
Rotation.X := _x;
Rotation.Y := _y;
Rotation.Z := _z;
RequestUpdateWorld := true;
end;
procedure TActor.SetRotation(_Vector: TVector3f);
begin
Rotation.X := _Vector.X;
Rotation.Y := _Vector.Y;
Rotation.Z := _Vector.Z;
RequestUpdateWorld := true;
end;
procedure TActor.SetPositionSpeed(_x, _y, _z: single);
begin
PositionSpeed.X := _x;
PositionSpeed.Y := _y;
PositionSpeed.Z := _z;
RequestUpdateWorld := true;
end;
procedure TActor.SetPositionSpeed(_Vector: TVector3f);
begin
PositionSpeed.X := _Vector.X;
PositionSpeed.Y := _Vector.Y;
PositionSpeed.Z := _Vector.Z;
RequestUpdateWorld := true;
end;
procedure TActor.SetRotationSpeed(_x, _y, _z: single);
begin
RotationSpeed.X := _x;
RotationSpeed.Y := _y;
RotationSpeed.Z := _z;
RequestUpdateWorld := true;
end;
procedure TActor.SetRotationSpeed(_Vector: TVector3f);
begin
RotationSpeed.X := _Vector.X;
RotationSpeed.Y := _Vector.Y;
RotationSpeed.Z := _Vector.Z;
RequestUpdateWorld := true;
end;
procedure TActor.SetPositionAcceleration(_x, _y, _z: single);
begin
PositionAcceleration.X := _x;
PositionAcceleration.Y := _y;
PositionAcceleration.Z := _z;
RequestUpdateWorld := true;
end;
procedure TActor.SetPositionAcceleration(_Vector: TVector3f);
begin
PositionAcceleration.X := _Vector.X;
PositionAcceleration.Y := _Vector.Y;
PositionAcceleration.Z := _Vector.Z;
RequestUpdateWorld := true;
end;
procedure TActor.SetRotationAcceleration(_x, _y, _z: single);
begin
RotationAcceleration.X := _x;
RotationAcceleration.Y := _y;
RotationAcceleration.Z := _z;
RequestUpdateWorld := true;
end;
procedure TActor.SetRotationAcceleration(_Vector: TVector3f);
begin
RotationAcceleration.X := _Vector.X;
RotationAcceleration.Y := _Vector.Y;
RotationAcceleration.Z := _Vector.Z;
RequestUpdateWorld := true;
end;
procedure TActor.SetNormalsModeRendering;
var
i : integer;
begin
ColoursType := C_COLOURS_DISABLED;
if High(Models) >= 0 then
begin
for i := Low(Models) to High(Models) do
begin
if Models[i] <> nil then
begin
Models[i]^.SetNormalsModeRendering;
end;
end;
RequestUpdateWorld := true;
end;
end;
procedure TActor.SetColourModeRendering;
var
i : integer;
begin
ColoursType := 1;
if High(Models) >= 0 then
begin
for i := Low(Models) to High(Models) do
begin
if Models[i] <> nil then
begin
Models[i]^.SetColourModeRendering;
end;
end;
RequestUpdateWorld := true;
end;
end;
procedure TActor.SetQuality(_value: integer);
var
i : integer;
begin
if High(Models) >= 0 then
begin
for i := Low(Models) to High(Models) do
begin
if Models[i] <> nil then
begin
Models[i]^.SetQuality(_value);
end;
end;
RequestUpdateWorld := true;
end;
end;
// Adds
procedure TActor.Add(const _filename: string);
begin
SetLength(Models,High(Models)+2);
Models[High(Models)] := ModelBank.Add(_filename,ShaderBank);
CommonAddActions;
end;
procedure TActor.Add(const _Model: PModel);
begin
SetLength(Models,High(Models)+2);
Models[High(Models)] := ModelBank.Add(_Model);
CommonAddActions;
end;
{$IFDEF VOXEL_SUPPORT}
procedure TActor.Add(const _Voxel: PVoxel; const _HVA: PHVA; const _Palette: PPalette; _Quality: integer);
begin
SetLength(Models,High(Models)+2);
Models[High(Models)] := ModelBank.Add(_Voxel,_HVA,_Palette,ShaderBank,_Quality);
CommonAddActions;
end;
procedure TActor.Add(const _VoxelSection: PVoxelSection; const _Palette: PPalette; _Quality: integer);
begin
SetLength(Models,High(Models)+2);
Models[High(Models)] := ModelBank.Add(_VoxelSection,_Palette,ShaderBank,_Quality);
CommonAddActions;
end;
{$ENDIF}
procedure TActor.AddReadOnly(const _filename: string);
begin
SetLength(Models,High(Models)+2);
Models[High(Models)] := ModelBank.AddReadOnly(_filename,ShaderBank);
CommonAddActions;
end;
procedure TActor.AddReadOnly(const _Model: PModel);
begin
SetLength(Models,High(Models)+2);
Models[High(Models)] := ModelBank.AddReadOnly(_Model);
CommonAddActions;
end;
{$IFDEF VOXEL_SUPPORT}
procedure TActor.AddReadOnly(const _Voxel: PVoxel; const _HVA: PHVA; const _Palette: PPalette; _Quality: integer);
begin
SetLength(Models,High(Models)+2);
Models[High(Models)] := ModelBank.AddReadOnly(_Voxel,_HVA,_Palette,ShaderBank,_Quality);
CommonAddActions;
end;
procedure TActor.AddReadOnly(const _VoxelSection: PVoxelSection; const _Palette: PPalette; _Quality: integer);
begin
SetLength(Models,High(Models)+2);
Models[High(Models)] := ModelBank.AddReadOnly(_VoxelSection,_Palette,ShaderBank,_Quality);
CommonAddActions;
end;
{$ENDIF}
procedure TActor.Clone(const _filename: string);
begin
SetLength(Models,High(Models)+2);
Models[High(Models)] := ModelBank.Clone(_filename,ShaderBank);
CommonAddActions;
end;
procedure TActor.Clone(const _Model: PModel);
begin
SetLength(Models,High(Models)+2);
Models[High(Models)] := ModelBank.Clone(_Model);
CommonAddActions;
end;
{$IFDEF VOXEL_SUPPORT}
procedure TActor.Clone(const _Voxel: PVoxel; const _HVA: PHVA; const _Palette: PPalette; _Quality: integer);
begin
SetLength(Models,High(Models)+2);
Models[High(Models)] := ModelBank.Clone(_Voxel,_HVA,_Palette,ShaderBank,_Quality);
CommonAddActions;
end;
procedure TActor.Clone(const _VoxelSection: PVoxelSection; const _Palette: PPalette; _Quality: integer);
begin
SetLength(Models,High(Models)+2);
Models[High(Models)] := ModelBank.Add(_VoxelSection,_Palette,ShaderBank,_Quality);
CommonAddActions;
end;
{$ENDIF}
procedure TActor.CommonAddActions;
begin
CurrentModel := High(Models);
if ColoursType = C_COLOURS_DISABLED then
begin
SetNormalsModeRendering;
end
else
begin
SetColourModeRendering;
end;
RequestUpdateWorld := true;
end;
// Removes
procedure TActor.Remove(var _Model : PModel);
var
i : integer;
begin
i := Low(Models);
while i <= High(Models) do
begin
if Models[i] = _Model then
begin
ModelBank.Delete(_Model);
while i < High(Models) do
begin
QuickSwitchModels(i,i+1);
inc(i);
end;
SetLength(Models,High(Models));
RequestUpdateWorld := true;
exit;
end;
inc(i);
end;
end;
// Switches
procedure TActor.SwitchModels(_m1, _m2: integer);
begin
if (_m1 <= High(Models)) and (_m1 > Low(Models)) then
if (_m2 <= High(Models)) and (_m2 > Low(Models)) then
QuickSwitchModels(_m1, _m2);
end;
procedure TActor.QuickSwitchModels(_m1, _m2: integer);
var
temp : PModel;
begin
Temp := Models[_m1];
Models[_m1] := Models[_m2];
Models[_m2] := temp;
end;
// Palette Related
procedure TActor.ChangeRemappable(_Colour: TColor);
var
i : integer;
begin
FactionColour := _Colour;
for i := Low(Models) to High(Models) do
begin
if Models[i] <> nil then
begin
Models[i].ChangeRemappable(FactionColour);
end;
end;
RequestUpdateWorld := true;
end;
procedure TActor.ChangeRemappable (_r,_g,_b : byte);
begin
ChangeRemappable(RGB(_r,_g,_b));
end;
procedure TActor.ChangePalette (const _Filename: string);
var
i : integer;
begin
for i := Low(Models) to High(Models) do
begin
if Models[i] <> nil then
begin
Models[i]^.ChangePalette(_Filename);
Models[i]^.ChangeRemappable(FactionColour);
end;
end;
RequestUpdateWorld := true;
end;
procedure TActor.SetTextureNumMipMaps(_NumMipMaps, _TextureType: integer);
var
i : integer;
begin
for i := Low(Models) to High(Models) do
begin
if Models[i] <> nil then
begin
Models[i]^.SetTextureNumMipMaps(_NumMipMaps,_TextureType);
end;
end;
RequestUpdateWorld := true;
end;
procedure TActor.ExportTextures(const _BaseDir, _Ext: string; _previewTextures: boolean);
var
i : integer;
begin
for i := Low(Models) to High(Models) do
begin
if Models[i] <> nil then
begin
Models[i]^.ExportTextures(_BaseDir,_Ext,_previewTextures);
end;
end;
RequestUpdateWorld := true;
end;
procedure TActor.ExportHeightMap(const _BaseDir, _Ext: string; _previewTextures: boolean);
var
i : integer;
begin
for i := Low(Models) to High(Models) do
begin
if Models[i] <> nil then
begin
Models[i]^.ExportHeightMap(_BaseDir,_Ext,_previewTextures);
end;
end;
RequestUpdateWorld := true;
end;
// Transparency methods
procedure TActor.ForceTransparency(_level: single);
var
i : integer;
begin
for i := Low(Models) to High(Models) do
begin
if Models[i] <> nil then
begin
Models[i]^.ForceTransparency(_level);
end;
end;
RequestUpdateWorld := true;
end;
procedure TActor.ForceTransparencyOnMesh(_Level: single; _ModelID,_MeshID: integer);
begin
if Models[_ModelID] <> nil then
begin
Models[_ModelID]^.ForceTransparencyOnMesh(_Level,_MeshID);
end;
RequestUpdateWorld := true;
end;
procedure TActor.ForceTransparencyExceptOnAMesh(_Level: single; _ModelID,_MeshID: integer);
begin
if Models[_ModelID] <> nil then
begin
Models[_ModelID]^.ForceTransparencyExceptOnAMesh(_Level,_MeshID);
end;
RequestUpdateWorld := true;
end;
// Mesh Operations
procedure TActor.RemoveInvisibleFaces;
var
i : integer;
begin
for i := Low(Models) to High(Models) do
begin
if Models[i] <> nil then
begin
Models[i]^.RemoveInvisibleFaces;
end;
end;
RequestUpdateWorld := true;
end;
// Quality Assurance
function TActor.GetAspectRatioHistogram(): THistogram;
var
i : integer;
begin
Result := THistogram.Create;
for i := Low(Models) to High(Models) do
begin
if Models[i] <> nil then
begin
Models[i]^.FillAspectRatioHistogram(Result);
end;
end;
end;
function TActor.GetSkewnessHistogram(): THistogram;
var
i : integer;
begin
Result := THistogram.Create;
for i := Low(Models) to High(Models) do
begin
if Models[i] <> nil then
begin
Models[i]^.FillSkewnessHistogram(Result);
end;
end;
end;
function TActor.GetSmoothnessHistogram(): THistogram;
var
i : integer;
begin
Result := THistogram.Create;
for i := Low(Models) to High(Models) do
begin
if Models[i] <> nil then
begin
Models[i]^.FillSmoothnessHistogram(Result);
end;
end;
end;
// Mesh Plugins
procedure TActor.AddNormalsPlugin;
var
i : integer;
begin
for i := Low(Models) to High(Models) do
begin
if Models[i] <> nil then
begin
Models[i]^.AddNormalsPlugin;
end;
end;
RequestUpdateWorld := true;
end;
procedure TActor.RemoveNormalsPlugin;
var
i : integer;
begin
for i := Low(Models) to High(Models) do
begin
if Models[i] <> nil then
begin
Models[i]^.RemoveNormalsPlugin;
end;
end;
RequestUpdateWorld := true;
end;
// Assign
procedure TActor.AssignForBackup(const _Source: TActor);
var
i : integer;
begin
RequestUpdateWorld := _Source.RequestUpdateWorld;
Next := _Source.Next;
for i := Low(_Source.Models) to High(_Source.Models) do
begin
Clone(_Source.Models[i]);
Models[i]^.ID := _Source.Models[i]^.ID;
end;
PositionAcceleration.X := _Source.PositionAcceleration.X;
PositionAcceleration.Y := _Source.PositionAcceleration.Y;
PositionAcceleration.Z := _Source.PositionAcceleration.Z;
PositionSpeed.X := _Source.PositionSpeed.X;
PositionSpeed.Y := _Source.PositionSpeed.Y;
PositionSpeed.Z := _Source.PositionSpeed.Z;
Position.X := _Source.Position.X;
Position.Y := _Source.Position.Y;
Position.Z := _Source.Position.Z;
RotationAcceleration.X := _Source.RotationAcceleration.X;
RotationAcceleration.Y := _Source.RotationAcceleration.Y;
RotationAcceleration.Z := _Source.RotationAcceleration.Z;
RotationSpeed.X := _Source.RotationSpeed.X;
RotationSpeed.Y := _Source.RotationSpeed.Y;
RotationSpeed.Z := _Source.RotationSpeed.Z;
Rotation.X := _Source.Rotation.X;
Rotation.Y := _Source.Rotation.Y;
Rotation.Z := _Source.Rotation.Z;
IsSelected := _Source.IsSelected;
ColoursType := _Source.ColoursType;
FactionColour := _Source.FactionColour;
ShaderBank := _Source.ShaderBank;
end;
end.
|
unit UFiles;
interface
implementation
uses
UTypes, UHistory, SysUtils, DateUtils;
const
HISTORY_PATH = 'history.dat';
{ Загружает историю из файла }
procedure readHistory(path: String);
var
historyFile: file of THistoryCell;
historyCell: THistoryCell;
begin
AssignFile(historyFile, path);
if FileExists(path) then
begin
Reset(historyFile);
while not eof(historyFile) do
begin
read(historyFile, historyCell);
if DaysBetween(historyCell.date, Today) < 5 then
addLastHistoryCell(historyCell);
end;
end
else
Rewrite(historyFile);
CloseFile(historyFile);
end;
{ Сохраняет историю в файл }
procedure saveHistory(path: String);
var
historyFile: file of THistoryCell;
historyCell: THistoryCell;
begin
AssignFile(historyFile, path);
Rewrite(historyFile);
while not isEmptyList do
begin
historyCell := pop;
write(historyFile, historyCell);
end;
CloseFile(historyFile);
end;
initialization
readHistory(HISTORY_PATH);
finalization
saveHistory(HISTORY_PATH);
end.
|
(*
* Copyright (c) 2011-2012, Ciobanu Alexandru
* All rights reserved.
*)
unit Myloo.Comp.Coll.Serialization;
interface
uses
SysUtils,
TypInfo,
Classes,
Rtti,
Generics.Collections,
Myloo.Comp.Coll.Base;
type
/// <summary>Annotate this attribute on fields that should not be serialized.</summary>
NonSerialized = class(TCustomAttribute);
/// <summary>An abstract base class for all serialization engines.</summary>
/// <remarks>Inherit this base class and implement its abstract methods to create a fully functional
/// serialization engine capable of serializing most data types provided by Delphi.</remarks>
TSerializer = class abstract(TInterfacedObject)
private
FObjectReg: TDictionary<Pointer, Int32>;
FDynArrayReg: TDictionary<Pointer, Int32>;
FRecordReg: TDictionary<Pointer, Int32>;
FLastId: Int32;
FSkipErrors: Boolean;
FRttiContext: TRttiContext;
procedure ErrorNotSupported(const ATypeInfo: PTypeInfo);
procedure ErrorNotEnoughRtti(const ATypeInfo: PTypeInfo);
procedure ErrorNoFieldRtti(const AField: TRttiField);
procedure SerializeInternal(const AType: TRttiType; const AValueRef: Pointer);
procedure WriteStaticArray(const ATypeInfo: PTypeInfo; const ARefToFirstElement: Pointer);
procedure WriteDynamicArray(const ATypeInfo: PTypeInfo; const ADynArray: Pointer);
procedure WriteRecord(const ATypeInfo: PTypeInfo; const ARefToRecord: Pointer);
procedure WriteClass(const ATypeInfo: PTypeInfo; const AObject: TObject);
protected
/// <summary>Specifies the RTTI context object used by this serializer to obtain the required
/// type information. Can be used in descending classes.</summary>
/// <returns>A RTTI context object.</returns>
property RttiContext: TRttiContext read FRttiContext;
/// <summary>Writes a 8-bit signed integer.</summary>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// facilitate writing of the specified value.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteInt8(const AValue: Int8); virtual; abstract;
/// <summary>Writes a 8-bit unsigned integer.</summary>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// facilitate writing of the specified value.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteUInt8(const AValue: UInt8); virtual; abstract;
/// <summary>Writes a 16-bit signed integer.</summary>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// facilitate writing of the specified value.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteInt16(const AValue: Int16); virtual; abstract;
/// <summary>Writes a 16-bit unsigned integer.</summary>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// facilitate writing of the specified value.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteUInt16(const AValue: UInt16); virtual; abstract;
/// <summary>Writes a 32-bit signed integer.</summary>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// facilitate writing of the specified value.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteInt32(const AValue: Int32); virtual; abstract;
/// <summary>Writes a 32-bit unsigned integer.</summary>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// facilitate writing of the specified value.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteUInt32(const AValue: UInt32); virtual; abstract;
/// <summary>Writes a 64-bit signed integer.</summary>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// facilitate writing of the specified value.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteInt64(const AValue: Int64); virtual; abstract;
/// <summary>Writes a 64-bit unsigned integer.</summary>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// facilitate writing of the specified value.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteUInt64(const AValue: UInt64); virtual; abstract;
/// <summary>Writes a single byte ANSI character.</summary>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// facilitate writing of the specified value.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteAnsiChar(const AValue: AnsiChar); virtual; abstract;
/// <summary>Writes a two byte WIDE character.</summary>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// facilitate writing of the specified value.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteWideChar(const AValue: WideChar); virtual; abstract;
/// <summary>Writes a single precision floating point value.</summary>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// facilitate writing of the specified value.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteSingle(const AValue: Single); virtual; abstract;
/// <summary>Writes a double precision floating point value.</summary>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// facilitate writing of the specified value.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteDouble(const AValue: Double); virtual; abstract;
/// <summary>Writes an extended precision floating point value.</summary>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// facilitate writing of the specified value.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteExtended(const AValue: Extended); virtual; abstract;
/// <summary>Writes a comp floating point value.</summary>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// facilitate writing of the specified value.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteComp(const AValue: Comp); virtual; abstract;
/// <summary>Writes a currency floating point value.</summary>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// facilitate writing of the specified value.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteCurrency(const AValue: Currency); virtual; abstract;
/// <summary>Writes a short ANSI string.</summary>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// facilitate writing of the specified value.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteShortString(const AValue: ShortString); virtual; abstract;
/// <summary>Writes a long ANSI string.</summary>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// facilitate writing of the specified value.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteAnsiString(const AValue: AnsiString); virtual; abstract;
/// <summary>Writes a long WIDE string.</summary>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// facilitate writing of the specified value.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteWideString(const AValue: WideString); virtual; abstract;
/// <summary>Writes a long UNICODE string.</summary>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// facilitate writing of the specified value.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteUnicodeString(const AValue: UnicodeString); virtual; abstract;
/// <summary>Writes a metaclass. Note that a metaclass might not be resolvable on deserialization.</summary>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// facilitate writing of the specified value.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteMetaClass(const AValue: TClass); virtual; abstract;
/// <summary>Writes a set.</summary>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <param name="ASetSize">The size in bytes of a set value.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteSet(const ASetSize: UInt8; const AValue); virtual; abstract;
/// <summary>Writes an enumeration.</summary>
/// <param name="AValue">The ordinal value of the enumeration.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteEnum(const AValue: Int64); virtual; abstract;
/// <summary>Notifies the serializer that the serialization for the root type is started.</summary>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// mark the beggining of the serialization process. This is a convenience method, if the serializer needs not prepare
/// itself then a simple empty implementation is enough.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure BeginWriteRoot(); virtual; abstract;
/// <summary>Notifies the serializer that the serialization for the root type has ended.</summary>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// mark the ending of the serialization process. This is a convenience method, if the serializer needs not prepare
/// itself then a simple empty implementation is enough.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure EndWriteRoot(); virtual; abstract;
/// <summary>Notifies the serializer that a class or record field is about to be serialized.</summary>
/// <param name="AField">The field RTTI information.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// prepare it for an upcoming field value. This method will never be called with a <c>nil</c> value.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure BeginWriteField(const AField: TRttiField); overload; virtual; abstract;
/// <summary>Notifies the serializer that a pseudo-field (otherwise known as a "label") is about to be serialized.</summary>
/// <param name="ALabel">The name of the pseudo-field.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes in order to
/// prepare it for an upcoming field value. The supplied <paramref name="ALabel" /> argument can hold anything inclusing and empty string.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure BeginWriteField(const ALabel: String); overload; virtual; abstract;
/// <summary>Notifies the serializer that a field or a label was serialized.</summary>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. This method marks the end
/// of serialization of a field or label.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure EndWriteField(); virtual; abstract;
/// <summary>Notifies the serializer that a record is about to be serialized.</summary>
/// <param name="ARecordType">The record RTTI information.</param>
/// <param name="AId">An internal ID that uniquily identifies this record.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. The supplied <paramref name="ARecordType"/>
/// will never be <c>nil</c>. The inheriting class should store some of the RTTI information along with the generated <paramref name="AId" />,
/// which will be required on deserialization.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure BeginWriteRecord(const ARecordType: TRttiRecordType; const AId: Int32); overload; virtual; abstract;
/// <summary>Notifies the serializer that a record was serialized.</summary>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. This method marks the end
/// of serialization of a record. It will only be called if <c>BeginWriteRecord</c> was priorly called.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure EndWriteRecord(); virtual; abstract;
/// <summary>Notifies the serializer that a record reference is about to be serialized.</summary>
/// <param name="AReference">An internal ID that uniquily identifies the referenced record.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. This method
/// is called if the serialier notices that the address of the record is the same with the address of another record that was already serialized
/// thus it needs only to store a "pointer" to that record. The supplied <paramref name="AReference" /> is the unique ID of the record that was already serialized
/// and has the same address with this one. Note, this method will only be called for "pointer to record" types and not static records.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteRecordReference(const AReference: Int32); virtual; abstract;
/// <summary>Notifies the serializer that a <c>nil</c> record reference is about to be serialized.</summary>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. This method
/// is called if the serialier notices that the address of the record is <c>nil</c> and thus there is nothing to do. Note, this method
/// will only be called for "pointer to record" types and not static records.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteNilRecordReference(); virtual; abstract;
/// <summary>Notifies the serializer that a class is about to be serialized.</summary>
/// <param name="AClassType">The class RTTI information.</param>
/// <param name="AType">The metaclass of the class.</param>
/// <param name="AId">An internal ID that uniquily identifies this class.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. The supplied <paramref name="AClassType"/>
/// will never be <c>nil</c>. The inheriting class should store some of the RTTI information, the meta class along with the generated <paramref name="AId" />,
/// which will be required on deserialization. This method is only called if the class was not already serialized.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure BeginWriteClass(const AClassType: TRttiInstanceType; const AType: TClass; const AId: Int32); virtual; abstract;
/// <summary>Notifies the serializer that a class was serialized.</summary>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. This method marks the end
/// of serialization of a class. It will only be called if <c>BeginWriteClass</c> was priorly called.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure EndWriteClass(); virtual; abstract;
/// <summary>Notifies the serializer that a class reference is about to be serialized.</summary>
/// <param name="AReference">An internal ID that uniquily identifies the referenced class.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. This method
/// is called if the serialier notices that the address of the class instance is the same with the address of another class instance
/// that was already serialized thus it needs only to store a "pointer" to that class instance. The supplied <paramref name="AReference" />
/// is the unique ID of the class instance that was already serialized and has the same address with this one.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteClassReference(const AReference: Int32); virtual; abstract;
/// <summary>Notifies the serializer that a <c>nil</c> class instance is about to be serialized.</summary>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. This method
/// is called if the serialier notices that the address of the class instance is <c>nil</c> and thus there is nothing to do. It is also impossible to
/// obtain the metaclass from a <c>nil</c> instance.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteNilClassReference(); virtual; abstract;
/// <summary>Notifies the serializer that a static array is about to be serialized.</summary>
/// <param name="AArrayType">The array RTTI information.</param>
/// <param name="ANumberOfElements">The number of elements that the array contains.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. This method must store some RTTI information along
/// with the number of elements. This information will be used later on deserialization time.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure BeginWriteStaticArray(const AArrayType: TRttiArrayType; const ANumberOfElements: NativeInt); virtual; abstract;
/// <summary>Notifies the serializer that a static array was serialized.</summary>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. This method marks the end
/// of serialization of a static array. It will only be called if <c>BeginWriteStaticArray</c> was priorly called.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure EndWriteStaticArray(); virtual; abstract;
/// <summary>Notifies the serializer that a dynamic array is about to be serialized.</summary>
/// <param name="AArrayType">The array RTTI information.</param>
/// <param name="ANumberOfElements">The number of elements to serialize. Can never be a value of zero.</param>
/// <param name="AId">An internal ID that uniquily identifies this array.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. The supplied <paramref name="AArrayType"/>
/// will never be <c>nil</c>. The inheriting class should store some of the RTTI information, the number of elements along with the generated <paramref name="AId" />,
/// which will be required on deserialization. This method is only called if the dynamic array was not already serialized.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure BeginWriteDynamicArray(const AArrayType: TRttiDynamicArrayType; const ANumberOfElements: NativeInt; const AId: Int32); virtual; abstract;
/// <summary>Notifies the serializer that a dynamic array was serialized.</summary>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. This method marks the end
/// of serialization of a dynamic array. It will only be called if <c>BeginWriteDynamicArray</c> was priorly called.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure EndWriteDynamicArray(); virtual; abstract;
/// <summary>Notifies the serializer that a dynamic array reference is about to be serialized.</summary>
/// <param name="AReference">An internal ID that uniquily identifies the referenced array.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. This method
/// is called if the serialier notices that the address of the array is the same with the address of another array
/// that was already serialized thus it needs only to store a "pointer" to that array. The supplied <paramref name="AReference" />
/// is the unique ID of the array that was already serialized and has the same address with this one.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteDynamicArrayReference(const AReference: Int32); virtual; abstract;
/// <summary>Notifies the serializer that a <c>nil</c> dynamic array is about to be serialized.</summary>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. This method
/// is called if the serialier notices that the address of the dynamic array is <c>nil</c> and thus there is nothing to do.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure WriteNilDynamicArrayReference(); virtual; abstract;
public
/// <summary>Creates a new serializer instance.</summary>
/// <remarks>When descending from this class this constructor must be called. If not called, some internal
/// data structures will remain un-initialized.</remarks>
constructor Create();
/// <summary>Destroys this serializer instance.</summary>
/// <remarks>Never forget to call this destructor in descendant classes, otherwise memory leaks will occur.</remarks>
destructor Destroy(); override;
/// <summary>Serializes an object.</summary>
/// <param name="AObject">The object that needs to be serialized. Can be <c>nil</c>.</param>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure Serialize(const AObject: TObject); overload;
/// <summary>Serializes an value.</summary>
/// <param name="ATypeInfo">The value's type information.</param>
/// <param name="AValue">The value that needs to be serialized.</param>
/// <exception cref="SysUtils|EArgumentNilException"><paramref name="ATypeInfo"/> is <c>nil</c>.</exception>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure Serialize(const ATypeInfo: PTypeInfo; const AValue); overload;
/// <summary>Serializes an generic value.</summary>
/// <param name="AValue">The value that needs to be serialized.</param>
/// <exception cref="SysUtils|EArgumentNilException"><paramref name="AValue"/> does not have RTTI.</exception>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure Serialize<T>(const AValue: T); overload;
/// <summary>Specifies whether the serializer throws exceptions for values that cannot be serialized.</summary>
/// <returns><c>True</c> if serializer skips problematic fields; <c>False</c> if the serializer raises an exception on
/// problematic fields.</returns>
property SkipErrors: Boolean read FSkipErrors write FSkipErrors;
/// <summary>Creates a new default serializer.</summary>
/// <param name="AStream">The stream into which to serialize.</param>
/// <returns>A new default binary serializer.</returns>
/// <remarks>Generally, serializers are not reusable for separate contexts. This means that after you serialize a root type
/// the serializer needs to be destroyed.</remarks>
/// <exception cref="SysUtils|EArgumentNilException"><paramref name="AStream"/> is <c>nil</c>.</exception>
class function Default(const AStream: TStream): TSerializer; static;
end;
/// <summary>An abstract base class for all deserialization engines.</summary>
/// <remarks>Inherit this base class and implement its abstract methods to create a fully functional
/// deserialization engine. A serialization engine must also be developed to complement the deserialization engine.</remarks>
TDeserializer = class abstract(TInterfacedObject)
protected type
/// <summary>Defines the possible ways a referencef type is stored.</summary>
TReferenceType = (
/// <summary>The type was stored completely. All fields or elements were stored.</summary>
rtInline,
/// <summary>The type was not stored, but rather a reference to another "instance" was stored.</summary>
rtPointer,
/// <summary>The type was not stored because it was a <c>nil</c> reference.</summary>
rtNil
);
private
FObjectReg: TDictionary<Int32, Pointer>;
FDynArrayReg: TDictionary<Int32, Pointer>;
FRecordReg: TDictionary<Int32, Pointer>;
FSkipErrors: Boolean;
FRttiContext: TRttiContext;
procedure ErrorNotSupported(const ATypeInfo: PTypeInfo);
procedure ErrorNotEnoughRtti(const ATypeInfo: PTypeInfo);
procedure ErrorNoFieldRtti(const AField: TRttiField);
procedure DeserializeInternal(const AType: TRttiType; const AValueRef: Pointer);
function CreateInstance(const AClassType: TRttiInstanceType): TObject;
procedure ReadStaticArray(const ATypeInfo: PTypeInfo; const ARefToFirstElement: Pointer);
procedure ReadDynamicArray(const ATypeInfo: PTypeInfo; out ADynArray: Pointer);
procedure ReadRecord(const ATypeInfo: PTypeInfo; var ARefToRecord: Pointer);
procedure ReadClass(const ATypeInfo: PTypeInfo; out AObject: TObject);
protected
/// <summary>Specifies the RTTI context object used by this deserializer to obtain the required
/// type information. Can be used in descending classes.</summary>
/// <returns>A RTTI context object.</returns>
property RttiContext: TRttiContext read FRttiContext;
/// <summary>Reads a 8-bit signed integer.</summary>
/// <param name="AValue">The output value in which read data is stored.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. A correct implementation must
/// verify that the next value in the stream is indeed compatible with this read request and only then read it. Otherwise, the deserializer
/// must raise an exception.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure ReadInt8(out AValue: Int8); virtual; abstract;
/// <summary>Reads a 8-bit unsigned integer.</summary>
/// <param name="AValue">The output value in which read data is stored.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. A correct implementation must
/// verify that the next value in the stream is indeed compatible with this read request and only then read it. Otherwise, the deserializer
/// must raise an exception.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure ReadUInt8(out AValue: UInt8); virtual; abstract;
/// <summary>Reads a 16-bit signed integer.</summary>
/// <param name="AValue">The output value in which read data is stored.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. A correct implementation must
/// verify that the next value in the stream is indeed compatible with this read request and only then read it. Otherwise, the deserializer
/// must raise an exception.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure ReadInt16(out AValue: Int16); virtual; abstract;
/// <summary>Reads a 16-bit unsigned integer.</summary>
/// <param name="AValue">The output value in which read data is stored.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. A correct implementation must
/// verify that the next value in the stream is indeed compatible with this read request and only then read it. Otherwise, the deserializer
/// must raise an exception.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure ReadUInt16(out AValue: UInt16); virtual; abstract;
/// <summary>Reads a 32-bit signed integer.</summary>
/// <param name="AValue">The output value in which read data is stored.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. A correct implementation must
/// verify that the next value in the stream is indeed compatible with this read request and only then read it. Otherwise, the deserializer
/// must raise an exception.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure ReadInt32(out AValue: Int32); virtual; abstract;
/// <summary>Reads a 32-bit unsigned integer.</summary>
/// <param name="AValue">The output value in which read data is stored.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. A correct implementation must
/// verify that the next value in the stream is indeed compatible with this read request and only then read it. Otherwise, the deserializer
/// must raise an exception.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure ReadUInt32(out AValue: UInt32); virtual; abstract;
/// <summary>Reads a 64-bit signed integer.</summary>
/// <param name="AValue">The output value in which read data is stored.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. A correct implementation must
/// verify that the next value in the stream is indeed compatible with this read request and only then read it. Otherwise, the deserializer
/// must raise an exception.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure ReadInt64(out AValue: Int64); virtual; abstract;
/// <summary>Reads a 64-bit unsigned integer.</summary>
/// <param name="AValue">The output value in which read data is stored.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. A correct implementation must
/// verify that the next value in the stream is indeed compatible with this read request and only then read it. Otherwise, the deserializer
/// must raise an exception.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure ReadUInt64(out AValue: UInt64); virtual; abstract;
/// <summary>Reads a single byte ANSI character.</summary>
/// <param name="AValue">The output value in which read data is stored.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. A correct implementation must
/// verify that the next value in the stream is indeed compatible with this read request and only then read it. Otherwise, the deserializer
/// must raise an exception.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure ReadAnsiChar(out AValue: AnsiChar); virtual; abstract;
/// <summary>Reads a two byte WIDE character.</summary>
/// <param name="AValue">The output value in which read data is stored.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. A correct implementation must
/// verify that the next value in the stream is indeed compatible with this read request and only then read it. Otherwise, the deserializer
/// must raise an exception.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure ReadWideChar(out AValue: WideChar); virtual; abstract;
/// <summary>Reads a single precision floating point value.</summary>
/// <param name="AValue">The output value in which read data is stored.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. A correct implementation must
/// verify that the next value in the stream is indeed compatible with this read request and only then read it. Otherwise, the deserializer
/// must raise an exception.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure ReadSingle(out AValue: Single); virtual; abstract;
/// <summary>Reads a double precision floating point value.</summary>
/// <param name="AValue">The output value in which read data is stored.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. A correct implementation must
/// verify that the next value in the stream is indeed compatible with this read request and only then read it. Otherwise, the deserializer
/// must raise an exception.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure ReadDouble(out AValue: Double); virtual; abstract;
/// <summary>Reads an extended precision floating point value.</summary>
/// <param name="AValue">The output value in which read data is stored.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. A correct implementation must
/// verify that the next value in the stream is indeed compatible with this read request and only then read it. Otherwise, the deserializer
/// must raise an exception.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure ReadExtended(out AValue: Extended); virtual; abstract;
/// <summary>Reads a comp floating point value.</summary>
/// <param name="AValue">The output value in which read data is stored.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. A correct implementation must
/// verify that the next value in the stream is indeed compatible with this read request and only then read it. Otherwise, the deserializer
/// must raise an exception.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure ReadComp(out AValue: Comp); virtual; abstract;
/// <summary>Reads a currency floating point value.</summary>
/// <param name="AValue">The output value in which read data is stored.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. A correct implementation must
/// verify that the next value in the stream is indeed compatible with this read request and only then read it. Otherwise, the deserializer
/// must raise an exception.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure ReadCurrency(out AValue: Currency); virtual; abstract;
/// <summary>Reads a short ANSI string.</summary>
/// <param name="AValue">The output value in which read data is stored.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. A correct implementation must
/// verify that the next value in the stream is indeed compatible with this read request and only then read it. Otherwise, the deserializer
/// must raise an exception.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure ReadShortString(out AValue: ShortString); virtual; abstract;
/// <summary>Reads a long ANSI string.</summary>
/// <param name="AValue">The output value in which read data is stored.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. A correct implementation must
/// verify that the next value in the stream is indeed compatible with this read request and only then read it. Otherwise, the deserializer
/// must raise an exception.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure ReadAnsiString(out AValue: AnsiString); virtual; abstract;
/// <summary>Reads a long WIDE string.</summary>
/// <param name="AValue">The output value in which read data is stored.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. A correct implementation must
/// verify that the next value in the stream is indeed compatible with this read request and only then read it. Otherwise, the deserializer
/// must raise an exception.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure ReadWideString(out AValue: WideString); virtual; abstract;
/// <summary>Reads a long UNICODE string.</summary>
/// <param name="AValue">The output value in which read data is stored.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. A correct implementation must
/// verify that the next value in the stream is indeed compatible with this read request and only then read it. Otherwise, the deserializer
/// must raise an exception.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure ReadUnicodeString(out AValue: UnicodeString); virtual; abstract;
/// <summary>Reads a meta class.</summary>
/// <param name="AValue">The output value in which read data is stored.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. A correct implementation must
/// verify that the next value in the stream is indeed compatible with this read request and only then read it. Otherwise, the deserializer
/// must raise an exception.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure ReadMetaClass(out AValue: TClass); virtual; abstract;
/// <summary>Reads a set.</summary>
/// <param name="ASetSize">The size of the expected set.</param>
/// <param name="AValue">The output value in which read data is stored.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure ReadSet(const ASetSize: UInt8; out AValue); virtual; abstract;
/// <summary>Reads an enumeration.</summary>
/// <param name="AValue">The output value in which read data is stored.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure ReadEnum(out AValue: Int64); virtual; abstract;
/// <summary>Notifies the deserializer that the root type is about to be read.</summary>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. It marks the
/// beggining of the deserialization process.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure BeginReadRoot(); virtual; abstract;
/// <summary>Notifies the deserializer that the root type was read.</summary>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. It marks the
/// end of the deserialization process.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure EndReadRoot(); virtual; abstract;
/// <summary>Notifies the deserializer that a field is about to be read.</summary>
/// <param name="AField">The field RTTI information. Can never be <c>nil</c>.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. The descendant class must
/// read RTTI and informational data that the complementing serializer has writtern.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure BeginReadField(const AField: TRttiField); overload; virtual; abstract;
/// <summary>Notifies the deserializer that a label is about to be read.</summary>
/// <param name="ALabel">The label. Can be any string including an empty one.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure BeginReadField(const ALabel: String); overload; virtual; abstract;
/// <summary>Notifies the deserializer that a field or label was read.</summary>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. It marks the
/// end of a field or label deserialization.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure EndReadField(); virtual; abstract;
/// <summary>Notifies the deserializer that a record is about to be read.</summary>
/// <param name="ARecordType">The record RTTI information. Can never be <c>nil</c>.</param>
/// <param name="AId">The expected unique record ID as assigned by the serializer. <param name="AId"/> should be filled if the result
/// of this function is <c>rtInline</c> or <c>rtPointer</c>.</param>
/// <returns><c>rtInline</c> is the record is serialized inline. <c>rtPointer</c> if the read data is actually a pointer to another record,
/// in which case <paramref name="AId"/> identifies the pointed record. A result of <c>rtNil</c> means that a <c>nil</c> reference is read.</returns>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. The descending deserializer must return the proper
/// type of serialized entry.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
function BeginReadRecord(const ARecordType: TRttiRecordType; out AId: Int32): TReferenceType; virtual; abstract;
/// <summary>Notifies the deserializer that a record was read.</summary>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. It marks the
/// end of a record deserialization and is called only if <c>BeginReadRecord</c> was called priorly.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure EndReadRecord(); virtual; abstract;
/// <summary>Notifies the deserializer that a class is about to be read.</summary>
/// <param name="AClassType">The class RTTI information. Can never be <c>nil</c>.</param>
/// <param name="AType">The expected metaclass that is used to instantiate the class. If a <c>nil</c> value is returned, RTTI class info is used (which can be wrong).</param>
/// <param name="AId">The expected unique class ID as assigned by the serializer. <param name="AId"/> should be filled if the result
/// of this function is <c>rtInline</c> or <c>rtPointer</c>.</param>
/// <returns><c>rtInline</c> is the class is serialized inline. <c>rtPointer</c> if the read data is actually a pointer to another class,
/// in which case <paramref name="AId"/> identifies the pointed class. A result of <c>rtNil</c> means that a <c>nil</c> reference is read.</returns>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. The descending deserializer must return the proper
/// type of serialized entry.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
function BeginReadClass(const AClassType: TRttiInstanceType; out AType: TClass; out AId: Int32): TReferenceType; virtual; abstract;
/// <summary>Notifies the deserializer that a class was read.</summary>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. It marks the
/// end of a record deserialization and is called only if <c>BeginReadClass</c> was called priorly.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure EndReadClass(); virtual; abstract;
/// <summary>Notifies the deserializer that a static array is about to be read.</summary>
/// <param name="AArrayType">The array RTTI information. Can never be <c>nil</c>.</param>
/// <param name="ANumberOfElements">The number of expected array elements.</param>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure BeginReadStaticArray(const AArrayType: TRttiArrayType; const ANumberOfElements: NativeInt); virtual; abstract;
/// <summary>Notifies the deserializer that a static array was read.</summary>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. It marks the
/// end of a record deserialization and is called only if <c>BeginReadDynamicArray</c> was called priorly.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure EndReadStaticArray(); virtual; abstract;
/// <summary>Notifies the deserializer that a dynamic array is about to be read.</summary>
/// <param name="AArrayType">The class RTTI information. Can never be <c>nil</c>.</param>
/// <param name="ANumberOfElements">The number of written array elements. Always greater than zero.</param>
/// <param name="AId">The expected unique array ID as assigned by the serializer. <param name="AId"/> should be filled if the result
/// of this function is <c>rtInline</c> or <c>rtPointer</c>.</param>
/// <returns><c>rtInline</c> is the array is serialized inline. <c>rtPointer</c> if the read data is actually a pointer to another array,
/// in which case <paramref name="AId"/> identifies the pointed array. A result of <c>rtNil</c> means that a <c>nil</c> reference is read.</returns>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. The descending deserializer must return the proper
/// type of serialized entry.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
function BeginReadDynamicArray(const AArrayType: TRttiDynamicArrayType; out ANumberOfElements: NativeInt; out AId: Int32): TReferenceType; virtual; abstract;
/// <summary>Notifies the deserializer that a dynamic array was read.</summary>
/// <remarks>This is an abstract method that must be implemented in desceding serializer classes. It marks the
/// end of a record deserialization and is called only if <c>BeginReadDynamicArray</c> was called priorly.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of deserialization problems.</exception>
procedure EndReadDynamicArray(); virtual; abstract;
public
/// <summary>Creates a new deserializer instance.</summary>
/// <remarks>When descending from this class this constructor must be called. If not called, some internal
/// data structures will remain un-initialized.</remarks>
constructor Create();
/// <summary>Destroys this deserializer instance.</summary>
/// <remarks>Never forget to call this destructor in descendant classes, otherwise memory leaks will occur.</remarks>
destructor Destroy(); override;
/// <summary>Deserializes an object.</summary>
/// <returns>The deserialized object.</returns>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function Deserialize(): TObject; overload;
/// <summary>Serializes an generic value.</summary>
/// <returns>The deserialized value.</returns>
/// <exception cref="SysUtils|EArgumentNilException"><paramref name="AValue"/> does not have RTTI.</exception>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function Deserialize<T>(): T; overload;
/// <summary>Deserializes an value.</summary>
/// <param name="ATypeInfo">The value's type information.</param>
/// <param name="AValue">The location of the value that needs to be deserialized.</param>
/// <exception cref="SysUtils|EArgumentNilException"><paramref name="ATypeInfo"/> is <c>nil</c>.</exception>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
procedure Deserialize(const ATypeInfo: PTypeInfo; out AValue); overload;
/// <summary>Specifies whether the deserializer throws exceptions for values that cannot be deserialized.</summary>
/// <returns><c>True</c> if deserializer skips problematic fields; <c>False</c> if the deserializer raises an exception on
/// problematic fields.</returns>
property SkipErrors: Boolean read FSkipErrors write FSkipErrors;
/// <summary>Creates a new default deserializer.</summary>
/// <param name="AStream">The stream from which to deserialize.</param>
/// <returns>A new default binary deserializer.</returns>
/// <remarks>Generally, deserializers are not reusable for separate contexts. This means that after you deserialize a root type
/// the serializer needs to be destroyed.</remarks>
/// <exception cref="SysUtils|EArgumentNilException"><paramref name="AStream"/> is <c>nil</c>.</exception>
class function Default(const AStream: TStream): TDeserializer; static;
end;
/// <summary>Defines a set of methods that can be used to write data to a serialization engine in a safe way.</summary>
/// <remarks>This type wraps a serialization engine and exposes some of its functionality to the consumer classes in a safe way.
/// This type is used by the <see cref="Collections.Serialization|ISerializable" /> interface. Note that all write operations must be performed in the same
/// order the read operation will be performed when the class will be deserialized.</remarks>
TOutputContext = record
private
FSerializer: TSerializer;
class function Create(const ASerializer: TSerializer): TOutputContext; static;
public
/// <summary>Writes a 8-bit signed integer using a given label.</summary>
/// <param name="AName">The name of the value to write. Otherwise known as the "label".</param>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <returns>This <see cref="Collections.Serialization|TOutputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function AddValue(const AName: String; const AValue: Int8): TOutputContext; overload;
/// <summary>Writes a 8-bit unsigned integer using a given label.</summary>
/// <param name="AName">The name of the value to write. Otherwise known as the "label".</param>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <returns>This <see cref="Collections.Serialization|TOutputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function AddValue(const AName: String; const AValue: UInt8): TOutputContext; overload;
/// <summary>Writes a 16-bit signed integer using a given label.</summary>
/// <param name="AName">The name of the value to write. Otherwise known as the "label".</param>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <returns>This <see cref="Collections.Serialization|TOutputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function AddValue(const AName: String; const AValue: Int16): TOutputContext; overload;
/// <summary>Writes a 16-bit unsigned integer using a given label.</summary>
/// <param name="AName">The name of the value to write. Otherwise known as the "label".</param>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <returns>This <see cref="Collections.Serialization|TOutputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function AddValue(const AName: String; const AValue: UInt16): TOutputContext; overload;
/// <summary>Writes a 32-bit signed integer using a given label.</summary>
/// <param name="AName">The name of the value to write. Otherwise known as the "label".</param>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <returns>This <see cref="Collections.Serialization|TOutputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function AddValue(const AName: String; const AValue: Int32): TOutputContext; overload;
/// <summary>Writes a 32-bit unsigned integer using a given label.</summary>
/// <param name="AName">The name of the value to write. Otherwise known as the "label".</param>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <returns>This <see cref="Collections.Serialization|TOutputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function AddValue(const AName: String; const AValue: UInt32): TOutputContext; overload;
/// <summary>Writes a 64-bit signed integer using a given label.</summary>
/// <param name="AName">The name of the value to write. Otherwise known as the "label".</param>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <returns>This <see cref="Collections.Serialization|TOutputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function AddValue(const AName: String; const AValue: Int64): TOutputContext; overload;
/// <summary>Writes a 64-bit unsigned integer using a given label.</summary>
/// <param name="AName">The name of the value to write. Otherwise known as the "label".</param>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <returns>This <see cref="Collections.Serialization|TOutputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function AddValue(const AName: String; const AValue: UInt64): TOutputContext; overload;
/// <summary>Writes a single byte ANSI character using a given label.</summary>
/// <param name="AName">The name of the value to write. Otherwise known as the "label".</param>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <returns>This <see cref="Collections.Serialization|TOutputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function AddValue(const AName: String; const AValue: AnsiChar): TOutputContext; overload;
/// <summary>Writes a two byte WIDE character using a given label.</summary>
/// <param name="AName">The name of the value to write. Otherwise known as the "label".</param>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <returns>This <see cref="Collections.Serialization|TOutputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function AddValue(const AName: String; const AValue: WideChar): TOutputContext; overload;
/// <summary>Writes a single precision floating point number using a given label.</summary>
/// <param name="AName">The name of the value to write. Otherwise known as the "label".</param>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <returns>This <see cref="Collections.Serialization|TOutputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function AddValue(const AName: String; const AValue: Single): TOutputContext; overload;
/// <summary>Writes a double precision floating point number using a given label.</summary>
/// <param name="AName">The name of the value to write. Otherwise known as the "label".</param>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <returns>This <see cref="Collections.Serialization|TOutputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function AddValue(const AName: String; const AValue: Double): TOutputContext; overload;
/// <summary>Writes an extended precision floating point number using a given label.</summary>
/// <param name="AName">The name of the value to write. Otherwise known as the "label".</param>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <returns>This <see cref="Collections.Serialization|TOutputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function AddValue(const AName: String; const AValue: Extended): TOutputContext; overload;
/// <summary>Writes a comp floating point number using a given label.</summary>
/// <param name="AName">The name of the value to write. Otherwise known as the "label".</param>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <returns>This <see cref="Collections.Serialization|TOutputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function AddValue(const AName: String; const AValue: Comp): TOutputContext; overload;
/// <summary>Writes a currency floating point number using a given label.</summary>
/// <param name="AName">The name of the value to write. Otherwise known as the "label".</param>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <returns>This <see cref="Collections.Serialization|TOutputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function AddValue(const AName: String; const AValue: Currency): TOutputContext; overload;
/// <summary>Writes a short ANSI string using a given label.</summary>
/// <param name="AName">The name of the value to write. Otherwise known as the "label".</param>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <returns>This <see cref="Collections.Serialization|TOutputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function AddValue(const AName: String; const AValue: ShortString): TOutputContext; overload;
/// <summary>Writes a long ANSI string using a given label.</summary>
/// <param name="AName">The name of the value to write. Otherwise known as the "label".</param>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <returns>This <see cref="Collections.Serialization|TOutputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function AddValue(const AName: String; const AValue: AnsiString): TOutputContext; overload;
/// <summary>Writes a long WIDE string using a given label.</summary>
/// <param name="AName">The name of the value to write. Otherwise known as the "label".</param>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <returns>This <see cref="Collections.Serialization|TOutputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function AddValue(const AName: String; const AValue: WideString): TOutputContext; overload;
/// <summary>Writes a long UNICODE string using a given label.</summary>
/// <param name="AName">The name of the value to write. Otherwise known as the "label".</param>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <returns>This <see cref="Collections.Serialization|TOutputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function AddValue(const AName: String; const AValue: UnicodeString): TOutputContext; overload;
/// <summary>Writes a metaclass using a given label. Note that the metaclass might not be resolvable on deserialization.</summary>
/// <param name="AName">The name of the value to write. Otherwise known as the "label".</param>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <returns>This <see cref="Collections.Serialization|TOutputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function AddValue(const AName: String; const AValue: TClass): TOutputContext; overload;
/// <summary>Writes an object using a given label. Note that the object's metaclass might not be resolvable on deserialization.</summary>
/// <param name="AName">The name of the value to write. Otherwise known as the "label".</param>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <returns>This <see cref="Collections.Serialization|TOutputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function AddValue(const AName: String; const AValue: TObject): TOutputContext; overload;
/// <summary>Writes a generic value using a given label.</summary>
/// <param name="AName">The name of the value to write. Otherwise known as the "label".</param>
/// <param name="AValue">The value containing the actual data to write.</param>
/// <returns>This <see cref="Collections.Serialization|TOutputContext" />. Can be used to chain read operations.</returns>
/// <remarks>This method can be used to serialize anything, starting with simple values like integer and ending in types such as arrays of records.</remarks>
/// <exception cref="Collections.Base|ESerializationException">A wide variety of serialization problems.</exception>
function AddValue<T>(const AName: String; const AValue: T): TOutputContext; overload;
end;
/// <summary>Defines a set of methods that can be used to read data from a deserialization engine in a safe way.</summary>
/// <remarks>This type wraps a deserialization engine and exposes some of its functionality to the consumer classes in a safe way.
/// This type is used by the <see cref="Collections.Serialization|ISerializable" /> interface. Note that all read operations must be performed in the same
/// order the write operation were performed when the class was serialized.</remarks>
TInputContext = record
private
FDeserializer: TDeserializer;
class function Create(const ADeserializer: TDeserializer): TInputContext; static;
public
/// <summary>Reads a 8-bit signed integer using a given label.</summary>
/// <param name="AName">The name of the value to read. Otherwise known as the "label".</param>
/// <param name="AValue">An output value containing the read data.</param>
/// <returns>This <see cref="Collections.Serialization|TInputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">The provided label wasn't found or the requested type is invalid.</exception>
function GetValue(const AName: String; out AValue: Int8): TInputContext; overload;
/// <summary>Reads a 8-bit unsigned integer using a given label.</summary>
/// <param name="AName">The name of the value to read. Otherwise known as the "label".</param>
/// <param name="AValue">An output value containing the read data.</param>
/// <returns>This <see cref="Collections.Serialization|TInputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">The provided label wasn't found or the requested type is invalid.</exception>
function GetValue(const AName: String; out AValue: UInt8): TInputContext; overload;
/// <summary>Reads a 16-bit signed integer using a given label.</summary>
/// <param name="AName">The name of the value to read. Otherwise known as the "label".</param>
/// <param name="AValue">An output value containing the read data.</param>
/// <returns>This <see cref="Collections.Serialization|TInputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">The provided label wasn't found or the requested type is invalid.</exception>
function GetValue(const AName: String; out AValue: Int16): TInputContext; overload;
/// <summary>Reads a 16-bit unsigned integer using a given label.</summary>
/// <param name="AName">The name of the value to read. Otherwise known as the "label".</param>
/// <param name="AValue">An output value containing the read data.</param>
/// <returns>This <see cref="Collections.Serialization|TInputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">The provided label wasn't found or the requested type is invalid.</exception>
function GetValue(const AName: String; out AValue: UInt16): TInputContext; overload;
/// <summary>Reads a 32-bit signed integer using a given label.</summary>
/// <param name="AName">The name of the value to read. Otherwise known as the "label".</param>
/// <param name="AValue">An output value containing the read data.</param>
/// <returns>This <see cref="Collections.Serialization|TInputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">The provided label wasn't found or the requested type is invalid.</exception>
function GetValue(const AName: String; out AValue: Int32): TInputContext; overload;
/// <summary>Reads a 32-bit unsigned integer using a given label.</summary>
/// <param name="AName">The name of the value to read. Otherwise known as the "label".</param>
/// <param name="AValue">An output value containing the read data.</param>
/// <returns>This <see cref="Collections.Serialization|TInputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">The provided label wasn't found or the requested type is invalid.</exception>
function GetValue(const AName: String; out AValue: UInt32): TInputContext; overload;
/// <summary>Reads a 64-bit signed integer using a given label.</summary>
/// <param name="AName">The name of the value to read. Otherwise known as the "label".</param>
/// <param name="AValue">An output value containing the read data.</param>
/// <returns>This <see cref="Collections.Serialization|TInputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">The provided label wasn't found or the requested type is invalid.</exception>
function GetValue(const AName: String; out AValue: Int64): TInputContext; overload;
/// <summary>Reads a 64-bit signed integer using a given label.</summary>
/// <param name="AName">The name of the value to read. Otherwise known as the "label".</param>
/// <param name="AValue">An output value containing the read data.</param>
/// <returns>This <see cref="Collections.Serialization|TInputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">The provided label wasn't found or the requested type is invalid.</exception>
function GetValue(const AName: String; out AValue: UInt64): TInputContext; overload;
/// <summary>Reads a single byte ANSI character.</summary>
/// <param name="AName">The name of the value to read. Otherwise known as the "label".</param>
/// <param name="AValue">An output value containing the read data.</param>
/// <returns>This <see cref="Collections.Serialization|TInputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">The provided label wasn't found or the requested type is invalid.</exception>
function GetValue(const AName: String; out AValue: AnsiChar): TInputContext; overload;
/// <summary>Reads a two-byte WIDE character.</summary>
/// <param name="AName">The name of the value to read. Otherwise known as the "label".</param>
/// <param name="AValue">An output value containing the read data.</param>
/// <returns>This <see cref="Collections.Serialization|TInputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">The provided label wasn't found or the requested type is invalid.</exception>
function GetValue(const AName: String; out AValue: WideChar): TInputContext; overload;
/// <summary>Reads a single precision floating point number.</summary>
/// <param name="AName">The name of the value to read. Otherwise known as the "label".</param>
/// <param name="AValue">An output value containing the read data.</param>
/// <returns>This <see cref="Collections.Serialization|TInputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">The provided label wasn't found or the requested type is invalid.</exception>
function GetValue(const AName: String; out AValue: Single): TInputContext; overload;
/// <summary>Reads a double precision floating point number.</summary>
/// <param name="AName">The name of the value to read. Otherwise known as the "label".</param>
/// <param name="AValue">An output value containing the read data.</param>
/// <returns>This <see cref="Collections.Serialization|TInputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">The provided label wasn't found or the requested type is invalid.</exception>
function GetValue(const AName: String; out AValue: Double): TInputContext; overload;
/// <summary>Reads an extended precision floating point number.</summary>
/// <param name="AName">The name of the value to read. Otherwise known as the "label".</param>
/// <param name="AValue">An output value containing the read data.</param>
/// <returns>This <see cref="Collections.Serialization|TInputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">The provided label wasn't found or the requested type is invalid.</exception>
function GetValue(const AName: String; out AValue: Extended): TInputContext; overload;
/// <summary>Reads comp floating point number.</summary>
/// <param name="AName">The name of the value to read. Otherwise known as the "label".</param>
/// <param name="AValue">An output value containing the read data.</param>
/// <returns>This <see cref="Collections.Serialization|TInputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">The provided label wasn't found or the requested type is invalid.</exception>
function GetValue(const AName: String; out AValue: Comp): TInputContext; overload;
/// <summary>Reads currency floating point number.</summary>
/// <param name="AName">The name of the value to read. Otherwise known as the "label".</param>
/// <param name="AValue">An output value containing the read data.</param>
/// <returns>This <see cref="Collections.Serialization|TInputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">The provided label wasn't found or the requested type is invalid.</exception>
function GetValue(const AName: String; out AValue: Currency): TInputContext; overload;
/// <summary>Reads short ANSI string.</summary>
/// <param name="AName">The name of the value to read. Otherwise known as the "label".</param>
/// <param name="AValue">An output value containing the read data.</param>
/// <returns>This <see cref="Collections.Serialization|TInputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">The provided label wasn't found or the requested type is invalid.</exception>
function GetValue(const AName: String; out AValue: ShortString): TInputContext; overload;
/// <summary>Reads a long ANSI string.</summary>
/// <param name="AName">The name of the value to read. Otherwise known as the "label".</param>
/// <param name="AValue">An output value containing the read data.</param>
/// <returns>This <see cref="Collections.Serialization|TInputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">The provided label wasn't found or the requested type is invalid.</exception>
function GetValue(const AName: String; out AValue: AnsiString): TInputContext; overload;
/// <summary>Reads a long WIDE string.</summary>
/// <param name="AName">The name of the value to read. Otherwise known as the "label".</param>
/// <param name="AValue">An output value containing the read data.</param>
/// <returns>This <see cref="Collections.Serialization|TInputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">The provided label wasn't found or the requested type is invalid.</exception>
function GetValue(const AName: String; out AValue: WideString): TInputContext; overload;
/// <summary>Reads a long UNICODE string.</summary>
/// <param name="AName">The name of the value to read. Otherwise known as the "label".</param>
/// <param name="AValue">An output value containing the read data.</param>
/// <returns>This <see cref="Collections.Serialization|TInputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">The provided label wasn't found or the requested type is invalid.</exception>
function GetValue(const AName: String; out AValue: UnicodeString): TInputContext; overload;
/// <summary>Reads a metaclass. If the metaclass cannot be resolved to a real type a <c>nil</c> values is returned.</summary>
/// <param name="AName">The name of the value to read. Otherwise known as the "label".</param>
/// <param name="AValue">An output value containing the read data.</param>
/// <returns>This <see cref="Collections.Serialization|TInputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">The provided label wasn't found or the requested type is invalid.</exception>
function GetValue(const AName: String; out AValue: TClass): TInputContext; overload;
/// <summary>Reads an object instance. If the metaclass of the object cannot be resolved the mest match is used.</summary>
/// <param name="AName">The name of the value to read. Otherwise known as the "label".</param>
/// <param name="AValue">An output value containing the read data.</param>
/// <returns>This <see cref="Collections.Serialization|TInputContext" />. Can be used to chain read operations.</returns>
/// <exception cref="Collections.Base|ESerializationException">The provided label wasn't found or the requested type is invalid.</exception>
function GetValue(const AName: String; out AValue: TObject): TInputContext; overload;
/// <summary>Reads a generic value. Use this method when none of the above overloads are helpful.</summary>
/// <param name="AName">The name of the value to read. Otherwise known as the "label".</param>
/// <param name="AValue">An output value containing the read data.</param>
/// <returns>This <see cref="Collections.Serialization|TInputContext" />. Can be used to chain read operations.</returns>
/// <remarks>This method can be used to deserialize anything, starting with simple values like integer and ending in types such as arrays of records. If the serialized data
/// is not compatible with the provided generic argument an exception will occur.</remarks>
/// <exception cref="Collections.Base|ESerializationException">The provided label wasn't found or the requested type is invalid.</exception>
function GetValue<T>(const AName: String; out AValue: T): TInputContext; overload;
end;
/// <summary>Defines a set of methods that need to be implemented by classes in order
/// to override the default serialization support.</summary>
/// <remarks>Implement this interface only if custom serialization code is needed for a
/// class. A class implementing this interface need not to worry about the reference counting mechanics. The serialization engine
/// will not modify the reference count of the instance being serialized or deserializaed.</remarks>
ISerializable = interface
['{F00C10CC-1744-4905-B4C9-F158DCF6A7A7}']
/// <summary>Serializes the instance of the class that implements this interface.</summary>
/// <param name="AContext">The output serialization context into which values need to be added.</param>
/// <remarks>This method is called automatically by the serialization engine when the class implementing this interface
/// is serialized. Use the provided context object to serialize distinct values that make up the object.</remarks>
procedure Serialize(const AContext: TOutputContext);
/// <summary>Deserializes the instance of the class that implements this interface.</summary>
/// <param name="AContext">The input serialization context from which values need to be read.</param>
/// <remarks>This method is called automatically by the deserialization engine when the class implementing this interface
/// is deserialized. Use the provided context object to read distinct values that make up the object. Note that this method is called
/// right after the default parameterless constructor of the class is called. The constructor need to prepare the object.</remarks>
procedure Deserialize(const AContext: TInputContext);
end;
implementation
function IsSerializable(const AField: TRttiField): Boolean;
var
LAttr: TCustomAttribute;
begin
ASSERT(Assigned(AField));
for LAttr in AField.GetAttributes() do
if LAttr is NonSerialized then
Exit(False);
Result := True;
end;
procedure GetSafeInterface(const AObject: TObject; const AIID: TGUID; var AOut: Pointer);
var
LIntfEntry: PInterfaceEntry;
begin
AOut := nil;
{ Nothing on nil object }
if not Assigned(AObject) then
Exit;
{ Obtain the interface entry }
LIntfEntry := AObject.GetInterfaceEntry(AIID);
{ If there is such an interface and it has an Object offset, get it }
if (Assigned(LIntfEntry)) and (LIntfEntry^.IOffset <> 0) then
AOut := Pointer(NativeUInt(AObject) + NativeUInt(LIntfEntry^.IOffset));
{ Note: No AddRef is performed since we have no idea if the object
has ref cont > 0 already! We're only using the "pseudo-intf" entry }
end;
type
PInt8 = ^Int8;
PUInt8 = ^UInt8;
PInt16 = ^Int16;
PUInt16 = ^UInt16;
PInt32 = ^Int32;
PUInt32 = ^UInt32;
PInt64 = ^Int64;
PUInt64 = ^UInt64;
PClass = ^TClass;
{$REGION 'Binary Serialization'}
type
TStreamedValueType = (
svStartRoot, svEndRoot,
svStartRecord, svEndRecord, svReferencedRecord, svNilRecord,
svStartField, svStartLabel, svEndField,
svStartClass, svEndClass, svReferencedClass, svNilClass,
svStartStaticArray, svEndStaticArray,
svStartDynamicArray, svEndDynamicArray, svReferencedDynamicArray, svNilDynamicArray,
svInt8, svUInt8, svInt16, svUInt16, svInt32, svUInt32, svInt64, svUInt64,
svSingle, svDouble, svExtended, svComp, svCurrency,
svAnsiChar, svWideChar,
svShortString, svAnsiString, svWideString, svUnicodeString,
svMetaClass, svNilMetaClass,
svEnum, svSet
);
TStreamedValueTypes = set of TStreamedValueType;
TBinarySerializer = class(TSerializer)
private
FStream: TStream;
procedure WriteCustomType(const AType: TRttiType);
procedure WriteType(const AType: TStreamedValueType);
procedure WriteData(const ASize: NativeInt; const AData);
protected
procedure WriteInt8(const AValue: Int8); override;
procedure WriteUInt8(const AValue: UInt8); override;
procedure WriteInt16(const AValue: Int16); override;
procedure WriteUInt16(const AValue: UInt16); override;
procedure WriteInt32(const AValue: Int32); override;
procedure WriteUInt32(const AValue: UInt32); override;
procedure WriteInt64(const AValue: Int64); override;
procedure WriteUInt64(const AValue: UInt64); override;
procedure WriteAnsiChar(const AValue: AnsiChar); override;
procedure WriteWideChar(const AValue: WideChar); override;
procedure WriteSingle(const AValue: Single); override;
procedure WriteDouble(const AValue: Double); override;
procedure WriteExtended(const AValue: Extended); override;
procedure WriteComp(const AValue: Comp); override;
procedure WriteCurrency(const AValue: Currency); override;
procedure WriteShortString(const AValue: ShortString); override;
procedure WriteAnsiString(const AValue: AnsiString); override;
procedure WriteWideString(const AValue: WideString); override;
procedure WriteUnicodeString(const AValue: UnicodeString); override;
procedure WriteMetaClass(const AValue: TClass); override;
procedure WriteSet(const ASetSize: UInt8; const AValue); override;
procedure WriteEnum(const AValue: Int64); override;
procedure BeginWriteRoot(); override;
procedure EndWriteRoot(); override;
procedure BeginWriteField(const AField: TRttiField); overload; override;
procedure BeginWriteField(const ALabel: String); overload; override;
procedure EndWriteField(); override;
procedure BeginWriteRecord(const ARecordType: TRttiRecordType; const AId: Int32); override;
procedure EndWriteRecord(); override;
procedure WriteRecordReference(const AReference: Int32); override;
procedure WriteNilRecordReference(); override;
procedure BeginWriteClass(const AClassType: TRttiInstanceType; const AType: TClass; const AId: Int32); override;
procedure EndWriteClass(); override;
procedure WriteClassReference(const AReference: Int32); override;
procedure WriteNilClassReference(); override;
procedure BeginWriteStaticArray(const AArrayType: TRttiArrayType; const ANumberOfElements: NativeInt); override;
procedure EndWriteStaticArray(); override;
procedure BeginWriteDynamicArray(const AArrayType: TRttiDynamicArrayType; const ANumberOfElements: NativeInt; const AId: Int32); override;
procedure EndWriteDynamicArray(); override;
procedure WriteDynamicArrayReference(const AReference: Int32); override;
procedure WriteNilDynamicArrayReference(); override;
public
constructor Create(const AStream: TStream);
end;
TBinaryDeserializer = class(TDeserializer)
private
FStream: TStream;
procedure ExpectType(const AWhatType: TRttiType);
procedure Expect(const AWhat: TStreamedValueType); overload;
function Expect(const AWhat: TStreamedValueTypes): TStreamedValueType; overload;
procedure ReadData(const ASize: NativeInt; out AData);
function GetMetaClass(const AUnit, AClass: String): TClass;
protected
procedure ReadInt8(out AValue: Int8); override;
procedure ReadUInt8(out AValue: UInt8); override;
procedure ReadInt16(out AValue: Int16); override;
procedure ReadUInt16(out AValue: UInt16); override;
procedure ReadInt32(out AValue: Int32); override;
procedure ReadUInt32(out AValue: UInt32); override;
procedure ReadInt64(out AValue: Int64); override;
procedure ReadUInt64(out AValue: UInt64); override;
procedure ReadAnsiChar(out AValue: AnsiChar); override;
procedure ReadWideChar(out AValue: WideChar); override;
procedure ReadSingle(out AValue: Single); override;
procedure ReadDouble(out AValue: Double); override;
procedure ReadExtended(out AValue: Extended); override;
procedure ReadComp(out AValue: Comp); override;
procedure ReadCurrency(out AValue: Currency); override;
procedure ReadShortString(out AValue: ShortString); override;
procedure ReadAnsiString(out AValue: AnsiString); override;
procedure ReadWideString(out AValue: WideString); override;
procedure ReadUnicodeString(out AValue: UnicodeString); override;
procedure ReadMetaClass(out AValue: TClass); override;
procedure ReadSet(const ASetSize: UInt8; out AValue); override;
procedure ReadEnum(out AValue: Int64); override;
procedure BeginReadRoot(); override;
procedure EndReadRoot(); override;
procedure BeginReadField(const AField: TRttiField); overload; override;
procedure BeginReadField(const ALabel: String); overload; override;
procedure EndReadField(); override;
function BeginReadRecord(const ARecordType: TRttiRecordType; out AId: Int32): TDeserializer.TReferenceType; override;
procedure EndReadRecord(); override;
function BeginReadClass(const AClassType: TRttiInstanceType; out AType: TClass; out AId: Int32): TDeserializer.TReferenceType; override;
procedure EndReadClass(); override;
procedure BeginReadStaticArray(const AArrayType: TRttiArrayType; const ANumberOfElements: NativeInt); override;
procedure EndReadStaticArray(); override;
function BeginReadDynamicArray(const AArrayType: TRttiDynamicArrayType; out ANumberOfElements: NativeInt; out AId: Int32): TDeserializer.TReferenceType; override;
procedure EndReadDynamicArray(); override;
public
constructor Create(const AStream: TStream);
end;
{ TBinarySerializer }
procedure TBinarySerializer.BeginWriteClass(const AClassType: TRttiInstanceType; const AType: TClass; const AId: Int32);
begin
WriteType(svStartClass);
WriteMetaClass(AType);
WriteInt32(AId);
end;
procedure TBinarySerializer.BeginWriteDynamicArray(const AArrayType: TRttiDynamicArrayType; const ANumberOfElements: NativeInt; const AId: Int32);
begin
ASSERT(Assigned(AArrayType));
ASSERT(ANumberOfElements > 0);
WriteType(svStartDynamicArray);
WriteCustomType(AArrayType);
WriteInt32(AId);
WriteInt64(ANumberOfElements);
end;
procedure TBinarySerializer.BeginWriteField(const ALabel: String);
begin
WriteType(svStartLabel);
WriteUnicodeString(ALabel);
end;
procedure TBinarySerializer.BeginWriteField(const AField: TRttiField);
begin
ASSERT(Assigned(AField));
WriteType(svStartField);
WriteCustomType(AField.FieldType);
WriteUnicodeString(AField.Name);
WriteInt64(AField.Offset);
end;
procedure TBinarySerializer.BeginWriteRecord(const ARecordType: TRttiRecordType; const AId: Int32);
begin
ASSERT(Assigned(ARecordType));
WriteType(svStartRecord);
WriteCustomType(ARecordType);
WriteInt32(AId);
end;
procedure TBinarySerializer.BeginWriteRoot;
begin
WriteType(svStartRoot);
end;
procedure TBinarySerializer.BeginWriteStaticArray(const AArrayType: TRttiArrayType; const ANumberOfElements: NativeInt);
begin
ASSERT(Assigned(AArrayType));
WriteType(svStartStaticArray);
WriteCustomType(AArrayType);
WriteInt64(ANumberOfElements);
end;
constructor TBinarySerializer.Create(const AStream: TStream);
begin
inherited Create();
if not Assigned(AStream) then
ExceptionHelper.Throw_ArgumentNilError('AStream');
FStream := AStream;
end;
procedure TBinarySerializer.EndWriteClass;
begin
WriteType(svEndClass);
end;
procedure TBinarySerializer.EndWriteDynamicArray;
begin
WriteType(svEndDynamicArray);
end;
procedure TBinarySerializer.EndWriteField;
begin
WriteType(svEndField);
end;
procedure TBinarySerializer.EndWriteRecord;
begin
WriteType(svEndRecord);
end;
procedure TBinarySerializer.EndWriteRoot;
begin
WriteType(svEndRoot);
end;
procedure TBinarySerializer.EndWriteStaticArray;
begin
WriteType(svEndStaticArray);
end;
procedure TBinarySerializer.WriteAnsiChar(const AValue: AnsiChar);
begin
WriteType(svAnsiChar);
WriteData(SizeOf(AValue), AValue);
end;
procedure TBinarySerializer.WriteAnsiString(const AValue: AnsiString);
var
LCodePage: UInt16;
LLength: NativeInt;
begin
LLength := Length(AValue);
LCodePage := StringCodePage(AValue);
WriteType(svAnsiString);
WriteData(SizeOf(LCodePage), LCodePage);
WriteData(SizeOf(LLength), LLength);
WriteData(LLength, AValue[1]);
end;
procedure TBinarySerializer.WriteClassReference(const AReference: Int32);
begin
WriteType(svReferencedClass);
WriteInt32(AReference);
end;
procedure TBinarySerializer.WriteComp(const AValue: Comp);
begin
WriteType(svComp);
WriteData(SizeOf(AValue), AValue);
end;
procedure TBinarySerializer.WriteCurrency(const AValue: Currency);
begin
WriteType(svCurrency);
WriteData(SizeOf(AValue), AValue);
end;
procedure TBinarySerializer.WriteCustomType(const AType: TRttiType);
begin
ASSERT(Assigned(AType));
WriteUnicodeString(AType.Name);
end;
procedure TBinarySerializer.WriteData(const ASize: NativeInt; const AData);
begin
FStream.WriteBuffer(AData, ASize);
end;
procedure TBinarySerializer.WriteDouble(const AValue: Double);
begin
WriteType(svDouble);
WriteData(SizeOf(AValue), AValue);
end;
procedure TBinarySerializer.WriteDynamicArrayReference(const AReference: Int32);
begin
WriteType(svReferencedDynamicArray);
WriteData(SizeOf(AReference), AReference);
end;
procedure TBinarySerializer.WriteEnum(const AValue: Int64);
begin
WriteType(svEnum);
WriteData(SizeOf(AValue), AValue);
end;
procedure TBinarySerializer.WriteExtended(const AValue: Extended);
begin
WriteType(svExtended);
WriteData(SizeOf(AValue), AValue);
end;
procedure TBinarySerializer.WriteInt16(const AValue: Int16);
begin
WriteType(svInt16);
WriteData(SizeOf(AValue), AValue);
end;
procedure TBinarySerializer.WriteInt32(const AValue: Int32);
begin
WriteType(svInt32);
WriteData(SizeOf(AValue), AValue);
end;
procedure TBinarySerializer.WriteInt64(const AValue: Int64);
begin
WriteType(svInt64);
WriteData(SizeOf(AValue), AValue);
end;
procedure TBinarySerializer.WriteInt8(const AValue: Int8);
begin
WriteType(svInt8);
WriteData(SizeOf(AValue), AValue);
end;
procedure TBinarySerializer.WriteMetaClass(const AValue: TClass);
begin
if Assigned(AValue) then
begin
WriteType(svMetaClass);
WriteUnicodeString(AValue.UnitName);
WriteUnicodeString(AValue.ClassName);
end else
WriteType(svNilMetaClass);
end;
procedure TBinarySerializer.WriteNilClassReference;
begin
WriteType(svNilClass);
end;
procedure TBinarySerializer.WriteNilDynamicArrayReference;
begin
WriteType(svNilDynamicArray);
end;
procedure TBinarySerializer.WriteNilRecordReference;
begin
WriteType(svNilRecord);
end;
procedure TBinarySerializer.WriteRecordReference(const AReference: Int32);
begin
WriteType(svReferencedRecord);
WriteInt32(AReference);
end;
procedure TBinarySerializer.WriteSet(const ASetSize: UInt8; const AValue);
begin
WriteType(svSet);
WriteUInt8(ASetSize);
WriteData(ASetSize, AValue);
end;
procedure TBinarySerializer.WriteShortString(const AValue: ShortString);
var
LLength: UInt8;
begin
LLength := Length(AValue);
WriteType(svShortString);
WriteData(SizeOf(LLength), LLength);
WriteData(LLength, AValue[1]);
end;
procedure TBinarySerializer.WriteSingle(const AValue: Single);
begin
WriteType(svSingle);
WriteData(SizeOf(AValue), AValue);
end;
procedure TBinarySerializer.WriteType(const AType: TStreamedValueType);
begin
FStream.WriteBuffer(AType, SizeOf(AType));
end;
procedure TBinarySerializer.WriteUInt16(const AValue: UInt16);
begin
WriteType(svUInt16);
WriteData(SizeOf(AValue), AValue);
end;
procedure TBinarySerializer.WriteUInt32(const AValue: UInt32);
begin
WriteType(svUInt32);
WriteData(SizeOf(AValue), AValue);
end;
procedure TBinarySerializer.WriteUInt64(const AValue: UInt64);
begin
WriteType(svUInt64);
WriteData(SizeOf(AValue), AValue);
end;
procedure TBinarySerializer.WriteUInt8(const AValue: UInt8);
begin
WriteType(svUInt8);
WriteData(SizeOf(AValue), AValue);
end;
procedure TBinarySerializer.WriteUnicodeString(const AValue: UnicodeString);
var
LLength: NativeInt;
LUtf8: RawByteString;
begin
LUtf8 := UTF8Encode(AValue);
LLength := Length(LUtf8);
WriteType(svUnicodeString);
WriteData(SizeOf(LLength), LLength);
WriteData(LLength, LUtf8[1]);
end;
procedure TBinarySerializer.WriteWideChar(const AValue: WideChar);
begin
WriteType(svWideChar);
WriteData(SizeOf(AValue), AValue);
end;
procedure TBinarySerializer.WriteWideString(const AValue: WideString);
var
LLength: NativeInt;
LUtf8: RawByteString;
begin
LUtf8 := UTF8Encode(AValue);
LLength := Length(LUtf8);
WriteType(svWideString);
WriteData(SizeOf(LLength), LLength);
WriteData(LLength, LUtf8[1]);
end;
{ TBinaryDeserializer }
function TBinaryDeserializer.BeginReadClass(const AClassType: TRttiInstanceType; out AType: TClass; out AId: Int32): TDeserializer.TReferenceType;
begin
ASSERT(Assigned(AClassType));
Result := rtInline;
case Expect([svStartClass, svReferencedClass, svNilClass]) of
svStartClass:
begin
ReadMetaClass(AType);
ReadInt32(AId);
end;
svReferencedClass:
begin
ReadInt32(AId);
Result := rtPointer;
end;
svNilClass:
Result := rtNil;
end;
end;
function TBinaryDeserializer.BeginReadDynamicArray(const AArrayType: TRttiDynamicArrayType;
out ANumberOfElements: NativeInt; out AId: Int32): TDeserializer.TReferenceType;
var
LCount: Int64;
begin
ASSERT(Assigned(AArrayType));
Result := rtInline;
case Expect([svStartDynamicArray, svReferencedDynamicArray, svNilDynamicArray]) of
svStartDynamicArray:
begin
ExpectType(AArrayType);
ReadInt32(AId);
ReadInt64(LCount);
ANumberOfElements := LCount;
end;
svReferencedDynamicArray:
begin
ReadInt32(AId);
Result := rtPointer;
end;
svNilDynamicArray:
Result := rtNil;
end;
end;
procedure TBinaryDeserializer.BeginReadField(const ALabel: String);
var
LLabel: String;
begin
Expect(svStartLabel);
ReadUnicodeString(LLabel);
if (LLabel <> ALabel) then
ExceptionHelper.Throw_ExpectedAnotherLabel(ALabel, LLabel);
end;
procedure TBinaryDeserializer.BeginReadField(const AField: TRttiField);
var
LName: String;
LOffset: Int64;
begin
ASSERT(Assigned(AField));
Expect(svStartField);
ExpectType(AField.FieldType);
ReadUnicodeString(LName);
ReadInt64(LOffset);
if (LName <> AField.Name) or (LOffset <> AField.Offset) then
ExceptionHelper.Throw_ExpectedAnotherField(AField, LName, LOffset);
end;
function TBinaryDeserializer.BeginReadRecord(const ARecordType: TRttiRecordType; out AId: Int32): TDeserializer.TReferenceType;
begin
ASSERT(Assigned(ARecordType));
Result := rtInline;
case Expect([svStartRecord, svReferencedRecord, svNilRecord]) of
svStartRecord:
begin
ExpectType(ARecordType);
ReadInt32(AId);
end;
svReferencedRecord:
begin
ReadInt32(AId);
Result := rtPointer;
end;
svNilRecord:
Result := rtNil;
end;
end;
procedure TBinaryDeserializer.BeginReadRoot;
begin
Expect(svStartRoot);
end;
procedure TBinaryDeserializer.BeginReadStaticArray(const AArrayType: TRttiArrayType; const ANumberOfElements: NativeInt);
var
LElements: Int64;
begin
ASSERT(Assigned(AArrayType));
Expect(svStartStaticArray);
ExpectType(AArrayType);
ReadInt64(LElements);
if (ANumberOfElements <> LElements) then
ExceptionHelper.Throw_ExpectedAnotherElementCount(AArrayType, ANumberOfElements, LElements);
end;
constructor TBinaryDeserializer.Create(const AStream: TStream);
begin
inherited Create();
if not Assigned(AStream) then
ExceptionHelper.Throw_ArgumentNilError('AStream');
FStream := AStream;
end;
procedure TBinaryDeserializer.EndReadClass;
begin
Expect(svEndClass);
end;
procedure TBinaryDeserializer.EndReadDynamicArray;
begin
Expect(svEndDynamicArray);
end;
procedure TBinaryDeserializer.EndReadField;
begin
Expect(svEndField);
end;
procedure TBinaryDeserializer.EndReadRecord;
begin
Expect(svEndRecord);
end;
procedure TBinaryDeserializer.EndReadRoot;
begin
Expect(svEndRoot);
end;
procedure TBinaryDeserializer.EndReadStaticArray;
begin
Expect(svEndStaticArray);
end;
function TBinaryDeserializer.Expect(const AWhat: TStreamedValueTypes): TStreamedValueType;
begin
FStream.ReadBuffer(Result, SizeOf(Result));
if not (Result in AWhat) then
ExceptionHelper.Throw_ExpectedAnotherBinaryValuePoint();
end;
procedure TBinaryDeserializer.ExpectType(const AWhatType: TRttiType);
var
LName: String;
begin
ASSERT(Assigned(AWhatType));
ReadUnicodeString(LName);
if (LName <> AWhatType.Name) then
ExceptionHelper.Throw_ExpectedAnotherType(AWhatType, LName);
end;
function TBinaryDeserializer.GetMetaClass(const AUnit, AClass: String): TClass;
var
LType: TRttiType;
begin
LType := RttiContext.FindType(AUnit + '.' + AClass);
{ Find out the type }
if LType is TRttiInstanceType then
Result := TRttiInstanceType(LType).MetaclassType
else
Result := nil;
end;
procedure TBinaryDeserializer.Expect(const AWhat: TStreamedValueType);
begin
Expect([AWhat]);
end;
procedure TBinaryDeserializer.ReadAnsiChar(out AValue: AnsiChar);
begin
Expect(svAnsiChar);
ReadData(SizeOf(AValue), AValue);
end;
procedure TBinaryDeserializer.ReadAnsiString(out AValue: AnsiString);
var
LCodePage: UInt16;
LLength: NativeInt;
begin
Expect(svAnsiString);
ReadData(SizeOf(LCodePage), LCodePage);
ReadData(SizeOf(LLength), LLength);
SetLength(AValue, LLength);
SetCodePage(RawByteString(AValue), LCodePage);
ReadData(LLength, AValue[1]);
end;
procedure TBinaryDeserializer.ReadComp(out AValue: Comp);
begin
Expect(svComp);
ReadData(SizeOf(AValue), AValue);
end;
procedure TBinaryDeserializer.ReadCurrency(out AValue: Currency);
begin
Expect(svCurrency);
ReadData(SizeOf(AValue), AValue);
end;
procedure TBinaryDeserializer.ReadData(const ASize: NativeInt; out AData);
begin
FStream.ReadBuffer(AData, ASize);
end;
procedure TBinaryDeserializer.ReadDouble(out AValue: Double);
begin
Expect(svDouble);
ReadData(SizeOf(AValue), AValue);
end;
procedure TBinaryDeserializer.ReadEnum(out AValue: Int64);
begin
Expect(svEnum);
ReadData(SizeOf(AValue), AValue);
end;
procedure TBinaryDeserializer.ReadExtended(out AValue: Extended);
begin
Expect(svExtended);
ReadData(SizeOf(AValue), AValue);
end;
procedure TBinaryDeserializer.ReadInt16(out AValue: Int16);
begin
Expect(svInt16);
ReadData(SizeOf(AValue), AValue);
end;
procedure TBinaryDeserializer.ReadInt32(out AValue: Int32);
begin
Expect(svInt32);
ReadData(SizeOf(AValue), AValue);
end;
procedure TBinaryDeserializer.ReadInt64(out AValue: Int64);
begin
Expect(svInt64);
ReadData(SizeOf(AValue), AValue);
end;
procedure TBinaryDeserializer.ReadInt8(out AValue: Int8);
begin
Expect(svInt8);
ReadData(SizeOf(AValue), AValue);
end;
procedure TBinaryDeserializer.ReadMetaClass(out AValue: TClass);
var
LUnit, LClass: String;
begin
case Expect([svMetaClass, svNilMetaClass]) of
svMetaClass:
begin
ReadUnicodeString(LUnit);
ReadUnicodeString(LClass);
AValue := GetMetaClass(LUnit, LClass);
end;
svNilMetaClass:
AValue := nil;
end;
end;
procedure TBinaryDeserializer.ReadSet(const ASetSize: UInt8; out AValue);
var
LSize: UInt8;
begin
Expect(svSet);
ReadUInt8(LSize);
if (LSize <> ASetSize) then
ExceptionHelper.Throw_ExpectedAnotherSetSize(ASetSize, LSize);
ReadData(LSize, AValue);
end;
procedure TBinaryDeserializer.ReadShortString(out AValue: ShortString);
var
LLength: UInt8;
begin
Expect(svShortString);
ReadData(SizeOf(LLength), LLength);
ReadData(LLength, AValue[1]);
AValue[0] := AnsiChar(LLength);
end;
procedure TBinaryDeserializer.ReadSingle(out AValue: Single);
begin
Expect(svSingle);
ReadData(SizeOf(AValue), AValue);
end;
procedure TBinaryDeserializer.ReadUInt16(out AValue: UInt16);
begin
Expect(svUInt16);
ReadData(SizeOf(AValue), AValue);
end;
procedure TBinaryDeserializer.ReadUInt32(out AValue: UInt32);
begin
Expect(svUInt32);
ReadData(SizeOf(AValue), AValue);
end;
procedure TBinaryDeserializer.ReadUInt64(out AValue: UInt64);
begin
Expect(svUInt64);
ReadData(SizeOf(AValue), AValue);
end;
procedure TBinaryDeserializer.ReadUInt8(out AValue: UInt8);
begin
Expect(svUInt8);
ReadData(SizeOf(AValue), AValue);
end;
procedure TBinaryDeserializer.ReadUnicodeString(out AValue: UnicodeString);
var
LLength: NativeInt;
Utf8: RawByteString;
begin
Expect(svUnicodeString);
ReadData(SizeOf(LLength), LLength);
SetLength(Utf8, LLength);
ReadData(LLength, Utf8[1]);
AValue := UTF8ToUnicodeString(Utf8);
end;
procedure TBinaryDeserializer.ReadWideChar(out AValue: WideChar);
begin
Expect(svWideChar);
ReadData(SizeOf(AValue), AValue);
end;
procedure TBinaryDeserializer.ReadWideString(out AValue: WideString);
var
LLength: NativeInt;
Utf8: RawByteString;
begin
Expect(svWideString);
ReadData(SizeOf(LLength), LLength);
SetLength(Utf8, LLength);
ReadData(LLength, Utf8[1]);
AValue := UTF8ToWideString(Utf8);
end;
{$ENDREGION}
{ TSerializer }
class function TSerializer.Default(const AStream: TStream): TSerializer;
begin
Result := TBinarySerializer.Create(AStream);
end;
constructor TSerializer.Create;
begin
FDynArrayReg := TDictionary<Pointer, Int32>.Create();
FObjectReg := TDictionary<Pointer, Int32>.Create();
FRecordReg := TDictionary<Pointer, Int32>.Create();
FSkipErrors := true;
end;
destructor TSerializer.Destroy;
begin
FRecordReg.Free;
FDynArrayReg.Free;
FObjectReg.Free;
inherited;
end;
procedure TSerializer.ErrorNoFieldRtti(const AField: TRttiField);
begin
if not FSkipErrors then
ExceptionHelper.Throw_FieldTypeDoesNotHaveEnoughRtti(AField);
end;
procedure TSerializer.ErrorNotEnoughRtti(const ATypeInfo: PTypeInfo);
begin
if not FSkipErrors then
ExceptionHelper.Throw_TypeDoesNotHaveEnoughRtti(ATypeInfo);
end;
procedure TSerializer.ErrorNotSupported(const ATypeInfo: PTypeInfo);
begin
if not FSkipErrors then
ExceptionHelper.Throw_TypeCannotBeSerialized(ATypeInfo);
end;
procedure TSerializer.Serialize(const ATypeInfo: PTypeInfo; const AValue);
begin
if not Assigned(ATypeInfo) then
ExceptionHelper.Throw_ArgumentNilError('ATypeInfo');
{ Call internal "un-checked" method. }
BeginWriteRoot();
SerializeInternal(FRttiContext.GetType(ATypeInfo), @AValue);
EndWriteRoot();
end;
procedure TSerializer.Serialize(const AObject: TObject);
begin
if Assigned(AObject) then
Serialize(AObject.ClassInfo, AObject)
else
Serialize(TypeInfo(TObject), AObject);
end;
procedure TSerializer.Serialize<T>(const AValue: T);
begin
Serialize(TypeInfo(T), AValue);
end;
procedure TSerializer.WriteClass(const ATypeInfo: PTypeInfo; const AObject: TObject);
var
LClass: TRttiInstanceType;
LField: TRttiField;
LClassId: Int32;
LSerializable: ISerializable;
begin
{ ARefToRecord points to the first field in the record }
ASSERT(ATypeInfo^.Kind = tkClass);
{ Get the class info }
LClass := nil;
if Assigned(AObject) then
LClass := FRttiContext.GetType(AObject.ClassType) as TRttiInstanceType;
if not Assigned(LClass) then
LClass := FRttiContext.GetType(ATypeInfo) as TRttiInstanceType;
if not Assigned(LClass) then
begin
ErrorNotEnoughRtti(ATypeInfo);
Exit;
end;
{ Check if the object is already serialized }
if not Assigned(AObject) then
WriteNilClassReference()
else if FObjectReg.TryGetValue(AObject, LClassId) then
WriteClassReference(LClassId)
else begin
{ Register object in the dictionary }
Inc(FLastId);
FObjectReg.Add(AObject, FLastId);
{ Notify that a class is being written }
BeginWriteClass(LClass, AObject.ClassType, FLastId);
{ Check if the class has it's own serialization code }
GetSafeInterface(AObject, ISerializable, Pointer(LSerializable));
if Assigned(LSerializable) then
begin
LSerializable.Serialize(TOutputContext.Create(Self));
Pointer(LSerializable) := nil;
end else begin
{ Walk through the record }
for LField in LClass.GetFields() do
begin
if not Assigned(LField.FieldType) then
begin
ErrorNoFieldRtti(LField);
continue;
end;
if IsSerializable(LField) then
begin
BeginWriteField(LField);
SerializeInternal(LField.FieldType, Pointer(LField.Offset + NativeInt(AObject)));
EndWriteField();
end;
end;
end;
EndWriteClass();
end;
end;
procedure TSerializer.WriteDynamicArray(const ATypeInfo: PTypeInfo; const ADynArray: Pointer);
var
LArray: TRttiDynamicArrayType;
LIndex, LCount: NativeInt;
LArrayId: Int32;
begin
{ ARefToRecord points to the first field in the record }
ASSERT(ATypeInfo^.Kind = tkDynArray);
LArray := FRttiContext.GetType(ATypeInfo) as TRttiDynamicArrayType;
if (not Assigned(LArray)) or (not Assigned(LArray.ElementType))then
begin
ErrorNotEnoughRtti(ATypeInfo);
Exit;
end;
{ Check if the array is already serialized }
if not Assigned(ADynArray) then
WriteNilDynamicArrayReference()
else if FDynArrayReg.TryGetValue(ADynArray, LArrayId) then
WriteDynamicArrayReference(LArrayId)
else begin
{ Register array in the dictionary }
Inc(FLastId);
FDynArrayReg.Add(ADynArray, LArrayId);
{ Obtain the count of elements }
LCount := DynArraySize(ADynArray);
{ Notify that a class is being written }
BeginWriteDynamicArray(LArray, LCount, FLastId);
{ Walk through the array }
for LIndex := 0 to LCount - 1 do
SerializeInternal(LArray.ElementType, Pointer(LIndex * LArray.ElementType.TypeSize + NativeInt(ADynArray)));
EndWriteDynamicArray();
end;
end;
procedure TSerializer.WriteRecord(const ATypeInfo: PTypeInfo; const ARefToRecord: Pointer);
var
LRecord: TRttiRecordType;
LField: TRttiField;
LRecordId: Int32;
begin
{ ARefToRecord points to the first field in the record }
ASSERT(ATypeInfo^.Kind = tkRecord);
LRecord := FRttiContext.GetType(ATypeInfo) as TRttiRecordType;
if not Assigned(LRecord) then
begin
ErrorNotEnoughRtti(ATypeInfo);
Exit;
end;
{ Check if the object is already serialized }
if not Assigned(ARefToRecord) then
WriteNilRecordReference()
else if FRecordReg.TryGetValue(ARefToRecord, LRecordId) then
WriteRecordReference(LRecordId)
else begin
{ Register object in the dictionary }
Inc(FLastId);
FRecordReg.Add(ARefToRecord, FLastId);
{ Notify that a class is being written }
BeginWriteRecord(LRecord, FLastId);
{ Walk through the record }
for LField in LRecord.GetFields() do
begin
if not Assigned(LField.FieldType) then
begin
ErrorNoFieldRtti(LField);
continue;
end;
if IsSerializable(LField) then
begin
BeginWriteField(LField);
SerializeInternal(LField.FieldType, Pointer(LField.Offset + NativeInt(ARefToRecord)));
EndWriteField();
end;
end;
EndWriteRecord();
end;
end;
procedure TSerializer.SerializeInternal(const AType: TRttiType; const AValueRef: Pointer);
var
LTypeData: PTypeData;
LSetOrd: Int64;
begin
LTypeData := GetTypeData(AType.Handle);
case AType.TypeKind of
tkProcedure,
tkUnknown,
tkMethod,
tkVariant,
tkInterface:
if not FSkipErrors then
ErrorNotSupported(AType.Handle);
tkEnumeration:
begin
LSetOrd := 0;
case AType.TypeSize of
1: LSetOrd := PInt8(AValueRef)^;
2: LSetOrd := PInt16(AValueRef)^;
4: LSetOrd := PInt32(AValueRef)^;
8: LSetOrd := PInt64(AValueRef)^;
else
ASSERT(False);
end;
WriteEnum(LSetOrd);
end;
tkSet:
WriteSet(AType.TypeSize, AValueRef^);
tkInteger:
begin
if Assigned(LTypeData) then
begin
case LTypeData^.OrdType of
otSByte:
WriteInt8(PInt8(AValueRef)^);
otUByte:
WriteUInt8(PUInt8(AValueRef)^);
otSWord:
WriteInt16(PInt16(AValueRef)^);
otUWord:
WriteUInt16(PUInt16(AValueRef)^);
otSLong:
WriteInt32(PInt32(AValueRef)^);
otULong:
WriteUInt32(PUInt32(AValueRef)^);
end;
end else
ErrorNotEnoughRtti(AType.Handle);
end;
tkInt64:
begin
if Assigned(LTypeData) then
begin
if LTypeData^.MaxInt64Value > LTypeData^.MinInt64Value then
WriteInt64(PInt64(AValueRef)^)
else
WriteUInt64(PUInt64(AValueRef)^);
end else
ErrorNotEnoughRtti(AType.Handle);
end;
tkChar:
WriteAnsiChar(PAnsiChar(AValueRef)^);
tkWChar:
WriteWideChar(PWideChar(AValueRef)^);
tkFloat:
begin
if Assigned(LTypeData) then
begin
case LTypeData^.FloatType of
ftSingle:
WriteSingle(PSingle(AValueRef)^);
ftDouble:
WriteDouble(PDouble(AValueRef)^);
ftExtended:
WriteExtended(PExtended(AValueRef)^);
ftComp:
WriteComp(PComp(AValueRef)^);
ftCurr:
WriteCurrency(PCurrency(AValueRef)^);
end;
end else
ErrorNotEnoughRtti(AType.Handle);
end;
tkString:
WriteShortString(PShortString(AValueRef)^);
tkLString:
WriteAnsiString(PAnsiString(AValueRef)^);
tkWString:
WriteWideString(PWideString(AValueRef)^);
tkUString:
WriteUnicodeString(PUnicodeString(AValueRef)^);
tkClassRef:
WriteMetaClass(PPointer(AValueRef)^);
tkRecord:
WriteRecord(AType.Handle, AValueRef);
tkClass:
WriteClass(AType.Handle, PPointer(AValueRef)^);
tkArray:
WriteStaticArray(AType.Handle, AValueRef);
tkDynArray:
WriteDynamicArray(AType.Handle, PPointer(AValueRef)^);
tkPointer:
begin
{ Check if this is apointer to a record }
if Assigned(LTypeData^.RefType) and Assigned(LTypeData^.RefType^) and (LTypeData^.RefType^^.Kind = tkRecord) then
WriteRecord(LTypeData^.RefType^, PPointer(AValueRef)^)
else
ErrorNotSupported(AType.Handle);
end;
end;
end;
procedure TSerializer.WriteStaticArray(const ATypeInfo: PTypeInfo; const ARefToFirstElement: Pointer);
var
LArray: TRttiArrayType;
LIndex: NativeInt;
begin
{ ARefToRecord points to the first field in the record }
ASSERT(ATypeInfo^.Kind = tkArray);
LArray := FRttiContext.GetType(ATypeInfo) as TRttiArrayType;
if (not Assigned(LArray)) or (not Assigned(LArray.ElementType)) then
begin
ErrorNotEnoughRtti(ATypeInfo);
Exit;
end;
{ Notify that a record is being written }
BeginWriteStaticArray(LArray, LArray.TotalElementCount);
{ Walk through the record }
for LIndex := 0 to LArray.TotalElementCount - 1 do
SerializeInternal(LArray.ElementType, Pointer(LIndex * LArray.ElementType.TypeSize + NativeInt(ARefToFirstElement)));
EndWriteStaticArray();
end;
{ TDeserializer }
class function TDeserializer.Default(const AStream: TStream): TDeserializer;
begin
Result := TBinaryDeserializer.Create(AStream);
end;
constructor TDeserializer.Create;
begin
FDynArrayReg := TDictionary<Int32, Pointer>.Create();
FObjectReg := TDictionary<Int32, Pointer>.Create();
FRecordReg := TDictionary<Int32, Pointer>.Create();
FSkipErrors := true;
end;
function TDeserializer.CreateInstance(const AClassType: TRttiInstanceType): TObject;
var
LMethod: TRttiMethod;
begin
if Assigned(AClassType) then
begin
{ Invoke the first parameterless constructor found. }
for LMethod in AClassType.GetMethods() do
if LMethod.HasExtendedInfo and LMethod.IsConstructor then
if LMethod.GetParameters() = nil then
Exit(LMethod.Invoke(AClassType.MetaclassType, []).AsObject);
{ Not found ... Use the old fashioned way }
Result := AClassType.MetaclassType.Create();
end else
Result := nil;
end;
procedure TDeserializer.Deserialize(const ATypeInfo: PTypeInfo; out AValue);
begin
if not Assigned(ATypeInfo) then
ExceptionHelper.Throw_ArgumentNilError('ATypeInfo');
{ Call internal "un-checked" method. }
BeginReadRoot();
DeserializeInternal(FRttiContext.GetType(ATypeInfo), @AValue);
EndReadRoot();
end;
function TDeserializer.Deserialize<T>: T;
begin
Deserialize(TypeInfo(T), Result);
end;
function TDeserializer.Deserialize: TObject;
begin
Deserialize(TypeInfo(TObject), Result);
end;
destructor TDeserializer.Destroy;
begin
FDynArrayReg.Free;
FObjectReg.Free;
FRecordReg.Free;
inherited;
end;
procedure TDeserializer.ErrorNoFieldRtti(const AField: TRttiField);
begin
if not FSkipErrors then
ExceptionHelper.Throw_FieldTypeDoesNotHaveEnoughRtti(AField);
end;
procedure TDeserializer.ErrorNotEnoughRtti(const ATypeInfo: PTypeInfo);
begin
if not FSkipErrors then
ExceptionHelper.Throw_TypeDoesNotHaveEnoughRtti(ATypeInfo);
end;
procedure TDeserializer.ErrorNotSupported(const ATypeInfo: PTypeInfo);
begin
if not FSkipErrors then
ExceptionHelper.Throw_TypeCannotBeSerialized(ATypeInfo);
end;
procedure TDeserializer.ReadClass(const ATypeInfo: PTypeInfo; out AObject: TObject);
var
LClass: TRttiInstanceType;
LField: TRttiField;
LClassId: Int32;
LClassType: TClass;
LSerializable: ISerializable;
begin
{ ARefToRecord points to the first field in the record }
ASSERT(ATypeInfo^.Kind = tkClass);
LClass := FRttiContext.GetType(ATypeInfo) as TRttiInstanceType;
if not Assigned(LClass) then
begin
ErrorNotEnoughRtti(ATypeInfo);
Exit;
end;
case BeginReadClass(LClass, LClassType, LClassId) of
rtInline:
begin
if Assigned(LClassType) then
LClass := FRttiContext.GetType(LClassType.ClassInfo) as TRttiInstanceType;
if not Assigned(LClass) then
LClass := FRttiContext.GetType(ATypeInfo) as TRttiInstanceType;
AObject := CreateInstance(LClass);
FObjectReg.AddOrSetValue(LClassId, Pointer(AObject));
try
GetSafeInterface(AObject, ISerializable, Pointer(LSerializable));
if Assigned(LSerializable) then
begin
LSerializable.Deserialize(TInputContext.Create(Self));
Pointer(LSerializable) := nil;
end else begin
{ Walk through the class }
for LField in LClass.GetFields() do
begin
if not Assigned(LField.FieldType) then
begin
ErrorNoFieldRtti(LField);
continue;
end;
if IsSerializable(LField) then
begin
BeginReadField(LField);
DeserializeInternal(LField.FieldType, Pointer(LField.Offset + NativeInt(AObject)));
EndReadField();
end;
end;
end;
EndReadClass();
except
AObject.Free;
AObject := nil;
end;
end;
rtPointer:
begin
if not FObjectReg.TryGetValue(LClassId, Pointer(AObject)) then
ExceptionHelper.Throw_BadClassReference(ATypeInfo);
end;
rtNil:
AObject := nil;
end;
end;
procedure TDeserializer.ReadDynamicArray(const ATypeInfo: PTypeInfo; out ADynArray: Pointer);
var
LArray: TRttiDynamicArrayType;
LIndex, LCount: NativeInt;
LArrayId: Int32;
LOutPtr: Pointer;
LDim: NativeInt;
begin
{ ARefToRecord points to the first field in the record }
ASSERT(ATypeInfo^.Kind = tkDynArray);
LArray := FRttiContext.GetType(ATypeInfo) as TRttiDynamicArrayType;
if (not Assigned(LArray)) or (not Assigned(LArray.ElementType))then
begin
ErrorNotEnoughRtti(ATypeInfo);
Exit;
end;
DynArrayClear(ADynArray, ATypeInfo);
case BeginReadDynamicArray(LArray, LCount, LArrayId) of
rtInline:
begin
LDim := LCount;
DynArraySetLength(ADynArray, ATypeInfo, 1, @LDim);
FDynArrayReg.AddOrSetValue(LArrayId, ADynArray);
{ Walk through the array }
for LIndex := 0 to LCount - 1 do
DeserializeInternal(LArray.ElementType, Pointer(LIndex * LArray.ElementType.TypeSize + NativeInt(ADynArray)));
EndReadDynamicArray();
end;
rtPointer:
begin
if not FDynArrayReg.TryGetValue(LArrayId, LOutPtr) then
ExceptionHelper.Throw_BadDynamicArrayReference(ATypeInfo)
else
TBytes(ADynArray) := TBytes(LOutPtr);
end;
rtNil:
ADynArray := nil;
end;
end;
procedure TDeserializer.ReadRecord(const ATypeInfo: PTypeInfo; var ARefToRecord: Pointer);
var
LRecord: TRttiRecordType;
LField: TRttiField;
LRecordId: Int32;
LHasAddr: Boolean;
begin
{ ARefToRecord points to the first field in the record }
ASSERT(ATypeInfo^.Kind = tkRecord);
LRecord := FRttiContext.GetType(ATypeInfo) as TRttiRecordType;
if not Assigned(LRecord) then
begin
ErrorNotEnoughRtti(ATypeInfo);
Exit;
end;
LHasAddr := Assigned(ARefToRecord);
case BeginReadRecord(LRecord, LRecordId) of
rtInline:
begin
if not LHasAddr then
begin
{ Allocate enough memory for the value and initialize it }
GetMem(ARefToRecord, LRecord.TypeSize);
InitializeArray(ARefToRecord, LRecord.Handle, 1);
end;
FRecordReg.AddOrSetValue(LRecordId, ARefToRecord);
try
{ Walk through the record }
for LField in LRecord.GetFields() do
begin
if not Assigned(LField.FieldType) then
begin
ErrorNoFieldRtti(LField);
continue;
end;
if IsSerializable(LField) then
begin
BeginReadField(LField);
DeserializeInternal(LField.FieldType, Pointer(LField.Offset + NativeInt(ARefToRecord)));
EndReadField();
end;
end;
EndReadRecord();
except
if not LHasAddr then
begin
FinalizeArray(ARefToRecord, LRecord.Handle, 1);
FreeMem(ARefToRecord);
ARefToRecord := nil;
end;
end;
end;
rtPointer:
begin
if not FRecordReg.TryGetValue(LRecordId, ARefToRecord) then
ExceptionHelper.Throw_BadRecordReference(ATypeInfo);
end;
rtNil:
ARefToRecord := nil;
end;
end;
procedure TDeserializer.ReadStaticArray(const ATypeInfo: PTypeInfo; const ARefToFirstElement: Pointer);
var
LArray: TRttiArrayType;
LIndex: NativeInt;
begin
{ ARefToRecord points to the first field in the record }
ASSERT(ATypeInfo^.Kind = tkArray);
LArray := FRttiContext.GetType(ATypeInfo) as TRttiArrayType;
if (not Assigned(LArray)) or (not Assigned(LArray.ElementType)) then
begin
ErrorNotEnoughRtti(ATypeInfo);
Exit;
end;
{ Notify that a record is being written }
BeginReadStaticArray(LArray, LArray.TotalElementCount);
{ Walk through the record }
for LIndex := 0 to LArray.TotalElementCount - 1 do
DeserializeInternal(LArray.ElementType, Pointer(LIndex * LArray.ElementType.TypeSize + NativeInt(ARefToFirstElement)));
EndReadStaticArray();
end;
procedure TDeserializer.DeserializeInternal(const AType: TRttiType; const AValueRef: Pointer);
var
LTypeData: PTypeData;
LRecordRef: Pointer;
LSetOrd: Int64;
begin
LTypeData := GetTypeData(AType.Handle);
case AType.TypeKind of
tkProcedure,
tkUnknown,
tkMethod,
tkVariant,
tkInterface:
if not FSkipErrors then
ErrorNotSupported(AType.Handle);
tkEnumeration:
begin
ReadEnum(LSetOrd);
case AType.TypeSize of
1: PInt8(AValueRef)^ := LSetOrd;
2: PInt16(AValueRef)^ := LSetOrd;
4: PInt32(AValueRef)^ := LSetOrd;
8: PInt64(AValueRef)^ := LSetOrd;
else
ASSERT(False);
end;
end;
tkSet:
ReadSet(AType.TypeSize, AValueRef^);
tkInteger:
begin
if Assigned(LTypeData) then
begin
case LTypeData^.OrdType of
otSByte:
ReadInt8(PInt8(AValueRef)^);
otUByte:
ReadUInt8(PUInt8(AValueRef)^);
otSWord:
ReadInt16(PInt16(AValueRef)^);
otUWord:
ReadUInt16(PUInt16(AValueRef)^);
otSLong:
ReadInt32(PInt32(AValueRef)^);
otULong:
ReadUInt32(PUInt32(AValueRef)^);
end;
end else
ErrorNotEnoughRtti(AType.Handle);
end;
tkInt64:
begin
if Assigned(LTypeData) then
begin
if LTypeData^.MaxInt64Value > LTypeData^.MinInt64Value then
ReadInt64(PInt64(AValueRef)^)
else
ReadUInt64(PUInt64(AValueRef)^);
end else
ErrorNotEnoughRtti(AType.Handle);
end;
tkChar:
ReadAnsiChar(PAnsiChar(AValueRef)^);
tkWChar:
ReadWideChar(PWideChar(AValueRef)^);
tkFloat:
begin
if Assigned(LTypeData) then
begin
case LTypeData^.FloatType of
ftSingle:
ReadSingle(PSingle(AValueRef)^);
ftDouble:
ReadDouble(PDouble(AValueRef)^);
ftExtended:
ReadExtended(PExtended(AValueRef)^);
ftComp:
ReadComp(PComp(AValueRef)^);
ftCurr:
ReadCurrency(PCurrency(AValueRef)^);
end;
end else
ErrorNotEnoughRtti(AType.Handle);
end;
tkString:
ReadShortString(PShortString(AValueRef)^);
tkLString:
ReadAnsiString(PAnsiString(AValueRef)^);
tkWString:
ReadWideString(PWideString(AValueRef)^);
tkUString:
ReadUnicodeString(PUnicodeString(AValueRef)^);
tkClassRef:
ReadMetaClass(PClass(AValueRef)^);
tkRecord:
begin
LRecordRef := AValueRef;
ReadRecord(AType.Handle, LRecordRef);
end;
tkClass:
ReadClass(AType.Handle, PObject(AValueRef)^);
tkArray:
ReadStaticArray(AType.Handle, AValueRef);
tkDynArray:
ReadDynamicArray(AType.Handle, PPointer(AValueRef)^);
tkPointer:
begin
PPointer(AValueRef)^ := nil;
{ Check if this is apointer to a record }
if Assigned(LTypeData^.RefType) and Assigned(LTypeData^.RefType^) and (LTypeData^.RefType^^.Kind = tkRecord) then
ReadRecord(LTypeData^.RefType^, PPointer(AValueRef)^)
else
ErrorNotSupported(AType.Handle);
end;
end;
end;
{ TOutputContext }
function TOutputContext.AddValue(const AName: String; const AValue: Int64): TOutputContext;
begin
{ Write data }
FSerializer.BeginWriteField(AName);
FSerializer.WriteInt64(AValue);
FSerializer.EndWriteField();
{ Return self for chaining }
Result := Self;
end;
function TOutputContext.AddValue(const AName: String; const AValue: UInt32): TOutputContext;
begin
{ Write data }
FSerializer.BeginWriteField(AName);
FSerializer.WriteUInt32(AValue);
FSerializer.EndWriteField();
{ Return self for chaining }
Result := Self;
end;
function TOutputContext.AddValue(const AName: String; const AValue: UInt64): TOutputContext;
begin
{ Write data }
FSerializer.BeginWriteField(AName);
FSerializer.WriteUInt64(AValue);
FSerializer.EndWriteField();
{ Return self for chaining }
Result := Self;
end;
function TOutputContext.AddValue(const AName: String; const AValue: WideChar): TOutputContext;
begin
{ Write data }
FSerializer.BeginWriteField(AName);
FSerializer.WriteWideChar(AValue);
FSerializer.EndWriteField();
{ Return self for chaining }
Result := Self;
end;
function TOutputContext.AddValue(const AName: String; const AValue: AnsiChar): TOutputContext;
begin
{ Write data }
FSerializer.BeginWriteField(AName);
FSerializer.WriteAnsiChar(AValue);
FSerializer.EndWriteField();
{ Return self for chaining }
Result := Self;
end;
function TOutputContext.AddValue(const AName: String; const AValue: UInt8): TOutputContext;
begin
{ Write data }
FSerializer.BeginWriteField(AName);
FSerializer.WriteUInt8(AValue);
FSerializer.EndWriteField();
{ Return self for chaining }
Result := Self;
end;
function TOutputContext.AddValue(const AName: String; const AValue: Int8): TOutputContext;
begin
{ Write data }
FSerializer.BeginWriteField(AName);
FSerializer.WriteInt8(AValue);
FSerializer.EndWriteField();
{ Return self for chaining }
Result := Self;
end;
function TOutputContext.AddValue(const AName: String; const AValue: Int16): TOutputContext;
begin
{ Write data }
FSerializer.BeginWriteField(AName);
FSerializer.WriteInt16(AValue);
FSerializer.EndWriteField();
{ Return self for chaining }
Result := Self;
end;
function TOutputContext.AddValue(const AName: String; const AValue: Int32): TOutputContext;
begin
{ Write data }
FSerializer.BeginWriteField(AName);
FSerializer.WriteInt32(AValue);
FSerializer.EndWriteField();
{ Return self for chaining }
Result := Self;
end;
function TOutputContext.AddValue(const AName: String; const AValue: UInt16): TOutputContext;
begin
{ Write data }
FSerializer.BeginWriteField(AName);
FSerializer.WriteUInt16(AValue);
FSerializer.EndWriteField();
{ Return self for chaining }
Result := Self;
end;
function TOutputContext.AddValue(const AName: String; const AValue: WideString): TOutputContext;
begin
{ Write data }
FSerializer.BeginWriteField(AName);
FSerializer.WriteWideString(AValue);
FSerializer.EndWriteField();
{ Return self for chaining }
Result := Self;
end;
function TOutputContext.AddValue(const AName: String; const AValue: AnsiString): TOutputContext;
begin
{ Write data }
FSerializer.BeginWriteField(AName);
FSerializer.WriteAnsiString(AValue);
FSerializer.EndWriteField();
{ Return self for chaining }
Result := Self;
end;
function TOutputContext.AddValue(const AName: String; const AValue: UnicodeString): TOutputContext;
begin
{ Write data }
FSerializer.BeginWriteField(AName);
FSerializer.WriteUnicodeString(AValue);
FSerializer.EndWriteField();
{ Return self for chaining }
Result := Self;
end;
function TOutputContext.AddValue(const AName: String; const AValue: TObject): TOutputContext;
begin
{ Write data }
FSerializer.BeginWriteField(AName);
FSerializer.WriteClass(TypeInfo(TObject), AValue);
FSerializer.EndWriteField();
{ Return self for chaining }
Result := Self;
end;
function TOutputContext.AddValue(const AName: String; const AValue: TClass): TOutputContext;
begin
{ Write data }
FSerializer.BeginWriteField(AName);
FSerializer.WriteMetaClass(AValue);
FSerializer.EndWriteField();
{ Return self for chaining }
Result := Self;
end;
function TOutputContext.AddValue(const AName: String; const AValue: ShortString): TOutputContext;
begin
{ Write data }
FSerializer.BeginWriteField(AName);
FSerializer.WriteShortString(AValue);
FSerializer.EndWriteField();
{ Return self for chaining }
Result := Self;
end;
function TOutputContext.AddValue(const AName: String; const AValue: Double): TOutputContext;
begin
{ Write data }
FSerializer.BeginWriteField(AName);
FSerializer.WriteDouble(AValue);
FSerializer.EndWriteField();
{ Return self for chaining }
Result := Self;
end;
function TOutputContext.AddValue(const AName: String; const AValue: Single): TOutputContext;
begin
{ Write data }
FSerializer.BeginWriteField(AName);
FSerializer.WriteSingle(AValue);
FSerializer.EndWriteField();
{ Return self for chaining }
Result := Self;
end;
function TOutputContext.AddValue(const AName: String; const AValue: Extended): TOutputContext;
begin
{ Write data }
FSerializer.BeginWriteField(AName);
FSerializer.WriteExtended(AValue);
FSerializer.EndWriteField();
{ Return self for chaining }
Result := Self;
end;
function TOutputContext.AddValue(const AName: String; const AValue: Currency): TOutputContext;
begin
{ Write data }
FSerializer.BeginWriteField(AName);
FSerializer.WriteCurrency(AValue);
FSerializer.EndWriteField();
{ Return self for chaining }
Result := Self;
end;
function TOutputContext.AddValue(const AName: String; const AValue: Comp): TOutputContext;
begin
{ Write data }
FSerializer.BeginWriteField(AName);
FSerializer.WriteComp(AValue);
FSerializer.EndWriteField();
{ Return self for chaining }
Result := Self;
end;
function TOutputContext.AddValue<T>(const AName: String; const AValue: T): TOutputContext;
begin
{ Write data }
FSerializer.BeginWriteField(AName);
FSerializer.SerializeInternal(
FSerializer.RttiContext.GetType(TypeInfo(T)), @AValue);
FSerializer.EndWriteField();
{ Return self for chaining }
Result := Self;
end;
class function TOutputContext.Create(const ASerializer: TSerializer): TOutputContext;
begin
Result.FSerializer := ASerializer;
end;
{ TInputContext }
class function TInputContext.Create(const ADeserializer: TDeserializer): TInputContext;
begin
Result.FDeserializer := ADeserializer;
end;
function TInputContext.GetValue(const AName: String; out AValue: Int64): TInputContext;
begin
{ Read data }
FDeserializer.BeginReadField(AName);
FDeserializer.ReadInt64(AValue);
FDeserializer.EndReadField();
{ Return self for chaining }
Result := Self;
end;
function TInputContext.GetValue(const AName: String; out AValue: UInt32): TInputContext;
begin
{ Read data }
FDeserializer.BeginReadField(AName);
FDeserializer.ReadUInt32(AValue);
FDeserializer.EndReadField();
{ Return self for chaining }
Result := Self;
end;
function TInputContext.GetValue(const AName: String; out AValue: UInt64): TInputContext;
begin
{ Read data }
FDeserializer.BeginReadField(AName);
FDeserializer.ReadUInt64(AValue);
FDeserializer.EndReadField();
{ Return self for chaining }
Result := Self;
end;
function TInputContext.GetValue(const AName: String; out AValue: WideChar): TInputContext;
begin
{ Read data }
FDeserializer.BeginReadField(AName);
FDeserializer.ReadWideChar(AValue);
FDeserializer.EndReadField();
{ Return self for chaining }
Result := Self;
end;
function TInputContext.GetValue(const AName: String; out AValue: AnsiChar): TInputContext;
begin
{ Read data }
FDeserializer.BeginReadField(AName);
FDeserializer.ReadAnsiChar(AValue);
FDeserializer.EndReadField();
{ Return self for chaining }
Result := Self;
end;
function TInputContext.GetValue(const AName: String; out AValue: UInt8): TInputContext;
begin
{ Read data }
FDeserializer.BeginReadField(AName);
FDeserializer.ReadUInt8(AValue);
FDeserializer.EndReadField();
{ Return self for chaining }
Result := Self;
end;
function TInputContext.GetValue(const AName: String; out AValue: Int8): TInputContext;
begin
{ Read data }
FDeserializer.BeginReadField(AName);
FDeserializer.ReadInt8(AValue);
FDeserializer.EndReadField();
{ Return self for chaining }
Result := Self;
end;
function TInputContext.GetValue(const AName: String; out AValue: Int16): TInputContext;
begin
{ Read data }
FDeserializer.BeginReadField(AName);
FDeserializer.ReadInt16(AValue);
FDeserializer.EndReadField();
{ Return self for chaining }
Result := Self;
end;
function TInputContext.GetValue(const AName: String; out AValue: Int32): TInputContext;
begin
{ Read data }
FDeserializer.BeginReadField(AName);
FDeserializer.ReadInt32(AValue);
FDeserializer.EndReadField();
{ Return self for chaining }
Result := Self;
end;
function TInputContext.GetValue(const AName: String; out AValue: UInt16): TInputContext;
begin
{ Read data }
FDeserializer.BeginReadField(AName);
FDeserializer.ReadUInt16(AValue);
FDeserializer.EndReadField();
{ Return self for chaining }
Result := Self;
end;
function TInputContext.GetValue(const AName: String; out AValue: Single): TInputContext;
begin
{ Read data }
FDeserializer.BeginReadField(AName);
FDeserializer.ReadSingle(AValue);
FDeserializer.EndReadField();
{ Return self for chaining }
Result := Self;
end;
function TInputContext.GetValue(const AName: String; out AValue: WideString): TInputContext;
begin
{ Read data }
FDeserializer.BeginReadField(AName);
FDeserializer.ReadWideString(AValue);
FDeserializer.EndReadField();
{ Return self for chaining }
Result := Self;
end;
function TInputContext.GetValue(const AName: String; out AValue: AnsiString): TInputContext;
begin
{ Read data }
FDeserializer.BeginReadField(AName);
FDeserializer.ReadAnsiString(AValue);
FDeserializer.EndReadField();
{ Return self for chaining }
Result := Self;
end;
function TInputContext.GetValue(const AName: String; out AValue: UnicodeString): TInputContext;
begin
{ Read data }
FDeserializer.BeginReadField(AName);
FDeserializer.ReadUnicodeString(AValue);
FDeserializer.EndReadField();
{ Return self for chaining }
Result := Self;
end;
function TInputContext.GetValue(const AName: String; out AValue: TObject): TInputContext;
begin
{ Read data }
FDeserializer.BeginReadField(AName);
FDeserializer.ReadClass(TypeInfo(TObject), AValue);
FDeserializer.EndReadField();
{ Return self for chaining }
Result := Self;
end;
function TInputContext.GetValue(const AName: String; out AValue: TClass): TInputContext;
begin
{ Read data }
FDeserializer.BeginReadField(AName);
FDeserializer.ReadMetaClass(AValue);
FDeserializer.EndReadField();
{ Return self for chaining }
Result := Self;
end;
function TInputContext.GetValue(const AName: String; out AValue: Extended): TInputContext;
begin
{ Read data }
FDeserializer.BeginReadField(AName);
FDeserializer.ReadExtended(AValue);
FDeserializer.EndReadField();
{ Return self for chaining }
Result := Self;
end;
function TInputContext.GetValue(const AName: String; out AValue: Double): TInputContext;
begin
{ Read data }
FDeserializer.BeginReadField(AName);
FDeserializer.ReadDouble(AValue);
FDeserializer.EndReadField();
{ Return self for chaining }
Result := Self;
end;
function TInputContext.GetValue(const AName: String; out AValue: Comp): TInputContext;
begin
{ Read data }
FDeserializer.BeginReadField(AName);
FDeserializer.ReadComp(AValue);
FDeserializer.EndReadField();
{ Return self for chaining }
Result := Self;
end;
function TInputContext.GetValue(const AName: String; out AValue: ShortString): TInputContext;
begin
{ Read data }
FDeserializer.BeginReadField(AName);
FDeserializer.ReadShortString(AValue);
FDeserializer.EndReadField();
{ Return self for chaining }
Result := Self;
end;
function TInputContext.GetValue(const AName: String; out AValue: Currency): TInputContext;
begin
{ Read data }
FDeserializer.BeginReadField(AName);
FDeserializer.ReadCurrency(AValue);
FDeserializer.EndReadField();
{ Return self for chaining }
Result := Self;
end;
function TInputContext.GetValue<T>(const AName: String; out AValue: T): TInputContext;
begin
{ Read data }
FDeserializer.BeginReadField(AName);
FDeserializer.DeserializeInternal(
FDeserializer.RttiContext.GetType(TypeInfo(T)), @AValue);
FDeserializer.EndReadField();
{ Return self for chaining }
Result := Self;
end;
end.
|
unit Node;
interface
uses
Types, Classes, Graphics, Style;
type
TContextBase = class
end;
TContextClass = class of TContextBase;
//
TNode = class;
TNodeClass = class of TNode;
TNodeList = class;
//
TNode = class
class function GetContextClass: TContextClass; virtual;
public
Nodes: TNodeList;
Style: TStyle;
Text: string;
constructor Create; virtual;
destructor Destroy; override;
function Add(inNodeClass: TNodeClass): TNode;
property ContextClass: TContextClass read GetContextClass;
end;
//
TNodeList = class(TList)
protected
function GetMax: Integer;
function GetNode(inIndex: Integer): TNode;
procedure SetNode(inIndex: Integer; const Value: TNode);
public
property Max: Integer read GetMax;
property Node[inIndex: Integer]: TNode read GetNode write SetNode; default;
end;
//
TNodeIterator = class
private
FIndex: Integer;
FNodes: TNodeList;
protected
function GetNext: Boolean;
function GetNode: TNode;
public
constructor Create(inNodes: TNodeList);
property Index: Integer read FIndex;
property Next: Boolean read GetNext;
property Node: TNode read GetNode;
end;
implementation
{ TNode }
class function TNode.GetContextClass: TContextClass;
begin
Result := TContextBase;
end;
constructor TNode.Create;
begin
Style := TStyle.Create;
end;
destructor TNode.Destroy;
begin
Style.Free;
Nodes.Free;
inherited;
end;
function TNode.Add(inNodeClass: TNodeClass): TNode;
begin
if Nodes = nil then
Nodes := TNodeList.Create;
Result := inNodeClass.Create;
Nodes.Add(Result);
end;
{ TNodeList }
function TNodeList.GetMax: Integer;
begin
Result := Pred(Count);
end;
function TNodeList.GetNode(inIndex: Integer): TNode;
begin
Result := TNode(Items[inIndex]);
end;
procedure TNodeList.SetNode(inIndex: Integer; const Value: TNode);
begin
Items[inIndex] := Value;
end;
{ TNodeIterator }
constructor TNodeIterator.Create(inNodes: TNodeList);
begin
FNodes := inNodes;
FIndex := -1;
end;
function TNodeIterator.GetNext: Boolean;
begin
Inc(FIndex);
Result := Index < FNodes.Count;
end;
function TNodeIterator.GetNode: TNode;
begin
Result := FNodes[FIndex];
end;
end.
|
unit frmAddEnvironmentVariableU;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.ImageList, Vcl.ImgList,
LibraryHelperU, System.UITypes,
System.Actions, Vcl.ActnList, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls,
Vcl.Mask, JvExMask, JvToolEdit;
type
TfrmAddEnvironmentVariable = class(TForm)
Panel2: TPanel;
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
ActionList: TActionList;
ActionOk: TAction;
ActionCancel: TAction;
Panel1: TPanel;
Label1: TLabel;
editName: TEdit;
Label2: TLabel;
editValue: TJvDirectoryEdit;
procedure ActionCancelExecute(Sender: TObject);
procedure ActionOkExecute(Sender: TObject);
private
FDelphiInstallation: TDelphiInstallation;
public
function Add(ADelphiInstallation: TDelphiInstallation): Boolean;
end;
implementation
{$R *.dfm}
uses
dmDelphiLibraryHelperU;
{ TfrmAddEnvironmentVariable }
procedure TfrmAddEnvironmentVariable.ActionCancelExecute(Sender: TObject);
begin
Self.ModalResult := mrCancel;
end;
procedure TfrmAddEnvironmentVariable.ActionOkExecute(Sender: TObject);
var
LAllow: Boolean;
begin
LAllow := True;
if Trim(editName.Text) = '' then
begin
MessageDlg('Please specify a valid name.', mtError, [mbOK], 0);
LAllow := False;
end;
if Trim(editValue.Text) = '' then
begin
MessageDlg('Please specify a valid value.', mtError, [mbOK], 0);
LAllow := False;
end;
if LAllow then
begin
FDelphiInstallation.EnvironmentVariables.Add(editName.Text, editValue.Text);
Self.ModalResult := mrOk;
end;
end;
function TfrmAddEnvironmentVariable.Add(ADelphiInstallation
: TDelphiInstallation): Boolean;
begin
FDelphiInstallation := ADelphiInstallation;
try
editName.Text := '';
editValue.Text := '';
Result := Self.ShowModal = mrOk;
finally
FDelphiInstallation := nil;
end;
end;
end.
|
unit Pospolite.View.CSS.StyleSheet;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Pospolite.View.Basics, Pospolite.View.HTML.Document,
Pospolite.View.CSS.Declaration, Pospolite.View.CSS.Selector,
Pospolite.View.CSS.MediaQuery, Pospolite.View.CSS.Binder,
Pospolite.View.Internet;
type
TPLCSSStyleSheetPartKind = (sspSelector, sspRule, sspUndefined);
{ TPLCSSStyleSheetPart }
TPLCSSStyleSheetPart = packed class
private
FKind: TPLCSSStyleSheetPartKind;
FName: TPLString;
public
constructor Create; virtual;
property Name: TPLString read FName write FName;
property Kind: TPLCSSStyleSheetPartKind read FKind;
end;
TPLCSSStyleSheetParts = class(specialize TPLObjectList<TPLCSSStyleSheetPart>);
{ TPLCSSStyleSheetPartSelector }
TPLCSSStyleSheetPartSelector = packed class(TPLCSSStyleSheetPart)
private
FProperties: TPLCSSDeclarations;
public
constructor Create; override;
destructor Destroy; override;
property Properties: TPLCSSDeclarations read FProperties;
end;
TPLCSSStyleSheetPartSelectors = class(specialize TPLObjectList<TPLCSSStyleSheetPartSelector>);
TPLCSSStyleSheetPartRule = class;
TPLCSSStyleSheetPartRules = class(specialize TPLObjectList<TPLCSSStyleSheetPartRule>);
{ TPLCSSStyleSheetPartRule }
TPLCSSStyleSheetPartRule = class(TPLCSSStyleSheetPart)
private
FMediaQueries: TPLCSSMediaQueries;
FNestedRules: TPLCSSStyleSheetPartRules;
FValue: TPLCSSPropertyValue;
public
constructor Create; override;
destructor Destroy; override;
property NestedRules: TPLCSSStyleSheetPartRules read FNestedRules;
property MediaQueries: TPLCSSMediaQueries read FMediaQueries;
property Value: TPLCSSPropertyValue read FValue;
end;
{ TPLCSSStyleSheet }
TPLCSSStyleSheet = packed class
private
FCharset: TPLString;
FFileName: TPLString;
FFontFaces: TPLCSSStyleSheetPartSelectors;
FImports: TPLCSSStyleSheetPartRules;
FKeyframes: TPLCSSStyleSheetPartRules;
FMediaQuery: TPLString;
FMedias: TPLCSSStyleSheetPartRules;
FNamespace: TPLString;
FPages: TPLCSSStyleSheetPartSelectors;
FSelectors: TPLCSSDeclarationsList;
public
constructor Create;
destructor Destroy; override;
procedure Load(ASource: TPLString; const AMerge: TPLBool = true);
procedure Merge(const AStyleSheet: TPLCSSStyleSheet);
procedure CleanUp;
function MediaAccepts(const AEnvironment: TPLCSSMediaQueriesEnvironment): TPLBool;
procedure SetupObject(const AObject: TPLHTMLObject; AEnvironment: Pointer);
property Charset: TPLString read FCharset write FCharset;
property Namespace: TPLString read FNamespace write FNamespace;
property FontFaces: TPLCSSStyleSheetPartSelectors read FFontFaces;
property Imports: TPLCSSStyleSheetPartRules read FImports;
property Keyframes: TPLCSSStyleSheetPartRules read FKeyframes;
property Medias: TPLCSSStyleSheetPartRules read FMedias;
property Pages: TPLCSSStyleSheetPartSelectors read FPages;
property Selectors: TPLCSSDeclarationsList read FSelectors;
property FileName: TPLString read FFileName write FFileName;
property MediaQuery: TPLString read FMediaQuery write FMediaQuery;
end;
TPLFuncsOfClassCSSStyleSheet = specialize TPLFuncsOfClass<TPLCSSStyleSheet>;
TPLCSSStyleSheetList = packed class(specialize TPLObjectList<TPLCSSStyleSheet>);
TPLCSSStyleSheetManager = class;
{ TPLCSSStylingThread }
TPLCSSStylingThread = class(TThread)
private
FManager: TPLCSSStyleSheetManager;
procedure UpdateStyles;
procedure LoadAllStyles;
public
constructor Create(AManager: TPLCSSStyleSheetManager);
procedure Execute; override;
procedure UpdateStyling;
procedure Annihilate;
end;
{ TPLCSSStyleSheetManager }
TPLCSSStyleSheetManager = class
private
FBinder: TPLCSSStyleBinder;
FExternals: TPLCSSStyleSheetList;
FInternal: TPLCSSStyleSheet;
FDocument: TPLHTMLDocument;
FStyling: TPLCSSStylingThread;
function ComparatorForSearch(const AObject: TPLCSSStyleSheet;
const ACriteria: Variant): TPLSign;
function ComparatorForSort(a, b: TPLCSSStyleSheet): TPLSign;
procedure Rebind;
procedure Restyle;
public
constructor Create(ADocument: TPLHTMLDocument);
destructor Destroy; override;
procedure AddToInternal(AStyle: TPLString); inline;
procedure AddExternal(AURL: TPLString);
procedure StartStyling;
procedure StopStyling;
procedure Rebuilt;
procedure ClearStyles;
property Internal: TPLCSSStyleSheet read FInternal;
property Externals: TPLCSSStyleSheetList read FExternals;
property Binder: TPLCSSStyleBinder read FBinder;
property Styling: TPLCSSStylingThread read FStyling;
public
Environment: TPLCSSMediaQueriesEnvironment;
function EnvironmentPrinter: TPLCSSMediaQueriesEnvironment;
end;
implementation
uses Variants, Pospolite.View.CSS.Basics, Pospolite.View.HTML.Basics,
Pospolite.View.CSS.UserAgentStyleSheet;
{ TPLCSSStyleSheetPart }
constructor TPLCSSStyleSheetPart.Create;
begin
inherited Create;
FName := '';
FKind := sspUndefined;
end;
{ TPLCSSStyleSheetPartSelector }
constructor TPLCSSStyleSheetPartSelector.Create;
begin
inherited Create;
FKind := sspSelector;
FProperties := TPLCSSDeclarations.Create();
end;
destructor TPLCSSStyleSheetPartSelector.Destroy;
begin
FProperties.Free;
inherited Destroy;
end;
{ TPLCSSStyleSheetPartRule }
constructor TPLCSSStyleSheetPartRule.Create;
begin
inherited Create;
FKind := sspRule;
FNestedRules := TPLCSSStyleSheetPartRules.Create(true);
FMediaQueries := TPLCSSMediaQueries.Create(true);
FValue := TPLCSSPropertyValue.Create(true);
end;
destructor TPLCSSStyleSheetPartRule.Destroy;
begin
FValue.Free;
FMediaQueries.Free;
FNestedRules.Free;
inherited Destroy;
end;
constructor TPLCSSStyleSheet.Create;
begin
inherited Create;
FFileName := '';
FMediaQuery := '';
FNamespace := 'http://www.w3.org/1999/xhtml';
FSelectors := TPLCSSDeclarationsList.Create(true);
FFontFaces := TPLCSSStyleSheetPartSelectors.Create(true);
FImports := TPLCSSStyleSheetPartRules.Create(true);
FKeyframes := TPLCSSStyleSheetPartRules.Create(true);
FMedias := TPLCSSStyleSheetPartRules.Create(true);
FPages := TPLCSSStyleSheetPartSelectors.Create(true);
CleanUp;
end;
destructor TPLCSSStyleSheet.Destroy;
begin
FSelectors.Free;
FFontFaces.Free;
FImports.Free;
FKeyframes.Free;
FMedias.Free;
FPages.Free;
inherited Destroy;
end;
procedure TPLCSSStyleSheet.Load(ASource: TPLString; const AMerge: TPLBool);
begin
RemoveCSSComments(ASource);
if not AMerge then CleanUp;
end;
procedure TPLCSSStyleSheet.Merge(const AStyleSheet: TPLCSSStyleSheet);
var
i: SizeInt;
begin
for i := 0 to AStyleSheet.Selectors.Count-1 do
FSelectors.Add(AStyleSheet.Selectors[i].Clone);
end;
procedure TPLCSSStyleSheet.CleanUp;
begin
FCharset := '';
FSelectors.Clear;
FFontFaces.Clear;
FImports.Clear;
FKeyframes.Clear;
FMedias.Clear;
FPages.Clear;
end;
function TPLCSSStyleSheet.MediaAccepts(
const AEnvironment: TPLCSSMediaQueriesEnvironment): TPLBool;
var
mq: TPLCSSMediaQueries;
begin
if TPLString.IsNullOrEmpty(FMediaQuery) then exit(true);
mq := TPLCSSMediaQueries.Create(true);
try
TPLCSSMediaQueryParser.ParseMediaQueries(FMediaQuery, mq);
Result := mq.Evaluate(AEnvironment);
finally
mq.Free;
end;
end;
procedure TPLCSSStyleSheet.SetupObject(const AObject: TPLHTMLObject;
AEnvironment: Pointer);
begin
AObject.SetEnvironment(AEnvironment);
end;
{ TPLCSSStylingThread }
procedure TPLCSSStylingThread.UpdateStyles;
procedure EnumStyleUpdates(obj: TPLHTMLObject);
var
e: TPLHTMLObject;
st: TPLCSSStyleSheet;
begin
if not Assigned(obj) then exit;
FManager.Internal.SetupObject(obj, @FManager.Environment);
for st in FManager.Externals do
st.SetupObject(obj, @FManager.Environment);
if Suspended then exit;
for e in obj.Children do
EnumStyleUpdates(e);
end;
begin
// aktualizacja stylów - nie może kłócić się to z przejściami
EnumStyleUpdates(FManager.FDocument.Body);
end;
procedure TPLCSSStylingThread.LoadAllStyles;
procedure EnumStyles(obj: TPLHTMLObject);
var
e: TPLHTMLObject;
m: TPLHTMLObjectAttribute;
s: TPLCSSStyleSheet;
begin
if not Assigned(obj) then exit;
if obj.Name = 'style' then
// internal
FManager.Internal.Load(obj.Text)
else if (obj.Name = 'link') and (obj.Attributes.Rel <> Default(TPLHTMLObjectAttribute)) then begin
// external
FManager.Externals.Add(TPLCSSStyleSheet.Create);
s := FManager.Externals.Last;
s.FileName := obj.Attributes.Href.Value;
m := obj.Attributes.Get('media');
if (m <> Default(TPLHTMLObjectAttribute)) and (not TPLString.IsNullOrEmpty(m.Value))
and (m.Value.ToLower <> 'all') then s.MediaQuery := m.Value;
s.Load(OnlineClient.FileGetContents(s.FileName)); // może załadować przy wczytywaniu dokumentu?
end else if obj.Attributes.Style <> Default(TPLHTMLObjectAttribute) then
// inline
obj.ApplyInlineStyles;
for e in obj.Children do
EnumStyles(e);
end;
begin
FManager.ClearStyles;
EnumStyles(FManager.FDocument.Root); // faster than query selector
end;
constructor TPLCSSStylingThread.Create(AManager: TPLCSSStyleSheetManager);
begin
inherited Create(true);
FManager := AManager;
end;
procedure TPLCSSStylingThread.Execute;
var
delay: Cardinal = 1000;
begin
LoadAllStyles;
FManager.Binder.UpdateBindings;
while not Terminated and not Suspended do begin
Synchronize(@UpdateStyles);
Sleep(delay);
end;
end;
procedure TPLCSSStylingThread.UpdateStyling;
begin
Start;
end;
procedure TPLCSSStylingThread.Annihilate;
begin
Suspended := true;
Free;
end;
{ TPLCSSStyleSheetManager }
function TPLCSSStyleSheetManager.ComparatorForSearch(
const AObject: TPLCSSStyleSheet; const ACriteria: Variant): TPLSign;
var
s: TPLString;
begin
s := VarToStr(ACriteria).ToLower;
if AObject.FFileName < s then Result := -1
else if AObject.FFileName > s then Result := 1
else Result := 0;
end;
function TPLCSSStyleSheetManager.ComparatorForSort(a, b: TPLCSSStyleSheet
): TPLSign;
begin
if a.FFileName < b.FFileName then Result := -1
else if a.FFileName > b.FFileName then Result := 1
else Result := 0;
end;
procedure TPLCSSStyleSheetManager.Rebind;
begin
FBinder.Annihilate;
FBinder := TPLCSSStyleBinder.Create(FDocument);
end;
procedure TPLCSSStyleSheetManager.Restyle;
begin
FStyling.Annihilate;
FStyling := TPLCSSStylingThread.Create(self);
end;
constructor TPLCSSStyleSheetManager.Create(ADocument: TPLHTMLDocument);
begin
inherited Create;
FDocument := ADocument;
FInternal := TPLCSSStyleSheet.Create;
FExternals := TPLCSSStyleSheetList.Create(true);
FBinder := TPLCSSStyleBinder.Create(ADocument);
FStyling := TPLCSSStylingThread.Create(self);
end;
destructor TPLCSSStyleSheetManager.Destroy;
begin
FStyling.Annihilate;
FBinder.Annihilate;
FInternal.Free;
FExternals.Free;
inherited Destroy;
end;
procedure TPLCSSStyleSheetManager.AddToInternal(AStyle: TPLString);
begin
FInternal.Load(AStyle);
end;
procedure TPLCSSStyleSheetManager.AddExternal(AURL: TPLString);
var
ss: TPLCSSStyleSheet = nil;
s: TPLString;
begin
if TPLFuncsOfClassCSSStyleSheet.FastSearch(FExternals, AURL,
@ComparatorForSearch) > -1 then exit;
try
s := OnlineClient.Download(AURL);
ss := TPLCSSStyleSheet.Create;
ss.FileName := AURL.ToLower;
ss.Load(s);
FExternals.Add(ss);
FExternals.Sort(@ComparatorForSort);
except
if Assigned(ss) then ss.Free;
end;
end;
procedure TPLCSSStyleSheetManager.StartStyling;
begin
FStyling.UpdateStyling;
end;
procedure TPLCSSStyleSheetManager.StopStyling;
begin
Restyle;
Rebind;
end;
procedure TPLCSSStyleSheetManager.Rebuilt;
begin
if FStyling.Suspended then
FBinder.UpdateBindings;
end;
procedure TPLCSSStyleSheetManager.ClearStyles;
begin
FInternal.CleanUp;
FInternal.Merge(TPLCSSStyleSheet(PLUserAgentInstance));
FExternals.Clear;
end;
function TPLCSSStyleSheetManager.EnvironmentPrinter: TPLCSSMediaQueriesEnvironment;
begin
Result := Environment;
Result.UsePrinter := true;
end;
end.
|
unit BsGroupObj;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxGraphics, cxCustomData, cxStyles, cxTL, DB, FIBDatabase,
pFIBDatabase, FIBDataSet, pFIBDataSet, cxControls, cxInplaceContainer,
cxTLData, cxDBTL, dxBar, dxBarExtItems, ActnList, cxMaskEdit, ImgList,
cxClasses, cxGridTableView, BsGroupObjEdit, uCommon_Types, FIBQuery,
pFIBQuery, pFIBStoredProc, ExtCtrls, DateUtils, cxTextEdit, cxDBEdit,
cxContainer, cxEdit, cxLabel, uCommon_Messages, basetypes, uCommon_Funcs,
uConsts;
type
TfrmGroupObject = class(TForm)
ObjectsList: TcxDBTreeList;
ObjectDB: TpFIBDatabase;
ObjectsDSet: TpFIBDataSet;
ObjectTransRead: TpFIBTransaction;
ObjectTransWrite: TpFIBTransaction;
ObjectsSource: TDataSource;
barManager: TdxBarManager;
btnAdd: TdxBarLargeButton;
btnEdit: TdxBarLargeButton;
btnDel: TdxBarLargeButton;
btnRefresh: TdxBarLargeButton;
btnSelect: TdxBarLargeButton;
btnExit: TdxBarLargeButton;
ActionList1: TActionList;
ActIns: TAction;
ActEdit: TAction;
ActDel: TAction;
ActRefresh: TAction;
ActSelect: TAction;
ActExit: TAction;
ObjctsList_Id_Gr_List_Obj: TcxDBTreeListColumn;
ObjctsList_Id_Pgr_List_Obj: TcxDBTreeListColumn;
ObjctsList_Name_Gr_List_Obj: TcxDBTreeListColumn;
ObjctsList_Note_Gr_List_Obj: TcxDBTreeListColumn;
ObjctsList_Id_Type_Gr_List_Obj: TcxDBTreeListColumn;
StyleRepository: TcxStyleRepository;
ImageList: TImageList;
StoredProc: TpFIBStoredProc;
ObjctsList_Kod_Obj: TcxDBTreeListColumn;
pnlBottom: TPanel;
lblComment: TcxLabel;
CommentEdit: TcxDBTextEdit;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
cxStyle3: TcxStyle;
cxStyle4: TcxStyle;
cxStyle5: TcxStyle;
cxStyle6: TcxStyle;
cxStyle7: TcxStyle;
cxStyle8: TcxStyle;
cxStyle9: TcxStyle;
cxStyle10: TcxStyle;
cxStyle11: TcxStyle;
cxStyle12: TcxStyle;
cxStyle13: TcxStyle;
cxStyle14: TcxStyle;
cxGridTableViewStyleSheet1: TcxGridTableViewStyleSheet;
cxStyle15: TcxStyle;
cxStyle16: TcxStyle;
cxStyle17: TcxStyle;
cxStyle18: TcxStyle;
cxStyle19: TcxStyle;
cxStyle20: TcxStyle;
cxStyle21: TcxStyle;
Default_StyleSheet: TcxGridTableViewStyleSheet;
procedure ActInsExecute(Sender: TObject);
procedure ActRefreshExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ActExitExecute(Sender: TObject);
procedure ActEditExecute(Sender: TObject);
procedure ActDelExecute(Sender: TObject);
procedure ActSelectExecute(Sender: TObject);
procedure ObjectsListDblClick(Sender: TObject);
private
SqlText:string;
HtKey:TbsShortCut;
BIniLanguage:Byte;
procedure GotoBookMark(Value:Integer);
public
{ Public declarations }
res : Variant;
constructor Create(AParameter:TBsSimpleParams);reintroduce;
procedure ObjectDSetCloseOpen;
end;
var
frmGroupObject: TfrmGroupObject;
implementation
{$R *.dfm}
constructor TfrmGroupObject.Create(AParameter:TBsSimpleParams);
begin
inherited Create(AParameter.Owner);
CommentEdit.Text:='';
ObjectDB.Handle:=AParameter.Db_Handle;
if AParameter.FormStyle=fsMDIChild then
begin
SqlText:='SELECT DISTINCT * FROM BS_NAME_GR_LIST_OBJ_SEL';
btnSelect.Visible:=ivNever;
end
else SqlText:='SELECT DISTINCT * FROM BS_NAME_GR_LIST_NODE_SEL('+IntToStr(AParameter.ID_Locate)+')';
ObjectDSetCloseOpen;
HtKey:=LoadShortCut(ObjectDB.Handle, Self);
ActIns.ShortCut:=HtKey.Add;
ActEdit.ShortCut:=HtKey.Edit;
ActDel.ShortCut:=HtKey.Del;
ActRefresh.ShortCut:=HtKey.Refresh;
ActSelect.ShortCut:=HtKey.Choice;
ActExit.ShortCut:=HtKey.Close;
BIniLanguage:=uCommon_Funcs.bsLanguageIndex();
ActIns.Caption:=uConsts.bs_InsertBtn_Caption[BIniLanguage];
ActEdit.Caption:=uConsts.bs_EditBtn_Caption[BIniLanguage];
ActDel.Caption:=uConsts.bs_DeleteBtn_Caption[BIniLanguage];
ActSelect.Caption:=uConsts.bs_SelectBtn_Caption[BIniLanguage];
ActExit.Caption:=uConsts.bs_ExitBtn_Caption[BIniLanguage];
end;
procedure TfrmGroupObject.ActInsExecute(Sender: TObject);
var frm:TfrmGroupObjEdit;
RetId:Integer;
begin
frm:=TfrmGroupObjEdit.Create(Self, ObjectsDSet['Id_Gr_List_Obj'], ObjectsDSet['Id_Pgr_List_Obj'], 'Add');
frm.Caption:='Додати';
if frm.ShowModal=mrOk then
begin
StoredProc.StoredProcName:='BS_NAME_GR_LIST_OBJ_INS';
StoredProc.Transaction.StartTransaction;
StoredProc.Prepare;
StoredProc.ParamByName('Id_Pgr_List_Obj').AsInt64:=frm.UpperNode;
StoredProc.ParamByName('Name_Gr_List_Obj').AsString:=frm.NameObjEdit.Text;
StoredProc.ParamByName('Note_Gr_List_Obj').AsString:=frm.NameComment.Text;
StoredProc.ParamByName('Kod_Obj').AsInteger:=StrToInt(frm.KodEdit.Text);
StoredProc.ParamByName('Id_Type_Gr_List_Obj').AsInteger:=1;
try
StoredProc.ExecProc;
RetId:=StoredProc.FieldByName('Ret_Value').AsInteger;
StoredProc.Transaction.Commit;
except on E:Exception do
begin
ShowMessage(E.Message);
StoredProc.Transaction.Rollback;
end;
end;
ObjectDSetCloseOpen;
end;
frm.Free;
ObjectsDSet.Locate('Id_Gr_List_Obj', RetId, []);
end;
procedure TfrmGroupObject.ObjectDSetCloseOpen;
begin
ObjectsDSet.Close;
ObjectsDSet.SQLs.SelectSQL.Text:=SqlText;
ObjectsDSet.Open;
end;
procedure TfrmGroupObject.ActRefreshExecute(Sender: TObject);
begin
ObjectDSetCloseOpen;
end;
procedure TfrmGroupObject.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if FormStyle = fsMDIChild then action:=caFree
end;
procedure TfrmGroupObject.ActExitExecute(Sender: TObject);
begin
Close;
end;
procedure TfrmGroupObject.ActEditExecute(Sender: TObject);
var frm:TfrmGroupObjEdit;
begin
if ObjectsDSet.IsEmpty then Exit;
frm:=TfrmGroupObjEdit.Create(Self, ObjectsDSet['Id_Gr_List_Obj'], ObjectsDSet['Id_Pgr_List_Obj'], 'Edit');
frm.Caption:='Змінити';
if (not VarIsNull(ObjectsDSet['Name_Gr_List_Obj'])) then frm.NameObjEdit.Text:=ObjectsDSet['Name_Gr_List_Obj'];
if (not VarIsNull(ObjectsDSet['Note_Gr_List_Obj'])) then frm.NameComment.Text:=ObjectsDSet['Note_Gr_List_Obj'];
frm.KodEdit.Text:=IntToStr(ObjectsDSet['Kod_Obj']);
if frm.ShowModal=mrOk then
begin
StoredProc.StoredProcName:='BS_NAME_GR_LIST_OBJ_UPD';
StoredProc.Transaction.StartTransaction;
StoredProc.Prepare;
StoredProc.ParamByName('Id_Gr_List_Obj').AsInt64:=frm.CurrentNode;
StoredProc.ParamByName('Id_Pgr_List_Obj').AsInt64:=frm.UpperNode;
StoredProc.ParamByName('Name_Gr_List_Obj').AsString:=frm.NameObjEdit.Text;
StoredProc.ParamByName('Note_Gr_List_Obj').AsString:=frm.NameComment.Text;
StoredProc.ParamByName('Id_Type_Gr_List_Obj').AsInteger:=ObjectsDSet['Id_Type_Gr_List_Obj'];
StoredProc.ParamByName('Kod_Obj').AsInteger:=StrToInt(frm.KodEdit.Text);
try
StoredProc.ExecProc;
StoredProc.Transaction.Commit;
except on E:Exception do
begin
ShowMessage(E.Message);
StoredProc.Transaction.Rollback;
end;
end;
ObjectDSetCloseOpen;
end;
frm.Free;
ObjectsDSet.Locate('Id_Gr_List_Obj', frm.CurrentNode, []);
end;
procedure TfrmGroupObject.ActDelExecute(Sender: TObject);
var s:string;
Id:Integer;
begin
if ObjectsDSet.IsEmpty then Exit;
if (agMessageDlg('Увага!', 'Ви дійсно бажаєте видалити цей запис?', mtConfirmation ,[mbYes, mbNo])=mrYes) then
begin
Id:=ObjectsDSet['Id_Pgr_List_Obj'];
StoredProc.StoredProcName:='BS_NAME_GR_LIST_OBJ_DEL';
StoredProc.Transaction.StartTransaction;
StoredProc.Prepare;
StoredProc.ParamByName('Id_Gr_List_Obj').AsInt64:=ObjectsDSet['Id_Gr_List_Obj'];
try
StoredProc.ExecProc;
s:=StoredProc.FieldByName('Is_Error').AsString;
if s='F' then StoredProc.Transaction.Commit
else
begin
ShowMessage(StoredProc.FieldByName('Out_Msg').AsString);
StoredProc.Transaction.Rollback;
end;
except on E:Exception do
begin
ShowMessage(E.Message);
StoredProc.Transaction.Rollback;
end;
end;
end;
ObjectDSetCloseOpen;
GotoBookMark(Id);
end;
procedure TfrmGroupObject.ActSelectExecute(Sender: TObject);
begin
if not ObjectsDSet.IsEmpty then
begin
res:=VarArrayCreate([0, 2], varVariant);
res[0] := ObjectsDSet['Id_Gr_List_Obj'];
res[1] := ObjectsDSet['Name_Gr_List_Obj'];
res[2] := ObjectsDSet['Kod_Obj'];
ModalResult:=mrOk;
end;
end;
procedure TfrmGroupObject.ObjectsListDblClick(Sender: TObject);
begin
ActSelectExecute(Sender);
end;
procedure TfrmGroupObject.GotoBookMark(Value:Integer);
var i:SmallInt;
Parent, Node:TcxTreeListNode;
begin
for i:=0 to ObjectsList.Nodes.TreeList.Count-1 do
begin
if ObjectsList.Nodes.Items[i].Values[1]=Value then
begin
Parent:=ObjectsList.Nodes[i];
Break;
end;
end;
try
Node:=Parent.GetFirstChild;
if not varIsNull(Node.Values[0]) then ObjectsDSet.Locate('Id_Gr_List_Obj', Node.Values[0], []);
except
ObjectsDSet.Locate('Id_Gr_List_Obj', Value, []);
end;
end;
end.
|
unit KpFault;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Mask, ToolEdit, Buttons, ExtCtrls, Db, DBTables, RxLookup,
uCommonForm,uOilQuery,Ora, uOilStoredProc, MemDS, DBAccess;
type
TKpFaultForm = class(TCommonForm)
Label3: TLabel;
Panel1: TPanel;
Panel3: TPanel;
Label1: TLabel;
deBegin: TDateEdit;
Label2: TLabel;
deEnd: TDateEdit;
Label4: TLabel;
edComment: TEdit;
Label5: TLabel;
edRespondent: TEdit;
Label6: TLabel;
Label7: TLabel;
cePodrazd: TComboEdit;
bbOk: TBitBtn;
bbCancel: TBitBtn;
qTest: TOilQuery;
qTestCO: TFloatField;
Label8: TLabel;
qGroups: TOilQuery;
qGroupsID: TFloatField;
qGroupsNAME: TStringField;
dsGroups: TOraDataSource;
dsTypes: TOraDataSource;
qTypes: TOilQuery;
qTypesID: TFloatField;
qTypesNAME: TStringField;
leGroups: TRxLookupEdit;
leTypes: TRxLookupEdit;
qTypesOPTIONS: TStringField;
procedure bbCancelClick(Sender: TObject);
procedure Save;
procedure Test;
procedure cbCrashTypeKeyPress(Sender: TObject; var Key: Char);
procedure bbOkClick(Sender: TObject);
procedure cePodrazdButtonClick(Sender: TObject);
procedure cbCrashTypeChange(Sender: TObject);
procedure leGroupsCloseUp(Sender: TObject);
procedure leTypesButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure leTypesCloseUp(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Id,Inst: integer;
Options: string;
end;
var
KpFaultForm: TKpFaultForm;
implementation
{$R *.DFM}
uses UDbFunc,OilStd,ChooseOrg,Main;
//==============================================================================
procedure TKpFaultForm.bbCancelClick(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
//==============================================================================
procedure TKpFaultForm.Test;
var s: string;
begin
if leGroups.Tag=0 then
Raise Exception.Create(TranslateText('Не выбрана группа сбоя'));
if leTypes.Tag=0 then
Raise Exception.Create(TranslateText('Не выбран тип сбоя'));
if cePodrazd.Tag=0 then
Raise Exception.Create(TranslateText('Не выбрано подразделение!'));
if deBegin.Date>deEnd.Date then
Raise Exception.Create(TranslateText('Начало сбоя не должно быть позже конца сбоя!'));
if trim(edComment.Text)='' then
Raise Exception.Create(TranslateText('Не введено описание!'));
if trim(edRespondent.Text)='' then
Raise Exception.Create(TranslateText('Не введена фамилия сотрудника!'));
S := trim(edRespondent.Text);
if (Length(S) <3) or
(ANSIUpperCase(Copy(S,1,1))<> Copy(S,1,1)) or
(Pos('1',S)+Pos('2',S)+Pos('3',S)+Pos('4',S)+Pos('5',S)+Pos('6',S)+
Pos('7',S)+Pos('8',S)+Pos('9',S)+Pos('0',S)<>0)
then Raise Exception.Create(TranslateText('Неправильно введена фамилия !'));
if qTest.Active then qTest.Close;
DefineQParams(qTest,
['crash_type', leTypes.Tag,
'dep_id', cePodrazd.Tag,
'start_date', deBegin.Date,
'end_date', deEnd.Date]);
_OpenQuery(qTest);
if (qTestCo.AsInteger>0) and (Id=0) or (qTestCo.AsInteger>1) and (Id>0) then
Raise Exception.Create(TranslateText('За этот период по этому подразделению уже введен сбой!'));
end;
//==============================================================================
procedure TKpFaultForm.Save;
begin
if Id=0 then Id:=GetSeqNextVal('S_OIL_KP_CRASH');
StartSqlOra;
_ExecProcOra('OIL.INSORUPDOIL_KP_CRASH',
['ID#', Id,
'STATE#', 'Y',
'INST#', Inst,
'CRASH_TYPE#', leTypes.Tag,
'DEP_ID#', cePodrazd.Tag,
'START_DATE#', deBegin.Date,
'END_DATE#', deEnd.Date,
'RESPONDENT#', edRespondent.Text,
'COMMENTS#', edComment.Text
],TRUE);
CommitSqlOra;
end;
//==============================================================================
procedure TKpFaultForm.cbCrashTypeKeyPress(Sender: TObject; var Key: Char);
begin
Key:=#0;
end;
//==============================================================================
procedure TKpFaultForm.bbOkClick(Sender: TObject);
begin
Test;
Save;
ModalResult:=mrOk;
end;
//==============================================================================
procedure TKpFaultForm.cePodrazdButtonClick(Sender: TObject);
var vId, vInst,n: Integer;
vName: String;
begin
if Options[1]='y' then n:=1
else n:=2;
if ChooseOrg.CaptureOrg(n, MAIN_ID, INST, 'yyy'+Options[1]+Options+'nn', vId, vInst, vName) then begin
cePodrazd.Tag := vId;
cePodrazd.Text := vName;
end;
end;
//==============================================================================
procedure TKpFaultForm.cbCrashTypeChange(Sender: TObject);
begin
if leTypes.Tag=0 then begin
cePodrazd.Tag:=REAL_INST;
cePodrazd.Text:=GetOrgName(REAL_INST,REAL_INST);
cePodrazd.Enabled:=FALSE;
end else begin
cePodrazd.Enabled:=TRUE;
end;
end;
//==============================================================================
procedure TKpFaultForm.leGroupsCloseUp(Sender: TObject);
begin
if leGroups.Tag<>qGroupsId.AsInteger then begin
leGroups.Tag:=qGroupsId.AsInteger;
leGroups.Text:=qGroupsName.AsString;
leTypes.Tag:=0;
leTypes.Text:='';
end;
end;
//==============================================================================
procedure TKpFaultForm.leTypesButtonClick(Sender: TObject);
begin
if leGroups.Text='' then leGroups.Tag:=0;
if qTypes.Active then qTypes.Close;
qTypes.ParamByName('id').Value:=leGroups.Tag;
_OpenQuery(qTypes);
end;
//==============================================================================
procedure TKpFaultForm.FormCreate(Sender: TObject);
begin
inherited;
if not qGroups.Active then _OpenQuery(qGroups);
if not qTypes.Active then _OpenQuery(qTypes);
end;
//==============================================================================
procedure TKpFaultForm.leTypesCloseUp(Sender: TObject);
begin
if qTypes.RecordCount=0 then exit;
leTypes.Tag:=qTypesId.AsInteger;
Options:=qTypesOptions.AsString;
cePodrazd.Enabled:=(Options<>'nn');
if Options='nn' then begin
cePodrazd.Tag:=Inst;
cePodrazd.Text:=GetOrgName(inst,inst);
end else begin
if (Options[1]='n') and (cePodrazd.Tag<1000000) or (Options[2]='n') and (cePodrazd.Tag>1000000) then begin
cePodrazd.Text:='';
cePodrazd.Tag:=0;
end;
end;
end;
//==============================================================================
end.
|
program dz3_mod(input,output);
const
MAX_CL = 40;
MAX = 255;
type
matrica = array [1..MAX_CL,1..MAX_CL] of integer;
skup = set of 1..MAX;
var
a : matrica;
m,n : integer;
s : skup;
nema : boolean;
procedure upis(var m,n:integer; var a: matrica; var nema: boolean);
var
i, j : integer;
begin
write(output,'Unesite broj vrsta i broj kolona koliko zelite da ima ova matrica: ');
readln(input,m,n);
if ( m > MAX_CL) or (n > MAX_CL) or ( m < 0 ) or ( n < 0) then
begin
nema := true;
exit;
end;
writeln(output,'Unesite matricu sa njenim clanovima ');
for i := 1 to m do
for j := 1 to n do
read( a[i,j] );
end;
procedure unosuskup(var s:skup);
const
MAX = 255;
var
i : integer;
begin
for i := 1 to MAX do {unosim brojeve od 1 do 255 u skup}
s := s + [i];
end;
procedure ispis(n,x:integer; a: matrica);
var
i : integer;
begin
writeln(output,'Vrsta simetricne matrice je: ');
for i := 1 to n do
write (output, a[x,i], ' ');
writeln();
end;
procedure provera(m,n:integer; a : matrica;s:skup);
var
x, i, j : integer;
palin,prekor : boolean;
begin
for x := 1 to m do
begin
palin := true;
prekor := true;
i := 1;
j := n;
while palin and prekor do
begin
if not( a[x,i] in s) or not(a[x,j] in s) then {ako brojevi nisu u skupu onda automatski prekidam while petlju sa false}
palin := false;
if ( a[x,i] <> a[x,j]) then
palin := false;
if ( i >= j ) then
prekor := false;
inc(i);
j := j - 1;
end;
if ( palin = true) then
ispis(n,x,a);
end;
end;
begin
repeat
upis(m,n,a,nema);
if ( nema = true) then
exit;
unosuskup(s);
provera(m,n,a,s);
writeln(output,'==============================================================================');
until nema = true;
end.
|
unit CFControl;
interface
uses
Windows, Classes, Controls, Messages, Graphics;
const
WM_CF_CAPTIONBAR = WM_USER + $100;
WM_CF_CARETCHANGE = WM_USER + $101;
WM_CF_LBUTTONDOWN = WM_USER + $102;
WM_CF_LBUTTONUP = WM_USER + $103;
WM_CF_MOUSEMOVE = WM_USER + $104;
WM_CF_LBUTTONDBLCLK = WM_USER + $105;
WM_CF_REMOVECONTROL = WM_USER + $106;
type
TMouseState = set of (cmsMouseIn, cmsMouseDown);
TCFCustomControl = class(TCustomControl)
private
FAlpha: Byte;
FMouseState: TMouseState;
FBorderVisible: Boolean;
FUpdateCount: Integer;
FBorderColor: TColor;
protected
procedure DrawControl(ACanvas: TCanvas); virtual;
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;
procedure CMMouseEnter(var Msg: TMessage ); message CM_MOUSEENTER;
procedure CMMouseLeave(var Msg: TMessage ); message CM_MOUSELEAVE;
/// <summary> 响应Tab键和方向键 </summary>
procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE;
procedure WMERASEBKGND(var Message: TWMEraseBkgnd); message WM_ERASEBKGND;
procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS;
procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS;
procedure SetBorderVisible(Value: Boolean);
public
constructor Create(AOwner: TComponent); override;
procedure BeginUpdate; virtual;
procedure EndUpdate; virtual;
procedure DrawTo(const ACanvas: TCanvas); virtual;
procedure UpdateDirectUI; overload;
procedure UpdateDirectUI(ARect: TRect); overload;
property MouseState: TMouseState read FMouseState;
published
property BorderVisible: Boolean read FBorderVisible write SetBorderVisible;
property Alpha: Byte read FAlpha write FAlpha;
property Align;
end;
/// <summary>
/// 文本类控件基类
/// </summary>
TCFTextControl = class(TCFCustomControl)
private
FRoundCorner: Byte;
FOnChange: TNotifyEvent;
protected
procedure DrawControl(ACanvas: TCanvas); override;
procedure AdjustBounds; dynamic;
procedure Loaded; override;
public
constructor Create(AOwner: TComponent); override;
property RoundCorner: Byte read FRoundCorner write FRoundCorner;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
published
property Font;
property Text;
end;
function KeysToShiftState(Keys: Word): TShiftState;
var
GRoundSize: Byte = 5;
GPadding: Byte = 2;
GIconWidth: Byte = 16;
GBorderWidth: Byte = 1;
GSpace: Byte = 2;
GMinWidth: Integer = 10;
GMinHeight: Integer = 20;
// 全局颜色
//GThemeColor: TColor = $FFFFFF; // 主色调
GTitleBackColor: TColor = $E8FFDF; // 标题区域背景色
GBackColor: TColor = $FFFFFF; // 默认背景色
GAreaBackColor: TColor = $008BBB68; // 区域背景色
GHotColor: TColor = $98F392; // 背景高亮色
GReadOlnyBackColor: TColor = clInfoBk; // 只读背景色
GAlertColor: TColor = $839EDA; // 警告色
GDownColor: TColor = $90E78B; // 选中背景色
GBorderColor: TColor = $78C074; // 边框静态色
GBorderHotColor: TColor = $588D55; // 边框激活时颜色
GLineColor: TColor = clMedGray;
GHightLightColor: TColor = clHighlight;
implementation
uses
SysUtils;
function KeysToShiftState(Keys: Word): TShiftState;
begin
Result := [];
if Keys and MK_SHIFT <> 0 then Include(Result, ssShift);
if Keys and MK_CONTROL <> 0 then Include(Result, ssCtrl);
if Keys and MK_LBUTTON <> 0 then Include(Result, ssLeft);
if Keys and MK_RBUTTON <> 0 then Include(Result, ssRight);
if Keys and MK_MBUTTON <> 0 then Include(Result, ssMiddle);
if GetKeyState(VK_MENU) < 0 then Include(Result, ssAlt);
end;
{ TCFCustomControl }
procedure TCFCustomControl.BeginUpdate;
begin
Inc(FUpdateCount);
end;
procedure TCFCustomControl.CMMouseEnter(var Msg: TMessage);
begin
inherited;
FMouseState := FMouseState + [cmsMouseIn];
end;
procedure TCFCustomControl.CMMouseLeave(var Msg: TMessage);
begin
inherited;
FMouseState := FMouseState - [cmsMouseIn, cmsMouseDown];
end;
constructor TCFCustomControl.Create(AOwner: TComponent);
begin
inherited;
Self.DoubleBuffered := True;
Color := GBackColor;
FAlpha := 255;
FUpdateCount := 0;
FBorderColor := GBorderColor;
FBorderVisible := True;
Width := 75;
Height := 25;
end;
procedure TCFCustomControl.DrawControl(ACanvas: TCanvas);
begin
ACanvas.Brush.Color := GBackColor;
end;
procedure TCFCustomControl.DrawTo(const ACanvas: TCanvas);
var
vMemDC: HDC;
vMemBitmap, vOldBitmap: HBITMAP;
vCanvas: TCanvas;
vBlendFunction: TBlendFunction;
vDCState: Integer;
vPoint: TPoint;
begin
if FAlpha <> 255 then
begin
// 不使用GDI因为在dll中初始化gdi时界面不显示
vMemBitmap := CreateCompatibleBitmap(ACanvas.Handle, Width, Height);
try
vMemDC := CreateCompatibleDC(ACanvas.Handle);
vOldBitmap := SelectObject(vMemDC, vMemBitmap);
BitBlt(vMemDC, 0, 0, Width, Height, ACanvas.Handle, Left, Top, SRCCOPY); // 拷贝Canvas此位置的图像
try
vCanvas := TCanvas.Create;
vCanvas.Handle := vMemDC;
vDCState := Windows.SaveDC(vCanvas.Handle); // 保存设备环境到上下文栈上
try
DrawControl(vCanvas); // 绘制控件(为支持直接调用DrawTo处理透明效果,所以透明处理放在各控件的DrawTo中)
finally
Windows.RestoreDC(vCanvas.Handle, vDCState); // 从设备上下文栈中对恢复设备环境
end;
vBlendFunction.BlendOp := AC_SRC_OVER;
vBlendFunction.BlendFlags := 0;
vBlendFunction.AlphaFormat := AC_SRC_OVER; // 源位图必须是32位深
vBlendFunction.SourceConstantAlpha := FAlpha; // 透明度
Windows.AlphaBlend(ACanvas.Handle,
Left,
Top,
Width,
Height,
vMemDC,
0,
0,
Width,
Height,
vBlendFunction
);
finally
SelectObject(vMemDC, vOldBitmap)
end;
finally
vCanvas.Free;
DeleteDC(vMemDC);
DeleteObject(vMemBitmap);
end;
end
else
DrawControl(ACanvas);
end;
procedure TCFCustomControl.EndUpdate;
begin
if FUpdateCount > 0 then
Dec(FUpdateCount);
UpdateDirectUI; // 其内校验 FUpdateCount = 0
end;
procedure TCFCustomControl.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
if not (csDesigning in ComponentState)
and (CanFocus {or (GetParentForm(Self) = nil)})
then
begin
SetFocus;
FMouseState := FMouseState + [cmsMouseDown];
end;
inherited;
end;
procedure TCFCustomControl.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
if not (csDesigning in ComponentState)
and (CanFocus {or (GetParentForm(Self) = nil)})
then
begin
FMouseState := FMouseState - [cmsMouseDown];
end;
inherited;
end;
procedure TCFCustomControl.Paint;
begin
inherited Paint;
if Self.Visible then
DrawControl(Canvas);
end;
procedure TCFCustomControl.SetBorderVisible(Value: Boolean);
begin
if FBorderVisible <> Value then
begin
FBorderVisible := Value;
UpdateDirectUI;
end;
end;
procedure TCFCustomControl.UpdateDirectUI(ARect: TRect);
begin
if FUpdateCount <> 0 then Exit;
if HandleAllocated then
InvalidateRect(Handle, ARect, False); // 绘制区域,False 不进行擦除
end;
procedure TCFCustomControl.WMERASEBKGND(var Message: TWMEraseBkgnd);
begin
Message.Result := 1;
end;
procedure TCFCustomControl.WMGetDlgCode(var Message: TWMGetDlgCode);
begin
Message.Result := DLGC_WANTTAB or DLGC_WANTARROWS;
end;
procedure TCFCustomControl.WMKillFocus(var Message: TWMKillFocus);
begin
inherited;
UpdateDirectUI;
end;
procedure TCFCustomControl.WMSetFocus(var Message: TWMSetFocus);
begin
inherited;
UpdateDirectUI;
end;
procedure TCFCustomControl.UpdateDirectUI;
begin
if HandleAllocated then
UpdateDirectUI(ClientRect);
end;
{ TCFTextControl }
procedure TCFTextControl.AdjustBounds;
var
vNewHeight, vNewWidth: Integer;
begin
if not (csReading in ComponentState) then
begin
Canvas.Font := Font;
vNewHeight := Canvas.TextHeight('荆') + GetSystemMetrics(SM_CYBORDER) * 4;
vNewWidth := Canvas.TextWidth(Caption) + GetSystemMetrics(SM_CYBORDER) * 4;
if vNewWidth < GMinWidth then
vNewWidth := GMinWidth;
SetBounds(Left, Top, vNewWidth, vNewHeight);
end;
end;
constructor TCFTextControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FRoundCorner := 0;
end;
procedure TCFTextControl.DrawControl(ACanvas: TCanvas);
begin
inherited DrawControl(ACanvas);
ACanvas.Font := Font;
end;
procedure TCFTextControl.Loaded;
begin
inherited Loaded;
AdjustBounds;
end;
end.
|
{**************************************************************************************}
{ }
{ CCR Exif - Delphi class library for reading and writing image metadata }
{ Version 1.5.1 }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 }
{ (the "License"); you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT }
{ WARRANTY OF ANY KIND, either express or implied. See the License for the specific }
{ language governing rights and limitations under the License. }
{ }
{ The Original Code is CCR.Exif.XMPUtils.pas. }
{ }
{ The Initial Developer of the Original Code is Chris Rolliston. Portions created by }
{ Chris Rolliston are Copyright (C) 2009-2012 Chris Rolliston. All Rights Reserved. }
{ }
{**************************************************************************************}
{$I CCR.Exif.inc}
unit CCR.Exif.XMPUtils;
{
This unit implements a IDOMDocument/IDOMNode-based XMP packet parser and editor. Since
v1.1.0, edited data is written out manually (i.e., the IDOMXXX interfaces are only
used to read).
Note that the UpdateXXX methods of TXMPPacket are called automatically when you set a
tag property of TCustomExifData. Their behaviour depends upon the TXMPPacket's
UpdatePolicy property, which has three possible values:
- xwAlwaysUpdate: if the new value is an empty string, then the XMP property is
deleted, else it is changed (or added). This setting is the default for standalone
TXMPPacket instances.
- xwUpdateIfExists: any existing property is updated, but if it doesn't already exist,
no property is added. This setting is the default for an TXMPPacket instance that is
attached to a TCustomExifData object; change this to xwAlwaysUpdate to mimic Windows
Vista's behaviour.
- xwRemove: always removes the property when UpdateProperty is called.
}
interface
uses
Types, SysUtils, Classes, xmldom, CCR.Exif.BaseUtils, CCR.Exif.TiffUtils, TimeSpan;
type
EInvalidXMPPacket = class(Exception);
EInvalidXMPOperation = class(EInvalidOperation);
TXMPProperty = class;
TXMPSchema = class;
TXMPPacket = class;
TXMPNamespace = (xsUnknown, xsRDF,
xsCameraRaw, xsColorant, xsDimensions, xsDublinCore, xsFont, xsExif,
xsExifAux, xsIPTC, xsJob, xsMicrosoftPhoto, xsPDF, xsPhotoshop, xsResourceEvent{*},
xsResourceRef{*}, xsThumbnail, xsTIFF, xsVersion, xsXMPBasic, xsXMPBasicJobTicket,
xsXMPDynamicMedia, xsXMPMediaManagement, xsXMPPagedText, xsXMPRights);
TXMPKnownNamespace = xsRDF..High(TXMPNamespace);
TKnownXMPNamespaces = record //personally I wouldn't have the 'T', but I'll keep with the D2009+ style...
private class var
FKnownURIs: TUnicodeStringList;
FKnownIndices: array[TXMPKnownNamespace] of Integer;
class procedure NeedKnownURIs; static;
class function GetPreferredPrefix(Namespace: TXMPKnownNamespace): UnicodeString; static;
class function GetURI(Namespace: TXMPKnownNamespace): UnicodeString; static;
public
class function Find(const URI: UnicodeString; out Namespace: TXMPNamespace): Boolean; static;
class property PreferredPrefix[Namespace: TXMPKnownNamespace]: UnicodeString read GetPreferredPrefix;
class property URI[Namespace: TXMPKnownNamespace]: UnicodeString read GetURI;
end;
TXMPNamespaceInfo = class(TPersistent)
strict private
FCustomPrefix: UnicodeString;
FCustomURI: UnicodeString;
FKind: TXMPNamespace;
FOnChange: TNotifyEvent;
procedure Changed;
function GetPrefix: UnicodeString;
function GetURI: UnicodeString;
procedure SetPrefix(const Value: UnicodeString);
protected
constructor Create(AKind: TXMPNamespace;
const APreferredPrefix, AURI: UnicodeString); overload;
procedure DoAssign(Source: TXMPNamespaceInfo); overload;
function DoAssign(const APrefix, AURI: UnicodeString): Boolean; overload;
public
constructor Create(AKind: TXMPKnownNamespace); overload;
constructor Create(const APreferredPrefix, AURI: UnicodeString); overload;
constructor Create(ASource: TXMPNamespaceInfo); overload;
procedure Assign(Source: TPersistent); overload; override;
procedure Assign(AKind: TXMPKnownNamespace); reintroduce; overload;
procedure Assign(const APrefix, AURI: UnicodeString); reintroduce; overload;
property Kind: TXMPNamespace read FKind;
property Prefix: UnicodeString read GetPrefix write SetPrefix;
property URI: UnicodeString read GetURI;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
IXMPPropertyEnumerator = interface
['{32054DDD-5415-4F5D-8A38-C79BBCFD1A50}']
function GetCurrent: TXMPProperty;
function MoveNext: Boolean;
property Current: TXMPProperty read GetCurrent;
end;
IXMPPropertyCollection = interface
['{A72E8B43-34AE-49E8-A889-36B51B6A6E48}']
function GetNamespaceInfo: TXMPNamespaceInfo;
function GetProperty(Index: Integer): TXMPProperty;
function GetPropertyCount: Integer;
function GetEnumerator: IXMPPropertyEnumerator;
property Count: Integer read GetPropertyCount;
property Items[Index: Integer]: TXMPProperty read GetProperty; default;
property NamespaceInfo: TXMPNamespaceInfo read GetNamespaceInfo;
end;
TXMPPropertyKind = (xpSimple, xpStructure, xpAltArray, xpBagArray, xpSeqArray);
TXMPProperty = class(TInterfacedPersistent, IXMPPropertyCollection)
strict private
FKind: TXMPPropertyKind;
FName: UnicodeString;
FNamespaceInfo: TXMPNamespaceInfo;
FParentNamespace: Boolean;
FParentProperty: TXMPProperty;
FSchema: TXMPSchema;
FSubProperties: TList;
FValue: UnicodeString;
procedure NamespaceInfoChanged(Sender: TObject);
procedure SetKind(const Value: TXMPPropertyKind);
procedure SetName(const Value: UnicodeString);
procedure SetParentNamespace(Value: Boolean);
procedure SetSubPropertyCount(NewCount: Integer);
protected
procedure Changed;
function GetNamespaceInfo: TXMPNamespaceInfo;
function GetSubProperty(Index: Integer): TXMPProperty;
function GetSubPropertyByName(const AName: UnicodeString): TXMPProperty;
function GetSubPropertyCount: Integer;
function IXMPPropertyCollection.GetProperty = GetSubProperty;
function IXMPPropertyCollection.GetPropertyCount = GetSubPropertyCount;
public
class function HasNamedSubProperties(Kind: TXMPPropertyKind): Boolean; overload; static; inline;
class function SupportsSubProperties(Kind: TXMPPropertyKind): Boolean; overload; static; inline;
public
constructor Create(ASchema: TXMPSchema; AParentProperty: TXMPProperty;
const ASourceNode: IDOMNode = nil);
destructor Destroy; override;
function GetEnumerator: IXMPPropertyEnumerator;
function AddSubProperty(const AName: UnicodeString): TXMPProperty; //AName is ignored if self is an array property
function FindSubProperty(const AName: UnicodeString; out Prop: TXMPProperty): Boolean;
function ReadValue(const Default: Boolean): Boolean; overload;
function ReadValue(const Default: Integer): Integer; overload;
function ReadValue(const Default: UnicodeString = ''): UnicodeString; overload;
function RemoveSubProperty(const AName: UnicodeString): Boolean;
function HasNamedSubProperties: Boolean; overload;
function SupportsSubProperties: Boolean; overload;
procedure UpdateSubProperty(const SubPropName: UnicodeString;
SubPropKind: TXMPPropertyKind; const NewValue: UnicodeString); overload;
procedure UpdateSubProperty(const SubPropName, NewValue: UnicodeString); overload; inline;
procedure UpdateSubProperty(const SubPropName: UnicodeString; NewValue: Integer); overload;
procedure UpdateSubProperty(const SubPropName: UnicodeString; NewValue: Boolean); overload;
procedure WriteValue(const NewValue: UnicodeString); overload;
procedure WriteValue(const NewValue: Integer); overload;
procedure WriteValue(const NewValue: Boolean); overload;
property Kind: TXMPPropertyKind read FKind write SetKind;
property Name: UnicodeString read FName write SetName;
property NamespaceInfo: TXMPNamespaceInfo read FNamespaceInfo;
property ParentNamespace: Boolean read FParentNameSpace write SetParentNamespace default True;
property ParentProperty: TXMPProperty read FParentProperty;
property Schema: TXMPSchema read FSchema;
property SubProperties[const Name: UnicodeString]: TXMPProperty read GetSubPropertyByName; default; //adds if necessary
property SubProperties[Index: Integer]: TXMPProperty read GetSubProperty; default;
property SubPropertyCount: Integer read GetSubPropertyCount write SetSubPropertyCount;
end;
TXMPSchemaKind = TXMPNamespace deprecated {$IFDEF DepCom}'Renamed TXMPNamespace'{$ENDIF};
TXMPKnownSchemaKind = TXMPKnownNamespace deprecated {$IFDEF DepCom}'Renamed TXMPKnownNamespace'{$ENDIF};
TXMPKnownSchemaKinds = set of TXMPKnownNamespace deprecated {$IFDEF DepCom}'Use set of TXMPKnownNamespace'{$ENDIF};
TXMPSchema = class(TInterfacedPersistent, IXMPPropertyCollection)
strict private
FLoadingProperty: Boolean;
FNamespaceInfo: TXMPNamespaceInfo;
FOwner: TXMPPacket;
FProperties: TList;
procedure NamespaceInfoChanged(Sender: TObject);
protected
function LoadProperty(const ASourceNode: IDOMNode): TXMPProperty;
procedure Changed;
function FindOrAddProperty(const AName: UnicodeString): TXMPProperty;
function GetNamespaceInfo: TXMPNamespaceInfo;
function GetOwner: TPersistent; override;
function GetProperty(Index: Integer): TXMPProperty;
function GetPropertyCount: Integer;
public //deprecated - to be removed in a later release
function Kind: TXMPNamespace; deprecated {$IFDEF DepCom}'Use NamespaceInfo.Kind'{$ENDIF};
function PreferredPrefix: UnicodeString; deprecated {$IFDEF DepCom}'Use NamespaceInfo.Prefix'{$ENDIF};
function URI: UnicodeString; deprecated {$IFDEF DepCom}'Use NamespaceInfo.URI'{$ENDIF};
public
constructor Create(AOwner: TXMPPacket; const AURI: UnicodeString);
destructor Destroy; override;
function GetEnumerator: IXMPPropertyEnumerator;
function AddProperty(const AName: UnicodeString): TXMPProperty;
function FindProperty(const AName: UnicodeString; var AProperty: TXMPProperty): Boolean;
function RemoveProperty(const AName: UnicodeString): Boolean;
function RemoveProperties(const ANames: array of UnicodeString): Boolean;
property NamespaceInfo: TXMPNamespaceInfo read FNamespaceInfo;
property Owner: TXMPPacket read FOwner;
property Properties[const Name: UnicodeString]: TXMPProperty read FindOrAddProperty; default;
property Properties[Index: Integer]: TXMPProperty read GetProperty; default;
property PropertyCount: Integer read GetPropertyCount;
end;
TXMPWritePolicy = (xwAlwaysUpdate, xwUpdateIfExists, xwRemove);
TXMPPacket = class(TComponent, IStreamPersist, IStreamPersistEx, ITiffRewriteCallback)
public type
TEnumerator = record
private
FIndex: Integer;
FPacket: TXMPPacket;
function GetCurrent: TXMPSchema;
public
constructor Create(Packet: TXMPPacket);
function MoveNext: Boolean;
property Current: TXMPSchema read GetCurrent;
end;
TLoadErrorEvent = procedure (Sender: TXMPPacket; Source: TStream) of object;
strict private
FAboutAttributeValue: UnicodeString;
FDataToLazyLoad: IMetadataBlock;
FRawXMLCache: UTF8String;
FSchemas: TUnicodeStringList;
FTiffRewriteCallback: TSimpleTiffRewriteCallbackImpl;
FUpdatePolicy: TXMPWritePolicy;
FOnChange: TNotifyEvent;
FOnLoadError: TLoadErrorEvent;
procedure Clear(StillUpdating: Boolean); overload;
procedure GetGraphicSaveMethod(Stream: TStream; var Method: TGraphicSaveMethod);
function GetRawXML: UTF8String;
function GetSchema(Index: Integer): TXMPSchema;
function GetSchemaCount: Integer;
procedure SetAboutAttributeValue(const Value: UnicodeString);
procedure SetDataToLazyLoad(const Value: IMetadataBlock);
procedure SetRawXML(const XML: UTF8String);
procedure DoSaveToJPEG(InStream, OutStream: TStream); inline;
procedure DoSaveToPSD(InStream, OutStream: TStream);
procedure DoSaveToTIFF(InStream, OutStream: TStream);
procedure DoUpdateProperty(Policy: TXMPWritePolicy; SchemaKind: TXMPKnownNamespace;
const PropName: UnicodeString; PropKind: TXMPPropertyKind; const NewValue: UnicodeString);
procedure DoUpdateArrayProperty(SchemaKind: TXMPKnownNamespace;
const PropName: UnicodeString; ArrayPropKind: TXMPPropertyKind;
const NewValues: array of UnicodeString); overload;
protected
procedure AssignTo(Dest: TPersistent); override;
procedure Changed(AResetRawXMLCache: Boolean = True); virtual;
function FindOrAddSchema(const URI: UnicodeString): TXMPSchema; overload;
function FindOrAddSchema(Kind: TXMPKnownNamespace): TXMPSchema; overload; inline;
function GetEmpty: Boolean; inline;
procedure LoadError(Source: TStream); virtual;
procedure NeedLazyLoadedData;
property UpdatePolicy: TXMPWritePolicy read FUpdatePolicy write FUpdatePolicy;
property TiffRewriteCallback: TSimpleTiffRewriteCallbackImpl read FTiffRewriteCallback implements ITiffRewriteCallback;
public
constructor Create(AOwner: TComponent = nil); override;
class function CreateAsSubComponent(AOwner: TComponent): TXMPPacket; //use a class function rather than a constructor to avoid compiler warning re C++ accessibility
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure Clear; overload; inline;
function FindSchema(const URI: UnicodeString; var Schema: TXMPSchema): Boolean; overload;
function FindSchema(Kind: TXMPKnownNamespace; var Schema: TXMPSchema): Boolean; overload; inline;
function GetEnumerator: TEnumerator;
procedure LoadFromFile(const FileName: string);
procedure LoadFromStream(Stream: TStream);
{ Whether or not metadata was found, LoadFromGraphic returns True if the graphic
format was one recognised as one we could extract XMP data from and False otherwise. }
function LoadFromGraphic(Stream: TStream): Boolean; overload;
function LoadFromGraphic(const Graphic: IStreamPersist): Boolean; overload;
function LoadFromGraphic(const FileName: string): Boolean; overload;
procedure SaveToFile(const FileName: string);
procedure SaveToGraphic(const FileName: string); overload;
procedure SaveToGraphic(const Stream: TStream); overload;
procedure SaveToGraphic(const Graphic: IStreamPersist); overload;
procedure SaveToStream(Stream: TStream);
function TryLoadFromStream(Stream: TStream): Boolean;
procedure ResetRawXMLCache;
procedure RemoveProperty(SchemaKind: TXMPKnownNamespace;
const PropName: UnicodeString); overload;
procedure RemoveProperties(SchemaKind: TXMPKnownNamespace;
const PropNames: array of UnicodeString); overload;
procedure UpdateProperty(SchemaKind: TXMPKnownNamespace; const PropName: UnicodeString;
PropKind: TXMPPropertyKind; const NewValue: UnicodeString); overload;
procedure UpdateBagProperty(SchemaKind: TXMPKnownNamespace; const PropName: UnicodeString;
const NewValues: array of UnicodeString); overload;
procedure UpdateBagProperty(SchemaKind: TXMPKnownNamespace; const PropName: UnicodeString;
const NewValueList: UnicodeString); overload; inline; //commas and/or semi-colons act as delimiters
procedure UpdateSeqProperty(SchemaKind: TXMPKnownNamespace; const PropName: UnicodeString;
const NewValues: array of UnicodeString); overload;
procedure UpdateSeqProperty(SchemaKind: TXMPKnownNamespace; const PropName: UnicodeString;
const NewValueList: UnicodeString); overload; inline; //commas and/or semi-colons act as delimiters
procedure UpdateProperty(SchemaKind: TXMPKnownNamespace;
const PropName, NewValue: UnicodeString); overload; inline;
procedure UpdateProperty(SchemaKind: TXMPKnownNamespace;
const PropName: UnicodeString; const NewValue: Integer); overload;
procedure UpdateDateTimeProperty(SchemaKind: TXMPKnownNamespace;
const PropName: UnicodeString; const NewValue: TDateTimeTagValue; ApplyLocalBias: Boolean = True); overload;
property AboutAttributeValue: UnicodeString read FAboutAttributeValue write SetAboutAttributeValue;
property DataToLazyLoad: IMetadataBlock read FDataToLazyLoad write SetDataToLazyLoad;
property Schemas[Kind: TXMPKnownNamespace]: TXMPSchema read FindOrAddSchema; default;
property Schemas[Index: Integer]: TXMPSchema read GetSchema; default;
property Schemas[const URI: UnicodeString]: TXMPSchema read FindOrAddSchema; default;
public //deprecated methods - to be removed in a future release
function LoadFromJPEG(const JPEGFileName: string): Boolean; inline; deprecated {$IFDEF DepCom}'Use LoadFromGraphic'{$ENDIF};
published
property Empty: Boolean read GetEmpty;
property RawXML: UTF8String read GetRawXML write SetRawXML;
property SchemaCount: Integer read GetSchemaCount;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property OnLoadError: TLoadErrorEvent read FOnLoadError write FOnLoadError;
end;
const
XMPBoolStrs: array[Boolean] of string = ('False', 'True'); //case as per the XMP spec
function DateTimeToXMPString(const Value: TDateTime; ApplyLocalBias: Boolean = True): UnicodeString;
function EscapeXML(const Source: UnicodeString): UnicodeString;
function HasXMPSegmentHeader(Stream: TStream): Boolean; deprecated {$IFDEF DepCom}'Use Segment.HasXMPHeader'{$ENDIF};
implementation
uses
{$IFNDEF HasTTimeZone}Windows,{$ENDIF} Math, RTLConsts, Contnrs, DateUtils, StrUtils,
CCR.Exif.Consts, CCR.Exif.TagIDs, CCR.Exif.StreamHelper;
const
XMLLangAttrName = 'xml:lang';
DefaultLangIdent = 'x-default';
type
RDF = record const
URI = UnicodeString('http://www.w3.org/1999/02/22-rdf-syntax-ns#');
PreferredPrefix = 'rdf';
AboutAttrLocalName = 'about';
AboutAttrName = PreferredPrefix + ':' + AboutAttrLocalName;
AltNodeName = PreferredPrefix + ':' + 'Alt';
BagNodeName = PreferredPrefix + ':' + 'Bag';
DescriptionNodeName = PreferredPrefix + ':' + 'Description';
ListNodeLocalName = 'li';
ListNodeName = PreferredPrefix + ':' + ListNodeLocalName;
SeqNodeName = PreferredPrefix + ':' + 'Seq';
end;
TStringListThatOwnsItsObjects = class(TUnicodeStringList)
public
destructor Destroy; override;
procedure Clear; override;
procedure Delete(Index: Integer); override;
end;
TXMPPropertyEnumerator = class(TInterfacedObject, IXMPPropertyEnumerator)
strict private
FIndex: Integer;
FSource: TList;
protected
function GetCurrent: TXMPProperty;
function MoveNext: Boolean;
public
constructor Create(Source: TList);
end;
function GetUTCOffset(const Value: TDateTime; out AHours, AMins: Integer): Int64;
{$IFDEF HasTTimeZone}
begin
with TTimeZone.Local.GetUTCOffset(Value) do
begin
Result := Ticks;
AHours := Hours;
AMins := Minutes;
end;
{$ELSE} {$J+}
const
UseNewAPI: (Maybe, No, Yes) = Maybe;
GetTimeZoneInformationForYear: function(wYear: Word; DynInfo: Pointer;
var TZInfo: TTimeZoneInformation): BOOL; stdcall = nil;
TzSpecificLocalTimeToSystemTime: function(var TZInfo: TTimeZoneInformation;
const LocalTime: TSystemTime; out UTCTime: TSystemTime): BOOL; stdcall = nil;
var
DoFallback: Boolean;
LocalTime, UTCTime: TSystemTime;
TimeZoneInfo: TTimeZoneInformation;
begin
Result := 0;
DoFallback := True;
if UseNewAPI = Maybe then
begin
GetTimeZoneInformationForYear := GetProcAddress(GetModuleHandle(kernel32), 'GetTimeZoneInformationForYear');
TzSpecificLocalTimeToSystemTime := GetProcAddress(GetModuleHandle(kernel32), 'TzSpecificLocalTimeToSystemTime');
if Assigned(GetTimeZoneInformationForYear) and Assigned(TzSpecificLocalTimeToSystemTime) then
UseNewAPI := Yes
else
UseNewAPI := No;
end;
if UseNewAPI = Yes then
begin
DateTimeToSystemTime(Value, LocalTime);
if GetTimeZoneInformationForYear(LocalTime.wYear, nil, TimeZoneInfo) then
if TzSpecificLocalTimeToSystemTime(TimeZoneInfo, LocalTime, UTCTime) then
begin
Result := Round(MinsPerDay * (Value - SystemTimeToDateTime(UTCTime)));
DoFallback := False;
end;
end;
if DoFallback then
case GetTimeZoneInformation(TimeZoneInfo) of
TIME_ZONE_ID_UNKNOWN: Result := TimeZoneInfo.Bias;
TIME_ZONE_ID_STANDARD: Result := TimeZoneInfo.Bias + TimeZoneInfo.StandardBias;
TIME_ZONE_ID_DAYLIGHT: Result := TimeZoneInfo.Bias + TimeZoneInfo.DaylightBias;
end;
AHours := Abs(Result) div MinsPerHour;
AMins := Abs(Result) mod MinsPerHour;
{$ENDIF}
end;
function DateTimeToXMPString(const Value: TDateTime; ApplyLocalBias: Boolean): UnicodeString;
const
PlusNegSyms: array[Boolean] of string = ('-', '+');
var
Hours, Mins: Integer;
begin
Result := FormatDateTime('yyyy''-''mm''-''dd''T''hh'':''nn'':''ss''.''zzz', Value);
if ApplyLocalBias then
Result := Format('%s%s%.2d:%.2d', [Result,
PlusNegSyms[GetUTCOffset(Value, Hours, Mins) >= 0], Hours, Mins]);
end;
function DefinesNS(const Attr: IDOMNode): Boolean;
begin
Result := (Attr.prefix = 'xmlns') or (Attr.namespaceURI = 'http://www.w3.org/2000/xmlns/');
end;
function EscapeXML(const Source: UnicodeString): UnicodeString;
var
Ch: WideChar;
begin
with TMemoryStream.Create do
try
for Ch in Source do
case Ch of
'<': WriteWideChars('<', SmallEndian);
'>': WriteWideChars('>', SmallEndian);
'&': WriteWideChars('&', SmallEndian);
'''': WriteWideChars(''', SmallEndian);
'"': WriteWideChars('"', SmallEndian);
else WriteBuffer(Ch, 2);
end;
SetString(Result, PWideChar(Memory), Size div 2);
finally
Free;
end;
end;
function FindRootRDFNode(const Document: IDOMDocument; out Node: IDOMNode): Boolean;
begin
Result := True;
Node := Document.firstChild;
while Node <> nil do
begin
if Node.nodeType = ELEMENT_NODE then
case IndexStr(Node.localName, ['RDF', 'xmpmeta', 'xapmeta']) of
0: Exit; //support ExifTool's XML dumps, which don't parent the RDF node
1..2: Break;
end;
Node := Node.nextSibling;
end;
if Node <> nil then
begin
Node := Node.firstChild;
while Node <> nil do
begin
if (Node.nodeName = 'rdf:RDF') and (Node.nodeType = ELEMENT_NODE) then Break;
Node := Node.nextSibling;
end;
end;
Result := (Node <> nil);
end;
function HasXMPSegmentHeader(Stream: TStream): Boolean;
begin
Result := Stream.TryReadHeader(TJPEGSegment.XMPHeader, SizeOf(TJPEGSegment.XMPHeader), True);
end;
procedure UpdateChildNamespaceInfos(const Parent: IXMPPropertyCollection);
var
Prop: TXMPProperty;
begin
for Prop in Parent do
if Prop.ParentNamespace then
begin
Prop.NamespaceInfo.DoAssign(Parent.NamespaceInfo);
UpdateChildNamespaceInfos(Prop);
end;
end;
{ TKnownXMPNamespaces }
class procedure TKnownXMPNamespaces.NeedKnownURIs;
var
I: Integer;
begin
if FKnownURIs <> nil then Exit;
FKnownURIs := TUnicodeStringList.Create;
with FKnownURIs do
begin
AddObject(RDF.URI, TObject(xsRDF));
AddObject('http://ns.adobe.com/camera-raw-settings/1.0/', TObject(xsCameraRaw));
AddObject('http://ns.adobe.com/xap/1.0/g', TObject(xsColorant));
AddObject('http://ns.adobe.com/xap/1.0/sType/Dimensions#', TObject(xsDimensions));
AddObject('http://purl.org/dc/elements/1.1/', TObject(xsDublinCore));
AddObject('http://ns.adobe.com/xap/1.0/sType/Font#', TObject(xsFont));
AddObject('http://ns.adobe.com/exif/1.0/', TObject(xsExif));
AddObject('http://ns.adobe.com/exif/1.0/aux/', TObject(xsExifAux));
AddObject('http://iptc.org/std/Iptc4xmpCore/1.0/xmlns/', TObject(xsIPTC));
AddObject('http://ns.adobe.com/xap/1.0/sType/Job#', TObject(xsJob));
AddObject('http://ns.microsoft.com/photo/1.0', TObject(xsMicrosoftPhoto));
AddObject('http://ns.adobe.com/pdf/1.3/', TObject(xsPDF));
AddObject('http://ns.adobe.com/photoshop/1.0/', TObject(xsPhotoshop));
AddObject('http://ns.adobe.com/xap/1.0/sType/ResourceEvent#', TObject(xsResourceEvent));
AddObject('http://ns.adobe.com/xap/1.0/sType/ResourceRef#', TObject(xsResourceRef));
AddObject('http://ns.adobe.com/xap/1.0/g/img/', TObject(xsThumbnail));
AddObject('http://ns.adobe.com/tiff/1.0/', TObject(xsTIFF));
AddObject('http://ns.adobe.com/xap/1.0/sType/Version#', TObject(xsVersion));
AddObject('http://ns.adobe.com/xap/1.0/', TObject(xsXMPBasic));
AddObject('http://ns.adobe.com/xap/1.0/bj/', TObject(xsXMPBasicJobTicket));
AddObject('http://ns.adobe.com/xmp/1.0/DynamicMedia/', TObject(xsXMPDynamicMedia));
AddObject('http://ns.adobe.com/xap/1.0/mm/', TObject(xsXMPMediaManagement));
AddObject('http://ns.adobe.com/xap/1.0/t/pg/', TObject(xsXMPPagedText));
AddObject('http://ns.adobe.com/xap/1.0/rights/', TObject(xsXMPRights));
Sorted := True;
for I := Count - 1 downto 0 do
FKnownIndices[TXMPKnownNamespace(Objects[I])] := I;
end;
end;
class function TKnownXMPNamespaces.GetPreferredPrefix(Namespace: TXMPKnownNamespace): UnicodeString;
begin
case Namespace of
xsRDF: Result := RDF.PreferredPrefix;
xsCameraRaw: Result := 'crs';
xsColorant: Result := 'xmpG';
xsDimensions: Result := 'stDim';
xsDublinCore: Result := 'dc';
xsFont: Result := 'stFnt';
xsExif: Result := 'exif';
xsExifAux: Result := 'aux';
xsIPTC: Result := 'Iptc4xmpCore';
xsJob: Result := 'stJob';
xsMicrosoftPhoto: Result := 'MicrosoftPhoto';
xsPDF: Result := 'pdf';
xsPhotoshop: Result := 'photoshop';
xsResourceEvent: Result := 'stEvt';
xsResourceRef: Result := 'stRef';
xsThumbnail: Result := 'xmpGImg';
xsTIFF: Result := 'tiff';
xsVersion: Result := 'stVer';
xsXMPBasic: Result := 'xmp';
xsXMPBasicJobTicket: Result := 'xmpBJ';
xsXMPDynamicMedia: Result := 'xmpDM';
xsXMPMediaManagement: Result := 'xmpMM';
xsXMPPagedText: Result := 'xmpTPg';
xsXMPRights: Result := 'xmpRights';
else Assert(False);
end;
end;
class function TKnownXMPNamespaces.GetURI(Namespace: TXMPKnownNamespace): UnicodeString;
begin
NeedKnownURIs;
Result := FKnownURIs[FKnownIndices[Namespace]];
end;
class function TKnownXMPNamespaces.Find(const URI: UnicodeString; out Namespace: TXMPNamespace): Boolean;
var
Index: Integer;
begin
NeedKnownURIs;
Result := FKnownURIs.Find(URI, Index);
if Result then
Namespace := TXMPNamespace(FKnownURIs.Objects[Index])
else
Namespace := xsUnknown;
end;
{ TStringListThatOwnsItsObjects }
destructor TStringListThatOwnsItsObjects.Destroy;
begin
Clear;
inherited;
end;
procedure TStringListThatOwnsItsObjects.Clear;
var
I: Integer;
begin
for I := Count - 1 downto 0 do
Objects[I].Free;
inherited;
end;
procedure TStringListThatOwnsItsObjects.Delete(Index: Integer);
begin
Objects[Index].Free;
inherited;
end;
{ TXMPPropertyEnumerator }
constructor TXMPPropertyEnumerator.Create(Source: TList);
begin
FIndex := -1;
FSource := Source;
end;
function TXMPPropertyEnumerator.GetCurrent: TXMPProperty;
begin
Result := FSource[FIndex];
end;
function TXMPPropertyEnumerator.MoveNext: Boolean;
begin
Inc(FIndex);
Result := (FIndex < FSource.Count);
end;
{ TXMPNamespaceInfo }
constructor TXMPNamespaceInfo.Create(AKind: TXMPNamespace;
const APreferredPrefix, AURI: UnicodeString);
begin
inherited Create;
FKind := AKind;
FCustomPrefix := APreferredPrefix;
FCustomURI := AURI;
end;
constructor TXMPNamespaceInfo.Create(AKind: TXMPKnownNamespace);
begin
Create(AKind, '', '');
end;
constructor TXMPNamespaceInfo.Create(const APreferredPrefix, AURI: UnicodeString);
begin
Create(xsUnknown, APreferredPrefix, AURI);
end;
constructor TXMPNamespaceInfo.Create(ASource: TXMPNamespaceInfo);
begin
inherited Create;
Assign(ASource);
end;
procedure TXMPNamespaceInfo.Assign(Source: TPersistent);
begin
if Source is TXMPNamespaceInfo then
begin
DoAssign(TXMPNamespaceInfo(Source));
Changed;
Exit;
end;
inherited;
end;
procedure TXMPNamespaceInfo.Assign(AKind: TXMPKnownNamespace);
begin
if FKind = AKind then Exit;
FCustomPrefix := '';
FCustomURI := '';
FKind := AKind;
Changed;
end;
procedure TXMPNamespaceInfo.Assign(const APrefix, AURI: UnicodeString);
begin
if DoAssign(APrefix, AURI) then Changed;
end;
procedure TXMPNamespaceInfo.Changed;
begin
if Assigned(FOnChange) then FOnChange(Self);
end;
procedure TXMPNamespaceInfo.DoAssign(Source: TXMPNamespaceInfo);
begin
FCustomPrefix := Source.FCustomPrefix;
FCustomURI := Source.FCustomURI;
FKind := Source.FKind;
end;
function TXMPNamespaceInfo.DoAssign(const APrefix, AURI: UnicodeString): Boolean;
begin
Result := (AURI <> URI) or (APrefix <> Prefix);
if not Result then Exit;
if TKnownXMPNamespaces.Find(AURI, FKind) and (AURI = TKnownXMPNamespaces.PreferredPrefix[FKind]) then
begin
FCustomPrefix := '';
FCustomURI := '';
end
else
begin
FCustomPrefix := APrefix;
FCustomURI := AURI;
end;
end;
function TXMPNamespaceInfo.GetPrefix: UnicodeString;
begin
if (FCustomPrefix <> '') or (FKind = xsUnknown) then
Result := FCustomPrefix
else
Result := TKnownXMPNamespaces.PreferredPrefix[FKind];
end;
function TXMPNamespaceInfo.GetURI: UnicodeString;
begin
if FKind = xsUnknown then
Result := FCustomURI
else
Result := TKnownXMPNamespaces.URI[FKind];
end;
procedure TXMPNamespaceInfo.SetPrefix(const Value: UnicodeString);
begin
if Value = Prefix then Exit;
FCustomPrefix := Value;
Changed;
end;
{ TXMPProperty }
class function TXMPProperty.HasNamedSubProperties(Kind: TXMPPropertyKind): Boolean;
begin
Result := (Kind in [xpStructure, xpAltArray]);
end;
class function TXMPProperty.SupportsSubProperties(Kind: TXMPPropertyKind): Boolean;
begin
Result := (Kind in [xpAltArray, xpBagArray, xpSeqArray, xpStructure]);
end;
constructor TXMPProperty.Create(ASchema: TXMPSchema; AParentProperty: TXMPProperty;
const ASourceNode: IDOMNode);
procedure UseSourceNodeNameAndNamespace;
begin
FName := ASourceNode.localName;
if FNamespaceInfo.DoAssign(ASourceNode.prefix, ASourceNode.namespaceURI) then
FParentNamespace := False;
end;
var
Attrs: IDOMNamedNodeMap;
ChildNode, DataNode, TextNode: IDOMNode;
DoAdd: Boolean;
I: Integer;
PropAndNodeStructure: Boolean;
S: string;
SourceAsElem: IDOMElement;
begin
inherited Create;
FParentNamespace := True;
FNamespaceInfo := TXMPNamespaceInfo.Create(ASchema.NamespaceInfo);
if AParentProperty <> nil then
FNamespaceInfo.DoAssign(AParentProperty.NamespaceInfo)
else if ASchema <> nil then
FNamespaceInfo.DoAssign(ASchema.NamespaceInfo)
else
FParentNamespace := False;
FParentProperty := AParentProperty;
FSchema := ASchema;
FSubProperties := TObjectList.Create;
if ASourceNode = nil then Exit;
//figure out our kind
PropAndNodeStructure := Supports(ASourceNode, IDOMElement, SourceAsElem) and
(SourceAsElem.getAttributeNS(RDF.URI, 'parseType') = 'Resource'); //http://www.w3.org/TR/REC-rdf-syntax/#section-Syntax-parsetype-resource
if PropAndNodeStructure then
begin
FKind := xpStructure;
DataNode := ASourceNode;
end
else
begin
DataNode := ASourceNode.firstChild;
if DataNode <> nil then
begin
repeat
{ Originally, this loop was exited as soon as a text node was found. This
however doesn't work with the ADOM backend (as used by default on OS X)
because ADOM can intepret whitespace prior to a child element as a text
node of the parent. }
case DataNode.nodeType of
TEXT_NODE: TextNode := DataNode;
ELEMENT_NODE:
begin
S := DataNode.nodeName;
if S = RDF.AltNodeName then
FKind := xpAltArray
else if S = RDF.BagNodeName then
FKind := xpBagArray
else if S = RDF.SeqNodeName then
FKind := xpSeqArray
else if S = RDF.DescriptionNodeName then
FKind := xpStructure;
Break;
end;
end;
DataNode := DataNode.nextSibling;
until (DataNode = nil);
if DataNode = nil then DataNode := TextNode;
end;
end;
{ Get the value, if appropriate, and check for super-inlined structures. For life of
me I can't see where in the XMP spec the latter are allowed - cf. p.19 of the spec
pt.1 PDF), but Adobe's XMP Toolkit can output them, at least in v4.x. }
if FKind = xpSimple then
if DataNode <> nil then
FValue := DataNode.nodeValue
else if ASourceNode.attributes <> nil then
begin
Attrs := ASourceNode.attributes;
for I := 0 to Attrs.length - 1 do
if not DefinesNS(Attrs[I]) then
begin
DataNode := ASourceNode;
FKind := xpStructure;
Break;
end;
end;
//get the name
if ParentProperty = nil then
UseSourceNodeNameAndNamespace
else
case ParentProperty.Kind of
xpBagArray, xpSeqArray: FName := '';
xpAltArray:
if SourceAsElem <> nil then
FName := SourceAsElem.getAttribute(XMLLangAttrName)
else
FName := '';
else UseSourceNodeNameAndNamespace;
end;
//load any sub-props
if not SupportsSubProperties then Exit;
Assert(DataNode <> nil);
Attrs := DataNode.attributes;
if (FKind = xpStructure) and not PropAndNodeStructure and (Attrs <> nil) then
begin
FSubProperties.Capacity := Attrs.length;
for I := 0 to FSubProperties.Capacity - 1 do
begin
ChildNode := Attrs[I];
if not DefinesNS(ChildNode) then
FSubProperties.Add(TXMPProperty.Create(Schema, Self, ChildNode));
end;
end;
FSubProperties.Capacity := FSubProperties.Count + DataNode.childNodes.length;
ChildNode := DataNode.firstChild;
while ChildNode <> nil do
begin
DoAdd := False;
if ChildNode.nodeType = ELEMENT_NODE then
begin
if FKind = xpStructure then
DoAdd := True
else if ChildNode.nodeName = RDF.ListNodeName then
DoAdd := (FKind <> xpAltArray) or
(ChildNode.attributes.getNamedItem(XMLLangAttrName) <> nil);
end;
if DoAdd then
FSubProperties.Add(TXMPProperty.Create(Schema, Self, ChildNode));
ChildNode := ChildNode.nextSibling;
end;
FNamespaceInfo.OnChange := NamespaceInfoChanged;
end;
destructor TXMPProperty.Destroy;
begin
FNamespaceInfo.Free;
FSubProperties.Free;
inherited;
end;
function TXMPProperty.AddSubProperty(const AName: UnicodeString): TXMPProperty;
begin
if not SupportsSubProperties then
raise EInvalidXMPOperation.CreateRes(@SSubPropertiesNotSupported);
if HasNamedSubProperties and (AName = '') then
raise EInvalidXMPOperation.CreateRes(@SSubPropertiesMustBeNamed);
Result := TXMPProperty.Create(Schema, Self);
FSubProperties.Add(Result);
if HasNamedSubProperties then Result.FName := AName;
Changed;
end;
procedure TXMPProperty.Changed;
begin
if FSchema <> nil then FSchema.Changed;
end;
function TXMPProperty.FindSubProperty(const AName: UnicodeString; out Prop: TXMPProperty): Boolean;
var
I: Integer;
begin
Result := True;
for I := SubPropertyCount - 1 downto 0 do
begin
Prop := SubProperties[I];
if Prop.Name = AName then Exit;
end;
Prop := nil;
Result := False;
end;
function TXMPProperty.GetEnumerator: IXMPPropertyEnumerator;
begin
Result := TXMPPropertyEnumerator.Create(FSubProperties);
end;
function TXMPProperty.GetNamespaceInfo: TXMPNamespaceInfo;
begin
Result := FNamespaceInfo;
end;
function TXMPProperty.GetSubProperty(Index: Integer): TXMPProperty;
begin
Result := TXMPProperty(FSubProperties[Index]);
end;
function TXMPProperty.GetSubPropertyByName(const AName: UnicodeString): TXMPProperty;
begin
if not FindSubProperty(AName, Result) then
Result := AddSubProperty(AName);
end;
function TXMPProperty.GetSubPropertyCount: Integer;
begin
Result := FSubProperties.Count;
end;
procedure TXMPProperty.NamespaceInfoChanged(Sender: TObject);
begin
FParentNamespace := False;
UpdateChildNamespaceInfos(Self);
Changed;
end;
function TXMPProperty.ReadValue(const Default: Boolean): Boolean;
var
S: string;
begin
S := ReadValue;
if SameText(S, XMPBoolStrs[True]) then
Result := True
else if SameText(S, XMPBoolStrs[False]) then
Result := False
else if S = '1' then
Result := True
else if S = '0' then
Result := False
else
Result := Default;
end;
function TXMPProperty.ReadValue(const Default: Integer): Integer;
begin
Result := StrToIntDef(ReadValue, Default);
end;
function TXMPProperty.ReadValue(const Default: UnicodeString): UnicodeString;
var
I: Integer;
begin
case Kind of
xpSimple: if Pointer(FValue) <> nil then Result := FValue else Result := Default;
xpAltArray: Result := SubProperties[DefaultLangIdent].ReadValue(Default);
xpBagArray, xpSeqArray:
case SubPropertyCount of
0: Result := Default;
1: Result := SubProperties[0].ReadValue(Default);
else
Result := SubProperties[0].ReadValue;
for I := 1 to SubPropertyCount - 1 do
Result := Result + ',' + SubProperties[I].ReadValue;
end;
else Result := Default;
end;
end;
function TXMPProperty.RemoveSubProperty(const AName: UnicodeString): Boolean;
var
I: Integer;
Prop: TXMPProperty;
begin
Result := False;
for I := 0 to SubPropertyCount - 1 do
begin
Prop := FSubProperties.List[I];
if AName = Prop.Name then
begin
FSubProperties.Delete(I);
Result := True;
Changed;
Exit;
end;
end;
end;
procedure TXMPProperty.SetKind(const Value: TXMPPropertyKind);
var
I: Integer;
SubProp: TXMPProperty;
begin
if Value = Kind then Exit;
if not SupportsSubProperties(Value) then
SubPropertyCount := 0
else
for I := SubPropertyCount - 1 downto 0 do
begin
SubProp := SubProperties[I];
if not HasNamedSubProperties(Value) then
SubProp.FName := ''
else if SubProp.FName = '' then
SubProp.FName := Format('SubProp%d', [I]);
end;
FKind := Value;
Changed;
end;
procedure TXMPProperty.SetName(const Value: UnicodeString);
begin
if Value = FName then Exit;
Assert(Value <> '');
FName := Value;
Changed;
end;
procedure TXMPProperty.SetParentNamespace(Value: Boolean);
begin
if Value = FParentNamespace then Exit;
FParentNamespace := Value;
if Value then
if ParentProperty <> nil then
FNamespaceInfo.DoAssign(ParentProperty.NamespaceInfo)
else
FNamespaceInfo.DoAssign(Schema.NamespaceInfo);
Changed;
end;
procedure TXMPProperty.SetSubPropertyCount(NewCount: Integer);
var
I: Integer;
NewSubProp: TXMPProperty;
begin
if NewCount < 0 then NewCount := 0;
if NewCount = FSubProperties.Count then Exit;
if not SupportsSubProperties then
raise EInvalidXMPOperation.CreateRes(@SSubPropertiesNotSupported);
if NewCount < FSubProperties.Count then
FSubProperties.Count := NewCount
else
for I := FSubProperties.Count to NewCount - 1 do
begin
NewSubProp := TXMPProperty.Create(Schema, Self);
if HasNamedSubProperties then NewSubProp.FName := Format('SubProp%d', [I]);
FSubProperties.Add(NewSubProp);
end;
Changed;
end;
function TXMPProperty.HasNamedSubProperties: Boolean;
begin
Result := HasNamedSubProperties(Kind);
end;
function TXMPProperty.SupportsSubProperties: Boolean;
begin
Result := SupportsSubProperties(Kind);
end;
procedure TXMPProperty.UpdateSubProperty(const SubPropName: UnicodeString;
SubPropKind: TXMPPropertyKind; const NewValue: UnicodeString);
var
SubProp: TXMPProperty;
begin
if (FSchema.Owner.UpdatePolicy = xwRemove) or (NewValue = '') then
begin
RemoveSubProperty(SubPropName);
Exit;
end;
if not FindSubProperty(SubPropName, SubProp) then
begin
if FSchema.Owner.UpdatePolicy = xwUpdateIfExists then Exit;
if not (Kind in [xpStructure, xpAltArray]) then Kind := xpStructure;
SubProp := AddSubProperty(SubPropName)
end;
SubProp.Kind := SubPropKind;
SubProp.WriteValue(NewValue);
end;
procedure TXMPProperty.UpdateSubProperty(const SubPropName, NewValue: UnicodeString);
begin
UpdateSubProperty(SubPropName, xpSimple, NewValue);
end;
procedure TXMPProperty.UpdateSubProperty(const SubPropName: UnicodeString; NewValue: Integer);
begin
UpdateSubProperty(SubPropName, xpSimple, IntToStr(NewValue));
end;
procedure TXMPProperty.UpdateSubProperty(const SubPropName: UnicodeString; NewValue: Boolean);
begin
UpdateSubProperty(SubPropName, xpSimple, XMPBoolStrs[NewValue]);
end;
procedure TXMPProperty.WriteValue(const NewValue: UnicodeString);
var
I, BeginPos, TotalLen: Integer;
Strings: TUnicodeStringList;
begin
case Kind of
xpSimple:
if NewValue <> FValue then
begin
FValue := NewValue;
Changed;
end;
xpStructure: raise EInvalidXMPOperation.CreateRes(@SCannotWriteSingleValueToStructureProperty);
xpAltArray: SubProperties[DefaultLangIdent].WriteValue(NewValue);
else
Strings := TUnicodeStringList.Create;
try
BeginPos := 1;
TotalLen := Length(NewValue);
for I := 1 to TotalLen do
if CharInSet(NewValue[I], [',', ';']) then
begin
Strings.Add(Copy(NewValue, BeginPos, I - BeginPos));
BeginPos := I + 1;
end;
if BeginPos <= TotalLen then Strings.Add(Copy(NewValue, BeginPos, TotalLen));
SubPropertyCount := Strings.Count;
for I := 0 to Strings.Count - 1 do
SubProperties[I].WriteValue(Strings[I]);
finally
Strings.Free;
end;
end;
end;
procedure TXMPProperty.WriteValue(const NewValue: Integer);
begin
WriteValue(IntToStr(NewValue));
end;
procedure TXMPProperty.WriteValue(const NewValue: Boolean);
begin
WriteValue(XMPBoolStrs[NewValue]);
end;
{ TXMPSchema }
constructor TXMPSchema.Create(AOwner: TXMPPacket; const AURI: UnicodeString);
var
Kind: TXMPNamespace;
begin
if TKnownXMPNamespaces.Find(AURI, Kind) then
FNamespaceInfo := TXMPNamespaceInfo.Create(Kind)
else
FNamespaceInfo := TXMPNamespaceInfo.Create('', AURI);
FNamespaceInfo.OnChange := NamespaceInfoChanged;
FOwner := AOwner;
FProperties := TObjectList.Create;
end;
destructor TXMPSchema.Destroy;
begin
FNamespaceInfo.Free;
FProperties.Free;
inherited;
end;
function TXMPSchema.AddProperty(const AName: UnicodeString): TXMPProperty;
begin
if NamespaceInfo.Prefix = '' then
raise EInvalidXMPOperation.CreateRes(@SPreferredPrefixMustBeSet);
Result := TXMPProperty.Create(Self, nil);
FProperties.Add(Result);
if AName <> '' then
Result.Name := AName
else
Changed;
end;
procedure TXMPSchema.Changed;
begin
if FOwner <> nil then FOwner.Changed;
end;
function TXMPSchema.FindProperty(const AName: UnicodeString; var AProperty: TXMPProperty): Boolean;
var
I: Integer;
begin
for I := 0 to PropertyCount - 1 do
begin
AProperty := Properties[I];
if AProperty.Name = AName then
begin
Result := True;
Exit;
end;
end;
AProperty := nil;
Result := False;
end;
function TXMPSchema.FindOrAddProperty(const AName: UnicodeString): TXMPProperty;
begin
if not FindProperty(AName, Result) then
Result := AddProperty(AName);
end;
function TXMPSchema.GetEnumerator: IXMPPropertyEnumerator;
begin
Result := TXMPPropertyEnumerator.Create(FProperties);
end;
function TXMPSchema.GetNamespaceInfo: TXMPNamespaceInfo;
begin
Result := FNamespaceInfo;
end;
function TXMPSchema.GetOwner: TPersistent;
begin
Result := FOwner;
end;
function TXMPSchema.GetProperty(Index: Integer): TXMPProperty;
begin
Result := FProperties[Index];
end;
function TXMPSchema.GetPropertyCount: Integer;
begin
Result := FProperties.Count;
end;
function TXMPSchema.LoadProperty(const ASourceNode: IDOMNode): TXMPProperty;
begin
FLoadingProperty := True;
try
if FProperties.Count = 0 then
NamespaceInfo.Prefix := ASourceNode.prefix;
Result := TXMPProperty.Create(Self, nil, ASourceNode);
FProperties.Add(Result);
finally
FLoadingProperty := False;
end;
end;
procedure TXMPSchema.NamespaceInfoChanged(Sender: TObject);
begin
UpdateChildNamespaceInfos(Self);
if not FLoadingProperty then Changed;
end;
function TXMPSchema.RemoveProperty(const AName: UnicodeString): Boolean;
begin
Result := RemoveProperties([AName]);
end;
function TXMPSchema.RemoveProperties(const ANames: array of UnicodeString): Boolean;
var
I, J: Integer;
Prop: TXMPProperty;
begin
Result := False;
for I := FProperties.Count - 1 downto 0 do
begin
Prop := FProperties.List[I];
for J := High(ANames) downto Low(ANames) do
if Prop.Name = ANames[J] then
begin
FProperties.Delete(I);
Result := True;
Break;
end;
end;
end;
function TXMPSchema.Kind: TXMPNamespace;
begin
Result := FNamespaceInfo.Kind;
end;
function TXMPSchema.PreferredPrefix: UnicodeString;
begin
Result := FNamespaceInfo.Prefix;
end;
function TXMPSchema.URI: UnicodeString;
begin
Result := FNamespaceInfo.URI;
end;
{ TXMPPacket }
constructor TXMPPacket.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSchemas := TStringListThatOwnsItsObjects.Create;
FSchemas.CaseSensitive := False;
FSchemas.Sorted := True;
FTiffRewriteCallback := TSimpleTiffRewriteCallbackImpl.Create(Self, ttXMP);
end;
class function TXMPPacket.CreateAsSubComponent(AOwner: TComponent): TXMPPacket;
begin
Result := Create(AOwner);
Result.Name := 'XMPPacket';
Result.SetSubComponent(True);
end;
destructor TXMPPacket.Destroy;
begin
FSchemas.Free;
FTiffRewriteCallback.Free;
inherited;
end;
procedure TXMPPacket.Assign(Source: TPersistent);
begin
if Source = nil then
Clear
else if Source is TXMPPacket then
begin
if TXMPPacket(Source).DataToLazyLoad <> nil then
DataToLazyLoad := TXMPPacket(Source).DataToLazyLoad
else
RawXML := TXMPPacket(Source).RawXML;
end
else if Source is TStrings then
RawXML := UTF8Encode(TStrings(Source).Text)
else if Source is TUnicodeStrings then
RawXML := UTF8Encode(TUnicodeStrings(Source).Text)
else
inherited;
end;
procedure TXMPPacket.AssignTo(Dest: TPersistent);
begin
if Dest is TStrings then
TStrings(Dest).Text := UTF8ToString(RawXML)
else if Dest is TUnicodeStrings then
TUnicodeStrings(Dest).Text := UTF8ToString(RawXML)
else
inherited;
end;
procedure TXMPPacket.Changed(AResetRawXMLCache: Boolean = True);
begin
if AResetRawXMLCache then FRawXMLCache := '';
if Assigned(FOnChange) then FOnChange(Self);
end;
procedure TXMPPacket.ResetRawXMLCache;
begin
FRawXMLCache := '';
end;
procedure TXMPPacket.Clear(StillUpdating: Boolean);
begin
FDataToLazyLoad := nil;
if (FSchemas.Count = 0) and (FAboutAttributeValue = '') then Exit;
FAboutAttributeValue := '';
FSchemas.Clear;
if not StillUpdating then Changed;
end;
procedure TXMPPacket.Clear;
begin
Clear(False);
end;
procedure TXMPPacket.DoSaveToJPEG(InStream, OutStream: TStream);
begin
UpdateApp1JPEGSegments(InStream, OutStream, nil, Self);
end;
procedure TXMPPacket.DoSaveToPSD(InStream, OutStream: TStream);
var
Block: IAdobeResBlock;
Info: TPSDInfo;
NewBlocks: IInterfaceList;
StartPos: Int64;
begin
StartPos := InStream.Position;
NewBlocks := TInterfaceList.Create;
if not Empty then NewBlocks.Add(CreateAdobeBlock(TAdobeResBlock.XMPTypeID, Self));
for Block in ParsePSDHeader(InStream, Info) do
if not Block.IsXMPBlock then NewBlocks.Add(Block);
WritePSDHeader(OutStream, Info.Header);
WritePSDResourceSection(OutStream, NewBlocks);
InStream.Position := StartPos + Info.LayersSectionOffset;
OutStream.CopyFrom(InStream, InStream.Size - InStream.Position);
end;
procedure TXMPPacket.DoSaveToTIFF(InStream, OutStream: TStream);
begin
RewriteTiff(InStream, OutStream, Self);
end;
function TXMPPacket.FindSchema(const URI: UnicodeString; var Schema: TXMPSchema): Boolean;
var
Index: Integer;
begin
NeedLazyLoadedData;
Result := FSchemas.Find(URI, Index);
if Result then Schema := FSchemas.Objects[Index] as TXMPSchema;
end;
function TXMPPacket.FindSchema(Kind: TXMPKnownNamespace; var Schema: TXMPSchema): Boolean;
begin
Result := FindSchema(TKnownXMPNamespaces.URI[Kind], Schema);
end;
function TXMPPacket.FindOrAddSchema(const URI: UnicodeString): TXMPSchema;
var
Index: Integer;
begin
NeedLazyLoadedData;
if FSchemas.Find(URI, Index) then
Result := FSchemas.Objects[Index] as TXMPSchema
else
begin
Result := TXMPSchema.Create(Self, URI);
FSchemas.AddObject(URI, Result);
end;
end;
function TXMPPacket.FindOrAddSchema(Kind: TXMPKnownNamespace): TXMPSchema;
begin
Result := FindOrAddSchema(TKnownXMPNamespaces.URI[Kind]);
end;
procedure TXMPPacket.SetAboutAttributeValue(const Value: UnicodeString);
begin
NeedLazyLoadedData;
if Value = FAboutAttributeValue then Exit;
FAboutAttributeValue := Value;
Changed;
end;
function TXMPPacket.GetEmpty: Boolean;
begin
Result := (DataToLazyLoad = nil) and (SchemaCount = 0);
end;
function TXMPPacket.GetEnumerator: TEnumerator;
begin
Result := TEnumerator.Create(Self);
end;
procedure TXMPPacket.GetGraphicSaveMethod(Stream: TStream; var Method: TGraphicSaveMethod);
begin
if HasJPEGHeader(Stream) then
Method := DoSaveToJPEG
else if HasPSDHeader(Stream) then
Method := DoSaveToPSD
else if HasTiffHeader(Stream) then
Method := DoSaveToTIFF
end;
function TXMPPacket.GetRawXML: UTF8String;
var
Stream: TMemoryStream;
begin
if FRawXMLCache = '' then
begin
Stream := TMemoryStream.Create;
try
SaveToStream(Stream);
SetString(FRawXMLCache, PAnsiChar(Stream.Memory), Stream.Size);
finally
Stream.Free;
end;
end;
Result := FRawXMLCache;
end;
function TXMPPacket.GetSchema(Index: Integer): TXMPSchema;
begin
NeedLazyLoadedData;
Result := FSchemas.Objects[Index] as TXMPSchema;
end;
function TXMPPacket.GetSchemaCount: Integer;
begin
NeedLazyLoadedData;
Result := FSchemas.Count;
end;
procedure TXMPPacket.LoadError(Source: TStream);
begin
if Assigned(FOnLoadError) then
FOnLoadError(Self, Source)
else
raise EInvalidXMPPacket.CreateRes(@SInvalidXMPPacket);
end;
procedure TXMPPacket.LoadFromFile(const FileName: string);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
function TXMPPacket.LoadFromGraphic(Stream: TStream): Boolean;
var
Block: IAdobeResBlock;
Directory: IFoundTiffDirectory;
PSDInfo: TPSDInfo;
Segment: IFoundJPEGSegment;
Tag: ITiffTag;
begin
Result := True;
if HasJPEGHeader(Stream) then
begin
for Segment in JPEGHeader(Stream, [jmApp1]) do
if Segment.IsXMPBlock then
begin
LoadFromStream(Segment.Data);
Exit;
end;
end
else if HasPSDHeader(Stream) then
begin
for Block in ParsePSDHeader(Stream, PSDInfo) do
if Block.IsXMPBlock then
begin
LoadFromStream(Block.Data);
Exit;
end;
end
else if HasTiffHeader(Stream) then
for Directory in ParseTiff(Stream) do
begin
if Directory.FindTag(ttXMP, Tag) and Tag.IsXMPBlock then
begin
LoadFromStream(Tag.Data);
Exit;
end;
Break; //only interested in the main IFD
end
else
Result := False;
Clear;
end;
function TXMPPacket.LoadFromGraphic(const Graphic: IStreamPersist): Boolean;
var
Stream: TMemoryStream;
begin
Stream := TMemoryStream.Create;
try
Graphic.SaveToStream(Stream);
Stream.Position := 0;
Result := LoadFromGraphic(Stream);
finally
Stream.Free;
end;
end;
function TXMPPacket.LoadFromGraphic(const FileName: string): Boolean;
var
Stream: TFileStream;
begin
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
Result := LoadFromGraphic(Stream)
finally
Stream.Free;
end;
end;
function TXMPPacket.LoadFromJPEG(const JPEGFileName: string): Boolean;
begin
Result := LoadFromGraphic(JPEGFileName);
end;
procedure TXMPPacket.LoadFromStream(Stream: TStream);
begin
if not TryLoadFromStream(Stream) then LoadError(Stream);
end;
procedure TXMPPacket.NeedLazyLoadedData;
var
Item: IMetadataBlock;
begin
if FDataToLazyLoad = nil then Exit;
Item := FDataToLazyLoad;
FDataToLazyLoad := nil; //in case of an exception, nil this beforehand
Item.Data.Seek(0, soFromBeginning);
LoadFromStream(Item.Data);
end;
procedure TXMPPacket.SaveToFile(const FileName: string);
var
Stream: TFileStream;
begin
Stream := TFileStream.Create(FileName, fmCreate);
try
SaveToStream(Stream);
finally
Stream.Free;
end;
end;
procedure TXMPPacket.SaveToGraphic(const FileName: string);
begin
DoSaveToGraphic(FileName, GetGraphicSaveMethod);
end;
procedure TXMPPacket.SaveToGraphic(const Stream: TStream);
begin
DoSaveToGraphic(Stream, GetGraphicSaveMethod);
end;
procedure TXMPPacket.SaveToGraphic(const Graphic: IStreamPersist);
begin
DoSaveToGraphic(Graphic, GetGraphicSaveMethod);
end;
procedure TXMPPacket.SaveToStream(Stream: TStream);
procedure WriteProps(Schema: TXMPSchema; Level: Integer;
const Props: IXMPPropertyCollection);
const
PropNodeStart: UnicodeString = #9#9#9'%s<%s:%s>'#10;
PropNodeEnd: UnicodeString = #9#9#9'%s</%s:%s>'#10;
SimpleFmt: UnicodeString = #9#9#9'%s<%s>%s</%1s>'#10;
var
Indent, QualName, NSDecl, RDFName, Value: UnicodeString;
Prop: TXMPProperty;
IsArrayElem: Boolean;
begin
Indent := StringOfChar(WideChar(#9), Level);
for Prop in Props do
begin
IsArrayElem := (Prop.ParentProperty <> nil) and (Prop.ParentProperty.Kind <> xpStructure);
if IsArrayElem or Prop.ParentNamespace then
NSDecl := '' //inherit from parent
else
NSDecl := UnicodeFormat(' xmlns:%s="%s"', [Prop.NamespaceInfo.Prefix,
Prop.NamespaceInfo.URI]);
QualName := Prop.NamespaceInfo.Prefix + ':' + Prop.Name;
if IsArrayElem then
begin
if Prop.ParentProperty.Kind = xpAltArray then
Value := UnicodeFormat(' xml:lang="%s"', [Prop.Name])
else
Value := '';
Stream.WriteUTF8Chars('%s<%s%s>', [Indent, RDF.ListNodeName, Value]);
end;
if Prop.Kind = xpSimple then
begin
Value := EscapeXML(Prop.ReadValue);
if IsArrayElem then
Stream.WriteUTF8Chars('%s</%s>'#10, [Value, RDF.ListNodeName])
else
Stream.WriteUTF8Chars('%s<%s%s>%s</%1:s>'#10, [Indent, QualName, NSDecl, Value]);
Continue;
end;
if IsArrayElem then
Stream.WriteByte(#10)
else
Stream.WriteUTF8Chars('%s<%s%s>'#10, [Indent, QualName, NSDecl]);
case Prop.Kind of
xpStructure: RDFName := RDF.DescriptionNodeName;
xpAltArray: RDFName := RDF.AltNodeName;
xpBagArray: RDFName := RDF.BagNodeName;
xpSeqArray: RDFName := RDF.SeqNodeName;
else Assert(False);
end;
Stream.WriteUTF8Chars('%s'#9'<%s>'#10, [Indent, RDFName]);
WriteProps(Schema, Level + 2, Prop);
Stream.WriteUTF8Chars('%s'#9'</%s>'#10, [Indent, RDFName]);
if IsArrayElem then
Stream.WriteUTF8Chars('%s</%s>'#10, [Indent, RDF.ListNodeName])
else
Stream.WriteUTF8Chars('%s</%s>'#10, [Indent, QualName]);
end;
end;
const
PacketStart: UTF8String =
'<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>'#10 +
'<x:xmpmeta xmlns:x="adobe:ns:meta/" CCRExifVersion="' + CCRExifVersion + '">'#10 +
#9'<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">'#10;
PacketEnd: UTF8String =
#9'</rdf:RDF>'#10 +
'</x:xmpmeta>'#10 +
'<?xpacket end="w"?> '; //The packet wrapper (i.e., the <?xpacket lines) are optional according to the XMP spec,
PaddingByte: AnsiChar = ' '; //but required by Windows Explorer in Vista. Vista also needs a trailing space character,
DescNodeStart: UnicodeString = //else it doesn't read and raises a spurious error when the user tries to write.
#9#9'<rdf:Description rdf:about="%s" xmlns:%s="%s">'#10;
DescNodeEnd: UTF8String =
#9#9'</rdf:Description>'#10;
var
DataPtr: PAnsiChar;
DataSize: Integer;
Schema: TXMPSchema;
begin
if FRawXMLCache <> '' then
begin
Stream.WriteUTF8Chars(FRawXMLCache);
if FRawXMLCache[Length(FRawXMLCache)] <> ' ' then
Stream.WriteBuffer(PaddingByte, 1); //see note above
Exit;
end;
if FDataToLazyLoad <> nil then
begin
DataPtr := FDataToLazyLoad.Data.Memory;
DataSize := FDataToLazyLoad.Data.Size;
if (DataSize >= SizeOf(TJPEGSegment.XMPHeader)) and
CompareMem(DataPtr, @TJPEGSegment.XMPHeader, SizeOf(TJPEGSegment.XMPHeader)) then
begin
Inc(DataPtr, SizeOf(TJPEGSegment.XMPHeader));
Dec(DataSize, SizeOf(TJPEGSegment.XMPHeader));
end;
Stream.WriteBuffer(DataPtr^, DataSize);
Exit;
end;
Stream.WriteUTF8Chars(PacketStart);
for Schema in Self do
begin
Stream.WriteUTF8Chars(DescNodeStart, [AboutAttributeValue,
Schema.NamespaceInfo.Prefix, Schema.NamespaceInfo.URI]);
WriteProps(Schema, 3, Schema);
Stream.WriteUTF8Chars(DescNodeEnd);
end;
Stream.WriteUTF8Chars(PacketEnd);
end;
procedure TXMPPacket.SetDataToLazyLoad(const Value: IMetadataBlock);
begin
if Value = FDataToLazyLoad then Exit;
Clear;
FDataToLazyLoad := Value;
end;
procedure TXMPPacket.SetRawXML(const XML: UTF8String);
var
Stream: TUserMemoryStream;
begin
if XML = '' then
Clear
else
begin
Stream := TUserMemoryStream.Create(Pointer(XML), Length(XML));
try
LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
end;
function TXMPPacket.TryLoadFromStream(Stream: TStream): Boolean;
var
I: Integer;
CharsPtr: PAnsiChar;
Document: IDOMDocument;
NewStream: TMemoryStream;
PropNode, RootRDFNode, SchemaNode: IDOMNode;
URI: UnicodeString;
begin
Result := False;
Stream.TryReadHeader(TJPEGSegment.XMPHeader, SizeOf(TJPEGSegment.XMPHeader)); //doesn't matter whether it was there or not
Document := GetDOM.createDocument('', '', nil);
NewStream := TMemoryStream.Create;
try
NewStream.SetSize(Stream.Size - Stream.Position);
Stream.ReadBuffer(NewStream.Memory^, NewStream.Size);
CharsPtr := NewStream.Memory;
for I := NewStream.Size - 1 downto 0 do //MSXML chokes on embedded nulls
if CharsPtr[I] = #0 then CharsPtr[I] := ' ';
if not (Document as IDOMPersist).loadFromStream(NewStream) then Exit;
if not FindRootRDFNode(Document, RootRDFNode) then Exit;
Clear(True);
if StrLComp(CharsPtr, PAnsiChar('<?xpacket '), 10) = 0 then
SetString(FRawXMLCache, CharsPtr, NewStream.Size)
else
FRawXMLCache := UTF8Encode((Document as IDOMPersist).xml)
finally
NewStream.Free;
end;
SchemaNode := RootRDFNode.firstChild;
while SchemaNode <> nil do
begin
if (SchemaNode.nodeType = ELEMENT_NODE) and (SchemaNode.namespaceURI = RDF.URI) and
UnicodeSameText(SchemaNode.nodeName, RDF.DescriptionNodeName) then
begin
if FAboutAttributeValue = '' then
with SchemaNode as IDOMElement do
begin
FAboutAttributeValue := getAttributeNS(RDF.URI, RDF.AboutAttrLocalName);
if FAboutAttributeValue = '' then
FAboutAttributeValue := getAttribute(RDF.AboutAttrLocalName);
end;
//look for tags stored as attributes
for I := 0 to SchemaNode.attributes.length - 1 do
begin
PropNode := SchemaNode.attributes.item[I];
if DefinesNS(PropNode) then Continue;
URI := PropNode.namespaceURI;
if (URI <> '') and (URI <> RDF.URI) then
Schemas[URI].LoadProperty(PropNode);
end;
//look for tags stored as element nodes
PropNode := SchemaNode.firstChild;
while PropNode <> nil do
begin
URI := PropNode.namespaceURI;
if (URI <> '') and (PropNode.nodeType = ELEMENT_NODE) then
Schemas[URI].LoadProperty(PropNode);
PropNode := PropNode.nextSibling;
end;
end;
SchemaNode := SchemaNode.nextSibling;
end;
Changed(False);
Result := True;
end;
procedure TXMPPacket.RemoveProperty(SchemaKind: TXMPKnownNamespace;
const PropName: UnicodeString);
var
Schema: TXMPSchema;
begin
if FindSchema(SchemaKind, Schema) then Schema.RemoveProperty(PropName);
end;
procedure TXMPPacket.RemoveProperties(SchemaKind: TXMPKnownNamespace;
const PropNames: array of UnicodeString);
var
Schema: TXMPSchema;
begin
if FindSchema(SchemaKind, Schema) then Schema.RemoveProperties(PropNames);
end;
procedure TXMPPacket.DoUpdateProperty(Policy: TXMPWritePolicy; SchemaKind: TXMPKnownNamespace;
const PropName: UnicodeString; PropKind: TXMPPropertyKind; const NewValue: UnicodeString);
var
Prop: TXMPProperty;
Schema: TXMPSchema;
begin
if (Policy = xwRemove) or (NewValue = '') then
begin
RemoveProperty(SchemaKind, PropName);
Exit;
end;
if Policy = xwAlwaysUpdate then
Schema := FindOrAddSchema(SchemaKind)
else
if not FindSchema(SchemaKind, Schema) then Exit;
if not Schema.FindProperty(PropName, Prop) then
if Policy = xwAlwaysUpdate then
Prop := Schema.AddProperty(PropName)
else
Exit;
Prop.Kind := PropKind;
Prop.WriteValue(TrimRight(NewValue));
end;
procedure TXMPPacket.DoUpdateArrayProperty(SchemaKind: TXMPKnownNamespace;
const PropName: UnicodeString; ArrayPropKind: TXMPPropertyKind;
const NewValues: array of UnicodeString);
var
I, NewSubPropCount: Integer;
Prop: TXMPProperty;
Schema: TXMPSchema;
begin
NewSubPropCount := Length(NewValues);
if (UpdatePolicy = xwRemove) or (NewSubPropCount = 0) then
begin
RemoveProperty(SchemaKind, PropName);
Exit;
end;
if UpdatePolicy = xwAlwaysUpdate then
Schema := FindOrAddSchema(SchemaKind)
else
if not FindSchema(SchemaKind, Schema) then Exit;
if not Schema.FindProperty(PropName, Prop) then
if UpdatePolicy = xwAlwaysUpdate then
Prop := Schema.AddProperty(PropName)
else
Exit;
if not (Prop.Kind in [xpSimple, xpBagArray, xpSeqArray]) then
begin
RemoveProperty(SchemaKind, PropName);
Prop := Schema.AddProperty(PropName);
end;
Prop.Kind := ArrayPropKind;
Prop.SubPropertyCount := NewSubPropCount;
for I := 0 to NewSubPropCount - 1 do
Prop[I].WriteValue(NewValues[I]);
end;
procedure TXMPPacket.UpdateProperty(SchemaKind: TXMPKnownNamespace;
const PropName: UnicodeString; PropKind: TXMPPropertyKind; const NewValue: UnicodeString);
var
SubPolicy: TXMPWritePolicy;
begin
DoUpdateProperty(UpdatePolicy, SchemaKind, PropName, PropKind, NewValue);
if (SchemaKind <> xsTIFF) or (PropKind <> xpSimple) or
(PropName[1] <> UpCase(PropName[1])) then Exit;
{ Special handling for the TIFF schema - basically, the spec has its properties all
with an initial capital, but Vista (perhaps for bkwards compat reasons) can write
to both this *and* an all lowercase version. }
SubPolicy := UpdatePolicy;
if SubPolicy = xwAlwaysUpdate then SubPolicy := xwUpdateIfExists;
DoUpdateProperty(SubPolicy, SchemaKind, LowerCase(PropName), PropKind, NewValue);
end;
procedure TXMPPacket.UpdateBagProperty(SchemaKind: TXMPKnownNamespace;
const PropName: UnicodeString; const NewValues: array of UnicodeString);
begin
DoUpdateArrayProperty(SchemaKind, PropName, xpBagArray, NewValues);
end;
procedure TXMPPacket.UpdateBagProperty(SchemaKind: TXMPKnownNamespace;
const PropName: UnicodeString; const NewValueList: UnicodeString);
begin
UpdateProperty(SchemaKind, PropName, xpBagArray, NewValueList);
end;
procedure TXMPPacket.UpdateSeqProperty(SchemaKind: TXMPKnownNamespace;
const PropName: UnicodeString; const NewValues: array of UnicodeString);
begin
DoUpdateArrayProperty(SchemaKind, PropName, xpSeqArray, NewValues);
end;
procedure TXMPPacket.UpdateSeqProperty(SchemaKind: TXMPKnownNamespace;
const PropName: UnicodeString; const NewValueList: UnicodeString);
begin
UpdateProperty(SchemaKind, PropName, xpSeqArray, NewValueList);
end;
procedure TXMPPacket.UpdateProperty(SchemaKind: TXMPKnownNamespace;
const PropName, NewValue: UnicodeString);
begin
UpdateProperty(SchemaKind, PropName, xpSimple, NewValue);
end;
procedure TXMPPacket.UpdateProperty(SchemaKind: TXMPKnownNamespace;
const PropName: UnicodeString; const NewValue: Integer);
begin
UpdateProperty(SchemaKind, PropName, xpSimple, IntToStr(NewValue));
end;
procedure TXMPPacket.UpdateDateTimeProperty(SchemaKind: TXMPKnownNamespace;
const PropName: UnicodeString; const NewValue: TDateTimeTagValue;
ApplyLocalBias: Boolean);
var
S: UnicodeString;
begin
if NewValue.MissingOrInvalid then
RemoveProperty(SchemaKind, PropName)
else
begin
S := DateTimeToXMPString(NewValue, ApplyLocalBias);
UpdateProperty(SchemaKind, PropName, xpSimple, S);
end;
end;
{ TXMPPacket.TEnumerator }
constructor TXMPPacket.TEnumerator.Create(Packet: TXMPPacket);
begin
FPacket := Packet;
FIndex := -1;
end;
function TXMPPacket.TEnumerator.GetCurrent: TXMPSchema;
begin
Result := FPacket[FIndex];
end;
function TXMPPacket.TEnumerator.MoveNext: Boolean;
begin
Inc(FIndex);
Result := (FIndex < FPacket.SchemaCount);
end;
initialization
{$IFDEF MSWINDOWS}
if IsConsole and Assigned(InitProc) then
begin //TXMPPacket implicitly uses MSXML, which requires CoInitialize
TProcedure(InitProc); //or CoInitializeEx to be called. This will be done
InitProc := nil; //automatically with a VCL app (the RTL's MSXML wrapper uses
end; //ComObj.pas, which assigns InitProc, which is called by
{$ENDIF} //Application.Initialize), but not in a console one.
finalization
TKnownXMPNamespaces.FKnownURIs.Free;
end.
|
unit URegraCRUDStatus;
interface
uses
URegraCRUD
,URepositorioDB
,URepositorioStatus
,UEntidade
,UStatus
;
type
TRegraCrudStatus = class (TRegraCRUD)
protected
procedure ValidaInsercao (const coENTIDADE: TENTIDADE); override;
public
constructor Create; override;
end;
implementation
{ TRegraCrudStatus }
uses
SysUtils
,UUtilitarios
,UMensagens
,UConstantes
;
constructor TRegraCrudStatus.Create;
begin
inherited;
FRepositorioDB := TRepositorioDB<TENTIDADE>(TRepositorioStatus.Create);
end;
procedure TRegraCrudStatus.ValidaInsercao(const coENTIDADE: TENTIDADE);
begin
inherited;
if Trim (TSTATUS(coENTIDADE).NOME) = EmptyStr then
raise EValidacaoNegocio.Create(STR_STATUS_NOME_NAO_INFORMADO);
end;
end.
|
namespace CirrusTraceAspectLibrary;
interface
uses
RemObjects.Elements.Cirrus;
type
// This attribute will be transformed into RemObjects Cirrus Aspect later.
// Note how RemObjects.Elements.Cirrus.IMethodDefinition interface is implemented
// Also note how WriteLine method declaration is marked. This method will be injected into target class of aspect
// Aspects should be declared in separate library so Cirrus framework will be able to apply them to target classes
// In most cases nor this library assembly containing Aspects nor RemObjects.Elements.Cirrus assembly aren't needed to
// run resulting application
[AttributeUsage(AttributeTargets.Class)]
TraceAttribute = public class(Attribute, RemObjects.Elements.Cirrus.IMethodImplementationDecorator)
public
[Aspect:RemObjects.Elements.Cirrus.AutoInjectIntoTarget]
method WriteLine(aEnter: Boolean; aName: String; Args: Array of Object);
method HandleImplementation(Services: RemObjects.Elements.Cirrus.IServices; aMethod: RemObjects.Elements.Cirrus.IMethodDefinition);
end;
implementation
method TraceAttribute.HandleImplementation(Services: RemObjects.Elements.Cirrus.IServices; aMethod: RemObjects.Elements.Cirrus.IMethodDefinition);
begin
// This check is needed to prefent endless recursion when method WriteLine is called
if (String.Equals(aMethod.Name, 'WriteLine', StringComparison.OrdinalIgnoreCase)) then
exit;
// This call modifies method implementation in target class by injecting there some code
// Note that typeOf(self) there will return type of target class, not type of TraceAttribute
// try .. finally statement is used to make sure that WriteLine method will be called after original method call, even if
// this method contain exit() statements
aMethod.SetBody(Services,
method begin
try
WriteLine(true, String.Format('{0}.{1}', typeOf(self), Aspects.MethodName), Aspects.GetParameters);
Aspects.OriginalBody;
finally
WriteLine(false, Aspects.MethodName, nil);
end;
end);
end;
// This method will be inserted into aspect target class
method TraceAttribute.WriteLine(aEnter: Boolean; aName: String; Args: Array of object);
begin
var lMessage: String := 'Trace: ' + iif(aEnter, 'Entering ', 'Exiting ') + aName;
if (aEnter and (assigned(Args))) then begin
lMessage := lMessage + ' with arguments';
for I: Int32 := 0 to length(Args)-1 do
lMessage := lMessage + String.Format(' {0}', Args[I]);
end;
Console.WriteLine(lMessage);
end;
end. |
namespace VirtualProperties.VirtualPropertiesClasses;
interface
uses
System.Windows.Forms;
type
{ This class is abstract and only serves as a base for descendants.
Notice how clean the Oxygene syntax is, compared to classic object pascal,
where you'd need to declare two virtual abstract methods to set and get Name. }
BaseClass = abstract class
public
property Name: String read write; abstract;
end;
{ Provides an implementation for the Name getter and setter by using a field. }
FirstDescendant = class(BaseClass)
private
fName: String;
public
property Name: String read fName write fName; override;
end;
{ This interface has the same syntax that saved us from the redundant code in
the declaration of BaseClass as it works on interfaces as well.
Interface methods are implicitly virtual abstract. }
IHasName = interface
property Name: String read write;
end;
{ Overrides the implementation of the getter and setter provided by FirstDescendant by
introducing two methods to do the job. }
SecondDescendant = class(FirstDescendant, IHasName)
private
method SetName(Value: String);
method GetName: String;
public
property Name: String read GetName write SetName; override;
end;
implementation
{ SecondDescendant }
method SecondDescendant.SetName(Value : string);
begin
MessageBox.Show('Setting Name to '+Value);
inherited Name := Value;
end;
method SecondDescendant.GetName: string;
begin
result := inherited Name;
end;
end. |
unit HandlebarsParser;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, contnrs, HandlebarsScanner, DataContext;
type
THandlebarsHash = class;
THandlebarsProgram = class;
THandlebarsStatement = class;
TStripFlag = (sfOpen, sfClose);
TStripFlags = set of TStripFlag;
TStringArray = array of String;
{ THandlebarsNode }
THandlebarsNode = class
protected
function GetNodeType: String;
public
function GetText({%H-}Context: TDataContext): String; virtual;
property NodeType: String read GetNodeType;
end;
THandlebarsExpression = class(THandlebarsNode)
private
end;
{ THandlebarsPathExpression }
THandlebarsPathExpression = class(THandlebarsExpression)
private
FOriginal: String;
FParts: TStringArray;
FDepth: Integer;
FData: Boolean;
public
property Data: Boolean read FData;
property Depth: Integer read FDepth;
property Original: String read FOriginal;
property Parts: TStringArray read FParts;
end;
{ THandlebarsSubExpression }
THandlebarsSubExpression = class(THandlebarsExpression)
private
FPath: THandlebarsPathExpression;
FParams: TFPObjectList; //[ Expression ];
FHash: THandlebarsHash;
function GetParamCount: Integer;
function GetParams(Index: Integer): THandlebarsExpression;
public
destructor Destroy; override;
property Hash: THandlebarsHash read FHash;
property Params[Index: Integer]: THandlebarsExpression read GetParams;
property ParamCount: Integer read GetParamCount;
property Path: THandlebarsPathExpression read FPath;
end;
{ THandlebarsLiteral }
THandlebarsLiteral = class(THandlebarsExpression)
private
function GetAsString: String; virtual; abstract;
public
property AsString: String read GetAsString;
end;
{ THandlebarsStringLiteral }
THandlebarsStringLiteral = class(THandlebarsLiteral)
private
FValue: String;
FOriginal: String;
function GetAsString: String; override;
public
constructor Create(const AValue: String);
property Value: String read FValue;
property Original: String read FOriginal;
end;
{ THandlebarsBooleanLiteral }
THandlebarsBooleanLiteral = class(THandlebarsLiteral)
private
FValue: Boolean;
FOriginal: Boolean;
function GetAsString: String; override;
public
constructor Create(const AValue: String);
property Original: Boolean read FOriginal;
property Value: Boolean read FValue;
end;
{ THandlebarsNumberLiteral }
THandlebarsNumberLiteral = class(THandlebarsLiteral)
private
FValue: Double;
FOriginal: Double;
function GetAsString: String; override;
public
constructor Create(const ValueStr: String);
property Original: Double read FOriginal;
property Value: Double read FValue;
end;
{ THandlebarsNullLiteral }
THandlebarsNullLiteral = class(THandlebarsLiteral)
private
function GetAsString: String; override;
end;
{ THandlebarsUndefinedLiteral }
THandlebarsUndefinedLiteral = class(THandlebarsLiteral)
private
function GetAsString: String; override;
end;
THandlebarsStatement = class(THandlebarsNode)
end;
{ THandlebarsMustacheStatement }
THandlebarsMustacheStatement = class(THandlebarsStatement)
private
FPath: THandlebarsExpression; //PathExpression | Literal
FParams: TFPObjectList; //[Expression]
FHash: THandlebarsHash;
FStrip: TStripFlags;
FScaped: Boolean;
function GetParamCount: Integer;
function GetParams(Index: Integer): THandlebarsExpression;
public
constructor Create;
destructor Destroy; override;
function GetText(Context: TDataContext): String; override;
property Hash: THandlebarsHash read FHash;
property Params[Index: Integer]: THandlebarsExpression read GetParams;
property ParamCount: Integer read GetParamCount;
property Path: THandlebarsExpression read FPath;
end;
{ THandlebarsBlockStatement }
THandlebarsBlockStatement = class(THandlebarsStatement)
private
FPath: THandlebarsExpression; //PathExpression | Literal
FParams: TFPObjectList; //[ Expression ];
FHash: THandlebarsHash;
FProgram: THandlebarsProgram;
FInverse: THandlebarsProgram;
FOpenStrip: TStripFlags;
FInverseStrip: TStripFlags;
FCloseStrip: TStripFlags;
function GetParamCount: Integer;
function GetParams(Index: Integer): THandlebarsExpression;
public
constructor Create;
destructor Destroy; override;
property Hash: THandlebarsHash read FHash;
property Inverse: THandlebarsProgram read FInverse;
property Params[Index: Integer]: THandlebarsExpression read GetParams;
property ParamCount: Integer read GetParamCount;
property Path: THandlebarsExpression read FPath;
property TheProgram: THandlebarsProgram read FProgram;
end;
{ THandlebarsPartialStatement }
THandlebarsPartialStatement = class(THandlebarsStatement)
private
FName: THandlebarsExpression; //PathExpression | SubExpression
FParams: TFPObjectList; // [ Expression ]
FHash: THandlebarsHash;
FIndent: String;
FStrip: TStripFlags;
function GetParamCount: Integer;
function GetParams(Index: Integer): THandlebarsExpression;
public
constructor Create;
destructor Destroy; override;
property Indent: String read FIndent;
property Hash: THandlebarsHash read FHash;
property Name: THandlebarsExpression read FName;
property Params[Index: Integer]: THandlebarsExpression read GetParams;
property ParamCount: Integer read GetParamCount;
end;
{ THandlebarsPartialBlockStatement }
THandlebarsPartialBlockStatement = class(THandlebarsStatement)
private
FName: THandlebarsExpression; //PathExpression | SubExpression
FParams: TFPObjectList; // [ Expression ]
FHash: THandlebarsHash;
FProgram: THandlebarsProgram;
FIndent: String;
FOpenStrip: TStripFlags;
FCloseStrip: TStripFlags;
function GetParamCount: Integer;
function GetParams(Index: Integer): THandlebarsExpression;
public
constructor Create;
destructor Destroy; override;
property Indent: String read FIndent;
property Hash: THandlebarsHash read FHash;
property Name: THandlebarsExpression read FName;
property Params[Index: Integer]: THandlebarsExpression read GetParams;
property ParamCount: Integer read GetParamCount;
property TheProgram: THandlebarsProgram read FProgram;
end;
{ THandlebarsContentStatement }
THandlebarsContentStatement = class(THandlebarsStatement)
private
FValue: String;
FOriginal: String;
public
function GetText({%h-}Context: TDataContext): String; override;
constructor Create(const Value: String);
property Value: String read FValue;
end;
{ THandlebarsCommentStatement }
THandlebarsCommentStatement = class(THandlebarsStatement)
private
FValue: String;
FStrip: TStripFlags;
public
property Value: String read FValue;
end;
{ THandlebarsDecorator }
THandlebarsDecorator = class(THandlebarsMustacheStatement)
private
public
end;
{ THandlebarsDecoratorBlock }
THandlebarsDecoratorBlock = class(THandlebarsBlockStatement)
private
public
end;
{ THandlebarsHashPair }
THandlebarsHashPair = class(THandlebarsNode)
private
FKey: String;
FValue: THandlebarsExpression;
public
constructor Create(const AKey: String; AValue: THandlebarsExpression);
destructor Destroy; override;
property Key: String read FKey;
property Value: THandlebarsExpression read FValue;
end;
{ THandlebarsHash }
THandlebarsHash = class(THandlebarsNode)
private
FPairs: TFPObjectList; //[ HashPair ]
function GetPairCount: Integer;
function GetPairs(Index: Integer): THandlebarsHashPair;
public
constructor Create;
destructor Destroy; override;
function AddPair(Pair: THandlebarsHashPair): THandlebarsHashPair;
property PairCount: Integer read GetPairCount;
property Pairs[Index: Integer]: THandlebarsHashPair read GetPairs;
end;
{ THandlebarsProgram }
THandlebarsProgram = class(THandlebarsNode)
private
FBody: TFPObjectList; //[ Statement ]
FBlockParams: TStringArray;
function GetBody(Index: Integer): THandlebarsStatement;
function GetBodyCount: Integer;
public
constructor Create;
destructor Destroy; override;
function GetText(Context: TDataContext): String; override;
property BlockParams: TStringArray read FBlockParams;
property Body[Index: Integer]: THandlebarsStatement read GetBody;
property BodyCount: Integer read GetBodyCount;
end;
EHandlebarsParse = class(Exception);
{ THandlebarsParser }
THandlebarsParser = class
private
FScanner: THandlebarsScanner;
function ParseBlock(ExpectsClose: Boolean = True; Inverted: Boolean = False): THandlebarsBlockStatement;
function ParseBlockParams: TStringArray;
procedure ParseCloseBlock(const OpenName: String);
function ParseComment: THandlebarsCommentStatement;
function ParseExpression(AllowSubExpression: Boolean): THandlebarsExpression;
function ParseMustache: THandlebarsMustacheStatement;
procedure ParseParamsAndHash(Params: TFPObjectList; out Hash: THandlebarsHash);
function ParsePartial: THandlebarsPartialStatement;
function ParsePartialBlock: THandlebarsPartialBlockStatement;
function ParsePath(IsData: Boolean): THandlebarsPathExpression;
function ParseProgram(BreakTokens: THandlebarsTokens; DoFetchToken: Boolean = True): THandlebarsProgram;
function ParseStatement: THandlebarsStatement;
procedure UnexpectedToken(Expected: THandlebarsTokens);
public
constructor Create(Source : TStream); overload;
constructor Create(const Source : String); overload;
destructor Destroy; override;
function Parse: THandlebarsProgram;
end;
implementation
uses
Variants;
{ THandlebarsUndefinedLiteral }
function THandlebarsUndefinedLiteral.GetAsString: String;
begin
Result := 'undefined';
end;
{ THandlebarsNullLiteral }
function THandlebarsNullLiteral.GetAsString: String;
begin
Result := 'null';
end;
{ THandlebarsHashPair }
constructor THandlebarsHashPair.Create(const AKey: String; AValue: THandlebarsExpression);
begin
FKey := AKey;
FValue := AValue;
end;
destructor THandlebarsHashPair.Destroy;
begin
FValue.Free;
inherited Destroy;
end;
{ THandlebarsBooleanLiteral }
function THandlebarsBooleanLiteral.GetAsString: String;
begin
Result := LowerCase(BoolToStr(FValue, True));
end;
constructor THandlebarsBooleanLiteral.Create(const AValue: String);
begin
FValue := AValue = 'true';
FOriginal := FValue;
end;
{ THandlebarsStringLiteral }
function THandlebarsStringLiteral.GetAsString: String;
begin
Result := FValue;
end;
constructor THandlebarsStringLiteral.Create(const AValue: String);
begin
FValue := AValue;
FOriginal := AValue;
end;
{ THandlebarsNumberLiteral }
function THandlebarsNumberLiteral.GetAsString: String;
begin
Result := FloatToStr(FValue);
end;
constructor THandlebarsNumberLiteral.Create(const ValueStr: String);
begin
FValue := StrToFloat(ValueStr);
FOriginal := FValue;
end;
{ THandlebarsContentStatement }
function THandlebarsContentStatement.GetText({%h-}Context: TDataContext): String;
begin
Result := FValue;
end;
constructor THandlebarsContentStatement.Create(const Value: String);
begin
FValue := Value;
FOriginal := Value;
end;
{ THandlebarsParser }
destructor THandlebarsParser.Destroy;
begin
FScanner.Destroy;
end;
{
block
: openBlock program inverseChain? closeBlock
| openInverse program inverseAndProgram? closeBlock
;
openBlock
: OPEN_BLOCK helperName param* hash? blockParams? CLOSE
;
openInverse
: OPEN_INVERSE helperName param* hash? blockParams? CLOSE
;
openInverseChain
: OPEN_INVERSE_CHAIN helperName param* hash? blockParams? CLOSE
;
inverseAndProgram
: INVERSE program
;
}
function THandlebarsParser.ParseBlock(ExpectsClose: Boolean; Inverted: Boolean): THandlebarsBlockStatement;
var
OpenName: String;
BlockParams: TStringArray;
TheProgram, InverseProgram: THandlebarsProgram;
IsDecorator: Boolean;
begin
IsDecorator := Pos('*', FScanner.CurTokenString) > 0;
if IsDecorator then
Result := THandlebarsDecoratorBlock.Create
else
Result := THandlebarsBlockStatement.Create;
TheProgram := nil;
InverseProgram := nil;
BlockParams := nil;
FScanner.FetchToken;
Result.FPath := ParseExpression(False);
if FScanner.CurToken = tkOpenBlockParams then
BlockParams := ParseBlockParams;
ParseParamsAndHash(Result.FParams, Result.FHash);
if FScanner.CurToken = tkOpenBlockParams then
BlockParams := ParseBlockParams;
case Result.FPath.NodeType of
'PathExpression':
OpenName := THandlebarsPathExpression(Result.FPath).Original;
'StringLiteral':
OpenName := THandlebarsStringLiteral(Result.FPath).Original;
'NumberLiteral':
OpenName := FloatToStr(THandlebarsNumberLiteral(Result.FPath).Original);
'BooleanLiteral':
OpenName := LowerCase(BoolToStr(THandlebarsBooleanLiteral(Result.FPath).Original, True));
end;
TheProgram := ParseProgram([tkOpenEndBlock, tkInverse, tkOpenInverseChain]);
TheProgram.FBlockParams := BlockParams;
if FScanner.CurToken in [tkInverse, tkOpenInverseChain] then
begin
if IsDecorator then
raise EHandlebarsParse.Create('Unexpected inverse');
InverseProgram := ParseProgram([tkOpenEndBlock], FScanner.CurToken <> tkOpenInverseChain);
end;
if not Inverted then
begin
Result.FProgram := TheProgram;
Result.FInverse := InverseProgram;
end
else
begin
Result.FInverse := TheProgram;
Result.FProgram := InverseProgram;
end;
if ExpectsClose then
ParseCloseBlock(OpenName);
end;
function THandlebarsParser.ParseBlockParams: TStringArray;
var
ItemCount: Integer;
begin
Result := nil;
FScanner.FetchToken;
while FScanner.CurToken = tkId do
begin
ItemCount := Length(Result);
SetLength(Result, ItemCount + 1);
Result[ItemCount] := FScanner.CurTokenString;
FScanner.FetchToken;
end;
if FScanner.CurToken <> tkCloseBlockParams then
UnexpectedToken([tkCloseBlockParams]);
FScanner.FetchToken;
end;
{
closeBlock
: OPEN_ENDBLOCK helperName CLOSE
;
}
procedure THandlebarsParser.ParseCloseBlock(const OpenName: String);
var
Expression: THandlebarsExpression;
CloseName: String;
begin
FScanner.FetchToken;
Expression := ParseExpression(True);
case Expression.NodeType of
'PathExpression':
CloseName := THandlebarsPathExpression(Expression).Original;
'StringLiteral':
CloseName := THandlebarsStringLiteral(Expression).Original;
'NumberLiteral':
CloseName := FloatToStr(THandlebarsNumberLiteral(Expression).Original);
'BooleanLiteral':
CloseName := LowerCase(BoolToStr(THandlebarsBooleanLiteral(Expression).Original, True));
else
CloseName := '';
end;
Expression.Free;
if CloseName <> OpenName then
raise EHandlebarsParse.CreateFmt('%s doesn''t match %s', [OpenName, CloseName]);
if FScanner.CurToken <> tkClose then
UnexpectedToken([tkClose]);
end;
function THandlebarsParser.ParseComment: THandlebarsCommentStatement;
var
Str: String;
begin
Result := THandlebarsCommentStatement.Create;
Str := FScanner.CurTokenString;
if Pos('--', Str) = 4 then
Str := Copy(Str, 6, Length(Str) - 9)
else
Str := Copy(Str, 4, Length(Str) - 5);
Result.FValue := Str;
end;
function THandlebarsParser.ParseExpression(AllowSubExpression: Boolean): THandlebarsExpression;
var
T: THandlebarsToken;
begin
T := FScanner.CurToken;
case T of
tkNumber: Result := THandlebarsNumberLiteral.Create(FScanner.CurTokenString);
tkString: Result := THandlebarsStringLiteral.Create(FScanner.CurTokenString);
tkBoolean: Result := THandlebarsBooleanLiteral.Create(FScanner.CurTokenString);
tkNull: Result := THandlebarsNullLiteral.Create;
tkUndefined: Result := THandlebarsUndefinedLiteral.Create;
tkId: Result := ParsePath(False);
tkData:
begin
if FScanner.FetchToken = tkId then
Result := ParsePath(True)
else
UnexpectedToken([tkId]);
end;
tkOpenSExpr:
begin
if not AllowSubExpression then
UnexpectedToken([tkUndefined..tkString, tkId, tkData]);
end
else
UnexpectedToken([tkUndefined..tkString, tkId, tkData, tkOpenSExpr]);
end;
if T in LiteralTokens then
FScanner.FetchToken;
end;
{
mustache
: OPEN helperName param* hash? CLOSE
| OPEN_UNESCAPED helperName param* hash? CLOSE_UNESCAPED;
helperName
: path
| dataName
| STRING
| NUMBER
| BOOLEAN
| UNDEFINED
| NULL
;
dataName
: DATA pathSegments
;
path
: pathSegments
;
pathSegments
: pathSegments SEP ID
| ID
;
}
function THandlebarsParser.ParseMustache: THandlebarsMustacheStatement;
var
IsDecorator: Boolean;
begin
IsDecorator := Pos('*', FScanner.CurTokenString) > 0;
if IsDecorator then
Result := THandlebarsDecorator.Create
else
Result := THandlebarsMustacheStatement.Create;
FScanner.FetchToken;
Result.FPath := ParseExpression(False);
ParseParamsAndHash(Result.FParams, Result.FHash);
end;
procedure THandlebarsParser.ParseParamsAndHash(Params: TFPObjectList; out Hash: THandlebarsHash);
var
PrevTokenString: String;
Expression: THandlebarsExpression;
begin
//params
while FScanner.CurToken <> tkClose do
begin
PrevTokenString := FScanner.CurTokenString;
Expression := ParseExpression(True);
if FScanner.CurToken <> tkEquals then
Params.Add(Expression)
else
begin
//discard previous expression
Expression.Destroy;
Hash := THandlebarsHash.Create;
FScanner.FetchToken;
Expression := ParseExpression(True);
Hash.AddPair(THandlebarsHashPair.Create(PrevTokenString, Expression));
//hash
while FScanner.CurToken = tkId do
begin
PrevTokenString := FScanner.CurTokenString;
if FScanner.FetchToken = tkEquals then
begin
FScanner.FetchToken;
Expression := ParseExpression(True);
Hash.AddPair(THandlebarsHashPair.Create(PrevTokenString, Expression));
end
else
UnexpectedToken([tkEquals]);
end;
end;
end;
end;
{
partial
: OPEN_PARTIAL partialName param* hash? CLOSE;
partialName
: helperName -> $1
| sexpr -> $1
;
}
function THandlebarsParser.ParsePartial: THandlebarsPartialStatement;
begin
Result := THandlebarsPartialStatement.Create;
FScanner.FetchToken;
Result.FName := ParseExpression(True);
ParseParamsAndHash(Result.FParams, Result.FHash);
end;
{
partialBlock
: openPartialBlock program closeBlock -> yy.preparePartialBlock($1, $2, $3, @$)
;
openPartialBlock
: OPEN_PARTIAL_BLOCK partialName param* hash? CLOSE -> { path: $2, params: $3, hash: $4, strip: yy.stripFlags($1, $5) }
;
}
function THandlebarsParser.ParsePartialBlock: THandlebarsPartialBlockStatement;
var
OpenName: String;
begin
Result := THandlebarsPartialBlockStatement.Create;
FScanner.FetchToken;
Result.FName := ParseExpression(True);
ParseParamsAndHash(Result.FParams, Result.FHash);
case Result.FName.NodeType of
'PathExpression':
OpenName := THandlebarsPathExpression(Result.FName).Original;
'StringLiteral':
OpenName := THandlebarsStringLiteral(Result.FName).Original;
'NumberLiteral':
OpenName := FloatToStr(THandlebarsNumberLiteral(Result.FName).Original);
'BooleanLiteral':
OpenName := LowerCase(BoolToStr(THandlebarsBooleanLiteral(Result.FName).Original, True));
end;
Result.FProgram := ParseProgram([tkOpenEndBlock]);
ParseCloseBlock(OpenName);
end;
function THandlebarsParser.ParsePath(IsData: Boolean): THandlebarsPathExpression;
var
PartCount: Integer;
Part: String;
begin
Result := THandlebarsPathExpression.Create;
Result.FData := IsData;
Result.FOriginal := '';
repeat
Part := FScanner.CurTokenString;
case Part of
'this', '.', '..':
begin
if Result.FOriginal <> '' then
raise EHandlebarsParse.CreateFmt('Invalid path: %s%s', [Result.FOriginal, Part]);
if Part = '..' then
Inc(Result.FDepth);
end;
else
begin
PartCount := Length(Result.Parts);
SetLength(Result.FParts, PartCount + 1);
Result.FParts[PartCount] := Part;
end;
end;
Result.FOriginal += Part;
if FScanner.FetchToken = tkSep then
begin
Result.FOriginal += FScanner.CurTokenString;
if FScanner.FetchToken <> tkId then
UnexpectedToken([tkId]);
end
else
Break;
until False;
end;
function THandlebarsParser.ParseProgram(BreakTokens: THandlebarsTokens; DoFetchToken: Boolean): THandlebarsProgram;
var
T: THandlebarsToken;
begin
Result := THandlebarsProgram.Create;
if DoFetchToken then
T := FScanner.FetchToken
else
T := FScanner.CurToken;
while not (T in BreakTokens) do
begin
Result.FBody.Add(ParseStatement);
//todo: make ParseStatement consistent, always let at next token or current token
if T = tkOpenInverseChain then
T := FScanner.CurToken
else
T := FScanner.FetchToken;
end;
end;
function THandlebarsParser.ParseStatement: THandlebarsStatement;
begin
case FScanner.CurToken of
tkContent:
Result := THandlebarsContentStatement.Create(FScanner.CurTokenString);
tkOpen, tkOpenUnescaped:
Result := ParseMustache;
tkOpenPartial:
Result := ParsePartial;
tkOpenPartialBlock:
Result := ParsePartialBlock;
tkComment:
Result := ParseComment;
tkOpenBlock:
Result := ParseBlock;
tkOpenInverseChain:
Result := ParseBlock(False);
tkOpenInverse:
Result := ParseBlock(True, True);
else
UnexpectedToken([tkContent, tkOpen, tkOpenUnescaped, tkOpenPartial, tkOpenPartialBlock,
tkComment, tkOpenInverse, tkOpenInverseChain]);
end;
end;
function TokenSetToStr(Tokens: THandlebarsTokens): String;
var
Token: THandlebarsToken;
TokenStr: String;
begin
Result := '[';
for Token in Tokens do
begin
WriteStr(TokenStr, Token);
Result := Result + TokenStr;
Result := Result + ',';
end;
Result := Result + ']';
end;
procedure THandlebarsParser.UnexpectedToken(Expected: THandlebarsTokens);
var
ActualStr, ExpectedStr: String;
begin
WriteStr(ActualStr, FScanner.CurToken);
ExpectedStr := TokenSetToStr(Expected);
raise EHandlebarsParse.CreateFmt('Got %s expected %s', [ActualStr, ExpectedStr]);
end;
constructor THandlebarsParser.Create(Source: TStream);
begin
FScanner := THandlebarsScanner.Create(Source);
end;
constructor THandlebarsParser.Create(const Source: String);
begin
FScanner := THandlebarsScanner.Create(Source);
end;
function THandlebarsParser.Parse: THandlebarsProgram;
begin
Result := ParseProgram([tkEOF]);
end;
{ THandlebarsHash }
function THandlebarsHash.GetPairCount: Integer;
begin
Result := FPairs.Count;
end;
function THandlebarsHash.GetPairs(Index: Integer): THandlebarsHashPair;
begin
Result := THandlebarsHashPair(FPairs[Index]);
end;
constructor THandlebarsHash.Create;
begin
FPairs := TFPObjectList.Create;
end;
destructor THandlebarsHash.Destroy;
begin
FPairs.Destroy;
inherited Destroy;
end;
function THandlebarsHash.AddPair(Pair: THandlebarsHashPair): THandlebarsHashPair;
begin
Result := Pair;
FPairs.Add(Pair);
end;
{ THandlebarsPartialBlockStatement }
function THandlebarsPartialBlockStatement.GetParamCount: Integer;
begin
Result := FParams.Count;
end;
function THandlebarsPartialBlockStatement.GetParams(Index: Integer): THandlebarsExpression;
begin
Result := THandlebarsExpression(FParams[Index]);
end;
constructor THandlebarsPartialBlockStatement.Create;
begin
FParams := TFPObjectList.Create;
end;
destructor THandlebarsPartialBlockStatement.Destroy;
begin
FName.Free;
FHash.Free;
FParams.Destroy;
inherited Destroy;
end;
{ THandlebarsPartialStatement }
function THandlebarsPartialStatement.GetParamCount: Integer;
begin
Result := FParams.Count;
end;
function THandlebarsPartialStatement.GetParams(Index: Integer): THandlebarsExpression;
begin
Result := THandlebarsExpression(FParams[Index]);
end;
constructor THandlebarsPartialStatement.Create;
begin
//todo: create on demand
FParams := TFPObjectList.Create;
end;
destructor THandlebarsPartialStatement.Destroy;
begin
FName.Free;
FHash.Free;
FParams.Free;
inherited Destroy;
end;
{ THandlebarsBlockStatement }
function THandlebarsBlockStatement.GetParamCount: Integer;
begin
Result := FParams.Count;
end;
function THandlebarsBlockStatement.GetParams(Index: Integer): THandlebarsExpression;
begin
Result := THandlebarsExpression(FParams[Index]);
end;
constructor THandlebarsBlockStatement.Create;
begin
FParams := TFPObjectList.Create;
end;
destructor THandlebarsBlockStatement.Destroy;
begin
FPath.Free;
FHash.Free;
FProgram.Free;
FInverse.Free;
FParams.Free;
inherited Destroy;
end;
{ THandlebarsMustacheStatement }
function THandlebarsMustacheStatement.GetParamCount: Integer;
begin
Result := FParams.Count;
end;
function THandlebarsMustacheStatement.GetParams(Index: Integer): THandlebarsExpression;
begin
Result := THandlebarsExpression(FParams[Index]);
end;
constructor THandlebarsMustacheStatement.Create;
begin
FParams := TFPObjectList.Create;
end;
destructor THandlebarsMustacheStatement.Destroy;
begin
FPath.Free;
FHash.Free;
FParams.Free;
inherited Destroy;
end;
function THandlebarsMustacheStatement.GetText(Context: TDataContext): String;
begin
if FPath is THandlebarsLiteral then
Result := VarToStr(Context.ResolvePath([THandlebarsLiteral(FPath).AsString]))
else
Result := VarToStr(Context.ResolvePath(THandlebarsPathExpression(FPath).FParts));
end;
{ THandlebarsNode }
function THandlebarsNode.GetNodeType: String;
const
PrefixOffset = 12; //THandlebars
var
TheClassName: String;
begin
TheClassName := ClassName;
Result := Copy(TheClassName, PrefixOffset, Length(TheClassName));
end;
function THandlebarsNode.GetText({%H-}Context: TDataContext): String;
begin
Result := '';
end;
{ THandlebarsSubExpression }
function THandlebarsSubExpression.GetParamCount: Integer;
begin
Result := FParams.Count;
end;
function THandlebarsSubExpression.GetParams(Index: Integer): THandlebarsExpression;
begin
Result := THandlebarsExpression(FParams[Index]);
end;
destructor THandlebarsSubExpression.Destroy;
begin
FPath.Free;
FHash.Free;
inherited Destroy;
end;
{ THandlebarsProgram }
function THandlebarsProgram.GetBody(Index: Integer): THandlebarsStatement;
begin
Result := THandlebarsStatement(FBody[Index]);
end;
function THandlebarsProgram.GetBodyCount: Integer;
begin
Result := FBody.Count;
end;
constructor THandlebarsProgram.Create;
begin
FBody := TFPObjectList.Create;
end;
destructor THandlebarsProgram.Destroy;
begin
FBody.Destroy;
inherited Destroy;
end;
function THandlebarsProgram.GetText(Context: TDataContext): String;
var
i: Integer;
begin
Result := '';
for i := 0 to BodyCount - 1 do
Result += Body[i].GetText(Context);
end;
end.
|
unit CmDialogTools;
interface
uses
Dialogs, Windows, Forms, Controls;
function CmMessageDlg(const Msg: string; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons; HelpCtx: Longint): Integer;
procedure CmShowMessage(const Msg: string);
implementation
function CmMessageDlg(const Msg: string; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons; HelpCtx: Longint): Integer;
var
Str: AnsiString;
UType: WORD;
CallMessageBox: Boolean;
MsgRet: integer;
begin
if HelpCtx=0 then
begin
uType := 0; //为了去掉编译警告,本身无用;
case DlgType of
mtWarning: begin
Str := '注意';
uType := MB_ICONWARNING;
end;
mtError: begin
Str := '错误';
uType := MB_ICONERROR;
end;
mtInformation: begin
Str := '提示';
uType := MB_ICONINFORMATION;
end;
mtConfirmation: begin
Str := '确认';
uType := MB_ICONQUESTION;
end;
mtCustom: begin
Str := Application.Title;
end;
end;
CallMessageBox := false;
if Buttons=mbYesNoCancel then
begin
uType := uType+MB_YESNOCANCEL+MB_DEFBUTTON3;
CallMessageBox := true;
end
else if Buttons=mbYesAllNoAllCancel then
begin
CallMessageBox := false;
end
else if Buttons = mbOKCancel then
begin
uType := uType+MB_OKCANCEL+MB_DEFBUTTON2;
CallMessageBox := true;
end
else if Buttons = mbAbortRetryIgnore then
begin
uType := uType+MB_ABORTRETRYIGNORE+MB_DEFBUTTON2;
CallMessageBox := true;
end
else if Buttons = mbAbortIgnore then
begin
uType := uType+MB_ABORTRETRYIGNORE+MB_DEFBUTTON2;
CallMessageBox := true;
end
else if Buttons = [mbOK] then
begin
uType := uType+MB_OK;
CallMessageBox := true;
end
else if Buttons = [mbYes,mbNo] then
begin
uType := uType+MB_YESNO+MB_DEFBUTTON2;
CallMessageBox := true;
end;
if CallMessageBox then
begin
MsgRet := MessageBox(Application.Handle,PAnsiChar(Msg),PAnsiChar(Str),uType);
case MsgRet of
IDABORT: Result := mrAbort;
IDCANCEL: Result := mrCancel;
IDIGNORE: Result := mrIgnore;
IDNO: Result := mrNo;
IDOK: Result := mrOK;
IDRETRY: Result := mrRetry;
IDYES: Result := mrYes;
else
Result := mrNo;
end;
end
else
Result := MessageDlg(Msg,DlgType,Buttons,HelpCtx);
end
else
Result := MessageDlg(Msg,DlgType,Buttons,HelpCtx);
end;
procedure CmShowMessage(const Msg: string);
begin
CmMessageDlg(Msg,mtInformation,[mbOK],0);
end;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2011 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of Delphi, C++Builder or RAD Studio (Embarcadero Products).
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit DmCSDemo;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
DBTables, DB, IBCustomDataSet, IBTable, IBStoredProc, IBDatabase;
type
TDmEmployee = class(TDataModule)
SalesSource: TDataSource;
CustomerSource: TDataSource;
EmployeeSource: TDataSource;
SalaryHistorySource: TDataSource;
EmployeeDatabase: TIBDatabase;
IBTransaction1: TIBTransaction;
ShipOrderProc: TIBStoredProc;
DeleteEmployeeProc: TIBStoredProc;
SalesTable: TIBTable;
CustomerTable: TIBTable;
CustomerTableCUST_NO: TIntegerField;
CustomerTableCUSTOMER: TIBStringField;
CustomerTableCONTACT_FIRST: TIBStringField;
CustomerTableCONTACT_LAST: TIBStringField;
CustomerTablePHONE_NO: TIBStringField;
CustomerTableADDRESS_LINE1: TIBStringField;
CustomerTableADDRESS_LINE2: TIBStringField;
CustomerTableCITY: TIBStringField;
CustomerTableSTATE_PROVINCE: TIBStringField;
CustomerTableCOUNTRY: TIBStringField;
CustomerTablePOSTAL_CODE: TIBStringField;
CustomerTableON_HOLD: TIBStringField;
SalesTablePO_NUMBER: TIBStringField;
SalesTableCUST_NO: TIntegerField;
SalesTableSALES_REP: TSmallintField;
SalesTableORDER_STATUS: TIBStringField;
SalesTableORDER_DATE: TDateTimeField;
SalesTableSHIP_DATE: TDateTimeField;
SalesTableDATE_NEEDED: TDateTimeField;
SalesTablePAID: TIBStringField;
SalesTableQTY_ORDERED: TIntegerField;
SalesTableTOTAL_VALUE: TIBBCDField;
SalesTableDISCOUNT: TFloatField;
SalesTableITEM_TYPE: TIBStringField;
SalesTableAGED: TFloatField;
EmployeeTable: TIBTable;
EmployeeTableEMP_NO: TSmallintField;
EmployeeTableFIRST_NAME: TIBStringField;
EmployeeTableLAST_NAME: TIBStringField;
EmployeeTablePHONE_EXT: TIBStringField;
EmployeeTableHIRE_DATE: TDateTimeField;
EmployeeTableDEPT_NO: TIBStringField;
EmployeeTableJOB_CODE: TIBStringField;
EmployeeTableJOB_GRADE: TSmallintField;
EmployeeTableJOB_COUNTRY: TIBStringField;
EmployeeTableSALARY: TIBBCDField;
EmployeeTableFULL_NAME: TIBStringField;
SalaryHistoryTable: TIBTable;
SalaryHistoryTableEMP_NO: TSmallintField;
SalaryHistoryTableCHANGE_DATE: TDateTimeField;
SalaryHistoryTableUPDATER_ID: TIBStringField;
SalaryHistoryTableOLD_SALARY: TIBBCDField;
SalaryHistoryTablePERCENT_CHANGE: TFloatField;
SalaryHistoryTableNEW_SALARY: TFloatField;
EmployeeLookup: TIBTable;
EmployeeLookupEMP_NO: TSmallintField;
EmployeeLookupFIRST_NAME: TIBStringField;
EmployeeLookupLAST_NAME: TIBStringField;
EmployeeLookupPHONE_EXT: TIBStringField;
EmployeeLookupHIRE_DATE: TDateTimeField;
EmployeeLookupDEPT_NO: TIBStringField;
EmployeeLookupJOB_CODE: TIBStringField;
EmployeeLookupJOB_GRADE: TSmallintField;
EmployeeLookupJOB_COUNTRY: TIBStringField;
EmployeeLookupSALARY: TIBBCDField;
EmployeeLookupFULL_NAME: TIBStringField;
procedure EmployeeTableBeforeDelete(DataSet: TDataSet);
procedure EmployeeTableAfterPost(DataSet: TDataSet);
procedure DmEmployeeCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
DmEmployee: TDmEmployee;
implementation
{$R *.dfm}
{ Note: Business rules go in the data model. Here is an example, used by
the transaction editing demo. Deletes for the employee table are done
with a stored procedure rather than the normal BDE record delete
mechanism, so an audit trail could be provided, etc... }
{ The database, EmployeeDatabase, is the InterBase example EMPLOYEE.GDB database
accessed thru the BDE alias IBLOCAL. This database contains examples
of stored procedures, triggers, check constraints, views, etc., many of
which are used within this demo project. }
procedure TDmEmployee.EmployeeTableBeforeDelete(DataSet: TDataSet);
begin
{ Assign the current employee's id to the stored procedure's parameter }
DeleteEmployeeProc.Params.ParamValues['EMP_NUM'] := EmployeeTable['EMP_NO'];
DeleteEmployeeProc.ExecProc; { Trigger the stored proc }
EmployeeTable.Refresh; { Refresh the data }
{ Block the EmployeeTable delete since the stored procedure did the work }
Abort;
end;
procedure TDmEmployee.EmployeeTableAfterPost(DataSet: TDataSet);
begin
{ A change in an employee salary triggers a change in the salary history,
so if that table is open, it needs to be refreshed now }
with SalaryHistoryTable do if Active then Refresh;
end;
procedure TDmEmployee.DmEmployeeCreate(Sender: TObject);
begin
EmployeeDatabase.Open;
end;
end.
|
unit uExplorerSearchProviders;
interface
uses
System.SysUtils,
System.Classes,
System.StrUtils,
Vcl.Graphics,
Dmitry.Utils.System,
Dmitry.Utils.Files,
Dmitry.Utils.ShellIcons,
Dmitry.PathProviders,
Dmitry.PathProviders.MyComputer,
Dmitry.PathProviders.FileSystem,
Dmitry.PathProviders.Network,
uMemory,
uConstants,
uStringUtils,
uDateUtils,
uColorUtils,
uTranslate;
type
TSearchItem = class(TPathItem)
private
FSearchPath: string;
FSearchTerm: string;
function GetSearchDisplayText: string;
function L(StringToTranslate: string): string;
public
procedure Assign(Item: TPathItem); override;
function LoadImage(Options, ImageSize: Integer): Boolean; override;
constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override;
property SearchPath: string read FSearchPath;
property SearchTerm: string read FSearchTerm;
property SearchDisplayText: string read GetSearchDisplayText;
end;
TDBSearchItem = class(TSearchItem)
protected
function InternalGetParent: TPathItem; override;
function InternalCreateNewInstance: TPathItem; override;
public
constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override;
end;
type
TFileSearchItem = class(TSearchItem)
protected
function InternalGetParent: TPathItem; override;
function InternalCreateNewInstance: TPathItem; override;
public
constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override;
end;
type
TImageSearchItem = class(TFileSearchItem)
protected
function InternalCreateNewInstance: TPathItem; override;
public
constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override;
end;
type
TSearchProvider = class(TPathProvider)
public
function Supports(Item: TPathItem): Boolean; override;
function Supports(Path: string): Boolean; override;
function CreateFromPath(Path: string): TPathItem; override;
end;
type
TDatabaseSortMode = (dsmID, dsmName, dsmRating, dsmDate, dsmFileSize, dsmImageSize, dsmComparing, dsmViewCount);
TDatabaseSortModeHelper = record helper for TDatabaseSortMode
function ToString: string;
class function FromString(S: string): TDatabaseSortMode; static;
end;
TDatabaseSearchParameters = class(TObject)
private
FGroups: TStringList;
FPersons: TStringList;
FColors: TStringList;
FGroupsAnd: Boolean;
FPersonsAnd: Boolean;
procedure Init;
public
DateFrom: TDateTime;
DateTo: TDateTime;
RatingFrom: Byte;
RatingTo: Byte;
SortMode: TDatabaseSortMode;
SortDescending: Boolean;
Text: string;
ShowPrivate: Boolean;
ShowHidden: Boolean;
constructor Create; overload;
constructor Create(AText: string; ADateFrom, ADateTo: TDateTime; ARatingFrom, ARatingTo: Byte;
ASortMode: TDatabaseSortMode; ASortDescending: Boolean); overload;
destructor Destroy; override;
function ToString: string; override;
procedure Parse(S: string);
property Groups: TStringList read FGroups;
property Persons: TStringList read FPersons;
property Colors: TStringList read FColors;
property GroupsAnd: Boolean read FGroupsAnd write FGroupsAnd;
property PersonsAnd: Boolean read FPersonsAnd write FPersonsAnd;
end;
implementation
{ TSearchProvider }
function TSearchProvider.Supports(Item: TPathItem): Boolean;
begin
Result := Item is TDBSearchItem;
Result := Result or Supports(Item.Path);
end;
function TSearchProvider.CreateFromPath(Path: string): TPathItem;
begin
Result := nil;
if StartsText(cDBSearchPath, AnsiLowerCase(Path)) then
Result := TDBSearchItem.CreateFromPath(Path, PATH_LOAD_NO_IMAGE, 0);
if Pos(cFilesSearchPath, AnsiLowerCase(Path)) > 0 then
Result := TFileSearchItem.CreateFromPath(Path, PATH_LOAD_NO_IMAGE, 0);
if Pos(cImagesSearchPath, AnsiLowerCase(Path)) > 0 then
Result := TImageSearchItem.CreateFromPath(Path, PATH_LOAD_NO_IMAGE, 0);
end;
function TSearchProvider.Supports(Path: string): Boolean;
begin
Result := StartsText(cDBSearchPath, AnsiLowerCase(Path));
Result := Result or (Pos(cImagesSearchPath, AnsiLowerCase(Path)) > 0);
Result := Result or (Pos(cFilesSearchPath, AnsiLowerCase(Path)) > 0);
end;
{ TDBSearchItem }
constructor TDBSearchItem.CreateFromPath(APath: string; Options,
ImageSize: Integer);
begin
inherited;
FDisplayName := Format(TA('Search in collection for: %s', 'Path'), [SearchDisplayText]) + '...';
end;
function TDBSearchItem.InternalCreateNewInstance: TPathItem;
begin
Result := TDBSearchItem.Create;
end;
function TDBSearchItem.InternalGetParent: TPathItem;
begin
Result := THomeItem.Create;
end;
{ TFileSearchItem }
constructor TFileSearchItem.CreateFromPath(APath: string; Options,
ImageSize: Integer);
begin
inherited;
FDisplayName := Format(TA('Search files for: %s', 'Path'), [SearchDisplayText]) + '...';
end;
function TFileSearchItem.InternalCreateNewInstance: TPathItem;
begin
Result := TFileSearchItem.Create;
end;
function TFileSearchItem.InternalGetParent: TPathItem;
begin
if SearchPath = '' then
Result := THomeItem.Create
else if IsNetworkShare(SearchPath) then
Result := TShareItem.CreateFromPath(SearchPath, PATH_LOAD_NO_IMAGE, 0)
else if IsDrive(SearchPath) then
Result := TDriveItem.CreateFromPath(SearchPath, PATH_LOAD_NO_IMAGE or PATH_LOAD_FAST, 0)
else
Result := TDirectoryItem.CreateFromPath(SearchPath, PATH_LOAD_NO_IMAGE, 0);
end;
{ TImageSearchItem }
constructor TImageSearchItem.CreateFromPath(APath: string; Options,
ImageSize: Integer);
begin
inherited;
FDisplayName := Format(TA('Search files (with EXIF) for: %s', 'Path'), [SearchDisplayText]) + '...';
end;
function TImageSearchItem.InternalCreateNewInstance: TPathItem;
begin
Result := TImageSearchItem.Create;
end;
{ TSearchItem }
function TSearchItem.L(StringToTranslate: string): string;
begin
Result := TA(StringToTranslate, 'Path');
end;
function TSearchItem.LoadImage(Options, ImageSize: Integer): Boolean;
var
Icon: TIcon;
begin
F(FImage);
FindIcon(HInstance, 'SEARCH', ImageSize, 32, Icon);
FImage := TPathImage.Create(Icon);
Result := True;
end;
procedure TSearchItem.Assign(Item: TPathItem);
begin
inherited;
FSearchPath := TSearchItem(Item).FSearchPath;
FSearchTerm := TSearchItem(Item).FSearchTerm;
end;
constructor TSearchItem.CreateFromPath(APath: string; Options,
ImageSize: Integer);
const
SchemaStart = '::';
SchemaEnd = '://';
var
PS, PE: Integer;
begin
inherited;
FDisplayName := TA('Search', 'Path');
PS := Pos(SchemaStart, APath);
PE := PosEx(SchemaEnd, APath, PS);
if (PS > 0) and (PE > PS) then
begin
FSearchPath := uStringUtils.Left(APath, PS - 1);
FSearchTerm := uStringUtils.Right(APath, PE + Length(SchemaEnd));
end;
if Options and PATH_LOAD_NO_IMAGE = 0 then
LoadImage(Options, ImageSize);
end;
function TSearchItem.GetSearchDisplayText: string;
var
I: Integer;
Parameters: TDatabaseSearchParameters;
ResultList: TStringList;
SortMode, SortDirection: string;
ColorNames: TStrings;
Palette: TPaletteArray;
PaletteHLS: TPaletteHLSArray;
function FindColorName(ColorCode: string): string;
const
InvalidColor = $111111;
var
Color: TColor;
I: Integer;
begin
Result := ColorCode;
if ColorCode = 'BW' then
Result := TA('Black and white', 'Colors');
Color := HexToIntDef(ColorCode, InvalidColor);
if Color <> InvalidColor then
begin
for I := 0 to Length(Palette) - 1 do
if Palette[I] = Color then
Result := TA(PaletteColorNames[I], 'Colors');
end;
end;
begin
Parameters := TDatabaseSearchParameters.Create;
ResultList := TStringList.Create;
try
Parameters.Parse(SearchTerm);
Result := '';
if Trim(Parameters.Text) <> '' then
Result := '"' + Parameters.Text + '"';
if (Parameters.RatingFrom = 0) and (Parameters.RatingTo = 5) then
begin
//any rating, skip
end else if (Parameters.RatingFrom > 0) and (Parameters.RatingTo < 5) then
begin
//rating between
ResultList.Add(FormatEx(L('rating between {0} and {1}'), [Parameters.RatingFrom, Parameters.RatingTo]));
end else if (Parameters.RatingFrom > 0) then
begin
ResultList.Add(FormatEx(L('rating more than {0}'), [Parameters.RatingFrom]));
end else if (Parameters.RatingTo < 5) then
begin
ResultList.Add(FormatEx(L('rating less than {0}'), [Parameters.RatingTo]));
end;
if (Parameters.DateFrom <= EncodeDate(cMinEXIFYear, 1, 1)) and (Parameters.DateTo >= EncodeDate(2100, 1, 1)) then
begin
//any rating, skip
end else if (Parameters.DateFrom > EncodeDate(cMinEXIFYear, 1, 1)) and (Parameters.DateTo < EncodeDate(2100, 1, 1)) then
begin
//rating between
ResultList.Add(FormatEx(L('date between {0} and {1}'), [FormatDateTimeShortDate(Parameters.DateFrom), FormatDateTimeShortDate(Parameters.DateTo)]));
end else if (Parameters.DateFrom > EncodeDate(cMinEXIFYear, 1, 1)) then
begin
ResultList.Add(FormatEx(L('date more than {0}'), [FormatDateTimeShortDate(Parameters.DateFrom)]));
end else if (Parameters.DateTo < EncodeDate(2100, 1, 1)) then
begin
ResultList.Add(FormatEx(L('date less than {0}'), [FormatDateTimeShortDate(Parameters.DateTo)]));
end;
if Trim(Parameters.Persons.Text) <> '' then
ResultList.Add(FormatEx(L('{0} on photo'), [Parameters.Persons.Join(IIF(Parameters.PersonsAnd, ' ' + L('and') + ' ', ' ' + L('or') + ' '))]));
if Trim(Parameters.Groups.Text) <> '' then
ResultList.Add(FormatEx(L('with groups: {0}'), [Parameters.Groups.Join(IIF(Parameters.GroupsAnd, ' ' + L('and') + ' ', ' ' + L('or') + ' '))]));
if Trim(Parameters.Colors.Text) <> '' then
begin
ColorNames := TStringList.Create;
try
FillColors(Palette, PaletteHLS);
for I := 0 to Parameters.Colors.Count - 1 do
ColorNames.Add(FindColorName(Parameters.Colors[I]));
ResultList.Add(FormatEx(L('with colors: {0}'), [ColorNames.Join(' ' + L('and') + ' ')]));
finally
F(ColorNames);
end;
end;
if ResultList.Count > 0 then
Result := ResultList.Join(', ');
if Result = '' then
Result := L('any photo');
if Parameters.ShowPrivate or Parameters.ShowHidden then
begin
ResultList.Clear;
if Parameters.ShowHidden then
ResultList.Add(L('hidden'));
if Parameters.ShowPrivate then
ResultList.Add(L('private'));
Result := Result + FormatEx(L(', including {0}'), [ResultList.Join(L(' ' + L('and') + ' '))]) ;
end;
if (Parameters.SortMode = dsmRating) and Parameters.SortDescending then
begin
//default sorting
end else
begin
case Parameters.SortMode of
dsmID:
SortDirection := 'ID';
dsmName:
SortDirection := 'name';
dsmRating:
SortDirection := 'rating';
dsmDate:
SortDirection := 'date';
dsmFileSize:
SortDirection := 'file size';
dsmImageSize:
SortDirection := 'image size';
dsmComparing:
SortDirection := 'comparing';
dsmViewCount:
SortDirection := 'view count';
end;
SortDirection := L(SortDirection);
if not Parameters.SortDescending then
SortMode := FormatEx(L(', sort by {0}, ascending'), [SortDirection])
else
SortMode := FormatEx(L(', sort by {0}, descending'), [SortDirection]);
Result := Result + SortMode;
end;
finally
F(ResultList);
F(Parameters);
end;
end;
{ TDatabaseSearchParameters }
constructor TDatabaseSearchParameters.Create;
begin
Init;
end;
constructor TDatabaseSearchParameters.Create(AText: string; ADateFrom, ADateTo: TDateTime;
ARatingFrom, ARatingTo: Byte; ASortMode: TDatabaseSortMode;
ASortDescending: Boolean);
begin
Init;
Text := AText;
DateFrom := ADateFrom;
DateTo := ADateTo;
RatingFrom := ARatingFrom;
RatingTo := ARatingTo;
SortMode := ASortMode;
SortDescending := ASortDescending;
end;
destructor TDatabaseSearchParameters.Destroy;
begin
F(FGroups);
F(FPersons);
F(FColors);
inherited;
end;
procedure TDatabaseSearchParameters.Init;
begin
FGroups := TStringList.Create;
FPersons := TStringList.Create;
FColors := TStringList.Create;
Text := '';
DateFrom := EncodeDate(cMinEXIFYear, 1, 1);
DateTo := EncodeDate(2100, 1, 1);
RatingFrom := 0;
RatingTo := 5;
SortMode := dsmRating;
SortDescending := True;
ShowPrivate := False;
ShowHidden := False;
FGroupsAnd := False;
FPersonsAnd := False;
end;
procedure TDatabaseSearchParameters.Parse(S: string);
var
I: Integer;
Parameters, Parameter: TArray<string>;
Key, Value: string;
begin
Parameters := S.Split([';']);
if Length(Parameters) > 0 then
begin
Text := Parameters[0];
for I := 1 to Length(Parameters) - 1 do
begin
Parameter := Parameters[I].Split(['=']);
if Length(Parameter) = 2 then
begin
Key := Parameter[0];
Value := Parameter[1];
if Key = 'RatingFrom' then
RatingFrom := StrToIntDef(Value, 0)
else if Key = 'RatingTo' then
RatingTo := StrToIntDef(Value, 0)
else if Key = 'DateFrom' then
DateFrom := DateTimeStrEval('yyyy.mm.dd', Value)
else if Key = 'DateTo' then
DateTo := DateTimeStrEval('yyyy.mm.dd', Value)
else if Key = 'SortBy' then
SortMode := TDatabaseSortMode.FromString(Value)
else if Key = 'SortAsc' then
SortDescending := not (Value = '1') or (Value = 'true')
else if Key = 'Groups' then
begin
Groups.Clear;
Groups.AddRange(Value.Split([',']));
end else if Key = 'GroupsMode' then
GroupsAnd := Value = 'and'
else if Key = 'Persons' then
begin
Persons.Clear;
Persons.AddRange(Value.Split([',']));
end else if Key = 'PersonsMode' then
PersonsAnd := Value = 'and'
else if Key = 'Colors' then
begin
Colors.Clear;
Colors.AddRange(Value.Split([',']));
end
else if Key = 'Private' then
ShowPrivate := (Value = '1') or (Value = 'true')
else if Key = 'Hidden' then
ShowHidden := (Value = '1') or (Value = 'true');
end;
end;
end;
end;
function TDatabaseSearchParameters.ToString: string;
var
Items: TStringList;
begin
Items := TStringList.Create;
try
Items.Add(Text.Replace(';', ' '));
if RatingFrom > 0 then
Items.Add('RatingFrom=' + IntToStr(RatingFrom));
if RatingTo < 5 then
Items.Add('RatingTo=' + IntToStr(RatingTo));
if DateFrom <> MinDateTime then
Items.Add('DateFrom=' + FormatDateTime('yyyy.mm.dd', DateFrom));
if DateTo <> MinDateTime then
Items.Add('DateTo=' + FormatDateTime('yyyy.mm.dd', DateTo));
if SortMode <> dsmRating then
Items.Add('SortBy=' + SortMode.ToString);
if not SortDescending then
Items.Add('SortAsc=1');
if Groups.Count > 0 then
begin
Items.Add('Groups=' + Groups.Join(','));
Items.Add('GroupsMode=' + IIF(GroupsAnd, 'and', 'or'));
end;
if Persons.Count > 0 then
begin
Items.Add('Persons=' + Persons.Join(','));
Items.Add('PersonsMode=' + IIF(PersonsAnd, 'and', 'or'));
end;
if ShowPrivate then
Items.Add('Private=1');
if ShowHidden then
Items.Add('Hidden=1');
if Colors.Count > 0 then
Items.Add('Colors=' + Colors.Join(','));
Result := Items.Join(';');
finally
F(Items);
end;
end;
{ TDatabaseSortModeHelper }
class function TDatabaseSortModeHelper.FromString(S: string): TDatabaseSortMode;
begin
if S = 'ID' then
Exit(dsmID);
if S = 'Name' then
Exit(dsmName);
if S = 'Rating' then
Exit(dsmRating);
if S = 'Date' then
Exit(dsmDate);
if S = 'FileSize' then
Exit(dsmFileSize);
if S = 'ImageSize' then
Exit(dsmImageSize);
if S = 'Comparing' then
Exit(dsmComparing);
if S = 'Views' then
Exit(dsmViewCount);
Exit(dsmRating);
end;
function TDatabaseSortModeHelper.ToString: string;
begin
Result := '';
case Self of
dsmID:
Exit('ID');
dsmName:
Exit('Name');
dsmRating:
Exit('Rating');
dsmDate:
Exit('Date');
dsmFileSize:
Exit('FileSize');
dsmImageSize:
Exit('ImageSize');
dsmComparing:
Exit('Comparing');
dsmViewCount:
Exit('Views');
end;
end;
initialization
PathProviderManager.RegisterProvider(TSearchProvider.Create);
end.
|
namespace TsmPluginFx.Manager;
uses
System.Text,
System.Runtime.InteropServices,
System.IO;
[DllImport('kernel32.dll')]
method LoadLibrary(aModulePath: not nullable String): IntPtr; external;
[DllImport('kernel32.dll')]
method GetProcAddress(aModule: IntPtr; aProcName: not nullable String): IntPtr; external;
[DllImport('kernel32.dll')]
method FreeLibrary(aModule: IntPtr): Boolean; external;
type
GetEnabledMethod = block(): [MarshalAs(UnmanagedType.I1)] Boolean;
GetPluginInfoMethod = block(aPluginInfo: StringBuilder; aSize: UInt32): UInt32;
GetPluginNameMethod = block(aPluginName: StringBuilder; aSize: UInt32): UInt32;
GetPluginVersionMethod = block(aPluginVersion: StringBuilder; aSize: UInt32): UInt32;
SetEnabledMethod = block([MarshalAs(UnmanagedType.I1)] aValue: Boolean);
ITsmPluginModule = interface
property Enabled: Boolean write;
property Info: String read;
property Loaded: Boolean read;
property Name: String read;
property Path: String read;
property Version: String read;
end;
TsmPluginModule = class(ITsmPluginModule)
private
fModule: IntPtr;
fModulePath: String;
fGetEnabledFuncPtr, fSetEnabledFuncPtr, fGetPluginInfoFuncPtr, fGetPluginNameFuncPtr, fGetPluginVersionFuncPtr: IntPtr;
private
_GetEnabled: GetEnabledMethod;
_GetPluginInfo: GetPluginInfoMethod;
_GetPluginName: GetPluginNameMethod;
_GetPluginVersion: GetPluginVersionMethod;
_SetEnabled: SetEnabledMethod;
public
constructor(aModulePath: not nullable String; aEnabled: Boolean := true);
begin
fModulePath := aModulePath;
fModule := LoadLibrary(fModulePath);
if fModule = IntPtr.Zero then exit;
fGetEnabledFuncPtr := GetProcAddress(fModule, 'GetEnabled');
fGetPluginInfoFuncPtr := GetProcAddress(fModule, 'GetPluginInfo');
fGetPluginNameFuncPtr := GetProcAddress(fModule, 'GetPluginName');
fGetPluginVersionFuncPtr := GetProcAddress(fModule, 'GetPluginVersion');
fSetEnabledFuncPtr := GetProcAddress(fModule, 'SetEnabled');
if fGetEnabledFuncPtr <> IntPtr.Zero then
_GetEnabled := Marshal.GetDelegateForFunctionPointer<GetEnabledMethod>(fGetEnabledFuncPtr);
if fGetPluginInfoFuncPtr <> IntPtr.Zero then
_GetPluginInfo := Marshal.GetDelegateForFunctionPointer<GetPluginInfoMethod>(fGetPluginInfoFuncPtr);
if fGetPluginNameFuncPtr <> IntPtr.Zero then
_GetPluginName := Marshal.GetDelegateForFunctionPointer<GetPluginNameMethod>(fGetPluginNameFuncPtr);
if fGetPluginVersionFuncPtr <> IntPtr.Zero then
_GetPluginVersion := Marshal.GetDelegateForFunctionPointer<GetPluginVersionMethod>(fGetPluginVersionFuncPtr);
if fSetEnabledFuncPtr <> IntPtr.Zero then
_SetEnabled := Marshal.GetDelegateForFunctionPointer<SetEnabledMethod>(fSetEnabledFuncPtr);
Enabled := aEnabled;
end;
finalizer;
begin
if fModule <> IntPtr.Zero then
FreeLibrary(fModule);
end;
property Enabled: Boolean
read require
assigned(_GetEnabled);
begin
exit _GetEnabled();
end
write begin
if assigned(_SetEnabled) then _SetEnabled(value);
end;
property Info: String
read require
assigned(_GetPluginInfo);
begin
var lSize := _GetPluginInfo(nil, 0);
var lStrBuilder := new StringBuilder(lSize);
_GetPluginInfo(lStrBuilder, lStrBuilder.Capacity + 1);
exit lStrBuilder.ToString;
end;
property Loaded: Boolean
read begin
exit fModule <> IntPtr.Zero;
end;
property Name: String
read require
assigned(_GetPluginName);
begin
var lStrBuilder := new StringBuilder(256);
_GetPluginName(lStrBuilder, lStrBuilder.Capacity + 1);
exit lStrBuilder.ToString;
end;
property Version: String
read require
assigned(_GetPluginVersion);
begin
var lStrBuilder := new StringBuilder(256);
_GetPluginVersion(lStrBuilder, lStrBuilder.Capacity + 1);
exit lStrBuilder.ToString;
end;
property Path: String read fModulePath;
end;
end. |
{******
单 元:uHotSpot.pas
作 者:刘景威
日 期:2007-11-25
说 明:热点题单元
更 新:
******}
unit uHotSpot;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls, PngImage;
type
//鼠标在指示区的位置
TMousePosition = (mpNone, mpLeft, mpTop, mpRight, mpBottom, mpTopLeft, mpTopRight,
mpBottomLeft, mpBottomRight, mpMiddle);
TShape = class(ExtCtrls.TShape)
protected
procedure Paint; override;
end;
TfraHotspot = class(TFrame)
sbImg: TScrollBox;
img: TImage;
imgHot: TImage;
spRect: TShape;
procedure imgClick(Sender: TObject);
procedure imgMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure imgMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure imgMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure spRectMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure spRectMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure spRectMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure sbImgCanResize(Sender: TObject; var NewWidth,
NewHeight: Integer; var Resize: Boolean);
private
{ Private declarations }
FImage: string;
FEdit: Boolean;
FIsDown: Boolean;
FOldX: Integer;
FOldY: Integer;
FHPos: Integer;
FVPos: Integer;
FImgSize: TSize;
FMousePosition: TMousePosition;
procedure SetImage(Value: string);
procedure SetEdit(Value: Boolean);
procedure SetHotPos(const AScale: Single); overload;
procedure SetImageInRect;
public
{ Public declarations }
procedure SetImageToOri;
procedure SetImageToFit;
procedure SetHotPos(const ARect: TRect); overload;
published
property Image: string read FImage write SetImage;
property Edit: Boolean read FEdit write SetEdit;
end;
implementation
uses uGlobal;
//热点鼠标感应宽度
const
PRECISION = 4;
MIN_SIZE = 8;
IMG_WIDTH = 377;
IMG_HEIGHT = 189;
{$R *.dfm}
{ TfraHotspot }
procedure TfraHotspot.SetImage(Value: string);
begin
if not FileExists(Value) then Exit;
if FImage <> Value then
begin
FImage := Value;
FImgSize := GetImageSize(Value);
img.Picture.LoadFromFile(Value);
if not FEdit then sbImg.SetFocus;
spRect.Visible := False;
imgHot.Visible := False;
//限制越界滚动
sbImg.HorzScrollBar.Range := img.Width;
sbImg.VertScrollBar.Range := img.Height;
sbImg.HorzScrollBar.Position := 0;
sbImg.VertScrollBar.Position := 0;
end;
end;
procedure TfraHotspot.SetEdit(Value: Boolean);
begin
if FEdit <> Value then FEdit := Value;
spRect.Visible := Value;
imgHot.Visible := Value;
end;
procedure TfraHotspot.SetHotPos(const AScale: Single);
begin
sbImg.HorzScrollBar.Position := 0;
sbImg.VertScrollBar.Position := 0;
spRect.Left := Round(spRect.Left * AScale);
spRect.Top := Round(spRect.Top * AScale);
spRect.Width := Round(spRect.Width * AScale);
spRect.Height := Round(spRect.Height * AScale);
SetImageInRect();
end;
procedure TfraHotspot.SetHotPos(const ARect: TRect);
begin
spRect.Visible := True;
imgHot.Visible := True;
spRect.Left := ARect.Left;
spRect.Top := ARect.Top;
spRect.Width := ARect.Right;
spRect.Height := ARect.Bottom;
SetImageInRect();
end;
procedure TfraHotspot.SetImageInRect;
begin
imgHot.Left := spRect.Left;
imgHot.Top := spRect.Top;
imgHot.Width := spRect.Width;
imgHot.Height := spRect.Height;
end;
procedure TfraHotspot.imgClick(Sender: TObject);
begin
SetFocus();
end;
procedure TfraHotspot.SetImageToOri;
begin
//重设热点位置及大小
if not img.AutoSize and spRect.Visible then
begin
if FImgSize.cy / FImgSize.cx > IMG_HEIGHT / IMG_WIDTH then
SetHotPos(FImgSize.cy / IMG_HEIGHT)
else SetHotPos(FImgSize.cx / IMG_WIDTH);
end;
Align := alNone;
sbImg.Align := alNone;
if TForm(Parent.Parent.Parent).Active then sbImg.SetFocus;
img.Align := alNone;
img.AutoSize := True;
//限制越界滚动
sbImg.HorzScrollBar.Range := img.Width;
sbImg.VertScrollBar.Range := img.Height;
sbImg.HorzScrollBar.Position := FHPos;
sbImg.VertScrollBar.Position := FVPos;
end;
procedure TfraHotspot.SetImageToFit;
begin
FHPos := sbImg.HorzScrollBar.Position;
FVPos := sbImg.VertScrollBar.Position;
//重设热点位置及大小
if img.AutoSize and spRect.Visible then
begin
if FImgSize.cy / FImgSize.cx > IMG_HEIGHT / IMG_WIDTH then
SetHotPos(IMG_HEIGHT / FImgSize.cy)
else SetHotPos(IMG_WIDTH / FImgSize.cx);
end;
Align := alClient;
sbImg.Align := alClient;
if TForm(Parent.Parent.Parent).Active then sbImg.SetFocus;
img.AutoSize := False;
img.Stretch := True;
img.Proportional := True;
//设置Image尺寸
if FImgSize.cy / FImgSize.cx > IMG_HEIGHT / IMG_WIDTH then
begin
img.Width := Round(FImgSize.cx * IMG_HEIGHT / FImgSize.cy);
img.Height := IMG_HEIGHT;
end
else
begin
img.Width := IMG_WIDTH;
img.Height := Round(FImgSize.cy * IMG_WIDTH / FImgSize.cx);
end;
//限制越界滚动
sbImg.HorzScrollBar.Range := img.Width;
sbImg.VertScrollBar.Range := img.Height;
end;
procedure TfraHotspot.imgMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
FIsDown := True;
FOldX := X;
FOldY := Y;
end;
procedure TfraHotspot.imgMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
if not FIsDown then Exit;
if X < 0 then X := 0;
if X > img.Width then X := img.Width;
if Y < 0 then Y := 0;
if Y > img.Height then Y := img.Height;
//显示热点
if (Abs(X - FOldX) > 0) and (Abs(Y - FOldY) > 0) then
begin
spRect.Visible := True;
imgHot.Visible := True;
if X > FOldX then
spRect.Left := FOldX
else spRect.Left := X;
if Y > FOldY then
spRect.Top := FOldY
else spRect.Top := Y;
spRect.Left := spRect.Left - sbImg.HorzScrollBar.Position;
spRect.Top := spRect.Top - sbImg.VertScrollBar.Position;
spRect.Width := Abs(X - FOldX);
spRect.Height := Abs(Y - FOldY);
SetImageInRect();
end;
end;
procedure TfraHotspot.imgMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
FIsDown := False;
end;
procedure TfraHotspot.spRectMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
FOldX := X;
FOldY := Y;
//设置鼠标位置
case spRect.Cursor of
crSizeNWSE:
if X <= PRECISION then
FMousePosition := mpTopLeft
else FMousePosition := mpBottomRight;
crSizeNESW:
if X <= PRECISION then
FMousePosition := mpBottomLeft
else FMousePosition := mpTopRight;
crSizeWE:
if X <= PRECISION then
FMousePosition := mpLeft
else FMousePosition := mpRight;
crSizeNS:
if Y <= PRECISION then
FMousePosition := mpTop
else FMousePosition := mpBottom;
crSizeAll: FMousePosition := mpMiddle;
end;
end;
procedure TfraHotspot.spRectMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
//TForm(Parent.Parent.Parent).Caption := Format('hpos: %d; vpos: %d', [sbImg.HorzScrollBar.Position, sbImg.VertScrollBar.Position]);
if FMousePosition = mpNone then
begin
//左上角、右下角
if (X <= PRECISION) and (Y <= PRECISION) or (X >= spRect.Width - PRECISION) and (Y >= spRect.Height - PRECISION) then
spRect.Cursor := crSizeNWSE
//左上角、右上角
else if (X <= PRECISION) and (Y >= spRect.Height - PRECISION) or (X >= spRect.Width - PRECISION) and (Y <= PRECISION) then
spRect.Cursor := crSizeNESW
//左部、右部
else if (X <= PRECISION) or (X >= spRect.Width - PRECISION) then
spRect.Cursor := crSizeWE
//上部、下部
else if (Y <= PRECISION) or (Y >= spRect.Height - PRECISION) then
spRect.Cursor := crSizeNS
else spRect.Cursor := crSizeAll;
end;
//改变大小或移动...
//左部
if FMousePosition in [mpTopLeft, mpLeft, mpBottomLeft] then
begin
if spRect.Left + X < - sbImg.HorzScrollBar.Position then X := - sbImg.HorzScrollBar.Position - spRect.Left;
if spRect.Width - X < MIN_SIZE then X := spRect.Width - MIN_SIZE;
spRect.Left := spRect.Left + X;
spRect.Width := spRect.Width - X;
end;
//上部
if FMousePosition in [mpTopLeft, mpTop, mpTopRight] then
begin
if spRect.Top + Y < - sbImg.VertScrollBar.Position then Y := - sbImg.VertScrollBar.Position - spRect.Top;
if spRect.Height - Y < MIN_SIZE then Y := spRect.Height - MIN_SIZE;
spRect.Top := spRect.Top + Y;
spRect.Height := spRect.Height - Y;
end;
//右部
if FMousePosition in [mpTopRight, mpRight, mpBottomRight] then
begin
if X < MIN_SIZE then X := MIN_SIZE;
if X > img.Width - sbImg.VertScrollBar.Position - spRect.Left then X := img.Width - sbImg.VertScrollBar.Position - spRect.Left;
spRect.Width := X;
end;
//下部
if FMousePosition in [mpBottomLeft, mpBottom, mpBottomRight] then
begin
if Y < MIN_SIZE then Y := MIN_SIZE;
if Y > img.Height - sbImg.VertScrollBar.Position - spRect.Top then Y := img.Height - sbImg.VertScrollBar.Position - spRect.Top;
spRect.Height := Y;
end;
//中间,移动
if FMousePosition = mpMiddle then
begin
spRect.Left := spRect.Left + X - FOldX;
spRect.Top := spRect.Top + Y - FOldY;
if spRect.Left < - sbImg.HorzScrollBar.Position then spRect.Left := - sbImg.HorzScrollBar.Position;
if spRect.Left > img.Width - sbImg.HorzScrollBar.Position - spRect.Width then spRect.Left := img.Width - sbImg.HorzScrollBar.Position - spRect.Width;
if spRect.Top < - sbImg.VertScrollBar.Position then spRect.Top := - sbImg.VertScrollBar.Position;
if spRect.Top > img.Height - sbImg.VertScrollBar.Position - spRect.Height then spRect.Top := img.Height - sbImg.VertScrollBar.Position - spRect.Height;
//自动滚动
if spRect.Left < 0 then sbImg.HorzScrollBar.Position := sbImg.HorzScrollBar.Position + spRect.Left;
if spRect.Left > sbImg.Width - spRect.Width then sbImg.HorzScrollBar.Position := sbImg.HorzScrollBar.Position + spRect.Left - spRect.Width;
if spRect.Top < 0 then sbImg.VertScrollBar.Position := sbImg.VertScrollBar.Position + spRect.Top;
if spRect.Top > sbImg.Height - spRect.Height then sbImg.VertScrollBar.Position := sbImg.VertScrollBar.Position + spRect.Top - spRect.Height;
end;
//图片跟随移动
SetImageInRect();
end;
procedure TfraHotspot.spRectMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
FMousePosition := mpNone;
if TForm(Parent.Parent.Parent).Active then sbImg.SetFocus;
end;
procedure TfraHotspot.sbImgCanResize(Sender: TObject; var NewWidth,
NewHeight: Integer; var Resize: Boolean);
begin
if TForm(Parent.Parent.Parent).Active then sbImg.SetFocus;
end;
{ TShape }
procedure TShape.Paint;
begin
inherited;
//画8个边界小矩形
with Canvas do
begin
Pen.Style := psSolid;
Rectangle(0, 0, 4, 4);
Rectangle(Round(Width / 2) - 2, 0, Round(Width / 2) + 2, 4);
Rectangle(Width- 4, 0, Width, 4);
Rectangle(0, Round(Height / 2) - 2, 4, Round(Height / 2) + 2);
Rectangle(Width - 4, Round(Height / 2) - 2, Width, Round(Height / 2) + 2);
Rectangle(0, Height - 4, 4, Height);
Rectangle(Round(Width / 2) - 2, Height - 4, Round(Width / 2) + 2, Height);
Rectangle(Width - 4, Height - 4, Width, Height);
end;
end;
end.
|
unit uForm3;
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, FMX.Layouts,
FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ListView;
type
TForm3 = class(TForm)
Layout1: TLayout;
Label1: TLabel;
ListView1: TListView;
AniIndicator1: TAniIndicator;
procedure FormShow(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure ListView1UpdatingObjects(const Sender: TObject; const AItem: TListViewItem; var AHandled: Boolean);
procedure ListView1Paint(Sender: TObject; Canvas: TCanvas; const ARect: TRectF);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
procedure ReLoadLV;
procedure OnColumnClick(const Sender: TObject; const Column: Integer; const X, Y: Single;
const AItem: TListViewItem; const DrawebleName: string);
public
{ Public declarations }
end;
var
Form3: TForm3;
implementation
{$R *.fmx}
uses
System.Threading, System.Math, System.IOUtils, System.Net.HTTPClient,
FMX.FireMonkey.Parser,
uForm2;
const
colTitle = 'title';
colBitmap = 'bitmap';
colLogo = 'logo';
colLoading = 'loading';
ColumnStartIndex = 1;
function getRealIndex(const Row, Column, Columns: Integer): Integer;
begin
Result := (((Row + 1) * Columns) - 1) - (Columns - Column);
end;
procedure LoadBitmapFromURL(const aURL: string; aBitmap: TBitmap);
// System.Net.HTTPClient
var
thread: TThread;
begin
thread := TThread.CreateAnonymousThread(
procedure
var
Http: THTTPClient;
Result: TMemoryStream;
begin
Result := TMemoryStream.Create;
Http := THTTPClient.Create;
try
try
Http.HandleRedirects := true;
Http.Get(aURL, Result);
TThread.Synchronize(TThread.CurrentThread,
procedure
var
aSourceBmp: TBitmap;
begin
aSourceBmp := TBitmap.Create;
aSourceBmp.LoadFromStream(Result);
if not aSourceBmp.IsEmpty then
begin
aBitmap.Clear(TAlphaColorRec.White);
aBitmap.SetSize(aSourceBmp.Width, aSourceBmp.Height);
aBitmap.CopyFromBitmap(aSourceBmp);
end;
FreeAndNil(aSourceBmp);
end);
except
FreeAndNil(Result);
end;
finally
FreeAndNil(Result);
FreeAndNil(Http);
end;
end);
thread.FreeOnTerminate := true;
thread.start;
end;
procedure TForm3.FormClose(Sender: TObject; var Action: TCloseAction);
begin
TFireMonkey.Clean;
end;
procedure TForm3.FormResize(Sender: TObject);
begin
if Tag = 0 then
ReLoadLV;
end;
procedure TForm3.FormShow(Sender: TObject);
begin
ListView1.ColumnWidth := 160;
ListView1.AutoColumns := true;
ListView1.ItemAppearance.ItemHeight := 180;
ListView1.StyleLookup := 'listviewstyle_panel';
ListView1.OnColumnClick := OnColumnClick;
ListView1.ShowScrollBar := false;
ListView1.EnableTouchAnimation(false);
TTask.Run(
procedure
begin
TFireMonkey.Request(TFireMonkey.GetURL);
TFireMonkey.MakeList;
TThread.Synchronize(nil,
procedure
begin
Tag := 0;
ReLoadLV;
end);
end);
end;
procedure TForm3.ListView1Paint(Sender: TObject; Canvas: TCanvas; const ARect: TRectF);
var
I, J, RowColumns: Integer;
iBitmap: TListItemImage;
aFirst, aLast: Integer;
begin
if ListView1.Items.Count <= 0 then
exit;
aFirst := Max(0, ListView1.getFirstVisibleItemIndex);
aLast := aFirst + ListView1.getVisibleCount;
for I := aFirst to aLast do
begin
if InRange(I, 0, ListView1.Items.Count - 1) then
begin
Label1.Text := string.Join(':', [I, ListView1.getFirstVisibleItemIndex, ListView1.getVisibleCount,
ListView1.getLastVisibleItemindex]);
RowColumns := ListView1.Items[I].Tag;
for J := 1 to RowColumns do
begin
iBitmap := ListView1.Items[I].Objects.FindObjectT<TListItemImage>(colBitmap + IntToStr(J));
if Assigned(iBitmap) then
begin
if Assigned(iBitmap.Bitmap) and (ListView1.Items[I].Data[colLoading + IntToStr(J)].AsInteger = 1) then
begin
ListView1.Items[I].Data[colLoading + IntToStr(J)] := 0;
LoadBitmapFromURL(ListView1.Items[I].Data[colLogo + IntToStr(J)].AsString, iBitmap.Bitmap);
end;
end;
end;
end
else
break;
end;
end;
procedure TForm3.ListView1UpdatingObjects(const Sender: TObject; const AItem: TListViewItem; var AHandled: Boolean);
var
iTitle: TListItemText;
iBitmap: TListItemImage;
aPos: Single;
I: Integer;
// realIndex: Integer;
begin
for I := 1 to ListView1.Columns do
begin
if not InRange(I, ColumnStartIndex, AItem.Tag) then
continue;
aPos := (((ListView1.ColumnWidth * I) - ListView1.ColumnWidth) - 6) + Trunc(ListView1.ColumnOffset * I);
iBitmap := AItem.Objects.FindObjectT<TListItemImage>(colBitmap + IntToStr(I));
if iBitmap = nil then
iBitmap := TListItemImage.Create(AItem);
iBitmap.Name := colBitmap + IntToStr(I);
iBitmap.Width := ListView1.ColumnWidth - 8;
iBitmap.Height := ListView1.ColumnWidth - 8;
iBitmap.ScalingMode := TImageScalingMode.Stretch;
iBitmap.PlaceOffset.X := aPos;
iBitmap.PlaceOffset.Y := 4;
iBitmap.OwnsBitmap := true;
if (iBitmap.Bitmap = nil) then
iBitmap.Bitmap := TBitmap.Create;
// заголовок
iTitle := AItem.Objects.FindObjectT<TListItemText>(colTitle + IntToStr(I));
if iTitle = nil then
iTitle := TListItemText.Create(AItem);
iTitle.Name := colTitle + IntToStr(I);
iTitle.TextAlign := TTextAlign.Center;
iTitle.TextVertAlign := TTextAlign.Center;
iTitle.SelectedTextColor := TAlphaColorRec.Black;
iTitle.TextColor := TAlphaColorRec.Black;
iTitle.Font.Size := 14;
iTitle.WordWrap := true;
iTitle.Width := iBitmap.Width - 8;
iTitle.PlaceOffset.X := aPos + 8;
iTitle.PlaceOffset.Y := iBitmap.Height;
iTitle.Height := ListView1.ItemAppearance.ItemHeight - iTitle.PlaceOffset.Y;
iTitle.Text := AItem.Data[colTitle + IntToStr(I)].AsString;
end;
AHandled := true;
end;
procedure TForm3.OnColumnClick(const Sender: TObject; const Column: Integer; const X, Y: Single;
const AItem: TListViewItem; const DrawebleName: string);
// var
// realIndex: Integer;
begin
ShowMessage(AItem.Data[colLogo + IntToStr(Column)].AsString);
// realIndex := getRealIndex(AItem.Index, Column, ListView1.Columns);
// ShowMessage(DrawebleName + #13#10 + realIndex.ToString + ' ' + FMembersList[realIndex].FileName + #13#10 +
// AItem.Data[colLogo + IntToStr(Column)].AsString);
end;
procedure TForm3.ReLoadLV;
var
J, realIndex, ColumnInRow, RowCount: Integer;
AItem: TListViewItem;
iBitmap: TListItemImage;
begin
ListView1.OnPaint := nil;
AniIndicator1.Enabled := true;
while ListView1.Items.Count > 0 do
begin
for J := 1 to ListView1.Items[0].Tag do
begin
iBitmap := ListView1.Items[0].Objects.FindObjectT<TListItemImage>(colBitmap + IntToStr(J));
if (Assigned(iBitmap) and iBitmap.OwnsBitmap) then
begin
iBitmap.Bitmap.Free;
iBitmap.Bitmap := nil;
end;
end;
ListView1.Items.Delete(0);
end;
if FMembersList.Count < 0 then
exit;
RowCount := ceil(FMembersList.Count / ListView1.Columns);
realIndex := -1;
for J := 0 to RowCount - 1 do
begin
inc(realIndex);
AItem := ListView1.Items.Add;
with AItem do
begin
ColumnInRow := ColumnStartIndex;
while realIndex < FMembersList.Count do
begin
Data[colTitle + IntToStr(ColumnInRow)] := FMembersList.Items[realIndex].Name;
Data[colLogo + IntToStr(ColumnInRow)] := FMembersList.Items[realIndex].URL;
Data[colLoading + IntToStr(ColumnInRow)] := 1;
Tag := ColumnInRow;
if ColumnInRow mod ListView1.Columns = 0 then
break;
inc(realIndex);
inc(ColumnInRow);
end;
end;
ListView1.Adapter.ResetView(AItem);
end;
AniIndicator1.Enabled := false;
ListView1.OnPaint := ListView1Paint;
end;
end.
|
procedure ConvTextOut(CV: TCanvas; const sText: String; x, y,angle:integer);
//
// Escreve um texto e converte-o em Imagem
//
var
LogFont: TLogFont;
SaveFont: TFont;
begin
SaveFont := TFont.Create;
SaveFont.Assign(CV.Font);
GetObject(SaveFont.Handle, sizeof(TLogFont), @LogFont);
with LogFont do
begin
lfEscapement := angle *10;
lfPitchAndFamily := FIXED_PITCH or FF_DONTCARE;
end; {with}
CV.Font.Handle := CreateFontIndirect(LogFont);
SetBkMode(CV.Handle, TRANSPARENT);
CV.TextOut(x, y, sText);
CV.Font.Assign(SaveFont);
SaveFont.Free;
end;
|
unit GraphicCrypt;
{$WARN SYMBOL_PLATFORM OFF}
interface
uses
Winapi.Windows,
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.Imaging.JPEG,
Vcl.Imaging.PngImage,
Data.DB,
Data.Win.ADODB,
Dmitry.CRC32,
Dmitry.Utils.System,
Dmitry.Utils.Files,
Dmitry.Memory,
DECUtil,
DECCipher,
GIFImage,
GraphicEx,
uAssociations,
uShellIntegration,
uTiffImage,
uRAWImage,
uConstants,
uTranslate,
uStrongCrypt,
uTransparentEncryption,
uErrors,
uDBConnection,
uActivationUtils,
uGraphicUtils,
uProgramStatInfo,
uShellUtils;
const
CRYPT_OPTIONS_NORMAL = 0;
CRYPT_OPTIONS_SAVE_CRC = 1;
function CryptGraphicFileV3(FileName: string; Password: string; Options: Integer; Progress: TFileProgress = nil): Integer;
function DeCryptGraphicFileEx(FileName: string; Password: string; var Pages: Word;
LoadFullRAW: Boolean = false; Page: Integer = 0): TGraphic;
function DeCryptGraphicFile(FileName: string; Password: string;
LoadFullRAW: Boolean = false; Page: Integer = 0): TGraphic;
function DecryptGraphicFileToStream(FileName, Password: string; S: TStream): Boolean;
function ValidPassInCryptGraphicFile(FileName, Password: string): Boolean;
function ResetPasswordInGraphicFile(FileName, Password: string; Progress: TFileProgress = nil): Integer;
function ChangePasswordInGraphicFile(FileName: string; OldPass, NewPass: string): Integer;
function ValidCryptGraphicFile(FileName: string): Boolean;
function ValidCryptGraphicStream(Stream: TStream): Boolean;
function GetPasswordCRCFromCryptGraphicFile(FileName: string): Cardinal;
function CryptBlobStream(DF: TField; Password: string): Boolean;
function DeCryptBlobStreamJPG(DF: TField; Password: string; JPEG: TJpegImage): Boolean;
function ValidCryptBlobStreamJPG(DF: TField): Boolean;
function ValidPassInCryptBlobStreamJPG(DF: TField; Password: string): Boolean;
function ResetPasswordInCryptBlobStreamJPG(DF: TField; Password: string): Boolean;
procedure EncryptGraphicImage(Image: TJpegImage; Password: string; Dest: TMemoryStream);
function DecryptFileToStream(FileName: string; Password: string; Stream: TStream): Boolean;
function DecryptStreamToStream(Src, Dest: TStream; Password: string): Boolean;
procedure EnryptStreamV3(S, D: TStream; Password: string; Options: Integer; FileName: string; Progress: TFileProgress = nil);
function ValidPassInCryptStream(S: TStream; Password: String): Boolean;
function SaveNewStreamForEncryptedFile(FileName: string; Password: string; Stream: TStream): Integer;
implementation
procedure FatalSaveStream(S: TStream; OriginalFileName: string);
var
FileName: string;
function SaveToFile(FileName: string): Boolean;
var
FS: TFileStream;
begin
Result := False;
try
FS := TFileStream.Create(FileName, fmCreate);
try
S.Seek(0, soFromBeginning);
FS.CopyFrom(S, S.Size);
Result := True;
finally
F(FS);
end;
except
Exit;
end;
end;
begin
FileName := ExtractFilePath(OriginalFileName) + ExtractFileName(OriginalFileName) + '.dump';
if not SaveToFile(FileName) then
SaveToFile(GetTempFileName + '.crypt_dump');
end;
procedure FillCharArray(var CharAray: TFileNameUnicode; Str: string);
var
I: Integer;
begin
for I := 1 to Length(Str) do
CharAray[I - 1] := Str[I];
CharAray[Length(Str)] := #0;
end;
(*function CryptGraphicFileV1W(FileName: string; Password: AnsiString; Options: Integer;
const Info; Size: Cardinal): Boolean;
var
FS: TFileStream;
X: TByteArray;
GraphicHeader: TGraphicCryptFileHeader;
GraphicHeaderV1: TGraphicCryptFileHeaderV1;
FileCRC: Cardinal;
FA: Integer;
begin
Result := False;
TryOpenFSForRead(FS, FileName);
if FS = nil then
Exit;
try
SetLength(X, FS.Size);
FS.Read(GraphicHeader, SizeOf(GraphicHeader));
if GraphicHeader.ID = PhotoDBFileHeaderID then
Exit;
FS.Seek(0, soFromBeginning);
FS.Read(Pointer(X)^, FS.Size);
finally
FS.Free;
end;
FA := FileGetAttr(FileName);
ResetFileattributes(FileName, FA);
FS := TFileStream.Create(FileName, fmOpenWrite or fmCreate);
try
WriteCryptHeaderV1(FS, X, FileName, Password, Options, GraphicHeaderV1);
CryptArrayByteV1(X, GraphicHeaderV1.Magic, Password);
if Size > 0 then
FS.Write(Info, Size);
FS.Write(Pointer(X)^, Length(X));
finally
FS.Free;
end;
FileSetAttr(FileName, FA);
Result := True;
end;
procedure CryptArrayByteV1(X : TByteArray; Magic : Cardinal; Password : AnsiString);
var
I, LPass : Integer;
XCos: array [0 .. 1023] of Byte;
begin
{$IFOPT R+}
{$DEFINE CKRANGE}
{$R-}
{$ENDIF}
LPass := Length(Password);
for I := 0 to 1023 do
XCos[I] := Round(255 * Cos(TMagicByte(Magic)[I mod 4] + I));
for I := 0 to length(x) - 1 do
X[I] := X[I] xor (TMagicByte(Magic)[I mod 4] xor Byte
(Password[I mod LPass + 1])) xor XCos[I mod 1024];
{$IFDEF CKRANGE}
{$UNDEF CKRANGE}
{$R+}
{$ENDIF}
end;
procedure WriteCryptHeaderV1(Stream : TStream; X : TByteArray; FileName : AnsiString; Password : AnsiString; Options: Integer; var GraphicHeaderV1: TGraphicCryptFileHeaderV1);
var
FileCRC : Cardinal;
GraphicHeader: TGraphicCryptFileHeader;
begin
GraphicHeaderV1.CRCFileExists := Options = CRYPT_OPTIONS_SAVE_CRC;
if GraphicHeaderV1.CRCFileExists then
begin
CalcBufferCRC32(X, Length(X), FileCRC);
GraphicHeaderV1.CRCFile := FileCRC;
end;
Randomize;
GraphicHeaderV1.Magic := Random(High(Integer));
GraphicHeader.ID := PhotoDBFileHeaderID;
GraphicHeader.Version := 1;
GraphicHeader.DBVersion := 0;
Stream.Write(GraphicHeader, SizeOf(TGraphicCryptFileHeader));
GraphicHeaderV1.Version := 2; // !!!!!!!!!!!!!!!!!
GraphicHeaderV1.FileSize := Length(X);
CalcStringCRC32(Password, GraphicHeaderV1.PassCRC);
GraphicHeaderV1.TypeExtract := 0;
GraphicHeaderV1.CryptFileName := False;
FillCharArray(GraphicHeaderV1.CFileName, ExtractFileName(FileName));
GraphicHeaderV1.TypeFileNameExtract := 0;
CalcStringCRC32(AnsiLowerCase(FileName), GraphicHeaderV1.FileNameCRC);
GraphicHeaderV1.Displacement := 0;
Stream.Write(GraphicHeaderV1, SizeOf(TGraphicCryptFileHeaderV1));
end;*)
{procedure WriteCryptHeaderV2(Stream: TStream; Src: TStream; FileName: string; Password: string; Options: Integer;
var Seed: Binary);
var
FileCRC: Cardinal;
GraphicHeader: TEncryptedFileHeader;
GraphicHeaderV2: TGraphicCryptFileHeaderV2;
begin
FillChar(GraphicHeaderV2, SizeOf(GraphicHeaderV2), #0);
GraphicHeaderV2.CRCFileExists := Options = CRYPT_OPTIONS_SAVE_CRC;
if GraphicHeaderV2.CRCFileExists and (Src is TMemoryStream) then
begin
CalcBufferCRC32(TMemoryStream(Src).Memory, Src.Size, FileCRC);
GraphicHeaderV2.CRCFile := FileCRC;
end;
Randomize;
Seed := RandomBinary(16);
GraphicHeaderV2.Seed := ConvertSeed(Seed);
GraphicHeader.ID := PhotoDBFileHeaderID;
GraphicHeader.Version := 2;
GraphicHeader.DBVersion := 0;
Stream.Write(GraphicHeader, SizeOf(TEncryptedFileHeader));
GraphicHeaderV2.Version := 1;
GraphicHeaderV2.Algorith := ValidCipher(nil).Identity;
GraphicHeaderV2.FileSize := Src.Size;
CalcStringCRC32(Password, GraphicHeaderV2.PassCRC);
GraphicHeaderV2.TypeExtract := 0;
GraphicHeaderV2.CryptFileName := False;
FillCharArray(GraphicHeaderV2.CFileName, ExtractFileName(FileName));
GraphicHeaderV2.TypeFileNameExtract := 0;
CalcStringCRC32(AnsiLowerCase(FileName), GraphicHeaderV2.FileNameCRC);
GraphicHeaderV2.Displacement := 0;
Stream.Write(GraphicHeaderV2, SizeOf(TGraphicCryptFileHeaderV2));
end; }
procedure EnryptStreamV3(S, D: TStream; Password: string; Options: Integer; FileName: string; Progress: TFileProgress = nil);
var
Chipper: TDECCipherClass;
begin
Chipper := ValidCipher(nil);
EncryptStreamEx(S, D, Password, Chipper,
procedure(BytesTotal, BytesDone: Int64; var BreakOperation: Boolean)
begin
if Assigned(Progress) then
Progress(FileName, BytesTotal, BytesDone, BreakOperation)
end
);
end;
function CryptGraphicFileV3W(FileName: string; Password: string; Options: Integer; Progress: TFileProgress = nil): Integer;
var
FS: TFileStream;
MS: TMemoryStream;
FA: Integer;
GraphicHeader: TEncryptedFileHeader;
begin
MS := TMemoryStream.Create;
try
try
TryOpenFSForRead(FS, FileName, DelayReadFileOperation);
if FS = nil then
begin
Result := CRYPT_RESULT_ERROR_READING_FILE;
Exit;
end;
try
FS.Read(GraphicHeader, SizeOf(GraphicHeader));
if GraphicHeader.ID = PhotoDBFileHeaderID then
begin
Result := CRYPT_RESULT_ALREADY_CRYPT;
Exit;
end;
FS.Seek(0, SoFromBeginning);
MS.CopyFrom(Fs, FS.Size);
MS.Position := 0;
finally
F(FS);
end;
except
Result := CRYPT_RESULT_ERROR_READING_FILE;
Exit;
end;
FA := FileGetAttr(FileName);
ResetFileAttributes(FileName, FA);
try
FS := TFileStream.Create(FileName, FmOpenWrite or FmCreate);
try
try
EnryptStreamV3(MS, FS, Password, Options, FileName, Progress);
except
//if any error in this block - user can lost original data, so we had to save it in any case
FatalSaveStream(MS, FileName);
raise;
end;
finally
F(FS);
end;
except
Result := CRYPT_RESULT_ERROR_WRITING_FILE;
Exit;
end;
finally
F(MS);
end;
FileSetAttr(FileName, FA);
Result := CRYPT_RESULT_OK;
end;
procedure EncryptGraphicImage(Image: TJpegImage; Password: string; Dest: TMemoryStream);
var
MS: TMemoryStream;
ACipher: TDECCipherClass;
begin
MS := TMemoryStream.Create;
try
Image.SaveToStream(MS);
MS.Seek(0, soFromBeginning);
ACipher := ValidCipher(nil);
EncryptStreamEx(MS, Dest, Password, ACipher, nil);
finally
F(MS);
end;
end;
function CryptGraphicFileV3(FileName: string; Password: string; Options: Integer; Progress: TFileProgress = nil): Integer;
var
FileSize: Int64;
begin
if TActivationManager.Instance.IsDemoMode then
begin
FileSize := GetFileSize(FileName);
if FileSize > uConstants.LimitDemoVideoSize then
begin
TThread.Synchronize(nil,
procedure
begin
MessageBoxDB(0, TA('Please, activate the program to encrypt files larger than 1Gb!', 'System'), TA('Warning'), TD_BUTTON_OK, TD_ICON_WARNING);
end
);
Sleep(500);
Exit(CRYPT_RESULT_OK);
end;
end;
if IsGraphicFile(FileName) then
begin
//using memory
Result := CryptGraphicFileV3W(FileName, Password, Options, Progress);
//statistics
ProgramStatistics.EncryptionImageUsed;
end else
begin
//using temporary file
Result := TransparentEncryptFileEx(FileName, Password, nil, Progress);
//statistics
ProgramStatistics.EncryptionFileUsed;
end;
end;
function DeCryptGraphicFile(FileName: string; Password: String;
LoadFullRAW: Boolean = False; Page: Integer = 0): TGraphic;
var
Pages: Word;
begin
Result := DeCryptGraphicFileEx(FileName, Password, Pages, LoadFullRAW, Page);
end;
function DecryptStream(Stream: TStream; GraphicHeader: TEncryptedFileHeader;
Password: string; MS: TStream): Boolean;
var
AnsiPassword: AnsiString;
FileCRC, CRC: Cardinal;
I, LPass: Integer;
XCos: array [0 .. 1023] of Byte;
X: TByteArray;
GraphicHeaderV1: TGraphicCryptFileHeaderV1;
GraphicHeaderV2: TGraphicCryptFileHeaderV2;
GraphicHeaderEx1: TEncryptFileHeaderExV1;
Chipper: TDECCipherClass;
begin
Result := False;
if GraphicHeader.Version = ENCRYPT_FILE_VERSION_BASIC then
begin
AnsiPassword := AnsiString(Password);
Stream.Read(GraphicHeaderV1, SizeOf(TGraphicCryptFileHeaderV1));
CalcAnsiStringCRC32(AnsiPassword, CRC);
if GraphicHeaderV1.PassCRC <> CRC then
Exit;
if GraphicHeaderV1.Displacement > 0 then
Stream.Seek(GraphicHeaderV1.Displacement, soCurrent);
SetLength(X, GraphicHeaderV1.FileSize);
Stream.Read(Pointer(X)^, GraphicHeaderV1.FileSize);
LPass := Length(AnsiPassword);
if GraphicHeaderV1.Version = 1 then
begin
for I := 0 to Length(X) - 1 do
X[I] := X[I] xor (TMagicByte(GraphicHeaderV1.Magic)[i mod 4] xor Byte(AnsiPassword[I mod LPass + 1]));
end;
if GraphicHeaderV1.Version = 2 then
begin
{$IFOPT R+}
{$DEFINE CKRANGE}
{$R-}
{$ENDIF}
for I := 0 to 1023 do
XCos[I] := Round(255 * Cos(TMagicByte(GraphicHeaderV1.Magic)[I mod 4] + I));
for I := 0 to length(X) - 1 do
X[I] := X[I] xor (TMagicByte(GraphicHeaderV1.Magic)[I mod 4] xor Byte
(AnsiPassword[I mod LPass + 1])) xor XCos[I mod 1024];
{$IFDEF CKRANGE}
{$UNDEF CKRANGE}
{$R+}
{$ENDIF}
end;
if GraphicHeaderV1.CRCFileExists then
begin
CalcBufferCRC32(X, length(X), FileCRC);
if GraphicHeaderV1.CRCFile <> FileCRC then
Exit;
end;
MS.Write(Pointer(X)^, Length(X));
Result := True;
end else if GraphicHeader.Version = ENCRYPT_FILE_VERSION_STRONG then
begin
StrongCryptInit;
Stream.Read(GraphicHeaderV2, SizeOf(TGraphicCryptFileHeaderV2));
CalcStringCRC32(Password, CRC);
if GraphicHeaderV2.PassCRC <> CRC then
Exit;
if GraphicHeaderV2.Displacement > 0 then
Stream.Seek(GraphicHeaderV2.Displacement, soCurrent);
Chipper := CipherByIdentity(GraphicHeaderV2.Algorith);
if Chipper <> nil then
begin
DeCryptStreamV2(Stream, MS, Password, SeedToBinary(GraphicHeaderV2.Seed), GraphicHeaderV2.FileSize, Chipper);
Result := True;
end;
end else if GraphicHeader.Version = ENCRYPT_FILE_VERSION_TRANSPARENT then
begin
StrongCryptInit;
Stream.Read(GraphicHeaderEx1, SizeOf(TEncryptFileHeaderExV1));
CalcStringCRC32(Password, CRC);
if GraphicHeaderEx1.PassCRC <> CRC then
Exit;
if GraphicHeaderEx1.Displacement > 0 then
Stream.Seek(GraphicHeaderEx1.Displacement, soCurrent);
Chipper := CipherByIdentity(GraphicHeaderEx1.Algorith);
if Chipper <> nil then
begin
Result := DecryptStreamEx(Stream, MS, Password, SeedToBinary(GraphicHeaderEx1.Seed), GraphicHeaderEx1.FileSize, Chipper, GraphicHeaderEx1.BlockSize32k);
end;
end;
end;
function DecryptGraphicFileToStream(FileName, Password: string; S: TStream): Boolean;
var
FS: TFileStream;
GraphicHeader: TEncryptedFileHeader;
begin
Result := False;
TryOpenFSForRead(FS, FileName, DelayReadFileOperation);
if FS = nil then
Exit;
try
FS.Read(GraphicHeader, SizeOf(TEncryptedFileHeader));
if GraphicHeader.ID <> PhotoDBFileHeaderID then
Exit;
if not DecryptStream(FS, GraphicHeader, Password, S) then
Exit;
S.Seek(0, soFromBeginning);
Result := True;
finally
F(FS);
end;
end;
function DecryptStreamToStream(Src, Dest: TStream; Password: string): Boolean;
var
GraphicHeader: TEncryptedFileHeader;
begin
Result := False;
Src.Read(GraphicHeader, SizeOf(TEncryptedFileHeader));
if GraphicHeader.ID <> PhotoDBFileHeaderID then
Exit;
if not DecryptStream(Src, GraphicHeader, Password, Dest) then
Exit;
Dest.Seek(0, soFromBeginning);
Result := True;
end;
function DecryptFileToStream(FileName: string; Password: string; Stream: TStream): Boolean;
var
FS: TFileStream;
begin
Result := False;
TryOpenFSForRead(FS, FileName, DelayReadFileOperation);
if FS = nil then
Exit;
try
Result := DecryptStreamToStream(FS, Stream, Password);
finally
F(FS);
end;
end;
function SaveNewStreamForEncryptedFile(FileName: String; Password: string; Stream: TStream): Integer;
var
FS: TFileStream;
MS: TMemoryStream;
ACipher: TDECCipherClass;
begin
Result := CRYPT_RESULT_UNDEFINED;
TryOpenFSForRead(FS, FileName, DelayReadFileOperation);
if FS = nil then
Exit;
try
if ValidPassInCryptStream(FS, Password) then
begin
F(FS);
MS := TMemoryStream.Create;
try
ACipher := ValidCipher(nil);
EncryptStreamEx(Stream, MS, Password, ACipher, nil);
try
FS := TFileStream.Create(FileName, fmOpenWrite or fmCreate);
try
try
MS.Seek(0, soFromBeginning);
FS.CopyFrom(MS, MS.Size);
except
//if any error in this block - user can lost original data, so we had to save it in any case
FatalSaveStream(MS, FileName);
raise;
end;
finally
F(FS);
end;
except
Result := CRYPT_RESULT_ERROR_WRITING_FILE;
Exit;
end;
finally
F(MS);
end;
end;
finally
F(FS);
end;
Result := CRYPT_RESULT_OK;
end;
//TODO: remove this function
function DeCryptGraphicFileEx(FileName: string; Password: string; var Pages: Word;
LoadFullRAW: Boolean = False; Page: Integer = 0): TGraphic;
var
FS: TFileStream;
MS: TMemoryStream;
GraphicHeader: TEncryptedFileHeader;
GraphicClass : TGraphicClass;
begin
Result := nil;
MS := TMemoryStream.Create;
try
TryOpenFSForRead(FS, FileName, DelayReadFileOperation);
if FS = nil then
Exit;
try
FS.Read(GraphicHeader, SizeOf(TEncryptedFileHeader));
if GraphicHeader.ID <> PhotoDBFileHeaderID then
Exit;
if not DecryptStream(FS, GraphicHeader, Password, MS) then
Exit;
MS.Seek(0, soFromBeginning);
GraphicClass := TFileAssociations.Instance.GetGraphicClass(ExtractFileExt(FileName));
if GraphicClass = nil then
Exit;
Result := GraphicClass.Create;
InitGraphic(Result);
if (Result is TRAWImage) then
(Result as TRAWImage).IsPreview := not LoadFullRAW;
if (Result is TTiffImage) then
begin
if Page = -1 then
(Result as TTiffImage).GetPagesCount(MS)
else
(Result as TTiffImage).LoadFromStreamEx(MS, Page);
Pages := (Result as TTiffImage).Pages;
end else
Result.LoadFromStream(MS);
finally
F(FS);
end;
finally
F(MS);
end;
end;
function ResetPasswordInGraphicFile(FileName, Password: string; Progress: TFileProgress = nil): Integer;
var
FS: TFileStream;
MS: TMemoryStream;
GraphicHeader: TEncryptedFileHeader;
FA: Integer;
begin
Result := CRYPT_RESULT_UNDEFINED;
//statistics
if IsGraphicFile(FileName) then
ProgramStatistics.DecryptionImageUsed
else
ProgramStatistics.DecryptionFileUsed;
MS := TMemoryStream.Create;
try
try
TryOpenFSForRead(FS, FileName, DelayReadFileOperation);
if FS = nil then
Exit;
try
FS.Read(GraphicHeader, SizeOf(TEncryptedFileHeader));
if GraphicHeader.ID <> PhotoDBFileHeaderID then
Exit;
if GraphicHeader.Version = ENCRYPT_FILE_VERSION_TRANSPARENT then
begin
F(FS);
Result := TransparentDecryptFileEx(FileName, Password, Progress);
Exit;
end;
if not DecryptStream(FS, GraphicHeader, Password, MS) then
Exit;
finally
F(FS);
end;
except
Result := CRYPT_RESULT_ERROR_READING_FILE;
Exit;
end;
FA := FileGetAttr(FileName);
ResetFileAttributes(FileName, FA);
try
FS := TFileStream.Create(FileName, fmOpenWrite or fmCreate);
try
try
MS.Seek(0, soFromBeginning);
FS.CopyFrom(MS, MS.Size);
except
//if any error in this block - user can lost original data, so we had to save it in any case
FatalSaveStream(MS, FileName);
raise;
end;
finally
F(FS);
end;
except
Result := CRYPT_RESULT_ERROR_WRITING_FILE;
Exit;
end;
finally
F(MS);
end;
FileSetAttr(FileName, FA);
Result := CRYPT_RESULT_OK;
end;
function ChangePasswordInGraphicFile(FileName: String; OldPass, NewPass: String): Integer;
var
FS: TFileStream;
MS: TMemoryStream;
GraphicHeader: TEncryptedFileHeader;
FA: Cardinal;
ACipher: TDECCipherClass;
begin
Result := CRYPT_RESULT_UNDEFINED;
MS := TMemoryStream.Create;
try
try
TryOpenFSForRead(FS, FileName, DelayReadFileOperation);
if FS = nil then
Exit;
try
FS.Read(GraphicHeader, SizeOf(TEncryptedFileHeader));
if GraphicHeader.ID <> PhotoDBFileHeaderID then
Exit;
if not DecryptStream(FS, GraphicHeader, OldPass, MS) then
Exit;
finally
F(FS);
end;
except
Result := CRYPT_RESULT_ERROR_READING_FILE;
Exit;
end;
FA := FileGetAttr(FileName);
ResetFileattributes(FileName, FA);
try
FS := TFileStream.Create(FileName, fmOpenWrite or fmCreate);
try
try
ACipher := ValidCipher(nil);
EncryptStreamEx(MS, FS, NewPass, ACipher, nil);
except
//if any error in this block - user can lost original data, so we had to save it in any case
FatalSaveStream(MS, FileName);
raise;
end;
finally
F(FS);
end;
except
Result := CRYPT_RESULT_ERROR_WRITING_FILE;
Exit;
end;
finally
F(MS);
end;
FileSetAttr(FileName, FA);
Result := CRYPT_RESULT_OK;
end;
function ValidPassInCryptGraphicFile(FileName, Password: String): Boolean;
var
FS: TFileStream;
CRC: Cardinal;
GraphicHeader: TEncryptedFileHeader;
GraphicHeaderV1: TGraphicCryptFileHeaderV1;
GraphicHeaderV2: TGraphicCryptFileHeaderV2;
GraphicHeaderEx1: TEncryptFileHeaderExV1;
begin
Result := False;
TryOpenFSForRead(FS, FileName, DelayReadFileOperation);
if FS = nil then
Exit;
try
FS.Read(GraphicHeader, SizeOf(TEncryptedFileHeader));
if GraphicHeader.ID <> PhotoDBFileHeaderID then
Exit;
if GraphicHeader.Version = ENCRYPT_FILE_VERSION_BASIC then
begin
FS.Read(GraphicHeaderV1, SizeOf(TGraphicCryptFileHeaderV1));
CalcAnsiStringCRC32(AnsiString(Password), CRC);
Result := GraphicHeaderV1.PassCRC = CRC;
end;
if GraphicHeader.Version = ENCRYPT_FILE_VERSION_STRONG then
begin
FS.Read(GraphicHeaderV2, SizeOf(TGraphicCryptFileHeaderV2));
CalcStringCRC32(Password, CRC);
Result := GraphicHeaderV2.PassCRC = CRC;
end;
if GraphicHeader.Version = ENCRYPT_FILE_VERSION_TRANSPARENT then
begin
FS.Read(GraphicHeaderEx1, SizeOf(GraphicHeaderEx1));
CalcStringCRC32(Password, CRC);
Result := GraphicHeaderEx1.PassCRC = CRC;
end;
finally
F(FS);
end;
end;
function ValidCryptGraphicStream(Stream: TStream): Boolean;
var
GraphicHeader: TEncryptedFileHeader;
Pos: Int64;
begin
Pos := Stream.Position;
Stream.Read(GraphicHeader, SizeOf(TEncryptedFileHeader));
Result := GraphicHeader.ID = PhotoDBFileHeaderID;
Stream.Seek(Pos, TSeekOrigin.soBeginning);
end;
function ValidCryptGraphicFile(FileName: String): Boolean;
var
FS: TFileStream;
begin
Result := False;
TryOpenFSForRead(FS, FileName, DelayReadFileOperation);
if FS = nil then
Exit;
try
Result := ValidCryptGraphicStream(FS);
finally
F(FS);
end;
end;
function GetPasswordCRCFromCryptGraphicFile(FileName: string): Cardinal;
var
FS: TFileStream;
GraphicHeader: TEncryptedFileHeader;
GraphicHeaderV1: TGraphicCryptFileHeaderV1;
GraphicHeaderV2: TGraphicCryptFileHeaderV2;
GraphicHeaderExV1: TEncryptFileHeaderExV1;
begin
Result := 0;
TryOpenFSForRead(FS, FileName, DelayReadFileOperation);
if FS = nil then
Exit;
try
FS.Read(GraphicHeader, SizeOf(TEncryptedFileHeader));
if GraphicHeader.ID = PhotoDBFileHeaderID then
begin
if GraphicHeader.Version = ENCRYPT_FILE_VERSION_BASIC then
begin
FS.Read(GraphicHeaderV1, SizeOf(GraphicHeaderV1));
Result := GraphicHeaderV1.PassCRC;
end;
if GraphicHeader.Version = ENCRYPT_FILE_VERSION_STRONG then
begin
FS.Read(GraphicHeaderV2, SizeOf(GraphicHeaderV2));
Result := GraphicHeaderV2.PassCRC;
end;
if GraphicHeader.Version = ENCRYPT_FILE_VERSION_TRANSPARENT then
begin
FS.Read(GraphicHeaderExV1, SizeOf(GraphicHeaderExV1));
Result := GraphicHeaderExV1.PassCRC;
end;
end;
finally
F(FS);
end;
end;
function CryptBlobStream(DF: TField; Password: String): Boolean;
var
FBS: TStream;
MS: TMemoryStream;
GraphicHeader: TEncryptedFileHeader;
ACipher: TDECCipherClass;
begin
Result := False;
MS := TMemoryStream.Create;
try
FBS := GetBlobStream(DF, bmRead);
try
FBS.Seek(0, soFromBeginning);
FBS.Read(GraphicHeader, SizeOf(GraphicHeader));
if GraphicHeader.ID = PhotoDBFileHeaderID then
Exit;
FBS.Seek(0, soFromBeginning);
finally
F(FBS);
end;
FBS := TADOBlobStream.Create(TBlobField(DF), bmWrite);
try
ACipher := ValidCipher(nil);
EncryptStreamEx(MS, FBS, Password, ACipher, nil);
finally
F(FBS);
end;
finally
F(MS);
end;
Result := True;
end;
function DeCryptBlobStreamJPG(DF: TField; Password: string; JPEG: TJpegImage) : Boolean;
var
FBS: TStream;
MS: TMemoryStream;
GraphicHeader: TEncryptedFileHeader;
begin
Result := False;
MS := TMemoryStream.Create;
try
FBS := GetBlobStream(DF, BmRead);
try
FBS.Seek(0, SoFromBeginning);
FBS.Read(GraphicHeader, SizeOf(TEncryptedFileHeader));
if GraphicHeader.ID <> PhotoDBFileHeaderID then
Exit;
if not DecryptStream(FBS, GraphicHeader, Password, MS) then
Exit;
MS.Seek(0, SoFromBeginning);
JPEG.LoadFromStream(MS);
finally
F(FBS);
end;
finally
F(MS);
end;
Result := True;
end;
function ValidCryptBlobStreamJPG(DF: TField): Boolean;
var
FBS: TStream;
GraphicHeader: TEncryptedFileHeader;
begin
FBS := GetBlobStream(DF, bmRead);
try
FBS.Seek(0, soFromBeginning);
FBS.Read(GraphicHeader, SizeOf(TEncryptedFileHeader));
Result := GraphicHeader.ID = PhotoDBFileHeaderID;
finally
F(FBS);
end;
end;
function ValidPassInCryptStream(S: TStream; Password: String): Boolean;
var
CRC: Cardinal;
GraphicHeader: TEncryptedFileHeader;
GraphicHeaderV1: TGraphicCryptFileHeaderV1;
GraphicHeaderV2: TGraphicCryptFileHeaderV2;
GraphicHeaderExV1: TEncryptFileHeaderExV1;
begin
Result := False;
S.Seek(0, soFromBeginning);
S.Read(GraphicHeader, SizeOf(TEncryptedFileHeader));
if GraphicHeader.ID <> PhotoDBFileHeaderID then
Exit;
if GraphicHeader.Version = ENCRYPT_FILE_VERSION_BASIC then
begin
S.Read(GraphicHeaderV1, SizeOf(TGraphicCryptFileHeaderV1));
CalcAnsiStringCRC32(AnsiString(Password), CRC);
Result := GraphicHeaderV1.PassCRC = CRC;
end;
if GraphicHeader.Version = ENCRYPT_FILE_VERSION_STRONG then
begin
S.Read(GraphicHeaderV2, SizeOf(TGraphicCryptFileHeaderV2));
CalcStringCRC32(Password, CRC);
Result := GraphicHeaderV2.PassCRC = CRC;
end;
if GraphicHeader.Version = ENCRYPT_FILE_VERSION_TRANSPARENT then
begin
S.Read(GraphicHeaderExV1, SizeOf(GraphicHeaderExV1));
CalcStringCRC32(Password, CRC);
Result := GraphicHeaderExV1.PassCRC = CRC;
end;
end;
function ValidPassInCryptBlobStreamJPG(DF: TField; Password: String): Boolean;
var
FBS: TStream;
begin
FBS := GetBlobStream(DF, bmRead);
try
Result := ValidPassInCryptStream(FBS, Password);
finally
F(FBS);
end;
end;
function ResetPasswordInCryptBlobStreamJPG(DF: TField; Password: String): Boolean;
var
FBS: TStream;
MS : TMemoryStream;
GraphicHeader: TEncryptedFileHeader;
begin
Result := False;
MS := TMemoryStream.Create;
try
FBS := GetBlobStream(DF, bmRead);
try
FBS.Read(GraphicHeader, SizeOf(TEncryptedFileHeader));
if GraphicHeader.ID <> PhotoDBFileHeaderID then
Exit;
if not DecryptStream(FBS, GraphicHeader, Password, MS) then
Exit;
finally
F(FBS);
end;
FBS := GetBlobStream(DF, bmWrite);
try
MS.Seek(0, soBeginning);
FBS.CopyFrom(MS, MS.Size);
finally
F(FBS);
end;
finally
F(MS);
end;
Result := True;
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, IPPeerClient,
FMX.Objects, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Edit, REST.Client,
REST.Authenticator.OAuth, Data.Bind.Components, Data.Bind.ObjectScope;
type
TForm1 = class(TForm)
RESTClient1: TRESTClient;
RESTResponse1: TRESTResponse;
RESTRequest1: TRESTRequest;
OAuth2Authenticator1: TOAuth2Authenticator;
edtName: TEdit;
edtEmail: TEdit;
btnLogin: TButton;
circle_photo: TCircle;
procedure RESTRequest1AfterExecute(Sender: TCustomRESTRequest);
procedure btnLoginClick(Sender: TObject);
private
{ Private declarations }
function LoadPhoto(url : string): TMemoryStream;
public
{ Public declarations }
FAccessToken : String;
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
uses
REST.Utils, System.JSON, Web.HTTPApp,System.Net.HttpClient,IdHTTP,
uFrmLogin;
procedure TForm1.btnLoginClick(Sender: TObject);
var
app_id, LURL : string;
begin
try
FAccessToken := '';
app_id := '1000017776848929'; // Your App ID here...
LURL := 'https://www.facebook.com/dialog/oauth'
+ '?client_id=' + URIEncode(app_id)
+ '&response_type=token'
+ '&scope=' + URIEncode('public_profile,email')
+ '&redirect_uri=' + URIEncode('https://www.facebook.com/connect/login_success.html');
// Abre tela de login do facebook...
try
FrmLogin := TFrmLogin.Create(nil);
FrmLogin.WebBrowser1.Navigate(LURL);
FrmLogin.ShowModal(
procedure(ModalResult: TModalResult)
begin
if FAccessToken <> '' then
begin
RESTRequest1.ResetToDefaults;
RESTClient1.ResetToDefaults;
RESTResponse1.ResetToDefaults;
RESTClient1.BaseURL := 'https://graph.facebook.com';
RESTClient1.Authenticator := OAuth2Authenticator1;
RESTRequest1.Resource := 'me?fields=first_name,last_name,email,picture.height(150)';
OAuth2Authenticator1.AccessToken := FAccessToken;
RESTRequest1.Execute;
end;
end);
finally
end;
except on e:exception do
showmessage(e.Message);
end;
end;
function TForm1.LoadPhoto(url : string): TMemoryStream;
var
MS : TMemoryStream;
photo: TBitmap;
http : THTTPClient;
begin
MS := TMemoryStream.Create;
http := THTTPClient.Create;
photo := TBitmap.Create;
try
try
http.Get(url, MS);
except on e: EIdHTTPProtocolException do
begin
if e.ErrorCode = 404 then
begin
// url not found
showmessage('Not found');
end
else
begin
// error.
showmessage('Error...');
end;
end;
end;
MS.Position := 0;
Result := MS;
finally
photo.Free;
end;
end;
procedure TForm1.RESTRequest1AfterExecute(Sender: TCustomRESTRequest);
var
LJsonObj : TJSONObject;
LElements: TJSONValue;
msg, url_photo, name, email, user_id : string;
MS: TMemoryStream;
begin
try
msg := '';
FAccessToken := '';
// Valid JSON
if Assigned(RESTResponse1.JSONValue) then
msg := RESTResponse1.JSONValue.ToString;
// Extract JSON fields
LJsonObj := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(msg), 0) as TJSONObject;
try
user_id := HTMLDecode(StringReplace(TJSONObject(LJsonObj).Get('id').JsonValue.ToString, '"', '', [rfReplaceAll]));
except
end;
try
email := StringReplace(TJSONObject(LJsonObj).Get('email').JsonValue.ToString, '"', '', [rfReplaceAll]);
except
end;
try
// First Name
name := StringReplace(TJSONObject(LJsonObj).Get('first_name').JsonValue.ToString, '"', '', [rfReplaceAll]);
except
end;
try
// Last Name
name := name + ' ' + StringReplace(TJSONObject(LJsonObj).Get('last_name').JsonValue.ToString, '"', '', [rfReplaceAll]);
except
end;
try
LElements := TJSONObject(TJSONObject(LJsonObj).Get('picture').JsonValue).Get('data').JsonValue;
url_photo := StringReplace(TJSONObject(LElements).Get('url').JsonValue.ToString, '"', '', [rfReplaceAll]);
except
end;
// Download Photo
try
MS := TMemoryStream.Create;
MS := LoadPhoto(url_photo);
circle_photo.Fill.Bitmap.Bitmap.LoadFromStream(MS);
except
showmessage('Error');
end;
edtName.Text := name;
edtEmail.Text := email;
except
end;
end;
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* 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.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFBaseScopedWrapper;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
type
TCEFBaseScopedWrapperRef = class
protected
FData: Pointer;
public
constructor Create(data: Pointer); virtual;
function Wrap: Pointer;
end;
implementation
constructor TCEFBaseScopedWrapperRef.Create(data: Pointer);
begin
inherited Create;
FData := data;
end;
function TCEFBaseScopedWrapperRef.Wrap: Pointer;
begin
Result := FData;
end;
end.
|
unit versionInfoUnit;
interface
const
VI_MAJOR_VERSION = 1;
VI_MINOR_VERSION = 2;
VI_RELEASE = 3;
VI_BUILD = 4;
VI_COMPANY_NAME = 1;
VI_FILE_DESCRIPTION = 2;
VI_FILE_VERSION = 3;
VI_INTERNAL_NAME = 4;
VI_LEGAL_COPYRIGHT = 5;
VI_ORIGINAL_FILENAME = 6;
VI_PRODUCT_NAME = 7;
VI_PRODUCT_VERSION = 8;
VI_COMMENTS = 9;
VI_LEGAL_TRADEMARKS = 10;
type
TVersionInfo = class
private
iDataSize : Integer;
pData : Pointer;
function iGetVersionInfo(Index : Integer) : Integer;
function sGetVersionInfo(Index : Integer) : String;
function GetVersionDateTime : TDateTime;
public
constructor Create;
constructor CreateFile(FileName : String);
destructor Destroy; override;
function GetVersionString(Key : String): String;
property MajorVersion : Integer index VI_MAJOR_VERSION read iGetVersionInfo;
property MinorVersion : Integer index VI_MINOR_VERSION read iGetVersionInfo;
property Release : Integer index VI_RELEASE read iGetVersionInfo;
property Build : Integer index VI_BUILD read iGetVersionInfo;
property DateTime : TDateTime read GetVersionDateTime;
property CompanyName : String index VI_COMPANY_NAME read sGetVersionInfo;
property FileDescription : String index VI_FILE_DESCRIPTION read sGetVersionInfo;
property FileVersion : String index VI_FILE_VERSION read sGetVersionInfo;
property InternalName : String index VI_INTERNAL_NAME read sGetVersionInfo;
property LegalCopyright : String index VI_LEGAL_COPYRIGHT read sGetVersionInfo;
property OriginalFilename : String index VI_ORIGINAL_FILENAME read sGetVersionInfo;
property ProductName : String index VI_PRODUCT_NAME read sGetVersionInfo;
property ProductVersion : String index VI_PRODUCT_VERSION read sGetVersionInfo;
property Comments : String index VI_COMMENTS read sGetVersionInfo;
property LegalTrademarks : String index VI_LEGAL_TRADEMARKS read sGetVersionInfo;
end;
function GetAppVersion : String;
var
VersionInfo : TVersionInfo = NIL;
implementation
uses
Windows, SysUtils;
function GetAppVersion : String;
var vi: TVersionInfo;
begin
vi := TVersionInfo.Create;
try
result:=(Format('%d.%d.%d.%d', [vi.MajorVersion, vi.MinorVersion, vi.Release, vi.Build]));
finally
vi.Free;
end;
end;
function TVersionInfo.iGetVersionInfo(Index: Integer): Integer;
var
FixedFileInfo : PVSFixedFileInfo;
BufferLen : Cardinal;
begin
Result := -1;
if iDataSize > 0 then begin
VerQueryValue(pData, '\', Pointer(FixedFileInfo), BufferLen);
with FixedFileInfo^ do
case Index of
VI_MAJOR_VERSION : Result := HiWord(dwFileVersionMS);
VI_MINOR_VERSION : Result := LoWord(dwFileVersionMS);
VI_RELEASE : Result := HiWord(dwFileVersionLS);
VI_BUILD : Result := LoWord(dwFileVersionLS);
end;
end;
end;
function TVersionInfo.GetVersionString(Key: String): String;
var
BufferLen : Cardinal;
Buffer : PChar;
P : Pointer;
S : String;
begin
Result := '';
if iDataSize > 0 then begin
VerQueryValue(pData, '\VarFileInfo\Translation', P, BufferLen);
S := Format('\StringFileInfo\%.4x%.4x\%s',
[LoWord(Integer(P^)), HiWord(Integer(P^)), Key]);
if VerQueryValue(pData, PChar(S), Pointer(Buffer), BufferLen) then
Result := StrPas(Buffer);
end;
end;
function TVersionInfo.GetVersionDateTime: TDateTime;
var
FixedFileInfo : PVSFixedFileInfo;
BufferLen : Cardinal;
FileTime : TFileTime;
SystemTime : TSystemTime;
begin
Result := 0;
if iDataSize > 0 then begin
VerQueryValue(pData, '\', Pointer(FixedFileInfo), BufferLen);
with FixedFileInfo^ do begin
FileTime.dwLowDateTime := dwFileDateLS;
FileTime.dwHighDateTime := dwFileDateMS;
FileTimeToSystemTime(FileTime, SystemTime);
with SystemTime do
Result := EncodeDate(wYear, wMonth, wDay) +
EncodeTime(wHour, wMinute, wSecond, wMilliSeconds);
end;
end;
end;
function TVersionInfo.sGetVersionInfo(Index : Integer): String;
var
KeyName : String;
begin
Result := '';
case Index of
VI_COMPANY_NAME : KeyName := 'CompanyName';
VI_FILE_DESCRIPTION : KeyName := 'FileDescription';
VI_FILE_VERSION : KeyName := 'FileVersion';
VI_INTERNAL_NAME : KeyName := 'InternalName';
VI_LEGAL_COPYRIGHT : KeyName := 'LegalCopyright';
VI_ORIGINAL_FILENAME : KeyName := 'OriginalFilename';
VI_PRODUCT_NAME : KeyName := 'ProductName';
VI_PRODUCT_VERSION : KeyName := 'ProductVersion';
VI_COMMENTS : KeyName := 'Comments';
VI_LEGAL_TRADEMARKS : KeyName := 'LegalTrademarks';
end;
Result := GetVersionString(KeyName);
end;
constructor TVersionInfo.Create;
var
BufferLen : Cardinal;
begin
inherited;
iDataSize := GetFileVersionInfoSize(PChar(ParamStr(0)), BufferLen);
if iDataSize > 0 then begin
GetMem(pData, iDataSize);
Win32Check(GetFileVersionInfo(PChar(ParamStr(0)), 0, iDataSize, pData));
end;
end;
constructor TVersionInfo.CreateFile(FileName: String);
var
BufferLen : Cardinal;
begin
inherited;
iDataSize := GetFileVersionInfoSize(PChar(FileName), BufferLen);
if iDataSize > 0 then begin
GetMem(pData, iDataSize);
Win32Check(GetFileVersionInfo(PChar(FileName), 0, iDataSize, pData));
end;
end;
destructor TVersionInfo.Destroy;
begin
FreeMem(pData,iDataSize);
inherited;
end;
end.
|
unit DP.TrackPoints;
//------------------------------------------------------------------------------
// !!! *** это не подноценый класс данных, а очень ограниченный *** !!!
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
interface
uses
SysUtils,
DP.Root,
Geo.Pos,
ZConnection, ZDataset,
Ils.MySql.Conf;
//------------------------------------------------------------------------------
type
//------------------------------------------------------------------------------
//! МИКРО-класс данных точек трека
//------------------------------------------------------------------------------
TTrackPoint = class(TDataObj)
private
FIMEI: Int64;
FDTMark: TDateTime;
FLatitude: Double;
FLongitude: Double;
protected
//!
function GetDTMark(): TDateTime; override;
public
constructor Create(
const IMEI: Int64;
const DTMark: TDateTime;
const Latitude: Double;
const Longitude: Double
); overload;
constructor Create(
Source: TTrackPoint
); overload;
function Clone(): IDataObj; override;
property IMEI: Int64 read FIMEI;
property Latitude: Double read FLatitude;
property Longitude: Double read FLongitude;
end;
//------------------------------------------------------------------------------
//! МИКРО-класс кэша точек трека
//------------------------------------------------------------------------------
TCacheTrackPoint = class(TCacheRoot)
protected
//! вставить запись в БД
procedure ExecDBInsert(
const AObj: IDataObj
); override;
//! обновить запись в БД
procedure ExecDBUpdate(
const AObj: IDataObj
); override;
//! преобразователь из записи БД в объект
function MakeObjFromReadReq(
const AQuery: TZQuery
): IDataObj; override;
public
constructor Create(
const ReadConnection: TZConnection;
const WriteConnection: TZConnection;
const IMEI: Int64;
const MaxKeepCount: Integer;
const LoadDelta: Double
);
end;
//------------------------------------------------------------------------------
//! класс списка кэшей точек трека
//------------------------------------------------------------------------------
TTrackPointDictionary = TCacheDictionaryRoot<Int64>;
//------------------------------------------------------------------------------
implementation
//------------------------------------------------------------------------------
// TClassTrackPoint
//------------------------------------------------------------------------------
constructor TTrackPoint.Create(
const IMEI: Int64;
const DTMark: TDateTime;
const Latitude: Double;
const Longitude: Double
);
begin
inherited Create();
//
FIMEI := IMEI;
FDTMark := DTMark;
FLatitude := Latitude;
FLongitude := Longitude;
end;
constructor TTrackPoint.Create(
Source: TTrackPoint
);
begin
inherited Create();
//
FIMEI := Source.IMEI;
FDTMark := Source.DTMark;
FLatitude := Source.Latitude;
FLongitude := Source.Longitude;
end;
function TTrackPoint.Clone(): IDataObj;
begin
Result := TTrackPoint.Create(Self);
end;
function TTrackPoint.GetDTMark(): TDateTime;
begin
Result := FDTMark;
end;
//------------------------------------------------------------------------------
// TCacheTrackPoint
//------------------------------------------------------------------------------
constructor TCacheTrackPoint.Create(
const ReadConnection: TZConnection;
const WriteConnection: TZConnection;
const IMEI: Int64;
const MaxKeepCount: Integer;
const LoadDelta: Double
);
const
CSQLReadRange = 'SELECT IMEI, DT, Latitude, Longitude'
+ ' FROM track'
+ ' WHERE IMEI = :imei'
+ ' AND DT >= :dt_from'
+ ' AND DT <= :dt_to';
CSQLReadBefore = 'SELECT IMEI, DT, Latitude, Longitude'
+ ' FROM track'
+ ' WHERE IMEI = :imei'
+ ' AND DT < :dt'
+ ' ORDER BY DT DESC'
+ ' LIMIT 1';
CSQLReadAfter = 'SELECT IMEI, DT, Latitude, Longitude'
+ ' FROM track'
+ ' WHERE IMEI = :imei'
+ ' AND DT > :dt'
+ ' ORDER BY DT'
+ ' LIMIT 1';
CSQLInsert = 'NI';
CSQLUpdate = 'NI';
CSQLDeleteRange = 'NI';
CSQLLastPresentDT = 'SELECT MAX(DT) AS DT'
+ ' FROM track'
+ ' WHERE IMEI = :imei';
//------------------------------------------------------------------------------
begin
inherited Create(
ReadConnection, WriteConnection, False, MaxKeepCount, LoadDelta,
CSQLReadRange, CSQLReadBefore, CSQLReadAfter, CSQLInsert, CSQLUpdate, CSQLDeleteRange, CSQLLastPresentDT
);
//
FQueryReadRange.ParamByName('imei').AsLargeInt := IMEI;
FQueryReadBefore.ParamByName('imei').AsLargeInt := IMEI;
FQueryReadAfter.ParamByName('imei').AsLargeInt := IMEI;
FQueryLastPresentDT.ParamByName('imei').AsLargeInt := IMEI;
end;
procedure TCacheTrackPoint.ExecDBInsert(
const AObj: IDataObj
);
begin
// with (AObj as TClassTrackPoint), FQueryInsert do
// begin
// Active := False;
// ParamByName('dt').AsDateTime := DTMark;
// ParamByName('Latitude').AsFloat := Latitude;
// ParamByName('Longitude').AsFloat := Longitude;
// ExecSQL();
// end;
end;
procedure TCacheTrackPoint.ExecDBUpdate(
const AObj: IDataObj
);
begin
// with (AObj as TClassTrackPoint), FQueryUpdate do
// begin
// Active := False;
// ParamByName('dt').AsDateTime := DTMark;
// ParamByName('Latitude').AsFloat := Latitude;
// ParamByName('Longitude').AsFloat := Longitude;
// ExecSQL();
// end;
end;
function TCacheTrackPoint.MakeObjFromReadReq(
const AQuery: TZQuery
): IDataObj;
begin
with AQuery do
begin
Result := TTrackPoint.Create(
FieldByName('IMEI').AsLargeInt,
FieldByName('DT').AsDateTime,
FieldByName('Latitude').AsFloat,
FieldByName('Longitude').AsFloat
);
end;
end;
end.
|
unit UDConnect;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, UCrpe32;
type
TCrpeConnectDlg = class(TForm)
pnlConnect1: TPanel;
lblCServerName: TLabel;
lblCDatabaseName: TLabel;
lblCUserID: TLabel;
lblCPassword: TLabel;
editServerName: TEdit;
editDatabaseName: TEdit;
editUserID: TEdit;
editPassword: TEdit;
cbPropagate: TCheckBox;
btnOk: TButton;
btnCancel: TButton;
btnClear: TButton;
btnTest: TButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure btnTestClick(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure editServerNameChange(Sender: TObject);
procedure editUserIDChange(Sender: TObject);
procedure editPasswordChange(Sender: TObject);
procedure editDatabaseNameChange(Sender: TObject);
procedure cbPropagateClick(Sender: TObject);
procedure UpdateConnect;
procedure btnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure InitializeControls(OnOff: boolean);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
rServerName : string;
rUserID : string;
rPassword : string;
rDatabaseName : string;
rPropagate : boolean;
end;
var
CrpeConnectDlg: TCrpeConnectDlg;
bConnect : boolean;
implementation
{$R *.DFM}
uses UCrpeUtl;
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpeConnectDlg.FormCreate(Sender: TObject);
begin
LoadFormPos(Self);
btnOk.Tag := 1;
btnCancel.Tag := 1;
bConnect := True;
end;
{------------------------------------------------------------------------------}
{ FormShow }
{------------------------------------------------------------------------------}
procedure TCrpeConnectDlg.FormShow(Sender: TObject);
begin
{Store VCL settings}
rServerName := Cr.Connect.ServerName;
rUserID := Cr.Connect.UserID;
rPassword := Cr.Connect.Password;
rDatabaseName := Cr.Connect.DatabaseName;
rPropagate := Cr.Connect.Propagate;
UpdateConnect;
end;
{------------------------------------------------------------------------------}
{ UpdateConnect }
{------------------------------------------------------------------------------}
procedure TCrpeConnectDlg.UpdateConnect;
var
OnOff : boolean;
begin
{Enable/Disable controls}
OnOff := not IsStrEmpty(Cr.ReportName);
InitializeControls(OnOff);
if OnOff then
begin
editServerName.Text := Cr.Connect.ServerName;
editUserID.Text := Cr.Connect.UserID;
editPassword.Text := Cr.Connect.Password;
editDatabaseName.Text := Cr.Connect.DatabaseName;
cbPropagate.Checked := Cr.Connect.Propagate;
end;
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpeConnectDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TCheckBox then
TCheckBox(Components[i]).Enabled := OnOff;
if Components[i] is TEdit then
begin
TEdit(Components[i]).Text := '';
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ editServerNameChange }
{------------------------------------------------------------------------------}
procedure TCrpeConnectDlg.editServerNameChange(Sender: TObject);
begin
Cr.Connect.ServerName := editServerName.Text;
end;
{------------------------------------------------------------------------------}
{ editUserIDChange }
{------------------------------------------------------------------------------}
procedure TCrpeConnectDlg.editUserIDChange(Sender: TObject);
begin
Cr.Connect.UserID := editUserID.Text;
end;
{------------------------------------------------------------------------------}
{ editPasswordChange }
{------------------------------------------------------------------------------}
procedure TCrpeConnectDlg.editPasswordChange(Sender: TObject);
begin
Cr.Connect.Password := editPassword.Text;
end;
{------------------------------------------------------------------------------}
{ editDatabaseNameChange }
{------------------------------------------------------------------------------}
procedure TCrpeConnectDlg.editDatabaseNameChange(Sender: TObject);
begin
Cr.Connect.DatabaseName := editDatabaseName.Text;
end;
{------------------------------------------------------------------------------}
{ cbPropagateClick }
{------------------------------------------------------------------------------}
procedure TCrpeConnectDlg.cbPropagateClick(Sender: TObject);
begin
Cr.Connect.Propagate := cbPropagate.Checked;
end;
{------------------------------------------------------------------------------}
{ btnTestClick }
{------------------------------------------------------------------------------}
procedure TCrpeConnectDlg.btnTestClick(Sender: TObject);
begin
if Cr.Connect.Test then
MessageDlg('Connect Succeeded!', mtInformation, [mbOk], 0)
else
MessageDlg('Connect Failed.' + Chr(10) + Cr.LastErrorString, mtError, [mbOk], 0);
end;
{------------------------------------------------------------------------------}
{ btnClearClick }
{------------------------------------------------------------------------------}
procedure TCrpeConnectDlg.btnClearClick(Sender: TObject);
begin
Cr.Connect.Clear;
UpdateConnect;
end;
{------------------------------------------------------------------------------}
{ btnOkClick }
{------------------------------------------------------------------------------}
procedure TCrpeConnectDlg.btnOkClick(Sender: TObject);
begin
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ btnCancelClick }
{------------------------------------------------------------------------------}
procedure TCrpeConnectDlg.btnCancelClick(Sender: TObject);
begin
{Restore Settings}
Cr.Connect.ServerName := rServerName;
Cr.Connect.UserID := rUserID;
Cr.Connect.Password := rPassword;
Cr.Connect.DatabaseName := rDatabaseName;
Cr.Connect.Propagate := rPropagate;
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose }
{------------------------------------------------------------------------------}
procedure TCrpeConnectDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
bConnect := False;
Release;
end;
end.
|
unit main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
MaskEdit, Spin;
type
{ Tpane }
Tpane = class(TForm)
button_help: TButton;
button_start: TButton;
check_spin: TCheckBox;
edit_isbn: TMaskEdit;
label_isbn: TLabel;
label_land: TLabel;
spin_land: TSpinEdit;
procedure button_startClick(Sender: TObject);
private
public
end;
var
pane: Tpane;
implementation
{$R *.lfm}
(**
gets the country of the isbn.
returns a new value from the spin if its enabled
**)
function getLand(isbn : String):Integer;
begin
getLand := 123456789;
IF pane.check_spin.Checked THEN
begin
getLand := pane.spin_land.Value;
end ELSE
begin
try
getLand := StrToInt(Copy(isbn, 5, 1));
finally
IF getLand = 123456789 THEN begin
getLand := 3;
ShowMessage('Convert Error at getLand --> overlook the input');
end;
end
end;
end;
{ Tpane }
procedure Tpane.button_startClick(Sender: TObject);
begin
ShowMessage(IntToStr(getLand(edit_isbn.Text)));
end;
end.
|
unit uWPDClasses;
interface
uses
Generics.Collections,
System.Classes,
System.SysUtils,
System.Math,
System.SyncObjs,
Winapi.Windows,
Winapi.ActiveX,
Vcl.Imaging.Jpeg,
Vcl.Imaging.pngimage,
Vcl.Graphics,
uGraphicUtils,
uConstants,
uMemory,
uPortableClasses,
uWPDInterfaces,
uBitmapUtils,
uJpegUtils,
GIFImage;
const
MAX_RESOURCE_WAIT_TIME = 60000; //60 sec to wait maximum
RESOURCE_RETRY_TIME = 100;
E_RESOURCE_IN_USE = -2147024726;// (800700aa)': Automation Error. The requested resource is in use.
E_NOT_FOUND = -2147023728;
type
TWPDDeviceManager = class;
TWPDDevice = class;
TWPDItem = class(TInterfacedObject, IPDItem)
private
FDevice: TWPDDevice;
FIDevice: IPDevice;
FItemType: TPortableItemType;
FName: string;
FItemKey: string;
FErrorCode: HRESULT;
FFullSize, FFreeSize: Int64;
FItemDate: TDateTime;
FDeviceID: string;
FDeviceName: string;
FWidth: Integer;
FHeight: Integer;
FLoadOnlyName: Boolean;
FVisible: Boolean;
procedure ErrorCheck(Code: HRESULT);
procedure TransferContent(ResourceID: TGUID; Stream: TStream; out ResourceFormat: TGUID;
CallBack: TPDProgressCallBack);
procedure ReadProperties;
public
constructor Create(ADevice: TWPDDevice; AItemKey: string; LoadOnlyName: Boolean = False);
function GetErrorCode: HRESULT;
function GetItemType: TPortableItemType;
function GetName: string;
function GetItemKey: string;
function GetFullSize: Int64;
function GetFreeSize: Int64;
function GetItemDate: TDateTime;
function GetDeviceID: string;
function GetDeviceName: string;
function GetWidth: Integer;
function GetHeight: Integer;
function GetIsVisible: Boolean;
function GetInnerInterface: IUnknown;
function ExtractPreview(var PreviewImage: TBitmap): Boolean;
function SaveToStream(S: TStream): Boolean;
function SaveToStreamEx(S: TStream; CallBack: TPDProgressCallBack): Boolean;
function Clone: IPDItem;
end;
TWPDDevice = class(TInterfacedObject, IPDevice)
private
FContent: IPortableDeviceContent;
FManager: TWPDDeviceManager;
FIManager: IPManager;
FDevice: IPortableDevice;
FErrorCode: HRESULT;
FDeviceID: string;
FName: string;
FPropertiesReaded: Boolean;
FBatteryStatus: Byte;
FDeviceType: TDeviceType;
procedure ErrorCheck(Code: HRESULT);
function GetContent: IPortableDeviceContent;
procedure InitProps;
procedure FillItemsCallBack(ParentKey: string; Packet: TList<IPDItem>; var Cancel: Boolean; Context: Pointer);
public
constructor Create(AManager: TWPDDeviceManager; Device: IPortableDevice);
function GetErrorCode: HRESULT;
function GetName: string;
function GetDeviceID: string;
function GetBatteryStatus: Byte;
function GetDeviceType: TDeviceType;
procedure FillItems(ItemKey: string; Items: TList<IPDItem>);
procedure FillItemsWithCallBack(ItemKey: string; CallBack: TFillItemsCallBack; Context: Pointer);
function GetItemByKey(ItemKey: string): IPDItem;
function GetItemByPath(Path: string): IPDItem;
function Delete(ItemKey: string): Boolean;
property Manager: TWPDDeviceManager read FManager;
property Content: IPortableDeviceContent read GetContent;
property Device: IPortableDevice read FDevice;
property DeviceID: string read GetDeviceID;
end;
TWPDDeviceManager = class(TInterfacedObject, IPManager)
private
FManager: IPortableDeviceManager;
FErrorCode: HRESULT;
procedure ErrorCheck(Code: HRESULT);
procedure FillDeviceCallBack(Packet: TList<IPDevice>; var Cancel: Boolean; Context: Pointer);
procedure FindDeviceByNameCallBack(Packet: TList<IPDevice>; var Cancel: Boolean; Context: Pointer);
procedure FindDeviceByIDCallBack(Packet: TList<IPDevice>; var Cancel: Boolean; Context: Pointer);
public
constructor Create;
function GetErrorCode: HRESULT;
procedure FillDevices(Devices: TList<IPDevice>);
procedure FillDevicesWithCallBack(CallBack: TFillDevicesCallBack; Context: Pointer);
function GetDeviceByName(DeviceName: string): IPDevice;
function GetDeviceByID(DeviceID: string): IPDevice;
property Manager: IPortableDeviceManager read FManager;
end;
TEventTargetInfo = class
public
EventTypes: TPortableEventTypes;
CallBack: TPortableEventCallBack;
end;
TEventDeviceInfo = class
public
DeviceID: string;
Device: IPortableDevice;
Cookie: string;
end;
TWPDDeviceEventCallback = class(TInterfacedObject, IPortableDeviceEventCallback)
public
function OnEvent(const pEventParameters: IPortableDeviceValues): HRESULT; stdcall;
end;
TWPDEventManager = class(TInterfacedObject, IPEventManager)
private
FSync: TCriticalSection;
FEventTargets: TList<TEventTargetInfo>;
FEventDevices: TList<TEventDeviceInfo>;
FDeviceCallBack: IPortableDeviceEventCallback;
procedure InvokeItem(EventType: TPortableEventType; DeviceID, ItemKey, ItemPath: string);
procedure UnregisterDevice(DeviceID: string);
procedure RegisterDevice(Device: TWPDDevice);
public
constructor Create;
destructor Destroy; override;
procedure RegisterNotification(EventTypes: TPortableEventTypes; CallBack: TPortableEventCallBack);
procedure UnregisterNotification(CallBack: TPortableEventCallBack);
end;
TFindDeviceContext = class(TObject)
public
Name: string;
Device: IPDevice;
end;
function WPDEventManager: TWPDEventManager;
implementation
var
//only one request to WIA at moment - limitation of WIA, looks like WPD has the same limitation
//http://msdn.microsoft.com/en-us/library/windows/desktop/ms630350%28v=vs.85%29.aspx
FEventManager: TWPDEventManager = nil;
FIEventManager: IPEventManager = nil;
function WPDEventManager: TWPDEventManager;
begin
if FEventManager = nil then
begin
FEventManager := TWPDEventManager.Create;
FIEventManager := FEventManager;
end;
Result := FEventManager;
end;
{ TWPDDeviceManager }
constructor TWPDDeviceManager.Create;
var
HR: HRESULT;
begin
FManager := nil;
FErrorCode := S_OK;
HR := CoCreateInstance(CLSID_PortableDeviceManager,
nil,
CLSCTX_INPROC_SERVER,
IID_PortableDeviceManager,
FManager);
ErrorCheck(HR);
end;
procedure TWPDDeviceManager.ErrorCheck(Code: HRESULT);
begin
if Failed(Code) then
FErrorCode := Code;
end;
procedure TWPDDeviceManager.FillDeviceCallBack(Packet: TList<IPDevice>;
var Cancel: Boolean; Context: Pointer);
begin
TList<IPDevice>(Context).AddRange(Packet);
end;
procedure TWPDDeviceManager.FillDevices(Devices: TList<IPDevice>);
begin
FillDevicesWithCallBack(FillDeviceCallBack, Devices);
end;
procedure TWPDDeviceManager.FillDevicesWithCallBack(CallBack: TFillDevicesCallBack; Context: Pointer);
var
HR: HRESULT;
PDISs: array of PWSTR;
DeviceIDCount: Cardinal;
I: Integer;
FDevice: IPortableDevice;
Key: _tagpropertykey;
ClientInformation: IPortableDeviceValues;
Device: TWPDDevice;
DevList: TList<IPDevice>;
Cancel: Boolean;
begin
if FManager = nil then
Exit;
Cancel := False;
DevList := TList<IPDevice>.Create;
try
repeat
HR := FManager.GetDevices(nil, @DeviceIDCount);
until E_RESOURCE_IN_USE <> HR;
if SUCCEEDED(HR) then
begin
SetLength(PDISs, DeviceIDCount);
repeat
HR := FManager.GetDevices(PLPWSTR(PDISs), @DeviceIDCount);
until E_RESOURCE_IN_USE <> HR;
if SUCCEEDED(HR) then
begin
for I := 0 to Integer(DeviceIDCount) - 1 do
begin
HR := CoCreateInstance(CLSID_PortableDevice{FTM},
nil,
CLSCTX_INPROC_SERVER,
IID_PortableDevice{FTM},
FDevice);
if SUCCEEDED(HR) then
begin
HR := CoCreateInstance(CLSID_PortableDeviceValues,
nil,
CLSCTX_INPROC_SERVER,
IID_PortableDeviceValues,
ClientInformation);
if SUCCEEDED(HR) then
begin
Key.fmtid := WPD_CLIENT_INFO;
Key.pid := 2;
HR := ClientInformation.SetStringValue(Key, PChar('Photo Database'));
if SUCCEEDED(HR) then
begin
Key.pid := 3;
ErrorCheck(ClientInformation.SetUnsignedIntegerValue(Key, MajorVersion));
Key.pid := 4;
ErrorCheck(ClientInformation.SetUnsignedIntegerValue(key, MinorVersion));
Key.pid := 5;
ErrorCheck(ClientInformation.SetUnsignedIntegerValue(key, 0)); //build number
end else
ErrorCheck(HR);
if Succeeded(HR) then
begin
repeat
HR := FDevice.Open(PWideChar(PDISs[I]), ClientInformation);
until E_RESOURCE_IN_USE <> HR;
//DEVICE IS READY FOR USING
if Succeeded(HR) then
begin
Device := TWPDDevice.Create(Self, FDevice);
if Device.GetDeviceType <> dtOther then
begin
DevList.Clear;
DevList.Add(Device);
CallBack(DevList, Cancel, Context);
if Cancel then
Break;
end else
F(Device);
end;
end;
end;
end;
end;
end;
end;
finally
F(DevList);
end;
end;
procedure TWPDDeviceManager.FindDeviceByIDCallBack(Packet: TList<IPDevice>;
var Cancel: Boolean; Context: Pointer);
var
Device: IPDevice;
C: TFindDeviceContext;
begin
C := TFindDeviceContext(Context);
for Device in Packet do
if AnsiUpperCase(Device.DeviceID) = AnsiUpperCase(C.Name) then
begin
C.Device := Device;
Cancel := True;
end;
end;
procedure TWPDDeviceManager.FindDeviceByNameCallBack(Packet: TList<IPDevice>;
var Cancel: Boolean; Context: Pointer);
var
Device: IPDevice;
C: TFindDeviceContext;
begin
C := TFindDeviceContext(Context);
for Device in Packet do
if AnsiUpperCase(Device.Name) = AnsiUpperCase(C.Name) then
begin
C.Device := Device;
Cancel := True;
end;
end;
function TWPDDeviceManager.GetDeviceByID(DeviceID: string): IPDevice;
var
Context: TFindDeviceContext;
begin
Context := TFindDeviceContext.Create;
try
Context.Name := DeviceID;
try
FillDevicesWithCallBack(FindDeviceByIDCallBack, Context);
finally
Result := Context.Device;
end;
finally
F(Context);
end;
end;
function TWPDDeviceManager.GetDeviceByName(DeviceName: string): IPDevice;
var
Context: TFindDeviceContext;
begin
Context := TFindDeviceContext.Create;
try
Context.Name := DeviceName;
try
FillDevicesWithCallBack(FindDeviceByNameCallBack, Context);
finally
Result := Context.Device;
end;
finally
F(Context);
end;
end;
function TWPDDeviceManager.GetErrorCode: HRESULT;
begin
Result := FErrorCode;
end;
{ TWPDDevice }
constructor TWPDDevice.Create(AManager: TWPDDeviceManager; Device: IPortableDevice);
var
HR: HRESULT;
cchFriendlyName: DWORD;
pszFriendlyName: PWChar;
pszDevID: PWChar;
begin
FDevice := Device;
FBatteryStatus := 255;
FDeviceType := dtOther;
FPropertiesReaded := False;
FContent := nil;
FName := DEFAULT_PORTABLE_DEVICE_NAME;
if FDevice = nil then
raise EInvalidOperation.Create('Device is null!');
FDevice := Device;
FManager := AManager;
FIManager := AManager;
repeat
HR := FDevice.GetPnPDeviceID(pszDevID);
until E_RESOURCE_IN_USE <> HR;
FDeviceID := pszDevID;
// First, pass NULL as the PWSTR return string parameter to get the total number
// of characters to allocate for the string value.
cchFriendlyName := 0;
repeat
HR := FManager.Manager.GetDeviceFriendlyName(PChar(FDeviceID), nil, @cchFriendlyName);
until E_RESOURCE_IN_USE <> HR;
// Second allocate the number of characters needed and retrieve the string value.
if (SUCCEEDED(HR) and (cchFriendlyName > 0)) then
begin
GetMem(pszFriendlyName, cchFriendlyName * SizeOf(WChar));
if (pszFriendlyName <> nil) then
begin
repeat
HR := FManager.Manager.GetDeviceFriendlyName(PChar(FDeviceID), pszFriendlyName, @cchFriendlyName);
until E_RESOURCE_IN_USE <> HR;
if (Failed(HR)) then
FName := DEFAULT_PORTABLE_DEVICE_NAME
else
FName := pszFriendlyName;
FreeMem(pszFriendlyName);
end else
FName := DEFAULT_PORTABLE_DEVICE_NAME;
end else
ErrorCheck(HR);
if FName = DEFAULT_PORTABLE_DEVICE_NAME then
begin
repeat
HR := FManager.Manager.GetDeviceDescription(PChar(FDeviceID), nil, @cchFriendlyName);
until E_RESOURCE_IN_USE <> HR;
// Second allocate the number of characters needed and retrieve the string value.
if (SUCCEEDED(HR) and (cchFriendlyName > 0)) then
begin
GetMem(pszFriendlyName, cchFriendlyName * SizeOf(WChar));
if (pszFriendlyName <> nil) then
begin
repeat
HR := FManager.Manager.GetDeviceDescription(PChar(FDeviceID), pszFriendlyName, @cchFriendlyName);
until E_RESOURCE_IN_USE <> HR;
if (Failed(HR)) then
FName := DEFAULT_PORTABLE_DEVICE_NAME
else
FName := pszFriendlyName;
FreeMem(pszFriendlyName);
end else
FName := DEFAULT_PORTABLE_DEVICE_NAME;
end else
ErrorCheck(HR);
end;
WPDEventManager.RegisterDevice(Self);
end;
function TWPDDevice.Delete(ItemKey: string): Boolean;
var
pObjectIDs: IPortableDevicePropVariantCollection;
ppResults: IPortableDevicePropVariantCollection;
HR: HRESULT;
pv: tag_inner_PROPVARIANT;
ObjID: PChar;
ppCapabilities: IPortableDeviceCapabilities;
Mode: Integer;
Command: _tagpropertykey;
ppOptions: IPortableDeviceValues;
key: _tagpropertykey;
BoolValue: Integer;
begin
Result := False;
//To see if recursive deletion is supported, call IPortableDeviceCapabilities::GetCommandOptions.
//If the retrieved IPortableDeviceValues interface contains a property value called
//WPD_OPTION_OBJECT_MANAGEMENT_RECURSIVE_DELETE_SUPPORTED with a boolVal value of True, the device supports recursive deletion.
Mode := PORTABLE_DEVICE_DELETE_NO_RECURSION;
HR := FDevice.Capabilities(ppCapabilities);
if Succeeded(HR) then
begin
Command.fmtid := WPD_CATEGORY_OBJECT_MANAGEMENT;
Command.pid := WPD_COMMAND_OBJECT_MANAGEMENT_DELETE_OBJECTS;
HR := ppCapabilities.GetCommandOptions(Command, ppOptions);
if Succeeded(HR) then
begin
key.fmtid := WPD_CATEGORY_OBJECT_MANAGEMENT;
key.pid := WPD_OPTION_OBJECT_MANAGEMENT_RECURSIVE_DELETE_SUPPORTED;
HR := ppOptions.GetBoolValue(key, BoolValue);
if Succeeded(HR) and (BoolValue = 1) then
Mode := PORTABLE_DEVICE_DELETE_WITH_RECURSION;
end;
end;
if Failed(HR) then
begin
ErrorCheck(HR);
Exit;
end;
HR := CoCreateInstance(CLSID_PortableDevicePropVariantCollection,
nil,
CLSCTX_INPROC_SERVER,
IID_PortableDevicePropVariantCollection,
pObjectIDs);
if Succeeded(HR) then
begin
HR := CoCreateInstance(CLSID_PortableDevicePropVariantCollection,
nil,
CLSCTX_INPROC_SERVER,
IID_PortableDevicePropVariantCollection,
ppResults);
if Succeeded(HR) then
begin
ObjID := SysAllocString(PChar(ItemKey));
try
pv.VT := VT_LPWSTR;
pv.__MIDL____MIDL_itf_PortableDeviceApi_0001_00000001.pwszVal := ObjID;
HR := pObjectIDs.Add(pv);
if Succeeded(HR) then
begin
HR := Content.Delete(Mode,
pObjectIDs,
ppResults);
Result := Succeeded(HR);
end;
finally
SysFreeString(ObjID);
end;
end;
end;
ErrorCheck(HR);
end;
procedure TWPDDevice.ErrorCheck(Code: HRESULT);
begin
if Failed(Code) then
FErrorCode := Code;
end;
procedure TWPDDevice.FillItems(ItemKey: string; Items: TList<IPDItem>);
begin
FillItemsWithCallBack(ItemKey, FillItemsCallBack, Items);
end;
procedure TWPDDevice.FillItemsCallBack(ParentKey: string;
Packet: TList<IPDItem>; var Cancel: Boolean; Context: Pointer);
begin
TList<IPDItem>(Context).AddRange(Packet);
end;
procedure TWPDDevice.FillItemsWithCallBack(ItemKey: string;
CallBack: TFillItemsCallBack; Context: Pointer);
const
NUM_OBJECTS_TO_REQUEST = 10;
var
HR: HRESULT;
cFetched: DWORD;
dwIndex: DWORD;
Cancel: Boolean;
EnumObjectIDs: IEnumPortableDeviceObjectIDs;
ObjectIDArray: array[0 .. NUM_OBJECTS_TO_REQUEST - 1] of PWSTR;
ObjectKey: string;
ItemList: TList<IPDItem>;
Item: IPDItem;
ParentPath: string;
begin
Cancel := False;
if ItemKey = '' then
ItemKey := WPD_DEVICE_OBJECT_ID;
ParentPath := PortableItemNameCache.GetPathByKey(FDeviceID, ItemKey);
ItemList := TList<IPDItem>.Create;
try
repeat
HR := Content.EnumObjects(0, // Flags are unused
PWideChar(ItemKey), // Starting from the passed in object
nil, // Filter is unused
EnumObjectIDs);
until E_RESOURCE_IN_USE <> HR;
// Loop calling Next() while S_OK is being returned.
while SUCCEEDED(HR) do
begin
repeat
HR := EnumObjectIDs.Next(NUM_OBJECTS_TO_REQUEST, // Number of objects to request on each NEXT call
@ObjectIDArray, // Array of PWSTR array which will be populated on each NEXT call
cFetched); // Number of objects written to the PWSTR array
until E_RESOURCE_IN_USE <> HR;
if cFetched = 0 then
Break;
if (SUCCEEDED(HR)) then
begin
// Traverse the results of the Next() operation and recursively enumerate
// Remember to free all returned object identifiers using CoTaskMemFree()
for dwIndex := 0 to cFetched - 1 do
begin
ObjectKey := string(ObjectIDArray[dwIndex]);
Item := TWPDItem.Create(Self, ObjectKey);
ItemList.Add(Item);
PortableItemNameCache.AddName(FDeviceID, Item.ItemKey, ItemKey, ParentPath + '\' + Item.Name);
CallBack(ItemKey, ItemList, Cancel, Context);
ItemList.Clear;
if Cancel then
Break;
end;
FreeList(ItemList, False);
end;
end;
finally
F(ItemList);
end;
end;
function TWPDDevice.GetBatteryStatus: Byte;
begin
InitProps;
Result := FBatteryStatus;
end;
function TWPDDevice.GetDeviceID: string;
begin
Result := FDeviceID;
end;
function TWPDDevice.GetDeviceType: TDeviceType;
begin
InitProps;
Result := FDeviceType;
end;
function TWPDDevice.GetErrorCode: HRESULT;
begin
Result := FErrorCode;
end;
function TWPDDevice.GetItemByKey(ItemKey: string): IPDItem;
begin
Result := TWPDItem.Create(Self, ItemKey);
end;
function TWPDDevice.GetItemByPath(Path: string): IPDItem;
var
ItemKey, CurrentPath: string;
HR: HRESULT;
pFilter: IPortableDeviceValues;
ppenum: IEnumPortableDeviceObjectIDs;
Key: _tagpropertykey;
cFetched: Cardinal;
ObjectID: PWSTR;
PathParts: TStringList;
I: Integer;
Item: IPDItem;
begin
ItemKey := PortableItemNameCache.GetKeyByPath(FDeviceID, Path);
if ItemKey = EMPTY_PATH then
begin
ItemKey := WPD_DEVICE_OBJECT_ID;
PathParts := TStringList.Create;
try
PathParts.Delimiter := '\';
PathParts.StrictDelimiter := True;
PathParts.DelimitedText := Path;
CurrentPath := '';
HR := CoCreateInstance(CLSID_PortableDeviceValues, nil, CLSCTX_INPROC_SERVER, IID_PortableDeviceValues, pFilter);
if Succeeded(HR) then
begin
for I := 0 to PathParts.Count - 1 do
begin
if PathParts[I] = '' then
Continue;
CurrentPath := CurrentPath + '\' + PathParts[I];
Key.fmtid := PKEY_GenericObj;
Key.pid := WPD_OBJECT_NAME;
HR := pFilter.SetStringValue(Key, PChar(PathParts[I]));
if Succeeded(HR) then
begin
repeat
HR := FContent.EnumObjects(0,
PChar(ItemKey),
pFilter, //not all devices support this feature
ppenum);
until E_RESOURCE_IN_USE <> HR;
while Succeeded(HR) do
begin
repeat
HR := ppenum.Next(1, // Number of objects to request on each NEXT call
@ObjectID, // Array of PWSTR array which will be populated on each NEXT call
cFetched); // Number of objects written to the PWSTR array
until E_RESOURCE_IN_USE <> HR;
if cFetched = 0 then
Break;
if Succeeded(HR) and (cFetched = 1) then
begin
Item := TWPDItem.Create(Self, string(ObjectID), True);
//check item name because filter can be ignored by device
if Item.GetName = PathParts[I] then
begin
PortableItemNameCache.AddName(FDeviceID, string(ObjectID), ItemKey, CurrentPath);
ItemKey := string(ObjectID);
Break;
end;
end;
end;
end;
end;
end;
finally
F(PathParts);
end;
end;
Result := GetItemByKey(ItemKey);
end;
function TWPDDevice.GetName: string;
begin
Result := FName;
end;
procedure TWPDDevice.InitProps;
var
HR: HRESULT;
ppProperties: IPortableDeviceProperties;
Key: _tagpropertykey;
PropertiesToRead: IPortableDeviceKeyCollection;
ppValues: IPortableDeviceValues;
V: Cardinal;
begin
if FPropertiesReaded then
Exit;
FPropertiesReaded := True;
HR := CoCreateInstance(CLSID_PortableDeviceKeyCollection, nil, CLSCTX_INPROC_SERVER, IID_PortableDeviceKeyCollection, PropertiesToRead);
if (SUCCEEDED(HR)) then
begin
repeat
HR := Content.Properties(ppProperties);
until E_RESOURCE_IN_USE <> HR;
end else
ErrorCheck(HR);
ErrorCheck(HR);
key.fmtid := PKEY_DeviceObj;
key.pid := WPD_DEVICE_POWER_LEVEL;
HR := PropertiesToRead.Add(key);
ErrorCheck(HR);
key.fmtid := PKEY_DeviceObj;
key.pid := WPD_DEVICE_TYPE;
HR := PropertiesToRead.Add(key);
ErrorCheck(HR);
// 3. Request the properties from the device.
repeat
HR := ppProperties.GetValues(PChar(WPD_DEVICE_OBJECT_ID), // The object whose properties we are reading
PropertiesToRead, // The properties we want to read
ppValues); // Result property values for the specified object
until E_RESOURCE_IN_USE <> HR;
if (SUCCEEDED(HR)) then
begin
key.fmtid := PKEY_DeviceObj;
key.pid := WPD_DEVICE_POWER_LEVEL;
HR := ppValues.GetUnsignedIntegerValue(key, V);
if Succeeded(HR) then
FBatteryStatus := Byte(V);
key.fmtid := PKEY_DeviceObj;
key.pid := WPD_DEVICE_TYPE;
HR := ppValues.GetUnsignedIntegerValue(key, V);
if Succeeded(HR) then
begin
case V of
WPD_DEVICE_TYPE_CAMERA:
FDeviceType := dtCamera;
WPD_DEVICE_TYPE_MEDIA_PLAYER,
WPD_DEVICE_TYPE_PHONE,
WPD_DEVICE_TYPE_PERSONAL_INFORMATION_MANAGER,
WPD_DEVICE_TYPE_AUDIO_RECORDER,
WPD_DEVICE_TYPE_GENERIC:
FDeviceType := dtPhone;
WPD_DEVICE_TYPE_VIDEO:
FDeviceType := dtVideo;
end;
end;
end else
ErrorCheck(HR);
end;
function TWPDDevice.GetContent: IPortableDeviceContent;
begin
if FContent = nil then
ErrorCheck(FDevice.Content(FContent));
Result := FContent;
end;
{ TWPDItem }
function TWPDItem.Clone: IPDItem;
begin
Result := Self;
end;
constructor TWPDItem.Create(ADevice: TWPDDevice; AItemKey: string; LoadOnlyName: Boolean = False);
begin
FDevice := ADevice;
FIDevice := ADevice; //to store reference to interface
FItemKey := AItemKey;
FErrorCode := S_OK;
FItemType := piFile;
FName := AItemKey;
FFreeSize := 0;
FFullSize := 0;
FItemDate := MinDateTime;
FDeviceID := ADevice.FDeviceID;
FDeviceName := ADevice.FName;
FWidth := 0;
FHeight := 0;
FVisible := True;
FLoadOnlyName := LoadOnlyName;
ReadProperties;
end;
procedure TWPDItem.ErrorCheck(Code: HRESULT);
begin
if Failed(Code) then
FErrorCode := Code;
end;
function TWPDItem.ExtractPreview(var PreviewImage: TBitmap): Boolean;
var
MS: TMemoryStream;
FormatGUID: TGUID;
J: TJpegImage;
PNG: TPngImage;
W, H: Integer;
CroppedImage: TBitmap;
GIF: TGIFImage;
Ext: string;
begin
Result := False;
MS := TMemoryStream.Create;
try
TransferContent(WPD_RESOURCE_THUMBNAIL, MS, FormatGUID, nil);
if MS.Size = 0 then
begin
Ext := AnsiLowerCase(ExtractFileExt(FName));
if (Ext = '.bmp') or (Ext = '.png') or (Ext = '.jpg') or (Ext = '.jpeg') or (Ext = '.gif') then
begin
TransferContent(WPD_RESOURCE_DEFAULT, MS, FormatGUID, nil);
if (Ext = '.bmp') then
FormatGUID := WPD_OBJECT_FORMAT_BMP;
if (Ext = '.png') then
FormatGUID := WPD_OBJECT_FORMAT_PNG;
if (Ext = '.jpg') or (Ext = '.jpeg') then
FormatGUID := WPD_OBJECT_FORMAT_JFIF;
if (Ext = '.gif') then
FormatGUID := WPD_OBJECT_FORMAT_GIF;
end else
Exit;
end;
MS.Seek(0, soFromBeginning);
if FormatGUID = WPD_OBJECT_FORMAT_BMP then
begin
PreviewImage.LoadFromStream(MS);
Result := not PreviewImage.Empty;
end else if FormatGUID = WPD_OBJECT_FORMAT_JFIF then
begin
J := TJpegImage.Create;
try
J.LoadFromStream(MS);
Result := not J.Empty;
if Result then
AssignJpeg(PreviewImage, J);
finally
F(J);
end;
end else if FormatGUID = WPD_OBJECT_FORMAT_PNG then
begin
PNG := TPngImage.Create;
try
PNG.LoadFromStream(MS);
Result := not PNG.Empty;
if Result then
AssignGraphic(PreviewImage, PNG);
finally
F(PNG);
end;
end else if FormatGUID = WPD_OBJECT_FORMAT_GIF then
begin
GIF := TGIFImage.Create;
try
GIF.LoadFromStream(MS);
Result := not GIF.Empty;
if Result then
AssignBitmap(PreviewImage, GIF.Bitmap);
finally
F(GIF);
end;
end;
finally
F(MS);
end;
if Result and (FWidth > 0) and (FHeight > 0) then
begin
W := FWidth;
H := FHeight;
ProportionalSize(PreviewImage.Width, PreviewImage.Height, W, H);
if ((W <> PreviewImage.Width) or (H <> PreviewImage.Height)) and (W > 0) and (H > 0) then
begin
CroppedImage := TBitmap.Create;
try
CroppedImage.PixelFormat := pf24Bit;
CroppedImage.SetSize(W, H);
DrawImageExRect(CroppedImage, PreviewImage, PreviewImage.Width div 2 - W div 2, PreviewImage.Height div 2 - H div 2, W, H, 0, 0);
F(PreviewImage);
Exchange(PreviewImage, CroppedImage);
finally
F(CroppedImage);
end;
end;
end;
end;
function TWPDItem.GetDeviceID: string;
begin
Result := FDeviceID;
end;
function TWPDItem.GetDeviceName: string;
begin
Result := FDeviceName;
end;
function TWPDItem.GetErrorCode: HRESULT;
begin
Result := FErrorCode;
end;
function TWPDItem.GetFreeSize: Int64;
begin
Result := FFreeSize;
end;
function TWPDItem.GetFullSize: Int64;
begin
Result := FFullSize;
end;
function TWPDItem.GetHeight: Integer;
begin
Result := FHeight;
end;
function TWPDItem.GetInnerInterface: IUnknown;
begin
Result := nil;
end;
function TWPDItem.GetIsVisible: Boolean;
begin
Result := FVisible;
end;
function TWPDItem.GetItemDate: TDateTime;
begin
Result := FItemDate;
end;
function TWPDItem.GetItemKey: string;
begin
Result := FItemKey;
end;
function TWPDItem.GetItemType: TPortableItemType;
begin
Result := FItemType;
end;
function TWPDItem.GetName: string;
begin
Result := FName;
end;
function TWPDItem.GetWidth: Integer;
begin
Result := FWidth;
end;
procedure TWPDItem.ReadProperties;
var
HR: HRESULT;
ppProperties: IPortableDeviceProperties;
PropertiesToRead: IPortableDeviceKeyCollection;
Key: _tagpropertykey;
ppValues: IPortableDeviceValues;
pszObjectName: PChar;
ObjectTypeGUID: TGUID;
Size: Int64;
V: tag_inner_PROPVARIANT;
W, H: Integer;
B: Integer;
begin
HR := CoCreateInstance(CLSID_PortableDeviceKeyCollection, nil, CLSCTX_INPROC_SERVER, IID_PortableDeviceKeyCollection, PropertiesToRead);
if (SUCCEEDED(HR)) then
begin
repeat
HR := FDevice.Content.Properties(ppProperties);
until E_RESOURCE_IN_USE <> HR;
if Succeeded(HR) then
begin
Key.fmtid := PKEY_GenericObj;
Key.pid := WPD_OBJECT_NAME;
ErrorCheck(PropertiesToRead.Add(key));
Key.fmtid := PKEY_GenericObj;
Key.pid := WPD_OBJECT_ORIGINAL_FILE_NAME;
ErrorCheck(PropertiesToRead.Add(key));
Key.fmtid := PKEY_GenericObj;
Key.pid := WPD_OBJECT_CONTENT_TYPE;
ErrorCheck(PropertiesToRead.Add(key));
Key.fmtid := PKEY_GenericObj;
Key.pid := WPD_OBJECT_ISHIDDEN;
ErrorCheck(PropertiesToRead.Add(key));
repeat
HR := ppProperties.GetValues(PChar(FItemKey), // The object whose properties we are reading
PropertiesToRead, // The properties we want to read
ppValues); // Result property values for the specified object
until E_RESOURCE_IN_USE <> HR;
if Succeeded(HR) then
begin
Key.fmtid := PKEY_GenericObj;
Key.pid := WPD_OBJECT_ORIGINAL_FILE_NAME;
HR := ppValues.GetStringValue(key, pszObjectName);
if (SUCCEEDED(HR)) then
FName := pszObjectName
else
begin
Key.fmtid := PKEY_GenericObj;
Key.pid := WPD_OBJECT_NAME;
HR := ppValues.GetStringValue(key, pszObjectName);
if (SUCCEEDED(HR)) then
FName := pszObjectName;
end;
Key.fmtid := PKEY_GenericObj;
Key.pid := WPD_OBJECT_ISHIDDEN;
HR := ppValues.GetBoolValue(key, B);
if Succeeded(HR) and (B = 1) then
FVisible := False;
Key.pid := WPD_OBJECT_CONTENT_TYPE;
HR := ppValues.GetGuidValue(key, ObjectTypeGUID);
if (SUCCEEDED(HR)) then
begin
if ObjectTypeGUID = WPD_CONTENT_TYPE_FOLDER then
FItemType := piDirectory;
if ObjectTypeGUID = WPD_CONTENT_TYPE_IMAGE then
FItemType := piImage;
if ObjectTypeGUID = WPD_CONTENT_TYPE_VIDEO then
FItemType := piVideo;
if ObjectTypeGUID = WPD_CONTENT_TYPE_FUNCTIONAL_OBJECT then
FItemType := piStorage;
end;
if FLoadOnlyName then
Exit;
PropertiesToRead.Clear;
case FItemType of
piImage,
piVideo,
piFile:
begin
Key.fmtid := PKEY_GenericObj;
Key.pid := WPD_OBJECT_SIZE;
ErrorCheck(PropertiesToRead.Add(key));
Key.fmtid := PKEY_GenericObj;
Key.pid := WPD_OBJECT_DATE_CREATED;
ErrorCheck(PropertiesToRead.Add(key));
key.fmtid := WPD_MEDIA_PROPERTIES_V1;
Key.pid := WPD_MEDIA_WIDTH;
PropertiesToRead.Add(key);
key.fmtid := WPD_MEDIA_PROPERTIES_V1;
Key.pid := WPD_MEDIA_HEIGHT;
PropertiesToRead.Add(key);
repeat
HR := ppProperties.GetValues(PChar(FItemKey), // The object whose properties we are reading
PropertiesToRead, // The properties we want to read
ppValues); // Result property values for the specified object
until E_RESOURCE_IN_USE <> HR;
if Succeeded(HR) then
begin
Key.fmtid := PKEY_GenericObj;
Key.pid := WPD_OBJECT_SIZE;
if ppValues.GetSignedLargeIntegerValue(key, Size) = S_OK then
FFullSize := Size;
Key.fmtid := PKEY_GenericObj;
Key.pid := WPD_OBJECT_DATE_CREATED;
if ppValues.GetValue(key, V) = S_OK then
FItemDate := V.__MIDL____MIDL_itf_PortableDeviceApi_0001_00000001.date;
key.fmtid := WPD_MEDIA_PROPERTIES_V1;
Key.pid := WPD_MEDIA_WIDTH;
if ppValues.GetSignedIntegerValue(key, W) = S_OK then
FWidth := W;
key.fmtid := WPD_MEDIA_PROPERTIES_V1;
Key.pid := WPD_MEDIA_HEIGHT;
if ppValues.GetSignedIntegerValue(key, H) = S_OK then
FHeight := H;
end;
end;
piStorage:
begin
Key.fmtid := WPD_STORAGE_OBJECT_PROPERTIES_V1;
Key.pid := WPD_STORAGE_CAPACITY;
ErrorCheck(PropertiesToRead.Add(key));
Key.fmtid := WPD_STORAGE_OBJECT_PROPERTIES_V1;
Key.pid := WPD_STORAGE_FREE_SPACE_IN_BYTES;
ErrorCheck(PropertiesToRead.Add(key));
repeat
HR := ppProperties.GetValues(PChar(FItemKey), // The object whose properties we are reading
PropertiesToRead, // The properties we want to read
ppValues); // Result property values for the specified object
until E_RESOURCE_IN_USE <> HR;
if Succeeded(HR) then
begin
Key.fmtid := WPD_STORAGE_OBJECT_PROPERTIES_V1;
Key.pid := WPD_STORAGE_CAPACITY;
if ppValues.GetSignedLargeIntegerValue(key, Size) = S_OK then
FFullSize := Size
else
FVisible := False;
Key.fmtid := WPD_STORAGE_OBJECT_PROPERTIES_V1;
Key.pid := WPD_STORAGE_FREE_SPACE_IN_BYTES;
if ppValues.GetSignedLargeIntegerValue(key, Size) = S_OK then
FFreeSize := Size
else
FVisible := False;
end;
end;
end;
end else
ErrorCheck(HR);
end else
ErrorCheck(HR);
end else
ErrorCheck(HR);
end;
function TWPDItem.SaveToStream(S: TStream): Boolean;
begin
Result := SaveToStreamEx(S, nil);
end;
function TWPDItem.SaveToStreamEx(S: TStream; CallBack: TPDProgressCallBack): Boolean;
var
FormatGUID: TGUID;
begin
TransferContent(WPD_RESOURCE_DEFAULT, S, FormatGUID, CallBack);
Result := FErrorCode = S_OK;
end;
//WPD_RESOURCE_THUMBNAIL or WPD_RESOURCE_DEFAULT
procedure TWPDItem.TransferContent(ResourceID: TGUID; Stream: TStream; out ResourceFormat: TGUID;
CallBack: TPDProgressCallBack);
const
DefaultBufferSize: Integer = 2 * 1024 * 1024;
var
HR: HRESULT;
pObjectDataStream: IStream;
Buff: PByte;
cbOptimalTransferSize: DWORD;
Key: _tagpropertykey;
ButesRead: Longint;
ppResources: IPortableDeviceResources;
ppResourceAttributes: IPortableDeviceValues;
BufferSize, ReadBufferSize: Int64;
ResFormat: TGUID;
IsBreak: Boolean;
begin
IsBreak := False;
FErrorCode := S_OK;
ResourceFormat := WPD_OBJECT_FORMAT_JFIF;
BufferSize := DefaultBufferSize;
repeat
HR := FDevice.Content.Transfer(ppResources);
until E_RESOURCE_IN_USE <> HR;
if (SUCCEEDED(HR)) then
begin
repeat
HR := ppResources.GetResourceAttributes(PChar(FItemKey),
Key,
ppResourceAttributes);
until E_RESOURCE_IN_USE <> HR;
if (SUCCEEDED(HR)) then
begin
key.fmtid := WPD_RESOURCE_ATTRIBUTES_V1;
Key.pid := WPD_RESOURCE_ATTRIBUTE_OPTIMAL_READ_BUFFER_SIZE;
if SUCCEEDED(ppResourceAttributes.GetSignedLargeIntegerValue(key, ReadBufferSize)) then
BufferSize := ReadBufferSize;
key.fmtid := WPD_RESOURCE_ATTRIBUTES_V1;
Key.pid := WPD_RESOURCE_ATTRIBUTE_FORMAT;
if SUCCEEDED(ppResourceAttributes.GetGuidValue(key, ResFormat)) and (ResFormat.D1 > 0) then
ResourceFormat := ResFormat;
end;
BufferSize := Max(BufferSize, DefaultBufferSize);
cbOptimalTransferSize := BufferSize;
Key.fmtid := ResourceID;
Key.pid := 0;
repeat
HR := ppResources.GetStream(PChar(FItemKey), // Identifier of the object we want to transfer
Key, // We are transferring the default resource (which is the entire object's data)
STGM_READ, // Opening a stream in READ mode, because we are reading data from the device.
cbOptimalTransferSize, // Driver supplied optimal transfer size
pObjectDataStream);
until E_RESOURCE_IN_USE <> HR;
if (SUCCEEDED(HR)) then
begin
GetMem(Buff, BufferSize);
try
repeat
HR := pObjectDataStream.Read(Buff, BufferSize, @ButesRead);
if (SUCCEEDED(HR) and (ButesRead > 0)) then
begin
Stream.WriteBuffer(Buff[0], ButesRead);
if Assigned(CallBack) then
CallBack(Self, FFullSize, Stream.Size, IsBreak);
end else if Failed(HR) and (HR <> E_RESOURCE_IN_USE) then
begin
IsBreak := False;
Break;
end;
if IsBreak then
begin
FErrorCode := E_ABORT;
Break;
end;
until (ButesRead = 0);
repeat
pObjectDataStream.Commit(0);
until E_RESOURCE_IN_USE <> HR;
finally
FreeMem(Buff);
end;
end else
ErrorCheck(HR);
end else
ErrorCheck(HR);
end;
{ TWPDEventManager }
constructor TWPDEventManager.Create;
begin
FSync := TCriticalSection.Create;
FEventTargets := TList<TEventTargetInfo>.Create;
FEventDevices := TList<TEventDeviceInfo>.Create;
FDeviceCallBack := TWPDDeviceEventCallback.Create;
end;
destructor TWPDEventManager.Destroy;
var
HR: HRESULT;
DevEventInfo: TEventDeviceInfo;
begin
FreeList(FEventTargets);
for DevEventInfo in FEventDevices do
begin
HR := DevEventInfo.Device.Unadvise(PChar(DevEventInfo.Cookie));
if Failed(HR) then
Break;
end;
FreeList(FEventDevices);
F(FSync);
inherited;
end;
procedure TWPDEventManager.InvokeItem(EventType: TPortableEventType; DeviceID, ItemKey, ItemPath: string);
var
Info: TEventTargetInfo;
begin
for Info in FEventTargets do
if EventType in Info.EventTypes then
Info.CallBack(EventType, DeviceID, ItemKey, ItemPath);
end;
procedure TWPDEventManager.RegisterNotification(EventTypes: TPortableEventTypes;
CallBack: TPortableEventCallBack);
var
Info: TEventTargetInfo;
begin
Info := TEventTargetInfo.Create;
Info.EventTypes := EventTypes;
Info.CallBack := CallBack;
FEventTargets.Add(Info);
end;
procedure TWPDEventManager.RegisterDevice(Device: TWPDDevice);
var
HR: HRESULT;
ppszCookie: PWideChar;
EventDeviceInfo: TEventDeviceInfo;
FDevice: IPortableDevice;
ClientInformation: IPortableDeviceValues;
begin
HR := CoInitializeEx(nil, COINIT_MULTITHREADED);
//COINIT_MULTITHREADED is already initialized
if HR = S_FALSE then
begin
FSync.Enter;
try
for EventDeviceInfo in FEventDevices do
if AnsiLowerCase(EventDeviceInfo.DeviceID) = AnsiLowerCase(Device.DeviceID) then
Exit;
HR := CoCreateInstance(CLSID_PortableDeviceFTM,
nil,
CLSCTX_INPROC_SERVER,
IID_PortableDeviceFTM,
FDevice);
if SUCCEEDED(HR) then
begin
HR := CoCreateInstance(CLSID_PortableDeviceValues,
nil,
CLSCTX_INPROC_SERVER,
IID_PortableDeviceValues,
ClientInformation);
if SUCCEEDED(HR) then
begin
repeat
HR := FDevice.Open(PWideChar(Device.DeviceID), ClientInformation);
until E_RESOURCE_IN_USE <> HR;
if Succeeded(HR) then
begin
repeat
HR := FDevice.Advise(0, FDeviceCallBack, nil, ppszCookie);
until E_RESOURCE_IN_USE <> HR;
if Succeeded(HR) then
begin
EventDeviceInfo := TEventDeviceInfo.Create;
EventDeviceInfo.Device := FDevice;
EventDeviceInfo.DeviceID := Device.DeviceID;
EventDeviceInfo.Cookie := string(ppszCookie);
FEventDevices.Add(EventDeviceInfo);
CoTaskMemFree(ppszCookie);
end;
end;
end;
end;
finally
FSync.Leave;
end;
end;
end;
procedure TWPDEventManager.UnregisterDevice(DeviceID: string);
var
I: Integer;
DevEventInfo: TEventDeviceInfo;
begin
FSync.Enter;
try
for I := FEventDevices.Count - 1 downto 0 do
begin
DevEventInfo := FEventDevices[I];
if AnsiLowerCase(DevEventInfo.DeviceID) = AnsiLowerCase(DeviceID) then
begin
DevEventInfo.DeviceID := '';
DevEventInfo.Cookie := '';
//todo: cleanup this in register event
//FEventDevices.Remove(DevEventInfo);
//DevEventInfo.Device.Unadvise(PChar(DevEventInfo.Cookie));
//F(DevEventInfo);
end;
end;
finally
FSync.Leave;
end;
end;
procedure TWPDEventManager.UnregisterNotification(CallBack: TPortableEventCallBack);
var
I: Integer;
Info: TEventTargetInfo;
begin
for I := FEventTargets.Count - 1 downto 0 do
begin
Info := FEventTargets[I];
if Addr(Info.CallBack) = Addr(CallBack) then
begin
FEventTargets.Remove(Info);
Info.Free;
end;
end;
end;
{ TWPDDeviceEventCallback }
function TWPDDeviceEventCallback.OnEvent(
const pEventParameters: IPortableDeviceValues): HRESULT;
var
HR: HRESULT;
Key: _tagpropertykey;
DeviceID: PChar;
EventGUID: TGUID;
FilePath: string;
PItemKey: PChar;
Manager: IPManager;
Device: IPDevice;
Item: IPDItem;
begin
Result := S_OK;
if pEventParameters <> nil then
begin
Key.fmtid := WPD_EVENT_PROPERTIES_V1;
Key.pid := WPD_EVENT_PARAMETER_PNP_DEVICE_ID;
HR := pEventParameters.GetStringValue(Key, DeviceID);
if Succeeded(HR) then
begin
Key.fmtid := WPD_EVENT_PROPERTIES_V1;
Key.pid := WPD_EVENT_PARAMETER_EVENT_ID;
HR := pEventParameters.GetGuidValue(Key, EventGUID);
if Succeeded(HR) then
begin
if EventGUID = WPD_EVENT_OBJECT_REMOVED then
begin
Manager := TWPDDeviceManager.Create;
Device := Manager.GetDeviceByID(DeviceID);
if Device <> nil then
begin
Key.fmtid := PKEY_GenericObj;
Key.pid := WPD_OBJECT_ID;
HR := pEventParameters.GetStringValue(Key, PItemKey);
if Succeeded(HR) then
begin
FilePath := Device.Name + PortableItemNameCache.GetPathByKey(DeviceID, string(PItemKey));
TThread.Synchronize(nil,
procedure
begin
WPDEventManager.InvokeItem(peItemRemoved, DeviceID, string(PItemKey), FilePath);
end
);
end;
end;
end;
if EventGUID = WPD_EVENT_OBJECT_ADDED then
begin
Key.fmtid := PKEY_GenericObj;
Key.pid := WPD_OBJECT_ID;
HR := pEventParameters.GetStringValue(Key, PItemKey);
if Succeeded(HR) then
begin
Manager := TWPDDeviceManager.Create;
Device := Manager.GetDeviceByID(DeviceID);
if Device <> nil then
begin
Item := Device.GetItemByKey(string(PItemKey));
if Item <> nil then
begin
FilePath := Device.Name + PortableItemNameCache.GetPathByKey(DeviceID, string(PItemKey));
TThread.Synchronize(nil,
procedure
begin
WPDEventManager.InvokeItem(peItemAdded, DeviceID, Item.ItemKey, FilePath);
end
);
end;
end;
end;
end;
if EventGUID = WPD_EVENT_DEVICE_REMOVED then
begin
WPDEventManager.UnregisterDevice(DeviceID);
PortableItemNameCache.ClearDeviceCache(DeviceID);
TThread.Synchronize(nil,
procedure
begin
WPDEventManager.InvokeItem(peDeviceDisconnected, DeviceID, '', '');
end
);
end;
end;
end;
end;
end;
initialization
finalization
FIEventManager := nil;
end.
|
unit AbsoluteValueTest;
interface
uses
DUnitX.TestFramework,
uIntXLibTypes,
uIntX;
type
[TestFixture]
TAbsoluteValueTest = class(TObject)
public
[Test]
procedure AbsoluteTest();
[Test]
procedure AbsoluteTestZero();
procedure NullAbsoluteTest();
[Test]
procedure CallNullAbsoluteTest();
end;
implementation
[Test]
procedure TAbsoluteValueTest.AbsoluteTest();
var
int1, res: TIntX;
begin
int1 := TIntX.Create(-5);
res := TIntX.AbsoluteValue(int1);
Assert.IsTrue(res = 5);
res := TIntX.AbsoluteValue(-25);
Assert.IsTrue(res = 25);
res := TIntX.AbsoluteValue(TIntX.Parse('-500'));
Assert.IsTrue(res = 500);
int1 := TIntX.Create(10);
res := TIntX.AbsoluteValue(int1);
Assert.IsTrue(res = 10);
res := TIntX.AbsoluteValue(80);
Assert.IsTrue(res = 80);
res := TIntX.AbsoluteValue(TIntX.Parse('900'));
Assert.IsTrue(res = 900);
end;
[Test]
procedure TAbsoluteValueTest.AbsoluteTestZero();
var
int1, res: TIntX;
begin
int1 := TIntX.Create(-0);
res := TIntX.AbsoluteValue(int1);
Assert.IsTrue(res = 0);
res := TIntX.AbsoluteValue(TIntX.Parse('-0'));
Assert.IsTrue(res = 0);
res := TIntX.AbsoluteValue(0);
Assert.IsTrue(res = 0);
res := TIntX.AbsoluteValue(TIntX.Parse('0'));
Assert.IsTrue(res = 0);
end;
procedure TAbsoluteValueTest.NullAbsoluteTest();
begin
TIntX.AbsoluteValue(Default (TIntX));
end;
[Test]
procedure TAbsoluteValueTest.CallNullAbsoluteTest();
var
TempMethod: TTestLocalMethod;
begin
TempMethod := NullAbsoluteTest;
Assert.WillRaise(TempMethod, EArgumentNilException);
end;
initialization
TDUnitX.RegisterTestFixture(TAbsoluteValueTest);
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1999 Inprise Corporation }
{ }
{ Русификация: 1998-2002 Polaris Software }
{ http://polesoft.da.ru }
{*******************************************************}
unit ADOConst;
interface
resourcestring
SInvalidEnumValue = 'Неверное Enum значение';
SMissingConnection = 'Не указано Connection или ConnectionString';
SNoDetailFilter = 'Свойство Filter не может использоваться для detail таблиц';
SBookmarksRequired = 'Набор данных (Dataset) не поддерживает закладки (bookmarks), которые требуются для элементов, работающих с данными нескольких записей';
SMissingCommandText = 'Не указано свойство %s';
SNoResultSet = 'CommandText не возвращает результат';
SADOCreateError = 'Ошибка создания объекта. Пожалуйста, проверьте, что Microsoft Data Access Components 2.1 (или выше) правильно установлены';
SEventsNotSupported = 'События не поддерживаются с TableDirect курсорами на серверной стороне';
SUsupportedFieldType = 'Неподдерживаемый тип поля (%s) в поле %s';
SNoMatchingADOType = 'Нет совпадающего типа данных ADO для %s';
SConnectionRequired = 'Соединяющий компонент требуется для асинх. ExecuteOptions';
SCantRequery = 'Не могу выполнить запрос после изменения соединения';
SNoFilterOptions = 'FilterOptions не поддерживается';
{$IFNDEF VER130}
SRecordsetNotOpen = 'Recordset не открыт';
{$IFNDEF VER140}
sNameAttr = 'Name';
sValueAttr = 'Value';
{$ENDIF}
{$ENDIF}
implementation
end.
|
//******************************************************************************
// Easter Component unit
// bb - sdtp May 2021
// Provides Easter dates and associated
// Parameters:
// EasterYear (Integer): Selected year for Easter dates
// Properties :
// InvalidYear (Boolean) True if year is invalid
// Easterdate (DateTime) : Easter date
// EasterMondaydate (TDateTime) : Easter monday date
// Ascensdate (TDateTime) : Ascension date
// Pentecdate (TDateTime) : Pentecost date
// PentecMondaydate (TDateTime) : Pentecost monday date
//******************************************************************************
unit Easter;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs;
type
TEaster = class(TComponent)
private
fVersion: String;
fEasteryear: Integer;
fEasterdate: TDateTime;
fEasterMondaydate: TDateTime;
fAscensdate: TDatetime;
fPentecdate: Tdatetime;
fPentecMondaydate: Tdatetime;
fInvalidYear: Boolean;
procedure GetEaster;
procedure setEasteryear(value: Integer);
protected
public
constructor create(AOwner: TComponent); override;
property InvalidYear: Boolean read fInvalidYear;
property Easterdate : TDateTime read fEasterdate;
property EasterMondaydate : TDateTime read fEasterMondaydate;
property Ascensdate: TDateTime read fAscensdate;
property Pentecdate: TDateTime read fPentecdate;
property PentecMondaydate: TDateTime read fPentecMondaydate;
published
property Version: String read fVersion;
property EasterYear: Integer read fEasteryear write setEasteryear;
end;
procedure Register;
implementation
procedure Register;
begin
{$I easter_icon.lrs}
RegisterComponents('lazbbAstroComponents',[TEaster]);
end;
constructor TEaster.create(AOwner: TComponent);
begin
inherited Create(AOwner);
fVersion:= '1.0';
fEasteryear:= CurrentYear;
end;
procedure TEaster.setEasteryear(value: Integer);
begin
if fEasterYear<>value then
begin
fEasterYear:= value;
if not (csDesigning in ComponentState) then GetEaster;
end;
end;
procedure TEaster.GetEaster; // Wikipedia
var
nMonth, nDay, nMoon, nEpact, nSunday, nGold, nCent, nCorx, nCorz: Integer;
begin
fInvalidYear:= false;
nGold := (fEasteryear mod 19) + 1; // The Golden Number of the year in the 19 year Metonic Cycle
nCent := (fEasteryear div 100) + 1; // Calculate the Century
{ Number of years in which leap year was dropped in order... }
{ to keep in step with the sun: }
nCorx := (3 * nCent) div 4 - 12;
nCorz := (8 * nCent + 5) div 25 - 5; // Special correction to syncronize Easter with moon's orbit
nSunday := (Longint(5) * fEasteryear) div 4 - nCorx - 10; // Find Sunday
{ ^ To prevent overflow at year 6554}
{ Set Epact - specifies occurrence of full moon: }
nEpact := (11 * nGold + 20 + nCorz - nCorx) mod 30;
if nEpact < 0 then
nEpact := nEpact + 30;
if ((nEpact = 25) and (nGold > 11)) or (nEpact = 24) then nEpact := nEpact + 1;
{ Find Full Moon: }
nMoon := 44 - nEpact;
if nMoon < 21 then
nMoon := nMoon + 30;
{ Advance to Sunday: }
nMoon := nMoon + 7 - ((nSunday + nMoon) mod 7);
if nMoon > 31 then
begin
nMonth := 4;
nDay := nMoon - 31;
end
else
begin
nMonth := 3;
nDay := nMoon;
end;
try
fEasterdate := EncodeDate(fEasteryear, nMonth, nDay);
fEasterMondaydate:= feasterdate+1;
fAscensdate:= fEasterdate+39;
fPentecdate:= fEasterdate+49;
fPentecMondaydate:= fEasterdate+50;
except
fInvalidYear:= true;
end;
end;
end.
|
unit f1df_Insertm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxRadioGroup,
cxTextEdit, cxMaskEdit, cxSpinEdit, cxControls, cxContainer, cxEdit,
cxLabel, ExtCtrls, ibase, ZProc, Unit_ZGlobal_Consts, PackageLoad,
f1df_AddOstm;
type
TFInsert = class(TForm)
Bevel1: TBevel;
LabelKvartal: TcxLabel;
LabelYear: TcxLabel;
RadioRee: TcxRadioButton;
RadioOst: TcxRadioButton;
YesBtn: TcxButton;
CancelBtn: TcxButton;
procedure CancelBtnClick(Sender: TObject);
procedure YesBtnClick(Sender: TObject);
private
PLanguageIndex:Byte;
PDb_Handle:TISC_DB_HANDLE;
ID:integer;
public
constructor Create(AOwner:TComponent;ADB_handle:TISC_DB_HANDLE;Id_1df:integer;Kvartal:integer;Year:integer);reintroduce;
end;
implementation
{$R *.dfm}
constructor TFInsert.Create(AOwner:TComponent;ADB_handle:TISC_DB_HANDLE;Id_1df:integer;Kvartal:integer;Year:integer);
begin
inherited Create(AOwner);
PDb_Handle := ADB_handle;
PLanguageIndex := LanguageIndex;
ID:=Id_1df;
Caption := Caption_Insert[PLanguageIndex];
LabelYear.Caption := LabelYear_Caption[PLanguageIndex]+' '+IntToStr(Year);
LabelKvartal.Caption := LabelKvartal_Caption[PLanguageIndex]+' '+IntToStr(Kvartal);
RadioRee.Caption := Reestr_Const[PLanguageIndex];
RadioOst.Caption := Ostatok_Const[PLanguageIndex];
YesBtn.Caption := YesBtn_Caption[PLanguageIndex];
CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex];
end;
procedure TFInsert.CancelBtnClick(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TFInsert.YesBtnClick(Sender: TObject);
var Form: TFAddOst;
begin
if RadioRee.Checked=true then
LoadReeVed(self,PDb_Handle,ID)
else
begin
Form:= TFAddOst.Create(self,PDb_Handle,ID);
Form.ShowModal;
end;
ModalResult:=mrYes;
end;
end.
|
namespace ;
interface
uses
System,
System.IO,
System.Collections.Generic,
System.Linq,
System.Text,
System.Threading.Tasks,
Windows.Storage,
Windows.Storage.Streams,
System.Runtime.Serialization,
Windows.ApplicationModel;
type
SuspensionManager = class
private
class var sessionState_: Dictionary<System.String, System.Object> := new Dictionary<System.String, System.Object>();
class var knownTypes_: List<&Type> := new List<&Type>();
const filename: System.String = '_sessionState.xml';
public
// Provides access to the currect session state
class property SessionState: Dictionary<System.String, System.Object> read sessionState_;
// Allows custom types to be added to the list of types that can be serialized
class property KnownTypes: List<&Type> read knownTypes_;
// Save the current session state
class method SaveAsync: Task;
// Restore the saved sesison state
class method RestoreAsync: Task;
end;
implementation
class method SuspensionManager.SaveAsync: Task;
begin
// Get the output stream for the SessionState file.
var file: StorageFile := await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
var raStream := await file.OpenAsync(FileAccessMode.ReadWrite);
file.OpenAsync(FileAccessMode.ReadWrite);
using outStream: IOutputStream := raStream.GetOutputStreamAt(0) do begin
// Serialize the Session State.
var serializer: DataContractSerializer := new DataContractSerializer(typeOf(Dictionary<System.String, System.Object>), knownTypes_);
serializer.WriteObject(outStream.AsStreamForWrite(), sessionState_);
await outStream.FlushAsync();
end
end;
class method SuspensionManager.RestoreAsync: Task;
begin
// Get the input stream for the SessionState file.
try
var file: StorageFile := await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
ApplicationData.Current.LocalFolder.GetFileAsync(filename);
if file = nil then exit;
var inStream: IInputStream := await file.OpenSequentialReadAsync();
file.OpenSequentialReadAsync();
// Deserialize the Session State.
var serializer: DataContractSerializer := new DataContractSerializer(typeOf(Dictionary<System.String, System.Object>), knownTypes_);
sessionState_ := Dictionary<System.String, System.Object>(serializer.ReadObject(inStream.AsStreamForRead()))
except
on Exception do
// Restoring state is best-effort. If it fails, the app will just come up with a new session.
end
end;
end.
|
unit ufrmListMembership;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMaster, StdCtrls, ExtCtrls, ComCtrls, ufraFooter5Button,
ActnList, System.Actions;
type
TfrmListMembership = class(TfrmMaster)
Label2: TLabel;
Label3: TLabel;
dtpFrom: TDateTimePicker;
dtpTo: TDateTimePicker;
Label1: TLabel;
cbbPilih: TComboBox;
fraFooter5Button1: TfraFooter5Button;
actlstMembership: TActionList;
actListPrintMembership: TAction;
procedure FormShow(Sender: TObject);
procedure actListPrintMembershipExecute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmListMembership: TfrmListMembership;
implementation
uses uConstanta, ufrmDialogPrintPreview, DateUtils, uRetnoUnit, uDMReport,
uAppUtils;
{$R *.dfm}
procedure TfrmListMembership.FormShow(Sender: TObject);
begin
inherited;
dtpFrom.Date := Now;
dtpTo.Date := Now;
end;
procedure TfrmListMembership.actListPrintMembershipExecute(
Sender: TObject);
var
sSQL: String;
// SeparatorDate: Char;
// data: TResultDataSet;
// ParamList: TStringList;
// formatTanggalPendek: string;
// arrParam: TArr;
begin
inherited;
// if cbbPilih.ItemIndex < 0 then Exit;
//
// SeparatorDate:= DateSeparator;
// try
// DateSeparator:= '/';
// formatTanggalPendek:= ShortDateFormat;
// ShortDateFormat:= 'mm/dd/yyyy';
//
//
//
// if not Assigned(MemberShip) then
// MemberShip:= TMemberShip.Create;
// SetLength(arrParam,2);
// arrParam[0].tipe:= ptDateTime;
// arrParam[0].data:= Trunc(dtpFrom.Date);
// arrParam[1].tipe:= ptDateTime;
// arrParam[1].data:= DateOf(IncDay(dtpTo.Date));
//
// ParamList := TStringList.Create;
// ParamList.Add(FormatDateTime('dd/mm/yyyy', dtpFrom.Date)); //0ab
// ParamList.Add(FormatDateTime('dd/mm/yyyy', dtpTo.Date)); //1ab
// ParamList.Add(FLoginFullname); //2ab
//
// if cbbPilih.ItemIndex = 0 then // List Membership
// begin
// data := MemberShip.GetListReportMembership(arrParam);
// end
// else
// begin
// data := MemberShip.GetListMembershipBiayaKartu(arrParam, cbbPilih.ItemIndex);
//
// if cbbPilih.ItemIndex = 1 then // Rekap Kartu Baru
// begin
// ParamList.Add(JENIS_BAYAR_KARTU_BARU); //3b
// end
// else if cbbPilih.ItemIndex = 2 then // Rekap Perpanjangan Kartu
// begin
// ParamList.Add(JENIS_BAYAR_PERPANJANGAN_KARTU); //3b
// end;
// end;
// ParamList.Add(MasterNewunit.Nama); //3a ato 4b
//
// if not assigned(frmDialogPrintPreview) then
// frmDialogPrintPreview:= TfrmDialogPrintPreview.Create(Application);
//
// frmDialogPrintPreview.ListParams:= ParamList;
// frmDialogPrintPreview.RecordSet:= data;
// if cbbPilih.ItemIndex = 0 then
// frmDialogPrintPreview.FilePath:= FFilePathReport+'frListMembership.fr3'
// else
// frmDialogPrintPreview.FilePath:= FFilePathReport+'frListRekapKartuMembership.fr3';
// SetFormPropertyAndShowDialog(frmDialogPrintPreview);
// finally
// FreeAndNil(ParamList);
// frmDialogPrintPreview.Free;
// DateSeparator:= SeparatorDate;
// ShortDateFormat:= formatTanggalPendek;
// end;
if cbbPilih.ItemIndex = 0 then
Begin
sSQL := 'select '
+ ' m.* from member m'
+ ' inner join ref$tipe_member tp on tp.tpmember_id=m.member_tpmember_id '
+ ' where m.member_registered_date between '
+ TAppUtils.QuotD(dtpFrom.Date) + ' and ' + TAppUtils.QuotD(dtpTo.Date)
+ ' and m.MEMBER_UNT_ID = ' + IntToStr(MasterNewUnit)
+ ' order by m.member_registered_date' ;
// dmReportNew.EksekusiReport('ListMembership', sSQL, '', True);
End
Else if cbbPilih.ItemIndex = 1 then // -- Aktifasi
Begin
sSQL := 'select '
+ ' ma.memberact_id, ma.date_create, m.member_id, m.member_card_no,'
+ ' m.member_name,ma.memberact_valid_date_to, ma.memberact_fee_activasi '
+ ' as "Biaya Kartu", ma.memberact_is_reactivasi '
+ ' from member_activasi ma '
+ ' inner join member m '
+ ' on (m.member_id=ma.memberact_member_id '
+ ' and m.member_unt_id=ma.memberact_member_unt_id) '
+ ' where (cast(ma.date_create as Date) between ' + TAppUtils.QuotD(dtpFrom.Date)
+ ' and ' + TAppUtils.QuotD(dtpTo.Date) + ')'
//+ ' and ma.memberact_fee_activasi <> 0 '
+ ' and ma.memberact_is_activasi = 1 '
+ ' and ma.MEMBERACT_UNT_ID = ' + IntToStr(MasterNewUnit)
+ ' order by ma.date_create' ;
// dmReportNew.EksekusiReport('ListBiayaAktifasiMember', sSQL, '', True);
End
Else if cbbPilih.ItemIndex = 2 then // -- Reaktifasi
Begin
sSQL := 'select '
+ ' ma.memberact_id, ma.date_create, m.member_id, m.member_card_no,'
+ ' m.member_name,ma.memberact_valid_date_to, ma.memberact_fee_reactivasi '
+ ' as "Biaya Kartu", ma.memberact_is_reactivasi '
+ ' from member_activasi ma '
+ ' inner join member m '
+ ' on (m.member_id=ma.memberact_member_id '
+ ' and m.member_unt_id=ma.memberact_member_unt_id) '
+ ' where (cast(ma.date_create as Date) between ' + TAppUtils.QuotD(dtpFrom.Date)
+ ' and ' + TAppUtils.QuotD(dtpTo.Date) + ')'
//+ ' and ma.memberact_fee_reactivasi <> 0 '
+ ' and ma.memberact_is_reactivasi = 1 '
+ ' and ma.MEMBERACT_UNT_ID = ' + IntToStr(MasterNewUnit)
+ ' order by ma.date_create' ;
// dmReportNew.EksekusiReport('ListBiayaReaktifasiMember', sSQL, '', True);
End;
end;
procedure TfrmListMembership.FormDestroy(Sender: TObject);
begin
inherited;
frmListMembership := nil;
end;
procedure TfrmListMembership.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
// inherited;
if (Key = Ord('P')) and (ssctrl in Shift) then
actListPrintMembershipExecute(Self);
if (Key = VK_Escape) and (ssctrl in Shift) then
Close;
end;
end.
|
unit uViewerTypes;
interface
uses
SyncObjs,
ActiveX,
uMemory,
uThreadForm,
uDBEntities;
type
TViewerForm = class(TThreadForm)
private
FFullScreenNow: Boolean;
FSlideShowNow: Boolean;
protected
function GetItem: TMediaItem; virtual;
public
CurrentFileNumber: Integer;
property FullScreenNow: Boolean read FFullScreenNow write FFullScreenNow;
property SlideShowNow: Boolean read FSlideShowNow write FSlideShowNow;
end;
TViewerManager = class(TObject)
private
FSync: TCriticalSection;
FSID: TGUID;
FForwardThreadSID: TGUID;
public
constructor Create;
destructor Destroy; override;
procedure UpdateViewerState(SID, ForwardThreadSID: TGUID);
function ValidateState(State: TGUID): Boolean;
end;
function ViewerManager: TViewerManager;
implementation
var
FViewerManager: TViewerManager = nil;
function ViewerManager: TViewerManager;
begin
if FViewerManager = nil then
FViewerManager := TViewerManager.Create;
Result := FViewerManager;
end;
{ TViewerForm }
function TViewerForm.GetItem: TMediaItem;
begin
Result := nil;
end;
{ TViewerManager }
constructor TViewerManager.Create;
begin
FSync := TCriticalSection.Create;
end;
destructor TViewerManager.Destroy;
begin
F(FSync);
inherited;
end;
procedure TViewerManager.UpdateViewerState(SID, ForwardThreadSID: TGUID);
begin
FSync.Enter;
try
FSID := SID;
FForwardThreadSID := ForwardThreadSID;
finally
FSync.Leave;
end;
end;
function TViewerManager.ValidateState(State: TGUID): Boolean;
begin
FSync.Enter;
try
Result := IsEqualGUID(FSID, State) or IsEqualGUID(State, FForwardThreadSID);
finally
FSync.Leave;
end;
end;
initialization
finalization
F(FViewerManager);
end.
|
PROGRAM PHONEBOOK;
CONST
n = 5; {number of total contact}
TYPE
contact_rec = RECORD
name : STRING;
family : STRING;
code : STRING;
number : STRING;
address : String;
END;
contact_arr = ARRAY[1..n] OF contact_rec;
VAR
contact : contact_arr;
input : INTEGER;
item : INTEGER ;
key : STRING;
i,j : INTEGER;
index : INTEGER;
contactFile : TEXT;
PROCEDURE showMessage; FORWARD; {Pre-Declare "showMessage" procedure}
PROCEDURE addContact;
BEGIN
writeln('Enter NAME : ');
readln(contact[item].name);
writeln('Enter FAMILY : ');
readln(contact[item].family);
writeln('Enter CODE : ');
readln(contact[item].code);
writeln('Enter NUMBER : ');
readln(contact[item].number);
writeln('Enter ADDRESS : ');
readln(contact[item].address);
item := item + 1;
showMessage;
END;
PROCEDURE showContact(x : INTEGER);
BEGIN
writeln('CONTACT ', x, ' : ');
writeln;
writeln('NAME : ', contact[x].name);
writeln('FAMILY : ', contact[x].family);
writeln('CODE : ', contact[x].code);
writeln('NUMBER : ', contact[x].number);
writeln('ADDRESS : ', contact[x].address);
writeln;
writeln;
showMessage;
END;
PROCEDURE showAll;
BEGIN
FOR i := 1 TO item-1 DO
BEGIN
writeln('CONTACT ', i, ' : ');
writeln;
writeln('NAME : ', contact[i].name);
writeln('FAMILY : ', contact[i].family);
writeln('CODE : ', contact[i].code);
writeln('NUMBER : ', contact[i].number);
writeln('ADDRESS : ', contact[i].address);
writeln;
writeln;
END;
showMessage;
END;
PROCEDURE search;
BEGIN
writeln('Please Enter Family Of Contact : ');
readln(key);
for i := 1 to item-1 do
BEGIN
IF (key = contact[i].family) THEN
showContact(i);
END;
writeln('Your Entered Family Is NOT In The Contact List');
showMessage;
END;
PROCEDURE sort;
var
tempName : STRING;
tempFamily : STRING;
tempCode : STRING;
tempNumber : STRING;
tempAddress : STRING;
BEGIN
FOR i := 1 TO item-1 DO
FOR j:= i+1 TO item-1 DO
IF(contact[i].family > contact[j].family) THEN
BEGIN
tempName := contact[i].name;
tempFamily := contact[i].family;
tempCode := contact[i].code;
tempNumber := contact[i].number;
tempAddress := contact[i].address;
contact[i].name := contact[j].name;
contact[i].family := contact[j].family;
contact[i].code := contact[j].code;
contact[i].number := contact[j].number;
contact[i].address := contact[j].address;
contact[j].name := tempName;
contact[j].family := tempFamily;
contact[j].code := tempCode;
contact[j].number := tempNumber;
contact[j].address := tempAddress;
END;
writeln('Sort DONE');
showMessage;
END;
PROCEDURE editContact;
var
tempName : STRING;
tempFamily : STRING;
tempCode : STRING;
tempNumber : STRING;
tempAddress : STRING;
BEGIN
writeln('Please Enter INDEX Of Contact You Want To Edit : ');
readln(index);
writeln('Name Of Contact ', index, ' is "', contact[index].name,
' " Enter New Name For It : ');
readln(tempName);
contact[i].name := tempName;
writeln('Family Of Contact ', index,' is "',contact[index].family,
' " Enter New Family For It : ');
readln(tempFamily);
contact[i].family := tempFamily;
writeln('Code Of Contact ', index, ' is "', contact[index].code,
' " Enter New Code For It : ');
readln(tempCode);
contact[i].code := tempCode;
writeln('Number Of Contact ', index,' is "',contact[index].number,
' " Enter New number For It : ');
readln(tempNumber);
contact[i].number := tempNumber;
writeln('Address Of Contact ',index,' is "',contact[index].address,
' " Enter New Address For It : ');
readln(tempAddress);
contact[i].address := tempAddress;
writeln;
writeln;
showMessage;
END;
PROCEDURE deleteContact;
var
tempNumber : String;
BEGIN
writeln('Enter NUMBER Of Contact You Want To Delete : ');
readln(tempNumber);
index := 0;
FOR i := 1 TO item-1 DO
IF (tempNumber = contact[i].number) THEN
index := i;
IF( index = 0) THEN
writeln('No Contact Found With These Number')
ELSE
BEGIN
FOR i := index TO item-1 DO
BEGIN
contact[i].name := contact[i+1].name;
contact[i].family := contact[i+1].family;
contact[i].code := contact[i+1].code;
contact[i].number := contact[i+1].number;
contact[i].address := contact[i+1].address;
END;
item := item - 1;
writeln('Delete DONE');
END;
showMessage;
END;
PROCEDURE quit;
BEGIN
HALT(0);
END;
PROCEDURE save;
BEGIN
ASSIGN(contactFile, 'savedContact.txt');
REWRITE(contactFile);
FOR i:= 1 TO item-1 DO
BEGIN
writeln(contactFile, contact[i].name);
writeln(contactFile, contact[i].family);
writeln(contactFile, contact[i].code);
writeln(contactFile, contact[i].number);
writeln(contactFile, contact[i].address);
END;
close(contactFile);
showMessage;
END;
PROCEDURE load;
BEGIN
ASSIGN(contactFile, 'savedContact.txt');
RESET(contactFile);
{FOR i:=1 TO n DO}
while NOT EOF(contactFile) DO
BEGIN
readln(contactFile, contact[item].name);
readln(contactFile, contact[item].family);
readln(contactFile, contact[item].code);
readln(contactFile, contact[item].number);
readln(contactFile, contact[item].address);
item := item + 1;
END;
close(contactFile);
showMessage;
END;
PROCEDURE showMessage;
BEGIN
writeln;
writeln('1. Add Contact');
writeln('2. Show All');
writeln('3. Search');
writeln('4. Sort');
writeln('5. Edit Contact');
writeln('6. Delete Contact');
writeln('7. Save Contact In File');
writeln('8. Load Contact From File');
writeln('9. Quit');
writeln;
writeln('Enter Your Choise : ');
readln(input);
CASE input OF
1 : addContact;
2 : showAll;
3 : search;
4 : sort;
5 : editContact;
6 : deleteContact;
7 : save;
8 : load;
9 : quit;
OTHERWISE showMessage;
END;
END;
BEGIN
item := 1;
showMessage;
END.
|
unit Darbre1;
INTERFACE
uses classes, util1,debug0;
const
chiffre:set of Ansichar=['0'..'9'];
lettre:set of Ansichar=['a'..'z','A'..'Z','_'];
Aerror:integer=0;
type
tabNom = TstringList;
tabVal=array of float;
typeFonc1=function(x:float):float;
typgenre=(op,nbr,vari,fonc);
ptelem=^typelem ;
typelem=record
case genre:typgenre of
op:(g,d:ptelem;opnom:Ansichar);
nbr:(vnbr:float);
vari:(num:byte);
fonc:(f:typeFonc1;arg:ptelem);
end;
procedure CreerArbre(var rac:ptelem;chdef:AnsiString;var pc:integer;
nomVar:TstringList);
{ pc et n doivent être initialisés avant l'appel }
procedure DetruireArbre(var rac:ptelem);
function affarbre0(var rac:ptelem; nomVar:TstringList): AnsiString;
Function evaluer(var rac:ptelem; valeur:tabval):float;
Function derivee(rac:ptelem;num:integer):ptelem;
procedure simplifier(var r:ptelem);
procedure VerifierExpression(var st:AnsiString;var pc:integer;var error:integer);
{ pc doit être initialisé }
procedure VerifierEgalite(st:AnsiString;var pc:integer;var error:integer;
var st1:AnsiString);
function numeroVariable(st:AnsiString; nomVar:TstringList): integer;
procedure verifierListe(list:TstringList;var lig,col,error:integer);
procedure CreerArbreListe(var rac:ptelem;texte:TstringList; nomVar:TstringList);
IMPLEMENTATION
const
ensop:set of Ansichar=['(',')','+','-','*','/','^'];
opad:set of Ansichar=['+','-'];
opmult:set of Ansichar=['*','/'];
var
FunctionList:TstringList;
DerivList: TstringList;
numVar:byte; { sert pour derivee }
PlusDeSimp:boolean; { sert pour simplifier }
function Fheaviside(x:float):float;
begin
if x<0 then result:=0
else result:= 1;
end;
function Fdirac (x:float):float;
begin
if x=0
then result:=1E200
else result:=0;
end;
function Fabs(x:float):float;
begin
Fabs:=abs(x);
end;
function Fnul(x:float):float;
begin
Fnul:=0;
end;
function Fsin(x:float):float;
begin
Fsin:=sin(x);
end;
function Fcos(x:float):float;
begin
Fcos:=cos(x);
end;
function Farctg(x:float):float;
begin
Farctg:=arctan(x);
end;
function Fexp(x:float):float;
begin
if abs(x)<690 then Fexp:=exp(x)
else
begin
if x<0 then Fexp:=1E-300
else Fexp:=1E300;
Aerror:=205;
end;
end;
function Flog(x:float):float;
begin
if x>0 then Flog:=ln(x)
else
begin
Flog:=-1E300;
Aerror:=206;
end;
end;
function Ffrac(x:float):float;
begin
Ffrac:=frac(x);
end;
function Fint(x:float):float;
begin
Fint:=int(x);
end;
function Fsqr(x:float):float;
begin
Fsqr:=sqr(x);
end;
function Fsqrt(x:float):float;
begin
if x>=0 then Fsqrt:=sqrt(x)
else
begin
Fsqrt:=0;
Aerror:=207;
end;
end;
function Ftg(x:float):float;
var
y:float;
begin
y:=x/pi-0.5;
y:=x+pi*(0.5+trunc(y));
if abs(y)>1E-19
then Ftg:=sin(x)/cos(x)
else
begin
Ftg:=0;
Aerror:=208;
end;
end;
function Fcotg(x:float):float;
var
y:float;
begin
y:=x/pi;
y:=x+pi*(trunc(y));
if abs(y)>1E-300
then Fcotg:=cos(x)/sin(x)
else
begin
Fcotg:=0;
Aerror:=209;
end;
end;
function Farcsin(x:float):float;
begin
if abs(x)<1E-300 then Farcsin:=0
else
if abs(x)<=1
then Farcsin:=2*arctan( (1-sqrt(1-sqr(x)))/x)
else
begin
Farcsin:=0;
Aerror:=210;
end;
end;
function Farccos(x:float):float;
begin
if abs(x)<=1 then
begin
if x<-1+1E-19 then Farccos:=pi
else
Farccos:=2*arctan((1-x)/(1+x));
end
else
begin
Farccos:=0;
Aerror:=211;
end
end;
function Farccotg(x:float):float;
begin
if abs(x)<1E-300 then Farccotg:=Pi/2
else
begin
Farccotg:=arctan(1/x);
if x<0 then x:=x+pi;
end;
end;
function Fsh(x:float):float;
begin
if abs(x)<690 then Fsh:=0.5*(exp(x)-exp(-x))
else
begin
Fsh:=0;
Aerror:=212;
end;
end;
function Fch(x:float):float;
begin
if abs(x)<690 then Fch:=0.5*(exp(x)+exp(-x))
else
begin
Fch:=0;
Aerror:=213;
end;
end;
function Fth(x:float):float;
begin
if abs(x)<690
then Fth:=(exp(x)-exp(-x))/(exp(x)+exp(-x))
else
begin
Fth:=0;
Aerror:=213;
end;
end;
function Fcoth(x:float):float;
begin
if abs(x)<1E-19 then
begin
Fcoth:=0;
Aerror:=213;
end
else
if x<-690 then Fcoth:=-1
else
if x>690 then Fcoth:=1
else Fcoth:=(exp(x)+exp(-x))/(exp(x)-exp(-x));
end;
function Ferf(x:float):float;
begin
//result:=erf(x);
end;
procedure AddFunction(name: AnsiString; f: typefonc1; derivee: AnsiString);
begin
FunctionList.addObject(name, @f);
DerivList.AddObject(derivee,nil);
end;
function calculDeriv(st: AnsiString): pointer;
var
pc:integer;
rac:ptelem;
nomvar: TstringList;
begin
nomvar:= TstringList.create;
nomvar.Add('x');
pc:=1;
CreerArbre( rac, st, pc, nomVar);
result:=rac;
nomvar.Free;
end;
procedure InitFunctions;
var
i:integer;
begin
FunctionList:=Tstringlist.create;
DerivList:=Tstringlist.create;
AddFunction( 'SIN' , Fsin, 'cos(x)');
AddFunction( 'COS' , Fcos, '-sin(x)');
AddFunction( 'TAN' , Ftg, '1+sqr(tan(x))');
AddFunction( 'TG' , Ftg, '1+sqr(tan(x))');
AddFunction( 'COT' , Fcotg, '-1-sqr(cotan(x))');
AddFunction( 'COTG' , Fcotg, '-1-sqr(cotan(x))');
AddFunction( 'COTAN' , Fcotg, '-1-sqr(cotan(x))');
AddFunction( 'ATAN' , Farctg, '1/(1+sqr(x))');
AddFunction( 'ARCTAN' , Farctg, '1/(1+sqr(x))');
AddFunction( 'ARCTG' , Farctg, '1/(1+sqr(x))');
AddFunction( 'ARCSIN' , Farcsin, '1/sqrt(1-sqr(x))');
AddFunction( 'ARCCOS' , Farccos, '-1/sqrt(1-sqr(x)) ');
AddFunction( 'EXP' , Fexp, 'exp(x)');
AddFunction( 'LN' , Flog, '1/x');
AddFunction( 'LOG' , Flog, '1/x ');
AddFunction( 'SQR' , Fsqr, '2*x');
AddFunction( 'SQRT' , Fsqrt, '1/2/sqrt(x)');
AddFunction( 'SH' , Fsh, 'ch(x)');
AddFunction( 'CH' , Fch, 'sh(x)');
AddFunction( 'TH' , Fth, '1-sqr(th(x))');
AddFunction( 'DIRAC', Fdirac, '');
AddFunction( 'HEAVISIDE', Fheaviside, 'DIRAC(x)');
AddFunction( 'ABS' , Fabs, 'HEAVISIDE(x)*2-1');
AddFunction( 'erf' , Ferf, '2/sqrt(PI)*exp(-x*x)');
with DerivList do
for i:=0 to count-1 do
objects[i]:= CalculDeriv(strings[i]);
end;
procedure FreeFunctions;
var
i:integer;
p: ptElem;
begin
FunctionList.free;
with DerivList do
for i:=0 to count-1 do
begin
p:=ptElem(objects[i]);
detruireArbre(p);
end;
DerivList.free;
end;
function ecrireel(x:float):AnsiString;
var
i:integer;
ch:AnsiString;
begin
if x=0 then begin ecrireel:='0';exit;end;
if (x<-1e10) or ((x>-1e-10) and (x<1E-10)) or (x>1E+10) then
begin
str(x,ch);
delete(ch,1,1);
if x>=0 then delete(ch,1,1);
i:=pos('E',ch)-1;
while ch[i] in ['0','.'] do
begin
delete(ch,i,1);
i:=i-1;
end;
end
else
begin
str(x:0:10,ch);
if pos('.',ch)<>0 then
begin
i:=length(ch);
while ch[i] = '0' do
begin
delete(ch,i,1);
i:=i-1;
end;
if ch[i]='.' then delete(ch,i,1);
end;
end;
ecrireel:=ch;
end;
function numeroVariable(st:AnsiString; nomVar:TstringList): integer;
begin
result:= nomvar.IndexOf(st);
if result<0 then result:= nomvar.Add(st);
end;
function numeroFonction1(st:AnsiString):pointer;
var
i:integer;
begin
st:=Fmaj(st);
with functionList do
begin
i:=indexof(st);
if i>=0
then numeroFonction1:=objects[i]
else NumeroFonction1:=@Fnul;
end;
end;
function NomFonc1(f1:typeFonc1):AnsiString;
var
i:integer;
begin
with functionList do
begin
i:=indexofObject(@f1);
if i>=0
then nomFonc1:=strings[i]
else NomFonc1:='NUL';
end;
end;
procedure CreerArbre(var rac:ptelem;chdef:AnsiString;var pc:integer; nomVar:TstringList);
var
i:integer;
st:AnsiString;
function lirenb:float;
var
st1:AnsiString;
x:float;
code:integer;
begin
st1:='';
while chdef[pc] in chiffre+['E','.'] do
begin
st1:=st1+chdef[pc];
inc(pc);
if (chdef[pc-1]='E') AND (chdef[pc] in opad) then
begin
st1:=st1+chdef[pc];
inc(pc);
end;
end;
val(st1,x,code);
lirenb:=x;
end;
function liremot:AnsiString;
var
st1:AnsiString;
begin
st1:=chdef[pc];
inc(pc);
while chdef[pc] in lettre+chiffre do
begin
st1:=st1+chdef[pc];
inc(pc);
end;
liremot:=st1;
end;
procedure creeelem(var rac:ptelem);forward;
procedure creearb(var rac:ptelem);
var
n1,n2,n3,n4,n5,n6,n7:ptelem;
begin
n1:=nil;
n2:=nil;
if chdef[pc]='+' then inc(pc);
if chdef[pc]='-' then
begin
creeelem(n1);
creeelem(n2);
n1^.g:=nil;
n1^.d:=n2;
end
else
creeelem(n1);
while true do
begin
if chdef[pc]=')' then
begin
rac:=n1;exit;
end;
creeelem(n2);
creeelem(n3);
n2^.g:=n1;
n2^.d:=n3;
n1:=n2;
if not(n2^.opnom in opmult) then
begin
if chdef[pc]=')' then
begin
rac:=n2;pc:=pc;exit;
end;
if (chdef[pc] in opmult) then
begin
creeelem(n4);
creeelem(n5);
n2^.d:=n4;
n4^.g:=n3;
n4^.d:=n5;
n1:=n2;
while chdef[pc] in opmult do
begin
creeelem(n6);
creeelem(n7);
n6^.g:=n4;
n6^.d:=n7;
n1^.d:=n6;
n4:=n6;
end;
end;
end;
end; (* fin du while *)
end; (* fin de creearb *)
procedure creeelem;
var
na,nb:ptelem;
begin
if chdef[pc]=')' then exit;
if chdef[pc]='(' then
begin
inc(pc);
creearb(na);
rac:=na;
end
else
if chdef[pc] in ensop then
begin
new(rac);
with rac^ do
BEGIN
genre:=op;
opnom:=chdef[pc];
END;
end
else
if chdef[pc] in chiffre+['.'] then
begin
new(rac);
rac^.genre:=nbr;
rac^.vnbr:=lirenb;
dec(pc);
end
else
if chdef[pc] in lettre then
begin
new(rac);
st:=liremot;
if st='PI' then
begin
rac^.genre:=nbr;
rac^.vnbr:=pi;
dec(pc);
end
else
if chdef[pc]<>'(' then
begin
rac^.genre:=vari;
rac^.num:=NumeroVariable(st,nomvar);
dec(pc);
end
else
begin
rac^.genre:=fonc;
@rac^.f:=NumeroFonction1(st);
inc(pc);
creearb(na);
rac^.arg:=na;
end;
end;
inc(pc);
if chdef[pc]='^' then
begin
new(na); na^.genre:=op; na^.opnom:='^';
inc(pc);
creeelem(nb);
na^.g:=rac;
na^.d:=nb;
rac:=na;
end;
end;(*of creeelem *)
begin
while pos(' ',chdef)>0 do delete(chdef,pos(' ',chdef),1);
chdef:=chdef+')))))';
creearb(rac);
end;
procedure detruireArbre(var rac:ptelem);
begin
if rac<>nil then
case rac^.genre of
op: begin
detruireArbre(rac^.g);
detruireArbre(rac^.d);
dispose(rac);
end;
fonc:begin
detruireArbre(rac^.arg);
dispose(rac);
end;
nbr,vari:dispose(rac);
end;
rac:=nil;
end;
function affarbre0(var rac:ptelem; nomVar:TstringList): AnsiString;
begin
result:='';
if rac<>nil then
begin
case rac^.genre of
op :begin
if assigned(rac^.g) and (rac^.g.genre=op) then result:=result+'(';
result:=result + Affarbre0(rac^.g,nomvar);
if assigned(rac^.g) and (rac^.g.genre=op) then result:=result+')';
result:=result+rac^.opnom;
if assigned(rac^.d) and (rac^.d.genre=op) then result:=result+'(';
result:=result + Affarbre0(rac^.d,nomvar);
if assigned(rac^.d) and (rac^.d.genre=op) then result:=result+')';
end;
nbr: result:=result+ecrireel(rac^.vnbr);
vari: result:=result+nomvar[rac^.num];
fonc:begin
result:=result+NomFonc1(rac^.f);
result:=result+'(';
result:= result+Affarbre0(rac^.arg,nomvar);
result:=result+')';
end;
end;
end
end;
Function evaluer(var rac:ptelem; valeur:tabval):float;
const
epsilon=1E-10;
var
x,y,z:float;
begin
if rac=nil then evaluer:=0
else
begin
case rac^.genre of
op :begin
x:=evaluer(rac^.g,valeur);
y:=evaluer(rac^.d,valeur);
case rac^.opnom of
'+':evaluer:=x+y;
'-':evaluer:=x-y;
'*':evaluer:=x*y;
'/':if y<>0 then evaluer:=x/y
else
begin
evaluer:=0;
Aerror:=200;
end;
'^':if x=0 then evaluer:=0
else
begin
z:=y*ln(abs(x));
if abs(z)<690 then
begin
z:=exp(z);
if (x<0) and ( abs(frac(y))<epsilon ) and
( abs(y)<2147483647 ) and ( trunc(y) mod 2=1)
then evaluer:=-z
else evaluer:=z;
end
else
if z<0 then evaluer:=0
else
evaluer:=1E300;
end;
end;
end;
nbr:evaluer:=rac^.vnbr;
vari:begin
evaluer:=valeur[rac^.num];
end;
fonc:begin
x:=evaluer(rac^.arg,valeur);
evaluer:=rac^.f(x);
end;
end;
end
end;
function Pnombre(n:float):Ptelem;
var
a:ptElem;
begin
new(a);
a^.genre:=nbr;
a^.vnbr:=n;
Pnombre:=a;
end;
function Poppose(r:ptelem):ptelem;
var
a:ptelem;
begin
if r=nil then Poppose:=nil
else
begin
new(a);
a^.genre:=op;
a^.opnom:='-';
a^.g:=nil;
a^.d:=r;
Poppose:=a;
end;
end;
function Pcopie(r:ptelem):ptelem;
var
a:ptelem;
begin
if r=nil then Pcopie:=nil
else
begin
new(a);
move(r^,a^,sizeof(typelem));
case r^.genre of
op: begin
a^.g:=Pcopie(r^.g);
a^.d:=Pcopie(r^.d);
end;
fonc:a^.arg:=Pcopie(r^.arg);
end;
Pcopie:=a;
end;
end;
function PCopyAndReplace(r,r1:ptelem):ptelem;
var
a:ptelem;
begin
if r=nil then result:=nil
else
begin
if r^.genre=vari then a:= Pcopie(r1)
else
begin
new(a);
move(r^,a^,sizeof(typelem));
case r^.genre of
op: begin
a^.g:=PcopyAndReplace(r^.g,r1);
a^.d:=PcopyAndReplace(r^.d,r1);
end;
fonc: a^.arg:=PcopyAndReplace(r^.arg,r1);
end;
end;
result:= a;
end;
end;
function BuildDeriv(f: typeFonc1 ; rac:ptElem): ptElem;
var
n:integer;
begin
n:=FunctionList.IndexOfObject(@f);
result:= PcopyAndReplace(ptElem(DerivList.Objects[n]),rac);
end;
function derivee1(rac:ptelem):ptelem;
var
a,b,c,d,e,f:ptelem;
begin
if rac=nil then
begin
derivee1:=nil;
exit;
end;
case rac^.genre of
op :case rac^.opnom of
'+','-':
begin
new(a);;
a^.genre:=op;
a^.opnom:=rac^.opnom;
a^.g:=derivee1(rac^.g);
a^.d:=derivee1(rac^.d);
derivee1:=a;
end;
'*':
begin
new(a);new(b);new(c);
a^.genre:=op;
a^.opnom:='+';
a^.g:=b;
a^.d:=c;
b^.genre:=op;
b^.opnom:='*';
b^.g:=Pcopie(rac^.g);
b^.d:=derivee1(rac^.d);
c^.genre:=op;
c^.opnom:='*';
c^.g:=derivee1(rac^.g);
c^.d:=Pcopie(rac^.d);
derivee1:=a;
end;
'/':
begin
new(a);new(b);new(c);new(d);new(e);new(f);
a^.genre:=op;
a^.opnom:='/';
a^.g:=b;
a^.d:=c;
b^.genre:=op;
b^.opnom:='-';
b^.g:=d;
b^.d:=e;
c^.genre:=op;
c^.opnom:='^';
c^.g:=Pcopie(rac^.d);
c^.d:=f;
d^.genre:=op;
d^.opnom:='*';
d^.g:=Pcopie(rac^.d);
d^.d:=derivee1(rac^.g);
e^.genre:=op;
e^.opnom:='*';
e^.g:=Pcopie(rac^.g);
e^.d:=derivee1(rac^.d);
f^.genre:=nbr;
f^.vnbr:=2;
derivee1:=a;
end;
'^':
if (rac^.d^.genre=nbr) then
begin
new(a);new(b);new(c);
a^.genre:=op;
a^.opnom:='*';
a^.d:=derivee1(rac^.g);
a^.g:=b;
b^.genre:=op;
b^.opnom:='*';
b^.g:=Pcopie(rac^.d);
b^.d:=c;
c^.genre:=op;
c^.opnom:='^';
c^.g:=Pcopie(rac^.g);
c^.d:=Pnombre(rac^.d^.vnbr-1);
derivee1:=a;
end
else
begin
new(a);new(b);new(c);
a^.genre:=op;
a^.opnom:='*';
a^.g:=Pcopie(rac);
b^.genre:=op; {construction de valeur*Log(u)}
b^.opnom:='*';
b^.g:=Pcopie(rac^.d);
b^.d:=c;
c^.genre:=fonc;
c^.f:=Flog;
c^.arg:=Pcopie(rac^.g);
a^.d:=derivee1(b);
detruireArbre(b);
derivee1:=a;
end;
end;
nbr:derivee1:=nil;
vari:if rac^.num<>numVar
then derivee1:=nil
else derivee1:=Pnombre(1);
fonc:
begin
new(a);
a^.genre:=op;
a^.opnom:='*';
a^.g:=derivee1(rac^.arg);
a^.d:= BuildDeriv(rac^.f, rac^.arg) ;
derivee1:=a;
end; {of fonc}
end
end;
function derivee(rac:ptelem;num:integer):ptelem;
begin
numVar:=num;
result:=derivee1(rac);
simplifier(result);
end;
function Pegal(r1,r2:ptelem):boolean;
begin
Pegal:=false;
end;
procedure simplifier1(var r:ptelem);
var
sg,sd:ptelem;
begin
if r=nil then exit;
case r^.genre of
nbr:if r^.vnbr=0 then
begin
dispose(r);
r:=nil;
PlusDeSimp:=false;
end;
op:begin
simplifier1(r^.g);
simplifier1(r^.d);
sg:=r^.g;
sd:=r^.d;
case r^.opnom of
'+':if sg=nil then { 0+x=x }
begin
dispose(r);
r:=sd;
PlusDeSimp:=false;
end
else
if sd=nil then { x+0=x }
begin
dispose(r);
r:=sg;
PlusDeSimp:=false;
end;
'-':if sd=nil then { x-0=x }
begin
dispose(r);
r:=sg;
PlusDeSimp:=false;
end
else
if Pegal(sd,sg) then { x-x=0 }
begin
detruireArbre(r);
r:=nil;
PlusDeSimp:=false;
end
else
if (sg=nil) and (sd^.genre=op) and (sd^.opnom='-') and
(sd^.g=nil) then
begin { -(-x)=x }
dispose(r);
r:=sd^.d;
dispose(sd);
PlusDeSimp:=false;
end;
'*':if sd=nil then { x*0=0 }
begin
dispose(r);
detruireArbre(sg);
r:=nil;
PlusDeSimp:=false;
end
else
if sg=nil then { 0*x=0 }
begin
dispose(r);
detruireArbre(sd);
r:=nil;
PlusDeSimp:=false;
end
else
if (sd^.genre=nbr) and (sd^.vnbr=1) then
begin
dispose(r); { x*1=x }
dispose(sd);
r:=sg;
PlusDeSimp:=false;
end
else
if (sg^.genre=nbr) and (sg^.vnbr=1) then
begin
dispose(r); { 1*x=x }
dispose(sg);
r:=sd;
PlusDeSimp:=false;
end;
'/':if sg=nil then { 0/x=0 }
begin
dispose(r);
detruireArbre(sd);
r:=nil;
PlusDeSimp:=false;
end
else
if Pegal(sd,sg) then
begin { x/x=1 }
detruirearbre(sd);
detruirearbre(sg);
dispose(r);
r:=Pnombre(1);
PlusDeSimp:=false;
end;
'^':if sd=nil then { x^0=1 }
begin
dispose(r);
detruireArbre(sg);
r:=Pnombre(1);
PlusDeSimp:=false;
end
else
if (sd^.genre=nbr) and (sd^.vnbr=1) then
begin { x^1=x }
dispose(r);
dispose(sd);
r:=sg;
PlusDeSimp:=false;
end
else
if (sg^.genre=nbr) and (sg^.vnbr=1) then
begin { 1^x=1 }
detruirearbre(r);
r:=Pnombre(1);
PlusDeSimp:=false;
end;
end; { of case r^.opnom }
end; { of op }
fonc:
begin
sd:=r^.arg;
if @r^.f=@Fcos then
if (sd^.genre=nbr) and (sd^.vnbr=0) then
begin
detruirearbre(r);
r:=Pnombre(1);
PlusDeSimp:=false;
end
else
if @r^.f=@Fexp then
if (sd^.genre=nbr) and (sd^.vnbr=0) then
begin
detruirearbre(r);
r:=Pnombre(1);
PlusDeSimp:=false;
end
else
if @r^.f=@Fsin then
if (sd^.genre=nbr) and (sd^.vnbr=0) then
begin
detruirearbre(r);
r:=nil;
end
end; {of fonc }
end; { of case r^.genre }
end; { of simplifier }
procedure simplifier(var r:ptelem);
begin
repeat
PlusDeSimp:=true;
simplifier1(r);
until plusDeSimp;
end;
procedure VerifierExpression(var st:AnsiString;var pc:integer;var error:integer);
var
nbPar:integer;
st1,st2:AnsiString;
procedure verifierExp;forward;
procedure verifierTerme;forward;
procedure lire;
begin
repeat
if pc<length(st)
then inc(pc)
else
begin
error:=1;
exit;
end;
until st[pc]<>' ';
end;
procedure VerifierNombre;
begin
while (st[pc] in chiffre) and (error=0) do lire;
if error>0 then exit;
if st[pc]='.' then
begin
lire;if error>0 then exit;
if not (st[pc] in chiffre) then
begin
error:=4;
exit;
end;
while (st[pc] in chiffre) and (error=0) do lire;
if error>0 then exit;
end;
if (st[pc]='E') or (st[pc]='e') then
begin
lire;if error>0 then exit;
if st[pc] in opAd then lire;
if error>0 then exit;
if not (st[pc] in chiffre) then
begin
error:=5;
exit;
end;
while (st[pc] in chiffre) and (error=0) do lire;
if error>0 then exit;
end;
end;
procedure VerifierVarFonc;
var
stF:AnsiString;
begin
stF:='';
while (st[pc] in lettre+chiffre) and (error=0) do
begin
stF:=stF+st[pc];
lire;
end;
if error>0 then exit;
if st[pc]='(' then
begin
if numeroFonction1(stF)=@Fnul then
begin
error:=10;
exit;
end;
inc(nbpar);
lire;if error>0 then exit;
verifierExp;
if error>0 then exit;
if st[pc]=')' then
begin
dec(nbpar);
lire;if error>0 then exit;
end
else
begin
error:=6;
exit;
end;
end;
end;
procedure VerifierTerme;
begin
if error>0 then exit;
if st[pc] in chiffre then verifierNombre
else
if st[pc] in lettre then verifierVarFonc
else
if st[pc]='(' then
begin
inc(nbpar);
lire;if error>0 then exit;
verifierExp;
if error>0 then exit;
if st[pc]<>')' then
begin
error:=2;
exit;
end;
dec(nbpar);
lire;if error>0 then exit;
end
else
begin
error:=3;
exit;
end;
if st[pc]='^' then
begin
lire;if error>0 then exit;
verifierTerme;
end;
end;
procedure VerifierExp;
begin
if error>0 then exit;
if st[pc] in opAd then lire;
if error>0 then exit;
while true do
BEGIN
verifierTerme;
if error=1 then
begin
error:=0;
exit;
end;
if error>0 then exit;
if st[pc] in opAd+opMult then
begin
lire;
if error>0 then exit;
end
else
if Not( (st[pc]=')') or (pc=length(st)) ) then
begin
error:=7;
exit;
end
else exit;
END;
end;
begin
dec(pc);
error:=0;
nbPar:=0;
lire;
verifierExp;
if ( error=0 ) and (nbpar<>0) then error:=10;
st1:=copy(st,pc+1,length(st)-pc);
while pos(' ',st1)>0 do delete(st1,pos(' ',st1),1);
if ( error=0 ) and ( st1<>'') then error:=11;
st2:=st;
while pos(' ',st2)>0 do delete(st2,pos(' ',st2),1);
if st2='' then
begin
error:=0;
pc:=1;
end;
end;
procedure VerifierEgalite(st:AnsiString;var pc:integer;var error:integer;
var st1:AnsiString);
procedure lire;
begin
repeat
if pc<length(st)
then inc(pc)
else
begin
error:=100;
exit;
end;
until st[pc]<>' ';
end;
begin
st1:='';
error:=0;
dec(pc);
lire;
if error>0 then
begin
if pc=0 then pc:=1;
exit;
end;
if Not (st[pc] in lettre) then
begin
error:=101;
exit;
end;
lire;
while (st[pc] in lettre+chiffre) and (error=0) do lire;
if pc>0 then st1:=copy(st,1,pc-1) else st1:='';
while pos(' ',st1)>0 do delete(st1,pos(' ',st1),1);
if Not (st[pc]='=') then
begin
error:=102;
exit;
end;
lire;
verifierExpression(st,pc,error);
end;
{**************************************************************************}
procedure CreerArbre1(var rac:ptelem;chdef:AnsiString;var pc:integer;
var nomVar:TstringList; exp:TstringList);
var
i:integer;
st:AnsiString;
function getExp(st1:AnsiString):ptElem;
var
i:integer;
begin
getExp:=nil;
i:=exp.indexof(st1);
if i>=0
then getExp:=Pcopie(ptElem(exp.objects[i]))
else getExp:=nil;
end;
function lirenb:float;
var
st1:AnsiString;
x:float;
code:integer;
begin
st1:='';
while chdef[pc] in chiffre+['E','.'] do
begin
st1:=st1+chdef[pc];
inc(pc);
if (chdef[pc-1]='E') AND (chdef[pc] in opad) then
begin
st1:=st1+chdef[pc];
inc(pc);
end;
end;
val(st1,x,code);
lirenb:=x;
end;
function liremot:AnsiString;
var
st1:AnsiString;
begin
st1:=chdef[pc];
inc(pc);
while chdef[pc] in lettre+chiffre do
begin
st1:=st1+chdef[pc];
inc(pc);
end;
liremot:=st1;
end;
procedure creeelem(var rac:ptelem);forward;
procedure creearb(var rac:ptelem);
var
n1,n2,n3,n4,n5,n6,n7:ptelem;
begin
n1:=nil;
n2:=nil;
if chdef[pc]='+' then inc(pc);
if chdef[pc]='-' then
begin
creeelem(n1);
creeelem(n2);
n1^.g:=nil;
n1^.d:=n2;
end
else
creeelem(n1);
while true do
begin
if chdef[pc]=')' then
begin
rac:=n1;exit;
end;
creeelem(n2);
creeelem(n3);
n2^.g:=n1;
n2^.d:=n3;
n1:=n2;
if not(n2^.opnom in opmult) then
begin
if chdef[pc]=')' then
begin
rac:=n2;pc:=pc;exit;
end;
if (chdef[pc] in opmult) then
begin
creeelem(n4);
creeelem(n5);
n2^.d:=n4;
n4^.g:=n3;
n4^.d:=n5;
n1:=n2;
while chdef[pc] in opmult do
begin
creeelem(n6);
creeelem(n7);
n6^.g:=n4;
n6^.d:=n7;
n1^.d:=n6;
n4:=n6;
end;
end;
end;
end; (* fin du while *)
end; (* fin de creearb *)
procedure creeelem;
var
na,nb:ptelem;
begin
if chdef[pc]=')' then exit;
if chdef[pc]='(' then
begin
inc(pc);
creearb(na);
rac:=na;
end
else
if chdef[pc] in ensop then
begin
new(rac);
with rac^ do
BEGIN
genre:=op;
opnom:=chdef[pc];
END;
end
else
if chdef[pc] in chiffre+['.'] then
begin
new(rac);
rac^.genre:=nbr;
rac^.vnbr:=lirenb;
dec(pc);
end
else
if chdef[pc] in lettre then
begin
st:=liremot;
if st='PI' then
begin
new(rac);
rac^.genre:=nbr;
rac^.vnbr:=pi;
dec(pc);
end
else
if chdef[pc]<>'(' then
begin
rac:=getExp(st);
if rac=nil then
begin
new(rac);
rac^.genre:=vari;
rac^.num:=NumeroVariable(st,nomvar);
end;
dec(pc);
end
else
begin
new(rac);
rac^.genre:=fonc;
@rac^.f:=NumeroFonction1(st);
inc(pc);
creearb(na);
rac^.arg:=na;
end;
end;
inc(pc);
if chdef[pc]='^' then
begin
new(na); na^.genre:=op; na^.opnom:='^';
inc(pc);
creeelem(nb);
na^.g:=rac;
na^.d:=nb;
rac:=na;
end;
end;(*of creeelem *)
begin
while pos(' ',chdef)>0 do delete(chdef,pos(' ',chdef),1);
chdef:=chdef+')))))';
creearb(rac);
end;
procedure verifierListe(list:TstringList;var lig,col,error:integer);
var
i:integer;
st1:AnsiString;
begin
with list do
for i:=0 to count-1 do
begin
lig:=i+1;
col:=1;
verifierEgalite(strings[i],col,error,st1);
if error<>0 then exit;
end;
end;
procedure compilerListe(Texte:TstringList;
var exp:TstringList;
nomvar:TstringList);
var
i:integer;
pc:integer;
rac:ptElem;
st,st1:AnsiString;
begin
nomvar.Clear;
exp.clear;
with texte do
for i:=0 to count-1 do
begin
st:=Fsupespace(strings[i]);
pc:=pos('=',st);
st1:=copy(st,1,pc-1);
inc(pc);
CreerArbre1(rac,st,pc,nomVar,exp);
exp.addObject(st1,Tobject(rac));
end;
end;
procedure CreerArbreListe(var rac:ptelem;texte:TstringList; nomVar:TstringList);
var
exp:TstringList;
i:integer;
f:text;
begin
exp:=TstringList.create;
compilerListe(Texte,exp,nomvar);
for i:=0 to exp.count-2 do
begin
rac:=ptElem(exp.objects[i]);
detruireArbre(rac);
end;
rac:=ptElem(exp.objects[exp.count-1]);
exp.free;
{
assign(f,'c:\delphe32\arbre.txt');
rewrite(f);
affarbre0(f,rac,nomvar);
close(f);
}
end;
Initialization
AffDebug('Initialization Darbre1',0);
initFunctions;
finalization
FreeFunctions;
end.
|
namespace org.remobjects.calculator;
interface
uses
java.util,
android.app,
android.content,
android.os,
android.util,
android.view,
android.widget,
Calculator.Engine;
type
MainActivity = public class(Activity)
private
var TbValue: TextView;
method btnBackspace(v: View);
method btnExecute(v: View);
method btnExit(v: View);
method btnChar(v: View);
public
method onCreate(savedInstanceState: Bundle); override;
end;
implementation
method MainActivity.btnBackspace(v: View);
begin
var s := TbValue.Text.toString();
if s.length() > 0 then begin
s := s.substring(0, s.length() - 1);
TbValue.Text := s;
end;
end;
method MainActivity.btnExecute(v: View);
begin
try
var eval := new Evaluator();
var res := eval.Evaluate(TbValue.Text.toString());
TbValue.Text := res.toString();
except
on e: Exception do
begin
var dlg := new AlertDialog.Builder(self);
dlg.Message := 'Error evaluating: ' + e.Message;
dlg.setPositiveButton('OK', nil);
dlg.Cancelable := true;
dlg.&create().show();
end;
end;
end;
method MainActivity.btnExit(v: View);
begin
finish();
end;
method MainActivity.btnChar(v: View);
begin
TbValue.Text := TbValue.Text.toString() + (Button(v)).Text.toString();
end;
method MainActivity.onCreate(savedInstanceState: Bundle);
begin
inherited onCreate(savedInstanceState);
ContentView := R.layout.main;
TbValue := TextView(findViewById(R.id.tbValue));
(Button(findViewById(R.id.btnBackspace))).OnClickListener := @btnBackspace;
(Button(findViewById(R.id.btnExit))).OnClickListener := @btnExit;
(Button(findViewById(R.id.btnEval))).OnClickListener := @btnExecute;
(Button(findViewById(R.id.btn0))).OnClickListener := @btnChar;
(Button(findViewById(R.id.btn1))).OnClickListener := @btnChar;
(Button(findViewById(R.id.btn2))).OnClickListener := @btnChar;
(Button(findViewById(R.id.btn3))).OnClickListener := @btnChar;
(Button(findViewById(R.id.btn4))).OnClickListener := @btnChar;
(Button(findViewById(R.id.btn5))).OnClickListener := @btnChar;
(Button(findViewById(R.id.btn6))).OnClickListener := @btnChar;
(Button(findViewById(R.id.btn7))).OnClickListener := @btnChar;
(Button(findViewById(R.id.btn8))).OnClickListener := @btnChar;
(Button(findViewById(R.id.btn9))).OnClickListener := @btnChar;
(Button(findViewById(R.id.btnAdd))).OnClickListener := @btnChar;
(Button(findViewById(R.id.btnSub))).OnClickListener := @btnChar;
(Button(findViewById(R.id.btnDiv))).OnClickListener := @btnChar;
(Button(findViewById(R.id.btnMul))).OnClickListener := @btnChar;
end;
end. |
(*
Copyright (c) 2016 Darian Miller
All rights reserved.
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, and/or sell copies of the
Software, and to permit persons to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice
appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation.
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 OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE
LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other
dealings in this Software without prior written authorization of the copyright holder.
As of January 2016, latest version available online at:
https://github.com/darianmiller/dxLib_Tests
*)
unit dxLib_Test_JSONFormatter;
interface
{$I '..\Dependencies\dxLib\Source\dxLib.inc'}
uses
TestFramework,
dxLib_JSONFormatter;
type
TestTdxJSONFormatter = class(TTestCase)
private
fFormatter:TdxJSONFormatter;
protected
procedure SetUp(); override;
procedure TearDown(); override;
function FormatObject(const aName:String;
const aValue:String;
const aIdentLevel:Integer=1;
const aIdentString:String=DEFAULT_IDENT_SPACING):String;
published
procedure TestEmptyObject();
procedure TestEmptyObjectWithWhitespace();
procedure TestEmptyArray();
procedure TestEmptyArrayWithWhitespace();
procedure TestEmptyObjectWithEmptyArray();
procedure TestSingleStringObject();
procedure TestSingleBooleanObject();
procedure TestSingleIntegerObject();
procedure TestSingleNullObject();
procedure TestCustomColonPrefixSpacing();
procedure TestCustomColonSuffixSpacing();
procedure TestCustomIdentSpacing();
procedure TestCompactOutput();
procedure TestObjectArray();
procedure TestInvalidText();
end;
implementation
uses
dxLib_JSONUtils,
dxLib_Strings;
procedure TestTdxJSONFormatter.Setup();
begin
inherited;
fFormatter := TdxJSONFormatter.Create();
end;
procedure TestTdxJSONFormatter.Teardown();
begin
fFormatter.Free();
inherited;
end;
function TestTdxJSONFormatter.FormatObject(const aName:String;
const aValue:String;
const aIdentLevel:Integer=1;
const aIdentString:String=DEFAULT_IDENT_SPACING):String;
var
i:Integer;
begin
Result := '{' + sLineBreak;
for i := 1 to aIdentLevel do
begin
Result := Result + aIdentString;
end;
Result := Result + '"' + aName + '"'
+ fFormatter.ColonPrefix + ':' + fFormatter.ColonSuffix
+ aValue
+ sLineBreak;
for i := 1 to aIdentLevel-1 do
begin
Result := Result + aIdentString;
end;
Result := Result + '}';
end;
procedure TestTdxJSONFormatter.TestEmptyObject();
var
vFormatted:String;
begin
vFormatted := fFormatter.FormatJSON('{}');
Check(vFormatted = JSON_EMPTY_OBJECT);
end;
procedure TestTdxJSONFormatter.TestEmptyObjectWithWhitespace();
var
vFormatted:String;
begin
vFormatted := fFormatter.FormatJSON('{ }');
Check(vFormatted = JSON_EMPTY_OBJECT);
vFormatted := fFormatter.FormatJSON('{' + Char(#9) + '}');
Check(vFormatted = JSON_EMPTY_OBJECT);
vFormatted := fFormatter.FormatJSON('{' + sLineBreak + ' }');
Check(vFormatted = JSON_EMPTY_OBJECT);
vFormatted := fFormatter.FormatJSON(Char(#9) + ' { } ' + sLineBreak);
Check(vFormatted = JSON_EMPTY_OBJECT);
end;
procedure TestTdxJSONFormatter.TestEmptyArray();
var
vFormatted:String;
begin
vFormatted := fFormatter.FormatJSON('[]');
Check(vFormatted = JSON_EMPTY_ARRAY);
end;
procedure TestTdxJSONFormatter.TestEmptyArrayWithWhitespace();
var
vFormatted:String;
begin
vFormatted := fFormatter.FormatJSON('[ ]');
Check(vFormatted = JSON_EMPTY_ARRAY);
vFormatted := fFormatter.FormatJSON('[' + Char(#9) + ']');
Check(vFormatted = JSON_EMPTY_ARRAY);
vFormatted := fFormatter.FormatJSON('[' + sLineBreak + ' ]');
Check(vFormatted = JSON_EMPTY_ARRAY);
vFormatted := fFormatter.FormatJSON(' [ ] ' + sLineBreak);
Check(vFormatted = JSON_EMPTY_ARRAY);
end;
procedure TestTdxJSONFormatter.TestEmptyObjectWithEmptyArray();
var
vFormatted:String;
begin
vFormatted := fFormatter.FormatJSON('{[]}');
Check(vFormatted = '{' + sLineBreak + fFormatter.IndentString + '[]' + sLineBreak + '}');
end;
procedure TestTdxJSONFormatter.TestSingleStringObject();
var
vFormatted:String;
begin
vFormatted := fFormatter.FormatJSON('{ "Test" : "Output" }');
Check(vFormatted = FormatObject('Test', '"Output"'));
end;
procedure TestTdxJSONFormatter.TestSingleBooleanObject();
var
vFormatted:String;
begin
vFormatted := fFormatter.FormatJSON('{ "Test" : true }');
Check(vFormatted = FormatObject('Test', 'true'));
end;
procedure TestTdxJSONFormatter.TestSingleIntegerObject();
var
vFormatted:String;
begin
vFormatted := fFormatter.FormatJSON('{"Test" : 123}');
Check(vFormatted = FormatObject('Test', '123'));
end;
procedure TestTdxJSONFormatter.TestSingleNullObject();
var
vFormatted:String;
begin
vFormatted := fFormatter.FormatJSON('{"Test":null }');
Check(vFormatted = FormatObject('Test', 'null'));
end;
procedure TestTdxJSONFormatter.TestCustomColonPrefixSpacing();
const
PADDING_AMOUNT = ' ';
var
vSave:String;
vFormatted:String;
begin
vSave := fFormatter.ColonPrefix;
try
fFormatter.ColonPrefix := PADDING_AMOUNT;
vFormatted := fFormatter.FormatJSON('{"Test":null }');
Check(vFormatted = '{' + sLineBreak
+ fFormatter.IndentString + '"Test"'
+ PADDING_AMOUNT + ':' + fFormatter.ColonSuffix
+ 'null'
+ sLineBreak + '}');
finally
fFormatter.ColonPrefix := vSave;
end;
end;
procedure TestTdxJSONFormatter.TestCustomColonSuffixSpacing();
const
PADDING_AMOUNT = ' ';
var
vSave:String;
vFormatted:String;
begin
vSave := fFormatter.ColonSuffix;
try
fFormatter.ColonSuffix := PADDING_AMOUNT;
vFormatted := fFormatter.FormatJSON('{"Test":null }');
Check(vFormatted = '{' + sLineBreak
+ fFormatter.IndentString + '"Test"'
+ fFormatter.ColonPrefix + ':' + PADDING_AMOUNT
+ 'null'
+ sLineBreak + '}');
finally
fFormatter.ColonSuffix := vSave;
end;
end;
procedure TestTdxJSONFormatter.TestCustomIdentSpacing();
const
PADDING_AMOUNT = ' ';
var
vSave:String;
vFormatted:String;
vExpected:String;
begin
vSave := fFormatter.IndentString;
try
fFormatter.IndentString := PADDING_AMOUNT;
vFormatted := fFormatter.FormatJSON('{"Test":null }');
vExpected := FormatObject('Test', 'null', 1, PADDING_AMOUNT);
Check(vFormatted = vExpected);
finally
fFormatter.IndentString := vSave;
end;
end;
procedure TestTdxJSONFormatter.TestCompactOutput();
var
vFormatted:String;
vExpected:String;
begin
fFormatter.SetCompactStyle();
try
vFormatted := fFormatter.FormatJSON(' { "TestArray" : [ {"Test" : 1 }' + sLineBreak + ', { "Test" : 2 } ] }');
vExpected := '{"TestArray":[{"Test":1},{"Test":2}]}';
Check(vFormatted = vExpected);
finally
fFormatter.SetDefaultStyle();
end;
end;
procedure TestTdxJSONFormatter.TestObjectArray();
var
vFormatted:String;
vExpected:String;
begin
vFormatted := fFormatter.FormatJSON('{"TestArray":[{"Test":1},{"Test":2}]}');
vExpected := '{' + sLineBreak
+ fFormatter.IndentString + '"TestArray"'
+ fFormatter.ColonPrefix + ':' + fFormatter.ColonSuffix
+ '[' + sLineBreak
+ fFormatter.IndentString + fFormatter.IndentString
+ FormatObject('Test', '1', 3)
+ ', '
+ sLineBreak + fFormatter.IndentString + fFormatter.IndentString //needed if CommaLineBreak=True
+ FormatObject('Test', '2', 3)
+ sLineBreak + fFormatter.IndentString + ']'
+ sLineBreak + '}';
Check(vFormatted = vExpected);
end;
procedure TestTdxJSONFormatter.TestInvalidText();
var
vFormatted:String;
vExpected:String;
begin
vFormatted := fFormatter.FormatJSON('{"Test": 123} Invalid Text Here');
//invalid characters are left in place... but note that all JSON whitespace is stripped
vExpected := FormatObject('Test', '123') + 'InvalidTextHere';
Check(vFormatted = vExpected);
end;
initialization
RegisterTest(TestTdxJSONFormatter.Suite);
end.
|
{-$Id: CRC32.pas,v 1.1.1.1 2005/07/07 10:35:07 oleg Exp $}
{******************************************************************************}
{ Автоматизированная система управления персоналом }
{ (c) Донецкий национальный университет, 2002-2004 }
{******************************************************************************}
{ Модуль "Расчет CRC" }
{ Функции по расчету CRC а также перекодировке текста }
{ Ответственный: Кропов Валентин }
unit CRC32;
interface
function CalculateCRC32(var Buffer : String):longword;
function CRCToString(ACRC:LongWord):string;
function StringToOem(s: String): String;
function StringToHalcyonASCII(S : String) : String;
implementation
uses sysutils, dialogs, windows;
type
TData=array [0..0] of byte;
const
HalcyonASCIITable:array [0..255] of Byte =
($00, $01, $02, $03,
$04, $05, $06, $07, $08, $09, $0A, $0B, $0C, $0D, $0E, $0F, $10, $11, $12, $13,
$14, $15, $16, $17, $18, $19, $1A, $1B, $1C, $1D, $1E, $1F, $20, $21, $22, $23,
$24, $25, $26, $27, $28, $29, $2A, $2B, $2C, $2D, $2E, $2F, $30, $31, $32, $33,
$34, $35, $36, $37, $38, $39, $3A, $3B, $3C, $3D, $3E, $3F, $40, $41, $42, $43,
$44, $45, $46, $47, $48, $49, $4A, $4B, $4C, $4D, $4E, $4F, $50, $51, $52, $53,
$54, $55, $56, $57, $58, $59, $5A, $5B, $5C, $5D, $5E, $5F, $60, $61, $62, $63,
$64, $65, $66, $67, $68, $69, $6A, $6B, $6C, $6D, $6E, $6F, $70, $71, $72, $73,
$74, $75, $76, $77, $78, $79, $7A, $7B, $7C, $7D, $7E, $7F, $B0, $B6, $B7, $B8,
$B9, $BA, $C0, $C1, $C2, $C3, $C4, $C5, $C6, $C7, $C8, $C9, $CA, $CB, $CC, $CD,
$CE, $CF, $D0, $D1, $D2, $D3, $D4, $D5, $D6, $D7, $D8, $D9, $FF, $F6, $F7, $DA,
$FD, $DB, $B3, $15, $F0, $DC, $F2, $DD, $BF, $DE, $DF, $F4, $F8, $B1, $B2, $F9,
$B4, $B5, $14, $FA, $F1, $FC, $F3, $BB, $BC, $BD, $BE, $F5, $80, $81, $82, $83,
$84, $85, $86, $87, $88, $89, $8A, $8B, $8C, $8D, $8E, $8F, $90, $91, $92, $93,
$94, $95, $96, $97, $98, $99, $9A, $9B, $9C, $9D, $9E, $9F, $A0, $A1, $A2, $A3,
$A4, $A5, $A6, $A7, $A8, $A9, $AA, $AB, $AC, $AD, $AE, $AF, $E0, $E1, $E2, $E3,
$E4, $E5, $E6, $E7, $E8, $E9, $EA, $EB, $EC, $ED, $EE, $EF);
const
CRC32Table:array [0..255] of longword=
($00000000,$77073096,$EE0E612C,$990951BA,$076DC419,$706AF48F,$E963A535,$9E6495A3,
$0EDB8832,$79DCB8A4,$E0D5E91E,$97D2D988,$09B64C2B,$7EB17CBD,$E7B82D07,$90BF1D91,
$1DB71064,$6AB020F2,$F3B97148,$84BE41DE,$1ADAD47D,$6DDDE4EB,$F4D4B551,$83D385C7,
$136C9856,$646BA8C0,$FD62F97A,$8A65C9EC,$14015C4F,$63066CD9,$FA0F3D63,$8D080DF5,
$3B6E20C8,$4C69105E,$D56041E4,$A2677172,$3C03E4D1,$4B04D447,$D20D85FD,$A50AB56B,
$35B5A8FA,$42B2986C,$DBBBC9D6,$ACBCF940,$32D86CE3,$45DF5C75,$DCD60DCF,$ABD13D59,
$26D930AC,$51DE003A,$C8D75180,$BFD06116,$21B4F4B5,$56B3C423,$CFBA9599,$B8BDA50F,
$2802B89E,$5F058808,$C60CD9B2,$B10BE924,$2F6F7C87,$58684C11,$C1611DAB,$B6662D3D,
$76DC4190,$01DB7106,$98D220BC,$EFD5102A,$71B18589,$06B6B51F,$9FBFE4A5,$E8B8D433,
$7807C9A2,$0F00F934,$9609A88E,$E10E9818,$7F6A0DBB,$086D3D2D,$91646C97,$E6635C01,
$6B6B51F4,$1C6C6162,$856530D8,$F262004E,$6C0695ED,$1B01A57B,$8208F4C1,$F50FC457,
$65B0D9C6,$12B7E950,$8BBEB8EA,$FCB9887C,$62DD1DDF,$15DA2D49,$8CD37CF3,$FBD44C65,
$4DB26158,$3AB551CE,$A3BC0074,$D4BB30E2,$4ADFA541,$3DD895D7,$A4D1C46D,$D3D6F4FB,
$4369E96A,$346ED9FC,$AD678846,$DA60B8D0,$44042D73,$33031DE5,$AA0A4C5F,$DD0D7CC9,
$5005713C,$270241AA,$BE0B1010,$C90C2086,$5768B525,$206F85B3,$B966D409,$CE61E49F,
$5EDEF90E,$29D9C998,$B0D09822,$C7D7A8B4,$59B33D17,$2EB40D81,$B7BD5C3B,$C0BA6CAD,
$EDB88320,$9ABFB3B6,$03B6E20C,$74B1D29A,$EAD54739,$9DD277AF,$04DB2615,$73DC1683,
$E3630B12,$94643B84,$0D6D6A3E,$7A6A5AA8,$E40ECF0B,$9309FF9D,$0A00AE27,$7D079EB1,
$F00F9344,$8708A3D2,$1E01F268,$6906C2FE,$F762575D,$806567CB,$196C3671,$6E6B06E7,
$FED41B76,$89D32BE0,$10DA7A5A,$67DD4ACC,$F9B9DF6F,$8EBEEFF9,$17B7BE43,$60B08ED5,
$D6D6A3E8,$A1D1937E,$38D8C2C4,$4FDFF252,$D1BB67F1,$A6BC5767,$3FB506DD,$48B2364B,
$D80D2BDA,$AF0A1B4C,$36034AF6,$41047A60,$DF60EFC3,$A867DF55,$316E8EEF,$4669BE79,
$CB61B38C,$BC66831A,$256FD2A0,$5268E236,$CC0C7795,$BB0B4703,$220216B9,$5505262F,
$C5BA3BBE,$B2BD0B28,$2BB45A92,$5CB36A04,$C2D7FFA7,$B5D0CF31,$2CD99E8B,$5BDEAE1D,
$9B64C2B0,$EC63F226,$756AA39C,$026D930A,$9C0906A9,$EB0E363F,$72076785,$05005713,
$95BF4A82,$E2B87A14,$7BB12BAE,$0CB61B38,$92D28E9B,$E5D5BE0D,$7CDCEFB7,$0BDBDF21,
$86D3D2D4,$F1D4E242,$68DDB3F8,$1FDA836E,$81BE16CD,$F6B9265B,$6FB077E1,$18B74777,
$88085AE6,$FF0F6A70,$66063BCA,$11010B5C,$8F659EFF,$F862AE69,$616BFFD3,$166CCF45,
$A00AE278,$D70DD2EE,$4E048354,$3903B3C2,$A7672661,$D06016F7,$4969474D,$3E6E77DB,
$AED16A4A,$D9D65ADC,$40DF0B66,$37D83BF0,$A9BCAE53,$DEBB9EC5,$47B2CF7F,$30B5FFE9,
$BDBDF21C,$CABAC28A,$53B39330,$24B4A3A6,$BAD03605,$CDD70693,$54DE5729,$23D967BF,
$B3667A2E,$C4614AB8,$5D681B02,$2A6F2B94,$B40BBE37,$C30C8EA1,$5A05DF1B,$2D02EF8D);
function StringToHalcyonASCII(S : String) : String;
var
res_str : String;
i, k : Integer;
begin
for i := 1 to Length(S)
do begin
k := Ord(S[i]);
res_str := res_str + Chr(HalcyonASCIITable[k]);
end;
result := res_str;
end;
function StringToOem(s: String): String;
var
i : Integer;
begin
if s = '' then
begin
Result := '';
Exit;
end;
SetLength(Result, Length(s));
CharToOem(PChar(s),PChar(result));
for i := 1 to Length(result)
do
if Ord(result[i]) = $5F then result[i] := Chr($F9);
end;
function CRCToString(ACRC:LongWord):string;
var
n:array[1..4] of integer;
c:array[1..4] of Char;
i:integer;
begin
for i:=1 to 4 do begin
n[i]:=ACRC mod 256;
ACRC:=(ACRC-n[i]) div 256;
c[i]:=Chr(n[i]);
end;
CRCToString := c[4]+c[3]+c[2]+c[1];
//Result := c[1]+c[2]+c[3]+c[4];
end;
function CalculateCRC32(var Buffer : String):longword;
var
i : Integer;
_ax, _bx, _dx : Word;
x: LongWord;
begin
_ax := $FFFF;
_dx := $FFFF;
for i := 1 to Length(Buffer)
do begin
_bx := Ord(Buffer[i]);
asm
push ax
push bx
push dx
mov ax, _ax
mov bx, _bx
mov dx, _dx
xor bl,al //; Calculate table index
shl bx,1 //; Word offset
shl bx,1 //; DWord offset
//; 0 -> DH -> DL -> AH -> AL -> bit bucket
mov al,ah //; Shr AH into AL
mov ah,dl //; Shr DL into AH
mov dl,dh //; Shr DH into DL
xor dh,dh //; DH = 0
mov _ax, ax
mov _bx, bx
mov _dx, dx
pop dx
pop bx
pop ax
end;
_bx := _bx div 4;
//;Get new CRC from table
x := Crc32Table[_bx];
_ax := _ax xor (x mod $10000); //; Get new CRC-LO
_dx := _dx xor (x div $10000); //; Get new CRC-HI
end;
//_ax := not _ax;
//_dx := not _dx;
x := _dx shl 16 + _ax;
result := x;
end;
begin
{ test;}
end.
|
unit uBuffer2;
interface
uses Buffer, Controls, IBDatabase, IBQuery, Halcn6Db, SysUtils;
type
BufList = array of String;
TBufferTransaction2 = class
private
Buffers: BufList;
IB_Buffers: BufList;
First_PBKey, Last_PBKey: Integer;
WorkTransaction: TIBTransaction;
BufferTransaction: TIBTransaction;
BufferQuery: TIBQuery;
DeleteQuery: TIBQuery;
LockQuery: TIBQuery;
Id_Transaction: Integer;
DBFWritten: Boolean;
RecordAdded: Boolean;
public
constructor Create(In_Buffers, In_IB_Buffers: String;
fWorkTransaction: TIBTransaction);
procedure WriteRange(In_First_PBKey, In_Last_PBKey: Integer);
procedure RollbackOnError;
procedure AddRange(In_First_PBKey, In_Last_PBKey: Integer);
procedure Write;
procedure ClearDBF;
procedure Clear;
destructor Destroy; override;
end;
implementation
uses NagScreenUnit;
procedure TBufferTransaction2.WriteRange(In_First_PBKey, In_Last_PBKey: Integer);
var
NagScreen: TNagScreen;
begin
NagScreen := TNagScreen.Create(nil);
NagScreen.Show;
NagScreen.SetStatusText('Занесення iнформацii про вiдкат...');
try
AddRange(In_First_PBKey, In_Last_PBKey);
finally
NagScreen.Free;
end;
Write;
Clear;
end;
procedure TBufferTransaction2.RollbackOnError;
begin
if DBFWritten then
try
ClearDBF;
except
end;
if RecordAdded then
try
Clear;
except
end;
end;
procedure TBufferTransaction2.ClearDBF;
var
buf_num: Integer;
ID_PBKey: Integer;
begin
for buf_num:=0 to High(Buffers) do
begin
// открываем нужный dbf
BufferTable.Close;
BufferTable.TableName := Buffers[buf_num];
BufferTable.Open;
for Id_PBKey:=First_PBKey to Last_PBKey do
begin
if BufferTable.Locate('Id_PBKey', Id_PBKey, []) then
BufferTable.Delete;
end;
BufferTable.Close;
end;
end;
procedure TBufferTransaction2.Write;
var
buf_num: Integer;
begin
DBFWritten := True;
for buf_num:=0 to High(Buffers) do
ExportRange(WorkTransaction, First_PBKey, Last_PBKey, Buffers[buf_num], IB_Buffers[buf_num]);
end;
constructor TBufferTransaction2.Create(In_Buffers, In_IB_Buffers: String;
fWorkTransaction: TIBTransaction);
var
p1, p2, ind: Integer;
begin
// распихиваем строки по массивам
ind := 0;
while True do
begin
p1 := Pos(',', In_Buffers);
p2 := Pos(',', In_IB_Buffers);
if ( ( p1 = 0 ) and ( p2 <> 0 ) ) or ( ( p1 <> 0 ) and (p2 = 0 ) )
then raise Exception.Create('TBufferTransaction2.Create bug in strings!');
// дошли по последнего буфера
if ( p1 = 0 ) then
begin
SetLength(Buffers, ind+1);
SetLength(IB_Buffers, ind+1);
Buffers[ind] := Trim(In_Buffers);
IB_Buffers[ind] := Trim(In_IB_Buffers);
inc(ind);
break;
end
else
begin
SetLength(Buffers, ind+1);
SetLength(IB_Buffers, ind+1);
Buffers[ind] := Trim(Copy(In_Buffers, 1, p1-1));
IB_Buffers[ind] := Trim(Copy(In_IB_Buffers, 1, p2-1));
In_Buffers := Copy(In_Buffers, p1+1, Length(In_Buffers));
In_IB_Buffers := Copy(In_IB_Buffers, p2+1, Length(In_IB_Buffers));
inc(ind);
end;
end;
WorkTransaction := fWorkTransaction;
// создаем нужные объекты
BufferTransaction := TIBTransaction.Create(WorkTransaction.DefaultDatabase);
BufferTransaction.DefaultDatabase := WorkTransaction.DefaultDatabase;
LockQuery := TIBQuery.Create(WorkTransaction);
LockQuery.Database := WorkTransaction.DefaultDatabase;
LockQuery.Transaction := WorkTransaction;
BufferQuery := TIBQuery.Create(BufferTransaction);
BufferQuery.Database := BufferTransaction.DefaultDatabase;
BufferQuery.Transaction := BufferTransaction;
DeleteQuery := TIBQuery.Create(fWorkTransaction);
DeleteQuery.Database := fWorkTransaction.DefaultDatabase;
DeleteQuery.Transaction := fWorkTransaction;
// Получаем идентификатор ДБФ-транзакции
BufferTransaction.StartTransaction;
try
with BufferQuery do
begin
Close;
SQL.Text := 'SELECT ID_TRANSACTION FROM GET_ID_TRANSACTION';
Open;
Id_Transaction := BufferQuery['Id_Transaction'];
BufferTransaction.Commit;
end;
except on e: Exception do
begin
BufferTransaction.Rollback;
raise e;
end;
end;
RecordAdded := False;
DBFWritten := False;
end;
destructor TBufferTransaction2.Destroy;
begin
BufferQuery.Free;
DeleteQuery.Free;
LockQuery.Free;
BufferTransaction.Free;
inherited Destroy;
end;
procedure TBufferTransaction2.AddRange(In_First_PBKey, In_Last_PBKey: Integer);
var
buf_num: Integer;
begin
First_PBKey := In_First_PBKey;
Last_PBKey := In_Last_PBKey;
BufferTransaction.StartTransaction;
BufferQuery.Close;
BufferQuery.SQL.Text := 'EXECUTE PROCEDURE Buffer_Add_Range_2' +
'(:BUFFER_NAME, :IB_BUFFER_NAME, :First_PBKey, :Last_PBKey, :ID_TRANSACTION, :Id_System)';
try
for buf_num:=0 to High(Buffers) do
begin
BufferQuery.Close;
BufferQuery.ParamByName('First_PBKey').AsInteger := First_PBKey;
BufferQuery.ParamByName('Last_PBKey').AsInteger := Last_PBKey;
BufferQuery.ParamByName('Buffer_Name').AsString := Buffers[buf_num];
BufferQuery.ParamByName('IB_Buffer_Name').AsString := IB_Buffers[buf_num];
BufferQuery.ParamByName('Id_Transaction').AsInteger := Id_Transaction;
BufferQuery.ParamByName('Id_System').AsInteger := Buffer_Id_System;
BufferQuery.ExecSQL;
end;
BufferTransaction.Commit;
// заблокировать записи, чтобы кто-то другой при старте их не стер
LockQuery.SQL.Text := 'SELECT * FROM Buff_Tran WHERE Id_Transaction = '
+ IntToStr(Id_Transaction) + ' WITH LOCK';
LockQuery.Open;
RecordAdded := True;
except on e: Exception do
begin
BufferTransaction.Rollback;
raise e;
end;
end;
end;
procedure TBufferTransaction2.Clear;
begin
// BufferTransaction.StartTransaction;
// try
DeleteQuery.SQL.Text := 'DELETE FROM Buff_Tran WHERE Id_Transaction = '
+ IntToStr(Id_Transaction);
DeleteQuery.ExecSQL;
// BufferTransaction.Commit;
// except on e: Exception do
// begin
// BufferTransaction.Rollback;
// raise e;
// end;
// end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.