text stringlengths 14 6.51M |
|---|
unit frmXEROTestU;
interface
uses
MidasLib,
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, XERO.API,
XERO.API.Response.ClientDataset, XERO.API.Invoices, Data.DB, Vcl.Grids,
Vcl.DBGrids, Vcl.Samples.Spin, Vcl.ComCtrls, Vcl.Imaging.pngimage;
type
TfrmXERO = class(TForm)
memoLog: TMemo;
XEROAppDetails: TXEROAppDetails;
XEROInvoices: TXEROInvoices;
XEROInvoiceResponse: TXEROInvoiceResponse;
dsInvoices: TDataSource;
dsInvoiceItems: TDataSource;
PageControlMain: TPageControl;
tabSearch: TTabSheet;
tabOptions: TTabSheet;
Panel1: TPanel;
btnSearch: TButton;
PageControlOptions: TPageControl;
tabConsumerDetails: TTabSheet;
tabPublicKey: TTabSheet;
tabPrivateKey: TTabSheet;
GroupBox2: TGroupBox;
Label3: TLabel;
editConsumerKey: TEdit;
Label4: TLabel;
editConsumerSecret: TEdit;
memoPrivateKey: TMemo;
memoPublicKey: TMemo;
PageControlSearch: TPageControl;
tabSearchGetDateRange: TTabSheet;
GroupBox1: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Label5: TLabel;
editStartDate: TDateTimePicker;
editEndDate: TDateTimePicker;
comboInvoiceType: TComboBox;
tabSearchLowLevel: TTabSheet;
GroupBox3: TGroupBox;
Label6: TLabel;
Label7: TLabel;
comboLowLevelSearch: TComboBox;
comboLowLevelOrderBy: TComboBox;
editLowLevelPage: TSpinEdit;
Label8: TLabel;
Label9: TLabel;
editLowLevelLastModifiedTime: TDateTimePicker;
tabAbout: TTabSheet;
PageControlData: TPageControl;
tabDataView: TTabSheet;
DBGridInvoices: TDBGrid;
DBGridInvoiceItems: TDBGrid;
tabXML: TTabSheet;
memoXML: TMemo;
GroupBox4: TGroupBox;
Image1: TImage;
memoAbout: TMemo;
Splitter1: TSplitter;
lblFileName: TLabel;
lblInfo: TLabel;
editLowLevelLastModifiedDate: TDateTimePicker;
procedure btnSearchClick(Sender: TObject);
procedure OnLog(Sender: TObject; AMessage: string);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure lblFileNameClick(Sender: TObject);
private
FSettingsFileName: TFileName;
procedure ResizeDBGrid(ADBGrid: TDBGrid);
procedure LoadSettings;
procedure SaveSettings;
public
{ Public declarations }
end;
var
frmXERO: TfrmXERO;
implementation
{$R *.dfm}
uses
System.DateUtils, System.IniFiles, Winapi.ShlObj, Winapi.ShellAPI;
function GetShellFolderPath(AFolder: integer): string;
const
SHGFP_TYPE_CURRENT = 0;
var
path: array [0 .. MAX_PATH] of char;
begin
if SUCCEEDED(SHGetFolderPath(0, AFolder, 0, SHGFP_TYPE_CURRENT, @path[0]))
then
Result := path
else
Result := '';
end;
function CheckDirectoryExists(ADirectory: string; ACreate: boolean): boolean;
begin
try
if ACreate then
begin
if not DirectoryExists(ADirectory) then
begin
ForceDirectories(ADirectory);
end;
end;
finally
Result := DirectoryExists(ADirectory);
end;
end;
function ExecuteFile(const Operation, FileName, Params, DefaultDir: string;
ShowCmd: word): integer;
var
zFileName, zParams, zDir: array [0 .. 255] of char;
begin
Result := ShellExecute(Application.Handle, PChar(Operation),
StrPCopy(zFileName, FileName), StrPCopy(zParams, Params),
StrPCopy(zDir, DefaultDir), ShowCmd);
end;
function GetUserAppDataDir: string;
begin
Result := IncludeTrailingPathDelimiter
(IncludeTrailingPathDelimiter(GetShellFolderPath(CSIDL_APPDATA)) +
Application.Title);
CheckDirectoryExists(Result, True);
end;
procedure TfrmXERO.FormCreate(Sender: TObject);
begin
PageControlMain.ActivePageIndex := 0;
PageControlOptions.ActivePageIndex := 0;
PageControlSearch.ActivePageIndex := 0;
PageControlData.ActivePageIndex := 0;
editLowLevelLastModifiedTime.Time := 0;
editLowLevelLastModifiedDate.Date := 0;
editStartDate.Date := StartOfTheMonth(Today);
editEndDate.Date := Today;
FSettingsFileName := GetUserAppDataDir + 'settings.ini';
LoadSettings;
end;
procedure TfrmXERO.FormDestroy(Sender: TObject);
begin
SaveSettings;
end;
procedure TfrmXERO.lblFileNameClick(Sender: TObject);
begin
ExecuteFile('open', lblFileName.Hint, '', ExtractFilePath(lblFileName.Hint),
SW_NORMAL);
end;
procedure TfrmXERO.LoadSettings;
var
INIFile: TIniFile;
begin
INIFile := TIniFile.Create(FSettingsFileName);
try
editConsumerKey.Text := INIFile.ReadString('XERO', 'ConsumerKey', '');
editConsumerSecret.Text := INIFile.ReadString('XERO', 'ConsumerSecret', '');
memoPrivateKey.Lines.Text := INIFile.ReadString('XERO', 'PrivateKey', '');
memoPublicKey.Lines.Text := INIFile.ReadString('XERO', 'PublicKey', '');
lblFileName.Hint := FSettingsFileName;
lblFileName.Caption := ExtractFileName(FSettingsFileName);
finally
FreeAndNil(INIFile);
end;
end;
procedure TfrmXERO.SaveSettings;
var
INIFile: TIniFile;
PublicKey, Privatekey: string;
begin
INIFile := TIniFile.Create(FSettingsFileName);
try
PublicKey := StringReplace(memoPublicKey.Lines.Text, #13, '',
[rfReplaceAll, rfIgnoreCase]);
PublicKey := StringReplace(PublicKey, #10, '',
[rfReplaceAll, rfIgnoreCase]);
Privatekey := StringReplace(memoPrivateKey.Lines.Text, #13, '',
[rfReplaceAll, rfIgnoreCase]);
Privatekey := StringReplace(Privatekey, #10, '',
[rfReplaceAll, rfIgnoreCase]);
INIFile.WriteString('XERO', 'ConsumerKey', editConsumerKey.Text);
INIFile.WriteString('XERO', 'ConsumerSecret', editConsumerSecret.Text);
INIFile.WriteString('XERO', 'PrivateKey', Privatekey);
INIFile.WriteString('XERO', 'PublicKey', PublicKey);
finally
FreeAndNil(INIFile);
end;
end;
procedure TfrmXERO.OnLog(Sender: TObject; AMessage: string);
begin
memoLog.Lines.Insert(0, AMessage);
Application.ProcessMessages;
end;
procedure TfrmXERO.ResizeDBGrid(ADBGrid: TDBGrid);
var
ColumnIdx: integer;
begin
with ADBGrid do
begin
Columns.BeginUpdate;
try
try
for ColumnIdx := 0 to Pred(Columns.Count) do
begin
if Assigned(Columns.Items[ColumnIdx].Field) then
begin
with Columns.Items[ColumnIdx] do
begin
case Columns.Items[ColumnIdx].Field.DataType of
ftString, ftMemo, ftFmtMemo, ftWideString:
begin
Columns.Items[ColumnIdx].Width := 100;
end;
ftBoolean, ftSmallint, ftBytes:
begin
Columns.Items[ColumnIdx].Width := 25;
end;
ftDate, ftTime, ftDateTime:
begin
Columns.Items[ColumnIdx].Width := 75;
end;
else
begin
Columns.Items[ColumnIdx].Width := 50;
end;
end;
end;
end;
end;
except
end;
finally
Columns.EndUpdate;
end;
end;
end;
procedure TfrmXERO.btnSearchClick(Sender: TObject);
var
LastModified: TDateTime;
begin
dsInvoices.DataSet := nil;
dsInvoiceItems.DataSet := nil;
XEROAppDetails.Privatekey.Text := memoPrivateKey.Lines.Text;
XEROAppDetails.PublicKey.Text := memoPublicKey.Lines.Text;
XEROAppDetails.ConsumerKey := editConsumerKey.Text;
XEROAppDetails.ConsumerSecret := editConsumerSecret.Text;
XEROInvoices.XEROAppDetails := XEROAppDetails;
XEROInvoices.OnLog := OnLog;
XEROInvoices.LogLevel := logDebug;
if PageControlSearch.ActivePage = tabSearchGetDateRange then
begin
XEROInvoices.GetDateRange(editStartDate.Date, editEndDate.Date, 1,
TXEROInvoiceType(comboInvoiceType.ItemIndex));
end;
if PageControlSearch.ActivePage = tabSearchLowLevel then
begin
if editLowLevelLastModifiedDate.Date <> 0 then
begin
LastModified := DateOf(editLowLevelLastModifiedDate.Date) +
TimeOf(editLowLevelLastModifiedTime.Time);
end
else
begin
LastModified := 0;
end;
XEROInvoices.Find(comboLowLevelSearch.Text, comboLowLevelOrderBy.Text,
editLowLevelPage.Value, LastModified);
end;
if XEROInvoices.Response.Result then
begin
memoXML.Lines.Text := XEROInvoiceResponse.AsString;
dsInvoices.DataSet := XEROInvoiceResponse.MasterDataset;
dsInvoiceItems.DataSet := XEROInvoiceResponse.DetailDataset;
ResizeDBGrid(DBGridInvoices);
ResizeDBGrid(DBGridInvoiceItems);
end
else
begin
MessageDlg(XEROInvoices.Response.ErrorMessage, mtError, [mbOK], 0);
end;
end;
end.
|
(*
#: 158462 S2/Turbo Pascal v.5
02-Feb-89 12:31:53
Sb: #158453-SetRGBPalette
Fm: John Sieraski (Sysop) 76117,2022
To: Art Steinmetz 76044,3204
Art,
Here's a few routines for reading and setting the DAC registers on MCGA
and VGA cards. All of this information can be found in the book
"Programmer's Guide to IBM PC & PS/2 Video Systems" by Richard Wilton.
*)
UNIT VgaUtil;
interface
uses
Dos;
type
RGBColor = record
Red, Green, Blue : byte;
end;
VGAPalette = array[0..255] of RGBColor;
var
VGAPal : VGAPalette; { Stores entire DAC block }
RGBVal : RGBColor; { Stores single DAC register }
procedure ReadSingleDAC(DACNum : byte; var RGBVal : RGBColor);
procedure SetSingleDAC(DACNum : byte; RGBVal : RGBColor);
procedure ReadDACBlock(Start, Count : integer; var VGAPal : VGAPalette);
procedure SetDACBlock(Start, Count : integer; var VGAPal : VGAPalette);
(* ============================================================= *)
implementation
procedure ReadSingleDAC(DACNum : byte; var RGBVal : RGBColor);
var
Regs : Registers;
begin
with Regs do
begin
AH := $10; AL := $15;
BX := DACNum;
Intr($10, Regs);
with RGBVal do
begin
Red := DH; Green := CH; Blue := CL;
end;
end;
end;
(* +++++++++++++++++++++++++++++++++++++++++++++++++++++++ *)
procedure SetSingleDAC(DACNum : byte; RGBVal : RGBColor);
var
Regs : Registers;
begin
with Regs do
begin
AH := $10; AL := $10;
BX := DACNum;
with RGBVal do
begin
DH := Red; CH := Green; CL := Blue;
end;
Intr($10, Regs);
end;
end;
(* +++++++++++++++++++++++++++++++++++++++++++++++++++++++ *)
procedure ReadDACBlock(Start, Count : integer; var VGAPal : VGAPalette);
var
Regs : Registers;
begin
with Regs do
begin
AH := $10; AL := $17;
BX := Start;
CX := Count;
ES := Seg(VGAPal);
DX := Ofs(VGAPal);
end;
Intr($10, Regs);
end;
(* +++++++++++++++++++++++++++++++++++++++++++++++++++++++ *)
procedure SetDACBlock(Start, Count : integer; var VGAPal : VGAPalette);
var
Regs : Registers;
begin
with Regs do
begin
AH := $10; AL := $12;
BX := Start;
CX := Count;
ES := Seg(VGAPal);
DX := Ofs(VGAPal);
end;
Intr($10, Regs);
end;
BEGIN
END {VgaUtil}. |
/////////////////////////////////////////////////////////
// //
// FlexGraphics library //
// Copyright (c) 2002-2009, FlexGraphics software. //
// //
// History (undo/redo) base classes //
// //
/////////////////////////////////////////////////////////
unit FlexHistory;
{$I FlexDefs.inc}
interface
uses
Classes;
const
DefaultHistoryDepth = 100; // actions
type
THistory = class;
THistoryGroup = class;
THistoryActionClass = class of THistoryAction;
THistoryState = ( hsIdle, hsRecord, hsUndo, hsRedo );
THistoryAction = class
private
FOwner: THistory;
FParent: THistoryGroup;
FCaption: string;
FTag: integer;
protected
FState: THistoryState;
FDestroyAfterEnd: boolean;
procedure ChangeState(NewState: THistoryState); virtual;
function BeginState(NewState: THistoryState): boolean; virtual;
function EndState: boolean; virtual;
class function DoIsRecordable(Source: TObject;
Parent: THistoryGroup): boolean; virtual;
function DoIsSame(ActionClass: THistoryActionClass;
Source: TObject): boolean; virtual;
procedure DoActionCaption(Source: TObject; var ACaption: string); virtual;
procedure DoBeginAction(Source: TObject); virtual;
procedure DoEndAction; virtual;
procedure DoRecordAction(Source: TObject); virtual; abstract;
procedure DoUndo(Source: TObject); virtual; abstract;
procedure DoRedo(Source: TObject); virtual; abstract;
public
constructor Create(AOwner: THistory; AParent: THistoryGroup); virtual;
property Owner: THistory read FOwner;
property Caption: string read FCaption write FCaption;
property State: THistoryState read FState;
property Parent: THistoryGroup read FParent;
property DestroyAfterEnd: boolean read FDestroyAfterEnd;
property Tag: integer read FTag write FTag;
end;
THistoryStreamAction = class(THistoryAction)
protected
FUndoStream: TStream;
FRedoStream: TStream;
function ProcessSource(Stream: TStream; Source: TObject;
DoLoad: boolean): boolean; virtual; abstract;
procedure DoRecordAction(Source: TObject); override;
procedure DoUndo(Source: TObject); override;
procedure DoRedo(Source: TObject); override;
public
destructor Destroy; override;
property UndoStream: TStream read FUndoStream;
property RedoStream: TStream read FRedoStream;
end;
THistoryGroupClass = class of THistoryGroup;
THistoryGroup = class(THistoryAction)
private
FActions: TList;
FInProcessIndex: integer;
FInProcessSource: TObject;
function GetAction(Index: integer): THistoryAction;
function GetActionCount: integer;
protected
FDestroyIfEmpty: boolean;
procedure Clear;
procedure DoEndAction; override;
procedure DoUndo(Source: TObject); override;
procedure DoRedo(Source: TObject); override;
procedure DoRecordAction(Source: TObject); override;
function BeginAction(ActionClass: THistoryActionClass;
const Source: TObject; ATag: integer = 0): THistoryAction;
function EndAction: boolean;
function EraseAction: boolean;
public
constructor Create(AOwner: THistory; AParent: THistoryGroup); override;
destructor Destroy; override;
property ActionCount: integer read GetActionCount;
property Actions[Index: integer]: THistoryAction read GetAction; default;
property InProcessIndex: integer read FInProcessIndex;
property InProcessSource: TObject read FInProcessSource;
end;
THistoryGetActionSourceEvent = procedure(Sender: TObject;
Action: THistoryAction; var Source: TObject;
var Enabled: boolean) of object;
THistorySetActionSourceEvent = procedure(Sender: TObject;
Action: THistoryAction; const Source: TObject) of object;
THistoryGetActionCaptionEvent = procedure(Sender: TObject;
Action: THistoryAction; const Source: TObject;
var Caption: string) of object;
THistoryIsRecordableEvent = procedure(Sender: TObject;
var ActionClass: THistoryActionClass; var Source: TObject;
Parent: THistoryGroup; var IsRecordable: boolean) of object;
THistoryIsSameEvent = procedure(Sender: TObject;
ExistedAction: THistoryAction; NewActionClass: THistoryActionClass;
const NewSource: TObject; var IsSame: boolean) of object;
THistory = class
private
FOwner: TObject;
FActive: boolean;
FActions: TList;
FActionIndex: integer;
FDepth: integer;
FOnChange: TNotifyEvent;
FOnGetActionCaption: THistoryGetActionCaptionEvent;
FOnGetActionSource: THistoryGetActionSourceEvent;
FOnSetActionSource: THistorySetActionSourceEvent;
FOnIsRecordable: THistoryIsRecordableEvent;
FOnIsSame: THistoryIsSameEvent;
function GetInProcess: boolean;
function GetInProcessAction: THistoryAction;
function GetInProcessSource: TObject;
function GetIsRecordable: boolean;
function GetCaption(Index: integer): string;
function GetAction(Index: integer): THistoryAction;
function GetActionCount: integer;
procedure SetDepth(const Value: integer);
procedure SetActive(const Value: boolean);
protected
FGroup: THistoryGroup;
FGroupLevel: integer;
FDisableLevel: integer;
FState: THistoryState;
FInProcessSource: TObject;
procedure ChangeState(NewState: THistoryState); virtual;
procedure DeleteActions(FromIndex: integer = 0; ToIndex: integer = -1);
function Scroll: integer;
procedure DoChange; virtual;
function DoGetActionSource(Action: THistoryAction;
var Enabled: boolean): TObject; virtual;
procedure DoSetActionSource(Action: THistoryAction;
const Source: TObject); virtual;
function DoGetActionCaption(Action: THistoryAction;
const Source: TObject): string; virtual;
function DoIsRecordable(var ActionClass: THistoryActionClass;
var Source: TObject; Parent: THistoryGroup): boolean; virtual;
function DoIsSame(ExistedAction: THistoryAction;
NewActionClass: THistoryActionClass; NewSource: TObject): boolean; virtual;
public
constructor Create(AOwner: TObject);
destructor Destroy; override;
class procedure RegisterAction(Action: THistoryActionClass);
procedure Clear;
function IndexOf(Action: THistoryAction): integer;
function BeginAction(ActionClass: THistoryActionClass;
Source: TObject; ATag: integer = 0;
DoRecord: boolean = true): THistoryAction;
function EndAction: boolean;
function CancelAction: boolean;
function RecordAction(ActionClass: THistoryActionClass;
const Source: TObject; ATag: integer = 0): THistoryAction;
function EraseAction: boolean;
function OpenLastGroup: THistoryGroup;
function Undo: boolean; virtual;
function Redo: boolean; virtual;
procedure DisableRecording;
function EnableRecording: boolean;
property Active: boolean read FActive write SetActive default false;
property Owner: TObject read FOwner;
property State: THistoryState read FState;
property Depth: integer read FDepth write SetDepth
default DefaultHistoryDepth;
property DisableLevel: integer read FDisableLevel;
property GroupLevel: integer read FGroupLevel;
property ActionCount: integer read GetActionCount;
property Actions[Index: integer]: THistoryAction read GetAction; default;
property ActionIndex: integer read FActionIndex;
property IsRecordable: boolean read GetIsRecordable;
property InProcess: boolean read GetInProcess;
property InProcessAction: THistoryAction read GetInProcessAction;
property InProcessSource: TObject read GetInProcessSource;
property Captions[Index: integer]: string read GetCaption;
property OnGetActionCaption: THistoryGetActionCaptionEvent
read FOnGetActionCaption write FOnGetActionCaption;
property OnGetActionSource: THistoryGetActionSourceEvent
read FOnGetActionSource write FOnGetActionSource;
property OnSetActionSource: THistorySetActionSourceEvent
read FOnSetActionSource write FOnSetActionSource;
property OnIsRecordable: THistoryIsRecordableEvent read FOnIsRecordable
write FOnIsRecordable;
property OnIsSame: THistoryIsSameEvent read FOnIsSame write FOnIsSame;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
implementation
var
HistoryActionClasses: TList;
// THistoryAction /////////////////////////////////////////////////////////////
constructor THistoryAction.Create(AOwner: THistory;
AParent: THistoryGroup);
begin
FOwner := AOwner;
FParent := AParent;
end;
procedure THistoryAction.ChangeState(NewState: THistoryState);
begin
FState := NewState;
end;
function THistoryAction.BeginState(NewState: THistoryState): boolean;
begin
Result := false;
if (FState = NewState) or
((NewState in [hsRecord, hsUndo, hsRedo]) and (FState <> hsIdle)) then exit;
ChangeState(NewState);
Result := true;
end;
function THistoryAction.EndState: boolean;
begin
Result := false;
if FState = hsIdle then exit;
ChangeState(hsIdle);
Result := true;
end;
function THistoryAction.DoIsSame(ActionClass: THistoryActionClass;
Source: TObject): boolean;
begin
Result := false;
end;
class function THistoryAction.DoIsRecordable(Source: TObject;
Parent: THistoryGroup): boolean;
begin
Result := true;
end;
procedure THistoryAction.DoBeginAction(Source: TObject);
begin
if FState <> hsIdle then exit;
ChangeState(hsRecord);
end;
procedure THistoryAction.DoEndAction;
begin
if FState = hsRecord then ChangeState(hsIdle);
end;
procedure THistoryAction.DoActionCaption(Source: TObject; var ACaption: string);
begin
// Abstract
end;
// THistoryStreamAction ///////////////////////////////////////////////////////
destructor THistoryStreamAction.Destroy;
begin
inherited;
FUndoStream.Free;
FRedoStream.Free;
end;
procedure THistoryStreamAction.DoRedo(Source: TObject);
begin
if Assigned(FRedoStream) and BeginState(hsRedo) then
try
// Do redo
FRedoStream.Position := 0;
ProcessSource(FRedoStream, Source, true);
finally
EndState;
end;
end;
procedure THistoryStreamAction.DoUndo(Source: TObject);
begin
if Assigned(FUndoStream) and BeginState(hsUndo) then
try
// Create redo stream
if Assigned(FRedoStream)
then FRedoStream.Size := 0
else FRedoStream := TMemoryStream.Create;
// Save current value (for redo)
ProcessSource(FRedoStream, Source, false);
// Do undo
FUndoStream.Position := 0;
ProcessSource(FUndoStream, Source, true);
finally
EndState;
end;
end;
procedure THistoryStreamAction.DoRecordAction(Source: TObject);
begin
if State <> hsRecord then exit;
// Create undo stream
if Assigned(FUndoStream)
then FUndoStream.Size := 0
else FUndoStream := TMemoryStream.Create;
// Save current value (for undo)
ProcessSource(FUndoStream, Source, false);
end;
// THistoryGroup //////////////////////////////////////////////////////////////
constructor THistoryGroup.Create(AOwner: THistory;
AParent: THistoryGroup);
begin
inherited;
FActions := TList.Create;
FInProcessIndex := -1;
end;
destructor THistoryGroup.Destroy;
begin
inherited;
Clear;
FActions.Free;
end;
function THistoryGroup.GetAction(Index: integer): THistoryAction;
begin
Result := THistoryAction(FActions[Index]);
end;
function THistoryGroup.GetActionCount: integer;
begin
Result := FActions.Count;
end;
procedure THistoryGroup.Clear;
var i: integer;
begin
for i:=FActions.Count-1 downto 0 do THistoryAction(FActions[i]).Free;
FActions.Clear;
end;
function THistoryGroup.BeginAction(ActionClass: THistoryActionClass;
const Source: TObject; ATag: integer = 0): THistoryAction;
var i: integer;
begin
Result := Nil;
if HistoryActionClasses.IndexOf(ActionClass) < 0 then exit;
// Check action alredy exist
for i:=0 to FActions.Count-1 do
if Owner.DoIsSame(THistoryAction(FActions[i]), ActionClass, Source) then exit;
// Create action
Result := ActionClass.Create(Owner, Self);
try
// Just add to list
FActions.Add(Result);
except
Result.Free;
raise;
end;
Result.Tag := ATag;
end;
function THistoryGroup.EndAction: boolean;
var Action: THistoryAction;
begin
if FActions.Count = 0
then Action := Nil
else Action := THistoryAction(FActions[FActions.Count-1]);
if Assigned(Action) and (Action.State = hsRecord) then begin
Action.DoEndAction;
if Action.DestroyAfterEnd then EraseAction;
end else
DoEndAction; // Self end action
Result := true;
end;
function THistoryGroup.EraseAction: boolean;
var Action: THistoryAction;
begin
Result := FActions.Count > 0;
if not Result then exit;
Action := THistoryAction(FActions[FActions.Count-1]);
FActions.Delete(FActions.Count-1);
Action.Free;
FOwner.DoChange;
end;
procedure THistoryGroup.DoRecordAction(Source: TObject);
begin
// Save nothing
end;
procedure THistoryGroup.DoEndAction;
begin
inherited;
FDestroyAfterEnd := FDestroyIfEmpty and (FActions.Count = 0);
end;
procedure THistoryGroup.DoUndo(Source: TObject);
var i: integer;
Enabled: boolean;
begin
if FState <> hsIdle then exit;
ChangeState(hsUndo);
try
for i:=FActions.Count-1 downto 0 do begin
FInProcessIndex := i;
FInProcessSource :=
FOwner.DoGetActionSource(THistoryAction(FActions[i]), Enabled);
if Enabled then THistoryAction(FActions[i]).DoUndo(FInProcessSource);
end;
finally
ChangeState(hsIdle);
FInProcessIndex := -1;
FInProcessSource := Nil;
end;
end;
procedure THistoryGroup.DoRedo(Source: TObject);
var i: integer;
Enabled: boolean;
begin
if FState <> hsIdle then exit;
ChangeState(hsRedo);
try
for i:=0 to FActions.Count-1 do begin
FInProcessIndex := i;
FInProcessSource :=
FOwner.DoGetActionSource(THistoryAction(FActions[i]), Enabled);
if Enabled then THistoryAction(FActions[i]).DoRedo(FInProcessSource);
end;
finally
ChangeState(hsIdle);
FInProcessIndex := -1;
FInProcessSource := Nil;
end;
end;
// THistory ///////////////////////////////////////////////////////////////////
constructor THistory.Create(AOwner: TObject);
begin
FOwner := AOwner;
FActions := TList.Create;
FActionIndex := -1;
FDepth := DefaultHistoryDepth;
FState := hsIdle;
end;
destructor THistory.Destroy;
begin
inherited;
DeleteActions;
FActions.Free;
end;
class procedure THistory.RegisterAction(Action: THistoryActionClass);
begin
if Assigned(Action) and (HistoryActionClasses.IndexOf(Action) < 0) then
HistoryActionClasses.Add(Action);
end;
function THistory.GetAction(Index: integer): THistoryAction;
begin
Result := THistoryAction(FActions[Index]);
end;
function THistory.GetActionCount: integer;
begin
Result := FActions.Count;
end;
function THistory.GetCaption(Index: integer): string;
begin
Result := THistoryAction(FActions[Index]).Caption;
end;
procedure THistory.SetDepth(const Value: integer);
begin
if Value = FDepth then exit;
FDepth := Value;
if FActions.Count > FDepth + 1 then begin
// Delete all out of range actions
DeleteActions(FDepth + 1);
DoChange;
end;
end;
procedure THistory.SetActive(const Value: boolean);
begin
if (Value = FActive) or (FState <> hsIdle) then exit;
FActive := Value;
if not FActive then begin
// Delete all actions
DeleteActions;
DoChange;
end;
end;
procedure THistory.ChangeState(NewState: THistoryState);
begin
FState := NewState;
end;
function THistory.DoGetActionCaption(Action: THistoryAction;
const Source: TObject): string;
begin
Result := '';
Action.DoActionCaption(Source, Result);
if Assigned(FOnGetActionCaption) then
FOnGetActionCaption(Self, Action, Source, Result);
end;
procedure THistory.DoChange;
begin
if Assigned(FOnChange) then FOnChange(Self);
end;
function THistory.DoGetActionSource(Action: THistoryAction;
var Enabled: boolean): TObject;
begin
Result := Nil;
if Assigned(FOnGetActionSource) then begin
Enabled := true;
FOnGetActionSource(Self, Action, Result, Enabled);
end else
Enabled := false;
end;
procedure THistory.DoSetActionSource(Action: THistoryAction;
const Source: TObject);
begin
if Assigned(FOnSetActionSource) then FOnSetActionSource(Self, Action, Source);
end;
function THistory.DoIsRecordable(var ActionClass: THistoryActionClass;
var Source: TObject; Parent: THistoryGroup): boolean;
begin
Result := ActionClass.DoIsRecordable(Source, Parent);
// HistoryActionClasses.IndexOf(ActionClass) >= 0;
if Result and Assigned(FOnIsRecordable) then
FOnIsRecordable(Self, ActionClass, Source, Parent, Result);
end;
function THistory.DoIsSame(ExistedAction: THistoryAction;
NewActionClass: THistoryActionClass; NewSource: TObject): boolean;
begin
Result := ExistedAction.DoIsSame(NewActionClass, NewSource);
if Assigned(FOnIsSame) then
FOnIsSame(Self, ExistedAction, NewActionClass, NewSource, Result);
end;
procedure THistory.Clear;
begin
if FActions.Count > 0 then begin
DeleteActions;
DoChange;
end;
end;
procedure THistory.DeleteActions(FromIndex: integer = 0;
ToIndex: integer = -1);
var i: integer;
NeedDel: boolean;
begin
if FromIndex < 0 then FromIndex := 0;
if ToIndex < 0 then ToIndex := FActions.Count + ToIndex;
NeedDel := (FromIndex > 0) or (ToIndex < FActions.Count-1);
for i:=ToIndex downto FromIndex do begin
THistoryAction(FActions[i]).Free;
if NeedDel then FActions.Delete(i);
end;
if not NeedDel then FActions.Clear;
if FActionIndex >= FActions.Count then FActionIndex := FActions.Count - 1;
end;
function THistory.IndexOf(Action: THistoryAction): integer;
begin
Result := FActions.IndexOf(Action);
end;
function THistory.Scroll: integer;
begin
if FActions.Count <= FDepth then
Result := 0
else begin
Result := FActions.Count - FDepth;
// Delete first out of range actions
DeleteActions(0, Result-1);
end;
end;
function THistory.BeginAction(ActionClass: THistoryActionClass;
Source: TObject; ATag: integer = 0; DoRecord: boolean = true): THistoryAction;
var Action: THistoryAction;
NewIndex: integer;
ParentGroup: THistoryGroup;
begin
Result := Nil;
if not FActive or (FDisableLevel > 0) or
not (FState in [hsIdle, hsRecord]) or
not DoIsRecordable(ActionClass, Source, FGroup) then exit;
// Check insert action in current group
if Assigned(FGroup) then begin
Result := FGroup.BeginAction(ActionClass, Source);
end else begin
if (HistoryActionClasses.IndexOf(ActionClass) < 0) then exit;
Action := ActionClass.Create(Self, Nil);
try
// Put action in list
NewIndex := FActionIndex + 1;
// Delete all following actions
if NewIndex < FActions.Count then DeleteActions(NewIndex);
// Add to end
FActions.Add(Action);
except
Action.Free;
raise;
end;
Result := Action;
Result.Tag := ATag;
// Scroll action list if count bigger then Depth
dec(NewIndex, Scroll);
FActionIndex := NewIndex;
// Set state
ChangeState(hsRecord);
end;
if Assigned(Result) then begin
// Encode source in action
DoSetActionSource(Result, Source);
// Set action caption
Result.Caption := DoGetActionCaption(Result, Source);
// Check action is a group
ParentGroup := FGroup;
if Result is THistoryGroup then begin
FGroup := THistoryGroup(Result);
inc(FGroupLevel);
end;
// Begin action
Result.DoBeginAction(Source);
if Result.State = hsRecord then begin
// Record action
if DoRecord then Result.DoRecordAction(Source);
// List changed
DoChange;
end else begin
// Action not in Record state. Erase action
if Assigned(ParentGroup) then begin
ParentGroup.EraseAction;
if FGroup <> ParentGroup then begin
FGroup := ParentGroup;
dec(FGroupLevel);
end;
end else
EraseAction;
Result := Nil;
end;
end;
end;
function THistory.EndAction: boolean;
var Action: THistoryAction;
NeedErase: boolean;
begin
Result := false;
if not FActive or (FDisableLevel > 0) or
(FActionIndex < 0) or (FState <> hsRecord) then exit;
if Assigned(FGroup) then begin
Result := FGroup.EndAction;
if FGroup.State = hsIdle then begin
// Check self destroying
NeedErase := FGroup.DestroyAfterEnd;
// Up one level
FGroup := FGroup.Parent;
dec(FGroupLevel);
// Erase if need
if NeedErase then
if Assigned(FGroup)
then FGroup.EraseAction
else EraseAction;
end;
// Check state
if not Assigned(FGroup) then ChangeState(hsIdle);
end else begin
Action := THistoryAction(FActions[FActionIndex]);
if Action.State = hsRecord then begin
Action.DoEndAction;
Result := true;
end;
// Set state
if (Action.State = hsIdle) or Action.DestroyAfterEnd then
ChangeState(hsIdle);
// Check destroying
if Action.DestroyAfterEnd then
EraseAction;
end;
end;
function THistory.CancelAction: boolean;
var Action: THistoryAction;
ActionParent: THistoryGroup;
begin
Result := false;
if not FActive or (FDisableLevel > 0) then exit;
if Assigned(FGroup) then begin
if FGroup.ActionCount > 0
then Action := FGroup.Actions[FGroup.ActionCount-1]
else Action := FGroup;
end else
if FActions.Count > 0
then Action := THistoryAction(FActions[FActions.Count-1])
else Action := Nil;
if not Assigned(Action) or (Action.State <> hsRecord) then exit;
ActionParent := Action.Parent;
if Assigned(ActionParent)
then Result := ActionParent.EraseAction
else Result := EraseAction;
if Result and (FGroup = Action) then begin
FGroup := ActionParent;
dec(FGroupLevel);
end;
end;
function THistory.Redo: boolean;
var Action: THistoryAction;
begin
Result := false;
if (FState <> hsIdle) or (FActionIndex = FActions.Count-1) then exit;
ChangeState(hsRedo);
try
Action := THistoryAction(FActions[FActionIndex + 1]);
FInProcessSource := DoGetActionSource(Action, Result);
if not Result then exit;
Action.DoRedo(FInProcessSource);
inc(FActionIndex);
finally
FInProcessSource := Nil;
ChangeState(hsIdle);
end;
Result := true;
end;
function THistory.Undo: boolean;
var Action: THistoryAction;
begin
Result := false;
if (FState <> hsIdle) or (FActionIndex < 0) then exit;
ChangeState(hsUndo);
try
Action := THistoryAction(FActions[FActionIndex]);
FInProcessSource := DoGetActionSource(Action, Result);
if not Result then exit;
Action.DoUndo(FInProcessSource);
dec(FActionIndex);
finally
FInProcessSource := Nil;
ChangeState(hsIdle);
end;
Result := true;
end;
function THistory.EraseAction: boolean;
begin
Result := FActive and (FActions.Count > 0);
if not Result then exit;
DeleteActions(FActions.Count - 1);
DoChange;
end;
function THistory.RecordAction(ActionClass: THistoryActionClass;
const Source: TObject; ATag: integer = 0): THistoryAction;
begin
Result := BeginAction(ActionClass, Source, ATag);
if Assigned(Result) then EndAction;
end;
procedure THistory.DisableRecording;
begin
inc(FDisableLevel);
end;
function THistory.EnableRecording: boolean;
begin
Result := FDisableLevel = 0;
if Result then exit;
dec(FDisableLevel);
end;
function THistory.OpenLastGroup: THistoryGroup;
var Action: THistoryAction;
NewGroup: THistoryGroup;
begin
Result := Nil;
NewGroup := Nil;
if (FState <> hsIdle) or (FDisableLevel > 0) then exit;
if Assigned(FGroup) then begin
if (FGroup.ActionCount = 0) or (FGroup.State <> hsIdle) or not
(FGroup[FGroup.ActionCount-1] is THistoryGroup) then exit;
NewGroup := THistoryGroup(FGroup[FGroup.ActionCount-1]);
end else
if FActions.Count > 0 then begin
Action := THistoryAction(FActions[FActions.Count-1]);
if not (Action is THistoryGroup) or (Action.State <> hsIdle) then exit;
NewGroup := THistoryGroup(Action);
end;
// Change group
if not Assigned(NewGroup) then exit;
NewGroup.ChangeState(hsRecord);
if NewGroup.State <> hsRecord then exit;
ChangeState(hsRecord);
FGroup := NewGroup;
Result := FGroup;
inc(FGroupLevel);
// List changed
DoChange;
end;
function THistory.GetInProcessAction: THistoryAction;
var Group: THistoryGroup;
Index: integer;
begin
Result := Nil;
if (FState <> hsUndo) and (FState <> hsRedo) then exit;
Index := FActionIndex;
if FState = hsRedo then inc(Index);
Result := THistoryAction(FActions[Index]);
if Result is THistoryGroup then begin
Group := THistoryGroup(Result);
while Assigned(Group) do begin
if Group.InProcessIndex < 0 then break;
Result := Group[Group.InProcessIndex];
if Result is THistoryGroup
then Group := THistoryGroup(Result)
else Group := Nil;
end;
end;
end;
function THistory.GetInProcessSource: TObject;
var Action: THistoryAction;
Group: THistoryGroup;
Index: integer;
begin
Result := Nil;
if (FState <> hsUndo) and (FState <> hsRedo) then exit;
Index := FActionIndex;
if FState = hsRedo then inc(Index);
Action := THistoryAction(FActions[Index]);
if Action is THistoryGroup then begin
Group := THistoryGroup(Action);
while Assigned(Group) do begin
if Group.InProcessIndex < 0 then break;
Action := Group[Group.InProcessIndex];
if Action is THistoryGroup
then Group := THistoryGroup(Action)
else break;
end;
end else
Group := Nil;
if Assigned(Group)
then Result := Group.InProcessSource
else Result := FInProcessSource;
end;
function THistory.GetIsRecordable: boolean;
begin
Result := FActive and (FState in [hsIdle, hsRecord]);
end;
function THistory.GetInProcess: boolean;
begin
Result := FState in [hsUndo, hsRedo];
end;
initialization
HistoryActionClasses := TList.Create;
// THistory.RegisterAction(THistoryAction); - Abstract class
THistory.RegisterAction(THistoryGroup);
finalization
HistoryActionClasses.Free;
end.
|
unit MediaStream.PtzProtocol.Ms3s;
interface
uses SysUtils, MediaStream.PtzProtocol.Base,MediaServer.Net.Ms3s.Stream;
type
TPtzProtocol_Ms3s = class (TPtzProtocol)
private
FStream: TMediaServerStream;
procedure CheckValid;
public
procedure Init(aStream: TMediaServerStream);
procedure PtzApertureDecrease(aDuration: cardinal); override;
procedure PtzApertureDecreaseStop; override;
procedure PtzApertureIncrease(aDuration: cardinal); override;
procedure PtzApertureIncreaseStop; override;
procedure PtzFocusIn(aDuration: cardinal); override;
procedure PtzFocusInStop; override;
procedure PtzFocusOut(aDuration: cardinal); override;
procedure PtzFocusOutStop; override;
procedure PtzZoomIn(aDuration: cardinal); override;
procedure PtzZoomInStop; override;
procedure PtzZoomOut(aDuration: cardinal); override;
procedure PtzZoomOutStop; override;
procedure PtzMoveDown(aDuration: cardinal; aSpeed: byte); override;
procedure PtzMoveDownStop; override;
procedure PtzMoveLeft(aDuration: cardinal; aSpeed: byte); override;
procedure PtzMoveLeftStop; override;
procedure PtzMoveRight(aDuration: cardinal; aSpeed: byte); override;
procedure PtzMoveRightStop; override;
procedure PtzMoveUp(aDuration: cardinal; aSpeed: byte); override;
procedure PtzMoveUpStop; override;
//===== Перемещение на заданную позицию
//Движение на указанную точку-пресет
procedure PtzMoveToPoint(aId: cardinal);override;
//Движение в указанную позицию. Позиция указывается по оси X и Y в градусах
procedure PtzMoveToPosition(const aPositionPan,aPositionTilt: double); override;
end;
implementation
procedure TPtzProtocol_Ms3s.CheckValid;
begin
if FStream=nil then
raise Exception.Create('Не инициализирован канал');
end;
procedure TPtzProtocol_Ms3s.Init(aStream: TMediaServerStream);
begin
FStream:=aStream;
end;
procedure TPtzProtocol_Ms3s.PtzApertureDecrease(aDuration: cardinal);
begin
CheckValid;
FStream.PtzApertureDecrease(aDuration);
end;
procedure TPtzProtocol_Ms3s.PtzApertureDecreaseStop;
begin
CheckValid;
FStream.PtzApertureDecreaseStop;
end;
procedure TPtzProtocol_Ms3s.PtzApertureIncrease(aDuration: cardinal);
begin
CheckValid;
FStream.PtzApertureIncrease(aDuration);
end;
procedure TPtzProtocol_Ms3s.PtzApertureIncreaseStop;
begin
CheckValid;
FStream.PtzApertureIncreaseStop;
end;
procedure TPtzProtocol_Ms3s.PtzFocusIn(aDuration: cardinal);
begin
CheckValid;
FStream.PtzFocusIn(aDuration);
end;
procedure TPtzProtocol_Ms3s.PtzFocusInStop;
begin
CheckValid;
FStream.PtzFocusInStop;
end;
procedure TPtzProtocol_Ms3s.PtzFocusOut(aDuration: cardinal);
begin
CheckValid;
FStream.PtzFocusOut(aDuration);
end;
procedure TPtzProtocol_Ms3s.PtzFocusOutStop;
begin
CheckValid;
FStream.PtzFocusOutStop;
end;
procedure TPtzProtocol_Ms3s.PtzMoveDown(aDuration: cardinal;aSpeed: byte);
begin
CheckValid;
FStream.PtzMoveDown(aDuration, aSpeed);
end;
procedure TPtzProtocol_Ms3s.PtzMoveDownStop;
begin
CheckValid;
FStream.PtzMoveDownStop;
end;
procedure TPtzProtocol_Ms3s.PtzMoveLeft(aDuration: cardinal;aSpeed: byte);
begin
CheckValid;
FStream.PtzMoveLeft(aDuration, aSpeed);
end;
procedure TPtzProtocol_Ms3s.PtzMoveLeftStop;
begin
CheckValid;
FStream.PtzMoveLeftStop;
end;
procedure TPtzProtocol_Ms3s.PtzMoveRight(aDuration: cardinal;aSpeed: byte);
begin
CheckValid;
FStream.PtzMoveRight(aDuration, aSpeed);
end;
procedure TPtzProtocol_Ms3s.PtzMoveRightStop;
begin
CheckValid;
FStream.PtzMoveRightStop;
end;
procedure TPtzProtocol_Ms3s.PtzMoveToPoint(aId: cardinal);
begin
CheckValid;
FStream.PtzMoveToPoint(aId);
end;
procedure TPtzProtocol_Ms3s.PtzMoveToPosition(const aPositionPan,aPositionTilt: double);
begin
CheckValid;
FStream.PtzMoveToPosition(aPositionPan, aPositionTilt);
end;
procedure TPtzProtocol_Ms3s.PtzMoveUp(aDuration: cardinal;aSpeed: byte);
begin
CheckValid;
FStream.PtzMoveUp(aDuration, aSpeed);
end;
procedure TPtzProtocol_Ms3s.PtzMoveUpStop;
begin
CheckValid;
FStream.PtzMoveUpStop;
end;
procedure TPtzProtocol_Ms3s.PtzZoomIn(aDuration: cardinal);
begin
CheckValid;
FStream.PtzZoomIn(aDuration);
end;
procedure TPtzProtocol_Ms3s.PtzZoomInStop;
begin
CheckValid;
FStream.PtzZoomInStop;
end;
procedure TPtzProtocol_Ms3s.PtzZoomOut(aDuration: cardinal);
begin
CheckValid;
FStream.PtzZoomOut(aDuration);
end;
procedure TPtzProtocol_Ms3s.PtzZoomOutStop;
begin
CheckValid;
FStream.PtzZoomOutStop;
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit frmMain;
interface
uses
Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Controls, OpenGL;
const
ImageWidth = 74;
ImageHeight = 74;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormPaint(Sender: TObject);
private
hrc: HGLRC;
Image : Array [0..ImageHeight-1, 0..ImageWidth - 1, 0..2] of GLUByte;
procedure MakeImage;
procedure SetDCPixelFormat (hdc : HDC);
end;
var
frmGL: TfrmGL;
implementation
{$R *.DFM}
{=======================================================================
Создание образа}
procedure TfrmGL.MakeImage;
var
i, j : Integer;
PixCol : TColor;
Bitmap : TBitmap;
begin
Bitmap := TBitmap.Create;
Bitmap.LoadFromFile ('Claudia.bmp');
For i := 0 to ImageHeight - 1 do
For j := 0 to ImageWidth - 1 do begin
PixCol := Bitmap.Canvas.Pixels [j, i];
Image[ImageHeight - i - 1][j][0] := PixCol and $FF;
Image[ImageHeight - i - 1][j][1] := (PixCol and $FF00) shr 8;
Image[ImageHeight - i - 1][j][2] := (PixCol and $FF0000) shr 16;
end;
Bitmap.Free;
end;
{=======================================================================
Рисование окна}
procedure TfrmGL.FormPaint(Sender: TObject);
begin
wglMakeCurrent(Canvas.Handle, hrc);
glClearColor (0.5, 0.5, 0.75, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
glRasterPos2f(-0.25, -0.25);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glDrawPixels(ImageWidth, ImageHeight, GL_RGB, GL_UNSIGNED_BYTE, @Image);
SwapBuffers (Canvas.Handle);
wglMakeCurrent(0, 0);
end;
{=======================================================================
Создание окна}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
SetDCPixelFormat (Canvas.Handle);
hrc := wglCreateContext(Canvas.Handle);
MakeImage;
end;
{=======================================================================
Формат пикселя}
procedure TfrmGL.SetDCPixelFormat (hdc : HDC);
var
pfd : TPixelFormatDescriptor;
nPixelFormat : Integer;
begin
FillChar (pfd, SizeOf (pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat (hdc, @pfd);
SetPixelFormat (hdc, nPixelFormat, @pfd);
end;
{=======================================================================
Конец работы программы}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglDeleteContext(hrc);
end;
end.
|
unit MonthlyExpenseDetail;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BasePopupDetail, RzButton, RzTabs,
Vcl.StdCtrls, RzLabel, Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel, Vcl.Mask,
RzEdit, RzDBEdit, Vcl.DBCtrls, RzDBCmbo, DB;
type
TfrmMonthlyExpDetail = class(TfrmBasePopupDetail)
dbluType: TRzDBLookupComboBox;
edMonthly: TRzDBNumericEdit;
Label1: TLabel;
Label2: TLabel;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
protected
procedure Save; override;
procedure Cancel; override;
procedure BindToObject; override;
function ValidEntry: boolean; override;
end;
var
frmMonthlyExpDetail: TfrmMonthlyExpDetail;
implementation
{$R *.dfm}
uses
LoanData, LoansAuxData, FormsUtil, Loan, MonthlyExpense, IFinanceDialogs;
procedure TfrmMonthlyExpDetail.FormCreate(Sender: TObject);
begin
inherited;
OpenDropdownDataSources(tsDetail);
end;
procedure TfrmMonthlyExpDetail.FormShow(Sender: TObject);
begin
inherited;
// disable type on editing
dbluType.Enabled := dbluType.DataSource.DataSet.State = dsInsert;
end;
procedure TfrmMonthlyExpDetail.Save;
var
expType, expName, expAmount: string;
begin
with dmLoan.dstMonExp do
begin
if State in [dsInsert,dsEdit] then
Post;
expType := FieldByName('exp_type').AsString;
expName := dbluType.Text;
expAmount := edMonthly.Text;
ln.AddMonthlyExpense(TMonthlyExpense.Create(expType,expName,expAmount),true);
end;
end;
procedure TfrmMonthlyExpDetail.BindToObject;
begin
inherited;
end;
procedure TfrmMonthlyExpDetail.Cancel;
begin
with dmLoan.dstMonExp do
if State in [dsInsert,dsEdit] then
Cancel;
end;
function TfrmMonthlyExpDetail.ValidEntry: boolean;
var
error: string;
begin
with dmLoan.dstMonExp do
begin
if Trim(dbluType.Text) = '' then
error := 'Please select a type.'
else if Trim(edMonthly.Text) = '' then
error := 'Please enter monthly amount.'
else if (State = dsInsert) and (ln.MonthlyExpenseExists(dbluType.GetKeyValue)) then
error := 'Expense already exists.';
end;
Result := error = '';
if not Result then ShowErrorBox(error);
end;
end.
|
unit UChooseAPServer;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, jpeg, ExtCtrls, RzBmpBtn, inifiles;
type
TChooseAPServerFrm = class(TForm)
Label3: TLabel;
EdtPassWord: TEdit;
EdtUserID: TEdit;
ComServerIP: TComboBox;
Label1: TLabel;
Label2: TLabel;
BtnLogin: TRzBmpButton;
BtnCancel: TRzBmpButton;
procedure FormCreate(Sender: TObject);
procedure GetServerIP(AIP: string; ACom: TComboBox);
private
{ Private declarations }
public
{ Public declarations }
end;
var
ChooseAPServerFrm: TChooseAPServerFrm;
implementation
{$R *.dfm}
procedure TChooseAPServerFrm.FormCreate(Sender: TObject);
var
iniFile: Tinifile;
begin
self.Caption:='==============================================<MANUFACTURE EXCUTE SYSTEM>[20090801]========================================================';
try
iniFile := Tinifile.Create(ExtractFilePath(Application.ExeName) + 'Sfisini.ini');
GetServerIP(iniFile.ReadString('APSERVER','IP',''),ComServerIP);
finally
iniFile.Free;
end;
EdtUserID.Clear;
EdtPassWord.Clear;
end;
procedure TChooseAPServerFrm.GetServerIP(AIP: string; ACom: TComboBox);
var
strIP: string;
index: integer;
begin
COmServerIP.Clear;
while Pos(';', AIP) > 0 do
begin
index := Pos(';', AIP);
strIP := Copy(AIP, 1, index - 1);
AIP := Copy(AIP, index + 1, 10000);
ComServerIP.Items.Add(strIP);
end;
if Trim(AIP)<>'' then ComServerIP.Items.Add(AIP);
end;
end.
|
{***********************************<_INFO>************************************}
{ <Проект> Библиотека медиа-обработки }
{ }
{ <Область> 16:Медиа-контроль }
{ }
{ <Задача> Инкапсуляция медиа-фрейма. Класс, обеспечивающий выделение и }
{ управление блоком памяти }
{ }
{ <Автор> Фадеев Р.В. }
{ }
{ <Дата> 14.01.2011 }
{ }
{ <Примечание> Нет примечаний. }
{ }
{ <Атрибуты> ООО НПП "Спецстрой-Связь", ООО "Трисофт" }
{ }
{***********************************</_INFO>***********************************}
unit MediaStream.Frame;
interface
uses
SysUtils, Windows, MediaProcessing.Definitions;
type
TMediaStreamFrame =class
private
FDataPtr:pointer;
FDataSize: cardinal;
FDataAllocatedSize: cardinal;
FInfoPtr:pointer;
FInfoSize: cardinal;
FInfoAllocatedSize: cardinal;
FFormat: TMediaStreamDataHeader;
procedure DisposeMemory;
public
constructor Create(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize:cardinal; aInfo: pointer; aInfoSize: cardinal);
destructor Destroy; override;
procedure Assign(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize:cardinal; aInfo: pointer; aInfoSize: cardinal; aReuseMemory: boolean=true);
property Format: TMediaStreamDataHeader read FFormat;
property DataPtr: pointer read FDataPtr;
property DataSize: cardinal read FDataSize;
property DataAllocatedBlockSize: cardinal read FDataAllocatedSize;
property InfoPtr: pointer read FInfoPtr;
property InfoSize: cardinal read FInfoSize;
property InfoAllocatedBlockSize: cardinal read FInfoAllocatedSize;
end;
implementation
{ TMediaStreamFrame }
destructor TMediaStreamFrame.Destroy;
begin
inherited;
DisposeMemory;
end;
procedure TMediaStreamFrame.DisposeMemory;
begin
FreeMem(FDataPtr);
FDataPtr:=nil;
FDataAllocatedSize:=0;
FDataSize:=0;
FreeMem(FInfoPtr);
FInfoPtr:=nil;
FInfoAllocatedSize:=0;
FInfoSize:=0;
end;
procedure TMediaStreamFrame.Assign(const aFormat: TMediaStreamDataHeader;
aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal;
aReuseMemory: boolean);
begin
if not aReuseMemory then
DisposeMemory;
FFormat:=aFormat;
if aDataSize>0 then
begin
//Если размер уже выделенного блока памяти мал, то нужно выделить блок памяти заново
if FDataAllocatedSize<aDataSize then
begin
FreeMem(FDataPtr);
FDataAllocatedSize:=0;
FDataSize:=0;
GetMem(FDataPtr,aDataSize);
FDataAllocatedSize:=aDataSize;
end;
FDataSize:=aDataSize;
CopyMemory(FDataPtr,aData,aDataSize);
end;
if aInfoSize>0 then
begin
//Если размер уже выделенного блока памяти мал, то нужно выделить блок памяти заново
if FInfoAllocatedSize<aInfoSize then
begin
FreeMem(FInfoPtr);
FInfoSize:=0;
FInfoAllocatedSize:=0;
GetMem(FInfoPtr,aInfoSize);
FInfoAllocatedSize:=aInfoSize;
end;
FInfoSize:=aInfoSize;
CopyMemory(FInfoPtr,aInfo,aInfoSize);
end;
end;
constructor TMediaStreamFrame.Create(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize:cardinal; aInfo: pointer; aInfoSize: cardinal);
begin
Assign(aFormat,aData,aDataSize,aInfo,aInfoSize);
end;
end.
|
unit ReportLangSelect;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, Buttons;
type
TReportLangSelectForm = class(TForm)
GroupBox1: TGroupBox;
rb_ReportLang_cn: TRadioButton;
rb_ReportLang_en: TRadioButton;
btn_cancel: TBitBtn;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure rb_ReportLang_cnClick(Sender: TObject);
procedure rb_ReportLang_enClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
ReportLangSelectForm: TReportLangSelectForm;
implementation
uses public_unit;
{$R *.dfm}
procedure TReportLangSelectForm.FormCreate(Sender: TObject);
begin
if g_ProjectInfo.prj_ReportLanguage =trChineseReport then
rb_ReportLang_cn.Checked := true
else if g_ProjectInfo.prj_ReportLanguage = trEnglishReport then
rb_ReportLang_en.Checked := true
end;
procedure TReportLangSelectForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TReportLangSelectForm.rb_ReportLang_cnClick(Sender: TObject);
begin
if TRadiobutton(Sender).Checked = true then
g_ProjectInfo.setReportLanguage(trChineseReport) ;
end;
procedure TReportLangSelectForm.rb_ReportLang_enClick(Sender: TObject);
begin
if TRadiobutton(Sender).Checked = true then
g_ProjectInfo.setReportLanguage(trEnglishReport) ;
end;
end.
|
{
"RTC Image Playback (VCL)"
- Copyright 2004-2017 (c) RealThinClient.com (http://www.realthinclient.com)
@exclude
}
unit rtcVImgPlayback;
interface
{$include rtcDefs.inc}
uses
Classes,
{$IFDEF IDE_XEup}
System.Types,
VCL.Graphics,
{$ELSE}
Types,
Graphics,
{$ENDIF}
rtcTypes,
rtcVBmpUtils,
rtcXImgPlayback;
type
{$IFDEF IDE_XE2up}
[ComponentPlatformsAttribute(pidAll)]
{$ENDIF}
TRtcImageVCLPlayback=class(TRtcImagePlayback)
private
FBmp:TBitmap;
protected
procedure DoImageCreate; override;
procedure DoImageUpdate; override;
procedure DoReceiveStop; override;
public
constructor Create(AOwner:TComponent); override;
procedure DrawBitmap(Canvas:TCanvas);
property Bitmap:TBitmap read FBmp;
end;
implementation
{ TRtcImagePlaybackFMX }
constructor TRtcImageVCLPlayback.Create(AOwner: TComponent);
begin
inherited;
FBmp:=nil;
end;
procedure TRtcImageVCLPlayback.DoImageCreate;
begin
Image:=NewBitmapInfo(False);
inherited;
end;
procedure TRtcImageVCLPlayback.DoImageUpdate;
begin
CopyInfoToBitmap(Image, FBmp);
inherited;
end;
procedure TRtcImageVCLPlayback.DoReceiveStop;
begin
inherited;
RtcFreeAndNil(FBmp);
end;
procedure TRtcImageVCLPlayback.DrawBitmap(Canvas: TCanvas);
begin
if assigned(Bitmap) then
begin
Canvas.Draw(0,0,Bitmap);
PaintCursor(Decoder.Cursor, Canvas, Bitmap, LastMouseX, LastMouseY, MouseControl);
end;
end;
end.
|
object LineBitsEditor: TLineBitsEditor
Left = 218
Top = 122
HelpContext = 1770
BorderStyle = bsDialog
Caption = 'Line bits settings'
ClientHeight = 139
ClientWidth = 293
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
KeyPreview = True
OldCreateOrder = True
Position = poScreenCenter
OnCreate = FormCreate
PixelsPerInch = 96
TextHeight = 13
object cData: TRadioGroup
Left = 104
Top = 8
Width = 89
Height = 57
Caption = 'Data bits'
Columns = 2
Items.Strings = (
'&8'
'&7'
'&6'
'&5')
TabOrder = 0
end
object cParity: TRadioGroup
Left = 8
Top = 8
Width = 89
Height = 121
Caption = 'Parity'
Items.Strings = (
'&None'
'&Odd'
'&Even'
'&Mark'
'&Space')
TabOrder = 1
end
object cStop: TRadioGroup
Left = 104
Top = 72
Width = 89
Height = 57
Caption = 'Stop bits'
Columns = 2
Items.Strings = (
'&1'
'1.5'
'&2')
TabOrder = 2
end
object bOK: TButton
Left = 208
Top = 12
Width = 75
Height = 23
Caption = 'OK'
Default = True
ModalResult = 1
TabOrder = 3
end
object bCancel: TButton
Left = 208
Top = 40
Width = 75
Height = 23
Cancel = True
Caption = 'Cancel'
ModalResult = 2
TabOrder = 4
end
object bHelp: TButton
Left = 208
Top = 68
Width = 75
Height = 23
Caption = 'Help'
TabOrder = 5
OnClick = bHelpClick
end
end
|
unit Main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
ActnList, StdCtrls, DateUtils;
type
{ TMainForm }
TMainForm = class(TForm)
AddInfo: TButton;
Generate: TButton;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
ProcessingID: TComboBox;
MessageType: TComboBox;
ControlID: TEdit;
InputBox: TEdit;
RefreshButton: TButton;
OptFieldBox: TComboBox;
ResultBox: TEdit;
procedure AddInfoClick(Sender: TObject);
procedure GenerateClick(Sender: TObject);
procedure Label1Click(Sender: TObject);
procedure RefreshButtonClick(Sender: TObject);
function generateMessage : String;
end;
var
MainForm: TMainForm;
fields: TStringList;
implementation
{$R *.lfm}
procedure TMainForm.GenerateClick(Sender: TObject);
var
msgType, msgID, prID: boolean;
messageTypes: TStringList;
i: Integer;
theDate: TDateTime;
begin
messageTypes := TStringList.Create;
//Initialize messageTypes list, CommaText syntax in Lazarus requires no spaces and must be all on one line
messageTypes.CommaText := 'A01-Admit/Visit=ADT^A01, A02-Transfer_Patient=ADT^A02, A03-Discharge/End_Visit=ADT^A03, A04-Register_Patient=ADT^A04, A05-Pre-admit_Patient=ADT^A05, A06-Outpatient_to_Inpatient=ADT^A06, A07-Inpatient_to_Outpatient=ADT^A07, A08-Update_Patient_Info=ADT^A08, A09-Patient_Departing_(tracking)=ADT^A09, A10-Patient_Arriving_(tracking)=ADT^A10';
theDate := Now;
//Check for user input in required fields
begin
if MessageType.Text <> ''
then msgType := true
else msgType := false;
if ControlID.Caption <> 'Control ID'
then msgID := true
else msgID := false;
if ProcessingID.Text <> ''
then prID := true
else prID := false;
end;
//Store required and predetermined fields in global TStringList
if msgType and msgID and prID then
begin
for i := 1 to 19 do
begin
fields.Add('');
end;
fields[7] := '2013' + IntToStr(MonthOfTheYear(theDate)) + IntToStr(DayOfTheMonth(theDate));
fields[9] := messageTypes.Values[MessageType.Caption];
fields[10] := ControlID.Caption;
fields[11] := ProcessingID.Caption;
fields[12] := '2.6';
ResultBox.Caption := generateMessage();
Generate.Enabled := False;
AddInfo.Enabled := True;
messageTypes.Free;
end else ResultBox.Caption := 'Please select and fill out the required fields';
end;
procedure TMainForm.Label1Click(Sender: TObject);
begin
end;
//Function allows code reuse by the GenerateClick and RefreshButtonClick procedures
function TMainForm.generateMessage: String;
var
i: Integer;
msg: String;
begin
msg := 'MSH|^~\&';
for i := 3 to 12 do
msg := msg + '|' + fields[i];
if fields[17] <> '' then
msg := msg + '||||' + fields[17];
Result := msg;
end;
//Updates the ResultBox after the user adds information to the HL7 message
procedure TMainForm.RefreshButtonClick(Sender: TObject);
begin
ResultBox.Caption := generateMessage();
RefreshButton.Enabled := False;
end;
//Inputs additional optional information that the user may want in the HL7 message
procedure TMainForm.AddInfoClick(Sender: TObject);
begin
case OptFieldBox.Caption of
'Sending Application' : fields[3] := InputBox.Caption;
'Sending Facility' : fields[4] := InputBox.Caption;
'Receiving Application' : fields[5] := InputBox.Caption;
'Receiving Facility' : fields[6] := InputBox.Caption;
'Country Code' : fields[17] := InputBox.Caption;
else InputBox.Caption := 'Not a valid choice';
end;
RefreshButton.Enabled := True;
end;
begin
//TStringList fields does not have it's memory freed because the application
//uses the data stored in this object until the user terminates the program
fields := TStringList.Create;
end.
|
{ BP and partly Delphi compatible System unit for GPC
This unit is released as part of the GNU Pascal project. It
implements some rather exotic BP and Delphi compatibility
features. Even many BP and Delphi programs don't need them, but
they're here for maximum compatibility. Most of BP's and Delphi's
System units' features are built into the compiler or the RTS.
Note: The things in this unit are really exotic. If you haven't
used BP or Delphi before, you don't want to look at this unit. :-)
This unit depends on the conditional defines `__BP_TYPE_SIZES__',
`__BP_RANDOM__', `__BP_PARAMSTR_0__' and `__BP_NO_ALLOCMEM__'.
If `__BP_TYPE_SIZES__' is defined (with the `-D__BP_TYPE_SIZES__'
option), the integer data types will be redefined to the sizes
they have in BP or Delphi. Note that this might cause problems,
e.g. when passing var parameters of integer types between units
that do and don't use System. However, of the BP compatibility
units, only Dos and WinDos use such parameters, and they have been
taken care of so they work.
If `__BP_RANDOM__' is defined (`-D__BP_RANDOM__'), this unit will
provide an exactly BP compatible pseudo random number generator.
In particular, the range for integer randoms will be truncated to
16 bits like in BP. The RandSeed variable is provided, and if it's
set to the same value as BP's RandSeed, it produces exactly the
same sequence of pseudo random numbers that BP's pseudo random
number generator does (whoever might need this ... ;-). Even the
Randomize function will behave exactly like in BP. However, this
will not be noted unless one explicitly tests for it.
If `__BP_PARAMSTR_0__' is defined (`-D__BP_PARAMSTR_0__'), this
unit will change the value of `ParamStr (0)' to that of
`ExecutablePath', overwriting the value actually passed by the
caller, to imitate BP's/Dos's behaviour. However *note*: On most
systems, `ExecutablePath' is *not* guaranteed to return the full
path, so defining this symbol doesn't change anything. In general,
you *cannot* expect to find the full executable path, so better
don't even try it, or your program will (at best) run on some
systems. For most cases where BP programs access their own
executable, there are cleaner alternatives available.
If `__BP_NO_ALLOCMEM__' is defined (`-D__BP_NO_ALLOCMEM__'), the
two Delphi compatible functions `AllocMemCount' and `AllocMemSize'
will not be provided. The advantage is that this unit will not
have to `Mark' the heap which makes memory de-/allocations much
faster if the program doesn't use `Mark' otherwise.
Copyright (C) 1998-2005 Free Software Foundation, Inc.
Authors: Peter Gerwinski <peter@gerwinski.de>
Prof. Abimbola A. Olowofoyeku <African_Chief@bigfoot.com>
Frank Heckenbach <frank@pascal.gnu.de>
Dominik Freche <dominik.freche@gmx.net>
This file is part of GNU Pascal.
GNU Pascal is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2, or (at your
option) any later version.
GNU Pascal is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Pascal; see the file COPYING. If not, write to the
Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
As a special exception, if you link this file with files compiled
with a GNU compiler to produce an executable, this does not cause
the resulting executable to be covered by the GNU General Public
License. This exception does not however invalidate any other
reasons why the executable file might be covered by the GNU
General Public License. }
{$gnu-pascal,I-}
{$if __GPC_RELEASE__ < 20030303}
{$error This unit requires GPC release 20030303 or newer.}
{$endif}
module System;
export System = all (FileMode {$ifdef __BP_TYPE_SIZES__}, SystemInteger => Integer, SystemWord => Word {$endif});
import GPC (MaxLongInt => GPC_MaxLongInt);
var
{ Chain of procedures to be executed at the end of the program }
ExitProc: ^procedure = nil;
{ Contains all the command line arguments passed to the program,
concatenated, with spaces between them }
CmdLine: CString;
{$ifdef __BP_RANDOM__}
{ Random seed, initialized by Randomize, but can also be set
explicitly }
RandSeed: Integer attribute (Size = 32) = 0;
{$endif}
type
OrigInt = Integer;
OrigWord = Word;
{ Delphi }
SmallInt = Integer attribute (Size = 16);
DWord = Cardinal attribute (Size = 32);
{ Short BP compatible type sizes if wanted }
{$ifdef __BP_TYPE_SIZES__}
ByteBool = Boolean attribute (Size = 8);
WordBool = Boolean attribute (Size = 16);
LongBool = Boolean attribute (Size = 32);
ShortInt = Integer attribute (Size = 8);
SystemInteger = Integer attribute (Size = 16);
LongInt = Integer attribute (Size = 32);
Comp = Integer attribute (Size = 64);
Byte = Cardinal attribute (Size = 8);
SystemWord = Cardinal attribute (Size = 16);
LongWord = Cardinal attribute (Size = 32); { Delphi }
{$else}
SystemInteger = Integer;
SystemWord = Word;
{$endif}
{$if False} { @@ doesn't work well (dialec3.pas) -- when GPC gets short
strings, it will be unnecessary }
{$ifopt borland-pascal}
String = String [255];
{$endif}
{$endif}
const
MaxInt = High (SystemInteger);
MaxLongInt = High (LongInt);
{ Return the lowest-order byte of x }
function Lo (x: LongestInt): Byte;
{ Return the second-lowest-order byte of x }
function Hi (x: LongestInt): Byte;
{ Swap the lowest-order and second-lowest-order bytes, mask out the
higher-order ones }
function Swap (x: LongestInt): SystemWord;
{ Store the current directory name (on the given drive number if
drive <> 0) in s }
procedure GetDir (Drive: Byte; var s: String);
{ Dummy routine for compatibility. @@Use two overloaded versions
rather than varargs when possible. }
procedure SetTextBuf (var f: Text; var Buf; ...);
{ Mostly useless BP compatible variables }
var
SelectorInc: SystemWord = $1000;
Seg0040: SystemWord = $40;
SegA000: SystemWord = $a000;
SegB000: SystemWord = $b000;
SegB800: SystemWord = $b800;
Test8086: Byte = 2;
Test8087: Byte = 3; { floating-point arithmetic is emulated
transparently by the OS if not present
in hardware }
OvrCodeList: SystemWord = 0;
OvrHeapSize: SystemWord = 0;
OvrDebugPtr: Pointer = nil;
OvrHeapOrg: SystemWord = 0;
OvrHeapPtr: SystemWord = 0;
OvrHeapEnd: SystemWord = 0;
OvrLoadList: SystemWord = 0;
OvrDosHandle: SystemWord = 0;
OvrEmsHandle: SystemWord = $ffff;
HeapOrg: Pointer absolute HeapLow;
HeapPtr: Pointer absolute HeapHigh;
HeapEnd: Pointer = Pointer (High (PtrCard));
FreeList: Pointer = nil;
FreeZero: Pointer = nil;
StackLimit: SystemWord = 0;
HeapList: SystemWord = 0;
HeapLimit: SystemWord = 1024;
HeapBlock: SystemWord = 8192;
HeapAllocFlags: SystemWord = 2;
CmdShow: SystemInteger = 0;
SaveInt00: Pointer = nil;
SaveInt02: Pointer = nil;
SaveInt0C: Pointer = nil;
SaveInt0D: Pointer = nil;
SaveInt1B: Pointer = nil;
SaveInt21: Pointer = nil;
SaveInt23: Pointer = nil;
SaveInt24: Pointer = nil;
SaveInt34: Pointer = nil;
SaveInt35: Pointer = nil;
SaveInt36: Pointer = nil;
SaveInt37: Pointer = nil;
SaveInt38: Pointer = nil;
SaveInt39: Pointer = nil;
SaveInt3A: Pointer = nil;
SaveInt3B: Pointer = nil;
SaveInt3C: Pointer = nil;
SaveInt3D: Pointer = nil;
SaveInt3E: Pointer = nil;
SaveInt3F: Pointer = nil;
SaveInt75: Pointer = nil;
RealModeRegs: array [0 .. 49] of Byte =
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0);
{ Mostly useless BP compatible pointer functions }
function Ofs (const x): PtrWord;
function Seg (const x): PtrWord;
function Ptr (Seg, Ofs: PtrWord): Pointer;
function CSeg: PtrWord;
function DSeg: PtrWord;
function SSeg: PtrWord;
function SPtr: PtrWord;
{ Routines to handle BP's 6 byte `Real' type which is formatted like
this:
47 0
-|------- -------- -------- -------- --------|--------
| |
+----------+ +------------+
47 Sign Bit | 8..46 Mantissa | 0..7 Biased Exponent
This format does not support infinities, NaNs and denormalized
numbers. The first digit after the binary point is not stored and
assumed to be 1. (This is called the normalized representation of
a binary floating point number.)
In GPC, this type is represented by the type `BPReal' which is
binary compatible to BP's type, and can therefore be used in
connection with binary files used by BP programs.
The functions `RealToBPReal' and `BPRealToReal' convert between
this type and GPC's `Real' type. Apart from that, `BPReal' should
be treated as opaque.
The variables `BPRealIgnoreOverflow' and `BPRealIgnoreUnderflow'
determine what to do in the case of overflows and underflows. The
default values are BP compatible. }
var
{ Ignore overflows, and use the highest possible value instead. }
BPRealIgnoreOverflow: Boolean = False;
{ Ignore underflows, and use 0 instead. This is BP's behaviour,
but has the disadvantage of diminishing computation precision. }
BPRealIgnoreUnderflow: Boolean = True;
type
BPRealInteral = Cardinal attribute (Size = 8);
BPReal = packed record
Format: packed array [1 .. 6] of BPRealInteral
end;
function RealToBPReal (r: Real) = BR: BPReal;
function BPRealToReal (const BR: BPReal) = RealValue: Real;
{ Heap management stuff }
const
{ Possible results for HeapError }
HeapErrorRunError = 0;
HeapErrorNil = 1;
HeapErrorRetry = 2;
var
{ If assigned to a function, it will be called when memory
allocations do not find enough free memory. Its result
determines if a run time error should be raised (the default),
or nil should be returned, or the allocation should be retried
(causing the routine to be called again if the allocation still
doesn't succeed).
Notes:
- Returning nil can cause some routines of the RTS and units
(shipped with GPC or third-party) to crash when they don't
expect nil, so better don't use this mechanism, but rather
CGetMem where needed.
- Letting the allocation be retried, of course, only makes sense
if the routine freed some memory before -- otherwise it will
cause an infinite loop! So, a meaningful HeapError routine
should dispose of some temporary objects, if available, and
return HeapErrorRetry, and return HeapErrorRunError when no
(more) of them are available. }
HeapError: ^function (Size: SystemWord): SystemInteger = nil;
{ Just returns HeapErrorNil. When this function is assigned to
HeapError, GetMem and New will return a nil pointer instead of
causing a runtime error when the allocation fails. See the comment
for HeapError above. }
function HeapErrorNilReturn (Size: SystemWord): SystemInteger;
{ Return the total free memory/biggest free memory block. Except
under Win32 and DJGPP, these are expensive routines -- try to
avoid them. Under Win32, MaxAvail returns the same as MemAvail, so
don't rely on being able to allocate a block of memory as big as
MaxAvail indicates. Generally it's preferable to not use these
functions at all in order to do a safe allocation, but just try to
allocate the memory needed using CGetMem, and check for a nil
result. What makes these routines unrealiable is, e.g., that on
multi-tasking systems, another process may allocate memory after
you've called MemAvail/MaxAvail and before you get to do the next
allocation. Also, please note that some systems over-commit
virtual memory which may cause MemAvail to return a value larger
than the actual (physical plus swap) memory available. Therefore,
if you want to be "sure" (modulo the above restrictions) that the
memory is actually available, use MaxAvail. }
function MemAvail: Cardinal;
function MaxAvail: Cardinal;
{ Delphi compatibility }
function CompToDouble (x: Comp): Double;
function DoubleToComp (x: Double): Comp;
{$ifndef __BP_NO_ALLOCMEM__}
function AllocMemCount = Count: SystemInteger;
function AllocMemSize = Size: SizeType;
{$endif}
procedure Assert (Condition: Boolean);
procedure DefaultAssertErrorProc (const Message, FileName: String; LineNumber: SystemInteger; ErrorAddr: Pointer);
var
AssertErrorProc: ^procedure (const Message, FileName: String; LineNumber: SystemInteger; ErrorAddr: Pointer) = @DefaultAssertErrorProc;
NoErrMsg: Boolean = False;
end;
function Lo (x: LongestInt): Byte;
begin
Lo := LongestCard (x) and $ff
end;
function Hi (x: LongestInt): Byte;
begin
Hi := (LongestCard (x) div $100) and $ff
end;
function Swap (x: LongestInt): SystemWord;
begin
Swap := (LongestCard (x) and $ff) * $100 + (LongestCard (x) div $100) and $ff
end;
procedure GetDir (Drive: Byte; var s: String);
begin
if Drive = 0 then
s := FExpand (DirSelf)
else
s := FExpand (Succ ('a', Drive - 1) + ':')
end;
procedure SetTextBuf (var f: Text; var Buf; ...);
begin
Discard (f);
Discard (Buf)
end;
function Ofs (const x): PtrWord;
begin
Ofs := PtrWord (@x)
end;
function Seg (const x): PtrWord;
begin
Discard (x);
Seg := 0
end;
function Ptr (Seg, Ofs: PtrWord): Pointer;
begin
Ptr := Pointer ($10 * Seg + Ofs)
end;
type
PointerType = ^Integer; { any typed pointer will do }
function CSeg: PtrWord;
begin
CSeg := Seg (PointerType (ReturnAddress (0))^)
end;
function DSeg: PtrWord;
begin
DSeg := Seg (ExitProc) { any global variable will do }
end;
function SSeg: PtrWord;
begin
SSeg := Seg (PointerType (FrameAddress (0))^)
end;
function SPtr: PtrWord;
begin
SPtr := Ofs (PointerType (FrameAddress (0))^)
end;
function RealToBPReal (r: Real) = BR: BPReal;
var
Mantissa: Extended;
Exponent: CInteger;
Sign, x: OrigInt;
begin
for x := 1 to 6 do BR.Format[x] := 0;
if IsNotANumber (r) then
RuntimeError (870) { BP compatible 6 byte `Real' type does not support NaN values }
else if IsInfinity (r) then
RuntimeError (871) { BP compatible 6 byte `Real' type does not support infinity }
else
begin
SplitReal (r, Exponent, Mantissa);
Inc (Exponent, $80);
Sign := 0;
if Mantissa < 0 then
begin
Mantissa := -Mantissa;
Sign := 1
end;
if Exponent < 0 then { number cannot be stored in BPReal due to an underflow }
begin
if not BPRealIgnoreUnderflow then
RuntimeError (872) { underflow while converting to BP compatible 6 byte `Real' type }
{ else Set BR to zero -- BR is pre-initialized with 0 already }
end
else if Exponent > 255 then
if BPRealIgnoreOverflow then
begin
{ Set BR to highest number representable in this format }
for x := 1 to 6 do BR.Format[x] := $ff;
and (BR.Format[6], not ((not Sign) shl 7)) { Set sign }
end
else
RuntimeError (873) { overflow while converting to BP compatible 6 byte `Real' type }
else
begin
{ Convert a non-infinite number }
BR.Format[1] := Exponent;
Mantissa := Mantissa * 2;
if Mantissa < 1 then { if r is normalized, first bit is set }
begin
if not BPRealIgnoreUnderflow then
RuntimeError (874) { cannot convert denormalized number to BP compatible 6 byte `Real' type }
{ else Set BR to zero -- BR is pre-initialized with 0 already }
end
else
begin
{ Leave out the first bit }
Mantissa := Mantissa - 1;
for x := 1 to 39 do
begin
Mantissa := Mantissa * 2;
if Mantissa >= 1 then
begin
or (BR.Format[6 - x div 8], 1 shl (7 - x mod 8));
Mantissa := Mantissa - 1
end
end;
{ Set sign }
and (BR.Format[6], not (1 shl 7));
or (BR.Format[6], Sign shl 7)
end
end
end
end;
function BPRealToReal (const BR: BPReal) = RealValue: Real;
var
x: Cardinal;
Mantissa, e: Real;
begin
Mantissa := 0.5;
e := 0.25;
{ Leave out the first bit }
for x := 1 to 39 do
begin
Mantissa := Mantissa +
((BR.Format[6 - x div 8] and (1 shl (7 - x mod 8))) shr (7 - x mod 8)) * e;
e := e / 2
end;
RealValue := Mantissa * Exp (Ln (2) * (BR.Format[1] - 128));
if (BR.Format[6] and 128) <> 0 then
RealValue := -RealValue
end;
{ Heap management stuff }
var
OldGetMem : GetMemType;
OldFreeMem : FreeMemType;
MaxAvailSave: Pointer = nil;
MaxAvailSize: SizeType = 0;
{$ifndef __BP_NO_ALLOCMEM__}
var
FirstMark: Pointer;
function AllocMemCount = Count: SystemInteger;
procedure CountBlock (aPointer: Pointer; aSize: SizeType; aCaller: Pointer);
begin
Discard (aPointer);
Discard (aSize);
Discard (aCaller);
Inc (Count)
end;
begin
Count := 0;
ForEachMarkedBlock (FirstMark, CountBlock)
end;
function AllocMemSize = Size: SizeType;
procedure CountBlockSize (aPointer: Pointer; aSize: SizeType; aCaller: Pointer);
begin
Discard (aPointer);
Discard (aCaller);
Inc (Size, aSize)
end;
begin
Size := 0;
ForEachMarkedBlock (FirstMark, CountBlockSize)
end;
{$endif}
function BPGetMem (Size: SizeType) = p: Pointer;
var Status: SystemInteger;
begin
if (MaxAvailSave <> nil) and (Size <= MaxAvailSize) then
begin
if Size = MaxAvailSize then
p := MaxAvailSave
else
p := CReAllocMem (MaxAvailSave, Size);
MaxAvailSave := nil;
MaxAvailSize := 0;
if p <> nil then Exit
end;
if HeapError = nil then
p := OldGetMem^ (Size)
else
begin
repeat
p := CGetMem (Size);
if p <> nil then Exit;
Status := HeapError^ (Size)
until Status <> HeapErrorRetry;
if Status = HeapErrorNil then p := UndocumentedReturnNil
end
end;
procedure BPFreeMem (aPointer: Pointer);
begin
if MaxAvailSave <> nil then
begin
CFreeMem (MaxAvailSave);
MaxAvailSave := nil;
MaxAvailSize := 0
end;
OldFreeMem^ (aPointer)
end;
function HeapErrorNilReturn (Size: SystemWord): SystemInteger;
begin
Discard (Size);
HeapErrorNilReturn := HeapErrorNil
end;
{$ifdef __GO32__}
type
DPMIFreeInfo = record
LargestAvailableFreeBlockInBytes,
MaximumUnlockedPageAllocationInPages,
MaximumLockedPageAllocationInPages,
LinearAddressSpaceSizeInPages,
TotalNumberOfUnlockedPages,
TotalNumberOfFreePages,
TotalNumberOfPhysicalPages,
FreeLinearAddressSpaceInPages,
SizeOfPagingFilePartitionInPages: Cardinal;
Reserved: array [0..2] of Cardinal
end;
function DPMIGetFreeMemInfo (var Info: DPMIFreeInfo): OrigInt; external name '__dpmi_get_free_memory_information';
function DPMIGetPageSize (var Size: Cardinal): OrigInt; external name '__dpmi_get_page_size';
function MemAvail: Cardinal;
var
D: DPMIFreeInfo;
W: Cardinal;
begin
Discard (DPMIGetFreeMemInfo (D));
Discard (DPMIGetPageSize (W));
MemAvail := (D.TotalNumberOfUnlockedPages * W)
end;
function MaxAvail: Cardinal;
var
D: DPMIFreeInfo;
W: Cardinal;
begin
Discard (DPMIGetFreeMemInfo (D));
Discard (DPMIGetPageSize (W));
MaxAvail := (D.TotalNumberOfFreePages * W)
end;
{$elif defined (_WIN32)}
type
TMemoryStatus = record
dwLength,
dwMemoryLoad,
dwTotalPhys,
dwAvailPhys,
dwTotalPageFile,
dwAvailPageFile,
dwTotalVirtual,
dwAvailVirtual: OrigInt
end;
procedure GlobalMemoryStatus (var Buffer: TMemoryStatus); attribute (stdcall); external name 'GlobalMemoryStatus';
function MemAvail: Cardinal;
var t: TMemoryStatus;
begin
t.dwLength := SizeOf (TMemoryStatus);
GlobalMemoryStatus (t);
MemAvail := Min (t.dwAvailPhys + t.dwAvailPageFile, t.dwAvailVirtual)
end;
function MaxAvail: Cardinal;
begin
MaxAvail := MemAvail
end;
{$else}
const
{ Parameters for MemAvail and MaxAvail }
StartSize = $100000; { 1MB }
MinSize = $10;
PrecisionBits = 5;
MaxBlocks = $10;
function FindLargestMemBlock (var p: Pointer): SizeType;
var
Size, Step: SizeType;
Bits: OrigInt;
begin
Size := StartSize;
p := CGetMem (Size);
while (p <> nil) and (Size <= High (Size) div 2) do
begin
Size := 2 * Size;
CFreeMem (p);
p := CGetMem (Size)
end;
repeat
Size := Size div 2;
p := CGetMem (Size)
until (p <> nil) or (Size <= MinSize);
Bits := PrecisionBits;
Step := Size;
while (Bits > 0) and (Size >= 2 * MinSize) and (p <> nil) do
begin
Dec (Bits);
CFreeMem (p);
Inc (Size, Step);
Step := Step div 2;
repeat
Dec (Size, Step);
p := CGetMem (Size)
until (p <> nil) or (Size <= MinSize)
end;
if p = nil then
Size := 0
else if Size = 0 then
p := nil;
FindLargestMemBlock := Size
end;
function MaxAvail: Cardinal;
begin
if MaxAvailSave <> nil then CFreeMem (MaxAvailSave);
MaxAvailSize := FindLargestMemBlock (MaxAvailSave);
MaxAvail := MaxAvailSize
end;
function MemAvail: Cardinal;
type PMemList = ^PMemList;
var
TotalSize, NewSize: SizeType;
MemList, p: PMemList;
LargeEnough: Boolean;
Blocks: Integer;
begin
TotalSize := MaxAvail;
MemList := nil;
Blocks := 0;
repeat
NewSize := FindLargestMemBlock (p);
Inc (TotalSize, NewSize);
LargeEnough := NewSize >= Max (SizeOf (p^), TotalSize shr PrecisionBits);
if LargeEnough then
begin
p^ := MemList;
MemList := p;
p := nil;
Inc (Blocks)
end
until not LargeEnough or (Blocks >= MaxBlocks);
if p <> nil then CFreeMem (p);
while MemList <> nil do
begin
p := MemList;
MemList := MemList^;
CFreeMem (p)
end;
MemAvail := TotalSize
end;
{$endif}
{ Delphi compatibility }
function CompToDouble (x: Comp): Double;
begin
CompToDouble := x
end;
function DoubleToComp (x: Double): Comp;
begin
DoubleToComp := Round (x)
end;
procedure Assert (Condition: Boolean);
begin
{ @@ parameters are dummies }
if not Condition then AssertErrorProc^ ('', '', 0, ReturnAddress (0))
end;
procedure DefaultAssertErrorProc (const Message, FileName: String; LineNumber: SystemInteger; ErrorAddr: Pointer);
var s: TString;
begin
WriteStr (s, Message, ' (', FileName, ':', LineNumber, ' ', PtrInt (ErrorAddr), ')');
RuntimeErrorCString (EAssertString, s)
end;
{$ifdef __BP_RANDOM__}
{ BP compatible random number generator }
procedure NextRand;
begin
RandSeed := {$local R-} $8088405 * RandSeed + 1 {$endlocal}
end;
function BP_RandInt (Range: LongestCard): LongestCard;
type Card64 = Cardinal attribute (Size = 64);
begin
NextRand;
BP_RandInt := ({$local R-} Card64 (RandSeed) {$endlocal} * (Range mod $10000)) div $100000000
end;
function BP_RandReal: LongestReal;
begin
NextRand;
BP_RandReal := RandSeed / $100000000 + 0.5
end;
procedure BP_SeedRandom (Seed: RandomSeedType);
begin
RandSeed := Seed
end;
procedure BP_Randomize;
var Time: TimeStamp;
begin
GetTimeStamp (Time);
with Time do BP_SeedRandom (((Second * $100 + (MicroSecond div 10000)) * $100 + Hour) * $100 + Minute)
end;
{$endif}
to begin do
begin
OldGetMem := GetMemPtr;
OldFreeMem := FreeMemPtr;
GetMemPtr := @BPGetMem;
FreeMemPtr := @BPFreeMem;
{$ifdef __BP_RANDOM__}
RandomizePtr := @BP_Randomize;
SeedRandomPtr := @BP_SeedRandom;
RandRealPtr := @BP_RandReal;
RandIntPtr := @BP_RandInt;
{$endif}
{$ifdef __BP_PARAMSTR_0__}
if ParamCount >= 0 then
CParameters^[0] := NewCString (ExecutablePath);
{$endif}
var CmdLineStr: TString; attribute (static);
var i: OrigInt;
CmdLineStr := ParamStr (1);
for i := 2 to ParamCount do CmdLineStr := CmdLineStr + ' ' + ParamStr (i);
CmdLine := CmdLineStr;
{$ifndef __BP_NO_ALLOCMEM__}
Mark (FirstMark)
{$endif}
end;
to end do
begin
while ExitProc <> nil do
begin
var Tmp: ^procedure;
Tmp := ExitProc;
ExitProc := nil;
Tmp^
end;
if NoErrMsg then ErrorMessageString := ''
end;
end.
|
unit ParamSubParamsQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, Vcl.StdCtrls, NotifyEvents, DSWrap, BaseEventsQuery;
type
TParamSubParamW = class(TDSWrap)
private
FChecked: TFieldWrap;
FID: TFieldWrap;
FIDParameter: TFieldWrap;
FIDSubParameter: TFieldWrap;
FName: TFieldWrap;
FProductCategoryId: TParamWrap;
FTranslation: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
procedure AppendSubParameter(AParamID, ASubParamID: Integer);
property Checked: TFieldWrap read FChecked;
property ID: TFieldWrap read FID;
property IDParameter: TFieldWrap read FIDParameter;
property IDSubParameter: TFieldWrap read FIDSubParameter;
property Name: TFieldWrap read FName;
property ProductCategoryId: TParamWrap read FProductCategoryId;
property Translation: TFieldWrap read FTranslation;
end;
TQueryParamSubParams = class(TQueryBaseEvents)
FDUpdateSQL: TFDUpdateSQL;
private
FW: TParamSubParamW;
procedure DoAfterOpen(Sender: TObject);
{ Private declarations }
protected
function CreateDSWrap: TDSWrap; override;
procedure DoBeforeOpen(Sender: TObject);
procedure DoBeforePost(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
function GetCheckedValues(const AFieldName: String): string;
function SearchBySubParam(AParamID, ASubParamID: Integer): Integer;
property W: TParamSubParamW read FW;
{ Public declarations }
end;
implementation
{$R *.dfm}
uses RepositoryDataModule, System.StrUtils, StrHelper, BaseQuery;
constructor TQueryParamSubParams.Create(AOwner: TComponent);
begin
inherited;
FW := FDSWrap as TParamSubParamW;
TNotifyEventWrap.Create(W.BeforePost, DoBeforePost, W.EventList);
TNotifyEventWrap.Create(W.AfterOpen, DoAfterOpen, W.EventList);
TNotifyEventWrap.Create(W.BeforeOpen, DoBeforeOpen, W.EventList);
end;
function TQueryParamSubParams.CreateDSWrap: TDSWrap;
begin
Result := TParamSubParamW.Create(FDQuery);
end;
procedure TQueryParamSubParams.DoAfterOpen(Sender: TObject);
begin
W.Checked.F.ReadOnly := False;
end;
procedure TQueryParamSubParams.DoBeforeOpen(Sender: TObject);
begin
// Этот параметр - постоянный
SetParameters([W.ProductCategoryId.FieldName],
[W.ProductCategoryId.DefaultValue]);
if FDQuery.FieldCount = 0 then
begin
// Обновляем описания полей и создаём поля по умолчанию
W.CreateDefaultFields(True);
W.Checked.F.FieldKind := fkInternalCalc;
end;
end;
procedure TQueryParamSubParams.DoBeforePost(Sender: TObject);
begin
if W.IDSubParameter.F.IsNull then
// Ничего не сохраняем на сервере
FDQuery.OnUpdateRecord := DoOnQueryUpdateRecord
else
// Всё сохраняем на сервере
FDQuery.OnUpdateRecord := nil;
end;
function TQueryParamSubParams.GetCheckedValues(const AFieldName
: String): string;
var
AClone: TFDMemTable;
begin
Assert(not AFieldName.IsEmpty);
Result := '';
AClone := W.AddClone(Format('%s = %d', [W.Checked.FieldName, 1]));
try
while not AClone.Eof do
begin
Result := Result + IfThen(Result.IsEmpty, '', ',') +
AClone.FieldByName(AFieldName).AsString;
AClone.Next;
end;
finally
W.DropClone(AClone);
end;
end;
function TQueryParamSubParams.SearchBySubParam(AParamID,
ASubParamID: Integer): Integer;
begin
Assert(AParamID > 0);
Assert(ASubParamID > 0);
Result := SearchEx([TParamRec.Create(W.IDParameter.FullName, AParamID),
TParamRec.Create(W.IDSubParameter.FullName, ASubParamID)])
end;
constructor TParamSubParamW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'ID', '', True);
FIDParameter := TFieldWrap.Create(Self, 'psp.IDParameter');
FIDSubParameter := TFieldWrap.Create(Self, 'psp.IDSubParameter');
FName := TFieldWrap.Create(Self, 'Name');
FTranslation := TFieldWrap.Create(Self, 'Translation');
FChecked := TFieldWrap.Create(Self, 'Checked');
// Параметры SQL запроса
FProductCategoryId := TParamWrap.Create(Self, 'cp.ProductCategoryId');
FProductCategoryId.DefaultValue := 0;
end;
procedure TParamSubParamW.AppendSubParameter(AParamID, ASubParamID: Integer);
begin
Assert(AParamID > 0);
Assert(ASubParamID > 0);
TryAppend;
IDParameter.F.Value := AParamID;
IDSubParameter.F.Value := ASubParamID;
TryPost;
end;
end.
|
unit UFigures;
{$mode objfpc}{$H+}
interface
uses
Windows, Graphics, UTransformation, UGraph;
type
RSelectedType = (DrawFigure,
SelectedDrawFigure,
SelectedNodeDrawFigure,
NotDrawFigure);
type
{$M+}
TFigure = Class
public
PointsArray: TDoublePointArray;
protected
_PenColor: TColor;
_PenWidth: Integer;
_PenStyle: Integer;
_Selected: RSelectedType;
procedure SetDefaultCanvas(Canva: TCanvas);
published
property PointsArr: TDoublePointArray read PointsArray write PointsArray;
property PC_PenCol: TColor read _PenColor write _PenColor;
property PW_PenWid: Integer read _PenWidth write _PenWidth;
property PS_PenSty: Integer read _PenStyle write _PenStyle;
property SelectedFigure: RSelectedType read _Selected write _Selected default DrawFigure;
public
// Добавить или изменить вершину
procedure AddPoint(MousePoint: TDoublePoint; Next: Boolean); virtual;
// Проверка на пренадлежность фигуры или вершины
function MouseOverFigure(MousePoint: TDoubleRect): Boolean; virtual; abstract;
function MouseOverFigureNode(MousePoint: TDoubleRect): Integer; virtual;
// Перемещение фигуры или вершины
procedure MoveFigure(MousePoint: TDoublePoint); virtual;
procedure MoveFigureNode(MousePoint: TDoublePoint; INode: Integer); virtual;
// Виды прорисовок
procedure SelectedDraw(Canva: TCanvas); virtual;
procedure SelectedNodeDraw(Canva: TCanvas); virtual;
procedure Draw(Canva: TCanvas); virtual;
end;
{$M-}
TFigureClass = Class of TFigure;
type
TTwoPointFig = Class(TFigure)
public
end;
type
TTwoPointFigFilling = Class(TTwoPointFig)
protected
_BrushStyle: Integer;
_BrushColor: TColor;
published
property BC_BrushCol: TColor read _BrushColor write _BrushColor;
property BS_BrushSty: Integer read _BrushStyle write _BrushStyle;
public
procedure Draw(Canva: TCanvas); override;
end;
TArrayFig = Class(TFigure)
end;
type
TPencil = Class(TArrayFig)
public
procedure Draw(Canva: TCanvas); override;
function MouseOverFigure(MousePoint: TDoubleRect): Boolean; override;
procedure SelectedDraw(Canva: TCanvas); override;
end;
type
TPolyLine = Class(TPencil)
end;
type
TLine = Class(TTwoPointFig)
public
procedure Draw(Canva: TCanvas); override;
function MouseOverFigure(MousePoint: TDoubleRect): Boolean; override;
end;
TRectangle = Class(TTwoPointFigFilling)
public
procedure Draw(Canva: TCanvas); override;
function MouseOverFigure(MousePoint: TDoubleRect): Boolean; override;
end;
TEllipse = Class(TTwoPointFigFilling)
public
procedure Draw(Canva: TCanvas); override;
function MouseOverFigure(MousePoint: TDoubleRect): Boolean; override;
end;
TRoundRect = Class(TTwoPointFigFilling)
protected
_Width_Ell, _Height_Ell: Integer;
published
property PW_WidthEll: Integer read _Width_Ell write _Width_Ell;
property PW_HeightEll: Integer read _Height_Ell write _Height_Ell;
public
procedure Draw(Canva: TCanvas); override;
function MouseOverFigure(MousePoint: TDoubleRect): Boolean; override;
end;
TControl_Figure = Class
type
TFigureClassArray = array of TFigureClass;
var
Class_Figure_Array: TFigureClassArray;
procedure Register_Figures(CLFigure: TFigureClass);
function CompareName(AName: String): TFigureClass;
end;
type
TFigureArray = array of TFigure;
var
ControlFigures: TControl_Figure;
implementation
//------------------------- Class TFigure --------------------------------------
procedure TFigure.SetDefaultCanvas(Canva: TCanvas);
begin
With Canva do begin
Pen.Color := clBlack;
Pen.Width := 1;
Pen.Style := psSolid;
Brush.Color := clWhite;
Brush.Style := bsSolid;
end;
end;
procedure TFigure.Draw(Canva: TCanvas);
begin
With Canva.Pen do begin
Color := _PenColor;
Width := _PenWidth;
Style := TPenStyle(_PenStyle);
end;
end;
procedure TFigure.SelectedNodeDraw(Canva: TCanvas);
var
I: Integer;
begin
Draw(Canva);
SetDefaultCanvas(Canva);
for I := 0 to High(PointsArray) do begin
Canva.Rectangle(ExpandRect(Trans.W2S(PointsArray[I]), 3));
end;
end;
procedure TFigure.SelectedDraw(Canva: TCanvas);
begin
SelectedNodeDraw(Canva);
end;
function TFigure.MouseOverFigureNode(MousePoint: TDoubleRect): Integer;
var
I: Integer;
RectangleRgn: HRGN;
begin
Result := -1;
for I := 0 to High(PointsArray) do begin
RectangleRgn := CreateRectRgnIndirect(ExpandRect(PointsArray[I], 3 / Trans.Scale));
if RectInRegion(RectangleRgn, MousePoint) then Result := I;
DeleteObject(RectangleRgn);
end;
end;
procedure TFigure.MoveFigureNode(MousePoint: TDoublePoint; INode: Integer);
begin
PointsArray[INode] += MousePoint;
end;
procedure TFigure.MoveFigure(MousePoint: TDoublePoint);
var
I: Integer;
begin
for I := 0 to High(PointsArray) do
PointsArray[I] += MousePoint;
end;
procedure TFigure.AddPoint(MousePoint: TDoublePoint; Next: Boolean);
begin
if Next then
SetLength(PointsArray, Length(PointsArray) + 1);
PointsArray[High(PointsArray)] := MousePoint;
end;
//------------------------- TTwoPointFigFilling --------------------------------
procedure TTwoPointFigFilling.Draw(Canva: TCanvas);
begin
Inherited;
With Canva.Brush do begin
Color := _BrushColor;
Style := TBrushStyle(_BrushStyle);
end;
end;
//------------------------- Class TPencil --------------------------------------
procedure TPencil.Draw(Canva: TCanvas);
begin
Inherited;
Canva.PolyLine(Trans.W2S(PointsArray));
end;
function TPencil.MouseOverFigure(MousePoint: TDoubleRect): Boolean;
var
I: Integer;
PencilRgn: HRGN;
LinePos: array of TPoint;
begin
Result := False;
SetLength(LinePos, 2 * Length(PointsArray) - 1);
for I := 0 to High(PointsArray) do
LinePos[I] := PointsArray[I];
for I := High(PointsArray) downto 0 do
LinePos[2 * Length(PointsArray) - 1 - I] := ExpandPoint(PointsArray[I], 1);
PencilRgn:=CreatePolygonRgn(LinePos[0], Length(LinePos), WINDING);
if RectInRegion(PencilRgn, MousePoint) then Result := True;
DeleteObject(PencilRgn);
end;
procedure TPencil.SelectedDraw(Canva: TCanvas);
begin
Draw(Canva);
SetDefaultCanvas(Canva);
Canva.Rectangle(ExpandRect(Trans.W2S(PointsArray[0]), 3));
Canva.Rectangle(ExpandRect(Trans.W2S(PointsArray[High(PointsArray)]), 3));
end;
//------------------------- Class TLine ----------------------------------------
procedure TLine.Draw(Canva: TCanvas);
begin
Inherited;
Canva.Line(Trans.W2S(PointsArray[0]), Trans.W2S(PointsArray[1]));
end;
function TLine.MouseOverFigure(MousePoint: TDoubleRect): Boolean;
var
LinePos: Array[0..3] of TPoint;
LineRgn: HRGN;
begin
Result := False;
LinePos[0] := ExpandPoint(PointsArray[0], 1);
LinePos[1] := PointsArray[0];
LinePos[2] := PointsArray[1];
LinePos[3] := ExpandPoint(PointsArray[1], 1);
LineRgn := CreatePolygonRgn(LinePos[0], 4, WINDING);
if RectInRegion(LineRgn, MousePoint) then Result := True;
DeleteObject(LineRgn);
end;
//------------------------- Class TRectangle -----------------------------------
procedure TRectangle.Draw(Canva: TCanvas);
begin
Inherited;
Canva.Rectangle(Trans.W2S(DoubleRect(PointsArray[0], PointsArray[1])));
end;
function TRectangle.MouseOverFigure(MousePoint: TDoubleRect): Boolean;
var
RectangleRgn: HRGN;
begin
Result := False;
RectangleRgn := CreateRectRgnIndirect(DoubleRect(PointsArray[0], PointsArray[1]));
if RectInRegion(RectangleRgn, MousePoint) then Result := True;
DeleteObject(RectangleRgn);
end;
//------------------------- Class TRoundRect -----------------------------------
procedure TRoundRect.Draw(Canva: TCanvas);
begin
Inherited;
Canva.RoundRect(Trans.W2S(DoubleRect(PointsArray[0], PointsArray[1])),
Round(_Width_Ell * Trans.Scale),
Round(_Height_Ell * Trans.Scale));
end;
function TRoundRect.MouseOverFigure(MousePoint: TDoubleRect): Boolean;
var
RoundRectRgn: HRGN;
begin
Result := False;
RoundRectRgn := CreateRoundRectRgn(
Round(PointsArray[0].X),
Round(PointsArray[0].Y),
Round(PointsArray[1].X),
Round(PointsArray[1].Y),
_Width_Ell,
_Height_Ell);
if RectInRegion(RoundRectRgn, MousePoint) then Result := True;
DeleteObject(RoundRectRgn);
end;
//------------------------- Class TEllipse -------------------------------------
procedure TEllipse.Draw(Canva: TCanvas);
begin
Inherited;
Canva.Ellipse(Trans.W2S(DoubleRect(PointsArray[0], PointsArray[1])));
end;
function TEllipse.MouseOverFigure(MousePoint: TDoubleRect): Boolean;
var
EllipseRgn: HRGN;
begin
Result := False;
EllipseRgn := CreateEllipticRgnIndirect(DoubleRect(PointsArray[0], PointsArray[1]));
if RectInRegion(EllipseRgn, MousePoint) then Result := True;
DeleteObject(EllipseRgn);
end;
//------------------------- Работа С Массивами ClassFigure ---------------------
procedure TControl_Figure.Register_Figures(CLFigure: TFigureClass);
begin
SetLength(Class_Figure_Array, Length(Class_Figure_Array) + 1);
Class_Figure_Array[High(Class_Figure_Array)] := CLFigure;
end;
function TControl_Figure.CompareName(AName: String): TFigureClass;
var
I: Integer;
begin
for I := 0 to High(Class_Figure_Array) do
if AName = Class_Figure_Array[I].ClassName then begin
Result := Class_Figure_Array[I];
exit;
end;
Result := nil;
end;
initialization
ControlFigures := TControl_Figure.Create;
with ControlFigures do
begin
Register_Figures(TEllipse);
Register_Figures(TRectangle);
Register_Figures(TLine);
Register_Figures(TPencil);
Register_Figures(TPolyLine);
Register_Figures(TRoundRect);
end;
end.
|
namespace RemObjects.SDK.CodeGen4;
uses
RemObjects.Elements.RTL;
type
ParamFlags = public enum (&In, &Out, &InOut, &Result);
RodlEntity = public abstract class
private
fOriginalName: String;
method getOriginalName: String;
begin
exit iif(String.IsNullOrEmpty(fOriginalName), Name, fOriginalName);
end;
fCustomAttributes: Dictionary<String,String> := new Dictionary<String,String>;
fCustomAttributes_lower: Dictionary<String,String> := new Dictionary<String,String>;
method getOwnerLibrary: RodlLibrary;
begin
var lOwner: RodlEntity := self;
while ((lOwner ≠ nil) and (not(lOwner is RodlLibrary))) do
lOwner := lOwner.Owner;
exit (lOwner as RodlLibrary);
end;
protected
method FixLegacyTypes(aName: String):String;
begin
exit iif(aName.ToLowerInvariant() = "string", "AnsiString", aName);
end;
public
constructor(); virtual; empty;
constructor(node: XmlElement);
begin
LoadFromXmlNode(node);
end;
constructor(node: JsonNode);
begin
LoadFromJsonNode(node);
end;
method LoadFromXmlNode(node: XmlElement); virtual;
begin
Name := node.Attribute["Name"]:Value;
EntityID := Guid.TryParse(node.Attribute["UID"]:Value);
FromUsedRodlId := Guid.TryParse(node.Attribute["FromUsedRodlUID"]:Value);
&Abstract := node.Attribute["Abstract"]:Value = "1";
DontCodegen := node.Attribute["DontCodeGen"]:Value = "1";
var lDoc := node.FirstElementWithName("Documentation");
if (lDoc ≠ nil) and (lDoc.Nodes.Count>0) and (lDoc.Nodes[0] is XmlCData) then begin
// FirstChild because data should be enclosed within CDATA
Documentation := (lDoc.Nodes[0] as XmlCData).Value;
end;
var lCustomAttributes := node.FirstElementWithName("CustomAttributes");
if assigned(lCustomAttributes) then begin
for each childNode: XmlElement in lCustomAttributes.Elements do begin
var lValue: XmlAttribute := childNode.Attribute["Value"];
if assigned(lValue) then begin
CustomAttributes[childNode.LocalName] := lValue.Value;
CustomAttributes_lower[childNode.LocalName.ToLowerInvariant] := lValue.Value;
if childNode.LocalName.ToLowerInvariant = "soapname" then fOriginalName := lValue.Value;
end;
end;
end;
end;
method LoadFromJsonNode(node: JsonNode); virtual;
begin
Name := node["Name"]:StringValue;
EntityID := Guid.TryParse(node["ID"]:StringValue);
FromUsedRodlId := Guid.TryParse(node["FromUsedRodlUID"]:StringValue);
&Abstract := node["Abstract"]:BooleanValue;
DontCodegen := node["DontCodeGen"]:BooleanValue;
Documentation := node["Documentation"]:StringValue;
var lCustomAttributes := node["CustomAttributes"];
if assigned(lCustomAttributes) then begin
for each k in lCustomAttributes.Keys do begin
var lValue := lCustomAttributes[k]:StringValue;
if length(lValue) > 0 then begin
CustomAttributes[k] := lValue;
CustomAttributes_lower[k.ToLowerInvariant] := lValue;
if k.ToLowerInvariant = "soapname" then fOriginalName := lValue;
end;
end;
end;
end;
method HasCustomAttributes: Boolean;
begin
Result := assigned(CustomAttributes) and (CustomAttributes:Count >0)
end;
property IsFromUsedRodl: Boolean read assigned(FromUsedRodl);
{$region Properties}
property EntityID: nullable Guid;
property Name: String;
property OriginalName: String read getOriginalName write fOriginalName;
property Documentation: String;
property &Abstract: Boolean;
property CustomAttributes: Dictionary<String,String> read fCustomAttributes;
property CustomAttributes_lower: Dictionary<String,String> read fCustomAttributes_lower;
//property PluginData :XmlDocument; //????
//property HasPluginData: Boolean read getPluginData;
property GroupUnder: RodlGroup;
property FromUsedRodl: RodlUse;
property FromUsedRodlId: nullable Guid;
property Owner: RodlEntity;
property OwnerLibrary: RodlLibrary read getOwnerLibrary;
property DontCodegen: Boolean;
{$endregion}
{$IFDEF ECHOES}
method ToString: String; override;
begin
exit Name;
end;
{$ENDIF}
end;
RodlTypedEntity = public abstract class (RodlEntity)
public
method LoadFromXmlNode(node: XmlElement); override;
begin
inherited LoadFromXmlNode(node);
DataType := FixLegacyTypes(node.Attribute["DataType"].Value);
end;
method LoadFromJsonNode(node: JsonNode); override;
begin
inherited LoadFromJsonNode(node);
DataType := FixLegacyTypes(node["DataType"]:StringValue);
end;
property DataType: String;
end;
RodlEntityWithAncestor = public abstract class (RodlEntity)
private
method setAncestorEntity(value: RodlEntity);
begin
value := getAncestorEntity;
end;
method getAncestorEntity: RodlEntity;
begin
if (String.IsNullOrEmpty(AncestorName)) then exit nil;
var lRodlLibrary: RodlLibrary := OwnerLibrary;
exit iif(lRodlLibrary = nil, nil , lRodlLibrary.FindEntity(AncestorName));
end;
public
method LoadFromXmlNode(node: XmlElement); override;
begin
inherited LoadFromXmlNode(node);
if (node.Attribute["Ancestor"] ≠ nil) then AncestorName := node.Attribute["Ancestor"].Value;
end;
method LoadFromJsonNode(node: JsonNode); override;
begin
inherited LoadFromJsonNode(node);
AncestorName := node["Ancestor"]:StringValue;
end;
property AncestorName: String;
property AncestorEntity: RodlEntity read getAncestorEntity write setAncestorEntity;
end;
RodlComplexEntity<T> = public abstract class (RodlEntityWithAncestor)
where T is RodlEntity;
private
fItemsNodeNameXml: nullable String;
fItemsNodeNameJson: nullable String;
fItems: EntityCollection<T>;
property ItemsNodeNameXml: String read fItemsNodeNameXml;
property ItemsNodeNameJson: String read coalesce(fItemsNodeNameJson, ItemsNodeNameXml);
public
constructor();abstract;
constructor(nodeName:String; aItemsNodeNameXmlJson: nullable String := nil);
begin
inherited constructor;
fItemsNodeNameXml := nodeName + "s";
fItemsNodeNameJson := aItemsNodeNameXmlJson;
fItems := new EntityCollection<T>(self, nodeName);
end;
method LoadFromXmlNode(node: XmlElement; aActivator: block : T);
begin
inherited LoadFromXmlNode(node);
fItems.LoadFromXmlNode(node.FirstElementWithName(ItemsNodeNameXml), nil, aActivator);
end;
method LoadFromJsonNode(node: JsonNode; aActivator: block : T);
begin
inherited LoadFromJsonNode(node);
fItems.LoadFromJsonNode(node[ItemsNodeNameJson], nil, aActivator);
end;
method GetInheritedItems: List<T>;
begin
var lancestor := AncestorEntity;
if assigned(lancestor) and (lancestor is RodlComplexEntity<T>) then begin
result := RodlComplexEntity<T>(lancestor).GetInheritedItems;
result.Add(RodlComplexEntity<T>(lancestor).fItems.Items);
end
else begin
result := new List<T>;
end;
end;
method GetAllItems: List<T>;
begin
result := GetInheritedItems;
result.Add(Self.fItems.Items);
end;
property Items: List<T> read fItems.Items;
property Count: Int32 read fItems.Count;
property Item[index: Integer]: T read fItems[index]; default;
end;
EntityCollection<T> = public class
where T is RodlEntity;
private
fEntityNodeName: String;
fItems: List<T> := new List<T>;
public
constructor(aOwner: RodlEntity; nodeName: String);
begin
fEntityNodeName := nodeName;
Owner := aOwner;
end;
method LoadFromXmlNode(node: XmlElement; usedRodl: RodlUse; aActivator: block : T);
begin
if (node = nil) then exit;
for lNode: XmlNode in node.Elements do begin
var lr := (lNode.NodeType = XmlNodeType.Element) and (XmlElement(lNode).LocalName = fEntityNodeName);
if lr then begin
var lEntity := aActivator();
lEntity.FromUsedRodl := usedRodl;
lEntity.Owner := Owner;
lEntity.LoadFromXmlNode(XmlElement(lNode));
var lIsNew := true;
for entity:T in fItems do begin
if (entity is RodlParameter) and (lEntity is RodlParameter) and
(RodlParameter(entity).ParamFlag ≠ RodlParameter(lEntity).ParamFlag) then Continue;
if entity.EntityID:&Equals(lEntity.EntityID) then begin
if entity.Name.EqualsIgnoringCaseInvariant(lEntity.Name) then begin
lIsNew := false;
break;
end
else begin
lEntity.EntityID := Guid.NewGuid;
end;
end;
end;
if lIsNew then
AddEntity(lEntity);
end;
end;
end;
method LoadFromJsonNode(node: JsonNode; usedRodl: RodlUse; aActivator: block : T);
begin
if (node = nil) then exit;
for lNode in (node as JsonArray) do begin
//var lr := (lNode.NodeType = XmlNodeType.Element) and (XmlElement(lNode).LocalName = fEntityNodeName);
//if lr then begin
var lEntity := aActivator();
lEntity.FromUsedRodl := usedRodl;
lEntity.Owner := Owner;
lEntity.LoadFromJsonNode(lNode);
var lIsNew := true;
for entity:T in fItems do begin
if (entity is RodlParameter) and (lEntity is RodlParameter) and
(RodlParameter(entity).ParamFlag ≠ RodlParameter(lEntity).ParamFlag) then Continue;
if entity.EntityID:&Equals(lEntity.EntityID) then begin
if entity.Name.EqualsIgnoringCaseInvariant(lEntity.Name) then begin
lIsNew := false;
break;
end
else begin
lEntity.EntityID := Guid.NewGuid;
end;
end;
end;
if lIsNew then
AddEntity(lEntity);
//end;
end;
end;
method AddEntity(entity : T);
begin
fItems.Add(entity);
end;
method RemoveEntity(entity: T);
begin
fItems.Remove(entity);
end;
method RemoveEntity(index: Int32);
begin
fItems.RemoveAt(index);
end;
method FindEntity(name: String): T;
begin
for lRodlEntity: T in fItems do
if not lRodlEntity.IsFromUsedRodl and lRodlEntity.Name.EqualsIgnoringCaseInvariant(name) then exit lRodlEntity;
for lRodlEntity: T in fItems do
if lRodlEntity.Name.EqualsIgnoringCaseInvariant(name) then exit lRodlEntity;
exit nil;
end;
method SortedByAncestor: List<T>;
begin
var lResult := new List<T>;
var lAncestors := new List<T>;
{if typeOf(T).Equals(typeOf(RodlEntityWithAncestor) then begin
lResult.Add(fItems);
exit;
end;}
for each lt in fItems.OrderBy(b->b.Name) do begin
var laname:= RodlEntityWithAncestor(lt):AncestorName;
if not String.IsNullOrEmpty(laname) and (fItems.Where(b->b.Name.EqualsIgnoringCaseInvariant(laname)).Count>0) then
lAncestors.Add(lt)
else
lResult.Add(lt);
end;
var lWorked := false;
while lAncestors.Count > 0 do begin
lWorked := false;
for i: Integer := lAncestors.Count-1 downto 0 do begin
var laname:= (lAncestors[i] as RodlEntityWithAncestor).AncestorName;
var lst := lResult.Where(b->b.Name.Equals(laname)).ToList;
if lst.Count = 1 then begin
var lIndex := lResult.IndexOf(lst[0]);
lResult.Insert(lIndex+1,lAncestors[i]);
lAncestors.RemoveAt(i);
lWorked := true;
end;
if (not lWorked) and (lAncestors.Count > 0) then
new Exception("Invalid or recursive inheritance detected");
end;
end;
exit lResult;
end;
property Owner : RodlEntity;
property Count: Integer read fItems.Count;
property Items: List<T> read fItems;
property Item[Index: Integer]: T read fItems[Index]; default;
end;
end. |
unit Test.RequestListBuilder;
interface
uses TestFrameWork, GMGlobals, Threads.ReqSpecDevTemplate, RequestList;
type
TRequestListBuilderTest = class(TTestCase)
private
FRequestCollection: TRequestCollection;
FBuilder: TRequestListBuilder;
protected
procedure SetUp(); override;
procedure TearDown(); override;
published
procedure TestBuild;
end;
implementation
uses GMConst;
{ TRequestListBuilderTest }
procedure TRequestListBuilderTest.SetUp;
begin
inherited;
FRequestCollection := TRequestCollection.Create();
FBuilder := TRequestListBuilder.Create(OBJ_TYPE_COM, 6);
end;
procedure TRequestListBuilderTest.TearDown;
begin
inherited;
FBuilder.Free();
FRequestCollection.Free();
end;
procedure TRequestListBuilderTest.TestBuild;
begin
FBuilder.Build(FRequestCollection);
Check(FRequestCollection.Count > 0);
end;
initialization
RegisterTest('GMIOPSrv/RequestListBuilder', TRequestListBuilderTest.Suite);
end.
|
{ *************************************************************************** }
{ }
{ Kylix and Delphi Cross-Platform Visual Component Library }
{ }
{ Copyright (c) 1995, 2001 Borland Software Corporation }
{ }
{ *************************************************************************** }
unit TypInfo;
{$T-,X+}
interface
uses Variants, SysUtils;
type
TTypeKind = (tkUnknown, tkInteger, tkChar, tkEnumeration, tkFloat,
tkString, tkSet, tkClass, tkMethod, tkWChar, tkLString, tkWString,
tkVariant, tkArray, tkRecord, tkInterface, tkInt64, tkDynArray);
// Easy access methods
function PropType(Instance: TObject; const PropName: string): TTypeKind; overload;
function PropType(AClass: TClass; const PropName: string): TTypeKind; overload;
function PropIsType(Instance: TObject; const PropName: string;
TypeKind: TTypeKind): Boolean; overload;
function PropIsType(AClass: TClass; const PropName: string;
TypeKind: TTypeKind): Boolean; overload;
function IsStoredProp(Instance: TObject; const PropName: string): Boolean; overload;
function IsPublishedProp(Instance: TObject; const PropName: string): Boolean; overload;
function IsPublishedProp(AClass: TClass; const PropName: string): Boolean; overload;
function GetOrdProp(Instance: TObject; const PropName: string): Longint; overload;
procedure SetOrdProp(Instance: TObject; const PropName: string;
Value: Longint); overload;
function GetEnumProp(Instance: TObject; const PropName: string): string; overload;
procedure SetEnumProp(Instance: TObject; const PropName: string;
const Value: string); overload;
function GetSetProp(Instance: TObject; const PropName: string;
Brackets: Boolean = False): string; overload;
procedure SetSetProp(Instance: TObject; const PropName: string;
const Value: string); overload;
function GetObjectProp(Instance: TObject; const PropName: string;
MinClass: TClass = nil): TObject; overload;
procedure SetObjectProp(Instance: TObject; const PropName: string;
Value: TObject); overload;
function GetObjectPropClass(Instance: TObject; const PropName: string): TClass; overload;
function GetStrProp(Instance: TObject; const PropName: string): string; overload;
procedure SetStrProp(Instance: TObject; const PropName: string;
const Value: string); overload;
function GetWideStrProp(Instance: TObject; const PropName: string): WideString; overload;
procedure SetWideStrProp(Instance: TObject; const PropName: string;
const Value: WideString); overload;
function GetFloatProp(Instance: TObject; const PropName: string): Extended; overload;
procedure SetFloatProp(Instance: TObject; const PropName: string;
const Value: Extended); overload;
function GetVariantProp(Instance: TObject; const PropName: string): Variant; overload;
procedure SetVariantProp(Instance: TObject; const PropName: string;
const Value: Variant); overload;
function GetMethodProp(Instance: TObject; const PropName: string): TMethod; overload;
procedure SetMethodProp(Instance: TObject; const PropName: string;
const Value: TMethod); overload;
function GetInt64Prop(Instance: TObject; const PropName: string): Int64; overload;
procedure SetInt64Prop(Instance: TObject; const PropName: string;
const Value: Int64); overload;
function GetInterfaceProp(Instance: TObject; const PropName: string): IInterface; overload;
procedure SetInterfaceProp(Instance: TObject; const PropName: string;
const Value: IInterface); overload;
function GetPropValue(Instance: TObject; const PropName: string;
PreferStrings: Boolean = True): Variant;
procedure SetPropValue(Instance: TObject; const PropName: string;
const Value: Variant);
{ This will take any RTTI enabled object and free and nil out each of its
object properties. Please note that will also clear any objects that this
object may have property references to, so make sure to nil those out first.
}
procedure FreeAndNilProperties(AObject: TObject);
{ TPublishableVariantType - This class further expands on the TCustomVariantType
by adding easy support for accessing published properties implemented by
custom decendent variant types. The decendent variant type simply needs
to implement the GetInstance function, publish their properties and this
class will take care of the. For examples on how to do that take a look
at VarCmplx and, if you have our database components, SqlTimSt. }
type
TPublishableVariantType = class(TInvokeableVariantType, IVarInstanceReference)
protected
{ IVarInstanceReference }
function GetInstance(const V: TVarData): TObject; virtual; abstract;
public
function GetProperty(var Dest: TVarData; const V: TVarData;
const Name: string): Boolean; override;
function SetProperty(const V: TVarData; const Name: string;
const Value: TVarData): Boolean; override;
end;
{ Property access types }
type
TTypeKinds = set of TTypeKind;
TOrdType = (otSByte, otUByte, otSWord, otUWord, otSLong, otULong);
TFloatType = (ftSingle, ftDouble, ftExtended, ftComp, ftCurr);
TMethodKind = (mkProcedure, mkFunction, mkConstructor, mkDestructor,
mkClassProcedure, mkClassFunction,
{ Obsolete }
mkSafeProcedure, mkSafeFunction);
TParamFlag = (pfVar, pfConst, pfArray, pfAddress, pfReference, pfOut);
{$EXTERNALSYM TParamFlag}
TParamFlags = set of TParamFlag;
TParamFlagsBase = set of TParamFlag;
{$EXTERNALSYM TParamFlagsBase}
TIntfFlag = (ifHasGuid, ifDispInterface, ifDispatch);
{$EXTERNALSYM TIntfFlag}
TIntfFlags = set of TIntfFlag;
TIntfFlagsBase = set of TIntfFlag;
{$EXTERNALSYM TIntfFlagsBase}
const
tkAny = [Low(TTypeKind)..High(TTypeKind)];
{$EXTERNALSYM tkAny}
tkMethods = [tkMethod];
{$EXTERNALSYM tkMethods}
tkProperties = tkAny - tkMethods - [tkUnknown];
{$EXTERNALSYM tkProperties}
(*$HPPEMIT 'namespace Typinfo'*)
(*$HPPEMIT '{'*)
(*$HPPEMIT ' enum TParamFlag {pfVar, pfConst, pfArray, pfAddress, pfReference, pfOut};'*)
(*$HPPEMIT ' enum TIntfFlag {ifHasGuid, ifDispInterface, ifDispatch};'*)
(*$HPPEMIT ' struct TTypeInfo;'*)
(*$HPPEMIT ' typedef TTypeInfo *PTypeInfo;'*)
(*$HPPEMIT ' typedef SetBase<TParamFlag, pfVar, pfOut> TParamFlagsBase;'*)
(*$HPPEMIT ' typedef SetBase<TIntfFlag, ifHasGuid, ifDispatch> TIntfFlagsBase;'*)
(*$HPPEMIT ' #define tkAny (System::Set<Typinfo::TTypeKind, tkUnknown, tkDynArray> () )' *)
(*$HPPEMIT ' #define tkMethods (System::Set<Typinfo::TTypeKind, tkUnknown, tkDynArray> () )' *)
(*$HPPEMIT ' #define tkProperties (System::Set<Typinfo::TTypeKind, tkUnknown, tkDynArray> () )' *)
(*$HPPEMIT '}'*)
type
ShortStringBase = string[255];
{$EXTERNALSYM ShortStringBase}
PPTypeInfo = ^PTypeInfo;
PTypeInfo = ^TTypeInfo;
TTypeInfo = record
Kind: TTypeKind;
Name: ShortString;
{TypeData: TTypeData}
end;
PTypeData = ^TTypeData;
TTypeData = packed record
case TTypeKind of
tkUnknown, tkLString, tkWString, tkVariant: ();
tkInteger, tkChar, tkEnumeration, tkSet, tkWChar: (
OrdType: TOrdType;
case TTypeKind of
tkInteger, tkChar, tkEnumeration, tkWChar: (
MinValue: Longint;
MaxValue: Longint;
case TTypeKind of
tkInteger, tkChar, tkWChar: ();
tkEnumeration: (
BaseType: PPTypeInfo;
NameList: ShortStringBase;
EnumUnitName: ShortStringBase));
tkSet: (
CompType: PPTypeInfo));
tkFloat: (
FloatType: TFloatType);
tkString: (
MaxLength: Byte);
tkClass: (
ClassType: TClass;
ParentInfo: PPTypeInfo;
PropCount: SmallInt;
UnitName: ShortStringBase;
{PropData: TPropData});
tkMethod: (
MethodKind: TMethodKind;
ParamCount: Byte;
ParamList: array[0..1023] of Char
{ParamList: array[1..ParamCount] of
record
Flags: TParamFlags;
ParamName: ShortString;
TypeName: ShortString;
end;
ResultType: ShortString});
tkInterface: (
IntfParent : PPTypeInfo; { ancestor }
IntfFlags : TIntfFlagsBase;
Guid : TGUID;
IntfUnit : ShortStringBase;
{PropData: TPropData});
tkInt64: (
MinInt64Value, MaxInt64Value: Int64);
tkDynArray: (
elSize: Longint;
elType: PPTypeInfo; // nil if type does not require cleanup
varType: Integer; // Ole Automation varType equivalent
elType2: PPTypeInfo; // independent of cleanup
DynUnitName: ShortStringBase);
end;
TPropData = packed record
PropCount: Word;
PropList: record end;
{PropList: array[1..PropCount] of TPropInfo}
end;
PPropInfo = ^TPropInfo;
TPropInfo = packed record
PropType: PPTypeInfo;
GetProc: Pointer;
SetProc: Pointer;
StoredProc: Pointer;
Index: Integer;
Default: Longint;
NameIndex: SmallInt;
Name: ShortString;
end;
TPropInfoProc = procedure(PropInfo: PPropInfo) of object;
PPropList = ^TPropList;
TPropList = array[0..16379] of PPropInfo;
EPropertyError = class(Exception);
EPropertyConvertError = class(Exception);
{ Property management/access routines }
function GetTypeData(TypeInfo: PTypeInfo): PTypeData;
function GetEnumName(TypeInfo: PTypeInfo; Value: Integer): string;
function GetEnumValue(TypeInfo: PTypeInfo; const Name: string): Integer;
function GetPropInfo(Instance: TObject; const PropName: string;
AKinds: TTypeKinds = []): PPropInfo; overload;
function GetPropInfo(AClass: TClass; const PropName: string;
AKinds: TTypeKinds = []): PPropInfo; overload;
function GetPropInfo(TypeInfo: PTypeInfo;
const PropName: string): PPropInfo; overload;
function GetPropInfo(TypeInfo: PTypeInfo; const PropName: string;
AKinds: TTypeKinds): PPropInfo; overload;
procedure GetPropInfos(TypeInfo: PTypeInfo; PropList: PPropList);
function GetPropList(TypeInfo: PTypeInfo; TypeKinds: TTypeKinds;
PropList: PPropList; SortList: Boolean = True): Integer; overload;
function GetPropList(TypeInfo: PTypeInfo; out PropList: PPropList): Integer; overload;
function GetPropList(AObject: TObject; out PropList: PPropList): Integer; overload;
procedure SortPropList(PropList: PPropList; PropCount: Integer);
function IsStoredProp(Instance: TObject; PropInfo: PPropInfo): Boolean; overload;
{ Property access routines }
function GetOrdProp(Instance: TObject; PropInfo: PPropInfo): Longint; overload;
procedure SetOrdProp(Instance: TObject; PropInfo: PPropInfo;
Value: Longint); overload;
function GetEnumProp(Instance: TObject; PropInfo: PPropInfo): string; overload;
procedure SetEnumProp(Instance: TObject; PropInfo: PPropInfo;
const Value: string); overload;
function GetSetProp(Instance: TObject; PropInfo: PPropInfo;
Brackets: Boolean = False): string; overload;
procedure SetSetProp(Instance: TObject; PropInfo: PPropInfo;
const Value: string); overload;
function GetObjectProp(Instance: TObject; PropInfo: PPropInfo;
MinClass: TClass = nil): TObject; overload;
procedure SetObjectProp(Instance: TObject; PropInfo: PPropInfo;
Value: TObject; ValidateClass: Boolean = True); overload;
function GetObjectPropClass(Instance: TObject; PropInfo: PPropInfo): TClass; overload;
function GetObjectPropClass(PropInfo: PPropInfo): TClass; overload;
function GetStrProp(Instance: TObject; PropInfo: PPropInfo): string; overload;
procedure SetStrProp(Instance: TObject; PropInfo: PPropInfo;
const Value: string); overload;
function GetWideStrProp(Instance: TObject; PropInfo: PPropInfo): WideString; overload;
procedure SetWideStrProp(Instance: TObject; PropInfo: PPropInfo;
const Value: WideString); overload;
function GetFloatProp(Instance: TObject; PropInfo: PPropInfo): Extended; overload;
procedure SetFloatProp(Instance: TObject; PropInfo: PPropInfo;
const Value: Extended); overload;
function GetVariantProp(Instance: TObject; PropInfo: PPropInfo): Variant; overload;
procedure SetVariantProp(Instance: TObject; PropInfo: PPropInfo;
const Value: Variant); overload;
function GetMethodProp(Instance: TObject; PropInfo: PPropInfo): TMethod; overload;
procedure SetMethodProp(Instance: TObject; PropInfo: PPropInfo;
const Value: TMethod); overload;
function GetInt64Prop(Instance: TObject; PropInfo: PPropInfo): Int64; overload;
procedure SetInt64Prop(Instance: TObject; PropInfo: PPropInfo;
const Value: Int64); overload;
function GetInterfaceProp(Instance: TObject; PropInfo: PPropInfo): IInterface; overload;
procedure SetInterfaceProp(Instance: TObject; PropInfo: PPropInfo;
const Value: IInterface); overload;
var
BooleanIdents: array [Boolean] of string = ('False', 'True');
DotSep: string = '.';
{ Set to String conversion. Valid only for "register sets" - sets with fewer
than Sizeof(Integer) * 8 elements. You will have to typecast the integer
value to/from your set type.
}
function SetToString(PropInfo: PPropInfo; Value: Integer; Brackets: Boolean = False): string;
function StringToSet(PropInfo: PPropInfo; const Value: string): Integer;
implementation
uses
RTLConsts;
procedure PropertyNotFound(const Name: string);
begin
raise EPropertyError.CreateResFmt(@SUnknownProperty, [Name]);
end;
function IsPublishedProp(Instance: TObject; const PropName: string): Boolean;
begin
Result := GetPropInfo(Instance, PropName) <> nil;
end;
function IsPublishedProp(AClass: TClass; const PropName: string): Boolean;
begin
Result := GetPropInfo(AClass, PropName) <> nil;
end;
function GetPropInfo(Instance: TObject; const PropName: string; AKinds: TTypeKinds): PPropInfo;
begin
Result := GetPropInfo(Instance.ClassType, PropName, AKinds);
end;
function GetPropInfo(AClass: TClass; const PropName: string; AKinds: TTypeKinds): PPropInfo;
begin
Result := GetPropInfo(PTypeInfo(AClass.ClassInfo), PropName, AKinds);
end;
function PropIsType(Instance: TObject; const PropName: string; TypeKind: TTypeKind): Boolean;
begin
Result := PropType(Instance, PropName) = TypeKind;
end;
function PropIsType(AClass: TClass; const PropName: string; TypeKind: TTypeKind): Boolean;
begin
Result := PropType(AClass, PropName) = TypeKind;
end;
function PropType(Instance: TObject; const PropName: string): TTypeKind;
begin
Result := PropType(Instance.ClassType, PropName);
end;
function FindPropInfo(AClass: TClass; const PropName: string): PPropInfo; overload;
begin
Result := GetPropInfo(AClass, PropName);
if Result = nil then
PropertyNotFound(PropName);
end;
function FindPropInfo(Instance: TObject; const PropName: string): PPropInfo; overload;
begin
Result := GetPropInfo(Instance, PropName);
if Result = nil then
PropertyNotFound(PropName);
end;
function PropType(AClass: TClass; const PropName: string): TTypeKind;
begin
Result := FindPropInfo(AClass, PropName)^.PropType^^.Kind;
end;
function IsStoredProp(Instance: TObject; const PropName: string): Boolean;
begin
Result := IsStoredProp(Instance, FindPropInfo(Instance, PropName));
end;
function GetOrdProp(Instance: TObject; const PropName: string): Longint;
begin
Result := GetOrdProp(Instance, FindPropInfo(Instance, PropName));
end;
procedure SetOrdProp(Instance: TObject; const PropName: string;
Value: Longint);
begin
SetOrdProp(Instance, FindPropInfo(Instance, PropName), Value);
end;
function GetEnumProp(Instance: TObject; const PropName: string): string;
begin
Result := GetEnumProp(Instance, FindPropInfo(Instance, PropName));
end;
procedure SetEnumProp(Instance: TObject; const PropName: string;
const Value: string);
begin
SetEnumProp(Instance, FindPropInfo(Instance, PropName), Value);
end;
function GetSetProp(Instance: TObject; const PropName: string;
Brackets: Boolean): string;
begin
Result := GetSetProp(Instance, FindPropInfo(Instance, PropName), Brackets);
end;
procedure SetSetProp(Instance: TObject; const PropName: string;
const Value: string);
begin
SetSetProp(Instance, FindPropInfo(Instance, PropName), Value);
end;
function GetObjectProp(Instance: TObject; const PropName: string;
MinClass: TClass): TObject;
begin
Result := GetObjectProp(Instance, FindPropInfo(Instance, PropName), MinClass);
end;
procedure SetObjectProp(Instance: TObject; const PropName: string;
Value: TObject);
begin
SetObjectProp(Instance, FindPropInfo(Instance, PropName), Value);
end;
function GetObjectPropClass(Instance: TObject; const PropName: string): TClass;
begin
Result := GetObjectPropClass(FindPropInfo(Instance, PropName));
end;
function GetStrProp(Instance: TObject; const PropName: string): string;
begin
Result := GetStrProp(Instance, FindPropInfo(Instance, PropName));
end;
procedure SetStrProp(Instance: TObject; const PropName: string;
const Value: string);
begin
SetStrProp(Instance, FindPropInfo(Instance, PropName), Value);
end;
function GetWideStrProp(Instance: TObject; const PropName: string): WideString;
begin
Result := GetWideStrProp(Instance, FindPropInfo(Instance, PropName));
end;
procedure SetWideStrProp(Instance: TObject; const PropName: string;
const Value: WideString);
begin
SetStrProp(Instance, FindPropInfo(Instance, PropName), Value);
end;
function GetFloatProp(Instance: TObject; const PropName: string): Extended;
begin
Result := GetFloatProp(Instance, FindPropInfo(Instance, PropName));
end;
procedure SetFloatProp(Instance: TObject; const PropName: string;
const Value: Extended);
begin
SetFloatProp(Instance, FindPropInfo(Instance, PropName), Value);
end;
function GetVariantProp(Instance: TObject; const PropName: string): Variant;
begin
Result := GetVariantProp(Instance, FindPropInfo(Instance, PropName));
end;
procedure SetVariantProp(Instance: TObject; const PropName: string;
const Value: Variant);
begin
SetVariantProp(Instance, FindPropInfo(Instance, PropName), Value);
end;
function GetMethodProp(Instance: TObject; const PropName: string): TMethod;
begin
Result := GetMethodProp(Instance, FindPropInfo(Instance, PropName));
end;
procedure SetMethodProp(Instance: TObject; const PropName: string;
const Value: TMethod);
begin
SetMethodProp(Instance, FindPropInfo(Instance, PropName), Value);
end;
function GetInt64Prop(Instance: TObject; const PropName: string): Int64;
begin
Result := GetInt64Prop(Instance, FindPropInfo(Instance, PropName));
end;
procedure SetInt64Prop(Instance: TObject; const PropName: string;
const Value: Int64);
begin
SetInt64Prop(Instance, FindPropInfo(Instance, PropName), Value);
end;
function GetPropValue(Instance: TObject; const PropName: string;
PreferStrings: Boolean): Variant;
var
PropInfo: PPropInfo;
begin
// assume failure
Result := Null;
// get the prop info
PropInfo := GetPropInfo(Instance, PropName);
if PropInfo = nil then
PropertyNotFound(PropName)
else
begin
// return the right type
case PropInfo^.PropType^^.Kind of
tkInteger, tkChar, tkWChar, tkClass:
Result := GetOrdProp(Instance, PropInfo);
tkEnumeration:
if PreferStrings then
Result := GetEnumProp(Instance, PropInfo)
else if GetTypeData(PropInfo^.PropType^)^.BaseType^ = TypeInfo(Boolean) then
Result := Boolean(GetOrdProp(Instance, PropInfo))
else
Result := GetOrdProp(Instance, PropInfo);
tkSet:
if PreferStrings then
Result := GetSetProp(Instance, PropInfo)
else
Result := GetOrdProp(Instance, PropInfo);
tkFloat:
Result := GetFloatProp(Instance, PropInfo);
tkMethod:
Result := PropInfo^.PropType^.Name;
tkString, tkLString:
Result := GetStrProp(Instance, PropInfo);
tkWString:
Result := GetWideStrProp(Instance, PropInfo);
tkVariant:
Result := GetVariantProp(Instance, PropInfo);
tkInt64:
Result := GetInt64Prop(Instance, PropInfo);
tkDynArray:
DynArrayToVariant(Result, Pointer(GetOrdProp(Instance, PropInfo)), PropInfo^.PropType^);
else
raise EPropertyConvertError.CreateResFmt(@SInvalidPropertyType,
[PropInfo.PropType^^.Name]);
end;
end;
end;
procedure SetPropValue(Instance: TObject; const PropName: string;
const Value: Variant);
function RangedValue(const AMin, AMax: Int64): Int64;
begin
Result := Trunc(Value);
if Result < AMin then
Result := AMin;
if Result > AMax then
Result := AMax;
end;
var
PropInfo: PPropInfo;
TypeData: PTypeData;
DynArray: Pointer;
begin
// get the prop info
PropInfo := GetPropInfo(Instance, PropName);
if PropInfo = nil then
PropertyNotFound(PropName)
else
begin
TypeData := GetTypeData(PropInfo^.PropType^);
// set the right type
case PropInfo.PropType^^.Kind of
tkInteger, tkChar, tkWChar:
if TypeData^.MinValue < TypeData^.MaxValue then
SetOrdProp(Instance, PropInfo, RangedValue(TypeData^.MinValue,
TypeData^.MaxValue))
else
// Unsigned type
SetOrdProp(Instance, PropInfo,
RangedValue(LongWord(TypeData^.MinValue),
LongWord(TypeData^.MaxValue)));
tkEnumeration:
if VarType(Value) = varString then
SetEnumProp(Instance, PropInfo, VarToStr(Value))
else if VarType(Value) = varBoolean then
// Need to map variant boolean values -1,0 to 1,0
SetOrdProp(Instance, PropInfo, Abs(Trunc(Value)))
else
SetOrdProp(Instance, PropInfo, RangedValue(TypeData^.MinValue,
TypeData^.MaxValue));
tkSet:
if VarType(Value) = varInteger then
SetOrdProp(Instance, PropInfo, Value)
else
SetSetProp(Instance, PropInfo, VarToStr(Value));
tkFloat:
SetFloatProp(Instance, PropInfo, Value);
tkString, tkLString:
SetStrProp(Instance, PropInfo, VarToStr(Value));
tkWString:
SetWideStrProp(Instance, PropInfo, VarToWideStr(Value));
tkVariant:
SetVariantProp(Instance, PropInfo, Value);
tkInt64:
SetInt64Prop(Instance, PropInfo, RangedValue(TypeData^.MinInt64Value,
TypeData^.MaxInt64Value));
tkDynArray:
begin
DynArrayFromVariant(DynArray, Value, PropInfo^.PropType^);
SetOrdProp(Instance, PropInfo, Integer(DynArray));
end;
else
raise EPropertyConvertError.CreateResFmt(@SInvalidPropertyType,
[PropInfo.PropType^^.Name]);
end;
end;
end;
procedure FreeAndNilProperties(AObject: TObject);
var
I, Count: Integer;
PropInfo: PPropInfo;
TempList: PPropList;
LObject: TObject;
begin
Count := GetPropList(AObject, TempList);
if Count > 0 then
try
for I := 0 to Count - 1 do
begin
PropInfo := TempList^[I];
if (PropInfo^.PropType^.Kind = tkClass) and
Assigned(PropInfo^.GetProc) and
Assigned(PropInfo^.SetProc) then
begin
LObject := GetObjectProp(AObject, PropInfo);
if LObject <> nil then
begin
SetObjectProp(AObject, PropInfo, nil);
LObject.Free;
end;
end;
end;
finally
FreeMem(TempList);
end;
end;
{ TPublishableVariantType }
function TPublishableVariantType.GetProperty(var Dest: TVarData;
const V: TVarData; const Name: string): Boolean;
begin
Variant(Dest) := GetPropValue(GetInstance(V), Name);
Result := True;
end;
function TPublishableVariantType.SetProperty(const V: TVarData;
const Name: string; const Value: TVarData): Boolean;
begin
SetPropValue(GetInstance(V), Name, Variant(Value));
Result := True;
end;
function GetTypeData(TypeInfo: PTypeInfo): PTypeData;
asm
{ -> EAX Pointer to type info }
{ <- EAX Pointer to type data }
{ it's really just to skip the kind and the name }
XOR EDX,EDX
MOV DL,[EAX].TTypeInfo.Name.Byte[0]
LEA EAX,[EAX].TTypeInfo.Name[EDX+1]
end;
function GetEnumName(TypeInfo: PTypeInfo; Value: Integer): string;
var
P: ^ShortString;
T: PTypeData;
begin
if TypeInfo^.Kind = tkInteger then
begin
Result := IntToStr(Value);
Exit;
end;
T := GetTypeData(GetTypeData(TypeInfo)^.BaseType^);
if (TypeInfo = System.TypeInfo(Boolean)) or (T^.MinValue < 0) then
begin
if TypeInfo = System.TypeInfo(Boolean) then
Result := BooleanIdents[Boolean(Value)]
else // LongBool/WordBool/ByteBool
Result := BooleanIdents[Ord(Value) <> 0]; // map non-zero to true
if SameText(HexDisplayPrefix, '0x') then Result := LowerCase(Result);
end
else
begin
P := @T^.NameList;
while Value <> 0 do
begin
Inc(Integer(P), Length(P^) + 1);
Dec(Value);
end;
Result := P^;
end;
end;
function GetEnumNameValue(TypeInfo: PTypeInfo; const Name: string): Integer;
asm
{ -> EAX Pointer to type info }
{ EDX Pointer to string }
{ <- EAX Value }
PUSH EBX
PUSH ESI
PUSH EDI
TEST EDX,EDX
JE @notFound
{ point ESI to first name of the base type }
XOR ECX,ECX
MOV CL,[EAX].TTypeInfo.Name.Byte[0]
MOV EAX,[EAX].TTypeInfo.Name[ECX+1].TTypeData.BaseType
MOV EAX,[EAX]
MOV CL,[EAX].TTypeInfo.Name.Byte[0]
LEA ESI,[EAX].TTypeInfo.Name[ECX+1].TTypeData.NameList
{ make EDI the high bound of the enum type }
MOV EDI,[EAX].TTypeInfo.Name[ECX+1].TTypeData.MaxValue
{ EAX is our running index }
XOR EAX,EAX
{ make ECX the length of the current string }
@outerLoop:
MOV CL,[ESI]
CMP ECX,[EDX-4]
JNE @lengthMisMatch
{ we know for sure the names won't be zero length }
@cmpLoop:
MOV BL,[EDX+ECX-1]
XOR BL,[ESI+ECX]
TEST BL,0DFH
JNE @misMatch
DEC ECX
JNE @cmpLoop
{ as we didn't have a mismatch, we must have found the name }
JMP @exit
@misMatch:
MOV CL,[ESI]
@lengthMisMatch:
INC EAX
LEA ESI,[ESI+ECX+1]
CMP EAX,EDI
JLE @outerLoop
{ we haven't found the thing - return -1 }
@notFound:
OR EAX,-1
@exit:
POP EDI
POP ESI
POP EBX
end;
function GetEnumValue(TypeInfo: PTypeInfo; const Name: string): Integer;
begin
if TypeInfo^.Kind = tkInteger then
Result := StrToInt(Name)
else
begin
assert(TypeInfo^.Kind = tkEnumeration);
if GetTypeData(TypeInfo)^.MinValue < 0 then // Longbool/wordbool/bytebool
begin
if SameText(Name, BooleanIdents[False]) then
Result := 0
else if SameText(Name, BooleanIdents[True]) then
Result := -1
else
Result := StrToInt(Name);
end
else
Result := GetEnumNameValue(TypeInfo, Name);
end;
end;
function GetPropInfo(TypeInfo: PTypeInfo; const PropName: string): PPropInfo;
asm
{ -> EAX Pointer to type info }
{ EDX Pointer to prop name }
{ <- EAX Pointer to prop info }
PUSH EBX
PUSH ESI
PUSH EDI
TEST EAX, EAX
JZ @exit
MOV ECX,EDX
OR EDX,EDX
JE @outerLoop
MOV CL,[EDX-4]
MOV CH,[EDX]
AND ECX,0DFFFH
@outerLoop:
XOR EBX,EBX
MOV BL,[EAX].TTypeInfo.Name.Byte[0]
LEA ESI,[EAX].TTypeInfo.Name[EBX+1]
MOV BL,[ESI].TTypeData.UnitName.Byte[0]
MOVZX EDI,[ESI].TTypeData.UnitName[EBX+1].TPropData.PropCount
TEST EDI,EDI
JE @parent
LEA EAX,[ESI].TTypeData.UnitName[EBX+1].TPropData.PropList
@innerLoop:
MOV BX,[EAX].TPropInfo.Name.Word[0]
AND BH,0DFH
CMP EBX,ECX
JE @matchStart
@nextProperty:
MOV BH,0
DEC EDI
LEA EAX,[EAX].TPropInfo.Name[EBX+1]
JNE @innerLoop
@parent:
MOV EAX,[ESI].TTypeData.ParentInfo
TEST EAX,EAX
JE @exit
MOV EAX,[EAX]
JMP @outerLoop
@misMatch:
MOV CH,[EDX]
AND CH,0DFH
MOV BL,[EAX].TPropInfo.Name.Byte[0]
JMP @nextProperty
@matchStart:
MOV BH,0
@matchLoop:
MOV CH,[EDX+EBX-1]
XOR CH,[EAX].TPropInfo.Name.Byte[EBX]
TEST CH,0DFH
JNE @misMatch
DEC EBX
JNE @matchLoop
@exit:
POP EDI
POP ESI
POP EBX
end;
function GetPropInfo(TypeInfo: PTypeInfo; const PropName: string; AKinds: TTypeKinds): PPropInfo;
begin
Result := GetPropInfo(TypeInfo, PropName);
if (Result <> nil) and
(AKinds <> []) and
not (Result^.PropType^^.Kind in AKinds) then
Result := nil;
end;
procedure GetPropInfos(TypeInfo: PTypeInfo; PropList: PPropList); assembler;
asm
{ -> EAX Pointer to type info }
{ EDX Pointer to prop list }
{ <- nothing }
PUSH EBX
PUSH ESI
PUSH EDI
XOR ECX,ECX
MOV ESI,EAX
MOV CL,[EAX].TTypeInfo.Name.Byte[0]
MOV EDI,EDX
XOR EAX,EAX
MOVZX ECX,[ESI].TTypeInfo.Name[ECX+1].TTypeData.PropCount
REP STOSD
@outerLoop:
MOV CL,[ESI].TTypeInfo.Name.Byte[0]
LEA ESI,[ESI].TTypeInfo.Name[ECX+1]
MOV CL,[ESI].TTypeData.UnitName.Byte[0]
MOVZX EAX,[ESI].TTypeData.UnitName[ECX+1].TPropData.PropCount
TEST EAX,EAX
JE @parent
LEA EDI,[ESI].TTypeData.UnitName[ECX+1].TPropData.PropList
@innerLoop:
MOVZX EBX,[EDI].TPropInfo.NameIndex
MOV CL,[EDI].TPropInfo.Name.Byte[0]
CMP dword ptr [EDX+EBX*4],0
JNE @alreadySet
MOV [EDX+EBX*4],EDI
@alreadySet:
LEA EDI,[EDI].TPropInfo.Name[ECX+1]
DEC EAX
JNE @innerLoop
@parent:
MOV ESI,[ESI].TTypeData.ParentInfo
XOR ECX,ECX
TEST ESI,ESI
JE @exit
MOV ESI,[ESI]
JMP @outerLoop
@exit:
POP EDI
POP ESI
POP EBX
end;
procedure SortPropList(PropList: PPropList; PropCount: Integer); assembler;
asm
{ -> EAX Pointer to prop list }
{ EDX Property count }
{ <- nothing }
PUSH EBX
PUSH ESI
PUSH EDI
MOV ECX,EAX
XOR EAX,EAX
DEC EDX
CALL @@qsort
POP EDI
POP ESI
POP EBX
JMP @@exit
@@qsort:
PUSH EAX
PUSH EDX
LEA EDI,[EAX+EDX] { pivot := (left + right) div 2 }
SHR EDI,1
MOV EDI,[ECX+EDI*4]
ADD EDI,OFFSET TPropInfo.Name
@@repeat: { repeat }
@@while1:
CALL @@compare { while a[i] < a[pivot] do inc(i);}
JAE @@endWhile1
INC EAX
JMP @@while1
@@endWhile1:
XCHG EAX,EDX
@@while2:
CALL @@compare { while a[j] > a[pivot] do dec(j);}
JBE @@endWhile2
DEC EAX
JMP @@while2
@@endWhile2:
XCHG EAX,EDX
CMP EAX,EDX { if i <= j then begin }
JG @@endRepeat
MOV EBX,[ECX+EAX*4] { x := a[i]; }
MOV ESI,[ECX+EDX*4] { y := a[j]; }
MOV [ECX+EDX*4],EBX { a[j] := x; }
MOV [ECX+EAX*4],ESI { a[i] := y; }
INC EAX { inc(i); }
DEC EDX { dec(j); }
{ end; }
CMP EAX,EDX { until i > j; }
JLE @@repeat
@@endRepeat:
POP ESI
POP EBX
CMP EAX,ESI
JL @@rightNonEmpty { if i >= right then begin }
CMP EDX,EBX
JG @@leftNonEmpty1 { if j <= left then exit }
RET
@@leftNonEmpty1:
MOV EAX,EBX
JMP @@qsort { qsort(left, j) }
@@rightNonEmpty:
CMP EAX,EBX
JG @@leftNonEmpty2
MOV EDX,ESI { qsort(i, right) }
JMP @@qsort
@@leftNonEmpty2:
PUSH EAX
PUSH ESI
MOV EAX,EBX
CALL @@qsort { qsort(left, j) }
POP EDX
POP EAX
JMP @@qsort { qsort(i, right) }
@@compare:
PUSH EAX
PUSH EDI
MOV ESI,[ECX+EAX*4]
ADD ESI,OFFSET TPropInfo.Name
PUSH ESI
XOR EBX,EBX
MOV BL,[ESI]
INC ESI
CMP BL,[EDI]
JBE @@firstLenSmaller
MOV BL,[EDI]
@@firstLenSmaller:
INC EDI
TEST BL,BL
JE @@endLoop
@@loop:
MOV AL,[ESI]
MOV AH,[EDI]
AND EAX,$DFDF
CMP AL,AH
JNE @@difference
INC ESI
INC EDI
DEC EBX
JNZ @@loop
@@endLoop:
POP ESI
POP EDI
MOV AL,[ESI]
MOV AH,[EDI]
CMP AL,AH
POP EAX
RET
@@difference:
POP ESI
POP EDI
POP EAX
RET
@@exit:
end;
{ TypeInfo is the type info of a class. Return all properties matching
TypeKinds in this class or its ancestors in PropList and return the count }
function GetPropList(TypeInfo: PTypeInfo; TypeKinds: TTypeKinds;
PropList: PPropList; SortList: Boolean): Integer;
var
I, Count: Integer;
PropInfo: PPropInfo;
TempList: PPropList;
begin
Result := 0;
Count := GetPropList(TypeInfo, TempList);
if Count > 0 then
try
for I := 0 to Count - 1 do
begin
PropInfo := TempList^[I];
if PropInfo^.PropType^.Kind in TypeKinds then
begin
if PropList <> nil then
PropList^[Result] := PropInfo;
Inc(Result);
end;
end;
if SortList and (PropList <> nil) and (Result > 1) then
SortPropList(PropList, Result);
finally
FreeMem(TempList);
end;
end;
function GetPropList(TypeInfo: PTypeInfo; out PropList: PPropList): Integer;
begin
Result := GetTypeData(TypeInfo)^.PropCount;
if Result > 0 then
begin
GetMem(PropList, Result * SizeOf(Pointer));
GetPropInfos(TypeInfo, PropList);
end;
end;
function GetPropList(AObject: TObject; out PropList: PPropList): Integer;
begin
Result := GetPropList(PTypeInfo(AObject.ClassInfo), PropList);
end;
function IsStoredProp(Instance: TObject; PropInfo: PPropInfo): Boolean;
asm
{ -> EAX Pointer to Instance }
{ EDX Pointer to prop info }
{ <- AL Function result }
MOV ECX,[EDX].TPropInfo.StoredProc
TEST ECX,0FFFFFF00H
JE @@returnCL
CMP [EDX].TPropInfo.StoredProc.Byte[3],0FEH
MOV EDX,[EDX].TPropInfo.Index
JB @@isStaticMethod
JA @@isField
{ the StoredProc is a virtual method }
MOVSX ECX,CX { sign extend slot offs }
ADD ECX,[EAX] { vmt + slotoffs }
CALL dword ptr [ECX] { call vmt[slot] }
JMP @@exit
@@isStaticMethod:
CALL ECX
JMP @@exit
@@isField:
AND ECX,$00FFFFFF
MOV CL,[EAX+ECX]
@@returnCL:
MOV AL,CL
@@exit:
end;
function GetOrdProp(Instance: TObject; PropInfo: PPropInfo): Longint;
asm
{ -> EAX Pointer to instance }
{ EDX Pointer to property info }
{ <- EAX Longint result }
PUSH EBX
PUSH EDI
MOV EDI,[EDX].TPropInfo.PropType
MOV EDI,[EDI]
MOV BL,otSLong
CMP [EDI].TTypeInfo.Kind,tkClass
JE @@isClass
XOR ECX,ECX
MOV CL,[EDI].TTypeInfo.Name.Byte[0]
MOV BL,[EDI].TTypeInfo.Name[ECX+1].TTypeData.OrdType
@@isClass:
MOV ECX,[EDX].TPropInfo.GetProc
CMP [EDX].TPropInfo.GetProc.Byte[3],$FE
MOV EDX,[EDX].TPropInfo.Index
JB @@isStaticMethod
JA @@isField
{ the GetProc is a virtual method }
MOVSX ECX,CX { sign extend slot offs }
ADD ECX,[EAX] { vmt + slotoffs }
CALL dword ptr [ECX] { call vmt[slot] }
JMP @@final
@@isStaticMethod:
CALL ECX
JMP @@final
@@isField:
AND ECX,$00FFFFFF
ADD ECX,EAX
MOV AL,[ECX]
CMP BL,otSWord
JB @@final
MOV AX,[ECX]
CMP BL,otSLong
JB @@final
MOV EAX,[ECX]
@@final:
CMP BL,otSLong
JAE @@exit
CMP BL,otSWord
JAE @@word
CMP BL,otSByte
MOVSX EAX,AL
JE @@exit
AND EAX,$FF
JMP @@exit
@@word:
MOVSX EAX,AX
JE @@exit
AND EAX,$FFFF
@@exit:
POP EDI
POP EBX
end;
procedure SetOrdProp(Instance: TObject; PropInfo: PPropInfo;
Value: Longint); assembler;
asm
{ -> EAX Pointer to instance }
{ EDX Pointer to property info }
{ ECX Value }
PUSH EBX
PUSH ESI
PUSH EDI
MOV EDI,EDX
MOV ESI,[EDI].TPropInfo.PropType
MOV ESI,[ESI]
MOV BL,otSLong
CMP [ESI].TTypeInfo.Kind,tkClass
JE @@isClass
XOR EBX,EBX
MOV BL,[ESI].TTypeInfo.Name.Byte[0]
MOV BL,[ESI].TTypeInfo.Name[EBX+1].TTypeData.OrdType
@@isClass:
MOV EDX,[EDI].TPropInfo.Index { pass Index in DX }
CMP EDX,$80000000
JNE @@hasIndex
MOV EDX,ECX { pass value in EDX }
@@hasIndex:
MOV ESI,[EDI].TPropInfo.SetProc
CMP [EDI].TPropInfo.SetProc.Byte[3],$FE
JA @@isField
JB @@isStaticMethod
{ SetProc turned out to be a virtual method. call it }
MOVSX ESI,SI { sign extend slot offset }
ADD ESI,[EAX] { vmt + slot offset }
CALL dword ptr [ESI]
JMP @@exit
@@isStaticMethod:
CALL ESI
JMP @@exit
@@isField:
AND ESI,$00FFFFFF
ADD EAX,ESI
MOV [EAX],CL
CMP BL,otSWord
JB @@exit
MOV [EAX],CX
CMP BL,otSLong
JB @@exit
MOV [EAX],ECX
@@exit:
POP EDI
POP ESI
POP EBX
end;
function GetEnumProp(Instance: TObject; PropInfo: PPropInfo): string;
begin
Result := GetEnumName(PropInfo^.PropType^, GetOrdProp(Instance, PropInfo));
end;
procedure SetEnumProp(Instance: TObject; PropInfo: PPropInfo;
const Value: string);
var
Data: Longint;
begin
Data := GetEnumValue(PropInfo^.PropType^, Value);
if Data < 0 then
raise EPropertyConvertError.CreateResFmt(@SInvalidPropertyElement, [Value]);
SetOrdProp(Instance, PropInfo, Data);
end;
function GetSetProp(Instance: TObject; PropInfo: PPropInfo;
Brackets: Boolean): string;
begin
Result := SetToString(PropInfo, GetOrdProp(Instance, PropInfo), Brackets);
end;
function SetToString(PropInfo: PPropInfo; Value: Integer; Brackets: Boolean): string;
var
S: TIntegerSet;
TypeInfo: PTypeInfo;
I: Integer;
begin
Result := '';
Integer(S) := Value;
TypeInfo := GetTypeData(PropInfo^.PropType^)^.CompType^;
for I := 0 to SizeOf(Integer) * 8 - 1 do
if I in S then
begin
if Result <> '' then
Result := Result + ',';
Result := Result + GetEnumName(TypeInfo, I);
end;
if Brackets then
Result := '[' + Result + ']';
end;
function StringToSet(PropInfo: PPropInfo; const Value: string): Integer;
var
P: PChar;
EnumName: string;
EnumValue: Longint;
EnumInfo: PTypeInfo;
// grab the next enum name
function NextWord(var P: PChar): string;
var
i: Integer;
begin
i := 0;
// scan til whitespace
while not (P[i] in [',', ' ', #0,']']) do
Inc(i);
SetString(Result, P, i);
// skip whitespace
while P[i] in [',', ' ',']'] do
Inc(i);
Inc(P, i);
end;
begin
Result := 0;
if Value = '' then Exit;
P := PChar(Value);
// skip leading bracket and whitespace
while P^ in ['[',' '] do
Inc(P);
EnumInfo := GetTypeData(PropInfo^.PropType^)^.CompType^;
EnumName := NextWord(P);
while EnumName <> '' do
begin
EnumValue := GetEnumValue(EnumInfo, EnumName);
if EnumValue < 0 then
raise EPropertyConvertError.CreateResFmt(@SInvalidPropertyElement, [EnumName]);
Include(TIntegerSet(Result), EnumValue);
EnumName := NextWord(P);
end;
end;
procedure SetSetProp(Instance: TObject; PropInfo: PPropInfo;
const Value: string);
begin
SetOrdProp(Instance, PropInfo, StringToSet(PropInfo, Value));
end;
function GetObjectProp(Instance: TObject; PropInfo: PPropInfo; MinClass: TClass): TObject;
begin
Result := TObject(GetOrdProp(Instance, PropInfo));
if (Result <> nil) and (MinClass <> nil) and
not (Result is MinClass) then
Result := nil;
end;
procedure SetObjectProp(Instance: TObject; PropInfo: PPropInfo;
Value: TObject; ValidateClass: Boolean);
begin
if (Value = nil) or
(not ValidateClass) or
(Value is GetObjectPropClass(PropInfo)) then
SetOrdProp(Instance, PropInfo, Integer(Value));
end;
function GetObjectPropClass(Instance: TObject; PropInfo: PPropInfo): TClass;
begin
Result := GetObjectPropClass(PropInfo);
end;
function GetObjectPropClass(PropInfo: PPropInfo): TClass;
var
TypeData: PTypeData;
begin
TypeData := GetTypeData(PropInfo^.PropType^);
if TypeData = nil then
raise EPropertyError.CreateRes(@SInvalidPropertyValue);
Result := TypeData^.ClassType;
end;
procedure GetShortStrProp(Instance: TObject; PropInfo: PPropInfo;
var Value: ShortString); assembler;
asm
{ -> EAX Pointer to instance }
{ EDX Pointer to property info }
{ ECX Pointer to result string }
PUSH ESI
PUSH EDI
MOV EDI,EDX
MOV EDX,[EDI].TPropInfo.Index { pass index in EDX }
CMP EDX,$80000000
JNE @@hasIndex
MOV EDX,ECX { pass value in EDX }
@@hasIndex:
MOV ESI,[EDI].TPropInfo.GetProc
CMP [EDI].TPropInfo.GetProc.Byte[3],$FE
JA @@isField
JB @@isStaticMethod
{ GetProc turned out to be a virtual method }
MOVSX ESI,SI { sign extend slot offset}
ADD ESI,[EAX] { vmt + slot offset }
CALL dword ptr [ESI]
JMP @@exit
@@isStaticMethod:
CALL ESI
JMP @@exit
@@isField:
AND ESI,$00FFFFFF
ADD ESI,EAX
MOV EDI,ECX
XOR ECX,ECX
MOV CL,[ESI]
INC ECX
REP MOVSB
@@exit:
POP EDI
POP ESI
end;
procedure SetShortStrProp(Instance: TObject; PropInfo: PPropInfo;
const Value: ShortString); assembler;
asm
{ -> EAX Pointer to instance }
{ EDX Pointer to property info }
{ ECX Pointer to string value }
PUSH ESI
PUSH EDI
MOV ESI,EDX
MOV EDX,[ESI].TPropInfo.Index { pass index in EDX }
CMP EDX,$80000000
JNE @@hasIndex
MOV EDX,ECX { pass value in EDX }
@@hasIndex:
MOV EDI,[ESI].TPropInfo.SetProc
CMP [ESI].TPropInfo.SetProc.Byte[3],$FE
JA @@isField
JB @@isStaticMethod
{ SetProc is a virtual method }
MOVSX EDI,DI
ADD EDI,[EAX]
CALL dword ptr [EDI]
JMP @@exit
@@isStaticMethod:
CALL EDI
JMP @@exit
@@isField:
AND EDI,$00FFFFFF
ADD EDI,EAX
MOV EAX,[ESI].TPropInfo.PropType
MOV EAX,[EAX]
MOV ESI,ECX
XOR ECX,ECX
MOV CL,[EAX].TTypeInfo.Name.Byte[0]
MOV CL,[EAX].TTypeInfo.Name[ECX+1].TTypeData.MaxLength
LODSB
CMP AL,CL
JB @@noTruncate
MOV AL,CL
@@noTruncate:
STOSB
MOV CL,AL
REP MOVSB
@@exit:
POP EDI
POP ESI
end;
procedure GetShortStrPropAsLongStr(Instance: TObject; PropInfo: PPropInfo;
var Value: string);
var
Temp: ShortString;
begin
GetShortStrProp(Instance, PropInfo, Temp);
Value := Temp;
end;
procedure SetShortStrPropAsLongStr(Instance: TObject; PropInfo: PPropInfo;
const Value: string);
var
Temp: ShortString;
begin
Temp := Value;
SetShortStrProp(Instance, PropInfo, Temp);
end;
procedure AssignLongStr(var Dest: string; const Source: string);
begin
Dest := Source;
end;
procedure GetLongStrProp(Instance: TObject; PropInfo: PPropInfo;
var Value: string); assembler;
asm
{ -> EAX Pointer to instance }
{ EDX Pointer to property info }
{ ECX Pointer to result string }
PUSH ESI
PUSH EDI
MOV EDI,EDX
MOV EDX,[EDI].TPropInfo.Index { pass index in EDX }
CMP EDX,$80000000
JNE @@hasIndex
MOV EDX,ECX { pass value in EDX }
@@hasIndex:
MOV ESI,[EDI].TPropInfo.GetProc
CMP [EDI].TPropInfo.GetProc.Byte[3],$FE
JA @@isField
JB @@isStaticMethod
@@isVirtualMethod:
MOVSX ESI,SI { sign extend slot offset }
ADD ESI,[EAX] { vmt + slot offset }
CALL DWORD PTR [ESI]
JMP @@exit
@@isStaticMethod:
CALL ESI
JMP @@exit
@@isField:
AND ESI,$00FFFFFF
MOV EDX,[EAX+ESI]
MOV EAX,ECX
CALL AssignLongStr
@@exit:
POP EDI
POP ESI
end;
procedure SetLongStrProp(Instance: TObject; PropInfo: PPropInfo;
const Value: string); assembler;
asm
{ -> EAX Pointer to instance }
{ EDX Pointer to property info }
{ ECX Pointer to string value }
PUSH ESI
PUSH EDI
MOV ESI,EDX
MOV EDX,[ESI].TPropInfo.Index { pass index in EDX }
CMP EDX,$80000000
JNE @@hasIndex
MOV EDX,ECX { pass value in EDX }
@@hasIndex:
MOV EDI,[ESI].TPropInfo.SetProc
CMP [ESI].TPropInfo.SetProc.Byte[3],$FE
JA @@isField
JB @@isStaticMethod
@@isVirtualMethod:
MOVSX EDI,DI
ADD EDI,[EAX]
CALL DWORD PTR [EDI]
JMP @@exit
@@isStaticMethod:
CALL EDI
JMP @@exit
@@isField:
AND EDI,$00FFFFFF
ADD EAX,EDI
MOV EDX,ECX
CALL AssignLongStr
@@exit:
POP EDI
POP ESI
end;
procedure GetWideStrPropAsLongStr(Instance: TObject; PropInfo: PPropInfo;
var Value: string);
begin
Value := GetWideStrProp(Instance, PropInfo);
end;
procedure SetWideStrPropAsLongStr(Instance: TObject; PropInfo: PPropInfo;
const Value: string);
var
Temp: WideString;
begin
Temp := Value;
SetWideStrProp(Instance, PropInfo, Temp);
end;
function GetStrProp(Instance: TObject; PropInfo: PPropInfo): string;
begin // helper functions minimize temps in general case
case PropInfo^.PropType^.Kind of
tkString: GetShortStrPropAsLongStr(Instance, PropInfo, Result);
tkLString: GetLongStrProp(Instance, PropInfo, Result);
tkWString: GetWideStrPropAsLongStr(Instance, PropInfo, Result);
else
Result := '';
end;
end;
procedure SetStrProp(Instance: TObject; PropInfo: PPropInfo;
const Value: string);
begin // helper functions minimize temps in general case
case PropInfo^.PropType^.Kind of
tkString: SetShortStrPropAsLongStr(Instance, PropInfo, Value);
tkLString: SetLongStrProp(Instance, PropInfo, Value);
tkWString: SetWideStrPropAsLongStr(Instance, PropInfo, Value);
end;
end;
function GetWideStrProp(Instance: TObject; PropInfo: PPropInfo): WideString;
type
TWideStringGetProc = function :WideString of object;
TWideStringIndexedGetProc = function (Index: Integer): WideString of object;
var
P: PWideString;
M: TMethod;
Getter: Longint;
begin
case PropInfo^.PropType^.Kind of
tkString,
tkLString: Result := GetStrProp(Instance, PropInfo);
tkWString:
begin
Getter := Longint(PropInfo^.GetProc);
if (Getter and $FF000000) = $FF000000 then
begin // field - Getter is the field's offset in the instance data
P := Pointer(Integer(Instance) + (Getter and $00FFFFFF));
Result := P^; // auto ref count
end
else
begin
if (Getter and $FF000000) = $FE000000 then
// virtual method - Getter is a signed 2 byte integer VMT offset
M.Code := Pointer(PInteger(PInteger(Instance)^ + SmallInt(Getter))^)
else
// static method - Getter is the actual address
M.Code := Pointer(Getter);
M.Data := Instance;
if PropInfo^.Index = Integer($80000000) then // no index
Result := TWideStringGetProc(M)()
else
Result := TWideStringIndexedGetProc(M)(PropInfo^.Index);
end;
end;
else
Result := '';
end;
end;
procedure SetWideStrProp(Instance: TObject; PropInfo: PPropInfo;
const Value: WideString); overload;
type
TWideStringSetProc = procedure (const Value: WideString) of object;
TWideStringIndexedSetProc = procedure (Index: Integer;
const Value: WideString) of object;
var
P: PWideString;
M: TMethod;
Setter: Longint;
begin
case PropInfo^.PropType^.Kind of
tkString,
tkLString: SetStrProp(Instance, PropInfo, Value);
tkWString:
begin
Setter := Longint(PropInfo^.SetProc);
if (Setter and $FF000000) = $FF000000 then
begin // field - Setter is the field's offset in the instance data
P := Pointer(Integer(Instance) + (Setter and $00FFFFFF));
P^ := Value; // auto ref count
end
else
begin
if (Setter and $FF000000) = $FE000000 then
// virtual method - Setter is a signed 2 byte integer VMT offset
M.Code := Pointer(PInteger(PInteger(Instance)^ + SmallInt(Setter))^)
else
// static method - Setter is the actual address
M.Code := Pointer(Setter);
M.Data := Instance;
if PropInfo^.Index = Integer($80000000) then // no index
TWideStringSetProc(M)(Value)
else
TWideStringIndexedSetProc(M)(PropInfo^.Index, Value);
end;
end;
end;
end;
function GetFloatProp(Instance: TObject; PropInfo: PPropInfo): Extended;
type
TFloatGetProc = function :Extended of object;
TFloatIndexedGetProc = function (Index: Integer): Extended of object;
var
P: Pointer;
M: TMethod;
Getter: Longint;
begin
Getter := Longint(PropInfo^.GetProc);
if (Getter and $FF000000) = $FF000000 then
begin // field - Getter is the field's offset in the instance data
P := Pointer(Integer(Instance) + (Getter and $00FFFFFF));
case GetTypeData(PropInfo^.PropType^).FloatType of
ftSingle: Result := PSingle(P)^;
ftDouble: Result := PDouble(P)^;
ftExtended: Result := PExtended(P)^;
ftComp: Result := PComp(P)^;
ftCurr: Result := PCurrency(P)^;
else
Result := 0;
end;
end
else
begin
if (Getter and $FF000000) = $FE000000 then
// virtual method - Getter is a signed 2 byte integer VMT offset
M.Code := Pointer(PInteger(PInteger(Instance)^ + SmallInt(Getter))^)
else
// static method - Getter is the actual address
M.Code := Pointer(Getter);
M.Data := Instance;
if PropInfo^.Index = Integer($80000000) then // no index
Result := TFloatGetProc(M)()
else
Result := TFloatIndexedGetProc(M)(PropInfo^.Index);
if GetTypeData(PropInfo^.PropType^).FloatType = ftCurr then
Result := Result / 10000;
end;
end;
procedure SetFloatProp(Instance: TObject; PropInfo: PPropInfo;
const Value: Extended);
type
TSingleSetProc = procedure (const Value: Single) of object;
TDoubleSetProc = procedure (const Value: Double) of object;
TExtendedSetProc = procedure (const Value: Extended) of object;
TCompSetProc = procedure (const Value: Comp) of object;
TCurrencySetProc = procedure (const Value: Currency) of object;
TSingleIndexedSetProc = procedure (Index: Integer;
const Value: Single) of object;
TDoubleIndexedSetProc = procedure (Index: Integer;
const Value: Double) of object;
TExtendedIndexedSetProc = procedure (Index: Integer;
const Value: Extended) of object;
TCompIndexedSetProc = procedure (Index: Integer;
const Value: Comp) of object;
TCurrencyIndexedSetProc = procedure (Index: Integer;
const Value: Currency) of object;
var
P: Pointer;
M: TMethod;
Setter: Longint;
FloatType: TFloatType;
begin
Setter := Longint(PropInfo^.SetProc);
FloatType := GetTypeData(PropInfo^.PropType^).FloatType;
if (Setter and $FF000000) = $FF000000 then
begin // field - Setter is the field's offset in the instance data
P := Pointer(Integer(Instance) + (Setter and $00FFFFFF));
case FloatType of
ftSingle: PSingle(P)^ := Value;
ftDouble: PDouble(P)^ := Value;
ftExtended: PExtended(P)^ := Value;
ftComp: PComp(P)^ := Value;
ftCurr: PCurrency(P)^ := Value;
end;
end
else
begin
if (Setter and $FF000000) = $FE000000 then
// virtual method - Setter is a signed 2 byte integer VMT offset
M.Code := Pointer(PInteger(PInteger(Instance)^ + SmallInt(Setter))^)
else
// static method - Setter is the actual address
M.Code := Pointer(Setter);
M.Data := Instance;
if PropInfo^.Index = Integer($80000000) then // no index
begin
case FloatType of
ftSingle : TSingleSetProc(M)(Value);
ftDouble : TDoubleSetProc(M)(Value);
ftExtended: TExtendedSetProc(M)(Value);
ftComp : TCompSetProc(M)(Value);
ftCurr : TCurrencySetProc(M)(Value);
end;
end
else // indexed
begin
case FloatType of
ftSingle : TSingleIndexedSetProc(M)(PropInfo^.Index, Value);
ftDouble : TDoubleIndexedSetProc(M)(PropInfo^.Index, Value);
ftExtended: TExtendedIndexedSetProc(M)(PropInfo^.Index, Value);
ftComp : TCompIndexedSetProc(M)(PropInfo^.Index, Value);
ftCurr : TCurrencyIndexedSetProc(M)(PropInfo^.Index, Value);
end;
end
end;
end;
procedure AssignVariant(var Dest: Variant; const Source: Variant);
begin
Dest := Source;
end;
function GetVariantProp(Instance: TObject; PropInfo: PPropInfo): Variant;
asm
{ -> EAX Pointer to instance }
{ EDX Pointer to property info }
{ ECX Pointer to result variant }
PUSH ESI
PUSH EDI
MOV EDI,EDX
MOV EDX,[EDI].TPropInfo.Index { pass index in EDX }
CMP EDX,$80000000
JNE @@hasIndex
MOV EDX,ECX { pass value in EDX }
@@hasIndex:
MOV ESI,[EDI].TPropInfo.GetProc
CMP [EDI].TPropInfo.GetProc.Byte[3],$FE
JA @@isField
JB @@isStaticMethod
@@isVirtualMethod:
MOVSX ESI,SI { sign extend slot offset }
ADD ESI,[EAX] { vmt + slot offset }
CALL DWORD PTR [ESI]
JMP @@exit
@@isStaticMethod:
CALL ESI
JMP @@exit
@@isField:
AND ESI,$00FFFFFF
LEA EDX,[EAX+ESI]
MOV EAX,ECX
CALL AssignVariant
@@exit:
POP EDI
POP ESI
end;
procedure SetVariantProp(Instance: TObject; PropInfo: PPropInfo;
const Value: Variant);
asm
{ -> EAX Pointer to instance }
{ EDX Pointer to property info }
{ ECX Pointer to variant value }
PUSH ESI
PUSH EDI
MOV ESI,EDX
MOV EDX,[ESI].TPropInfo.Index { pass index in EDX }
CMP EDX,$80000000
JNE @@hasIndex
MOV EDX,ECX { pass value in EDX }
@@hasIndex:
MOV EDI,[ESI].TPropInfo.SetProc
CMP [ESI].TPropInfo.SetProc.Byte[3],$FE
JA @@isField
JB @@isStaticMethod
@@isVirtualMethod:
MOVSX EDI,DI
ADD EDI,[EAX]
CALL DWORD PTR [EDI]
JMP @@exit
@@isStaticMethod:
CALL EDI
JMP @@exit
@@isField:
AND EDI,$00FFFFFF
ADD EAX,EDI
MOV EDX,ECX
CALL AssignVariant
@@exit:
POP EDI
POP ESI
end;
function GetMethodProp(Instance: TObject; PropInfo: PPropInfo): TMethod;
assembler;
asm
{ -> EAX Pointer to instance }
{ EDX Pointer to property info }
{ ECX Pointer to result }
PUSH EBX
PUSH ESI
MOV ESI,EDX
MOV EDX,[ESI].TPropInfo.Index { pass Index in DX }
CMP EDX,$80000000
JNE @@hasIndex
MOV EDX,ECX { pass value in EDX }
@@hasIndex:
MOV EBX,[ESI].TPropInfo.GetProc
CMP [ESI].TPropInfo.GetProc.Byte[3],$FE
JA @@isField
JB @@isStaticMethod
{ GetProc is a virtual method }
MOVSX EBX,BX { sign extend slot number }
ADD EBX,[EAX]
CALL dword ptr [EBX]
JMP @@exit
@@isStaticMethod:
CALL EBX
JMP @@exit
@@isField:
AND EBX,$00FFFFFF
ADD EAX,EBX
MOV EDX,[EAX]
MOV EBX,[EAX+4]
MOV [ECX],EDX
MOV [ECX+4],EBX
@@exit:
POP ESI
POP EBX
end;
procedure SetMethodProp(Instance: TObject; PropInfo: PPropInfo;
const Value: TMethod); assembler;
asm
{ -> EAX Pointer to instance }
{ EDX Pointer to property info }
{ ECX Pointer to value }
PUSH EBX
MOV EBX,[EDX].TPropInfo.SetProc
CMP [EDX].TPropInfo.SetProc.Byte[3],$FE
JA @@isField
MOV EDX,[EDX].TPropInfo.Index
PUSH dword ptr [ECX+4]
PUSH dword ptr [ECX]
JB @@isStaticMethod
{ SetProc is a virtual method }
MOVSX EBX,BX
ADD EBX,[EAX]
CALL dword ptr [EBX]
JMP @@exit
@@isStaticMethod:
CALL EBX
JMP @@exit
@@isField:
AND EBX,$00FFFFFF
ADD EAX,EBX
MOV EDX,[ECX]
MOV EBX,[ECX+4]
MOV [EAX],EDX
MOV [EAX+4],EBX
@@exit:
POP EBX
end;
function GetInt64Prop(Instance: TObject; PropInfo: PPropInfo): Int64;
assembler;
asm
{ -> EAX Pointer to instance }
{ EDX Pointer to property info }
{ <- EDX:EAX result }
CMP [EDX].TPropInfo.GetProc.Byte[3],$FE
MOV ECX,[EDX].TPropInfo.GetProc
MOV EDX,[EDX].TPropInfo.Index { pass Index in EDX }
JA @@isField
JB @@isStaticMethod
{ GetProc is a virtual method }
MOVSX ECX,CX { sign extend slot number }
ADD ECX,[EAX]
CALL dword ptr [ECX]
JMP @@exit
@@isStaticMethod:
CALL ECX
JMP @@exit
@@isField:
AND ECX,$00FFFFFF
ADD EAX,ECX
MOV EDX,[EAX].Integer[4]
MOV EAX,[EAX].Integer[0]
@@exit:
end;
procedure SetInt64Prop(Instance: TObject; PropInfo: PPropInfo;
const Value: Int64); assembler;
asm
{ -> EAX Pointer to instance }
{ EDX Pointer to property info }
{ [ESP+4] Value }
CMP [EDX].TPropInfo.SetProc.Byte[3],$FE
MOV ECX,[EDX].TPropInfo.SetProc
JA @@isField
MOV EDX,[EDX].TPropInfo.Index
PUSH Value.Integer[4]
PUSH Value.Integer[0]
JB @@isStaticMethod
{ SetProc is a virtual method }
MOVSX ECX,CX
ADD ECX,[EAX]
CALL dword ptr [ECX]
JMP @@exit
@@isStaticMethod:
CALL ECX
JMP @@exit
@@isField:
AND ECX,$00FFFFFF
ADD EAX,ECX
MOV EDX,Value.Integer[0]
MOV ECX,Value.Integer[4]
MOV [EAX].Integer[0],EDX
MOV [EAX].Integer[4],ECX
@@exit:
end;
function GetInterfaceProp(Instance: TObject; const PropName: string): IInterface;
begin
Result := GetInterfaceProp(Instance, FindPropInfo(Instance, PropName));
end;
procedure SetInterfaceProp(Instance: TObject; const PropName: string;
const Value: IInterface);
begin
SetInterfaceProp(Instance, FindPropInfo(Instance, PropName), Value);
end;
function GetInterfaceProp(Instance: TObject; PropInfo: PPropInfo): IInterface;
type
TInterfaceGetProc = function :IInterface of object;
TInterfaceIndexedGetProc = function (Index: Integer): IInterface of object;
var
P: ^IInterface;
M: TMethod;
Getter: Longint;
begin
Getter := Longint(PropInfo^.GetProc);
if (Getter and $FF000000) = $FF000000 then
begin // field - Getter is the field's offset in the instance data
P := Pointer(Integer(Instance) + (Getter and $00FFFFFF));
Result := P^; // auto ref count
end
else
begin
if (Getter and $FF000000) = $FE000000 then
// virtual method - Getter is a signed 2 byte integer VMT offset
M.Code := Pointer(PInteger(PInteger(Instance)^ + SmallInt(Getter))^)
else
// static method - Getter is the actual address
M.Code := Pointer(Getter);
M.Data := Instance;
if PropInfo^.Index = Integer($80000000) then // no index
Result := TInterfaceGetProc(M)()
else
Result := TInterfaceIndexedGetProc(M)(PropInfo^.Index);
end;
end;
procedure SetInterfaceProp(Instance: TObject; PropInfo: PPropInfo;
const Value: IInterface);
type
TInterfaceSetProc = procedure (const Value: IInterface) of object;
TInterfaceIndexedSetProc = procedure (Index: Integer;
const Value: IInterface) of object;
var
P: ^IInterface;
M: TMethod;
Setter: Longint;
begin
Setter := Longint(PropInfo^.SetProc);
if (Setter and $FF000000) = $FF000000 then
begin // field - Setter is the field's offset in the instance data
P := Pointer(Integer(Instance) + (Setter and $00FFFFFF));
P^ := Value; // auto ref count
end
else
begin
if (Setter and $FF000000) = $FE000000 then
// virtual method - Setter is a signed 2 byte integer VMT offset
M.Code := Pointer(PInteger(PInteger(Instance)^ + SmallInt(Setter))^)
else
// static method - Setter is the actual address
M.Code := Pointer(Setter);
M.Data := Instance;
if PropInfo^.Index = Integer($80000000) then // no index
TInterfaceSetProc(M)(Value)
else
TInterfaceIndexedSetProc(M)(PropInfo^.Index, Value);
end;
end;
end.
|
unit Providers.Consts;
interface
const
C_BPL_FOLDER = '.bpl';
C_BIN_FOLDER = '.bin';
C_MODULES_FOLDER = 'modules\';
C_BOSS_CACHE_FOLDER = '.boss';
C_DATA_FILE = 'boss.ide';
C_BOSS_TAG = '[Boss]';
implementation
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{ CAUTION!! This unit is for internal purposes only, can change in a future. }
unit System.Internal.DebugUtils;
interface
uses
System.Generics.Collections;
type
TDebugUtils = class
private const
{$IF defined(MACOS) or defined(LINUX) or defined(ANDROID)}
EnvSeparator: string = ':';
{$ENDIF}
{$IFDEF MSWINDOWS}
EnvSeparator: string = ';';
{$ENDIF MSWINDOWS}
private class var
EnabledConditionMap: TDictionary<string, Boolean>;
UnenabledConditionMap: TDictionary<string, Boolean>;
DEBUG_CLASS: TArray<string>;
private
class procedure ParseEnv(Env: string);
class function SubMatch(Cond: string; Category: string): Boolean;
class function Match(Cond: string): Boolean;
class function CheckDebugClass(Cond: string): Boolean;
public
class constructor Create;
class destructor Destroy;
//type
// DebugCode = class(TCustomAttribute)
// end;
//[DebugCode]
///
/// Conditionally outputs a formatted string to the debugging output. The condition
/// is controlled by the environment variable <code>DEBUG_CLASS</code>.
class procedure DebugPrint(Cond: string; Fmt: string; const Args: array of const); overload;
//[DebugCode]
class procedure DebugPrint(Cond: string; Fmt: string); overload;
end;
implementation
uses
System.SysUtils, System.StrUtils;
class constructor TDebugUtils.Create;
begin
EnabledConditionMap := TDictionary<string, Boolean>.Create;
UnenabledConditionMap := TDictionary<string, Boolean>.Create;
ParseEnv(GetEnvironmentVariable('DEBUG_CLASS'));
end;
class destructor TDebugUtils.Destroy;
begin
EnabledConditionMap.Free;
UnenabledConditionMap.Free;
end;
class procedure TDebugUtils.ParseEnv(Env: string);
begin
SetLength(DEBUG_CLASS, 2);
DEBUG_CLASS := TArray<string>(SplitString(Env, EnvSeparator));
// DEBUG_CLASS := TArray<string>.Create;
end;
///
/// Compares a category to a condition. If the strings are identical, we
/// return True. If the strings are not, we look for wildcards in the category.
/// If we find one, we match the strings up to that point. If they match,
/// we're done, and we return True. Otherwise we return False.
///
/// Examples:
/// Cond = a.b.c Category = a.b.c.d -> False
/// Cond = a.b.c Category = a.b.c -> True
/// Cond = a.b.c Category = a.b.* -> True
/// Cond = a.b.c Category = a.* -> True
/// Cond = a.blueberry.c Category = a.blue* -> True
/// Cond = a.blueberry.c Category = a.blueberry -> False
class function TDebugUtils.SubMatch(Cond: string; Category: string): Boolean;
var
P: Integer;
I: Integer;
begin
Result := False;
if Cond = Category then
Exit(True);
P := Pos('*', Category);
// a.b.c vs x.y.nn*
if P > 0 then
begin
if P > Length(Cond) - 1 then
Exit(False);
for I:= 1 to P - 1 do
if Cond[I] <> Category[I] then
Exit(False);
Exit(True);
end;
end;
class function TDebugUtils.Match(Cond: string): Boolean;
var
S: string;
begin
Result := False;
for S in DEBUG_CLASS do
if SubMatch(Cond, S) then
Exit(True);
end;
class function TDebugUtils.CheckDebugClass(Cond: string): Boolean;
begin
if (EnabledConditionMap.ContainsKey(Cond)) then
Exit(True);
if (UnenabledConditionMap.ContainsKey(Cond)) then
Exit(False);
// Exit(False);
if Match(Cond) then
begin
Result := True;
EnabledConditionMap.Add(Cond, True);
end
else
begin
Result := False;
UnenabledConditionMap.Add(Cond, True);
end;
end;
class procedure TDebugUtils.DebugPrint(Cond: string; Fmt: string; const Args: array of const);
begin
if not TDebugUtils.CheckDebugClass(Cond) then Exit;
Write(Cond + ': ');
Writeln(Format(Fmt, Args));
end;
class procedure TDebugUtils.DebugPrint(Cond: string; Fmt: string);
begin
if not TDebugUtils.CheckDebugClass(Cond) then Exit;
Writeln(Cond + ': ' + Fmt);
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit frmMain;
interface
uses
Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Menus,
Controls, Dialogs, SysUtils,
OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
DC : HDC;
hrc : HGLRC;
Angle : GLfloat;
uTimerId : uint;
// массив свойств материала
MaterialColor: Array[0..3] of GLfloat;
procedure Init;
procedure SetDCPixelFormat;
end;
const
GLF_START_LIST = 1000;
var
frmGL: TfrmGL;
implementation
uses mmSystem;
{$R *.DFM}
const
stripeImageWidth = 32;
var
stripeImage : Array [0..3*stripeImageWidth-1] of GLubyte;
procedure makeStripeImage;
var
j : GLint;
begin
For j := 0 to stripeImageWidth - 1 do begin
If j <= 4
then stripeImage[3*j] := 255
else stripeImage[3*j] := 0;
If j > 4
then stripeImage[3*j + 1] := 255
else stripeImage[3*j + 1] := 0;
stripeImage[3*j+2] := 0;
end;
end;
{=======================================================================
Вывод текста}
procedure OutText (Litera : PChar);
begin
glListBase(GLF_START_LIST);
glCallLists(Length (Litera), GL_UNSIGNED_BYTE, Litera);
end;
{=======================================================================
Процедура инициализации источника цвета}
procedure TfrmGL.Init;
const
sgenparams : Array [0..3] of GLfloat = (1.0, 1.0, 1.0, 0.0);
begin
glEnable(GL_DEPTH_TEST);// разрешаем тест глубины
glEnable(GL_LIGHTING); // разрешаем работу с освещенностью
glEnable(GL_LIGHT0); // включаем источник света 0
makeStripeImage();
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage1D(GL_TEXTURE_1D, 0, 3, stripeImageWidth, 0,
GL_RGB, GL_UNSIGNED_BYTE, @stripeImage);
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
glTexGenfv(GL_S, GL_OBJECT_PLANE, @sgenparams);
glEnable(GL_TEXTURE_GEN_S);
glEnable(GL_TEXTURE_1D);
end;
{=======================================================================
Перерисовка окна}
procedure TfrmGL.FormPaint(Sender: TObject);
begin
// очистка буфера цвета и буфера глубины
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glPushMatrix;
glRotatef(Angle, 0.0, 1.0, 0.0); // поворот на угол
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, @MaterialColor);
// вывод текста
OutText ('Проба');
glPopMatrix;
SwapBuffers(DC);
end;
{=======================================================================
Обработка таймера}
procedure FNTimeCallBack(uTimerID, uMessage: UINT;dwUser, dw1, dw2: DWORD) stdcall;
begin
With frmGL do begin
Angle := Angle + 0.2;
If (Angle >= 720.0) then Angle := 0.0;
MaterialColor [0] := (720.0 - Angle) / 720.0;
MaterialColor [1] := Angle / 720.0;
MaterialColor [2] := Angle / 720.0;
InvalidateRect(Handle, nil, False);
end;
end;
{=======================================================================
Создание окна}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
Angle := 0;
DC := GetDC(Handle);
SetDCPixelFormat;
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
wglUseFontOutlines(Canvas.Handle, 0, 255, GLF_START_LIST, 0.0, 0.15,
WGL_FONT_POLYGONS, nil);
Init;
uTimerID := timeSetEvent (1, 0, @FNTimeCallBack, 0, TIME_PERIODIC);
end;
{=======================================================================
Изменение размеров окна}
procedure TfrmGL.FormResize(Sender: TObject);
begin
glViewport(0, 0, ClientWidth, ClientHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
gluPerspective(40.0, ClientWidth / ClientHeight, 1.0, 20.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glTranslatef(0.0, 0.0, -8.0);
glRotatef(30.0, 1.0, 0.0, 0.0);
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Конец работы приложения}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
timeKillEvent(uTimerID);
glDeleteLists (GLF_START_LIST, 256);
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC(Handle, DC);
DeleteDC (DC);
end;
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close
end;
{=======================================================================
Установка формата пикселей}
procedure TfrmGL.SetDCPixelFormat;
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
with pfd do begin
nSize := sizeof(pfd);
nVersion := 1;
dwFlags := PFD_DRAW_TO_WINDOW or
PFD_SUPPORT_OPENGL or
PFD_DOUBLEBUFFER;
iPixelType:= PFD_TYPE_RGBA;
cColorBits:= 24;
cDepthBits:= 32;
iLayerType:= PFD_MAIN_PLANE;
end;
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
end;
end.
|
unit Map;
{$MODE Delphi}
INTERFACE
USES LCLIntf, LCLType, LMessages, sysutils, graphics, types;
CONST TILE_SIZE = 24;
VAR gfx : TBitmap;
TYPE TTile = BYTE;
TYPE TMap = CLASS
PUBLIC
CONSTRUCTOR create(_w, _h : INTEGER); OVERLOAD;
CLASS PROCEDURE loadGfx();
FUNCTION getTile(x, y : INTEGER) : TTILE;
FUNCTION getPixel(x, y : INTEGER) : TTILE;
PROCEDURE setTile(x, y : INTEGER; t : TTILE);
FUNCTION getWidth() : INTEGER;
FUNCTION getHeight() : INTEGER;
PROCEDURE draw(canvas : TCanvas);
PRIVATE
data : ARRAY OF TTILE;
w, h : INTEGER;
END;
IMPLEMENTATION
CONSTRUCTOR TMap.create(_w, _h : INTEGER);
BEGIN
w := _w;
h := _h;
SETLENGTH(data, w*h);
END;
CLASS PROCEDURE TMap.loadGfx();
VAR i : INTEGER;
BEGIN
gfx := TBitmap.Create();
gfx.loadFromFile('gfx/tileset.bmp');
END;
FUNCTION TMap.getTile(x, y : INTEGER) : TTILE;
BEGIN
IF (y < 0) OR (y > h-1) OR (x < 0) OR (x > w-1) THEN
getTile := 0
ELSE
getTile := data[y*w+x];
END;
FUNCTION TMap.getPixel(x, y : INTEGER) : TTILE;
BEGIN
getPixel := getTile(x DIV TILE_SIZE, y DIV TILE_SIZE);
END;
PROCEDURE TMap.setTile(x, y : INTEGER; t : TTILE);
BEGIN
data[y*w+x] := t;
END;
FUNCTION TMap.getWidth() : INTEGER;
BEGIN
getWidth := w;
END;
FUNCTION TMap.getHeight() : INTEGER;
BEGIN
getHeight := h;
END;
PROCEDURE TMap.draw(canvas : TCanvas);
VAR x, y, tile : INTEGER;
VAR dest, src : TRECT;
BEGIN
FOR x := 0 TO getWidth()-1 DO
BEGIN
FOR y := 0 TO getHeight()-1 DO
BEGIN
tile := 6;
IF getTile(x,y) > 0 THEN
BEGIN
IF (getTile(x-1, y)<>0) AND (getTile(x+1, y)=0) THEN tile := 7;
IF (getTile(x+1, y)<>0) AND (getTile(x-1, y)=0) THEN tile := 8;
IF (getTile(x, y+1)<>0) AND (getTile(x, y-1)=0)THEN tile := 10;
IF (getTile(x, y-1)<>0) AND (getTile(x, y+1)=0)THEN tile := 9;
IF (getTile(x, y+1)<>0) AND (getTile(x, y-1)<>0) AND ((getTile(x+1,y)=0) OR (getTile(x-1,y)=0)) THEN tile := 1;
IF (getTile(x+1, y)<>0) AND (getTile(x-1, y)<>0) AND ((getTile(x,y+1)=0) OR (getTile(x,y-1)=0)) THEN tile := 0;
IF (getTile(x+1, y)<>0) AND (getTile(x, y+1)<>0) AND ((getTile(x+1, y+1)=0) OR (getTile(x-1, y)=0) AND (getTile(x, y-1)=0)) THEN tile := 5;
IF (getTile(x+1, y)<>0) AND (getTile(x, y-1)<>0) AND ((getTile(x+1, y-1)=0) OR (getTile(x-1, y)=0) AND (getTile(x, y+1)=0)) THEN tile := 4;
IF (getTile(x-1, y)<>0) AND (getTile(x, y+1)<>0) AND ((getTile(x-1, y+1)=0) OR (getTile(x+1, y)=0) AND (getTile(x, y-1)=0)) THEN tile := 2;
IF (getTile(x-1, y)<>0) AND (getTile(x, y-1)<>0) AND ((getTile(x-1, y-1)=0) OR (getTile(x+1, y)=0) AND (getTile(x, y+1)=0)) THEN tile := 3;
tile := tile + (getTile(x,y)-1)*12;
END
ELSE
tile := 11;
dest.left := x*TILE_SIZE;
dest.top := y * TILE_SIZE;
dest.right := dest.left + TILE_SIZE;
dest.bottom := dest.top + TILE_SIZE;
src.left := (tile MOD (gfx.width DIV TILE_SIZE)) * TILE_SIZE;
src.top := (tile DIV (gfx.width DIV TILE_SIZE)) * TILE_SIZE;
src.right := src.left + TILE_SIZE;
src.bottom := src.top + TILE_SIZE;
canvas.copyRect(dest, gfx.canvas, src);
END;
END;
END;
END.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit WebUsers;
interface
uses System.Classes, Web.HTTPApp, WebComp, SiteComp, System.SysUtils;
type
TWebUserItem = class;
TWebUserItem = class(TCollectionItem)
private
FUserName: string;
FPassword: string;
FAccessRights: string;
FAccessRightsStrings: TStrings;
function GetUserID: Variant;
function GetAccessRightsStrings: TStrings;
procedure SetAccessRights(const Value: string);
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
property UserID: Variant read GetUserID;
function CheckRights(const ARights: string): Boolean;
property AccessRightsStrings: TStrings read GetAccessRightsStrings;
published
property UserName: string read FUserName write FUserName;
property Password: string read FPassword write FPassword;
property AccessRights: string read FAccessRights write SetAccessRights;
end;
TWebUserItems = class(TCollection)
private
FOwner: TComponent;
function GetUserItem(Index: Integer): TWebUserItem;
procedure SetUserItem(Index: Integer; const Value: TWebUserItem);
protected
function GetAttrCount: Integer; override;
function GetAttr(Index: Integer): string; override;
function GetItemAttr(Index, ItemIndex: Integer): string; override;
function GetOwner: TPersistent; override;
public
function FindUserName(AUserName: string): TWebUserItem;
function FindUserID(AUserID: Variant): TWebUserItem;
constructor Create(AOwner: TComponent; ItemClass: TCollectionItemClass);
property Items[Index: Integer]: TWebUserItem read GetUserItem
write SetUserItem; default;
end;
TValidateUserError = (vuBlankPassword, vuBlankUserName, vuUnknownUserName, vuUnknownPassword);
TCheckAccessRightsEvent = procedure(UserID: Variant; Rights: string; var HasRight: Boolean) of object;
TCheckAccessRightsHandledEvent = procedure(UserID: Variant; Rights: string; var HasRight: Boolean; var Handled: Boolean) of object;
TValidateUserEvent = procedure(Strings: TStrings; var UserID: Variant) of object;
TValidateUserHandledEvent = procedure(Strings: TStrings; var UserID: Variant; var Handled: Boolean) of object;
TValidateUserErrorEvent = procedure(Error: TValidateUserError; Strings: TStrings; var UserID: Variant; var Handled: Boolean) of object;
TCustomWebUserList = class(TComponent, IWebUserList)
private
FItems: TWebUserItems;
FLock: TMultiReadExclusiveWriteSynchronizer;
FOnAfterCheckAccessRights: TCheckAccessRightsEvent;
FOnBeforeCheckAccessRights: TCheckAccessRightsHandledEvent;
FOnUserIDNotFound: TCheckAccessRightsHandledEvent;
FOnAfterValidateUser: TValidateUserEvent;
FOnBeforeValidateUser: TValidateUserHandledEvent;
FOnValidateUserError: TValidateUserErrorEvent;
procedure SetItems(const Value: TWebUserItems);
function GetItem(I: Integer): TWebUserItem;
protected
{ IWebUserList }
function ValidateUser(Strings: TStrings): Variant;
function CheckAccessRights(AUserID: Variant; ARights: string): Boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure LoadFromFile(FileName: string);
procedure SaveToFile(FileName: string);
property UserItems: TWebUserItems read FItems write SetItems;
property Users[I: Integer]: TWebUserItem read GetItem;
property OnBeforeCheckAccessRights: TCheckAccessRightsHandledEvent read FOnBeforeCheckAccessRights write FOnBeforeCheckAccessRights;
property OnAfterCheckAccessRights: TCheckAccessRightsEvent read FOnAfterCheckAccessRights write FOnAfterCheckAccessRights;
property OnUserIDNotFound: TCheckAccessRightsHandledEvent read FOnUserIDNotFound write FOnUserIDNotFound;
property OnBeforeValidateUser: TValidateUserHandledEvent read FOnBeforeValidateUser write FOnBeforeValidateUser;
property OnAfterValidateUser: TValidateUserEvent read FOnAfterValidateUser write FOnAfterValidateUser;
property OnValidateUserError: TValidateUserErrorEvent read FOnValidateUserError write FOnValidateUserError;
end;
TWebUserList = class(TCustomWebUserList)
published
property UserItems;
property OnBeforeCheckAccessRights;
property OnAfterCheckAccessRights;
property OnUserIDNotFound;
property OnBeforeValidateUser;
property OnAfterValidateUser;
property OnValidateUserError;
end;
EWebUsersListException = class(EWebBrokerException)
end;
EUserIDNotFoundException = class(EWebUsersListException);
EValidateUserException = class(EWebUsersListException)
end;
implementation
uses
System.Variants, SiteConst, WebAdapt;
procedure TWebUserItem.Assign(Source: TPersistent);
begin
if Source is TWebUserItem then
begin
if Assigned(Collection) then Collection.BeginUpdate;
try
UserName := TWebUserItem(Source).UserName;
Password := TWebUserItem(Source).Password;
AccessRights := TWebUserItem(Source).AccessRights;
finally
if Assigned(Collection) then Collection.EndUpdate;
end;
end
else
inherited Assign(Source);
end;
{ TWebUserItems }
constructor TWebUserItems.Create(AOwner: TComponent; ItemClass: TCollectionItemClass);
begin
FOwner := AOwner;
inherited Create(ItemClass);
end;
function TWebUserItems.FindUserID(AUserID: Variant): TWebUserItem;
begin
{ UserID and UserName are the same }
Result := FindUserName(AUserID);
end;
function TWebUserItems.FindUserName(AUserName: string): TWebUserItem;
var
I: Integer;
begin
for I := 0 to Count - 1 do
begin
Result := Items[I] as TWebUserItem;
if Result.UserName = AUserName then
Exit;
end;
Result := nil;
end;
function RightsAsStrings(const S: string): TStrings;
begin
Result := TStringList.Create;
try
ExtractStrings([',', ';', ' '], [], PChar(S), Result);
except
Result.Free;
raise;
end;
end;
// Grant access if there are no required rights or
// a user has a right that matches one of the required rights.
function TWebUserItem.CheckRights(const ARights: string): Boolean;
var
S: TStrings;
I: Integer;
begin
Result := True;
S := RightsAsStrings(ARights);
try
if S.Count = 0 then Exit;
for I := 0 to S.Count - 1 do
if AccessRightsStrings.IndexOf(S[I]) >= 0 then
Exit;
Result := False;
finally
S.Free;
end;
end;
constructor TWebUserItem.Create(Collection: TCollection);
begin
inherited;
end;
destructor TWebUserItem.Destroy;
begin
inherited;
FAccessRightsStrings.Free;
end;
function TWebUserItems.GetAttrCount: Integer;
begin
Result := 3;
end;
function TWebUserItems.GetAttr(Index: Integer): string;
begin
case Index of
0: Result := sWebUserName;
1: Result := sWebUserPassword;
2: Result := sWebUserAccessRights;
else
Result := '';
end;
end;
function TWebUserItems.GetItemAttr(Index, ItemIndex: Integer): string;
begin
case Index of
0: Result := Items[ItemIndex].UserName;
1: Result := Items[ItemIndex].Password;
2: Result := Items[ItemIndex].AccessRights;
else
Result := '';
end;
end;
function TWebUserItems.GetOwner: TPersistent;
begin
Result := FOwner;
end;
function TWebUserItems.GetUserItem(Index: Integer): TWebUserItem;
begin
Result := TWebUserItem(inherited Items[Index]);
end;
procedure TWebUserItems.SetUserItem(Index: Integer;
const Value: TWebUserItem);
begin
Items[Index].Assign(Value);
end;
{ TCustomWebUserList }
function TCustomWebUserList.CheckAccessRights(AUserID: Variant;
ARights: string): Boolean;
var
Item: TWebUserItem;
Handled: Boolean;
begin
Handled := False;
if Assigned(OnBeforeCheckAccessRights) then
OnBeforeCheckAccessRights(AUserID, ARights, Result, Handled);
if not Handled then
begin
if ARights = '' then
Result := True
else if VarIsEmpty(AUserID) then
Result := False
else
begin
Item := FItems.FindUserID(AUserID);
if Item <> nil then
Result := Item.CheckRights(ARights)
else
begin
if Assigned(OnUserIDNotFound) then
OnUserIDNotFound(AUserID, ARights, Result, Handled);
if not Handled then
raise EUserIDNotFoundException.Create(sUserIDNotFound);
end;
end;
end;
if Assigned(OnAfterCheckAccessRights) then
OnAfterCheckAccessRights(AUserID, ARights, Result);
end;
constructor TCustomWebUserList.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FItems := TWebUserItems.Create(Self, TWebUserItem);
FLock := TMultiReadExclusiveWriteSynchronizer.Create;
end;
destructor TCustomWebUserList.Destroy;
begin
inherited;
FLock.Free;
FItems.Free;
end;
procedure TCustomWebUserList.LoadFromFile(FileName: string);
begin
FLock.BeginRead;
try
ReadComponentResFile(FileName, Self)
finally
FLock.EndRead;
end;
end;
procedure TCustomWebUserList.SaveToFile(FileName: string);
begin
FLock.BeginWrite;
try
WriteComponentResFile(FileName, Self);
finally
FLock.EndWrite;
end;
end;
function TCustomWebUserList.GetItem(I: Integer): TWebUserItem;
begin
Result := FItems[I];
end;
procedure TCustomWebUserList.SetItems(const Value: TWebUserItems);
begin
FItems.Assign(Value);
end;
function TCustomWebUserList.ValidateUser(Strings: TStrings): Variant;
var
Item: TWebUserItem;
Handled: Boolean;
begin
Handled := False;
if Assigned(OnBeforeValidateUser) then
OnBeforeValidateUser(Strings, Result, Handled);
if not Handled then
begin
if Strings.IndexOfName(sLoginUserName) >= 0 then
begin
Item := FItems.FindUserName(Strings.Values[sLoginUserName]);
if Item <> nil then
begin
Result := Item.UserID;
if Item.Password <> '' then
if Strings.IndexOfName(sLoginPassword) >= 0 then
if Strings.Values[sLoginPassword] = Item.Password then
else
begin
if Assigned(OnValidateUserError) then
OnValidateUserError(vuBlankPassword, Strings, Result, Handled);
if not Handled then
raise EValidateUserException.Create(sInvalidPassword);
end
else
begin
if Assigned(OnValidateUserError) then
OnValidateUserError(vuBlankPassword, Strings, Result, Handled);
if not Handled then
raise EValidateUserException.Create(sMissingPassword);
end;
end
else
begin
if Assigned(OnValidateUserError) then
OnValidateUserError(vuUnknownUserName, Strings, Result, Handled);
if not Handled then
raise EValidateUserException.Create(sUnknownUserName);
end
end
else
begin
if Assigned(OnValidateUserError) then
OnValidateUserError(vuBlankUserName, Strings, Result, Handled);
if not Handled then
raise EValidateUserException.Create(sMissingUserName);
end;
end;
if Assigned(OnAfterValidateUser) then
OnAfterValidateUser(Strings, Result);
end;
function TWebUserItem.GetAccessRightsStrings: TStrings;
begin
if FAccessRightsStrings = nil then
FAccessRightsStrings := RightsAsStrings(FAccessRights);
Result := FAccessRightsStrings;
end;
function TWebUserItem.GetUserID: Variant;
begin
Result := FUserName;
end;
procedure TWebUserItem.SetAccessRights(const Value: string);
begin
FreeAndNil(FAccessRightsStrings);
FAccessRights := Value;
end;
end.
|
unit Slivbd;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,mysqlite3conn, controls, sqldb, dialogs;
type
{ TslivBD }
TslivBD=class(TSQLite3Connection)
private
Fcurrpath, Fattachpath:string;
protected
public
constructor Create(pathdb, attachBD:string;frm:TCustomControl);
destructor Destroy;override;
procedure createbdinmemory;
procedure Sliyanie;
end;
implementation
{ TslivBD }
constructor TslivBD.Create(pathdb, attachBD: string; frm: TCustomControl);
{var
existsdb:boolean; }
begin
Fcurrpath:=pathdb;
Fattachpath:=attachBD;
// Подключение к БД
try
//Добавить проверку версии присоединяемой базы!!!
//Создадим объект подключения
inherited create(frm);
//настроим параметры подключения к базе
DatabaseName:=':memory:';//Fpath;//'rod.db3';
Params.Add('foreign_keys=ON');
Params.Add('journal_mode=DELETE');
Params.Add('synchronous=full');
Params.Add('auto_vacuum=full');
//Создадим пустую базу
Transaction:=TSQLTransaction.Create(frm);
Open;
//прицепим текущую базу
execsql('ATTACH "'+Fcurrpath+'" AS currBD');
//прицепим базу которую будем подгружать
if not fileexists(Fattachpath) then raise exception.Create('база для присоединения не найдена');
execsql('ATTACH "'+Fattachpath+'" AS attachBD');
except
on E: Exception do
begin
//result:=false;
raise Exception.Create('Ошибка подключения/содания базы '+pathdb);
end;
end;
//Создадим нужную таблицу в памяти
createbdinmemory;
end;
destructor TslivBD.Destroy;
begin
inherited Destroy;
end;
procedure TslivBD.createbdinmemory;
begin
//Создадим таблицу
// Создание таблицы SlivBD
ExecuteDirect( 'CREATE temp TABLE IF NOT EXISTS SlivBD '+lineending+
'([id] INTEGER primary key,'+lineending+
'[id_old] INTEGER NOT NULL,'+lineending+ //тут id который был
'[id_new] INTEGER NOT NULL'+lineending+ //тут id который стал в новой таблице
');');
Transaction.Commit;
end;
procedure TslivBD.Sliyanie;
var
SQL_query:string;
SQL_table:TSQLiteTable2;
begin
//Заполним таблицу SlivBD
//сначало добавим тех, кто уже есть в текущей базе
SQL_query:='insert into SlivBD select null, attachBD.people.id, currBD.people.id from currBD.people join attachBD.people on '+lineending+
'((currBD.people.fam = attachBD.people.fam)and(currBD.people.nam = attachBD.people.nam)and(currBD.people.otch = attachBD.people.otch)and(currBD.people.dtb = attachBD.people.dtb));';
ExecuteDirect(SQL_query);
//Теперь тех, кого нет в текущей базе
//Надо в цикле каждого отдельно!!!
//Выберем тех кого нету в основной базе
SQL_query:='select attachBD.people.id, attachBD.people.fam, attachBD.people.nam, attachBD.people.otch, attachBD.people.sex, attachBD.people.famfirst, '+lineending+
'attachBD.people.dtb, attachBD.people.dtd, attachBD.people.dopinfo from attachBD.people where ('+
'not exists ('+
'select * from currBD.people where '+
'((currBD.people.fam = attachBD.people.fam)and(currBD.people.nam = attachBD.people.nam)and(currBD.people.otch = attachBD.people.otch)and(currBD.people.dtb = attachBD.people.dtb))'+
'))';
SQL_table:=GetTable(SQL_query);
//Теперь переберем и добавим в основную базу, а потом в SlivBD
if SQL_table.Count>0 then
begin
SQL_table.First;
while not SQL_table.EOF do
begin
//обрабатываем
//Добавим в основную базу
ExecuteDirect('insert into currBD.people (fam, nam, otch, sex, dtb, dtd, famfirst, dopinfo) values('+
'"'+SQL_table.FieldAsString('fam')+'",'+
'"'+SQL_table.FieldAsString('nam')+'",'+
'"'+SQL_table.FieldAsString('otch')+'",'+
''+SQL_table.FieldAsString('sex')+','+
'"'+SQL_table.FieldAsString('dtb')+'",'+
'"'+SQL_table.FieldAsString('dtd')+'",'+
'"'+SQL_table.FieldAsString('famfirst')+'",'+
'"'+SQL_table.FieldAsString('dopinfo')+'"'+
');');
//Добавим в SlivBD
ExecuteDirect('insert into SlivBD (id_old, id_new) values('+SQL_table.FieldAsString('id')+','+inttostr(GetInsertID)+')');
SQL_table.Next;
end;
Transaction.Commit;
end;
//Теперь перенесем связи
SQL_query:='select id from SlivBD';
SQL_table:=GetTable(SQL_query);
if SQL_table.Count>0 then
begin
SQL_query:='insert into currBD.parent '+
'select null, SlBDppl.id_new, SlBDprnt.id_new from '+
'attachBD.parent join SlivBD as SlBDppl on (attachBD.parent.id_people = SlBDppl.id_old) join '+
'SlivBD as SlBDprnt on (attachBD.parent.id_parent = SlBDprnt.id_old) '+
'where '+
'not exists('+
'select * from currBD.parent as currP where ((currP.id_people = SlBDppl.id_new)and(currP.id_parent = SlBDprnt.id_new)) '+
')';
self.ExecuteDirect(SQL_query);
end;
Transaction.Commit;
end;
end.
|
unit uFormulario;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.AppEvnts, Vcl.StdCtrls,
JSDialog, JclDebug;
type
TFormCapturaExcecoes = class(TForm)
ApplicationEvents: TApplicationEvents;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Button5: TButton;
Bevel: TBevel;
Memo: TMemo;
mmoLog: TMemo;
btnteste: TButton;
JSDialog1: TJSDialog;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure ApplicationEventsException(Sender: TObject; E: Exception);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure AppException(Sender: TObject; E: Exception);
procedure divisao;
procedure btntesteClick(Sender: TObject);
end;
var
FormCapturaExcecoes: TFormCapturaExcecoes;
implementation
uses
System.Contnrs, uCapturaExcecoes, DBClient, uMensagem;
{$R *.dfm}
function VersaoExe: String;
type
PFFI = ^vs_FixedFileInfo;
var
F : PFFI;
Handle : Dword;
Len : Longint;
Data : Pchar;
Buffer : Pointer;
Tamanho : Dword;
Parquivo: Pchar;
Arquivo,Versao : String;
release : String;
Parte : TStringList;
begin
Arquivo := Application.ExeName;
Parquivo := StrAlloc(Length(Arquivo) + 1);
StrPcopy(Parquivo, Arquivo);
Len := GetFileVersionInfoSize(Parquivo, Handle);
Result := '';
if Len > 0 then begin
Data:=StrAlloc(Len+1);
if GetFileVersionInfo(Parquivo,Handle,Len,Data) then begin
VerQueryValue(Data, '\',Buffer,Tamanho);
F := PFFI(Buffer);
Versao := Format('%d.%d.%d.%d',
[HiWord(F^.dwFileVersionMs),
LoWord(F^.dwFileVersionMs),
HiWord(F^.dwFileVersionLs),
Loword(F^.dwFileVersionLs)]
);
release := Versao;
Parte := TStringList.Create;
try
Parte.Clear;
ExtractStrings(['.'],[], PChar(release), Parte);
release := IntToStr(StrToInt64(Parte[0])+StrToInt64(Parte[1])+StrToInt64(Parte[2])+StrToInt64(Parte[3]));
finally
Parte.Free;
end;
result := Versao;
end;
StrDispose(Data);
end;
StrDispose(Parquivo);
end;
procedure TFormCapturaExcecoes.AppException(Sender: TObject; E: Exception);
var
DataHora: string;
CapturaExcecoes: TCapturaExcecoes;
Strings: TStringList;
begin
mmoLog.Lines.Clear;
Strings := TStringList.Create;
CapturaExcecoes := TCapturaExcecoes.Create;
DataHora := FormatDateTime('dd-mm-yyyy_hh-nn-ss', Now);
mmoLog.Lines.Add('Exceção Programada.: Victor Hugo Gonzales');
mmoLog.Lines.Add('Data/Hora.......: ' + DateTimeToStr(Now));
mmoLog.Lines.Add('Mensagem........: ' + E.Message);
mmoLog.Lines.Add('Classe Exceção..: ' + E.ClassName);
mmoLog.Lines.Add('Formulário......: ' + Screen.ActiveForm.Name);
mmoLog.Lines.Add('Unit............: ' + Sender.UnitName);
mmoLog.Lines.Add('Controle Visual.: ' + Screen.ActiveControl.Name);
mmoLog.Lines.Add('Usuario.........: ' + CapturaExcecoes.GetUsuario);
mmoLog.Lines.Add('Versão Windows..: ' + CapturaExcecoes.GetVersaoWindows);
//mmoLog.Lines.Add(e.GetStackInfoStringProc(e.StackInfo));
JSDialog1.Content.Clear;
JSDialog1.Content.Add(e.Message);
if(JSDialog1.Execute = mrYesToAll) then begin
JclLastExceptStackListToStrings( Strings , True, False, True, False);
fMensagem.Memo1.Lines.Clear;
fMensagem.Memo1.Lines.Add('Exceção Programada...: Erro desconhecido');
fMensagem.Memo1.Lines.Add('Analista Responsável.: Victor Hugo Gonzales');
fMensagem.Memo1.Lines.Add('Data/Hora............: ' + DateTimeToStr(Now));
fMensagem.Memo1.Lines.Add('Mensagem.............: ' + E.Message);
fMensagem.Memo1.Lines.Add('Classe Exceção.......: ' + E.ClassName);
fMensagem.Memo1.Lines.Add('Formulário...........: ' + Screen.ActiveForm.Name);
fMensagem.Memo1.Lines.Add('Unit.................: ' + Sender.UnitName);
fMensagem.Memo1.Lines.Add('Controle Visual......: ' + Screen.ActiveControl.Name);
fMensagem.Memo1.Lines.Add('Usuario..............: ' + CapturaExcecoes.GetUsuario);
fMensagem.Memo1.Lines.Add('Versão Windows.......: ' + CapturaExcecoes.GetVersaoWindows);
fMensagem.Memo1.Lines.Add('Versão Aplicação.....: ' + versaoExe);
fMensagem.Memo1.Lines.Add('');
fMensagem.Memo1.Lines.Add('Informação do Stack :');
fMensagem.Memo1.Lines.Add('');
fMensagem.Memo1.Lines.AddStrings(Strings);
fMensagem.showModal;
end;
mmoLog.Lines.Add(e.StackTrace);
mmoLog.Lines.Add(StringOfChar('-', 70));
end;
procedure TFormCapturaExcecoes.ApplicationEventsException(Sender: TObject; E: Exception);
var
CapturaExcecoes: TCapturaExcecoes;
begin
// Cria a classe de captura de exceções
CapturaExcecoes := TCapturaExcecoes.Create;
try
// Invoca o método de captura, informando os parâmetros
CapturaExcecoes.CapturarExcecao(Sender, E);
// Carrega novamente o arquivo de log no Memo
Memo.Lines.LoadFromFile(GetCurrentDir + '\LogExcecoes.txt');
// Navega para o final do Memo para mostrar a exceção mais recente
SendMessage(Memo.Handle, EM_LINESCROLL, 0,Memo.Lines.Count);
finally
CapturaExcecoes.Free;
end;
end;
procedure TFormCapturaExcecoes.btntesteClick(Sender: TObject);
begin
divisao;
end;
procedure TFormCapturaExcecoes.Button1Click(Sender: TObject);
begin
// EConvertError
StrToInt('A');
end;
procedure TFormCapturaExcecoes.Button2Click(Sender: TObject);
var
N1: integer;
N2: integer;
Resultado: integer;
begin
// EDivByZero
N1 := 10;
N2 := 0;
Resultado := N1 div N2;
ShowMessage(IntToStr(Resultado));
end;
procedure TFormCapturaExcecoes.Button3Click(Sender: TObject);
var
Lista: TObjectList;
Objeto: TObject;
begin
// EListError
Lista := TObjectList.Create;
try
Objeto := Lista.Items[1];
ShowMessage(Objeto.ClassName);
finally
Lista.Free;
end;
end;
procedure TFormCapturaExcecoes.Button4Click(Sender: TObject);
begin
// EFOpenError
Memo.Lines.LoadFromFile('C:\ArquivoInexistente.txt');
end;
procedure TFormCapturaExcecoes.Button5Click(Sender: TObject);
var
ClientDataSet: TClientDataSet;
begin
// EDatabaseError
ClientDataSet := TClientDataSet.Create(nil);
try
ShowMessage(ClientDataSet.FieldByName('Campo').AsString);
finally
ClientDataSet.Free;
end;
end;
procedure TFormCapturaExcecoes.divisao;
var
divisor : Integer;
conta : real;
begin
divisor:=0;
conta := 100/divisor;
ShowMessage('testetetet a'+FloatToStr(conta));
end;
procedure TFormCapturaExcecoes.FormCreate(Sender: TObject);
begin
mmoLog.Lines.Clear;
Application.OnException := AppException;
JclStartExceptionTracking;
end;
procedure TFormCapturaExcecoes.FormShow(Sender: TObject);
begin
// Carrega novamente o arquivo de log no Memo
Memo.Lines.LoadFromFile(GetCurrentDir + '\LogExcecoes.txt');
end;
end.
|
{ *********************************************************************
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Autor: Brovin Y.D.
* E-mail: y.brovin@gmail.com
*
******************************************************************** }
unit FGX.FlipView;
interface
uses
System.Classes, System.UITypes, FMX.Graphics, FMX.Types, FMX.Controls.Presentation, FMX.Controls.Model,
FGX.Images.Types, FGX.FlipView.Types, FGX.Types, FGX.Consts;
type
{ TfgFlipView }
TfgFlipViewMessages = class
public const
{ Model messages }
MM_ITEM_INDEX_CHANGED = MM_USER + 1;
MM_EFFECT_OPTIONS_CHANGED = MM_USER + 2;
MM_SLIDE_OPTIONS_CHANGED = MM_USER + 3;
MM_SLIDESHOW_OPTIONS_CHANGED = MM_USER + 4;
MM_SHOW_NAVIGATION_BUTTONS_CHANGED = MM_USER + 5;
MM_FLIPVIEW_USER = MM_USER + 6;
{ Control messages }
PM_GO_TO_IMAGE = PM_USER + 1;
PM_FLIPVIEW_USER = PM_USER + 2;
end;
/// <summary>Information showing new image action. Is used for sending message from <b>TfgCustomFlipView</b>
/// to presentation in <c>TfgCustomFlipView.GoToImage</c></summary>
TfgShowImageInfo = record
NewItemIndex: Integer;
Animate: Boolean;
Direction: TfgDirection;
end;
TfgCustomFlipView = class;
TfgImageClickEvent = procedure (Sender: TObject; const AFlipView: TfgCustomFlipView; const AImageIndex: Integer) of object;
TfgFlipViewModel = class(TDataModel)
public const
DefaultShowNavigationButtons = True;
private
FFlipViewEvents: IfgFlipViewNotifications;
FImages: TfgImageCollection;
FItemIndex: Integer;
FSlideShowOptions: TfgFlipViewSlideShowOptions;
FSlidingOptions: TfgFlipViewSlideOptions;
FEffectOptions: TfgFlipViewEffectOptions;
FIsSliding: Boolean;
FShowNavigationButtons: Boolean;
FOnStartChanging: TfgChangingImageEvent;
FOnFinishChanging: TNotifyEvent;
FOnImageClick: TfgImageClickEvent;
procedure SetEffectOptions(const Value: TfgFlipViewEffectOptions);
procedure SetImages(const Value: TfgImageCollection);
procedure SetItemIndex(const Value: Integer);
procedure SetSlideShowOptions(const Value: TfgFlipViewSlideShowOptions);
procedure SetSlidingOptions(const Value: TfgFlipViewSlideOptions);
procedure SetShowNavigationButtons(const Value: Boolean);
function GetCurrentImage: TBitmap;
function GetImageCount: Integer;
procedure HandlerOptionsChanged(Sender: TObject);
procedure HandlerSlideShowOptionsChanged(Sender: TObject);
procedure HandlerEffectOptionsChanged(Sender: TObject);
procedure HandlerImagesChanged(Collection: TfgCollection; Item: TCollectionItem; const Action: TfgCollectionNotification);
public
constructor Create; override;
destructor Destroy; override;
function IsFirstImage: Boolean;
function IsLastImage: Boolean;
procedure StartChanging(const ANewItemIndex: Integer); virtual;
procedure FinishChanging; virtual;
procedure UpdateCurrentImage;
property CurrentImage: TBitmap read GetCurrentImage;
property ImagesCount: Integer read GetImageCount;
property IsSliding: Boolean read FIsSliding;
public
property EffectOptions: TfgFlipViewEffectOptions read FEffectOptions write SetEffectOptions;
property Images: TfgImageCollection read FImages write SetImages;
property ItemIndex: Integer read FItemIndex write SetItemIndex default -1;
property SlideOptions: TfgFlipViewSlideOptions read FSlidingOptions write SetSlidingOptions;
property SlideShowOptions: TfgFlipViewSlideShowOptions read FSlideShowOptions write SetSlideShowOptions;
property ShowNavigationButtons: Boolean read FShowNavigationButtons write SetShowNavigationButtons;
property OnStartChanging: TfgChangingImageEvent read FOnStartChanging write FOnStartChanging;
property OnFinishChanging: TNotifyEvent read FOnFinishChanging write FOnFinishChanging;
property OnImageClick: TfgImageClickEvent read FOnImageClick write FOnImageClick;
end;
TfgCustomFlipView = class(TPresentedControl, IfgFlipViewNotifications)
public const
DefaultMode = TfgFlipViewMode.Effects;
private
FSlideShowTimer: TTimer;
FMode: TfgFlipViewMode;
function GetModel: TfgFlipViewModel;
function GetEffectOptions: TfgFlipViewEffectOptions;
function GetImages: TfgImageCollection;
function GetItemIndex: Integer;
function GetSlideShowOptions: TfgFlipViewSlideShowOptions;
function GetSlidingOptions: TfgFlipViewSlideOptions;
function GetShowNavigationButtons: Boolean;
function GetOnFinishChanging: TNotifyEvent;
function GetOnStartChanging: TfgChangingImageEvent;
function GetOnImageClick: TfgImageClickEvent;
function IsEffectOptionsStored: Boolean;
function IsSlideOptionsStored: Boolean;
function IsSlideShowOptionsStored: Boolean;
procedure SetEffectOptions(const Value: TfgFlipViewEffectOptions);
procedure SetImages(const Value: TfgImageCollection);
procedure SetItemIndex(const Value: Integer);
procedure SetSlideShowOptions(const Value: TfgFlipViewSlideShowOptions);
procedure SetSlidingOptions(const Value: TfgFlipViewSlideOptions);
procedure SetShowNavigationButtons(const Value: Boolean);
procedure SetMode(const Value: TfgFlipViewMode);
procedure SetOnFinishChanging(const Value: TNotifyEvent);
procedure SetOnStartChanging(const Value: TfgChangingImageEvent);
procedure SetOnImageClick(const Value: TfgImageClickEvent);
protected
procedure HandlerTimer(Sender: TObject); virtual;
procedure UpdateTimer;
{ IfgFlipViewEvents }
procedure StartChanging;
procedure FinishChanging;
protected
function DefineModelClass: TDataModelClass; override;
function DefinePresentationName: string; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function CanSlideShow: Boolean;
{ Manipulation }
procedure GoToNext(const Animate: Boolean = True);
procedure GoToPrevious(const Animate: Boolean = True);
procedure GoToImage(const AImageIndex: Integer; const ADirection: TfgDirection = TfgDirection.Forward;
const Animate: Boolean = True);
property Model: TfgFlipViewModel read GetModel;
public
property EffectOptions: TfgFlipViewEffectOptions read GetEffectOptions write SetEffectOptions
stored IsEffectOptionsStored;
property Images: TfgImageCollection read GetImages write SetImages;
property ItemIndex: Integer read GetItemIndex write SetItemIndex default -1;
property Mode: TfgFlipViewMode read FMode write SetMode default DefaultMode;
property SlideOptions: TfgFlipViewSlideOptions read GetSlidingOptions write SetSlidingOptions
stored IsSlideOptionsStored;
property SlideShowOptions: TfgFlipViewSlideShowOptions read GetSlideShowOptions write SetSlideShowOptions
stored IsSlideShowOptionsStored;
property ShowNavigationButtons: Boolean read GetShowNavigationButtons write SetShowNavigationButtons
default TfgFlipViewModel.DefaultShowNavigationButtons;
property OnStartChanging: TfgChangingImageEvent read GetOnStartChanging write SetOnStartChanging;
property OnFinishChanging: TNotifyEvent read GetOnFinishChanging write SetOnFinishChanging;
property OnImageClick: TfgImageClickEvent read GetOnImageClick write SetOnImageClick;
end;
/// <summary>
/// Slider of images. Supports several way for displaying images.
/// </summary>
/// <remarks>
/// <note type="note">
/// Style's elements:
/// <list type="table">
/// <item>
/// <term>image: TImage</term>
/// <description>Container for current slide</description>
/// </item>
/// <item>
/// <term>image-next: TImage</term>
/// <description>Additional container for second image (in case of sliding mode)</description>
/// </item>
/// <item>
/// <term>next-button: TControl</term>
/// <description>Button 'Next slide'</description>
/// </item>
/// <item>
/// <term>prev-button: TControl</term>
/// <description>Button 'Previous slide'</description>
/// </item>
/// </list>
/// </note>
/// </remarks>
[ComponentPlatformsAttribute(fgAllPlatform)]
TfgFlipView = class(TfgCustomFlipView)
published
property Images;
property ItemIndex;
property Mode;
property EffectOptions;
property SlideOptions;
property SlideShowOptions;
property ShowNavigationButtons;
property OnStartChanging;
property OnFinishChanging;
property OnImageClick;
{ inherited }
property Align;
property Anchors;
property ClipChildren default False;
property ClipParent default False;
property Cursor default crDefault;
property DragMode default TDragMode.dmManual;
property EnableDragHighlight default True;
property Enabled default True;
property Locked default False;
property Height;
property HitTest default True;
property Padding;
property Opacity;
property Margins;
property PopupMenu;
property Position;
property RotationAngle;
property RotationCenter;
property Scale;
property Size;
property StyleLookup;
property TabOrder;
property TouchTargetExpansion;
property Visible default True;
property Width;
property OnDragEnter;
property OnDragLeave;
property OnDragOver;
property OnDragDrop;
property OnDragEnd;
property OnKeyDown;
property OnKeyUp;
property OnCanFocus;
property OnClick;
property OnDblClick;
property OnEnter;
property OnExit;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnMouseEnter;
property OnMouseLeave;
property OnPainting;
property OnPaint;
property OnPresentationNameChoosing;
property OnResize;
end;
implementation
uses
System.SysUtils, System.Math, FGX.Asserts, FGX.FlipView.Effect, FGX.FlipView.Sliding;
{ TfgCustomFlipView }
function TfgCustomFlipView.CanSlideShow: Boolean;
begin
AssertIsNotNil(Model);
AssertIsNotNil(SlideShowOptions);
Result := SlideShowOptions.Enabled and not(csDesigning in ComponentState) and not Model.IsSliding;
end;
constructor TfgCustomFlipView.Create(AOwner: TComponent);
begin
inherited;
FMode := DefaultMode;
FSlideShowTimer := TTimer.Create(nil);
FSlideShowTimer.Stored := False;
UpdateTimer;
FSlideShowTimer.OnTimer := HandlerTimer;
Touch.InteractiveGestures := Touch.InteractiveGestures + [TInteractiveGesture.Pan];
Touch.DefaultInteractiveGestures := Touch.DefaultInteractiveGestures + [TInteractiveGesture.Pan];
Touch.StandardGestures := Touch.StandardGestures + [TStandardGesture.sgLeft, TStandardGesture.sgRight,
TStandardGesture.sgUp, TStandardGesture.sgDown];
end;
function TfgCustomFlipView.DefineModelClass: TDataModelClass;
begin
Result := TfgFlipViewModel;
end;
function TfgCustomFlipView.DefinePresentationName: string;
var
Postfix: string;
begin
case Mode of
TfgFlipViewMode.Effects:
Postfix := 'Effect';
TfgFlipViewMode.Sliding:
Postfix := 'Sliding';
TfgFlipViewMode.Custom:
Postfix := 'Custom';
else
raise Exception.Create('Unknown value of [FGX.FlipView.Types.TfgFlipViewMode])');
end;
Result := 'fgFlipView-' + Postfix;
end;
destructor TfgCustomFlipView.Destroy;
begin
FreeAndNil(FSlideShowTimer);
inherited;
end;
function TfgCustomFlipView.GetEffectOptions: TfgFlipViewEffectOptions;
begin
AssertIsNotNil(Model);
Result := Model.EffectOptions;
end;
function TfgCustomFlipView.GetImages: TfgImageCollection;
begin
AssertIsNotNil(Model);
Result := Model.Images;
end;
function TfgCustomFlipView.GetItemIndex: Integer;
begin
AssertIsNotNil(Model);
Result := Model.ItemIndex;
end;
function TfgCustomFlipView.GetModel: TfgFlipViewModel;
begin
Result := inherited GetModel<TfgFlipViewModel>;
AssertIsNotNil(Result, 'TfgCustomFlipView.GetModel must return Model of [TfgFlipViewModel] class');
end;
function TfgCustomFlipView.GetOnFinishChanging: TNotifyEvent;
begin
AssertIsNotNil(Model);
Result := Model.OnFinishChanging;
end;
function TfgCustomFlipView.GetOnImageClick: TfgImageClickEvent;
begin
Result := Model.OnImageClick;
end;
function TfgCustomFlipView.GetOnStartChanging: TfgChangingImageEvent;
begin
AssertIsNotNil(Model);
Result := Model.OnStartChanging;
end;
function TfgCustomFlipView.GetShowNavigationButtons: Boolean;
begin
Result := Model.ShowNavigationButtons;
end;
function TfgCustomFlipView.GetSlideShowOptions: TfgFlipViewSlideShowOptions;
begin
AssertIsNotNil(Model);
Result := Model.SlideShowOptions;
end;
function TfgCustomFlipView.GetSlidingOptions: TfgFlipViewSlideOptions;
begin
AssertIsNotNil(Model);
Result := Model.SlideOptions;
end;
procedure TfgCustomFlipView.GoToImage(const AImageIndex: Integer; const ADirection: TfgDirection;
const Animate: Boolean);
var
ShowImageInfo: TfgShowImageInfo;
begin
if HasPresentationProxy then
begin
ShowImageInfo.NewItemIndex := AImageIndex;
ShowImageInfo.Animate := Animate;
ShowImageInfo.Direction := ADirection;
PresentationProxy.SendMessage<TfgShowImageInfo>(TfgFlipViewMessages.PM_GO_TO_IMAGE, ShowImageInfo);
end;
end;
procedure TfgCustomFlipView.GoToNext(const Animate: Boolean = True);
begin
GoToImage(IfThen(Model.IsLastImage, 0, ItemIndex + 1), TfgDirection.Forward, Animate);
end;
procedure TfgCustomFlipView.GoToPrevious(const Animate: Boolean = True);
begin
GoToImage(IfThen(Model.IsFirstImage, Model.ImagesCount - 1, ItemIndex - 1), TfgDirection.Backward, Animate);
end;
procedure TfgCustomFlipView.HandlerTimer(Sender: TObject);
begin
AssertIsNotNil(FSlideShowTimer);
FSlideShowTimer.Enabled := False;
try
GoToNext;
finally
FSlideShowTimer.Enabled := True;
end;
end;
function TfgCustomFlipView.IsEffectOptionsStored: Boolean;
begin
AssertIsNotNil(EffectOptions);
Result := not EffectOptions.IsDefaultValues;
end;
function TfgCustomFlipView.IsSlideOptionsStored: Boolean;
begin
AssertIsNotNil(SlideOptions);
Result := not SlideOptions.IsDefaultValues;
end;
function TfgCustomFlipView.IsSlideShowOptionsStored: Boolean;
begin
AssertIsNotNil(SlideShowOptions);
Result := not SlideShowOptions.IsDefaultValues;
end;
procedure TfgCustomFlipView.SetEffectOptions(const Value: TfgFlipViewEffectOptions);
begin
AssertIsNotNil(Value);
AssertIsNotNil(Model);
AssertIsNotNil(Model.EffectOptions);
Model.EffectOptions := Value;
end;
procedure TfgCustomFlipView.SetImages(const Value: TfgImageCollection);
begin
AssertIsNotNil(Value);
AssertIsNotNil(Model);
AssertIsNotNil(Model.Images);
Model.Images := Value;
end;
procedure TfgCustomFlipView.SetItemIndex(const Value: Integer);
begin
AssertIsNotNil(Model);
Model.ItemIndex := Value;
end;
procedure TfgCustomFlipView.SetMode(const Value: TfgFlipViewMode);
begin
if FMode <> Value then
begin
FMode := Value;
if [csDestroying, csReading] * ComponentState = [] then
ReloadPresentation;
end;
end;
procedure TfgCustomFlipView.SetOnFinishChanging(const Value: TNotifyEvent);
begin
AssertIsNotNil(Model);
Model.OnFinishChanging := Value;
end;
procedure TfgCustomFlipView.SetOnImageClick(const Value: TfgImageClickEvent);
begin
Model.OnImageClick := Value;
end;
procedure TfgCustomFlipView.SetOnStartChanging(const Value: TfgChangingImageEvent);
begin
AssertIsNotNil(Model);
Model.OnStartChanging := Value;
end;
procedure TfgCustomFlipView.SetShowNavigationButtons(const Value: Boolean);
begin
Model.ShowNavigationButtons := Value;
end;
procedure TfgCustomFlipView.SetSlideShowOptions(const Value: TfgFlipViewSlideShowOptions);
begin
AssertIsNotNil(Value);
AssertIsNotNil(Model);
AssertIsNotNil(Model.SlideShowOptions);
Model.SlideShowOptions := Value;
end;
procedure TfgCustomFlipView.SetSlidingOptions(const Value: TfgFlipViewSlideOptions);
begin
AssertIsNotNil(Value);
AssertIsNotNil(Model);
AssertIsNotNil(Model.SlideOptions);
Model.SlideOptions := Value;
end;
procedure TfgCustomFlipView.StartChanging;
begin
AssertIsNotNil(FSlideShowTimer);
FSlideShowTimer.Enabled := False;
end;
procedure TfgCustomFlipView.UpdateTimer;
begin
FSlideShowTimer.Interval := SlideShowOptions.Duration * MSecsPerSec;
FSlideShowTimer.Enabled := CanSlideShow;
end;
procedure TfgCustomFlipView.FinishChanging;
begin
AssertIsNotNil(FSlideShowTimer);
FSlideShowTimer.Enabled := CanSlideShow;
end;
{ TFgFlipViewModel }
procedure TfgFlipViewModel.StartChanging(const ANewItemIndex: Integer);
begin
FIsSliding := True;
if FFlipViewEvents <> nil then
FFlipViewEvents.StartChanging;
if Assigned(OnStartChanging) then
OnStartChanging(Owner, ANewItemIndex);
end;
procedure TfgFlipViewModel.UpdateCurrentImage;
begin
SendMessage<Integer>(TfgFlipViewMessages.MM_ITEM_INDEX_CHANGED, FItemIndex);
end;
constructor TfgFlipViewModel.Create;
begin
inherited Create;
FImages := TfgImageCollection.Create(Owner, TfgImageCollectionItem, HandlerImagesChanged);
FItemIndex := -1;
FIsSliding := False;
FSlideShowOptions := TfgFlipViewSlideShowOptions.Create(Owner, HandlerSlideShowOptionsChanged);
FSlidingOptions := TfgFlipViewSlideOptions.Create(Owner, HandlerOptionsChanged);
FEffectOptions := TfgFlipViewEffectOptions.Create(Owner, HandlerEffectOptionsChanged);
FShowNavigationButtons := DefaultShowNavigationButtons;
Supports(Owner, IfgFlipViewNotifications, FFlipViewEvents);
end;
destructor TfgFlipViewModel.Destroy;
begin
FFlipViewEvents := nil;
FreeAndNil(FImages);
FreeAndNil(FSlidingOptions);
FreeAndNil(FEffectOptions);
FreeAndNil(FSlideShowOptions);
inherited;
end;
procedure TfgFlipViewModel.FinishChanging;
begin
FIsSliding := False;
if FFlipViewEvents <> nil then
FFlipViewEvents.FinishChanging;
if Assigned(OnFinishChanging) then
OnFinishChanging(Owner);
end;
function TfgFlipViewModel.GetCurrentImage: TBitmap;
begin
AssertIsNotNil(FImages);
AssertInRange(ItemIndex, -1, ImagesCount - 1);
if InRange(ItemIndex, 0, ImagesCount - 1) then
Result := FImages[ItemIndex].Bitmap
else
Result := nil;
end;
function TfgFlipViewModel.GetImageCount: Integer;
begin
AssertIsNotNil(FImages);
Result := FImages.Count;
end;
procedure TfgFlipViewModel.HandlerEffectOptionsChanged(Sender: TObject);
begin
SendMessage(TfgFlipViewMessages.MM_EFFECT_OPTIONS_CHANGED);
end;
procedure TfgFlipViewModel.HandlerImagesChanged(Collection: TfgCollection; Item: TCollectionItem;
const Action: TfgCollectionNotification);
begin
AssertIsNotNil(Item);
if Action = TfgCollectionNotification.Updated then
UpdateCurrentImage;
if (Action = TfgCollectionNotification.Added) and (ItemIndex = -1) then
ItemIndex := 0;
if Action in [TfgCollectionNotification.Deleting, TfgCollectionNotification.Extracting] then
ItemIndex := EnsureRange(ItemIndex, -1, ImagesCount - 2); // -2, because ImageCount return count before removing item
end;
procedure TfgFlipViewModel.HandlerOptionsChanged(Sender: TObject);
begin
SendMessage(TfgFlipViewMessages.MM_SLIDE_OPTIONS_CHANGED);
end;
procedure TfgFlipViewModel.HandlerSlideShowOptionsChanged(Sender: TObject);
begin
SendMessage(TfgFlipViewMessages.MM_SLIDESHOW_OPTIONS_CHANGED);
if Owner is TfgCustomFlipView then
TfgCustomFlipView(Owner).UpdateTimer;
end;
function TfgFlipViewModel.IsFirstImage: Boolean;
begin
Result := ItemIndex = 0;
end;
function TfgFlipViewModel.IsLastImage: Boolean;
begin
Result := ItemIndex = ImagesCount - 1;
end;
procedure TfgFlipViewModel.SetEffectOptions(const Value: TfgFlipViewEffectOptions);
begin
AssertIsNotNil(Value);
FEffectOptions.Assign(Value);
end;
procedure TfgFlipViewModel.SetImages(const Value: TfgImageCollection);
begin
AssertIsNotNil(Value);
FImages.Assign(Value);
end;
procedure TfgFlipViewModel.SetItemIndex(const Value: Integer);
begin
if FItemIndex <> Value then
begin
FItemIndex := EnsureRange(Value, -1, ImagesCount - 1);
SendMessage<Integer>(TfgFlipViewMessages.MM_ITEM_INDEX_CHANGED, FItemIndex);
end;
end;
procedure TfgFlipViewModel.SetShowNavigationButtons(const Value: Boolean);
begin
if FShowNavigationButtons <> Value then
begin
FShowNavigationButtons := Value;
SendMessage<Boolean>(TfgFlipViewMessages.MM_SHOW_NAVIGATION_BUTTONS_CHANGED, FShowNavigationButtons);
end;
end;
procedure TfgFlipViewModel.SetSlideShowOptions(const Value: TfgFlipViewSlideShowOptions);
begin
AssertIsNotNil(Value);
FSlideShowOptions.Assign(Value);
end;
procedure TfgFlipViewModel.SetSlidingOptions(const Value: TfgFlipViewSlideOptions);
begin
AssertIsNotNil(Value);
FSlidingOptions.Assign(Value);
end;
initialization
RegisterFmxClasses([TfgCustomFlipView, TfgFlipView]);
end.
|
{
this file is part of Ares
Aresgalaxy ( http://aresgalaxy.sourceforge.net )
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
}
{
Description:
various protocol command values (alway 1 byte)
}
unit const_commands;
interface
const
MSG_CLIENT_LOGIN_REQ = 0;
MSG_CLIENT_PUSH_REQ = 7;
MSG_CLIENT_PUSH_REQNOCRYPT = 8;
MSG_CLIENT_ADD_SEARCH_NEW = 9;
MSG_CLIENT_ENDOFSEARCH = 12;
MSG_CLIENT_ADD_SEARCH_NEWUNICODE = 13;
MSG_CLIENT_REMOVING_SHARED = 21;
MSG_CLIENT_ADD_SHARE_KEY = 23;
MSG_CLIENT_ADD_CRCSHARE_KEY = 28;
MSG_CLIENT_LOGMEOFF = 26;
MSG_CLIENT_STAT_REQ = 30;
MSG_CLIENT_UPDATING_NICK = 34;
MSG_CLIENT_DUMMY = 35;
MSG_CLIENT_COMPRESSED = 50;
MSG_CLIENT_BROWSE_REQ = 71;
MSG_CLIENT_CHAT_NEWPUSH = 73;
MSG_CLIENT_CHAT_NEWPUSHNOCRYPT = 6;
MSG_CLIENT_WANT_DL_SORCS = 75;
MSG_CLIENT_ADD_HASHREQUEST = 80;
MSG_CLIENT_REM_HASHREQUEST = 81;
MSG_CLIENT_USERFIREWALL_REPORT = 82; //2967+ 28-6-2005
MSG_CLIENT_USERFIREWALL_REQ = 82; //2967+ 28-6-2005
MSG_CLIENT_USERFIREWALL_RESULT = 83;
MSG_CLIENT_FIRST_LOG = 90;
MSG_CLIENT_TEST = 91;
MSG_SUPERNODE_FIRST_LOG = 93;
MSG_SUPERNODE_SECOND_LOG = 98;
CMD_TAG_SUPPORTDIRECTCHAT = 1; //handshaked to verify compatibility
CMD_RELAYING_SOCKET_PACKET = 3; //server->localclient (data from remote user)
CMD_RELAYING_SOCKET_OUTBUFSIZE = 4; //server->localclient (slow down)
MSG_CLIENT_RELAYDIRECTCHATPACKET = 14; //localclient->server->remote requesting user
CMD_RELAYING_SOCKET_REQUEST = 5; // someone wants us to relay to our local user
CMD_RELAYING_SOCKET_OFFLINE = 6; //let remote user know user isn't here anymore
CMD_RELAYING_SOCKET_START = 7; //let remote user know we're ready
CMD_SERVER_RELAYINGSOCKETREQUEST = 8; // someone wants us to relay to our local user, let client know this
CMD_CLIENT_RELAYDIRECTCHATDROP = 2; // localclient closes window
implementation
end.
|
namespace RemObjects.Marzipan;
interface
uses
mono.utils,
mono.jit,
mono.metadata,
Foundation;
type
MZString = public class(MZObject)
private
method get_length: Integer;
method get_NSString: NSString;
class var fLength: method(aInstance: ^MonoObject; aEx: ^^MonoException): Integer;
class var fType: MZType := MZMonoRuntime.sharedInstance.getCoreType('System.String');
public
class method getType: MZType; override;
class method stringWithNSString(s: NSString): MZString;
class method MonoStringWithNSString(s: NSString): ^MonoString;
class method NSStringWithMonoString(s: ^MonoString): NSString;
property length: Integer read get_length;
property NSString: NSString read get_NSString;
end;
MZDateTime = public int64_t;
MZArray = public class(MZObject, sequence of id)
private
fNSArray: NSArray;
public
constructor withMonoInstance(aInst: ^MonoObject) elementType(aType: &Class);
constructor withNSArray(aArray: NSArray);
//constructor withArray<T>(aArray: array of T);
constructor withArray(aArray: array of String);
property &type: &Class := typeOf(MZObject);
property elements: ^^MonoObject read ^^MonoObject(mono_array_addr_with_size(^MonoArray(__instance), sizeOf(^MonoObject), 0));
property count: NSUInteger read mono_array_length(^MonoArray(__instance));
property «Count»: NSUInteger read count;
property Length: NSUInteger read count;
method objectAtIndex(aIndex: Integer): id;
method objectAtIndexedSubscript(aIndex: Integer): id;
method setObject(aObject: NSObject) atIndexedSubscript(aValue: Integer);
method countByEnumeratingWithState(state: ^NSFastEnumerationState) objects(buffer: ^id) count(len: NSUInteger): NSUInteger;
method NSArray: NSArray;
end;
MZObjectList = public class(MZObject, INSFastEnumeration)
assembly
fSize: ^Int32;
fItems: ^^MonoArray;
fLastItems: ^MonoArray;
fArray: MZArray;
fNSArray: NSArray;
class var fSizeField: ^MonoClassField;
class var fItemsField: ^MonoClassField;
method get_count: NSUInteger;
public
property &type: &Class := typeOf(MZObject);
constructor withNSArray(aNSArray: NSArray);
constructor withObject(aObject: id);
constructor withMonoInstance(aInst: ^MonoObject) elementType(aType: &Class);
method clear;
property count: NSUInteger read get_count;
property «Count»: NSUInteger read count;
method objectAtIndex(aIndex: Integer): id;
method objectAtIndexedSubscript(aIndex: Integer): id;
method countByEnumeratingWithState(state: ^NSFastEnumerationState) objects(buffer: ^id) count(len: NSUInteger): NSUInteger;
method NSArray: NSArray;
end;
RemObjects.Marzipan.Generic.MZObjectList<T> = public class(INSFastEnumeration<T>) mapped to MZObjectList
where T is class;
public
property count: NSUInteger read mapped.count;
//property «Count»: NSUInteger read count;
method objectAtIndex(aIndex: Integer): T; mapped to objectAtIndex(aIndex);
method objectAtIndexedSubscript(aIndex: Integer): T; mapped to objectAtIndexedSubscript(aIndex);
end;
NSString_Marzipan_Helpers = public extension class(NSString)
public
class method stringwithMonoString(s: ^MonoString): NSString;
method MonoString: ^MonoString;
end;
implementation
{ MZString }
class method MZString.getType: MZType;
begin
exit fType;
end;
method MZString.get_length: Integer;
begin
if fLength = nil then
^^Void(@fLength)^ := fType.getMethodThunk(':get_Length()');
var ex: ^MonoException := nil;
result := fLength(__instance, @ex);
if ex <> nil then raiseException(ex);
end;
class method MZString.stringWithNSString(s: NSString): MZString;
begin
if s = nil then exit nil;
exit new MZString withMonoInstance(^MonoObject(mono_string_from_utf16(^mono_unichar2(s.cStringUsingEncoding(NSStringEncoding.NSUnicodeStringEncoding)))));
end;
method MZString.get_NSString: NSString;
begin
exit Foundation.NSString.stringWithCharacters(^unichar(mono_string_chars(^MonoString(__instance)))) length(mono_string_length(^MonoString(__instance)));
end;
class method MZString.NSStringWithMonoString(s: ^MonoString): NSString;
begin
if s = nil then exit nil;
exit Foundation.NSString.stringWithCharacters(^unichar(mono_string_chars(^MonoString(s)))) length(mono_string_length(^MonoString(s)));
end;
class method MZString.MonoStringWithNSString(s: NSString): ^MonoString;
begin
if s = nil then exit nil;
exit mono_string_new_wrapper(s.cStringUsingEncoding(NSStringEncoding.NSUTF8StringEncoding));
end;
class method NSString_Marzipan_Helpers.stringwithMonoString(s: ^MonoString): NSString;
begin
if s = nil then exit nil;
exit Foundation.NSString.stringWithCharacters(^unichar(mono_string_chars(^MonoString(s)))) length(mono_string_length(^MonoString(s)));
end;
method NSString_Marzipan_Helpers.MonoString: ^MonoString;
begin
if self = nil then exit nil;
exit mono_string_from_utf16(^mono_unichar2(self.cStringUsingEncoding(NSStringEncoding.NSUnicodeStringEncoding)));
end;
{ MZArray }
constructor MZArray withMonoInstance(aInst: ^MonoObject) elementType(aType: &Class);
begin
self := inherited initWithMonoInstance(aInst);
if assigned(self) then begin
&type := aType;
end;
result := self;
end;
constructor MZArray withNSArray(aArray: NSArray);
begin
if aArray.count > 0 then begin
self := inherited initWithMonoInstance(mono_array_new(MZMonoRuntime.sharedInstance.domain, (aArray[0] as MZObject).getClass(), aArray.count) as ^MonoObject);
for i: Integer := 0 to aArray.count-1 do begin
var lInst := MZObject(aArray[i]):__instance;
elements[i] := lInst;
end;
end
else begin
self := inherited initWithMonoInstance(mono_array_new(MZMonoRuntime.sharedInstance.domain, mono_class_from_mono_type(MZMonoRuntime.sharedInstance.getCoreType('System.Object').type), 0) as ^MonoObject);
end;
end;
//constructor MZArray withArray<T>(aArray: array of T);
//begin
//if length(aArray) > 0 then begin
//self := inherited initWithMonoInstance(mono_array_new(MZMonoRuntime.sharedInstance.domain, (aArray[0] as MZObject).getClass(), length(aArray)) as ^MonoObject);
//for i: Integer := 0 to length(aArray)-1 do begin
//var lInst := MZObject(aArray[i]):__instance;
//elements[i] := lInst;
//end;
//end
//else begin
//self := inherited initWithMonoInstance(mono_array_new(MZMonoRuntime.sharedInstance.domain, mono_class_from_mono_type(MZMonoRuntime.sharedInstance.getCoreType('System.Object').type), 0) as ^MonoObject);
//end;
//end;
constructor MZArray withArray(aArray: array of String);
begin
self := inherited initWithMonoInstance(mono_array_new(MZMonoRuntime.sharedInstance.domain, mono_class_from_mono_type(MZString.getType.type), RemObjects.Elements.System.length(aArray)) as ^MonoObject);
for i: Integer := 0 to RemObjects.Elements.System.length(aArray)-1 do begin
var lInst := MZString.MonoStringWithNSString(aArray[i]) as ^MonoObject;
elements[i] := lInst;
end;
end;
method MZArray.objectAtIndex(aIndex: Integer): id;
begin
var lItem := elements[aIndex];
if lItem = nil then exit nil;
if &type = typeOf(NSString) then begin
exit MZString.NSStringWithMonoString(^MonoString(lItem));
end;
var lTmp := &type.alloc();
exit id(lTmp).initWithMonoInstance(lItem);
end;
method MZArray.objectAtIndexedSubscript(aIndex: Integer): id;
begin
var lItem := elements[aIndex];
if lItem = nil then exit nil;
if &type = typeOf(NSString) then begin
exit MZString.NSStringWithMonoString(^MonoString(lItem));
end;
var lTmp := &type.alloc();
exit id(lTmp).initWithMonoInstance(lItem);
end;
method MZArray.setObject(aObject: NSObject) atIndexedSubscript(aValue: Integer);
begin
if &type = typeOf(NSString) then
elements[aValue] := MZString.stringWithNSString(NSString(aObject)):__instance
else begin
var lInst := MZObject(aObject):__instance;
elements[aValue] := lInst;
end;
end;
method MZArray.NSArray: NSArray;
begin
if fNSArray = nil then begin
var lTmp := new NSMutableArray withCapacity(count);
var lElements := elements;
if &type = typeOf(String) then begin
for i: Integer := 0 to count -1 do
lTmp[i] := MZString.NSStringWithMonoString(^MonoString(lElements[i]));
end
else begin
for i: Integer := 0 to count -1 do
lTmp[i] := id(&type.alloc()).initWithMonoInstance(lElements[i]);
end;
fNSArray := lTmp;
end;
result := fNSArray;
end;
method MZArray.countByEnumeratingWithState(state: ^NSFastEnumerationState) objects(buffer: ^id) count(len: NSUInteger): NSUInteger;
begin
result := NSArray.countByEnumeratingWithState(state) objects(buffer) count(len);
end;
{ MZObjectList }
constructor MZObjectList withNSArray(aNSArray: NSArray);
begin
fNSArray := aNSArray;
end;
constructor MZObjectList withObject(aObject: id);
begin
fNSArray := Foundation.NSArray.arrayWithObject(aObject);
end;
constructor MZObjectList withMonoInstance(aInst: ^MonoObject) elementType(aType: &Class);
begin
self := inherited initWithMonoInstance(aInst);
if assigned(self) then begin
&type := aType;
end;
result := self;
end;
method MZObjectList.clear;
begin
if fItems = nil then MZObjectListInitFields(self); // global methods optimize better.
if (fItems^ <> fLastItems) or (fArray = nil) then MZObjectListLoadArray(self);
for i: Integer := count -1 downto 0 do // just unset the objects and release them.
fArray.setObject(nil) atIndexedSubscript(i);
fSize^ := 0;
end;
method MZObjectList.objectAtIndex(aIndex: Integer): id;
begin
if fItems = nil then MZObjectListInitFields(self); // global methods optimize better.
if (fItems^ <> fLastItems) or (fArray = nil) then MZObjectListLoadArray(self);
exit fArray[aIndex];
end;
method MZObjectList.objectAtIndexedSubscript(aIndex: Integer): id;
begin
if fItems = nil then MZObjectListInitFields(self); // global methods optimize better.
if (fItems^ <> fLastItems) or (fArray = nil) then MZObjectListLoadArray(self);
exit fArray[aIndex];
end;
method MZObjectList.countByEnumeratingWithState(state: ^NSFastEnumerationState) objects(buffer: ^id) count(len: NSUInteger): NSUInteger;
begin
result := NSArray.countByEnumeratingWithState(state) objects(buffer) count(len);
end;
method MZObjectList.get_count: NSUInteger;
begin
if fItems = nil then MZObjectListInitFields(self);
exit fSize^;
end;
method MZObjectList.NSArray: NSArray;
begin
if fNSArray = nil then begin
if fItems = nil then MZObjectListInitFields(self);
if (fArray = nil) then MZObjectListLoadArray(self);
var lTmp := new NSMutableArray withCapacity(count);
for i: Integer := 0 to count-1 do
lTmp[i] := fArray[i];
fNSArray := lTmp;
end;
result := fNSArray;
end;
method MZObjectListInitFields(aInst: MZObjectList);
begin
if MZObjectList.fSizeField = nil then begin
var lClass := mono_object_get_class(aInst.__instance);
MZObjectList.fSizeField := mono_class_get_field_from_name(lClass, '_size');
MZObjectList.fItemsField := mono_class_get_field_from_name(lClass, '_items');
end;
aInst.fSize := ^Int32(^Byte(aInst.__instance) + mono_field_get_offset(MZObjectList.fSizeField));
aInst.fItems := ^^MonoArray(^Byte(aInst.__instance) + mono_field_get_offset(MZObjectList.fItemsField));
end;
method MZObjectListLoadArray(aInst: MZObjectList);
begin
var lItems := aInst.fItems^;
aInst.fLastItems := lItems;
if lItems = nil then begin
aInst.fArray := nil;
exit;
end;
aInst.fArray := new MZArray withMonoInstance(^MonoObject(lItems));
aInst.fArray.type := aInst.type;
end;
end. |
{ @exclude }
unit rtcService;
{$include rtcDefs.inc}
interface
uses
Windows,
WinSvc,
SysUtils;
function IsServiceStarting(const ServiceName:string):boolean;
function IsDesktopMode(const ServiceName:string):boolean;
function IsMiniMode:boolean;
implementation
function IsServiceStarting(const ServiceName:string): Boolean;
var
Svc: Integer;
SvcMgr: Integer;
ServSt: TServiceStatus;
begin
Result := False;
SvcMgr := OpenSCManager(nil, nil, SC_MANAGER_CONNECT);
if SvcMgr = 0 then Exit;
try
Svc := OpenService (SvcMgr, PChar(ServiceName), SERVICE_QUERY_STATUS);
if Svc = 0 then Exit;
try
if not QueryServiceStatus (Svc, ServSt) then Exit;
Result := (ServSt.dwCurrentState = SERVICE_START_PENDING);
finally
CloseServiceHandle(Svc);
end;
finally
CloseServiceHandle(SvcMgr);
end;
end;
function IsDesktopMode(const ServiceName:string):boolean;
begin
if (Win32Platform <> VER_PLATFORM_WIN32_NT) then
Result := True
else
begin
Result := not FindCmdLineSwitch('INSTALL', ['-', '/'], True) and
not FindCmdLineSwitch('UNINSTALL', ['-', '/'], True) and
not IsServiceStarting(ServiceName);
end;
end;
function IsMiniMode:boolean;
begin
Result:=FindCmdLineSwitch('M',['-','/'],True);
end;
end.
|
unit SaberCommercialCompareUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, Db, DBTables, ComCtrls, ExtCtrls;
type
TForm1 = class(TForm)
StartButton: TBitBtn;
CancelButton: TBitBtn;
ParcelTable: TTable;
CommercialBuildingTable: TTable;
CommercialRentTable: TTable;
SaberParcelTable: TTable;
SaberCommercialBuildingTable: TTable;
SaberCommercialRentTable: TTable;
Label9: TLabel;
SwisCodeListBox: TListBox;
ProgressBar: TProgressBar;
SwisCodeTable: TTable;
InitializationTimer: TTimer;
SystemTable: TTable;
AssessmentYearControlTable: TTable;
CommercialInventoryTable: TTable;
SaberCommercialInventoryTable: TTable;
procedure FormCreate(Sender: TObject);
procedure StartButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure InitializationTimerTimer(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Cancelled : Boolean;
Procedure InitializeForm;
Procedure GetDifferencesThisParcel(DifferencesThisParcel : TList);
Procedure PrintThisParcel(var ExtractFile : TextFile;
SwisSBLKey : String;
Owner : String;
Location : String;
DifferencesThisParcel : TList);
end;
DifferenceRecord = record
DifferenceField : Integer;
PASValue : String;
SaberValue : String;
end;
DifferencePointer = ^DifferenceRecord;
var
Form1: TForm1;
implementation
{$R *.DFM}
uses GlblVars, GlblCnst, Winutils, Utilitys, PASUtils, Types, PASTypes;
const
dfParcelExists = 0;
dfYearBuilt = 1;
dfFloorArea = 2;
dfPerimeter = 3;
dfStories = 4;
dfUsedAsCode = 5;
dfUsedAsDescription = 6;
dfRentType = 7;
dfRentalArea = 8;
dfTotalUnits = 9;
dfImprovementCode = 10;
dfImprovementDescription = 11;
dfDimension1 = 12;
dfDimension2 = 13;
dfQuantity = 14;
DecimalEditDisplay = '0.00';
{=============================================}
Procedure TForm1.FormCreate(Sender: TObject);
begin
InitializationTimer.Enabled := True;
end;
{=============================================}
Procedure TForm1.InitializationTimerTimer(Sender: TObject);
begin
InitializationTimer.Enabled := False;
InitializeForm;
end;
{=============================================}
Procedure TForm1.InitializeForm;
begin
ParcelTable.Open;
CommercialBuildingTable.Open;
CommercialRentTable.Open;
CommercialImprovementTable.Open;
SaberParcelTable.Open;
SaberCommercialBuildingTable.Open;
SaberCommercialRentTable.Open;
SaberCommercialImprovementTable.Open;
SystemTable.Open;
SwisCodeTable.Open;
AssessmentYearControlTable.Open;
SetGlobalSystemVariables(SystemTable);
SetGlobalSBLSegmentFormats(AssessmentYearControlTable);
FillOneListBox(SwisCodeListBox, SwisCodeTable,
'SwisCode', 'MunicipalityName', 20,
True, True, ThisYear, GlblThisYear);
end; {InitializeForm}
{===========================================}
Function Power10(Places : Byte):Double;
{DS: Raise 10 to the indicated power (limited to 0,1,2,3,4,or 5) }
Var
Res : Double;
begin
Res := 0;
{ensure argument is in range...}
If Places > 5 then Places := 5;
Case Places of
0: Res := 1.0;
1: Res := 10.0;
2: Res := 100.0;
3: Res := 1000.0;
4: Res := 10000.0;
5: Res := 100000.0;
end; {case}
Power10 := Res;
end; { function Power10}
{==================================================================}
Function Roundoff(Number : Extended;
NumPlaces : Integer) : Extended;
var
I, FirstPlaceAfterDecimalPos, Pos,
DeterminingDigit, DigitInt, ReturnCode : Integer;
Digit : Real;
Answer : Extended;
AnswerStr, NumString : Str14;
AddOne : Boolean;
DigitStr : Str1;
begin
{They can only round off up to 5 places.}
If (NumPlaces > 5)
then NumPlaces := 5;
Str(Number:14:6, NumString);
NumString := LTrim(NumString);
{Find the decimal point.}
Pos := 1;
while ((Pos <= Length(NumString)) and (NumString[Pos] <> '.')) do
Pos := Pos + 1;
FirstPlaceAfterDecimalPos := Pos + 1;
{Now let's look at the place that we need to in order to determine
whether to round up or round down.}
DeterminingDigit := FirstPlaceAfterDecimalPos + NumPlaces;
Val(NumString[DeterminingDigit], DigitInt, ReturnCode);
(*DigitInt := Trunc(Digit);*)
{If the determining digit is >= 5, then round up. Otherwise, round
down.}
If (DigitInt >= 5)
then
begin
AnswerStr := '';
AddOne := True;
{We are rounding up, so first let's add one to the digit to
the left of the determining digit. If it takes us to ten,
continue working to the left until we don't roll over a
digit to ten.}
For I := (DeterminingDigit - 1) downto 1 do
begin
If (NumString[I] = '.')
then AnswerStr := '.' + AnswerStr
else
begin {The character is a digit.}
{FXX05261998-1: Not leaving the negative sign if
this is a negative number.}
If (NumString[I] = '-')
then AnswerStr := '-' + AnswerStr
else
begin
Val(NumString[I], Digit, ReturnCode);
DigitInt := Trunc(Digit);
If AddOne
then DigitInt := DigitInt + 1;
If (DigitInt = 10)
then AnswerStr := '0' + AnswerStr
else
begin
AddOne := False;
Str(DigitInt:1, DigitStr);
AnswerStr := DigitStr + AnswerStr;
end; {else of If (((DigitInt + 1) = 10) and AddOne)}
end; {else of If (NumString[I] = '-')}
end; {else of If (NumString[I] = '.')}
end; {For I := Pos to 1 do}
If AddOne
then AnswerStr := '1' + AnswerStr;
end {If (DigitInt >= 5)}
else AnswerStr := Copy(NumString, 1, (DeterminingDigit - 1));
Val(AnswerStr, Answer, ReturnCode);
Roundoff := Answer;
end; { function Roundoff....}
{=============================================}
Procedure AddDifferenceEntry(DifferencesThisParcel : TList;
_DifferenceField : Integer;
_PASValue : String;
_SaberValue : String;
Numeric : Boolean;
Float : Boolean);
var
DifferencePtr : DifferencePointer;
TempIntPAS, TempIntSaber : LongInt;
TempFloatPAS, TempFloatSaber : Double;
begin
New(DifferencePtr);
If Numeric
then
begin
If Float
then
begin
try
TempFloatPAS := StrToFloat(_PASValue);
except
TempFloatPAS := 0;
end;
try
TempFloatSaber := StrToFloat(_SaberValue);
except
TempFloatSaber := 0;
end;
If ((Roundoff(TempFloatPAS, 2) = 0) and
(Roundoff(TempFloatSaber, 2) = 0))
then
begin
_PASValue := '';
_SaberValue := '';
end
else
begin
If (Roundoff(TempFloatPAS, 2) = 0)
then _PASValue := '0'
else _PASValue := FormatFloat(DecimalEditDisplay,
TempFloatPAS);
If (Roundoff(TempFloatSaber, 2) = 0)
then _SaberValue := '0'
else _SaberValue := FormatFloat(DecimalEditDisplay,
TempFloatSaber);
end; {else of If ((TempFloatPAS = 0) and ...}
end {If Float}
else
begin
try
TempIntPAS := StrToInt(_PASValue);
except
TempIntPAS := 0;
end;
try
TempIntSaber := StrToInt(_SaberValue);
except
TempIntSaber := 0;
end;
If ((TempIntPAS = 0) and
(TempIntSaber = 0))
then
begin
_PASValue := '';
_SaberValue := '';
end
else
begin
If (TempIntPAS = 0)
then _PASValue := '0';
If (TempIntSaber = 0)
then _SaberValue := '0';
end; {else of If ((TempIntPAS = 0) and ...}
end; {else of If Float}
end; {If Numeric}
with DifferencePtr^ do
begin
DifferenceField := _DifferenceField;
PASValue := _PASValue;
SaberValue := _SaberValue;
end;
DifferencesThisParcel.Add(DifferencePtr);
end; {AddDifferenceEntry}
{=============================================}
Procedure CompareOneField(DifferencesThisParcel : TList;
DifferenceType : Integer;
FieldName : String;
PASTable : TTable;
SaberTable : TTable;
Numeric : Boolean;
Float : Boolean);
var
PASValue, SaberValue : String;
PASFloat, SaberFloat : Double;
DifferencesExists : Boolean;
begin
try
PASValue := Trim(PASTable.FieldByName(FieldName).Text);
except
PASValue := '';
end;
try
SaberValue := Trim(SaberTable.FieldByName(FieldName).Text);
except
SaberValue := '';
end;
DifferencesExists := (PASValue <> SaberValue);
If (Numeric and Float)
then
begin
try
PASFloat := Roundoff(StrToFloat(PASValue), 2);
except
PASFloat := 0;
end;
try
SaberFloat := Roundoff(StrToFloat(SaberValue), 2);
except
SaberFloat := 0;
end;
DifferencesExists := (Roundoff(PASFloat, 2) <> Roundoff(SaberFloat, 2));
end; {If (Numeric and Float)}
If DifferencesExists
then AddDifferenceEntry(DifferencesThisParcel, DifferenceType,
PASValue, SaberValue, Numeric, Float);
end; {CompareOneField}
{=============================================}
Procedure TForm1.GetDifferencesThisParcel(DifferencesThisParcel : TList);
var
ParcelFound, Done, FirstTimeThrough : Boolean;
PASBuildingStyle, SaberBuildingStyle,
PASBuildingStyleDesc, SaberBuildingStyleDesc,
SwisSBLKey, PASPoolType, SaberPoolType : String;
SBLRec : SBLRecord;
begin
SwisSBLKey := ExtractSSKey(ParcelTable);
SBLRec := ExtractSwisSBLFromSwisSBLKey(SwisSBLKey);
with SBLRec do
ParcelFound := FindKeyOld(SaberParcelTable,
['TaxRollYr', 'SwisCode', 'Section',
'Subsection', 'Block', 'Lot', 'Sublot', 'Suffix'],
['2002', SwisCode, Section,
SubSection, Block, Lot, Sublot, Suffix]);
If ParcelFound
then
begin
SetRangeOld(CommercialBuildingTable, ['TaxRollYr', 'SwisSBLKey'],
[GlblThisYear, SwisSBLKey], [GlblThisYear, SwisSBLKey]);
SetRangeOld(SaberCommercialBuildingTable, ['TaxRollYr', 'SwisSBLKey'],
['2002', SwisSBLKey], ['2002', SwisSBLKey]);
SetRangeOld(CommercialRentTable, ['TaxRollYr', 'SwisSBLKey'],
[GlblThisYear, SwisSBLKey], [GlblThisYear, SwisSBLKey]);
SetRangeOld(SaberCommercialRentTable, ['TaxRollYr', 'SwisSBLKey'],
['2002', SwisSBLKey], ['2002', SwisSBLKey]);
SetRangeOld(CommercialImprovementTable, ['TaxRollYr', 'SwisSBLKey'],
[GlblThisYear, SwisSBLKey], [GlblThisYear, SwisSBLKey]);
SetRangeOld(SaberCommercialImprovementTable, ['TaxRollYr', 'SwisSBLKey'],
['2002', SwisSBLKey], ['2002', SwisSBLKey]);
dfYearBuilt = 1;
dfFloorArea = 2;
dfPerimeter = 3;
dfStories = 4;
dfUsedAsCode = 5;
dfUsedAsDescription = 6;
dfRentType = 7;
dfRentalArea = 8;
dfTotalUnits = 9;
dfImprovementCode = 10;
dfImprovementDescription = 11;
dfDimension1 = 12;
dfDimension2 = 13;
dfQuantity = 14;
CompareOneField(DifferencesThisParcel, dfYearBuilt, 'EffectiveYearBuilt',
CommercialBuildingTable, SaberCommercialBuildingTable, True, False);
CompareOneField(DifferencesThisParcel, dfFloorArea, 'GrossFloorArea',
CommercialBuildingTable, SaberCommercialBuildingTable, True, True);
CompareOneField(DifferencesThisParcel, dfPerimeter, 'BuildingPerimeter',
CommercialBuildingTable, SaberCommercialBuildingTable, True, False);
CompareOneField(DifferencesThisParcel, dfStories, 'NumberStories',
CommercialBuildingTable, SaberCommercialBuildingTable, True, False);
CompareOneField(DifferencesThisParcel, dfUsedAsCode, 'SqFootLivingArea',
CommercialBuildingTable, SaberCommercialBuildingTable, True, True);
CompareOneField(DifferencesThisParcel, dfHalfStory, 'HalfStoryArea',
CommercialBuildingTable, SaberCommercialBuildingTable, True, True);
CompareOneField(DifferencesThisParcel, dfFirstFloor, 'FirstStoryArea',
CommercialBuildingTable, SaberCommercialBuildingTable, True, True);
CompareOneField(DifferencesThisParcel, dfSecondFloor, 'SecondStoryArea',
CommercialBuildingTable, SaberCommercialBuildingTable, True, True);
CompareOneField(DifferencesThisParcel, dfThirdFloor, 'ThirdStoryArea',
CommercialBuildingTable, SaberCommercialBuildingTable, True, True);
(* CompareOneField(DifferencesThisParcel, dfBuildingStyle, 'BuildingStyleCode',
CommercialBuildingTable, SaberCommercialBuildingTable, False, False);*)
{Always show building style and do it as the description.}
PASBuildingStyle := CommercialBuildingTable.FieldByName('BuildingStyleCode').Text;
SaberBuildingStyle := SaberCommercialBuildingTable.FieldByName('BuildingStyleCode').Text;
PASBuildingStyleDesc := '';
SaberBuildingStyleDesc := '';
If ((Deblank(PASBuildingStyle) <> '') and
FindKeyOld(BuildingStyleCodeTable, ['MainCode'], [PASBuildingStyle]))
then PASBuildingStyleDesc := BuildingStyleCodeTable.FieldByName('Description').Text;
If ((Deblank(SaberBuildingStyle) <> '') and
FindKeyOld(BuildingStyleCodeTable, ['MainCode'], [SaberBuildingStyle]))
then SaberBuildingStyleDesc := BuildingStyleCodeTable.FieldByName('Description').Text;
AddDifferenceEntry(DifferencesThisParcel, dfBuildingStyle,
PASBuildingStyleDesc, SaberBuildingStyleDesc, False, False);
CompareOneField(DifferencesThisParcel, dfFinishedAttic, 'FinishedAtticArea',
CommercialBuildingTable, SaberCommercialBuildingTable, True, True);
CompareOneField(DifferencesThisParcel, dfFinishedBasement, 'FinishedBasementArea',
CommercialBuildingTable, SaberCommercialBuildingTable, True, True);
CompareOneField(DifferencesThisParcel, dfFinishedRecRoom, 'FinishedRecRoom',
CommercialBuildingTable, SaberCommercialBuildingTable, True, True);
CompareOneField(DifferencesThisParcel, dfFinishedOverGarage, 'FinishedAreaOverGara',
CommercialBuildingTable, SaberCommercialBuildingTable, True, True);
CompareOneField(DifferencesThisParcel, dfPorchType, 'PorchTypeCode',
CommercialBuildingTable, SaberCommercialBuildingTable, False, False);
CompareOneField(DifferencesThisParcel, dfPorchSquareFeet, 'PorchArea',
CommercialBuildingTable, SaberCommercialBuildingTable, True, True);
{Do the pool type.}
PASPoolType := '';
SaberPoolType := '';
Done := False;
FirstTimeThrough := True;
CommercialRentTable.First;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else CommercialRentTable.Next;
If CommercialRentTable.EOF
then Done := True;
If ((not Done) and
(Copy(CommercialRentTable.FieldByName('StructureCode').Text, 1, 2) = 'LS'))
then PASPoolType := CommercialRentTable.FieldByName('StructureCode').Text;
until Done;
Done := False;
FirstTimeThrough := True;
SaberCommercialRentTable.First;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else SaberCommercialRentTable.Next;
If SaberCommercialRentTable.EOF
then Done := True;
If ((not Done) and
(Copy(SaberCommercialRentTable.FieldByName('StructureCode').Text, 1, 2) = 'LS'))
then SaberPoolType := SaberCommercialRentTable.FieldByName('StructureCode').Text;
until Done;
If (PASPoolType <> SaberPoolType)
then AddDifferenceEntry(DifferencesThisParcel, dfInGroundPool,
PASPoolType, SaberPoolType, False, False);
CompareOneField(DifferencesThisParcel, dfAcreage, 'Acreage',
ParcelTable, SaberParcelTable, True, True);
CompareOneField(DifferencesThisParcel, dfPropertyClass, 'PropertyClassCode',
ParcelTable, SaberParcelTable, False, False);
end {If ParcelFound}
else AddDifferenceEntry(DifferencesThisParcel, dfParcelExists,
ConvertSwisSBLToDashDotNoSwis(SwisSBLKey), '', False, False);
end; {GetDifferencesThisParcel}
{=============================================}
Function FindDifferenceItem( DifferencesThisParcel : TList;
_DifferenceField : Integer;
var Index : Integer) : Boolean;
var
I : Integer;
begin
Result := False;
Index := -1;
For I := 0 to (DifferencesThisParcel.Count - 1) do
If ((Index = -1) and
(DifferencePointer(DifferencesThisParcel[I])^.DifferenceField = _DifferenceField))
then
begin
Index := I;
Result := True;
end;
end; {FindDifferenceItem}
{=============================================}
Procedure WriteOneDifference(var ExtractFile : TextFile;
DifferencesThisParcel : TList;
_DifferenceField : Integer);
var
_PASValue, _SaberValue : String;
I : Integer;
begin
_PASValue := '';
_SaberValue := '';
If FindDifferenceItem(DifferencesThisParcel, _DifferenceField, I)
then
with DifferencePointer(DifferencesThisParcel[I])^ do
begin
_PASValue := PASValue;
_SaberValue := SaberValue;
end;
Write(ExtractFile, FormatExtractField(_PASValue),
FormatExtractField(_SaberValue));
end; {WriteOneDifference}
{=============================================}
Procedure TForm1.PrintThisParcel(var ExtractFile : TextFile;
SwisSBLKey : String;
Owner : String;
Location : String;
DifferencesThisParcel : TList);
var
I : Integer;
begin
Write(ExtractFile, Copy(SwisSBLKey, 1, 6),
FormatExtractField(ConvertSwisSBLToDashDotNoSwis(SwisSBLKey)),
FormatExtractField(Owner),
FormatExtractField(Location));
dfParcelExists = 0;
dfYearBuilt = 1;
dfFloorArea = 2;
dfPerimeter = 3;
dfStories = 4;
dfUsedAsCode = 5;
dfUsedAsDescription = 6;
dfRentType = 7;
dfRentalArea = 8;
dfTotalUnits = 9;
dfImprovementCode = 10;
dfImprovementDescription = 11;
dfDimension1 = 12;
dfDimension2 = 13;
dfQuantity = 14;
If FindDifferenceItem(DifferencesThisParcel, dfParcelExists, I)
then Writeln(ExtractFile, FormatExtractField('No Saber parcel found.'))
else
begin
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfYearBuilt);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfFloorArea);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfPerimeter);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfStories);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfUsedAsCode);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfusedAsDescription);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfRentType);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfRentalArea);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfTotalUnits);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfImprovementCode);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfImprovmentDescription);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfDimension1);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfDimension2);
WriteOneDifference(ExtractFile, DifferencesThisParcel, dfQuantity);
Writeln(ExtractFile);
end; {else of If FindDifferenceItem(DifferencesThisParcel, dfParcelExists, I)}
end; {PrintThisParcel}
{=============================================}
Procedure TForm1.StartButtonClick(Sender: TObject);
var
ExtractFile : TextFile;
SpreadsheetFileName : String;
Done, FirstTimeThrough : Boolean;
DifferencesThisParcel : TList;
SelectedSwisCodes : TStringList;
I : Integer;
begin
Cancelled := False;
SelectedSwisCodes := TStringList.Create;
DifferencesThisParcel := TList.Create;
SpreadsheetFileName := GetPrintFileName(Self.Caption, True);
AssignFile(ExtractFile, SpreadsheetFileName);
Rewrite(ExtractFile);
Writeln(ExtractFile, ',,,,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber,',
'PAS,',
'Saber');
Writeln(ExtractFile, 'Swis,',
'Parcel ID,',
'Owner,',
'Legal Address,',
'Year Built,',
'Year Built,',
'Floor Area,',
'Floor Area,',
'Perimeter,',
'Perimeter,',
'Stories,',
'Stories,'
'Used As,',
'Used As,',
'Used As Desc,',
'Used As Desc,',
'Rent Type,',
'Rent Type,',
'Rental Area,',
'Rental Area,',
'Units,',
'Units,',
'Imp Code,',
'Imp Code,',
'Imp Desc,',
'Imp Desc,',
'Dim 1,',
'Dim 1,',
'Dim 2,',
'Dim 2,',
'Quantity,',
'Quantity')
For I := 0 to (SwisCodeListBox.Items.Count - 1) do
If SwisCodeListBox.Selected[I]
then SelectedSwisCodes.Add(Take(6, SwisCodeListBox.Items[I]));
Done := False;
FirstTimeThrough := True;
ParcelTable.First;
ProgressBar.Max := GetRecordCount(ParcelTable);
ProgressBar.Position := 0;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else ParcelTable.Next;
ProgressBar.Position := ProgressBar.Position + 1;
Application.ProcessMessages;
If ParcelTable.EOF
then Done := True;
If ((not Done) and
(SelectedSwisCodes.IndexOf(ParcelTable.FieldByName('SwisCode').Text) > -1))
then
begin
ClearTList(DifferencesThisParcel, SizeOf(DifferenceRecord));
GetDifferencesThisParcel(DifferencesThisParcel);
If (DifferencesThisParcel.Count > 0)
then PrintThisParcel(ExtractFile,
ExtractSSKey(ParcelTable),
ParcelTable.FieldByName('Name1').Text,
GetLegalAddressFromTable(ParcelTable),
DifferencesThisParcel);
end; {If not Done}
until (Done or Cancelled);
FreeTList(DifferencesThisParcel, SizeOf(DifferenceRecord));
CloseFile(ExtractFile);
SendTextFileToExcelSpreadsheet(SpreadsheetFileName, True,
False, '');
SelectedSwisCodes.Free;
ProgressBar.Position := 0;
end; {StartButtonClick}
{=================================================================}
Procedure TForm1.CancelButtonClick(Sender: TObject);
begin
If (MessageDlg('Are you sure you want to cancel the comparison?',
mtConfirmation, [mbYes, mbNo], 0) = idYes)
then Cancelled := True;
end; {CancelButtonClick}
end. |
unit BasicUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, BasicService;
type
TForm1 = class(TForm)
txtName: TEdit;
lblSayMyName: TLabel;
btnInvoke: TButton;
Memo1: TMemo;
btnUser: TButton;
procedure btnInvokeClick(Sender: TObject);
procedure btnUserClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btnInvokeClick(Sender: TObject);
var
service:IBasicService;
result:string;
begin
service := GetIBasicService(true,'',nil);
result := service.HelloWorld(txtName.Text);
Memo1.Lines.Add('Method invoked. Result is : "' +result + '"');
end;
procedure TForm1.btnUserClick(Sender: TObject);
var
service:IBasicService;
user:BasicUser;
begin
user := BasicUser.Create;
user.Username := 'Pinkman';
user.Password := '123';
Memo1.Lines.Add('Username : ' + user.Username);
Memo1.Lines.Add('Password : ' + user.Password);
service := GetIBasicService(true,'',nil);
user := service.GetBasicUser;
Memo1.Lines.Add('GetBasicUser Method invoked.');
Memo1.Lines.Add('Username : ' + user.Username);
Memo1.Lines.Add('Password : ' + user.Password);
end;
end.
|
{*********************************************}
{ TeeChart Delphi Component Library }
{ Auto Axis scaling Demo }
{ Copyright (c) 1995-2001 by David Berneda }
{ All rights reserved }
{*********************************************}
unit uscroll;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, Chart, Series, ExtCtrls, Teengine, Buttons,
TeeProcs;
type
TScrollForm = class(TForm)
Chart1: TChart;
LineSeries1: TLineSeries;
Panel1: TPanel;
Button1: TButton;
BitBtn3: TBitBtn;
CBVertical: TCheckBox;
procedure LineSeries1AfterAdd(Sender: TChartSeries;
ValueIndex: Longint);
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure CBVerticalClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Procedure AddPoint(Const x,y:Double; AColor:TColor);
procedure FillDemoPoints;
end;
implementation
{$R *.dfm}
{ This is the event we need to arrange Axis scale as new points are added. }
procedure TScrollForm.LineSeries1AfterAdd(Sender: TChartSeries;
ValueIndex: Longint);
begin
{ If VERTICAL SCROLL }
if CBVertical.Checked then
begin
With Sender.GetVertAxis do { <-- with the Vertical Axis... }
Begin
Automatic := False; { <-- we dont want automatic scaling }
{ In this example, we will set the Axis Minimum and Maximum values to
show One Hour of data ending at last point Time plus 5 minutes
}
Minimum := 0;
Maximum := Sender.YValues.MaxValue + DateTimeStep[ dtFiveMinutes ];
Minimum := Maximum - DateTimeStep[ dtOneHour ];
end;
end
else
begin
With Sender.GetHorizAxis do { <-- with the Horizontal Axis... }
Begin
Automatic := False; { <-- we dont want automatic scaling }
{ In this example, we will set the Axis Minimum and Maximum values to
show One Hour of data ending at last point Time plus 5 minutes
}
Minimum := 0;
Maximum := Sender.XValues.MaxValue + DateTimeStep[ dtFiveMinutes ];
Minimum := Maximum - DateTimeStep[ dtOneHour ];
end;
End;
end;
Procedure TScrollForm.AddPoint(Const x,y:Double; AColor:TColor);
begin
if CBVertical.Checked then { If VERTICAL SCROLL }
LineSeries1.AddXY(y,x,'',AColor)
else
LineSeries1.AddXY(x,y,'',AColor);
end;
procedure TScrollForm.FormCreate(Sender: TObject);
begin
FillDemoPoints;
end;
procedure TScrollForm.FillDemoPoints;
var t:Longint;
begin
{ fill the LineSeries with some random data }
LineSeries1.Clear; { <-- this removes all points from LineSeries1 }
{ let's add 60 minutes from 12:00 to 12:59 }
for t:= 0 to 59 do
AddPoint( EncodeTime( 12, t, 0,0),Random(100),clRed );
{ let's add 60 more minutes from 13:00 to 13:59 }
for t:= 0 to 59 do
AddPoint( EncodeTime( 13, t, 0,0),Random(100),clRed);
end;
procedure TScrollForm.Button1Click(Sender: TObject);
var h,m,s,msec:word;
begin
if CBVertical.Checked then { if VERTICAL SCROLL.... }
DecodeTime( LineSeries1.YValues.Last , h, m, s, msec)
else
DecodeTime( LineSeries1.XValues.Last , h, m, s, msec);
{ add a new random point to the Series (one more minute) }
inc(m);
if m=60 then
begin
m:=0;
inc(h);
end;
AddPoint( EncodeTime( h, m, s, msec), Random(100), clYellow );
end;
procedure TScrollForm.CBVerticalClick(Sender: TObject);
begin
With LineSeries1 do
if CBVertical.Checked then { If VERTICAL SCROLL }
begin
YValues.Order:=loAscending;
XValues.Order:=loNone;
end
else
begin
XValues.Order:=loAscending;
YValues.Order:=loNone;
end;
Chart1.LeftAxis.Automatic:=True; { <-- this makes axis scales AUTOMATIC AGAIN ! }
Chart1.BottomAxis.Automatic:=True; { <-- this makes axis scales AUTOMATIC AGAIN ! }
FillDemoPoints; { <-- fill sample values again ! }
end;
end.
|
unit SymbolTable;
interface
uses
Contnrs, Token, Scanner;
const
TABLE_SIZE = 98317; // 49157; 6151; 196613; 393241
type
TSymbolTable = class
private
Table : array[0..TABLE_SIZE - 1] of TToken;
Stack : TStack;
Current : Integer;
Scope : Word;
function Hash(const S : string) : Cardinal;
public
constructor Create;
destructor Destroy; override;
function GetHash(Name : string) : Cardinal;
function Get(Name : string) : TToken;
function Count : Integer;
procedure Add(Token : TToken);
procedure Delete(Token : TToken);
procedure PushScope;
procedure PopScope;
function Last : TToken;
function Previous : TToken;
property Tokens[Name : string] : TToken read Get; default;
end;
implementation
uses
CompilerUtils;
{$R-,O-}
function TSymbolTable.Hash(const S : string) : Cardinal;
var // Jenkins
I : Cardinal;
begin
Result := 0;
for I := 1 to Length(S) do begin
inc(Result, (Result + ord(UpCase(S[I]))) shl 10);
Result := Result xor (Result shr 6);
end;
inc(Result, Result shl 3);
Result := Result xor (Result shr 11);
Result := ((Result + (Result shl 15)) + ord(S[length(S)]) * 2) mod TABLE_SIZE;
end;
{$R+,O+}
function TSymbolTable.GetHash(Name : string) : Cardinal; begin
Result := Hash(Name);
while (Table[Result] <> nil) and (LowerCase(Table[Result].Lexeme) <> LowerCase(Name)) do
Result := (Result + 1) mod TABLE_SIZE;
end;
function TSymbolTable.Get(Name : string) : TToken; begin
Result := Table[GetHash(Name)];
end;
function TSymbolTable.Count : Integer; begin
Result := Stack.Count - 1 - Scope;
end;
constructor TSymbolTable.Create; begin
Stack := TStack.Create;
Stack.Push(nil);
end;
destructor TSymbolTable.Destroy; begin
while Stack.Count <> 0 do TToken(Stack.Pop).Free;
Stack.Free;
inherited;
end;
{$R-,O-}
procedure TSymbolTable.Add(Token : TToken);
var
H : Cardinal;
begin
if Count >= TABLE_SIZE then raise EFatal.Create('Symbol table is full');
H := Hash(Token.Lexeme);
Token.Scope := Scope;
while Table[H] <> nil do
if LowerCase(Table[H].Lexeme) = LowerCase(Token.Lexeme) then begin
if Table[H].Scope = Token.Scope then
raise EError.CreateFmt('Identifier redeclared "%s"', [Token.Lexeme])
else
Token.NextScope := Table[H];
break;
end
else
H := (H + 1) mod TABLE_SIZE;
Token.Hash := H;
Table[H] := Token;
Stack.Push(Token);
end;
{$R+,O+}
procedure TSymbolTable.Delete(Token : TToken);
var
H : Cardinal;
begin
H := Token.Hash;
if (H >= TABLE_SIZE) or (Table[H] = nil) or
(LowerCase(Table[H].Lexeme) <> LowerCase(Token.Lexeme)) then
raise EFatal.CreateFmt('Trying to delete invalid token "%s", possibly data corruption', [Token.Lexeme])
else
Table[H] := Table[H].NextScope;
Token.Free;
end;
procedure TSymbolTable.PushScope; begin
inc(Scope);
Stack.Push(nil);
end;
procedure TSymbolTable.PopScope; begin
while Stack.Peek <> nil do Delete(TToken(Stack.Pop));
Stack.Pop;
if Scope > 0 then dec(Scope);
end;
function TSymbolTable.Last : TToken; begin
Current := Stack.Count - 1;
Result := Stack.Peek;
end;
type
THackStack = class(TStack);
function TSymbolTable.Previous : TToken; begin
if Current >= 0 then begin
if THackStack(Stack).List[Current] <> nil then dec(Current);
Result := THackStack(Stack).List[Current];
end
else
Result := nil;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{ : Eng
Language created to localize your application.
In Delphi, the text is encoded using Ansi cp1251 and can not be encoded \ decoding.
In Lazarus has the ability to upload text from any encoding.
Ru
TLanguage создан для локализации вашего приложения
В Delphi текст имеет кодировку Ansi cp1251 и не подлежит кодировке\декодировке.
В Lazarus можно загружать текст любой кодировки
<b>History : </b><font size=-1><ul>
<li>25/01/15 - PW - Fixed usage of String instead of AnsiString types
<li>04/11/10 - DaStr - Added Delphi5 and Delphi6 compatibility
<li>20/04/10 - Yar - Added to GLScene
(Created by Rustam Asmandiarov aka Predator)
</ul></font>
}
unit GLSLanguage;
interface
{$I GLScene.inc}
uses
System.Classes, System.IniFiles, System.SysUtils;
type
TLanguageEntry = record
ID: String; // **< identifier
Text: String; // **< translation
end;
TLanguageEntryArray = array of TLanguageEntry;
{ TLanguage }
{ **
* Eng
* Class TLanguage is used for downloading and translation, as in the final product it's no need for text processing.
* Ru
* Класс TLanguage используется толко для загрузки и перевода текста, так как в конечном
* продукте нет необходимости в обработке текста.
* }
TLanguage = class
private
FCurrentLanguageFile: String;
Entry: TLanguageEntryArray; // **< Entrys of Chosen Language
public
function FindID(const ID: String): integer;
function Translate(const ID: String): String;
procedure LoadLanguageFromFile(const Language: String);
property CurrentLanguageFile: String read FCurrentLanguageFile;
end;
{ **
* Eng
* Advanced class is designed for loading and processing, will be useful for the editors of language.
* Ru
* Расширенный класс созданный для загрузки и обработки текста, будет полезен для редакторов языка.
* }
TLanguageExt = class(TLanguage)
private
function GetEntry(Index: integer): TLanguageEntry;
procedure SetEntry(Index: integer; aValue: TLanguageEntry);
function GetCount: integer;
public
procedure AddConst(const ID: String; const Text: String);
procedure AddConsts(aValues: TStrings);
procedure ChangeConst(const ID: String; const Text: String);
property Items[Index: integer]: TLanguageEntry read GetEntry write SetEntry;
property Count: integer read GetCount;
procedure SaveLanguageFromFile(const Language: String); overload;
procedure SaveLanguageFromFile; overload;
end;
{ TGLSLanguage }
{ : Abstract class for control Language.<p> }
{ : Абстрактный класс, для палитры компонентов<p> }
TGLSLanguage = class(TComponent)
private
FLanguage: TLanguageExt;
FLanguageList: TStrings;
procedure SetLanguage(aValue: TLanguageExt);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure LoadLanguageFromFile(const Language: String);
procedure SaveLanguageFromFile(const Language: String); overload;
procedure SaveLanguageFromFile; overload;
function Translate(const ID: String): String;
property Language: TLanguageExt read FLanguage write SetLanguage;
end;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
implementation
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
uses
GLCrossPlatform, GLSLog;
{ TLanguage }
{ **
* Load the specified LanguageFile
* }
procedure TLanguage.LoadLanguageFromFile(const Language: String);
var
IniFile: TMemIniFile;
E: integer; // entry
S: TStringList;
I: integer;
begin
If Language = '' then
Exit;
if not FileExists(string(Language)) then
begin
{$IFDEF GLS_LOGGING}
GLSLogger.LogFatalError(ExtractFileName(string(Language)) +
' Languagefile missing!');
{$ENDIF}
Exit;
end;
SetLength(Entry, 0);
FCurrentLanguageFile := Language;
IniFile := TMemIniFile.Create(string(Language));
S := TStringList.Create;
IniFile.ReadSectionValues('Text', S);
// Problem Solving with symbols wrap (#13#10)
I := 0;
for E := 0 to S.Count - 1 do
begin
If S.Names[E] = '' then
begin
S.Strings[I] := S.Strings[I] + #13#10 + GetValueFromStringsIndex(S, E);
end
else
I := E;
end;
SetLength(Entry, S.Count);
for E := 0 to high(Entry) do
If S.Names[E] <> '' then
begin
Entry[E].ID := S.Names[E];
Entry[E].Text := GetValueFromStringsIndex(S, E);
end;
S.Free;
IniFile.Free;
end;
{ **
* Find the index of ID an array of language entry.
* @returns the index on success, -1 otherwise.
* }
function TLanguage.FindID(const ID: String): integer;
var
Index: integer;
begin
for Index := 0 to High(Entry) do
begin
if UpperCase(string(ID)) = UpperCase(string(Entry[Index].ID)) then
begin
Result := Index;
Exit;
end;
end;
Result := -1;
end;
{ **
* Translate the Text.
* If Text is an ID, text will be translated according to the current language
* setting. If Text is not a known ID, it will be returned as is.
* @param Text either an ID or an UTF-8 encoded string
* }
function TLanguage.Translate(const ID: String): String;
var
EntryIndex: integer;
begin
// fallback result in case Text is not a known ID
Result := ID;
// Check if ID exists
EntryIndex := FindID(ID);
if (EntryIndex >= 0) then
begin
Result := Entry[EntryIndex].Text;
Exit;
end;
end;
{ TLanguageExt }
{ **
* Add a Constant ID that will be Translated but not Loaded from the LanguageFile
* }
procedure TLanguageExt.AddConst(const ID: String; const Text: String);
begin
SetLength(Entry, Length(Entry) + 1);
Entry[high(Entry)].ID := ID;
Entry[high(Entry)].Text := Text;
end;
procedure TLanguageExt.AddConsts(aValues: TStrings);
var
I: integer;
begin
if aValues <> nil then
for I := 0 to aValues.Count - 1 do
If aValues.Names[I] <> '' then
AddConst(aValues.Names[I],GetValueFromStringsIndex(aValues, I));
end;
{ **
* Change a Constant Value by ID
* }
procedure TLanguageExt.ChangeConst(const ID: String;
const Text: String);
var
I: integer;
begin
for I := 0 to high(Entry) do
begin
if Entry[I].ID = ID then
begin
Entry[I].Text := Text;
Break;
end;
end;
end;
function TLanguageExt.GetEntry(Index: integer): TLanguageEntry;
begin
Result := Entry[Index];
end;
procedure TLanguageExt.SetEntry(Index: integer; aValue: TLanguageEntry);
begin
Entry[Index] := aValue;
end;
function TLanguageExt.GetCount: integer;
begin
Result := high(Entry) + 1;
end;
{ **
* Save Update Language File
* }
procedure TLanguageExt.SaveLanguageFromFile(const Language: String);
var
IniFile: TMemIniFile;
E: integer; // entry
begin
if Language = '' then
Exit;
IniFile := TMemIniFile.Create(string(Language));
for E := 0 to Count - 1 do
begin
IniFile.WriteString('Text', string(Items[E].ID), string(Items[E].Text));
end;
IniFile.UpdateFile;
IniFile.Free;
end;
procedure TLanguageExt.SaveLanguageFromFile;
begin
SaveLanguageFromFile(CurrentLanguageFile);
end;
{ TGLSLanguage }
constructor TGLSLanguage.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FLanguage := TLanguageExt.Create;
FLanguageList := TStringList.Create;
end;
destructor TGLSLanguage.Destroy;
begin
FLanguage.Free;
FLanguageList.Free;
inherited Destroy;
end;
procedure TGLSLanguage.LoadLanguageFromFile(const Language: String);
begin
FLanguage.LoadLanguageFromFile(Language);
end;
procedure TGLSLanguage.SetLanguage(aValue: TLanguageExt);
begin
if aValue <> nil then
FLanguage := aValue;
end;
procedure TGLSLanguage.SaveLanguageFromFile(const Language: String);
begin
if Language = '' then
Exit;
FLanguage.SaveLanguageFromFile(Language);
end;
procedure TGLSLanguage.SaveLanguageFromFile;
begin
FLanguage.SaveLanguageFromFile;
end;
function TGLSLanguage.Translate(const ID: String): String;
begin
Result := FLanguage.Translate(ID);
end;
// ------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
initialization
// ------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
RegisterClass(TGLSLanguage);
end.
|
{********************************************}
{ TeeChart Pro Charting Library }
{ Copyright (c) 1995-2004 by David Berneda }
{ All Rights Reserved }
{********************************************}
unit TeeMACDFuncEdit;
{$I TeeDefs.inc}
interface
uses
{$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QComCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls,
{$ENDIF}
TeCanvas, TeePenDlg, StatChar, TeeBaseFuncEdit;
type
TMACDFuncEditor = class(TBaseFunctionEditor)
Label3: TLabel;
ENum: TEdit;
UpDown1: TUpDown;
Label1: TLabel;
Edit1: TEdit;
UpDown2: TUpDown;
Label2: TLabel;
Edit2: TEdit;
UpDown3: TUpDown;
BHistogram: TButtonPen;
BMACDExp: TButtonPen;
BMACD: TButtonPen;
procedure ENumChange(Sender: TObject);
private
{ Private declarations }
protected
procedure ApplyFormChanges; override;
procedure SetFunction; override;
public
{ Public declarations }
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
procedure TMACDFuncEditor.ApplyFormChanges;
begin
inherited;
with TMACDFunction(IFunction) do
begin
Period:=UpDown1.Position;
Period2:=UpDown2.Position;
Period3:=UpDown3.Position;
end;
end;
procedure TMACDFuncEditor.ENumChange(Sender: TObject);
begin
EnableApply;
end;
procedure TMACDFuncEditor.SetFunction;
begin
inherited;
with TMACDFunction(IFunction) do
begin
UpDown1.Position:=Round(Period);
UpDown2.Position:=Round(Period2);
UpDown3.Position:=Round(Period3);
BHistogram.LinkPen(HistogramPen);
BMACD.LinkPen(MACDPen);
BMACDExp.LinkPen(MACDExpPen);
end;
end;
initialization
RegisterClass(TMACDFuncEditor);
end.
|
unit UI.Design.GridColumns;
interface
uses
UI.Grid,
System.Math,
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Objects, Data.DB,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation, FMX.Edit, FMX.Layouts, UI.Base, UI.Standard,
FMX.ListBox;
type
TGridColumnsDesigner = class(TForm)
Layout3: TLayout;
Label1: TLabel;
Label2: TLabel;
edtOpacity: TEdit;
Label3: TLabel;
edtRowsPan: TEdit;
Label4: TLabel;
edtPaddingBottom: TEdit;
GridView: TStringGridView;
cbGravity: TComboBox;
cbDataType: TComboBox;
Label5: TLabel;
Label6: TLabel;
edtColsPan: TEdit;
Label7: TLabel;
edtPaddingLeft: TEdit;
Label8: TLabel;
edtPaddingTop: TEdit;
Label9: TLabel;
edtPaddingRight: TEdit;
Label10: TLabel;
edtTag: TEdit;
ckLocked: TCheckBox;
ckDataFilter: TCheckBox;
ckReadOnly: TCheckBox;
ckVisible: TCheckBox;
ckEnabled: TCheckBox;
ckWordWrap: TCheckBox;
Label11: TLabel;
edtTitle: TEdit;
Layout1: TLayout;
Button2: TButton;
btnOk: TButton;
btnUp: TButton;
btnNext: TButton;
tvIndex: TLabel;
Label12: TLabel;
edtRowCount: TEdit;
tvColCount: TLabel;
edtColCount: TEdit;
Line1: TLine;
edtFieldName: TEdit;
tvField: TLabel;
edtFixedColCount: TEdit;
tvFixedColCount: TLabel;
edtWidth: TEdit;
Label13: TLabel;
Label14: TLabel;
edtWeight: TEdit;
cbFieldType: TComboBox;
Label15: TLabel;
procedure btnOkClick(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure GridViewFixedCellClick(Sender: TObject; const ACol,
ARow: Integer);
procedure GridViewTitleClick(Sender: TObject; Item: TGridColumnItem);
procedure edtRowCountKeyDown(Sender: TObject; var Key: Word;
var KeyChar: Char; Shift: TShiftState);
procedure edtRowCountExit(Sender: TObject);
procedure edtColCountExit(Sender: TObject);
procedure edtTitleExit(Sender: TObject);
procedure cbGravityClick(Sender: TObject);
procedure cbDataTypeClick(Sender: TObject);
procedure tvFieldExit(Sender: TObject);
procedure edtOpacityExit(Sender: TObject);
procedure edtPaddingLeftExit(Sender: TObject);
procedure edtPaddingTopExit(Sender: TObject);
procedure edtPaddingRightExit(Sender: TObject);
procedure edtPaddingBottomExit(Sender: TObject);
procedure edtTagExit(Sender: TObject);
procedure edtRowsPanExit(Sender: TObject);
procedure edtColsPanExit(Sender: TObject);
procedure edtFixedColCountExit(Sender: TObject);
procedure ckLockedClick(Sender: TObject);
procedure ckDataFilterClick(Sender: TObject);
procedure ckReadOnlyClick(Sender: TObject);
procedure ckVisibleClick(Sender: TObject);
procedure ckEnabledClick(Sender: TObject);
procedure ckWordWrapClick(Sender: TObject);
procedure btnUpClick(Sender: TObject);
procedure btnNextClick(Sender: TObject);
procedure edtWidthExit(Sender: TObject);
procedure GridViewDrawFixedColText(Sender: TObject; Canvas: TCanvas;
Item: TGridColumnItem; const R: TRectF; var DefaultDraw: Boolean);
procedure edtFieldNameExit(Sender: TObject);
procedure edtWeightExit(Sender: TObject);
procedure cbFieldTypeClick(Sender: TObject);
private
{ Private declarations }
[Weak] SrcGridView: TGridBase;
[Weak] CurItem: TGridColumnItem;
FIsDBGrid: Boolean;
FCol, FRow: Integer;
FUpdateing: Boolean;
procedure DoChange();
procedure SetColumns(const Value: TGridColumns);
function GetColumns: TGridColumns;
procedure UpdateState;
public
{ Public declarations }
property Columns: TGridColumns read GetColumns write SetColumns;
end;
var
GridColumnsDesigner: TGridColumnsDesigner;
implementation
{$R *.fmx}
const
CInvNo = -9999;
procedure TGridColumnsDesigner.btnNextClick(Sender: TObject);
function SkipPanCol(const ACol: Integer): Integer;
var
Item: TGridColumnItem;
begin
if Columns.TryGetItem(ACol, FRow, Item) and (Assigned(Item)) and (Item.ColsPan > 0) then
Result := ACol + Item.ColsPan
else
Result := ACol + 1;
end;
var
MCol, MRow: Integer;
begin
MCol := Columns.ColsCount - 1;
MRow := Columns.RowsCount - 1;
if (FRow <= MRow) or (FCol <= MRow) then begin
if FCol < MCol then begin
FCol := SkipPanCol(FCol);
end else begin
if FRow < MRow then begin
Inc(FRow);
FCol := 0;
end;
end;
GridView.ScrollToCell(TGridCell.Create(0, FCol));
CurItem := Columns.Items[FCol, FRow];
UpdateState;
end;
end;
procedure TGridColumnsDesigner.btnOkClick(Sender: TObject);
var
Item: TGridColumnItem;
I, J: Integer;
begin
if Assigned(SrcGridView) then begin
if (SrcGridView is TStringGridView) then
TStringGridView(SrcGridView).ColCount := GridView.ColCount;
SrcGridView.NeedSaveColumns := True;
end;
for I := 0 to Columns.RowsCount - 1 do begin
for J := 0 to Columns.ColsCount - 1 do begin
if Columns.TryGetItem(J, I, Item) and Assigned(Item) then
Item.ColIndex := J;
end;
end;
ModalResult := mrOk;
end;
procedure TGridColumnsDesigner.btnUpClick(Sender: TObject);
function SkipPanCol(const ACol: Integer): Integer;
var
I, J: Integer;
Item: TGridColumnItem;
begin
I := 0;
J := ACol;
while I <= ACol do begin
Item := nil;
J := I;
if Columns.TryGetItem(I, FRow, Item) and (Assigned(Item)) and (Item.ColsPan > 0) then
I := I + Item.ColsPan
else
Inc(I);
end;
Result := J;
end;
begin
if (FRow > 0) or (FCol > 0) then begin
if FCol > 0 then begin
Dec(FCol);
FCol := SkipPanCol(FCol);
end else begin
if FRow > 0 then begin
Dec(FRow);
FCol := SkipPanCol(Columns.ColsCount - 1);
end;
end;
GridView.ScrollToCell(TGridCell.Create(0, FCol));
CurItem := Columns.Items[FCol, FRow];
UpdateState;
end;
end;
procedure TGridColumnsDesigner.Button2Click(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TGridColumnsDesigner.cbDataTypeClick(Sender: TObject);
begin
if Assigned(CurItem) and (not FUpdateing) then begin
CurItem.DataType := TGridDataType(cbDataType.ItemIndex);
DoChange();
end;
end;
procedure TGridColumnsDesigner.cbFieldTypeClick(Sender: TObject);
begin
if FIsDBGrid then
Exit;
if Assigned(CurItem) and (not FUpdateing) then begin
CurItem.FieldType := TFieldType(cbFieldType.ItemIndex);
DoChange();
end;
end;
procedure TGridColumnsDesigner.cbGravityClick(Sender: TObject);
begin
if Assigned(CurItem) and (not FUpdateing) then begin
CurItem.Gravity := TLayoutGravity(cbGravity.ItemIndex);
DoChange();
end;
end;
procedure TGridColumnsDesigner.ckDataFilterClick(Sender: TObject);
begin
if Assigned(CurItem) and (not FUpdateing) then begin
CurItem.DataFilter := TCheckBox(Sender).IsChecked;
DoChange();
end;
end;
procedure TGridColumnsDesigner.ckEnabledClick(Sender: TObject);
begin
if Assigned(CurItem) and (not FUpdateing) then begin
CurItem.Enabled := TCheckBox(Sender).IsChecked;
DoChange();
end;
end;
procedure TGridColumnsDesigner.ckLockedClick(Sender: TObject);
begin
if Assigned(CurItem) and (not FUpdateing) then begin
CurItem.Locked := TCheckBox(Sender).IsChecked;
DoChange();
end;
end;
procedure TGridColumnsDesigner.ckReadOnlyClick(Sender: TObject);
begin
if Assigned(CurItem) and (not FUpdateing) then begin
CurItem.ReadOnly := TCheckBox(Sender).IsChecked;
DoChange();
end;
end;
procedure TGridColumnsDesigner.ckVisibleClick(Sender: TObject);
begin
if Assigned(CurItem) and (not FUpdateing) then begin
CurItem.Visible := TCheckBox(Sender).IsChecked;
DoChange();
end;
end;
procedure TGridColumnsDesigner.ckWordWrapClick(Sender: TObject);
begin
if Assigned(CurItem) and (not FUpdateing) then begin
CurItem.WordWrap := TCheckBox(Sender).IsChecked;
DoChange();
end;
end;
procedure TGridColumnsDesigner.DoChange;
begin
if not FUpdateing then
Columns.Change;
end;
procedure TGridColumnsDesigner.edtColCountExit(Sender: TObject);
begin
Columns.ColsCount := StrToIntDef(TEdit(Sender).Text, Columns.ColsCount);
end;
procedure TGridColumnsDesigner.edtColsPanExit(Sender: TObject);
begin
if Assigned(CurItem) then begin
CurItem.ColsPan := StrToIntDef(TEdit(Sender).Text, CurItem.ColsPan);
DoChange();
end;
end;
procedure TGridColumnsDesigner.edtFieldNameExit(Sender: TObject);
begin
if Assigned(CurItem) and (CurItem is TGridColumnItem) then begin
TGridColumnItem(CurItem).FieldName := TEdit(Sender).Text;
DoChange();
end;
end;
procedure TGridColumnsDesigner.edtFixedColCountExit(Sender: TObject);
begin
GridView.FixedCols := StrToIntDef(TEdit(Sender).Text, GridView.FixedCols);
end;
procedure TGridColumnsDesigner.edtOpacityExit(Sender: TObject);
begin
if Assigned(CurItem) then begin
CurItem.Opacity := StrToFloatDef(TEdit(Sender).Text, CurItem.Opacity);
DoChange();
end;
end;
procedure TGridColumnsDesigner.edtPaddingBottomExit(Sender: TObject);
begin
if Assigned(CurItem) then begin
CurItem.Padding.Bottom := StrToFloatDef(TEdit(Sender).Text, CurItem.Padding.Bottom);
DoChange();
end;
end;
procedure TGridColumnsDesigner.edtPaddingLeftExit(Sender: TObject);
begin
if Assigned(CurItem) then begin
CurItem.Padding.Left := StrToFloatDef(TEdit(Sender).Text, CurItem.Padding.Left);
DoChange();
end;
end;
procedure TGridColumnsDesigner.edtPaddingRightExit(Sender: TObject);
begin
if Assigned(CurItem) then begin
CurItem.Padding.Right := StrToFloatDef(TEdit(Sender).Text, CurItem.Padding.Right);
DoChange();
end;
end;
procedure TGridColumnsDesigner.edtPaddingTopExit(Sender: TObject);
begin
if Assigned(CurItem) then begin
CurItem.Padding.Top := StrToFloatDef(TEdit(Sender).Text, CurItem.Padding.Top);
DoChange();
end;
end;
procedure TGridColumnsDesigner.edtRowCountExit(Sender: TObject);
begin
Columns.RowsCount := StrToIntDef(TEdit(Sender).Text, Columns.RowsCount);
end;
procedure TGridColumnsDesigner.edtRowCountKeyDown(Sender: TObject;
var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
if Key = vkReturn then
TControl(Sender).FocusToNext();
end;
procedure TGridColumnsDesigner.edtRowsPanExit(Sender: TObject);
begin
if Assigned(CurItem) then begin
CurItem.RowsPan := StrToIntDef(TEdit(Sender).Text, CurItem.RowsPan);
DoChange();
end;
end;
procedure TGridColumnsDesigner.edtTagExit(Sender: TObject);
begin
if Assigned(CurItem) then
CurItem.Tag := StrToIntDef(TEdit(Sender).Text, CurItem.Tag);
end;
procedure TGridColumnsDesigner.edtTitleExit(Sender: TObject);
begin
if Assigned(CurItem) then begin
CurItem.Title := TEdit(Sender).Text;
DoChange();
end;
end;
procedure TGridColumnsDesigner.edtWeightExit(Sender: TObject);
begin
if Assigned(CurItem) then begin
CurItem.Weight := StrToFloatDef(TEdit(Sender).Text, 0);
DoChange;
end;
end;
procedure TGridColumnsDesigner.edtWidthExit(Sender: TObject);
begin
if Assigned(CurItem) then begin
CurItem.Width := StrToFloatDef(TEdit(Sender).Text, 0);
DoChange;
end;
end;
function TGridColumnsDesigner.GetColumns: TGridColumns;
begin
Result := GridView.Columns;
end;
procedure TGridColumnsDesigner.GridViewDrawFixedColText(Sender: TObject;
Canvas: TCanvas; Item: TGridColumnItem; const R: TRectF; var DefaultDraw: Boolean);
var
VR: TRectF;
begin
VR.Left := R.Left + Item.Padding.Left;
VR.Top := R.Top + Item.Padding.Top;
VR.Right := R.Right - Item.Padding.Right;
VR.Bottom := R.Bottom - item.Padding.Bottom;
if Item = CurItem then begin
GridView.Background.DrawStateTo(Canvas, R, TViewState.Selected);
end;
GridView.FixedSettings.TextSettings.Draw(Canvas, Item.DispLayText, VR, GridView.Opacity * Item.Opacity, GridView.DrawState);
end;
procedure TGridColumnsDesigner.GridViewFixedCellClick(Sender: TObject;
const ACol, ARow: Integer);
begin
FCol := ACol;
FRow := -1;
CurItem := Columns.Items[FCol, FRow];
UpdateState;
end;
procedure TGridColumnsDesigner.GridViewTitleClick(Sender: TObject;
Item: TGridColumnItem);
begin
FCol := Item.ColIndex;
FRow := Item.RowIndex;
CurItem := Item;
UpdateState;
end;
procedure TGridColumnsDesigner.SetColumns(const Value: TGridColumns);
begin
if Value = nil then
Exit;
GridView.Columns.RegisterColumnClass(Value.ColumnClass);
GridView.Columns.Assign(Value);
FIsDBGrid := False;
SrcGridView := nil;
if Assigned(Value) and Assigned(Value.GridView) then begin
SrcGridView := Value.GridView;
FIsDBGrid := Value.GridView is TDBGridView;
GridView.ColCount := Value.GridView.ColCount;
edtFixedColCount.Enabled := SrcGridView is TStringGridView;
GridView.FixedCols := SrcGridView.FixedCols;
end else
edtFixedColCount.Enabled := False;
tvFixedColCount.Enabled := edtFixedColCount.Enabled;
// if not FIsDBGrid then
//begin
tvField.Visible := True;
edtFieldName.Visible := True;
edtTitle.Width := edtFieldName.Position.X + edtFieldName.Width - edtTitle.Position.X;
//end;
if FIsDBGrid then
begin
cbFieldTYpe.Visible := False;
label15.Visible := False;
// edtTitle.Width := edtFieldName.Position.X + edtFieldName.Width - edtTitle.Position.X;
end;
FCol := CInvNo;
FRow := CInvNo;
UpdateState;
end;
procedure TGridColumnsDesigner.tvFieldExit(Sender: TObject);
begin
if Assigned(CurItem) then begin
TGridColumnItem(CurItem).FieldName := TEdit(Sender).Text;
DoChange();
end;
end;
procedure TGridColumnsDesigner.UpdateState;
procedure Clear();
begin
cbGravity.ItemIndex := -1;
cbDataType.ItemIndex := -1;
cbFieldType.ItemIndex := 1;
edtFieldName.Text := '';
edtOpacity.Text := '';
edtPaddingLeft.Text := '';
edtPaddingTop.Text := '';
edtPaddingRight.Text := '';
edtPaddingBottom.Text := '';
edtWidth.Text := '';
edtWeight.Text := '';
edtTag.Text := '';
edtRowsPan.Text := '';
edtColsPan.Text := '';
ckLocked.IsChecked := False;
ckEnabled.IsChecked := False;
ckDataFilter.IsChecked := False;
ckReadOnly.IsChecked := False;
ckVisible.IsChecked := False;
ckWordWrap.IsChecked := False;
end;
begin
FUpdateing := True;
try
edtRowCount.Text := IntToStr(Columns.RowsCount);
edtColCount.Text := IntToStr(Columns.ColsCount);
if FRow < 0 then begin
btnUp.Enabled := False;
btnNext.Enabled := False;
edtRowsPan.Enabled := False;
edtColsPan.Enabled := False;
ckLocked.Enabled := False;
ckEnabled.Enabled := False;
ckDataFilter.Enabled := False;
ckReadOnly.Enabled := False;
ckVisible.Enabled := False;
ckWordWrap.Enabled := False;
Label3.Enabled := False;
Label6.Enabled := False;
end else begin
btnUp.Enabled := (FRow > 0) or (FCol > 0);
btnNext.Enabled := (FRow < Columns.RowsCount - 1) or (FCol < Columns.ColsCount - 1);
edtRowsPan.Enabled := True;
edtColsPan.Enabled := True;
ckLocked.Enabled := True;
ckEnabled.Enabled := True;
ckDataFilter.Enabled := True;
ckReadOnly.Enabled := True;
ckVisible.Enabled := True;
ckWordWrap.Enabled := True;
Label3.Enabled := True;
Label6.Enabled := True;
end;
edtFixedColCount.Text := IntToStr(GridView.FixedCols);
if (CurItem = nil) or (FCol = CInvNo) or (FRow = CInvNo) then begin
tvIndex.Text := '';
Clear();
Exit;
end else
tvIndex.Text := Format('Col: %d Row: %d', [FCol, FRow]);
if FRow < 0 then begin
Clear();
cbGravity.ItemIndex := Ord(CurItem.Gravity);
cbDataType.ItemIndex := Ord(CurItem.DataType);
cbFieldType.ItemIndex := Ord(CurItem.FieldType);
edtTitle.Text := CurItem.Title;
edtFieldName.Enabled := False;
edtOpacity.Text := FloatToStr(Round(CurItem.Opacity * 10000) / 10000);
edtPaddingLeft.Text := FloatToStr(Round(CurItem.Padding.Left * 10000) / 10000);
edtPaddingTop.Text := FloatToStr(Round(CurItem.Padding.Top * 10000) / 10000);
edtPaddingRight.Text := FloatToStr(Round(CurItem.Padding.Right * 10000) / 10000);
edtPaddingBottom.Text := FloatToStr(Round(CurItem.Padding.Bottom * 10000) / 10000);
edtWidth.Text := FloatToStr(Round(CurItem.Width * 10000) / 10000);
edtWeight.Text := FloatToStr(Round(CurItem.Weight * 10000) / 10000);
edtTag.Text := IntToStr(CurItem.Tag);
end else begin
cbGravity.ItemIndex := Ord(CurItem.Gravity);
cbDataType.ItemIndex := Ord(CurItem.DataType);
cbFieldType.ItemIndex := Ord(CurItem.FieldType);
edtTitle.Text := CurItem.Title;
edtFieldName.Enabled := CurItem is TGridColumnItem;
if edtFieldName.Enabled then begin
if Assigned(CurItem) then
edtFieldName.Text := TGridDBColumnItem(CurItem).AbsoluteFieldName
else
edtFieldName.Text := CurItem.FieldName;
end else
edtFieldName.Text := '';
edtOpacity.Text := FloatToStr(Round(CurItem.Opacity * 10000) / 10000);
edtPaddingLeft.Text := FloatToStr(Round(CurItem.Padding.Left * 10000) / 10000);
edtPaddingTop.Text := FloatToStr(Round(CurItem.Padding.Top * 10000) / 10000);
edtPaddingRight.Text := FloatToStr(Round(CurItem.Padding.Right * 10000) / 10000);
edtPaddingBottom.Text := FloatToStr(Round(CurItem.Padding.Bottom * 10000) / 10000);
edtWidth.Text := FloatToStr(Round(CurItem.Width * 10000) / 10000);
edtWeight.Text := FloatToStr(Round(CurItem.Weight * 10000) / 10000);
edtTag.Text := IntToStr(CurItem.Tag);
edtRowsPan.Text := IntToStr(CurItem.RowsPan);
edtColsPan.Text := IntToStr(CurItem.ColsPan);
ckLocked.IsChecked := CurItem.Locked;
ckEnabled.IsChecked := CurItem.Enabled;
ckDataFilter.IsChecked := CurItem.DataFilter;
ckReadOnly.IsChecked := CurItem.ReadOnly;
ckVisible.IsChecked := CurItem.Visible;
ckWordWrap.IsChecked := CurItem.WordWrap;
end;
finally
FUpdateing := False;
GridView.Invalidate;
end;
end;
end.
|
(* NaturalVectorClass: MM, 2020-06-05 *)
(* ------ *)
(* Simple Class to store Natural Vectors in an IntArray *)
(* ========================================================================= *)
UNIT NaturalVectorClass;
INTERFACE
USES VectorClass;
TYPE
NaturalVector = ^NaturalVectorObj;
NaturalVectorObj = OBJECT(VectorObj)
PUBLIC
CONSTRUCTOR Init;
DESTRUCTOR Done; VIRTUAL;
PROCEDURE Add(value: INTEGER); VIRTUAL;
PROCEDURE InsertElementAt(pos, value: INTEGER); VIRTUAL;
END; (* NaturalVectorObj *)
IMPLEMENTATION
CONSTRUCTOR NaturalVectorObj.Init;
BEGIN (* NaturalVectorObj.Init *)
INHERITED Init;
END; (* NaturalVectorObj.Init *)
DESTRUCTOR NaturalVectorObj.Done;
BEGIN (* NaturalVectorObj.Done *)
INHERITED Done;
END; (* NaturalVectorObj.Done *)
PROCEDURE NaturalVectorObj.Add(value: INTEGER);
BEGIN (* NaturalVectorObj.Add *)
IF (value >= 0) THEN
INHERITED Add(value)
ELSE
WriteLn('"', value, '" is not a Natural Number, cannot be added.');
END; (* NaturalVectorObj.Add *)
PROCEDURE NaturalVectorObj.InsertElementAt(pos, value: INTEGER);
BEGIN (* NaturalVectorObj.InsertElementAt *)
IF (value >= 0) THEN
INHERITED InsertElementAt(pos, value)
ELSE
WriteLn('"', value, '" is not a Natural Number, cannot be added.');
END; (* NaturalVectorObj.InsertElementAt *)
END. (* NaturalVectorClass *) |
unit UProduto;
interface
uses
Data.DB, Data.Win.ADODB;
type
TProduto = class
private
Fdescricao: string;
Fcodigo: Integer;
FprecoVenda: Double;
procedure Setcodigo(const Value: Integer);
procedure Setdescricao(const Value: string);
procedure SetprecoVenda(const Value: Double);
public
property codigo: Integer read Fcodigo write Setcodigo;
property descricao: string read Fdescricao write Setdescricao;
property precoVenda: Double read FprecoVenda write SetprecoVenda;
end;
implementation
{ TProduto }
procedure TProduto.Setcodigo(const Value: Integer);
begin
Fcodigo := Value;
end;
procedure TProduto.Setdescricao(const Value: string);
begin
Fdescricao := Value;
end;
procedure TProduto.SetprecoVenda(const Value: Double);
begin
FprecoVenda := Value;
end;
end.
|
unit DataTypeHelper;
interface
uses
SysUtils,
Classes;
type
TDCString = type string;
TDCStringHelper = record helper for TDCString
function SquareBracket():TDCString;
function Bracket():TDCString;
function Surround(SurChar:Char):TDCString;
function Quotes:TDCString;
function AddString(const s:string):TDCString;
function ToString(): string;
class function EmptyStr() : TDCString; static;
end;
implementation
{ TDCStringHelper }
function TDCStringHelper.AddString(const s: string): TDCString;
begin
Self := Self + s;
Result := Self;
end;
function TDCStringHelper.Bracket: TDCString;
begin
Result := '(' + Self + ')';
end;
class function TDCStringHelper.EmptyStr: TDCString;
begin
Result := '';
end;
function TDCStringHelper.Quotes: TDCString;
begin
Result := Self.Surround('''');
end;
function TDCStringHelper.SquareBracket: TDCString;
begin
Result := '['+ Self +']';
end;
function TDCStringHelper.Surround(SurChar: Char): TDCString;
begin
Result := SurChar + Self + SurChar;
end;
function TDCStringHelper.ToString(): string;
begin
Result := Self;
end;
end.
|
unit Preview;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, RPBase, RPCanvas, RPFPrint,
RPreview, RPDefine, GlblVars, Winutils;
type
TPreviewForm = class(TForm)
Panel2: TPanel;
SBZoomIn: TSpeedButton;
SBZoomOut: TSpeedButton;
Label1: TLabel;
SBPrevPage: TSpeedButton;
SBNextPage: TSpeedButton;
Label2: TLabel;
FilePreview: TFilePreview;
FilePrinter: TFilePrinter;
SBDone: TSpeedButton;
SBPrint: TSpeedButton;
ScrollBox1: TScrollBox;
ZoomEdit: TEdit;
SBZoomPageWidth: TSpeedButton;
SBZoomPage: TSpeedButton;
PageEdit: TEdit;
PageLabel: TLabel;
PrinterSetupDialog: TPrinterSetupDialog;
FirstPageButton: TSpeedButton;
LastPageButton: TSpeedButton;
PrintDialog: TPrintDialog;
procedure SBZoomInClick(Sender: TObject);
procedure SBZoomOutClick(Sender: TObject);
procedure SBPrevPageClick(Sender: TObject);
procedure SBNextPageClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure SBPrintClick(Sender: TObject);
procedure SBDoneClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure SBZoomPageWidthClick(Sender: TObject);
procedure SBZoomPageClick(Sender: TObject);
procedure FilePreviewPageChange(Sender: TObject);
procedure FilePreviewZoomChange(Sender: TObject);
procedure ZoomEditExit(Sender: TObject);
procedure PageEditExit(Sender: TObject);
procedure ZoomEditKeyPress(Sender: TObject; var Key: Char);
procedure PageEditKeyPress(Sender: TObject; var Key: Char);
procedure FirstPageButtonClick(Sender: TObject);
procedure LastPageButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
end;
var
PreviewForm: TPreviewForm;
implementation
{$R *.DFM}
procedure TPreviewForm.SBZoomInClick(Sender: TObject);
begin
FilePreview.ZoomIn;
end;
procedure TPreviewForm.SBZoomOutClick(Sender: TObject);
begin
FilePreview.ZoomOut;
end;
procedure TPreviewForm.SBPrevPageClick(Sender: TObject);
begin
FilePreview.PrevPage;
end;
procedure TPreviewForm.SBNextPageClick(Sender: TObject);
begin
FilePreview.NextPage;
end;
procedure TPreviewForm.FormActivate(Sender: TObject);
begin
{FXX04091999-7: The following line is to prevent the progress dialog from appearing
when switch from PAS and then back to Preview form.}
ScrollBox1.SetFocus;
FilePreview.Start;
{Make full page visible.}
{FXX10272001-1: If there is no zoom factor in the user record, make it 100.}
With FilePreview do
If (GlblDefaultPreviewZoomPercent = 0)
then ZoomFactor := 0
else ZoomFactor := GlblDefaultPreviewZoomPercent;
end;
{======================================================}
Procedure TPreviewForm.SBPrintClick(Sender: TObject);
var
_Copies, _FirstPage, _LastPage : Integer;
begin
{FXX08031999-3: Allow users to specify ranges, copies.}
If PrintDialog.Execute
then
begin
with FilePrinter as TBaseReport do
begin
_Copies := PrintDialog.Copies;
_FirstPage := 1;
_LastPage := 32000;
If (PrintDialog.ToPage > 0)
then
begin
_FirstPage := PrintDialog.FromPage;
_LastPage := PrintDialog.ToPage;
end;
end; { with FilePrinter as TBaseReport do}
(* FilePrinter.Execute; *)
{FXX04282000-2: Multiple copies from preview screen not working.}
{FXX04022001-3: Reinstate copies.}
If (PrintDialog.PrintRange = prAllPages)
then FilePrinter.Execute
else FilePrinter.ExecuteCustom(_FirstPage, _LastPage, _Copies);
{FXX09071999-6: Tell people that printing is starting and
done.}
DisplayPrintingFinishedMessage(PrintDialog.PrintToFile);
end; {If PrintDialog.Execute}
end; {SBPrintClick}
procedure TPreviewForm.SBDoneClick(Sender: TObject);
begin
Close;
end;
procedure TPreviewForm.FormClose( Sender: TObject;
var Action: TCloseAction);
begin
FilePreview.Finish;
end;
procedure TPreviewForm.SBZoomPageWidthClick(Sender: TObject);
begin
With FilePreview do begin
ZoomFactor := ZoomPageWidthFactor;
end; { with }
end;
procedure TPreviewForm.SBZoomPageClick(Sender: TObject);
begin
With FilePreview do begin
ZoomFactor := ZoomPageFactor;
end; { with }
end;
procedure TPreviewForm.FilePreviewPageChange(Sender: TObject);
begin
With FilePreview do begin
PageEdit.Text := IntToStr(CurrentPage);
PageLabel.Caption := 'Page ' + IntToStr(CurrentPage - FirstPage + 1) +
' of ' + IntToStr(Pages);
end; { with }
end;
procedure TPreviewForm.FilePreviewZoomChange(Sender: TObject);
var
S1: string[10];
begin
Str(FilePreview.ZoomFactor:1:1,S1);
ZoomEdit.Text := S1;
FilePreview.RedrawPage;
end;
procedure TPreviewForm.ZoomEditExit(Sender: TObject);
var
F1: double;
ErrCode: integer;
begin
Val(ZoomEdit.Text,F1,ErrCode);
If (ErrCode = 0) and (FilePreview.ZoomFactor <> F1) then begin
FilePreview.ZoomFactor := F1;
end; { if }
end;
procedure TPreviewForm.PageEditExit(Sender: TObject);
var
I1: integer;
ErrCode: integer;
begin
Val(PageEdit.Text,I1,ErrCode);
If (ErrCode = 0) and (FilePreview.CurrentPage <> I1) then begin
FilePreview.PrintPage(I1);
end; { if }
end;
procedure TPreviewForm.ZoomEditKeyPress(Sender: TObject; var Key: Char);
begin
If Key = #13 then begin
ZoomEditExit(Sender);
end; { if }
end;
procedure TPreviewForm.PageEditKeyPress(Sender: TObject; var Key: Char);
begin
If Key = #13 then begin
PageEditExit(Sender);
end; { if }
end;
{Added by MDT.}
procedure TPreviewForm.FirstPageButtonClick(Sender: TObject);
begin
If (FilePreview.CurrentPage <> 1) then
FilePreview.PrintPage(1);
end;
procedure TPreviewForm.LastPageButtonClick(Sender: TObject);
begin
If (FilePreview.CurrentPage <> FilePreview.Pages) then
FilePreview.PrintPage(FilePreview.Pages);
end;
procedure TPreviewForm.FormShow(Sender: TObject);
begin
{FXX04091999-7: Problem where progress dialog would come back up if shifted away from
PAS and then back while Preview form was up.}
ScrollBox1.SetFocus;
end;
end.
|
unit MainFrm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FGX.LinkedLabel, FMX.Edit,
FMX.Controls.Presentation;
type
TForm1 = class(TForm)
PanelSettings: TPanel;
gbCommonSettings: TGroupBox;
Label1: TLabel;
edURI: TEdit;
Label2: TLabel;
edCaption: TEdit;
cbVisited: TCheckBox;
fgLinkedLabel: TfgLinkedLabel;
procedure edURIChangeTracking(Sender: TObject);
procedure edCaptionChangeTracking(Sender: TObject);
procedure cbVisitedChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
procedure TForm1.cbVisitedChange(Sender: TObject);
begin
fgLinkedLabel.Visited := cbVisited.IsChecked;
end;
procedure TForm1.edCaptionChangeTracking(Sender: TObject);
begin
fgLinkedLabel.Text := edCaption.Text;
end;
procedure TForm1.edURIChangeTracking(Sender: TObject);
begin
fgLinkedLabel.Url := edURI.Text;
end;
end.
|
{*********************************************************************
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Autor: Brovin Y.D.
* E-mail: y.brovin@gmail.com
*
********************************************************************}
unit FGX.FlipView.Presentation;
interface
uses
System.Classes, System.Types, FMX.Presentation.Style, FMX.Graphics, FMX.Types, FMX.Controls.Model,
FMX.Presentation.Messages, FMX.Objects, FMX.Controls, FGX.FlipView, FGX.FlipView.Types;
type
{ TStyledFlipViewBasePresentation }
/// <summary>Base styled presentation of <c>TFlipView</c></summary>
TfgStyledFlipViewBasePresentation = class(TStyledPresentation)
private
[Weak] FImageContainer: TImage;
[Weak] FPreviousButton: TControl;
[Weak] FNextButton: TControl;
FSavedTapLocation: TPointF;
FIsGestureStarted: Boolean;
function GetModel: TfgFlipViewModel;
procedure HandlerNextButtonClick(Sender: TObject);
procedure HandlerPreviousButtonClick(Sender: TObject);
procedure HandlerCurrentSlideClick(Sender: TObject);
protected
{ Messages from PresentationProxy }
procedure PMGoToImage(var Message: TDispatchMessageWithValue<TfgShowImageInfo>); message TfgFlipViewMessages.PM_GO_TO_IMAGE;
{ Messages From Model}
procedure MMItemIndexChanged(var AMessage: TDispatchMessageWithValue<Integer>); message TfgFlipViewMessages.MM_ITEM_INDEX_CHANGED;
procedure MMShowNavigationButtons(var AMessage: TDispatchMessageWithValue<Boolean>); message TfgFlipViewMessages.MM_SHOW_NAVIGATION_BUTTONS_CHANGED;
protected
function DefineModelClass: TDataModelClass; override;
procedure UpdateNavigationButtonsVisible;
{ Styles }
procedure ApplyStyle; override;
procedure FreeStyle; override;
function GetStyleObject: TFmxObject; override;
{ Gesture }
procedure CMGesture(var EventInfo: TGestureEventInfo); override;
public
constructor Create(AOwner: TComponent); override;
/// <summary>Show next slide</summary>
procedure ShowNextImage(const ANewItemIndex: Integer; const ADirection: TfgDirection; const AAnimate: Boolean); virtual;
/// <summary>Returns link on style object <c>"image"</c>. Can be nil, if style doesn't have it.</summary>
property ImageContainer: TImage read FImageContainer;
/// <summary>Returns link on style object <c>"next-button"</c>. Can be nil, if style doesn't have it.</summary>
property NextButton: TControl read FNextButton;
/// <summary>Returns link on style object <c>"prev-button"</c>. Can be nil, if style doesn't have it.</summary>
property PreviousButton: TControl read FPreviousButton;
/// <summary>Return model of <c>TfgFlipVIew</c></summary>
property Model: TfgFlipViewModel read GetModel;
end;
implementation
uses
System.SysUtils, System.Math, System.UITypes, FMX.Styles, FGX.Asserts;
{ TfgStyledFlipViewBasePresentation }
procedure TfgStyledFlipViewBasePresentation.ApplyStyle;
var
StyleObject: TFmxObject;
begin
inherited ApplyStyle;
{ Next button }
StyleObject := FindStyleResource('next-button');
if StyleObject is TControl then
begin
FNextButton := TControl(StyleObject);
FNextButton.OnClick := HandlerNextButtonClick;
end;
{ Previous button }
StyleObject := FindStyleResource('prev-button');
if StyleObject is TControl then
begin
FPreviousButton := TControl(StyleObject);
FPreviousButton.OnClick := HandlerPreviousButtonClick;
end;
{ Image container for current slide }
StyleObject := FindStyleResource('image');
if StyleObject is TImage then
begin
FImageContainer := TImage(StyleObject);
FImageContainer.Visible := True;
FImageContainer.Cursor := crHandPoint;
FImageContainer.OnClick := HandlerCurrentSlideClick;
end;
UpdateNavigationButtonsVisible;
end;
procedure TfgStyledFlipViewBasePresentation.CMGesture(var EventInfo: TGestureEventInfo);
var
Vector: TPointF;
begin
inherited;
if EventInfo.GestureID = igiPan then
begin
if TInteractiveGestureFlag.gfBegin in EventInfo.Flags then
begin
FSavedTapLocation := EventInfo.Location;
FIsGestureStarted := True;
end;
if TInteractiveGestureFlag.gfEnd in EventInfo.Flags then
begin
Vector := EventInfo.Location - FSavedTapLocation;
if Vector.X < 0 then
ShowNextImage(IfThen(Model.IsLastImage, 0, Model.ItemIndex + 1), TfgDirection.Forward, True)
else
ShowNextImage(IfThen(Model.IsFirstImage, Model.ImagesCount - 1, Model.ItemIndex - 1), TfgDirection.Backward, True);
end;
end;
end;
constructor TfgStyledFlipViewBasePresentation.Create(AOwner: TComponent);
begin
inherited;
FIsGestureStarted := False;
Touch.InteractiveGestures := Touch.InteractiveGestures + [TInteractiveGesture.Pan];
Touch.StandardGestures := Touch.StandardGestures + [TStandardGesture.sgLeft, TStandardGesture.sgRight,
TStandardGesture.sgUp, TStandardGesture.sgDown];
end;
function TfgStyledFlipViewBasePresentation.DefineModelClass: TDataModelClass;
begin
Result := TfgFlipViewModel;
end;
procedure TfgStyledFlipViewBasePresentation.FreeStyle;
begin
if FNextButton <> nil then
FNextButton.OnClick := nil;
FNextButton := nil;
if FPreviousButton <> nil then
FPreviousButton.OnClick := nil;
FPreviousButton := nil;
FImageContainer := nil;
inherited FreeStyle;
end;
function TfgStyledFlipViewBasePresentation.GetModel: TfgFlipViewModel;
begin
Result := inherited GetModel<TfgFlipViewModel>;
end;
function TfgStyledFlipViewBasePresentation.GetStyleObject: TFmxObject;
const
ResourceName = 'TfgFlipViewStyle';
var
StyleContainer: TFmxObject;
begin
Result := nil;
if StyleLookup.IsEmpty and (FindResource(HInstance, PChar(ResourceName), RT_RCDATA) <> 0) then
begin
StyleContainer := TStyleStreaming.LoadFromResource(HInstance, ResourceName, RT_RCDATA);
Result := StyleContainer.FindStyleResource('fgFlipViewStyle', True);
if Result <> nil then
Result.Parent := nil;
StyleContainer.Free;
end;
if Result = nil then
Result := inherited GetStyleObject;
end;
procedure TfgStyledFlipViewBasePresentation.HandlerCurrentSlideClick(Sender: TObject);
begin
AssertIsClass(PresentedControl, TfgCustomFlipView);
if not FIsGestureStarted and Assigned(Model.OnImageClick) and (PresentedControl is TfgCustomFlipView) and (Model.ItemIndex <> -1) then
Model.OnImageClick(PresentedControl, TfgCustomFlipView(PresentedControl), Model.ItemIndex);
// FireMonkey invoke Click, even if fmx recognized a gesture. So we use this way for notify, that we shouldn't invoke
// OnImageClick.
FIsGestureStarted := False;
end;
procedure TfgStyledFlipViewBasePresentation.HandlerNextButtonClick(Sender: TObject);
begin
AssertIsNotNil(Model);
ShowNextImage(IfThen(Model.IsLastImage, 0, Model.ItemIndex + 1), TfgDirection.Forward, True);
end;
procedure TfgStyledFlipViewBasePresentation.HandlerPreviousButtonClick(Sender: TObject);
begin
AssertIsNotNil(Model);
ShowNextImage(IfThen(Model.IsFirstImage, Model.ImagesCount - 1, Model.ItemIndex - 1), TfgDirection.Backward, True);
end;
procedure TfgStyledFlipViewBasePresentation.MMItemIndexChanged(var AMessage: TDispatchMessageWithValue<Integer>);
begin
AssertIsNotNil(Model);
if ImageContainer <> nil then
ImageContainer.Bitmap.Assign(Model.CurrentImage);
end;
procedure TfgStyledFlipViewBasePresentation.MMShowNavigationButtons(var AMessage: TDispatchMessageWithValue<Boolean>);
begin
UpdateNavigationButtonsVisible;
end;
procedure TfgStyledFlipViewBasePresentation.PMGoToImage(var Message: TDispatchMessageWithValue<TfgShowImageInfo>);
begin
ShowNextImage(Message.Value.NewItemIndex, Message.Value.Direction, Message.Value.Animate);
end;
procedure TfgStyledFlipViewBasePresentation.ShowNextImage(const ANewItemIndex: Integer; const ADirection: TfgDirection;
const AAnimate: Boolean);
begin
AssertIsNotNil(Model);
Model.DisableNotify;
try
Model.ItemIndex := ANewItemIndex;
Model.StartChanging(ANewItemIndex);
finally
Model.EnableNotify;
end;
end;
procedure TfgStyledFlipViewBasePresentation.UpdateNavigationButtonsVisible;
begin
if NextButton <> nil then
NextButton.Visible := Model.ShowNavigationButtons;
if PreviousButton <> nil then
PreviousButton.Visible := Model.ShowNavigationButtons;
end;
end.
|
unit gExpressionConstants;
interface
Uses
gExpressionEvaluator
;
Type
TConstant = class(TgExpressionToken)
End;
TMaxInt = Class(TConstant)
Public
Procedure Evaluate(AStack : TgVariantStack);Override;
End;
TTrue = Class(TConstant)
Public
Procedure Evaluate(AStack : TgVariantStack);Override;
End;
TFalse = Class(TConstant)
Public
Procedure Evaluate(AStack : TgVariantStack);Override;
End;
TUnassigned = class(TConstant)
Public
Procedure Evaluate(AStack : TgVariantStack);Override;
End;
implementation
Uses
SysUtils
, Variants
;
{ TMaxInt }
procedure TMaxInt.Evaluate(AStack : TgVariantStack);
begin
AStack.Push(MaxInt);
end;
{ TTrue }
procedure TTrue.Evaluate(AStack : TgVariantStack);
begin
AStack.Push(True);
end;
{ TFalse }
procedure TFalse.Evaluate(AStack : TgVariantStack);
begin
AStack.Push(False);
end;
{ TTrue }
procedure TUnassigned.Evaluate(AStack : TgVariantStack);
begin
AStack.Push(Unassigned);
end;
Initialization
TMaxInt.Register('MaxInt');
TTrue.Register('True');
TFalse.Register('False');
TUnassigned.Register('Unassigned');
end.
|
unit ExceptionForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Layouts, FMX.Memo;
type
TForm1 = class(TForm)
Memo1: TMemo;
btnNoException: TButton;
btnRaiseException: TButton;
procedure btnNoExceptionClick(Sender: TObject);
procedure btnRaiseExceptionClick(Sender: TObject);
private
{ Private declarations }
public
procedure Show (const msg: string);
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
type
TObjectWithList = class
private
FStringList: TStringList;
public
constructor Create (Value: Integer);
destructor Destroy; override;
end;
procedure TForm1.btnNoExceptionClick(Sender: TObject);
var
Obj: TObjectWithList;
begin
Obj := TObjectWithList.Create (10);
try
// do something
finally
Show ('Freeing object');
Obj.Free;
end;
end;
procedure TForm1.btnRaiseExceptionClick(Sender: TObject);
var
Obj: TObjectWithList;
begin
Obj := TObjectWithList.Create (-10);
try
// do something
finally
Show ('Freeing object');
Obj.Free;
end;
end;
procedure TForm1.Show(const Msg: string);
begin
Memo1.Lines.Add(Msg);
end;
{ TObjectWithList }
constructor TObjectWithList.Create(Value: Integer);
begin
if Value < 0 then
raise Exception.Create('Negative value not allowed');
FStringList := TStringList.Create;
FStringList.Add('one');
end;
destructor TObjectWithList.Destroy;
begin
// remove the if assinged test to see the error
if Assigned (FStringList) then
begin
FStringList.Clear;
FStringList.Free;
end;
inherited;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ Web server application components }
{ }
{ Copyright (c) 2001-2002 Borland Software Corp. }
{ }
{*******************************************************}
unit DbgSiteAS;
interface
uses SysUtils, Classes, Contnrs, HTTPApp, HTTPProd, AscrLib, ActiveX, ActivDbgLib, WebScript,
WebScriptAs, AutoAdapAS;
type
TTimeoutThread = class;
TBaseDebugScriptSite = class(TActiveScriptSite, IActiveScriptSiteWindow, IDebugDocumentHost, IActiveScriptSiteDebug)
private
FDebugDocumentHelper: IDebugDocumentHelper;
FDebugApplication: IDebugApplication;
FTimeOut: TTimeoutThread;
protected
procedure HandleScriptError(const AErrorDebug: IActiveScriptErrorDebug;
var AEnterDebugger: Boolean); virtual;
function BreakOnFirstStatement: Boolean; virtual;
property DebugDocumentHelper: IDebugDocumentHelper read FDebugDocumentHelper;
property DebugApplication: IDebugApplication read FDebugApplication;
function SetupDebugApplication(var AProcessDebugManager: IProcessDebugManager;
var ADebugApplication: IDebugApplication; var AApplicationCookie: DWord;
AScriptFile: TScriptFile): Boolean;
function SetupDebugDocumentHelper(AProcessDebugManager: IProcessDebugManager;
ADebugApplication: IDebugApplication; DebugDocumentHost: IDebugDocumentHost;
AApplicationCookie: DWord; AScriptFile: TScriptFile): IDebugDocumentHelper;
function SetupDebugScript(AActiveScript: IActiveScript; AScriptFile: TScriptFile;
ADebugDocHelper: IDebugDocumentHelper): DWord;
{ IActiveScriptSiteWindow }
function GetWindow(out phwnd: wireHWND): HResult; stdcall;
function EnableModeless(fEnable: Integer): HResult; stdcall;
{ IDebugDocumentHost }
function GetDeferredText {Flags(1), (5/5) CC:4, INV:1, DBG:6}({VT_19:0}dwTextStartCookie: LongWord;
{VT_2:1}var pcharText: Smallint;
{VT_18:1}var pstaTextAttr: Word;
{VT_19:1}var pcNumChars: LongWord;
{VT_19:0}cMaxChars: LongWord): HResult; stdcall;
function GetScriptTextAttributes {Flags(1), (5/5) CC:4, INV:1, DBG:6}({VT_31:0}pstrCode: PWideChar;
{VT_19:0}uNumCodeChars: LongWord;
{VT_31:0}pstrDelimiter: PWideChar;
{VT_19:0}dwFlags: LongWord;
{VT_18:1}var pattr: Word): HResult; stdcall;
function OnCreateDocumentContext {Flags(1), (1/1) CC:4, INV:1, DBG:6}({VT_13:1}out ppunkOuter: IUnknown): HResult; stdcall;
function GetPathName {Flags(1), (2/2) CC:4, INV:1, DBG:6}({VT_8:1}out pbstrLongName: WideString;
{VT_3:1}out pfIsOriginalFile: Integer): HResult; stdcall;
function GetFileName {Flags(1), (1/1) CC:4, INV:1, DBG:6}({VT_8:1}out pbstrShortName: WideString): HResult; stdcall;
function NotifyChanged {Flags(1), (0/0) CC:4, INV:1, DBG:6}: HResult; stdcall;
{ IActiveScriptSiteDebug }
function GetDocumentContextFromPosition {Flags(1), (4/4) CC:4, INV:1, DBG:6}({VT_19:0}dwSourceContext: LongWord;
{VT_19:0}uCharacterOffset: LongWord;
{VT_19:0}uNumChars: LongWord;
{VT_29:2}out ppsc: IDebugDocumentContext): HResult; stdcall;
function GetApplication {Flags(1), (1/1) CC:4, INV:1, DBG:6}({VT_29:2}out ppda: IDebugApplication): HResult; stdcall;
function GetRootApplicationNode {Flags(1), (1/1) CC:4, INV:1, DBG:6}({VT_29:2}out ppdanRoot: IDebugApplicationNode): HResult; stdcall;
function OnScriptErrorDebug {Flags(1), (3/3) CC:4, INV:1, DBG:6}({VT_29:1}const AErrorDebug: IActiveScriptErrorDebug;
{VT_3:1}out AEnterDebuggerFlag: Integer;
{VT_3:1}out ACallOnScriptErrorWhenContinuingFlag: Integer): HResult; stdcall;
public
procedure RunExpression(AScriptFile: TScriptFile;
AEngine: IInterface); override;
end;
TTimeoutThread = class(TThread)
private
FTimeOutSecs: Integer;
FEndTime: TDateTime;
FEngine: IActiveScript;
FTimedout: Boolean;
public
constructor Create(ATimeoutSecs: Integer; AEngine: IActiveScript);
procedure Execute; override;
property Timedout: Boolean read FTimedout;
end;
function CreateDebugManager: IProcessDebugManager;
implementation
uses ComObj, SiteComp;
{ TTimeoutThread }
constructor TTimeoutThread.Create(ATimeoutSecs: Integer; AEngine: IActiveScript);
begin
FTimeoutSecs := ATimeoutSecs;
FEngine := AEngine;
inherited Create(True { Suspended });
end;
const
SCRIPTTHREADID_BASE = -2;
SCRIPTINTERRUPT_RAISEEXCEPTION = 1;
var
ExcepInfo: TExcepInfo;
procedure TTimeoutThread.Execute;
function IncSecond(const AValue: TDateTime;
const ANumberOfSeconds: Int64): TDateTime;
begin
Result := ((AValue * SecsPerDay) + ANumberOfSeconds) / SecsPerDay;
end;
begin
while not Terminated do
begin
if FEndTime = 0 then
FEndTime := IncSecond(Now, FTimeoutSecs)
else
if Now > FEndTime then
begin
FTimedout := True;
FEngine.InterruptScriptThread(LongWord(SCRIPTTHREADID_BASE), ExcepInfo, SCRIPTINTERRUPT_RAISEEXCEPTION);
Exit;
end;
end;
end;
function TBaseDebugScriptSite.GetWindow(out phwnd: wireHWND): HResult;
begin
{ IActiveScriptSiteWindow }
{ Get design window? }
// phwnd := FForm.Handle;
// Result := S_OK;
Result := S_FALSE;
end;
function TBaseDebugScriptSite.EnableModeless(fEnable: Integer): HResult;
begin
{ IActiveScriptSiteWindow }
Result := S_FALSE;
end;
function TBaseDebugScriptSite.GetDeferredText(dwTextStartCookie: LongWord;
var pcharText: Smallint; var pstaTextAttr: Word;
var pcNumChars: LongWord; cMaxChars: LongWord): HResult;
begin
{ IDebugDocumentHost }
Result := E_NOTIMPL;
end;
function TBaseDebugScriptSite.GetScriptTextAttributes(pstrCode: PWideChar;
uNumCodeChars: LongWord; pstrDelimiter: PWideChar; dwFlags: LongWord;
var pattr: Word): HResult;
begin
{ IDebugDocumentHost }
Result := E_NOTIMPL;
end;
function TBaseDebugScriptSite.OnCreateDocumentContext(
out ppunkOuter: IUnknown): HResult;
begin
{ IDebugDocumentHost }
Result := E_NOTIMPL;
end;
function TBaseDebugScriptSite.GetPathName(out pbstrLongName: WideString;
out pfIsOriginalFile: Integer): HResult;
begin
{ IDebugDocumentHost }
// Provide the full path (including file name) to the document's source file.
// IsOriginalPath is True if the path refers to the original file for the document,
// False if the path refers to a newly created temporary file
// Result is E_FAIL if no source file can be created/determined.
pbstrLongName := 'GetTheLongName';
pfIsOriginalFile := 0; { False }
Result := S_OK;
end;
function TBaseDebugScriptSite.GetFileName(out pbstrShortName: WideString): HResult;
begin
{ IDebugDocumentHost }
// Provide just the name of the document, with no path information.
// (Used for "Save As...")
pbstrShortName := 'GetFileName';
Result := S_OK;
end;
function TBaseDebugScriptSite.NotifyChanged: HResult;
begin
{ IDebugDocumentHost }
// Notify the host that the document's source file has been saved and
// that its contents should be refreshed.
Result := S_OK;
end;
function TBaseDebugScriptSite.GetDocumentContextFromPosition(dwSourceContext,
uCharacterOffset, uNumChars: LongWord;
out ppsc: IDebugDocumentContext): HResult;
var
ulStartPos: LongWord;
temp1: IActiveScript;
temp2: LongWord;
begin
{ IActiveScriptSiteDebug }
if (FDebugDocumentHelper <> nil) then
begin
FDebugDocumentHelper.GetScriptBlockInfo(dwSourceContext, temp1, ulStartPos, temp2);
Result := FDebugDocumentHelper.CreateDebugDocumentContext(ulStartPos + uCharacterOffset, uNumChars, ppsc);
end
else
begin
Result := E_NOTIMPL;
end;
end;
function TBaseDebugScriptSite.GetApplication(out ppda: IDebugApplication): HResult;
begin
{ IActiveScriptSiteDebug }
ppda := FDebugApplication;
Result := S_OK;
end;
function TBaseDebugScriptSite.GetRootApplicationNode(
out ppdanRoot: IDebugApplicationNode): HResult;
begin
{ IActiveScriptSiteDebug }
if FDebugDocumentHelper <> nil then
begin
Result := FDebugDocumentHelper.GetDebugApplicationNode(ppdanRoot);
end
else
Result := E_NOTIMPL;
end;
procedure TBaseDebugScriptSite.HandleScriptError(
const AErrorDebug: IActiveScriptErrorDebug; var AEnterDebugger: Boolean);
begin
GlobalObjects.Producer.HandleScriptError(AErrorDebug);
end;
function TBaseDebugScriptSite.OnScriptErrorDebug(
const AErrorDebug: IActiveScriptErrorDebug; out AEnterDebuggerFlag,
ACallOnScriptErrorWhenContinuingFlag: Integer): HResult;
var
EnterDebugger: Boolean;
begin
{ IActiveScriptSiteDebug }
if FTimeout <> nil then
FTimeout.Terminate;
ACallOnScriptErrorWhenContinuingFlag := 0;
EnterDebugger := True;
HandleScriptError(AErrorDebug, EnterDebugger);
if EnterDebugger then
AEnterDebuggerFlag := 1
else
AEnterDebuggerFlag := 0;
Result := S_OK;
end;
function TBaseDebugScriptSite.SetupDebugScript(AActiveScript: IActiveScript; AScriptFile: TScriptFile; ADebugDocHelper: IDebugDocumentHelper): DWord;
var
hr: HRESULT;
SourceContext: DWord;
S: string;
begin
S := AScriptFile.Source;
hr := ADebugDocHelper.AddDBCSText(PChar(S));
if (FAILED(hr)) then
Assert(False, 'AddDBCSText failed');
SourceContext := 0;
ADebugDocHelper.DefineScriptBlock(0, Length(S), AActiveScript, 0 { False }, SourceContext);
Result := SourceContext;
end;
function TBaseDebugScriptSite.SetupDebugDocumentHelper(AProcessDebugManager: IProcessDebugManager;
ADebugApplication: IDebugApplication; DebugDocumentHost: IDebugDocumentHost;
AApplicationCookie: DWord; AScriptFile: TScriptFile): IDebugDocumentHelper;
var
DebugDocHelper: IDebugDocumentHelper;
hr: HRESULT;
begin
// XX ActiveX Scripting with debug support XX
Assert(DebugDocHelper = nil);
hr := AProcessDebugManager.CreateDebugDocumentHelper(nil, DebugDocHelper);
if FAILED(hr) then
Assert(False, 'Could not create debug document helper');
Assert(DebugDocHelper <> nil);
hr := DebugDocHelper.Init(ADebugApplication,PWideChar(WideString(AScriptFile.ShortName)), PWideChar(WideString(AScriptFile.LongName)), TEXT_DOC_ATTR_READONLY);
if FAILED(hr) then
Assert(False, 'Could not init debug document helper');
hr := DebugDocHelper.Attach(nil);
if FAILED(hr) then
Assert(False, 'Could not attach debug document helper');
hr := DebugDocHelper.SetDocumentAttr(TEXT_DOC_ATTR_READONLY);
if FAILED(hr) then
Assert(False, 'Could not setdocumentattr');
// this step is optional but it deosn't require much effort to perform
hr := DebugDocHelper.SetDebugDocumentHost(DebugDocumentHost);
if FAILED(hr) then
Assert(False, 'Could not set debug document host');
Result := DebugDocHelper;
end;
function CreateDebugManager: IProcessDebugManager;
var
ClsID: TGuid;
hr: HRESULT;
begin
CLSIDFromProgID('ProcessDebugManager.ProcessDebugManager', ClsID);
hr := CoCreateInstance(ClsID, nil, CLSCTX_INPROC_SERVER or CLSCTX_LOCAL_SERVER,
IProcessDebugManager, Result);
if FAILED(hr) then
begin
CLSIDFromProgID('ProcessDebugManager', ClsID);
hr := CoCreateInstance(ClsID, nil, CLSCTX_INPROC_SERVER or CLSCTX_LOCAL_SERVER,
IProcessDebugManager, Result);
if FAILED(hr) then
Result := nil;
end
end;
function TBaseDebugScriptSite.SetupDebugApplication(var AProcessDebugManager: IProcessDebugManager; var ADebugApplication: IDebugApplication;
var AApplicationCookie: DWord; AScriptFile: TScriptFile): Boolean;
var
hr: HRESULT;
begin
try
AProcessDebugManager := CreateDebugManager;
if AProcessDebugManager = nil then
begin
Result := False;
Assert(False, 'Could not create process debug manager');
end
else
begin
hr := AProcessDebugManager.CreateApplication(ADebugApplication);
if FAILED(hr) then
Assert(False, 'Could not create debug application');
hr := ADebugApplication.SetName(PWideChar(WideString(AScriptFile.ApplicationName)));
if FAILED(hr) then
Assert(False, 'Could not set debug app name');
hr := AProcessDebugManager.AddApplication(ADebugApplication, AApplicationCookie);
if FAILED(hr) then
Assert(False, 'Could not add application');
Result := True;
end
except
if ADebugApplication <> nil then
begin
AProcessDebugManager.RemoveApplication(AApplicationCookie);
ADebugApplication.Close();
end;
ADebugApplication := nil;
AProcessDebugManager := nil;
Result := False;
end;
end;
resourcestring
sCouldNotInitializeDebugger = 'Initialization of script debugger failed. Verify that a script debugger is installed';
sScriptTimedout = 'Script execution timed out after %d seconds';
procedure TBaseDebugScriptSite.RunExpression(AScriptFile: TScriptFile;
AEngine: IInterface);
procedure TimeoutError(TimeoutSecs: Integer);
begin
with GlobalObjects.Producer.Errors do
if (Count > 0) and (Errors[Count-1].Description = '') then
Errors[Count-1].Description := Format(sScriptTimedOut, [TimeoutSecs])
else
raise EActiveScriptError.CreateFmt(sScriptTimedOut, [TimeoutSecs])
end;
var
ExcepInfo: TExcepInfo;
ActiveScriptParse: IActiveScriptParse;
hr: HRESULT;
I: Integer;
SourceContext: DWord;
ProcessDebugManager: IProcessDebugManager;
ApplicationCookie: DWord;
ScriptSite: TActiveScriptSite;
SaveScriptSite: IUnknown;
TimeoutSecs: Integer;
Engine: IActiveScript;
begin
Engine := AEngine as IActiveScript;
if InternetEnvOptions <> nil then
TimeoutSecs := InternetEnvOptions.ScriptTimeoutSecs
else
TimeoutSecs := 0;
try
if not SetupDebugApplication(ProcessDebugManager, FDebugApplication, ApplicationCookie, AScriptFile) then
begin
if BreakOnFirstStatement then
raise EActiveScriptError.Create(sCouldNotInitializeDebugger)
else
begin
// Use non debug script site
ScriptSite := TActiveScriptSite.Create(GlobalObjects.Producer);
SaveScriptSite := ScriptSite;
if TimeoutSecs > 0 then
begin
FTimeout := TTimeOutThread.Create(TimeoutSecs, Engine);
try
FTimeout.Resume;
ScriptSite.RunExpression(AScriptFile, Engine);
if FTimeout.Timedout then
TimeoutError(TimeoutSecs);
finally
FTimeout.Terminate;
FreeAndNil(FTimeout);
end;
end
else
ScriptSite.RunExpression(AScriptFile, AEngine);
Exit;
end;
end;
//Now query for the IActiveScriptParse interface of the engine
hr := AEngine.QueryInterface(IActiveScriptParse, ActiveScriptParse);
OLECHECK(hr);
//The engine needs to know the host it runs on.
hr := Engine.SetScriptSite(Self);
OLECHECK(hr);
//Initialize the script engine so it's ready to run.
hr := ActiveScriptParse.InitNew();
OLECHECK(hr);
for I := 0 to GlobalObjects.NamedItemCount - 1 do
Engine.AddNamedItem(PWideChar(WideString(GlobalObjects.NamedItemName[I])), SCRIPTITEM_ISVISIBLE);
FDebugDocumentHelper := SetupDebugDocumentHelper(ProcessDebugManager, FDebugApplication, Self,
ApplicationCookie, AScriptFile);
SourceContext := SetupDebugScript(Engine, AScriptFile, FDebugDocumentHelper);
hr := ActiveScriptParse.ParseScriptText(PWideChar(WideString(AScriptFile.Script)), nil {sScriptMain}, nil, nil,
SourceContext, 0, 0, { VariantResult }nil, ExcepInfo);
// hr <> S_OK means that an error occured. FErrors should
// contain the error
Assert((hr = S_OK) or (GlobalObjects.Producer.Errors.Count > 0), 'Errors expected');
if BreakOnFirstStatement then
begin
FDebugDocumentHelper.BringDocumentToTop();
hr := FDebugApplication.CauseBreak();
if (FAILED(hr)) then
Assert(False,'Error causing break point');
end;
if hr = S_OK then
begin
if (TimeoutSecs > 0) and not BreakOnFirstStatement then
begin
FTimeout := TTimeOutThread.Create(TimeoutSecs, Engine);
try
FTimeout.Resume;
hr := Engine.SetScriptState(SCRIPTSTATE_CONNECTED);
if FTimeout.Timedout then
TimeoutError(TimeoutSecs);
finally
FTimeout.Terminate;
FreeAndNil(FTimeout);
end
end
else
hr := Engine.SetScriptState(SCRIPTSTATE_CONNECTED);
// hr <> S_OK means that an error occured. FErrors should
// contain the error
Assert((hr = S_OK) or (GlobalObjects.Producer.Errors.Count > 0), 'Errors expected');
end;
finally
if FDebugDocumentHelper <> nil then
begin
hr := FDebugDocumentHelper.Detach;
if (FAILED(hr)) then
Assert(False, 'Error detaching document helper');
end;
if ProcessDebugManager <> nil then
begin
hr := ProcessDebugManager.RemoveApplication(ApplicationCookie);
if (FAILED(hr)) then
Assert(False, 'Error removing application helper');
end;
if FDebugApplication <> nil then
begin
hr := FDebugApplication.Close();
if (FAILED(hr)) then
Assert(False, 'Error closing debug application');
end;
FDebugDocumentHelper := nil;
end;
end;
function TBaseDebugScriptSite.BreakOnFirstStatement: Boolean;
begin
Result := False;
end;
end.
|
(* umenu.pas -- (c) 1989 by Tom Swan *)
unit umenu;
interface
uses crt, ukeys, uitem, ucmds, ulist;
type
menuPtr = ^menu;
menu = object( list )
menuRow, menuCol : word; { Menu command-line location }
menuTitle : ^string; { Menu name string }
menuDisplay : ^string; { Menu commands string }
menuAttr : word; { Display attribute }
constructor init( col, row : word; title : string; attr : word );
destructor done; virtual;
function menuStr : string;
function getMenuAttr : Word;
function getMenuRow : Word;
function getMenuCol : Word;
procedure displayMenu; virtual;
procedure beforeCommand; virtual;
procedure afterCommand; virtual;
procedure performCommands; virtual;
{ ----- Replacement methods inherited from list object. }
procedure insertItem( ip : ItemPtr ); virtual;
procedure removeItem( ip : ItemPtr ); virtual;
end;
implementation
const
ESC = #27; { ASCII escape char }
{ ----- Initialize a new menu command list. }
constructor menu.init( col, row : word; title : string; attr : word );
begin
menuRow := row;
menuCol := col;
menuAttr := attr;
menuDisplay := nil; { Created by menu.menuStr }
getMem( menuTitle, length( title ) + 1 );
if menuTitle = nil then
begin
fail;
done;
end else
menuTitle^ := title;
list.init;
end;
{ ----- Dispose of a menu command list. }
destructor menu.done;
begin
if menuTitle <> nil then
begin
freeMem( menuTitle, length( menuTitle^ ) + 1 );
menuTitle := nil;
end;
if menuDisplay <> nil then
begin
freeMem( menuDisplay, length( menuDisplay^ ) + 1 );
menuDisplay := nil;
end;
list.done;
end;
{ ----- Create and/or return current menu string. }
function menu.menuStr : string;
var
s1, s2 : string[80];
begin
if menuDisplay = nil then
begin
s1 := ''; { Null string }
if not listEmpty then
begin
resetList;
repeat
s2 := commandPtr( currentItem )^.getstring;
if length( s2 ) > 0
then s1 := s1 + ' ' + s2; { Add command to s1 }
nextItem;
until atHeadOfList;
end;
getMem( menuDisplay, length( s1 ) + 1 );
if menuDisplay <> nil
then menuDisplay^ := s1;
end else
s1 := menuDisplay^;
if menuTitle <> nil
then s1 := menuTitle^ + s1;
menuStr := s1;
end;
{ ----- Return menu attribute word. }
function menu.getMenuAttr : Word;
begin
getMenuAttr := menuAttr;
end;
{ ----- Return menu row. }
function menu.getMenuRow : Word;
begin
getMenuRow := menuRow;
end;
{ ----- Return menu column. }
function menu.getMenuCol : Word;
begin
getMenuCol := menuCol;
end;
{ ----- Display the menu name and command strings. }
procedure menu.displayMenu;
var
oldAttr : word; { For saving current attribute }
begin
oldAttr := textAttr;
textAttr := menuAttr;
gotoxy( menuCol, menuRow );
write( menuStr );
clreol;
textAttr := oldAttr;
end;
{ ----- Called at the top of the menu.performCommands repeat loop,
providing host programs a way to hook into the keyboard polling loop.
Optionally replaced by host program's menu object. }
procedure menu.beforeCommand;
begin
end;
{ ----- Called after menu.duringCommand. Optionally replaced by host
program's menu object. Note: you may use this procedure to modify the
menu list, allowing one command to alter the availability of other
commands. }
procedure menu.afterCommand;
begin
displayMenu; { Usually a good idea }
end;
{ ----- Process commands in menu list. Guaranteed to return upon
pressing <Esc>. Repeatedly calls beforeCommand while polling keyboard
for input. Calls afterCommand after processing a selected command in
the menu list. }
procedure menu.performCommands;
var
ch : char;
begin
displayMenu; { Display menu name and commands }
ch := chr( 0 ); { Initialize ch to null }
repeat
beforeCommand; { Activate host polling hook }
if keyWaiting then
begin
ch := upcase( getKey );
if ch <> ESC then
begin
resetList;
if not listEmpty then
repeat
if ch = commandPtr( currentItem )^.getcmdCh then
begin
currentItem^.processItem; { Perform command }
resetList; { Force loop to end }
afterCommand; { Host post-cmd hook }
end else
nextItem;
until atHeadOfList;
end;
end;
until ch = ESC; { Until <Esc> pressed or forced }
end;
{ ----- Insert a new command into menu. Parameter ip must address a
command object as defined in ucmds.pas. Also dispose of the current
menu display string if neccessary, as these are invalid after new
commands are added to the list. }
procedure menu.insertItem( ip : ItemPtr );
begin
if menuDisplay <> nil then
begin
freeMem( menuDisplay, length( menuDisplay^ ) + 1 );
menuDisplay := nil;
end;
list.insertItem( ip );
end;
{ ----- Delete a single command from the menu. Parameter ip should
address a command object (or a descendant). Also dispose the current
menu display string. }
procedure menu.removeItem( ip : ItemPtr );
begin
if menuDisplay <> nil then
begin
freeMem( menuDisplay, length( menuDisplay^ ) + 1 );
menuDisplay := nil;
end;
list.removeItem( ip );
end;
end.
|
{*******************************************************}
{ }
{ Delphi Text DataSet Sample }
{ }
{ Copyright (c) 1997,98 Borland International }
{ }
{*******************************************************}
unit TextData;
{
This file contains a very basic TDataSet implementation which works with
text files. For simplicity, the text file is interpreted as a single column,
multiple row table.
Currently, the notes in this source file represent the only documnentation
on how to create a TDataSet implentation. For more information you can
refer to TBDEDataSet in DBTABLES.PAS which represents a complete TDataSet
implementation and provides a good example of what methods can be overridden
and what they should do.
Any TDataSet implementation must provide Bookmark capabilities and
implement all functions which directly access the record buffer. The base
TDataSet manages a group of record buffers, but has no requirements regarding
what is contained in each record buffer. The base TDataSet also manages
the communcation with any attached TDataSource components and the respective
data aware controls.
}
interface
uses
DB, Classes;
const
MaxStrLen = 240; { This is an arbitrary limit }
type
{ TRecInfo }
{ This structure is used to access additional information stored in
each record buffer which follows the actual record data.
Buffer: PChar;
||
\/
--------------------------------------------
| Record Data | Bookmark | Bookmark Flag |
--------------------------------------------
^-- PRecInfo = Buffer + FRecInfoOfs
Keep in mind that this is just an example of how the record buffer
can be used to store additional information besides the actual record
data. There is no requirement that TDataSet implementations do it this
way.
For the purposes of this demo, the bookmark format used is just an integer
value. For an actual implementation the bookmark would most likely be
a native bookmark type (as with BDE), or a fabricated bookmark for
data providers which do not natively support bookmarks (this might be
a variant array of key values for instance).
The BookmarkFlag is used to determine if the record buffer contains a
valid bookmark and has special values for when the dataset is positioned
on the "cracks" at BOF and EOF. }
PRecInfo = ^TRecInfo;
TRecInfo = packed record
Bookmark: Integer;
BookmarkFlag: TBookmarkFlag;
end;
{ TTextDataSet }
TTextDataSet = class(TDataSet)
private
FData: TStrings;
FRecBufSize: Integer;
FRecInfoOfs: Integer;
FCurRec: Integer;
FFileName: string;
FLastBookmark: Integer;
FSaveChanges: Boolean;
protected
{ Overriden abstract methods (required) }
function AllocRecordBuffer: PChar; override;
procedure FreeRecordBuffer(var Buffer: PChar); override;
procedure GetBookmarkData(Buffer: PChar; Data: Pointer); override;
function GetBookmarkFlag(Buffer: PChar): TBookmarkFlag; override;
function GetRecord(Buffer: PChar; GetMode: TGetMode; DoCheck: Boolean): TGetResult; override;
function GetRecordSize: Word; override;
procedure InternalAddRecord(Buffer: Pointer; Append: Boolean); override;
procedure InternalClose; override;
procedure InternalDelete; override;
procedure InternalFirst; override;
procedure InternalGotoBookmark(Bookmark: Pointer); override;
procedure InternalHandleException; override;
procedure InternalInitFieldDefs; override;
procedure InternalInitRecord(Buffer: PChar); override;
procedure InternalLast; override;
procedure InternalOpen; override;
procedure InternalPost; override;
procedure InternalSetToRecord(Buffer: PChar); override;
function IsCursorOpen: Boolean; override;
procedure SetBookmarkFlag(Buffer: PChar; Value: TBookmarkFlag); override;
procedure SetBookmarkData(Buffer: PChar; Data: Pointer); override;
procedure SetFieldData(Field: TField; Buffer: Pointer); override;
protected
{ Additional overrides (optional) }
function GetRecordCount: Integer; override;
function GetRecNo: Integer; override;
procedure SetRecNo(Value: Integer); override;
public
function GetFieldData(Field: TField; Buffer: Pointer): Boolean; override;
published
property FileName: string read FFileName write FFileName;
property Active;
end;
procedure Register;
implementation
uses Windows, SysUtils, Forms;
{ TTextDataSet }
{ This method is called by TDataSet.Open and also when FieldDefs need to
be updated (usually by the DataSet designer). Everything which is
allocated or initialized in this method should also be freed or
uninitialized in the InternalClose method. }
procedure TTextDataSet.InternalOpen;
var
I: Integer;
begin
{ Load the textfile into a stringlist }
FData := TStringList.Create;
FData.LoadFromFile(FileName);
{ Fabricate integral bookmark values }
for I := 1 to FData.Count do
FData.Objects[I-1] := Pointer(I);
FLastBookmark := FData.Count;
{ Initialize our internal position.
We use -1 to indicate the "crack" before the first record. }
FCurRec := -1;
{ Initialize an offset value to find the TRecInfo in each buffer }
FRecInfoOfs := MaxStrLen;
{ Calculate the size of the record buffers.
Note: This is NOT the same as the RecordSize property which
only gets the size of the data in the record buffer }
FRecBufSize := FRecInfoOfs + SizeOf(TRecInfo);
{ Tell TDataSet how big our Bookmarks are (REQUIRED) }
BookmarkSize := SizeOf(Integer);
{ Initialize the FieldDefs }
InternalInitFieldDefs;
{ Create TField components when no persistent fields have been created }
if DefaultFields then CreateFields;
{ Bind the TField components to the physical fields }
BindFields(True);
end;
procedure TTextDataSet.InternalClose;
begin
{ Write any edits to disk and free the managing string list }
if FSaveChanges then FData.SaveToFile(FileName);
FData.Free;
FData := nil;
{ Destroy the TField components if no persistent fields }
if DefaultFields then DestroyFields;
{ Reset these internal flags }
FLastBookmark := 0;
FCurRec := -1;
end;
{ This property is used while opening the dataset.
It indicates if data is available even though the
current state is still dsInActive. }
function TTextDataSet.IsCursorOpen: Boolean;
begin
Result := Assigned(FData);
end;
{ For this simple example we just create one FieldDef, but a more complete
TDataSet implementation would create multiple FieldDefs based on the
actual data. }
procedure TTextDataSet.InternalInitFieldDefs;
begin
FieldDefs.Clear;
FieldDefs.Add('Line', ftString, MaxStrLen, False);
end;
{ This is the exception handler which is called if an exception is raised
while the component is being stream in or streamed out. In most cases this
should be implemented useing the application exception handler as follows. }
procedure TTextDataSet.InternalHandleException;
begin
Application.HandleException(Self);
end;
{ Bookmarks }
{ ========= }
{ In this sample the bookmarks are stored in the Object property of the
TStringList holding the data. Positioning to a bookmark just requires
finding the offset of the bookmark in the TStrings.Objects and using that
value as the new current record pointer. }
procedure TTextDataSet.InternalGotoBookmark(Bookmark: Pointer);
var
Index: Integer;
begin
Index := FData.IndexOfObject(TObject(PInteger(Bookmark)^));
if Index <> -1 then
FCurRec := Index else
DatabaseError('Bookmark not found');
end;
{ This function does the same thing as InternalGotoBookmark, but it takes
a record buffer as a parameter instead }
procedure TTextDataSet.InternalSetToRecord(Buffer: PChar);
begin
InternalGotoBookmark(@PRecInfo(Buffer + FRecInfoOfs).Bookmark);
end;
{ Bookmark flags are used to indicate if a particular record is the first
or last record in the dataset. This is necessary for "crack" handling.
If the bookmark flag is bfBOF or bfEOF then the bookmark is not actually
used; InternalFirst, or InternalLast are called instead by TDataSet. }
function TTextDataSet.GetBookmarkFlag(Buffer: PChar): TBookmarkFlag;
begin
Result := PRecInfo(Buffer + FRecInfoOfs).BookmarkFlag;
end;
procedure TTextDataSet.SetBookmarkFlag(Buffer: PChar; Value: TBookmarkFlag);
begin
PRecInfo(Buffer + FRecInfoOfs).BookmarkFlag := Value;
end;
{ These methods provide a way to read and write bookmark data into the
record buffer without actually repositioning the current record }
procedure TTextDataSet.GetBookmarkData(Buffer: PChar; Data: Pointer);
begin
PInteger(Data)^ := PRecInfo(Buffer + FRecInfoOfs).Bookmark;
end;
procedure TTextDataSet.SetBookmarkData(Buffer: PChar; Data: Pointer);
begin
PRecInfo(Buffer + FRecInfoOfs).Bookmark := PInteger(Data)^;
end;
{ Record / Field Access }
{ ===================== }
{ This method returns the size of just the data in the record buffer.
Do not confuse this with RecBufSize which also includes any additonal
structures stored in the record buffer (such as TRecInfo). }
function TTextDataSet.GetRecordSize: Word;
begin
Result := MaxStrLen;
end;
{ TDataSet calls this method to allocate the record buffer. Here we use
FRecBufSize which is equal to the size of the data plus the size of the
TRecInfo structure. }
function TTextDataSet.AllocRecordBuffer: PChar;
begin
GetMem(Result, FRecBufSize);
end;
{ Again, TDataSet calls this method to free the record buffer.
Note: Make sure the value of FRecBufSize does not change before all
allocated buffers are freed. }
procedure TTextDataSet.FreeRecordBuffer(var Buffer: PChar);
begin
FreeMem(Buffer, FRecBufSize);
end;
{ This multi-purpose function does 3 jobs. It retrieves data for either
the current, the prior, or the next record. It must return the status
(TGetResult), and raise an exception if DoCheck is True. }
function TTextDataSet.GetRecord(Buffer: PChar; GetMode: TGetMode;
DoCheck: Boolean): TGetResult;
begin
if FData.Count < 1 then
Result := grEOF else
begin
Result := grOK;
case GetMode of
gmNext:
if FCurRec >= RecordCount - 1 then
Result := grEOF else
Inc(FCurRec);
gmPrior:
if FCurRec <= 0 then
Result := grBOF else
Dec(FCurRec);
gmCurrent:
if (FCurRec < 0) or (FCurRec >= RecordCount) then
Result := grError;
end;
if Result = grOK then
begin
StrLCopy(Buffer, PChar(FData[FCurRec]), MaxStrLen);
with PRecInfo(Buffer + FRecInfoOfs)^ do
begin
BookmarkFlag := bfCurrent;
Bookmark := Integer(FData.Objects[FCurRec]);
end;
end else
if (Result = grError) and DoCheck then DatabaseError('No Records');
end;
end;
{ This routine is called to initialize a record buffer. In this sample,
we fill the buffer with zero values, but we might have code to initialize
default values or do other things as well. }
procedure TTextDataSet.InternalInitRecord(Buffer: PChar);
begin
FillChar(Buffer^, RecordSize, 0);
end;
{ Here we copy the data from the record buffer into a field's buffer.
This function, and SetFieldData, are more complex when supporting
calculated fields, filters, and other more advanced features.
See TBDEDataSet for a more complete example. }
function TTextDataSet.GetFieldData(Field: TField; Buffer: Pointer): Boolean;
begin
StrLCopy(Buffer, ActiveBuffer, Field.Size);
Result := PChar(Buffer)^ <> #0;
end;
procedure TTextDataSet.SetFieldData(Field: TField; Buffer: Pointer);
begin
StrLCopy(ActiveBuffer, Buffer, Field.Size);
DataEvent(deFieldChange, Longint(Field));
end;
{ Record Navigation / Editing }
{ =========================== }
{ This method is called by TDataSet.First. Crack behavior is required.
That is we must position to a special place *before* the first record.
Otherwise, we will actually end up on the second record after Resync
is called. }
procedure TTextDataSet.InternalFirst;
begin
FCurRec := -1;
end;
{ Again, we position to the crack *after* the last record here. }
procedure TTextDataSet.InternalLast;
begin
FCurRec := FData.Count;
end;
{ This method is called by TDataSet.Post. Most implmentations would write
the changes directly to the associated datasource, but here we simply set
a flag to write the changes when we close the dateset. }
procedure TTextDataSet.InternalPost;
begin
FSaveChanges := True;
{ For inserts, just update the data in the string list }
if State = dsEdit then FData[FCurRec] := ActiveBuffer else
begin
{ If inserting (or appending), increment the bookmark counter and
store the data }
Inc(FLastBookmark);
FData.InsertObject(FCurRec, ActiveBuffer, Pointer(FLastBookmark));
end;
end;
{ This method is similar to InternalPost above, but the operation is always
an insert or append and takes a pointer to a record buffer as well. }
procedure TTextDataSet.InternalAddRecord(Buffer: Pointer; Append: Boolean);
begin
FSaveChanges := True;
Inc(FLastBookmark);
if Append then InternalLast;
FData.InsertObject(FCurRec, PChar(Buffer), Pointer(FLastBookmark));
end;
{ This method is called by TDataSet.Delete to delete the current record }
procedure TTextDataSet.InternalDelete;
begin
FSaveChanges := True;
FData.Delete(FCurRec);
if FCurRec >= FData.Count then
Dec(FCurRec);
end;
{ Optional Methods }
{ ================ }
{ The following methods are optional. When provided they will allow the
DBGrid and other data aware controls to track the current cursor postion
relative to the number of records in the dataset. Because we are dealing
with a small, static data store (a stringlist), these are very easy to
implement. However, for many data sources (SQL servers), the concept of
record numbers and record counts do not really apply. }
function TTextDataSet.GetRecordCount: Longint;
begin
Result := FData.Count;
end;
function TTextDataSet.GetRecNo: Longint;
begin
UpdateCursorPos;
if (FCurRec = -1) and (RecordCount > 0) then
Result := 1 else
Result := FCurRec + 1;
end;
procedure TTextDataSet.SetRecNo(Value: Integer);
begin
if (Value >= 0) and (Value < FData.Count) then
begin
FCurRec := Value - 1;
Resync([]);
end;
end;
{ This procedure is used to register this component on the component palette }
procedure Register;
begin
RegisterComponents('Data Access', [TTextDataSet]);
end;
end.
|
unit Tests.DialogListener;
interface
uses
DUnitX.TestFramework;
type
TTestDialogListenerBase = class(TObject)
public
[TEST]
procedure TestDialog; virtual;
[TEST]
procedure TestDialogCallback; virtual;
end;
[TestFixture]
TTestDialogListenerFMX = class(TTestDialogListenerBase)
public
[SetupFixture]
procedure Setup;
[TearDownFixture]
procedure TearDown;
end;
type
[TestFixture]
TTestDialogListenerVCL = class(TTestDialogListenerBase)
public
[SetupFixture]
procedure Setup;
[TearDownFixture]
procedure TearDown;
end;
implementation
uses
System.Messaging,
DX.Messages.Dialog,
DX.Messages.Dialog.Listener.FMX,
DX.Messages.Dialog.Listener.VCL, DX.Messages.Dialog.Types;
{ TTestDialogListenerFMX }
procedure TTestDialogListenerFMX.Setup;
begin
DX.Messages.Dialog.Listener.FMX.TMessageDialogListener.Register;
end;
procedure TTestDialogListenerFMX.TearDown;
begin
DX.Messages.Dialog.Listener.FMX.TMessageDialogListener.UnRegister;
end;
{ TTestDialogListenerVCL }
procedure TTestDialogListenerVCL.Setup;
begin
DX.Messages.Dialog.Listener.VCL.TMessageDialogListener.Register;
end;
procedure TTestDialogListenerVCL.TearDown;
begin
DX.Messages.Dialog.Listener.VCL.TMessageDialogListener.UnRegister;
end;
{ TTestDialogListenerBase }
procedure TTestDialogListenerBase.TestDialog;
var
LMessage: TMessageDialogRequest;
LResult: TDialogOption;
begin
LMessage := TMessageDialogRequest.Create('Test: Press OK', [TDialogOption.OK, TDialogOption.cancel]);
LMessage.Default := TDialogOption.Cancel;
TMessageManager.DefaultManager.SendMessage(self, LMessage);
LResult := LMessage.Response;
Assert.IsTrue(LResult = TDialogOption.OK);
end;
procedure TTestDialogListenerBase.TestDialogCallback;
var
LMessage: TMessageDialogRequest;
LResult: TDialogOption;
begin
LMessage := TMessageDialogRequest.Create('Test: Press OK', [TDialogOption.OK, TDialogOption.cancel]);
LMessage.Default := TDialogOption.Cancel;
//This is only suitable for synchronous message handling.
//Tessing async messages, requires some sort of a busy loop here
TMessageManager.DefaultManager.SendMessage(self, LMessage.OnResult(
procedure(AResult: TDialogOption)
begin
LResult := LMessage.Response;
Assert.IsTrue(LResult = TDialogOption.OK);
end));
end;
initialization
TDUnitX.RegisterTestFixture(TTestDialogListenerFMX);
TDUnitX.RegisterTestFixture(TTestDialogListenerVCL);
end.
|
unit BCEditor.Editor.RightMargin;
interface
uses
Classes, Graphics, Controls, BCEditor.Editor.RightMargin.Colors, BCEditor.Types;
type
TBCEditorRightMargin = class(TPersistent)
strict private
FColors: TBCEditorRightMarginColors;
FCursor: TCursor;
FMouseOver: Boolean;
FMoving: Boolean;
FOnChange: TNotifyEvent;
FOptions: TBCEditorRightMarginOptions;
FPosition: Integer;
FVisible: Boolean;
procedure DoChange;
procedure SetColors(const Value: TBCEditorRightMarginColors);
procedure SetOnChange(Value: TNotifyEvent);
procedure SetPosition(const Value: Integer);
procedure SetVisible(const Value: Boolean);
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
property Moving: Boolean read FMoving write FMoving;
property MouseOver: Boolean read FMouseOver write FMouseOver;
published
property Colors: TBCEditorRightMarginColors read FColors write SetColors;
property Cursor: TCursor read FCursor write FCursor default crHSplit;
property OnChange: TNotifyEvent read FOnChange write SetOnChange;
property Options: TBCEditorRightMarginOptions read FOptions write FOptions default [rmoMouseMove, rmoShowMovingHint];
property Position: Integer read FPosition write SetPosition;
property Visible: Boolean read FVisible write SetVisible;
end;
implementation
{ TBCEditorRightMargin }
constructor TBCEditorRightMargin.Create;
begin
inherited;
FVisible := True;
FPosition := 80;
FColors := TBCEditorRightMarginColors.Create;
FOptions := [rmoMouseMove, rmoShowMovingHint];
FMoving := False;
FMouseOver := False;
FCursor := crHSplit;
end;
destructor TBCEditorRightMargin.Destroy;
begin
FColors.Free;
inherited;
end;
procedure TBCEditorRightMargin.SetOnChange(Value: TNotifyEvent);
begin
FOnChange := Value;
FColors.OnChange := Value;
end;
procedure TBCEditorRightMargin.Assign(Source: TPersistent);
begin
if Assigned(Source) and (Source is TBCEditorRightMargin) then
with Source as TBCEditorRightMargin do
begin
Self.FVisible := FVisible;
Self.FPosition := FPosition;
Self.FColors.Assign(fColors);
Self.FOptions := FOptions;
Self.FCursor := FCursor;
Self.DoChange;
end
else
inherited Assign(Source);
end;
procedure TBCEditorRightMargin.DoChange;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TBCEditorRightMargin.SetColors(const Value: TBCEditorRightMarginColors);
begin
FColors.Assign(Value);
end;
procedure TBCEditorRightMargin.SetPosition(const Value: Integer);
begin
if FPosition <> Value then
begin
FPosition := Value;
DoChange
end;
end;
procedure TBCEditorRightMargin.SetVisible(const Value: Boolean);
begin
if FVisible <> Value then
begin
FVisible := Value;
DoChange
end;
end;
end.
|
unit fIdentificationOptions;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, fOptionsBase, StdCtrls;
type
TIdentificationOptionsFrame = class(TOptionsBaseFrame)
Label1: TLabel;
NickEdit: TEdit;
Label2: TLabel;
AltNickEdit: TEdit;
Label3: TLabel;
RealNameEdit: TEdit;
Label4: TLabel;
UserNameEdit: TEdit;
public
function Save: Boolean; override;
procedure Load; override;
end;
implementation
uses IniFiles, uConst;
{$R *.dfm}
{ TIdentificationOptionsFrame }
procedure TIdentificationOptionsFrame.Load;
var
IniFile: TIniFile;
begin
IniFile := TIniFile.Create(SettingsFilePath);
try
NickEdit.Text := IniFile.ReadString(IdentificationSection, NickNameIdent, '');
AltNickEdit.Text := IniFile.ReadString(IdentificationSection, AltNickIdent, '');
RealNameEdit.Text := IniFile.ReadString(IdentificationSection, RealNameIdent, '');
UserNameEdit.Text := IniFile.ReadString(IdentificationSection, UserNameIdent, '');
finally
IniFile.Free;
end;
end;
function TIdentificationOptionsFrame.Save: Boolean;
var
IniFile: TIniFile;
begin
IniFile := TIniFile.Create(SettingsFilePath);
try
IniFile.WriteString(IdentificationSection, NickNameIdent, NickEdit.Text);
IniFile.WriteString(IdentificationSection, AltNickIdent, AltNickEdit.Text);
IniFile.WriteString(IdentificationSection, RealNameIdent, RealNameEdit.Text);
IniFile.WriteString(IdentificationSection, UserNameIdent, UserNameEdit.Text);
finally
IniFile.Free;
end;
Result := True;
end;
end.
|
program TestEnums;
type
Days = (Sun, Mon, Tue, Wed, Thu, Fri, Sat);
var day : Days;
begin
WriteLn('Mon < Fri: ', Mon < Fri);
day := Tue;
WriteLn('Fri < day: ', Fri < day);
end.
|
unit FC.Trade.Trainer.CloseOrderDialog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufmDialogOKCancel_B, ActnList, StdCtrls, ExtendControls, ExtCtrls,
FC.Trade.TrainerDialog, Mask,
StockChart.Definitions, FC.Definitions;
type
TfmTrainerCloseOrderDialog = class(TfmDialogOkCancel_B)
edComment: TExtendEdit;
laCommentTitle: TLabel;
Label8: TLabel;
laSymbol: TLabel;
laPrice: TLabel;
laPriceValue: TLabel;
laProfit: TLabel;
Label2: TLabel;
procedure acOKExecute(Sender: TObject);
private
FTrader: TStockTraderTrainer;
FOpenedOrder: IStockOrder;
public
property OpenedOrder: IStockOrder read FOpenedOrder write FOpenedOrder;
property Trader : TStockTraderTrainer read FTrader;
constructor Create(const aTrader: TStockTraderTrainer; aOrder: IStockorder); reintroduce;
destructor Destroy; override;
end;
implementation
uses Math, Baseutils, SystemService, FC.Datautils, FC.Trade.Trader.Base;
{$R *.dfm}
{ TfmTrainerCloseOrderDialog }
procedure TfmTrainerCloseOrderDialog.acOKExecute(Sender: TObject);
begin
try
OpenedOrder.Close(edComment.Text);
except
on E:Exception do
begin
ModalResult:=mrNone;
MsgBox.MessageFailure(0,E.Message);
end;
end;
end;
constructor TfmTrainerCloseOrderDialog.Create(const aTrader: TStockTraderTrainer; aOrder: IStockorder);
var
aMarketPrice: TStockRealNumber;
begin
if aOrder=nil then
raise EAlgoError.Create;
if not (aOrder.GetState in [osOpened]) then
raise EAlgoError.Create;
inherited Create(nil);
FTrader:=aTrader;
OpenedOrder:=aOrder;
Caption:='Close '+OrderKindNames[aOrder.GetKind]+' Order';
laSymbol.Caption:=FTrader.GetSymbol;
if OpenedOrder.GetKind=okSell then
begin
aMarketPrice:=FTrader.GetBroker.GetCurrentPrice(FTrader.GetSymbol,bpkAsk);
laPrice.Caption:='Close Price (Ask)';
end
else begin
aMarketPrice:=FTrader.GetBroker.GetCurrentPrice(FTrader.GetSymbol,bpkBid);
laPrice.Caption:='Close Price (Bid)';
end;
laPriceValue.Caption:=PriceToStr(FTrader,aMarketPrice);
laProfit.Caption:=IntToStr(aOrder.GetBroker.PriceToPoint(aOrder.GetSymbol,aOrder.GetCurrentProfit));
end;
destructor TfmTrainerCloseOrderDialog.Destroy;
begin
inherited;
end;
end.
|
Unit UnAtualizacao3;
interface
Uses Classes, DbTables,SysUtils;
Type
TAtualiza3 = Class
Private
Aux : TQuery;
DataBase : TDataBase;
procedure AtualizaSenha( Senha : string );
public
function AtualizaTabela(VpaNumAtualizacao : Integer) : Boolean;
function AtualizaBanco : Boolean;
constructor criar( aowner : TComponent; ADataBase : TDataBase );
end;
Const
CT_SenhaAtual = '9774';
implementation
Uses FunSql, ConstMsg, FunNumeros, Registry, Constantes, FunString, funvalida, AAtualizaSistema;
{*************************** cria a classe ************************************}
constructor TAtualiza3.criar( aowner : TComponent; ADataBase : TDataBase );
begin
inherited Create;
Aux := TQuery.Create(aowner);
DataBase := ADataBase;
Aux.DataBaseName := 'BaseDados';
end;
{*************** atualiza senha na base de dados ***************************** }
procedure TAtualiza3.AtualizaSenha( Senha : string );
var
ini : TRegIniFile;
senhaInicial : string;
begin
try
if not DataBase.InTransaction then
DataBase.StartTransaction;
// atualiza regedit
Ini := TRegIniFile.Create('Software\Systec\Sistema');
senhaInicial := Ini.ReadString('SENHAS','BANCODADOS', ''); // guarda senha do banco
Ini.WriteString('SENHAS','BANCODADOS', Criptografa(senha)); // carrega senha do banco
// atualiza base de dados
LimpaSQLTabela(aux);
AdicionaSQLTabela(Aux, 'grant connect, to DBA identified by ''' + senha + '''');
Aux.ExecSQL;
if DataBase.InTransaction then
DataBase.commit;
ini.free;
except
if DataBase.InTransaction then
DataBase.Rollback;
Ini.WriteString('SENHAS','BANCODADOS', senhaInicial);
ini.free;
end;
end;
{*********************** atualiza o banco de dados ****************************}
function TAtualiza3.AtualizaBanco : boolean;
begin
result := true;
AdicionaSQLAbreTabela(Aux,'Select I_Ult_Alt from Cfg_Geral ');
if Aux.FieldByName('I_Ult_Alt').AsInteger < CT_VersaoBanco Then
result := AtualizaTabela(Aux.FieldByName('I_Ult_Alt').AsInteger);
end;
{**************************** atualiza a tabela *******************************}
function TAtualiza3.AtualizaTabela(VpaNumAtualizacao : Integer) : Boolean;
var
VpfErro : String;
begin
result := true;
repeat
Try
if VpaNumAtualizacao < 395 Then
begin
VpfErro := '395';
// ExecutaComandoSql(Aux,' delete MovComissoes;');
ExecutaComandoSql(Aux,' drop index FK_Ref_68047_FK; ' +
' alter table MovComissoes ' +
' drop foreign Key FK_Ref_68047; ');
// ExecutaComandoSql(Aux,' alter table MovComissoes ' +
//' delete I_LAN_APG, ' +
//' delete D_DAT_VEN, ' +
//' delete D_DAT_VAL, ' +
//' delete N_PER_PAG; ' );
ExecutaComandoSql(Aux,' alter table MovComissoes ' +
' add N_QTD_VEN integer null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 395' );
end;
if VpaNumAtualizacao < 396 Then
begin
VpfErro := '396';
ExecutaComandoSql(Aux,' alter table CFG_Fiscal ' +
' delete I_COM_PRO, ' +
' delete I_COM_SER; ' );
ExecutaComandoSql(Aux,' alter table CFG_Financeiro ' +
' modify C_COM_PAR integer null; ');
ExecutaComandoSql(Aux,' alter table CFG_Financeiro ' +
' add I_PAG_COM integer null, ' +
' add I_COM_PRO integer null, ' +
' add I_COM_SER integer null, ' +
' add I_COM_PAD integer null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 396' );
end;
if VpaNumAtualizacao < 397 Then
begin
VpfErro := '397';
ExecutaComandoSql(Aux,' alter table CADCONDICOESPAGTO ' +
' delete N_PER_CON; ' );
ExecutaComandoSql(Aux,' alter table MOVCONDICAOPAGTO ' +
' ADD N_PER_AJU numeric(8,3) null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 397' );
end;
if VpaNumAtualizacao < 398 Then
begin
VpfErro := '398';
ExecutaComandoSql(Aux,' alter table CADSERVICO ' +
' ADD N_VLR_COM numeric(17,7) null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 398' );
end;
if VpaNumAtualizacao < 399 Then // CadPercentualVendas
begin
VpfErro := '399';
ExecutaComandoSql(Aux,' Create table CADMETACOMISSAO '+
' ( ' +
' I_EMP_FIL integer not null, '+
' I_COD_MET integer not null, '+
' C_NOM_MET char(60) null, '+
' D_ULT_ALT date null, '+
' I_COD_USU integer null, '+
' D_DAT_CAD date null, '+
' primary key (I_EMP_FIL, I_COD_MET) '+');'+
' comment on table CADMETACOMISSAO is ''CADASTRO DE METAS COMISSAO''; '+
' comment on column CADMETACOMISSAO.I_EMP_FIL is ''CODIGO DA FILIAL''; '+
' comment on column CADMETACOMISSAO.I_COD_MET is ''CODIGO DA META''; '+
' comment on column CADMETACOMISSAO.C_NOM_MET is ''DESCRICAO DA META''; '+
' comment on column CADMETACOMISSAO.D_ULT_ALT is ''ULTIMA ALTERACAO''; '+
' comment on column CADMETACOMISSAO.I_COD_USU is ''CODIGO DO USUARIO''; '+
' comment on column CADMETACOMISSAO.D_DAT_CAD is ''DATA DE CADASTRO''; '+
' Create table MOVMETACOMISSAO '+
' ( ' +
' I_EMP_FIL integer not null, '+
' I_SEQ_MOV integer not null, '+
' I_COD_MET integer not null, '+
' N_TOT_MET numeric(17,3) null, '+
' N_PER_MET numeric(17,3) null, '+
' N_VLR_MET numeric(17,3) null, '+
' I_QTD_MET integer null, '+
' N_VLR_QTD numeric(17,3) null, '+
' I_COD_USU integer null, '+
' D_ULT_ALT date null, '+
' primary key (I_EMP_FIL,I_COD_MET, I_SEQ_MOV)' + ');' +
' comment on table MOVMETACOMISSAO is ''MOVIMENTO META COMISSAO''; '+
' comment on column MOVMETACOMISSAO.I_EMP_FIL is ''CODIGO DA FILIAL''; '+
' comment on column MOVMETACOMISSAO.I_COD_MET is ''CODIGO DA META''; '+
' comment on column MOVMETACOMISSAO.I_SEQ_MOV is ''SEQUENCIAL DO MOVIMENTO''; '+
' comment on column MOVMETACOMISSAO.N_TOT_MET is ''VALOR TOTAL DA META''; '+
' comment on column MOVMETACOMISSAO.N_PER_MET is ''PERCENTUAL DA META''; '+
' comment on column MOVMETACOMISSAO.N_VLR_MET is ''VALOR UNITARIO DA META''; '+
' comment on column MOVMETACOMISSAO.I_QTD_MET is ''QUANTIDADE DA META''; '+
' comment on column MOVMETACOMISSAO.N_VLR_QTD is ''VALOR DA QUANTIDADE DA META''; '+
' comment on column MOVMETACOMISSAO.I_COD_USU is ''CODIGO DO USUARIO''; '+
' comment on column MOVMETACOMISSAO.D_ULT_ALT is ''ULTIMA ALTERACAO'';' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 399');
end;
if VpaNumAtualizacao < 400 Then
begin
VpfErro := '400';
ExecutaComandoSql(Aux,' alter table CADVENDEDORES ' +
' ADD I_COD_MET INTEGER null; '+
' alter table MOVCOMISSOES ' +
' ADD I_COD_MET INTEGER null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 400' );
end;
if VpaNumAtualizacao < 401 Then
begin
VpfErro := '401';
ExecutaComandoSql(Aux,' alter table MOVCOMISSOES ' +
' ADD I_NRO_DOC integer null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 401' );
end;
if VpaNumAtualizacao < 402 Then
begin
VpfErro := '402';
ExecutaComandoSql(Aux,' alter table CADFILIAIS ' +
' ADD I_COD_MET integer null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 402' );
end;
if VpaNumAtualizacao < 403 Then
begin
VpfErro := '403';
ExecutaComandoSql(Aux,' alter table CFG_FINANCEIRO ' +
' ADD I_TIP_CAL integer null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 403' );
end;
if VpaNumAtualizacao < 404 Then
begin
VpfErro := '404';
ExecutaComandoSql(Aux,' alter table MOVMETACOMISSAO ' +
' ADD N_MET_FIM numeric(17,7) null, ' +
' ADD I_QTD_FIM integer null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 404' );
end;
if VpaNumAtualizacao < 405 Then
begin
VpfErro := '405';
ExecutaComandoSql(Aux,' alter table MOVCOMISSOES ' +
' ADD N_CON_PER numeric(17,3) null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 405' );
end;
if VpaNumAtualizacao < 406 Then
begin
VpfErro := '406';
ExecutaComandoSql(Aux,' alter table MOVMETACOMISSAO ' +
' ADD N_PER_QTD numeric(17,3) null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 406' );
end;
if VpaNumAtualizacao < 407 Then
begin
VpfErro := '407';
ExecutaComandoSql(Aux,' alter table MOVCOMISSOES ' +
' ADD D_INI_FEC date null, ' +
' ADD D_FIM_FEC date null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 407' );
end;
if VpaNumAtualizacao < 408 Then
begin
VpfErro := '408';
ExecutaComandoSql(Aux,' alter table MOVCOMISSOES ' +
' ADD N_VLR_PAR numeric(17,3) null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 408' );
end;
if VpaNumAtualizacao < 409 Then
begin
VpfErro := '409';
// ExecutaComandoSql(Aux,' alter table MOVCOMISSOES ' +
// ' ADD D_DAT_VEN date null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 409' );
end;
if VpaNumAtualizacao < 410 Then
begin
VpfErro := '410';
ExecutaComandoSql(Aux,' alter table CFG_FINANCEIRO ' +
' ADD I_TIP_MET integer null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 410' );
end;
if VpaNumAtualizacao < 411 Then
begin
VpfErro := '411';
ExecutaComandoSql(Aux,' alter table CADMETACOMISSAO ' +
' ADD I_FOR_MET integer null, ' +
' ADD I_ANA_MET integer null, ' +
' ADD I_CAL_MET integer null, ' +
' ADD I_PAG_MET integer null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 411' );
end;
if VpaNumAtualizacao < 412 Then
begin
VpfErro := '412';
ExecutaComandoSql(Aux,' alter table MOVCOMISSOES ' +
' ADD N_VLR_MET numeric(17,3) null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 412' );
end;
if VpaNumAtualizacao < 413 Then
begin
VpfErro := '413';
ExecutaComandoSql(Aux,' alter table CADMETACOMISSAO ' +
' ADD I_ORI_MET integer null, ' +
' ADD I_VAL_MET integer null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 413' );
end;
if VpaNumAtualizacao < 414 Then
begin
VpfErro := '414';
ExecutaComandoSql(Aux,' alter table CFG_FINANCEIRO ' +
' ADD N_DES_PAR numeric(17,3) null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 414' );
end;
if VpaNumAtualizacao < 415 Then
begin
VpfErro := '415';
ExecutaComandoSql(Aux,' alter table CADVENDEDORES ' +
' ADD I_COD_ME2 integer null,' +
' ADD I_COD_ME3 integer null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 415' );
end;
if VpaNumAtualizacao < 416 Then
begin
VpfErro := '416';
ExecutaComandoSql(Aux,' alter table MOVCOMISSOES ' +
' ADD I_COD_ME2 integer null,' +
' ADD I_COD_ME3 integer null; '+
' alter table CFG_FINANCEIRO '+
' ADD I_MET_ATU integer null;');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 416' );
end;
if VpaNumAtualizacao < 417 Then
begin
VpfErro := '417';
ExecutaComandoSql(Aux,' alter table MOVCOMISSOES ' +
' ADD N_VLR_ME2 numeric(17,3) null,' +
' ADD N_VLR_ME3 numeric(17,3) null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 417' );
end;
if VpaNumAtualizacao < 418 Then
begin
VpfErro := '418';
ExecutaComandoSql(Aux,' Create table MOVFECHAMENTO '+
' ( ' +
' I_EMP_FIL integer not null, '+
' I_SEQ_MOV integer not null, '+
' I_COD_VEN integer not null, '+
' I_COD_MET integer null, '+
' I_COD_ME2 integer null, '+
' I_COD_ME3 integer null, '+
' N_VLR_MET numeric(17,3) null, '+
' N_VLR_ME2 numeric(17,3) null, '+
' N_VLR_ME3 numeric(17,3) null, '+
' N_PER_VEN numeric(17,3) null, '+
' N_VLR_COM numeric(17,3) null, '+
' N_VLR_PON numeric(17,3) null, '+
' D_INI_FEC date null, '+
' D_FIM_FEC date null, '+
' I_COD_USU integer null, '+
' D_ULT_ALT date null, '+
' primary key (I_EMP_FIL,I_COD_VEN, I_SEQ_MOV)' + ');' +
' comment on table MOVFECHAMENTO is ''FECHAMENTO DE METAS''; '+
' comment on column MOVFECHAMENTO.I_EMP_FIL is ''CODIGO DA FILIAL''; '+
' comment on column MOVFECHAMENTO.I_COD_MET is ''CODIGO DA META1''; '+
' comment on column MOVFECHAMENTO.I_COD_ME2 is ''CODIGO DA META2''; '+
' comment on column MOVFECHAMENTO.I_COD_ME3 is ''CODIGO DA META3''; '+
' comment on column MOVFECHAMENTO.I_SEQ_MOV is ''SEQUENCIAL DO MOVIMENTO''; '+
' comment on column MOVFECHAMENTO.I_COD_VEN is ''CODIGO DO VENDEDOR''; '+
' comment on column MOVFECHAMENTO.N_VLR_MET is ''VALOR DA META1''; '+
' comment on column MOVFECHAMENTO.N_VLR_ME2 is ''VALOR DA META2''; '+
' comment on column MOVFECHAMENTO.N_VLR_ME3 is ''VALOR DA META3 ''; '+
' comment on column MOVFECHAMENTO.N_PER_VEN is ''PERCENTUAL DE COMISSAO DO VENDEDOR''; '+
' comment on column MOVFECHAMENTO.N_VLR_PON is ''QUANTIDADE DE PONTOS''; '+
' comment on column MOVFECHAMENTO.N_VLR_COM is ''VALOR DA COMISSAO DO VENDEDOR''; '+
' comment on column MOVFECHAMENTO.I_COD_USU is ''CODIGO DO USUARIO''; '+
' comment on column MOVFECHAMENTO.D_ULT_ALT is ''ULTIMA ALTERACAO'';'+
' comment on column MOVFECHAMENTO.D_INI_FEC is ''DATA DE INICIO DO FECHAMENTO'';'+
' comment on column MOVFECHAMENTO.D_FIM_FEC is ''DATA DE FIM DO FECHAMENTO'';');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 418');
end;
if VpaNumAtualizacao < 419 Then
begin
VpfErro := '419';
ExecutaComandoSql(Aux,' alter table MOVCOMISSOES ' +
' ADD C_FLA_FEC char(1) null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 419' );
end;
if VpaNumAtualizacao < 420 Then
begin
VpfErro := '420';
ExecutaComandoSql(Aux,' alter table MOVCOMISSOES ' +
' ADD C_FLA_PAR char(1) null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 420' );
end;
if VpaNumAtualizacao < 421 Then
begin
VpfErro := '421';
ExecutaComandoSql(Aux,' alter table MOVFECHAMENTO ' +
' ADD N_VLR_FAT numeric(17,3) null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 421' );
end;
if VpaNumAtualizacao < 422 Then
begin
VpfErro := '422';
ExecutaComandoSql(Aux,' alter table CADCONTASARECEBER ' +
' ADD I_SEQ_MAT integer null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 422' );
end;
if VpaNumAtualizacao < 423 Then
begin
VpfErro := '423';
ExecutaComandoSql(Aux,' Create table MOVVENDEDORES '+
' ( ' +
' I_EMP_FIL integer not null, '+
' I_SEQ_MOV integer not null, '+
' I_COD_VEN integer null, '+
' I_COD_MAT integer null, '+
' I_SEQ_NOT integer null, '+
' I_LAN_REC integer null, '+
' I_COD_USU integer null, '+
' D_ULT_ALT date null, '+
' primary key (I_EMP_FIL, I_SEQ_MOV)' + ');' +
' comment on table MOVVENDEDORES is ''VENDEDORES DA NOTA OU CONTRATO''; '+
' comment on column MOVVENDEDORES.I_EMP_FIL is ''CODIGO DA FILIAL''; '+
' comment on column MOVVENDEDORES.I_COD_MAT is ''CODIGO DA MATRICULA''; '+
' comment on column MOVVENDEDORES.I_SEQ_NOT is ''CODIGO DA NOTA FISCAL''; '+
' comment on column MOVVENDEDORES.I_LAN_REC is ''CODIGO DA LANCAMENTO RECEBER''; '+
' comment on column MOVVENDEDORES.I_SEQ_MOV is ''SEQUENCIAL DO MOVIMENTO''; '+
' comment on column MOVVENDEDORES.I_COD_VEN is ''CODIGO DO VENDEDOR''; '+
' comment on column MOVFECHAMENTO.I_COD_USU is ''CODIGO DO USUARIO''; '+
' comment on column MOVFECHAMENTO.D_ULT_ALT is ''ULTIMA ALTERACAO'';');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 423');
end;
if VpaNumAtualizacao < 424 Then
begin
VpfErro := '424';
ExecutaComandoSql(Aux,' alter table MOVCOMISSOES ' +
' ADD I_COD_MAT integer null, '+
' ADD I_SEQ_NOT integer null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 424' );
end;
if VpaNumAtualizacao < 425 Then
begin
VpfErro := '425';
ExecutaComandoSql(Aux,' alter table MOVCOMISSOES ' +
' ADD I_NRO_LOT integer null');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 425' );
end;
if VpaNumAtualizacao < 426 Then
begin
VpfErro := '426';
ExecutaComandoSql(Aux,' alter table MOVFECHAMENTO ' +
' ADD I_NRO_LOT integer null');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 426' );
end;
if VpaNumAtualizacao < 427 Then
begin
VpfErro := '427';
ExecutaComandoSql(Aux,' alter table MOVFECHAMENTO ' +
' ADD N_TOT_MET numeric(17,3) null,'+
' ADD N_TOT_ME2 numeric(17,3) null,'+
' ADD N_TOT_ME3 numeric(17,3) null;' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 427' );
end;
if VpaNumAtualizacao < 428 Then
begin
VpfErro := '428';
ExecutaComandoSql(Aux,' alter table MOVFECHAMENTO ' +
' ADD C_FLA_MOV char(1) null;');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 428' );
end;
if VpaNumAtualizacao < 429 Then
begin
VpfErro := '429';
ExecutaComandoSql(Aux,' create unique index CADMETACOMISSAO_PK ' +
' on CADMETACOMISSAO(I_EMP_FIL asc, I_COD_MET asc); ' +
' create unique index MOVMETACOMISSAO_PK ' +
' on MOVMETACOMISSAO(I_EMP_FIL asc, I_COD_MET asc, I_SEQ_MOV asc); ' +
' create unique index MOVFECHAMENTO_PK ' +
' on MOVFECHAMENTO(I_EMP_FIL asc, I_COD_VEN asc, I_SEQ_MOV asc); ' +
' create unique index MOVVENDEDORES_PK ' +
' on MOVVENDEDORES(I_EMP_FIL asc, I_SEQ_MOV asc); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 429' );
end;
if VpaNumAtualizacao < 430 Then
begin
VpfErro := '430';
ExecutaComandoSql(Aux,' alter table MOVMETACOMISSAO ' +
' add foreign key FK_MOVMETACOMISSAO_987 (I_EMP_FIL, I_COD_MET) ' +
' references CADMETACOMISSAO(I_EMP_FIL, I_COD_MET) on update restrict on delete restrict; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 430' );
end;
if VpaNumAtualizacao < 431 Then
begin
VpfErro := '431';
ExecutaComandoSql(Aux,' alter table MOVVENDEDORES ' +
' add foreign key FK_CR_9483 (I_EMP_FIL, I_LAN_REC) ' +
' references CADCONTASARECEBER(I_EMP_FIL, I_LAN_REC) on update restrict on delete restrict; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 431' );
end;
if VpaNumAtualizacao < 432 Then
begin
VpfErro := '432';
ExecutaComandoSql(Aux,' alter table MOVVENDEDORES ' +
' add foreign key FK_MOVVENDEDORES_346 (I_COD_VEN) ' +
' references CADVENDEDORES(I_COD_VEN) on update restrict on delete restrict; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 432' );
end;
if VpaNumAtualizacao < 433 Then
begin
VpfErro := '433';
ExecutaComandoSql(Aux,' create index VEN_MOVVEN_FK on MOVVENDEDORES(I_COD_VEN asc); ' );
ExecutaComandoSql(Aux,' create index CR_MOVVEN_FK on MOVVENDEDORES(I_EMP_FIL, I_LAN_REC asc); ' );
ExecutaComandoSql(Aux,' create index CADMET_MOVMET_FK on MOVMETACOMISSAO(I_EMP_FIL, I_COD_MET asc); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 433' );
end;
if VpaNumAtualizacao < 434 Then
begin
VpfErro := '434';
ExecutaComandoSql(Aux,' alter table cfg_financeiro add C_OPE_COB char(3) null');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 434' );
end;
if VpaNumAtualizacao < 435 Then
begin
VpfErro := '435';
ExecutaComandoSql(Aux,' create table CADITEMPEDIDO ' +
' ( ' +
' I_COD_ITE integer not null, ' +
' L_DES_ITE Long VarChar null, ' +
' D_ULT_ALT date null, ' +
' primary key (I_COD_ITE) ' +
' );' +
' comment on table CADITEMPEDIDO is ''CADITEMPEDIDO '';' +
' comment on column CADITEMPEDIDO.I_COD_ITE is ''CODIGO DO ITEM '';' +
' comment on column CADITEMPEDIDO.L_DES_ITE is ''NOME DO ITEM '';' +
' comment on column CADITEMPEDIDO.D_ULT_ALT is ''DATA DA ULTIMA ALTERAÇAO '';');
ExecutaComandoSql(Aux,' create unique index CADITEMPEDIDO_PK ' +
' on CADITEMPEDIDO(I_COD_ITE asc); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 435' );
end;
if VpaNumAtualizacao < 436 Then
begin
VpfErro := '436';
ExecutaComandoSql(Aux,' create table MOVITEMPEDIDO ' +
' ( ' +
' I_EMP_FIL integer not null, ' +
' I_LAN_ORC integer not null, ' +
' I_COD_ITE integer not null, ' +
' D_ULT_ALT date null, ' +
' primary key (I_EMP_FIL, I_LAN_ORC, I_COD_ITE) ' +
' );' +
' comment on table MOVITEMPEDIDO is ''MOVITEMPEDIDO '';' +
' comment on column MOVITEMPEDIDO.I_EMP_FIL is ''CODIGO DA FILIAL '';' +
' comment on column MOVITEMPEDIDO.I_LAN_ORC is ''NRO DO ORCAMENTO '';' +
' comment on column MOVITEMPEDIDO.I_COD_ITE is ''CODIGO DO ITEM '';' +
' comment on column MOVITEMPEDIDO.D_ULT_ALT is ''DATA ULTIMA ALTERACAO '';' +
' alter table MOVITEMPEDIDO ' +
' add foreign key FK_MOVITEMP_REF_55_CADORCAM (I_EMP_FIL, I_LAN_ORC) ' +
' references CADORCAMENTOS (I_EMP_FIL, I_LAN_ORC) on update restrict on delete restrict; ');
ExecutaComandoSql(Aux,' create unique index MOVITEMPEDIDO_PK ' +
' on MOVITEMPEDIDO(I_EMP_FIL asc, I_LAN_ORC asc, I_COD_ITE asc); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 436' );
end;
if VpaNumAtualizacao < 437 Then
begin
VpfErro := '437';
ExecutaComandoSql(Aux,' alter table CFG_FINANCEIRO '+
' ADD C_ALT_DAT char(1) null, '+
' ADD C_MAI_VEN char(1) null;');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 437' );
end;
if VpaNumAtualizacao < 438 Then
begin
VpfErro := '438';
ExecutaComandoSql(Aux,' alter table CFG_FINANCEIRO '+
' ADD I_CAI_COP integer null, '+
' ADD I_CAI_COR integer null;');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 438' );
end;
if VpaNumAtualizacao < 439 Then
begin
VpfErro := '439';
ExecutaComandoSql(Aux,' alter table CadContas ' +
' add C_MOS_FLU char(1) null;' +
' Update CadContas ' +
' set C_MOS_FLU = ''S'';' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 439' );
end;
if VpaNumAtualizacao < 440 Then
begin
VpfErro := '440';
ExecutaComandoSql(Aux,' alter table CFG_GERAL ' +
' add C_MOD_SIS char(1) null;' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 440' );
end;
if VpaNumAtualizacao < 441 Then
begin
VpfErro := '441';
ExecutaComandoSql(Aux,' alter table CFG_produto ' +
' delete C_CUP_AUT ;' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 441' );
end;
if VpaNumAtualizacao < 442 Then
begin
VpfErro := '442';
ExecutaComandoSql(Aux,' alter table CFG_FINANCEIRO ' +
' add I_IMP_AUT integer null;' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 442' );
end;
if VpaNumAtualizacao < 443 Then
begin
VpfErro := '443';
ExecutaComandoSql(Aux,' alter table CFG_FINANCEIRO ' +
' add I_MOD_AUT integer null,' +
' add C_FON_NEG char(1) null,' +
' add C_FON_ITA char(1) null,' +
' add C_FON_SUB char(1) null,' +
' add C_FON_EXP char(1) null;' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 443' );
end;
if VpaNumAtualizacao < 444 Then
begin
VpfErro := '444';
ExecutaComandoSql(Aux,' alter table CFG_FINANCEIRO ' +
' add I_NUM_AUT integer null;' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 444' );
end;
if VpaNumAtualizacao < 445 Then
begin
VpfErro := '445';
ExecutaComandoSql(Aux,' alter table Cad_Caixa ' +
' add FLA_CAD_PAG char(1) null, '+
' add FLA_CAD_REC char(1) null, '+
' add FLA_PAG_PAG char(1) null, '+
' add FLA_REC_REC char(1) null;' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 445' );
end;
if VpaNumAtualizacao < 446 Then
begin
VpfErro := '446';
ExecutaComandoSql(Aux,' alter table CFG_FINANCEIRO ' +
' add I_FLA_COM integer null;' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 446' );
end;
if VpaNumAtualizacao < 447 Then
begin
VpfErro := '447';
ExecutaComandoSql(Aux,' alter table CFG_FISCAL ' +
' delete C_MOD_CAI ;' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 447' );
end;
if VpaNumAtualizacao < 448 Then
begin
VpfErro := '448';
ExecutaComandoSql(Aux,' alter table CFG_GERAL ' +
' add I_TIP_SIS integer null;' +
' Update CFG_GERAL ' +
' set I_TIP_SIS = 0 ;' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 448' );
end;
if VpaNumAtualizacao < 449 Then
begin
VpfErro := '449';
ExecutaComandoSql(Aux,' alter table CFG_PRODUTO ' +
' delete C_TIP_IND ;' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 449' );
end;
if VpaNumAtualizacao < 450 Then
begin
VpfErro := '450';
ExecutaComandoSql(Aux,' alter table CFG_FINANCEIRO ' +
' add I_FRM_BAN integer null;' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 450' );
end;
if VpaNumAtualizacao < 451 Then
begin
VpfErro := '451';
ExecutaComandoSql(Aux,' alter table MOVCONDICAOPAGTO ' +
' add C_DAT_INI char(1) null;' +
' Update MOVCONDICAOPAGTO ' +
' Set C_DAT_INI = ''N''; ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 451' );
end;
if VpaNumAtualizacao < 452 Then
begin
VpfErro := '452';
ExecutaComandoSql(Aux,' alter table cfg_financeiro ' +
' add C_CAI_COP char(1) null,' +
' add C_CAI_COR char(1) null;' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 452' );
end;
if VpaNumAtualizacao < 453 Then
begin
VpfErro := '453';
ExecutaComandoSql(Aux,' alter table cfg_Servicos ' +
' add C_OBR_AVI char(1) null;' +
' alter Table cadordemservico ' +
' add I_DIA_ENT integer null ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 453' );
end;
if VpaNumAtualizacao < 454 Then
begin
VpfErro := '454';
ExecutaComandoSql(Aux,' drop index fk_REF_31475_FK; ' +
' drop index fk_REF_31485_FK; ' +
' alter table ITE_CAIXA ' +
' drop foreign key FK_PAGAR; ' +
' alter table ITE_CAIXA ' +
' drop foreign key FK_RECEBER; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 454' );
end;
if VpaNumAtualizacao < 455 Then
begin
VpfErro := '455';
ExecutaComandoSql(Aux,' alter table ITE_CAIXA ' +
' add foreign key FK_PAGAR(FIL_ORI,LAN_PAGAR, NRO_PAGAR) ' +
' references MOVCONTASAPAGAR(I_EMP_FIL, I_LAN_APG, I_NRO_PAR) on update restrict on delete restrict; ' +
' alter table ITE_CAIXA ' +
' add foreign key FK_RECEBER(FIL_ORI,LAN_RECEBER, NRO_RECEBER) ' +
' references MOVCONTASARECEBER(I_EMP_FIL, I_LAN_REC, I_NRO_PAR) on update restrict on delete restrict; ' +
' create index fk_REF_31475_FK on ITE_CAIXA(FIL_ORI,LAN_RECEBER, NRO_RECEBER asc); ' +
' create index fk_REF_31485_FK on ITE_CAIXA(FIL_ORI,LAN_PAGAR, NRO_PAGAR asc); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 455' );
end;
if VpaNumAtualizacao < 456 Then
begin
VpfErro := '456';
ExecutaComandoSql(Aux,' alter table ITE_Caixa ' +
' add C_NRO_NOT char(15) null,'+
' add D_DAT_NOT date null;');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 456' );
end;
if VpaNumAtualizacao < 457 Then
begin
VpfErro := '457';
ExecutaComandoSql(Aux,' alter table CADEVENTOS ' +
' modify C_NOM_EVE char(50) null ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 457' );
end;
if VpaNumAtualizacao < 458 Then
begin
VpfErro := '458';
ExecutaComandoSql(Aux,' create table CADLIGACOES ' +
' ( ' +
' I_EMP_FIL integer not null, ' +
' I_SEQ_LIG integer not null, ' +
' D_DAT_LIG date not null, ' +
' I_COD_USU integer null, ' +
' I_COD_CLI integer null, ' +
' C_NOM_CLI char(50) null, ' +
' C_TEX_LIG long varchar null, ' +
' T_HOR_LIG timestamp null, ' +
' primary key (I_EMP_FIL, I_SEQ_LIG, D_DAT_LIG) ' +
' ); ' +
' comment on table CADLIGACOES is ''CADLIGACOES''; ' +
' comment on column CADLIGACOES.I_EMP_FIL is ''CODIGO DA EMPRESA FILIAL''; ' +
' comment on column CADLIGACOES.I_SEQ_LIG is ''CODIGO SEQUENCIAL DA LIGACAO''; ' +
' comment on column CADLIGACOES.D_DAT_LIG is ''DATA DA LIGACAO''; ' +
' comment on column CADLIGACOES.I_COD_USU is ''CODIGO DO USUARIO''; ' +
' comment on column CADLIGACOES.I_COD_CLI is ''CODIGO DO CLIENTE''; ' +
' comment on column CADLIGACOES.C_NOM_CLI is ''NOME DO CLIENTE''; ' +
' comment on column CADLIGACOES.C_TEX_LIG is ''ASSUNTO DA LIGACAO''; ' +
' comment on column CADLIGACOES.T_HOR_LIG is ''HORA DA LIGACAO'';');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 458' );
end;
if VpaNumAtualizacao < 459 Then
begin
VpfErro := '459';
ExecutaComandoSql(Aux,' create unique index CADLIGACOES_PK on CADLIGACOES(I_EMP_FIL, I_SEQ_LIG, D_DAT_LIG asc); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 459' );
end;
if VpaNumAtualizacao < 460 Then
begin
VpfErro := '460';
ExecutaComandoSql(Aux,' Alter Table cfg_fiscal add I_TIP_TEF integer null ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 460' );
end;
if VpaNumAtualizacao < 461 Then
begin
VpfErro := '461';
ExecutaComandoSql(Aux,' Alter Table cadligacoes ' +
' add C_RET_LIG char(1) null ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 461' );
end;
if VpaNumAtualizacao < 462 Then
begin
VpfErro := '462';
ExecutaComandoSql(Aux,' alter table CADMETACOMISSAO ' +
' ADD I_CAL_FEC integer null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 462' );
end;
if VpaNumAtualizacao < 463 Then
begin
VpfErro := '463';
ExecutaComandoSql(Aux,' alter table CFG_GERAL ' +
' ADD C_SEN_CAI char(15) null, ' +
' ADD C_SEN_ADM char(15) null, ' +
' ADD C_SEN_SER char(15) null, ' +
' ADD C_SEN_FIN char(15) null; ' +
' update cfg_geral ' +
' set C_SEN_CAI = (select c_sen_cai from cfg_financeiro ),' +
' C_SEN_ADM = C_SEN_LIB, ' +
' C_SEN_SER = C_SEN_LIB, ' +
' C_SEN_FIN = C_SEN_LIB ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 463' );
end;
if VpaNumAtualizacao < 464 Then
begin
VpfErro := '464';
ExecutaComandoSql(Aux,' update CFG_GERAL ' +
' set C_SEN_CAI = null; ');
aviso('Caso você utilize o módulo caixa, favor atualizar a senha de linheração do caixa!');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 464' );
end;
if VpaNumAtualizacao < 465 Then
begin
VpfErro := '465';
ExecutaComandoSql(Aux,' alter Table CadFiliais ' +
' add N_PER_ISS numeric(8,3) null, ' +
' add I_COD_BOL integer null ; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 465' );
end;
if VpaNumAtualizacao < 466 Then
begin
VpfErro := '466';
ExecutaComandoSql(Aux,' alter Table CadFiliais ' +
' add I_TEX_BOL integer null; ' );
ExecutaComandoSql(Aux,' update CadFiliais ' +
' set N_PER_ISS = (select n_per_isq from cfg_fiscal), ' +
' I_COD_BOL = (select i_bol_pad from cfg_fiscal), ' +
' I_TEX_BOL = (select i_dad_bol from cfg_fiscal); ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 466' );
end;
if VpaNumAtualizacao < 467 Then
begin
VpfErro := '467';
ExecutaComandoSql(Aux,' alter Table CadNotaFiscais ' +
' add N_PER_ISS numeric(8,3) null; ');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 467' );
end;
if VpaNumAtualizacao < 468 Then
begin
VpfErro := '468';
ExecutaComandoSql(Aux,' create table TEMPORARIACPCR ' +
'( ' +
' I_COD_CLI integer null , ' +
' D_DAT_VEN date null , ' +
' D_DAT_EMI date null , ' +
' N_VLR_CCR numeric(17,5) null , ' +
' I_NRO_NOT integer null , ' +
' I_TIP_CAD char(1) null , ' +
' N_VLR_CCP numeric(17,5) null , ' +
' I_NRO_PAR integer null , ' +
' D_DAT_PAG timestamp null ' +
' ); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 468' );
end;
if VpaNumAtualizacao < 469 Then
begin
VpfErro := '469';
ExecutaComandoSql(Aux,' Alter Table cadligacoes ' +
' add C_RET_REC char(1) null, '+
' add C_NOM_REC char(60) null,'+
' add C_FEZ_RET char(1) null, '+
' add C_FEZ_REC char(1) null');
ExecutaComandoSql(Aux,' Alter Table cadligacoes ' +
' add C_NOM_SOL char(50) null, '+
' add C_FON_CLI char(20) null;');
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 469' );
end;
if VpaNumAtualizacao < 470 Then
begin
VpfErro := '470';
ExecutaComandoSql(Aux,' create table TEMPORARIABANCO ' +
'( ' +
' N_SAL_ATU numeric(17,5) null , ' +
' N_LIM_CRE numeric(17,5) null , ' +
' C_NRO_CON char(15) null ' +
' ); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 470' );
end;
if VpaNumAtualizacao < 471 Then
begin
VpfErro := '471';
ExecutaComandoSql(Aux,' alter table cfg_geral ' +
' add C_PAT_ATU char(40) null ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 471' );
end;
if VpaNumAtualizacao < 472 Then
begin
VpfErro := '472';
ExecutaComandoSql(Aux,' alter table cad_caixa ' +
' add C_CAI_GER char(1) null ' );
ExecutaComandoSql(Aux,' alter table MovBancos ' +
' add D_DAT_MOV date null ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 472' );
end;
if VpaNumAtualizacao < 473 Then
begin
VpfErro := '473';
ExecutaComandoSql(Aux,' create table MOVSALDOBANCO ' +
'( ' +
' I_SEQ_MOV integer null, ' +
' SEQ_DIARIO integer null , ' +
' N_SAL_ATU numeric(17,5) null , ' +
' C_NRO_CON char(15) null ,' +
' D_ULT_ALT date null , ' +
' primary key (I_SEQ_MOV,SEQ_DIARIO) ); ' +
' create unique index MOVSALDOBANCO_PK ' +
' on MOVSALDOBANCO(I_SEQ_MOV asc, SEQ_DIARIO asc ); ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 473' );
end;
if VpaNumAtualizacao < 474 Then
begin
VpfErro := '474';
ExecutaComandoSql(Aux,' alter table cadusuarios ' +
' add L_TEX_NOT Long VarChar null ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 474' );
end;
if VpaNumAtualizacao < 476 Then
begin
VpfErro := '476';
ExecutaComandoSql(Aux,' alter table cfg_financeiro ' +
' add I_FRM_BAN INTEGER null ' );
ExecutaComandoSql(Aux,' Update Cfg_Geral set I_Ult_Alt = 476' );
end;
if VpaNumAtualizacao < 478 Then
begin
VpfErro := '478';
aux.sql.clear;
aux.sql.add(
' create table MOVEQUIPAMENTOOS ' +
' ( ' +
' I_EMP_FIL integer not null, ' +
' I_COD_ORS integer not null, ' +
' I_SEQ_MOV integer not null, ' +
' I_COD_EQU integer null, ' +
' I_COD_MAR integer null, ' +
' I_COD_MOD integer null, ' +
' C_ACE_EQU varchar(100) null, ' +
' C_GAR_EQU char(1) null, ' +
' C_ORC_EQU char(1) null, ' +
' C_NRO_NOT char(40) null, ' +
' C_DEF_APR varchar(250) null, ' +
' primary key (I_EMP_FIL, I_COD_ORS, I_SEQ_MOV) ' +
' ); ' +
' comment on table MOVEQUIPAMENTOOS is ''EQUIPAMENTOS DA ORDEM DE SERVICO''; ' +
' comment on column MOVEQUIPAMENTOOS.I_EMP_FIL is ''EMPRESA FILIAL''; ' +
' comment on column MOVEQUIPAMENTOOS.I_COD_ORS is ''CODIGO DA ORDEM DE SERVICO''; ' +
' comment on column MOVEQUIPAMENTOOS.I_COD_EQU is ''CODIGO DA EQUIPAMENTO''; ' +
' comment on column MOVEQUIPAMENTOOS.I_COD_MAR is ''CODIGO DA MARCA''; ' +
' comment on column MOVEQUIPAMENTOOS.I_COD_MOD is ''CODIGO DO MODELO''; ' +
' comment on column MOVEQUIPAMENTOOS.C_ACE_EQU is ''ACESSORIOS DO EQUIPAMENTO''; ' +
' comment on column MOVEQUIPAMENTOOS.C_GAR_EQU is ''POSSUI GARANTIA S/N''; ' +
' comment on column MOVEQUIPAMENTOOS.C_ORC_EQU is ''FAZER ORCAMENTO S/N''; ' +
' comment on column MOVEQUIPAMENTOOS.C_DEF_APR is ''DEFEITO APRESENTADO''; ' +
' comment on column MOVEQUIPAMENTOOS.C_NRO_NOT is ''NUMERO DA NOTA CASO GARANTIA''; ' );
aux.ExecSQL;
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 478');
end;
if VpaNumAtualizacao < 479 Then
begin
VpfErro := '479';
ExecutaComandoSql(Aux,
' alter table MOVEQUIPAMENTOOS ' +
' add foreign key FK_CADORDEM_REF_65A_CADMODEL (I_COD_MOD) ' +
' references CADMODELO (I_COD_MOD) on update restrict on delete restrict; ' +
' alter table MOVEQUIPAMENTOOS ' +
' add foreign key FK_CADORDEM_REF_61A_CADMARCA (I_COD_MAR) ' +
' references CADMARCAS (I_COD_MAR) on update restrict on delete restrict; ' +
' alter table MOVEQUIPAMENTOOS ' +
' add foreign key FK_CADORDEM_REF_13281A_CADEQUIP (I_COD_EQU) ' +
' references CADEQUIPAMENTOS (I_COD_EQU) on update restrict on delete restrict; ' +
' alter table MOVEQUIPAMENTOOS ' +
' add foreign key FK_MOVORDEM_REF_77A_CADORDEM (I_EMP_FIL, I_COD_ORS) ' +
' references CADORDEMSERVICO (I_EMP_FIL, I_COD_ORS) on update restrict on delete restrict; ' +
' create index Ref_65A_FK on MOVEQUIPAMENTOOS (I_COD_MOD asc); ' +
' create index Ref_61A_FK on MOVEQUIPAMENTOOS (I_COD_MAR asc); ' +
' create index Ref_132813A_FK on MOVEQUIPAMENTOOS (I_COD_EQU asc); ' +
' create unique index MOVEQUIPAMENTOOS_PK on MOVEQUIPAMENTOOS (I_EMP_FIL asc, I_COD_ORS asc, I_SEQ_MOV asc); ' );
ExecutaComandoSql(Aux,'Update CFG_GERAL set I_Ult_Alt = 479');
end;
if VpaNumAtualizacao < 480 Then
begin
VpfErro := '480';
ExecutaComandoSql(Aux,' ALTER TABLE MovEquipamentoOS ' +
' add D_ULT_ALT date null, ' +
' add N_QTD_EQU numeric(17,3) null, ' +
' add C_VOL_ENT char(10) null,' +
' add C_NRO_SER char(20) null ' );
ExecutaComandoSql(Aux,'Update Cfg_Geral set I_Ult_Alt = 480');
end;
except
result := false;
FAtualizaSistema.MostraErro(Aux.sql,'cfg_geral');
Erro(VpfErro + ' - OCORREU UM ERRO DURANTE A ATUALIZAÇÃO DO SISTEMA!');
exit;
end;
until result;
end;
end.
|
{
You are free to use this, but be weary its absolutely garbage and isn't guaranteed to work at all.
Use with caution as it is extraordinarily primitive.
}
unit GhettoFileDetection;
interface
uses
Classes;
function IsWebM(FilePath: string): boolean;
function IsWebP(FilePath: string): boolean;
function IsMOV(FilePath: string): boolean;
function IsMP4(FilePath: string): boolean;
function IsMP3(FilePath: string): boolean;
function IsWAV(FilePath: string): boolean;
function IsOGG(FilePath: string): boolean;
function IsJPEG(FilePath: string): boolean;
function IsGif(FilePath: string): boolean;
function IsPNG(FilePath: string): boolean;
implementation
function IsWebM(FilePath: string): boolean;
var
FileReader: TStream;
header: array[0..3] of byte;
begin
Result := False;
FileReader := TFileStream.Create(FilePath, fmOpenRead);
try
FileReader.seek(0, soFromBeginning);
FileReader.ReadBuffer(header, Length(header));
if header[0] = 26 then
if header[1] = 69 then
if header[2] = 223 then
if header[3] = 163 then
Result := True;
finally
FileReader.Free;
end;
end;
function IsWebP(FilePath: string): boolean;
var
FileReader: TStream;
header: array[0..11] of byte;
begin
Result := False;
FileReader := TFileStream.Create(FilePath, fmOpenRead);
try
FileReader.seek(0, soFromBeginning);
FileReader.ReadBuffer(header, Length(header));
if header[8] = 87 then
if header[9] = 69 then
if header[10] = 66 then
if header[11] = 80 then
Result := True;
finally
FileReader.Free;
end;
end;
function IsMOV(FilePath: string): boolean;
var
FileReader: TStream;
header: array[0..9] of byte;
begin
Result := False;
FileReader := TFileStream.Create(FilePath, fmOpenRead);
try
FileReader.seek(0, soFromBeginning);
FileReader.ReadBuffer(header, Length(header));
if header[0] = 0 then
if header[1] = 0 then
if header[2] = 0 then
if header[3] = 20 then
if header[4] = 102 then
if header[5] = 116 then
if header[6] = 121 then
if header[7] = 112 then
if header[8] = 113 then
if header[9] = 116 then
Result := True;
finally
FileReader.Free;
end;
end;
function IsMP4(FilePath: string): boolean;
var
FileReader: TStream;
header: array[0..9] of byte;
begin
Result := False;
FileReader := TFileStream.Create(FilePath, fmOpenRead);
try
FileReader.seek(0, soFromBeginning);
FileReader.ReadBuffer(header, Length(header));
if header[0] = 0 then
if header[1] = 0 then
if header[2] = 0 then
if header[3] = 32 then
if header[4] = 102 then
if header[5] = 116 then
if header[6] = 121 then
if header[7] = 112 then
if header[8] = 105 then
if header[9] = 115 then
Result := True;
finally
FileReader.Free;
end;
end;
function IsMP3(FilePath: string): boolean;
var
FileReader: TStream;
header: array[0..2] of byte;
begin
Result := False;
FileReader := TFileStream.Create(FilePath, fmOpenRead);
try
FileReader.seek(0, soFromBeginning);
FileReader.ReadBuffer(header, Length(header));
if header[0] = 73 then
if header[1] = 68 then
if header[2] = 51 then
Result := True;
finally
FileReader.Free;
end;
end;
function IsWAV(FilePath: string): boolean;
var
FileReader: TStream;
header: array[0..11] of byte;
begin
Result := False;
FileReader := TFileStream.Create(FilePath, fmOpenRead);
try
FileReader.seek(0, soFromBeginning);
FileReader.ReadBuffer(header, Length(header));
if header[8] = 87 then
if header[9] = 65 then
if header[10] = 86 then
if header[11] = 69 then
Result := True;
finally
FileReader.Free;
end;
end;
function IsOGG(FilePath: string): boolean;
var
FileReader: TStream;
header: array[0..3] of byte;
begin
Result := False;
FileReader := TFileStream.Create(FilePath, fmOpenRead);
try
FileReader.seek(0, soFromBeginning);
FileReader.ReadBuffer(header, Length(header));
if header[0] = 79 then
if header[1] = 103 then
if header[2] = 103 then
if header[3] = 83 then
Result := True;
finally
FileReader.Free;
end;
end;
function IsJPEG(FilePath: string): boolean;
var
FileReader: TStream;
header: array[0..2] of byte;
begin
Result := False;
FileReader := TFileStream.Create(FilePath, fmOpenRead);
try
FileReader.seek(0, soFromBeginning);
FileReader.ReadBuffer(header, Length(header));
if header[0] = 255 then
if header[1] = 216 then
if header[2] = 255 then
Result := True;
finally
FileReader.Free;
end;
end;
function IsGif(FilePath: string): boolean;
var
FileReader: TStream;
header: array[0..2] of byte;
begin
Result := False;
FileReader := TFileStream.Create(FilePath, fmOpenRead);
try
FileReader.seek(0, soFromBeginning);
FileReader.ReadBuffer(header, Length(header));
if chr(header[0]) = 'G' then
if chr(header[1]) = 'I' then
if chr(header[2]) = 'F' then
Result := True;
finally
FileReader.Free;
end;
end;
function IsPNG(FilePath: string): boolean;
var
FileReader: TStream;
header: array[0..3] of byte;
begin
Result := False;
FileReader := TFileStream.Create(FilePath, fmOpenRead);
try
FileReader.seek(0, soFromBeginning);
FileReader.ReadBuffer(header, Length(header));
if header[0] = 137 then
if header[1] = 80 then
if header[2] = 78 then
if header[3] = 71 then
Result := True;
finally
FileReader.Free;
end;
end;
end.
|
unit ansichar_1;
interface
implementation
var C: AnsiChar;
procedure Test;
begin
C := 'A';
end;
initialization
Test();
finalization
Assert(C = AnsiChar('A'));
end. |
unit uInjectDecryptFile;
interface
uses System.Classes, Vcl.ExtCtrls, System.Generics.Collections,
shellapi, Winapi.UrlMon, IdHTTP, Winapi.Windows, uTInject.Constant;
type
TInjectDecryptFile = class(TComponent)
private
function DownLoadInternetFile(Source, Dest: string): Boolean;
procedure DownloadFile(Source, Dest: string);
function shell(program_path: string): string;
function idUnique(id: string): string;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function download(clientUrl, mediaKey, tipo, id: string) :string;
end;
implementation
uses
System.StrUtils, System.SysUtils, Vcl.Forms;
{ TImagem }
constructor TInjectDecryptFile.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor TInjectDecryptFile.Destroy;
begin
inherited;
end;
procedure TInjectDecryptFile.DownloadFile(Source, Dest: String);
var
IdHTTP1 : TIdHTTP;
Stream : TMemoryStream;
Url, FileName: String;
begin
IdHTTP1 := TIdHTTP.Create(nil);
Stream := TMemoryStream.Create;
try
IdHTTP1.Get(Source, Stream);
Stream.SaveToFile(Dest);
finally
Stream.Free;
IdHTTP1.Free;
end;
end;
function TInjectDecryptFile.DownLoadInternetFile(Source, Dest: String): Boolean;
var ret:integer;
begin
try
ret:=URLDownloadToFile(nil, PChar(Source), PChar(Dest), 0, nil);
if ret <> 0 then
begin
DownloadFile(Source, Dest) ;
if FileExists(dest) then
ret := 0;
end;
Result := ret = 0
except
Result := False;
end;
end;
function TInjectDecryptFile.idUnique(id: string): String;
var
gID: TGuid;
begin
CreateGUID(gID);
result := copy(gID.ToString, 2, length(gID.ToString) - 2);
end;
function TInjectDecryptFile.download(clientUrl, mediaKey, tipo, id: string): string;
var
form, imagem, diretorio, arq:string;
begin
Result := '';
diretorio := ExtractFilePath(ParamStr(0)) + 'temp\';
Sleep(1);
if not DirectoryExists(diretorio) then
CreateDir(diretorio);
arq := idUnique(id);
imagem := diretorio + arq;
Sleep(1);
if DownLoadInternetFile(clientUrl, imagem + '.enc') then
if FileExists(imagem + '.enc') then
begin
form := format('--in %s.enc --out %s.%s --key %s', [imagem, imagem, tipo, mediakey]);
shell(form);
Sleep(10);
Result:= imagem + '.' + tipo;
end;
end;
function TInjectDecryptFile.shell(program_path: string): string;
var
s1: string;
begin
s1 := ExtractFilePath(Application.ExeName)+'decryptFile.dll ';
ShellExecute(0, nil, 'cmd.exe', PChar('/c '+ s1 + program_path ), PChar(s1 + program_path), SW_HIDE);
end;
end.
|
unit Referee;
interface
uses
Entity, ADODB, DB;
type
TReferee = class(TEntity)
private
FName: string;
public
procedure Add; override;
procedure Save; override;
procedure Edit; override;
procedure Cancel; override;
property Name: string read FName write FName;
constructor Create;
end;
var
ref: TReferee;
implementation
uses
EntitiesData;
constructor TReferee.Create;
begin
if ref = nil then
ref := self;
end;
procedure TReferee.Add;
var
i: integer;
begin
with dmEntities do
begin
for i:=0 to ComponentCount - 1 do
begin
if Components[i] is TADODataSet then
begin
if (Components[i] as TADODataSet).Tag in [9,10] then
begin
(Components[i] as TADODataSet).Open;
(Components[i] as TADODataSet).Append;
end;
end;
end;
end;
end;
procedure TReferee.Save;
var
i: integer;
begin
with dmEntities do
begin
for i:=0 to ComponentCount - 1 do
begin
if Components[i] is TADODataSet then
if (Components[i] as TADODataSet).Tag in [9,10] then
if (Components[i] as TADODataSet).State in [dsInsert,dsEdit] then
(Components[i] as TADODataSet).Post;
end;
end;
end;
procedure TReferee.Edit;
begin
end;
procedure TReferee.Cancel;
var
i: integer;
begin
with dmEntities do
begin
for i:=0 to ComponentCount - 1 do
begin
if Components[i] is TADODataSet then
if (Components[i] as TADODataSet).Tag in [9,10] then
if (Components[i] as TADODataSet).State in [dsInsert,dsEdit] then
(Components[i] as TADODataSet).Cancel;
end;
end;
end;
end.
|
unit ubads;
{$mode delphi}
interface
uses
Classes, SysUtils, utypes, Laz_And_Controls, AndroidWidget;
const
MaxBad = 5000;
type
TBadState = (bsStay, bsLive, bsGone, bsSleep);
TBad = record
Center : TPointF;
BadState : TBadState;
Orange : boolean;
ind : integer;
Bad : boolean;
Gems : boolean;
bmp : jBitMap;
mass : Single;
Border : Boolean;
DX, DY : Single;
end;
procedure DrawBads(Canvas : jCanvas);
procedure Collide_Ball(var ball: TBad; var ball2: TBad);
procedure SetBad(aX, aY : Single; Bord : boolean = False; ForceOrange : boolean = False);
function BallHitBad(pBall : TPointF; var Bonus : integer) : boolean;
procedure CheckCollides;
procedure BadOnTimer;
var
Bads : array[ 0.. MaxBad ] of TBad;
BadCount : integer = 0;
StartBad : integer = 0;
implementation
uses uball, ubgr, ucurr, ububble, asset, Math, ttcalc, udbg;
function Check(P : TPointF) : boolean;
var I : integer;
dx0, dy0 : Single;
begin
Result := False;
I := BadCount - 1;
while (I >= StartBad) do with Bads[ I ] do
begin
dx0 := P.x - Center.x;
dy0 := P.y - Center.y;
if dx0 * dx0 + dy0 * dy0 < WallWallGap then
Exit;
Dec(I);
end;
Result := True;
end;
procedure BadOnTimer;
var I : integer;
begin
for I := StartBad to BadCount - 1 do with Bads[ I ] do if BadState = bsLive then
begin
Center.Y := Center.Y + DY;
Center.X := Center.X + DX;
// end else
// begin
// if (BadState = bsSleep) and (Cent.Y - Center.Y < ScreenHeight4) then
// BadState := bsLive;
end;
end;
function BallHitBad(pBall : TPointF; var Bonus : integer) : boolean;
var I : integer;
d : Single;
begin
Result := False;
Bonus := 0;
d := (gm.BallDiam + gm.StoneDiam) / 2;
for I := StartBad to BadCount - 1 do with Bads[ I ] do
if (BadState < bsGone) and (Distance(pBall, Center) < d) then
begin
BadState := bsGone;
if Bad then
begin
Result := True;
Exit;;
end else
begin
if Gems then
begin
Bonus := GemBonus;
Play('bleep.mp3');
end
else if Orange then
begin
Bonus := OrangeBonus;
Play('chime.mp3');
end
else
begin
Bonus := FruitBonus;
Play('chime1.mp3');
end;
MakeBubbles(Center.X - LeftX, Center.Y - TopY, Bonus);
end;
end;
end;
procedure SetBad(aX, aY : Single; Bord : boolean = False; ForceOrange : boolean = False);
begin
// zz('setBad,aX=' + inttostr(round(aX)) + ',aY='+inttostr(round(aY)) + ifthen(bord, ',bord',''));
if aY > StartLimY then
Exit;
{$IFDEF DEBUG}
try
{$ENDIF}
with Bads[ BadCount ] do
begin
Center := PointF(aX, aY);
bmp := nil;
BadState := bsStay;
DX := 0;
DY := 0;
ind := 0;
Border := Bord;
Mass := 100;
Orange := False;
if Bord then
begin
if not Check(Center) then
Exit;
Bad := True;
if Cat then
bmp := GetCats(ind)
else
bmp := GetAlien(ind);
end else
begin
Bad := False;
if ForceOrange then
begin
if not Check(Center) then
Exit;
//zz('Orange ' + ifthen((aX > LeftX) and (aX < LeftX + gm.ScreenWidth), 'scr ', '--- ') + p2s(pointf(ax,ay)));
Orange := True;
bmp := GetFruit(ind);
end
else
begin
Center := PointF(aX + gm.Pad + gm.Off * (random(100) * 0.01),
aY + gm.Pad + gm.Off * (random(100) * 0.01));
if not Check(Center) then
Exit;
if random(100) < MulDiv(70 - Level * 3, BadNum, GoodNum) then
begin
Inc(GoodNum);
if random(100) < 20 then
bmp := GetGem(ind)
else
bmp := GetFruit(ind);
end
else
begin
Inc(BadNum);
Bad := True;
mass := 1;
if Cat then
bmp := GetCats(ind)
else
bmp := GetAlien(ind);
end;
end;
end;
end;
Inc(BadCount);
if MaxBad = BadCount then
Fatal('MaxBad = BadCount');
{$IFDEF DEBUG}
except
zz('*setbad');
raise;
end;
{$ENDIF}
end;
procedure TrimBads;
begin
while Bads[StartBad].Center.Y > FisScrSt.Bottom do
begin
Bads[StartBad].BadState := bsGone;
Inc(StartBad);
if StartBad = BadCount then
Break;
end;
end;
procedure DrawBads(Canvas : jCanvas);
var I : integer;
NowAlive : boolean;
Cent : TPointF;
sp : Single;
begin
TrimBads;
NowAlive := (User <> uNovice) and (TimeCount mod 12 = 2) and not (asDemo in AppState);
for I := StartBad to BadCount - 1 do with Bads[I] do
begin
if (BadState < bsGone) and PtInRect(FisScrSt, Center) then
begin
if NowAlive and (BadState = bsStay) and (mass = 1) then
begin
BadState := bsLive;
if not Border then
begin
sp := speed * 0.2;
DX := sp * ((50 - random(100)) / 100);
DY := sp * (random(100) / 100);
end;
end;
Cent.X := Center.X - LeftX;
Cent.Y := Center.Y - TopY;
PutBitMap(Canvas, bmp, Cent);
end;
end;
end;
procedure Collide_Ball(var ball: TBad; var ball2: TBad);
var
dx, dy, D : Single;
collisionision_angle : Single;
magnitude_1, magnitude_2, direction_1, direction_2 : Single;
new_xspeed_1, new_yspeed_1, new_xspeed_2, new_yspeed_2 : Single;
final_xspeed_1, final_xspeed_2, final_yspeed_1, final_yspeed_2 : Single;
pa, pb : TPointF;
begin
if (ball.BadState <> bsLive) and (ball2.BadState <> bsLive) or (abs(ball.Center.X - ball2.Center.X) > gm.BallDiam) or (abs(ball.Center.Y - ball2.Center.Y) > gm.BallDiam) then
Exit;
pa := ball.Center;
pb := ball2.Center;
D := Distance(pa, pb);
if D < 1 then
Exit;
if D > gm.StoneDiam then
Exit;
pa.x := pa.x + ball.dx;
pa.y := pa.y + ball.dy;
pb.x := pb.x + ball2.dx;
pb.y := pb.y + ball2.dy;
if Distance(pa, pb) > D then
Exit;
dx := ball.Center.x - ball2.Center.x;
dy := ball.Center.y - ball2.Center.y;
collisionision_angle := arctan2(dy, dx);
magnitude_1 := sqrt(ball.dx * ball.dx + ball.dy * ball.dy);
magnitude_2 := sqrt(ball2.dx * ball2.dx + ball2.dy * ball2.dy);
direction_1 := arctan2(ball.dy, ball.dx);
direction_2 := arctan2(ball2.dy, ball2.dx);
new_xspeed_1 := magnitude_1 * cos(direction_1 - collisionision_angle);
new_yspeed_1 := magnitude_1 * sin(direction_1 - collisionision_angle);
new_xspeed_2 := magnitude_2 * cos(direction_2 - collisionision_angle);
new_yspeed_2 := magnitude_2 * sin(direction_2 - collisionision_angle);
final_xspeed_1 := ((ball.mass - ball2.mass) * new_xspeed_1 + (ball2.mass + ball2.mass) * new_xspeed_2) / (ball.mass + ball2.mass);
final_xspeed_2 := ((ball.mass + ball.mass) * new_xspeed_1 + (ball2.mass - ball.mass) * new_xspeed_2) / (ball.mass + ball2.mass);
final_yspeed_1 := new_yspeed_1;
final_yspeed_2 := new_yspeed_2;
ball.dx := cos(collisionision_angle) * final_xspeed_1 + cos(collisionision_angle + PI/2) * final_yspeed_1;
ball.dy := sin(collisionision_angle) * final_xspeed_1 + sin(collisionision_angle + PI/2) * final_yspeed_1;
ball2.dx := cos(collisionision_angle) * final_xspeed_2 + cos(collisionision_angle + PI/2) * final_yspeed_2;
ball2.dy := sin(collisionision_angle) * final_xspeed_2 + sin(collisionision_angle + PI/2) * final_yspeed_2;
ball.BadState := bsLive;
ball2.BadState := bsLive;
end;
procedure CheckCollides;
var I, J : integer;
begin
for I := StartBad to BadCount - 1 do
for J := I + 1 to BadCount - 1 do
Collide_Ball(Bads[ I ], Bads[ J ]);
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2019 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit RSConsole.FrameViews;
interface
uses
System.Classes, FMX.StdCtrls, FMX.Forms,
RSConsole.Data, FMX.Grid, System.Generics.Collections,
RSConsole.FrameAdd, FMX.TabControl,
RSConsole.Types, RSConsole.TypesViews, FMX.Controls,
FMX.Controls.Presentation, FMX.Types, RSConsole.FramePush,
RSConsole.FrameExplorer;
type
TViewsFrame = class(TFrame)
ViewsControl: TTabControl;
PushTabItem: TTabItem;
PushFrame1: TPushFrame;
ExplorerTabItem: TTabItem;
ExplorerFrame: TExplorerFrame;
procedure ViewsControlChange(Sender: TObject);
private
{ Private declarations }
FEMSConsoleData: TEMSConsoleData;
// procedure OnTabItemClick(Sender: TObject);
function CreateTab(const AName: string): TEMSTabItem;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure DisableTabs(ATab: TEMSTabItem = nil);
procedure EnableTabs;
procedure ChangeTab(AIndex: Integer);
procedure CreateUsersView(const AUserID: string);
procedure CreateGroupsView(const AGroupName: string);
procedure CreateInstallationsView(const AInstallationID: string);
procedure CreateEdgeModulesView(const AEdgePointID: string);
procedure CreateResourcesView(const AResourceID: string);
procedure RefreshEndpoints;
procedure UpdateStyle(const AStyle: String);
property EMSConsoleData: TEMSConsoleData read FEMSConsoleData
write FEMSConsoleData;
end;
implementation
uses RSConsole.Form, RSConsole.Consts;
{$R *.fmx}
{ TViewsFrame }
constructor TViewsFrame.Create(AOwner: TComponent);
begin
inherited;
FEMSConsoleData := TEMSConsoleData.Create;
CreateUsersView('');
CreateGroupsView('');
CreateInstallationsView('');
CreateEdgeModulesView('');
CreateResourcesView('');
ViewsControl.ActiveTab := ExplorerTabItem;
ViewsControl.Repaint;
end;
procedure TViewsFrame.UpdateStyle(const AStyle: String);
var
LIndex: Integer;
begin
for LIndex := 0 to 4 do
TEMSTabItem(ViewsControl.Tabs[LIndex]).FrameJSONGrid.UpdateStyle(AStyle);
ExplorerFrame.UpdateStyle(AStyle);
end;
procedure TViewsFrame.ChangeTab(AIndex: Integer);
begin
case AIndex of
USERS_ITEM:
begin
ViewsControl.TabIndex := 0;
TEMSTabItem(ViewsControl.ActiveTab).OnTabItemClick(Self);
end;
GROUPS_ITEM:
begin
ViewsControl.TabIndex := 1;
TEMSTabItem(ViewsControl.ActiveTab).OnTabItemClick(Self);
end;
INSTALLATIONS_ITEM:
begin
ViewsControl.TabIndex := 2;
TEMSTabItem(ViewsControl.ActiveTab).OnTabItemClick(Self);
end;
MODULES_ITEM:
begin
ViewsControl.TabIndex := 3;
TEMSTabItem(ViewsControl.ActiveTab).OnTabItemClick(Self);
end;
RESOURCES_ITEM:
begin
ViewsControl.TabIndex := 4;
TEMSTabItem(ViewsControl.ActiveTab).OnTabItemClick(Self);
end;
PUSH_ITEM:
begin
ViewsControl.ActiveTab := PushTabItem;
end;
ENDPOINTS_ITEM:
begin
ViewsControl.ActiveTab := ExplorerTabItem;
end;
end;
end;
procedure TViewsFrame.CreateUsersView(const AUserID: string);
var
LTabItem: TEMSTabItem;
begin
LTabItem := CreateTab(strUsers);
LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(0);
LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(1);
LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(2);
end;
procedure TViewsFrame.CreateGroupsView(const AGroupName: string);
var
LTabItem: TEMSTabItem;
begin
LTabItem := CreateTab(strGroups);
LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(0);
LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(1);
LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(2);
end;
procedure TViewsFrame.CreateInstallationsView(const AInstallationID: string);
var
LTabItem: TEMSTabItem;
begin
LTabItem := CreateTab(strInstallations);
LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(0);
LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(1);
LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(2);
LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(3);
LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(4);
{$IFNDEF DEBUG}
LTabItem.FrameJSONGrid.AddItemButton.Visible := False;
{$ENDIF}
end;
procedure TViewsFrame.CreateEdgeModulesView(const AEdgePointID: string);
var
LTabItem: TEMSTabItem;
begin
LTabItem := CreateTab(strEdgeModules);
LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(0);
LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(1);
LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(2);
LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(3);
LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(4);
LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(5);
LTabItem.FrameJSONGrid.AddItemButton.Visible := False;
end;
procedure TViewsFrame.CreateResourcesView(const AResourceID: string);
var
LTabItem: TEMSTabItem;
begin
LTabItem := CreateTab(strResources);
LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(0);
LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(1);
LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(2);
LTabItem.FrameJSONGrid.ColumnsReadOnly.Add(3);
LTabItem.FrameJSONGrid.AddItemButton.Visible := False;
end;
function TViewsFrame.CreateTab(const AName: string): TEMSTabItem;
begin
Result := nil;
if AName = strUsers then
Result := TEMSTabItem(ViewsControl.Insert(0, TUsersTabItem));
if AName = strGroups then
Result := TEMSTabItem(ViewsControl.Insert(1, TGroupsTabItem));
if AName = strInstallations then
Result := TEMSTabItem(ViewsControl.Insert(2, TInstallationTabItem));
if AName = strEdgeModules then
Result := TEMSTabItem(ViewsControl.Insert(3, TEdgeModuleTabItem));
if AName = strResources then
Result := TEMSTabItem(ViewsControl.Insert(4, TResourceTabItem));
Result.Name := AName + cTab;
Result.Text := AName;
Result.EMSConsoleData := FEMSConsoleData;
ViewsControl.ActiveTab := Result;
end;
destructor TViewsFrame.Destroy;
begin
FEMSConsoleData.Free;
inherited;
end;
procedure TViewsFrame.DisableTabs(ATab: TEMSTabItem = nil);
var
I: Integer;
begin
for I := 0 to ViewsControl.TabCount - 1 do
if ATab <> ViewsControl.Tabs[I] then
ViewsControl.Tabs[I].Enabled := False;
end;
procedure TViewsFrame.EnableTabs;
var
I: Integer;
begin
for I := 0 to ViewsControl.TabCount - 1 do
ViewsControl.Tabs[I].Enabled := True;
end;
procedure TViewsFrame.ViewsControlChange(Sender: TObject);
begin
RefreshEndpoints;
end;
procedure TViewsFrame.RefreshEndpoints;
begin
if ViewsControl.ActiveTab = ExplorerTabItem then
ExplorerFrame.RefreshEndpoints;
end;
end.
|
unit fGMV_AddVCQ;
{
================================================================================
*
* Application: Vitals
* Revision: $Revision: 1 $ $Modtime: 12/20/07 12:43p $
* Developer: ddomain.user@domain.ext/doma.user@domain.ext
* Site: Hines OIFO
*
* Description: Used to selected Vitals/Categories/Qualifiers from the
* TGMV_FileReference objects
*
* Notes:
*
================================================================================
* $Archive: /Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSCOMMON/fGMV_AddVCQ.pas $
*
* $History: fGMV_AddVCQ.pas $
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 8/12/09 Time: 8:29a
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSCOMMON
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 3/09/09 Time: 3:38p
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_6/Source/VITALSCOMMON
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 1/13/09 Time: 1:26p
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_4/Source/VITALSCOMMON
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/14/07 Time: 10:29a
* Created in $/Vitals GUI 2007/Vitals-5-0-18/VITALSCOMMON
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/16/06 Time: 5:43p
* Created in $/Vitals/VITALS-5-0-18/VitalsCommon
* GUI v. 5.0.18 updates the default vital type IENs with the local
* values.
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/16/06 Time: 5:33p
* Created in $/Vitals/Vitals-5-0-18/VITALS-5-0-18/VitalsCommon
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/24/05 Time: 3:33p
* Created in $/Vitals/Vitals GUI v 5.0.2.1 -5.0.3.1 - Patch GMVR-5-7 (CASMed, No CCOW) - Delphi 6/VitalsCommon
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 4/16/04 Time: 4:17p
* Created in $/Vitals/Vitals GUI Version 5.0.3 (CCOW, CPRS, Delphi 7)/VITALSCOMMON
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 1/26/04 Time: 1:06p
* Created in $/Vitals/Vitals GUI Version 5.0.3 (CCOW, Delphi7)/V5031-D7/Common
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 10/29/03 Time: 4:14p
* Created in $/Vitals503/Common
* Version 5.0.3
*
* ***************** Version 2 *****************
* User: Zzzzzzandria Date: 7/05/02 Time: 3:49p
* Updated in $/Vitals GUI Version 5.0/Common
*
* ***************** Version 1 *****************
* User: Zzzzzzpetitd Date: 4/04/02 Time: 3:53p
* Created in $/Vitals GUI Version 5.0/Common
*
*
*
================================================================================
}
interface
uses
Windows,
Messages,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls;
type
TfrmGMV_AddVCQ = class(TForm)
btnCancel: TButton;
btnOK: TButton;
lbxVitals: TListBox;
procedure LoadVitals;
procedure LoadCategory;
procedure LoadQualifiers;
procedure lbxVitalsDblClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmGMV_AddVCQ: TfrmGMV_AddVCQ;
implementation
uses uGMV_Common, uGMV_FileEntry, uGMV_Const, uGMV_GlobalVars;
{$R *.DFM}
procedure TfrmGMV_AddVCQ.LoadVitals;
var
i: integer;
begin
for i := 0 to GMVTypes.Entries.Count - 1 do
lbxVitals.Items.AddObject(GMVTypes.Entries[i], GMVTypes.Entries.Objects[i]);
Caption := 'Add Vital';
end;
procedure TfrmGMV_AddVCQ.LoadCategory;
var
i: integer;
begin
for i := 0 to GMVCats.Entries.Count - 1 do
lbxVitals.Items.AddObject(GMVCats.Entries[i], GMVCats.Entries.Objects[i]);
Caption := 'Add Vital Category';
end;
procedure TfrmGMV_AddVCQ.LoadQualifiers;
var
i: integer;
begin
for i := 0 to GMVQuals.Entries.Count - 1 do
lbxVitals.Items.AddObject(GMVQuals.Entries[i], GMVQuals.Entries.Objects[i]);
Caption := 'Add Vital Qualifier';
end;
procedure TfrmGMV_AddVCQ.lbxVitalsDblClick(Sender: TObject);
begin
GetParentForm(Self).Perform(CM_VITALSELECTED,0,0);
end;
end.
|
(****************************************************************************)
(* *)
(* REV97.PAS - The Relativity Emag (coded in Turbo Pascal 7.0) *)
(* *)
(* "The Relativity Emag" was originally written by En|{rypt, |MuadDib|. *)
(* This source may not be copied, distributed or modified in any shape *)
(* or form. Some of the code has been derived from various sources and *)
(* units to help us produce a better quality electronic magazine to let *)
(* the scene know that we are THE BOSS. *)
(* *)
(* Program Notes : This program presents "The Relativity Emag" *)
(* *)
(* ASM/TP70 Coder : xxxxx xxxxxxxxx (En|{rypt) - xxxxxx@xxxxxxxxxx.xxx *)
(* ------------------------------------------------------------------------ *)
(* TP70 Coder : xxxxx xxxxxxxxx (|MuadDib|) - xxxxxx@xxxxxxxxxx.xxx *)
(* *)
(****************************************************************************)
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
(****************************************************************************)
(* Reserved Words - The Heading Specifies The Program Name And Parameters. *)
(****************************************************************************)
Program The_Relativity_Electronic_Magazine;
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
(****************************************************************************)
(* Compiler Directives - These Directives Are Not Meant To Be Modified. *)
(****************************************************************************)
{$A+}{$B+}{$D+}{$F+}{$G+}{$I+}{$K+}{$L+}{$N+}{$O-}{$P+}{$Q-}{$R-}{$S+}{$T+}
{$V-}{$W+}{$X+}{$Y+}
{$C MOVEABLE PRELOAD DISCARDABLE}
{$D The Relativity Emag (in Turbo Pascal 7.0)}
{$M 65000,0,655360}
{$S 32768}
{$IFNDEF __BPREAL__}
{$DEFINE NOEMS}
{$ENDIF}
{$DEFINE MSDOS}
{$DEFINE VER70}
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
(****************************************************************************)
(* Reserved Words - Each Identifier Names A Unit Used By The Program. *)
(****************************************************************************)
uses Crt,Dos,RevDat,RevGfx,RevMem,U_Vga,U_ffGif,
U_Kb,RevAnsi,revsmoot,REVCOM,REVSET,AdvHSC,revhelp,
revconst,revhsc,revrad,revmus,revinit,revmid,worms;
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
(****************************************************************************)
(* Reserved Words - Extended FileExists Function From The RevDat.pas. *)
(****************************************************************************)
function FileExists(filename: string) : Boolean;
var
f: file;
begin
{$I-}
Assign(f, FileName);
FileMode := 0;
Reset(f);
Close(f);
{$I+}
FileExists := (IOResult = 0) and (FileName <> '');
end;
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
(****************************************************************************)
(* Reserved Words - Controls The Initialization Phases. (EXE And WAD Files) *)
(****************************************************************************)
procedure InitializeDetectionPhase;
begin
GetMainMemory;
CheckMainMemory;
FlushDiskCaches;
CheckXMSEMSMemory;
end;
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
(****************************************************************************)
(* Reserved Words - Starting And Ending Initialization Phases (Detection). *)
(****************************************************************************)
procedure PrintDetectionPhase;
begin
HideCursor;
Writeln;
Writeln('CPU IDENTIFICATION ROUTINES HAVE BEEN EXCLUDED IN THIS ISSUE.');
Writeln('--------------------------------------------------------------------------------');
Writeln('Type Rev-01.EXE /? for Help');
Writeln;
InitializeDetectionPhase;
Writeln;
Writeln('Last Updated: December 10th, 1996');
Writeln;
Writeln('--------------------------------------------------------------------------------');
end;
procedure PrintEndingPhase;
var k:char;
begin
Reset80x25VideoScreen;
HideCursor;
Writeln(' Relativity Emag Issue #1!');
Writeln(' Coded by En|{rypt/MuadDib');
Writeln(' Relativity Productions(c)1997');
Writeln;
Writeln(' Credits to all REV 97 members for');
Writeln(' sticking through all the 5 months');
Writeln(' of pain & agony, but its worthit!');
Writeln;
Writeln(' For Future Issues Goto Http://www.geocities.com/soho/6477 ');
Writeln;
Writeln(' press any key to continue');
k:=readkey;
end;
procedure DisplayGIF(GIFname:string);
begin
BgiPath := '';
Fname1 := GIFname;
if Gif_Info(Fname1,Info1)<>Gif_Ok then begin
Writeln('Error: ',Gif_ErrStr); Halt; end;
with Info1 do
DummyGif := Gif_Display(Fname1,BgiPath,-1);
ClearKeyBuf; WaitKey(0);
FadedownRGBScreen;
SetVideo(U_Lm);
end;
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
(****************************************************************************)
(* Reserved Words - Stops The Menu Phase And Begins The Ending Phase. (FIN) *)
(****************************************************************************)
procedure StopMainMenuPhase;
begin
if curmus<>musdef then
begin
StopMusic(music[curmus,1],music[curmus,2]);
PlayMusic(music[musdef,1],music[musdef,2]);
end;
Reset80x25VideoScreen;
ExtractFileFromDat('SVGA256.BGI');
ExtractFileFromDat(closinggif);
DisplayGIF(closinggif);
DeleteDatFile(closinggif);
DeleteDatFile('SVGA256.BGI');
Reset80x25VideoScreen;
TextColor(7);
TextBackground(black);
PrintEndingPhase;
Reset80x25VideoScreen;
StopMusic(music[musdef,1],music[musdef,2]);
Halt;
end;
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
(****************************************************************************)
(* Reserved Words - Procedures Related To Ansi & The Menu Highlight Bars. *)
(****************************************************************************)
procedure write_bar(e,b,t:integer);
var
i,a,x,y:integer;
str:st22;
begin
textcolor(black);
textbackground(lightgray);
x:=25;
y:=15;
for a := 1 to 18 do
begin
if b=a then
begin
gotoxy(x-1,y);
str:=subscreen[e][a];
textbackground(red);
write(' ');
textcolor(darkgray);
write(str[1]);
write(str[2]);
for i:= 3 to length(str) do
write(str[i]);
end
else
begin
gotoxy(x-1,y);
str:=subscreen[e][a];
textbackground(darkgray);
write(' ');
textcolor(red);
write(str[1]);
textcolor(lightred);
write(str[2]);
textcolor(darkgray);
for i:= 3 to length(str) do
write(str[i]);
end;
inc(y);
if a=9 then
begin
y:=15;
x:=48;
end;
end;
end;
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
(****************************************************************************)
(* Reserved Words - Starts The Main Menu Phase And Controls All Sub Menus. *)
(****************************************************************************)
Procedure ShowArticle(str,str2:st12);
var dep:longint;
begin
ExtractFileFromDat(str);
FadedownRGBScreen;
Reset80x25VideoScreen;
ReadAnsiBinAndLoadToMem(str,dep);
DeleteDatFile(str);
SmoothScroll(dep,str);
DisplayaNsi(str2);
hidecursor;
end;
Function EmptySub(sub:subscr):boolean;
var i:integer;
begin
EmptySub:=True;
for i:= 1 to topics do
begin
if sub[i]<>'' then
EmptySub:=false;
end;
end;
procedure StartMainMenuPhase;
procedure StartCurrentMenu(e:integer);
var c,b,P,code : Integer;
k : Char;
str : string;
label stop,damn;
begin
FadedownRGBScreen;
Reset80x25VideoScreen;
HideCursor;
Displayansi(defmenufile);
k:=#22;
c:=1;
write_bar(e,c,topics);
{k:=readkey;}
k:=#22;
repeat
if (k<>#13) and (k<>#27)then
k:=readkey;
if k=#0 then
k:=readkey;
case k of
#59 : begin
help(false,subfile[e][c]);
hidecursor;
Displayansi(defmenufile);
write_bar(e,c,topics);
end;
#72 : begin dec(c); end;
#77 : begin
if c in [1,2,3,4,5,6,7,8,9] then c:=c+9;
end;
#80 : begin inc(c); end;
#81 : begin
if c in [10,11,12,13,14,15,16,17,18] then c:=18;
if c=9 then c:=10;
if c in [1,2,3,4,5,6,7,8] then c:=9;
end;
#73 : begin
if c in [1,2,3,4,5,6,7,8,9] then c:=1;
if c=10 then c:=9;
if c in [10,11,12,13,14,15,16,17,18] then c:=10;
end;
#75 : begin
if c in [10,11,12,13,14,15,16,17,18] then c:=c-9;
end;
#27,'q' : begin StartMainMenuPhase; end;
#13 : Begin
if c in [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17] then
begin
if subfile[e][c]<>'' then
ShowArticle(subfile[e][c],DEFMENUFILE)
else
nope;
k:=#22;
end;
if c=18 then
StartMainMenuPhase;
end;
end;
if c = topics+1 then
c := 1;
if c = 0 then
c := topics;
write_bar(e,c,topics);
k:=readkey;
until true=false; {never....hehe}
end;
var c,b,P,code : Integer;
k : Char;
str : string;
label stop,damn;
begin
c:=cc;
FadedownRGBScreen;
Reset80x25VideoScreen;
HideCursor;
Displayansi(DEFMENUFILE);
k:=#22;
write_bar(topics+1,c,topics);
k:=readkey;
repeat
if (k<>#13) and (k<>#27) then
k:=readkey;
if k=#0 then
k:=readkey;
case k of
#59 : begin
cc:=c;
help(false,subfile[1][c]);
hidecursor;
Displayansi(defmenufile);
write_bar(topics+1,c,topics);
end;
#72 : begin dec(c); end;
#77 : begin
if c in [1,2,3,4,5,6,7,8,9] then c:=c+9;
end;
#80 : begin inc(c); end;
#81 : begin
if c in [10,11,12,13,14,15,16,17,18] then c:=18;
if c=9 then c:=10;
if c in [1,2,3,4,5,6,7,8] then c:=9;
end;
#73 : begin
if c in [1,2,3,4,5,6,7,8,9] then c:=1;
if c=10 then c:=9;
if c in [10,11,12,13,14,15,16,17,18] then c:=10;
end;
#75 : begin
if c in [10,11,12,13,14,15,16,17,18] then c:=c-9;
end;
#27,'q' : begin FadedownRGBScreen; StopMainMenuPhase; end;
#13 : Begin
if c= 1 then
begin
cc:=c;
ShowArticle(subfile[1][1],DEFMENUFILE);
end;
if c= 11 then
begin
cc:=c;
FadedownRGBScreen;
Reset80x25VideoScreen;
if not fileexists('WORMS.LVL') THEN
extractfilefromdat('WORMS.LVL');
startgame;
FadedownRGBScreen;
Reset80x25VideoScreen;
HideCursor;
Displayansi(DEFMENUFILE);
write_bar(topics+1,c,topics);
K:=#22;
end;
if c in [{1,}2,3,4,5,6,7,8,9,10,{11,}12,13,14,15,16,17] then
begin
if not emptysub(subscreen[c]) then
begin
cc:=c;
StartCurrentMenu(c);
end
else
nope;
end;
if c= 18 then
StopMainMenuPhase;
end;
end;
if c = topics+1 then
c := 1;
if c = 0 then
c := topics;
write_bar(topics+1,c,topics);
k:=readkey;
until true=false; {never....hehe}
end;
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
(****************************************************************************)
(* Reserved Words - Preperation Phases For The Introduction & Detection. *)
(****************************************************************************)
procedure PhazePre;
begin
Reset80x25VideoScreen;
TextColor(7);
PrintDetectionPhase;
DelayScreen(1000);
Reset80x25VideoScreen;
hidecursor;
PlayMusic(music[musdef,1],music[musdef,2]);
{ ExtractFileFromDat('DUNEINTR.MOD');
StartBackgroundMusic('DUNEINTR.MOD');}
ExtractFileFromDat('SVGA256.BGI');
ExtractFileFromDat(openinggif);
DisplayGIF(openinggif);
DeleteDatFile(openinggif);
Reset80x25VideoScreen;
end;
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
(****************************************************************************)
(* Reserved Words - Checks For Configuration File, Dosen't Work In TP IDE!! *)
(****************************************************************************)
procedure CheckCFG;
var k:char;
begin
if not FileExists(ConfigFile) then
begin
SetMidasCfg;
Writeln;
Writeln('Press any key to continue...');
k:=readkey;
end;
end;
Procedure InitRadVol;
begin
vol:=62;
radvolume(vol);
volu:=true;
end;
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
(****************************************************************************)
(* Reserved Words - Statements To Be Executed When The Program Runs. *)
(****************************************************************************)
begin
CHECKBREAK:=FALSE;
cc:=1;
{ initkey(10);}
InitradVol;
InitMusic;
InitSubFiles;
InitSubScreen;
RevCommand;
{ CheckCFG;}
PhazePre;
StartMainMenuPhase;
{ initkey(10);}
end. |
{*******************************************************}
{ }
{ Delphi REST Client Framework }
{ }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$HPPEMIT LINKUNIT}
unit REST.Backend.KinveyPushDevice;
interface
uses
System.Classes,
System.SysUtils,
System.JSON,
System.PushNotification,
REST.Backend.Providers,
REST.Backend.PushTypes,
REST.Backend.KinveyProvider,
REST.Backend.KinveyApi,
REST.Backend.Exception;
type
{$IFDEF IOS}
{$DEFINE PUSH}
{$ENDIF}
{$IFDEF ANDROID}
{$DEFINE PUSH}
{$ENDIF}
TKinveyPushDeviceAPI = class(TKinveyServiceAPIAuth, IBackendPushDeviceApi)
private const
sKinvey = 'Kinvey';
private
FGCMAppID: string;
protected
{ IBackendPushDeviceAPI }
function GetPushService: TPushService; // May raise exception
function HasPushService: Boolean;
procedure RegisterDevice(AOnRegistered: TDeviceRegisteredAtProviderEvent);
procedure UnregisterDevice;
end;
TKinveyPushDeviceService = class(TKinveyBackendService<TKinveyPushDeviceAPI>, IBackendService, IBackendPushDeviceService)
protected
procedure DoAfterConnectionChanged; override;
function CreateBackendApi: TKinveyPushDeviceAPI; override;
{ IBackendPushDeviceService }
function CreatePushDeviceApi: IBackendPushDeviceApi;
function GetPushDeviceApi: IBackendPushDeviceApi;
end;
EKinveyPushNotificationError = class(EBackendServiceError);
implementation
uses
System.Generics.Collections,
System.TypInfo,
REST.Backend.Consts,
REST.Backend.ServiceFactory
{$IFDEF PUSH}
{$IFDEF IOS}
,FMX.PushNotification.IOS // inject IOS push provider
{$ENDIF}
{$IFDEF ANDROID}
,FMX.PushNotification.Android // inject GCM push provider
{$ENDIF}
{$ENDIF}
;
{ TKinveyPushDeviceService }
function TKinveyPushDeviceService.CreatePushDeviceApi: IBackendPushDeviceApi;
begin
Result := CreateBackendApi;
end;
function TKinveyPushDeviceService.CreateBackendApi: TKinveyPushDeviceAPI;
begin
Result := inherited;
if ConnectionInfo <> nil then
Result.FGCMAppID := ConnectionInfo.AndroidPush.GCMAppID
else
Result.FGCMAppID := '';
end;
function TKinveyPushDeviceService.GetPushDeviceApi: IBackendPushDeviceApi;
begin
EnsureBackendApi;
Result := BackendAPI;
end;
procedure TKinveyPushDeviceService.DoAfterConnectionChanged;
begin
inherited;
if BackendAPI <> nil then
begin
if ConnectionInfo <> nil then
BackendAPI.FGCMAppID := ConnectionInfo.AndroidPush.GCMAppID
else
BackendAPI.FGCMAppID := '';
end;
end;
{ TKinveyPushDeviceAPI }
function GetDeviceID(const AService: TPushService): string;
begin
Result := AService.DeviceIDValue[TPushService.TDeviceIDNames.DeviceID];
end;
function GetDeviceName: string;
begin
{$IFDEF IOS}
Result := 'ios'; // Do not localize
{$ENDIF}
{$IFDEF ANDROID}
Result := 'android'; // Do not localize
{$ENDIF}
{$IFDEF MSWINDOWS}
Result := 'windows'; // Do not localize
{$ENDIF}
end;
function GetServiceName: string;
begin
{$IFDEF PUSH}
{$IFDEF IOS}
Result := TPushService.TServiceNames.APS;
{$ENDIF}
{$IFDEF ANDROID}
Result := TPushService.TServiceNames.GCM;
{$ENDIF}
{$IFDEF MSWINDOWS}
Result := '';
{$ENDIF}
{$ENDIF}
end;
function GetService(const AServiceName: string): TPushService;
begin
Result := TPushServiceManager.Instance.GetServiceByName(AServiceName);
end;
procedure GetRegistrationInfo(const APushService: TPushService;
out ADeviceID, ADeviceToken: string);
begin
ADeviceID := APushService.DeviceIDValue[TPushService.TDeviceIDNames.DeviceID];
ADeviceToken := APushService.DeviceTokenValue[TPushService.TDeviceTokenNames.DeviceToken];
if ADeviceID = '' then
raise EKinveyPushNotificationError.Create(sDeviceIDUnavailable);
if ADeviceToken = '' then
raise EKinveyPushNotificationError.Create(sDeviceTokenUnavailable);
end;
function TKinveyPushDeviceAPI.GetPushService: TPushService;
var
LServiceName: string;
LDeviceName: string;
LService: TPushService;
begin
LDeviceName := GetDeviceName;
Assert(LDeviceName <> '');
LServiceName := GetServiceName;
if LServiceName = '' then
raise EKinveyPushNotificationError.CreateFmt(sPushDeviceNoPushService, [sKinvey, LDeviceName]);
LService := GetService(LServiceName);
if LService = nil then
raise EKinveyPushNotificationError.CreateFmt(sPushDevicePushServiceNotFound, [sKinvey, LServiceName]);
if LService.ServiceName = TPushService.TServiceNames.GCM then
if not (LService.Status in [TPushService.TStatus.Started]) then
begin
if FGCMAppID = '' then
raise EKinveyPushNotificationError.Create(sPushDeviceGCMAppIDBlank);
LService.AppProps[TPushService.TAppPropNames.GCMAppID] := FGCMAppID;
end;
Result := LService;
end;
function TKinveyPushDeviceAPI.HasPushService: Boolean;
var
LServiceName: string;
begin
LServiceName := GetServiceName;
Result := (LServiceName <> '') and (GetService(LServiceName) <> nil);
end;
procedure TKinveyPushDeviceAPI.RegisterDevice(
AOnRegistered: TDeviceRegisteredAtProviderEvent);
var
LDeviceName: string;
LServiceName: string;
{$IFDEF PUSH}
LDeviceID: string;
LDeviceToken: string;
{$ENDIF}
begin
LDeviceName := GetDeviceName;
Assert(LDeviceName <> '');
LServiceName := GetServiceName;
if LServiceName = '' then
raise EKinveyPushNotificationError.CreateFmt(sPushDeviceNoPushService, [sKinvey, LDeviceName]);
{$IFDEF PUSH}
GetRegistrationInfo(GetPushService, LDeviceID, LDeviceToken); // May raise exception
{$IFDEF IOS}
KinveyAPI.PushRegisterDevice(TKinveyApi.TPlatformType.IOS, LDeviceToken);
{$ELSE}
KinveyAPI.PushRegisterDevice(TKinveyApi.TPlatformType.Android, LDeviceToken);
{$ENDIF}
if Assigned(AOnRegistered) then
AOnRegistered(GetPushService);
{$ELSE}
raise EKinveyPushNotificationError.CreateFmt(sPushDeviceNoPushService, [sKinvey, LDeviceName]);
{$ENDIF}
end;
procedure TKinveyPushDeviceAPI.UnregisterDevice;
{$IFDEF PUSH}
var
LDeviceID: string;
LDeviceToken: string;
{$ENDIF}
begin
{$IFDEF PUSH}
GetRegistrationInfo(GetPushService, LDeviceID, LDeviceToken); // May raise exception
{$IFDEF IOS}
KinveyAPI.PushUnregisterDevice(TKinveyApi.TPlatformType.IOS, LDeviceToken);
{$ELSE}
KinveyAPI.PushUnregisterDevice(TKinveyApi.TPlatformType.Android, LDeviceToken);
{$ENDIF}
{$ENDIF}
end;
type
TKinveyPushDeviceServiceFactory = class(TProviderServiceFactory<IBackendPushDeviceService>)
protected
function CreateService(const AProvider: IBackendProvider; const IID: TGUID): IBackendService; override;
public
constructor Create;
end;
constructor TKinveyPushDeviceServiceFactory.Create;
begin
inherited Create(TCustomKinveyProvider.ProviderID, 'REST.Backend.KinveyPushDevice'); // Do not localize
end;
function TKinveyPushDeviceServiceFactory.CreateService(const AProvider: IBackendProvider;
const IID: TGUID): IBackendService;
begin
Result := TKinveyPushDeviceService.Create(AProvider);
end;
var
FFactory: TKinveyPushDeviceServiceFactory;
initialization
FFactory := TKinveyPushDeviceServiceFactory.Create;
FFactory.Register;
finalization
FFactory.Unregister;
FFactory.Free;
end.
|
{$mode objfpc}{$H+}{$J-}
(*
Problem 2: set up variables to convert pounds to kg;
*)
program Problem_2;
const
RATIO = 0.453592;
var
pounds : Real; // to store pounds value
kilograms : Real; // to store kg value
begin
writeln('pounds to kg');
end. |
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;
type
//Class Fruit.
TFrutas = class
private
FisRedonda: boolean;
FTamanho: single;
FDiametro: single;
FLargura: single;
procedure SetDiametro(const Value: single);
procedure SetisRedonda(const Value: boolean);
procedure SetLargura(const Value: single);
procedure SetTamanho(const Value: single);
published
property isRedonda: boolean read FisRedonda write SetisRedonda;
property Tamanho: single read FTamanho write SetTamanho;
property Largura: single read FLargura write SetLargura;
property Diametro: single read FDiametro write SetDiametro;
public
constructor Create(pDiametro:single); overload;
constructor Create(pTamanho: single; pLargura:single); overload;
end;
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
procedure ShowFruta(pFruit:TFrutas);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TFrutas }
constructor TFrutas.Create(pDiametro: single);
begin
FisRedonda:= true;
FDiametro := pDiametro;
end;
constructor TFrutas.Create(pTamanho, pLargura: single);
begin
FisRedonda:=false;
FTamanho:= pTamanho;
FLargura:= pLargura;
end;
procedure TFrutas.SetDiametro(const Value: single);
begin
FDiametro := Value;
end;
procedure TFrutas.SetisRedonda(const Value: boolean);
begin
FisRedonda := Value;
end;
procedure TFrutas.SetLargura(const Value: single);
begin
FLargura := Value;
end;
procedure TFrutas.SetTamanho(const Value: single);
begin
FTamanho := Value;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
maca, banana: TFrutas;
begin
maca:= TFrutas.Create(1.5);
banana:= TFrutas.Create(7,1.75);
try
ShowFruta(maca);
ShowFruta(banana);
finally
maca.Free;
banana.Free;
end;
end;
procedure TForm1.ShowFruta(pFruit: TFrutas);
begin
if pFruit.isRedonda then
showmessage('Temos uma fruta redonda com '+floattostr(pFruit.Diametro)+' de diametro.')
else
showmessage('Temos uma longa fruta com '+floattostr(pFruit.Largura)+' de largura e '+#13+floattostr(pFruit.Tamanho)+' de tamanho.')
end;
end.
|
unit uNsGraphVCL;
interface
uses
SysUtils, Classes, Types, VCL.Graphics, DB, System.UITypes, VCL.Dialogs, Vcl.ExtCtrls;
const
I_MIN_CELL_SIZE = 5;
C_COLOR_REGULAR = clGray;
C_COLOR_BOLD = clGray;
I_THICKNESS_REGULAR = 1;
I_THICKNESS_BOLD = 1;
I_CANVAS_FONT_SIZE = 8;
type
TNsGraph = class(TImage)
private
FDX: Integer;
FDY: Integer;
FMinY: Integer;
FMaxY: Integer;
FXAxisPos: Integer;
FYAxisPos: Integer;
FLinesWidth: Integer;
FDataSet: TDataSet;
FBeginDate: TDateTime;
FEndDate: TDateTime;
FDateField: string;
FKeyField: string;
FValueField: string;
FNameField: string;
FColorField: string;
FDataSource: TDataSource;
FDataLink: TDataLink;
//
procedure DrawLine(var aCanvas: TCanvas; aPoint1, aPoint2: TPoint; aColor: TAlphaColor; aThickness: Integer = 1);
procedure FillText(var aCanvas: TCanvas; aRect: TRect; aText: string; aColor: TAlphaColor);
procedure ClearCanvas;
procedure DrawHorizontalGridLines(aDiapasoneY: Integer; aXAxisUsefulLen: Integer);
procedure DrawVerticalGridLines(aDiapasoneX: Integer; aYAxisUsefulLen: Integer);
procedure DrawAxis(aXAxisLen, aYAxisLen: Integer);
procedure SetDataSet(const aDataSet: TDataSet);
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
procedure DrawGrid;
procedure DrawGraph(aFieldFieldName: string);
published
property LinesWidth: Integer read FLinesWidth write FLinesWidth;
property MinY: Integer read FMinY write FMinY;
property MaxY: Integer read FMaxY write FMaxY;
property DataSet: TDataSet read FDataSet write SetDataSet;
property BeginDate: TDateTime read FBeginDate write FBeginDate;
property EndDate: TDateTime read FEndDate write FEndDate;
property DateField: string read FDateField write FDateField;
property KeyField: string read FKeyField write FKeyField;
property ValueField: string read FValueField write FValueField;
property NameField: string read FNameField write FNameField;
property ColorField: string read FColorField write FColorField;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('NeferSky', [TNsGraph]);
end;
{ TNsGraph }
constructor TNsGraph.Create(aOwner: TComponent);
begin
inherited;
FDataSource := TDataSource.Create(Self);
FDataLink := TDataLink.Create;
FDX := 10;
FDY := 10;
FMinY := 10;
FMaxY := 100;
FXAxisPos := 10;
FYAxisPos := 10;
FLinesWidth := 1;
FDataSet := nil;
FBeginDate := 0;
FEndDate := 0;
FKeyField := '';
FValueField := '';
FNameField := '';
FColorField := '';
Picture.Bitmap.Height := Height;
Picture.Bitmap.Width := Width;
ClearCanvas;
end;
destructor TNsGraph.Destroy;
begin
if Assigned(FDataSource) then
FDataSource.Free;
if Assigned(FDataLink) then
FDataLink.Free;
end;
procedure TNsGraph.DrawLine(var aCanvas: TCanvas; aPoint1, aPoint2: TPoint; aColor: TAlphaColor; aThickness: Integer);
begin
aCanvas.Pen.Color := aColor;
aCanvas.Pen.Width := aThickness;
aCanvas.MoveTo(aPoint1.X, aPoint1.Y);
aCanvas.LineTo(aPoint2.X, aPoint2.Y);
end;
procedure TNsGraph.FillText(var aCanvas: TCanvas; aRect: TRect; aText: string; aColor: TAlphaColor);
begin
aCanvas.Font.Color := aColor;
aCanvas.TextOut(aRect.Left, aRect.Top, aText);
end;
procedure TNsGraph.ClearCanvas;
var
bmpCanvas: TCanvas;
begin
bmpCanvas := Picture.Bitmap.Canvas;
bmpCanvas.Lock;
try
bmpCanvas.Brush.Color := 0;
bmpCanvas.FillRect(Self.BoundsRect);
finally
bmpCanvas.Unlock;
end;
end;
procedure TNsGraph.DrawGrid;
var
XAxisLen,
YAxisLen,
XAxisUsefulLen,
YAxisUsefulLen: Integer;
DiapasoneX,
DiapasoneY: Integer;
begin
FXAxisPos := Height - 23; // Offset of XAxis from the bottom edge of canvas
FYAxisPos := 23; // Offset of YAxis from the left edge of canvas
XAxisLen := Width - FYAxisPos - 20; // Full length of XAxis
YAxisLen := FXAxisPos - 20; // Full length of YAxis
XAxisUsefulLen := XAxisLen - 20; // Useful length of XAxis for marks
YAxisUsefulLen := YAxisLen - 20; // Useful length of YAxis for marks
DiapasoneX := Round((FEndDate - FBeginDate) + 1); // Marks count on XAxis
DiapasoneY := FMaxY - FMinY; // Marks count on YAxis
// Dimensions of grid cell
FDX := XAxisUsefulLen div DiapasoneX;
FDY := YAxisUsefulLen div DiapasoneY;
// If cells is very small - decrease its count
if (FDX < I_MIN_CELL_SIZE) then
begin
FDX := I_MIN_CELL_SIZE;
DiapasoneX := Round(XAxisUsefulLen / FDX);
end;
if (FDY < I_MIN_CELL_SIZE) then
begin
FDY := I_MIN_CELL_SIZE;
DiapasoneY := Round(YAxisUsefulLen / FDY);
end;
// Prepare bitmap
Picture.Bitmap.Height := Height;
Picture.Bitmap.Width := Width;
ClearCanvas;
DrawHorizontalGridLines(DiapasoneY, XAxisUsefulLen);
DrawVerticalGridLines(DiapasoneX, YAxisUsefulLen);
DrawAxis(XAxisLen, YAxisLen);
end;
procedure TNsGraph.DrawHorizontalGridLines(aDiapasoneY: Integer; aXAxisUsefulLen: Integer);
var
bmpCanvas: TCanvas;
I: Integer;
Point1,
Point2: TPoint;
Rect: TRect;
Color: TAlphaColor;
Thickness: Integer;
begin
bmpCanvas := Picture.Bitmap.Canvas;
bmpCanvas.Font.Size := I_CANVAS_FONT_SIZE;
bmpCanvas.Lock;
try
for I := 1 to aDiapasoneY do
begin
Rect := TRect.Create(0, FXAxisPos - (bmpCanvas.Font.Size div 2) - I * FDY, FYAxisPos, FXAxisPos + (bmpCanvas.Font.Size div 2) - I * FDY);
FillText(bmpCanvas, Rect, IntToStr(I + FMinY), clWhite);
// Every 5'th line - dark
if ((I + MinY) mod 5 = 0) then
begin
Color := C_COLOR_BOLD;
Thickness := I_THICKNESS_BOLD;
end
else
begin
Color := C_COLOR_REGULAR;
Thickness := I_THICKNESS_REGULAR;
end;
Point1 := TPoint.Create(FYAxisPos, FXAxisPos - I * FDY);
Point2 := TPoint.Create(FYAxisPos + aXAxisUsefulLen, FXAxisPos - I * FDY);
DrawLine(bmpCanvas, Point1, Point2, Color, Thickness);
end;
finally
bmpCanvas.Unlock;
end;
end;
procedure TNsGraph.DrawVerticalGridLines(aDiapasoneX: Integer; aYAxisUsefulLen: Integer);
var
bmpCanvas: TCanvas;
I: Integer;
CounterDate: TDateTime;
cd,
cm,
cy: Word;
Point1,
Point2: TPoint;
Rect: TRect;
Color: TAlphaColor;
Thickness: Integer;
begin
// Zero on X-axis
CounterDate := FBeginDate;
bmpCanvas := Picture.Bitmap.Canvas;
bmpCanvas.Font.Size := I_CANVAS_FONT_SIZE;
bmpCanvas.Lock;
try
for I := 1 to aDiapasoneX do
begin
DecodeDate(CounterDate, cy, cm, cd);
Rect := TRect.Create(FYAxisPos - bmpCanvas.Font.Size + I * FDX, FXAxisPos, FYAxisPos + bmpCanvas.Font.Size + I * FDX, Height);
FillText(bmpCanvas, Rect, IntToStr(cd), clWhite);
CounterDate := CounterDate + 1;
// Every 5'th line - dark
if (I mod 5 = 0) then
begin
Color := C_COLOR_BOLD;
Thickness := I_THICKNESS_BOLD;
end
else
begin
Color := C_COLOR_REGULAR;
Thickness := I_THICKNESS_REGULAR;
end;
Point1 := TPoint.Create(FYAxisPos + I * FDX, FXAxisPos);
Point2 := TPoint.Create(FYAxisPos + I * FDX, FXAxisPos - aYAxisUsefulLen);
DrawLine(bmpCanvas, Point1, Point2, Color, Thickness);
end;
finally
bmpCanvas.Unlock;
end;
end;
procedure TNsGraph.DrawAxis(aXAxisLen, aYAxisLen: Integer);
const
C_COLOR_AXIS = clWhite;
var
bmpCanvas: TCanvas;
Point1, Point2: TPoint;
begin
bmpCanvas := Picture.Bitmap.Canvas;
bmpCanvas.Lock;
try
// X-axis
Point1 := TPoint.Create(FYAxisPos, FXAxisPos);
Point2 := TPoint.Create(FYAxisPos + aXAxisLen, FXAxisPos);
DrawLine(bmpCanvas, Point1, Point2, C_COLOR_AXIS);
Point1 := TPoint.Create(FYAxisPos + aXAxisLen, FXAxisPos);
Point2 := TPoint.Create(FYAxisPos + aXAxisLen - 13, FXAxisPos - 2);
DrawLine(bmpCanvas, Point1, Point2, C_COLOR_AXIS);
Point1 := TPoint.Create(FYAxisPos + aXAxisLen, FXAxisPos);
Point2 := TPoint.Create(FYAxisPos + aXAxisLen - 13, FXAxisPos + 2);
DrawLine(bmpCanvas, Point1, Point2, C_COLOR_AXIS);
// Y-axis
Point1 := TPoint.Create(FYAxisPos, FXAxisPos);
Point2 := TPoint.Create(FYAxisPos, FXAxisPos - aYAxisLen);
DrawLine(bmpCanvas, Point1, Point2, C_COLOR_AXIS);
Point1 := TPoint.Create(FYAxisPos, FXAxisPos - aYAxisLen);
Point2 := TPoint.Create(FYAxisPos + 2, FXAxisPos - aYAxisLen + 13);
DrawLine(bmpCanvas, Point1, Point2, C_COLOR_AXIS);
Point1 := TPoint.Create(FYAxisPos, FXAxisPos - aYAxisLen);
Point2 := TPoint.Create(FYAxisPos - 2, FXAxisPos - aYAxisLen + 13);
DrawLine(bmpCanvas, Point1, Point2, C_COLOR_AXIS);
finally
bmpCanvas.Unlock;
end;
end;
procedure TNsGraph.DrawGraph(aFieldFieldName: string);
var
CounterDate,
RecordDate: TDateTime;
cd, cm, cy,
rd, rm, ry: Word;
X, X1, Y: Integer;
Value, Value1: Integer;
ValName: string;
bmpCanvas: TCanvas;
Rect: TRect;
Point1, Point2: TPoint;
begin
DataSet.Filtered := False;
DataSet.Filter := FKeyField + '=''' + aFieldFieldName + '''';
DataSet.Filtered := True;
if (DataSet.RecordCount <= 0) then Exit;
bmpCanvas := Picture.Bitmap.Canvas;
bmpCanvas.Font.Size := 10;
// Inverse - it's okay
X := FYAxisPos;
Y := FXAxisPos;
// Get first value and set pen position to start point
DataSet.First;
ValName := DataSet.FieldByName(FNameField).AsString;
Value := Round(Y - (DataSet.FieldByName(FValueField).AsFloat - FMinY) * FDY);
Rect := TRect.Create(X, Value - 8 - bmpCanvas.Font.Size, X + 300, Value);
bmpCanvas.Font.Color := DataSet.FieldByName(FColorField).AsLongWord and $FFFFFF;
bmpCanvas.Lock;
try
bmpCanvas.TextRect(Rect, ValName, [TTextFormats.tfLeft, TTextFormats.tfVerticalCenter, TTextFormats.tfSingleLine]);
finally
bmpCanvas.Unlock;
end;
X1 := X;
Value1 := Value;
Point1 := TPoint.Create(X1, Value1);
CounterDate := FBeginDate;
// Loop by selected days interval
bmpCanvas.Lock;
try
while CounterDate <= FEndDate do
begin
// Step X coordinate
X := X + FDX;
// Check DatasetRecordDate = LoopCounterDate
RecordDate := DataSet.FieldByName(FDateField).AsDateTime;
DecodeDate(RecordDate, ry, rm, rd);
DecodeDate(CounterDate, cy, cm, cd);
CounterDate := CounterDate + 1; // here!!!
//if (cd <> rd) then continue; // It means we haven't this day in dataset
// Get value and draw graph line
Value := Round(Y - (DataSet.FieldByName(FValueField).AsFloat - FMinY) * FDY);
Point2 := TPoint.Create(X, Value);
DrawLine(bmpCanvas, Point1, Point2, DataSet.FieldByName(FColorField).AsLongWord and $FFFFFF, FLinesWidth);
Point1 := Point2;
// Next record
DataSet.Next;
end;
finally
bmpCanvas.Unlock;
end;
end;
procedure TNsGraph.SetDataSet(const aDataSet: TDataSet);
begin
if aDataSet = FDatalink.DataSet then
Exit;
FDataSet := aDataSet;
FDataSource.DataSet := aDataSet;
if Assigned(aDataSet) then
FDataLink.DataSource := FDataSource
else
begin
FDataLink.DataSource := nil;
FDateField := '';
FKeyField := '';
FValueField := '';
FNameField := '';
FColorField := '';
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Data.DBXCommonTable;
interface
uses
Data.DBXCommon,
Data.DBXDelegate,
Data.DBXJSON,
Data.DBXPlatform;
type
TDBXStreamerRow = class;
TDBXTable = class;
TDBXActiveTableReaderItem = class
public
destructor Destroy; override;
procedure ResetEos;
procedure SetParameterEos(const ParameterOrdinal: Integer; const Eos: Boolean);
function IsParameterEos(const ParameterOrdinal: Integer): Boolean;
protected
function IsReaderEos: Boolean;
procedure SetParameterList(const AParameterList: TDBXParameterList);
procedure SetReader(const AReader: TDBXReader);
procedure SetStreamerRow(const StreamerRow: TDBXStreamerRow); virtual;
function GetStreamerRow: TDBXStreamerRow; virtual;
procedure SetReaderEos(const Eos: Boolean); virtual;
private
procedure InitEos;
public
FStreamerRowHandle: Integer;
FNext: TDBXActiveTableReaderItem;
private
FStreamerRow: TDBXStreamerRow;
FParameterList: TDBXParameterList;
FReader: TDBXReader;
FEos: Boolean;
FEosParams: TDBXBooleans;
FOwnsRow: Boolean;
FIsParameterRow: Boolean;
public
property ParameterList: TDBXParameterList read FParameterList write SetParameterList;
property ReaderEos: Boolean read IsReaderEos write SetReaderEos;
property Reader: TDBXReader read FReader write SetReader;
property StreamerRow: TDBXStreamerRow read GetStreamerRow write SetStreamerRow;
property OwnsRow: Boolean write FOwnsRow;
property ParameterRow: Boolean read FIsParameterRow write FIsParameterRow;
end;
TDBXActiveTableReaderList = class
public
destructor Destroy; override;
function AllocateRowHandle: Integer;
function AddDBXStreamerRow(const Row: TDBXStreamerRow; const RowHandle: Integer; const OwnsRow: Boolean; const IsParameterRow: Boolean): TDBXActiveTableReaderItem;
function FindStreamerRowItem(const StreamerRowHandle: Integer): TDBXActiveTableReaderItem;
procedure CloseAllActiveTableReaders;
protected
function IsEos: Boolean;
private
FFirst: TDBXActiveTableReaderItem;
FLastRowHandle: Integer;
public
property Eos: Boolean read IsEos;
end;
TDBXJSONTableReader = class(TDBXReader)
public
constructor Create(const DbxContext: TDBXContext; const Table: TJSONObject; const OwnsJSONObject: Boolean = false);
destructor Destroy; override;
function DerivedNext: Boolean; override;
procedure DerivedClose; override;
function GetValueType(const Ordinal: Integer): TDBXValueType; override;
function GetValue(const Ordinal: Integer): TDBXValue; override;
protected
function GetByteReader: TDBXByteReader; override;
function GetColumnCount: Integer; override;
private
procedure CleanRowValues;
procedure CleanValueTypes;
function CreateWritableValue(const Ordinal: Integer): TDBXWritableValue;
function GetColumnDataPair(AIndex: Integer): TJSONPair;
private
FJsonTable: TJSONObject;
FRowNb: Integer;
FValueTypes: TDBXValueTypeArray;
FRow: TDBXWritableValueArray;
FColumnCount: Integer;
FOwnsJsonTable: Boolean;
end;
TDBXSQLColumnFlags = class
public
const FlagReadonly = 1;
const FlagSearchable = 2;
const FlagCurrency = 4;
const FlagNullable = 8;
const FlagSigned = 16;
const FlagCasesensitive = 32;
const FlagAutoincrement = 64;
const FlagInternalrow = 128;
end;
TDBXStreamerRow = class abstract(TDBXRow)
public
constructor Create(const AContext: TDBXContext);
procedure RecordDBXReaderSet(const ValueType: TDBXValueType);
protected
procedure ValueNotSet(const Value: TDBXWritableValue); override;
private
FRowHandle: Integer;
FFirstDBXReaderOrdinal: Integer;
FLastDBXReaderOrdinal: Integer;
FNeedsNext: Boolean;
public
property RowHandle: Integer read FRowHandle write FRowHandle;
property FirstDBXReaderOrdinal: Integer read FFirstDBXReaderOrdinal;
property LastDBXReaderOrdinal: Integer read FLastDBXReaderOrdinal;
property NeedsNext: Boolean read FNeedsNext write FNeedsNext;
end;
TDBXNoOpRow = class(TDBXStreamerRow)
public
constructor Create(const AContext: TDBXContext);
function CreateCustomValue(const ValueType: TDBXValueType): TDBXValue; override;
protected
procedure NotImplemented; override;
function GetGeneration: Integer; override;
end;
TDBXTableEntity = class
public
constructor Create(const ATable: TDBXTable; const AOwnTable: Boolean);
destructor Destroy; override;
private
FTable: TDBXTable;
FOwnTable: Boolean;
public
property Table: TDBXTable read FTable;
end;
TDBXTableReader = class(TDBXReader)
public
constructor Create(const DbxTable: TDBXTable); overload;
constructor Create(const Context: TDBXContext; const DbxTable: TDBXTable); overload;
destructor Destroy; override;
function GetValue(const Ordinal: Integer): TDBXValue; override;
function GetValueType(const Ordinal: Integer): TDBXValueType; override;
function GetValueByName(const Name: UnicodeString): TDBXValue; override;
function DerivedNext: Boolean; override;
function Next: Boolean; override;
procedure DerivedClose; override;
protected
function GetColumnCount: Integer; override;
function GetByteReader: TDBXByteReader; override;
private
FTable: TDBXTable;
FBeforeFirst: Boolean;
end;
TDBXTableRow = class abstract(TDBXWritableValueList)
public
constructor Create(const DbxContext: TDBXContext);
function CopyColumns: TDBXValueTypeArray; virtual; abstract;
protected
function GetColumns: TDBXValueTypeArray; virtual; abstract;
procedure SetColumns(const Columns: TDBXValueTypeArray); virtual; abstract;
procedure SetDBXTableName(const Name: UnicodeString); virtual; abstract;
function GetDBXTableName: UnicodeString; virtual; abstract;
function GetOriginalRow: TDBXTableRow; virtual; abstract;
/// <summary> Returns column zero-based index based on column name
///
/// </summary>
/// <param name="columnName">String - column name, case insensitive</param>
/// <returns>int - column index, -1 if not found</returns>
function ColumnIndex(const ColumnName: UnicodeString): Integer; virtual;
public
property Columns: TDBXValueTypeArray read GetColumns write SetColumns;
property DBXTableName: UnicodeString read GetDBXTableName write SetDBXTableName;
property OriginalRow: TDBXTableRow read GetOriginalRow;
end;
TDBXTable = class abstract(TDBXTableRow)
public
constructor Create(const DbxContext: TDBXContext);
function InBounds: Boolean; virtual; abstract;
function Next: Boolean; virtual; abstract;
function First: Boolean; virtual; abstract;
function CopyColumns: TDBXValueTypeArray; override;
procedure CopyFrom(const Source: TDBXTable); overload; virtual;
procedure CopyFrom(const Source: TDBXReader); overload; virtual;
procedure Insert; virtual;
procedure Post; virtual;
procedure Close; virtual;
procedure Clear; virtual;
procedure DeleteRow; virtual;
function FindStringKey(const Ordinal: Integer; const Value: UnicodeString): Boolean; virtual;
procedure AcceptChanges; virtual;
function CreateTableView(const OrderByColumnName: UnicodeString): TDBXTable; virtual;
protected
procedure SetDBXTableName(const Name: UnicodeString); override;
function GetDBXTableName: UnicodeString; override;
function GetOriginalRow: TDBXTableRow; override;
procedure SetColumns(const Columns: TDBXValueTypeArray); override;
function IsUpdateable: Boolean; virtual;
function GetStorage: TObject; virtual;
function GetCommand: TObject; virtual;
function GetDeletedRows: TDBXTable; virtual;
function GetInsertedRows: TDBXTable; virtual;
function GetUpdatedRows: TDBXTable; virtual;
function GetTableId: Integer; virtual;
function GetTableCount: Integer; virtual;
public
property Updateable: Boolean read IsUpdateable;
property Storage: TObject read GetStorage;
property Command: TObject read GetCommand;
property DeletedRows: TDBXTable read GetDeletedRows;
property InsertedRows: TDBXTable read GetInsertedRows;
property UpdatedRows: TDBXTable read GetUpdatedRows;
property TableId: Integer read GetTableId;
property TableCount: Integer read GetTableCount;
end;
TDBXDelegateTable = class(TDBXTable)
public
constructor Create;
destructor Destroy; override;
function ReplaceStorage(const Table: TDBXTable): TDBXTable; virtual;
function InBounds: Boolean; override;
function First: Boolean; override;
function Next: Boolean; override;
procedure Insert; override;
procedure Post; override;
procedure CopyFrom(const Source: TDBXTable); override;
procedure Close; override;
procedure Clear; override;
procedure DeleteRow; override;
function FindStringKey(const Ordinal: Integer; const Value: UnicodeString): Boolean; override;
procedure AcceptChanges; override;
function CreateTableView(const OrderByColumnName: UnicodeString): TDBXTable; override;
function GetOrdinal(const ColumnName: UnicodeString): Integer; override;
protected
function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override;
procedure SetTable(const Table: TDBXTable); virtual;
function IsUpdateable: Boolean; override;
function GetStorage: TObject; override;
function GetCommand: TObject; override;
function GetDeletedRows: TDBXTable; override;
function GetInsertedRows: TDBXTable; override;
function GetUpdatedRows: TDBXTable; override;
function GetColumns: TDBXValueTypeArray; override;
procedure SetColumns(const Columns: TDBXValueTypeArray); override;
function GetDBXTableName: UnicodeString; override;
function GetOriginalRow: TDBXTableRow; override;
protected
FTable: TDBXTable;
public
property Table: TDBXTable write SetTable;
end;
TDBXStringTrimTable = class(TDBXDelegateTable)
public
constructor Create(const Table: TDBXTable; const TrimValues: TDBXWritableValueArray);
class function CreateTrimTableIfNeeded(const Table: TDBXTable): TDBXTable; static;
destructor Destroy; override;
protected
function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override;
private
class function HasCharTypes(const Columns: TDBXValueTypeArray): Boolean; static;
public
FTrimValues: TDBXWritableValueArray;
end;
TDBXTrimStringValue = class(TDBXDelegateWritableValue)
public
constructor Create(const Value: TDBXWritableValue);
function GetWideString: UnicodeString; override;
protected
function GetAsString: UnicodeString; override;
end;
TDBXReaderTable = class(TDBXTable)
public
constructor Create(const AReader: TDBXReader);
function First: Boolean; override;
function InBounds: Boolean; override;
function Next: Boolean; override;
function GetOrdinal(const ColumnName: UnicodeString): Integer; override;
procedure Close; override;
protected
function GetColumns: TDBXValueTypeArray; override;
function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override;
private
FReader: TDBXReader;
FNextCount: Integer;
FLastNext: Boolean;
end;
/// <summary> Models persisted-able table. It is based on a current row being handled
/// </summary>
/// <remarks> It is based on a current row being handled
/// by a DBXRow instance. Having a null DBXRow is supported but not encouraged;
/// a DBXMemoryTable should be used instead.
///
/// It assumes DBXRow ownership.
/// </remarks>
TDBXRowTable = class abstract(TDBXTable)
public
/// <param name="dbxContext"></param>
/// <param name="row"></param>
constructor Create(const DbxContext: TDBXContext; const Row: TDBXRow);
destructor Destroy; override;
protected
procedure RowNavigated; virtual;
procedure CreateValues; overload; virtual;
private
class function CreateValues(const Context: TDBXContext; const LocalColumns: TDBXValueTypeArray; const Row: TDBXRow): TDBXWritableValueArray; overload; static;
protected
FRow: TDBXRow;
end;
TDBXCustomValueRow = class(TDBXRowTable)
public
constructor Create(const DbxContext: TDBXContext; const Row: TDBXRow);
function InBounds: Boolean; override;
function Next: Boolean; override;
function First: Boolean; override;
function GetOrdinal(const ColumnName: UnicodeString): Integer; override;
protected
function GetOriginalRow: TDBXTableRow; override;
function GetColumns: TDBXValueTypeArray; override;
procedure SetColumns(const ValueTypes: TDBXValueTypeArray); override;
procedure SetDBXTableName(const Name: UnicodeString); override;
function GetDBXTableName: UnicodeString; override;
private
FValueTypes: TDBXValueTypeArray;
end;
TDBXSingleValueRow = class(TDBXCustomValueRow)
public
constructor Create;
protected
procedure SetColumns(const ValueTypes: TDBXValueTypeArray); override;
end;
implementation
uses
Data.DBXJSONCommon,
System.SysUtils,
Data.DBXCommonResStrs;
destructor TDBXActiveTableReaderItem.Destroy;
begin
if FOwnsRow then
FreeAndNil(FStreamerRow);
FEosParams := nil;
inherited Destroy;
end;
function TDBXActiveTableReaderItem.IsReaderEos: Boolean;
var
Ordinal: Integer;
begin
if not FEos and not FIsParameterRow then
Exit(False);
if FIsParameterRow then
InitEos;
if FEosParams <> nil then
for Ordinal := 0 to Length(FEosParams) - 1 do
if not FEosParams[Ordinal] then
Exit(False);
Result := True;
end;
procedure TDBXActiveTableReaderItem.SetParameterList(const AParameterList: TDBXParameterList);
begin
FEosParams := nil;
self.FParameterList := AParameterList;
end;
procedure TDBXActiveTableReaderItem.ResetEos;
begin
FEosParams := nil;
end;
procedure TDBXActiveTableReaderItem.InitEos;
var
Parameter: TDBXParameter;
Ordinal: Integer;
begin
if (FEosParams = nil) and (FParameterList <> nil) then
begin
SetLength(FEosParams, FParameterList.Count);
for Ordinal := 0 to Length(FEosParams) - 1 do
begin
Parameter := FParameterList.Parameter[Ordinal];
case Parameter.DataType of
TDBXDataTypes.AnsiStringType,
TDBXDataTypes.WideStringType,
TDBXDataTypes.BinaryBlobType:
if (Parameter.ParameterDirection = TDBXParameterDirections.OutParameter) or (Parameter.ParameterDirection = TDBXParameterDirections.InOutParameter) or (Parameter.ParameterDirection = TDBXParameterDirections.ReturnParameter) then
FEosParams[Ordinal] := not TDBXDriverHelp.HasOverflowBytes(Parameter.Value)
else
FEosParams[Ordinal] := True;
else
FEosParams[Ordinal] := True;
end;
end;
end;
end;
procedure TDBXActiveTableReaderItem.SetParameterEos(const ParameterOrdinal: Integer; const Eos: Boolean);
begin
if FParameterList <> nil then
begin
InitEos;
FEosParams[ParameterOrdinal] := Eos;
end;
end;
function TDBXActiveTableReaderItem.IsParameterEos(const ParameterOrdinal: Integer): Boolean;
begin
InitEos;
if FEosParams = nil then
Exit(False);
Result := FEosParams[ParameterOrdinal];
end;
procedure TDBXActiveTableReaderItem.SetReader(const AReader: TDBXReader);
begin
self.ReaderEos := False;
self.FReader := AReader;
end;
procedure TDBXActiveTableReaderItem.SetStreamerRow(const StreamerRow: TDBXStreamerRow);
begin
self.FStreamerRow := StreamerRow;
end;
function TDBXActiveTableReaderItem.GetStreamerRow: TDBXStreamerRow;
begin
self.ReaderEos := False;
Result := FStreamerRow;
end;
procedure TDBXActiveTableReaderItem.SetReaderEos(const Eos: Boolean);
begin
self.FEos := Eos;
end;
destructor TDBXActiveTableReaderList.Destroy;
begin
CloseAllActiveTableReaders;
FreeAndNil(FFirst);
inherited Destroy;
end;
function TDBXActiveTableReaderList.IsEos: Boolean;
var
Item: TDBXActiveTableReaderItem;
begin
Item := FFirst;
while Item <> nil do
begin
if not Item.ReaderEos then
Exit(False);
Item := Item.FNext;
end;
Result := True;
end;
function TDBXActiveTableReaderList.AllocateRowHandle: Integer;
begin
Inc(FLastRowHandle);
Result := FLastRowHandle;
end;
function TDBXActiveTableReaderList.AddDBXStreamerRow(const Row: TDBXStreamerRow; const RowHandle: Integer; const OwnsRow: Boolean; const IsParameterRow: Boolean): TDBXActiveTableReaderItem;
var
Item: TDBXActiveTableReaderItem;
begin
Item := TDBXActiveTableReaderItem.Create;
Item.StreamerRow := Row;
Item.OwnsRow := OwnsRow;
Item.ParameterRow := IsParameterRow;
Item.FStreamerRowHandle := RowHandle;
Row.RowHandle := RowHandle;
Item.FNext := FFirst;
FFirst := Item;
Result := Item;
end;
function TDBXActiveTableReaderList.FindStreamerRowItem(const StreamerRowHandle: Integer): TDBXActiveTableReaderItem;
var
Item: TDBXActiveTableReaderItem;
begin
Item := FFirst;
while Item <> nil do
begin
if Item.FStreamerRowHandle = StreamerRowHandle then
Exit(Item);
Item := Item.FNext;
end;
Result := nil;
end;
procedure TDBXActiveTableReaderList.CloseAllActiveTableReaders;
var
Item: TDBXActiveTableReaderItem;
TempItem: TDBXActiveTableReaderItem;
begin
Item := FFirst;
if Item <> nil then
begin
Item.ResetEos;
Item := Item.FNext;
FFirst.FNext := nil;
end;
while Item <> nil do
begin
TempItem := Item;
Item := Item.FNext;
FreeAndNil(TempItem);
end;
FLastRowHandle := 0;
end;
constructor TDBXJSONTableReader.Create(const DbxContext: TDBXContext; const Table: TJSONObject;
const OwnsJSONObject: Boolean);
var
MetaPair: TJSONPair;
I: Integer;
LValues: TDBXWritableValueArray;
begin
inherited Create(DbxContext, TDBXNoOpRow.Create(DbxContext), nil);
FOwnsJsonTable := OwnsJSONObject;
FJsonTable := Table;
FRowNb := -1;
FColumnCount := 0;
MetaPair := Table.Get(TABLE_PAIR);
if MetaPair <> nil then
begin
FColumnCount := (TJSONArray(MetaPair.JsonValue)).Size;
SetLength(FValueTypes, FColumnCount);
SetLength(FRow, FColumnCount);
SetLength(LValues, FColumnCount);
for I := 0 to FColumnCount - 1 do
begin
FValueTypes[I] := TDBXJSONTools.JSONToValueType(TJSONArray((TJSONArray(MetaPair.JsonValue)).Get(I)));
LValues[I] := CreateWritableValue(I);
end;
end
else
begin
SetLength(FRow, FColumnCount);
SetLength(FValueTypes, FColumnCount);
SetLength(LValues, FColumnCount);
end;
SetValues(LValues);
end;
destructor TDBXJSONTableReader.Destroy;
begin
CleanRowValues;
CleanValueTypes;
if FOwnsJsonTable then
FJsonTable.Free;
inherited Destroy;
end;
procedure TDBXJSONTableReader.CleanRowValues;
var
I: Integer;
begin
for I := 0 to Length(FRow) - 1 do
begin
FRow[I].Free;
FRow[I] := nil;
end;
end;
procedure TDBXJSONTableReader.CleanValueTypes;
var
I: Integer;
begin
for I := 0 to Length(FValueTypes) - 1 do
begin
FValueTypes[I].Free;
FValueTypes[I] := nil;
end;
end;
// Find the column data based on an index, but assume JSONObject has unordered pairs.
// Tables look like this:
// '{"table":[["Column1",6,0,0,0,0,0,0,false,false,0,false,false]],"Column1":[0,1,2,3,4,5,6,7,8,9]}'
function TDBXJSONTableReader.GetColumnDataPair(AIndex: Integer): TJSONPair;
var
ColMetaData: TJSONValue;
JsonPair: TJSONPair;
ColName: TJSONValue;
begin
Result := nil;
JsonPair := FJsonTable.Get(TABLE_PAIR);
if JsonPair <> nil then
if JsonPair.JsonValue is TJSONArray then
begin
ColMetaData := TJSONArray(JsonPair.JsonValue).Get(AIndex);
if ColMetaData is TJSONArray then
begin
ColName := TJSONArray(ColMetaData).Get(0);
if ColName is TJSONString then
Result := FJsonTable.Get(ColName.Value);
end;
end;
end;
function TDBXJSONTableReader.DerivedNext: Boolean;
var
Col1: TJSONPair;
begin
Col1 := GetColumnDataPair(0);
if Col1 = nil then
Exit(False);
if FRowNb < (TJSONArray(Col1.JsonValue)).Size - 1 then
begin
IncrAfter(FRowNb);
CleanRowValues;
Result := True;
end
else
Result := False;
end;
procedure TDBXJSONTableReader.DerivedClose;
begin
FRowNb := -1;
CleanRowValues;
end;
function TDBXJSONTableReader.GetByteReader: TDBXByteReader;
begin
Result := nil;
end;
function TDBXJSONTableReader.GetValueType(const Ordinal: Integer): TDBXValueType;
begin
if Ordinal < FColumnCount then
Exit(FValueTypes[Ordinal]);
Result := nil;
end;
function TDBXJSONTableReader.CreateWritableValue(const Ordinal: Integer): TDBXWritableValue;
begin
Result := nil;
if Ordinal < FColumnCount then
begin
Result := TDBXValue.CreateValue(DBXContext, TDBXValueType(self.ValueType[Ordinal].Clone()), GetRow, False);
end;
end;
function TDBXJSONTableReader.GetValue(const Ordinal: Integer): TDBXValue;
var
JCell: TJSONValue;
JSonPair: TJSONPair;
begin
if Ordinal < FColumnCount then
begin
if FRow[Ordinal] = nil then
begin
JsonPair := GetColumnDataPair(Ordinal);
JCell := nil;
if (JsonPair <> nil) and (JsonPair.JsonValue is TJSONArray) then
JCell := TJSONArray(JsonPair.JSonValue).Get(FRowNb);
if JCell = nil then
Exit(nil);
FRow[Ordinal] := CreateWritableValue(Ordinal); //TDBXValue.CreateValue(DBXContext, TDBXValueType(self.ValueType[Ordinal].Clone()), GetRow, False);
TDBXJSONTools.JSONToDBX(JCell, FRow[Ordinal], self.ValueType[Ordinal].DataType, False);
end;
Exit(FRow[Ordinal]);
end;
Result := nil;
end;
function TDBXJSONTableReader.GetColumnCount: Integer;
begin
Result := FColumnCount;
end;
constructor TDBXStreamerRow.Create(const AContext: TDBXContext);
begin
inherited Create(AContext);
FFirstDBXReaderOrdinal := -1;
end;
procedure TDBXStreamerRow.RecordDBXReaderSet(const ValueType: TDBXValueType);
var
Ordinal: Integer;
begin
Ordinal := ValueType.Ordinal;
if (FFirstDBXReaderOrdinal < 0) or (FFirstDBXReaderOrdinal > Ordinal) then
FFirstDBXReaderOrdinal := Ordinal;
if FLastDBXReaderOrdinal < Ordinal then
FLastDBXReaderOrdinal := Ordinal;
end;
procedure TDBXStreamerRow.ValueNotSet(const Value: TDBXWritableValue);
begin
case Value.ValueType.ParameterDirection of
TDBXParameterDirections.OutParameter,
TDBXParameterDirections.ReturnParameter:
raise TDBXError.Create(TDBXErrorCodes.ParameterNotSet, Format(SParameterNotSet, [IntToStr(Value.ValueType.Ordinal)]));
end;
SetNull(Value);
end;
constructor TDBXNoOpRow.Create(const AContext: TDBXContext);
begin
inherited Create(AContext);
end;
procedure TDBXNoOpRow.NotImplemented;
begin
end;
function TDBXNoOpRow.CreateCustomValue(const ValueType: TDBXValueType): TDBXValue;
begin
case ValueType.DataType of
TDBXDataTypes.WideStringType:
Exit(TDBXStringValue.Create(ValueType));
end;
Result := nil;
end;
function TDBXNoOpRow.GetGeneration: Integer;
begin
Result := -1;
end;
constructor TDBXTableEntity.Create(const ATable: TDBXTable; const AOwnTable: Boolean);
begin
inherited Create;
FTable := ATable;
FOwnTable := AOwnTable;
end;
destructor TDBXTableEntity.Destroy;
begin
if FOwnTable then
FreeAndNil(FTable);
inherited Destroy;
end;
constructor TDBXTableReader.Create(const DbxTable: TDBXTable);
begin
Create(nil, DbxTable);
end;
constructor TDBXTableReader.Create(const Context: TDBXContext; const DbxTable: TDBXTable);
begin
inherited Create(Context, nil, nil);
FTable := DbxTable;
FBeforeFirst := DbxTable.First;
SetValues(DbxTable.Values);
end;
destructor TDBXTableReader.Destroy;
var
Empty: TDBXWritableValueArray;
begin
SetLength(Empty, 0);
SetValues(Empty);
FreeAndNil(FTable);
inherited Destroy;
end;
function TDBXTableReader.GetColumnCount: Integer;
begin
Result := Length(FTable.Columns);
end;
function TDBXTableReader.GetValue(const Ordinal: Integer): TDBXValue;
begin
Result := FTable.Value[Ordinal];
end;
function TDBXTableReader.GetValueType(const Ordinal: Integer): TDBXValueType;
begin
Result := FTable.Columns[Ordinal];
end;
function TDBXTableReader.GetValueByName(const Name: UnicodeString): TDBXValue;
begin
Result := FTable.Value[FTable.GetOrdinal(Name)];
end;
function TDBXTableReader.GetByteReader: TDBXByteReader;
begin
Result := nil;
end;
function TDBXTableReader.DerivedNext: Boolean;
begin
if FBeforeFirst then
begin
FBeforeFirst := False;
Result := True;
end
else
Result := FTable.Next;
end;
function TDBXTableReader.Next: Boolean;
begin
Result := DerivedNext;
end;
procedure TDBXTableReader.DerivedClose;
begin
FTable := nil;
end;
constructor TDBXTableRow.Create(const DbxContext: TDBXContext);
begin
inherited Create(DbxContext);
end;
function TDBXTableRow.ColumnIndex(const ColumnName: UnicodeString): Integer;
var
J: Integer;
begin
for J := 0 to Length(Columns) - 1 do
begin
if CompareText(Columns[J].Name, ColumnName) = 0 then
Exit(J);
end;
Result := -1;
end;
constructor TDBXTable.Create(const DbxContext: TDBXContext);
begin
inherited Create(DbxContext);
end;
procedure TDBXTable.SetDBXTableName(const Name: UnicodeString);
begin
raise Exception.Create(SUnsupportedOperation);
end;
function TDBXTable.GetDBXTableName: UnicodeString;
begin
raise Exception.Create(SUnsupportedOperation);
end;
function TDBXTable.GetOriginalRow: TDBXTableRow;
begin
raise Exception.Create(SUnsupportedOperation);
end;
procedure TDBXTable.SetColumns(const Columns: TDBXValueTypeArray);
begin
raise Exception.Create(SUnsupportedOperation);
end;
function TDBXTable.CopyColumns: TDBXValueTypeArray;
var
CurrentColumns: TDBXValueTypeArray;
CopyColumns: TDBXValueTypeArray;
Ordinal: Integer;
begin
CurrentColumns := Columns;
SetLength(CopyColumns, Length(CurrentColumns));
for Ordinal := 0 to Length(CurrentColumns) - 1 do
CopyColumns[Ordinal] := TDBXValueType(CurrentColumns[Ordinal].Clone());
Result := CopyColumns;
end;
procedure TDBXTable.CopyFrom(const Source: TDBXTable);
var
ColumnCount, Ordinal: Integer;
begin
ColumnCount := Length(Columns);
while Source.Next do
begin
Insert;
for Ordinal := 0 to ColumnCount - 1 do
self.Value[Ordinal].SetValue(Source.Value[Ordinal]);
Post;
end;
end;
procedure TDBXTable.CopyFrom(const Source: TDBXReader);
var
ColumnCount, Ordinal: Integer;
begin
ColumnCount := Length(Columns);
while Source.Next do
begin
Insert;
for Ordinal := 0 to ColumnCount - 1 do
self.Value[Ordinal].SetValue(Source.Value[Ordinal]);
Post;
end;
end;
function TDBXTable.IsUpdateable: Boolean;
begin
Result := False;
end;
procedure TDBXTable.Insert;
begin
raise Exception.Create(SUnsupportedOperation);
end;
procedure TDBXTable.Post;
begin
raise Exception.Create(SUnsupportedOperation);
end;
procedure TDBXTable.Close;
begin
raise Exception.Create(SUnsupportedOperation);
end;
procedure TDBXTable.Clear;
begin
raise Exception.Create(SUnsupportedOperation);
end;
procedure TDBXTable.DeleteRow;
begin
raise Exception.Create(SUnsupportedOperation);
end;
function TDBXTable.GetStorage: TObject;
begin
Result := nil;
end;
function TDBXTable.GetCommand: TObject;
begin
Result := nil;
end;
function TDBXTable.FindStringKey(const Ordinal: Integer; const Value: UnicodeString): Boolean;
begin
raise Exception.Create(SUnsupportedOperation);
end;
procedure TDBXTable.AcceptChanges;
begin
raise Exception.Create(SUnsupportedOperation);
end;
function TDBXTable.CreateTableView(const OrderByColumnName: UnicodeString): TDBXTable;
begin
raise Exception.Create(SUnsupportedOperation);
end;
function TDBXTable.GetDeletedRows: TDBXTable;
begin
raise Exception.Create(SUnsupportedOperation);
end;
function TDBXTable.GetInsertedRows: TDBXTable;
begin
raise Exception.Create(SUnsupportedOperation);
end;
function TDBXTable.GetUpdatedRows: TDBXTable;
begin
raise Exception.Create(SUnsupportedOperation);
end;
function TDBXTable.GetTableId: Integer;
begin
Result := 0;
end;
function TDBXTable.GetTableCount: Integer;
begin
Result := 1;
end;
constructor TDBXDelegateTable.Create;
begin
inherited Create(nil);
end;
function TDBXDelegateTable.GetWritableValue(const Ordinal: Integer): TDBXWritableValue;
begin
Result := FTable.Value[Ordinal];
end;
procedure TDBXDelegateTable.SetTable(const Table: TDBXTable);
begin
self.FTable := Table;
end;
destructor TDBXDelegateTable.Destroy;
begin
FreeAndNil(FTable);
inherited Destroy;
end;
function TDBXDelegateTable.ReplaceStorage(const Table: TDBXTable): TDBXTable;
var
OldTable: TDBXTable;
begin
OldTable := self.FTable;
self.FTable := Table;
Result := OldTable;
end;
function TDBXDelegateTable.IsUpdateable: Boolean;
begin
Result := FTable.Updateable;
end;
function TDBXDelegateTable.InBounds: Boolean;
begin
Result := FTable.InBounds;
end;
function TDBXDelegateTable.First: Boolean;
begin
Result := FTable.First;
end;
function TDBXDelegateTable.Next: Boolean;
begin
Result := FTable.Next;
end;
procedure TDBXDelegateTable.Insert;
begin
FTable.Insert;
end;
procedure TDBXDelegateTable.Post;
begin
FTable.Post;
end;
procedure TDBXDelegateTable.CopyFrom(const Source: TDBXTable);
begin
FTable.CopyFrom(Source);
end;
procedure TDBXDelegateTable.Close;
begin
FTable.Close;
end;
procedure TDBXDelegateTable.Clear;
begin
FTable.Clear;
end;
procedure TDBXDelegateTable.DeleteRow;
begin
FTable.DeleteRow;
end;
function TDBXDelegateTable.GetStorage: TObject;
begin
Result := FTable.Storage;
end;
function TDBXDelegateTable.GetCommand: TObject;
begin
Result := FTable.Command;
end;
function TDBXDelegateTable.FindStringKey(const Ordinal: Integer; const Value: UnicodeString): Boolean;
begin
Result := FTable.FindStringKey(Ordinal, Value);
end;
procedure TDBXDelegateTable.AcceptChanges;
begin
FTable.AcceptChanges;
end;
function TDBXDelegateTable.CreateTableView(const OrderByColumnName: UnicodeString): TDBXTable;
begin
Result := FTable.CreateTableView(OrderByColumnName);
end;
function TDBXDelegateTable.GetDeletedRows: TDBXTable;
begin
Result := FTable.DeletedRows;
end;
function TDBXDelegateTable.GetInsertedRows: TDBXTable;
begin
Result := FTable.InsertedRows;
end;
function TDBXDelegateTable.GetUpdatedRows: TDBXTable;
begin
Result := FTable.UpdatedRows;
end;
function TDBXDelegateTable.GetColumns: TDBXValueTypeArray;
begin
Result := FTable.Columns;
end;
procedure TDBXDelegateTable.SetColumns(const Columns: TDBXValueTypeArray);
begin
FTable.Columns := Columns;
end;
function TDBXDelegateTable.GetDBXTableName: UnicodeString;
begin
Result := FTable.DBXTableName;
end;
function TDBXDelegateTable.GetOrdinal(const ColumnName: UnicodeString): Integer;
begin
Result := FTable.GetOrdinal(ColumnName);
end;
function TDBXDelegateTable.GetOriginalRow: TDBXTableRow;
begin
Result := FTable.OriginalRow;
end;
constructor TDBXStringTrimTable.Create(const Table: TDBXTable; const TrimValues: TDBXWritableValueArray);
begin
inherited Create;
self.FTable := Table;
self.FTrimValues := TrimValues;
end;
class function TDBXStringTrimTable.HasCharTypes(const Columns: TDBXValueTypeArray): Boolean;
var
Column: TDBXValueType;
Ordinal: Integer;
begin
for Ordinal := 0 to Length(Columns) - 1 do
begin
Column := Columns[Ordinal];
if Column.SubType = TDBXDataTypes.CharArrayType then
Exit(True);
end;
Result := False;
end;
class function TDBXStringTrimTable.CreateTrimTableIfNeeded(const Table: TDBXTable): TDBXTable;
var
Columns: TDBXValueTypeArray;
TrimValues: TDBXWritableValueArray;
Ordinal: Integer;
begin
Columns := Table.Columns;
if HasCharTypes(Columns) then
begin
SetLength(TrimValues, Length(Columns));
for Ordinal := 0 to Length(Columns) - 1 do
TrimValues[Ordinal] := nil;
Exit(TDBXStringTrimTable.Create(Table, TrimValues));
end;
Result := Table;
end;
function TDBXStringTrimTable.GetWritableValue(const Ordinal: Integer): TDBXWritableValue;
var
Value: TDBXWritableValue;
begin
Value := FTrimValues[Ordinal];
if Value = nil then
begin
Value := FTable.Value[Ordinal];
if Value.ValueType.SubType = TDBXDataTypes.CharArrayType then
begin
Value := TDBXTrimStringValue.Create(FTable.Value[Ordinal]);
FTrimValues[Ordinal] := Value;
end;
end;
Result := Value;
end;
destructor TDBXStringTrimTable.Destroy;
begin
FreeObjectArray(TDBXFreeArray(FTrimValues));
inherited Destroy;
end;
constructor TDBXTrimStringValue.Create(const Value: TDBXWritableValue);
begin
inherited Create(TDBXValueType(Value.ValueType.Clone()), Value);
end;
function TDBXTrimStringValue.GetWideString: UnicodeString;
var
Value: UnicodeString;
begin
Value := inherited GetWideString;
Result := Trim(Value);
end;
function TDBXTrimStringValue.GetAsString: UnicodeString;
var
Value: UnicodeString;
begin
Value := inherited GetAsString;
Result := Trim(Value);
end;
constructor TDBXReaderTable.Create(const AReader: TDBXReader);
begin
inherited Create(nil);
FReader := AReader;
end;
function TDBXReaderTable.First: Boolean;
begin
if FNextCount = 0 then
begin
Inc(FNextCount);
if FReader.Next then
begin
FLastNext := True;
Exit(True);
end;
end
else
FLastNext := False;
Result := FLastNext;
end;
function TDBXReaderTable.InBounds: Boolean;
begin
if FNextCount = 0 then
Exit(First);
Result := FLastNext;
end;
function TDBXReaderTable.Next: Boolean;
begin
Inc(FNextCount);
FLastNext := FReader.Next;
Result := FLastNext;
end;
function TDBXReaderTable.GetColumns: TDBXValueTypeArray;
begin
Result := nil;
end;
function TDBXReaderTable.GetOrdinal(const ColumnName: UnicodeString): Integer;
begin
Result := FReader.GetOrdinal(ColumnName);
end;
function TDBXReaderTable.GetWritableValue(const Ordinal: Integer): TDBXWritableValue;
begin
Result := TDBXWritableValue(FReader.Value[Ordinal]);
end;
procedure TDBXReaderTable.Close;
begin
FReader.Close;
FReader := nil;
end;
constructor TDBXRowTable.Create(const DbxContext: TDBXContext; const Row: TDBXRow);
begin
inherited Create(DbxContext);
self.FRow := Row;
if Row <> nil then
Row.NewRowGeneration;
end;
destructor TDBXRowTable.Destroy;
begin
FreeAndNil(FRow);
inherited Destroy;
end;
procedure TDBXRowTable.RowNavigated;
begin
if FRow <> nil then
FRow.NewRowGeneration;
end;
class function TDBXRowTable.CreateValues(const Context: TDBXContext; const LocalColumns: TDBXValueTypeArray; const Row: TDBXRow): TDBXWritableValueArray;
var
Value: TDBXWritableValue;
Values: TDBXWritableValueArray;
Ordinal: Integer;
begin
SetLength(Values, Length(LocalColumns));
for Ordinal := 0 to Length(Values) - 1 do
begin
if LocalColumns[Ordinal] <> nil then
begin
Value := TDBXWritableValue(TDBXValue.CreateValue(Context, LocalColumns[Ordinal], Row, False));
Value.ValueType.Ordinal := Ordinal;
Values[Ordinal] := Value;
end;
end;
if Row <> nil then
Row.NewRowGeneration;
Result := Values;
end;
procedure TDBXRowTable.CreateValues;
var
List: TDBXWritableValueArray;
begin
List := CreateValues(FDbxContext, Columns, FRow);
SetValues(List, Length(List));
end;
constructor TDBXCustomValueRow.Create(const DbxContext: TDBXContext; const Row: TDBXRow);
begin
inherited Create(DbxContext, Row);
end;
function TDBXCustomValueRow.InBounds: Boolean;
begin
Result := True;
end;
function TDBXCustomValueRow.Next: Boolean;
begin
Result := False;
end;
function TDBXCustomValueRow.First: Boolean;
begin
Result := True;
end;
function TDBXCustomValueRow.GetOriginalRow: TDBXTableRow;
begin
raise Exception.Create(SUnsupportedOperation);
end;
function TDBXCustomValueRow.GetColumns: TDBXValueTypeArray;
begin
Result := FValueTypes;
end;
procedure TDBXCustomValueRow.SetColumns(const ValueTypes: TDBXValueTypeArray);
begin
self.FValueTypes := ValueTypes;
end;
function TDBXCustomValueRow.GetOrdinal(const ColumnName: UnicodeString): Integer;
var
Index: Integer;
begin
for index := 0 to Length(FValueTypes) - 1 do
begin
if CompareText(FValueTypes[Index].Name, ColumnName) = 0 then
Exit(Index);
end;
Result := -1;
end;
procedure TDBXCustomValueRow.SetDBXTableName(const Name: UnicodeString);
begin
raise Exception.Create(SUnsupportedOperation);
end;
function TDBXCustomValueRow.GetDBXTableName: UnicodeString;
begin
raise Exception.Create(SUnsupportedOperation);
end;
constructor TDBXSingleValueRow.Create;
begin
inherited Create(nil, nil);
end;
procedure TDBXSingleValueRow.SetColumns(const ValueTypes: TDBXValueTypeArray);
begin
inherited SetColumns(ValueTypes);
CreateValues;
end;
end.
|
unit EOLConv.Converters;
interface
uses
System.Classes;
procedure ConvertBytes(const InStream, OutStream: TStream; LineBreaks: TTextLineBreakStyle);
procedure Convert16BE(const InStream, OutStream: TStream; LineBreaks: TTextLineBreakStyle);
procedure Convert16LE(const InStream, OutStream: TStream; LineBreaks: TTextLineBreakStyle);
function ConvertFile(const InFileName, OutFileName: string; LineBreaks: TTextLineBreakStyle): Boolean;
implementation
uses
System.SysUtils;
procedure ConvertBytes(const InStream, OutStream: TStream; LineBreaks: TTextLineBreakStyle);
var
PIn, POut, PEnd: PByte;
CurByte: Byte;
LLen: Integer;
InBuffer, OutBuffer: TArray<Byte>;
Size: Integer;
begin
if InStream.Size > 1024 * 1024 then
Size := 1024 * 1024
else
Size := InStream.Size;
SetLength(InBuffer, Size);
SetLength(OutBuffer, 2 * Size);
repeat
LLen := InStream.Read(InBuffer[0], Size);
if LLen = 0 then
Break;
// Start conversion single byte
PIn := @InBuffer[0];
PEnd := PIn + LLen;
POut := @OutBuffer[0];
while PIn < PEnd do
begin
CurByte := PIn^;
if (CurByte = 10) or (CurByte = 13) then
begin
if LineBreaks = tlbsCRLF then
begin
POut^ := 13;
Inc(POut);
end;
POut^ := 10;
Inc(POut);
Inc(PIn);
if (CurByte = 13) and (PIn^ = 10) then
Inc(PIn);
end
else
begin
POut^ := PIn^;
Inc(POut);
Inc(PIn);
end;
end;
OutStream.Write(OutBuffer, POut - PByte(OutBuffer));
until LLen < Size;
end;
{$POINTERMATH ON}
procedure Convert16BE(const InStream, OutStream: TStream; LineBreaks: TTextLineBreakStyle);
var
PIn, POut, PEnd: PWord;
CurChar: Word;
LLen: Integer;
InBuffer, OutBuffer: TArray<Word>;
Size: Integer;
begin
if InStream.Size > (1024 * 1024) * SizeOf(Char) then
Size := 1024 * 1024
else
Size := InStream.Size div SizeOf(Char);
SetLength(InBuffer, Size);
SetLength(OutBuffer, 2 * Size);
repeat
LLen := InStream.Read(InBuffer[0], Size * SizeOf(Char));
if LLen = 0 then
Break;
// Start conversion single byte
PIn := @InBuffer[0];
PEnd := PIn + (LLen div SizeOf(Char));
POut := @OutBuffer[0];
while PIn < PEnd do
begin
CurChar := PIn^;
if (CurChar = $0A00) or (CurChar = $0D00) then
begin
if LineBreaks = tlbsCRLF then
begin
POut^ := $0D00;
Inc(POut);
end;
POut^ := $0A00;
Inc(POut);
Inc(PIn);
if (CurChar = $0D00) and (PIn^ = $0A00) then
Inc(PIn);
end
else
begin
POut^ := PIn^;
Inc(POut);
Inc(PIn);
end;
end;
OutStream.Write(OutBuffer[0], (POut - PWord(OutBuffer)) * SizeOf(Char));
until LLen < Size * SizeOf(Char);
end;
procedure Convert16LE(const InStream, OutStream: TStream; LineBreaks: TTextLineBreakStyle);
var
PIn, POut, PEnd: PWord;
CurChar: Word;
LLen: Integer;
InBuffer, OutBuffer: TArray<Word>;
Size: Integer;
begin
if InStream.Size > (1024 * 1024) * SizeOf(Char) then
Size := 1024 * 1024
else
Size := InStream.Size div SizeOf(Char);
SetLength(InBuffer, Size);
SetLength(OutBuffer, 2 * Size);
repeat
LLen := InStream.Read(InBuffer[0], Size * SizeOf(Char));
if LLen = 0 then
Break;
// Start conversion single byte
PIn := @InBuffer[0];
PEnd := PIn + (LLen div SizeOf(Char));
POut := @OutBuffer[0];
while PIn < PEnd do
begin
CurChar := PIn^;
if (CurChar = $000A) or (CurChar = $000D) then
begin
if LineBreaks = tlbsCRLF then
begin
POut^ := $000D;
Inc(POut);
end;
POut^ := $000A;
Inc(POut);
Inc(PIn);
if (CurChar = $000D) and (PIn^ = $000A) then
Inc(PIn);
end
else
begin
POut^ := PIn^;
Inc(POut);
Inc(PIn);
end;
end;
OutStream.Write(OutBuffer[0], (POut - PWord(@OutBuffer[0])) * SizeOf(Char));
until LLen < Size * SizeOf(Char);
end;
function ConvertFile(const InFileName, OutFileName: string; LineBreaks: TTextLineBreakStyle): Boolean;
var
InStream, OutStream: TStream;
InBuffer: array[0..1] of Byte;
begin
Result := True;
OutStream := nil;
try
InStream := TFileStream.Create(InFileName, fmOpenRead);
try
OutStream := TFileStream.Create(OutFileName, fmCreate);
if (InStream.Read(InBuffer[0], 2) = 2) then
begin
// Check for UTF-16 BE BOM
if (InBuffer[0] = $FE) and (InBuffer[1] = $FF) then
begin
OutStream.Write(InBuffer, 2);
Convert16BE(InStream, OutStream, LineBreaks)
end
// Check for UTF-16 LE BOM
else if (InBuffer[0] = $FF) and (InBuffer[1] = $FE) then
begin
OutStream.Write(InBuffer, 2);
Convert16LE(InStream, OutStream, LineBreaks)
end
else
begin
// Assume single-byte encoding
InStream.Position := 0;
ConvertBytes(InStream, OutStream, LineBreaks);
end
end
else
begin
// Size can only be 0 or 1:
if Instream.Size = 1 then
OutStream.Write(InBuffer, 1);
end;
finally
OutStream.Free;
InStream.Free;
end;
except
Result := False;
end;
end;
end.
|
unit JD.Weather.Services.WUnderground;
interface
{$R 'WUndergroundRes.res' 'WUndergroundRes.rc'}
uses
System.SysUtils,
System.Classes,
StrUtils,
JD.Weather.Intf,
JD.Weather.SuperObject,
System.Generics.Collections;
const
SVC_CAPTION = 'Weather Underground';
SVC_NAME = 'WUnderground';
SVC_UID = '{87940B1A-0435-4E2D-8DE8-6DE3BDCD43BB}';
URL_MAIN = 'http://www.wunderground.com';
URL_API = 'https://www.wunderground.com/weather/api/';
URL_REGISTER = 'https://www.wunderground.com/member/registration';
URL_LOGIN = 'https://www.wunderground.com/login.asp';
URL_LEGAL = 'https://www.wunderground.com/weather/api/d/terms.html';
SUP_INFO = [wiLocation, wiConditions, wiAlerts, wiForecastSummary,
wiForecastHourly, wiForecastDaily, wiMaps];
SUP_UNITS = [wuImperial, wuMetric];
SUP_LOC = [wlZip, wlCityState, wlCoords, wlAutoIP,
wlCountryCity, wlAirportCode, wlPWS];
SUP_LOGO = [ltColor, ltColorInvert, ltColorWide, ltColorInvertWide,
ltColorLeft, ltColorRight];
SUP_COND_PROP = [wpIcon, wpCaption, wpURL, wpStation, wpTemp,
wpFeelsLike, wpWindDir, wpWindSpeed, wpWindGust, wpHeatIndex, wpPressure,
wpHumidity, wpDewPoint, wpVisibility, wpSolarRad, wpUVIndex, wpPrecipAmt];
SUP_ALERT_TYPE = [waNone, waHurricaneStat, waTornadoWarn,
waTornadoWatch, waSevThundWarn, waSevThundWatch, waWinterAdv,
waFloodWarn, waFloodWatch, waHighWind, waSevStat, waHeatAdv, waFogAdv,
waSpecialStat, waFireAdv, waVolcanicStat, waHurricaneWarn,
waRecordSet, waPublicRec, waPublicStat];
SUP_ALERT_PROP = [apZones, apVerticies, apStorm, apType,
apDescription, apExpires, apMessage, apPhenomena, apSignificance];
SUP_FOR = [ftSummary, ftHourly, ftDaily];
SUP_FOR_SUM = [wpCaption, wpDescription, wpIcon, wpPrecipPred];
SUP_FOR_HOUR = [wpIcon,
wpCaption,
wpDescription,
wpTemp,
wpFeelsLike,
wpWindDir,
wpWindSpeed,
wpWindChill,
wpHeatIndex,
wpPressure,
wpHumidity,
wpDewPoint,
wpUVIndex,
wpPrecipAmt,
wpSnowAmt,
wpPrecipPred];
SUP_FOR_DAY = [wpIcon,
wpCaption,
wpDescription,
wpTemp,
wpTempMin,
wpTempMax,
wpWindDir,
wpWindSpeed,
wpHumidity,
wpPrecipAmt,
wpSnowAmt,
wpPrecipPred];
SUP_MAP = [mpSatellite, mpRadar, mpSatelliteRadar,
mpAniSatellite, mpAniRadar, mpAniSatelliteRadar];
SUP_MAP_FOR = [wfPng, wfGif, wfFlash];
type
TWUEndpoint = (weAll, weAlerts, weAlmanac, weAstronomy, weConditions,
weCurrentHurricane, weForecast, weForecast10Day, weGeoLookup, weHistory,
weHourly, weHourly10Day, wePlanner, weRawTide, weTide, weWebCams, weYesterday,
weRadar, weSatellite, weRadarSatellite,
weAniRadar, weAniSatellite, weAniRadarSatellite);
TWUEndpoints = set of TWUEndpoint;
////////////////////////////////////////////////////////////////////////////////
TWeatherSupport = class(TInterfacedObject, IWeatherSupport)
public
function GetSupportedLogos: TWeatherLogoTypes;
function GetSupportedUnits: TWeatherUnitsSet;
function GetSupportedInfo: TWeatherInfoTypes;
function GetSupportedLocations: TWeatherLocationTypes;
function GetSupportedAlerts: TWeatherAlertTypes;
function GetSupportedAlertProps: TWeatherAlertProps;
function GetSupportedConditionProps: TWeatherPropTypes;
function GetSupportedForecasts: TWeatherForecastTypes;
function GetSupportedForecastSummaryProps: TWeatherPropTypes;
function GetSupportedForecastHourlyProps: TWeatherPropTypes;
function GetSupportedForecastDailyProps: TWeatherPropTypes;
function GetSupportedMaps: TWeatherMapTypes;
function GetSupportedMapFormats: TWeatherMapFormats;
property SupportedLogos: TWeatherLogoTypes read GetSupportedLogos;
property SupportedUnits: TWeatherUnitsSet read GetSupportedUnits;
property SupportedInfo: TWeatherInfoTypes read GetSupportedInfo;
property SupportedLocations: TWeatherLocationTypes read GetSupportedLocations;
property SupportedAlerts: TWeatherAlertTypes read GetSupportedAlerts;
property SupportedAlertProps: TWeatherAlertProps read GetSupportedAlertProps;
property SupportedConditionProps: TWeatherPropTypes read GetSupportedConditionProps;
property SupportedForecasts: TWeatherForecastTypes read GetSupportedForecasts;
property SupportedForecastSummaryProps: TWeatherPropTypes read GetSupportedForecastSummaryProps;
property SupportedForecastHourlyProps: TWeatherPropTypes read GetSupportedForecastHourlyProps;
property SupportedForecastDailyProps: TWeatherPropTypes read GetSupportedForecastDailyProps;
property SupportedMaps: TWeatherMapTypes read GetSupportedMaps;
property SupportedMapFormats: TWeatherMapFormats read GetSupportedMapFormats;
end;
TWeatherURLs = class(TInterfacedObject, IWeatherURLs)
public
function GetMainURL: WideString;
function GetApiURL: WideString;
function GetLoginURL: WideString;
function GetRegisterURL: WideString;
function GetLegalURL: WideString;
property MainURL: WideString read GetMainURL;
property ApiURL: WideString read GetApiURL;
property LoginURL: WideString read GetLoginURL;
property RegisterURL: WideString read GetRegisterURL;
property LegalURL: WideString read GetLegalURL;
end;
TWeatherServiceInfo = class(TInterfacedObject, IWeatherServiceInfo)
private
FSupport: TWeatherSupport;
FURLs: IWeatherURLs;
FLogos: TLogoArray;
procedure SetLogo(const LT: TWeatherLogoType; const Value: IWeatherGraphic);
procedure LoadLogos;
public
constructor Create;
destructor Destroy; override;
public
function GetCaption: WideString;
function GetName: WideString;
function GetUID: WideString;
function GetURLs: IWeatherURLs;
function GetSupport: IWeatherSupport;
function GetLogo(const LT: TWeatherLogoType): IWeatherGraphic;
property Logos[const LT: TWeatherLogoType]: IWeatherGraphic read GetLogo write SetLogo;
property Caption: WideString read GetCaption;
property Name: WideString read GetName;
property UID: WideString read GetUID;
property Support: IWeatherSupport read GetSupport;
property URLs: IWeatherURLs read GetURLs;
end;
////////////////////////////////////////////////////////////////////////////////
TWeatherService = class(TWeatherServiceBase, IWeatherService)
private
FInfo: TWeatherServiceInfo;
FLocation: TWeatherLocation;
function GetEndpointUrl(const Endpoint: TWUEndpoint): String;
function GetMultiEndpointUrl(const Endpoints: TWUEndpoints; const Ext: String): String;
function GetEndpoint(const Endpoint: TWUEndpoint): ISuperObject;
function GetMultiEndpoints(const Endpoints: TWUEndpoints; const Ext: String): ISuperObject;
function StrToAlertType(const S: String): TWeatherAlertType;
procedure FillConditions(const O: ISuperObject;
Conditions: TWeatherProps);
procedure FillAlerts(const O: ISuperObject; Alerts: TWeatherAlerts);
procedure FillForecastDaily(const O: ISuperObject;
Forecast: TWeatherForecast);
procedure FillForecastHourly(const O: ISuperObject;
Forecast: TWeatherForecast);
procedure FillForecastSummary(const O: ISuperObject;
Forecast: TWeatherForecast);
public
constructor Create; override;
destructor Destroy; override;
public
function GetInfo: IWeatherServiceInfo;
function GetMultiple(const Info: TWeatherInfoTypes): IWeatherMultiInfo;
function GetLocation: IWeatherLocation;
function GetConditions: IWeatherProps;
function GetAlerts: IWeatherAlerts;
function GetForecastSummary: IWeatherForecast;
function GetForecastHourly: IWeatherForecast;
function GetForecastDaily: IWeatherForecast;
function GetMaps: IWeatherMaps;
property Info: IWeatherServiceInfo read GetInfo;
end;
implementation
////////////////////////////////////////////////////////////////////////////////
{ TWeatherSupport }
function TWeatherSupport.GetSupportedUnits: TWeatherUnitsSet;
begin
Result:= SUP_UNITS;
end;
function TWeatherSupport.GetSupportedLocations: TWeatherLocationTypes;
begin
Result:= SUP_LOC;
end;
function TWeatherSupport.GetSupportedLogos: TWeatherLogoTypes;
begin
Result:= SUP_LOGO;
end;
function TWeatherSupport.GetSupportedAlertProps: TWeatherAlertProps;
begin
Result:= SUP_ALERT_PROP;
end;
function TWeatherSupport.GetSupportedAlerts: TWeatherAlertTypes;
begin
Result:= SUP_ALERT_TYPE;
end;
function TWeatherSupport.GetSupportedConditionProps: TWeatherPropTypes;
begin
Result:= SUP_COND_PROP;
end;
function TWeatherSupport.GetSupportedForecasts: TWeatherForecastTypes;
begin
Result:= SUP_FOR;
end;
function TWeatherSupport.GetSupportedForecastDailyProps: TWeatherPropTypes;
begin
Result:= SUP_FOR_DAY;
end;
function TWeatherSupport.GetSupportedForecastHourlyProps: TWeatherPropTypes;
begin
Result:= SUP_FOR_HOUR;
end;
function TWeatherSupport.GetSupportedForecastSummaryProps: TWeatherPropTypes;
begin
Result:= SUP_FOR_SUM;
end;
function TWeatherSupport.GetSupportedInfo: TWeatherInfoTypes;
begin
Result:= SUP_INFO;
end;
function TWeatherSupport.GetSupportedMapFormats: TWeatherMapFormats;
begin
Result:= SUP_MAP_FOR;
end;
function TWeatherSupport.GetSupportedMaps: TWeatherMapTypes;
begin
Result:= SUP_MAP;
end;
{ TWeatherURLs }
function TWeatherURLs.GetApiURL: WideString;
begin
Result:= URL_API;
end;
function TWeatherURLs.GetLegalURL: WideString;
begin
Result:= URL_LEGAL;
end;
function TWeatherURLs.GetLoginURL: WideString;
begin
Result:= URL_LOGIN;
end;
function TWeatherURLs.GetMainURL: WideString;
begin
Result:= URL_MAIN;
end;
function TWeatherURLs.GetRegisterURL: WideString;
begin
Result:= URL_REGISTER;
end;
{ TWeatherServiceInfo }
constructor TWeatherServiceInfo.Create;
var
LT: TWeatherLogoType;
begin
FSupport:= TWeatherSupport.Create;
FSupport._AddRef;
FURLs:= TWeatherURLs.Create;
FURLs._AddRef;
for LT:= Low(TWeatherLogoType) to High(TWeatherLogoType) do begin
FLogos[LT]:= TWeatherGraphic.Create;
FLogos[LT]._AddRef;
end;
LoadLogos;
end;
destructor TWeatherServiceInfo.Destroy;
var
LT: TWeatherLogoType;
begin
for LT:= Low(TWeatherLogoType) to High(TWeatherLogoType) do begin
FLogos[LT]._Release;
end;
FURLs._Release;
FURLs:= nil;
FSupport._Release;
FSupport:= nil;
inherited;
end;
function TWeatherServiceInfo.GetCaption: WideString;
begin
Result:= SVC_CAPTION;
end;
function TWeatherServiceInfo.GetName: WideString;
begin
Result:= SVC_NAME;
end;
function TWeatherServiceInfo.GetSupport: IWeatherSupport;
begin
Result:= FSupport;
end;
function TWeatherServiceInfo.GetUID: WideString;
begin
Result:= SVC_UID;
end;
function TWeatherServiceInfo.GetURLs: IWeatherURLs;
begin
Result:= FURLs;
end;
function TWeatherServiceInfo.GetLogo(const LT: TWeatherLogoType): IWeatherGraphic;
begin
Result:= FLogos[LT];
end;
procedure TWeatherServiceInfo.SetLogo(const LT: TWeatherLogoType;
const Value: IWeatherGraphic);
begin
FLogos[LT].Base64:= Value.Base64;
end;
procedure TWeatherServiceInfo.LoadLogos;
function Get(const N, T: String): IWeatherGraphic;
var
S: TResourceStream;
R: TStringStream;
begin
Result:= TWeatherGraphic.Create;
if ResourceExists(N, T) then begin
raise Exception.Create('TEST!');
S:= TResourceStream.Create(HInstance, N, PChar(T));
try
R:= TStringStream.Create;
try
S.Position:= 0;
R.LoadFromStream(S);
R.Position:= 0;
Result.Base64:= R.DataString;
finally
FreeAndNil(R);
end;
finally
FreeAndNil(S);
end;
end;
end;
begin
SetLogo(ltColor, Get('LOGO_COLOR', 'JPG'));
SetLogo(ltColorInvert, Get('LOGO_COLOR_INVERT', 'JPG'));
SetLogo(ltColorWide, Get('LOGO_COLOR_WIDE', 'JPG'));
SetLogo(ltColorInvertWide, Get('LOGO_COLOR_INVERT_WIDE', 'JPG'));
SetLogo(ltColorLeft, Get('LOGO_COLOR_LEFT', 'JPG'));
SetLogo(ltColorRight, Get('LOGO_COLOR_RIGHT', 'JPG'));
end;
////////////////////////////////////////////////////////////////////////////////
{ TWeatherService }
constructor TWeatherService.Create;
begin
inherited;
FInfo:= TWeatherServiceInfo.Create;
FInfo._AddRef;
end;
destructor TWeatherService.Destroy;
begin
FInfo._Release;
FInfo:= nil;
inherited;
end;
function TWeatherService.GetEndpointUrl(const Endpoint: TWUEndpoint): String;
var
S: String;
begin
case Endpoint of
weAll: S:= 'conditions/alerts/hourly/forecast10day';
weAlerts: S:= 'alerts';
weAlmanac: S:= 'almanac';
weAstronomy: S:= 'astronomy';
weConditions: S:= 'conditions';
weCurrentHurricane: S:= 'currenthurricane';
weForecast: S:= 'forecast';
weForecast10Day: S:= 'forecast10day';
weGeoLookup: S:= 'geolookup';
weHistory: S:= 'history';
weHourly: S:= 'hourly';
weHourly10Day: S:= 'hourly10day';
wePlanner: S:= 'planner';
weRawTide: S:= 'rawtide';
weTide: S:= 'tide';
weWebCams: S:= 'webcams';
weYesterday: S:= 'yesterday';
weRadar: S:= 'radar';
weSatellite: S:= 'satellite';
weRadarSatellite: S:= 'radar/satellite';
weAniRadar: S:= 'animatedradar';
weAniSatellite: S:= 'animatedsatellite';
weAniRadarSatellite: S:= 'animatedradar/animatedsatellite';
end;
Result:= 'http://api.wunderground.com/api/'+Key+'/' + S + '/q/';
case LocationType of
wlZip: Result:= Result + LocationDetail1;
wlCityState: Result:= Result + LocationDetail2+'/'+LocationDetail1;
wlCoords: Result:= Result + LocationDetail1+','+LocationDetail2;
wlAutoIP: Result:= Result + 'autoip';
wlCityCode: Result:= Result + ''; //TODO
wlCountryCity: Result:= Result + LocationDetail1+'/'+LocationDetail2;
wlAirportCode: Result:= Result + LocationDetail1;
wlPWS: Result:= Result + 'pws:'+LocationDetail1;
end;
case Endpoint of
weRadar..weAniRadarSatellite: begin
Result:= Result + '.gif';
end;
else begin
Result:= Result + '.json';
end;
end;
end;
function TWeatherService.GetMultiEndpointUrl(const Endpoints: TWUEndpoints; const Ext: String): String;
var
S: String;
procedure Chk(const E: TWUEndpoint; const V: String);
begin
if E in Endpoints then begin
if S <> '' then S:= S + '/';
S:= S + V;
end;
end;
begin
S:= '';
Chk(weAlerts, 'alerts');
Chk(weAlmanac, 'almanac');
Chk(weAstronomy, 'astronomy');
Chk(weConditions, 'conditions');
Chk(weCurrentHurricane, 'currenthurricane');
Chk(weForecast, 'forecast');
Chk(weForecast10Day, 'forecast10day');
Chk(weGeoLookup, 'geolookup');
Chk(weHistory, 'history');
Chk(weHourly, 'hourly');
Chk(weHourly10Day, 'hourly10day');
Chk(wePlanner, 'planner');
Chk(weRawTide, 'rawtide');
Chk(weTide, 'tide');
Chk(weWebCams, 'webcams');
Chk(weYesterday, 'yesterday');
Chk(weRadar, 'radar');
Chk(weSatellite, 'satellite');
Chk(weAniRadar, 'animatedradar');
Chk(weAniSatellite, 'animatedsatellite');
Result:= 'http://api.wunderground.com/api/'+Key+'/' + S + '/q/';
case LocationType of
wlZip: Result:= Result + LocationDetail1;
wlCityState: Result:= Result + LocationDetail2+'/'+LocationDetail1;
wlCoords: Result:= Result + LocationDetail1+','+LocationDetail2;
wlAutoIP: Result:= Result + 'autoip';
wlCityCode: Result:= Result + ''; //TODO
wlCountryCity: Result:= Result + LocationDetail1+'/'+LocationDetail2;
wlAirportCode: Result:= Result + LocationDetail1;
wlPWS: Result:= Result + 'pws:'+LocationDetail1;
end;
Result:= Result + Ext;
end;
function TWeatherService.GetEndpoint(const Endpoint: TWUEndpoint): ISuperObject;
var
U: String;
S: String;
begin
U:= GetEndpointUrl(Endpoint);
S:= Web.Get(U);
Result:= SO(S);
end;
function TWeatherService.GetMultiEndpoints(const Endpoints: TWUEndpoints; const Ext: String): ISuperObject;
var
U: String;
S: String;
begin
U:= GetMultiEndpointUrl(Endpoints, Ext);
S:= Web.Get(U);
Result:= SO(S);
end;
function TWeatherService.GetMultiple(const Info: TWeatherInfoTypes): IWeatherMultiInfo;
var
O: ISuperObject;
R: TWeatherMultiInfo;
Con: TWeatherProps;
Alr: TWeatherAlerts;
Fos: TWeatherForecast;
Foh: TWeatherForecast;
Fod: TWeatherForecast;
Map: IWeatherMaps;
E: TWUEndpoints;
begin
R:= TWeatherMultiInfo.Create;
try
Con:= TWeatherProps.Create;
Alr:= TWeatherAlerts.Create;
Fos:= TWeatherForecast.Create;
Foh:= TWeatherForecast.Create;
Fod:= TWeatherForecast.Create;
E:= [];
if wiConditions in Info then begin
E:= E + [weConditions];
end;
if wiAlerts in Info then begin
E:= E + [weAlerts];
end;
if wiForecastSummary in Info then begin
E:= E + [weForecast];
end;
if wiForecastHourly in Info then begin
E:= E + [weForecast10Day];
end;
if wiForecastDaily in Info then begin
E:= E + [weHourly];
end;
O:= GetMultiEndpoints(E, '.json');
if wiConditions in Info then begin
FillConditions(O, Con);
end;
if wiAlerts in Info then begin
FillAlerts(O, Alr);
end;
if wiForecastSummary in Info then begin
FillForecastSummary(O, Fos);
end;
if wiForecastHourly in Info then begin
FillForecastHourly(O, Foh);
end;
if wiForecastDaily in Info then begin
FillForecastDaily(O, Fod);
end;
if wiMaps in Info then begin
Map:= GetMaps;
end else begin
Map:= TWeatherMaps.Create;
end;
R.SetAll(Con, Alr, Fos, Foh, Fod, Map);
finally
Result:= R;
end;
end;
function TWeatherService.GetConditions: IWeatherProps;
var
O: ISuperObject;
R: TWeatherProps;
begin
R:= TWeatherProps.Create;
try
O:= GetEndpoint(TWUEndpoint.weConditions);
FillConditions(O, R);
finally
Result:= R;
end;
end;
function TWeatherService.GetAlerts: IWeatherAlerts;
var
O: ISuperObject;
R: TWeatherAlerts;
begin
R:= TWeatherAlerts.Create;
try
O:= GetEndpoint(TWUEndpoint.weAlerts);
FillAlerts(O, R);
finally
Result:= R;
end;
end;
function TWeatherService.GetForecastDaily: IWeatherForecast;
var
O: ISuperObject;
R: TWeatherForecast;
begin
R:= TWeatherForecast.Create;
try
O:= GetEndpoint(TWUEndpoint.weForecast10Day);
FillForecastDaily(O, R);
finally
Result:= R;
end;
end;
function TWeatherService.GetForecastHourly: IWeatherForecast;
var
O: ISuperObject;
R: TWeatherForecast;
begin
R:= TWeatherForecast.Create;
try
O:= GetEndpoint(TWUEndpoint.weHourly);
FillForecastHourly(O, R);
finally
Result:= R;
end;
end;
function TWeatherService.GetForecastSummary: IWeatherForecast;
var
O: ISuperObject;
R: TWeatherForecast;
begin
R:= TWeatherForecast.Create;
try
O:= GetEndpoint(TWUEndpoint.weForecast);
FillForecastSummary(O, R);
finally
Result:= R;
end;
end;
function TWeatherService.GetInfo: IWeatherServiceInfo;
begin
Result:= FInfo;
end;
function TWeatherService.GetLocation: IWeatherLocation;
begin
Result:= FLocation;
end;
function MapOptions(
const Width: Integer = 400;
const Height: Integer = 400;
const NumFrames: Integer = 10;
const Delay: Integer = 50;
const FrameIndex: Integer = 0;
const NoClutter: Boolean = True;
const SmoothColors: Boolean = True;
const RainSnow: Boolean = True;
const TimeLabel: Boolean = True;
const TimeLabelX: Integer = 10;
const TimeLabelY: Integer = 20): String;
begin
Result:= 'newmaps=1';
Result:= Result + '&width='+IntToStr(Width);
Result:= Result + '&height='+IntToStr(Height);
Result:= Result + '&delay='+IntToStr(Delay);
Result:= Result + '&num='+IntToStr(NumFrames);
Result:= Result + '&frame='+IntToStr(FrameIndex);
Result:= Result + '&noclutter='+IfThen(NoClutter, '1','0');
Result:= Result + '&smooth='+IfThen(SmoothColors, '1','0');
Result:= Result + '&rainsnow='+IfThen(RainSnow, '1','0');
if TimeLabel then begin
Result:= Result + '&timelabel=1';
Result:= Result + '&timelabel.x='+IntToStr(TimeLabelX);
Result:= Result + '&timelabel.y='+IntToStr(TimeLabelY);
end;
end;
function TWeatherService.GetMaps: IWeatherMaps;
var
{$IFDEF USE_VCL}
I: TGifImage;
{$ENDIF}
R: TWeatherMaps;
S: TStringStream;
U: String;
procedure GetMap(const EP: TWUEndpoint; const MT: TWeatherMapType);
begin
S.Clear;
S.Position:= 0;
U:= GetEndpointUrl(EP);
U:= U + '?'+MapOptions(700, 700, 15, 60);
Web.Get(U, S);
S.Position:= 0;
{$IFDEF USE_VCL}
I:= TGifImage.Create;
try
I.LoadFromStream(S);
Maps.Maps[MT].Assign(I);
finally
I.Free;
end;
{$ELSE}
Result.Maps[MT].Base64:= S.DataString;
{$ENDIF}
end;
begin
R:= TWeatherMaps.Create;
try
S:= TStringStream.Create;
try
//TODO...
finally
FreeAndNil(S);
end;
finally
Result:= R;
end;
end;
procedure TWeatherService.FillConditions(const O: ISuperObject; Conditions: TWeatherProps);
var
OB, L: ISuperObject;
function LD(const O: ISuperObject; const N: String): Double;
var
T: String;
I: Integer;
begin
T:= O.S[N];
for I := Length(T) downto 1 do begin
if not CharInSet(T[I], ['0'..'9', '.', ',']) then
Delete(T, I, 1);
end;
Result:= StrToFloatDef(T, 0);
end;
begin
OB:= O.O['current_observation'];
if not Assigned(OB) then Exit;
L:= OB.O['display_location'];
if not Assigned(L) then Exit;
if Assigned(FLocation) then
IWeatherLocation(FLocation)._Release;
FLocation:= TWeatherLocation.Create;
FLocation.FDisplayName:= L.S['full'];
FLocation.FCity:= L.S['city'];
FLocation.FState:= L.S['state_name'];
FLocation.FStateAbbr:= L.S['state'];
FLocation.FCountry:= L.S['country'];
FLocation.FCountryAbbr:= L.S['country_iso3166'];
FLocation.FLongitude:= LD(L, 'longitude');
FLocation.FLatitude:= LD(L, 'latitude');
FLocation.FElevation:= LD(L, 'elevation');
FLocation.FZipCode:= L.S['zip'];
//TODO: Trigger event for location.....
Conditions.FSupport:= Self.Info.Support.SupportedConditionProps;
Conditions.FDateTime:= EpochLocal(StrToIntDef(OB.S['observation_epoch'], 0)); // Now; //TODO
Conditions.FCaption:= OB.S['weather'];
Conditions.FURL:= OB.S['ob_url'];
Conditions.FStation:= OB.S['station_id'];
Conditions.FHumidity:= LD(OB, 'relative_humidity');
Conditions.FWindDir:= OB.D['wind_degrees'];
Conditions.FSolarRad:= LD(OB, 'solarradiation');
Conditions.FUVIndex:= LD(OB, 'UV');
case Units of
wuKelvin: begin
//Not Supported
//TODO: Convert so that it can be supported
end;
wuImperial: begin
Conditions.FTemp:= OB.D['temp_f'];
Conditions.FVisibility:= LD(OB, 'visibility_mi');
Conditions.FDewPoint:= OB.D['dewpoint_f'];
Conditions.FPressure:= LD(OB, 'pressure_in');
Conditions.FWindSpeed:= LD(OB, 'wind_mph');
Conditions.FWindGusts:= LD(OB, 'wind_gust_mph');
Conditions.FWindChill:= LD(OB, 'windchill_f');
Conditions.FFeelsLike:= LD(OB, 'feelslike_f');
Conditions.FHeatIndex:= LD(OB, 'heat_index_f');
Conditions.FPrecipAmt:= LD(OB, 'precip_today_in');
end;
wuMetric: begin
Conditions.FTemp:= OB.D['temp_c'];
Conditions.FVisibility:= LD(OB, 'visibility_km');
Conditions.FDewPoint:= OB.D['dewpoint_c'];
Conditions.FPressure:= LD(OB, 'pressure_mb');
Conditions.FWindSpeed:= LD(OB, 'wind_kph');
Conditions.FWindGusts:= LD(OB, 'wind_gust_kph');
Conditions.FWindChill:= LD(OB, 'windchill_c');
Conditions.FFeelsLike:= LD(OB, 'feelslike_c');
Conditions.FHeatIndex:= LD(OB, 'heat_index_c');
Conditions.FPrecipAmt:= LD(OB, 'precip_today_metric');
end;
end;
//LoadPicture(OB.S['icon_url'], Conditions.FPicture);
end;
function TWeatherService.StrToAlertType(const S: String): TWeatherAlertType;
procedure Chk(const Val: String; const T: TWeatherAlertType);
begin
if SameText(S, Val) then begin
Result:= T;
end;
end;
begin
Chk('', TWeatherAlertType.waNone);
Chk('HUR', TWeatherAlertType.waHurricaneStat);
Chk('TOR', TWeatherAlertType.waTornadoWarn);
Chk('TOW', TWeatherAlertType.waTornadoWatch);
Chk('WRN', TWeatherAlertType.waSevThundWarn);
Chk('SEW', TWeatherAlertType.waSevThundWatch);
Chk('WIN', TWeatherAlertType.waWinterAdv);
Chk('FLO', TWeatherAlertType.waFloodWarn);
Chk('WAT', TWeatherAlertType.waFloodWatch);
Chk('WND', TWeatherAlertType.waHighWind);
Chk('SVR', TWeatherAlertType.waSevStat);
Chk('HEA', TWeatherAlertType.waHeatAdv);
Chk('FOG', TWeatherAlertType.waFogAdv);
Chk('SPE', TWeatherAlertType.waSpecialStat);
Chk('FIR', TWeatherAlertType.waFireAdv);
Chk('VOL', TWeatherAlertType.waVolcanicStat);
Chk('HWW', TWeatherAlertType.waHurricaneWarn);
Chk('REC', TWeatherAlertType.waRecordSet);
Chk('REP', TWeatherAlertType.waPublicRec);
Chk('PUB', TWeatherAlertType.waPublicStat);
end;
procedure TWeatherService.FillAlerts(const O: ISuperObject; Alerts: TWeatherAlerts);
var
A: TSuperArray;
Tmp: Int64;
I: TWeatherAlert;
Obj: ISuperObject;
X: Integer;
function LD(const O: ISuperObject; const N: String): Double;
var
T: String;
begin
T:= O.S[N];
Result:= StrToFloatDef(T, 0);
end;
begin
A:= O.A['alerts'];
if not Assigned(A) then Exit;
for X := 0 to A.Length-1 do begin
Obj:= A.O[X];
I:= TWeatherAlert.Create;
try
I.FAlertType:= StrToAlertType(Obj.S['type']);
I.FDescription:= Obj.S['description'];
Tmp:= StrToIntDef(Obj.S['date_epoch'], 0);
I.FDateTime:= EpochLocal(Tmp);
Tmp:= StrToIntDef(Obj.S['expires_epoch'], 0);
I.FExpires:= EpochLocal(Tmp);
I.FMsg:= Obj.S['message'];
I.FPhenomena:= Obj.S['phenomena'];
I.FSignificance:= Obj.S['significance'];
//Zones
//Storm
finally
Alerts.FItems.Add(I);
end;
end;
end;
procedure TWeatherService.FillForecastSummary(const O: ISuperObject; Forecast: TWeatherForecast);
var
OB: ISuperObject;
A: TSuperArray;
I: TWeatherProps;
X: Integer;
function LD(const O: ISuperObject; const N: String): Double;
var
T: String;
begin
T:= O.S[N];
Result:= StrToFloatDef(T, 0);
end;
begin
OB:= O.O['forecast'];
if not Assigned(OB) then Exit;
OB:= OB.O['txt_forecast'];
if not Assigned(OB) then Exit;
A:= OB.A['forecastday'];
if not Assigned(A) then begin
Exit;
end;
for X := 0 to A.Length-1 do begin
OB:= A.O[X];
I:= TWeatherProps.Create;
try
case Units of
wuKelvin: begin
//TODO: NOT SUPPORTED - Calculate?
I.FTempMin:= StrToFloatDef(OB.O['temp'].S['metric'], 0);
I.FTempMax:= StrToFloatDef(OB.O['temp'].S['metric'], 0);
I.FDewPoint:= StrToFloatDef(OB.O['dewpoint'].S['metric'], 0);
I.FWindSpeed:= OB.O['wspd'].D['metric'];
end;
wuImperial: begin
I.FTempMin:= StrToFloatDef(OB.O['temp'].S['english'], 0);
I.FTempMax:= StrToFloatDef(OB.O['temp'].S['english'], 0);
I.FWindSpeed:= StrToFloatDef(OB.O['wspd'].S['english'], 0);
I.FDewPoint:= StrToFloatDef(OB.O['dewpoint'].S['english'], 0);
end;
wuMetric: begin
I.FTempMin:= StrToFloatDef(OB.O['temp'].S['metric'], 0);
I.FTempMax:= StrToFloatDef(OB.O['temp'].S['metric'], 0);
I.FWindSpeed:= StrToFloatDef(OB.O['wspd'].S['metric'], 0);
I.FDewPoint:= StrToFloatDef(OB.O['dewpoint'].S['metric'], 0);
end;
end;
I.FDateTime:= EpochLocal(StrToIntDef(OB.O['FCTTIME'].S['epoch'], 0));
I.FTemp:= I.FTempMax; //TODO
I.FHumidity:= StrToFloatDef(OB.S['humidity'], 0);
I.FPressure:= 0;
I.FCaption:= OB.S['condition'];
I.FDescription:= OB.S['condition'];
I.FWindDir:= StrToFloatDef(OB.O['wdir'].S['degrees'], 0);
I.FVisibility:= 0;
{$IFDEF USE_VCL}
LoadPicture(OB.S['icon_url'], I.FPicture);
{$ENDIF}
finally
Forecast.FItems.Add(I);
end;
end;
end;
procedure TWeatherService.FillForecastDaily(const O: ISuperObject; Forecast: TWeatherForecast);
var
OB: ISuperObject;
A: TSuperArray;
I: TWeatherProps;
X: Integer;
function LD(const O: ISuperObject; const N: String): Double;
var
T: String;
begin
T:= O.S[N];
Result:= StrToFloatDef(T, 0);
end;
begin
OB:= O.O['forecast'];
if not Assigned(OB) then begin
Exit;
end;
OB:= OB.O['simpleforecast'];
if not Assigned(OB) then begin
Exit;
end;
A:= OB.A['forecastday'];
if not Assigned(A) then begin
Exit;
end;
for X := 0 to A.Length-1 do begin
OB:= A.O[X];
I:= TWeatherProps.Create;
try
case Units of
wuKelvin: begin
//TODO: NOT SUPPORTED - Calculate?
I.FTempMin:= StrToFloatDef(OB.O['low'].S['celsius'], 0);
I.FTempMax:= StrToFloatDef(OB.O['high'].S['celsius'], 0);
I.FWindSpeed:= OB.O['avewind'].D['kph'];
I.FDewPoint:= 0; //Not Supported
end;
wuImperial: begin
I.FTempMin:= StrToFloatDef(OB.O['low'].S['ferenheit'], 0);
I.FTempMax:= StrToFloatDef(OB.O['high'].S['ferenheit'], 0);
I.FWindSpeed:= StrToFloatDef(OB.O['avewind'].S['mph'], 0);
I.FDewPoint:= 0; //Not Supported
end;
wuMetric: begin
I.FTempMin:= StrToFloatDef(OB.O['low'].S['celsius'], 0);
I.FTempMax:= StrToFloatDef(OB.O['high'].S['celsius'], 0);
I.FWindSpeed:= StrToFloatDef(OB.O['avewind'].S['kph'], 0);
I.FDewPoint:= 0; //Not Supported
end;
end;
I.FDateTime:= EpochLocal(StrToIntDef(OB.O['date'].S['epoch'], 0));
I.FTemp:= I.FTempMax; //TODO
I.FHumidity:= StrToFloatDef(OB.S['avehumidity'], 0);
I.FPressure:= 0;
I.FCaption:= OB.S['conditions'];
I.FDescription:= OB.S['conditions'];
I.FWindDir:= StrToFloatDef(OB.O['avewind'].S['degrees'], 0);
I.FVisibility:= 0; //Not Supported
{$IFDEF USE_VCL}
LoadPicture(OB.S['icon_url'], I.FPicture);
{$ENDIF}
finally
Forecast.FItems.Add(I);
end;
end;
end;
procedure TWeatherService.FillForecastHourly(const O: ISuperObject; Forecast: TWeatherForecast);
var
OB: ISuperObject;
A: TSuperArray;
I: TWeatherProps;
X: Integer;
function LD(const O: ISuperObject; const N: String): Double;
var
T: String;
begin
T:= O.S[N];
Result:= StrToFloatDef(T, 0);
end;
begin
A:= O.A['hourly_forecast'];
if not Assigned(A) then begin
Exit;
end;
for X := 0 to A.Length-1 do begin
OB:= A.O[X];
I:= TWeatherProps.Create;
try
case Units of
wuKelvin: begin
//TODO: NOT SUPPORTED - Calculate?
I.FTempMin:= StrToFloatDef(OB.O['temp'].S['metric'], 0);
I.FTempMax:= StrToFloatDef(OB.O['temp'].S['metric'], 0);
I.FDewPoint:= StrToFloatDef(OB.O['dewpoint'].S['metric'], 0);
I.FWindSpeed:= OB.O['wspd'].D['metric'];
end;
wuImperial: begin
I.FTempMin:= StrToFloatDef(OB.O['temp'].S['english'], 0);
I.FTempMax:= StrToFloatDef(OB.O['temp'].S['english'], 0);
I.FWindSpeed:= StrToFloatDef(OB.O['wspd'].S['english'], 0);
I.FDewPoint:= StrToFloatDef(OB.O['dewpoint'].S['english'], 0);
end;
wuMetric: begin
I.FTempMin:= StrToFloatDef(OB.O['temp'].S['metric'], 0);
I.FTempMax:= StrToFloatDef(OB.O['temp'].S['metric'], 0);
I.FWindSpeed:= StrToFloatDef(OB.O['wspd'].S['metric'], 0);
I.FDewPoint:= StrToFloatDef(OB.O['dewpoint'].S['metric'], 0);
end;
end;
I.FDateTime:= EpochLocal(StrToIntDef(OB.O['FCTTIME'].S['epoch'], 0));
I.FTemp:= I.FTempMax; //TODO
I.FHumidity:= StrToFloatDef(OB.S['humidity'], 0);
I.FPressure:= 0;
I.FCaption:= OB.S['condition'];
I.FDescription:= OB.S['condition'];
I.FWindDir:= StrToFloatDef(OB.O['wdir'].S['degrees'], 0);
I.FVisibility:= 0;
{$IFDEF USE_VCL}
LoadPicture(OB.S['icon_url'], I.FPicture);
{$ELSE}
I.FIcon.SetBase64(''); //TODO
{$ENDIF}
finally
Forecast.FItems.Add(I);
end;
end;
end;
end.
|
const fileinp = 'bprimes.inp';
fileout = 'bprimes.out';
var n,h:longint;
procedure Init;
begin
assign(input,fileinp); reset(input);
readln(n,h);
close(input);
end;
function BitCount(a:longint):longint;
begin
BitCount:=0;
while a <> 0 do
begin
if a mod 2 = 1 then inc(BitCount);
a:=a div 2;
end;
end;
function isPrime(x:longint):boolean;
var i:longint;
begin
for i:=2 to trunc(sqrt(x)) do
if x mod i = 0 then
exit(false);
exit(true);
end;
procedure Print;
var i,count:longint;
begin
assign(output,fileout); rewrite(output);
count:=0;
for i:=2 to n do
if (BitCount(i) = h) and (isPrime(i)) then
inc(count);
writeln(count);
close(output);
end;
begin
Init;
Print;
end.
|
unit AssoFiles;
interface
uses System.Win.Registry, ShlObj, Vcl.Forms,System.Types,Winapi.Windows, System.Classes, System.SysUtils, System.IniFiles;
procedure Associate;
procedure DeleteAssociate;
implementation
var Reg: TRegistry;
procedure Associate;
var
s:string;
begin
try
Reg:=TRegistry.Create; // создаем
Reg.RootKey:=HKEY_CLASSES_ROOT; // указываем корневую ветку
Reg.OpenKey('.pdf\OpenWithProgids\', true);
Reg.WriteString('NPV.exe', '');
Reg.OpenKey('\NPV.exe\DefaultIcon\', true);
s:=Application.ExeName+',0';
Reg.WriteString('', s);
Reg.OpenKey('\NPV.exe\Shell\Open\', true);
Reg.WriteString('', 'Открыть в Nano PDF Viewer');
Reg.OpenKey('command\', true);
s:='"'+Application.ExeName+'" "%1"';
Reg.WriteString('', s);
finally
Reg.Free;
end;
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, nil, nil);
end;
procedure DeleteAssociate;
begin
Reg:=TRegistry.Create;
Reg.RootKey := HKEY_CLASSES_ROOT;
reg.DeleteKey('.pdf');
reg.DeleteKey('NPF.exe');
Reg.Free;
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, nil, nil);
end;
end.
|
(*
Name: VisualKeyboardInfo
Copyright: Copyright (C) 2003-2017 SIL International.
Documentation:
Description:
Create Date: 3 May 2011
Modified Date: 3 May 2011
Authors: mcdurdin
Related Files:
Dependencies:
Bugs:
Todo:
Notes:
History: 03 May 2011 - mcdurdin - I2890 - Record diagnostic data when encountering registry errors
*)
unit VisualKeyboardInfo;
interface
uses VisualKeyboard, Contnrs;
type
TVisualKeyboardInfo = class
public
Keyboard: TVisualKeyboard;
FileName: string;
KeymanID: Integer;
KeymanName: string;
destructor Destroy; override;
end;
TVisualKeyboardInfoList = class(TObjectList)
protected
function Get(Index: Integer): TVisualKeyboardInfo;
procedure Put(Index: Integer; Item: TVisualKeyboardInfo);
public
property Items[Index: Integer]: TVisualKeyboardInfo read Get write Put; default;
function Add(Item: TVisualKeyboardInfo): Integer;
procedure Load;
end;
implementation
uses
Classes,
klog,
ErrorControlledRegistry,
RegistryKeys,
SysUtils,
Windows;
{ TVisualKeyboardInfoList }
function TVisualKeyboardInfoList.Add(Item: TVisualKeyboardInfo): Integer;
begin
Result := inherited Add(Item);
end;
function TVisualKeyboardInfoList.Get(Index: Integer): TVisualKeyboardInfo;
begin
Result := TVisualKeyboardInfo(inherited Get(Index));
end;
procedure TVisualKeyboardInfoList.Load;
procedure LoadExt(hkey: HKEY);
var
i: Integer;
begin
with TRegistryErrorControlled.Create do // I2890
try
RootKey := hkey;
for i := 0 to Count - 1 do
if OpenKeyReadOnly('\'+SRegKey_InstalledKeyboards+'\'+Items[i].KeymanName) then
if ValueExists(SRegValue_VisualKeyboard) then Items[i].FileName := ReadString(SRegValue_VisualKeyboard);
finally
Free;
end;
end;
var
str: TStringList;
vki: TVisualKeyboardInfo;
i: Integer;
begin
KL.Log('Loading visual keyboards');
Clear;
str := TStringList.Create;
with TRegistryErrorControlled.Create do // I2890
try
RootKey := HKEY_CURRENT_USER;
if OpenKeyReadOnly(SRegKey_ActiveKeyboards) then
begin
GetValueNames(str);
for i := 0 to str.Count - 1 do
begin
vki := TVisualKeyboardInfo.Create;
vki.KeymanID := StrToIntDef(str[i], 10000);
vki.KeymanName := ReadString(str[i]);
vki.Keyboard := nil;
vki.FileName := '';
Add(vki);
end;
end;
LoadExt(HKEY_CURRENT_USER);
LoadExt(HKEY_LOCAL_MACHINE);
for i := 0 to Count - 1 do
KL.Log('Visual Keyboard '+Items[i].KeymanName+'='+Items[i].FileName);
finally
Free;
str.Free;
end;
end;
procedure TVisualKeyboardInfoList.Put(Index: Integer; Item: TVisualKeyboardInfo);
begin
inherited Put(Index, Item);
end;
{ TVisualKeyboardInfo }
destructor TVisualKeyboardInfo.Destroy;
begin
FreeAndNil(Keyboard);
inherited Destroy;
end;
end.
|
{ 25/05/2007 10:50:23 (GMT+1:00) > [Akadamia] checked in }
{ 25/05/2007 10:30:11 (GMT+1:00) > [Akadamia] checked out /}
{ 14/02/2007 08:28:48 (GMT+0:00) > [Akadamia] checked in }
{ 14/02/2007 08:28:29 (GMT+0:00) > [Akadamia] checked out /}
{ 12/02/2007 10:12:26 (GMT+0:00) > [Akadamia] checked in }
{ 12/02/2007 10:12:19 (GMT+0:00) > [Akadamia] checked out /}
{ 12/02/2007 10:11:32 (GMT+0:00) > [Akadamia] checked in }
{ 08/02/2007 14:07:15 (GMT+0:00) > [Akadamia] checked in }
{-----------------------------------------------------------------------------
Unit Name: DBMU
Author: ken.adam
Date: 15-Jan-2007
Purpose: Translation of DialogBoxMode example to Delphi
If the key combination U+Q is typed, a request is sent to set
Dialog Mode, and if it is successful, a message box is rendered, and then
Dialog Mode is turned off.
History:
-----------------------------------------------------------------------------}
unit DBMU;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ImgList, ToolWin, ActnMan, ActnCtrls, XPStyleActnCtrls,
ActnList, ComCtrls, SimConnect, StdActns;
const
// Define a user message for message driven version of the example
WM_USER_SIMCONNECT = WM_USER + 2;
type
// Use enumerated types to create unique IDs as required
TGroupId = (Group0);
TEventID = (Event0);
TInputId = (Input0);
TDataRequestId = (Request0);
// The form
TDialogBoxModeForm = class(TForm)
StatusBar: TStatusBar;
ActionManager: TActionManager;
ActionToolBar: TActionToolBar;
Images: TImageList;
Memo: TMemo;
StartPoll: TAction;
FileExit: TFileExit;
StartEvent: TAction;
procedure StartPollExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure SimConnectMessage(var Message: TMessage); message
WM_USER_SIMCONNECT;
procedure StartEventExecute(Sender: TObject);
private
{ Private declarations }
RxCount: integer; // Count of Rx messages
Quit: boolean; // True when signalled to quit
hSimConnect: THandle; // Handle for the SimConection
public
{ Public declarations }
procedure DispatchHandler(pData: PSimConnectRecv; cbData: DWORD; pContext:
Pointer);
end;
var
DialogBoxModeForm: TDialogBoxModeForm;
implementation
resourcestring
StrRx6d = 'Rx: %6d';
{$R *.dfm}
{-----------------------------------------------------------------------------
Procedure: MyDispatchProc
Wraps the call to the form method in a simple StdCall procedure
Author: ken.adam
Date: 11-Jan-2007
Arguments:
pData: PSimConnectRecv
cbData: DWORD
pContext: Pointer
-----------------------------------------------------------------------------}
procedure MyDispatchProc(pData: PSimConnectRecv; cbData: DWORD; pContext:
Pointer); stdcall;
begin
DialogBoxModeForm.DispatchHandler(pData, cbData, pContext);
end;
{-----------------------------------------------------------------------------
Procedure: DispatchHandler
Handle the Dispatched callbacks in a method of the form. Note that this is
used by both methods of handling the interface.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
pData: PSimConnectRecv
cbData: DWORD
pContext: Pointer
-----------------------------------------------------------------------------}
procedure TDialogBoxModeForm.DispatchHandler(pData: PSimConnectRecv; cbData:
DWORD;
pContext: Pointer);
var
hr: HRESULT;
Evt: PSimconnectRecvEvent;
OpenData: PSimConnectRecvOpen;
pState: PSimConnectRecvSystemState;
begin
// Maintain a display of the message count
Inc(RxCount);
StatusBar.Panels[1].Text := Format(StrRx6d, [RxCount]);
// Only keep the last 200 lines in the Memo
while Memo.Lines.Count > 200 do
Memo.Lines.Delete(0);
// Handle the various types of message
case TSimConnectRecvId(pData^.dwID) of
SIMCONNECT_RECV_ID_OPEN:
begin
StatusBar.Panels[0].Text := 'Opened';
OpenData := PSimConnectRecvOpen(pData);
with OpenData^ do
begin
Memo.Lines.Add('');
Memo.Lines.Add(Format('%s %1d.%1d.%1d.%1d', [szApplicationName,
dwApplicationVersionMajor, dwApplicationVersionMinor,
dwApplicationBuildMajor, dwApplicationBuildMinor]));
Memo.Lines.Add(Format('%s %1d.%1d.%1d.%1d', ['SimConnect',
dwSimConnectVersionMajor, dwSimConnectVersionMinor,
dwSimConnectBuildMajor, dwSimConnectBuildMinor]));
Memo.Lines.Add('');
end;
end;
SIMCONNECT_RECV_ID_EVENT:
begin
evt := PSimconnectRecvEvent(pData);
case TEventId(evt^.uEventID) of
Event0:
begin
Memo.Lines.Add(Format('EVENT0: %d', [evt^.dwData]));
// Send a request to turn Dialog Mode on
hr := SimConnect_SetSystemState(hSimConnect, 'DialogMode', 1, 0,
nil);
// Send a request to ask whether Dialog Mode is on
hr := SimConnect_RequestSystemState(hSimConnect, Ord(REQUEST0),
'DialogMode');
end;
else
Memo.Lines.Add(Format('SIMCONNECT_RECV_EVENT: 0x%08X 0x%08X 0x%X',
[evt^.uEventID, evt^.dwData, cbData]));
end;
end;
SIMCONNECT_RECV_ID_SYSTEM_STATE:
begin
pState := PSimConnectRecvSystemState(pData);
case TDataRequestId(pState^.dwRequestID) of
REQUEST0:
begin
// If Dialog Mode is on, show a Message box
if pState^.dwInteger <> 0 then
begin
MessageBox(0, 'Test!', 'Dialog Mode is on', MB_OK);
// Send a request to turn Dialog Mode off
hr := SimConnect_SetSystemState(hSimConnect, 'DialogMode', 0, 0,
nil);
end;
end;
end;
Memo.Lines.Add(Format('SIMCONNECT_RECV_SYSTEM_STATE RequestID=%d dwInteger=%d fFloat=%f szString="%s"',
[pState^.dwRequestID, pState^.dwInteger, pState^.fFloat,
pState^.szString]));
end;
SIMCONNECT_RECV_ID_QUIT:
begin
Quit := True;
StatusBar.Panels[0].Text := 'FS X Quit';
end
else
Memo.Lines.Add(Format('Unknown dwID: %d', [pData.dwID]));
end;
end;
{-----------------------------------------------------------------------------
Procedure: FormCloseQuery
Ensure that we can signal "Quit" to the busy wait loop
Author: ken.adam
Date: 11-Jan-2007
Arguments: Sender: TObject var CanClose: Boolean
Result: None
-----------------------------------------------------------------------------}
procedure TDialogBoxModeForm.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
Quit := True;
CanClose := True;
end;
{-----------------------------------------------------------------------------
Procedure: FormCreate
We are using run-time dynamic loading of SimConnect.dll, so that the program
will execute and fail gracefully if the DLL does not exist.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
Result: None
-----------------------------------------------------------------------------}
procedure TDialogBoxModeForm.FormCreate(Sender: TObject);
begin
if InitSimConnect then
StatusBar.Panels[2].Text := 'SimConnect.dll Loaded'
else
begin
StatusBar.Panels[2].Text := 'SimConnect.dll NOT FOUND';
StartPoll.Enabled := False;
StartEvent.Enabled := False;
end;
Quit := False;
hSimConnect := 0;
StatusBar.Panels[0].Text := 'Not Connected';
RxCount := 0;
StatusBar.Panels[1].Text := Format(StrRx6d, [RxCount]);
end;
{-----------------------------------------------------------------------------
Procedure: SimConnectMessage
This uses CallDispatch, but could probably avoid the callback and use
SimConnect_GetNextDispatch instead.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
var Message: TMessage
-----------------------------------------------------------------------------}
procedure TDialogBoxModeForm.SimConnectMessage(var Message: TMessage);
begin
SimConnect_CallDispatch(hSimConnect, MyDispatchProc, nil);
end;
{-----------------------------------------------------------------------------
Procedure: StartEventExecute
Opens the connection for Event driven handling. If successful sets up the data
requests and hooks the system event "SimStart".
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
-----------------------------------------------------------------------------}
procedure TDialogBoxModeForm.StartEventExecute(Sender: TObject);
var
hr: HRESULT;
begin
if (SUCCEEDED(SimConnect_Open(hSimConnect, 'Set Data', Handle,
WM_USER_SIMCONNECT, 0, 0))) then
begin
StatusBar.Panels[0].Text := 'Connected';
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(Event0));
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GROUP0),
Ord(Event0));
hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(INPUT0), 'U+Q',
Ord(Event0));
hr := SimConnect_SetInputGroupState(hSimConnect, Ord(INPUT0),
Ord(SIMCONNECT_STATE_ON));
StartEvent.Enabled := False;
StartPoll.Enabled := False;
end;
end;
{-----------------------------------------------------------------------------
Procedure: StartPollExecute
Opens the connection for Polled access. If successful sets up the data
requests and hooks the system event "SimStart", and then loops indefinitely
on CallDispatch.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
-----------------------------------------------------------------------------}
procedure TDialogBoxModeForm.StartPollExecute(Sender: TObject);
var
hr: HRESULT;
begin
if (SUCCEEDED(SimConnect_Open(hSimConnect, 'Set Data', 0, 0, 0, 0))) then
begin
StatusBar.Panels[0].Text := 'Connected';
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(Event0));
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GROUP0),
Ord(Event0));
hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(INPUT0), 'U+Q',
Ord(Event0));
hr := SimConnect_SetInputGroupState(hSimConnect, Ord(INPUT0),
Ord(SIMCONNECT_STATE_ON));
StartEvent.Enabled := False;
StartPoll.Enabled := False;
while not Quit do
begin
SimConnect_CallDispatch(hSimConnect, MyDispatchProc, nil);
Application.ProcessMessages;
Sleep(1);
end;
hr := SimConnect_Close(hSimConnect);
end;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit System.Character;
interface
uses System.RTLConsts, System.SysUtils;
{$SCOPEDENUMS ON}
type
TUnicodeCategory = (
ucControl,
ucFormat,
ucUnassigned,
ucPrivateUse,
ucSurrogate,
ucLowercaseLetter,
ucModifierLetter,
ucOtherLetter,
ucTitlecaseLetter,
ucUppercaseLetter,
ucCombiningMark,
ucEnclosingMark,
ucNonSpacingMark,
ucDecimalNumber,
ucLetterNumber,
ucOtherNumber,
ucConnectPunctuation,
ucDashPunctuation,
ucClosePunctuation,
ucFinalPunctuation,
ucInitialPunctuation,
ucOtherPunctuation,
ucOpenPunctuation,
ucCurrencySymbol,
ucModifierSymbol,
ucMathSymbol,
ucOtherSymbol,
ucLineSeparator,
ucParagraphSeparator,
ucSpaceSeparator
);
TUnicodeBreak = (
ubMandatory,
ubCarriageReturn,
ubLineFeed,
ubCombiningMark,
ubSurrogate,
ubZeroWidthSpace,
ubInseparable,
ubNonBreakingGlue,
ubContingent,
ubSpace,
ubAfter,
ubBefore,
ubBeforeAndAfter,
ubHyphen,
ubNonStarter,
ubOpenPunctuation,
ubClosePunctuation,
ubQuotation,
ubExclamation,
ubIdeographic,
ubNumeric,
ubInfixSeparator,
ubSymbol,
ubAlphabetic,
ubPrefix,
ubPostfix,
ubComplexContext,
ubAmbiguous,
ubUnknown,
ubNextLine,
ubWordJoiner,
ubHangulLJamo,
ubHangulVJamo,
ubHangulTJamo,
ubHangulLvSyllable,
ubHangulLvtSyllable
);
type
TCharacter = class sealed
private
class procedure Initialize; static;
class function IsLatin1(C: Char): Boolean; inline; static;
class function IsAscii(C: Char): Boolean; inline; static;
class function CheckLetter(uc: TUnicodeCategory): Boolean; inline; static;
class function CheckLetterOrDigit(uc: TUnicodeCategory): Boolean; inline; static;
class function CheckNumber(uc: TUnicodeCategory): Boolean; inline; static;
class function CheckPunctuation(uc: TUnicodeCategory): Boolean; inline; static;
class function CheckSymbol(uc: TUnicodeCategory): Boolean; inline; static;
class function CheckSeparator(uc: TUnicodeCategory): Boolean; inline; static;
public
constructor Create;
class function ConvertFromUtf32(C: UCS4Char): string; static;
class function ConvertToUtf32(const S: string; Index: Integer): UCS4Char; overload; inline; static;
class function ConvertToUtf32(const S: string; Index: Integer; out CharLength: Integer): UCS4Char; overload; static;
class function ConvertToUtf32(const HighSurrogate, LowSurrogate: Char): UCS4Char; overload; static;
class function GetNumericValue(C: Char): Double; overload; static;
class function GetNumericValue(const S: string; Index: Integer): Double; overload; static;
class function GetUnicodeCategory(C: Char): TUnicodeCategory; overload; static;
class function GetUnicodeCategory(const S: string; Index: Integer): TUnicodeCategory; overload; static;
class function IsControl(C: Char): Boolean; overload; static;
class function IsControl(const S: string; Index: Integer): Boolean; overload; static;
class function IsDigit(C: Char): Boolean; overload; static;
class function IsDigit(const S: string; Index: Integer): Boolean; overload; static;
class function IsHighSurrogate(C: Char): Boolean; overload; inline; static;
class function IsHighSurrogate(const S: string; Index: Integer): Boolean; overload; inline; static;
class function IsLetter(C: Char): Boolean; overload; static;
class function IsLetter(const S: string; Index: Integer): Boolean; overload; static;
class function IsLetterOrDigit(C: Char): Boolean; overload; static;
class function IsLetterOrDigit(const S: string; Index: Integer): Boolean; overload; static;
class function IsLower(C: Char): Boolean; overload; static;
class function IsLower(const S: string; Index: Integer): Boolean; overload; static;
class function IsLowSurrogate(C: Char): Boolean; overload; inline; static;
class function IsLowSurrogate(const S: string; Index: Integer): Boolean; overload; inline; static;
class function IsNumber(C: Char): Boolean; overload; static;
class function IsNumber(const S: string; Index: Integer): Boolean; overload; static;
class function IsPunctuation(C: Char): Boolean; overload; static;
class function IsPunctuation(const S: string; Index: Integer): Boolean; overload; static;
class function IsSeparator(C: Char): Boolean; overload; static;
class function IsSeparator(const S: string; Index: Integer): Boolean; overload; static;
class function IsSurrogate(Surrogate: Char): Boolean; overload; inline; static;
class function IsSurrogate(const S: string; Index: Integer): Boolean; overload; static;
class function IsSurrogatePair(const HighSurrogate, LowSurrogate: Char): Boolean; overload; inline; static;
class function IsSurrogatePair(const S: string; Index: Integer): Boolean; overload; static;
class function IsSymbol(C: Char): Boolean; overload; static;
class function IsSymbol(const S: string; Index: Integer): Boolean; overload; static;
class function IsUpper(C: Char): Boolean; overload; static;
class function IsUpper(const S: string; Index: Integer): Boolean; overload; static;
class function IsWhiteSpace(C: Char): Boolean; overload; static;
class function IsWhiteSpace(const S: string; Index: Integer): Boolean; overload; static;
class function ToLower(C: Char): Char; overload; static;
class function ToLower(const S: string): string; overload; static;
class function ToUpper(C: Char): Char; overload; static;
class function ToUpper(const S: string): string; overload; static;
end;
function ConvertFromUtf32(C: UCS4Char): string; inline;
function ConvertToUtf32(const S: string; Index: Integer): UCS4Char; overload; inline;
function ConvertToUtf32(const S: string; Index: Integer; out CharLength: Integer): UCS4Char; overload; inline;
function ConvertToUtf32(const HighSurrogate, LowSurrogate: Char): UCS4Char; overload; inline;
function GetNumericValue(C: Char): Double; overload; inline;
function GetNumericValue(const S: string; Index: Integer): Double; overload; inline;
function GetUnicodeCategory(C: Char): TUnicodeCategory; overload; inline;
function GetUnicodeCategory(const S: string; Index: Integer): TUnicodeCategory; overload; inline;
function IsControl(C: Char): Boolean; overload; inline;
function IsControl(const S: string; Index: Integer): Boolean; overload; inline;
function IsDigit(C: Char): Boolean; overload; inline;
function IsDigit(const S: string; Index: Integer): Boolean; overload; inline;
function IsHighSurrogate(C: Char): Boolean; overload; inline;
function IsHighSurrogate(const S: string; Index: Integer): Boolean; overload; inline;
function IsLetter(C: Char): Boolean; overload; inline;
function IsLetter(const S: string; Index: Integer): Boolean; overload; inline;
function IsLetterOrDigit(C: Char): Boolean; overload; inline;
function IsLetterOrDigit(const S: string; Index: Integer): Boolean; overload; inline;
function IsLower(C: Char): Boolean; overload; inline;
function IsLower(const S: string; Index: Integer): Boolean; overload; inline;
function IsLowSurrogate(C: Char): Boolean; overload; inline;
function IsLowSurrogate(const S: string; Index: Integer): Boolean; overload; inline;
function IsNumber(C: Char): Boolean; overload; inline;
function IsNumber(const S: string; Index: Integer): Boolean; overload; inline;
function IsPunctuation(C: Char): Boolean; overload; inline;
function IsPunctuation(const S: string; Index: Integer): Boolean; overload; inline;
function IsSeparator(C: Char): Boolean; overload; inline;
function IsSeparator(const S: string; Index: Integer): Boolean; overload; inline;
function IsSurrogate(Surrogate: Char): Boolean; overload; inline;
function IsSurrogate(const S: string; Index: Integer): Boolean; overload; inline;
function IsSurrogatePair(const HighSurrogate, LowSurrogate: Char): Boolean; overload; inline;
function IsSurrogatePair(const S: string; Index: Integer): Boolean; overload; inline;
function IsSymbol(C: Char): Boolean; overload; inline;
function IsSymbol(const S: string; Index: Integer): Boolean; overload; inline;
function IsUpper(C: Char): Boolean; overload; inline;
function IsUpper(const S: string; Index: Integer): Boolean; overload; inline;
function IsWhiteSpace(C: Char): Boolean; overload; inline;
function IsWhiteSpace(const S: string; Index: Integer): Boolean; overload; inline;
function ToLower(C: Char): Char; overload; inline;
function ToLower(const S: string): string; overload; inline;
function ToUpper(C: Char): Char; overload; inline;
function ToUpper(const S: string): string; overload; inline;
implementation
{$IFDEF MSWINDOWS}
uses Winapi.Windows;
{$ENDIF MSWINDOWS}
{$IFDEF POSIX}
uses Posix.Wctype;
{$ENDIF POSIX}
type
TIndexArray = array[0..32767] of Word;
PIndexArray = ^TIndexArray;
TCategoryArray = array[0..65535] of TUnicodeCategory;
PCategoryArray = ^TCategoryArray;
TNumberArray = array[0..4095] of Double;
PNumberArray = ^TNumberArray;
PDataTableOffsets = ^TDataTableOffsets;
TDataTableOffsets = record
IndexTable1Offset: Integer;
IndexTable2Offset: Integer;
DataTableOffset: Integer;
NumberIndex1Offset: Integer;
NumberIndex2Offset: Integer;
NumberDataOffset: Integer;
end;
var
DataTable: Pointer;
CatIndexPrimary: PIndexArray;
CatIndexSecondary: PIndexArray;
CategoryTable: PCategoryArray;
NumIndexPrimary: PIndexArray;
NumIndexSecondary: PIndexArray;
NumericValueTable: PNumberArray;
{ TCharacter }
function InternalGetUnicodeCategory(C: UCS4Char): TUnicodeCategory; inline;
begin
if CategoryTable = nil then
TCharacter.Initialize;
Result := CategoryTable[CatIndexSecondary[CatIndexPrimary[C shr 8] + ((C shr 4) and $F)] + C and $F];
end;
function NumberValue(C: UCS4Char): Double; inline;
begin
if NumericValueTable = nil then
TCharacter.Initialize;
Result := NumericValueTable[NumIndexSecondary[NumIndexPrimary[C shr 8] + ((C shr 4) and $F)] + C and $F];
end;
const
Latin1Categories: array[0..255] of TUnicodeCategory =
( { page 0 }
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucSpaceSeparator, TUnicodeCategory.ucOtherPunctuation,
TUnicodeCategory.ucOtherPunctuation,
TUnicodeCategory.ucOtherPunctuation, TUnicodeCategory.ucCurrencySymbol,
TUnicodeCategory.ucOtherPunctuation,
TUnicodeCategory.ucOtherPunctuation,
TUnicodeCategory.ucOtherPunctuation,
TUnicodeCategory.ucOpenPunctuation,
TUnicodeCategory.ucClosePunctuation,
TUnicodeCategory.ucOtherPunctuation, TUnicodeCategory.ucMathSymbol,
TUnicodeCategory.ucOtherPunctuation,
TUnicodeCategory.ucDashPunctuation,
TUnicodeCategory.ucOtherPunctuation,
TUnicodeCategory.ucOtherPunctuation, TUnicodeCategory.ucDecimalNumber,
TUnicodeCategory.ucDecimalNumber, TUnicodeCategory.ucDecimalNumber,
TUnicodeCategory.ucDecimalNumber, TUnicodeCategory.ucDecimalNumber,
TUnicodeCategory.ucDecimalNumber, TUnicodeCategory.ucDecimalNumber,
TUnicodeCategory.ucDecimalNumber, TUnicodeCategory.ucDecimalNumber,
TUnicodeCategory.ucDecimalNumber, TUnicodeCategory.ucOtherPunctuation,
TUnicodeCategory.ucOtherPunctuation, TUnicodeCategory.ucMathSymbol,
TUnicodeCategory.ucMathSymbol, TUnicodeCategory.ucMathSymbol,
TUnicodeCategory.ucOtherPunctuation,
TUnicodeCategory.ucOtherPunctuation,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucOpenPunctuation,
TUnicodeCategory.ucOtherPunctuation,
TUnicodeCategory.ucClosePunctuation, TUnicodeCategory.ucModifierSymbol,
TUnicodeCategory.ucConnectPunctuation,
TUnicodeCategory.ucModifierSymbol, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucOpenPunctuation,
TUnicodeCategory.ucMathSymbol, TUnicodeCategory.ucClosePunctuation,
TUnicodeCategory.ucMathSymbol, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucControl, TUnicodeCategory.ucControl,
TUnicodeCategory.ucSpaceSeparator, TUnicodeCategory.ucOtherPunctuation,
TUnicodeCategory.ucCurrencySymbol, TUnicodeCategory.ucCurrencySymbol,
TUnicodeCategory.ucCurrencySymbol, TUnicodeCategory.ucCurrencySymbol,
TUnicodeCategory.ucOtherSymbol, TUnicodeCategory.ucOtherSymbol,
TUnicodeCategory.ucModifierSymbol, TUnicodeCategory.ucOtherSymbol,
TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucInitialPunctuation, TUnicodeCategory.ucMathSymbol,
TUnicodeCategory.ucDashPunctuation, TUnicodeCategory.ucOtherSymbol,
TUnicodeCategory.ucModifierSymbol, TUnicodeCategory.ucOtherSymbol,
TUnicodeCategory.ucMathSymbol, TUnicodeCategory.ucOtherNumber,
TUnicodeCategory.ucOtherNumber, TUnicodeCategory.ucModifierSymbol,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucOtherSymbol,
TUnicodeCategory.ucOtherPunctuation, TUnicodeCategory.ucModifierSymbol,
TUnicodeCategory.ucOtherNumber, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucFinalPunctuation, TUnicodeCategory.ucOtherNumber,
TUnicodeCategory.ucOtherNumber, TUnicodeCategory.ucOtherNumber,
TUnicodeCategory.ucOtherPunctuation,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucMathSymbol,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucUppercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucMathSymbol,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucLowercaseLetter, TUnicodeCategory.ucLowercaseLetter
);
function InternalGetLatin1Category(C: Char): TUnicodeCategory; inline;
begin
Result := Latin1Categories[Byte(C)];
end;
procedure CheckStringRange(const S: string; Index: Integer); inline;
begin
if (Index > Length(S)) or (Index < 1) then
raise EArgumentOutOfRangeException.CreateResFmt(@sArgumentOutOfRange_StringIndex, [Index, Length(S)]);
end;
class function TCharacter.CheckLetter(uc: TUnicodeCategory): Boolean;
begin
case uc of
TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucTitlecaseLetter,
TUnicodeCategory.ucModifierLetter,
TUnicodeCategory.ucOtherLetter: Result := True;
else
Result := False;
end;
end;
class function TCharacter.CheckLetterOrDigit(uc: TUnicodeCategory): Boolean;
begin
case uc of
TUnicodeCategory.ucUppercaseLetter,
TUnicodeCategory.ucLowercaseLetter,
TUnicodeCategory.ucTitlecaseLetter,
TUnicodeCategory.ucModifierLetter,
TUnicodeCategory.ucOtherLetter,
TUnicodeCategory.ucDecimalNumber: Result := True;
else
Result := False;
end;
end;
class function TCharacter.CheckNumber(uc: TUnicodeCategory): Boolean;
begin
case uc of
TUnicodeCategory.ucOtherNumber,
TUnicodeCategory.ucLetterNumber,
TUnicodeCategory.ucDecimalNumber: Result := True;
else
Result := False;
end;
end;
class function TCharacter.CheckPunctuation(uc: TUnicodeCategory): Boolean;
begin
case uc of
TUnicodeCategory.ucConnectPunctuation,
TUnicodeCategory.ucDashPunctuation,
TUnicodeCategory.ucClosePunctuation,
TUnicodeCategory.ucFinalPunctuation,
TUnicodeCategory.ucInitialPunctuation,
TUnicodeCategory.ucOtherPunctuation,
TUnicodeCategory.ucOpenPunctuation: Result := True;
else
Result := False;
end;
end;
class function TCharacter.CheckSeparator(uc: TUnicodeCategory): Boolean;
begin
case uc of
TUnicodeCategory.ucLineSeparator,
TUnicodeCategory.ucParagraphSeparator,
TUnicodeCategory.ucSpaceSeparator: Result := True;
else
Result := False;
end;
end;
class function TCharacter.CheckSymbol(uc: TUnicodeCategory): Boolean;
begin
case uc of
TUnicodeCategory.ucCurrencySymbol,
TUnicodeCategory.ucModifierSymbol,
TUnicodeCategory.ucMathSymbol,
TUnicodeCategory.ucOtherSymbol: Result := True;
else
Result := False;
end;
end;
class function TCharacter.IsLatin1(C: Char): Boolean;
begin
Result := Integer(C) <= $FF;
end;
class function TCharacter.IsLetter(C: Char): Boolean;
begin
if not IsLatin1(C) then
Result := CheckLetter(InternalGetUnicodeCategory(UCS4Char(C)))
else if not IsAscii(C) then
Result := CheckLetter(InternalGetLatin1Category(C))
else
begin
C := Char(Integer(C) or Ord(' '));
Result := (C >= 'a') and (C <= 'z');
end;
end;
class function TCharacter.IsLetter(const S: string; Index: Integer): Boolean;
begin
CheckStringRange(S, Index);
Result := IsLetter(S[Index]);
end;
class function TCharacter.IsLetterOrDigit(const S: string; Index: Integer): Boolean;
var
C: Char;
begin
CheckStringRange(S, Index);
C := S[Index];
if IsLatin1(C) then
Result := CheckLetterOrDigit(InternalGetLatin1Category(C))
else
Result := CheckLetterOrDigit(GetUnicodeCategory(S, Index));
end;
class function TCharacter.IsLetterOrDigit(C: Char): Boolean;
begin
if IsLatin1(C) then
Result := CheckLetterOrDigit(InternalGetLatin1Category(C))
else
Result := CheckLetterOrDigit(InternalGetUnicodeCategory(UCS4Char(C)));
end;
class function TCharacter.IsAscii(C: Char): Boolean;
begin
Result := Integer(C) <= $7F;
end;
class function TCharacter.IsControl(const S: string; Index: Integer): Boolean;
var
C: Char;
begin
CheckStringRange(S, Index);
C := S[Index];
if IsLatin1(C) then
Result := InternalGetLatin1Category(C) = TUnicodeCategory.ucControl
else
Result := GetUnicodeCategory(S, Index) = TUnicodeCategory.ucControl;
end;
class function TCharacter.IsControl(C: Char): Boolean;
begin
if IsLatin1(C) then
Result := InternalGetLatin1Category(C) = TUnicodeCategory.ucControl
else
Result := InternalGetUnicodeCategory(UCS4Char(C)) = TUnicodeCategory.ucControl;
end;
class function TCharacter.IsDigit(C: Char): Boolean;
begin
if not IsLatin1(C) then
Result := InternalGetUnicodeCategory(UCS4Char(C)) = TUnicodeCategory.ucDecimalNumber
else
Result := (C >= '0') and (C <= '9');
end;
class function TCharacter.IsDigit(const S: string; Index: Integer): Boolean;
var
C: Char;
begin
CheckStringRange(S, Index);
C := S[Index];
if not IsLatin1(C) then
Result := GetUnicodeCategory(S, Index) = TUnicodeCategory.ucDecimalNumber
else
Result := (C >= '0') and (C <= '9');
end;
class function TCharacter.IsHighSurrogate(C: Char): Boolean;
begin
Result := (Integer(C) >= $D800) and (Integer(C) <= $DBFF);
end;
class function TCharacter.IsLowSurrogate(C: Char): Boolean;
begin
Result := (Integer(C) >= $DC00) and (Integer(C) <= $DFFF);
end;
class function TCharacter.IsSurrogate(Surrogate: Char): Boolean;
begin
Result := (Integer(Surrogate) >= $D800) and (Integer(Surrogate) <= $DFFF);
end;
class function TCharacter.IsSurrogatePair(const HighSurrogate, LowSurrogate: Char): Boolean;
begin
Result := (Integer(HighSurrogate) >= $D800) and (Integer(HighSurrogate) <= $DBFF) and
(Integer(LowSurrogate) >= $DC00) and (Integer(LowSurrogate) <= $DFFF);
end;
class function TCharacter.GetUnicodeCategory(C: Char): TUnicodeCategory;
begin
if IsLatin1(C) then
Result := InternalGetLatin1Category(C)
else
Result := InternalGetUnicodeCategory(UCS4Char(C));
end;
class function TCharacter.ConvertToUtf32(const S: string; Index: Integer; out CharLength: Integer): UCS4Char;
var
LowSurrogate, HighSurrogate: Integer;
begin
CheckStringRange(S, Index);
CharLength := 1;
HighSurrogate := Integer(S[Index]) - $D800;
if (HighSurrogate < 0) or (HighSurrogate > $7FF) then
Result := UCS4Char(S[Index])
else
begin
if HighSurrogate > $3FF then
raise EArgumentException.CreateResFmt(@sArgument_InvalidLowSurrogate, [Index]);
if Index > Length(S) - 1 then
raise EArgumentException.CreateResFmt(@sArgument_InvalidHighSurrogate, [Index]);
LowSurrogate := Integer(S[Index + 1]) - $DC00;
if (LowSurrogate < 0) or (LowSurrogate > $3FF) then
raise EArgumentException.CreateResFmt(@sArgument_InvalidHighSurrogate, [Index]);
Inc(CharLength);
Result := (HighSurrogate * $400) + LowSurrogate + $10000;
end;
end;
class function TCharacter.ConvertToUtf32(const S: string; Index: Integer): UCS4Char;
var
CharLength: Integer;
begin
Result := ConvertToUtf32(S, Index, CharLength);
end;
class function TCharacter.ConvertFromUtf32(C: UCS4Char): string;
begin
if (C > $10FFFF) or ((C >= $D800) and (C <= $DFFF)) then
raise EArgumentOutOfRangeException.CreateRes(@sArgumentOutOfRange_InvalidUTF32);
if C < $10000 then
Result := Char(C)
else
begin
Dec(C, $10000);
Result := Char(C div $400 + $D800) + Char(C mod $400 + $DC00);
end;
end;
class function TCharacter.ConvertToUtf32(const HighSurrogate, LowSurrogate: Char): UCS4Char;
begin
if not IsHighSurrogate(HighSurrogate) then
raise EArgumentOutOfRangeException.CreateRes(@sArgumentOutOfRange_InvalidHighSurrogate);
if not IsLowSurrogate(LowSurrogate) then
raise EArgumentOutOfRangeException.CreateRes(@sArgumentOutOfRange_InvalidLowSurrogate);
Result := ((Integer(HighSurrogate) - $D800) * $400) + (Integer(LowSurrogate) - $DC00) + $10000;
end;
constructor TCharacter.Create;
begin
raise ENoConstructException.CreateResFmt(@sNoConstruct, [ClassName]);
end;
class procedure TCharacter.Initialize;
{$INCLUDE *.inc}
var
Offsets: PDataTableOffsets;
begin
{$IF DEFINED(CPUX86)}
{$IFOPT W+}
DataTable := PDataTableOffsets(PByte(@bin_data) + 3); // This skips the PUSH EBP, MOV EBP,ESP preamble
{$ELSE}
DataTable := @bin_data;
{$ENDIF}
{$ELSE not CPUX86}
{$IFOPT W+}
DataTable := PDataTableOffsets(PByte(@bin_data) + 4); // push rbp, mov rbp, rsp
{$ELSE}
DataTable := @bin_data;
{$ENDIF}
{$IFEND not CPUX86}
Offsets := DataTable;
CatIndexPrimary := Pointer(PByte(DataTable) + Offsets.IndexTable1Offset);
CatIndexSecondary := Pointer(PByte(DataTable) + Offsets.IndexTable2Offset);
CategoryTable := Pointer(PByte(DataTable) + Offsets.DataTableOffset);
NumIndexPrimary := Pointer(PByte(DataTable) + Offsets.NumberIndex1Offset);
NumIndexSecondary := Pointer(PByte(DataTable) + Offsets.NumberIndex2Offset);
NumericValueTable := Pointer(PByte(DataTable) + Offsets.NumberDataOffset);
end;
class function TCharacter.GetNumericValue(C: Char): Double;
begin
Result := NumberValue(UCS4Char(C));
end;
class function TCharacter.GetNumericValue(const S: string; Index: Integer): Double;
begin
Result := NumberValue(ConvertToUTF32(S, Index));
end;
class function TCharacter.GetUnicodeCategory(const S: string; Index: Integer): TUnicodeCategory;
begin
CheckStringRange(S, Index);
if IsLatin1(S[Index]) then
Result := InternalGetLatin1Category(S[Index])
else
Result := InternalGetUnicodeCategory(ConvertToUtf32(S, Index));
end;
class function TCharacter.IsHighSurrogate(const S: string; Index: Integer): Boolean;
begin
CheckStringRange(S, Index);
Result := IsHighSurrogate(S[Index]);
end;
class function TCharacter.IsLower(C: Char): Boolean;
begin
if not IsLatin1(C) then
Result := InternalGetUnicodeCategory(UCS4Char(C)) = TUnicodeCategory.ucLowercaseLetter
else if not IsAscii(C) then
Result := InternalGetLatin1Category(C) = TUnicodeCategory.ucLowercaseLetter
else
Result := (C >= 'a') and (C <= 'z');
end;
class function TCharacter.IsLower(const S: string; Index: Integer): Boolean;
var
C: Char;
begin
CheckStringRange(S, Index);
C := S[Index];
if not IsLatin1(C) then
Result := GetUnicodeCategory(S, Index) = TUnicodeCategory.ucLowercaseLetter
else if not IsAscii(C) then
Result := InternalGetLatin1Category(C) = TUnicodeCategory.ucLowercaseLetter
else
Result := (C >= 'a') and (C <= 'z');
end;
class function TCharacter.IsLowSurrogate(const S: string; Index: Integer): Boolean;
begin
CheckStringRange(S, Index);
Result := IsLowSurrogate(S[Index]);
end;
class function TCharacter.IsNumber(C: Char): Boolean;
begin
if not IsLatin1(C) then
Result := CheckNumber(InternalGetUnicodeCategory(UCS4Char(C)))
else if not IsAscii(C) then
Result := CheckNumber(InternalGetLatin1Category(C))
else
Result := (C >= '0') and (C <= '9');
end;
class function TCharacter.IsNumber(const S: string; Index: Integer): Boolean;
var
C: Char;
begin
CheckStringRange(S, Index);
C := S[Index];
if not IsLatin1(C) then
Result := CheckNumber(GetUnicodeCategory(S, Index))
else if not IsAscii(C) then
Result := CheckNumber(InternalGetLatin1Category(C))
else
Result := (C >= '0') and (C <= '9');
end;
class function TCharacter.IsPunctuation(const S: string; Index: Integer): Boolean;
var
C: Char;
begin
CheckStringRange(S, Index);
C := S[Index];
if IsLatin1(C) then
Result := CheckPunctuation(InternalGetLatin1Category(C))
else
Result := CheckPunctuation(GetUnicodeCategory(S, Index));
end;
class function TCharacter.IsPunctuation(C: Char): Boolean;
begin
if IsLatin1(C) then
Result := CheckPunctuation(InternalGetLatin1Category(C))
else
Result := CheckPunctuation(InternalGetUnicodeCategory(UCS4Char(C)));
end;
class function TCharacter.IsSeparator(C: Char): Boolean;
begin
if not IsLatin1(C) then
Result := CheckSeparator(InternalGetUnicodeCategory(UCS4Char(C)))
else
Result := (C = ' ') or (C = Char($A0));
end;
class function TCharacter.IsSeparator(const S: string; Index: Integer): Boolean;
var
C: Char;
begin
CheckStringRange(S, Index);
C := S[Index];
if not IsLatin1(C) then
Result := CheckSeparator(GetUnicodeCategory(S, Index))
else
Result := (C = ' ') or (C = Char($A0));
end;
class function TCharacter.IsSurrogate(const S: string; Index: Integer): Boolean;
begin
CheckStringRange(S, Index);
Result := IsSurrogate(S[Index]);
end;
class function TCharacter.IsSurrogatePair(const S: string; Index: Integer): Boolean;
begin
CheckStringRange(S, Index);
Result := (Index < Length(S)) and IsSurrogatePair(S[Index], S[Index + 1]);
end;
class function TCharacter.IsSymbol(C: Char): Boolean;
begin
if IsLatin1(C) then
Result := CheckSymbol(InternalGetLatin1Category(C))
else
Result := CheckSymbol(InternalGetUnicodeCategory(UCS4Char(C)));
end;
class function TCharacter.IsSymbol(const S: string; Index: Integer): Boolean;
var
C: Char;
begin
CheckStringRange(S, Index);
C := S[Index];
if IsLatin1(C) then
Result := CheckSymbol(InternalGetLatin1Category(C))
else
Result := CheckSymbol(GetUnicodeCategory(S, Index));
end;
class function TCharacter.IsUpper(const S: string; Index: Integer): Boolean;
var
C: Char;
begin
CheckStringRange(S, Index);
C := S[Index];
if not IsLatin1(C) then
Result := GetUnicodeCategory(S, Index) = TUnicodeCategory.ucUppercaseLetter
else if not IsAscii(C) then
Result := InternalGetLatin1Category(C) = TUnicodeCategory.ucUppercaseLetter
else
Result := (C >= 'A') and (C <= 'Z');
end;
class function TCharacter.IsUpper(C: Char): Boolean;
begin
if not IsLatin1(C) then
Result := InternalGetUnicodeCategory(UCS4Char(C)) = TUnicodeCategory.ucUppercaseLetter
else if not IsAscii(C) then
Result := InternalGetLatin1Category(C) = TUnicodeCategory.ucUppercaseLetter
else
Result := (C >= 'A') and (C <= 'Z');
end;
class function TCharacter.IsWhiteSpace(const S: string; Index: Integer): Boolean;
var
C: Char;
begin
CheckStringRange(S, Index);
C := S[Index];
if IsLatin1(C) then
Result := (C = ' ') or ((C >= #$0009) and (C <= #$000D)) or (C = #$00A0) or (C = #$0085)
else
Result := CheckSeparator(GetUnicodeCategory(S, Index));
end;
class function TCharacter.ToLower(C: Char): Char;
begin
{$IFDEF POSIX}
Result := Char(towlower_l(UCS4Char(C), UTF8CompareLocale));
{$ENDIF}
{$IFDEF MSWINDOWS}
Result := Char(NativeInt(CharLower(PChar(C))));
{$ENDIF}
end;
class function TCharacter.ToLower(const S: string): string;
{$IFDEF POSIX}
var
I, J, ICharLen, JCharLen, K: Integer;
LowerChar: UCS4Char;
Ucs2String: string;
{$ENDIF}
{$IFDEF MSWINDOWS}
var
MapLocale: LCID;
{$ENDIF}
begin
Result := S;
if Result <> '' then
begin
UniqueString(Result);
{$IFDEF POSIX}
I := 1;
J := 1;
while I <= Length(Result) do
begin
ICharLen := 1;
JCharLen := 1;
if (S[I] >= 'A') and (S[I] <= 'Z') then
Result[J] := Char(Ord(S[I]) + $20)
else if IsAscii(S[I]) then
Result[J] := S[I]
else
begin
if IsSurrogate(S[I]) then
LowerChar := ConvertToUtf32(S, I, ICharLen)
else
LowerChar := UCS4Char(S[I]);
LowerChar := towlower_l(LowerChar, UTF8CompareLocale);
if LowerChar < $10000 then
Result[J] := Char(LowerChar)
else
begin
Ucs2String := ConvertFromUtf32(LowerChar);
JCharLen := Length(Ucs2String);
if JCharLen > 1 then
begin
SetLength(Result, Length(Result) + JCharLen - 1);
for K := 1 to Length(Ucs2String) do
Result[J + K - 1] := Ucs2String[K];
end else
Result[J] := Ucs2String[1];
end;
end;
Inc(I, ICharLen);
Inc(J, JCharLen);
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
if TOSVersion.Check(5, 1) then
MapLocale := LOCALE_INVARIANT
else
MapLocale := LOCALE_SYSTEM_DEFAULT;
if LCMapString(MapLocale, LCMAP_LOWERCASE, PChar(S), Length(S), PChar(Result), Length(Result)) = 0 then
RaiseLastOSError;
{$ENDIF}
end;
end;
class function TCharacter.ToUpper(C: Char): Char;
begin
{$IFDEF POSIX}
Result := Char(towupper_l(UCS4Char(C), UTF8CompareLocale));
{$ENDIF}
{$IFDEF MSWINDOWS}
Result := Char(NativeInt(CharUpper(PChar(C))));
{$ENDIF}
end;
class function TCharacter.ToUpper(const S: string): string;
{$IFDEF POSIX}
var
I, J, ICharLen, JCharLen, K: Integer;
UpperChar: UCS4Char;
Ucs2String: string;
{$ENDIF}
{$IFDEF MSWINDOWS}
var
MapLocale: LCID;
{$ENDIF}
begin
Result := S;
if Result <> '' then
begin
UniqueString(Result);
{$IFDEF POSIX}
I := 1;
J := 1;
while I <= Length(Result) do
begin
ICharLen := 1;
JCharLen := 1;
if (S[I] >= 'a') and (S[I] <= 'z') then
Result[J] := Char(Ord(S[I]) - $20)
else if IsAscii(S[I]) then
Result[J] := S[I]
else
begin
if IsSurrogate(S[I]) then
UpperChar := ConvertToUtf32(S, I, ICharLen)
else
UpperChar := UCS4Char(S[I]);
UpperChar := towupper_l(UpperChar, UTF8CompareLocale);
if UpperChar < $10000 then
Result[J] := Char(UpperChar)
else
begin
Ucs2String := ConvertFromUtf32(UpperChar);
JCharLen := Length(Ucs2String);
if JCharLen > 1 then
begin
SetLength(Result, Length(Result) + JCharLen - 1);
for K := 1 to Length(Ucs2String) do
Result[J + K - 1] := Ucs2String[K];
end else
Result[J] := Ucs2String[1];
end;
end;
Inc(I, ICharLen);
Inc(J, JCharLen);
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
if TOSVersion.Check(5, 1) then
MapLocale := LOCALE_INVARIANT
else
MapLocale := LOCALE_SYSTEM_DEFAULT;
if LCMapString(MapLocale, LCMAP_UPPERCASE, PChar(S), Length(S), PChar(Result), Length(Result)) = 0 then
RaiseLastOSError;
{$ENDIF}
end;
end;
class function TCharacter.IsWhiteSpace(C: Char): Boolean;
begin
if IsLatin1(C) then
Result := (C = ' ') or ((C >= #$0009) and (C <= #$000D)) or (C = #$00A0) or (C = #$0085)
else
Result := CheckSeparator(InternalGetUnicodeCategory(UCS4Char(C)));
end;
function ConvertFromUtf32(C: UCS4Char): string;
begin
Result := TCharacter.ConvertFromUtf32(C);
end;
function ConvertToUtf32(const S: string; Index: Integer): UCS4Char;
begin
Result := TCharacter.ConvertToUtf32(S, Index);
end;
function ConvertToUtf32(const S: string; Index: Integer; out CharLength: Integer): UCS4Char;
begin
Result := TCharacter.ConvertToUtf32(S, Index, CharLength);
end;
function ConvertToUtf32(const HighSurrogate, LowSurrogate: Char): UCS4Char;
begin
Result := TCharacter.ConvertToUtf32(HighSurrogate, LowSurrogate);
end;
function GetNumericValue(C: Char): Double;
begin
Result := TCharacter.GetNumericValue(C);
end;
function GetNumericValue(const S: string; Index: Integer): Double;
begin
Result := TCharacter.GetNumericValue(S, Index);
end;
function GetUnicodeCategory(C: Char): TUnicodeCategory;
begin
Result := TCharacter.GetUnicodeCategory(C);
end;
function GetUnicodeCategory(const S: string; Index: Integer): TUnicodeCategory;
begin
Result := TCharacter.GetUnicodeCategory(S, Index);
end;
function IsControl(C: Char): Boolean;
begin
Result := TCharacter.IsControl(C);
end;
function IsControl(const S: string; Index: Integer): Boolean;
begin
Result := TCharacter.IsControl(S, Index);
end;
function IsDigit(C: Char): Boolean;
begin
Result := TCharacter.IsDigit(C);
end;
function IsDigit(const S: string; Index: Integer): Boolean;
begin
Result := TCharacter.IsDigit(S, Index);
end;
function IsHighSurrogate(C: Char): Boolean;
begin
Result := TCharacter.IsHighSurrogate(C);
end;
function IsHighSurrogate(const S: string; Index: Integer): Boolean;
begin
Result := TCharacter.IsHighSurrogate(S, Index);
end;
function IsLetter(C: Char): Boolean;
begin
Result := TCharacter.IsLetter(C);
end;
function IsLetter(const S: string; Index: Integer): Boolean;
begin
Result := TCharacter.IsLetter(S, Index);
end;
function IsLetterOrDigit(C: Char): Boolean;
begin
Result := TCharacter.IsLetterOrDigit(C);
end;
function IsLetterOrDigit(const S: string; Index: Integer): Boolean;
begin
Result := TCharacter.IsLetterOrDigit(S, Index);
end;
function IsLower(C: Char): Boolean;
begin
Result := TCharacter.IsLower(C);
end;
function IsLower(const S: string; Index: Integer): Boolean;
begin
Result := TCharacter.IsLower(S, Index);
end;
function IsLowSurrogate(C: Char): Boolean;
begin
Result := TCharacter.IsLowSurrogate(C);
end;
function IsLowSurrogate(const S: string; Index: Integer): Boolean;
begin
Result := TCharacter.IsLowSurrogate(S, Index);
end;
function IsNumber(C: Char): Boolean;
begin
Result := TCharacter.IsNumber(C);
end;
function IsNumber(const S: string; Index: Integer): Boolean;
begin
Result := TCharacter.IsNumber(S, Index);
end;
function IsPunctuation(C: Char): Boolean;
begin
Result := TCharacter.IsPunctuation(C);
end;
function IsPunctuation(const S: string; Index: Integer): Boolean;
begin
Result := TCharacter.IsPunctuation(S, Index);
end;
function IsSeparator(C: Char): Boolean;
begin
Result := TCharacter.IsSeparator(C);
end;
function IsSeparator(const S: string; Index: Integer): Boolean;
begin
Result := TCharacter.IsSeparator(S, Index);
end;
function IsSurrogate(Surrogate: Char): Boolean;
begin
Result := TCharacter.IsSurrogate(Surrogate);
end;
function IsSurrogate(const S: string; Index: Integer): Boolean;
begin
Result := TCharacter.IsSurrogate(S, Index);
end;
function IsSurrogatePair(const HighSurrogate, LowSurrogate: Char): Boolean;
begin
Result := TCharacter.IsSurrogatePair(HighSurrogate, LowSurrogate);
end;
function IsSurrogatePair(const S: string; Index: Integer): Boolean;
begin
Result := TCharacter.IsSurrogatePair(S, Index);
end;
function IsSymbol(C: Char): Boolean;
begin
Result := TCharacter.IsSymbol(C);
end;
function IsSymbol(const S: string; Index: Integer): Boolean;
begin
Result := TCharacter.IsSymbol(S, Index);
end;
function IsUpper(C: Char): Boolean;
begin
Result := TCharacter.IsUpper(C);
end;
function IsUpper(const S: string; Index: Integer): Boolean;
begin
Result := TCharacter.IsUpper(S, Index);
end;
function IsWhiteSpace(C: Char): Boolean;
begin
Result := TCharacter.IsWhiteSpace(C);
end;
function IsWhiteSpace(const S: string; Index: Integer): Boolean;
begin
Result := TCharacter.IsWhiteSpace(S, Index);
end;
function ToLower(C: Char): Char;
begin
Result := TCharacter.ToLower(C);
end;
function ToLower(const S: string): string;
begin
Result := TCharacter.ToLower(S);
end;
function ToUpper(C: Char): Char;
begin
Result := TCharacter.ToUpper(C);
end;
function ToUpper(const S: string): string;
begin
Result := TCharacter.ToUpper(S);
end;
end.
|
unit uMeetingsClass;
interface
uses
{The various uses which the unit may require are loaded.}
SysUtils, Classes;
{Class is created as TMeetings.}
type TMeetings = class
{The Private attributes are added.}
private
mMeetingID : integer;
mDate : string;
mTime : string;
mLocation : string;
mAttendance : integer;
mTheme : string;
mChairman : string;
mOpeningGrace : string;
mToastmaster : string;
mClosingGrace : string;
mGrammarian : string;
mTopicsMaster : string;
mSgtAtArms : string;
mOpeningComments : string;
mClosingComments : string;
mProgramme : integer;
{The public methods are added.}
public
{The constructor is described.}
constructor Create(id : integer; date, time, location : string;
attendance : integer; theme, chairman, openingGrace, toastmaster,
closingGrace, grammarian, topics, sgtAtArms, openingComments,
closingComments : string; programme : integer);
{The functions which return values.}
function getID : integer;
function getDate : string;
function getTime : string;
function getLocation : string;
function getAttendance : integer;
function getTheme : string;
function getChairman : string;
function getOpeningGrace : string;
function getToastmaster : string;
function getClosingGrace : string;
function getGrammarian : string;
function getTopicsMaster : string;
function getSgtAtArms : string;
function getOpeningComments : string;
function getClosingComments : string;
function getProgramme : integer;
{AddSpaces function allows for equal spacing between strings.}
function addSpaces(s : String; i : integer) : string;
{ToString function converts all the data to a single string
and returns it.}
function toString : string;
{The procedures which allow values in the class to be set
to a specific value.}
procedure setID(id : integer);
procedure setDate(date : string);
procedure setTime(time : string);
procedure setLocation(location : string);
procedure setAttendance(attendance : integer);
procedure setTheme(theme : string);
procedure setChairman(chairman : string);
procedure setOpeningGrace(openingGrace : string);
procedure setToastmaster(toastmaster : string);
procedure setClosingGrace(closingGrace : string);
procedure setGrammarian(grammarian : string);
procedure setTopicsMaster(topicsMaster : string);
procedure setSgtAtArms(sgtAtArms : string);
procedure setOpeningComments(openingComments : string);
procedure setClosingComments(closingComments : string);
procedure setProgramme(programme : integer);
end;
implementation
{ TMeetings }
{Allows strings to fill a preset number of spaces (i) and appends the
string with spaces if it is less than that lenght (i).}
function TMeetings.addSpaces(s: String; i: integer): string;
var
counter : integer;
begin
Result := s;
for counter := 1 to i - length(s) do
begin
Result := Result + ' ';
end;
end;
constructor TMeetings.Create(id: integer; date, time, location: string;
attendance: integer; theme, chairman, openingGrace, toastmaster,
closingGrace, grammarian, topics, sgtAtArms, openingComments,
closingComments: string; programme: integer);
begin
mMeetingID := id;
mDate := date;
mTime := time;
mLocation := location;
mAttendance := attendance;
mTheme := theme;
mChairman := chairman;
mOpeningGrace := openingGrace;
mToastmaster := toastmaster;
mClosingGrace := closingGrace;
mGrammarian := grammarian;
mTopicsMaster := topics;
mSgtAtArms := sgtAtArms;
mOpeningComments := openingComments;
mClosingComments := closingComments;
mProgramme := programme;
end;
{The following functions return the values found in the attributes of
the class.}
function TMeetings.getAttendance: integer;
begin
Result := mAttendance;
end;
function TMeetings.getChairman: string;
begin
Result := mChairman;
end;
function TMeetings.getClosingComments: string;
begin
Result := mClosingComments;
end;
function TMeetings.getClosingGrace: string;
begin
Result := mClosingGrace;
end;
function TMeetings.getDate: string;
begin
Result := mDate;
end;
function TMeetings.getGrammarian: string;
begin
Result := mGrammarian;
end;
function TMeetings.getID: integer;
begin
Result := mMeetingID;
end;
function TMeetings.getLocation: string;
begin
Result := mLocation;
end;
function TMeetings.getOpeningComments: string;
begin
Result := mOpeningComments;
end;
function TMeetings.getOpeningGrace: string;
begin
Result := mOpeningGrace;
end;
function TMeetings.getProgramme: integer;
begin
Result := mProgramme;
end;
function TMeetings.getSgtAtArms: string;
begin
Result := mSgtAtArms;
end;
function TMeetings.getTheme: string;
begin
Result := mTheme;
end;
function TMeetings.getTime: string;
begin
Result := mTime;
end;
function TMeetings.getToastmaster: string;
begin
Result := mToastmaster;
end;
function TMeetings.getTopicsMaster: string;
begin
Result := mTopicsMaster;
end;
{The following procedures set the attributes of the class to the values
that are entered into the procedure.}
procedure TMeetings.setAttendance(attendance: integer);
begin
mAttendance := attendance;
end;
procedure TMeetings.setChairman(chairman: string);
begin
mChairman := chairman;
end;
procedure TMeetings.setClosingComments(closingComments: string);
begin
mClosingComments := closingComments;
end;
procedure TMeetings.setClosingGrace(closingGrace: string);
begin
mClosingGrace := closingGrace;
end;
procedure TMeetings.setDate(date: string);
begin
mDate := date;
end;
procedure TMeetings.setGrammarian(grammarian: string);
begin
mGrammarian := grammarian;
end;
procedure TMeetings.setID(id: integer);
begin
mMeetingID := id;
end;
procedure TMeetings.setLocation(location: string);
begin
mLocation := location;
end;
procedure TMeetings.setOpeningComments(openingComments: string);
begin
mOpeningComments := openingComments;
end;
procedure TMeetings.setOpeningGrace(openingGrace: string);
begin
mOpeningGrace := openingGrace;
end;
procedure TMeetings.setProgramme(programme: integer);
begin
mProgramme := programme;
end;
procedure TMeetings.setSgtAtArms(sgtAtArms: string);
begin
mSgtAtArms := sgtAtArms;
end;
procedure TMeetings.setTheme(theme: string);
begin
mTheme := theme;
end;
procedure TMeetings.setTime(time: string);
begin
mTime := time;
end;
procedure TMeetings.setToastmaster(toastmaster: string);
begin
mToastmaster := toastmaster;
end;
procedure TMeetings.setTopicsMaster(topicsMaster: string);
begin
mTopicsMaster := topicsMaster;
end;
{A function that compiles the crucial information in the class and returns
it as a single, formatted string for output purposes.}
function TMeetings.toString: string;
begin
Result := addSpaces(IntToStr(mMeetingID), 6) + addSpaces(mDate, 11) +
addSpaces(mTheme,10);
end;
end.
|
program Sample;
var
H : String;
function hello(): String;
var hstr : String;
begin
hstr := 'Hello';
hello := hstr;
end;
begin
WriteLn(hello(), ' World');
end.
|
////////////////////////////////////////////////////////////////////////////////
//
//
// FileName : frmMSNPop.pas
// Creator : Shen Min
// Date : 2003-11-25
// Comment :
//
// Copyright (c) 2002-2003 Sunisoft
// http://www.sunisoft.com
// Email: support@sunisoft.com
//
////////////////////////////////////////////////////////////////////////////////
unit frmMSNPop;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;
type
TfrmMSNPopForm = class(TForm)
Timer1: TTimer;
lbl_title: TLabel;
lbl_text: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormHide(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure FormClick(Sender: TObject);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
private
m_Buf : TBitmap;
m_Start : Cardinal;
m_QuickHide : Boolean;
protected
procedure Paint(); override;
procedure CreateParams(var Param: TCreateParams); override;
procedure WMPRINTCLIENT(var Msg : TMessage); message WM_PRINTCLIENT;
public
AnimateTime : Integer;
StayTime : Integer;
ClickHide : Boolean;
CloseCallback : TNotifyEvent;
end;
var
frmMSNPopForm: TfrmMSNPopForm;
implementation
uses SUIPublic;
{$R *.dfm}
procedure RefreshControl(Control: TControl); { Refresh Self and SubControls }
var
i: Integer;
begin
if Control is TWinControl then
for i := 0 to TWinControl(Control).ControlCount - 1 do
RefreshControl(TWinControl(Control).Controls[i]);
Control.Invalidate;
end;
{ TfrmMSNPopForm }
procedure TfrmMSNPopForm.Paint;
var
Buf : TBitmap;
begin
Buf := TBitmap.Create();
Buf.Width := ClientWidth;
Buf.Height := ClientHeight;
Buf.Canvas.Draw(0, 0, m_Buf);
BitBlt(Canvas.Handle, 0, 0, Width, Height, Buf.Canvas.Handle, 0, 0, SRCCOPY);
Buf.Free();
end;
procedure TfrmMSNPopForm.FormCreate(Sender: TObject);
begin
m_Buf := TBitmap.Create();
m_Buf.LoadFromResourceName(hInstance, 'MSNPOPFORM');
m_QuickHide := false;
Width := m_Buf.Width;
Height := m_Buf.Height;
Left := GetWorkAreaRect().Right - Width - 18;
Top := GetWorkAreaRect().Bottom - Height;
lbl_title.Left := 10;
lbl_title.Top := 5;
lbl_title.Width := ClientWidth - 30;
lbl_title.Height := 18;
lbl_text.Left := 10;
lbl_text.Top := 40;
lbl_text.Width := ClientWidth - 20;
lbl_text.Height := ClientHeight - 50;
end;
procedure TfrmMSNPopForm.FormDestroy(Sender: TObject);
begin
m_Buf.Free();
m_Buf := nil;
end;
procedure TfrmMSNPopForm.CreateParams(var Param: TCreateParams);
begin
inherited;
Param.WndParent := GetDesktopWindow;
Param.Style := WS_POPUP;
end;
procedure TfrmMSNPopForm.FormShow(Sender: TObject);
begin
SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE or SWP_NOMOVE or SWP_NOACTIVATE);
SUIAnimateWindow(Handle, AnimateTime, AW_SLIDE or AW_VER_NEGATIVE);
RefreshControl(Self);
m_Start := GetTickCount();
end;
procedure TfrmMSNPopForm.WMPRINTCLIENT(var Msg: TMessage);
begin
PaintTo(HDC(Msg.WParam), 0, 0);
end;
procedure TfrmMSNPopForm.FormHide(Sender: TObject);
begin
if not m_QuickHide then
begin
SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE or SWP_NOMOVE or SWP_NOACTIVATE);
SUIAnimateWindow(Handle, AnimateTime, AW_SLIDE or AW_VER_POSITIVE or AW_HIDE);
RefreshControl(Self);
end
else
m_QuickHide := false;
if Assigned(CloseCallback) then
CloseCallback(nil);
end;
procedure TfrmMSNPopForm.Timer1Timer(Sender: TObject);
var
PastTime : Integer;
begin
PastTime := GetTickCount() - m_Start;
if (PastTime >= StayTime) or (PastTime < 0) then
begin
Timer1.Enabled := false;
Hide();
end;
end;
procedure TfrmMSNPopForm.FormClick(Sender: TObject);
begin
if ClickHide then
begin
Timer1.Enabled := false;
Hide();
end;
end;
procedure TfrmMSNPopForm.FormMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then
begin
if (
(X >= 162) and
(X <= 175) and
(Y >= 6) and
(Y <= 19)
) then
begin
m_QuickHide := true;
Timer1.Enabled := false;
Hide();
end;
end;
end;
end.
|
unit UnitMainForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls;
type
TMainForm = class(TForm)
Image: TImage;
ButtonStart: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
uses Constants, ClassAnimation;
{$R *.DFM}
procedure TMainForm.FormCreate(Sender: TObject);
begin
Animation := TAnimation.Create( Image , CREATURES_DIR+'Creature1.bmb' );
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
Animation.Free;
end;
end.
|
unit frm_GricViewDemo;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Menus, ActnList, ImgList, ExtCtrls, ComCtrls, ToolWin,
HCGridView, HCTableCell, HCItem, HCCommon, HCCustomData;
type
TfrmGridViewDemo = class(TForm)
mmMain: TMainMenu;
mniN1: TMenuItem;
mniMerge: TMenuItem;
mniDeleteCurRow: TMenuItem;
mniInsertRowTop: TMenuItem;
mniInsertRowBottom: TMenuItem;
mniDeleteCurCol: TMenuItem;
mniN2: TMenuItem;
mniN7: TMenuItem;
mniN8: TMenuItem;
mniInsertColLeft: TMenuItem;
mniInsertColRight: TMenuItem;
N1: TMenuItem;
N2: TMenuItem;
mniN3: TMenuItem;
mniN4: TMenuItem;
mniN5: TMenuItem;
pmGridView: TPopupMenu;
mniCut: TMenuItem;
mniN6: TMenuItem;
mniPaste: TMenuItem;
mniTable: TMenuItem;
mni3: TMenuItem;
mni4: TMenuItem;
mniN10: TMenuItem;
mni5: TMenuItem;
mni6: TMenuItem;
mniN11: TMenuItem;
mni7: TMenuItem;
mniSplitRow: TMenuItem;
mniN47: TMenuItem;
mni8: TMenuItem;
mni9: TMenuItem;
mniN25: TMenuItem;
mniBorder: TMenuItem;
mniTableProperty: TMenuItem;
mniPara: TMenuItem;
mniControlItem: TMenuItem;
mniModAnnotate: TMenuItem;
mniDelAnnotate: TMenuItem;
actlst: TActionList;
actSearch: TAction;
actCut: TAction;
actCopy: TAction;
actPaste: TAction;
tlbTool: TToolBar;
btnOpen: TToolButton;
btnNew: TToolButton;
btnSave: TToolButton;
btnprint: TToolButton;
btn3: TToolButton;
btnUndo: TToolButton;
btnRedo: TToolButton;
cbbZoom: TComboBox;
btn6: TToolButton;
cbbFont: TComboBox;
btn1: TToolButton;
cbbFontSize: TComboBox;
cbbFontColor: TColorBox;
cbbBackColor: TColorBox;
btnBold: TToolButton;
btnItalic: TToolButton;
btnUnderLine: TToolButton;
btnStrikeOut: TToolButton;
btnSuperScript: TToolButton;
btnSubScript: TToolButton;
btn2: TToolButton;
btnRightIndent: TToolButton;
btnLeftIndent: TToolButton;
btnAlignLeft: TToolButton;
btnAlignCenter: TToolButton;
btnAlignRight: TToolButton;
btnAlignJustify: TToolButton;
btnAlignScatter: TToolButton;
btnLineSpace: TToolButton;
il1: TImageList;
pmLineSpace: TPopupMenu;
mniLS100: TMenuItem;
mniLS115: TMenuItem;
mniLS150: TMenuItem;
mniLS200: TMenuItem;
mniLSFix: TMenuItem;
mniSave: TMenuItem;
mniOpen: TMenuItem;
mniNew: TMenuItem;
mniN9: TMenuItem;
mniN12: TMenuItem;
mnigif1: TMenuItem;
mniN13: TMenuItem;
mniN14: TMenuItem;
mniN15: TMenuItem;
mniN17: TMenuItem;
mniN18: TMenuItem;
mniHC1: TMenuItem;
mniCheckBox1: TMenuItem;
mniEdit1: TMenuItem;
mniCombobox1: TMenuItem;
mniDateTimePicker1: TMenuItem;
mniRadioGroup1: TMenuItem;
mniN19: TMenuItem;
mniN20: TMenuItem;
mniN21: TMenuItem;
mniN22: TMenuItem;
mniN23: TMenuItem;
mniExplore: TMenuItem;
mniN24: TMenuItem;
mniAlignTopLeft: TMenuItem;
mniAlignTopCenter: TMenuItem;
mniAlignTopRight: TMenuItem;
mniAlignCenterLeft: TMenuItem;
mniAlignCenterCenter: TMenuItem;
mniAlignCenterRight: TMenuItem;
mniAlignBottomLeft: TMenuItem;
mniAlignBottomCenter: TMenuItem;
mniAlignBottomRight: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure mniMergeClick(Sender: TObject);
procedure mniDeleteCurRowClick(Sender: TObject);
procedure mniInsertRowTopClick(Sender: TObject);
procedure mniInsertRowBottomClick(Sender: TObject);
procedure mniInsertColLeftClick(Sender: TObject);
procedure mniInsertColRightClick(Sender: TObject);
procedure mniDeleteCurColClick(Sender: TObject);
procedure mniN4Click(Sender: TObject);
procedure mniN5Click(Sender: TObject);
procedure mniCutClick(Sender: TObject);
procedure mniN6Click(Sender: TObject);
procedure mniPasteClick(Sender: TObject);
procedure mniParaClick(Sender: TObject);
procedure mniControlItemClick(Sender: TObject);
procedure cbbFontChange(Sender: TObject);
procedure btnBoldClick(Sender: TObject);
procedure btnAlignLeftClick(Sender: TObject);
procedure mniLS100Click(Sender: TObject);
procedure cbbBackColorChange(Sender: TObject);
procedure cbbFontColorChange(Sender: TObject);
procedure btnprintClick(Sender: TObject);
procedure btnUndoClick(Sender: TObject);
procedure btnRedoClick(Sender: TObject);
procedure mniNewClick(Sender: TObject);
procedure mniOpenClick(Sender: TObject);
procedure mniSaveClick(Sender: TObject);
procedure mniExploreClick(Sender: TObject);
procedure N2Click(Sender: TObject);
procedure mniN24Click(Sender: TObject);
procedure mniN12Click(Sender: TObject);
procedure mnigif1Click(Sender: TObject);
procedure mniN14Click(Sender: TObject);
procedure mniN15Click(Sender: TObject);
procedure mniN17Click(Sender: TObject);
procedure mniN18Click(Sender: TObject);
procedure mniCheckBox1Click(Sender: TObject);
procedure mniEdit1Click(Sender: TObject);
procedure mniCombobox1Click(Sender: TObject);
procedure mniDateTimePicker1Click(Sender: TObject);
procedure mniRadioGroup1Click(Sender: TObject);
procedure mniN20Click(Sender: TObject);
procedure mniN21Click(Sender: TObject);
procedure mniN22Click(Sender: TObject);
procedure mniN23Click(Sender: TObject);
procedure cbbFontSizeChange(Sender: TObject);
procedure mniBorderClick(Sender: TObject);
procedure mniTablePropertyClick(Sender: TObject);
procedure mniAlignTopLeftClick(Sender: TObject);
private
{ Private declarations }
FGridView: THCGridView;
function SaveFile: Boolean;
procedure DoGridCellPaintBK(const Sender: TObject;
const ACell: THCTableCell; const ARect: TRect; const ACanvas: TCanvas;
const APaintInfo: TPaintInfo; var ADrawDefault: Boolean);
procedure DoComboboxPopupItem(Sender: TObject);
public
{ Public declarations }
end;
var
frmGridViewDemo: TfrmGridViewDemo;
implementation
uses
HCPrinters, HCTextStyle, HCParaStyle, HCViewData, HCFractionItem, HCExpressItem,
HCSupSubScriptItem, HCCheckBoxItem, HCEditItem, HCComboboxItem, HCDateTimePicker,
HCRadioGroup, HCBarCodeItem, HCQRCodeItem, HCTextItem, frm_Annotate, frm_TableProperty,
frm_TableBorderBackColor, frm_PrintView, frm_Paragraph, frm_ControlItemProperty,
frm_InsertTable, frm_PageSet, CFBalloonHint, HCImageItem, HCRichData;
{$R *.dfm}
procedure TfrmGridViewDemo.btnAlignLeftClick(Sender: TObject);
begin
case (Sender as TToolButton).Tag of
0: FGridView.ApplyParaAlignHorz(TParaAlignHorz.pahLeft);
1: FGridView.ApplyParaAlignHorz(TParaAlignHorz.pahCenter);
2: FGridView.ApplyParaAlignHorz(TParaAlignHorz.pahRight);
3: FGridView.ApplyParaAlignHorz(TParaAlignHorz.pahJustify); // 两端
4: FGridView.ApplyParaAlignHorz(TParaAlignHorz.pahScatter); // 分散
5: FGridView.ApplyParaLeftIndent;
6: FGridView.ApplyParaLeftIndent(False);
end;
end;
procedure TfrmGridViewDemo.btnBoldClick(Sender: TObject);
begin
case (Sender as TToolButton).Tag of
0: FGridView.ApplyTextStyle(THCFontStyle.tsBold);
1: FGridView.ApplyTextStyle(THCFontStyle.tsItalic);
2: FGridView.ApplyTextStyle(THCFontStyle.tsUnderline);
3: FGridView.ApplyTextStyle(THCFontStyle.tsStrikeOut);
4: FGridView.ApplyTextStyle(THCFontStyle.tsSuperscript);
5: FGridView.ApplyTextStyle(THCFontStyle.tsSubscript);
end;
end;
procedure TfrmGridViewDemo.btnprintClick(Sender: TObject);
var
vPrintDlg: TPrintDialog;
begin
vPrintDlg := TPrintDialog.Create(nil);
try
if vPrintDlg.Execute then
FGridView.Print(HCPrinter.Printers[HCPrinter.PrinterIndex]);
finally
FreeAndNil(vPrintDlg);
end;
end;
procedure TfrmGridViewDemo.btnRedoClick(Sender: TObject);
begin
FGridView.Redo;
end;
procedure TfrmGridViewDemo.btnUndoClick(Sender: TObject);
begin
FGridView.Undo;
end;
procedure TfrmGridViewDemo.cbbBackColorChange(Sender: TObject);
begin
FGridView.ApplyTextBackColor(cbbBackColor.Selected);
end;
procedure TfrmGridViewDemo.cbbFontChange(Sender: TObject);
begin
FGridView.ApplyTextFontName(cbbFont.Text);
if not FGridView.Focused then
FGridView.SetFocus;
end;
procedure TfrmGridViewDemo.cbbFontColorChange(Sender: TObject);
begin
FGridView.ApplyTextColor(cbbFontColor.Selected);
if not FGridView.Focused then
FGridView.SetFocus;
end;
procedure TfrmGridViewDemo.cbbFontSizeChange(Sender: TObject);
begin
FGridView.ApplyTextFontSize(GetFontSize(cbbFontSize.Text));
if not FGridView.Focused then
FGridView.SetFocus;
end;
procedure TfrmGridViewDemo.DoComboboxPopupItem(Sender: TObject);
begin
if Sender is THCComboboxItem then
begin
if (Sender as THCComboboxItem).Items.Count > 20 then
(Sender as THCComboboxItem).Items.Clear;
(Sender as THCComboboxItem).Items.Add('选项' + IntToStr((Sender as THCComboboxItem).Items.Count - 1));
end;
end;
procedure TfrmGridViewDemo.DoGridCellPaintBK(const Sender: TObject;
const ACell: THCTableCell; const ARect: TRect; const ACanvas: TCanvas;
const APaintInfo: TPaintInfo; var ADrawDefault: Boolean);
begin
// if (ARect.Left + FGridView.HorOffset > 250) then
// //if (ARect.Top + FGridView.VerOffset > 250) then
// begin
// ACanvas.Brush.Color := clYellow;
// ACanvas.FillRect(ARect);
// end;
end;
procedure TfrmGridViewDemo.FormCreate(Sender: TObject);
begin
FGridView := THCGridView.CreateEx(nil, 80, 12);
//FGridView.OnCellPaintBK := DoGridCellPaintBK;
FGridView.Align := alClient;
FGridView.Parent := Self;
FGridView.PopupMenu := pmGridView;
end;
procedure TfrmGridViewDemo.FormDestroy(Sender: TObject);
begin
FreeAndNil(FGridView);
end;
procedure TfrmGridViewDemo.mniMergeClick(Sender: TObject);
begin
//FGridView.MergeTableSelectCells;
FGridView.MergeSelectCells;
end;
procedure TfrmGridViewDemo.mniNewClick(Sender: TObject);
var
vFrmInsertTable: TfrmInsertTable;
begin
vFrmInsertTable := TfrmInsertTable.Create(Self);
try
vFrmInsertTable.ShowModal;
if vFrmInsertTable.ModalResult = mrOk then
begin
FGridView.ReSetRowCol(StrToInt(vFrmInsertTable.edtRows.Text),
StrToInt(vFrmInsertTable.edtCols.Text));
end;
finally
FreeAndNil(vFrmInsertTable);
end;
end;
procedure TfrmGridViewDemo.mniOpenClick(Sender: TObject);
var
vOpenDlg: TOpenDialog;
vExt: string;
begin
vOpenDlg := TOpenDialog.Create(Self);
try
vOpenDlg.Filter := '支持的文件|*' + HC_EXT + '; *.xml; *.xlsx|HCGridView (*.hcf)|*' + HC_EXT + '|HCGridView xml (*.xml)|*.xml|Excel 2007 Document (*.xlsx)|*.xlsx';
if vOpenDlg.Execute then
begin
if vOpenDlg.FileName <> '' then
begin
Application.ProcessMessages; // 解决双击打开文件后,触发下层控件的Mousemove,Mouseup事件
vExt := LowerCase(ExtractFileExt(vOpenDlg.FileName)); // 后缀
if vExt = HC_EXT then
FGridView.LoadFromFile(vOpenDlg.FileName)
else
if vExt = '.xml' then
FGridView.LoadFromXml(vOpenDlg.FileName)
else
//FGridView.LoadFromDocumentFile(vOpenDlg.FileName, vExt)
end;
end;
finally
FreeAndNil(vOpenDlg);
end;
end;
procedure TfrmGridViewDemo.mniN12Click(Sender: TObject);
var
vOpenDlg: TOpenDialog;
vImageItem: THCImageItem;
vTopData: THCRichData;
begin
vOpenDlg := TOpenDialog.Create(Self);
try
vOpenDlg.Filter := '图像文件|*.bmp; *.jpg; *.jpeg; *.png|Windows Bitmap|*.bmp|JPEG 文件|*.jpg; *.jpge|可移植网络图形|*.png';
FGridView.Enabled := False;
try
if vOpenDlg.Execute then
begin
if vOpenDlg.FileName <> '' then
begin
vTopData := FGridView.TopLevelData as THCRichData;
vImageItem := THCImageItem.Create(vTopData);
vImageItem.LoadFromBmpFile(vOpenDlg.FileName);
vImageItem.RestrainSize(vTopData.Width, vImageItem.Height);
Application.ProcessMessages; // 解决双击打开文件后,触发下层控件的Mousemove,Mouseup事件
FGridView.InsertItem(vImageItem);
end;
end;
finally
FGridView.Enabled := True;
end;
finally
FreeAndNil(vOpenDlg);
end;
end;
procedure TfrmGridViewDemo.mniN14Click(Sender: TObject);
var
vTopData: THCCustomData;
vFractionItem: THCFractionItem;
begin
//vTopData := FGridView.ActiveSectionTopLevelData;
vTopData := FGridView.TopLevelData;
if Assigned(vTopData) then
begin
vFractionItem := THCFractionItem.Create(vTopData, '12', '2019');
FGridView.InsertItem(vFractionItem);
end;
end;
procedure TfrmGridViewDemo.mniN15Click(Sender: TObject);
var
vTopData: THCCustomData;
vExpressItem: THCExpressItem;
begin
//vTopData := FGridView.ActiveSectionTopLevelData;
vTopData := FGridView.TopLevelData;
if Assigned(vTopData) then
begin
vExpressItem := THCExpressItem.Create(vTopData,
'12', '5-6', '2017-6-3', '28-30');
FGridView.InsertItem(vExpressItem);
end;
end;
procedure TfrmGridViewDemo.mniN17Click(Sender: TObject);
var
vTopData: THCCustomData;
vSupSubScriptItem: THCSupSubScriptItem;
begin
//vTopData := FGridView.ActiveSectionTopLevelData;
vTopData := FGridView.TopLevelData;
if Assigned(vTopData) then
begin
vSupSubScriptItem := THCSupSubScriptItem.Create(vTopData, '20g', '先煎');
FGridView.InsertItem(vSupSubScriptItem);
end;
end;
procedure TfrmGridViewDemo.mniN18Click(Sender: TObject);
begin
FGridView.InsertLine(1);
end;
procedure TfrmGridViewDemo.mniN20Click(Sender: TObject);
var
vTopData: THCCustomData;
vHCBarCode: THCBarCodeItem;
vS: string;
begin
vS := InputBox('文本框', '文本', 'HC-' + FormatDateTime('YYYYMMDD', Now));
//vTopData := FGridView.ActiveSectionTopLevelData;
vTopData := FGridView.TopLevelData;
if Assigned(vTopData) then
begin
vHCBarCode := THCBarCodeItem.Create(vTopData, vS);
FGridView.InsertItem(vHCBarCode);
end;
end;
procedure TfrmGridViewDemo.mniN21Click(Sender: TObject);
var
vTopData: THCCustomData;
vQRCode: THCQRCodeItem;
vS: string;
begin
vS := InputBox('文本框', '文本', 'HCView使用了DelphiZXingQRCode二维码控件');
//vTopData := FGridView.ActiveSectionTopLevelData;
vTopData := FGridView.TopLevelData;
if Assigned(vTopData) then
begin
vQRCode := THCQRCodeItem.Create(vTopData, vS);
FGridView.InsertItem(vQRCode);
end;
end;
procedure TfrmGridViewDemo.mniN22Click(Sender: TObject);
var
vTopData: THCCustomData;
vTextItem: THCTextItem;
begin
//vTopData := FGridView.ActiveSectionTopLevelData;
vTopData := FGridView.TopLevelData;
if Assigned(vTopData) then
begin
vTextItem := vTopData.CreateDefaultTextItem as THCTextItem;
vTextItem.Text := '打开百度';
vTextItem.HyperLink := 'www.baidu.com';
FGridView.InsertItem(vTextItem);
end;
end;
procedure TfrmGridViewDemo.mniN23Click(Sender: TObject);
var
vTopData: THCViewData;
vFrmAnnotate: TfrmAnnotate;
begin
//vTopData := FGridView.ActiveSectionTopLevelData as THCViewData;
vTopData := FGridView.TopLevelData as THCViewData;;
if Assigned(vTopData) then
begin
if not vTopData.SelectExists then Exit;
vFrmAnnotate := TfrmAnnotate.Create(Self);
try
vFrmAnnotate.SetAnnotate(nil);
if vFrmAnnotate.ModalResult = mrOk then
vTopData.InsertAnnotate(vFrmAnnotate.edtTitle.Text, vFrmAnnotate.mmoText.Text);
finally
FreeAndNil(vFrmAnnotate);
end;
end;
end;
procedure TfrmGridViewDemo.mniN24Click(Sender: TObject);
var
vFrmInsertTable: TfrmInsertTable;
begin
vFrmInsertTable := TfrmInsertTable.Create(Self);
try
vFrmInsertTable.ShowModal;
if vFrmInsertTable.ModalResult = mrOk then
begin
FGridView.InsertTable(StrToInt(vFrmInsertTable.edtRows.Text),
StrToInt(vFrmInsertTable.edtCols.Text));
end;
finally
FreeAndNil(vFrmInsertTable);
end;
end;
procedure TfrmGridViewDemo.mniParaClick(Sender: TObject);
var
vFrmParagraph: TfrmParagraph;
begin
vFrmParagraph := TfrmParagraph.Create(Self);
try
vFrmParagraph.SetGridView(FGridView);
finally
FreeAndNil(vFrmParagraph);
end;
end;
procedure TfrmGridViewDemo.mniN4Click(Sender: TObject);
var
vFrmPrintView: TfrmPrintView;
begin
vFrmPrintView := TfrmPrintView.Create(Self);
try
vFrmPrintView.SetGridView(FGridView);
finally
FreeAndNil(vFrmPrintView);
end;
end;
procedure TfrmGridViewDemo.mniN5Click(Sender: TObject);
begin
FGridView.Print;
end;
procedure TfrmGridViewDemo.mniN6Click(Sender: TObject);
begin
// FGridView.Copy;
end;
procedure TfrmGridViewDemo.mniPasteClick(Sender: TObject);
begin
// FGridView.Paste;
end;
procedure TfrmGridViewDemo.mniRadioGroup1Click(Sender: TObject);
var
vTopData: THCCustomData;
vHCRadioGroup: THCRadioGroup;
begin
//vTopData := FGridView.ActiveSectionTopLevelData;
vTopData := FGridView.TopLevelData;
if Assigned(vTopData) then
begin
vHCRadioGroup := THCRadioGroup.Create(vTopData);
vHCRadioGroup.AddItem('选项1');
vHCRadioGroup.AddItem('选项2');
vHCRadioGroup.AddItem('选项3');
FGridView.InsertItem(vHCRadioGroup);
end;
end;
procedure TfrmGridViewDemo.mniSaveClick(Sender: TObject);
begin
if SaveFile then
BalloonMessage('保存成功!');
end;
procedure TfrmGridViewDemo.mniTablePropertyClick(Sender: TObject);
var
vFrmTableProperty: TFrmTableProperty;
begin
vFrmTableProperty := TFrmTableProperty.Create(Self);
try
vFrmTableProperty.SetGridView(FGridView);
finally
FreeAndNil(vFrmTableProperty);
end;
end;
procedure TfrmGridViewDemo.N2Click(Sender: TObject);
var
vFrmPageSet: TFrmPageSet;
begin
vFrmPageSet := TFrmPageSet.Create(Self);
try
vFrmPageSet.SetGridView(FGridView);
finally
FreeAndNil(vFrmPageSet);
end;
end;
function TfrmGridViewDemo.SaveFile: Boolean;
var
vDlg: TSaveDialog;
begin
Result := False;
if FGridView.FileName <> '' then
begin
FGridView.SaveToFile(FGridView.FileName);
FGridView.IsChanged := False;
Result := True;
end
else
begin
vDlg := TSaveDialog.Create(Self);
try
vDlg.Filter := 'HCView (*.hcf)|*' + HC_EXT + '|HCView xml (*.xml)|*.xml';//|Word 2007 Document (*.docx)|*.docx';
vDlg.Execute;
if vDlg.FileName <> '' then
begin
case vDlg.FilterIndex of
1:
begin
if ExtractFileExt(vDlg.FileName) <> HC_EXT then
vDlg.FileName := vDlg.FileName + HC_EXT;
FGridView.SaveToFile(vDlg.FileName);
FGridView.IsChanged := False;
Result := True;
end;
2:
begin
if LowerCase(ExtractFileExt(vDlg.FileName)) <> '.xml' then
vDlg.FileName := vDlg.FileName + '.xml';
FGridView.SaveToXml(vDlg.FileName, TEncoding.Unicode);
FGridView.IsChanged := False;
Result := True;
end;
// 3: // .docx
// begin
// if LowerCase(ExtractFileExt(vDlg.FileName)) <> HC_EXT_DOCX then
// vDlg.FileName := vDlg.FileName + HC_EXT_DOCX;
//
// FGridView.SaveToDocumentFile(vDlg.FileName, HC_EXT_DOCX);
// FGridView.IsChanged := False;
// Result := True;
// end;
end;
end;
finally
vDlg.Free;
end;
end;
end;
procedure TfrmGridViewDemo.mniAlignTopLeftClick(Sender: TObject);
begin
case (Sender as TMenuItem).Tag of
0: FGridView.ApplyTableCellAlign(THCContentAlign.tcaTopLeft);
1: FGridView.ApplyTableCellAlign(THCContentAlign.tcaTopCenter);
2: FGridView.ApplyTableCellAlign(THCContentAlign.tcaTopRight);
3: FGridView.ApplyTableCellAlign(THCContentAlign.tcaCenterLeft);
4: FGridView.ApplyTableCellAlign(THCContentAlign.tcaCenterCenter);
5: FGridView.ApplyTableCellAlign(THCContentAlign.tcaCenterRight);
6: FGridView.ApplyTableCellAlign(THCContentAlign.tcaBottomLeft);
7: FGridView.ApplyTableCellAlign(THCContentAlign.tcaBottomCenter);
8: FGridView.ApplyTableCellAlign(THCContentAlign.tcaBottomRight);
end;
end;
procedure TfrmGridViewDemo.mniBorderClick(Sender: TObject);
var
vFrmBorderBackColor: TfrmBorderBackColor;
begin
vFrmBorderBackColor := TfrmBorderBackColor.Create(Self);
try
vFrmBorderBackColor.SetGridView(FGridView);
finally
FreeAndNil(vFrmBorderBackColor);
end;
end;
procedure TfrmGridViewDemo.mniCheckBox1Click(Sender: TObject);
var
vTopData: THCCustomData;
vCheckBox: THCCheckBoxItem;
vS: string;
begin
vS := '勾选框';
if InputQuery('勾选框', '文本', vS) then
begin
//vTopData := FGridView.ActiveSectionTopLevelData;
vTopData := FGridView.TopLevelData;
if Assigned(vTopData) then
begin
vCheckBox := THCCheckBoxItem.Create(vTopData, vS, False);
FGridView.InsertItem(vCheckBox);
end;
end;
end;
procedure TfrmGridViewDemo.mniCombobox1Click(Sender: TObject);
var
vTopData: THCCustomData;
vCombobox: THCComboboxItem;
vS: string;
begin
vS := '默认值';
if InputQuery('下拉框', '文本内容', vS) then
begin
//vTopData := FGridView.ActiveSectionTopLevelData;
vTopData := FGridView.TopLevelData;
if Assigned(vTopData) then
begin
vCombobox := THCComboboxItem.Create(vTopData, vS);
vCombobox.Items.Add('选项1');
vCombobox.Items.Add('选项2');
vCombobox.Items.Add('选项3');
vCombobox.OnPopupItem := DoComboboxPopupItem;
//vCombobox.ItemIndex := 0;
FGridView.InsertItem(vCombobox);
end;
end;
end;
procedure TfrmGridViewDemo.mniControlItemClick(Sender: TObject);
var
vFrmControlItemProperty: TfrmControlItemProperty;
begin
// vFrmControlItemProperty := TfrmControlItemProperty.Create(nil);
// try
// vFrmControlItemProperty.SetHCView(FHCView);
// finally
// FreeAndNil(vFrmControlItemProperty);
// end;
end;
procedure TfrmGridViewDemo.mniCutClick(Sender: TObject);
begin
// FGridView.Cut;
end;
procedure TfrmGridViewDemo.mniDateTimePicker1Click(Sender: TObject);
var
vTopData: THCCustomData;
vHCDateTimePicker: THCDateTimePicker;
begin
//vTopData := FGridView.ActiveSectionTopLevelData;
vTopData := FGridView.TopLevelData;
if Assigned(vTopData) then
begin
vHCDateTimePicker := THCDateTimePicker.Create(vTopData, Now);
FGridView.InsertItem(vHCDateTimePicker);
end;
end;
procedure TfrmGridViewDemo.mniDeleteCurColClick(Sender: TObject);
begin
//FGridView.ActiveTableDeleteCurCol;
FGridView.DeleteCurCol;
end;
procedure TfrmGridViewDemo.mniDeleteCurRowClick(Sender: TObject);
begin
//FGridView.ActiveTableDeleteCurRow;
FGridView.DeleteCurRow;
end;
procedure TfrmGridViewDemo.mniEdit1Click(Sender: TObject);
var
vTopData: THCCustomData;
vEdit: THCEditItem;
vS: string;
begin
vS := '文本';
if InputQuery('文本框', '文本内容', vS) then
begin
//vTopData := FGridView.ActiveSectionTopLevelData;
vTopData := FGridView.TopLevelData;
if Assigned(vTopData) then
begin
vEdit := THCEditItem.Create(vTopData, vS);
FGridView.InsertItem(vEdit);
end;
end;
end;
procedure TfrmGridViewDemo.mniExploreClick(Sender: TObject);
var
vDlg: TSaveDialog;
vExt: string;
begin
vDlg := TSaveDialog.Create(Self);
try
vDlg.Filter := 'pdf格式|*.pdf' + '|htm格式|*.html';
vDlg.Execute;
if vDlg.FileName <> '' then
begin
vExt := '';
case vDlg.FilterIndex of
1: vExt := '.pdf';
2: vExt := '.html';
else
Exit;
end;
if ExtractFileExt(vDlg.FileName) <> vExt then // 避免重复后缀
vDlg.FileName := vDlg.FileName + vExt;
case vDlg.FilterIndex of
1: FGridView.SaveToPDF(vDlg.FileName);
2: FGridView.SaveToHtml(vDlg.FileName, False);
end;
end;
finally
vDlg.Free;
end;
end;
procedure TfrmGridViewDemo.mnigif1Click(Sender: TObject);
var
vOpenDlg: TOpenDialog;
begin
vOpenDlg := TOpenDialog.Create(Self);
try
vOpenDlg.Filter := '图像文件|*.gif';
if vOpenDlg.Execute then
begin
if vOpenDlg.FileName <> '' then
begin
Application.ProcessMessages; // 解决双击打开文件后,触发下层控件的Mousemove,Mouseup事件
FGridView.InsertGifImage(vOpenDlg.FileName);
end;
end;
finally
FreeAndNil(vOpenDlg);
end;
end;
procedure TfrmGridViewDemo.mniInsertColLeftClick(Sender: TObject);
begin
//FGridView.ActiveTableInsertColBefor(1);
FGridView.InsertColBefor(1);
end;
procedure TfrmGridViewDemo.mniInsertColRightClick(Sender: TObject);
begin
//FGridView.ActiveTableInsertColAfter(1);
FGridView.InsertColAfter(1);
end;
procedure TfrmGridViewDemo.mniInsertRowBottomClick(Sender: TObject);
begin
//FGridView.ActiveTableInsertRowAfter(1);
FGridView.InsertRowAfter(1);
end;
procedure TfrmGridViewDemo.mniInsertRowTopClick(Sender: TObject);
begin
//FGridView.ActiveTableInsertRowBefor(1);
FGridView.InsertRowBefor(1);
end;
procedure TfrmGridViewDemo.mniLS100Click(Sender: TObject);
begin
if Sender is TMenuItem then
begin
case (Sender as TMenuItem).Tag of
0: FGridView.ApplyParaLineSpace(TParaLineSpaceMode.pls100); // 单倍
1: FGridView.ApplyParaLineSpace(TParaLineSpaceMode.pls115); // 1.15倍
2: FGridView.ApplyParaLineSpace(TParaLineSpaceMode.pls150); // 1.5倍
3: FGridView.ApplyParaLineSpace(TParaLineSpaceMode.pls200); // 双倍
4: FGridView.ApplyParaLineSpace(TParaLineSpaceMode.plsFix); // 固定值
end;
end;
end;
end.
|
//================================================//
// uFileSaver //
//------------------------------------------------//
// Unit yang menangani penyimpanan kembali data //
//================================================//
unit uFileSaver;
interface
uses uFileLoader;
procedure SaveBuku(var arrBuku : BArr ; filename : string);
{Mengisi ulang file filename dengan elemen-elemen dari arrBuku
dengan format sesuai format awal file Buku}
{I.S. : file filename berisi elemen arrBuku pada awal program}
{F.S. : file filename berisi elemen arrBuku paling baru pada saat save}
procedure SaveUser(var arrUser : UArr ; filename : string);
{Mengisi ulang file filename dengan elemen-elemen dari arrUser
dengan format sesuai format awal file User}
{I.S. : file filename berisi elemen arrUser pada awal program}
{F.S. : file filename berisi elemen arrUser paling baru pada saat save}
procedure SaveHistoryPeminjaman(var arrHistoryPeminjaman : PinjamArr ; filename : string);
{Mengisi ulang file filename dengan elemen-elemen dari arrHistoryPeminjaman
dengan format sesuai format awal file Riwayat Peminjaman}
{I.S. : file filename berisi elemen arrHistoryPeminjaman pada awal program}
{F.S. : file filename berisi elemen arrHistoryPeminjaman paling baru pada saat save}
procedure SaveHistoryPengembalian(var arrHistoryPengembalian : KembaliArr ; filename : string);
{Mengisi ulang file filename dengan elemen-elemen dari arrHistoryPengembalian
dengan format sesuai format awal file Riwayat Pengembalian}
{I.S. : file filename berisi elemen arrHistoryPengembalian pada awal program}
{F.S. : file filename berisi elemen arrHistoryPengembalian paling baru pada saat save}
procedure SaveLaporanHilang(var arrLaporanHilang : HilangArr ; filename : string);
{Mengisi ulang file filename dengan elemen-elemen dari arrLaporanHilang
dengan format sesuai format awal file Laporan Hilang}
{I.S. : file filename berisi elemen arrLaporanHilang pada awal program}
{F.S. : file filename berisi elemen arrLaporanHilang paling baru pada saat save}
implementation
procedure SaveBuku(var arrBuku : BArr ; filename : string);
{Mengisi ulang file filename dengan elemen-elemen dari arrBuku
dengan format sesuai format awal file Buku}
{I.S. : file filename berisi elemen arrBuku pada awal program}
{F.S. : file filename berisi elemen arrBuku paling baru pada saat save}
{ KAMUS LOKAL }
var
UserFile : Text;
i : integer;
header : string;
{ ALGORITMA }
begin
{INISIALISASI FILE UNTUK DIBACA}
system.Assign(UserFile, filename);
system.Rewrite(UserFile);
// header adalah bagian baris atas file .csv (nama kolom)
header := 'ID_Buku,Judul_Buku,Author,Jumlah_Buku,Tahun_Penerbit,Kategori';
writeln(UserFile, header);
// For loop untuk menulis elemen array sesuai format .csv
for i := 1 to lenBuku do
begin
writeln(UserFile, arrBuku[i].ID_Buku, ',', arrBuku[i].Judul_Buku, ',', arrBuku[i].Author, ',',
arrBuku[i].Jumlah_Buku, ',', arrBuku[i].Tahun_Penerbit, ',', arrBuku[i].Kategori);
end;
Close(UserFile);
end;
procedure SaveUser(var arrUser : UArr ; filename : string);
{Mengisi ulang file filename dengan elemen-elemen dari arrUser
dengan format sesuai format awal file User}
{I.S. : file filename berisi elemen arrUser pada awal program}
{F.S. : file filename berisi elemen arrUser paling baru pada saat save}
{ KAMUS LOKAL }
var
UserFile : Text;
i : integer;
header, alamat : string;
{ ALGORITMA }
begin
{INISIALISASI FILE UNTUK DIBACA}
system.Assign(UserFile, filename);
system.Rewrite(UserFile);
// header adalah bagian baris atas file .csv (nama kolom)
header := 'Nama,Alamat,Username,Password,Role';
writeln(UserFile, header);
// For loop untuk menulis elemen array sesuai format .csv
for i := 1 to lenUser do
begin
alamat := '"' + arrUser[i].Alamat + '"';
writeln(UserFile, arrUser[i].Nama, ',', alamat, ',',
arrUser[i].Username, ',', arrUser[i].Password, ',',
arrUser[i].Role);
end;
Close(UserFile);
end;
procedure SaveHistoryPeminjaman(var arrHistoryPeminjaman : PinjamArr ; filename : string);
{Mengisi ulang file filename dengan elemen-elemen dari arrHistoryPeminjaman
dengan format sesuai format awal file Riwayat Peminjaman}
{I.S. : file filename berisi elemen arrHistoryPeminjaman pada awal program}
{F.S. : file filename berisi elemen arrHistoryPeminjaman paling baru pada saat save}
{ KAMUS LOKAL }
var
UserFile : Text;
i : integer;
header: string;
{ ALGORITMA }
begin
{INISIALISASI FILE UNTUK DIBACA}
system.Assign(UserFile, filename);
system.Rewrite(UserFile);
// header adalah bagian baris atas file .csv (nama kolom)
header := 'Username,ID_Buku,Tanggal_Peminjaman,Tanggal_Batas_Pengembalian,Status_Pengembalian';
writeln(UserFile, header);
// For loop untuk menulis elemen array sesuai format .csv
for i := 1 to lenHistoryPeminjaman do
begin
writeln(UserFile, arrHistoryPeminjaman[i].Username, ',', arrHistoryPeminjaman[i].ID_Buku, ',',
arrHistoryPeminjaman[i].Tanggal_Peminjaman.DD, '/',arrHistoryPeminjaman[i].Tanggal_Peminjaman.MM, '/',
arrHistoryPeminjaman[i].Tanggal_Peminjaman.YYYY, ',',
arrHistoryPeminjaman[i].Tanggal_Batas_Pengembalian.DD, '/', arrHistoryPeminjaman[i].Tanggal_Batas_Pengembalian.MM, '/',
arrHistoryPeminjaman[i].Tanggal_Batas_Pengembalian.YYYY, ',',
arrHistoryPeminjaman[i].Status_Pengembalian);
end;
Close(UserFile);
end;
procedure SaveHistoryPengembalian(var arrHistoryPengembalian : KembaliArr ; filename : string);
{Mengisi ulang file filename dengan elemen-elemen dari arrHistoryPengembalian
dengan format sesuai format awal file Riwayat Pengembalian}
{I.S. : file filename berisi elemen arrHistoryPengembalian pada awal program}
{F.S. : file filename berisi elemen arrHistoryPengembalian paling baru pada saat save}
{ KAMUS LOKAL }
var
UserFile : Text;
i : integer;
header: string;
{ ALGORITMA }
begin
{INISIALISASI FILE UNTUK DIBACA}
system.Assign(UserFile, filename);
system.Rewrite(UserFile);
// header adalah bagian baris atas file .csv (nama kolom)
header := 'Username,ID_Buku,Tanggal_Pengembalian';
writeln(UserFile, header);
// For loop untuk menulis elemen array sesuai format .csv
for i := 1 to lenHistoryPengembalian do
begin
writeln(UserFile, arrHistoryPengembalian[i].Username, ',', arrHistoryPengembalian[i].ID_Buku, ',',
arrHistoryPengembalian[i].Tanggal_Pengembalian.DD, '/',arrHistoryPengembalian[i].Tanggal_Pengembalian.MM, '/',
arrHistoryPengembalian[i].Tanggal_Pengembalian.YYYY);
end;
Close(UserFile);
end;
procedure SaveLaporanHilang(var arrLaporanHilang : HilangArr ; filename : string);
{Mengisi ulang file filename dengan elemen-elemen dari arrLaporanHilang
dengan format sesuai format awal file Laporan Hilang}
{I.S. : file filename berisi elemen arrLaporanHilang pada awal program}
{F.S. : file filename berisi elemen arrLaporanHilang paling baru pada saat save}
{ KAMUS LOKAL }
var
UserFile : Text;
i : integer;
header: string;
{ ALGORITMA }
begin
{INISIALISASI FILE UNTUK DIBACA}
system.Assign(UserFile, filename);
system.Rewrite(UserFile);
// header adalah bagian baris atas file .csv (nama kolom)
header := 'Username,ID_Buku_Hilang,Tanggal_Laporan';
writeln(UserFile, header);
// For loop untuk menulis elemen array sesuai format .csv
for i := 1 to lenLaporanHilang do
begin
writeln(UserFile, arrLaporanHilang[i].Username, ',', arrLaporanHilang[i].ID_Buku_Hilang, ',',
arrLaporanHilang[i].Tanggal_Laporan.DD, '/',arrLaporanHilang[i].Tanggal_Laporan.MM, '/',
arrLaporanHilang[i].Tanggal_Laporan.YYYY);
end;
Close(UserFile);
end;
end. |
{ #(@)$Id: UnitTestGUITesting.pas 7 2008-04-24 11:59:47Z judc $ }
{: DUnit: An XTreme testing framework for Delphi programs.
@author The DUnit Group.
@version $Revision: 7 $ uberto 08/03/2001
}
(*
* 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 DUnit.
*
* The Initial Developers of the Original Code are Serge Beaumont
* and Juancarlo Aņez.
* Portions created The Initial Developers are Copyright (C) 1999-2000.
* Portions created by The DUnit Group are Copyright (C) 2000-2003.
* All rights reserved.
*
* Contributor(s):
* Serge Beaumont <beaumose@iquip.nl>
* Juanco Aņez <juanco@users.sourceforge.net>
* Uberto Barbini <uberto@usa.net>
* Kris Golko <neuromancer@users.sourceforge.net>
* Kenneth Semeijn <kennethsem@users.sourceforge.net>
* Jon Bertrand <jonbsfnet@users.sourceforge.net>
* The DUnit group at SourceForge <http://dunit.sourceforge.net>
*
*)
{$IFDEF LINUX}
{$DEFINE DUNIT_CLX}
{$ENDIF}
unit UnitTestGUITesting;
interface
uses
GUITesting,
{$IFDEF DUNIT_CLX}
Qt, QGraphics, QForms, QMenus, QStdCtrls, QControls,
QGUITestRunner,
{$ELSE}
Windows, Messages, Graphics, Forms, Menus, StdCtrls, Controls,
GUITestRunner,
{$ENDIF}
SysUtils,
Classes {Variants,};
const
rcs_id: string = '#(@)$Id: UnitTestGUITesting.pas 7 2008-04-24 11:59:47Z judc $';
type
TDunitDialogCracker = class(TGUITestRunner);
{ This form is used to test some of the methods in TGUITestCase }
TTestForm = class(TForm)
xButton: TButton;
xEdit: TEdit;
xMemo: TMemo;
MainMenu1: TMainMenu;
est11: TMenuItem;
xAltBackspace: TMenuItem;
xCtrlA: TMenuItem;
F21: TMenuItem;
xButton2: TButton;
xButton3: TButton;
procedure xButtonClick(Sender: TObject);
procedure xEditKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormCreate(Sender: TObject);
procedure xEditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure xAltBackspaceClick(Sender: TObject);
procedure xCtrlAClick(Sender: TObject);
procedure F8Click(Sender: TObject);
public
ButtonClickCount, EditKeyDownCount, EditKeyUpCount,
FormKeyDownCount, FormKeyUpCount : integer;
AltBackspaceCount, ControlACount, Function8Count : integer;
FormKeys : string;
procedure ResetForm;
end;
T_TGUITestCase = class(TGUITestCase)
protected
mForm : TTestForm;
procedure SetUp; override;
public
procedure TearDown; override;
published
procedure Test_Form_Releases;
procedure Test_IsFocused;
procedure Test_Sleep;
procedure Test_EnterKeyInto;
procedure Test_EnterKey;
procedure Test_EnterTextInto;
procedure Test_Tab;
end;
TGUITestRunnerTests = class(TGUITestCase)
private
FRunner :TGUITestRunner;
public
{ Test BOOLEVAL OFF Directive }
mRefCountA, mRefCountB : integer;
function TestA(const ReturnValue : boolean) : boolean;
function TestB(const ReturnValue : boolean) : boolean;
procedure TestAnd(const A, B : boolean);
procedure TestOr(const A, B : boolean);
procedure SetUp; override;
procedure TearDown; override;
{$IFDEF LINUX}
procedure TestStatus;
{$ENDIF}
published
procedure Test_BooleanEvalOff;
procedure TestTabOrder;
procedure TestViewResult;
procedure TestElapsedTime;
procedure RunEmptySuite;
procedure RunSuccessSuite;
procedure RunFailureSuite;
{$IFDEF WIN32}
procedure TestStatus;
{$ENDIF}
procedure TestRunSelectedTestWithDecorator;
procedure TestRunSelectedTestWithSetupDecorator;
{$IFNDEF DUNIT_CLX}
procedure TestGoToPrevNextSelectedNode;
{$ENDIF}
end;
implementation
uses
TestFramework,
TestExtensions;
{$R *.dfm}
type
TSuccessTestCase = class(TTestCase)
published
procedure OneSuccess;
procedure SecondSuccess;
end;
TFailuresTestCase = class(TTestCase)
private
procedure DoNothing;
published
procedure OneSuccess;
procedure OneFailure;
procedure SecondFailure;
procedure OneError;
end;
TTimeTestCase = class(TTestCase)
published
procedure TestTime;
end;
TStatusTestCase = class(TTestCase)
published
procedure OneSuccessWithStatus;
procedure SecondSuccessWithStatus;
public
procedure SetUp; override;
end;
TSetupTestCase = class(TTestSetup)
protected
FSetupCount : integer;
FTearDownCount : integer;
procedure SetUp; override;
procedure TearDown; override;
public
procedure AfterConstruction; override;
end;
{ TTestForm }
procedure TTestForm.ResetForm;
begin
ButtonClickCount := 0;
EditKeyDownCount := 0;
EditKeyUpCount := 0;
FormKeyDownCount := 0;
FormKeyUpCount := 0;
AltBackspaceCount := 0;
ControlACount := 0;
Function8Count := 0;
xEdit.Text := '';
FormKeys := '';
end;
procedure TTestForm.FormCreate(Sender: TObject);
begin
ResetForm;
end;
procedure TTestForm.xButtonClick(Sender: TObject);
begin
inc(ButtonClickCount);
end;
procedure TTestForm.xEditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inc(EditKeyDownCount);
end;
procedure TTestForm.xEditKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inc(EditKeyUpCount);
end;
procedure TTestForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inc(FormKeyDownCount);
Assert(FormKeyDownCount > EditKeyDownCount);
end;
procedure TTestForm.FormKeyPress(Sender: TObject; var Key: Char);
begin
FormKeys := FormKeys + Key;
end;
procedure TTestForm.FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inc(FormKeyUpCount);
Assert(FormKeyUpCount > EditKeyUpCount);
end;
procedure TTestForm.xAltBackspaceClick(Sender: TObject);
begin
inc(AltBackSpaceCount);
end;
procedure TTestForm.xCtrlAClick(Sender: TObject);
begin
inc(ControlACount);
end;
procedure TTestForm.F8Click(Sender: TObject);
begin
inc(Function8Count);
end;
{ T_TGUITestCase }
procedure T_TGUITestCase.SetUp;
begin
inherited;
mForm := TTestForm.Create(nil);
ActionDelay := 10;
mForm.Show;
Application.ProcessMessages;
end;
procedure T_TGUITestCase.TearDown;
begin
mForm.Release;
Application.ProcessMessages;
inherited;
end;
procedure T_TGUITestCase.Test_IsFocused;
begin
fFailsOnNoChecksExecuted := False;
SetFocus(mForm.xButton);
Assert(not IsFocused(mForm.xButton2));
Assert(IsFocused(mForm.xButton));
end;
procedure T_TGUITestCase.Test_Sleep;
var before, after, diff : TDateTime;
begin
fFailsOnNoChecksExecuted := False;
AllowedMemoryLeakSize := 24;
before := Now;
Sleep(250);
after := Now;
Assert(after > before);
diff := after - before;
Assert(diff > 2.0e-6);
{ Sleep is done in EnterKeyInto }
ActionDelay := 125;
before := Now;
EnterKeyInto(mForm, ord('A'), []);
after := Now;
Assert(after > before);
diff := after - before;
Assert(diff > 2.0e-6);
end;
procedure T_TGUITestCase.Test_EnterKeyInto;
const VK_A = ord('A');
begin
fFailsOnNoChecksExecuted := False;
SetFocus(mForm.xButton);
{ Make sure:
focus shifts to the correct control
form key preview works
control gets the proper key(s)
works for TEdit, TButton, TMemo
}
{ Keys pressed: A }
EnterKeyInto(mForm.xEdit, VK_A, []);
Assert(mForm.xEdit.Text = 'a');
Assert(mForm.EditKeyDownCount = 1);
Assert(mForm.EditKeyUpCount = 1);
Assert(mForm.FormKeyDownCount = 1);
Assert(mForm.FormKeyUpCount = 1);
Assert(mForm.FormKeys = 'a');
{ Keys pressed: Shift, A }
mForm.ResetForm;
EnterKeyInto(mForm.xEdit, VK_A, [ssShift]);
Assert(mForm.xEdit.Text = 'A');
Assert(mForm.EditKeyDownCount = 1);
Assert(mForm.EditKeyUpCount = 1);
Assert(mForm.FormKeyDownCount = 1);
Assert(mForm.FormKeyUpCount = 1);
Assert(mForm.FormKeys = 'A');
{ Keys pressed: Shift, A }
mForm.ResetForm;
EnterKeyInto(mForm.xMemo, VK_A, [ssShift]);
Assert(mForm.xMemo.Text = 'A');
Assert(mForm.FormKeyDownCount = 1);
Assert(mForm.FormKeyUpCount = 1);
Assert(mForm.FormKeys = 'A');
{ Keys pressed: Shift, A }
mForm.ResetForm;
EnterKeyInto(mForm.xButton, VK_A, [ssShift]);
Assert(mForm.FormKeyDownCount = 1);
Assert(mForm.FormKeyUpCount = 1);
Assert(mForm.FormKeys = 'A');
{ Keys pressed : F8 }
mForm.ResetForm;
EnterKeyInto(mForm, VK_F8, []);
Assert(mForm.Function8Count = 1);
Assert(mForm.FormKeyDownCount = 0); { Keydown gets munched ?}
Assert(mForm.FormKeyUpCount = 1);
{ Keys pressed : Alt, Backspace }
mForm.ResetForm;
EnterKeyInto(mForm, VK_BACK, [ssAlt]);
Assert(mForm.AltBackspaceCount = 1);
{ Keys pressed : Ctrl, A }
mForm.ResetForm;
EnterKeyInto(mForm, VK_A, [ssCtrl]);
Assert(mForm.ControlACount = 1);
end;
procedure T_TGUITestCase.Test_EnterKey;
begin
fFailsOnNoChecksExecuted := False;
EnterKey(VK_F8);
{$IFNDEF DUNIT_CLX}
Assert(mForm.Function8Count = 1);
{$ENDIF}
SetFocus(mForm.xMemo);
EnterKey('M');
Assert(mForm.xMemo.Text = 'm');
SetFocus(mForm);
EnterKey(VK_F8);
{$IFNDEF DUNIT_CLX}
Assert(mForm.Function8Count = 2);
{$ENDIF}
end;
procedure T_TGUITestCase.Test_EnterTextInto;
const c_text = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ `1234567890-=~!@#$%^&*()_+[]{}\|;'':",./<>?';
begin
fFailsOnNoChecksExecuted := False;
EnterTextInto(mForm.xMemo, c_text);
Assert(mForm.xMemo.Text = c_text);
EnterTextInto(mForm.xEdit, c_text);
Assert(mForm.xEdit.Text = c_text);
end;
procedure T_TGUITestCase.Test_Tab;
begin
fFailsOnNoChecksExecuted := False;
Tab(2);
Assert(GetFocused = mForm.xButton3);
Tab(-1);
Assert(GetFocused = mForm.xButton2);
Tab(-1);
Assert(GetFocused = mForm.xButton);
end;
procedure T_TGUITestCase.Test_Form_Releases;
begin
AllowedMemoryLeakSize := 24;
Application.ProcessMessages;
Check(MForm.Enabled, 'Form should be enabled and release without leaking');
end;
{ TGUITestRunnerTests }
procedure TGUITestRunnerTests.SetUp;
begin
inherited;
FRunner := TGUITestRunner.Create(nil);
FRunner.Color := clWhite;
FRunner.Caption := 'This Form is being tested';
FRunner.Left := FRunner.Left + 200;
FRunner.Top := FRunner.Top + 100;
FRunner.Width := 300;
FRunner.Height := 480;
FRunner.AutoSaveAction.Checked := False;
FRunner.HideTestNodesOnOpenAction.Checked := False;
GUI := FRunner;
end;
procedure TGUITestRunnerTests.TearDown;
begin
GUI := nil;
FRunner.Free;
inherited;
end;
procedure TGUITestRunnerTests.TestTabOrder;
begin
fFailsOnNoChecksExecuted := False;
AllowedMemoryLeakSize := 24;
// need to set a test suite, or buttons will be disabled
FRunner.Suite := TFailuresTestCase.Suite;
FRunner.AutoSaveAction.Checked := False;
FRunner.BreakOnFailuresAction.Checked := False;
Show;
(*!! Actions are now in Toolbar
CheckFocused(FRunner.RunButton);
Tab;
CheckFocused(FRunner.CloseButton);
Tab;
*)
{$IFDEF DUNIT_CLX}
FRunner.SetFocusedControl(FRunner);
FRunner.TestTree.SetFocus;
{$ENDIF}
CheckFocused(FRunner.TestTree);
Tab;
CheckFocused(FRunner.ResultsView);
Tab;
CheckFocused(FRunner.FailureListView);
Tab;
{$IFNDEF DUNIT_CLX}
CheckFocused(FRunner.ErrorMessageRTF);
Tab;
{$ENDIF}
(*
CheckFocused(FRunner.RunButton);
Tab;
CheckTabTo('RunButton');
*)
end;
procedure TGUITestRunnerTests.RunEmptySuite;
begin
// no suite
Show;
{$IFDEF DUNIT_CLX}
FRunner.SetFocusedControl(FRunner);
FRunner.TestTree.SetFocus;
{$ENDIF}
CheckEquals(0, FRunner.ProgressBar.Position, 'progress bar');
CheckEqualsString('', FRunner.LbProgress.Caption, 'progress label');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[0], 'tests');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[1], 'run count');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[2], 'failure count');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[3], 'error count');
CheckEquals(0, FRunner.FailureListView.Items.Count, 'failure list');
EnterKey(vk_F9);
// nothing happens
CheckEquals(0, FRunner.ProgressBar.Position, 'progress bar');
CheckEqualsString('', FRunner.LbProgress.Caption, 'progress label');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[0], 'tests');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[1], 'run count');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[2], 'failure count');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[3], 'error count');
CheckEquals(0, FRunner.FailureListView.Items.Count, 'failure list');
EnterKey('X', [ssAlt]);
Check(not FRunner.Visible, 'form closed?');
end;
procedure TGUITestRunnerTests.RunSuccessSuite;
begin
FRunner.Suite := TSuccessTestCase.Suite;
FRunner.AutoSaveAction.Checked := False;
FRunner.BreakOnFailuresAction.Checked := False;
Show;
{$IFDEF DUNIT_CLX}
FRunner.SetFocusedControl(FRunner);
FRunner.TestTree.SetFocus;
{$ENDIF}
CheckEquals(0, FRunner.ProgressBar.Position, 'progress bar');
CheckEqualsString('', FRunner.LbProgress.Caption, 'progress label');
CheckEqualsString('2', FRunner.ResultsView.Items[0].SubItems[0], 'tests');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[1], 'run count');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[2], 'failure count');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[3], 'error count');
CheckEquals(0, FRunner.FailureListView.Items.Count, 'failure list');
EnterKey('R', [ssAlt]);
CheckEquals(2, FRunner.ProgressBar.Position, 'progress bar');
CheckEqualsString('100%', FRunner.LbProgress.Caption, 'progress label');
CheckEqualsString('2', FRunner.ResultsView.Items[0].SubItems[0], 'tests');
CheckEqualsString('2', FRunner.ResultsView.Items[0].SubItems[1], 'run count');
CheckEqualsString('0', FRunner.ResultsView.Items[0].SubItems[2], 'failure count');
CheckEqualsString('0', FRunner.ResultsView.Items[0].SubItems[3], 'error count');
CheckEquals(0, FRunner.FailureListView.Items.Count, 'failure list');
EnterKey('X', [ssAlt]);
Check(not FRunner.Visible, 'form closed?');
end;
procedure TGUITestRunnerTests.RunFailureSuite;
begin
FRunner.Suite := TFailuresTestCase.Suite;
FRunner.AutoSaveAction.Checked := False;
FRunner.BreakOnFailuresAction.Checked := False;
FRunner.FailIfNoChecksExecutedAction.Checked := False;
Show;
{$IFDEF DUNIT_CLX}
FRunner.SetFocusedControl(FRunner);
FRunner.TestTree.SetFocus;
{$ENDIF}
CheckEquals(0, FRunner.ProgressBar.Position, 'progress bar');
CheckEqualsString('', FRunner.LbProgress.Caption, 'progress label');
CheckEqualsString('4', FRunner.ResultsView.Items[0].SubItems[0], 'tests');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[1], 'run count');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[2], 'failure count');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[3], 'error count');
CheckEquals(0, FRunner.FailureListView.Items.Count, 'failure list');
EnterKey('R', [ssAlt]);
CheckEquals(4, FRunner.ProgressBar.Position, 'progress bar');
CheckEqualsString('25%', FRunner.LbProgress.Caption, 'progress label');
CheckEqualsString('4', FRunner.ResultsView.Items[0].SubItems[0], 'tests');
CheckEqualsString('4', FRunner.ResultsView.Items[0].SubItems[1], 'run count');
CheckEqualsString('2', FRunner.ResultsView.Items[0].SubItems[2], 'failure count');
CheckEqualsString('1', FRunner.ResultsView.Items[0].SubItems[3], 'error count');
CheckEquals(3, FRunner.FailureListView.Items.Count, 'failure list');
EnterKey('X', [ssAlt]);
Check(not FRunner.Visible, 'form closed?');
end;
procedure TGUITestRunnerTests.TestViewResult;
begin
FRunner.Suite := TFailuresTestCase.Suite;
FRunner.AutoSaveAction.Checked := False;
FRunner.BreakOnFailuresAction.Checked := False;
Show;
{$IFDEF DUNIT_CLX}
FRunner.SetFocusedControl(FRunner);
{$ENDIF}
FRunner.TestTree.SetFocus;
FRunner.TestTree.Items[0].Item[0].Selected := true;
FRunner.TestTree.Items[0].Item[0].Selected := true;
{$IFNDEF DUNIT_CLX}
EnterKey('D',[ssAlt]); //to uncheck node
{$ENDIF}
CheckEquals(0, FRunner.ProgressBar.Position, 'progress bar');
CheckEqualsString('', FRunner.LbProgress.Caption, 'progress label');
CheckEqualsString('4', FRunner.ResultsView.Items[0].SubItems[0], 'tests');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[1], 'run count');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[2], 'failure count');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[3], 'error count');
CheckEquals(0, FRunner.FailureListView.Items.Count, 'failure list');
end;
procedure TGUITestRunnerTests.TestElapsedTime;
var
ElapTime, MinTime, MaxTime: string;
begin
FRunner.Suite := TTimeTestCase.Suite;
FRunner.AutoSaveAction.Checked := False;
FRunner.BreakOnFailuresAction.Checked := False;
Show;
{$IFDEF DUNIT_CLX}
FRunner.SetFocusedControl(FRunner);
FRunner.TestTree.SetFocus;
{$ENDIF}
EnterKey(vk_F9);
ElapTime := FRunner.ResultsView.Items[0].SubItems[6];
MinTime := '0:00:00.070';
MaxTime := '0:00:00.300';
Check(ElapTime > MinTime, 'Test Time ('+ElapTime+') should be bigger than ' + MinTime);
Check(ElapTime < MaxTime, 'Test Time ('+ElapTime+') should be lesser than ' + MaxTime);
end;
procedure TGUITestRunnerTests.TestStatus;
const
{$IFDEF WIN32}
constLineDelim = #13#10;
{$ENDIF}
{$IFDEF LINUX}
constLineDelim = #10;
{$ENDIF}
constStatusTestStr =
'SecondSuccessWithStatus:' + constLineDelim
+ 'Line 1' + constLineDelim
+ 'Line 2' + constLineDelim
+ 'Line 3' + constLineDelim;
begin
SetAllowedLeakArray([288, 312]);
FRunner.Suite := TStatusTestCase.Suite;
FRunner.AutoSaveAction.Checked := False;
FRunner.BreakOnFailuresAction.Checked := False;
Show;
{$IFDEF DUNIT_CLX}
FRunner.SetFocusedControl(FRunner);
FRunner.TestTree.SetFocus;
{$ENDIF}
CheckEquals(0, FRunner.ProgressBar.Position, 'progress bar');
CheckEqualsString('', FRunner.LbProgress.Caption, 'progress label');
CheckEqualsString('2', FRunner.ResultsView.Items[0].SubItems[0], 'tests');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[1], 'run count');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[2], 'failure count');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[3], 'error count');
CheckEquals(0, FRunner.FailureListView.Items.Count, 'failure list');
{$IFNDEF DUNIT_CLX}
CheckEquals(0, FRunner.ErrorMessageRTF.Lines.Count, 'Status in ErrorMessageRTF');
{$ENDIF}
EnterKey('R', [ssAlt]);
CheckEquals(2, FRunner.ProgressBar.Position, 'progress bar');
CheckEqualsString('100%', FRunner.LbProgress.Caption, 'progress label');
CheckEqualsString('2', FRunner.ResultsView.Items[0].SubItems[0], 'tests');
CheckEqualsString('2', FRunner.ResultsView.Items[0].SubItems[1], 'run count');
CheckEqualsString('0', FRunner.ResultsView.Items[0].SubItems[2], 'failure count');
CheckEqualsString('0', FRunner.ResultsView.Items[0].SubItems[3], 'error count');
CheckEquals(0, FRunner.FailureListView.Items.Count, 'failure list');
{$IFNDEF DUNIT_CLX}
CheckEqualsString(constStatusTestStr, FRunner.ErrorMessageRTF.Lines.Text,
'Statustext in ErrorMessageRTF');
CheckEquals(4, FRunner.ErrorMessageRTF.Lines.Count, 'Status in ErrorMessageRTF');
{$ENDIF}
EnterKey('X', [ssAlt]);
Check(not FRunner.Visible, 'form closed?');
end;
procedure TGUITestRunnerTests.TestRunSelectedTestWithDecorator;
var
LTestSuite : ITest;
SuccessTest : ITest;
begin
SuccessTest := TSuccessTestCase.Suite;
LTestSuite := TRepeatedTest.Create( SuccessTest , 2);
FRunner.Suite := LTestSuite;
FRunner.AutoSaveAction.Checked := False;
FRunner.BreakOnFailuresAction.Checked := False;
Show;
{$IFDEF DUNIT_CLX}
FRunner.SetFocusedControl(FRunner);
FRunner.TestTree.SetFocus;
{$ENDIF}
CheckEquals(0, FRunner.ProgressBar.Position, 'progress bar');
CheckEqualsString('', FRunner.LbProgress.Caption, 'progress label');
CheckEqualsString('4', FRunner.ResultsView.Items[0].SubItems[0], 'tests');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[1], 'run count');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[2], 'failure count');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[3], 'error count');
CheckEquals(0, FRunner.FailureListView.Items.Count, 'failure list');
CheckEquals(1, FRunner.Suite.Tests.Count, 'Before Suite.Tests.Count');
CheckEquals(2, (FRunner.Suite.Tests[0] as ITest).Tests.Count, 'Before Suite.Tests[0].Tests.Count');
CheckEquals(4, FRunner.Suite.CountEnabledTestCases, 'Before CountEnabledTestCases');
CheckEquals(4, TDunitDialogCracker(FRunner).FTests.Count, 'Before testcount');
CheckSame(LTestSuite, FRunner.Suite, 'Before LTestSuite');
CheckSame(SuccessTest, FRunner.Suite.Tests[0], 'Before SuccesTest');
FRunner.TestTree.SetFocus;
CheckFocused(FRunner.TestTree);
EnterKeyInto(FRunner.TestTree, VK_END);
EnterKey(VK_F8);
CheckEquals(1, FRunner.ProgressBar.Position, 'After first progress bar');
CheckEqualsString('100%', FRunner.LbProgress.Caption, 'After first progress label');
CheckEqualsString('4', FRunner.ResultsView.Items[0].SubItems[0], 'After first tests');
CheckEqualsString('2', FRunner.ResultsView.Items[0].SubItems[1], 'After first run count');
CheckEqualsString('0', FRunner.ResultsView.Items[0].SubItems[2], 'After first failure count');
CheckEqualsString('0', FRunner.ResultsView.Items[0].SubItems[3], 'After first error count');
CheckEquals(0, FRunner.FailureListView.Items.Count, 'After first failure list');
CheckEquals(1, FRunner.Suite.Tests.Count, 'After first Suite.Tests.Count');
CheckEquals(2, (FRunner.Suite.Tests[0] as ITest).Tests.Count, 'After first Suite.Tests[0].Tests.Count');
CheckSame(LTestSuite, FRunner.Suite, 'After first LTestSuite');
CheckSame(SuccessTest, FRunner.Suite.Tests[0], 'After first SuccesTest');
CheckEquals(4, FRunner.Suite.CountEnabledTestCases, 'After first CountEnabledTestCases');
CheckEquals(4, TDunitDialogCracker(FRunner).FTests.Count, 'After first testcount');
CheckFocused(FRunner.TestTree);
// Second time could generate an pointer error
EnterKeyInto(FRunner.TestTree, VK_F8);
CheckEquals(1, FRunner.ProgressBar.Position, 'After second progress bar');
CheckEqualsString('100%', FRunner.LbProgress.Caption, 'After second progress label');
CheckEqualsString('4', FRunner.ResultsView.Items[0].SubItems[0], 'After second tests');
CheckEqualsString('2', FRunner.ResultsView.Items[0].SubItems[1], 'After second run count');
CheckEqualsString('0', FRunner.ResultsView.Items[0].SubItems[2], 'After second failure count');
CheckEqualsString('0', FRunner.ResultsView.Items[0].SubItems[3], 'After second error count');
CheckEquals(0, FRunner.FailureListView.Items.Count, 'After second failure list');
CheckEquals(4, FRunner.Suite.CountEnabledTestCases, 'After second CountEnabledTestCases');
CheckEquals(4, TDunitDialogCracker(FRunner).FTests.Count, 'testcount');
// Normal test after single test. Should run all enabled tests.
EnterKeyInto(FRunner.TestTree, VK_F9);
CheckEquals(4, FRunner.ProgressBar.Position, 'Normal after progress bar');
CheckEqualsString('100%', FRunner.LbProgress.Caption, 'Normal after progress label');
CheckEqualsString('4', FRunner.ResultsView.Items[0].SubItems[0], 'Normal after tests');
CheckEqualsString('4', FRunner.ResultsView.Items[0].SubItems[1], 'Normal after run count');
CheckEqualsString('0', FRunner.ResultsView.Items[0].SubItems[2], 'Normal after failure count');
CheckEqualsString('0', FRunner.ResultsView.Items[0].SubItems[3], 'Normal after error count');
CheckEquals(0, FRunner.FailureListView.Items.Count, 'Normal after failure list');
CheckEquals(4, FRunner.Suite.CountEnabledTestCases, 'Normal after CountEnabledTestCases');
CheckEquals(4, TDunitDialogCracker(FRunner).FTests.Count, 'Normal after testcount');
EnterKey('X', [ssAlt]);
Check(not FRunner.Visible, 'form closed?');
end;
procedure TGUITestRunnerTests.TestRunSelectedTestWithSetupDecorator;
var LTestSuite : TSetupTestCase;
ITestSuite : ITest;
SuccessTest : ITest;
begin
SuccessTest := TSuccessTestCase.Suite;
LTestSuite := TSetupTestCase.Create( SuccessTest);
ITestSuite := LTestSuite;
FRunner.Suite := ITestSuite;
FRunner.AutoSaveAction.Checked := False;
FRunner.BreakOnFailuresAction.Checked := False;
Show;
{$IFDEF DUNIT_CLX}
FRunner.SetFocusedControl(FRunner);
FRunner.TestTree.SetFocus;
{$ENDIF}
CheckEquals(0, FRunner.ProgressBar.Position, 'progress bar');
CheckEqualsString('', FRunner.LbProgress.Caption, 'progress label');
CheckEqualsString('2', FRunner.ResultsView.Items[0].SubItems[0], 'tests');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[1], 'run count');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[2], 'failure count');
CheckEqualsString('', FRunner.ResultsView.Items[0].SubItems[3], 'error count');
CheckEquals(0, FRunner.FailureListView.Items.Count, 'failure list');
CheckEquals(1, FRunner.Suite.Tests.Count, 'Before Suite.Tests.Count');
CheckEquals(2, (FRunner.Suite.Tests[0] as ITest).Tests.Count, 'Before Suite.Tests[0].Tests.Count');
CheckEquals(2, FRunner.Suite.CountEnabledTestCases, 'Before CountEnabledTestCases');
CheckEquals(4, TDunitDialogCracker(FRunner).FTests.Count, 'Before testcount');
CheckEquals(0, LTestSuite.FSetupCount, 'Before SetupCount');
CheckEquals(0, LTestSuite.FTearDownCount, 'Before TearDownCount');
FRunner.TestTree.SetFocus;
CheckFocused(FRunner.TestTree);
EnterKeyInto(FRunner.TestTree, VK_END);
EnterKey(VK_F8);
CheckEquals(1, FRunner.ProgressBar.Position, 'After first progress bar');
CheckEqualsString('100%', FRunner.LbProgress.Caption, 'After first progress label');
CheckEqualsString('2', FRunner.ResultsView.Items[0].SubItems[0], 'After first tests');
CheckEqualsString('1', FRunner.ResultsView.Items[0].SubItems[1], 'After first run count');
CheckEqualsString('0', FRunner.ResultsView.Items[0].SubItems[2], 'After first failure count');
CheckEqualsString('0', FRunner.ResultsView.Items[0].SubItems[3], 'After first error count');
CheckEquals(0, FRunner.FailureListView.Items.Count, 'After first failure list');
CheckEquals(1, FRunner.Suite.Tests.Count, 'After first Suite.Tests.Count');
CheckEquals(2, (FRunner.Suite.Tests[0] as ITest).Tests.Count, 'After first Suite.Tests[0].Tests.Count');
CheckEquals(2, FRunner.Suite.CountEnabledTestCases, 'After first CountEnabledTestCases');
CheckEquals(4, TDunitDialogCracker(FRunner).FTests.Count, 'After first testcount');
CheckEquals(1, LTestSuite.FSetupCount, 'After first SetupCount');
CheckEquals(1, LTestSuite.FTearDownCount, 'After first TearDownCount');
CheckFocused(FRunner.TestTree);
// Second time could generate a pointer error
EnterKeyInto(FRunner.TestTree, VK_F8);
CheckEquals(1, FRunner.ProgressBar.Position, 'After second progress bar');
CheckEqualsString('100%', FRunner.LbProgress.Caption, 'After second progress label');
CheckEqualsString('2', FRunner.ResultsView.Items[0].SubItems[0], 'After second tests');
CheckEqualsString('1', FRunner.ResultsView.Items[0].SubItems[1], 'After second run count');
CheckEqualsString('0', FRunner.ResultsView.Items[0].SubItems[2], 'After second failure count');
CheckEqualsString('0', FRunner.ResultsView.Items[0].SubItems[3], 'After second error count');
CheckEquals(0, FRunner.FailureListView.Items.Count, 'After second failure list');
CheckEquals(2, FRunner.Suite.CountEnabledTestCases, 'After second CountEnabledTestCases');
CheckEquals(4, TDunitDialogCracker(FRunner).FTests.Count, 'testcount');
CheckEquals(2, LTestSuite.FSetupCount, 'After second SetupCount');
CheckEquals(2, LTestSuite.FTearDownCount, 'After second TearDownCount');
// Normal test after single test. Should run all enabled tests.
EnterKeyInto(FRunner.TestTree, VK_F9);
CheckEquals(2, FRunner.ProgressBar.Position, 'Normal after progress bar');
CheckEqualsString('100%', FRunner.LbProgress.Caption, 'Normal after progress label');
CheckEqualsString('2', FRunner.ResultsView.Items[0].SubItems[0], 'Normal after tests');
CheckEqualsString('2', FRunner.ResultsView.Items[0].SubItems[1], 'Normal after run count');
CheckEqualsString('0', FRunner.ResultsView.Items[0].SubItems[2], 'Normal after failure count');
CheckEqualsString('0', FRunner.ResultsView.Items[0].SubItems[3], 'Normal after error count');
CheckEquals(0, FRunner.FailureListView.Items.Count, 'Normal after failure list');
CheckEquals(2, FRunner.Suite.CountEnabledTestCases, 'Normal after CountEnabledTestCases');
CheckEquals(4, TDunitDialogCracker(FRunner).FTests.Count, 'Normal after testcount');
CheckEquals(3, LTestSuite.FSetupCount, 'Normal after SetupCount');
CheckEquals(3, LTestSuite.FTearDownCount, 'Normal after TearDownCount');
EnterKey('X', [ssAlt]);
Check(not FRunner.Visible, 'form closed?');
if ITestSuite <> nil then
ITestSuite := nil;
end;
{$IFNDEF DUNIT_CLX}
procedure TGUITestRunnerTests.TestGoToPrevNextSelectedNode;
begin
FRunner.Suite := TSuccessTestCase.Suite;
Show;
FRunner.TestTree.SetFocus;
Check(FRunner.TestTree.Selected = FRunner.TestTree.Items[0], 'ensure starting at root node');
FRunner.GoToNextSelectedTestAction.Execute;
Check(FRunner.TestTree.Selected = FRunner.TestTree.Items[1], 'testing from non-test to next test node');
FRunner.GoToNextSelectedTestAction.Execute;
Check(FRunner.TestTree.Selected = FRunner.TestTree.Items[2], 'testing test node to next test node');
FRunner.GoToNextSelectedTestAction.Execute;
Check(FRunner.TestTree.Selected = FRunner.TestTree.Items[2], 'testing the end of the line, next should stay put');
FRunner.GoToPrevSelectedTestAction.Execute;
Check(FRunner.TestTree.Selected = FRunner.TestTree.Items[1], 'testing test to prev test');
FRunner.GoToPrevSelectedTestAction.Execute;
Check(FRunner.TestTree.Selected = FRunner.TestTree.Items[1], 'beg of the line, prev should stay put');
end;
{$ENDIF}
procedure TGUITestRunnerTests.Test_BooleanEvalOff;
begin
{ this test makes sure boolean evals short circuit }
fFailsOnNoChecksExecuted := False;
//Added because the test leaks memory.
AllowedMemoryLeakSize := 288;
{$BOOLEVAL OFF}
TestOr(true, false);
Assert(mRefCountA = 1);
Assert(mRefCountB = 0);
TestOr(true, true);
Assert(mRefCountA = 1);
Assert(mRefCountB = 0);
TestOr(false, true);
Assert(mRefCountA = 1);
Assert(mRefCountB = 1);
TestOr(false, false);
Assert(mRefCountA = 1);
Assert(mRefCountB = 1);
TestAnd(false, false);
Assert(mRefCountA = 1);
Assert(mRefCountB = 0);
TestAnd(true, false);
Assert(mRefCountA = 1);
Assert(mRefCountB = 1);
TestAnd(true, true);
Assert(mRefCountA = 1);
Assert(mRefCountB = 1);
TestAnd(false, true);
Assert(mRefCountA = 1);
Assert(mRefCountB = 0);
end;
function TGUITestRunnerTests.TestA(const ReturnValue: boolean): boolean;
begin
inc(mRefCountA);
Result := ReturnValue;
end;
procedure TGUITestRunnerTests.TestAnd(const A, B: boolean);
begin
mRefCountA := 0;
mRefCountB := 0;
if TestA(a) and TestB(b) then
begin
end;
end;
function TGUITestRunnerTests.TestB(const ReturnValue: boolean): boolean;
begin
inc(mRefCountB);
Result := ReturnValue;
end;
procedure TGUITestRunnerTests.TestOr(const A, B: boolean);
begin
mRefCountA := 0;
mRefCountB := 0;
if TestA(a) or TestB(b) then
begin
end;
end;
{ TSuccessTestCase }
procedure TSuccessTestCase.OneSuccess;
begin
check(true);
end;
procedure TSuccessTestCase.SecondSuccess;
begin
check(true);
end;
{ TFailuresTestCase }
procedure TFailuresTestCase.OneSuccess;
begin
DoNothing;
end;
procedure TFailuresTestCase.OneError;
begin
raise EAbort.Create('One Error');
end;
procedure TFailuresTestCase.OneFailure;
begin
fail('One failure');
end;
procedure TFailuresTestCase.SecondFailure;
begin
fail('Second failure');
end;
procedure TFailuresTestCase.DoNothing;
begin
// Do Nothing
end;
{ TTimeTestCase }
procedure TTimeTestCase.TestTime;
const
DELAY = 100;
begin
Sleep(DELAY);
Check( True );
end;
{ TStatusTestCase }
procedure TStatusTestCase.OneSuccessWithStatus;
begin
Status('Line 1');
Status('Line 2');
Status('Line 3');
end;
procedure TStatusTestCase.SecondSuccessWithStatus;
begin
Status('Line 1');
Sleep(200);
Status('Line 2');
Sleep(200);
Status('Line 3');
Sleep(200);
end;
procedure TStatusTestCase.SetUp;
begin
inherited;
FailsOnNoChecksExecuted := False;
FailsOnMemoryLeak := False;
end;
{ TSetupTestCase }
procedure TSetupTestCase.AfterConstruction;
begin
inherited;
FSetupCount := 0;
FTearDownCount := 0;
end;
procedure TSetupTestCase.SetUp;
begin
inherited;
inc(FSetupCount)
end;
procedure TSetupTestCase.TearDown;
begin
inherited;
inc(FTearDownCount)
end;
initialization
RegisterTests('', [T_TGUITestCase.Suite]);
RegisterTests('GUI Tests', [TGUITestRunnerTests.Suite]);
end.
|
unit uActiveDirectory;
interface
uses
{$IF CompilerVersion > 22}
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
{$ELSE}
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls,
{$IFEND}
CNClrLib.Control.EnumTypes, CNClrLib.Control.Base,
CNClrLib.Component.DirectorySearcher, CNClrLib.Component.DirectoryEntry;
type
TfrmAD = class(TForm)
grpForm: TGroupBox;
GroupBox2: TGroupBox;
GroupBox3: TGroupBox;
GroupBox4: TGroupBox;
Label1: TLabel;
txtUsername: TEdit;
txtPassword: TEdit;
Label2: TLabel;
txtAddress: TEdit;
Label3: TLabel;
txtSearchUser: TEdit;
Label4: TLabel;
btnSearchUserName: TButton;
lblUsernameDisplay: TLabel;
lblFirstname: TLabel;
lblCity: TLabel;
lblMiddleName: TLabel;
lblLastName: TLabel;
lblCompany: TLabel;
lblTitle: TLabel;
lblEmailId: TLabel;
lblState: TLabel;
lblCountry: TLabel;
lblPostal: TLabel;
lblTelephone: TLabel;
pnlBlock: TPanel;
CnDirectorySearcher1: TCnDirectorySearcher;
CnDirectoryEntry1: TCnDirectoryEntry;
GroupBox1: TGroupBox;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
txtFirstName: TEdit;
txtMiddleName: TEdit;
txtLastName: TEdit;
btnCommitChanges: TButton;
btnClearValues: TButton;
procedure btnSearchUserNameClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnClearValuesClick(Sender: TObject);
procedure btnCommitChangesClick(Sender: TObject);
private
FModifySearchResult: _SearchResult;
function GetSystemDomain: String;
procedure GetUserInformation(UserName, Password, Domain: String);
procedure ShowUserInformation(SearchResult: _SearchResult);
procedure DoInitialiseDirectorySearch(UserName, Password, Domain: String);
function SearchUserByUserName(UserName: String): _SearchResult;
function SearchUserByEmail(Email: String): _SearchResult;
procedure SetUpdateUserInfoValues(SearchResult: _SearchResult);
procedure SetEnabledUpdateUserInfoCtrls(AEnabled: Boolean);
public
{ Public declarations }
end;
var
frmAD: TfrmAD;
implementation
{$R *.dfm}
uses CNClrLib.Host, CNClrLib.DirectoryServices;
procedure TfrmAD.btnClearValuesClick(Sender: TObject);
begin
lblUsernameDisplay.Caption := '';
lblFirstname.Caption := '';
lblMiddleName.Caption := '';
lblLastName.Caption := '';
lblEmailId.Caption := '';
lblTitle.Caption := '';
lblCompany.Caption := '';
lblCity.Caption := '';
lblState.Caption := '';
lblCountry.Caption := '';
lblPostal.Caption := '';
lblTelephone.Caption := '';
SetUpdateUserInfoValues(nil);
end;
procedure TfrmAD.btnCommitChangesClick(Sender: TObject);
var
directoryEntryIntf: _DirectoryEntry;
begin
if FModifySearchResult <> nil then
begin
directoryEntryIntf := FModifySearchResult.GetDirectoryEntry();
directoryEntryIntf.Properties['givenName'].Value := txtFirstName.Text;
directoryEntryIntf.Properties['initials'].Value := txtMiddleName.Text;
directoryEntryIntf.Properties['sn'].Value := txtLastName.Text;
directoryEntryIntf.CommitChanges;
end;
end;
procedure TfrmAD.btnSearchUserNameClick(Sender: TObject);
begin
if (Trim(txtAddress.Text) <> '') and (Trim(txtSearchUser.Text) <> '') then
begin
GetUserInformation(Trim(txtUsername.Text), Trim(txtPassword.Text), Trim(txtAddress.Text));
end
else
begin
TClrMessageBox.Show('Please specify both the domain and search entries.', 'Missing Information', TMessageBoxButtons.mbbsOK, TMessageBoxIcon.mbiInformation);
end;
end;
procedure TfrmAD.DoInitialiseDirectorySearch(UserName, Password,
Domain: String);
begin
CnDirectoryEntry1.Path := 'LDAP://' + domain;
CnDirectoryEntry1.Username := txtUsername.Text;
CnDirectoryEntry1.Password := txtPassword.Text;
CnDirectorySearcher1.SearchRoot := CnDirectoryEntry1;
end;
procedure TfrmAD.FormShow(Sender: TObject);
begin
txtUsername.SetFocus;
btnSearchUserName.SetFocus;
txtAddress.Text := GetSystemDomain();
end;
function TfrmAD.GetSystemDomain: String;
begin
try
Result := LowerCase(CoDomainHelper.CreateInstance.GetComputerDomain.ToString);
except
Result := '';
end;
end;
procedure TfrmAD.GetUserInformation(UserName, Password, Domain: String);
var
rs: _SearchResult;
begin
Cursor := crHourGlass;
try
DoInitialiseDirectorySearch(UserName, Password, Domain);
if Pos('@', Trim(txtSearchUser.Text)) > 0 then
rs := SearchUserByEmail(Trim(txtSearchUser.Text))
else
rs := SearchUserByUserName(Trim(txtSearchUser.Text));
if rs <> nil then
ShowUserInformation(rs)
else
TClrMessageBox.Show('User not found!!!', 'Search Information', TMessageBoxButtons.mbbsOK, TMessageBoxIcon.mbiInformation);
SetUpdateUserInfoValues(rs);
finally
Cursor := crDefault;
end;
end;
function TfrmAD.SearchUserByEmail(Email: String): _SearchResult;
begin
CnDirectorySearcher1.Filter := '(&((&(objectCategory=Person)(objectClass=User)))(mail=' + email + '))';
CnDirectorySearcher1.SearchScope := TSearchScope.ssSubtree;
CnDirectorySearcher1.ServerTimeLimit := '00:01:30';//90seconds in hh:mm:ss;
Result := CnDirectorySearcher1.FindOne;
end;
function TfrmAD.SearchUserByUserName(UserName: String): _SearchResult;
begin
CnDirectorySearcher1.Filter := '(&((&(objectCategory=Person)(objectClass=User)))(samaccountname=' + username + '))';
CnDirectorySearcher1.SearchScope := TSearchScope.ssSubtree;
CnDirectorySearcher1.ServerTimeLimit := '00:01:30';//90seconds in hh:mm:ss;
Result := CnDirectorySearcher1.FindOne;
end;
procedure TfrmAD.SetEnabledUpdateUserInfoCtrls(AEnabled: Boolean);
begin
txtFirstName.Enabled := AEnabled;
txtMiddleName.Enabled := AEnabled;
txtLastName.Enabled := AEnabled;
end;
procedure TfrmAD.SetUpdateUserInfoValues(SearchResult: _SearchResult);
var
directoryEntryIntf: _DirectoryEntry;
begin
txtFirstName.Text := '';
txtMiddleName.Text := '';
txtLastName.Text := '';
FModifySearchResult := SearchResult;
if FModifySearchResult <> nil then
begin
directoryEntryIntf := FModifySearchResult.GetDirectoryEntry();
if directoryEntryIntf.Properties['givenName'].Value <> null then
txtFirstName.Text := directoryEntryIntf.Properties['givenName'].Value;
if (directoryEntryIntf.Properties['initials'].Value <> null) then
txtMiddleName.Text := directoryEntryIntf.Properties['initials'].Value;
if (directoryEntryIntf.Properties['sn'].Value <> null) then
txtLastName.Text := directoryEntryIntf.Properties['sn'].Value;
end;
SetEnabledUpdateUserInfoCtrls(FModifySearchResult <> nil);
end;
procedure TfrmAD.ShowUserInformation(SearchResult: _SearchResult);
var
directoryEntryIntf: _DirectoryEntry;
begin
directoryEntryIntf := SearchResult.GetDirectoryEntry();
if (directoryEntryIntf.Properties['samaccountname'].Value <> null) then
lblUsernameDisplay.Caption := 'Username : ' + directoryEntryIntf.Properties['samaccountname'].Value;
if (directoryEntryIntf.Properties['givenName'].Value <> null) then
lblFirstname.Caption := 'First Name : ' + directoryEntryIntf.Properties['givenName'].Value;
if (directoryEntryIntf.Properties['initials'].Value <> null) then
lblMiddleName.Caption := 'Middle Name : ' + directoryEntryIntf.Properties['initials'].Value;
if (directoryEntryIntf.Properties['sn'].Value <> null) then
lblLastName.Caption := 'Last Name : ' + directoryEntryIntf.Properties['sn'].Value;
if (directoryEntryIntf.Properties['mail'].Value <> null) then
lblEmailId.Caption := 'Email ID : ' + directoryEntryIntf.Properties['mail'].Value;
if (directoryEntryIntf.Properties['title'].Value <> null) then
lblTitle.Caption := 'Title : ' + directoryEntryIntf.Properties['title'].Value;
if (directoryEntryIntf.Properties['company'].Value <> null) then
lblCompany.Caption := 'Company : ' + directoryEntryIntf.Properties['company'].Value;
if (directoryEntryIntf.Properties['l'].Value <> null) then
lblCity.Caption := 'City : ' + directoryEntryIntf.Properties['l'].Value;
if (directoryEntryIntf.Properties['st'].Value <> null) then
lblState.Caption := 'State : ' + directoryEntryIntf.Properties['st'].Value;
if (directoryEntryIntf.Properties['co'].Value <> null) then
lblCountry.Caption := 'Country : ' + directoryEntryIntf.Properties['co'].Value;
if (directoryEntryIntf.Properties['postalCode'].Value <> null) then
lblPostal.Caption := 'Postal Code : ' + directoryEntryIntf.Properties['postalCode'].Value;
if (directoryEntryIntf.Properties['telephoneNumber'].Value <> null) then
lblTelephone.Caption := 'Telephone No. : ' + directoryEntryIntf.Properties['telephoneNumber'].Value;
end;
end.
|
unit ZUtil;
(************************************************************************
Configuration dependent utility and debugging function
Copyright (C) 1998 by Jacques Nomssi Nzali
For conditions of distribution and use, see copyright notice in readme.txt
------------------------------------------------------------------------
Modifications by W.Ehrhardt:
Feb 2002
- moved type declarations to ZLibH
- Source code reformating/reordering
- "const" strings in debug function
- make code work under BP7/DPMI&Win
- removed $ifdef CALLDOS
- constant C_NL used in Trace calls for leading newline
Mar 2005
- Code cleanup for WWW upload
May 2005
- Trace: no writeln
- Assert moved to zlibh
Sep 2008
- Avoid write for WIN32 GUI debug code (use OutputDebugString/MessageBox)
Jul 2009
- D12 fixes
*************************************************************************)
interface
{$x+}
{$I zconf.inc}
uses
{$ifdef debug}
{$ifdef WIN32}
windows, {must be listed in interface and before ZLibH}
{otherwise some type related problems will be occur}
{$endif}
{$endif}
ZLibH;
procedure zmemcpy(destp: pBytef; sourcep: pBytef; len: uInt);
function zmemcmp(s1p, s2p: pBytef; len: uInt): int;
procedure zmemzero(destp: pBytef; len: uInt);
procedure zcfree(opaque: voidpf; ptr: voidpf);
function zcalloc(opaque: voidpf; items: uInt; size: uInt): voidpf;
{Original: C macros}
function Z_ALLOC(var strm: z_stream; items: uInt; size: uInt): voidpf;
procedure Z_FREE(var strm: z_stream; ptr: voidpf);
procedure TRY_FREE(var strm: z_stream; ptr: voidpf);
{$ifdef debug}
{Debug functions}
procedure z_error(const m: str255);
procedure Trace(const x: str255);
procedure Tracev(const x: str255);
procedure Tracevv(const x: str255);
procedure Tracevvv(const x: str255);
procedure Tracec(c: boolean; const x: str255);
procedure Tracecv(c: boolean; const x: str255);
function IntToStr(value: longint): str255;
{$endif}
implementation
{$ifdef ver80}
{$define Delphi16}
{$endif}
{$undef DPMI_OR_WIN}
{$ifdef ver70}
{$define HugeMem}
{$ifdef DPMI}
{$define DPMI_OR_WIN}
{$undef HugeMem} {*we 0202}
{$endif}
{$ifdef WINDOWS}
{$define DPMI_OR_WIN}
{$undef HugeMem} {*we 0202}
{$endif}
{$endif}
{$ifdef ver60}
{$define HugeMem}
{$endif}
{$ifdef Delphi16}
uses
WinTypes,
WinProcs;
{$endif}
{$ifndef FPC}
{$ifdef DPMI_OR_WIN}
uses
WinAPI;
{$endif}
{$endif}
{$ifdef HugeMem}
{$define HEAP_LIST}
{$endif}
{$ifdef HEAP_LIST}
const
MaxAllocEntries = 50;
{Allocation record which stores size of block for use with free}
type
TMemRec = record
orgvalue,
value: pointer;
size: longint;
end;
const
allocatedCount: 0..MaxAllocEntries = 0;
var
allocatedList: array[0..MaxAllocEntries-1] of TMemRec;
{---------------------------------------------------------------------------}
function NewAllocation(ptr0, ptr: pointer; memsize: longint): boolean;
begin
if (allocatedCount<MaxAllocEntries) and (ptr0<>nil) then begin
with allocatedList[allocatedCount] do begin
orgvalue := ptr0;
value := ptr;
size := memsize;
end;
inc(allocatedCount); {we don't check for duplicate}
NewAllocation := true;
end
else NewAllocation := false;
end;
{$endif}
{$ifdef HugeMem}
{we: It seems that Jacques Nomssi Nzali used parts of Duncan Murdoch's
contribution to MEMORY.SWG from SWAG for real mode.
Credits to dmurdoch@mast.queensu.ca (Duncan Murdoch)}
{The code below is extremely version specific to the TP 6/7 heap manager!!}
type
LH = record
L, H: word;
end;
type
PFreeRec = ^TFreeRec;
TFreeRec = record
next: PFreeRec;
size: pointer;
end;
type
HugePtr = voidpf;
{---------------------------------------------------------------------------}
procedure IncPtr(var p: pointer; count: word);
{-Increments pointer}
begin
inc(LH(p).L,count);
if LH(p).L < count then inc(LH(p).H,SelectorInc);
end;
{---------------------------------------------------------------------------}
function Normalized(p: pointer): pointer;
var
count: word;
begin
count := LH(p).L and $FFF0;
Normalized := ptr(LH(p).H + (count shr 4), LH(p).L and $F);
end;
{---------------------------------------------------------------------------}
procedure FreeHuge(var p: HugePtr; size: longint);
const
blocksize = $FFF0;
var
block: word;
begin
while size>0 do begin
{block := minimum(size, blocksize);}
if size > blocksize then block := blocksize else block := size;
dec(size,block);
FreeMem(p,block);
IncPtr(p,block); {we may get ptr($xxxx, $fff8) and 31 bytes left}
p := Normalized(p); {to free, so we must normalize}
end;
end;
{---------------------------------------------------------------------------}
function FreeMemHuge(ptr: pointer): boolean;
var
i: integer; {-1..MaxAllocEntries}
begin
FreeMemHuge := false;
i := allocatedCount - 1;
while i>=0 do begin
if ptr=allocatedList[i].value then begin
with allocatedList[i] do FreeHuge(orgvalue, size);
Move(allocatedList[i+1], allocatedList[i], sizeof(TMemRec)*(allocatedCount - 1 - i));
dec(allocatedCount);
FreeMemHuge := true;
break;
end;
dec(i);
end;
end;
{---------------------------------------------------------------------------}
procedure GetMemHuge(var p: HugePtr; memsize: longint);
const
blocksize = $FFF0;
var
size: longint;
prev,free: PFreeRec;
save,temp: pointer;
block: word;
begin
p := nil;
{Handle the easy cases first}
if memsize > MaxAvail then exit
else if memsize <= blocksize then begin
GetMem(p, memsize);
if not NewAllocation(p, p, memsize) then begin
FreeMem(p, memsize);
p := nil;
end;
end
else begin
size := memsize + 15;
{Find the block that has enough space}
prev := PFreeRec(@FreeList);
free := prev^.next;
while (free <> HeapPtr) and (ptr2int(free^.size) < size) do begin
prev := free;
free := prev^.next;
end;
{Now free points to a region with enough space; make it the first one and
multiple allocations will be contiguous.}
save := FreeList;
FreeList := free;
{In TP 6, this works; check against other heap managers}
while size > 0 do begin
{block := minimum(size, blocksize);}
if size > blocksize then block := blocksize else block := size;
dec(size,block);
GetMem(temp,block);
end;
{We've got what we want now; just sort things out and restore the
free list to normal}
p := free;
if prev^.next <> FreeList then begin
prev^.next := FreeList;
FreeList := save;
end;
if p<>nil then begin
{return pointer with 0 offset}
temp := p;
if Ofs(p^)<>0 then p := ptr(seg(p^)+1,0); {hack}
if not NewAllocation(temp, p, memsize + 15) then begin
FreeHuge(temp, size);
p := nil;
end;
end;
end;
end;
{$endif}
{---------------------------------------------------------------------------}
procedure zmemcpy(destp: pBytef; sourcep: pBytef; len: uInt);
begin
Move(sourcep^, destp^, len);
end;
{---------------------------------------------------------------------------}
function zmemcmp(s1p, s2p: pBytef; len: uInt): int;
var
j: uInt;
source,
dest: pBytef;
begin
source := s1p;
dest := s2p;
for j := 0 to pred(len) do begin
if source^<>dest^ then begin
zmemcmp := 2*ord(source^ > dest^)-1;
exit;
end;
inc(source);
inc(dest);
end;
zmemcmp := 0;
end;
{---------------------------------------------------------------------------}
procedure zmemzero(destp: pBytef; len: uInt);
begin
fillchar(destp^, len, 0);
end;
{---------------------------------------------------------------------------}
procedure zcfree(opaque: voidpf; ptr: voidpf);
{$ifdef Delphi16}
var
Handle: THandle;
{$endif}
{$ifdef FPC}
var
memsize: uint;
{$endif}
begin
{$ifdef DPMI_OR_WIN}
GlobalFreePtr(ptr);
{$else}
{$ifdef HugeMem}
FreeMemHuge(ptr);
{$else}
{$ifdef Delphi16}
Handle := GlobalHandle(HiWord(longint(ptr)));
GlobalUnLock(Handle);
GlobalFree(Handle);
{$else}
{$ifdef FPC}
dec(puIntf(ptr));
memsize := puIntf(ptr)^;
FreeMem(ptr, memsize+sizeof(uInt));
{$else}
FreeMem(ptr); {Delphi 2,3,4}
{$endif}
{$endif}
{$endif}
{$endif}
end;
{---------------------------------------------------------------------------}
function zcalloc(opaque: voidpf; items: uInt; size: uInt): voidpf;
var
p: voidpf;
memsize: uLong;
{$ifdef Delphi16}
handle: THandle;
{$endif}
begin
memsize := uLong(items) * uLong(size);
{$ifdef DPMI_OR_WIN}
p := GlobalAllocPtr(gmem_moveable, memsize);
{$else}
{$ifdef HugeMem}
GetMemHuge(p, memsize);
{$else}
{$ifdef Delphi16}
Handle := GlobalAlloc(HeapAllocFlags, memsize);
p := GlobalLock(Handle);
{$else}
{$ifdef FPC}
GetMem(p, memsize+sizeof(uInt));
puIntf(p)^:= memsize;
inc(puIntf(p));
{$else}
GetMem(p, memsize); {Delphi: p := AllocMem(memsize);}
{$endif}
{$endif}
{$endif}
{$endif}
zcalloc := p;
end;
{---------------------------------------------------------------------------}
function Z_ALLOC(var strm: z_stream; items: uInt; size: uInt): voidpf;
begin
Z_ALLOC := strm.zalloc(strm.opaque, items, size);
end;
{---------------------------------------------------------------------------}
procedure Z_FREE(var strm: z_stream; ptr: voidpf);
begin
strm.zfree(strm.opaque, ptr);
end;
{---------------------------------------------------------------------------}
procedure TRY_FREE(var strm: z_stream; ptr: voidpf);
begin
{if @strm <> Z_NULL then}
strm.zfree(strm.opaque, ptr);
end;
{$ifdef debug}
{$ifdef WIN32}
{$ifdef Unicode}
{---------------------------------------------------------------------------}
procedure z_error(const m: str255);
var
ax: string;
begin
if IsConsole then begin
writeLn(output, m);
write('Zlib - Halt...');
readLn;
end
else
begin
ax := 'Zlib - Halt: '+string(m);
MessageBox(0, PChar(ax), 'Error', MB_OK);
end;
halt(1);
end;
{---------------------------------------------------------------------------}
procedure Trace(const x: str255);
var
ax: string;
ls: integer;
begin
{$ifndef WIN32_USE_ODS}
if IsConsole then begin
write(x);
exit;
end;
{$endif}
{strip #13#10 from debug string}
ax := string(x);
ls := length(ax);
if (ls>1) and (ax[ls]=#10) and (ax[ls-1]=#13) then dec(ls,2);
ax := copy(ax,1,ls);
OutputDebugString(PChar(ax));
end;
{$else}
{---------------------------------------------------------------------------}
procedure z_error(const m: str255);
var
ax: ansistring;
begin
if IsConsole then begin
writeLn(output, m);
write('Zlib - Halt...');
readLn;
end
else
begin
ax := 'Zlib - Halt: '+m;
MessageBox(0, PChar8(ax), 'Error', MB_OK);
end;
halt(1);
end;
{---------------------------------------------------------------------------}
procedure Trace(const x: str255);
var
ax: ansistring;
ls: integer;
begin
{$ifndef WIN32_USE_ODS}
if IsConsole then begin
write(x);
exit;
end;
{$endif}
{strip #13#10 from debug string}
ls := length(x);
if (ls>1) and (x[ls]=#10) and (x[ls-1]=#13) then dec(ls,2);
ax := copy(x,1,ls);
OutputDebugString(PChar8(ax));
end;
{$endif}
{$else}
{---------------------------------------------------------------------------}
procedure z_error(const m: str255);
begin
writeLn(output, m);
write('Zlib - Halt...');
readLn;
halt(1);
end;
{---------------------------------------------------------------------------}
procedure Trace(const x: str255);
begin
write(x);
end;
{$endif}
{---------------------------------------------------------------------------}
procedure Tracev(const x: str255);
begin
if z_verbose>0 then Trace(x);
end;
{---------------------------------------------------------------------------}
procedure Tracevv(const x: str255);
begin
if z_verbose>1 then Trace(x);
end;
{---------------------------------------------------------------------------}
procedure Tracevvv(const x: str255);
begin
if z_verbose>2 then Trace(x);
end;
{---------------------------------------------------------------------------}
procedure Tracec(c: boolean; const x: str255);
begin
if (z_verbose>0) and c then Trace(x);
end;
{---------------------------------------------------------------------------}
procedure Tracecv(c: boolean; const x: str255);
begin
if (z_verbose>1) and c then Trace(x);
end;
{---------------------------------------------------------------------------}
function IntToStr(value: longint): str255;
{-Convert any integer type to a string }
var
s: string[20];
begin
Str(value:0, s);
IntToStr := s;
end;
{$endif}
end.
|
//**************************************************************************************************
//
// Unit Main
// unit for the WMI Delphi Code Creator
// https://github.com/RRUZ/wmi-delphi-code-creator
//
// 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 Main.pas.
//
// The Initial Developer of the Original Code is Rodrigo Ruz V.
// Portions created by Rodrigo Ruz V. are Copyright (C) 2011-2015 Rodrigo Ruz V.
// All Rights Reserved.
//
//**************************************************************************************************
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, ExtCtrls, Rtti, Generics.Collections, uHostsAdmin,
SynEdit, ImgList, ToolWin, uSettings, Menus, Buttons, Vcl.Styles.ColorTabs,
Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnPopup, Vcl.ActnList, Vcl.ActnMan,
System.Actions;
type
TFrmMain = class(TForm)
PanelMain: TPanel;
StatusBar1: TStatusBar;
ToolBar1: TToolBar;
ToolButtonAbout: TToolButton;
ToolButton4: TToolButton;
MemoConsole: TMemo;
PanelConsole: TPanel;
ImageList1: TImageList;
PageControl2: TPageControl;
TabSheet3: TTabSheet;
ToolButtonSettings: TToolButton;
PopupActionBar1: TPopupActionBar;
TreeViewTasks: TTreeView;
Splitter1: TSplitter;
PageControlTasks: TPageControl;
TabSheet1: TTabSheet;
PageControl3: TPageControl;
TabSheetTask: TTabSheet;
TabSheet2: TTabSheet;
MemoLog: TMemo;
Splitter2: TSplitter;
ActionManager1: TActionManager;
ActionRegisterHost: TAction;
RegisterHost1: TMenuItem;
ActionConnect: TAction;
ConnecttoHost1: TMenuItem;
ActionPing: TAction;
PingHost1: TMenuItem;
ToolButton1: TToolButton;
ActionDisconnect: TAction;
DisconnectHost1: TMenuItem;
ToolButtonExit: TToolButton;
PopupActionBar2: TPopupActionBar;
procedure FormCreate(Sender: TObject);
procedure ToolButtonAboutClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ToolButtonSettingsClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure TreeViewTasksChange(Sender: TObject; Node: TTreeNode);
procedure FormShow(Sender: TObject);
procedure ActionRegisterHostUpdate(Sender: TObject);
procedure ActionRegisterHostExecute(Sender: TObject);
procedure ActionConnectUpdate(Sender: TObject);
procedure ActionConnectExecute(Sender: TObject);
procedure ActionPingUpdate(Sender: TObject);
procedure ActionPingExecute(Sender: TObject);
procedure ActionDisconnectUpdate(Sender: TObject);
procedure ToolButton1Click(Sender: TObject);
procedure ToolButtonExitClick(Sender: TObject);
procedure TreeViewTasksCustomDrawItem(Sender: TCustomTreeView;
Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean);
private
FSettings: TSettings;
FCtx : TRttiContext;
FRegisteredInstances : TDictionary<string,TForm>;
FListWINHosts : TObjectList<TWMIHost>;
procedure RegisterTask(const ParentTask, Name : string;ImageIndex:Integer; LinkObject : TRttiType);
procedure RegisterWMIHosts;
procedure SetLog(const Log :string);
procedure SetMsg(const Msg: string);
public
property Settings : TSettings read FSettings;
end;
var
FrmMain: TFrmMain;
implementation
uses
uStdActionsPopMenu,
uMisc,
uWmi_Metadata,
uLog,
uGlobals,
uSqlWMIContainer,
uWMIClassesContainer,
uWmiDatabase,
uWmiClassTree,
uWMIEventsContainer,
uWMIMethodsContainer,
uWmiTree,
uWmiInfo,
Vcl.Styles.FormStyleHooks,
Vcl.Styles.Ext,
Vcl.Themes,
uWmi_About;
Const
HostCIMStr = 'CIM Repository (%s)';
{$R *.dfm}
function GetNodeByText(ATree : TTreeView; const AValue:String; AVisible: Boolean=False): TTreeNode;
var
Node: TTreeNode;
begin
Result := nil;
if ATree.Items.Count = 0 then Exit;
Node := ATree.Items[0];
while Node <> nil do
begin
if SameText(Node.Text,AValue) then
begin
Result := Node;
if AVisible then
Result.MakeVisible;
Break;
end;
Node := Node.GetNext;
end;
end;
procedure TFrmMain.ActionConnectExecute(Sender: TObject);
Var
LForm : TFrmWMIInfo;
LWMIHost : TWMIHost;
LNameSpaces: TStrings;
LIndex : Integer;
LNode : TTreeNode;
begin
LWMIHost:=TWMIHost(TreeViewTasks.Selected.Data);
if LWMIHost.Form=nil then
begin
if Ping(LWMIHost.Host, 4, 32, MemoConsole.Lines) then
begin
LForm:=TFrmWMIInfo.Create(Self);
LForm.Parent:=TabSheetTask;
LForm.BorderStyle:=bsNone;
LForm.Align:=alClient;
LForm.SetLog:=SetLog;
LForm.WMIHost:=LWMIHost;
LWMIHost.Form:=LForm;
LWMIHost.Form.Show;
TreeViewTasks.Selected.ImageIndex:=6;
TreeViewTasks.Selected.SelectedIndex:=6;
LNameSpaces:=TStringList.Create;
SetMsg(Format('Getting WMI namespaces from [%s]',[LWMIHost.Host]));
try
LNameSpaces.AddStrings(CachedWMIClasses.GetNameSpacesHost(LWMIHost.Host, LWMIHost.User, LWMIHost.Password));
for LIndex := 0 to LNameSpaces.Count-1 do
RegisterTask(Format(HostCIMStr, [LWMIHost.Host]), LNameSpaces[LIndex], 58, FCtx.GetType(TFrmWMITree));
LNode:=GetNodeByText(TreeViewTasks, Format(HostCIMStr, [LWMIHost.Host]));
if LNode<>nil then
LNode.Expand(True);
finally
LNameSpaces.Free;
SetMsg('');
end;
end
else
begin
TreeViewTasks.Selected.ImageIndex:=12;
TreeViewTasks.Selected.SelectedIndex:=12;
MsgWarning('Was not possible establish a connection with the host');
end;
end;
end;
procedure TFrmMain.ActionConnectUpdate(Sender: TObject);
begin
TAction(Sender).Enabled:=(PageControlTasks.Visible) and (TreeViewTasks.Selected<>nil) and (TObject(TreeViewTasks.Selected.Data) is TWMIHost) and (TWMIHost(TreeViewTasks.Selected.Data).Form=nil);
end;
procedure TFrmMain.ActionDisconnectUpdate(Sender: TObject);
begin
TAction(Sender).Enabled:=(PageControlTasks.Visible) and (TreeViewTasks.Selected<>nil) and (TObject(TreeViewTasks.Selected.Data) is TWMIHost) and (TWMIHost(TreeViewTasks.Selected.Data).Form<>nil);
end;
procedure TFrmMain.ActionPingExecute(Sender: TObject);
begin
Ping(TWMIHost(TreeViewTasks.Selected.Data).Host, 4, 32, MemoConsole.Lines);
end;
procedure TFrmMain.ActionPingUpdate(Sender: TObject);
begin
TAction(Sender).Enabled:=(PageControlTasks.Visible) and (TreeViewTasks.Selected<>nil) and (TObject(TreeViewTasks.Selected.Data) is TWMIHost);
end;
procedure TFrmMain.ActionRegisterHostExecute(Sender: TObject);
Var
Frm : TFrmHostAdmin;
begin
Frm:=TFrmHostAdmin.Create(Self);
Frm.ShowModal;
end;
procedure TFrmMain.ActionRegisterHostUpdate(Sender: TObject);
begin
TAction(Sender).Enabled:=True;
end;
procedure TFrmMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
WriteSettings(Settings);
end;
procedure TFrmMain.FormCreate(Sender: TObject);
Var
LNameSpaces : TStrings;
LIndex : Integer;
begin
{$WARN SYMBOL_PLATFORM OFF}
//ReportMemoryLeaksOnShutdown:=DebugHook<>0;
{$WARN SYMBOL_PLATFORM ON}
//FillPopupActionBar(PopupActionBar1);
FillPopupActionBar(PopupActionBar2);
AssignStdActionsPopUpMenu(Self, PopupActionBar2);
FListWINHosts:=nil;
FCtx:=TRttiContext.Create;
FRegisteredInstances:=TDictionary<string, TForm>.Create;
FSettings :=TSettings.Create;
SetLog('Reading settings');
ReadSettings(FSettings);
LoadVCLStyle(Settings.VCLStyle);
if FSettings.DisableVClStylesNC then
begin
TStyleManager.Engine.RegisterStyleHook(TCustomForm, TFormStyleHookNC);
TStyleManager.Engine.RegisterStyleHook(TForm, TFormStyleHookNC);
//GlassFrame.Enabled:=True;
end
else
if FSettings.ActivateCustomForm then
begin
TStyleManager.Engine.RegisterStyleHook(TCustomForm, TFormStyleHookBackground);
TStyleManager.Engine.RegisterStyleHook(TForm, TFormStyleHookBackground);
if FSettings.CustomFormNC then
begin
TFormStyleHookBackground.NCSettings.Enabled := True;
TFormStyleHookBackground.NCSettings.UseColor := FSettings.UseColorNC;
TFormStyleHookBackground.NCSettings.Color := FSettings.ColorNC;
TFormStyleHookBackground.NCSettings.ImageLocation := FSettings.ImageNC;
end;
if FSettings.CustomFormBack then
begin
TFormStyleHookBackground.BackGroundSettings.Enabled := True;
TFormStyleHookBackground.BackGroundSettings.UseColor := FSettings.UseColorBack;
TFormStyleHookBackground.BackGroundSettings.Color := FSettings.ColorBack;
TFormStyleHookBackground.BackGroundSettings.ImageLocation := FSettings.ImageBack;
end;
end;
//RegisterTask('','Code Generation', 30, nil);
RegisterTask('','WMI Class Code Generation', 40, FCtx.GetType(TFrmWMiClassesContainer));
RegisterTask('','WMI Methods Code Generation', 41, FCtx.GetType(TFrmWmiMethodsContainer));
RegisterTask('','WMI Events Code Generation', 45, FCtx.GetType(TFrmWmiEventsContainer));
//RegisterTask('','WMI Explorer', 29, Ctx.GetType(TFrmWMITree));
RegisterTask('','WMI Classes Tree', 47, FCtx.GetType(TFrmWmiClassTree));
RegisterTask('','WMI Finder', 57, FCtx.GetType(TFrmWmiDatabase));
RegisterTask('','WQL', 56, FCtx.GetType(TFrmSqlWMIContainer));
//RegisterTask('','Events Monitor', 28, nil);
//RegisterTask('','Log', 32, Ctx.GetType(TFrmLog));
RegisterTask('','CIM Repository (localhost)', 6, FCtx.GetType(TFrmWMIInfo));
LNameSpaces:=TStringList.Create;
try
LNameSpaces.AddStrings(CachedWMIClasses.NameSpaces);
for LIndex := 0 to LNameSpaces.Count-1 do
RegisterTask('CIM Repository (localhost)', LNameSpaces[LIndex], 58, FCtx.GetType(TFrmWMITree));
finally
LNameSpaces.Free;
end;
{
for LHost in GetWMIRegisteredHosts do
RegisterTask('',Format('CIM Repository (%s)', [LHost]), 31, nil);
}
RegisterWMIHosts;
TreeViewTasks.FullExpand;
//TreeViewTasks.Selected:=TreeViewTasks.Items[0];
MemoConsole.Color:=Settings.BackGroundColor;
MemoConsole.Font.Color:=Settings.ForeGroundColor;
MemoLog.Color:=MemoConsole.Color;
MemoLog.Font.Color:=MemoConsole.Font.Color;
StatusBar1.Panels[2].Text := Format('WMI installed version %s', [GetWmiVersion]);
{
AssignStdActionsPopUpMenu(Self, PopupActionBar1);
ApplyVclStylesOwnerDrawFix(Self, True);
}
end;
procedure TFrmMain.FormDestroy(Sender: TObject);
Var
Pair : TPair<string,TForm>;
begin
if FListWINHosts<>nil then
FreeAndNil(FListWINHosts);
for Pair in FRegisteredInstances do
begin
Pair.Value.Close;
Pair.Value.Free;
end;
FRegisteredInstances.Free;
Settings.Free;
end;
procedure TFrmMain.FormShow(Sender: TObject);
begin
if TreeViewTasks.Selected=nil then
TreeViewTasks.Selected:=TreeViewTasks.Items[0];
end;
procedure TFrmMain.SetLog(const Log: string);
begin
MemoLog.Lines.Add(Log);
end;
procedure TFrmMain.SetMsg(const Msg: string);
begin
StatusBar1.Panels[0].Text := Msg;
StatusBar1.Update;
end;
procedure TFrmMain.ToolButton1Click(Sender: TObject);
begin
PageControlTasks.Visible:=not PageControlTasks.Visible;
end;
procedure TFrmMain.ToolButtonAboutClick(Sender: TObject);
var
Frm: TFrmAbout;
begin
Frm := TFrmAbout.Create(nil);
Frm.ShowModal();
end;
procedure TFrmMain.ToolButtonExitClick(Sender: TObject);
begin
Close();
end;
procedure TFrmMain.RegisterTask(const ParentTask, Name: string; ImageIndex: Integer;
LinkObject: TRttiType);
Var
PNode : TTreeNode;
Node : TTreeNode;
begin
if ParentTask='' then
Node:=TreeViewTasks.Items.AddObject(nil, Name, LinkObject)
else
begin
PNode:=GetNodeByText(TreeViewTasks, ParentTask);
Node:=TreeViewTasks.Items.AddChildObject(PNode, Name, LinkObject);
end;
Node.ImageIndex :=ImageIndex;//add BN ??
Node.SelectedIndex :=ImageIndex;
end;
procedure TFrmMain.RegisterWMIHosts;
Var
Node : TTreeNode;
LWMIHost : TWMIHost;
begin
if FListWINHosts<>nil then
FreeAndNil(FListWINHosts);
FListWINHosts:=GetListWMIRegisteredHosts;
for LWMIHost in FListWINHosts do
begin
Node:=TreeViewTasks.Items.AddObject(nil, Format(HostCIMStr, [LWMIHost.Host]), LWMIHost);
Node.ImageIndex :=31;//add BN ??
Node.SelectedIndex :=31;
end;
end;
procedure TFrmMain.ToolButtonSettingsClick(Sender: TObject);
var
Frm : TFrmSettings;
begin
Frm :=TFrmSettings.Create(nil);
try
Frm.Form:=Self;
Frm.LoadSettings;
Frm.ShowModal();
finally
Frm.Free;
ReadSettings(FSettings);
end;
end;
procedure TFrmMain.TreeViewTasksChange(Sender: TObject; Node: TTreeNode);
var
LRttiInstanceType : TRttiInstanceType;
LValue : TValue;
LRttiProperty : TRttiProperty;
LForm : TForm;
LIndex : integer;
LProc : TProcLog;
begin
if Node.Text<>'' then
begin
TabSheetTask.Caption:=Node.Text;
TabSheetTask.ImageIndex:=Node.ImageIndex;
for LIndex := 0 to TabSheetTask.ControlCount-1 do
if (TabSheetTask.Controls[LIndex] is TForm) and (TForm(TabSheetTask.Controls[LIndex]).Visible) then
begin
TForm(TabSheetTask.Controls[LIndex]).Hide;
break;
end;
if (Node.Data<>nil) and (Node.Parent<>nil) and (TObject(Node.Parent.Data) is TWMIHost) then
begin
if FRegisteredInstances.ContainsKey(Node.Parent.Text+Node.Text) then
FRegisteredInstances.Items[Node.Parent.Text+Node.Text].Show
else
if Node.Data<>nil then
begin
LRttiInstanceType:=TRttiInstanceType(Node.Data);
LValue:=LRttiInstanceType.GetMethod('Create').Invoke(LRttiInstanceType.MetaclassType,[Self]);
LForm:=TForm(LValue.AsObject);
LForm.Parent:=TabSheetTask;
LForm.BorderStyle:=bsNone;
LForm.Align:=alClient;
LRttiProperty:=LRttiInstanceType.GetProperty('Console');
if LRttiProperty<>nil then
LRttiProperty.SetValue(LForm, MemoConsole);
LProc:=SetMsg;
LRttiProperty:=LRttiInstanceType.GetProperty('SetMsg');
if LRttiProperty<>nil then
LRttiProperty.SetValue(LForm, TValue.From<TProcLog>(LProc));
LProc:=SetLog;
LRttiProperty:=LRttiInstanceType.GetProperty('SetLog');
if LRttiProperty<>nil then
LRttiProperty.SetValue(LForm, TValue.From<TProcLog>(LProc));
LRttiProperty:=LRttiInstanceType.GetProperty('Settings');
if LRttiProperty<>nil then
LRttiProperty.SetValue(LForm, FSettings);
LRttiProperty:=LRttiInstanceType.GetProperty('NameSpace');
if LRttiProperty<>nil then
LRttiProperty.SetValue(LForm, Node.Text);
LRttiProperty:=LRttiInstanceType.GetProperty('WMIHost');
if LRttiProperty<>nil then
LRttiProperty.SetValue(LForm, TWMIHost(Node.Parent.Data));
LForm.Show;
FRegisteredInstances.Add(Node.Parent.Text+Node.Text, LForm);
end;
end
else
if (Node.Data<>nil) and (TObject(Node.Data) is TWMIHost) then
begin
if TWMIHost(Node.Data).Form<>nil then
TWMIHost(Node.Data).Form.Show;
end
else
begin
if FRegisteredInstances.ContainsKey(Node.Text) then
FRegisteredInstances.Items[Node.Text].Show
else
if Node.Data<>nil then
begin
LRttiInstanceType:=TRttiInstanceType(Node.Data);
LValue:=LRttiInstanceType.GetMethod('Create').Invoke(LRttiInstanceType.MetaclassType,[Self]);
LForm:=TForm(LValue.AsObject);
LForm.Parent:=TabSheetTask;
LForm.BorderStyle:=bsNone;
LForm.Align:=alClient;
LRttiProperty:=LRttiInstanceType.GetProperty('Console');
if LRttiProperty<>nil then
LRttiProperty.SetValue(LForm, MemoConsole);
LProc:=SetMsg;
LRttiProperty:=LRttiInstanceType.GetProperty('SetMsg');
if LRttiProperty<>nil then
LRttiProperty.SetValue(LForm, TValue.From<TProcLog>(LProc));
LProc:=SetLog;
LRttiProperty:=LRttiInstanceType.GetProperty('SetLog');
if LRttiProperty<>nil then
LRttiProperty.SetValue(LForm, TValue.From<TProcLog>(LProc));
LRttiProperty:=LRttiInstanceType.GetProperty('Settings');
if LRttiProperty<>nil then
LRttiProperty.SetValue(LForm, FSettings);
LRttiProperty:=LRttiInstanceType.GetProperty('NameSpace');
if LRttiProperty<>nil then
LRttiProperty.SetValue(LForm, Node.Text);
LForm.Show;
FRegisteredInstances.Add(Node.Text, LForm);
end;
end;
end;
end;
procedure TFrmMain.TreeViewTasksCustomDrawItem(Sender: TCustomTreeView;
Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean);
begin
if not StyleServices.IsSystemStyle then
if cdsSelected in State then
begin
TTreeView(Sender).Canvas.Brush.Color := StyleServices.GetSystemColor(clHighlight);
TTreeView(Sender).Canvas.Font.Color := StyleServices.GetSystemColor(clHighlightText);
end;
end;
initialization
if not IsStyleHookRegistered(TCustomSynEdit, TScrollingStyleHook) then
TStyleManager.Engine.RegisterStyleHook(TCustomSynEdit, TScrollingStyleHook);
{
TCustomStyleEngine.RegisterStyleHook(TCustomTabControl, TTabColorControlStyleHook);
TCustomStyleEngine.RegisterStyleHook(TTabControl, TTabColorControlStyleHook);
}
end.
|
(********************************************************************************************
** PROGRAM : cgicook
** VERSION : 1.0.0
** DESCRIPTION : Demonstrates how to use cookies in CGI programs.
** AUTHOR : Stuart King
** COPYRIGHT : Copyright (c) Irie Tools, 2002. All Rights Reserved.
** NOTES :
** This sample program is distributed with Irie Pascal, and was written to illustrate
** how to use cookies (i.e. how to read, write, and delete cookies). To make best use of
** this sample you should have a basic understanding of Pascal as well as a basic
** understanding of the Common Gateway Interface (CGI).
**
** Before describing how to use cookies, here is a very brief description of what
** cookies are and what they are used for. Cookies are named pieces of information that a
** website can ask a client (usually a browser) to store on its behalf. This information
** can be sent back to the website (and any other website in the cookies domain) whenever
** the browser sends a request to the website. Cookies are usually stored on the client's
** hard drive and can persist for weeks, months, or even years. This makes cookies very
** useful for 'remembering' information about website visitors.
** IMPORTANT: The cookies sent between the client and the website are sent in text format
** and are visible to any snooper, so sensitive information should either be encrypted
** or sent only over a secure connection.
**
** Cookies are written by sending a "Set-Cookie" response header back to the client. The
** syntax for the "Set-Cookie" header is given below:
**
** Set-Cookie: name=value; domain=.domain.com; path=/path;
** expires=Day, dd-Mon-yyyy hh:mm:ss GMT; secure
** Where
** "name" is the name of the cookie.
** "value" is the information stored by the cookie and must be specified. If you want
** to delete a cookie then specify an expiry date that has already passed.
** "domain" restricts the domains that will receive the cookie. The client should only send
** the cookie to matching domains. Domains are matched from right to left. So
** "domain=.irietools.com" matches "www.irietools.com" and "info.irietools.com".
** If "domain" is specified it must match the domain of the website setting the
** cookie. "domain" can't specify a top-level domain like ".com" or ".edu.jm".
** If "domain" is not specified then the domain name of the website setting
** the cookie is used.
** "path" restricts the URLs within a domain that will receive the cookie. Paths are
** matched from left to right and trailing /'s are ignored. If "path" is not
** specified then the full path of the request is used.
** "expires" specifies when the cookie should expire. The format of the expiry info
** must be exactly as shown above:
** "Day" is the three letter day of the week (Mon, Tue, Wed, Thu, Fri, Sat, or Sun).
** "dd" is the two digit day of the month (01-31).
** "Mon" is the three letter abbreviated month name
** (Jan, Feb, Mar, Apr, Jun, Jul, Aug, Sep, Oct, Nov, Dec).
** For example: "Mon, 16-Sep-2002 17:03:48 GMT".
** If "expire" is not specified then the cookie is stored memory until the client
** exits.
** "secure" indicates that the cookie should only be sent over a secure connection.
**
** The browser sends cookies back to the website in the form of Cookie headers. The
** format for Cookie headers is given below:
**
** Cookie: Cookie1; ...; CookieN
** Where
** each Cookiue is given as: name=value
**
** Only the "name" and the "value" of the cookies is returned, the other information
** such as the "domain" is not returned. CGI programs can't read the Cookie headers
** directly, so the webserver will make the Cookie header information available to the
** CGI program in the HTTP_COOKIE environment variable.
**********************************************************************************************)
program cookies;
const
MAX_BUFFER = 4096;
MAX_COOKIE_DATA = 200;
//SCRIPT_NAME = '/irietools/cgibin/cookies.exe';
type
positive = 0..maxint;
BufferType = string[MAX_BUFFER];
CookieDataType = string[MAX_COOKIE_DATA];
DayOfWeek = 1..7;
Days = 1..31;
Months = 1..12;
date = record
day : Days;
month : Months;
year : integer;
dow : DayOfWeek
end;
Cookie = record
name : string;
value : CookieDataType
end;
CookieList = list of Cookie;
var
buffer : BufferType;
strSetCookie : BufferType;
DaysInMonth : array[Months] of Days;
DaysElapsed : array[Months] of integer;
DayOfWeekShortNames : array[DayOfWeek] of string[3];
MonthShortNames : array[Months] of string[3];
Cookies : CookieList;
procedure DateToInt(dt : date; var iDays : integer); forward;
procedure IntToDate(iDays : integer; var dt : date); forward;
procedure CalculateDayOfWeek(var dt : date); forward;
function urlencode(strIn : string) : string; forward;
function EscapeCharacters(s : string) : string; forward;
//PURPOSE: Performs program initialization
procedure Initialize;
var
m : months;
begin (* Initialize *)
DaysInMonth[1] := 31;
DaysInMonth[2] := 28;
DaysInMonth[3] := 31;
DaysInMonth[4] := 30;
DaysInMonth[5] := 31;
DaysInMonth[6] := 30;
DaysInMonth[7] := 31;
DaysInMonth[8] := 31;
DaysInMonth[9] := 30;
DaysInMonth[10] := 31;
DaysInMonth[11] := 30;
DaysInMonth[12] := 31;
DaysElapsed[1] := 0;
for m := 2 to 12 do
DaysElapsed[m] := DaysElapsed[m-1]+DaysInMonth[m-1];
DayOfWeekShortNames[1] := 'Sun';
DayOfWeekShortNames[2] := 'Mon';
DayOfWeekShortNames[3] := 'Tue';
DayOfWeekShortNames[4] := 'Wed';
DayOfWeekShortNames[5] := 'Thu';
DayOfWeekShortNames[6] := 'Fri';
DayOfWeekShortNames[7] := 'Sat';
MonthShortNames[1] := 'Jan';
MonthShortNames[2] := 'Feb';
MonthShortNames[3] := 'Mar';
MonthShortNames[4] := 'Apr';
MonthShortNames[5] := 'May';
MonthShortNames[6] := 'Jun';
MonthShortNames[7] := 'Jul';
MonthShortNames[8] := 'Aug';
MonthShortNames[9] := 'Sep';
MonthShortNames[10] := 'Oct';
MonthShortNames[11] := 'Nov';
MonthShortNames[12] := 'Dec';
new(Cookies); //initialize the list of cookies
end; (* Initialize *)
//PURPOSE: Retrieves the information passed to the CGI applications.
//PARAMETER(s): cl - Used to store all the cookies that were passed to the CGI program
//GLOBAL(s) - buffer - Used to store the GET or POST information passed to the CGI program
procedure GetCGIData(var cl : CookieList);
var
RequestMethod : string;
//PURPOSE: Retrieves the cookies passed to the CGI program and puts then in the list.
//PARAMETER(s): cl - Used to store all the cookies that were passed to the CGI program
procedure GetCookieInfo(var cl : CookieList);
var
data : BufferType;
iNumCookies, iCurrCookie : positive;
iPos, iLen : positive;
strCurrCookie : CookieDataType;
c : Cookie;
begin (* GetCookieInfo *)
//The cookies are stored in the environment variable HTTP_COOKIE as space
// deliminated words with trailing semi-colons after each word (except the last word).
//Each word being a single cookie.
//Retrieve the cookies
data := getenv('HTTP_COOKIE');
//Retrieve the number words/cookies.
iNumCookies := countwords(data);
//Retrieve each cookie and use the "=" to seperate the name from the value
//then insert the cookie into the list.
for iCurrCookie := 1 to iNumCookies do
begin
strCurrCookie := copyword(data, iCurrCookie);
iPos := pos('=', strCurrCookie);
if iPos <> 0 then
begin
c.name := trim(copy(strCurrCookie, 1, iPos-1));
c.value := trim(copy(strCurrCookie, iPos+1));
iLen := length(c.value);
if (iLen<>0) and (c.value[iLen]=';') then
c.value := copy(c.value, 1, iLen-1);
insert(c, cl);
end;
end;
end; (* GetCookieInfo *)
//PURPOSE: Retrieves information sent to by a GET request (i.e. in the QUERY_STRING
// environment variable).
procedure GetRequest;
begin (* GetRequest *)
buffer := getenv('QUERY_STRING')
end; (* GetRequest *)
//PURPOSE: Retrieves information sent to by a POST request (i.e. through the standard
// input stream, with the length of the data in the environment variable
// CONTENT_LENGTH).
procedure PostRequest;
var
len, i : positive;
err : integer;
ContentLength : string;
c : char;
begin (* PostRequest *)
buffer := '';
ContentLength := getenv('CONTENT_LENGTH');
if ContentLength <> '' then
val(ContentLength, len, err)
else
len := 0;
if len <= MAX_BUFFER then
for i := 1 to len do
begin
read(c);
buffer := buffer + c
end
end; (* PostRequest *)
begin (* GetCGIData *)
GetCookieInfo(cl);
RequestMethod := getenv('REQUEST_METHOD');
if RequestMethod = 'GET' then
GetRequest
else
PostRequest
end; (* GetCGIData *)
//PURPOSE: Process the data passed to the program.
//NOTES: This is the main part of the program. After retreiving
// the information passed to the program this procedure is
// called to perform the required processing. This program receives to kinds
// of information:
// 1. Cookies sent back by the brower. These have already been retrieved by the
// the procedure "GetCGIData" and do not require further processing here.
// The procedure 'GenerateResponse' will display the retrieved cookies.
// 2. Information entered by the user about a cookie to add or delete. This
// information needs to formated and put in the global 'strSetCookie', so that
// it can be included in the response by the procedure 'GenerateResponse'.
procedure ProcessCGIData;
var
i, num, p : integer;
EncodedVariable, DecodedVariable, name, value : string;
strName : string;
strValue : string;
strExpiry : string;
blnDelete : boolean;
//PURPOSE: Converts a expiry date into a string in the format required
// by the Set-Cookie header (i.e. Day, dd-Mon-yyyy hh:mm:ss GMT
//ARGUMENT(s): dt - Expire date to convert.
//RETURNS: The expiry date/time in Set-Cookie format
//NOTES:
// This function just hard-codes the last second in the day "23:59:59"
// instead of using the current time or allowing the expiry time to be specified.
//This is done because
// 1. It is easier and this is just a sample program
// 2. Usually cookie will be set to expire either when the browser closes
// or after many days have passed, so the exact time is not important.
function FormatCookieExpiryString(dt : date) : string;
var
s : string;
//PURPOSE: Converts an integer into a zero-padded string
//ARGUMENT(s):
// 1. i - The integer to convert
// 2. len - The length of the string to return
//RETURNS:
// The zero padded string
function Int2String(i : integer; len : integer) : string;
var
S : string;
begin (* Int2String *)
str(i:1, s);
while length(s) < len do
s := '0' + s;
Int2String := s
end; (* Int2String *)
begin (* FormatCookieExpiryString *)
CalculateDayOfWeek(dt);
s := DayOfWeekShortNames[dt.dow]+', ';
s := s + Int2String(dt.day, 2)+'-'+MonthShortNames[dt.month]+'-'+Int2String(dt.year, 4)+' ';
s := s + '23:59:59 GMT';
FormatCookieExpiryString := s;
end; (* FormatCookieExpiryString *)
//PURPOSE: Processes the named value pairs sent with the GET or POST request.
// Which in this case is the information entered by the user about the
// cookie to add or delete.
//ARGUMENT(s): name - name part of the name/value pair
// value - value part of name/value pair
//NOTES:
// The information entered by the user is sent as name/value pairs (i.e. name-value)
//with the name part being the name of the form element holding the information and
//the value part being the actual information held by the form element.
procedure ProcessNameValuePair(var name, value : string);
var
dt : date;
dow : integer;
iDays, iErr : integer;
iDate : integer;
begin
//If the name is 'txtname' then this is the name of the cookie.
//The name is urlencoded in case it contains special characters
if name='txtname' then
strName := urlencode(value)
//If the name is 'txtvalue' then this is the value of the cookie.
//The value is urlencoded in case it contains special characters
else if name='txtvalue' then
strValue := urlencode(value)
//If the name is 'txtdays' then this is the number of days before the cookie
//expires. The value is converted to an integer and if the conversion is
//successful the value is added to the current date to get the expiry date
//and this date is formatted for use in a Set-Cookie header.
else if name='txtdays' then
begin
val(value, iDays, iErr);
if iErr=0 then
begin
getdate(dt.year, dt.month, dt.day, dow);//Get current date
DateToInt(dt, iDate); //Convert current date to number of days since Jan 1, 0001 AD
iDate := iDate + iDays; //Add in the number of days to expire
IntToDate(iDate, dt); //Convert the result back into a date
strExpiry := FormatCookieExpiryString(dt); //Format date
end;
end
//If the name is 'cmddelete' then the cookie should be deleted not added.
//The cookie is deleted by setting an expiry date that has already passed.
else if name='cmddelete' then
begin
getdate(dt.year, dt.month, dt.day, dow);
DateToInt(dt, iDate);
iDate := iDate - 2;
IntToDate(iDate, dt);
strExpiry := FormatCookieExpiryString(dt);
blnDelete := true
end
else
;
end;
begin (* ProcessCGIData *)
strSetCookie := '';
strName := '';
strValue := '';
strExpiry := '';
blnDelete := false;
//Retrieve each name/value pair from the form and processes them.
num := CountWords(buffer, '&');
for i := 1 to num do
begin
EncodedVariable := CopyWord(buffer, i, '&');
DecodedVariable := URLDecode(EncodedVariable);
p := pos('=', DecodedVariable);
if p > 0 then
begin
name := lowercase(trim(copy(DecodedVariable, 1, p-1)));
value := trim(copy(DecodedVariable, p+1));
ProcessNameValuePair(name, value);
end
end;
//If after processing each name/value pair we have enough data for a
//"Set-Cookie" header then generate a "Set-Cookie" header in the global
//"strSetCookie".
//if (strName<>'') and ((strValue<>'') or blnDelete) and (strExpiry<>'') then
if (strName<>'') and ((strValue='') or (strExpiry<>'')) then
begin
//Set-Cookie: name=value; domain=.irietools.com; path=/cgibin;
// expires=Tue, 03-Sep-2002 20:42:19 GMT; secure
strSetCookie := 'Set-Cookie: ' + strName + '=' + strValue + ';';
if strExpiry<>'' then
strSetCookie := strSetCookie + ' expires=' + strExpiry;
end;
end; (* ProcessCGIData *)
//PURPOSE: Generates the response to send back to the browser.
//NOTES:
// Most of the HTML generated by this procedure actually comes from a template file.
//The HTML from the template file is common to almost all the pages on this website.
//The HTML specific to this program (i.e. the form that accepts the cookie information
//from the user), is generated by the local procedure 'GenerateBodyData'. So this procedure
//basically reads the template file and sends most of it to the webserver except for
//a small section which it repalces with the output of the procedure 'GenerateBodyData'.
//The template file is divided into sections using HTML comments. The start of a section
//is marked by the following
//
// <!--section SectionName-->
//
//Where "SectionName" is the name of the section.
//
//The end of a section is marked by
//
// <!--/section-->
//
//What this procedure actually does is read the template file and write the contents
//of all the sections except one to the webserver. The section not written to the webserver
//is called "bodydata". Instead of writing the contents of the section "bodydata" to the
//webserver the ouput of the procedure "GenerateBodyData" is sent to the webserver.
//This is done because it is much easier to work with HTML using an HTML editor rather
//than using embedded writeln's inside a CGI program. So an HTML editor is used to
//create and update the template file and the portion of the generated output that
//is specific to this program is generated by "GenerateBodyData". You will notice
//when you run this program that the page generated looks alot like the other pages
//on the website because most of it comes from the template file.
procedure GenerateResponse;
const
TEMPLATE_FILE = 'template.html';
START_SECTION = '<!--section';
END_SECTION = '<!--/section-->';
SECTION_NAME = 'bodydata';
var
f : text;
line : BufferType;
blnSkipping : boolean;
//PURPOSE: Generates the portion of the response page that is specific to this
// program (the rest of the response page comes from the template file).
//NOTES:
// Tables are used to organise the layout of the generated pages on this website.
//The portion of the response page generated by this procedure is a single row of
//a table. Unless you are an HTML expert the easiest way to understand the HTML
//generated by this procedure is probably to run this program and view the
//response pages generated.
procedure GenerateBodyData;
var
iNumCookies, iCurrCookie : positive;
c : Cookie;
begin (* GenerateBodyData *)
writeln('<tr>');
writeln('<td width="100%">');
//Generate the HTML to display the cookies returned by the browser.
writeln('<h1>Current Cookies</h1>');
iNumCookies := length(Cookies); //Number of cookies returned by the browser
if iNumCookies=0 then
writeln('<p>None</p>')
else
//For each cookie returned write it's name and value
//NOTE: The name and value are escaped in case they contain
//special characters.
for iCurrCookie := 1 to iNumCookies do
begin
c := Cookies[iCurrCookie];
writeln('<p>', EscapeCharacters(urldecode(c.name)), '=', EscapeCharacters(urldecode(c.value)),'</p>');
end;
writeln('<hr>');
writeln('<p>', getenv('SCRIPT_NAME'), '</p>');
writeln('<hr>');
//Generate the HTML for the form
writeln('<form method="POST" action="', getenv('SCRIPT_NAME'), '">');
writeln('<p><big><strong>Name:</strong></big> <input type="text" name="txtName" size="25"></p>');
writeln('<p><big><strong>Value:</strong></big> <input type="text" name="txtValue" size="56"></p>');
writeln('<p><big><strong>Expiries in:</strong></big> <input type="text" name="txtDays" size="5"> <big><strong>Days</strong></big></p>');
writeln('<p><input type="submit" value=" Add Cookie " name="cmdAdd">');
writeln('<input type="submit" value=" Delete Cookie " name="cmdDelete">');
writeln('<input type="reset" value=" Reset " name="cmdReset"></p>');
writeln('</form>');
writeln('</td>');
writeln('</tr>');
end; (* GenerateBodyData *)
begin (* GenerateResponse *)
//Generate the response headers (including the blank line at the end).
writeln('content-type: text/html');
if strSetCookie <> '' then
writeln(strSetCookie);
writeln;
blnSkipping := false;
reset(f, TEMPLATE_FILE);
//Read each line in the template file and search for section markers
//If a target section marker is found then call 'GenerateBodyData' to
//generate the HTML for that section and set 'blnSkipping' to true so
//that the contents of that section, from the template file, will be skipped.
while not eof(f) do
begin
readln(f, line);
line := trim(line);
if pos(START_SECTION, line) > 0 then
begin
if pos(SECTION_NAME, line) > 0 then
begin
GenerateBodyData;
blnSkipping := true;
end
end
else if line=END_SECTION then
blnSkipping := false
else if not blnSkipping then
writeln(line);
end;
close(f);
end; (* GenerateResponse *)
procedure Shutdown;
begin (* Shutdown *)
dispose(Cookies);
end; (* Shutdown *)
//PUPOSE: Determines if a year was a leap year.
function IsLeapYear(year : integer) : boolean;
begin (* IsLeapYear *)
IsLeapYear :=
((year mod 4)=0)
and
(
((year mod 100)<>0)
or
((year mod 400)=0)
);
end; (* IsLeapYear *)
//PURPOSE: Converts a date into an integer. The integer represents the
// number of days since 'Jan 1, 0001 AD'. Negative values present
// the number of days before 'Jan 1, 0001 AD' (i.e. BC dates).
//ARGUMENT(s): dt - The date to convert to an integer
// iDays - The converted date as an integer.
procedure DateToInt;
var
i, year : integer;
//PURPOSE: Used to help adjust for the leap years when calulating the number
// of days that have already elapsed since the year began.
//RETURNS: +1 if the date is a leap year and the month of february
// has already passed.
// or
// 0 otherwise
function LeapYearAdjustment(dt : date) : integer;
var
iAdjustment : integer;
begin (* LeapYearAdjustment *)
iAdjustment := 0;
if (IsLeapYear(dt.year)) and (dt.month >= 3) then
iAdjustment := 1;
LeapYearAdjustment := iAdjustment;
end; (* LeapYearAdjustment *)
begin (* DateToInt *)
if dt.year < 0 then
year := dt.year+1 //Adjust for the fact that there was no year 0.
else
year := dt.year;
//Calculate days since Jan 1, 0001 AD ignoring leap years.
i := (year-1)*365 + DaysElapsed[dt.month] + (dt.day-1);
//Adjust for leap years except the final year
i := i + ((year-1) div 4) - ((year-1) div 100) + ((year-1) div 400);
//Add 1 if the final year is a leap year and february has passed.
iDays := i + LeapYearAdjustment(dt);
end; (* DateToInt *)
//PURPOSE: Coverts an integer, representing the number of days since Jan 1, 0001 AD
// to a date.
//ARGUMENT(s): iDays - The integer to convert to a date.
// dt - The converted date.
//NOTE: There are 365.2425 days in the year adjusting for leap years.
procedure IntToDate;
var
m : Months;
d : integer;
iError, iTemp : integer;
begin
//First calculate an approximation of the correct answer
if iDays >= 0 then
begin
dt.year := trunc(idays / 365.2425)+1;
iTemp := iDays - trunc((dt.year-1)*365.2425);
end
else
begin
dt.year := -(trunc(abs(idays) / 365.2425)+1);
iTemp := abs(abs(iDays) - trunc((abs(dt.year)-1)*365.2425));
end;
dt.month := 12;
for m := 1 to 12 do
if iTemp >= DaysElapsed[m] then
dt.month := m;
iTemp := iTemp - DaysElapsed[dt.month];
d := iTemp+1;
if d > DaysInMonth[dt.month] then
dt.day := DaysInMonth[dt.month]
else
dt.day := d;
//Now to keep adjusting our approximation until it is exact
DateToInt(dt, iTemp);
while iTemp<>iDays do
begin
//Number of days that need to be added to the approximation to make it correct.
iError := iDays-iTemp;
//If adding the days would make the day of the month negative then
// then move the approximation to the beginning of the previous month.
// Adjusting the year if necessary (i.e. it is the first month of the year).
if (dt.day + iError) < 1 then
begin
if dt.month=1 then
begin
dt.month := 12;
dt.year := dt.year - 1;
if dt.year = 0 then
dt.year := -1;
end
else
dt.month := dt.month - 1;
dt.day := 1;
end
//If adding the days might take the date into the next month then
// check if adding the days actually takes the date to Feb 29 on a leap year
// if so then adjust the date to Feb 29
//otherwise move the date to the beginning of the next month.
else if (dt.day + iError) > DaysInMonth[dt.month] then
begin
if (dt.month=2) and (IsLeapYear(dt.year)) and (dt.day+iError=DaysInMonth[dt.month]+1) then
dt.day := DaysInMonth[dt.month]+1
else
begin
if dt.month=12 then
begin
dt.month := 1;
dt.year := dt.year + 1;
if dt.year = 0 then
dt.year := 1;
end
else
dt.month := dt.month + 1;
dt.day := 1
end
end
//else adding the days results in a valid day of the month then
// just add the days.
else
dt.day := dt.day + iError;
DateToInt(dt, iTemp);
end;
end;
//PURPOSE: Calculates the day of the week of a given date
//ARGUMENT(s): dt - The date to calculate the day of the week of.
//NOTES:
// First the date is converted into the number of days since (Jan 1, 0001 AD)
//Next this value is adjusted with the day of the week of Jan 1, 0001 AD.
//Next mod 7 is used to give a value in the range 0..6 that repeats every
//seven days (like the days of the week).
//Finally the value is incremented by 1 to give a value in the range 1..7
//
//The most interesting part of this algorithm is probably the adjustment for the
//first day of the week. Suppose this adjustment was not made then of the date
//was Jan 1, 0001 AD then 'DateToInt' would calculate the number of days as 0.
//Then (0 mod 7) + 1 would give the value 1 or Sunday. But Jan 1, 0001 AD was a
//Monday, so we need to add a 1 to adjust for this fact. How do I know that
//Jan 1, 0001 AD was a Monday? I don't, but I do know that day of the week of
//today. So what I did was calculate the day of the week for today without the
//adjustment and then added an adjustment that resulted in the correct value.
procedure CalculateDayOfWeek;
const
ADJUST_FOR_FIRST_DAY = 1; //Apparently Jan 1, 0001 AD was a Monday
var
iDays : integer;
begin (* CalculateDayOfWeek *)
DateToInt(dt, iDays);
dt.dow := ((iDays+ADJUST_FOR_FIRST_DAY) mod 7) + 1;
end; (* CalculateDayOfWeek *)
//PURPOSE: Returns the URL encoded version of a string.
//ARGUMENT(s): strIn - The string to be encoded.
//NOTES:
// Spaces are converted to '-' and non-alphanumeric characters are converted
//to %NN, where NN is the hexidecimal value of the chacters ordinal value. This
//is the reverse of the built-in function 'urldecode'.
function urlencode;
var
strOut : string;
i : positive;
c : char;
sTemp : string[3];
begin (* urlencode *)
strOut := '';
for i := 1 to length(strIn) do
begin
c := strIn[i];
if c = ' ' then
strOut := strOut + '+'
else if isalphanum(c) then
strOut := strOut + c
else
begin
sTemp := hex(ord(c));
if length(sTemp)=1 then
sTemp := '0' + sTemp;
strOut := strOut + '%' + sTemp
end;
end;
urlencode := strOut;
end; (* urlencode *)
//*************************************************************************
//PURPOSE: This function converts certain characters that have a
// special meaning in HTML documents to their HTML representation.
//ARGUMENT(s): s - The string to be escaped.
//RETURNS: The string with all special characters escaped.
//NOTES: The characters converted are < > "
function EscapeCharacters;
const
LessThanChar = '<';
GreaterThanChar = '>';
QuoteChar = '"';
HTMLLessThan = '<';
HTMLGreaterThan = '>';
HTMLQuote = '"';
var
i : positive;
procedure ReplaceChar(var strBuffer : string; strReplace : string; i : positive);
begin
delete(strBuffer, i, 1);
insert(strReplace, strBuffer, i)
end;
begin (* EscapeCharacters *)
repeat
i := pos(LessThanChar, s, 1);
if i > 0 then
ReplaceChar(s, HTMLLessThan, i)
until i = 0;
repeat
i := pos(GreaterThanChar, s, 1);
if i > 0 then
ReplaceChar(s, HTMLGreaterThan, i)
until i = 0;
repeat
i := pos(QuoteChar, s, 1);
if i > 0 then
ReplaceChar(s, HTMLQuote, i)
until i = 0;
EscapeCharacters := s;
end; (* EscapeCharacters *)
begin
Initialize;
GetCGIData(Cookies);
ProcessCGIData;
GenerateResponse;
Shutdown;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC MySQL API }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.MySQLCli;
interface
uses
FireDAC.Stan.Intf;
{------------------------------------------------------------------------------}
{ mysql_com.h }
{ Common definition between mysql server & client }
{------------------------------------------------------------------------------}
const
NAME_LEN = 64; // Field/table name length
HOSTNAME_LEN = 60;
USERNAME_LEN = 16;
SERVER_VERSION_LEN = 60;
SQLSTATE_LEN = 5;
LOCAL_HOST = 'localhost';
LOCAL_HOST_NAMEDPIPE = '.';
MYSQL_PORT = 3306; // Alloced by ISI for MySQL
MYSQL_UNIX_ADDR = '/tmp/mysql.sock';
MYSQL_NAMEDPIPE = 'MySQL';
MYSQL_SERVICENAME = 'MySql';
type
my_enum = Integer;
my_bool = Byte;
Pmy_bool = ^my_bool;
my_socket = Integer;
GPtr = PFDAnsiString;
PPByte = ^PByte;
my_pchar = PFDAnsiString;
my_ppchar = ^my_pchar;
my_ulong = LongWord;
my_long = LongInt;
my_size_t = TFDsize_t;
Pmy_ulong = ^my_ulong;
Pmy_long = ^my_long;
Pmy_size_t = ^my_size_t;
PNET = Pointer;
PMEM_ROOT = Pointer;
PMYSQL_FIELD = Pointer;
PMYSQL_ROWS = Pointer;
PPMYSQL_ROWS = ^PMYSQL_ROWS;
PMYSQL_DATA = Pointer;
PMYSQL_OPTIONS = Pointer;
PMYSQL = Pointer;
PMYSQL_RES = Pointer;
PMYSQL_BIND = Pointer;
PMYSQL_STMT = Pointer;
PMYSQL_METHODS = Pointer;
type
enum_server_command = my_enum;
const
COM_SLEEP = 0;
COM_QUIT = 1;
COM_INIT_DB = 2;
COM_QUERY = 3;
COM_FIELD_LIST = 4;
COM_CREATE_DB = 5;
COM_DROP_DB = 6;
COM_REFRESH = 7;
COM_SHUTDOWN = 8;
COM_STATISTICS = 9;
COM_PROCESS_INFO = 10;
COM_CONNECT = 11;
COM_PROCESS_KILL = 12;
COM_DEBUG = 13;
COM_PING = 14;
COM_TIME = 15;
COM_DELAYED_INSERT = 16;
COM_CHANGE_USER = 17;
COM_BINLOG_DUMP = 18;
COM_TABLE_DUMP = 19;
COM_CONNECT_OUT = 20;
{>= 4.0}
COM_REGISTER_SLAVE = 21;
{>= 4.1}
COM_STMT_PREPARE = 22;
COM_STMT_EXECUTE = 23;
COM_STMT_SEND_LONG_DATA = 24;
COM_STMT_CLOSE = 25;
COM_STMT_RESET = 26;
COM_SET_OPTION = 27;
{>= 5.0}
COM_STMT_FETCH = 28;
{>= 5.1}
COM_DAEMON = 29;
{>= 5.6}
COM_BINLOG_DUMP_GTID = 30;
COM_END = 31;
const
SCRAMBLE_LENGTH = 20;
SCRAMBLE_LENGTH_323 = 8;
NOT_NULL_FLAG = 1; // Field can't be NULL
PRI_KEY_FLAG = 2; // Field is part of a primary key
UNIQUE_KEY_FLAG = 4; // Field is part of a unique key
MULTIPLE_KEY_FLAG = 8; // Field is part of a key
BLOB_FLAG = 16; // Field is a blob
UNSIGNED_FLAG = 32; // Field is unsigned
ZEROFILL_FLAG = 64; // Field is zerofill
BINARY_FLAG = 128;
// The following are only sent to new clients
ENUM_FLAG = 256; // field is an enum
AUTO_INCREMENT_FLAG = 512; // field is a autoincrement field
TIMESTAMP_FLAG = 1024; // Field is a timestamp
SET_FLAG = 2048; // field is a set
NO_DEFAULT_VALUE_FLAG = 4096; // Field doesn't have default value
ON_UPDATE_NOW_FLAG = 8192; // Field is set to NOW on UPDATE
NUM_FLAG = 32768; // Field is num (for clients)
PART_KEY_FLAG = 16384; // Intern; Part of some key
GROUP_FLAG = 32768; // Intern: Group field
UNIQUE_FLAG = 65536; // Intern: Used by sql_yacc
{>= 4.1}
BINCMP_FLAG = 131072; // Intern: Used by sql_yacc
{>= 5.1}
GET_FIXED_FIELDS_FLAG = 1 shl 18; // Used to get fields in item tree
FIELD_IN_PART_FUNC_FLAG = 1 shl 19; // Field part of partition func
FIELD_IN_ADD_INDEX = 1 shl 20; // Intern: Field used in ADD INDEX
FIELD_IS_RENAMED = 1 shl 21; // Intern: Field is being renamed
REFRESH_GRANT = 1; // Refresh grant tables
REFRESH_LOG = 2; // Start on new log file
REFRESH_TABLES = 4; // close all tables
REFRESH_HOSTS = 8; // Flush host cache
REFRESH_STATUS = 16; // Flush status variables
REFRESH_THREADS = 32; // Flush status variables
REFRESH_SLAVE = 64; // Reset master info and restart slave thread
REFRESH_MASTER = 128; // Remove all bin logs in the index and truncate the index
// The following can't be set with mysql_refresh()
REFRESH_READ_LOCK = 16384; // Lock tables for read
REFRESH_FAST = 32768; // Intern flag
{>= 4.0}
// RESET (remove all queries) from query cache
REFRESH_QUERY_CACHE = 65536;
REFRESH_QUERY_CACHE_FREE = $20000; // pack query cache
REFRESH_DES_KEY_FILE = $40000;
REFRESH_USER_RESOURCES = $80000;
CLIENT_LONG_PASSWORD = 1; // new more secure passwords
CLIENT_FOUND_ROWS = 2; // Found instead of affected rows
CLIENT_LONG_FLAG = 4; // Get all column flags
CLIENT_CONNECT_WITH_DB = 8; // One can specify db on connect
CLIENT_NO_SCHEMA = 16; // Don't allow database.table.column
CLIENT_COMPRESS = 32; // Can use compression protocol
CLIENT_ODBC = 64; // Odbc client
CLIENT_LOCAL_FILES = 128; // Can use LOAD DATA LOCAL
CLIENT_IGNORE_SPACE = 256; // Ignore spaces before '('
{>= 4.0 begin}
CLIENT_CHANGE_USER = 512; // Support the mysql_change_user()
FD_50_CLIENT_PROTOCOL_41= 512; // New 4.1 protocol
{>= 4.0 end}
CLIENT_INTERACTIVE = 1024; // This is an interactive client
CLIENT_SSL = 2048; // Switch to SSL after handshake
CLIENT_IGNORE_SIGPIPE = 4096; // IGNORE sigpipes
CLIENT_TRANSACTIONS = 8192; // Client knows about transactions
{>= 4.1 begin}
CLIENT_PROTOCOL_41 = 16384; // New 4.1 protocol
FD_50_CLIENT_RESERVED = 16384; // Old flag for 4.1 protocol
CLIENT_SECURE_CONNECTION = 32768; // New 4.1 authentication
CLIENT_MULTI_STATEMENTS = 65536; // Enable/disable multi-stmt support
CLIENT_MULTI_QUERIES = CLIENT_MULTI_STATEMENTS;
CLIENT_MULTI_RESULTS = 131072; // Enable/disable multi-results
{>= 4.1 end}
{>= 5.5 begin}
CLIENT_PS_MULTI_RESULTS = 1 shl 18; // Multi-results in PS-protocol
CLIENT_PLUGIN_AUTH = 1 shl 19; // Client supports plugin authentication
{>= 5.5 end}
{>= 5.6 begin}
CLIENT_CONNECT_ATTRS = 1 shl 20; // Client supports connection attributes
// Enable authentication response packet to be larger than 255 bytes.
CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA = 1 shl 21;
// Don't close the connection for a connection with expired password.
CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS = 1 shl 22;
{>= 5.6 end}
{>= 5.0.6 begin}
CLIENT_SSL_VERIFY_SERVER_CERT = 1 shl 30;
CLIENT_REMEMBER_OPTIONS = 1 shl 31;
{>= 5.0.6 end}
SERVER_STATUS_IN_TRANS = 1; // Transaction has started
SERVER_STATUS_AUTOCOMMIT = 2; // Server in auto_commit mode
{>= 4.1 begin}
SERVER_STATUS_MORE_RESULTS = 4; // More results on server
SERVER_MORE_RESULTS_EXISTS = 8; // Multi query - next query exists
SERVER_QUERY_NO_GOOD_INDEX_USED = 16;
SERVER_QUERY_NO_INDEX_USED = 32;
{>= 4.1 end}
{>= 5.0.6 begin}
// The server was able to fulfill client request and open read-only
// non-scrollable cursor for the query. This flag comes in server
// status with reply to COM_EXECUTE and COM_EXECUTE_DIRECT commands.
SERVER_STATUS_CURSOR_EXISTS = 64;
// This flag is sent with last row of read-only cursor, in reply to
// COM_FETCH command.
SERVER_STATUS_LAST_ROW_SENT = 128;
{>= 5.0.6 end}
SERVER_STATUS_DB_DROPPED = 256;
{>= 5.1 begin}
SERVER_STATUS_NO_BACKSLASH_ESCAPES = 512;
SERVER_STATUS_METADATA_CHANGED = 1024;
{>= 5.1 end}
{>= 5.5 begin}
SERVER_QUERY_WAS_SLOW = 2048;
// To mark ResultSet containing output parameter values.
SERVER_PS_OUT_PARAMS = 4096;
{>= 5.1 end}
{>= 5.6 begin}
// Set at the same time as SERVER_STATUS_IN_TRANS if the started
// multi-statement transaction is a read-only transaction. Cleared
// when the transaction commits or aborts. Since this flag is sent
// to clients in OK and EOF packets, the flag indicates the
// transaction status at the end of command execution.
SERVER_STATUS_IN_TRANS_READONLY = 8192;
{>= 5.6 end}
MYSQL_ERRMSG_SIZE_0300 = 200;
MYSQL_ERRMSG_SIZE_0500 = 512;
NET_READ_TIMEOUT = 30; // Timeout on read
NET_WRITE_TIMEOUT = 60; // Timeout on write
NET_WAIT_TIMEOUT = 8*60*60; // Wait for new query
ONLY_KILL_QUERY = 1;
type
PNET0510 = ^NET0510;
NET0510 = record
vio: Pointer;
buff,
buff_end,
write_pos,
read_pos: my_pchar;
fd: my_socket;
// The following variable is set if we are doing several queries in one
// command ( as in LOAD TABLE ... FROM MASTER ),
// and do not want to confuse the client with OK at the wrong time
remain_in_buf,
length,
buf_length,
where_b: my_ulong;
max_packet,
max_packet_size: my_ulong;
pkt_nr,
compress_pkt_nr: Cardinal;
write_timeout,
read_timeout,
retry_count: Cardinal;
fcntl: Integer;
return_status: PCardinal;
reading_or_writing:Byte;
save_char: TFDAnsiChar;
unused0: my_bool; // Please remove with the next incompatible ABI change.
unused: my_bool; // Please remove with the next incompatible ABI change.
compress: my_bool;
unused1: my_bool; // Please remove with the next incompatible ABI change.
// Pointer to query object in query cache, do not equal NULL (0) for
// queries in cache that have not stored its results yet
// 'query_cache_query' should be accessed only via query cache
// functions and methods to maintain proper locking.
query_cache_query:GPtr;
last_errno: Cardinal;
error: Byte;
unused2: my_bool; // Please remove with the next incompatible ABI change.
return_errno: my_bool;
// Client library error message buffer. Actually belongs to struct MYSQL.
last_error: array[0 .. MYSQL_ERRMSG_SIZE_0500 - 1] of TFDAnsiChar;
// Client library sqlstate buffer. Set along with the error message.
sqlstate: array[0 .. SQLSTATE_LEN] of TFDAnsiChar;
extension: Pointer;
end;
PNET0506 = ^NET0506;
NET0506 = record
vio: Pointer;
buff,
buff_end,
write_pos,
read_pos: my_pchar;
fd: my_socket;
max_packet,
max_packet_size: my_ulong;
pkt_nr,
compress_pkt_nr: Cardinal;
write_timeout,
read_timeout,
retry_count: Cardinal;
fcntl: Integer;
compress: my_bool;
// The following variable is set if we are doing several queries in one
// command ( as in LOAD TABLE ... FROM MASTER ),
// and do not want to confuse the client with OK at the wrong time
remain_in_buf,
length,
buf_length,
where_b: my_ulong;
return_status: PCardinal;
reading_or_writing:Byte;
save_char: TFDAnsiChar;
no_send_ok: my_bool; // For SPs and other things that do multiple stmts
no_send_eof: my_bool; // For SPs' first version read-only cursors
// Set if OK packet is already sent, and we do not need to send error
// messages
no_send_error: my_bool;
// Pointer to query object in query cache, do not equal NULL (0) for
// queries in cache that have not stored its results yet
last_error: array[0 .. MYSQL_ERRMSG_SIZE_0500 - 1] of TFDAnsiChar;
sqlstate: array[0 .. SQLSTATE_LEN] of TFDAnsiChar;
last_errno: Cardinal;
error: Byte;
query_cache_query:GPtr;
report_error: my_bool; // We should report error (we have unreported error)
return_errno: my_bool;
end;
PNET0500 = ^NET0500;
NET0500 = record
vio: Pointer;
buff,
buff_end,
write_pos,
read_pos: my_pchar;
fd: my_socket;
max_packet,
max_packet_size: my_ulong;
pkt_nr,
compress_pkt_nr: Cardinal;
write_timeout,
read_timeout,
retry_count: Cardinal;
fcntl: Integer;
compress: my_bool;
// The following variable is set if we are doing several queries in one
// command ( as in LOAD TABLE ... FROM MASTER ),
// and do not want to confuse the client with OK at the wrong time
remain_in_buf,
length,
buf_length,
where_b: my_ulong;
return_status: PCardinal;
reading_or_writing:Byte;
save_char: TFDAnsiChar;
no_send_ok: my_bool; // For SPs and other things that do multiple stmts
no_send_eof: my_bool; // For SPs' first version read-only cursors
// Pointer to query object in query cache, do not equal NULL (0) for
// queries in cache that have not stored its results yet
last_error: array[0 .. MYSQL_ERRMSG_SIZE_0500 - 1] of TFDAnsiChar;
sqlstate: array[0 .. SQLSTATE_LEN] of TFDAnsiChar;
last_errno: Cardinal;
error: Byte;
query_cache_query:GPtr;
report_error: my_bool; // We should report error (we have unreported error)
return_errno: my_bool;
end;
PNET0410 = ^NET0410;
NET0410 = record
vio: Pointer;
buff,
buff_end,
write_pos,
read_pos: my_pchar;
fd: my_socket;
max_packet,
max_packet_size: my_ulong;
pkt_nr,
compress_pkt_nr: Cardinal;
write_timeout,
read_timeout,
retry_count: Cardinal;
fcntl: Integer;
compress: my_bool;
// The following variable is set if we are doing several queries in one
// command ( as in LOAD TABLE ... FROM MASTER ),
// and do not want to confuse the client with OK at the wrong time
remain_in_buf,
length,
buf_length,
where_b: my_ulong;
return_status: PCardinal;
reading_or_writing:Byte;
save_char: TFDAnsiChar;
no_send_ok: my_bool; // For SPs and other things that do multiple stmts
// Pointer to query object in query cache, do not equal NULL (0) for
// queries in cache that have not stored its results yet
last_error: array[0 .. MYSQL_ERRMSG_SIZE_0300 - 1] of TFDAnsiChar;
sqlstate: array[0 .. SQLSTATE_LEN] of TFDAnsiChar;
last_errno: Cardinal;
error: Byte;
query_cache_query:GPtr;
report_error: my_bool; // We should report error (we have unreported error)
return_errno: my_bool;
end;
PNET0400 = ^NET0400;
NET0400 = record
vio: Pointer;
buff,
buff_end,
write_pos,
read_pos: my_pchar;
fd: my_socket;
max_packet,
max_packet_size: my_ulong;
last_errno,
pkt_nr,
compress_pkt_nr: Cardinal;
write_timeout,
read_timeout,
retry_count: Cardinal;
fcntl: Integer;
last_error: array[0 .. MYSQL_ERRMSG_SIZE_0300 - 1] of TFDAnsiChar;
error: Byte;
return_errno,
compress: my_bool;
// The following variable is set if we are doing several queries in one
// command ( as in LOAD TABLE ... FROM MASTER ),
// and do not want to confuse the client with OK at the wrong time
remain_in_buf,
length,
buf_length,
where_b: my_ulong;
return_status: PCardinal;
reading_or_writing: Byte;
save_char: TFDAnsiChar;
no_send_ok: my_bool;
query_cache_query: GPtr;
end;
PNET0323 = ^NET0323;
NET0323 = record
vio: Pointer;
fd: my_socket;
fcntl: Integer; // For Perl DBI/dbd
buff,
buff_end,
write_pos,
read_pos: my_pchar;
last_error: array[0 .. MYSQL_ERRMSG_SIZE_0300 - 1] of TFDAnsiChar;
last_errno,
max_packet,
timeout,
pkt_nr: Cardinal;
error: Byte;
return_errno,
compress,
no_send_ok: my_bool; // needed if we are doing several queries in one
// command ( as in LOAD TABLE ... FROM MASTER ), and do not want to confuse
// the client with OK at the wrong time
remain_in_buf,
length,
buf_length,
where_b: my_ulong;
return_status: PCardinal;
reading_or_writing: Byte;
save_char: TFDAnsiChar;
end;
PNET0320 = ^NET0320;
NET0320 = record
vio: Pointer;
fd: my_socket;
fcntl: Integer; // For Perl DBI/dbd
buff,
buff_end,
write_pos,
read_pos: my_pchar;
last_error: array[0 .. MYSQL_ERRMSG_SIZE_0300 - 1] of TFDAnsiChar;
last_errno,
max_packet,
timeout,
pkt_nr: Cardinal;
error: Byte;
return_errno,
compress: my_bool;
remain_in_buf,
length,
buf_length,
where_b: my_ulong;
more: Byte;
save_char: TFDAnsiChar;
end;
{------------------------------------------------------------------------------}
{ mysql.h }
{ defines for the Libmysql }
{------------------------------------------------------------------------------}
type
PUSED_MEM = ^USED_MEM;
USED_MEM = record // struct for once_alloc
next: PUSED_MEM; // Next block in use
left: my_size_t; // memory left in block
size: my_size_t; // size of block
end;
TVoidProc = procedure;
PVoidProc = ^TVoidProc;
PSI_memory_key = Cardinal;
PMEM_ROOT0600 = ^MEM_ROOT0600;
MEM_ROOT0600 = record
free: PUSED_MEM;
used: PUSED_MEM;
pre_alloc: PUSED_MEM;
min_malloc: my_size_t;
block_size: my_size_t;
block_num: Cardinal;
first_block_usage: Cardinal;
error_handler: PVoidProc;
m_psi_key: PSI_memory_key;
end;
PMEM_ROOT0570 = ^MEM_ROOT0570;
MEM_ROOT0570 = record
free: PUSED_MEM;
used: PUSED_MEM;
pre_alloc: PUSED_MEM;
min_malloc: my_size_t;
block_size: my_size_t;
block_num: Cardinal;
first_block_usage: Cardinal;
max_capacity: my_size_t;
allocated_size: my_size_t;
error_for_capacity_exceeded: my_bool;
error_handler: PVoidProc;
m_psi_key: PSI_memory_key;
end;
PMEM_ROOT0410 = ^MEM_ROOT0410;
MEM_ROOT0410 = record
free: PUSED_MEM;
used: PUSED_MEM;
pre_alloc: PUSED_MEM;
min_malloc: my_size_t;
block_size: my_size_t;
block_num: Cardinal;
first_block_usage:Cardinal;
error_handler: PVoidProc;
end;
PMEM_ROOT0323 = ^MEM_ROOT0323;
MEM_ROOT0323 = record
free: PUSED_MEM;
used: PUSED_MEM;
pre_alloc: PUSED_MEM;
min_malloc: my_size_t;
block_size: my_size_t;
error_handler: PVoidProc;
end;
PMEM_ROOT0320 = ^MEM_ROOT0320;
MEM_ROOT0320 = record
free: PUSED_MEM;
used: PUSED_MEM;
min_malloc: my_size_t;
block_size: my_size_t;
error_handler: PVoidProc;
end;
PMYSQL_FIELD0510 = ^MYSQL_FIELD0510;
MYSQL_FIELD0510 = record
name: my_pchar; // Name of column
org_name: my_pchar; // Original column name, if an alias
table: my_pchar; // Table of column if column was a field
org_table: my_pchar; // Org table name if table was an alias
db: my_pchar; // Database for table
catalog: my_pchar; // Catalog for table
def: my_pchar; // Default value (set by mysql_list_fields)
length: my_ulong; // Width of column
max_length: my_ulong; // Max width of selected set
name_length: Cardinal;
org_name_length: Cardinal;
table_length: Cardinal;
org_table_length: Cardinal;
db_length: Cardinal;
catalog_length: Cardinal;
def_length: Cardinal;
flags: Cardinal; // Div flags
decimals: Cardinal; // Number of decimals in field
charsetnr: Cardinal; // Character set
type_: Byte; // Type of field. See enum_field_types.
extension: Pointer;
end;
PMYSQL_FIELD0410 = ^MYSQL_FIELD0410;
MYSQL_FIELD0410 = record
name: my_pchar; // Name of column
org_name: my_pchar; // Original column name, if an alias
table: my_pchar; // Table of column if column was a field
org_table: my_pchar; // Org table name if table was an alias
db: my_pchar; // Database for table
catalog: my_pchar; // Catalog for table
def: my_pchar; // Default value (set by mysql_list_fields)
length: my_ulong; // Width of column
max_length: my_ulong; // Max width of selected set
name_length: Cardinal;
org_name_length: Cardinal;
table_length: Cardinal;
org_table_length: Cardinal;
db_length: Cardinal;
catalog_length: Cardinal;
def_length: Cardinal;
flags: Cardinal; // Div flags
decimals: Cardinal; // Number of decimals in field
charsetnr: Cardinal; // Character set
type_: Byte; // Type of field. See enum_field_types.
end;
PMYSQL_FIELD0401 = ^MYSQL_FIELD0401;
MYSQL_FIELD0401 = record
name: my_pchar; // Name of column
org_name: my_pchar; // Original column name, if an alias
table: my_pchar; // Table of column if column was a field
org_table: my_pchar; // Org table name if table was an alias
db: my_pchar; // Database for table
def: my_pchar; // Default value (set by mysql_list_fields)
length: my_ulong; // Width of column
max_length: my_ulong; // Max width of selected set
name_length: Cardinal;
org_name_length: Cardinal;
table_length: Cardinal;
org_table_length: Cardinal;
db_length: Cardinal;
def_length: Cardinal;
flags: Cardinal; // Div flags
decimals: Cardinal; // Number of decimals in field
charsetnr: Cardinal; // Character set
type_: Byte; // Type of field. See mysql_com.h for types
end;
PMYSQL_FIELD0400 = ^MYSQL_FIELD0400;
MYSQL_FIELD0400 = record
name: my_pchar; // Name of column
table: my_pchar; // Table of column if column was a field
org_table: my_pchar; // Org table name if table was an alias
db: my_pchar; // Database for table
def: my_pchar; // Default value (set by mysql_list_fields)
length: my_ulong; // Width of column
max_length: my_ulong; // Max width of selected set
flags: Cardinal; // Div flags
decimals: Cardinal; // Number of decimals in field
type_: Byte; // Type of field. See mysql_com.h for types
end;
PMYSQL_FIELD0320 = ^MYSQL_FIELD0320;
MYSQL_FIELD0320 = record
name: my_pchar; // Name of column
table: my_pchar; // Table of column if column was a field
def: my_pchar; // Default value (set by mysql_list_fields)
type_: Byte; // Type of field. See mysql_com.h for types
length: Cardinal; // Width of column
max_length: Cardinal; // Max width of selected set
flags: Cardinal; // Div flags
decimals: Cardinal; // Number of decimals in field
end;
MYSQL_ROW = PPByte; // return data as array of strings
MYSQL_FIELD_OFFSET = Cardinal; // offset to current field
type
my_ulonglong = UInt64;
const
MYSQL_COUNT_ERROR: my_ulonglong = $FFFFFFFFFFFFFFFF;
type
PMYSQL_ROWS0410 = ^MYSQL_ROWS0410;
MYSQL_ROWS0410 = record
next: PMYSQL_ROWS; // list of rows
data: MYSQL_ROW;
length: my_long;
end;
PMYSQL_ROWS0320 = ^MYSQL_ROWS0320;
MYSQL_ROWS0320 = record
next: PMYSQL_ROWS; // list of rows
data: MYSQL_ROW;
end;
MYSQL_ROW_OFFSET = PMYSQL_ROWS; // offset to current row
PMYSQL_DATA0600 = ^MYSQL_DATA0600;
MYSQL_DATA0600 = record
data: PMYSQL_ROWS;
embedded_info: Pointer;
alloc: MEM_ROOT0600;
rows: my_ulonglong;
fields: Cardinal;
// extra info for embedded library
extension: Pointer;
end;
PMYSQL_DATA0570 = ^MYSQL_DATA0570;
MYSQL_DATA0570 = record
data: PMYSQL_ROWS;
embedded_info: Pointer;
alloc: MEM_ROOT0570;
rows: my_ulonglong;
fields: Cardinal;
// extra info for embedded library
extension: Pointer;
end;
PMYSQL_DATA0510 = ^MYSQL_DATA0510;
MYSQL_DATA0510 = record
data: PMYSQL_ROWS;
embedded_info: Pointer;
alloc: MEM_ROOT0410;
rows: my_ulonglong;
fields: Cardinal;
// extra info for embedded library
extension: Pointer;
end;
PMYSQL_DATA0506 = ^MYSQL_DATA0506;
MYSQL_DATA0506 = record
rows: my_ulonglong;
fields: Cardinal;
data: PMYSQL_ROWS;
alloc: MEM_ROOT0410;
prev_ptr: PPMYSQL_ROWS;
end;
PMYSQL_DATA0410 = ^MYSQL_DATA0410;
MYSQL_DATA0410 = record
rows: my_ulonglong;
fields: Cardinal;
data: PMYSQL_ROWS;
alloc: MEM_ROOT0410;
end;
PMYSQL_DATA0323 = ^MYSQL_DATA0323;
MYSQL_DATA0323 = record
rows: my_ulonglong;
fields: Cardinal;
data: PMYSQL_ROWS;
alloc: MEM_ROOT0323;
end;
PMYSQL_DATA0320 = ^MYSQL_DATA0320;
MYSQL_DATA0320 = record
rows: my_ulonglong;
fields: Cardinal;
data: PMYSQL_ROWS;
alloc: MEM_ROOT0320;
end;
type
mysql_option = my_enum;
const
MYSQL_OPT_CONNECT_TIMEOUT = 0;
MYSQL_OPT_COMPRESS = 1;
MYSQL_OPT_NAMED_PIPE = 2;
MYSQL_INIT_COMMAND = 3;
MYSQL_READ_DEFAULT_FILE = 4;
MYSQL_READ_DEFAULT_GROUP = 5;
MYSQL_SET_CHARSET_DIR = 6;
MYSQL_SET_CHARSET_NAME = 7;
MYSQL_OPT_LOCAL_INFILE = 8;
{>= 4.1 begin}
MYSQL_OPT_PROTOCOL = 9;
MYSQL_SHARED_MEMORY_BASE_NAME = 10;
MYSQL_OPT_READ_TIMEOUT = 11;
MYSQL_OPT_WRITE_TIMEOUT = 12;
MYSQL_OPT_USE_RESULT = 13;
MYSQL_OPT_USE_REMOTE_CONNECTION = 14;
MYSQL_OPT_USE_EMBEDDED_CONNECTION = 15;
MYSQL_OPT_GUESS_CONNECTION = 16;
MYSQL_SET_CLIENT_IP = 17;
MYSQL_SECURE_AUTH = 18;
{>= 4.1 end}
{>= 5.0.6 begin}
MYSQL_REPORT_DATA_TRUNCATION = 19;
{>= 5.0.6 end}
{>= 5.1 begin}
MYSQL_OPT_RECONNECT = 20;
MYSQL_OPT_SSL_VERIFY_SERVER_CERT = 21;
{>= 5.1 end}
type
PMYSQL_OPTIONS0510 = ^MYSQL_OPTIONS0510;
MYSQL_OPTIONS0510 = record
connect_timeout,
read_timeout,
write_timeout,
port,
protocol: Cardinal;
client_flag: my_ulong;
host,
user,
password,
unix_socket,
db: my_pchar;
init_commands: Pointer;
my_cnf_file,
my_cnf_group: my_pchar;
charset_dir,
charset_name: my_pchar;
ssl_key, // PEM key file
ssl_cert, // PEM cert file
ssl_ca, // PEM CA file
ssl_capath, // PEM directory of CA-s?
ssl_cipher: my_pchar; // cipher to use
shared_memory_base_name: my_pchar;
max_allowed_packet: my_ulong;
use_ssl: my_bool; // if to use SSL or not
compress,
named_pipe: my_bool;
// On connect, find out the replication role of the server, and
// establish connections to all the peers
rpl_probe: my_bool;
// Each call to mysql_real_query() will parse it to tell if it is a read
// or a write, and direct it to the slave or the master
rpl_parse: my_bool;
// If set, never read from a master,only from slave, when doing
// a read that is replication-aware
no_master_reads: my_bool;
separate_thread: my_bool;
methods_to_use: mysql_option;
client_ip: my_pchar;
// Refuse client connecting to server if it uses old (pre-4.1.1) protocol
secure_auth: my_bool;
// 0 - never report, 1 - always report (default)
report_data_truncation: my_bool;
// function pointers for local infile support
local_infile_init: Pointer;
local_infile_read: Pointer;
local_infile_end: Pointer;
local_infile_error:Pointer;
local_infile_userdata: Pointer;
extension: Pointer;
end;
PMYSQL_OPTIONS0506 = ^MYSQL_OPTIONS0506;
MYSQL_OPTIONS0506 = record
connect_timeout,
read_timeout,
write_timeout,
port,
protocol,
client_flag: Cardinal;
host,
user,
password,
unix_socket,
db: my_pchar;
init_commands: Pointer;
my_cnf_file,
my_cnf_group: my_pchar;
charset_dir,
charset_name: my_pchar;
ssl_key, // PEM key file
ssl_cert, // PEM cert file
ssl_ca, // PEM CA file
ssl_capath, // PEM directory of CA-s?
ssl_cipher: my_pchar; // cipher to use
shared_memory_base_name: my_pchar;
max_allowed_packet: my_ulong;
use_ssl: my_bool; // if to use SSL or not
compress,
named_pipe: my_bool;
// On connect, find out the replication role of the server, and
// establish connections to all the peers
rpl_probe: my_bool;
// Each call to mysql_real_query() will parse it to tell if it is a read
// or a write, and direct it to the slave or the master
rpl_parse: my_bool;
// If set, never read from a master,only from slave, when doing
// a read that is replication-aware
no_master_reads: my_bool;
separate_thread: my_bool;
methods_to_use: mysql_option;
client_ip: my_pchar;
// Refuse client connecting to server if it uses old (pre-4.1.1) protocol
secure_auth: my_bool;
// 0 - never report, 1 - always report (default)
report_data_truncation: my_bool;
// function pointers for local infile support
local_infile_init: Pointer;
local_infile_read: Pointer;
local_infile_end: Pointer;
local_infile_error:Pointer;
local_infile_userdata: Pointer;
end;
PMYSQL_OPTIONS0410 = ^MYSQL_OPTIONS0410;
MYSQL_OPTIONS0410 = record
connect_timeout,
read_timeout,
write_timeout,
port,
protocol,
client_flag: Cardinal;
host,
user,
password,
unix_socket,
db: my_pchar;
init_commands: Pointer;
my_cnf_file,
my_cnf_group: my_pchar;
charset_dir,
charset_name: my_pchar;
ssl_key, // PEM key file
ssl_cert, // PEM cert file
ssl_ca, // PEM CA file
ssl_capath, // PEM directory of CA-s?
ssl_cipher: my_pchar; // cipher to use
shared_memory_base_name: my_pchar;
max_allowed_packet: my_ulong;
use_ssl: my_bool; // if to use SSL or not
compress,
named_pipe: my_bool;
// On connect, find out the replication role of the server, and
// establish connections to all the peers
rpl_probe: my_bool;
// Each call to mysql_real_query() will parse it to tell if it is a read
// or a write, and direct it to the slave or the master
rpl_parse: my_bool;
// If set, never read from a master,only from slave, when doing
// a read that is replication-aware
no_master_reads: my_bool;
methods_to_use: mysql_option;
client_ip: my_pchar;
// Refuse client connecting to server if it uses old (pre-4.1.1) protocol
secure_auth: my_bool;
// function pointers for local infile support
local_infile_init: Pointer;
local_infile_read: Pointer;
local_infile_end: Pointer;
local_infile_error:Pointer;
local_infile_userdata: Pointer;
end;
PMYSQL_OPTIONS0400 = ^MYSQL_OPTIONS0400;
MYSQL_OPTIONS0400 = record
connect_timeout,
client_flag: Cardinal;
port: Cardinal;
host,
init_command,
user,
password,
unix_socket,
db: my_pchar;
my_cnf_file,
my_cnf_group: my_pchar;
charset_dir,
charset_name: my_pchar;
ssl_key, // PEM key file
ssl_cert, // PEM cert file
ssl_ca, // PEM CA file
ssl_capath, // PEM directory of CA-s?
ssl_cipher: my_pchar; // cipher to use
max_allowed_packet: my_ulong;
use_ssl: my_bool; // if to use SSL or not
compress,
named_pipe: my_bool;
// On connect, find out the replication role of the server, and
// establish connections to all the peers
rpl_probe: my_bool;
// Each call to mysql_real_query() will parse it to tell if it is a read
// or a write, and direct it to the slave or the master
rpl_parse: my_bool;
// If set, never read from a master,only from slave, when doing
// a read that is replication-aware
no_master_reads: my_bool;
end;
PMYSQL_OPTIONS0320 = ^MYSQL_OPTIONS0320;
MYSQL_OPTIONS0320 = record
connect_timeout,
client_flag: Cardinal;
compress,
named_pipe: my_bool;
port: Cardinal;
host,
init_command,
user,
password,
unix_socket,
db: my_pchar;
my_cnf_file,
my_cnf_group: my_pchar;
charset_dir,
charset_name: my_pchar;
use_ssl: my_bool; // if to use SSL or not
ssl_key, // PEM key file
ssl_cert, // PEM cert file
ssl_ca, // PEM CA file
ssl_capath: my_pchar; // PEM directory of CA-s?
end;
type
mysql_status = my_enum;
const
MYSQL_STATUS_READY = 0;
MYSQL_STATUS_GET_RESULT = 1;
MYSQL_STATUS_USE_RESULT = 2;
{>= 4.1 begin}
type
mysql_protocol_type = my_enum;
const
MYSQL_PROTOCOL_DEFAULT = 0;
MYSQL_PROTOCOL_TCP = 1;
MYSQL_PROTOCOL_SOCKET = 2;
MYSQL_PROTOCOL_PIPE = 3;
MYSQL_PROTOCOL_MEMORY = 4;
{>= 4.1 end}
{>= 4.0 begin}
// There are three types of queries - the ones that have to go to
// the master, the ones that go to a slave, and the adminstrative
// type which must happen on the pivot connectioin
type
mysql_rpl_type = my_enum;
const
MYSQL_RPL_MASTER = 0;
MYSQL_RPL_SLAVE = 1;
MYSQL_RPL_ADMIN = 2;
{>= 4.0 end}
{>= 4.1 begin}
type
PMYSQL_METHODS0510 = ^MYSQL_METHODS0510;
MYSQL_METHODS0510 = record
read_query_result: function (mysql: PMYSQL): my_bool;
advanced_command: function (mysql: PMYSQL; command: enum_server_command;
header: PByte; header_length: my_ulong; arg: PByte; arg_length: my_ulong;
skip_check: my_bool; stmt: PMYSQL_STMT): my_bool;
read_rows: function (mysql: PMYSQL; mysql_fields: PMYSQL_FIELD;
fields: Cardinal): PMYSQL_DATA;
use_result: function (mysql: PMYSQL): PMYSQL_RES;
fetch_lengths: procedure (_to: Pmy_ulong; column: MYSQL_ROW;
field_count: Cardinal);
flush_use_result: procedure (mysql: PMYSQL);
list_fields: function (mysql: PMYSQL): PMYSQL_FIELD;
read_prepare_result: function (mysql: PMYSQL; stmt: PMYSQL_STMT): my_bool;
stmt_execute: function (stmt: PMYSQL_STMT): Integer;
read_binary_rows: function (stmt: PMYSQL_STMT): Integer;
unbuffered_fetch: function (mysql: PMYSQL; row: PPChar): Integer;
free_embedded_thd: procedure (mysql: PMYSQL);
read_statistics: function (mysql: PMYSQL): my_pchar;
next_result: function (mysql: PMYSQL): my_bool;
read_change_user_result: function (mysql: PMYSQL; buff: my_pchar;
passwd: my_pchar): Integer;
read_rows_from_cursor: function (stmt: PMYSQL_STMT): Integer;
end;
PMYSQL_METHODS0506 = ^MYSQL_METHODS0506;
MYSQL_METHODS0506 = record
read_query_result: function (mysql: PMYSQL): my_bool;
advanced_command: function (mysql: PMYSQL; command: enum_server_command;
header: my_pchar; header_length: my_ulong; arg: my_pchar; arg_length: my_ulong;
skip_check: my_bool): my_bool;
read_rows: function (mysql: PMYSQL; mysql_fields: PMYSQL_FIELD;
fields: Cardinal): PMYSQL_DATA;
use_result: function (mysql: PMYSQL): PMYSQL_RES;
fetch_lengths: procedure (_to: Pmy_ulong; column: MYSQL_ROW;
field_count: Cardinal);
flush_use_result: procedure (mysql: PMYSQL);
list_fields: function (mysql: PMYSQL): PMYSQL_FIELD;
read_prepare_result: function (mysql: PMYSQL; stmt: PMYSQL_STMT): my_bool;
stmt_execute: function (stmt: PMYSQL_STMT): Integer;
read_binary_rows: function (stmt: PMYSQL_STMT): Integer;
unbuffered_fetch: function (mysql: PMYSQL; row: PPChar): Integer;
free_embedded_thd: procedure (mysql: PMYSQL);
read_statistics: function (mysql: PMYSQL): my_pchar;
next_result: function (mysql: PMYSQL): my_bool;
read_change_user_result: function (mysql: PMYSQL; buff: my_pchar;
passwd: my_pchar): Integer;
end;
PMYSQL_METHODS0410 = ^MYSQL_METHODS0410;
MYSQL_METHODS0410 = record
read_query_result: function (mysql: PMYSQL): my_bool;
advanced_command: function (mysql: PMYSQL; command: enum_server_command;
header: my_pchar; header_length: my_ulong; arg: my_pchar; arg_length: my_ulong;
skip_check: my_bool): my_bool;
read_rows: function (mysql: PMYSQL; mysql_fields: PMYSQL_FIELD;
fields: Cardinal): PMYSQL_DATA;
use_result: function (mysql: PMYSQL): PMYSQL_RES;
fetch_lengths: procedure (_to: Pmy_ulong; column: MYSQL_ROW;
field_count: Cardinal);
list_fields: function (mysql: PMYSQL): PMYSQL_FIELD;
read_prepare_result: function (mysql: PMYSQL; stmt: PMYSQL_STMT): my_bool;
stmt_execute: function (stmt: PMYSQL_STMT): Integer;
read_binary_rows: function (stmt: PMYSQL_STMT): Integer;
unbuffered_fetch: function (mysql: PMYSQL; row: PPChar): Integer;
free_embedded_thd: procedure (mysql: PMYSQL);
read_statistics: function (mysql: PMYSQL): my_pchar;
next_result: function (mysql: PMYSQL): my_bool;
read_change_user_result: function (mysql: PMYSQL; buff: my_pchar;
passwd: my_pchar): Integer;
end;
{>= 4.1 end}
PMYSQL_LIST = ^MYSQL_LIST;
MYSQL_LIST = record
prev, next: PMYSQL_LIST;
data: Pointer;
end;
PMY_CHARSET_INFO = ^MY_CHARSET_INFO;
MY_CHARSET_INFO = record
number: Cardinal; // character set number
state: Cardinal; // character set state
csname: my_pchar; // collation name
name: my_pchar; // character set name
comment: my_pchar; // comment
dir: my_pchar; // character set directory
mbminlen: Cardinal; // min. length for multibyte strings
mbmaxlen: Cardinal; // max. length for multibyte strings
end;
PMYSQL0600 = ^MYSQL0600;
MYSQL0600 = record
net: NET0510; // Communication parameters
connector_fd: GPtr; // ConnectorFd for SSL
host,
user,
passwd,
unix_socket,
server_version,
host_info,
info,
db: my_pchar;
charset: PMY_CHARSET_INFO;
fields: PMYSQL_FIELD0510;
field_alloc: MEM_ROOT0600;
affected_rows,
insert_id, // id if insert on table with NEXTNR
extra_info: my_ulonglong; // Used by mysqlshow
thread_id: LongWord; // Id for connection in server
packet_length: LongWord;
port: Cardinal;
client_flag,
server_capabilities: LongWord;
protocol_version: Cardinal;
field_count: Cardinal;
server_status: Cardinal;
server_language: Cardinal;
warning_count: Cardinal;
options: MYSQL_OPTIONS0510;
status: mysql_status;
free_me, // If free in mysql_close
reconnect: my_bool; // set to 1 if automatic reconnect
scramble: array[0..SCRAMBLE_LENGTH] of TFDAnsiChar;
// Set if this is the original connection, not a master or a slave we have
// added though mysql_rpl_probe() or mysql_set_master()/ mysql_add_slave()
rpl_pivot: my_bool;
// Pointers to the master, and the next slave connections, points to
// itself if lone connection.
master,
next_slave: PMYSQL;
last_used_slave: PMYSQL; // needed for round-robin slave pick
// needed for send/read/store/use result to work correctly with replication
last_used_con: PMYSQL;
stmts: PMYSQL_LIST; // list of all statements
methods: PMYSQL_METHODS0510;
thd: Pointer;
// Points to boolean flag in MYSQL_RES or MYSQL_STMT. We set this flag
// from mysql_stmt_close if close had to cancel result set of this object.
unbuffered_fetch_owner: my_bool;
// needed for embedded server - no net buffer to store the 'info'
info_buffer: my_pchar;
extension: Pointer;
end;
PMYSQL0570 = ^MYSQL0570;
MYSQL0570 = record
net: NET0510; // Communication parameters
connector_fd: GPtr; // ConnectorFd for SSL
host,
user,
passwd,
unix_socket,
server_version,
host_info,
info,
db: my_pchar;
charset: PMY_CHARSET_INFO;
fields: PMYSQL_FIELD0510;
field_alloc: MEM_ROOT0570;
affected_rows,
insert_id, // id if insert on table with NEXTNR
extra_info: my_ulonglong; // Used by mysqlshow
thread_id: LongWord; // Id for connection in server
packet_length: LongWord;
port: Cardinal;
client_flag,
server_capabilities: LongWord;
protocol_version: Cardinal;
field_count: Cardinal;
server_status: Cardinal;
server_language: Cardinal;
warning_count: Cardinal;
options: MYSQL_OPTIONS0510;
status: mysql_status;
free_me, // If free in mysql_close
reconnect: my_bool; // set to 1 if automatic reconnect
scramble: array[0..SCRAMBLE_LENGTH] of TFDAnsiChar;
// Set if this is the original connection, not a master or a slave we have
// added though mysql_rpl_probe() or mysql_set_master()/ mysql_add_slave()
rpl_pivot: my_bool;
// Pointers to the master, and the next slave connections, points to
// itself if lone connection.
master,
next_slave: PMYSQL;
last_used_slave: PMYSQL; // needed for round-robin slave pick
// needed for send/read/store/use result to work correctly with replication
last_used_con: PMYSQL;
stmts: PMYSQL_LIST; // list of all statements
methods: PMYSQL_METHODS0510;
thd: Pointer;
// Points to boolean flag in MYSQL_RES or MYSQL_STMT. We set this flag
// from mysql_stmt_close if close had to cancel result set of this object.
unbuffered_fetch_owner: my_bool;
// needed for embedded server - no net buffer to store the 'info'
info_buffer: my_pchar;
extension: Pointer;
end;
PMYSQL0510 = ^MYSQL0510;
MYSQL0510 = record
net: NET0510; // Communication parameters
connector_fd: GPtr; // ConnectorFd for SSL
host,
user,
passwd,
unix_socket,
server_version,
host_info,
info,
db: my_pchar;
charset: PMY_CHARSET_INFO;
fields: PMYSQL_FIELD0510;
field_alloc: MEM_ROOT0410;
affected_rows,
insert_id, // id if insert on table with NEXTNR
extra_info: my_ulonglong; // Used by mysqlshow
thread_id: LongWord; // Id for connection in server
packet_length: LongWord;
port: Cardinal;
client_flag,
server_capabilities: LongWord;
protocol_version: Cardinal;
field_count: Cardinal;
server_status: Cardinal;
server_language: Cardinal;
warning_count: Cardinal;
options: MYSQL_OPTIONS0510;
status: mysql_status;
free_me, // If free in mysql_close
reconnect: my_bool; // set to 1 if automatic reconnect
scramble: array[0..SCRAMBLE_LENGTH] of TFDAnsiChar;
// Set if this is the original connection, not a master or a slave we have
// added though mysql_rpl_probe() or mysql_set_master()/ mysql_add_slave()
rpl_pivot: my_bool;
// Pointers to the master, and the next slave connections, points to
// itself if lone connection.
master,
next_slave: PMYSQL;
last_used_slave: PMYSQL; // needed for round-robin slave pick
// needed for send/read/store/use result to work correctly with replication
last_used_con: PMYSQL;
stmts: PMYSQL_LIST; // list of all statements
methods: PMYSQL_METHODS0510;
thd: Pointer;
// Points to boolean flag in MYSQL_RES or MYSQL_STMT. We set this flag
// from mysql_stmt_close if close had to cancel result set of this object.
unbuffered_fetch_owner: my_bool;
// needed for embedded server - no net buffer to store the 'info'
info_buffer: my_pchar;
extension: Pointer;
end;
PMYSQL0506 = ^MYSQL0506;
MYSQL0506 = record
net: NET0506; // Communication parameters
connector_fd: GPtr; // ConnectorFd for SSL
host,
user,
passwd,
unix_socket,
server_version,
host_info,
info,
db: my_pchar;
charset: PMY_CHARSET_INFO;
fields: PMYSQL_FIELD;
field_alloc: MEM_ROOT0410;
affected_rows,
insert_id, // id if insert on table with NEXTNR
extra_info: my_ulonglong; // Used by mysqlshow
thread_id: LongWord; // Id for connection in server
packet_length: LongWord;
port: Cardinal;
client_flag,
server_capabilities: LongWord;
protocol_version: Cardinal;
field_count: Cardinal;
server_status: Cardinal;
server_language: Cardinal;
warning_count: Cardinal;
options: MYSQL_OPTIONS0506;
status: mysql_status;
free_me, // If free in mysql_close
reconnect: my_bool; // set to 1 if automatic reconnect
scramble: array[0..SCRAMBLE_LENGTH] of TFDAnsiChar;
// Set if this is the original connection, not a master or a slave we have
// added though mysql_rpl_probe() or mysql_set_master()/ mysql_add_slave()
rpl_pivot: my_bool;
// Pointers to the master, and the next slave connections, points to
// itself if lone connection.
master,
next_slave: PMYSQL;
last_used_slave: PMYSQL; // needed for round-robin slave pick
// needed for send/read/store/use result to work correctly with replication
last_used_con: PMYSQL;
stmts: PMYSQL_LIST; // list of all statements
methods: PMYSQL_METHODS0506;
thd: Pointer;
// Points to boolean flag in MYSQL_RES or MYSQL_STMT. We set this flag
// from mysql_stmt_close if close had to cancel result set of this object.
unbuffered_fetch_owner: my_bool;
// needed for embedded server - no net buffer to store the 'info'
info_buffer: my_pchar;
end;
PMYSQL0500 = ^MYSQL0500;
MYSQL0500 = record
net: NET0500; // Communication parameters
connector_fd: GPtr; // ConnectorFd for SSL
host,
user,
passwd,
unix_socket,
server_version,
host_info,
info,
db: my_pchar;
charset: PMY_CHARSET_INFO;
fields: PMYSQL_FIELD;
field_alloc: MEM_ROOT0410;
affected_rows,
insert_id, // id if insert on table with NEXTNR
extra_info: my_ulonglong; // Used by mysqlshow
thread_id: LongWord; // Id for connection in server
packet_length: LongWord;
port: Cardinal;
client_flag,
server_capabilities: LongWord;
protocol_version: Cardinal;
field_count: Cardinal;
server_status: Cardinal;
server_language: Cardinal;
warning_count: Cardinal;
options: MYSQL_OPTIONS0410;
status: mysql_status;
free_me, // If free in mysql_close
reconnect: my_bool; // set to 1 if automatic reconnect
scramble: array[0..SCRAMBLE_LENGTH] of TFDAnsiChar;
// Set if this is the original connection, not a master or a slave we have
// added though mysql_rpl_probe() or mysql_set_master()/ mysql_add_slave()
rpl_pivot: my_bool;
// Pointers to the master, and the next slave connections, points to
// itself if lone connection.
master,
next_slave: PMYSQL;
last_used_slave: PMYSQL; // needed for round-robin slave pick
// needed for send/read/store/use result to work correctly with replication
last_used_con: PMYSQL;
stmts: PMYSQL_LIST; // list of all statements
methods: PMYSQL_METHODS;
thd: Pointer;
// Points to boolean flag in MYSQL_RES or MYSQL_STMT. We set this flag
// from mysql_stmt_close if close had to cancel result set of this object.
unbuffered_fetch_owner: my_bool;
// needed for embedded server - no net buffer to store the 'info'
info_buffer: my_pchar;
end;
PMYSQL0410 = ^MYSQL0410;
MYSQL0410 = record
net: NET0410; // Communication parameters
connector_fd: GPtr; // ConnectorFd for SSL
host,
user,
passwd,
unix_socket,
server_version,
host_info,
info,
db: my_pchar;
charset: PMY_CHARSET_INFO;
fields: PMYSQL_FIELD;
field_alloc: MEM_ROOT0410;
affected_rows,
insert_id, // id if insert on table with NEXTNR
extra_info: my_ulonglong; // Used by mysqlshow
thread_id: LongWord; // Id for connection in server
packet_length: LongWord;
port,
client_flag,
server_capabilities: Cardinal;
protocol_version: Cardinal;
field_count: Cardinal;
server_status: Cardinal;
server_language: Cardinal;
warning_count: Cardinal;
options: MYSQL_OPTIONS0410;
status: mysql_status;
free_me, // If free in mysql_close
reconnect: my_bool; // set to 1 if automatic reconnect
scramble: array[0..SCRAMBLE_LENGTH] of TFDAnsiChar;
// Set if this is the original connection, not a master or a slave we have
// added though mysql_rpl_probe() or mysql_set_master()/ mysql_add_slave()
rpl_pivot: my_bool;
// Pointers to the master, and the next slave connections, points to
// itself if lone connection.
master,
next_slave: PMYSQL;
last_used_slave: PMYSQL; // needed for round-robin slave pick
// needed for send/read/store/use result to work correctly with replication
last_used_con: PMYSQL;
stmts: PMYSQL_LIST; // list of all statements
methods: PMYSQL_METHODS;
thd: Pointer;
// Points to boolean flag in MYSQL_RES or MYSQL_STMT. We set this flag
// from mysql_stmt_close if close had to cancel result set of this object.
unbuffered_fetch_owner: my_bool;
end;
PMYSQL0400 = ^MYSQL0400;
MYSQL0400 = record
net: NET0400; // Communication parameters
connector_fd: GPtr; // ConnectorFd for SSL
host,
user,
passwd,
unix_socket,
server_version,
host_info,
info,
db: my_pchar;
charset: PMY_CHARSET_INFO;
fields: PMYSQL_FIELD;
field_alloc: MEM_ROOT0323;
affected_rows,
insert_id, // id if insert on table with NEXTNR
extra_info: my_ulonglong; // Used by mysqlshow
thread_id: LongWord; // Id for connection in server
packet_length: LongWord;
port,
client_flag,
server_capabilities: Cardinal;
protocol_version: Cardinal;
field_count: Cardinal;
server_status: Cardinal;
server_language: Cardinal;
options: MYSQL_OPTIONS0400;
status: mysql_status;
free_me, // If free in mysql_close
reconnect: my_bool; // set to 1 if automatic reconnect
scramble_buff: array[0..SCRAMBLE_LENGTH_323] of TFDAnsiChar;
// Set if this is the original connection, not a master or a slave we have
// added though mysql_rpl_probe() or mysql_set_master()/ mysql_add_slave()
rpl_pivot: my_bool;
// Pointers to the master, and the next slave connections, points to
// itself if lone connection.
master,
next_slave: PMYSQL;
last_used_slave: PMYSQL; // needed for round-robin slave pick
// needed for send/read/store/use result to work correctly with replication
last_used_con: PMYSQL;
end;
PMYSQL0323 = ^MYSQL0323;
MYSQL0323 = record
net: NET0323; // Communication parameters
connector_fd: GPtr; // ConnectorFd for SSL
host,
user,
passwd,
unix_socket,
server_version,
host_info,
info,
db: my_pchar;
port,
client_flag,
server_capabilities: Cardinal;
protocol_version: Cardinal;
field_count: Cardinal;
server_status: Cardinal;
thread_id: LongWord; // Id for connection in server
affected_rows,
insert_id, // id if insert on table with NEXTNR
extra_info: my_ulonglong; // Used by mysqlshow
packet_length: LongWord;
status: mysql_status;
fields: PMYSQL_FIELD;
field_alloc: MEM_ROOT0323;
free_me, // If free in mysql_close
reconnect: my_bool; // set to 1 if automatic reconnect
options: MYSQL_OPTIONS0320;
scramble_buff: array[0..SCRAMBLE_LENGTH_323] of TFDAnsiChar;
charset: PMY_CHARSET_INFO;
server_language: Cardinal;
end;
PMYSQL0320 = ^MYSQL0320;
MYSQL0320 = record
net: NET0320; // Communication parameters
connector_fd: GPtr; // ConnectorFd for SSL
host,
user,
passwd,
unix_socket,
server_version,
host_info,
info,
db: my_pchar;
port,
client_flag,
server_capabilities: Cardinal;
protocol_version: Cardinal;
field_count: Cardinal;
thread_id: LongWord; // Id for connection in server
affected_rows,
insert_id, // id if insert on table with NEXTNR
extra_info: my_ulonglong; // Used by mysqlshow
packet_length: LongWord;
status: mysql_status;
fields: PMYSQL_FIELD;
field_alloc: MEM_ROOT0320;
free_me, // If free in mysql_close
reconnect: my_bool; // set to 1 if automatic reconnect
options: MYSQL_OPTIONS0320;
scramble_buff: array[0..SCRAMBLE_LENGTH_323] of TFDAnsiChar;
charset: PMY_CHARSET_INFO;
end;
PMYSQL_RES0600 = ^MYSQL_RES0600;
MYSQL_RES0600 = record
row_count: my_ulonglong;
fields: PMYSQL_FIELD0510;
data: PMYSQL_DATA0600;
data_cursor: PMYSQL_ROWS0410;
lengths: Pmy_long; // column lengths of current row
handle: PMYSQL0600; // for unbuffered reads
methods: PMYSQL_METHODS0510;
row: MYSQL_ROW; // If unbuffered read
current_row: MYSQL_ROW; // buffer to current row
field_alloc: MEM_ROOT0600;
field_count,
current_field: Cardinal;
eof: my_bool; // Used my mysql_fetch_row
// mysql_stmt_close() had to cancel this result
unbuffered_fetch_cancelled: my_bool;
extension: Pointer;
end;
PMYSQL_RES0570 = ^MYSQL_RES0570;
MYSQL_RES0570 = record
row_count: my_ulonglong;
fields: PMYSQL_FIELD0510;
data: PMYSQL_DATA0570;
data_cursor: PMYSQL_ROWS0410;
lengths: Pmy_long; // column lengths of current row
handle: PMYSQL0570; // for unbuffered reads
methods: PMYSQL_METHODS0510;
row: MYSQL_ROW; // If unbuffered read
current_row: MYSQL_ROW; // buffer to current row
field_alloc: MEM_ROOT0570;
field_count,
current_field: Cardinal;
eof: my_bool; // Used my mysql_fetch_row
// mysql_stmt_close() had to cancel this result
unbuffered_fetch_cancelled: my_bool;
extension: Pointer;
end;
PMYSQL_RES0510 = ^MYSQL_RES0510;
MYSQL_RES0510 = record
row_count: my_ulonglong;
fields: PMYSQL_FIELD0510;
data: PMYSQL_DATA0510;
data_cursor: PMYSQL_ROWS0410;
lengths: Pmy_long; // column lengths of current row
handle: PMYSQL0510; // for unbuffered reads
methods: PMYSQL_METHODS0510;
row: MYSQL_ROW; // If unbuffered read
current_row: MYSQL_ROW; // buffer to current row
field_alloc: MEM_ROOT0410;
field_count,
current_field: Cardinal;
eof: my_bool; // Used my mysql_fetch_row
// mysql_stmt_close() had to cancel this result
unbuffered_fetch_cancelled: my_bool;
extension: Pointer;
end;
PMYSQL_RES0410 = ^MYSQL_RES0410;
MYSQL_RES0410 = record
row_count: my_ulonglong;
fields: PMYSQL_FIELD;
data: PMYSQL_DATA;
data_cursor: PMYSQL_ROWS;
lengths: Pmy_long; // column lengths of current row
handle: PMYSQL; // for unbuffered reads
field_alloc: MEM_ROOT0410;
field_count,
current_field: Cardinal;
row: MYSQL_ROW; // If unbuffered read
current_row: MYSQL_ROW; // buffer to current row
eof: my_bool; // Used my mysql_fetch_row
// mysql_stmt_close() had to cancel this result
unbuffered_fetch_cancelled: my_bool;
methods: PMYSQL_METHODS;
end;
PMYSQL_RES0323 = ^MYSQL_RES0323;
MYSQL_RES0323 = record
row_count: my_ulonglong;
field_count,
current_field: Cardinal;
fields: PMYSQL_FIELD;
data: PMYSQL_DATA;
data_cursor: PMYSQL_ROWS;
field_alloc: MEM_ROOT0323;
row: MYSQL_ROW; // If unbuffered read
current_row: MYSQL_ROW; // buffer to current row
lengths: Pmy_long; // column lengths of current row
handle: PMYSQL; // for unbuffered reads
eof: my_bool; // Used my mysql_fetch_row
end;
PMYSQL_RES0320 = ^MYSQL_RES0320;
MYSQL_RES0320 = record
row_count: my_ulonglong;
field_count,
current_field: Cardinal;
fields: PMYSQL_FIELD;
data: PMYSQL_DATA;
data_cursor: PMYSQL_ROWS;
field_alloc: MEM_ROOT0320;
row: MYSQL_ROW; // If unbuffered read
current_row: MYSQL_ROW; // buffer to current row
lengths: Pmy_long; // column lengths of current row
handle: PMYSQL; // for unbuffered reads
eof: my_bool; // Used my mysql_fetch_row
end;
{------------------------------------------------------------------------------}
{ The following definitions are added for the enhanced }
{ client-server protocol }
{------------------------------------------------------------------------------}
type
enum_field_types = my_enum;
const
MYSQL_TYPE_DECIMAL = 0;
MYSQL_TYPE_TINY = 1;
MYSQL_TYPE_SHORT = 2;
MYSQL_TYPE_LONG = 3;
MYSQL_TYPE_FLOAT = 4;
MYSQL_TYPE_DOUBLE = 5;
MYSQL_TYPE_NULL = 6;
MYSQL_TYPE_TIMESTAMP = 7;
MYSQL_TYPE_LONGLONG = 8;
MYSQL_TYPE_INT24 = 9;
MYSQL_TYPE_DATE = 10;
MYSQL_TYPE_TIME = 11;
MYSQL_TYPE_DATETIME = 12;
MYSQL_TYPE_YEAR = 13;
MYSQL_TYPE_NEWDATE = 14;
{>= 5.0.6 begin}
MYSQL_TYPE_VARCHAR = 15;
MYSQL_TYPE_BIT = 16;
{>= 5.7}
MYSQL_TYPE_JSON = 245;
MYSQL_TYPE_NEWDECIMAL = 246;
{>= 5.0.6 end}
MYSQL_TYPE_ENUM = 247;
MYSQL_TYPE_SET = 248;
MYSQL_TYPE_TINY_BLOB = 249;
MYSQL_TYPE_MEDIUM_BLOB = 250;
MYSQL_TYPE_LONG_BLOB = 251;
MYSQL_TYPE_BLOB = 252;
MYSQL_TYPE_VAR_STRING = 253;
MYSQL_TYPE_STRING = 254;
MYSQL_TYPE_GEOMETRY = 255;
type
// statement state
PREP_STMT_STATE0410 = my_enum;
const
MY_ST_UNKNOWN = 0;
MY_ST_PREPARE = 1;
MY_ST_EXECUTE = 2;
type
PREP_STMT_STATE0411 = my_enum;
const
MYSQL_STMT_INIT_DONE = 1;
MYSQL_STMT_PREPARE_DONE = 2;
MYSQL_STMT_EXECUTE_DONE = 3;
MYSQL_STMT_FETCH_DONE = 4;
type
// client TIME structure to handle TIME, DATE and TIMESTAMP directly in
// binary protocol
mysql_st_timestamp_type = my_enum;
const
OLD_MYSQL_TIMESTAMP_NONE = 0;
OLD_MYSQL_TIMESTAMP_DATE = 1;
OLD_MYSQL_TIMESTAMP_FULL = 2;
OLD_MYSQL_TIMESTAMP_TIME = 3;
{>= 5.0.6 begin}
type
enum_mysql_timestamp_type = my_enum;
const
MYSQL_TIMESTAMP_NONE = -2;
MYSQL_TIMESTAMP_ERROR = -1;
MYSQL_TIMESTAMP_DATE = 0;
MYSQL_TIMESTAMP_DATETIME = 1;
MYSQL_TIMESTAMP_TIME = 2;
// Structure which is used to represent datetime values inside MySQL.
// We assume that values in this structure are normalized, i.e. year <= 9999,
// month <= 12, day <= 31, hour <= 23, hour <= 59, hour <= 59. Many functions
// in server such as my_system_gmt_sec() or make_time() family of functions
// rely on this (actually now usage of make_*() family relies on a bit weaker
// restriction). Also functions that produce MYSQL_TIME as result ensure this.
// There is one exception to this rule though if this structure holds time
// value (time_type == MYSQL_TIMESTAMP_TIME) days and hour member can hold
// bigger values.
type
PMYSQL_TIME0506 = ^MYSQL_TIME0506;
MYSQL_TIME0506 = record
year, month, day,
hour, minute, second: Cardinal;
second_part: my_ulong;
neg: my_bool;
time_type: enum_mysql_timestamp_type;
end;
{>= 5.0.6 end}
PMYSQL_TIME0410 = ^MYSQL_TIME0410;
MYSQL_TIME0410 = record
year, month, day,
hour, minute, second: Cardinal;
second_part: my_ulong;
neg: my_bool;
time_type: mysql_st_timestamp_type;
end;
// bind structure
TMYSQL_BIND_store_param_func = procedure(net: PNET; param: PMYSQL_BIND); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TMYSQL_BIND_fetch_result = procedure(p1: PMYSQL_BIND; row: PPByte); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TMYSQL_BIND_skip_result = procedure(p1: PMYSQL_BIND; p2: PMYSQL_FIELD; row: PPByte); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
PMYSQL_BIND0510 = ^MYSQL_BIND0510;
MYSQL_BIND0510 = record
length: Pmy_ulong; // output length pointer
is_null: Pmy_bool; // Pointer to null indicators
buffer: PByte; // buffer to get/put data
// set this if you want to track data truncations happened during fetch
error: Pmy_bool;
row_ptr: PByte; // for the current data position
store_param_func: TMYSQL_BIND_store_param_func;
fetch_result: TMYSQL_BIND_fetch_result;
skip_result: TMYSQL_BIND_skip_result;
// Must be set for string/blob data
buffer_length: my_ulong; // buffer length
offset: my_ulong; // offset position for char/binary fetch
length_value: my_ulong; // Used if length is 0
param_number: Cardinal; // For null count and error messages
pack_length: Cardinal; // Internal length for data
buffer_type: enum_field_types; // buffer type
error_value: my_bool; // used if error is 0
is_unsigned: my_bool; // set if integer type is unsigned
long_data_used: my_bool; // If used with mysql_send_long_data
is_null_value: my_bool; // Used if is_null is 0
extension: Pointer;
end;
PMYSQL_BIND0506 = ^MYSQL_BIND0506;
MYSQL_BIND0506 = record
length: Pmy_ulong; // output length pointer
is_null: Pmy_bool; // Pointer to null indicators
buffer: PByte; // buffer to get/put data
// set this if you want to track data truncations happened during fetch
error: Pmy_bool;
buffer_type: enum_field_types; // buffer type
// Must be set for string/blob data
buffer_length: my_ulong; // buffer length
// Following are for internal use. Set by mysql_stmt_bind_param
row_ptr: PByte; // for the current data position
offset: my_ulong; // offset position for char/binary fetch
length_value: my_ulong; // Used if length is 0
param_number: Cardinal; // For null count and error messages
pack_length: Cardinal; // Internal length for data
error_value: my_bool; // used if error is 0
is_unsigned: my_bool; // set if integer type is unsigned
long_data_used: my_bool; // If used with mysql_send_long_data
is_null_value: my_bool; // Used if is_null is 0
store_param_func: TMYSQL_BIND_store_param_func;
fetch_result: TMYSQL_BIND_fetch_result;
skip_result: TMYSQL_BIND_skip_result;
end;
PMYSQL_BIND0411 = ^MYSQL_BIND0411;
MYSQL_BIND0411 = record
length: Pmy_ulong; // output length pointer
is_null: Pmy_bool; // Pointer to null indicators
buffer: PByte; // buffer to get/put data
buffer_type: enum_field_types; // buffer type
// Must be set for string/blob data
buffer_length: LongWord; // buffer length
// Following are for internal use. Set by mysql_stmt_bind_param
inter_buffer: PByte; // for the current data position
offset: my_ulong; // offset position for char/binary fetch
internal_length: my_ulong; // Used if length is 0
param_number: Cardinal; // For null count and error messages
pack_length: Cardinal; // Internal length for data
is_unsigned: my_bool; // set if integer type is unsigned
long_data_used: my_bool; // If used with mysql_send_long_data
internal_is_null: my_bool; // Used if is_null is 0
store_param_func: TMYSQL_BIND_store_param_func;
fetch_result: TMYSQL_BIND_fetch_result;
skip_result: TMYSQL_BIND_skip_result;
end;
PMYSQL_BIND0410 = ^MYSQL_BIND0410;
MYSQL_BIND0410 = record
length: PLongWord; // output length pointer
is_null: Pmy_bool; // Pointer to null indicators
buffer: PByte; // buffer to get/put data
buffer_type: enum_field_types; // buffer type
// Must be set for string/blob data
buffer_length: Cardinal; // buffer length
// The following are for internal use. Set by mysql_bind_param
param_number: Cardinal; // For null count and error messages
long_data_used: my_bool; // If used with mysql_send_long_data
// store_param_func: TMYSQL_BIND_store_param_func;
// fetch_result: TMYSQL_BIND_fetch_result;
end;
// statement handler
TMYSQL_STMT_read_row_func = function (stmt: PMYSQL_STMT; row: PPChar): Integer;
PMYSQL_STMT0600 = ^MYSQL_STMT0600;
MYSQL_STMT0600 = record
mem_root: MEM_ROOT0600; // root allocations
list: MYSQL_LIST; // list to keep track of all stmts
mysql: PMYSQL0600; // connection handle
params: PMYSQL_BIND0510; // input parameters
bind: PMYSQL_BIND0510; // row binding
fields: PMYSQL_FIELD0510; // prepare meta info
result: PMYSQL_RES0600; // resultset
data_cursor: PMYSQL_ROWS0410; // current row in cached result
// mysql_stmt_fetch() calls this function to fetch one row (it's different
// for buffered, unbuffered and cursor fetch).
read_row_func: TMYSQL_STMT_read_row_func;
// copy of mysql->affected_rows after statement execution
affected_rows: my_ulonglong;
insert_id: my_ulonglong; // copy of mysql->insert_id
stmt_id: my_ulong; // Id for prepared statement
flags: my_ulong; // i.e. type of cursor to open
prefetch_rows: my_ulong; // number of rows per one COM_FETCH
server_status: Cardinal;
last_errno: Cardinal; // error code
param_count: Cardinal; // parameters count
field_count: Cardinal; // fields count
state: PREP_STMT_STATE0411; // statement state
last_error: array [0 .. MYSQL_ERRMSG_SIZE_0500 - 1] of TFDAnsiChar; // error message
sqlstate: array [0 .. SQLSTATE_LEN] of TFDAnsiChar;
// Types of input parameters should be sent to server
send_types_to_server: my_bool; // Types sent to server
bind_param_done: my_bool; // input buffers were supplied
bind_result_done: my_bool; // output buffers were supplied
// mysql_stmt_close() had to cancel this result
unbuffered_fetch_cancelled: my_bool;
// Is set to true if we need to calculate field->max_length for
// metadata fields when doing mysql_stmt_store_result.
update_max_length: my_bool;
extension: Pointer;
end;
PMYSQL_STMT0570 = ^MYSQL_STMT0570;
MYSQL_STMT0570 = record
mem_root: MEM_ROOT0570; // root allocations
list: MYSQL_LIST; // list to keep track of all stmts
mysql: PMYSQL0570; // connection handle
params: PMYSQL_BIND0510; // input parameters
bind: PMYSQL_BIND0510; // row binding
fields: PMYSQL_FIELD0510; // prepare meta info
result: PMYSQL_RES0570; // resultset
data_cursor: PMYSQL_ROWS0410; // current row in cached result
// mysql_stmt_fetch() calls this function to fetch one row (it's different
// for buffered, unbuffered and cursor fetch).
read_row_func: TMYSQL_STMT_read_row_func;
// copy of mysql->affected_rows after statement execution
affected_rows: my_ulonglong;
insert_id: my_ulonglong; // copy of mysql->insert_id
stmt_id: my_ulong; // Id for prepared statement
flags: my_ulong; // i.e. type of cursor to open
prefetch_rows: my_ulong; // number of rows per one COM_FETCH
server_status: Cardinal;
last_errno: Cardinal; // error code
param_count: Cardinal; // parameters count
field_count: Cardinal; // fields count
state: PREP_STMT_STATE0411; // statement state
last_error: array [0 .. MYSQL_ERRMSG_SIZE_0500 - 1] of TFDAnsiChar; // error message
sqlstate: array [0 .. SQLSTATE_LEN] of TFDAnsiChar;
// Types of input parameters should be sent to server
send_types_to_server: my_bool; // Types sent to server
bind_param_done: my_bool; // input buffers were supplied
bind_result_done: my_bool; // output buffers were supplied
// mysql_stmt_close() had to cancel this result
unbuffered_fetch_cancelled: my_bool;
// Is set to true if we need to calculate field->max_length for
// metadata fields when doing mysql_stmt_store_result.
update_max_length: my_bool;
extension: Pointer;
end;
PMYSQL_STMT0510 = ^MYSQL_STMT0510;
MYSQL_STMT0510 = record
mem_root: MEM_ROOT0410; // root allocations
list: MYSQL_LIST; // list to keep track of all stmts
mysql: PMYSQL0510; // connection handle
params: PMYSQL_BIND0510; // input parameters
bind: PMYSQL_BIND0510; // row binding
fields: PMYSQL_FIELD0510; // prepare meta info
result: PMYSQL_RES0510; // resultset
data_cursor: PMYSQL_ROWS0410; // current row in cached result
// mysql_stmt_fetch() calls this function to fetch one row (it's different
// for buffered, unbuffered and cursor fetch).
read_row_func: TMYSQL_STMT_read_row_func;
// copy of mysql->affected_rows after statement execution
affected_rows: my_ulonglong;
insert_id: my_ulonglong; // copy of mysql->insert_id
stmt_id: my_ulong; // Id for prepared statement
flags: my_ulong; // i.e. type of cursor to open
prefetch_rows: my_ulong; // number of rows per one COM_FETCH
server_status: Cardinal;
last_errno: Cardinal; // error code
param_count: Cardinal; // parameters count
field_count: Cardinal; // fields count
state: PREP_STMT_STATE0411; // statement state
last_error: array [0 .. MYSQL_ERRMSG_SIZE_0500 - 1] of TFDAnsiChar; // error message
sqlstate: array [0 .. SQLSTATE_LEN] of TFDAnsiChar;
// Types of input parameters should be sent to server
send_types_to_server: my_bool; // Types sent to server
bind_param_done: my_bool; // input buffers were supplied
bind_result_done: my_bool; // output buffers were supplied
// mysql_stmt_close() had to cancel this result
unbuffered_fetch_cancelled: my_bool;
// Is set to true if we need to calculate field->max_length for
// metadata fields when doing mysql_stmt_store_result.
update_max_length: my_bool;
extension: Pointer;
end;
PMYSQL_STMT0506 = ^MYSQL_STMT0506;
MYSQL_STMT0506 = record
mem_root: MEM_ROOT0410; // root allocations
list: MYSQL_LIST; // list to keep track of all stmts
mysql: PMYSQL; // connection handle
params: PMYSQL_BIND; // input parameters
bind: PMYSQL_BIND; // row binding
fields: PMYSQL_FIELD; // prepare meta info
result: PMYSQL_RES; // resultset
data_cursor: PMYSQL_ROWS; // current row in cached result
// copy of mysql->affected_rows after statement execution
affected_rows: my_ulonglong;
insert_id: my_ulonglong; // copy of mysql->insert_id
// mysql_stmt_fetch() calls this function to fetch one row (it's different
// for buffered, unbuffered and cursor fetch).
read_row_func: TMYSQL_STMT_read_row_func;
stmt_id: my_ulong; // Id for prepared statement
flags: my_ulong; // i.e. type of cursor to open
prefetch_rows: my_ulong; // number of rows per one COM_FETCH
server_status: Cardinal;
last_errno: Cardinal; // error code
param_count: Cardinal; // parameters count
field_count: Cardinal; // fields count
state: PREP_STMT_STATE0411; // statement state
last_error: array [0 .. MYSQL_ERRMSG_SIZE_0500 - 1] of TFDAnsiChar; // error message
sqlstate: array [0 .. SQLSTATE_LEN] of TFDAnsiChar;
// Types of input parameters should be sent to server
send_types_to_server: my_bool; // Types sent to server
bind_param_done: my_bool; // input buffers were supplied
bind_result_done: my_bool; // output buffers were supplied
// mysql_stmt_close() had to cancel this result
unbuffered_fetch_cancelled: my_bool;
// Is set to true if we need to calculate field->max_length for
// metadata fields when doing mysql_stmt_store_result.
update_max_length: my_bool;
end;
PMYSQL_STMT0411 = ^MYSQL_STMT0411;
MYSQL_STMT0411 = record
mem_root: MEM_ROOT0410; // root allocations
list: MYSQL_LIST; // list to keep track of all stmts
mysql: PMYSQL; // connection handle
params: PMYSQL_BIND; // input parameters
bind: PMYSQL_BIND; // row binding
fields: PMYSQL_FIELD; // prepare meta info
result: PMYSQL_RES; // resultset
data_cursor: PMYSQL_ROWS; // current row in cached result
// copy of mysql->affected_rows after statement execution
affected_rows: my_ulonglong;
insert_id: my_ulonglong; // copy of mysql->insert_id
// mysql_stmt_fetch() calls this function to fetch one row (it's different
// for buffered, unbuffered and cursor fetch).
read_row_func: TMYSQL_STMT_read_row_func;
stmt_id: my_ulong; // Id for prepared statement
last_errno: Cardinal; // error code
param_count: Cardinal; // parameters count
field_count: Cardinal; // fields count
state: PREP_STMT_STATE0411; // statement state
last_error: array [0 .. MYSQL_ERRMSG_SIZE_0300 - 1] of TFDAnsiChar; // error message
sqlstate: array [0 .. SQLSTATE_LEN] of TFDAnsiChar;
// Types of input parameters should be sent to server
send_types_to_server: my_bool; // Types sent to server
bind_param_done: my_bool; // input buffers were supplied
bind_result_done: my_bool; // output buffers were supplied
// mysql_stmt_close() had to cancel this result
unbuffered_fetch_cancelled: my_bool;
// Is set to true if we need to calculate field->max_length for
// metadata fields when doing mysql_stmt_store_result.
update_max_length: my_bool;
end;
PMYSQL_STMT0410 = ^MYSQL_STMT0410;
MYSQL_STMT0410 = record
mysql: PMYSQL; // connection handle
params: PMYSQL_BIND; // input parameters
result: PMYSQL_RES; // resultset
bind: PMYSQL_BIND; // row binding
fields: PMYSQL_FIELD; // prepare meta info
list: MYSQL_LIST; // list to keep track of all stmts
query: PByte; // query buffer
mem_root: MEM_ROOT0323; // root allocations
param_count: Cardinal; // parameters count
field_count: Cardinal; // fields count
stmt_id: my_ulong; // Id for prepared statement
last_errno: Cardinal; // error code
state: PREP_STMT_STATE0410; // statement state
last_error: array [0 .. MYSQL_ERRMSG_SIZE_0300 - 1] of TFDAnsiChar; // error message
long_alloced: my_bool; // flag to indicate long alloced
send_types_to_server: my_bool; // Types sent to server
param_buffers: my_bool; // param bound buffers
res_buffers: my_bool; // output bound buffers
result_buffered: my_bool; // Results buffered
end;
type
enum_stmt_attr_type = my_enum;
const
// When doing mysql_stmt_store_result calculate max_length attribute
// of statement metadata. This is to be consistent with the old API,
// where this was done automatically.
// In the new API we do that only by request because it slows down
// mysql_stmt_store_result sufficiently.
STMT_ATTR_UPDATE_MAX_LENGTH = 0;
{>= 5.0.6 begin}
// unsigned long with combination of cursor flags (read only, for update,
// etc)
STMT_ATTR_CURSOR_TYPE = 1;
// Amount of rows to retrieve from server per one fetch if using cursors.
// Accepts unsigned long attribute in the range 1 - ulong_max
STMT_ATTR_PREFETCH_ROWS = 2;
{>= 5.0.6 end}
// new status messages
MYSQL_SUCCESS = 0;
MYSQL_STATUS_ERROR = 1;
MYSQL_NO_DATA = 100;
{>= 5.0.6 begin}
MYSQL_DATA_TRUNCATED = 101;
{>= 5.0.6 end}
MYSQL_NEED_DATA = 99;
type
enum_cursor_type = my_enum;
const
CURSOR_TYPE_NO_CURSOR = 0;
CURSOR_TYPE_READ_ONLY = 1;
CURSOR_TYPE_FOR_UPDATE = 2;
CURSOR_TYPE_SCROLLABLE = 4;
{------------------------------------------------------------------------------}
{ mysql_error.h }
{ Definefile for error messagenumbers }
{------------------------------------------------------------------------------}
const
ER_ACCESS_DENIED_ERROR = 1045;
ER_BAD_TABLE_ERROR = 1051;
ER_DUP_ENTRY = 1062;
ER_PARSE_ERROR = 1064;
ER_NO_SUCH_TABLE = 1146;
ER_LOCK_WAIT_TIMEOUT = 1205;
ER_NO_REFERENCED_ROW = 1216;
ER_ROW_IS_REFERENCED = 1217;
ER_SP_DOES_NOT_EXIST = 1305;
ER_QUERY_INTERRUPTED = 1317;
ER_SP_WRONG_NO_OF_ARGS = 1318;
ER_TRG_DOES_NOT_EXIST = 1360;
ER_SP_NOT_VAR_ARG = 1414;
ER_MUST_CHANGE_PASSWORD = 1820;
ER_MUST_CHANGE_PASSWORD_LOGIN = 1862;
CR_CONN_HOST_ERROR = 2003;
ER_SERVER_GONE_ERROR = 2006;
ER_SERVER_LOST = 2013;
CR_NO_DATA = 2051;
ER_UNKNOWN_VIEW = 4092;
type
TPrcmysql_num_rows = function(res: PMYSQL_RES): my_ulonglong; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_num_fields = function(res: PMYSQL_RES): Cardinal; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_eof = function(res: PMYSQL_RES): my_bool; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_fetch_field_direct = function(res: PMYSQL_RES; fieldnr: Integer): PMYSQL_FIELD; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_fetch_fields = function(res: PMYSQL_RES): PMYSQL_FIELD; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_row_tell = function(res: PMYSQL_RES): PMYSQL_ROWS; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_field_tell = function(res: PMYSQL_RES): MYSQL_FIELD_OFFSET; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_field_count = function(mysql: PMYSQL): Cardinal; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_affected_rows = function(mysql: PMYSQL): my_ulonglong; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_insert_id = function(mysql: PMYSQL): my_ulonglong; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_errno = function(mysql: PMYSQL): Cardinal; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_error = function(mysql: PMYSQL): my_pchar; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_sqlstate = function(mysql: PMYSQL): my_pchar; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_info = function(mysql: PMYSQL): my_pchar; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_thread_id = function(mysql: PMYSQL): LongWord; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_character_set_name = function(mysql: PMYSQL): my_pchar; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_get_character_set_info = procedure (mysql: PMYSQL; var charset: MY_CHARSET_INFO); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_set_character_set = function (mysql: PMYSQL; cs_name: my_pchar): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_warning_count = function(mysql: PMYSQL): Cardinal; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_init = function(mysql: PMYSQL): PMYSQL; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_ssl_set = function(mysql: PMYSQL; const key, cert, ca, capath, cipher: my_pchar): my_bool; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_get_ssl_cipher = function(mysql: PMYSQL): my_pchar; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_change_user = function(mysql: PMYSQL; const user, passwd, db: my_pchar): my_bool; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_real_connect = function(mysql: PMYSQL; const host, user, passwd, db: my_pchar;
port: Cardinal; const unix_socket: my_pchar; clientflag: my_ulong): PMYSQL; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_close = procedure(sock: PMYSQL); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_select_db = function(mysql: PMYSQL; const db: my_pchar): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_query = function(mysql: PMYSQL; const q: my_pchar): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_send_query = function(mysql: PMYSQL; const q: my_pchar; length: my_ulong): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_read_query_result = function(mysql: PMYSQL): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_real_query = function(mysql: PMYSQL; const q: my_pchar; length: my_ulong): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_shutdown = function(mysql: PMYSQL): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_dump_debug_info = function(mysql: PMYSQL): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_refresh = function(mysql: PMYSQL; refresh_options: Cardinal): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_kill = function(mysql: PMYSQL; pid: my_ulong): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_ping = function(mysql: PMYSQL): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stat = function(mysql: PMYSQL): my_pchar; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_get_server_info = function(mysql: PMYSQL): my_pchar; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_get_client_info = function: my_pchar; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_get_host_info = function(mysql: PMYSQL): my_pchar; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_get_proto_info = function(mysql: PMYSQL): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_list_dbs = function(mysql: PMYSQL; const wild: my_pchar): PMYSQL_RES; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_list_tables = function(mysql: PMYSQL; const wild: my_pchar): PMYSQL_RES; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_list_fields = function(mysql: PMYSQL; const table, wild: my_pchar): PMYSQL_RES; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_list_processes = function(mysql: PMYSQL): PMYSQL_RES; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_store_result = function(mysql: PMYSQL): PMYSQL_RES; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_use_result = function(mysql: PMYSQL): PMYSQL_RES; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_options = function(mysql: PMYSQL; option: mysql_option; const arg: PByte): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_free_result = procedure(res: PMYSQL_RES); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_data_seek0320 = procedure(res: PMYSQL_RES; offset: LongWord); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_data_seek0323 = procedure(res: PMYSQL_RES; offset: my_ulonglong); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_row_seek = function(res: PMYSQL_RES; Row: MYSQL_ROW_OFFSET): MYSQL_ROW_OFFSET; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_field_seek = function(res: PMYSQL_RES; offset: MYSQL_FIELD_OFFSET): MYSQL_FIELD_OFFSET; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_fetch_row = function(res: PMYSQL_RES): MYSQL_ROW; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_fetch_lengths = function(res: PMYSQL_RES): Pmy_ulong; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_fetch_field = function(res: PMYSQL_RES): PMYSQL_FIELD; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_escape_string = function(szTo: my_pchar; const szFrom: my_pchar; from_length: my_ulong): my_ulong; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_real_escape_string = function(mysql: PMYSQL; szTo: my_pchar; const szFrom: my_pchar;
length: my_ulong): my_ulong; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_debug = procedure(const debug: my_pchar); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmyodbc_remove_escape = procedure(mysql: PMYSQL; name: my_pchar); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_thread_safe = function: Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// USE_OLD_FUNCTIONS
TPrcmysql_connect = function(mysql: PMYSQL; const host, user, passwd: my_pchar): PMYSQL; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_create_db = function(mysql: PMYSQL; const DB: my_pchar): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_drop_db = function(mysql: PMYSQL; const DB: my_pchar): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// 4.1
TPrcmysql_autocommit = function(mysql: PMYSQL; mode: my_bool): my_bool; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_commit = function(mysql: PMYSQL): my_bool; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_rollback = function(mysql: PMYSQL): my_bool; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_more_results = function(mysql: PMYSQL): my_bool; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_next_result = function(mysql: PMYSQL): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// 5.0
TPrcmysql_stmt_init = function(mysql: PMYSQL): PMYSQL_STMT; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_prepare = function(stmt: PMYSQL_STMT; const query: my_pchar;
length: my_ulong): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_execute = function (stmt: PMYSQL_STMT): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_fetch = function(stmt: PMYSQL_STMT): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_fetch_column = function(stmt: PMYSQL_STMT; bind: PMYSQL_BIND;
column: Cardinal; offset: my_ulong): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_store_result = function(stmt: PMYSQL_STMT): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_param_count = function(stmt: PMYSQL_STMT): my_ulong; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_attr_set = function(stmt: PMYSQL_STMT; attr_type: enum_stmt_attr_type;
attr: Pointer): my_bool; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_attr_get = function(stmt: PMYSQL_STMT; attr_type: enum_stmt_attr_type;
attr: Pointer): my_bool; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_bind_param = function(stmt: PMYSQL_STMT; bnd: PMYSQL_BIND): my_bool; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_bind_result = function(stmt: PMYSQL_STMT; bnd: PMYSQL_BIND): my_bool; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_close = function(stmt: PMYSQL_STMT): my_bool; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_reset = function(stmt: PMYSQL_STMT): my_bool; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_free_result = function(stmt: PMYSQL_STMT): my_bool; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_send_long_data = function(stmt: PMYSQL_STMT; param_number: Cardinal;
const data: PByte; length: my_ulong): my_bool; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_result_metadata = function(stmt: PMYSQL_STMT): PMYSQL_RES; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_errno = function(stmt: PMYSQL_STMT): Cardinal; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_error = function(stmt: PMYSQL_STMT): my_pchar; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_sqlstate = function(stmt: PMYSQL_STMT): my_pchar; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_row_seek = function(stmt: PMYSQL_STMT; offset: MYSQL_ROW_OFFSET):
MYSQL_ROW_OFFSET; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_row_tell = function(stmt: PMYSQL_STMT): MYSQL_ROW_OFFSET; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_data_seek = procedure (stmt: PMYSQL_STMT; offset: my_ulonglong); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_num_rows = function (stmt: PMYSQL_STMT): my_ulonglong; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_affected_rows = function (stmt: PMYSQL_STMT): my_ulonglong; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_insert_id = function (stmt: PMYSQL_STMT): my_ulonglong; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_field_count = function (stmt: PMYSQL_STMT): Cardinal; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_stmt_next_result = function (stmt: PMYSQL_STMT): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// Set up and bring down the server; to ensure that applications will
// work when linked against either the standard client library or the
// embedded server library, these functions should be called.
TPrcmysql_server_init = function (argc: Integer; argv: my_ppchar; groups: my_ppchar): Integer; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_server_end = procedure (); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
// Set up and bring down a thread; these function should be called
// for each thread in an application which opens at least one MySQL
// connection. All uses of the connection(s) should be between these
// function calls.
TPrcmysql_thread_init = function (): my_bool; {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
TPrcmysql_thread_end = procedure (); {$IFDEF MSWINDOWS} stdcall {$ELSE} cdecl {$ENDIF};
implementation
end.
|
{$mode objfpc}{$H+}{$J-} // Эту строку необходимо использовать во всех современных программах
program MyProgram; // Сохраните этот файл под названием myprogram.lpr
begin
WriteLn('Hello world!');
end.
|
(*************************************************************************
Cephes Math Library Release 2.8: June, 2000
Copyright by Stephen L. Moshier
Contributors:
* Sergey Bochkanov (ALGLIB project). Translation from C to
pseudocode.
See subroutines comments for additional copyrights.
>>> SOURCE LICENSE >>>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation (www.fsf.org); either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
A copy of the GNU General Public License is available at
http://www.fsf.org/licensing/licenses
>>> END OF LICENSE >>>
*************************************************************************)
unit fresnel;
interface
uses Math, Sysutils, Ap;
procedure FresnelIntegral(X : AlglibFloat; var C : AlglibFloat; var S : AlglibFloat);
implementation
(*************************************************************************
Fresnel integral
Evaluates the Fresnel integrals
x
-
| |
C(x) = | cos(pi/2 t**2) dt,
| |
-
0
x
-
| |
S(x) = | sin(pi/2 t**2) dt.
| |
-
0
The integrals are evaluated by a power series for x < 1.
For x >= 1 auxiliary functions f(x) and g(x) are employed
such that
C(x) = 0.5 + f(x) sin( pi/2 x**2 ) - g(x) cos( pi/2 x**2 )
S(x) = 0.5 - f(x) cos( pi/2 x**2 ) - g(x) sin( pi/2 x**2 )
ACCURACY:
Relative error.
Arithmetic function domain # trials peak rms
IEEE S(x) 0, 10 10000 2.0e-15 3.2e-16
IEEE C(x) 0, 10 10000 1.8e-15 3.3e-16
Cephes Math Library Release 2.8: June, 2000
Copyright 1984, 1987, 1989, 2000 by Stephen L. Moshier
*************************************************************************)
procedure FresnelIntegral(X : AlglibFloat; var C : AlglibFloat; var S : AlglibFloat);
var
XXA : AlglibFloat;
F : AlglibFloat;
G : AlglibFloat;
CC : AlglibFloat;
SS : AlglibFloat;
T : AlglibFloat;
U : AlglibFloat;
X2 : AlglibFloat;
SN : AlglibFloat;
SD : AlglibFloat;
CN : AlglibFloat;
CD : AlglibFloat;
FN : AlglibFloat;
FD : AlglibFloat;
GN : AlglibFloat;
GD : AlglibFloat;
MPI : AlglibFloat;
MPIO2 : AlglibFloat;
begin
MPI := 3.14159265358979323846;
MPIO2 := 1.57079632679489661923;
XXA := X;
X := AbsReal(XXA);
X2 := X*X;
if AP_FP_Less(X2,2.5625) then
begin
T := x2*x2;
SN := -2.99181919401019853726E3;
SN := SN*T+7.08840045257738576863E5;
SN := SN*T-6.29741486205862506537E7;
SN := SN*T+2.54890880573376359104E9;
SN := SN*T-4.42979518059697779103E10;
SN := SN*T+3.18016297876567817986E11;
SD := 1.00000000000000000000E0;
SD := SD*T+2.81376268889994315696E2;
SD := SD*T+4.55847810806532581675E4;
SD := SD*T+5.17343888770096400730E6;
SD := SD*T+4.19320245898111231129E8;
SD := SD*T+2.24411795645340920940E10;
SD := SD*T+6.07366389490084639049E11;
CN := -4.98843114573573548651E-8;
CN := CN*T+9.50428062829859605134E-6;
CN := CN*T-6.45191435683965050962E-4;
CN := CN*T+1.88843319396703850064E-2;
CN := CN*T-2.05525900955013891793E-1;
CN := CN*T+9.99999999999999998822E-1;
CD := 3.99982968972495980367E-12;
CD := CD*T+9.15439215774657478799E-10;
CD := CD*T+1.25001862479598821474E-7;
CD := CD*T+1.22262789024179030997E-5;
CD := CD*T+8.68029542941784300606E-4;
CD := CD*T+4.12142090722199792936E-2;
CD := CD*T+1.00000000000000000118E0;
S := Sign(XXA)*x*x2*SN/SD;
C := Sign(XXA)*x*CN/CD;
Exit;
end;
if AP_FP_Greater(x,36974.0) then
begin
c := Sign(XXA)*0.5;
s := Sign(XXA)*0.5;
Exit;
end;
x2 := x*x;
t := MPI*x2;
u := 1/(t*t);
t := 1/t;
FN := 4.21543555043677546506E-1;
FN := FN*U+1.43407919780758885261E-1;
FN := FN*U+1.15220955073585758835E-2;
FN := FN*U+3.45017939782574027900E-4;
FN := FN*U+4.63613749287867322088E-6;
FN := FN*U+3.05568983790257605827E-8;
FN := FN*U+1.02304514164907233465E-10;
FN := FN*U+1.72010743268161828879E-13;
FN := FN*U+1.34283276233062758925E-16;
FN := FN*U+3.76329711269987889006E-20;
FD := 1.00000000000000000000E0;
FD := FD*U+7.51586398353378947175E-1;
FD := FD*U+1.16888925859191382142E-1;
FD := FD*U+6.44051526508858611005E-3;
FD := FD*U+1.55934409164153020873E-4;
FD := FD*U+1.84627567348930545870E-6;
FD := FD*U+1.12699224763999035261E-8;
FD := FD*U+3.60140029589371370404E-11;
FD := FD*U+5.88754533621578410010E-14;
FD := FD*U+4.52001434074129701496E-17;
FD := FD*U+1.25443237090011264384E-20;
GN := 5.04442073643383265887E-1;
GN := GN*U+1.97102833525523411709E-1;
GN := GN*U+1.87648584092575249293E-2;
GN := GN*U+6.84079380915393090172E-4;
GN := GN*U+1.15138826111884280931E-5;
GN := GN*U+9.82852443688422223854E-8;
GN := GN*U+4.45344415861750144738E-10;
GN := GN*U+1.08268041139020870318E-12;
GN := GN*U+1.37555460633261799868E-15;
GN := GN*U+8.36354435630677421531E-19;
GN := GN*U+1.86958710162783235106E-22;
GD := 1.00000000000000000000E0;
GD := GD*U+1.47495759925128324529E0;
GD := GD*U+3.37748989120019970451E-1;
GD := GD*U+2.53603741420338795122E-2;
GD := GD*U+8.14679107184306179049E-4;
GD := GD*U+1.27545075667729118702E-5;
GD := GD*U+1.04314589657571990585E-7;
GD := GD*U+4.60680728146520428211E-10;
GD := GD*U+1.10273215066240270757E-12;
GD := GD*U+1.38796531259578871258E-15;
GD := GD*U+8.39158816283118707363E-19;
GD := GD*U+1.86958710162783236342E-22;
f := 1-u*FN/FD;
g := t*GN/GD;
t := MPIO2*x2;
cc := cos(t);
ss := sin(t);
t := MPI*x;
c := 0.5+(f*ss-g*cc)/t;
s := 0.5-(f*cc+g*ss)/t;
C := C*Sign(XXA);
S := S*sign(XXA);
end;
end. |
unit record_methods_1;
interface
type
TRec = record
function Get5: Int32;
function Get6: Int32;
end;
var
G1, G2: Int32;
implementation
function TRec.Get5: Int32;
begin
Result := 5;
end;
function TRec.Get6: Int32;
begin
Result := 6;
end;
procedure Test;
var
R: TRec;
begin
#bpt;
G1 := R.Get5();
G2 := R.Get6();
end;
initialization
Test();
finalization
Assert(G1 = 5);
Assert(G2 = 6);
end. |
unit InterfaceConversor;
interface
uses
Data.DB, System.SysUtils, System.IOUtils, Datasnap.DBClient, System.JSON;
type
TConversor = class
function Converter: string; virtual; abstract;
constructor Create(const Arquivo: string; ClientDataSet: TClientDataSet); virtual; abstract;
end;
implementation
end.
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Copyright (c) 2020-2020 Skybuck Flying
// Copyright (c) 2020-2020 The Delphicoin Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Bitcoin file: src/chain.h
// Bitcoin file: src/chain.cpp
// Bitcoin commit hash: f656165e9c0d09e654efabd56e6581638e35c26c
unit Unit_TBlockStatus;
interface
type
TBlockStatus : longword =
(
//! Unused.
BLOCK_VALID_UNKNOWN = 0,
//! Reserved (was BLOCK_VALID_HEADER).
BLOCK_VALID_RESERVED = 1,
//! All parent headers found, difficulty matches, timestamp >= median previous, checkpoint. Implies all parents
//! are also at least TREE.
BLOCK_VALID_TREE = 2,
// /**
// * Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids,
// * sigops, size, merkle root. Implies all parents are at least TREE but not necessarily TRANSACTIONS. When all
// * parent blocks also have TRANSACTIONS, CBlockIndex::nChainTx will be set.
// */
BLOCK_VALID_TRANSACTIONS = 3,
//! Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends, BIP30.
//! Implies all parents are also at least CHAIN.
BLOCK_VALID_CHAIN = 4,
//! Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
BLOCK_VALID_SCRIPTS = 5,
//! All validity bits.
BLOCK_VALID_MASK = BLOCK_VALID_RESERVED | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS |
BLOCK_VALID_CHAIN | BLOCK_VALID_SCRIPTS,
BLOCK_HAVE_DATA = 8, //!< full block available in blk*.dat
BLOCK_HAVE_UNDO = 16, //!< undo data available in rev*.dat
BLOCK_HAVE_MASK = BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO,
BLOCK_FAILED_VALID = 32, //!< stage after last reached validness failed
BLOCK_FAILED_CHILD = 64, //!< descends from failed block
BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD,
BLOCK_OPT_WITNESS = 128, //!< block data in blk*.data was received with a witness-enforcing client
};
implementation
end.
|
{ Copyright (C) 1998-2018, written by Shkolnik Mike, Scalabium
E-Mail: mshkolnik@scalabium.com
mshkolnik@yahoo.com
WEB: http://www.scalabium.com
Этот компонент заливает рамку выбранным цветом Color.
Рамка делится на Count+1 полос, каждая из которых равномерно уменьшает или
увеличивает (в зависимости от направления Direction) цветовую гамму.
Предусмотрена возможность использования 10 разных направлений заливок (смена цвета):
TopToBottom - заливка с верхнего края экрана к нижнему
BottomToTop - заливка с нижнего края экрана к верхнему
LeftToRight - заливка с левого края экрана к правому
RightToLeft - заливка с правого края экрана к левому
EdgesToCenter - заливка от краев экрана (сверху/снизу/справа/слева) к его центру
CenterToEdges - заливка с центра экрана к его краям (вверх/вниз/вправо/влево)
HCenterToEdges - заливка от горизоонтального центра экрана к еего краям (вверх/вниз)
EdgesToHCenter - заливка от краев экрана (сверху/снизу) к его горизонтальному центру
VCenterToEdges - заливка от вертикального центра экрана к его краям (вправо/влево) к его центру
EdgesToVCenter - заливка от краев экрана (справа/слева) к его вертикальному центру
TopLeft - заливка от левого верхнего угла к нижнему правому
BottomLeft - заливка от левого нижнего угла к верхнему правому
TopRight - заливка от правого верхнего угла к нижнему левому
BottomRight - заливка от правого нижнего угла к верхнему левому
}
unit GradPnl;
interface
{$I SMVersion.inc}
uses
Classes, Graphics, Controls;
type TDirection = (TopToBottom, BottomToTop,
LeftToRight, RightToLeft,
EdgesToCenter, CenterToEdges,
HCenterToEdges, EdgesToHCenter,
VCenterToEdges, EdgesToVCenter,
TopLeft, BottomLeft,
TopRight, BottomRight,
EllipticIn, EllipticOut);
type TCountOfColor = 1..255;
type
{$IFDEF SM_ADD_ComponentPlatformsAttribute}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TGradientPanel = class(TGraphicControl)
private
{ Private declarations }
FColorFrom: TColor;
FColorTo: TColor;
FCount: TCountOfColor;
FDirection: TDirection;
protected
procedure Paint; override;
procedure SetPaintColorFrom(Value: TColor);
procedure SetPaintColorTo(Value: TColor);
procedure SetPaintCount(Value: TCountOfColor);
procedure SetPaintDirection(Value: TDirection);
public
constructor Create(AOwner: TComponent); override;
published
property ColorFrom: TColor read FColorFrom write SetPaintColorFrom;
property ColorTo: TColor read FColorTo write SetPaintColorTo;
property ColorCount: TCountOfColor read FCount write SetPaintCount;
property Direction: TDirection read FDirection write SetPaintDirection;
property Align;
property DragCursor;
property DragMode;
property Enabled;
property Font;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Visible;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
implementation
uses Windows;
constructor TGradientPanel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FColorFrom := clBlue;
FColorTo := clBlack;
FCount := 64;
Height := 100;
Width := 100;
Invalidate;
end;
procedure TGradientPanel.Paint;
var RedFrom, GreenFrom, BlueFrom,
RedTo, GreenTo, BlueTo: Byte;
DiffRed, DiffGreen, DiffBlue: Integer;
i,
StartHeight, EndHeight, StartWidth, EndWidth: Integer;
StepHeight, StepWidth: Double;
begin
StartHeight := 0;
StartWidth := 0;
EndHeight := 0;
EndWidth := 0;
StepHeight := 0;
StepWidth := 0;
case FDirection of
TopToBottom,
BottomToTop: begin
EndHeight := Height;
StepHeight := Height/(FCount+1);
end;
LeftToRight,
RightToLeft: begin
EndWidth := Width;
StepWidth := Width/(FCount+1);
end;
EdgesToCenter,
CenterToEdges,
EllipticIn,
EllipticOut: begin
EndWidth := Trunc(Width/2);
StepWidth := Width/(2*FCount+2);
EndHeight := Trunc(Height/2);
StepHeight := Height/(2*FCount+2);
end;
HCenterToEdges,
EdgesToHCenter: begin
EndHeight := Trunc(Height/2);
StepHeight := Height/(2*FCount+2);
end;
VCenterToEdges,
EdgesToVCenter: begin
EndWidth := Trunc(Width/2);
StepWidth := Width/(2*FCount+2);
end;
TopLeft,
BottomLeft,
TopRight,
BottomRight: begin
EndWidth := Width;
StepWidth := Width/(FCount+1);
EndHeight := Trunc(Height/2);
StepHeight := Height/(FCount+1);
end;
end;
{устанавливаем начальный цвет и разницу между начальным и конечным}
if (FDirection in [BottomToTop, RightToLeft, CenterToEdges, EllipticOut, HCenterToEdges,
VCenterToEdges, TopLeft, BottomLeft, TopRight, BottomRight]) then
begin
RedFrom := (FColorTo and $000000FF);
GreenFrom := (FColorTo and $0000FF00) shr 8;
BlueFrom := (FColorTo and $00FF0000) shr 16;
RedTo := (FColorFrom and $000000FF);
GreenTo := (FColorFrom and $0000FF00) shr 8;
BlueTo := (FColorFrom and $00FF0000) shr 16;
end
else
begin
RedFrom := (FColorFrom and $000000FF);
GreenFrom := (FColorFrom and $0000FF00) shr 8;
BlueFrom := (FColorFrom and $00FF0000) shr 16;
RedTo := (FColorTo and $000000FF);
GreenTo := (FColorTo and $0000FF00) shr 8;
BlueTo := (FColorTo and $00FF0000) shr 16;
end;
DiffRed := RedTo - RedFrom;
DiffGreen := GreenTo - GreenFrom;
DiffBlue := BlueTo - BlueFrom;
if (FDirection in [EllipticIn, EllipticOut]) then
begin
with inherited Canvas do
begin
Pen.Style := psClear;
Brush.Color := RGB(RedFrom, GreenFrom, BlueFrom);
Rectangle(0, 0, Width, Height);
end;
end;
for i := 0 to FCount-1 do
begin
with inherited Canvas do
begin
Pen.Style := psClear;
if FCount > 1 then
Brush.Color := RGB(RedFrom + MulDiv(i, DiffRed, FCount - 1),
GreenFrom + MulDiv(i, DiffGreen, FCount - 1),
BlueFrom + MulDiv(i, DiffBlue, FCount - 1))
else Brush.Color := RGB(RedFrom, GreenFrom, BlueFrom);
case FDirection of
TopToBottom,
BottomToTop: Rectangle(0, StartHeight + Trunc(StepHeight*i) - 1, Width, StartHeight + Trunc(StepHeight*(i+1)));
LeftToRight,
RightToLeft: Rectangle(StartWidth + Trunc(StepWidth*i) - 1, 0, StartWidth + Trunc(StepWidth*(i+1)), Height);
EdgesToCenter,
CenterToEdges: Rectangle(StartWidth + Trunc(StepWidth*i) - 1, StartHeight + Trunc(StepHeight*i) - 1, Width - StartWidth - Trunc(StepWidth*i), Height - StartHeight - Trunc(StepHeight*i));
HCenterToEdges,
EdgesToHCenter: begin
Rectangle(0, StartHeight + Trunc(StepHeight*i) - 1, Width, StartHeight + Trunc(StepHeight*(i+1)));
Rectangle(0, Height - StartHeight - Trunc(StepHeight*i) + 1, Width, Height - StartHeight - Trunc(StepHeight*(i+1)));
end;
VCenterToEdges,
EdgesToVCenter: begin
Rectangle(StartWidth + Trunc(StepWidth*i) - 1, 0, StartWidth + Trunc(StepWidth*(i+1)), Height);
Rectangle(Width - StartWidth - Trunc(StepWidth*i) + 1, 0, Width - StartWidth - Trunc(StepWidth*(i+1)), Height);
end;
TopLeft: Rectangle(0, 0, Width - StartWidth - Trunc(StepWidth*i) + 1, Height - StartHeight - Trunc(StepHeight*i) + 1);
BottomLeft: Rectangle(0, StartHeight + Trunc(StepHeight*i) - 1, Width - StartWidth - Trunc(StepWidth*i) + 1, Height);
TopRight: Rectangle(StartWidth + Trunc(StepWidth*i) - 1, 0, Width, Height - StartHeight - Trunc(StepHeight*i) + 1);
BottomRight: Rectangle(StartWidth + Trunc(StepWidth*i) - 1, StartHeight + Trunc(StepHeight*i) - 1, Width, Height);
EllipticIn,
EllipticOut: Ellipse(StartWidth + Trunc(StepWidth*i) - 1, StartHeight + Trunc(StepHeight*i) - 1, Width - StartWidth - Trunc(StepWidth*i), Height - StartHeight - Trunc(StepHeight*i));
end;
end;
end;
with inherited Canvas do
begin
Pen.Style := psClear;
Brush.Color := RGB(RedTo, GreenTo, BlueTo);
case FDirection of
TopToBottom, BottomToTop: Rectangle(0, StartHeight + Trunc(StepHeight*FCount) - 1, Width, EndHeight);
LeftToRight, RightToLeft: Rectangle(StartWidth + Trunc(StepWidth*FCount) - 1, 0, EndWidth, Height);
HCenterToEdges,
EdgesToHCenter: begin
Rectangle(0, StartHeight + Trunc(StepHeight*FCount) - 1, Width, EndHeight);
Rectangle(0, EndHeight - 1, Width, Height - StartHeight - Trunc(StepHeight*(FCount-1)));
end;
VCenterToEdges,
EdgesToVCenter: begin
Rectangle(StartWidth + Trunc(StepWidth*FCount) - 1, 0, EndWidth, Height);
Rectangle(EndWidth - 1, 0, Width - StartWidth - Trunc(StepWidth*(FCount-1)), Height);
end;
end;
end;
end;
procedure TGradientPanel.SetPaintColorFrom(Value: TColor);
begin
if FColorFrom <> Value then
begin
FColorFrom := Value;
Paint;
end;
end;
procedure TGradientPanel.SetPaintColorTo(Value: TColor);
begin
if FColorTo <> Value then
begin
FColorTo := Value;
Paint;
end;
end;
procedure TGradientPanel.SetPaintCount(Value: TCountOfColor);
begin
if FCount <> Value then
begin
FCount := Value;
Paint;
end;
end;
procedure TGradientPanel.SetPaintDirection(Value: TDirection);
begin
if FDirection <> Value then
begin
FDirection := Value;
Paint;
end;
end;
end.
|
unit CSCBase;
interface
uses Dialogs, SysUtils, Windows, Messages, Controls, Classes, ScktComp;
const
Socket_Error = -1;
type
ECSError = class(Exception)
public
ErrorCode: Integer;
SocketError: Integer;
constructor Create(EC: Integer);
constructor CreateSckError(EC: Integer);
end;
TNetMsgDataType = Byte;
PnmHeader = ^TnmHeader;
TnmHeader = packed record {..General message header}
nmhEvent : Boolean; {..True if it is an event}
nmhMsgID : longint; {..message identifier}
nmhMsgLen : longint; {..size of this message, incl. header}
nmhTotalSize : longint; {..size of all messages}
nmhFirst : Boolean; {..First of possible many parts}
nmhLast : Boolean; {..Last of possible many parts}
nmhDataType : TNetMsgDataType; {..Byte array or Stream}
nmhErrorCode : word; {..error code, or 0 for success}
nmhData : byte; {..data marker}
end;
PCSCPacket = ^TCSCPacket;
TCSCPacket = packed record
pkLength : longint;
pkStart : longint;
pkData : PByteArray;
pkNext : PCSCPacket;
end;
const
ptVocare = $7577;
ptVocareScript = $8577;
ptWinPBX = $9577;
ptVocareGuardiao = $A077;
ptTelemanager = $A177;
ptCyberMgr = $A277;
ptOpera = $A377;
ptNexCafe = 16201;
tpStart = 0;
tpMiddle = 1;
tpEnd = 2;
FileTransTimeout = 30000; // 30 seconds
CSCErr_None = 0;
CSCErr_ServerCommLost = 30001;
CSCErr_ServerNotFound = 30002;
CSCErr_SystemBusy = 30003;
CSCErr_Timeout = 30004;
CSCErr_CannotOpenFile = 30005;
CSCErr_Unknow = 30006;
CSCErr_Socket = 30007;
nmdByteArray = 0;
nmdStream = 1;
MaxNetMsgSize : Integer = 1024 * 24;
CSCMaxFileNameSize = 512;
NetMsgHeaderSize = sizeof(TnmHeader) - Sizeof(byte);
SendAllClients = $FFFF;
cscm_DataReceived = WM_USER + $0FF1;
cscm_EventReceived = WM_USER + $0FF2;
cscm_FileEventReceived = WM_USER + $0FF3;
cscm_RefreshLic = WM_USER + $0FF4;
cscm_FTQItemReceived = WM_USER + $0FF5;
cscnmAck = $0001;
cscnmNewConnection = $0002;
cscnmEndConnection = $0003;
cscnmFirstFilePacket = 30001;
cscnmGetFileReq = 30002;
cscnmNextFilePacketReq = 30003;
cscnmFilePacket = 30004;
cscnmLastPacketRcv = 30005;
cscnmUploadFile = 30006;
cscnmDownloadFile = 30007;
cscnmFileTransmissionEv = 30008;
type
TCSCFileName = Array[0..CSCMaxFileNameSize-1] of Char;
PCSCnmFirstFilePacket = ^TCSCnmFirstFilePacket;
TCSCnmFirstFilePacket = packed record
nmSourceFN: TCSCFileName;
nmDestFN : TCSCFileName;
nmFileInfo: TCSCFileName;
nmUserInfo: Array[1..512] of Byte;
nmSubMsgID: Integer;
end;
TCSCnmGetFileReq = TCSCnmFirstFilePacket;
TCSCnmNextFilePacketReq = packed record
nmSourceHandle: Integer;
end;
TCSCnmFilePacket = packed record
nmSourceHandle: Integer;
nmFileSize : Integer;
nmLast : Boolean;
end;
TCSCUserInfo = Array[1..512] of Byte;
PCSCnmFileTransmissionEv = ^TCSCnmFileTransmissionEv;
TCSCnmFileTransmissionEv = record
nmHandle : Integer;
nmPos : Byte; // Start=0; Middle=1; End=2
nmSending : Boolean;
nmFileName : String[255];
nmFileInfo : String[255];
nmUserInfo : TCSCUserInfo;
nmFileSize : Integer;
nmFilePos : Integer;
nmSubMsgID : Integer;
nmError : Integer;
end;
TCSCCommBase = class ( TComponent )
protected
FIsServer: Boolean;
FNotifyHandle : HWND;
procedure SetNotifyHandle(Value: HWND);
public
procedure MsgReceived(aClientSck: TCustomWinSocket; aMsg: PnmHeader); virtual; abstract;
procedure SendFilePacket(aClientSck: TCustomWinSocket;
aFFP: PCSCnmFirstFilePacket;
aFP : TCSCnmFilePacket;
aFS : TFileStream); virtual; abstract;
procedure SendMsg(aMsg : longint;
aEvent : Boolean;
aClient : TCustomWinSocket;
aData : pointer;
aDataLen : LongInt;
aDataType : TNetMsgDataType;
aErrorCode : Word); virtual; abstract;
property IsServer: Boolean
read FIsServer;
property NotifyHandle: HWND
read FNotifyHandle write SetNotifyHandle;
end;
TCSCMsgReceivedEvent = procedure (Socket: TCustomWinSocket; Data: Pointer; DataLen: Integer) of object;
TCSCSenderReceiver = class
private
FSocket : TCustomWinSocket;
FPacketHead: PCSCPacket;
FPacketTail: PCSCPacket;
FSending : Boolean;
FRcvBuffer : PByteArray;
FRcvOffSet : integer;
FOnMsgRcv : TCSCMsgReceivedEvent;
private
procedure WinsockBreath;
public
constructor Create(aSocket: TCustomWinSocket);
destructor Destroy; override;
function Send(aData : PByteArray;
aDataLen : longint;
aDataStart : longint;
var aBytesSent : longint) : integer;
procedure Read;
procedure Write;
property OnMsgReceived : TCSCMsgReceivedEvent
read FOnMsgRcv write FOnMsgRcv;
end;
function GetCSErrorString(EC: Integer): String;
implementation
function GetCSErrorString(EC: Integer): String;
begin
case EC of
CSCErr_ServerCommLost :
Result := 'Falha de comunicação com servidor';
CSCErr_ServerNotFound :
Result := 'Servidor não encontrado';
CSCErr_SystemBusy :
Result := 'Sistema Está Ocupado';
CSCErr_Timeout :
Result := 'Tempo máximo aguardando transmissão de arquivo';
CSCErr_CannotOpenFile :
Result := 'Arquivo não pode ser aberto';
CSCErr_Unknow :
Result := 'Erro Desconhecido';
CSCErr_Socket :
Result := 'Erro de comunicação TCP/IP';
else Result := '';
end;
end;
constructor ECSError.Create(EC: Integer);
begin
inherited Create('CS Communication Error '+IntToStr(EC)+': '+GetCSErrorString(EC));
ErrorCode := EC;
SocketError := 0;
end;
constructor ECSError.CreateSckError(EC: Integer);
begin
inherited Create(GetCSErrorString(CSCErr_Socket) + ' (' + IntToStr(EC) +')');
ErrorCode := CSCErr_Socket;
SocketError := EC;
end;
procedure TCSCCommBase.SetNotifyHandle(Value: HWND);
begin
FNotifyHandle := Value;
end;
constructor TCSCSenderReceiver.Create(aSocket: TCustomWinSocket);
begin
inherited Create;
FOnMsgRcv := nil;
FSocket := aSocket;
FPacketHead:= nil;
FPacketTail:= nil;
FSending := False;
GetMem(FRcvBuffer, MaxNetMsgSize);
FRcvOffSet := 0;
end;
destructor TCSCSenderReceiver.Destroy;
begin
FreeMem(FRcvBuffer, maxNetMsgSize);
inherited;
end;
function TCSCSenderReceiver.Send(aData : PByteArray;
aDataLen : longint;
aDataStart : longint;
var aBytesSent : longint) : integer;
var
BytesSent : longint;
PacketBuffer : PCSCPacket;
begin
Result := 0;
if (aDataLen-aDataStart) > 0 then begin
{Add the data packet to the wscPacketList }
New(PacketBuffer);
GetMem(PacketBuffer^.pkData, aDataLen);
PacketBuffer^.pkLength := aDataLen;
PacketBuffer^.pkStart := aDataStart;
Move(aData^[0], PacketBuffer^.pkData^, PacketBuffer^.pkLength);
PacketBuffer^.pkNext := Nil;
{Add the packet to the end of the list }
if not assigned(FPacketHead) then
FPacketHead := PacketBuffer
else if assigned(FPacketTail) then
FPacketTail^.pkNext := PacketBuffer;
FPacketTail := PacketBuffer;
aBytesSent := aDataLen-aDataStart; {Always report all bytes sent}
end;
if (not FSending) and Assigned(FPacketHead) then begin
{now try to send some data}
try
{send the first waiting data packet}
with FPacketHead^ do
BytesSent := FSocket.SendBuf(pkData^[pkStart], pkLength-pkStart);
except
BytesSent := SOCKET_ERROR;
end;
if (BytesSent = SOCKET_ERROR) then begin
Result := 0;
FSending := True;
end else if BytesSent < (FPacketHead^.pkLength - FPacketHead^.pkStart) then begin
if BytesSent=0 then
WinsockBreath;
{ we didn't send the whole thing, so re-size the data packet}
inc(FPacketHead^.pkStart, BytesSent);
{ now try sending the remaining data again }
Result := Send(nil, 0, 0, BytesSent);
end else begin
{we sent the packet, so remove it and continue }
FreeMem(FPacketHead^.pkData, FPacketHead^.pkLength);
PacketBuffer := FPacketHead;
FPacketHead := FPacketHead^.pkNext;
if not Assigned(FPacketHead) then
FPacketTail := Nil;
Dispose(PacketBuffer);
Result := 0;
end;
end;
end;
procedure TCSCSenderReceiver.WinsockBreath;
var Msg : TMsg;
begin
while PeekMessage(Msg, FSocket.Handle, 0, 0, PM_REMOVE) do begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;
procedure TCSCSenderReceiver.Write;
var Dummy: integer;
begin
FSending := False;
while (not FSending) and Assigned(FPacketHead) do
Send(nil, 0, 0, Dummy);
end;
procedure TCSCSenderReceiver.Read;
var
MsgLen,
BytesRead: Integer;
begin
try
BytesRead := FSocket.ReceiveBuf(FRcvBuffer^[FRcvOffSet], MaxNetMsgSize-FRcvOffSet);
except
BytesRead := 0;
end;
if BytesRead<1 then
Exit;
Inc(FRcvOffSet, BytesRead);
while FRcvOffSet >= NetMsgHeaderSize do begin
MsgLen := PnmHeader(FRcvBuffer)^.nmhMsgLen;
if (FRcvOffset >= MsgLen) then begin
FRcvOffset := FRcvOffset - MsgLen;
if Assigned(FOnMsgRcv)
then FOnMsgRcv(FSocket, FRcvBuffer, MsgLen);
if (FRcvOffset > 0) then
Move(FRcvBuffer^[MsgLen], FRcvBuffer^[0], FRcvOffset);
end else Exit;
end;
end;
end.
|
program factorial;
const
number = 5;
var
result: integer;
{* demonstrate that a function name is how a function returns its value *}
function fact(n: integer): integer;
var
i, answer: integer;
begin
fact := 1;
answer := 1;
if n > 1 then
for i := 2 to n do
answer := answer * i;
fact := answer;
end;
begin {* main program *}
result := fact(number);
write('Factorial of ', number);
write(' is ', result);
end.
|
namespace RemObjects.Elements.System;
interface
uses
Foundation;
{$G+}
method __ElementsClassLockEnter(var x: intptr_t): Boolean; public;
method __ElementsClassLockExit(var x: intptr_t); public;
method __ElementsReadLine(): String; public;
method __ElementsNullReferenceRaiseException(s: String); public;
method __ElementsObjcClassInfoToString(clz: &Class): ^AnsiChar; public;
implementation
method __ElementsNullReferenceRaiseException(s: String);
begin
if s = nil then
NSException.&raise('NullReferenceException') format('Null Reference Exception');
NSException.&raise('NullReferenceException') format('Null Reference Exception for expression: %@', s);
end;
method __ElementsClassLockEnter(var x: intptr_t): Boolean;
begin
if x = -1 then exit false;
var cid: uint64_t;
pthread_threadid_np(nil, var cid);
var lValue := interlockedCompareExchange(var x, cid, 0); // returns old
if lValue = 0 then exit true; // value was zero, we should run.
if lValue = cid then exit false; // same thread, but already running, don't go again.
if lValue = -1 then exit false; // it's done in the mean time, we should exit.
// At this point it's NOT the same thread, and not done loading yet.
repeat
sched_yield;
usleep(10);
until interlockedCompareExchange(var x, -1, -1) = -1;
exit false;
end;
method __ElementsClassLockExit(var x:intptr_t);
begin
interlockedExchange(var x, -1)
end;
method __ElementsReadLine: String;
begin
result := '';
loop begin
var c := getchar();
if c in [10, 13] then
exit;
result := result+Char(c);
end;
end;
var __ElementsObjcClassInfoToStringValue: String;
method __ElementsObjcClassInfoToString(clz: &Class): ^AnsiChar;
begin
var cl := class_getName(clz);
var s := new Foundation.NSString withCString(cl) encoding(Foundation.NSStringEncoding.UTF8StringEncoding);
var res := new NSMutableString withCapacity(1024);
res.appendString('{"name":"');
res.appendString(s);
res.appendString('"');
var sz := class_getSuperclass(clz);
if sz <> nil then begin
s := new Foundation.NSString withCString(class_getName(sz)) encoding(Foundation.NSStringEncoding.UTF8StringEncoding);
res.appendString(',"base":"');
res.appendString(s);
res.appendString('"');
end;
res.appendString( ',"methods":[');
var methodCount: UInt32 := 0;
var methods: ^&Method := class_copyMethodList(clz, @methodCount);
for i: Integer := 0 to methodCount - 1 do begin
var &method: &Method := methods[i];
cl := sel_getName(method_getName(&method));
s := new Foundation.NSString withCString(cl) encoding(Foundation.NSStringEncoding.UTF8StringEncoding);
if i <> 0 then
res.appendString(',');
res.appendString('{"selector":"');
res.appendString(s);
res.appendString('"');
cl := method_getTypeEncoding(&method);
s := new Foundation.NSString withCString(cl) encoding(Foundation.NSStringEncoding.UTF8StringEncoding);
s := s.stringByReplacingOccurrencesOfString('"') withString('\"');
res.appendString(',"signature":"');
res.appendString(s);
res.appendString('"');
var imp := method_getImplementation(&method);
var impl := Int64(^IntPtr(@imp)^);
res.appendString( ',"implementation":"'+impl);
res.appendString('"}');
//res.appendString( '}';
end;
rtl.free(methods);
res.appendString(']');
begin
res.appendString( ',"properties":[');
//var methodCount: UInt32 := 0;
var props: ^objc_property_t := class_copyPropertyList(clz, @methodCount);
for i: Integer := 0 to methodCount - 1 do begin
var &prop := props[i];
cl := property_getName(&prop);
s := new Foundation.NSString withCString(cl) encoding(Foundation.NSStringEncoding.UTF8StringEncoding);
if i <> 0 then
res.appendString(',');
res.appendString( '{"name":"');
res.appendString(s);
res.appendString('"');
cl := property_getAttributes(&prop);
s := new Foundation.NSString withCString(cl) encoding(Foundation.NSStringEncoding.UTF8StringEncoding);
s := s.stringByReplacingOccurrencesOfString('"') withString('\"');
res.appendString(',"signature":"');
res.appendString(s);
res.appendString('"}');
//res.appendString( '}';
end;
rtl.free(props);
res.appendString(']');
end;
begin
res.appendString(',"fields":[');
//var methodCount: UInt32 := 0;
var props: ^Ivar := class_copyIvarList(clz, @methodCount);
for i: Integer := 0 to methodCount - 1 do begin
var &prop := props[i];
cl := ivar_getName(&prop);
s := new Foundation.NSString withCString(cl) encoding(Foundation.NSStringEncoding.UTF8StringEncoding);
if i <> 0 then
res.appendString(',');
res.appendString( '{"name":"');
res.appendString(s);
res.appendString('"');
cl := ivar_getTypeEncoding(&prop);
s := new Foundation.NSString withCString(cl) encoding(Foundation.NSStringEncoding.UTF8StringEncoding);
s := s.stringByReplacingOccurrencesOfString('"') withString('\"');
res.appendString( ',"type":"');
res.appendString(s);
res.appendString('"');
var off := ivar_getOffset(&prop);
res.appendString( ',"offset":"'+off);
res.appendString('"}');
//res.appendString('}';
end;
rtl.free(props);
res.appendString(']');
end;
clz := objc_getMetaClass(class_getName(clz));
res.appendString( ',"classMethods":[');
methodCount := 0;
methods := class_copyMethodList(clz, @methodCount);
for i: Integer := 0 to methodCount - 1 do begin
var &method: &Method := methods[i];
cl := sel_getName(method_getName(&method));
s := new Foundation.NSString withCString(cl) encoding(Foundation.NSStringEncoding.UTF8StringEncoding);
if i <> 0 then
res.appendString(',');
res.appendString('{"selector":"');
res.appendString(s);
res.appendString('"');
cl := method_getTypeEncoding(&method);
s := new Foundation.NSString withCString(cl) encoding(Foundation.NSStringEncoding.UTF8StringEncoding);
s := s.stringByReplacingOccurrencesOfString('"') withString('\"');
res.appendString( ',"signature":"');
res.appendString(s);
res.appendString('"');
var imp := method_getImplementation(&method);
var impl := Int64(^IntPtr(@imp)^);
res.appendString( ',"implementation":"'+impl);
res.appendString('"}');
//res.appendString( '}';
end;
rtl.free(methods);
res.appendString(']');
res.appendString(',"classProperties":[');
//var methodCount: UInt32 := 0;
var props: ^objc_property_t := class_copyPropertyList(clz, @methodCount);
for i: Integer := 0 to methodCount - 1 do begin
var &prop := props[i];
cl := property_getName(&prop);
s := new Foundation.NSString withCString(cl) encoding(Foundation.NSStringEncoding.UTF8StringEncoding);
if i <> 0 then
res.appendString(',');
res.appendString( '{"name":"');
res.appendString(s);
res.appendString('"');
cl := property_getAttributes(&prop);
s := new Foundation.NSString withCString(cl) encoding(Foundation.NSStringEncoding.UTF8StringEncoding);
s := s.stringByReplacingOccurrencesOfString('"') withString('\"');
res.appendString(',"signature":"');
res.appendString(s);
res.appendString('"}');
//res.appendString( '}';
end;
rtl.free(props);
res.appendString(']}');
__ElementsObjcClassInfoToStringValue := res;
exit __ElementsObjcClassInfoToStringValue.UTF8String;
//exit buf;
end;
end. |
unit fWfxPluginCopyMoveOperationOptions;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, StdCtrls, ExtCtrls,
uFileSourceOperationOptionsUI,
uFileSourceCopyOperation,
uWfxPluginCopyOperation,
uWfxPluginMoveOperation,
uWfxPluginCopyInOperation,
uWfxPluginCopyOutOperation;
type
{ TWfxPluginCopyMoveOperationOptionsUI }
TWfxPluginCopyMoveOperationOptionsUI = class(TFileSourceOperationOptionsUI)
cbCopyTime: TCheckBox;
cbWorkInBackground: TCheckBox;
cmbFileExists: TComboBox;
grpOptions: TGroupBox;
lblFileExists: TLabel;
pnlCheckboxes: TPanel;
pnlComboBoxes: TPanel;
procedure cbWorkInBackgroundChange(Sender: TObject);
private
procedure SetCopyOptions(CopyOperation: TFileSourceCopyOperation);
procedure SetOperationOptions(CopyOperation: TWfxPluginCopyOperation); overload;
procedure SetOperationOptions(MoveOperation: TWfxPluginMoveOperation); overload;
procedure SetOperationOptions(CopyInOperation: TWfxPluginCopyInOperation); overload;
procedure SetOperationOptions(CopyOutOperation: TWfxPluginCopyOutOperation); overload;
public
constructor Create(AOwner: TComponent; AFileSource: IInterface); override;
procedure SaveOptions; override;
procedure SetOperationOptions(Operation: TObject); override;
end;
TWfxPluginCopyOperationOptionsUI = class(TWfxPluginCopyMoveOperationOptionsUI)
end;
TWfxPluginMoveOperationOptionsUI = class(TWfxPluginCopyMoveOperationOptionsUI)
end;
{ TWfxPluginCopyInOperationOptionsUI }
TWfxPluginCopyInOperationOptionsUI = class(TWfxPluginCopyMoveOperationOptionsUI)
public
constructor Create(AOwner: TComponent; AFileSource: IInterface); override;
end;
{ TWfxPluginCopyOutOperationOptionsUI }
TWfxPluginCopyOutOperationOptionsUI = class(TWfxPluginCopyMoveOperationOptionsUI)
public
constructor Create(AOwner: TComponent; AFileSource: IInterface); override;
end;
implementation
{$R *.lfm}
uses
DCStrUtils, uLng, DCOSUtils, WfxPlugin, fCopyMoveDlg, uGlobs, uWfxPluginFileSource,
uFileSourceOperationOptions, uOperationsManager;
{ TWfxPluginCopyMoveOperationOptionsUI }
constructor TWfxPluginCopyMoveOperationOptionsUI.Create(AOwner: TComponent; AFileSource: IInterface);
begin
inherited Create(AOwner, AFileSource);
ParseLineToList(rsFileOpCopyMoveFileExistsOptions, cmbFileExists.Items);
// Load default options.
case gOperationOptionFileExists of
fsoofeNone : cmbFileExists.ItemIndex := 0;
fsoofeOverwrite: cmbFileExists.ItemIndex := 1;
fsoofeSkip : cmbFileExists.ItemIndex := 2;
end;
with (AFileSource as IWfxPluginFileSource).WfxModule do
begin
cbCopyTime.Visible := Assigned(FsSetTime) or Assigned(FsSetTimeW);
cbCopyTime.Checked := cbCopyTime.Visible and gOperationOptionCopyTime;
end;
end;
procedure TWfxPluginCopyMoveOperationOptionsUI.SaveOptions;
begin
// TODO: Saving options for each file source operation separately.
end;
procedure TWfxPluginCopyMoveOperationOptionsUI.SetOperationOptions(Operation: TObject);
begin
if Operation is TWfxPluginCopyOperation then
SetOperationOptions(Operation as TWfxPluginCopyOperation)
else if Operation is TWfxPluginMoveOperation then
SetOperationOptions(Operation as TWfxPluginMoveOperation)
else if Operation is TWfxPluginCopyInOperation then
SetOperationOptions(Operation as TWfxPluginCopyInOperation)
else if Operation is TWfxPluginCopyOutOperation then
SetOperationOptions(Operation as TWfxPluginCopyOutOperation);
end;
procedure TWfxPluginCopyMoveOperationOptionsUI.cbWorkInBackgroundChange(
Sender: TObject);
begin
with (Owner as TfrmCopyDlg) do
begin
if not cbWorkInBackground.Checked then
QueueIdentifier:= ModalQueueId
else begin
QueueIdentifier:= SingleQueueId;
end;
btnAddToQueue.Visible:= cbWorkInBackground.Checked;
btnCreateSpecialQueue.Visible:= btnAddToQueue.Visible;
end;
end;
procedure TWfxPluginCopyMoveOperationOptionsUI.SetCopyOptions(CopyOperation: TFileSourceCopyOperation);
begin
with CopyOperation do
begin
if cbCopyTime.Checked then
CopyAttributesOptions := CopyAttributesOptions + [caoCopyTime]
else begin
CopyAttributesOptions := CopyAttributesOptions - [caoCopyTime];
end;
end;
end;
procedure TWfxPluginCopyMoveOperationOptionsUI.SetOperationOptions(CopyOperation: TWfxPluginCopyOperation);
begin
with CopyOperation do
begin
case cmbFileExists.ItemIndex of
0: FileExistsOption := fsoofeNone;
1: FileExistsOption := fsoofeOverwrite;
2: FileExistsOption := fsoofeSkip;
end;
SetCopyOptions(CopyOperation);
end;
end;
procedure TWfxPluginCopyMoveOperationOptionsUI.SetOperationOptions(MoveOperation: TWfxPluginMoveOperation);
begin
with MoveOperation do
begin
case cmbFileExists.ItemIndex of
0: FileExistsOption := fsoofeNone;
1: FileExistsOption := fsoofeOverwrite;
2: FileExistsOption := fsoofeSkip;
end;
end;
end;
procedure TWfxPluginCopyMoveOperationOptionsUI.SetOperationOptions(CopyInOperation: TWfxPluginCopyInOperation);
begin
with CopyInOperation do
begin
NeedsConnection:= not cbWorkInBackground.Checked;
case cmbFileExists.ItemIndex of
0: FileExistsOption := fsoofeNone;
1: FileExistsOption := fsoofeOverwrite;
2: FileExistsOption := fsoofeSkip;
end;
SetCopyOptions(CopyInOperation);
end;
end;
procedure TWfxPluginCopyMoveOperationOptionsUI.SetOperationOptions(CopyOutOperation: TWfxPluginCopyOutOperation);
begin
with CopyOutOperation do
begin
NeedsConnection:= not cbWorkInBackground.Checked;
case cmbFileExists.ItemIndex of
0: FileExistsOption := fsoofeNone;
1: FileExistsOption := fsoofeOverwrite;
2: FileExistsOption := fsoofeSkip;
end;
SetCopyOptions(CopyOutOperation);
end;
end;
{ TWfxPluginCopyInOperationOptionsUI }
constructor TWfxPluginCopyInOperationOptionsUI.Create(AOwner: TComponent;
AFileSource: IInterface);
const
CAN_UPLOAD = BG_UPLOAD or BG_ASK_USER;
begin
inherited Create(AOwner, AFileSource);
with (AFileSource as IWfxPluginFileSource) do
begin
cbWorkInBackground.Visible:= (WfxModule.BackgroundFlags and CAN_UPLOAD) = CAN_UPLOAD;
if cbWorkInBackground.Visible then
cbWorkInBackground.Checked:= False
else
cbWorkInBackground.Checked:= (WfxModule.BackgroundFlags and BG_UPLOAD <> 0);
end;
cbWorkInBackgroundChange(cbWorkInBackground);
end;
{ TWfxPluginCopyOutOperationOptionsUI }
constructor TWfxPluginCopyOutOperationOptionsUI.Create(AOwner: TComponent;
AFileSource: IInterface);
const
CAN_DOWNLOAD = BG_DOWNLOAD or BG_ASK_USER;
begin
inherited Create(AOwner, AFileSource);
with (AFileSource as IWfxPluginFileSource) do
begin
cbWorkInBackground.Visible:= (WfxModule.BackgroundFlags and CAN_DOWNLOAD) = CAN_DOWNLOAD;
if cbWorkInBackground.Visible then
cbWorkInBackground.Checked:= False
else
cbWorkInBackground.Checked:= (WfxModule.BackgroundFlags and BG_DOWNLOAD <> 0);
end;
cbWorkInBackgroundChange(cbWorkInBackground);
end;
end.
|
unit Pagamentos;
interface
uses
{ Fluente }
Util;
type
IPagamentoDinheiro = interface
['{81C9D4FB-BE52-48F5-9DCA-A6DA609E6B75}']
function Parametros: TMap;
procedure RegistrarPagamentoEmDinheiro(const Parametros: TMap);
end;
IPagamentoCartaoDeDebito = interface
['{2EB6B1D5-B28A-4A4D-9A57-244ABC0F8218}']
function Parametros: TMap;
procedure RegistrarPagamentoCartaoDeDebito(const Parametros: TMap);
end;
IPagamentoCartaoDeCredito = interface
['{F95F08EA-76C0-4505-B6CA-AC15A0E8B702}']
function Parametros: TMap;
procedure RegistrarPagamentoCartaoDeCredito(const Parametros: TMap);
end;
implementation
end.
|
unit Thread.Trim.Helper.List;
interface
uses
SysUtils, Classes,
TrimList, Thread.Trim.Helper.Partition, Thread.Trim.Helper.Partition.Direct,
Thread.Trim.Helper.Partition.OS, ThreadToView.Trim, Component.ProgressSection,
OS.Version.Helper, Getter.OS.Version, Getter.External;
type
TTrimStage = (Initial, InProgress, Finished, Error);
TListTrimmer = class
private
IsUIInteractionNeededReadWrite: Boolean;
ProgressReadWrite: Integer;
TrimStageReadWrite: TTrimStage;
TrimThreadToView: TTrimThreadToView;
PartitionsToTrim: TTrimList;
ThreadToSynchronize: TThread;
ProgressSynchronizer: TProgressSection;
function IsFreeFromSynchronizeIssue: Boolean;
procedure CheckSynchronizeIssue;
procedure CheckIssueAndTrimAppliedPartitions;
procedure TrimAppliedPartitions;
procedure CheckNilPartitionListIssue;
procedure TrimPartition(const PartitionPathToTrim: String);
procedure CheckEntryAndTrimPartition(PartitionToTrim: TTrimListEntry);
function GetTrimSynchronization: TTrimSynchronization;
procedure IfNeedUICreateModelController;
procedure IfNeedUIFreeModelController;
procedure IfPartitionListExistsFreeAndNil;
procedure TrimAppliedPartitionsWithProgressSection;
function IsExternal(const PartitionPathToTrim: String): Boolean;
function NeedDirectTrim(const PartitionPathToTrim: String): Boolean;
public
property IsUIInteractionNeeded:
Boolean read IsUIInteractionNeededReadWrite;
property Progress: Integer read ProgressReadWrite;
property TrimStage: TTrimStage read TrimStageReadWrite;
constructor Create(IsUIInteractionNeeded: Boolean);
function SetPartitionList(PartitionsToSet: TTrimList): Boolean;
procedure TrimAppliedPartitionsWithUI(ThreadToSynchronize: TThread);
procedure TrimAppliedPartitionsWithoutUI;
end;
implementation
{ TTrimmer }
function TListTrimmer.SetPartitionList(PartitionsToSet: TTrimList): Boolean;
begin
result := PartitionsToSet <> nil;
if not result then
exit;
PartitionsToTrim := PartitionsToSet;
end;
function TListTrimmer.IsFreeFromSynchronizeIssue:
Boolean;
begin
result :=
(not IsUIInteractionNeeded) or
(IsUIInteractionNeeded and (ThreadToSynchronize <> nil));
end;
procedure TListTrimmer.TrimAppliedPartitionsWithoutUI;
begin
TrimAppliedPartitionsWithUI(nil);
end;
procedure TListTrimmer.CheckSynchronizeIssue;
begin
if not IsFreeFromSynchronizeIssue then
raise EInvalidOperation.Create
('Invalid Operation: Call with proper thread to synchronize');
end;
procedure TListTrimmer.CheckNilPartitionListIssue;
begin
if PartitionsToTrim = nil then
raise EArgumentNilException.Create
('Null Argument: Call with proper partition list to trim');
end;
procedure TListTrimmer.IfPartitionListExistsFreeAndNil;
begin
if PartitionsToTrim <> nil then
FreeAndNil(PartitionsToTrim);
end;
procedure TListTrimmer.TrimAppliedPartitionsWithProgressSection;
begin
try
ProgressSynchronizer.ShowProgress;
CheckIssueAndTrimAppliedPartitions;
IfPartitionListExistsFreeAndNil;
except
TrimStageReadWrite := TTrimStage.Error;
end;
end;
procedure TListTrimmer.TrimAppliedPartitionsWithUI
(ThreadToSynchronize: TThread);
begin
self.ThreadToSynchronize := ThreadToSynchronize;
ProgressSynchronizer := TProgressSection.Create(ThreadToSynchronize);
try
TrimAppliedPartitionsWithProgressSection;
finally
FreeAndNil(ProgressSynchronizer);
end;
end;
procedure TListTrimmer.CheckIssueAndTrimAppliedPartitions;
begin
CheckSynchronizeIssue;
CheckNilPartitionListIssue;
TrimStageReadWrite := TTrimStage.InProgress;
TrimAppliedPartitions;
TrimStageReadWrite := TTrimStage.Finished;
end;
procedure TListTrimmer.IfNeedUICreateModelController;
begin
if ThreadToSynchronize <> nil then
TrimThreadToView := TTrimThreadToView.Create(GetTrimSynchronization);
end;
procedure TListTrimmer.IfNeedUIFreeModelController;
begin
if TrimThreadToView <> nil then
begin
TrimThreadToView.ApplyOriginalUI;
ProgressSynchronizer.HideProgress;
FreeAndNil(TrimThreadToView);
end;
end;
procedure TListTrimmer.TrimAppliedPartitions;
var
CurrentPartition: Integer;
begin
IfNeedUICreateModelController;
for CurrentPartition := 0 to PartitionsToTrim.Count - 1 do //FI:W528
CheckEntryAndTrimPartition(PartitionsToTrim.GetNextPartition);
IfNeedUIFreeModelController;
end;
constructor TListTrimmer.Create(IsUIInteractionNeeded: Boolean);
begin
IsUIInteractionNeededReadWrite := IsUIInteractionNeeded;
end;
procedure TListTrimmer.CheckEntryAndTrimPartition(
PartitionToTrim: TTrimListEntry);
begin
if PartitionToTrim.Status =
TNextPartitionStatus.CompleteLastPartitionFirst then
exit;
TrimPartition(PartitionToTrim.PartitionPath);
PartitionsToTrim.CompleteCurrentPartition;
end;
function TListTrimmer.GetTrimSynchronization: TTrimSynchronization;
begin
result.IsUIInteractionNeeded := IsUIInteractionNeededReadWrite;
result.ThreadToSynchronize := ThreadToSynchronize;
result.Progress.CurrentPartition := PartitionsToTrim.CurrentPartition;
result.Progress.PartitionCount := PartitionsToTrim.Count;
end;
function TListTrimmer.IsExternal(const PartitionPathToTrim: String): Boolean;
var
ExternalGetter: TExternalGetter;
begin
ExternalGetter := TExternalGetter.Create;
try
result := ExternalGetter.IsExternal(PartitionPathToTrim);
finally
FreeAndNil(ExternalGetter);
end;
end;
function TListTrimmer.NeedDirectTrim(const PartitionPathToTrim: String):
Boolean;
begin
result :=
IsBelowWindows8(VersionHelper.Version) or IsExternal(PartitionPathToTrim);
end;
procedure TListTrimmer.TrimPartition(const PartitionPathToTrim: String);
var
PartitionTrimmer: TPartitionTrimmer;
TrimSynchronization: TTrimSynchronization;
begin
if NeedDirectTrim(PartitionPathToTrim) then
PartitionTrimmer := TDirectPartitionTrimmer.Create(PartitionPathToTrim)
else
PartitionTrimmer := TOSPartitionTrimmer.Create(PartitionPathToTrim);
TrimSynchronization := GetTrimSynchronization;
PartitionTrimmer.TrimPartition(TrimSynchronization);
FreeAndNil(PartitionTrimmer);
end;
end.
|
unit ParametersValueQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
BaseEventsQuery, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, Vcl.StdCtrls, ParametricExcelDataModule,
BaseQuery, DSWrap;
type
TParameterValueW = class(TDSWrap)
private
FParamSubParamId: TFieldWrap;
FID: TFieldWrap;
FProductId: TFieldWrap;
FValue: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
procedure AddNewValue(const AValue: string);
procedure LocateOrAppend(AValue: string);
property ParamSubParamId: TFieldWrap read FParamSubParamId;
property ID: TFieldWrap read FID;
property ProductId: TFieldWrap read FProductId;
property Value: TFieldWrap read FValue;
end;
TQueryParametersValue = class(TQueryBaseEvents)
private
FW: TParameterValueW;
procedure DoAfterInsert(Sender: TObject);
{ Private declarations }
protected
function CreateDSWrap: TDSWrap; override;
public
constructor Create(AOwner: TComponent); override;
procedure Search(AIDComponent, AParamSubParamID: Integer); overload;
property W: TParameterValueW read FW;
{ Public declarations }
end;
implementation
{$R *.dfm}
uses NotifyEvents;
constructor TQueryParametersValue.Create(AOwner: TComponent);
begin
inherited;
FW := FDSWrap as TParameterValueW;
TNotifyEventWrap.Create(W.AfterInsert, DoAfterInsert, W.EventList);
end;
function TQueryParametersValue.CreateDSWrap: TDSWrap;
begin
Result := TParameterValueW.Create(FDQuery);
end;
procedure TQueryParametersValue.DoAfterInsert(Sender: TObject);
begin
W.ParamSubParamId.F.AsInteger :=
FDQuery.ParamByName(W.ParamSubParamId.FieldName).AsInteger;
W.ProductId.F.AsInteger := FDQuery.ParamByName(W.ProductId.FieldName)
.AsInteger;
end;
procedure TQueryParametersValue.Search(AIDComponent, AParamSubParamID: Integer);
begin
Assert(AIDComponent > 0);
Assert(AParamSubParamID > 0);
SearchEx([TParamRec.Create(W.ProductId.FullName, AIDComponent),
TParamRec.Create(W.ParamSubParamId.FullName, AParamSubParamID)]);
end;
constructor TParameterValueW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'pv.ID', '', True);
FParamSubParamId := TFieldWrap.Create(Self, 'pv.ParamSubParamId');
FProductId := TFieldWrap.Create(Self, 'pv.ProductId');
FValue := TFieldWrap.Create(Self, 'pv.Value');
end;
procedure TParameterValueW.AddNewValue(const AValue: string);
begin
TryAppend;
Value.F.AsString := AValue;
TryPost;
end;
procedure TParameterValueW.LocateOrAppend(AValue: string);
var
OK: Boolean;
begin
OK := FDDataSet.LocateEx(Value.FieldName, AValue, []);
if not OK then
AddNewValue(AValue);
end;
end.
|
unit Chronogears.Form.Main;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation, FMX.Layouts, FMX.ListBox, FMX.Objects,
FMX.ScrollBox, FMX.Memo, FMX.Edit, IPPeerClient,
Chronogears.Azure.Model, Chronogears.Form.Authorize, Data.Bind.Components,
Data.Bind.ObjectScope, REST.Client, REST.Types, REST.Json, System.JSON,
FMX.Memo.Types;
type
TMainForm = class(TForm)
CommandLogIn: TButton;
LabelAuthStatus: TLabel;
Line1: TLine;
CommandGetResourceGroups: TButton;
ListResGroup: TListBox;
LabelRaw: TLabel;
LabelList: TLabel;
Line2: TLine;
FieldResGroupName: TEdit;
FieldRawResponse: TMemo;
CommandCreateResGroup: TButton;
CommandGetAccessToken: TButton;
LabelToken: TLabel;
Line3: TLine;
RESTTokenRequest: TRESTRequest;
RESTTokenResponse: TRESTResponse;
RESTListResGroupRequest: TRESTRequest;
RESTClient: TRESTClient;
RESTListResGroupResponse: TRESTResponse;
RESTCreateResGroupRequest: TRESTRequest;
RESTCreateResGroupResponse: TRESTResponse;
procedure FormCreate(Sender: TObject);
procedure CommandLogInClick(Sender: TObject);
procedure CommandGetAccessTokenClick(Sender: TObject);
procedure RESTTokenRequestAfterExecute(Sender: TCustomRESTRequest);
procedure CommandGetResourceGroupsClick(Sender: TObject);
procedure RESTListResGroupRequestAfterExecute(Sender: TCustomRESTRequest);
procedure CommandCreateResGroupClick(Sender: TObject);
procedure RESTCreateResGroupRequestAfterExecute(Sender: TCustomRESTRequest);
private
{ Private declarations }
FConnection: TAzureConnection;
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.fmx}
uses
System.NetEncoding, System.Net.URLClient;
procedure TMainForm.CommandCreateResGroupClick(Sender: TObject);
var
LResource: string;
begin
Cursor := crHourGlass;
CommandCreateResGroup.Enabled := false;
LResource := Format(
'subscriptions/%s/resourcegroups/%s?api-version=2018-02-01',
[FConnection.SubscriptionId, FieldResGroupName.Text]
);
RESTClient.BaseURL := FConnection.RESTEndPoint;
RESTCreateResGroupRequest.Resource := LResource;
RESTCreateResGroupRequest.Method := TRESTRequestMethod.rmPUT;
RESTCreateResGroupRequest.Params.Clear;
RESTCreateResGroupRequest.Params.AddItem('Authorization', 'Bearer ' + FConnection.AuthToken, TRESTRequestParameterKind.pkHTTPHEADER, [poDoNotEncode]);
RESTCreateResGroupRequest.Body.Add('{location:''canadacentral''}', TRESTContentType.ctAPPLICATION_JSON);
RESTCreateResGroupRequest.Execute;
end;
procedure TMainForm.CommandGetAccessTokenClick(Sender: TObject);
begin
RestClient.BaseURL := FConnection.TokenEndPoint;
RESTTokenRequest.Method := TRESTRequestMethod.rmPOST;
RESTTokenRequest.Params.AddItem('client_id', FConnection.ClientId, TRestRequestParameterKind.pkQUERY);
RESTTokenRequest.Params.AddItem('grant_type', 'authorization_code', TRestRequestParameterKind.pkREQUESTBODY);
RESTTokenRequest.Params.AddItem('client_id', FConnection.ClientId, TRestRequestParameterKind.pkREQUESTBODY);
RESTTokenRequest.Params.AddItem('code', FConnection.AuthCode, TRestRequestParameterKind.pkREQUESTBODY);
RESTTokenRequest.Params.AddItem('client_secret', FConnection.ClientSecret, TRestRequestParameterKind.pkREQUESTBODY);
RESTTokenRequest.Params.AddItem('resource', FConnection.Resource, TRestRequestParameterKind.pkREQUESTBODY);
// RESTTokenRequest.Params.AddItem('scope', 'openid', TRestRequestParameterKind.pkREQUESTBODY);
RESTTokenRequest.Params.AddItem('redirect_uri', FConnection.RedirectURL, TRestRequestParameterKind.pkREQUESTBODY);
Cursor := crHourGlass;
RESTTokenRequest.ExecuteAsync;
end;
procedure TMainForm.CommandGetResourceGroupsClick(Sender: TObject);
begin
Cursor := crHourGlass;
RESTClient.BaseURL := FConnection.RESTEndPoint;
RESTListResGroupRequest.Resource := 'subscriptions/' + FConnection.SubscriptionId + '/resourcegroups?api-version=2018-02-01';
RESTListResGroupRequest.Params.AddItem('Authorization', 'Bearer ' + FConnection.AuthToken, TRESTRequestParameterKind.pkHTTPHEADER, [poDoNotEncode]);
RESTListResGroupRequest.Params.AddItem('Content-Type', 'application/json', TRESTRequestParameterKind.pkHTTPHEADER);
RESTListResGroupRequest.ExecuteAsync;
end;
procedure TMainForm.CommandLogInClick(Sender: TObject);
begin
AuthorizeForm.GetAuthToken(FConnection);
if AuthorizeForm.ModalResult = mrOk then
begin
LabelAuthStatus.Text := 'Authentication Code: ' + FConnection.AuthCode.Substring(0, 8) + '...';
CommandGetAccessToken.Enabled := True;
end;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
{$MESSAGE ERROR 'Enter your tenant id, subscription id, client id, and client secret below then delete this line'}
FConnection := TAzureConnection.Create;
FConnection.TenantId := '<<TENANT ID>>';
FConnection.SubscriptionId := '<<SUBSCRIPTION ID>>';
FConnection.ClientId := '<<CLIENT ID';
FConnection.ClientSecret := '<<CLIENT SECRET>>';
FConnection.Resource := 'https://management.core.windows.net/';
FConnection.RedirectURL := 'https://chronogears.com/azure';
FConnection.AuthorizeEndPoint := 'https://login.microsoftonline.com/' + FConnection.TenantId + '/oauth2/v2.0/authorize';
FConnection.TokenEndPoint := 'https://login.microsoftonline.com/' + FConnection.TenantId + '/oauth2/token';
FConnection.RESTEndPoint := 'https://management.azure.com';
end;
procedure TMainForm.RESTCreateResGroupRequestAfterExecute(
Sender: TCustomRESTRequest);
begin
Cursor := crArrow;
CommandCreateResGroup.Enabled := true;
CommandGetResourceGroupsClick(Sender);
end;
procedure TMainForm.RESTListResGroupRequestAfterExecute(Sender: TCustomRESTRequest);
var
ResGroup: TJSONValue;
ResGroupName: string;
begin
Cursor := crArrow;
FieldRawResponse.Text := TJSON.Format(RESTListResGroupResponse.JSONValue);
ListResGroup.Items.Clear;
for ResGroup in RESTListResGroupResponse.JSONValue.GetValue<TJSONArray>('value') do
begin
ResGroupName := ResGroup.GetValue<string>('name');
ListResGroup.Items.Add(ResGroupName);
end;
end;
procedure TMainForm.RESTTokenRequestAfterExecute(Sender: TCustomRESTRequest);
begin
Cursor := crArrow;
if RESTTokenResponse.StatusCode = 200 then
begin
FConnection.AuthToken := RESTTokenResponse.JSONValue.GetValue<String>('access_token');
LabelToken.Text := 'Access Token: ' + FConnection.AuthToken.Substring(0, 8) + '...';
CommandGetResourceGroups.Enabled := True;
CommandCreateResGroup.Enabled := True;
end else begin
MessageDlg(RESTTokenResponse.Content, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0);
end;
end;
end.
|
unit peminjaman_handler;
interface
uses
tipe_data;
{ KONSTANTA }
const
nmax = 1000; // Asumsi bahwa size terbesar dari database adalah 1000
{ DEKLARASI TIPE }
type
peminjaman = record
Username, ID_Buku, Tanggal_Peminjaman, Tanggal_Batas_Pengembalian, Status_Pengembalian : string;
end;
tabel_peminjaman = record
t: array [0..nmax] of peminjaman;
sz: integer; // effective size
end;
{ DEKLARASI FUNGSI DAN PROSEDUR }
function tambah(s: arr_str): tabel_peminjaman;
procedure tulis(data_temppeminjaman: tabel_peminjaman);
function konversi_csv(data_temppeminjaman: tabel_peminjaman): arr_str;
{ IMPLEMENTASI FUNGSI DAN PROSEDUR }
implementation
function tambah(s: arr_str): tabel_peminjaman;
{ DESKRIPSI : Memasukkan data dari array of string kedalam tabel_peminjaman }
{ PARAMETER : array of string }
{ RETURN : data peminjaman }
{ KAMUS LOKAL }
var
col, row: integer; // col = data ke-N, row = baris ke-N dari file csv
temp: string; // string temporer, berfungsi
c: char;
data_temppeminjaman : tabel_peminjaman;
{ ALGORITMA }
begin
data_temppeminjaman.sz := 0;
for row:=0 to s.sz-1 do
begin
col := 0;
temp := '';
for c in s.st[row] do
begin
if(c=',') then
begin
// 0 based indexing
case col of
0: data_temppeminjaman.t[data_temppeminjaman.sz].Username := temp;
1: data_temppeminjaman.t[data_temppeminjaman.sz].ID_Buku := temp;
2: data_temppeminjaman.t[data_temppeminjaman.sz].Tanggal_Peminjaman := temp;
3: data_temppeminjaman.t[data_temppeminjaman.sz].Tanggal_Batas_Pengembalian := temp;
end;
col := col+1;
temp := '';
end else temp := temp+c;
end;
data_temppeminjaman.t[data_temppeminjaman.sz].Status_Pengembalian := temp;
data_temppeminjaman.sz := data_temppeminjaman.sz+1;
end;
tambah := data_temppeminjaman;
end;
function konversi_csv(data_temppeminjaman: tabel_peminjaman): arr_str;
{ DESKRIPSI : Fungsi untuk mengubah data peminjaman menjadi array of string }
{ PARAMETER : data peminjaman }
{ RETURN : array of string }
{ KAMUS LOKAL }
var
i : integer;
ret : arr_str;
{ ALGORITMA }
begin
ret.sz := data_temppeminjaman.sz;
for i:=0 to data_temppeminjaman.sz do
begin
ret.st[i] := data_temppeminjaman.t[i].Username + ',' +
data_temppeminjaman.t[i].ID_Buku + ',' +
data_temppeminjaman.t[i].Tanggal_Peminjaman + ','+
data_temppeminjaman.t[i].Tanggal_Batas_Pengembalian + ',' +
data_temppeminjaman.t[i].Status_Pengembalian;
end;
konversi_csv := ret;
end;
procedure tulis(data_temppeminjaman: tabel_peminjaman);
{ DESKRIPSI : Prosedur sederhana yang digunakan pada proses pembuatan program untuk debugging, prosedur ini mencetak data ke layar }
{ PARAMETER : Data yang akan dicetak }
{ KAMUS LOKAL }
var
i: integer;
{ ALGORITMA }
begin
for i:=0 to data_temppeminjaman.sz-1 do
begin
writeln(data_temppeminjaman.t[i].Username, ' | ', data_temppeminjaman.t[i].ID_Buku, ' | ', data_temppeminjaman.t[i].Tanggal_Peminjaman, ' | ', data_temppeminjaman.t[i].Tanggal_Batas_Pengembalian, ' | ', data_temppeminjaman.t[i].Status_Pengembalian);
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.