text stringlengths 14 6.51M |
|---|
(*
Name: BaseKeyboards
Copyright: Copyright (C) 2003-2017 SIL International.
Documentation:
Description:
Create Date: 16 Apr 2014
Modified Date: 16 Apr 2014
Authors: mcdurdin
Related Files:
Dependencies:
Bugs:
Todo:
Notes:
History: 16 Apr 2014 - mcdurdin - I4169 - V9.0 - Mnemonic layouts should be recompiled to positional based on user-selected base keyboard
*)
unit BaseKeyboards; // I4169
interface
uses
System.Classes;
type
TBaseKeyboards = class
private
class function IsLatinKeyboard(const KeyboardID: string; LatinKeyboardIDs: TStrings): Boolean;
class function TestAndCacheIsLatinKeyboard(
const KeyboardID: string): Boolean; static;
public
class function EnumerateXML(BaseKeyboardID: Cardinal): string;
class function GetName(BaseKeyboardID: Cardinal): string;
end;
implementation
uses
Winapi.Windows,
System.Character,
System.SysUtils,
System.Win.Registry,
Glossary,
LoadIndirectStringUnit,
RegistryKeys,
UnicodeBlocks,
utilxml;
{ TBaseKeyboards }
class function TBaseKeyboards.EnumerateXML(BaseKeyboardID: Cardinal): string;
var
FKeyNames: TStrings;
I: Integer;
FCaption: string;
FKeyboardID: Integer;
FLanguageName: string;
FLangNames: TStringList;
FLatinKeyboardIDs: TStringList;
begin
FLangNames := TStringList.Create;
FKeyNames := TStringList.Create;
FLatinKeyboardIDs := TStringList.Create;
try
with TRegistry.Create do
try
RootKey := HKEY_LOCAL_MACHINE;
if OpenKeyReadOnly(SRegKey_LatinKeyboardCache) then
begin
GetValueNames(FLatinKeyboardIDs);
for i := 0 to FLatinKeyboardIDs.Count - 1 do
FLatinKeyboardIDs.ValueFromIndex[i] := ReadString(FLatinKeyboardIDs[i]);
end;
finally
Free;
end;
with TRegistry.Create do
try
RootKey := HKEY_LOCAL_MACHINE;
if OpenKeyReadOnly(SRegKey_KeyboardLayouts) then
begin
GetKeyNames(FKeyNames);
for I := 0 to FKeyNames.Count - 1 do
begin
if TryStrToInt('$'+FKeyNames[i], FKeyboardID) and
OpenKeyReadOnly('\' + SRegKey_KeyboardLayouts + '\' + FKeyNames[i]) then
begin
if not IsLatinKeyboard(FKeyNames[i], FLatinKeyboardIDs) then
Continue;
if ValueExists(SRegValue_LayoutDisplayName) then
begin
FCaption := LoadIndirectString(ReadString(SRegValue_LayoutDisplayName));
end
else if ValueExists(SRegValue_KeyboardLayoutText) then
FCaption := ReadString(SRegValue_KeyboardLayoutText)
else
FCaption := FKeyNames[i];
GetLanguageName(HKLToLanguageID(FKeyboardID), FLanguageName);
if not SameText(Copy(FCaption, 1, Length(FLanguageName)), FLanguageName) then
FCaption := FLanguageName + ' - ' + FCaption;
FLangNames.AddObject(FCaption, Pointer(FKeyboardID));
end;
end;
end;
Result := '<BaseKeyboards>';
FLangNames.Sort;
for I := 0 to FLangNames.Count-1 do
begin
Result := Result + '<BaseKeyboard>'+
'<id>'+IntToHex(Integer(FLangNames.Objects[i]),8)+'</id>'+
'<name>'+XMLEncode(FLangNames[i])+'</name>';
if Cardinal(FLangNames.Objects[i]) = BaseKeyboardID then
Result := Result + '<selected />';
Result := Result + '</BaseKeyboard>';
end;
Result := Result + '</BaseKeyboards>';
finally
Free;
end;
finally
FKeyNames.Free;
FLangNames.Free;
end;
end;
class function TBaseKeyboards.GetName(BaseKeyboardID: Cardinal): string;
var
FCaption: string;
FLanguageName: string;
FKeyboardIDString: string;
begin
FKeyboardIDString := IntToHex(BaseKeyboardID, 8);
with TRegistry.Create do
try
RootKey := HKEY_LOCAL_MACHINE;
if OpenKeyReadOnly(SRegKey_KeyboardLayouts + '\' + FKeyboardIDString) then
begin
if ValueExists(SRegValue_LayoutDisplayName) then
begin
FCaption := LoadIndirectString(ReadString(SRegValue_LayoutDisplayName));
end
else if ValueExists(SRegValue_KeyboardLayoutText) then
begin
FCaption := ReadString(SRegValue_KeyboardLayoutText)
end
else
begin
FCaption := FKeyboardIDString;
end;
GetLanguageName(HKLToLanguageID(BaseKeyboardID), FLanguageName);
if not SameText(Copy(FCaption, 1, Length(FLanguageName)), FLanguageName) then
FCaption := FLanguageName + ' - ' + FCaption;
Result := FCaption;
end;
finally
Free;
end;
end;
class function TBaseKeyboards.IsLatinKeyboard(const KeyboardID: string; LatinKeyboardIDs: TStrings): Boolean;
var
v: string;
begin
v := LatinKeyboardIDs.Values[KeyboardID];
if v = ''
then Result := TestAndCacheIsLatinKeyboard(KeyboardID)
else Result := v = '1';
end;
function IsLatin(ch: string): Boolean;
var
i: Integer;
begin
if Char.IsLetter(ch, 0) then
for i := 0 to High(SUnicodeBlocks) do
if (Ord(ch[1]) >= SUnicodeBlocks[i].Ch1) and (Ord(ch[1]) <= SUnicodeBlocks[i].Ch2) then
Exit(SameText(SUnicodeBlocks[i].CleanName, 'Latin'));
Result := False;
end;
class function TBaseKeyboards.TestAndCacheIsLatinKeyboard(const KeyboardID: string): Boolean;
var
i, v, count: Integer;
h: HKL;
hp, hkls: PHKL;
Found: Boolean;
FIsLatin: Integer;
buf: array[0..8] of char;
keystate: TKeyboardState;
begin
FIsLatin := 0;
if not TryStrToInt('$'+KeyboardID, v) then
begin
// Ignore the keyboard ID if it is not hexadecimal
end
else if PRIMARYLANGID(v) in [LANG_ARABIC, LANG_CHINESE, LANG_JAPANESE, LANG_KOREAN] then
begin
// Special case: ignore Arabic, CJK "English" alternate keyboards
end
else if Copy(KeyboardID, 1, 1) = '0' then
begin
// Only support basic system-supplied DLLs -- not custom "A" or IME/TSF "E" DLLs
GetKeyboardState(keystate);
hkls := GetKeyboardLayouts(count);
if Assigned(hkls) then
begin
// Test the keyboard layout A-Z characters for Latin letters.
h := LoadKeyboardLayout(KeyboardID, KLF_NOTELLSHELL);
if h <> 0 then
begin
for i := Ord('A') to Ord('Z') do
begin
case ToUnicodeEx(i, 0, keystate, buf, 8, 0, h) of
-1: Continue;
0: Continue;
1: ;
else Break;
end;
// ch := buf[0];
if not Char.IsLetter(buf, 0) then
Continue;
if IsLatin(buf)
then FIsLatin := 1;
Break;
end;
// Unload the keyboard layout if not already loaded
hp := hkls;
Found := False;
for i := 0 to count - 1 do
begin
if hp^ = h then
begin
Found := True;
Break;
end;
Inc(hp);
end;
if not Found then
begin
UnloadKeyboardLayout(h);
end;
end;
FreeMem(hkls);
end;
end;
with TRegistry.Create do
try
RootKey := HKEY_LOCAL_MACHINE;
if OpenKey(SRegKey_LatinKeyboardCache, True) then
begin
WriteString(KeyboardID, IntToStr(FIsLatin));
end;
finally
Free;
end;
Result := FIsLatin = 1;
end;
end.
|
unit Amazon.Environment;
interface
Uses {$IFNDEF FPC}
System.SysUtils;
{$ELSE}
SysUtils;
{$ENDIF}
const
AWS_REGION = 'AWS_REGION';
AWS_ACCESS_KEY_ID = 'AWS_ACCESS_KEY_ID';
AWS_SECRET_ACCESS_KEY = 'AWS_SECRET_ACCESS_KEY';
AWS_CREDENTIAL_FILE = 'AWS_CREDENTIAL_FILE';
AWS_PROFILE = 'AWS_PROFILE';
type
TAmazonEnvironment = class
protected
fsprofile: UTF8String;
fssecret_key: UTF8String;
fsaccess_key: UTF8String;
fsregion: UTF8String;
fscredential_file: UTF8String;
private
function getsecret_key: UTF8String;
procedure setsecret_key(value: UTF8String);
function getaccess_key: UTF8String;
procedure setaccess_key(value: UTF8String);
function getregion: UTF8String;
procedure setregion(value: UTF8String);
function getprofile: UTF8String;
procedure setprofile(value: UTF8String);
function getcredential_file: UTF8String;
procedure setcredential_file(value: UTF8String);
function GetEnvVariableValue(const aVariablename: string): string;
public
property profile: UTF8String read getprofile write setprofile;
property credential_file: UTF8String read getcredential_file
write setcredential_file;
property region: UTF8String read getregion write setregion;
property secret_key: UTF8String read getsecret_key write setsecret_key;
property access_key: UTF8String read getaccess_key write setaccess_key;
procedure GetEnvironmentVariables;
end;
implementation
function TAmazonEnvironment.GetEnvVariableValue(const aVariablename
: string): string;
var
BufSize: Integer;
begin
Result := Trim(GetEnvironmentVariable(aVariablename));
end;
procedure TAmazonEnvironment.GetEnvironmentVariables;
begin
fsaccess_key := GetEnvVariableValue(AWS_ACCESS_KEY_ID);
fssecret_key := GetEnvVariableValue(AWS_SECRET_ACCESS_KEY);
fsregion := GetEnvVariableValue(AWS_REGION);
fscredential_file := GetEnvVariableValue(AWS_CREDENTIAL_FILE);
fsprofile := GetEnvVariableValue(AWS_PROFILE);
end;
function TAmazonEnvironment.getaccess_key: UTF8String;
begin
Result := fsaccess_key;
end;
procedure TAmazonEnvironment.setaccess_key(value: UTF8String);
begin
fsaccess_key := value;
end;
function TAmazonEnvironment.getsecret_key: UTF8String;
begin
Result := fssecret_key;
end;
procedure TAmazonEnvironment.setsecret_key(value: UTF8String);
begin
fssecret_key := value;
end;
function TAmazonEnvironment.getregion: UTF8String;
begin
Result := fsregion;
end;
procedure TAmazonEnvironment.setregion(value: UTF8String);
begin
fsregion := value;
end;
function TAmazonEnvironment.getprofile: UTF8String;
begin
Result := fsprofile;
end;
procedure TAmazonEnvironment.setprofile(value: UTF8String);
begin
fsprofile := value;
end;
function TAmazonEnvironment.getcredential_file: UTF8String;
begin
Result := fscredential_file;
end;
procedure TAmazonEnvironment.setcredential_file(value: UTF8String);
begin
fscredential_file := value;
end;
end.
|
unit adot.Tools.Performance;
{
TTiming = class
Time measuring functions (recursive Start/Stop etc)
TTimeOut = record
Allows to avoid of some operations to be executed too often.
TEventStat = class
Simple way to maintain statistic of action calls
}
interface
uses
adot.Collections.Maps,
System.Diagnostics, { TStopwatch }
System.TimeSpan,
System.Generics.Collections,
System.Generics.Defaults,
System.SysUtils;
type
{ Simple API for time measuring (supports recursion and calculates sum time). Example:
TTiming.Start;
<do something>
OpTime := TTiming.Stop;
Caption := Format('Execution time: %.2f seconds, [OpTime.TotalSeconds]);
or
OpTime := TTiming.Stop('TMyForm.LoadData', TotalTime);
Caption := Format('Execution time: %.2f seconds (total: %.2f), [OpTime.TotalSeconds, TotalTime.TotalSeconds]); }
{ Time measuring functions (recursive Start/Stop etc) }
TTiming = class
protected
type
TTotalStat = record
private
Span: TTimeSpan;
Calls: int64;
public
procedure Init(const ASpan: TTimeSpan; const ACalls: int64);
end;
class var
FTimeStack: TStack<TStopwatch>;
FTotalTimes: TDictionary<string, TTotalStat>;
class function GetTimeStack: TStack<TStopwatch>; static;
class function GetTotalTimes: TDictionary<string, TTotalStat>; static;
class destructor DestroyClass; static;
class property TimeStack: TStack<TStopwatch> read GetTimeStack;
class property TotalTimes: TDictionary<string, TTotalStat> read GetTotalTimes;
public
class procedure Start; static;
class function Stop: TTimeSpan; overload; static;
class function Stop(const OpId: string; out ATotalStat: TTotalStat): TTimeSpan; overload; static;
class function StopAndGetCaption(const OpId: string): string; overload; static;
class function StopAndGetCaption(const OpId,Msg: string): string; overload; static;
end;
{ Simple API to perform periodical actions. Example:
T.StartSec(1, 10); Timeout is 1 sec, check for timeout every 10th iteration.
for i := 0 to Count-1 do
if T.Timedout then
Break
else
ProcessItem(I); }
{ Allows to avoid of some operations to be executed too often }
TTimeOut = record
private
FOpTimedOut: Boolean;
FCounter: integer;
FCheckPeriod: integer;
FStartTime: TDateTime;
FMaxTimeForOp: TDateTime;
function GetTimedOut: Boolean;
public
procedure Init;
{ If we check for timeout every iteration, usually (when iterations are short)
it is too often and our checks may consume more time then usefull work itself.
To check only 1 time for N iterations set ACheckPeriod=N. }
procedure Start(AMaxTimeForOp: TDateTime; ACheckPeriod: integer = 0);
procedure StartSec(AMaxTimeForOpSec: double; ACheckPeriod: integer = 0);
procedure StartInfinite;
procedure Restart;
{ If set True manually, then it will be constantly True until next Start* }
property TimedOut: Boolean read GetTimedOut write FOpTimedOut;
property StartTime: TDateTime read FStartTime;
end;
TEventStat = class
private
FEvents: TMap<string, int64>;
public
procedure Reg(const EventCategory: string); overload;
procedure Reg(const EventCategory: string; Count: int64); overload;
procedure UnReg(const EventCategory: string); overload;
procedure UnReg(const EventCategory: string; Count: int64); overload;
procedure Add(const Src: TArray<TPair<string, int64>>);
procedure Clear;
function GetStat: TArray<TPair<string, int64>>;
function GetCategoryStat(const EventCategory: string): int64;
end;
implementation
uses
adot.Tools;
{ TTiming.TTotalStat }
procedure TTiming.TTotalStat.Init(const ASpan: TTimeSpan; const ACalls: int64);
begin
Self := Default(TTiming.TTotalStat);
Span := ASpan;
Calls := ACalls;
end;
{ TTiming }
class destructor TTiming.DestroyClass;
begin
Sys.FreeAndNil(FTimeStack);
Sys.FreeAndNil(FTotalTimes);
end;
class function TTiming.GetTimeStack: TStack<TStopwatch>;
begin
if FTimeStack=nil then
FTimeStack := TStack<TStopwatch>.Create;
result := FTimeStack;
end;
class function TTiming.GetTotalTimes: TDictionary<string, TTotalStat>;
begin
if FTotalTimes=nil then
FTotalTimes := TDictionary<string, TTotalStat>.Create(TOrdinalIStringComparer.Ordinal);
result := FTotalTimes;
end;
class procedure TTiming.Start;
begin
TimeStack.Push(TStopwatch.StartNew);
end;
class function TTiming.Stop: TTimeSpan;
begin
Result := TimeStack.Pop.Elapsed;
end;
class function TTiming.Stop(const OpId: string; out ATotalStat: TTotalStat): TTimeSpan;
begin
result := Stop;
if not TotalTimes.TryGetValue(OpId, ATotalStat) then
ATotalStat.Init(TTimeSpan.Create(0), 0);
ATotalStat.Span := ATotalStat.Span + result;
inc(ATotalStat.Calls);
TotalTimes.AddOrSetValue(OpId, ATotalStat);
end;
class function TTiming.StopAndGetCaption(const OpId, Msg: string): string;
var
OpTime: TTimeSpan;
TotalStat: TTotalStat;
begin
OpTime := Stop(OpId, TotalStat);
result := Format('%s (%s): %.2f sec (total: %.2f sec; calls: %d)', [
OpId, Msg, OpTime.TotalSeconds, TotalStat.Span.TotalSeconds, TotalStat.Calls]);
end;
class function TTiming.StopAndGetCaption(const OpId: string): string;
var
OpTime: TTimeSpan;
TotalStat: TTotalStat;
begin
OpTime := Stop(OpId, TotalStat);
result := Format('%s: %.2f sec (total: %.2f sec; calls: %d)', [
OpId, OpTime.TotalSeconds, TotalStat.Span.TotalSeconds, TotalStat.Calls]);
end;
{ TTimeOut }
procedure TTimeOut.Init;
begin
Self := Default(TTimeOut);
end;
procedure TTimeOut.Start(AMaxTimeForOp: TDateTime; ACheckPeriod: integer = 0);
begin
FMaxTimeForOp:= AMaxTimeForOp;
FCheckPeriod := ACheckPeriod;
Restart;
end;
procedure TTimeOut.StartSec(AMaxTimeForOpSec: double; ACheckPeriod: integer = 0);
begin
Start(AMaxTimeForOpSec/SecsPerDay, ACheckPeriod);
end;
procedure TTimeOut.StartInfinite;
begin
Start(-1); { negative MaxTimeForOp means that .TimedOut is constantly False }
end;
procedure TTimeOut.Restart;
begin
FStartTime := Now;
FCounter := FCheckPeriod;
FOpTimedOut := FMaxTimeForOp = 0;
end;
function TTimeOut.GetTimedOut: Boolean;
begin
{ negative value = infinite (never timed out) }
if FMaxTimeForOp < 0 then Result := False else
{ already timed out }
if FOpTimedOut then Result := True else
{ check for timeout }
begin
Dec(FCounter);
if FCounter > 0 then Result := False else
begin
FCounter := FCheckPeriod;
Result := Now-FStartTime>FMaxTimeForOp;
FOpTimedOut := Result;
end;
end;
end;
{ TEventStat }
procedure TEventStat.Reg(const EventCategory: string);
begin
Reg(EventCategory, 1);
end;
procedure TEventStat.Reg(const EventCategory: string; Count: int64);
var
C: int64;
begin
if not FEvents.TryGetValue(EventCategory, C) then
C:= 0;
inc(C, Count);
FEvents.AddOrSetValue(EventCategory, C);
end;
procedure TEventStat.UnReg(const EventCategory: string);
begin
UnReg(EventCategory, 1);
end;
procedure TEventStat.UnReg(const EventCategory: string; Count: int64);
var
C: int64;
begin
if FEvents.TryGetValue(EventCategory, C) then
begin
dec(C, Count);
if C <=0
then FEvents.Remove(EventCategory)
else FEvents.AddOrSetValue(EventCategory, C);
end;
end;
procedure TEventStat.Add(const Src: TArray<TPair<string, int64>>);
var
I: Integer;
begin
for I := Low(Src) to High(Src) do
Reg(Src[I].Key, Src[I].Value);
end;
function TEventStat.GetCategoryStat(const EventCategory: string): int64;
begin
if not FEvents.TryGetValue(EventCategory, result) then
result := 0;
end;
function TEventStat.GetStat: TArray<TPair<string, int64>>;
var
C: IComparer<TPair<string, int64>>;
S: IComparer<string>;
begin
result := FEvents.ToArray;
S := TIStringComparer.Ordinal;
C := TDelegatedComparer<TPair<string, int64>>.Create(
function (const A,B: TPair<string, int64>): integer
begin
result := S.Compare(A.Key, B.Key);
if result = 0 then
if A.Key < B.Key then result := -1 else
if A.Key = B.Key then result := 0 else
result := 1 else
end);
TArray.Sort<TPair<string, int64>>(result, C);
end;
procedure TEventStat.Clear;
begin
FEvents.Clear;
end;
end.
|
unit fDebugReport;
{
*
* Debug report
*
* Mutli Thread disabled at this time
* Reason: Issue with nil pointer for threadbroker. Looks as if its being used
* after the thread dies off???
*
*
}
{$WARN SYMBOL_PLATFORM OFF}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ImgList, StdCtrls, Buttons, ExtCtrls, ORNet, Trpcb, uCore,
Vcl.ComCtrls, VAUtils;
type
tRPCArray = record
RPCData: TStringList;
end;
tDebugThread = class(TThread)
private
fThreadDone: Boolean;
fDescription: TStringList;
RPCArray: array of tRPCArray;
ThreadBroker: TRPCBroker;
protected
procedure Execute; override;
public
constructor Create(ActionDescription: TStrings; RPCParams, CurContext: string);
destructor Destroy; override;
end;
tRPCArrayIdent = array of tRPCArray;
tRPCArrayIdentHelper = Record helper for tRPCArrayIdent
public
Procedure Clear;
End;
TfrmDebugReport = class(TForm)
pnlLeft: TPanel;
img1: TImage;
pnlMain: TPanel;
splUser: TSplitter;
Panel1: TPanel;
lbl2: TLabel;
ActionMemo: TMemo;
pnl1: TPanel;
lbl1: TLabel;
IssueMemo: TMemo;
pnl2: TPanel;
btnSend: TBitBtn;
btnCancel: TBitBtn;
DebugProgBar: TProgressBar;
PnlProg: TPanel;
Label1: TLabel;
procedure ActionMemoChange(Sender: TObject);
procedure btnSendClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
private
{ Private declarations }
fRPCS: tRPCArrayIdent;
fDebugReportBroker: TRPCBroker;
fCallbackCrntLoop: Integer;
fCallBackKey: String;
fTaskDLG: TTaskDialog;
fErrTxt: String;
procedure RunNonThread();
function GetTopRPCNumber: Integer;
public
{ Public declarations }
destructor Destroy; override;
function FilteredString(const x: string; ATabWidth: Integer = 8): string;
procedure SendTheRpc(RPCList: TStringList; UniqueKey: string);
procedure SendTheDesc(Description: TStringList; UniqueKey: string);
procedure EnsureDebugBroker;
procedure SendDataCallback(Sender: TObject; TickCount: Cardinal; var Reset: Boolean);
Property TopRPCNumber: Integer read GetTopRPCNumber;
property RPCS: tRPCArrayIdent read fRPCS write fRPCS;
property DebugReportBroker: TRPCBroker read fDebugReportBroker write fDebugReportBroker;
property CallbackCurrentLoop: Integer read fCallbackCrntLoop write fCallbackCrntLoop;
property CallbackKey: String read fCallBackKey write fCallBackKey;
property ErrorText: String read fErrTxt write fErrTxt;
property TaskDlg: TTaskDialog read fTaskDLG write fTaskDLG;
end;
Procedure LogBrokerErrors(const ErrTxt: String);
Const
UseMultThread: Boolean = false;
MAX_CALLS = 95;
var
frmDebugReport: TfrmDebugReport;
implementation
{$R *.dfm}
Procedure LogBrokerErrors(const ErrTxt: String);
var
frmDebug: TfrmDebugReport;
ReturnCursor: Integer;
begin
frmDebug := TfrmDebugReport.Create(nil);
ReturnCursor := Screen.cursor;
Screen.cursor := crHourGlass;
try
//set unique key
frmDebug.CallbackKey := IntToStr(User.DUZ) + '^' + FormatDateTime('mm/dd/yyyy hh:mm:ss', Now());
//save the Error text
frmDebug.ErrorText := ErrTxt;
//set the loop
frmDebug.CallbackCurrentLoop := frmDebug.TopRPCNumber;
//create the task dialog
frmDebug.TaskDLG := TTaskDialog.Create(nil);
with frmDebug.TaskDLG do
begin
try
Caption := 'CPRS Error Log';
Title := 'Capturing debug information';
Text := 'Please wait this may take a minute.';
CommonButtons := [tcbCancel];
MainIcon := tdiInformation;
ProgressBar.Position := 70;
ProgressBar.MarqueeSpeed := 1;
Flags := [tfShowMarqueeProgressBar, tfCallbackTimer, tfAllowDialogCancellation ];
OnTimer := frmDebug.SendDataCallback;
Execute;
finally
Free;
end
end;
Finally
Screen.cursor := ReturnCursor;
FreeAndNil(frmDebug);
end;
end;
procedure TfrmDebugReport.SendDataCallback(Sender: TObject; TickCount: Cardinal;
var Reset: Boolean);
var
RPCData: TStringList;
begin
RPCData := TStringList.Create;
//Pause the timer
fTaskDLG.OnTimer := nil;
try
// 1st call
if fCallbackCrntLoop = TopRPCNumber then
begin
// ensure the broker exist
EnsureDebugBroker;
//Send the error message
RPCData.Add(fErrTxt);
SendTheDesc(RPCData, fCallBackKey);
RPCData.Clear;
end;
//Need to sync this call
LoadRPCData(RPCData, fCallbackCrntLoop);
//Send in the rpc list
SendTheRpc(RPCData, fCallBackKey);
if fCallbackCrntLoop = MAX_CALLS then
begin
fTaskDLG.OnTimer := nil;
fTaskDLG.ProgressBar.Position := 100;
fTaskDLG.ModalResult := mrOk;
SendMessage(fTaskDLG.Handle, WM_CLOSE, 0 , 0);
end else
dec(fCallbackCrntLoop);
finally
// reset the timer
fTaskDLG.OnTimer := SendDataCallback;
FreeandNil(RPCData);
end;
end;
procedure TfrmDebugReport.ActionMemoChange(Sender: TObject);
begin
btnSend.Enabled := Trim(ActionMemo.Text) > '';
end;
procedure TfrmDebugReport.btnCancelClick(Sender: TObject);
begin
Self.Close;
end;
procedure TfrmDebugReport.btnSendClick(Sender: TObject);
var
DebugThread: tDebugThread;
ConnectionParam: string;
ReturnCursor: Integer;
begin
ReturnCursor := Screen.Cursor;
Screen.Cursor := crHourGlass;
try
if UseMultThread then
begin
// threaded
if Trim(ActionMemo.Text) > '' then
begin
ConnectionParam := RPCBrokerV.Server + '^' +
IntToStr(RPCBrokerV.ListenerPort) + '^' +
GetAppHandle(RPCBrokerV) + '^' +
RPCBrokerV.User.Division;
DebugThread := tDebugThread.Create(ActionMemo.Lines, ConnectionParam, RPCBrokerV.CurrentContext);
{$WARN SYMBOL_DEPRECATED OFF} // researched
DebugThread.Resume;
{$WARN SYMBOL_DEPRECATED ON} // researched
Self.Close;
end;
end
else
begin
// Non threaded
RunNonThread;
end;
finally
Screen.Cursor := ReturnCursor;
end;
end;
procedure TfrmDebugReport.FormShow(Sender: TObject);
begin
ActionMemo.Text := '';
btnSend.Enabled := False;
ActionMemo.SetFocus;
PnlProg.Visible := false;
end;
function TfrmDebugReport.GetTopRPCNumber: Integer;
begin
Result := (RetainedRPCCount - 1);
end;
constructor tDebugThread.Create(ActionDescription: TStrings; RPCParams, CurContext: string);
function Piece(const S: string; Delim: char; PieceNum: Integer): string;
{ returns the Nth piece (PieceNum) of a string delimited by Delim }
var
i: Integer;
Strt, Next: PChar;
begin
i := 1;
Strt := PChar(S);
Next := StrScan(Strt, Delim);
while (i < PieceNum) and (Next <> nil) do
begin
Inc(i);
Strt := Next + 1;
Next := StrScan(Strt, Delim);
end;
if Next = nil then Next := StrEnd(Strt);
if i < PieceNum then Result := '' else SetString(Result, Strt, Next - Strt);
end;
begin
inherited Create(True);
fThreadDone := false;
fDescription := TStringList.Create;
fDescription.Assign(ActionDescription);
FreeOnTerminate := True;
SetLength(RPCArray, 0);
try
ThreadBroker := TRPCBroker.Create(nil);
ThreadBroker.Server := Piece(RPCParams, '^', 1);
ThreadBroker.ListenerPort := StrToIntDef(Piece(RPCParams, '^', 2), 9200);
ThreadBroker.LogIn.LogInHandle := Piece(RPCParams, '^', 3);
ThreadBroker.LogIn.Division := Piece(RPCParams, '^', 4);
ThreadBroker.LogIn.Mode := lmAppHandle;
ThreadBroker.KernelLogIn := False;
ThreadBroker.Connected := True;
ThreadBroker.CreateContext(CurContext);
except
FreeAndNil(ThreadBroker);
end;
end;
destructor tDebugThread.Destroy;
var
I: Integer;
begin
fDescription.Free;
fThreadDone := true;
for I := High(RPCArray) downto Low(RPCArray) do
if Assigned(RPCArray[i].RPCData) then
FreeAndNil(RPCArray[i].RPCData);
SetLength(RPCArray, 0);
ThreadBroker.Connected := false;
FreeAndNil(ThreadBroker);
inherited;
end;
procedure tDebugThread.Execute;
var
I: Integer;
UniqueKey: string;
function FilteredString(const x: string; ATabWidth: Integer = 8): string;
var
i, j: Integer;
c: char;
begin
Result := '';
for i := 1 to Length(x) do begin
c := x[i];
if c = #9 then begin
for j := 1 to (ATabWidth - (Length(Result) mod ATabWidth)) do
Result := Result + ' ';
end else if CharInSet(c, [#32..#127]) then begin
Result := Result + c;
end else if CharInSet(c, [#10, #13, #160]) then begin
Result := Result + ' ';
end else if CharInSet(c, [#128..#159]) then begin
Result := Result + '?';
end else if CharInSet(c, [#161..#255]) then begin
Result := Result + x[i];
end;
end;
if Copy(Result, Length(Result), 1) = ' ' then Result := TrimRight(Result) + ' ';
end;
procedure SendTheRpc(RPCList: TStringList; UniqueKey: string);
var
LnCnt: Integer;
begin
LockBroker;
try
with ThreadBroker do
begin
ClearParameters := True;
RemoteProcedure := 'ORDEBUG SAVERPCS';
//send the unique key
Param[0].PType := literal;
Param[0].Value := UniqueKey;
//send the RPC Data
Param[1].PType := list;
for LnCnt := 0 to RPCList.Count - 1 do
ThreadBroker.Param[1].Mult[IntToStr(LnCnt)] := FilteredString(RPCList.Strings[LnCnt]);
ThreadBroker.Call;
end;
finally
UnlockBroker;
end;
end;
procedure SendTheDesc(Description: TStringList; UniqueKey: string);
var
LnCnt: Integer;
begin
LockBroker;
try
with ThreadBroker do
begin
ClearParameters := True;
RemoteProcedure := 'ORDEBUG SAVEDESC';
//send the unique key
Param[0].PType := literal;
Param[0].Value := UniqueKey;
//send the RPC Data
Param[1].PType := list;
for LnCnt := 0 to Description.Count - 1 do
ThreadBroker.Param[1].Mult[IntToStr(LnCnt)] := FilteredString(Description.Strings[LnCnt]);
ThreadBroker.Call;
//CallBroker;
end;
finally
UnlockBroker;
end;
end;
begin
if Terminated then Exit;
//set unique key
UniqueKey := IntToStr(User.DUZ) + '^' + FormatDateTime('mm/dd/yyyy hh:mm:ss', Now());
//save the users text
SendTheDesc(fDescription, UniqueKey);
//Collect all the RPC's up to that point
for I := (RetainedRPCCount - 1) downto 0 do
begin
SetLength(RPCArray, Length(RPCArray) + 1);
RPCArray[High(RPCArray)].RPCData := TStringList.Create;
//Need to sync this call
LoadRPCData(RPCArray[High(RPCArray)].RPCData, I);
end;
//Send in the rpc list
for I := High(RPCArray) downto Low(RPCArray) do
begin
SendTheRpc(RPCArray[i].RPCData, UniqueKey);
end;
Sleep(Random(100));
end;
procedure TfrmDebugReport.RunNonThread();
var
I: Integer;
UniqueKey: string;
ActionDesc: TStringList;
begin
RPCS.Clear;
DebugReportBroker := TRPCBroker.Create(nil);
try
//Setup the progress bar
DebugProgBar.Max := (RetainedRPCCount + 3);
DebugProgBar.Position := 0;
PnlProg.Visible := True;
Application.ProcessMessages; //Allow the screen to draw
EnsureDebugBroker;
DebugProgBar.Position := DebugProgBar.Position + 1;
//set unique key
UniqueKey := IntToStr(User.DUZ) + '^' + FormatDateTime('mm/dd/yyyy hh:mm:ss', Now());
//save the users text
ActionDesc := TStringList.Create;
try
ActionDesc.assign(ActionMemo.Lines);
SendTheDesc(ActionDesc, UniqueKey);
DebugProgBar.Position := DebugProgBar.Position + 1;
finally
ActionDesc.Free;
end;
//Collect all the RPC's up to that point
for I := TopRPCNumber downto 0 do
begin
SetLength(fRPCS, Length(fRPCS) + 1);
fRPCS[High(fRPCS)].RPCData := TStringList.Create;
//Need to sync this call
LoadRPCData(fRPCS[High(fRPCS)].RPCData, I);
end;
DebugProgBar.Position := DebugProgBar.Position + 1;
//Send in the rpc list
for I := High(fRPCS) downto Low(fRPCS) do
begin
SendTheRpc(fRPCS[i].RPCData, UniqueKey);
DebugProgBar.Position := DebugProgBar.Position + 1;
end;
Sleep(1000); //ONE SEC
Finally
RPCS.Clear;
DebugReportBroker.Connected := false;
FreeAndNil(fDebugReportBroker);
Self.Close;
end;
end;
procedure TfrmDebugReport.EnsureDebugBroker;
begin
if not Assigned(DebugReportBroker) then
DebugReportBroker := TRPCBroker.Create(nil);
//Setup the broker
DebugReportBroker.Server := RPCBrokerV.Server;
DebugReportBroker.ListenerPort := RPCBrokerV.ListenerPort;
DebugReportBroker.LogIn.LogInHandle := GetAppHandle(RPCBrokerV);
DebugReportBroker.LogIn.Division := RPCBrokerV.User.Division;
DebugReportBroker.LogIn.Mode := lmAppHandle;
DebugReportBroker.KernelLogIn := False;
DebugReportBroker.Connected := True;
if DebugReportBroker.CreateContext(RPCBrokerV.CurrentContext) = false then
ShowMessage('Error switching broker context');
end;
function TfrmDebugReport.FilteredString(const x: string; ATabWidth: Integer = 8): string;
var
i, j: Integer;
c: char;
begin
Result := '';
for i := 1 to Length(x) do begin
c := x[i];
if c = #9 then begin
for j := 1 to (ATabWidth - (Length(Result) mod ATabWidth)) do
Result := Result + ' ';
end else if CharInSet(c, [#32..#127]) then begin
Result := Result + c;
end else if CharInSet(c, [#10, #13, #160]) then begin
Result := Result + ' ';
end else if CharInSet(c, [#128..#159]) then begin
Result := Result + '?';
end else if CharInSet(c, [#161..#255]) then begin
Result := Result + x[i];
end;
end;
if Copy(Result, Length(Result), 1) = ' ' then Result := TrimRight(Result) + ' ';
end;
procedure TfrmDebugReport.SendTheRpc(RPCList: TStringList; UniqueKey: string);
var
LnCnt: Integer;
begin
LockBroker;
try
with DebugReportBroker do
begin
ClearParameters := True;
RemoteProcedure := 'ORDEBUG SAVERPCS';
//send the unique key
Param[0].PType := literal;
Param[0].Value := UniqueKey;
//send the RPC Data
Param[1].PType := list;
for LnCnt := 0 to RPCList.Count - 1 do
Param[1].Mult[IntToStr(LnCnt)] := FilteredString(RPCList.Strings[LnCnt]);
Call;
end;
finally
UnlockBroker;
end;
end;
procedure TfrmDebugReport.SendTheDesc(Description: TStringList; UniqueKey: string);
var
LnCnt: Integer;
begin
LockBroker;
try
with DebugReportBroker do
begin
ClearParameters := True;
RemoteProcedure := 'ORDEBUG SAVEDESC';
//send the unique key
Param[0].PType := literal;
Param[0].Value := UniqueKey;
//send the RPC Data
Param[1].PType := list;
for LnCnt := 0 to Description.Count - 1 do
Param[1].Mult[IntToStr(LnCnt)] := FilteredString(Description.Strings[LnCnt]);
Call;
end;
finally
UnlockBroker;
end;
end;
destructor TfrmDebugReport.Destroy;
begin
if assigned(DebugReportBroker) then
begin
DebugReportBroker.Connected := false;
FreeAndNil(fDebugReportBroker);
end;
Inherited;
end;
Procedure tRPCArrayIdentHelper.Clear;
Var
I: Integer;
begin
for I := High(self) downto Low(self) do
if Assigned(self[i].RPCData) then
FreeAndNil(self[i].RPCData);
SetLength(self, 0);
end;
{$WARN SYMBOL_PLATFORM ON}
end.
|
{********************************************}
{ TSeriesBandTool and Editor Dialog }
{ Copyright (c) 2003-2004 by David Berneda }
{ and Martin Kaul (mkaul@leuze.de) }
{********************************************}
unit TeeSeriesBandTool;
{$I TeeDefs.inc}
interface
uses {$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls,
{$ENDIF}
{$IFDEF LINUX}
Types,
{$ENDIF}
TeeToolSeriesEdit, TeCanvas, TeePenDlg, TeeTools, TeEngine,
TeeProcs, Chart, TeeConst, TeeProCo;
type
// Series-Band tool, use it to display a band between two (line) series
// created 2003-12-14 by mkaul@leuze.de
TSeriesBandTool=class(TTeeCustomToolSeries)
private
FDrawBehind : Boolean;
FGradient : TTeeGradient;
FSeries2 : TChartSeries;
FTransparency : TTeeTransparency;
ISerie1Drawed : Boolean;
ISerie2Drawed : Boolean;
procedure AfterSeriesDraw(Sender: TObject);
procedure BeforeSeriesDraw(Sender: TObject);
procedure SetDrawBehind(const Value: Boolean);
procedure SetGradient(const Value: TTeeGradient);
procedure SetTransparency(const Value: TTeeTransparency);
protected
procedure ChartEvent(AEvent: TChartToolEvent); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure SetSeries(const Value: TChartSeries); override;
procedure SetSeries2(const Value: TChartSeries); virtual;
procedure DrawBandTool; virtual;
class Function GetEditorClass:String; override;
public
Constructor Create(AOwner:TComponent); override;
Destructor Destroy; override;
class Function Description:String; override;
published
property Active;
property Brush;
property DrawBehindSeries:Boolean read FDrawBehind
write SetDrawBehind default True;
property Gradient:TTeeGradient read FGradient write SetGradient;
property Pen;
property Series;
property Series2:TChartSeries read FSeries2 write SetSeries2;
property Transparency:TTeeTransparency read FTransparency
write SetTransparency default 0;
end;
TSeriesBandToolEdit = class(TSeriesToolEditor)
Button1: TButton;
CBDrawBehindSeries: TCheckBox;
BPen: TButtonPen;
Label2: TLabel;
CBSeries2: TComboFlat;
Button2: TButton;
Label4: TLabel;
ETransp: TEdit;
UDTransp: TUpDown;
procedure Button1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure CBDrawBehindSeriesClick(Sender: TObject);
procedure CBSeries2Change(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure ETranspChange(Sender: TObject);
private
{ Private declarations }
SeriesBand : TSeriesBandTool;
protected
public
{ Public declarations }
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
Uses Math, TeeBrushDlg, TeeEdiGrad;
procedure TSeriesBandToolEdit.Button1Click(Sender: TObject);
begin
EditChartBrush(Self,SeriesBand.Brush);
end;
procedure TSeriesBandToolEdit.FormShow(Sender: TObject);
begin
inherited;
SeriesBand:=TSeriesBandTool(Tag);
if Assigned(SeriesBand) then
With SeriesBand do
begin
FillSeriesCombo(CBSeries2,Series2,ParentChart);
BPen.LinkPen(Pen);
CBDrawBehindSeries.Checked:=DrawBehindSeries;
UDTransp.Position:=Transparency;
end;
end;
procedure TSeriesBandToolEdit.CBDrawBehindSeriesClick(Sender: TObject);
begin
SeriesBand.DrawBehindSeries:=CBDrawBehindSeries.Checked;
end;
procedure TSeriesBandToolEdit.CBSeries2Change(Sender: TObject);
begin
With CBSeries2 do SeriesBand.Series2:=TChartSeries(Items.Objects[CBSeries2.ItemIndex]);
end;
// created 2003-12-14 by mkaul@leuze.de
{ TSeriesBandTool }
Constructor TSeriesBandTool.Create(AOwner: TComponent);
begin
inherited;
FDrawBehind:=True;
Brush.Color:=clWhite;
Pen.Visible:=False;
FGradient:=TTeeGradient.Create(CanvasChanged);
end;
procedure TSeriesBandTool.AfterSeriesDraw(Sender: TObject);
begin
if not FDrawBehind then
begin
if Assigned(Series) and (Sender=Series) then ISerie1Drawed:=True;
if Assigned(Series2) and (Sender=Series2) then ISerie2Drawed:=True;
if ISerie1Drawed and ISerie2Drawed then DrawBandTool;
end;
end;
procedure TSeriesBandTool.BeforeSeriesDraw(Sender: TObject);
begin
if FDrawBehind then
begin
if Assigned(Series) and (Sender=Series) then ISerie1Drawed:=True;
if Assigned(Series2) and (Sender=Series2) then ISerie2Drawed:=True;
if ISerie1Drawed or ISerie2Drawed then
if not (ISerie1Drawed and ISerie2Drawed) then DrawBandTool;
end;
end;
procedure TSeriesBandTool.SetDrawBehind(const Value: Boolean);
begin
SetBooleanProperty(FDrawBehind,Value);
end;
procedure TSeriesBandTool.ChartEvent(AEvent: TChartToolEvent);
begin
inherited;
if AEvent=cteBeforeDrawSeries then
begin
ISerie1Drawed:=False;
ISerie2Drawed:=False;
end;
end;
class Function TSeriesBandTool.Description:String;
begin
result:=TeeMsg_SeriesBandTool;
end;
procedure TSeriesBandTool.Notification(AComponent: TComponent;
Operation: TOperation);
begin
if Operation=opRemove then
begin
if Assigned(Series) and (AComponent=Series) then
begin
Series.AfterDrawValues:=nil;
Series.BeforeDrawValues:=nil;
end;
if Assigned(Series2) and (AComponent=Series2) then
begin
Series2.AfterDrawValues:=nil;
Series2.BeforeDrawValues:=nil;
end;
end;
inherited;
end;
procedure TSeriesBandTool.SetSeries(const Value: TChartSeries);
begin
inherited;
if Assigned(Series) then
begin
Series.AfterDrawValues:=AfterSeriesDraw;
Series.BeforeDrawValues:=BeforeSeriesDraw;
end;
Repaint;
end;
procedure TSeriesBandTool.SetSeries2(const Value: TChartSeries);
begin
if FSeries2<>Value then
begin
{$IFDEF D5}
if Assigned(FSeries2) then FSeries2.RemoveFreeNotification(Self);
{$ENDIF}
FSeries2:=Value;
if Assigned(FSeries2) then FSeries2.FreeNotification(Self);
if Assigned(Series2) then
begin
Series2.AfterDrawValues:=AfterSeriesDraw;
Series2.BeforeDrawValues:=BeforeSeriesDraw;
end;
Repaint;
end;
end;
type
TSeriesAccess=class(TChartSeries);
procedure TSeriesBandTool.DrawBandTool;
var t : Integer;
i : Integer;
l1 : Integer;
l2 : Integer;
tmpPoints : TPointArray;
tmpZ : Integer;
tmpR : TRect;
tmpBlend : TTeeBlend;
begin
if Active and Assigned(ParentChart) and
Assigned(Series) and Assigned(Series2) then
begin
TSeriesAccess(Series).CalcFirstLastVisibleIndex;
TSeriesAccess(Series2).CalcFirstLastVisibleIndex;
if (Series.FirstValueIndex<>-1) and (Series2.FirstValueIndex<>-1) then
begin
l1:=Series.LastValueIndex-Series.FirstValueIndex+1;
l2:=Series2.LastValueIndex-Series2.FirstValueIndex+1;
SetLength(tmpPoints,l1+l2);
if Assigned(tmpPoints) then
try
i:=0;
for t:=Series.FirstValueIndex to Series.LastValueIndex do
begin
tmpPoints[i].X:=Series.CalcXPos(t);
tmpPoints[i].Y:=Series.CalcYPos(t);
Inc(i);
end;
for t:=Series2.LastValueIndex downto Series2.FirstValueIndex do
begin
tmpPoints[i].X:=Series2.CalcXPos(t);
tmpPoints[i].Y:=Series2.CalcYPos(t);
Inc(i);
end;
tmpZ:=Math.Max(Series.StartZ,Series2.StartZ);
if Transparency>0 then
begin
tmpR:=PolygonBounds(tmpPoints);
tmpBlend:=ParentChart.Canvas.BeginBlending(
ParentChart.Canvas.RectFromRectZ(tmpR,tmpZ),Transparency)
end
else
tmpBlend:=nil;
if Gradient.Visible and ParentChart.CanClip then
begin
Gradient.Draw(ParentChart.Canvas,tmpPoints,tmpZ,ParentChart.View3D);
ParentChart.Canvas.Brush.Style:=bsClear;
end
else
with ParentChart.Canvas do
begin
ClipRectangle( RectFromRectZ(ParentChart.ChartRect, tmpZ));
AssignBrushColor(Self.Brush,Self.Brush.Color,clBlack);
AssignVisiblePen(Self.Pen);
if ParentChart.View3D then PolygonWithZ(tmpPoints,tmpZ)
else Polygon(tmpPoints);
UnClipRectangle;
end;
if Assigned(tmpBlend) then
ParentChart.Canvas.EndBlending(tmpBlend);
finally
tmpPoints:=nil;
end;
end;
end;
end;
class function TSeriesBandTool.GetEditorClass: String;
begin
result:='TSeriesBandToolEdit';
end;
procedure TSeriesBandTool.SetGradient(const Value: TTeeGradient);
begin
FGradient.Assign(Value);
end;
destructor TSeriesBandTool.Destroy;
begin
FGradient.Free;
inherited;
end;
procedure TSeriesBandToolEdit.Button2Click(Sender: TObject);
begin
EditTeeGradient(Self,SeriesBand.Gradient)
end;
procedure TSeriesBandTool.SetTransparency(const Value: TTeeTransparency);
begin
if FTransparency<>Value then
begin
FTransparency:=Value;
Repaint;
end;
end;
procedure TSeriesBandToolEdit.ETranspChange(Sender: TObject);
begin
if Showing then
SeriesBand.Transparency:=UDTransp.Position;
end;
initialization
RegisterTeeTools([TSeriesBandTool]);
RegisterClass(TSeriesBandToolEdit);
finalization
UnRegisterTeeTools([TSeriesBandTool]);
end.
|
unit fRptBox;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ORFn, ComCtrls, ExtCtrls, fFrame, fBase508Form,
VA508AccessibilityManager, uReports, Vcl.Menus, U_CPTEditMonitor, fDeviceSelect,
WinApi.ShellApi, WinApi.RichEdit;
type
TfrmReportBox = class(TfrmBase508Form)
lblFontTest: TLabel;
memReport: TRichEdit;
pnlButton: TPanel;
cmdPrint: TButton;
dlgPrintReport: TPrintDialog;
cmdClose: TButton;
pmnu: TPopupMenu;
mnuCopy: TMenuItem;
CPRptBox: TCopyEditMonitor;
procedure memReportClick(Sender: TObject);
procedure cmdPrintClick(Sender: TObject);
procedure cmdCloseClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormResize(Sender: TObject);
procedure mnuCopyClick(Sender: TObject);
procedure CPRptBoxCopyToMonitor(Sender: TObject; var AllowMonitor: Boolean);
private
fPrintHeader: Boolean;
fVistAPrint: boolean;
property PrintHeader: Boolean read fPrintHeader write fPrintHeader;
property VistAPrint: boolean read fVistaPrint write fVistAPrint;
protected
procedure WndProc(var Message: TMessage); override;
public
VistADevice: string;
end;
procedure ReportBox(ReportText: TStrings; ReportTitle: string; AllowPrint: boolean; includeHeader: boolean = true);
function ModelessReportBox(ReportText: TStrings; ReportTitle: string; AllowPrint: boolean; includeHeader: boolean = true): TfrmReportBox;
function VistAPrintReportBox(ReportText: TStrings; ReportTitle: string): string;
procedure PrintStrings(Form: TForm; StringText: TStrings; const Title, Trailer: string; includeHeader: boolean = true);
implementation
uses
uCore, rCore, rReports, Printers, rMisc;
{$R *.DFM}
function CreateReportBox(ReportText: TStrings; ReportTitle: string; AllowPrint: boolean; includeHeader: boolean = true;
VistAPrintOnly: boolean = true): TfrmReportBox;
var
i, AWidth, MinWidth, MaxWidth, AHeight: Integer;
Rect: TRect;
BtnArray: array of TButton;
BtnRight: array of integer;
BtnLeft: array of integer;
//cmdCloseRightMargin: integer;
//cmdPrintRightMargin: integer;
j, k: integer;
begin
Result := TfrmReportBox.Create(Application);
try
with Result do
begin
{ Enable URL detection in the memReport TRichEdit }
i := SendMessage(memReport.Handle, EM_GETEVENTMASK, 0, 0);
SendMessage(memReport.Handle, EM_SETEVENTMASK, 0, i or ENM_LINK);
SendMessage(memReport.Handle, EM_AUTOURLDETECT, Integer(True), 0);
k := 0;
MinWidth := 0;
with pnlButton do for j := 0 to ControlCount - 1 do
if Controls[j] is TButton then
begin
SetLength(BtnArray, k+1);
SetLength(BtnRight, k+1);
BtnArray[k] := TButton(Controls[j]);
BtnRight[k] := ResizeWidth(Font, MainFont, BtnArray[k].Width - BtnArray[k].Width - BtnArray[k].Left);
k := k + 1;
end;
//cmdCloseRightMargin := ResizeWidth(Font, MainFont, pnlButton.Width - cmdClose.Width - cmdClose.Left);
//cmdPrintRightMargin := ResizeWidth(Font, MainFont, pnlButton.Width - cmdPrint.Width - cmdPrint.Left);
MaxWidth := 350;
for i := 0 to ReportText.Count - 1 do
begin
AWidth := lblFontTest.Canvas.TextWidth(ReportText[i]);
if AWidth > MaxWidth then MaxWidth := AWidth;
end;
cmdPrint.Visible := AllowPrint;
printHeader := includeHeader;
vistaPrint := VistaPrintOnly;
vistaDevice := '';
MaxWidth := MaxWidth + GetSystemMetrics(SM_CXVSCROLL);
AHeight := (ReportText.Count * (lblFontTest.Height + 2)) + pnlbutton.Height;
AHeight := HigherOf(AHeight, 250);
if AHeight > (Screen.Height - 80) then AHeight := Screen.Height - 80;
if MaxWidth > Screen.Width then MaxWidth := Screen.Width;
ClientWidth := MaxWidth;
ClientHeight := AHeight;
ResizeAnchoredFormToFont(Result);
memReport.Align := alClient; //CQ6661
//CQ6889 - force Print & Close buttons to bottom right of form regardless of selected font size
cmdClose.Left := (pnlButton.Left+pnlButton.Width)-cmdClose.Width;
cmdPrint.Left := (cmdClose.Left-cmdPrint.Width)-1;
//end CQ6889
SetLength(BtnLeft, k);
for j := 0 to k - 1 do
begin
BtnLeft[j] := pnlButton.Width - BtnArray[j].Width - BtnRight[j];
MinWidth := MinWidth + BtnArray[j].Width;
end;
Width := width + (GetSystemMetrics(SM_CXVSCROLL) *2);
Constraints.MinWidth := MinWidth + (MinWidth div 2) + (GetSystemMetrics(SM_CXVSCROLL) *2);
if (mainFontSize = 8) then Constraints.MinHeight := 285
else if (mainFontSize = 10) then Constraints.MinHeight := 325
else if (mainFontSize = 12) then Constraints.MinHeight := 390
else if mainFontSize = 14 then Constraints.MinHeight := 460
else Constraints.MinHeight := 575;
QuickCopy(ReportText, memReport);
for i := 1 to Length(ReportTitle) do if ReportTitle[i] = #9 then ReportTitle[i] := ' ';
Caption := ReportTitle;
memReport.SelStart := 0;
Rect := BoundsRect;
ForceInsideWorkArea(Rect);
BoundsRect := Rect;
SetLength(BtnArray, 0);
SetLength(BtnRight, 0);
SetLength(BtnLeft, 0);
end;
except
KillObj(@Result);
raise;
end;
end;
procedure ReportBox(ReportText: TStrings; ReportTitle: string; AllowPrint: boolean; includeHeader: boolean = true);
var
frmReportBox: TfrmReportBox;
begin
Screen.Cursor := crHourglass; //wat cq 18425 added hourglass and disabled mnuFileOpen
fFrame.frmFrame.mnuFileOpen.Enabled := False;
frmReportBox := CreateReportBox(ReportText, ReportTitle, AllowPrint, includeHeader, false);
try
frmReportBox.ShowModal;
finally
frmReportBox.Release;
Screen.Cursor := crDefault;
fFrame.frmFrame.mnuFileOpen.Enabled := True;
end;
end;
function ModelessReportBox(ReportText: TStrings; ReportTitle: string; AllowPrint: boolean; includeHeader: boolean = true): TfrmReportBox;
begin
Result := CreateReportBox(ReportText, ReportTitle, AllowPrint, includeHeader, false);
Result.FormStyle := fsStayOnTop;
Result.Show;
end;
function VistAPrintReportBox(ReportText: TStrings; ReportTitle: string): string;
var
frmReportBox: TfrmReportBox;
begin
Screen.Cursor := crHourglass; //wat cq 18425 added hourglass and disabled mnuFileOpen
fFrame.frmFrame.mnuFileOpen.Enabled := False;
frmReportBox := CreateReportBox(ReportText, ReportTitle, true, false, true);
try
frmReportBox.ShowModal;
Result := frmReportBox.VistADevice;
finally
frmReportBox.Release;
Screen.Cursor := crDefault;
fFrame.frmFrame.mnuFileOpen.Enabled := True;
end;
end;
procedure PrintStrings(Form: TForm; StringText: TStrings; const Title, Trailer: string; includeHeader: boolean = true);
var
AHeader: TStringList;
memPrintReport: TRichEdit;
MaxLines, LastLine, ThisPage, i: integer;
ErrMsg: string;
// RemoteSiteID: string; //for Remote site printing
// RemoteQuery: string; //for Remote site printing
dlgPrintReport: TPrintDialog;
BM: TBitmap;
const
PAGE_BREAK = '**PAGE BREAK**';
begin
// RemoteSiteID := '';
// RemoteQuery := '';
BM := TBitmap.Create;
try
dlgPrintReport := TPrintDialog.Create(Form);
try
frmFrame.CCOWBusy := True;
if dlgPrintReport.Execute then
begin
AHeader := TStringList.Create;
if includeHeader then CreatePatientHeader(AHeader, Title);
memPrintReport := CreateReportTextComponent(Form);
try
MaxLines := 60 - AHeader.Count;
LastLine := 0;
ThisPage := 0;
BM.Canvas.Font := memPrintReport.Font;
with memPrintReport do
begin
repeat
with Lines do
begin
for i := 0 to MaxLines do begin
if BM.Canvas.TextWidth(StringText[LastLine + i]) > Width then begin
MaxLines := Maxlines - (BM.Canvas.TextWidth(StringText[LastLine + i]) div Width);
end;
if i >= MaxLines then begin
break;
end;
if i < StringText.Count then
// Add(IntToStr(i) + ') ' + StringText[LastLine + i])
Add(StringText[LastLine + i])
else
Break;
end;
LastLine := LastLine + i;
Add(' ');
Add(' ');
Add(StringOfChar('-', 74));
if LastLine >= StringText.Count - 1 then
Add(Trailer)
else
begin
ThisPage := ThisPage + 1;
Add('Page ' + IntToStr(ThisPage));
Add(PAGE_BREAK);
MaxLines := 60 - AHeader.Count;
end;
end;
until LastLine >= StringText.Count - 1;
PrintWindowsReport(memPrintReport, PAGE_BREAK, Title, ErrMsg, includeHeader);
end;
finally
memPrintReport.Free;
AHeader.Free;
end;
end;
finally
frmFrame.CCOWBusy := False;
dlgPrintReport.Free;
end;
finally
BM.free;
end;
end;
{ Enable URL detection in the memReport TRichEdit }
procedure TfrmReportBox.WndProc(var Message: TMessage);
var
p: TENLink;
aURL: string;
begin
if (Message.Msg = WM_NOTIFY) then
begin
if (PNMHDR(Message.LParam).code = EN_LINK) then
begin
p := TENLink(Pointer(TWMNotify(Message).NMHdr)^);
if (p.Msg = WM_LBUTTONDOWN) then
begin
SendMessage(memReport.Handle, EM_EXSETSEL, 0, LongInt(@(p.chrg)));
aURL := memReport.SelText;
ShellExecute(Handle, 'open', PChar(aURL), NIL, NIL, SW_SHOWNORMAL);
end
end
end;
inherited;
end;
procedure TfrmReportBox.memReportClick(Sender: TObject);
begin
//Close;
end;
procedure TfrmReportBox.mnuCopyClick(Sender: TObject);
begin
inherited;
memReport.CopyToClipboard;
end;
procedure TfrmReportBox.cmdPrintClick(Sender: TObject);
begin
if VistAPrint then
begin
VistaDevice := SelectDevice(Self, Encounter.Location, FALSE, 'Print Device Selection');
end
else
begin
PrintStrings(Self, memReport.Lines, Self.Caption, 'End of report', PrintHeader);
memReport.Invalidate;
end;
end;
procedure TfrmReportBox.CPRptBoxCopyToMonitor(Sender: TObject; var AllowMonitor: Boolean);
begin
inherited;
CPRptBox.RelatedPackage := self.Caption+';'+ Patient.Name;
CPRptBox.ItemIEN := -1;
AllowMonitor := true;
end;
procedure TfrmReportBox.cmdCloseClick(Sender: TObject);
begin
Close;
end;
procedure TfrmReportBox.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if(not (fsModal in FormState)) then
Action := caFree;
end;
procedure TfrmReportBox.FormResize(Sender: TObject);
begin
inherited;
self.memReport.Refresh;
end;
end.
|
unit vgr_GUIFunctions;
{$I vtk.inc}
interface
uses
SysUtils, Windows, Graphics, Classes, Forms, Controls,
comctrls, vgr_Functions;
const
{Specifies the set of charactes which will be used as "wrap" characters.}
WordWrapChars: set of char = [' '];
type
TvgrTextHorzAlign = (vgrthaLeft, vgrthaCenter, vgrthaRight);
{Describes the image align within a rectangle.
Items:
vgridmCenter - The image should be centered in the rectangle.
vgridmStretch - The image should be changed so that it exactly fits the rectangle.
vgridmStretchProp - The image should be changed, without distortion, so that it fits the rectangle.}
TvgrImageDrawMode = (vgridmCenter, vgridmStretch, vgridmStretchProp);
RGNDATAHEADER = packed record
dwSize: Integer;
iType: Integer;
nCount: Integer;
nRgnSize: Integer;
rcBound: TRect;
end;
pRGNDATAHEADER = ^RGNDATAHEADER;
/////////////////////////////////////////////////
//
// TvgrFastRegion
//
/////////////////////////////////////////////////
(*$NODEFINE TvgrFastRegion*)
(*$HPPEMIT 'class DELPHICLASS TvgrFastRegion;'*)
(*$HPPEMIT 'class PASCALIMPLEMENTATION TvgrFastRegion : public System::TObject'*)
(*$HPPEMIT '{'*)
(*$HPPEMIT ' typedef System::TObject inherited;'*)
(*$HPPEMIT ''*)
(*$HPPEMIT 'private:'*)
(*$HPPEMIT ' RGNDATAHEADER *FRegionData;'*)
(*$HPPEMIT ' TRect *FRects;'*)
(*$HPPEMIT ' int FCapacity;'*)
(*$HPPEMIT ''*)
(*$HPPEMIT 'protected:'*)
(*$HPPEMIT ' void __fastcall Grow(void);'*)
(*$HPPEMIT ''*)
(*$HPPEMIT 'public:'*)
(*$HPPEMIT ' __fastcall TvgrFastRegion(void);'*)
(*$HPPEMIT ' __fastcall virtual ~TvgrFastRegion(void);'*)
(*$HPPEMIT ' void __fastcall Clear(void);'*)
(*$HPPEMIT ' void __fastcall AddRect(const TRect &ARect);'*)
(*$HPPEMIT ' HRGN __fastcall BuildRegion(void);'*)
(*$HPPEMIT '};'*)
{ This class describes region consisting from a collection of rectangles.
The given class allows much faster to create region consisting from a
collection of regions than standard API function CombineRgn. }
TvgrFastRegion = class(TObject)
private
FRegionData: pRGNDATAHEADER;
FRects: PRectArray;
FCapacity: Integer;
protected
procedure Grow;
public
{Creates a TvgrFastRegion instance.}
constructor Create;
{Destroys an instance of TvgrFastRegion.}
destructor Destroy; override;
{ Deletes all rects from the region. }
procedure Clear;
{ Add rect to region.
Parameters:
ARect - TRect object}
procedure AddRect(const ARect: TRect);
{ Build API region.
Return value:
The return value is the handle to the region.}
function BuildRegion: HRGN;
end;
/////////////////////////////////////////////////
//
// TvgrWrapLine
//
/////////////////////////////////////////////////
{Represents the info about separate line in text.
This structure is used by WrapMemo function to return information
about strings in text.
Length member specifies the length of string without CRLF chars and trailing spaces,
CreatedFromCrLf has true value if string created on wrapping.
Syntax:
TvgrWrapLine = packed record
Start: Integer;
Length: Integer;
CreatedFromCrLf: Boolean;
end;}
TvgrWrapLine = packed record
Start: Integer;
Length: Integer;
CreatedFromCrLf: Boolean;
end;
TvgrWrapLineDynArray = array of TvgrWrapLine;
/////////////////////////////////////////////////
//
// Functions
//
/////////////////////////////////////////////////
{ The vgrCalcStringHeight function computes the height of the specified string of text.
Text may contain many lines, lines must be separated by #13#10 chars.
Parameters:
ACanvas - TCanvas object
S - string
Return value:
Integer}
function vgrCalcStringHeight(ACanvas: TCanvas; const S: string): Integer;
{ The vgrCalcStringSize function computes the sizes (width and height) of the specified string of text.
Text may contain many lines, lines must be separated by #13#10 chars.
Also function returns count of lines in text.
Parameters:
ACanvas - TCanvas object
S - string
ALineCount - Integer (output count of lines in text)
Return value:
TSize}
function vgrCalcStringSize(ACanvas: TCanvas; const S: string; var ALineCount: Integer): TSize; overload;
{ The vgrCalcStringSize function computes the sizes (width and height) of the specified string of text.
Text may contain many lines, lines must be separated by #13#10 chars.
Parameters:
ACanvas - TCanvas object
S - string
Return value:
TSize}
function vgrCalcStringSize(ACanvas: TCanvas; const S: string): TSize; overload;
{ The vgrDrawString procedure draws formatted text in the specified rectangle.
It horizontally align the text according to the AHorzAlign parameter.
Parameters:
ACanvas - TCanvas object
S - string
ARect - TRect object
AVertOffset - Integer
AHorzAlign - TvgrTextHorzAlign, indicates how to align text horizontally}
procedure vgrDrawString(ACanvas: TCanvas;
const S: string;
const ARect: TRect;
AVertOffset: Integer;
AHorzAlign: TvgrTextHorzAlign);
{ The CreateFont function creates a logical font with the characteristics specified by Font object.
The returned logical font not depend from Font object and can subsequently be selected as the font for any device.
Parameters:
Font - TFont object
Return value:
HFont, font object handle}
function CreateAPIFont(Font: TFont) : HFont;
{ Returns height of specified font in logical units relative to display device context.
Parameters:
Font - TFont object
Return value:
integer}
function GetFontHeight(Font: TFont): integer;
{ Returns width of string in logical units when used the specified Font on display device context.
Parameters:
s - string
Font - TFont object
Return value:
Integer, width of string in logical units}
function GetStringWidth(const s: string; Font: TFont) : integer;
{ The SetCanvasTransparentMode function sets the background mix mode of the specified device context.
The background mix mode is used with text, hatched brushes, and pen styles that are not solid lines.
Parameters:
Canvas - TCanvas object
ATransparent - Boolean. If ATransparent = False - Background is filled with the current background color
before the text, hatched brush, or pen is drawn otherwise Background remains untouched.
Return value:
Boolean}
function SetCanvasTransparentMode(Canvas: TCanvas; ATransparent: Boolean): Boolean;
{ The CombineRectAndRegion procedure combines region and rectangle and stores the result in a region (ARegion parameter).
If ARegion parameter is zero, then function creates a new rectangular region
according Rect parameter.
The region and rect are combined according to the specified mode.
<br>RGN_AND Creates the intersection of the ARegion and Rect
<br>RGN_COPY Creates a copy of the region identified by Rect.
<br>RGN_DIFF Combines the parts of ARegion that are not part of Rect.
<br>RGN_OR Creates the union of ARegion and Rect.
<br>RGN_XOR Creates the union of ARegion and Rect except for any overlapping areas.
Parameters:
ARegion - HRGN, handle to a region
Rect - TRect object
ACombineMode - Integer, default value = RGN_OR}
procedure CombineRectAndRegion(var ARegion: HRGN; const Rect: TRect; ACombineMode: Integer = RGN_OR);
{ The CombineRegionAndRegion procedure combines ADestRegion and AAddedRegion and stores the result in a region (ADestRegion parameter).
If ADestRegion parameter is zero, AAddedRegion returned.
Note!!! If ADestRegion not is zero then AAddedRegion destroyed after combine.
The regions are combined according to the specified mode:
<br>RGN_AND Creates the intersection of the ARegion and Rect
<br>RGN_COPY Creates a copy of the region identified by Rect.
<br>RGN_DIFF Combines the parts of ARegion that are not part of Rect.
<br>RGN_OR Creates the union of ARegion and Rect.
<br>RGN_XOR Creates the union of ARegion and Rect except for any overlapping areas.
Parameters:
ADestRegion - HRGN, handle to a region
AAddedRegion - HRGN, handle to a region
ACombineMode - Integer, default = RGN_OR}
procedure CombineRegionAndRegion(var ADestRegion: HRGN; AAddedRegion: HRGN; ACombineMode: Integer = RGN_OR);
{ The CombineRegionAndRegionNoDelete procedure combines ADestRegion and AAddedRegion and stores the result in a region (ADestRegion parameter).
If ADestRegion parameter is zero, AAddedRegion returned.
The regions are combined according to the specified mode:
<br>RGN_AND Creates the intersection of the ARegion and Rect
<br>RGN_COPY Creates a copy of the region identified by Rect.
<br>RGN_DIFF Combines the parts of ARegion that are not part of Rect.
<br>RGN_OR Creates the union of ARegion and Rect.
<br>RGN_XOR Creates the union of ARegion and Rect except for any overlapping areas.
Parameters:
ADestRegion - HRGN, handle to a region
AAddedRegion - HRGN, handle to a region
ACombineMode - Integer, default value = RGN_OR}
procedure CombineRegionAndRegionNoDelete(var ADestRegion: HRGN; AAddedRegion: HRGN; ACombineMode: Integer = RGN_OR);
{ The ExcludeClipRect procedure creates a new clipping region that consists of the
existing clipping region minus the specified rectangle.
The lower and right edges of the specified rectangle are not excluded from the clipping region.
Parameters:
Canvas - TCanvas object
Rect - TRect object}
procedure ExcludeClipRect(Canvas: TCanvas; const Rect: TRect);
{ The ExcludeClipRegion procedure creates a new clipping region that consists of the
existing clipping region minus the specified region.
The lower and right edges of the specified rectangle are not excluded from the clipping region.
If canvas don`t has clipping region, new rectangular region created with coords (0, 0, 32000, 32000).
Parameters:
Canvas - TCanvas object
ARegion - HRGN, handle to a region}
procedure ExcludeClipRegion(Canvas: TCanvas; ARegion: HRGN);
{ The GetClipRegion function retrieves a handle identifying the current application-defined
clipping region for the specified canvas.
Parameters:
Canvas - TCanvas object
Return value:
HRGN, handle to a region}
function GetClipRegion(Canvas: TCanvas): HRGN;
{ The SelectClipRgn function selects a region as the current clipping region for the specified canvas.
Parameters:
Canvas - TCanvas object
AClipRegion - HRGN, handle to a region}
procedure SetClipRegion(Canvas: TCanvas; AClipRegion: HRGN);
{ The SelectClipRgn function selects a specified rectangle as the current clipping rectangle for the specified canvas.
Parameters:
Canvas - TCanvas object
AClipRect - TRect object}
procedure SetClipRect(Canvas: TCanvas; const AClipRect: TRect);
{ The CombineClipRegionAndRect procedure combines the specified rectangle with the current clipping region using the specified mode.
<br>RGN_AND The new clipping region combines the overlapping areas of the current
clipping region and the ractangle identified by ARect.
<br>RGN_COPY The new clipping region is a rectangular region appropriate ARect parameter.
<br>RGN_DIFF The new clipping region combines the areas of the current
clipping region with those areas excluded from the ractangle identified by ARect.
<br>RGN_OR The new clipping region combines the current clipping region
and the ractangle identified by ARect.
<br>RGN_XOR The new clipping region combines the current clipping region and the ractangle identified by ARect
but excludes any overlapping areas.
Parameters:
Canvas: TCanvas object
ARect - TRect object
ACombineMode - Integer,default value = RGN_OR}
procedure CombineClipRegionAndRect(Canvas: TCanvas; const ARect: TRect; ACombineMode: Integer = RGN_OR);
{ The ExtSelectClipRgn function combines the specified region with the current clipping region using the specified mode.
<br>RGN_AND The new clipping region combines the overlapping areas of the
current clipping region and the region identified by AClipRegion.
<br>RGN_COPY The new clipping region is a copy of the region identified by AClipRegion.
This is identical to SelectClipRgn. If the region identified by AClipRegion is NULL,
the new clipping region is the default clipping region
(the default clipping region is a null region).
<br>RGN_DIFF The new clipping region combines the areas of the current
clipping region with those areas excluded from the region identified by AClipRegion.
<br>RGN_OR The new clipping region combines the current clipping region and
the region identified by AClipRegion.
<br>RGN_XOR The new clipping region combines the current clipping region
and the region identified by AClipRegion but excludes any overlapping areas.
Parameters:
Canvas: TCanvas object
AClipRegion - HRGN, handle to a region
ACombineMode - Integer, default value = RGN_OR}
procedure CombineClipRegionAndRegion(Canvas: TCanvas; AClipRegion: HRGN; ACombineMode: Integer = RGN_OR);
{ The FillRgn function fills a region by using the current brush.
Parameters:
Canvas - TCanvas object
ARegion - HRGN, handle to a region}
procedure FillRegion(Canvas: TCanvas; ARegion: HRGN);
{ Function convert a color value in delphi format to a color value in Windows API format.
(It call GetSysColor function if color is system color like clWindow, clBtnFace etc).
Parameters:
AColor - TColor
Return value:
TColor}
function GetRGBColor(AColor: TColor): TColor;
{ Function returns a highlighted color for specified color by mixing a specified color
and clHighlighted color.
Parameters:
AColor - TColor type
Return value:
TColor, highlighted color}
function GetHighlightColor(AColor: TColor): TColor;
{ Function are mixing two colors according ATransparentValue parameter.
Parameters:
ATransparentValue - Byte
AColor1 - TColor
AColor2 - TColor
Return value:
TColor<br>
if ATransparentValue = 0 AColor2 returned,<br>
if ATransparentValue = 100 AColor1 returned. }
function MixingColors(ATransparentValue: Byte; AColor1, AColor2: TColor): TColor;
{ Splits each string in a memo into multiple lines as its length approaches a specified size.
AMaxWidth is the maximum line width in pixels.
Parameters:
ACanvas - TCanvas object
AMemo - TStrings
AMaxWidth - Integer, maximum line width in pixels}
// procedure WrapMemo(ACanvas: TCanvas; AMemo: TStrings; AMaxWidth : Integer); overload;
{Wrap the passed string on lines with using CRLF characters only.
Parameters:
S - string to wrap.
ALines - array of TvgrWrapLine structures each structure describe the separate line.}
procedure WrapMemo(const S: string;
var ALines: TvgrWrapLineDynArray;
ASkipEmptyLines: Boolean); overload;
procedure WrapMemo(ACanvas: TCanvas;
const S: string;
AMaxWidth: Integer;
var ALines: TvgrWrapLineDynArray;
ASkipEmptyLines: Boolean); overload;
procedure WrapMemo(ADC: HDC;
const S: string;
AMaxWidth: Integer;
var ALines: TvgrWrapLineDynArray;
ASkipEmptyLines: Boolean); overload;
procedure WrapMemo(ADC: HDC;
const S: string;
AMaxWidth: Integer;
var ALines: TvgrWrapLineDynArray;
AWordWrap: Boolean;
ADeleteEmptyLines: Boolean;
ADeleteEmptyLinesAtEnd: Boolean); overload;
{Wrap the passed string on lines, the AMaxWidth parameters specifies the maximum length of line in chars.}
procedure WrapMemoChars(const S: string;
AMaxWidth: Integer;
var ALines: TvgrWrapLineDynArray;
ASkipEmptyLines: Boolean); overload;
procedure WrapMemoChars(const S: string;
AMaxWidth: Integer;
var ALines: TvgrWrapLineDynArray;
AWordWrap: Boolean;
ADeleteEmptyLines: Boolean;
ADeleteEmptyLinesAtEnd: Boolean); overload;
function WrapMemo(ACanvas: TCanvas; const S: string; AMaxWidth: Integer): string; overload;
{ The LoadCursor procedure loads the specified cursor resource from the executable (.EXE)
file associated with an application instance and add them to a TScreen.Cursors collection.
Parameters:
ACursorName - string that contains the name of the cursor resource to be loaded
ACursorID - after call contains identificator of a cursor in TScreen.Cursors collection
ALoadedCusrorID - if cursor resource with given name exists this value returned
ADefaultCursor - if cursor resource with given name not exists this value returned}
procedure LoadCursor(const ACursorName: string; var ACursorID: TCursor; ALoadedCusrorID, ADefaultCursor: TCursor);
{ Draws a one pixel borders around a specified rectangle and fill inner area by specified color.
Parameters:
ACanvas - TCanvas object
ABorderRect - TRect object
AFlags parameter are specifies borders for drawing:
<br>BF_LEFT - left border
<br>BF_TOP - top border
<br>BF_RIGHT - right border
<br>BF_BOTTOM - bottom border
AColor - color of borders
AFillColor - color for fill inner area, default - clNone (no fill). }
procedure DrawBorders(ACanvas: TCanvas; const ABorderRect: TRect; AFlags: Cardinal; AColor: TColor; AFillColor: TColor = clNone); overload;
{ Draws a one pixel borders around a specified rectangle and fill inner area by specified color.
Parameters:
ACanvas - TCanvas object
ABorderRect - TRect object
ALeft - Boolean, draw(True) left border or not(False)
ATop - Boolean, draw top border or not
ARight - Boolean, draw right border or not
ABottom - Boolean, draw bottom border or not
AColor - color of borders
AFillColor - color for fill inner area, default - clNone (no fill). }
procedure DrawBorders(ACanvas: TCanvas; const ABorderRect: TRect; ALeft, ATop, ARight, ABottom: Boolean; AColor: TColor; AFillColor: TColor = clNone); overload;
{ Draw a border of specified type around control and returns rectangle which excludes a drawn border,
also procedure calculate width and height of this rectangle.
Parameters:
AControl - TControl
ACanvas - TCanvas
ABorderStyle - TBorderStyle
AInternalRect - TRect
AWidth - Integer, output by reference
AHeight - Integer, output by reference}
procedure DrawBorder(AControl: TControl; ACanvas: TCanvas; ABorderStyle: TBorderStyle; var AInternalRect: TRect; var AWidth, AHeight: Integer);
{ Draw frame around the specified rectangle by specified color.
Parameters:
ACanvas - TCanvas, canvas on which draw frame around rectangle
ARect - TRect, rectangle
AColor - TColor, color for draw}
procedure DrawFrame(ACanvas: TCanvas; const ARect: TRect; AColor: TColor);
{ Convert a value in degrees to a value in radians.
Parameters:
Angle - Double, angle in degrees
Return value:
Double, angle in radians.}
function ToRadians(Angle: Double): Double;
{ Returns coordinates of center of specified rectangle.
Parameters:
ARect - TRect object
Return value:
TPoint}
function RectCenter(const ARect: TRect): TPoint;
{ Returns height of specified rectangle.
Parameters:
ARect - TRect object
Return value:
Integer, height of ARect rectangle}
function RectHeight(const ARect: TRect): Integer;
{ Returns width of specified rectangle.
Parameters:
ARect - TRect object
Return value:
Integer, width of ARect rectangle}
function RectWidth(const ARect: TRect): Integer;
{ Rotate a point by specified angle (in degrees).
Parameters:
APoint - TPoint
AAngle - Double, angle in degrees
Return value:
TPoint}
function RotatePoint(const APoint: TPoint; AAngle: Double): TPoint;
{ Create a new logical font according a Font parameter rotated by angle specified
by RotateAngle parameter (angle in degrees).
Parameters:
Font - TFont object
RotateAngle - Integer, angle in degrees
Return value:
HFONT, handle to a font}
function GetRotatedFontHandle(Font: TFont; RotateAngle: Integer): HFONT;
function GetRotatedTextSize(Canvas: TCanvas; const Text: string; Font: TFont; RotateAngle: Integer): TSize;
procedure GetRotatedTextRectSize(Canvas: TCanvas; const Text: string; Font: TFont; RotateAngle: Integer; var RectSize: TSize; var TextSize: TSize); overload;
procedure GetRotatedTextRectSize(TextSize: TSize; RotateAngle: Integer; var RectSize: TSize); overload;
{ Change StateIndex property of TTreeNode object specified by ANode parameter.
if StateIndex equals AChecked them AStateIndex = ANotChecked, otherwise
StateIndex equals AChecked.
This function also update StateIndex property of parent nodes and child nodes.
Parameters:
ANode - TTreeNode object
ANotChecked - Integer
AChecked - Integer
AGrayed - Integer}
procedure ChangeStateOfTreeNode(ANode: TTreeNode; ANotChecked, AChecked, AGrayed: Integer);
{Draws the image on a canvas.
Parameters:
ACanvas - The TCanvas object.
AImage - Image to drawing.
ARect - The bounds rectangle, within of which the image should be aligned.
AScaleX, AScaleY - Specify the scaling of image.
ADrawMode - Specifies the image alignment.}
procedure DrawImage(ACanvas: TCanvas;
AImage: TGraphic;
const ARect: TRect;
AScaleX, AScaleY: Extended;
ADrawMode: TvgrImageDrawMode);
{Searches an optimum place for popup form.
Parameters:
AButtonRect - Rectangle of button that causes the showing of popup form.
AWidth - Width of popup form.
AHeight - Height of popup form.
Return value:
Point at which the form must be displayed.}
function FindPopupPoint(const AButtonRect: TRect; AWidth, AHeight: Integer): TPoint;
implementation
uses
Math, vgr_Consts;
const
ACrLfChars: set of char = [#13, #10];
function FindPopupPoint(const AButtonRect: TRect; AWidth, AHeight: Integer): TPoint;
var
R: TRect;
begin
SystemParametersInfo(SPI_GETWORKAREA, 0, @R, 0);
if AButtonRect.Left + AWidth > r.Right then
Result.X := r.Right - AWidth
else
Result.X := AButtonRect.Left;
if AButtonRect.Bottom + AHeight > r.Bottom then
Result.Y := AButtonRect.Top - AHeight
else
Result.Y := AButtonRect.Bottom;
end;
/////////////////////////////////////////////////
//
// TvgrFastRegion
//
/////////////////////////////////////////////////
constructor TvgrFastRegion.Create;
begin
inherited Create;
FRegionData := AllocMem(SizeOf(RGNDATAHEADER));
FRegionData.dwSize := SizeOf(RGNDATAHEADER);
FRegionData.iType := RDH_RECTANGLES;
end;
destructor TvgrFastRegion.Destroy;
begin
FreeMem(FRegionData);
inherited;
end;
procedure TvgrFastRegion.Clear;
begin
ReallocMem(FRegionData, SizeOf(RGNDATAHEADER));
FRects := PRectArray(PChar(FRegionData) + SizeOf(RGNDATAHEADER));
with FRegionData^ do
begin
nCount := 0;
rcBound.Left := 0;
rcBound.Top := 0;
rcBound.Right := 0;
rcBound.Bottom := 0;
end;
FCapacity := 0;
end;
procedure TvgrFastRegion.Grow;
begin
FCapacity := FCapacity + FRegionData.nCount div 5 + 1;
ReallocMem(FRegionData, FCapacity * SizeOf(TRect) + SizeOf(RGNDATAHEADER));
FRects := PRectArray(PChar(FRegionData) + SizeOf(RGNDATAHEADER));
end;
// Count div 5 + 1
procedure TvgrFastRegion.AddRect(const ARect: TRect);
begin
if FRegionData.nCount = FCapacity then
Grow;
with FRects^[FRegionData.nCount] do
begin
Left := ARect.Left;
Top := ARect.Top;
Right := ARect.Right;
Bottom := ARect.Bottom;
end;
with FRegionData^.rcBound do
begin
if ARect.Left < Left then
Left := ARect.Left;
if ARect.Top < Top then
Top := ARect.Top;
if ARect.Right > Right then
Right := ARect.Right;
if ARect.Bottom < Bottom then
Bottom := ARect.Bottom;
end;
Inc(FRegionData.nCount);
end;
function TvgrFastRegion.BuildRegion: HRGN;
begin
if FRegionData.nCount = 0 then
Result := 0
else
Result := ExtCreateRegion(nil, FCapacity * SizeOf(TRect) + SizeOf(RGNDATAHEADER), PRgnData(FRegionData)^);
end;
/////////////////////////////////////////////////
//
// Functions
//
/////////////////////////////////////////////////
function vgrCalcStringHeight(ACanvas: TCanvas; const S: string): Integer;
var
ALineCount: Integer;
ATextMetrics: tagTEXTMETRIC;
ALineInfo: TvgrTextLineInfo;
begin
ALineCount := 0;
BeginEnumLines(S, ALineInfo);
while EnumLines(S, ALineInfo) do
Inc(ALineCount);
GetTextMetrics(ACanvas.Handle, ATextMetrics);
Result := ATextMetrics.tmHeight * (ALineCount{ + 1});
end;
function vgrCalcStringSize(ACanvas: TCanvas; const S: string; var ALineCount: Integer): TSize;
var
ATextMetrics: tagTEXTMETRIC;
ALineInfo: TvgrTextLineInfo;
ATextSize: TSize;
ALine: string;
begin
BeginEnumLines(S, ALineInfo);
ALineCount := 0;
Result.cx := 0;
while EnumLines(S, ALineInfo) do
begin
ALine := Copy(S, ALineInfo.Start, ALineInfo.Length);
GetTextExtentPoint32(ACanvas.Handle, PChar(S), ALineInfo.Length, ATextSize);
if ATextSize.cx > Result.cx then
Result.cx := ATextSize.cx;
Inc(ALineCount);
end;
GetTextMetrics(ACanvas.Handle, ATextMetrics);
Result.cy := ATextMetrics.tmHeight * (ALineCount{ + 1});
end;
function vgrCalcStringSize(ACanvas: TCanvas; const S: string): TSize;
var
ALineCount: Integer;
begin
Result := vgrCalcStringSize(ACanvas, S, ALineCount);
end;
procedure vgrDrawString(ACanvas: TCanvas;
const S: string;
const ARect: TRect;
AVertOffset: Integer;
AHorzAlign: TvgrTextHorzAlign);
var
X, Y, AWidth: Integer;
ALineInfo: TvgrTextLineInfo;
ALine: string;
ATextMetrics: tagTEXTMETRIC;
ALineSize: TSize;
begin
GetTextMetrics(ACanvas.Handle, ATextMetrics);
BeginEnumLines(S, ALineInfo);
Y := ARect.Top + AVertOffset;
AWidth := ARect.Right - ARect.Left;
while EnumLines(S, ALineInfo) do
begin
ALine := Copy(S, ALineInfo.Start, ALineInfo.Length);
GetTextExtentPoint32(ACanvas.Handle, PChar(ALine), ALineInfo.Length, ALineSize);
case AHorzAlign of
vgrthaCenter: X := ARect.Left + (AWidth - ALineSize.cx) div 2;
vgrthaRight: X := ARect.Right - ALineSize.cx;
else X := ARect.Left;
end;
ExtTextOut(ACanvas.Handle, X, Y, ETO_CLIPPED, @ARect, PChar(ALine), ALineInfo.Length, nil);
Y := Y + ATextMetrics.tmHeight;
end;
end;
function CreateAPIFont(Font : TFont) : HFont;
var
F: TLogFont;
begin
GetObject(Font.Handle,SizeOf(TLogFont),@F);
Result := CreateFontIndirect(F);
end;
function GetFontHeight(Font: TFont): Integer;
var
ATextMetrics: tagTEXTMETRIC;
DC: HDC;
OldFont: HFONT;
begin
DC := GetDC(0);
OldFont := SelectObject(DC, Font.Handle);
GetTextMetrics(DC, ATextMetrics);
SelectObject(DC, OldFont);
ReleaseDC(0, DC);
Result := ATextMetrics.tmHeight;
end;
function GetStringWidth(const s : string; Font : TFont) : integer;
var
sz: TSize;
DC: HDC;
OldFont,NewFont: HFONT;
begin
DC := GetDC(0);
NewFont := CreateAPIFont(Font);
OldFont := SelectObject(DC,NewFont);
GetTextExtentPoint(DC,PChar(s),Length(s),sz);
Result := sz.cx;
SelectObject(DC,OldFont);
DeleteObject(NewFont);
ReleaseDC(0,DC);
end;
function SetCanvasTransparentMode(Canvas: TCanvas; ATransparent: Boolean): Boolean;
const
aBkMode: array [Boolean] of Integer = (OPAQUE , TRANSPARENT);
begin
Result := SetBkMode(Canvas.Handle, aBkMode[ATransparent]) = TRANSPARENT;
end;
procedure ExcludeClipRect(Canvas: TCanvas; const Rect: TRect);
begin
Windows.ExcludeClipRect(Canvas.Handle, Rect.Left, Rect.Top, Rect.Right, Rect.Bottom);
end;
procedure CombineRegionAndRegionNoDelete(var ADestRegion: HRGN; AAddedRegion: HRGN; ACombineMode: Integer = RGN_OR);
begin
if ADestRegion = 0 then
begin
ADestRegion := CreateRectRgn(0, 0, 0, 0);
CombineRgn(ADestRegion, ADestRegion, AAddedRegion, RGN_COPY);
end
else
CombineRgn(ADestRegion, ADestRegion, AAddedRegion, ACombineMode);
end;
procedure CombineRegionAndRegion(var ADestRegion: HRGN; AAddedRegion: HRGN; ACombineMode: Integer = RGN_OR);
begin
if ADestRegion = 0 then
ADestRegion := AAddedRegion
else
begin
CombineRgn(ADestRegion, ADestRegion, AAddedRegion, ACombineMode);
DeleteObject(AAddedRegion);
end
end;
procedure CombineRectAndRegion(var ARegion: HRGN; const Rect: TRect; ACombineMode: Integer = RGN_OR);
var
ATempRegion: HRGN;
begin
if ARegion = 0 then
ARegion := CreateRectRgnIndirect(Rect)
else
begin
ATempRegion := CreateRectRgnIndirect(Rect);
CombineRgn(ARegion, ARegion, ATempRegion, ACombineMode);
DeleteObject(ATempRegion);
end;
end;
procedure ExcludeClipRegion(Canvas: TCanvas; ARegion: HRGN);
var
ATempRegion: HRGN;
begin
ATempRegion := CreateRectRgn(0, 0, 0, 0);
if GetClipRgn(Canvas.Handle, ATempRegion) = 0 then
begin
DeleteObject(ATempRegion);
ATempRegion := CreateRectRgn(0, 0, 32000, 32000); // !!! other values cause bug on Win9X
SelectClipRgn(Canvas.Handle, ATempRegion);
end;
ExtSelectClipRgn(Canvas.Handle, ARegion, RGN_DIFF);
DeleteObject(ATempRegion);
end;
function GetClipRegion(Canvas: TCanvas): HRGN;
begin
Result := CreateRectRgn(0, 0, 0, 0);
if GetClipRgn(Canvas.Handle, Result) = 0 then
begin
DeleteObject(Result);
Result := 0;
end;
end;
procedure SetClipRegion(Canvas: TCanvas; AClipRegion: HRGN);
begin
SelectClipRgn(Canvas.Handle, AClipRegion);
end;
procedure CombineClipRegionAndRect(Canvas: TCanvas; const ARect: TRect; ACombineMode: Integer = RGN_OR);
var
ARegion: HRGN;
begin
ARegion := GetClipRegion(Canvas);
if ARegion = 0 then
SetClipRect(Canvas, ARect)
else
begin
CombineRectAndRegion(ARegion, ARect, ACombineMode);
SelectClipRgn(Canvas.Handle, ARegion);
DeleteObject(ARegion);
end;
end;
procedure CombineClipRegionAndRegion(Canvas: TCanvas; AClipRegion: HRGN; ACombineMode: Integer = RGN_OR);
begin
ExtSelectClipRgn(Canvas.Handle, AClipRegion, ACombineMode);
end;
procedure SetClipRect(Canvas: TCanvas; const AClipRect: TRect);
var
ARegion: HRGN;
begin
ARegion := CreateRectRgnIndirect(AClipRect);
SelectClipRgn(Canvas.Handle, ARegion);
DeleteObject(ARegion);
end;
procedure FillRegion(Canvas: TCanvas; ARegion: HRGN);
begin
FillRgn(Canvas.Handle, ARegion, Canvas.Brush.Handle);
end;
function GetRGBColor(AColor: TColor): TColor;
begin
if (AColor and $FF0000000) <> 0 then
Result := GetSysColor(AColor and not $FF000000)
else
Result := AColor;
end;
function MixingColors(ATransparentValue: Byte; AColor1, AColor2: TColor): TColor;
var
r1, g1, b1: byte;
r2, g2, b2: byte;
r3, g3, b3: byte;
v: single;
ARGBColor1, ARGBColor2: TColor;
begin
v := ATransparentValue / 100;
ARGBColor1 := GetRGBColor(AColor1);
ARGBColor2 := GetRGBColor(AColor2);
r1 := lo(ARGBColor1);
g1 := lo(ARGBColor1 shr 8);
b1 := lo(ARGBColor1 shr 16);
r2 := lo(ARGBColor2);
g2 := lo(ARGBColor2 shr 8);
b2 := lo(ARGBColor2 shr 16);
r3 := round(r1 * v + r2 * (1 - v));
g3 := round(g1 * v + g2 * (1 - v));
b3 := round(b1 * v + b2 * (1 - v));
result := RGB(r3, g3, b3);
end;
function GetHighlightColor(AColor: TColor): TColor;
begin
Result := MixingColors(70, AColor, clHighlight);
end;
procedure LoadCursor(const ACursorName: string; var ACursorID: TCursor; ALoadedCusrorID, ADefaultCursor: TCursor);
var
ACursor: HCURSOR;
begin
ACursor := LoadImage(hInstance, PChar(ACursorName), IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE or LR_DEFAULTCOLOR);
if ACursor = 0 then
ACursorID := ADefaultCursor
else
begin
Screen.Cursors[ALoadedCusrorID] := ACursor;
ACursorID := ALoadedCusrorID;
end;
end;
procedure WrapMemoChars(const S: string;
AMaxWidth: Integer;
var ALines: TvgrWrapLineDynArray;
ASkipEmptyLines: Boolean);
var
I, J, N, M, ALen: Integer;
ACrLf: Boolean;
begin
ALen := Length(S);
SetLength(ALines, 0);
//
I := 1;
while I <= ALen do
begin
J := I;
while (I <= ALen) and
(not (S[I] in ACrLfChars)) and
(I - J < AMaxWidth) do
Inc(I);
ACrLf := (I <= ALen) and (S[I] in ACrLfChars);
if (I <= ALen) and not (S[I] in ACrLfChars) then
begin
if I = J then
begin
// width of symbol large then AMaxWidth
Inc(I);
end
else
begin
if S[I] = ' ' then
while (I <= ALen) and (S[I] = ' ') do Inc(I)
else
begin
N := I;
while (I > J) and not (S[I] in WordWrapChars) do
Dec(I);
if I <= J then
I := N
else
begin
Inc(I);
while (I <= ALen) and (S[I] = ' ') do Inc(I);
end;
end;
end;
end;
N := I;
FindEndOfLineBreak(S, ALen, I);
M := N;
while (M > J) and (S[M - 1] = ' ') do Dec(M);
if not ASkipEmptyLines or (M - J > 0) then
begin
SetLength(ALines, Length(ALines) + 1);
with ALines[High(ALines)] do
begin
Start := J;
Length := M - J;
CreatedFromCrLf := ACrLf;
end;
end;
end;
end;
procedure WrapMemoChars(const S: string;
AMaxWidth: Integer;
var ALines: TvgrWrapLineDynArray;
AWordWrap: Boolean;
ADeleteEmptyLines: Boolean;
ADeleteEmptyLinesAtEnd: Boolean);
var
I: Integer;
begin
if AWordWrap and (AMaxWidth > 0) then
WrapMemoChars(S, AMaxWidth, ALines, ADeleteEmptyLines)
else
WrapMemo(S, ALines, ADeleteEmptyLines);
if not ADeleteEmptyLines and ADeleteEmptyLinesAtEnd then
begin
I := High(ALines);
while (I > 0) and (ALines[I].Length = 0) do Dec(I);
SetLength(ALines, I + 1);
end;
end;
procedure WrapMemo(ADC: HDC;
const S: string;
AMaxWidth: Integer;
var ALines: TvgrWrapLineDynArray;
AWordWrap: Boolean;
ADeleteEmptyLines: Boolean;
ADeleteEmptyLinesAtEnd: Boolean);
var
I: Integer;
begin
if AWordWrap then
WrapMemo(ADC, S, AMaxWidth, ALines, ADeleteEmptyLines)
else
WrapMemo(S, ALines, ADeleteEmptyLines);
if not ADeleteEmptyLines and ADeleteEmptyLinesAtEnd then
begin
I := High(ALines);
while (I > 0) and (ALines[I].Length = 0) do Dec(I);
SetLength(ALines, I + 1);
end;
end;
procedure WrapMemo(ACanvas: TCanvas; const S: string; AMaxWidth: Integer; var ALines: TvgrWrapLineDynArray; ASkipEmptyLines: Boolean);
begin
WrapMemo(ACanvas.Handle, S, AMaxWidth, ALines, ASkipEmptyLines);
end;
procedure WrapMemo(const S: string; var ALines: TvgrWrapLineDynArray; ASkipEmptyLines: Boolean);
var
I, J, N, M, ALen: Integer;
ACrLf: Boolean;
begin
SetLength(ALines, 0);
ALen := Length(S);
I := 1;
while I <= ALen do
begin
J := I;
while (I <= ALen) and (not (S[I] in ACrLfChars)) do
Inc(I);
ACrLf := (I < ALen) and (S[I] in ACrLfChars);
N := I;
FindEndOfLineBreak(S, ALen, I);
M := N;
while (M > J) and (S[M - 1] = ' ') do Dec(M);
if not ASkipEmptyLines or (M - J > 0) then
begin
SetLength(ALines, Length(ALines) + 1);
with ALines[High(ALines)] do
begin
Start := J;
Length := M - J;
CreatedFromCrLf := ACrLf;
end;
end;
end;
end;
procedure WrapMemo(ADC: HDC; const S: string; AMaxWidth: Integer; var ALines: TvgrWrapLineDynArray; ASkipEmptyLines: Boolean);
const
ABlockSize = 8192;
var
ABuf: PIntArray;
ASize: TSize;
AFit, I, J, N, M, ALen, AWidth: Integer;
ACrLf: Boolean;
function IsWordWrapChar(C: char): Boolean;
begin
Result := C = ' ';
end;
begin
SetLength(ALines, 0);
ALen := Length(S);
GetMem(ABuf, ALen * 4);
try
I := 1;
while I < ALen do
begin
GetTextExtentExPoint(ADC,
@S[I],
Min(ABlockSize, ALen - I + 1),
MaxInt,
@AFit,
PInteger(PChar(ABuf) + (I - 1) * 4),
ASize);
for J := Min(ALen - 1, I + ABlockSize - 2) downto I do
ABuf^[J] := ABuf^[J] - ABuf^[J - 1];
I := I + ABlockSize;
end;
//
I := 1;
while I <= ALen do
begin
J := I;
AWidth := 0;
while (I <= ALen) and
(not (S[I] in ACrLfChars)) and
(AWidth + ABuf^[I - 1] < AMaxWidth) do
begin
AWidth := AWidth + ABuf^[I - 1];
Inc(I);
end;
ACrLf := (I <= ALen) and (S[I] in ACrLfChars);
if (I <= ALen) and not (S[I] in ACrLfChars) then
begin
if I = J then
begin
// width of symbol large then AMaxWidth
Inc(I);
end
else
begin
if S[I] = ' ' then
while (I <= ALen) and (S[I] = ' ') do Inc(I)
else
begin
N := I;
while (I > J) and not IsWordWrapChar(S[I]) do
Dec(I);
if I <= J then
I := N
else
begin
Inc(I);
while (I <= ALen) and (S[I] = ' ') do Inc(I);
end;
end;
end;
end;
N := I;
FindEndOfLineBreak(S, ALen, I);
M := N;
while (M > J) and (S[M - 1] = ' ') do Dec(M);
if not ASkipEmptyLines or (M - J > 0) then
begin
SetLength(ALines, Length(ALines) + 1);
with ALines[High(ALines)] do
begin
Start := J;
Length := M - J;
CreatedFromCrLf := ACrLf;
end;
end;
end;
finally
FreeMem(ABuf);
end;
end;
function WrapMemo(ACanvas: TCanvas; const S: string; AMaxWidth: Integer): string;
const
ABlockSize = 8192;
var
ABuf: PIntArray;
ASize: TSize;
AFit, I, J, K, N, M, ALen, AWidth: Integer;
function IsWordWrapChar(C: char): Boolean;
begin
Result := C = ' ';
end;
begin
ALen := Length(S);
GetMem(ABuf, ALen * 4);
try
I := 1;
while I < ALen do
begin
GetTextExtentExPoint(ACanvas.Handle,
@S[I],
Min(ABlockSize, ALen - I + 1),
MaxInt,
@AFit,
PInteger(PChar(ABuf) + (I - 1) * 4),
ASize);
for J := Min(ALen - 1, I + ABlockSize - 2) downto I do
begin
if S[J + 1] in ACrLfChars then
ABuf^[J] := 0
else
ABuf^[J] := ABuf^[J] - ABuf^[J - 1];
end;
I := I + ABlockSize;
end;
//
SetLength(Result, ALen * 4);
I := 1;
K := 1;
while I <= ALen do
begin
J := I;
AWidth := 0;
while (I <= ALen) and (AWidth + ABuf^[I - 1] < AMaxWidth) do
begin
Result[K] := S[I];
if (S[I] = #13) or (S[I] = #10) then
AWidth := 0
else
AWidth := AWidth + ABuf^[I - 1];
Inc(I);
Inc(K);
end;
if I <= ALen then
begin
if I = J then
begin
// width of symbol large then AMaxWidth
Result[K] := S[I];
Inc(K);
Inc(I);
end
else
begin
if S[I] = ' ' then
while (I <= ALen) and (S[I] = ' ') do Inc(I)
else
begin
N := I;
M := K;
while (I > J) and not IsWordWrapChar(S[I]) do
begin
Dec(I);
Dec(K);
end;
if I <= J then
begin
I := N;
K := M;
end
else
begin
Inc(I);
Inc(K);
end;
end;
end;
Result[K] := #13;
Inc(K);
Result[K] := #10;
Inc(K);
end;
end;
SetLength(Result, K - 1);
finally
FreeMem(ABuf);
end;
end;
{
procedure WrapMemo(ACanvas: TCanvas; AMemo: TStrings; AMaxWidth : Integer);
var
l: TStringList;
s: string;
sz: TSize;
i, ls, p1, p2, p3 : integer;
begin
l := TStringList.Create;
try
for i:=0 to AMemo.Count-1 do
begin
s := AMemo[i];
ls := Length(s);
p1 := 1;
p2 := 1;
while p2<=ls do
begin
GetTextExtentExPoint(ACanvas.Handle, PChar(@s[p2]), ls - p2 + 1, AMaxWidth, @p1, nil, sz);
if p2+p1<=ls then
begin
//
if s[p1+p2]=' ' then
begin
while (p1+p2<=ls) and (s[p1+p2]=' ') do Inc(p1);
end
else
begin
p3 := p1+p2-1;
while (p3>=p2) and not(s[p3] in [' ','.',',','-',';']) do Dec(p3);
if p3>=p2 then
p1 := p3-p2+1;
end;
end;
if p1=0 then
p1 :=1;
// add string part from p2 to p1
l.Add(Trim(Copy(s, p2, p1)));
p2 := p2+p1;
end;
end;
AMemo.Assign(l);
finally
l.Free;
end;
end;
}
procedure DrawBorders(ACanvas: TCanvas; const ABorderRect: TRect; AFlags: Cardinal; AColor: TColor; AFillColor: TColor = clNone);
begin
DrawBorders(ACanvas, ABorderRect,
(BF_LEFT and AFlags) <>0,
(BF_TOP and AFlags) <>0,
(BF_RIGHT and AFlags) <>0,
(BF_BOTTOM and AFlags) <>0,
AColor,
AFillColor);
end;
procedure DrawBorders(ACanvas: TCanvas; const ABorderRect: TRect; ALeft, ATop, ARight, ABottom: Boolean; AColor: TColor; AFillColor: TColor = clNone);
var
ARect: TRect;
begin
ARect := ABorderRect;
ACanvas.Brush.Color := AColor;
if ALeft then
begin
ACanvas.FillRect(Rect(ARect.Left, ARect.Top, ARect.Left + 1, ARect.Bottom));
ARect.Left := ARect.Left + 1;
end;
if ATop then
begin
ACanvas.FillRect(Rect(ARect.Left, ARect.Top, ARect.Right, ARect.Top + 1));
ARect.Top := ARect.Top + 1;
end;
if ARight then
begin
ACanvas.FillRect(Rect(ARect.Right - 1, ARect.Top, ARect.Right, ARect.Bottom));
ARect.Right := ARect.Right - 1;
end;
if ABottom then
begin
ACanvas.FillRect(Rect(ARect.Left, ARect.Bottom - 1, ARect.Right, ARect.Bottom));
ARect.Bottom := ARect.Bottom - 1;
end;
if AFillColor <> clNone then
begin
ACanvas.Brush.Color := AFillColor;
ACanvas.FillRect(ARect);
end;
end;
function RectCenter(const ARect: TRect): TPoint;
begin
with ARect do
begin
Result.X := Left + (Right - Left) div 2;
Result.Y := Top + (Bottom - Top) div 2;
end;
end;
function RectHeight(const ARect: TRect): Integer;
begin
Result := ARect.Bottom - ARect.Top;
end;
function RectWidth(const ARect: TRect): Integer;
begin
Result := ARect.Right - ARect.Left;
end;
function ToRadians(Angle: Double): Double;
begin
Result := Pi / 180 * Angle;
end;
function GetRotatedFontHandle(Font: TFont; RotateAngle: Integer): HFONT;
var
LF: TLogFont;
begin
GetObject(Font.Handle, SizeOf(TLogFont), @LF);
LF.lfEscapement := RotateAngle * 10;
LF.lfOrientation := RotateAngle * 10;
Result := CreateFontIndirect(LF);
end;
function GetRotatedTextSize(Canvas: TCanvas; const Text: string; Font: TFont; RotateAngle: Integer): TSize;
var
OldFont,NewFont: HFONT;
ARect: TRect;
begin
NewFont := GetRotatedFontHandle(Font,RotateAngle);
OldFont := SelectObject(Canvas.Handle,NewFont);
ARect := Rect(0,0, MaxInt, MaxInt);
DrawText(Canvas.Handle, PChar(Text), Length(Text), ARect, DT_CALCRECT or DT_LEFT or DT_NOPREFIX);
Result.cx := ARect.Right - ARect.Left;
Result.cy := ARect.Bottom - ARect.Top;
SelectObject(Canvas.Handle,OldFont);
DeleteObject(NewFont);
end;
procedure GetRotatedTextRectSize(TextSize: TSize; RotateAngle: Integer; var RectSize: TSize);
var
SinAngle,CosAngle,RadianAngle: Double;
begin
RadianAngle := ToRadians(RotateAngle);
SinAngle := sin(RadianAngle);
CosAngle := cos(RadianAngle);
RectSize.cx := Abs(Round(TextSize.cx * CosAngle)) + Abs(Round(TextSize.cy * SinAngle));
RectSize.cy := Abs(Round(TextSize.cx * SinAngle)) + Abs(Round(TextSize.cy * CosAngle));
end;
procedure GetRotatedTextRectSize(Canvas: TCanvas; const Text: string; Font: TFont; RotateAngle: Integer; var RectSize: TSize; var TextSize: TSize);
begin
TextSize := GetRotatedTextSize(Canvas, Text, Font, RotateAngle);
GetRotatedTextRectSize(TextSize, RotateAngle, RectSize);
end;
function RotatePoint(const APoint: TPoint; AAngle: Double): TPoint;
var
SinAngle,CosAngle,RadianAngle: Double;
begin
RadianAngle := ToRadians(AAngle);
SinAngle := sin(RadianAngle);
CosAngle := cos(RadianAngle);
Result.X := Round(APoint.X * CosAngle - APoint.Y * SinAngle);
Result.Y := Round(APoint.X * SinAngle + APoint.Y * CosAngle);
end;
procedure ChangeStateOfTreeNode(ANode: TTreeNode; ANotChecked, AChecked, AGrayed: Integer);
var
AParent: TTreeNode;
procedure SetAllChildrenStateIndex(ANode: TTreeNode; AStateIndex: Integer);
var
AChild: TTreeNode;
begin
ANode.StateIndex := AStateIndex;
AChild := ANode.getFirstChild;
while AChild <> nil do
begin
SetAllChildrenStateIndex(AChild, AStateIndex);
AChild := ANode.GetNextChild(AChild);
end;
end;
procedure CheckParent(ANode: TTreeNode);
var
AChild: TTreeNode;
AStateIndex: Integer;
begin
AChild := ANode.getFirstChild;
if AChild <> nil then
begin
AStateIndex := AChild.StateIndex;
if AStateIndex <> AGrayed then
begin
while (AChild <> nil) and (AStateIndex = AChild.StateIndex) do
AChild := ANode.GetNextChild(AChild);
if AChild <> nil then
AStateIndex := AGrayed;
end;
ANode.StateIndex := AStateIndex;
end;
end;
begin
if ANode.StateIndex = AChecked then
ANode.StateIndex := ANotChecked
else
ANode.StateIndex := AChecked;
SetAllChildrenStateIndex(ANode, ANode.StateIndex);
AParent := ANode.Parent;
while AParent <> nil do
begin
CheckParent(AParent);
AParent := AParent.Parent;
end;
end;
procedure DrawBorder(AControl: TControl; ACanvas: TCanvas; ABorderStyle: TBorderStyle; var AInternalRect: TRect; var AWidth, AHeight: Integer);
begin
AInternalRect := Rect(0, 0, AControl.ClientWidth, AControl.ClientHeight);
case ABorderStyle of
bsSingle: DrawEdge(ACanvas.Handle, AInternalRect, EDGE_SUNKEN, BF_ADJUST or BF_RECT);
end;
AWidth := AInternalRect.Right - AInternalRect.Left;
AHeight := AInternalRect.Bottom - AInternalRect.Top;
end;
procedure DrawFrame(ACanvas: TCanvas; const ARect: TRect; AColor: TColor);
begin
ACanvas.Brush.Style := bsSolid;
ACanvas.Brush.Color := AColor;
with ARect do
begin
ACanvas.FillRect(Rect(Left, Top, Right, Top + 1));
ACanvas.FillRect(Rect(Right - 1, Top, Right, Bottom));
ACanvas.FillRect(Rect(Left, Bottom - 1, Right, Bottom));
ACanvas.FillRect(Rect(Left, Top, Left + 1, Bottom));
end;
end;
procedure DrawImage(ACanvas: TCanvas;
AImage: TGraphic;
const ARect: TRect;
AScaleX, AScaleY: Extended;
ADrawMode: TvgrImageDrawMode);
var
AOldClipRgn, AClipRgn: HRGN;
AOrgEx: TPoint;
AImageWidth, AImageHeight: Integer;
R: TRect;
kmul, kdiv: Integer;
begin
AImageWidth := Round(AImage.Width * AScaleX);
AImageHeight := Round(AImage.Height * AScaleY);
if (AImageWidth = 0) or (AImageHeight = 0) then exit;
case ADrawMode of
vgridmCenter:
begin
// center
AOldClipRgn := GetClipRegion(ACanvas);
GetViewportOrgEx(ACanvas.Handle, AOrgEx);
AClipRgn := CreateRectRgn(ARect.Left + AOrgEx.X,
ARect.Top + AOrgEx.Y,
ARect.Right + AOrgEx.X,
ARect.Bottom + AOrgEx.Y);
SetClipRegion(ACanvas, AClipRgn);
with ARect do
begin
R.Left := Left + (Right - Left - AImageWidth) div 2;
R.Top := Top + (Bottom - Top - AImageHeight) div 2;
R.Right := r.Left + AImageWidth;
R.Bottom := r.Top + AImageHeight;
end;
ACanvas.StretchDraw(R, AImage);
SetClipRegion(ACanvas, AOldClipRgn);
DeleteObject(AClipRgn);
if AOldClipRgn <> 0 then
DeleteObject(AOldClipRgn)
end;
vgridmStretch:
begin
// stretch in rect
ACanvas.StretchDraw(ARect, AImage);
end;
vgridmStretchProp:
begin
if (ARect.Right - ARect.Left) / AImageWidth < (ARect.Bottom - ARect.Top) / AImageHeight then
begin
kmul := ARect.Right - ARect.Left;
kdiv := AImageWidth;
end
else
begin
kmul := ARect.Bottom - ARect.Top;
kdiv := AImageHeight;
end;
AImageWidth := muldiv(AImageWidth, kmul, kdiv);
AImageHeight := muldiv(AImageHeight, kmul, kdiv);
with ARect do
begin
R.Left := Left + (Right - Left - AImageWidth) div 2;
R.Top := Top + (Bottom - Top - AImageHeight) div 2;
R.Right := r.Left + AImageWidth;
R.Bottom := r.Top + AImageHeight;
end;
ACanvas.StretchDraw(R, AImage);
end;
end;
end;
end.
|
unit MainForm;
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.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FB,
FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.Client,
Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Buttons, FireDAC.Stan.Param, FireDAC.DatS,
FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, System.RegularExpressions,
System.Hash, IdHashMessageDigest;
type
TForm1 = class(TForm)
FDConnection1: TFDConnection;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
edtUserName: TEdit;
edtPassword: TEdit;
Label1: TLabel;
Label2: TLabel;
Button1: TButton;
Memo1: TMemo;
FDQuery1: TFDQuery;
ButtonLoginWithParams: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ButtonLoginWithParamsClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function EncUser(const UserName: string): string;
begin
Result := UpperCase(UserName);
end;
(*
function IndyMD5Str(const Value: string): string;
var
MD5 : TIdHashMessageDigest5;
begin
MD5 := TIdHashMessageDigest5.Create;
try
Result := MD5.HashStringAsHex(Value);
finally
MD5.Free;
end;
end;
*)
function EncPassword(const UserName, Password: string): string;
const
PasswordSalt = 'df\gjjh45è89p6b&%/%6dfklgjdbèòò34@@523rsdef';
begin
Result := UpperCase(THashMD5.GetHashString(PasswordSalt + ':' + UpperCase(UserName) + ':' + Password));
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if edtPassword.PasswordChar = #0 then
edtPassword.PasswordChar := '*'
else
edtPassword.PasswordChar := #0;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
PageControl1.ActivePageIndex := 0;
FDConnection1.Connected := True;
end;
procedure TForm1.ButtonLoginWithParamsClick(Sender: TObject);
begin
// LUCA/password1
FDQuery1.ParamByName('USER_NAME').AsString := EncUser(edtUserName.Text);
FDQuery1.ParamByName('PASSWORD').AsString := EncPassword(edtUserName.Text, edtPassword.Text);
FDQuery1.Open;
if not FDQuery1.IsEmpty then
Memo1.Text := FDQuery1.FieldByName('FULL_NAME').AsString
else
Memo1.Text := '';
FDQuery1.Close;
end;
end.
|
unit MediaStream.Filer.Log;
interface
uses SysUtils,Classes, Windows, SyncObjs, MediaStream.Filer, MediaProcessing.Definitions;
type
TStreamFilerLog = class (TStreamFiler)
private
FLastTimeStamps: array [TMediaType] of int64;
FLastTickCounts: array [TMediaType] of int64;
protected
procedure DoWriteData(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); override;
public
constructor Create; override;
destructor Destroy; override;
procedure Open(const aFileName: string); override;
class function DefaultExt: string; override;
end;
implementation
{ TStreamFilerLog }
constructor TStreamFilerLog.Create;
begin
inherited;
end;
class function TStreamFilerLog.DefaultExt: string;
begin
result:='.log';
end;
destructor TStreamFilerLog.Destroy;
begin
inherited;
end;
procedure TStreamFilerLog.DoWriteData(const aFormat: TMediaStreamDataHeader;
aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal);
var
s: AnsiString;
x: cardinal;
aTickCountStr: string;
begin
inherited;
x:=GetTickCount;
aTickCountStr:=IntToStr(x);
if (FLastTickCounts[aFormat.biMediaType]<>0) and (x>=FLastTickCounts[aFormat.biMediaType]) then
aTickCountStr:=aTickCountStr+Format('(+%d)',[x-FLastTickCounts[aFormat.biMediaType]]);
FLastTickCounts[aFormat.biMediaType]:=x;
s:=Format('%s;%s;%s;%s;%s;%d;%d;%d;%d;%d'#13#10,[
aTickCountStr,
MediaTypeNames[aFormat.biMediaType],
GetStreamTypeName(aFormat.biStreamType),
GetStreamTypeName(aFormat.biStreamSubType),
FrameFlagsToString(aFormat.biFrameFlags),
aFormat.Channel,
aFormat.TimeStamp,
aFormat.TimeKoeff,
aDataSize,
aInfoSize
]);
FStream.Write(PAnsiChar(s)^,Length(s));
end;
procedure TStreamFilerLog.Open(const aFileName: string);
var
s: AnsiString;
begin
inherited;
s:='LocalTime;MediaType;StreamType;StreamSubType;FrameFlags;Channel;Timestamp;TimeKoeff;DataSize;InfoSize'#13#10;
FStream.Write(PAnsiChar(s)^,Length(s));
ZeroMemory(@FLastTimeStamps,sizeof(FLastTimeStamps));
ZeroMemory(@FLastTickCounts,sizeof(FLastTickCounts));
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: Classe de controle do DAV.
The MIT License
Copyright: Copyright (C) 2010 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
@author Albert Eije (T2Ti.COM)
@version 1.0
*******************************************************************************}
unit DAVController;
interface
uses
Classes, SQLExpr, SysUtils, Generics.Collections, DB, DAVVO;
type
TDAVController = class
protected
public
function ListaDAVPeriodo(DataInicio:String; DataFim:String): TObjectList<TDAVVO>;
end;
implementation
uses UDataModule;
var
ConsultaSQL: String;
Query: TSQLQuery;
function TDAVController.ListaDAVPeriodo(DataInicio:String; DataFim:String): TObjectList<TDAVVO>;
var
ListaDAV: TObjectList<TDAVVO>;
DAVCabecalho: TDAVVO;
TotalRegistros: Integer;
begin
ConsultaSQL :=
'select count(*) AS TOTAL from ECF_DAV_CABECALHO where SITUACAO = "E" and DATA_HORA_EMISSAO between ' +
QuotedStr(DataInicio) + ' and ' + QuotedStr(DataFim);
try
try
Query := TSQLQuery.Create(nil);
Query.SQLConnection := FDataModule.Conexao;
Query.sql.Text := ConsultaSQL;
Query.Open;
TotalRegistros := Query.FieldByName('TOTAL').AsInteger;
if TotalRegistros > 0 then
begin
ListaDAV := TObjectList<TDAVVO>.Create;
ConsultaSQL :=
'select * from ECF_DAV_CABECALHO where SITUACAO = "E" and DATA_HORA_EMISSAO between ' +
QuotedStr(DataInicio) + ' and ' + QuotedStr(DataFim);
Query.sql.Text := ConsultaSQL;
Query.Open;
Query.First;
while not Query.Eof do
begin
DAVCabecalho := TDAVVO.Create;
DAVCabecalho.Id := Query.FieldByName('ID').AsInteger;
DAVCabecalho.DataHoraEmissao := Query.FieldByName('DATA_HORA_EMISSAO').AsString;
DAVCabecalho.Valor := Query.FieldByName('VALOR').AsFloat;
ListaDAV.Add(DAVCabecalho);
Query.next;
end;
result := ListaDAV;
end
//caso não exista a relacao, retorna um ponteiro nulo
else
result := nil;
except
result := nil;
end;
finally
Query.Free;
end;
end;
end.
|
unit uHIDControl;
interface
uses Classes, KbdMacro, XMLIntf, uGameDevices, uMidiDevices, Windows;
type
THIDControl = class (TObject)
private
fDevices: TList;
fGameControl: TGameControl;
fMidiControl: TMidiControl;
fKeyboardsCount: Integer;
fMousesCount: Integer;
fGameCount: Integer;
fMidiCount: Integer;
fWindowHandle: HWND; // handle of CfgWindow - where to sent messages
function GetItems(Index: Integer): THIDKeyboard;
procedure DebugLog(pMessage: String);
function GetGameAvailable: Boolean;
function GetCount: Integer;
procedure SetWindowHandle(const Value: HWND);
public
constructor Create;
procedure Init;
function GetDevice(pName: String): THIDKeyboard;
function GetDeviceBySysId(pName: String): THIDKeyboard;
destructor Destroy; Override;
function DetectDevices: Integer;
procedure AssignDefaultNames;
procedure AddGameDevice(pDevice: THIDJoystick);
procedure AddMidiDevice(pDevice: TMIDIDevice);
function LoadFromXml(parent : IXMLNode): Boolean;
procedure SaveToXML(parent : IXMLNode);
property GameAvailable: Boolean read GetGameAvailable;
property Items[Index: Integer]: THIDKeyboard read GetItems;
property Count: Integer read GetCount;
property KeyboardsCount: Integer read fKeyboardsCount;
property MousesCount: Integer read fMousesCount;
property GameCount: Integer read fGameCount;
property MidiCount: Integer read fMidiCount;
property WindowHandle: HWND read fWindowHandle write SetWindowHandle;
end;
implementation
uses SysUtils,
uRawInput,
uGlobals;
procedure THIDControl.AddGameDevice(pDevice: THIDJoystick);
begin
fDevices.Add(pDevice);
Inc(fGameCount);
end;
procedure THIDControl.AddMidiDevice(pDevice: TMIDIDevice);
begin
fDevices.Add(pDevice);
Inc(fMidiCount);
end;
procedure THIDControl.AssignDefaultNames;
var
I: Integer;
lPrefix: String;
lCnt: Integer;
lDev: THIDKeyboard;
begin
for I := 0 to fDevices.Count - 1 do
begin
lDev := THIDKeyboard(fDevices[I]);
if lDev.Name = '' then
begin
if lDev is THIDMouse then
lPrefix := 'Mouse'
else if lDev is TMIDIDevice then
lPrefix := 'Midi'
else if lDev is THIDKeyboard then
lPrefix := 'Keyb'
else if lDev is THIDJoystick then
lPrefix := 'Game'
else
lPrefix := 'Dev';
lCnt := 1;
while (GetDevice(lPrefix + IntToStr(lCnt)) <> nil) do
Inc(lCnt);
lDev.Name := lPrefix + IntToStr(lCnt);
end;
end;
end;
constructor THIDControl.Create;
begin
fDevices := TList.Create;
fGameControl := TGameControl.Create;
fGameControl.OnNewDevice := AddGameDevice;
fMidiControl := TMidiControl.Create;
fMidiControl.OnNewDevice := AddMidiDevice;
fKeyboardsCount := 0;
fMousesCount := 0;
fGameCount := 0;
fMidiCount := 0;
end;
procedure THIDControl.DebugLog(pMessage: String);
begin
Glb.DebugLog(pMessage, 'HID');
end;
destructor THIDControl.Destroy;
begin
fGameControl.Free;
fMidiControl.Free;
fDevices.Free;
inherited;
end;
function THIDControl.DetectDevices: Integer;
var
deviceCount, StrLen, TmpSize: UINT;
//devicesHID: array of RAWINPUTDEVICELIST;
pDevicesHID: PRAWINPUTDEVICELIST;
pDevice: PRAWINPUTDEVICELIST;
pDeviceName: PChar;
I: Integer;
pDeviceInfo: PRID_DEVICE_INFO;
newKbd: THIDKeyboard;
newMou: THIDMouse;
begin
pDeviceInfo := nil;
pDevicesHID := nil;
deviceCount := 0;
if (GetRawInputDeviceList(nil, deviceCount, sizeof(RAWINPUTDEVICELIST)) = 0) then
begin
try
GetMem(pDevicesHID, deviceCount * sizeOf(RAWINPUTDEVICELIST));
GetMem(pDeviceInfo, sizeOf(RID_DEVICE_INFO));
pDevice := pDevicesHID;
GetRawInputDeviceList(pDevicesHID, deviceCount, sizeof(RAWINPUTDEVICELIST));
begin
// process the list
strLen := 0;
for I := 0 to deviceCount - 1 do
begin
if (GetRawInputDeviceInfo(pDevice^.hDevice, RIDI_DEVICENAME,
nil, StrLen) = 0) then
begin
GetMem(pDeviceName, StrLen + 1);
try
GetRawInputDeviceInfo(pDevice^.hDevice, RIDI_DEVICENAME,
pDeviceName, StrLen);
TmpSize := sizeof(RID_DEVICE_INFO);
pDeviceInfo^.cbSize := TmpSize;
GetRawInputDeviceInfo(pDevice^.hDevice, RIDI_DEVICEINFO,
pDeviceInfo, TmpSize);
if (pDeviceInfo^.dwType = RIM_TYPEKEYBOARD) and (strpos(strUpper(pDeviceName), 'ROOT') = nil) then
begin
// add string to log
DebugLog('Found keyboard: ' + IntToStr(pDevice^.hDevice) + ': ' + pDeviceName);
// create kbd object
newKbd := THIDKeyboard.Create(pDeviceName, pDevice^.hDevice);
newKbd.Name := '';
fDevices.Add(newKbd);
Inc(fKeyboardsCount);
end else if (pDeviceInfo^.dwType = RIM_TYPEMOUSE) and (strpos(strUpper(pDeviceName), 'ROOT') = nil) then
begin
// add string to log
DebugLog('Found mouse: ' + IntToStr(pDevice^.hDevice) + ': ' + pDeviceName);
// create kbd object
newMou := THIDMouse.Create(pDeviceName, pDevice^.hDevice);
newMou.Name := '';
fDevices.Add(newMou);
Inc(fMousesCount);
end
finally
FreeMem(pDeviceName);
end;
end;
Inc(pDevice);
end;
end;
finally
//devicesHID := nil;
FreeMem(pDevicesHID);
FreeMem(pDeviceInfo);
end;
end;
Result := deviceCount;
end;
function THIDControl.GetCount: Integer;
begin
Result := fDevices.Count;
end;
function THIDControl.GetDevice(pName: String): THIDKeyboard;
var
I: Integer;
begin
Result := nil;
for I := 0 to fDevices.Count - 1 do
if (THIDKeyboard(fDevices[I]).Name = pName) then
begin
Result := THIDKeyboard(fDevices[I]);
break;
end;
end;
function THIDControl.GetDeviceBySysId(pName: String): THIDKeyboard;
var
I: Integer;
begin
Result := nil;
for I := 0 to fDevices.Count - 1 do
if (THIDKeyboard(fDevices[I]).SystemID = pName) then
begin
Result := THIDKeyboard(fDevices[I]);
break;
end;
end;
function THIDControl.GetGameAvailable: Boolean;
begin
Result := fGameControl.Available;
end;
function THIDControl.GetItems(Index: Integer): THIDKeyboard;
begin
if (Index < 0) or (Index > fDevices.Count - 1) then
Result := nil
else
Result := THIDKeyboard(fDevices[Index]);
end;
procedure THIDControl.Init;
begin
fKeyboardsCount := 0;
fMousesCount := 0;
fGameCount := 0;
fMidiCount := 0;
fGameControl.InitDirectX;
fMidiControl.Init;
end;
function THIDControl.LoadFromXml(parent: IXMLNode): Boolean;
var
parentNode, aNode: IXMLNode;
J :Integer;
tmpSysID, tmpName, lDevType: String;
lDev: THIDKeyboard;
begin
parentNode := parent.ChildNodes.First;
while parentNode <> nil do
begin
lDevType := UpperCase(parentNode.NodeName);
if (lDevType = 'KEYBOARD') or
(lDevType = 'MOUSE') or
(lDevType = 'GAME') then
begin
tmpSysID := '';
tmpName := '';
aNode := parentNode.ChildNodes.First;
while aNode <> nil do
begin
if UpperCase(aNode.NodeName) = 'SYSTEMID' then
tmpSysID := aNode.Text
else if UpperCase(aNode.NodeName) = 'NAME' then
tmpName := aNode.Text;
aNode := aNode.NextSibling;
end;
lDev := GetDeviceBySysId(tmpSysID);
if (lDev <> nil) then
lDev.Name := tmpName
else
begin
// create "dead" keyboard - just loaded, but without real systemId (handle = 0)
if (lDevType = 'KEYBOARD') then
begin
lDev := THIDKeyboard.Create(tmpSysID, 0);
Inc(fKeyboardsCount);
end;
if (lDevType = 'MOUSE') then
begin
lDev := THIDMouse.Create(tmpSysID, 0);
Inc(fMousesCount);
end;
if (lDevType = 'GAME') then
begin
lDev := THIDJoystick.Create(tmpSysID, 0);
Inc(fGameCount);
end;
if (lDev <> nil) then // should be always
begin
lDev.Name := tmpName;
fDevices.Add(lDev);
end;
end;
end;
parentNode := parentNode.NextSibling;
end;
end;
procedure THIDControl.SaveToXML(parent: IXMLNode);
var
kb : THIDKeyboard;
I: Integer;
begin
// save keyboards
for I := 0 to fDevices.Count - 1 do
begin
kb := THIDKeyboard(fDevices[I]);
if (kb is THIDMouse) then
kb.SaveToXml(parent, 'Mouse')
else if (kb is THIDJoystick) then
kb.SaveToXml(parent, 'Game')
else if (kb is TMIDIDevice) then
kb.SaveToXml(parent, 'Midi')
else
kb.SaveToXml(parent, 'Keyboard');
end;
end;
procedure THIDControl.SetWindowHandle(const Value: HWND);
begin
fWindowHandle := Value;
//fMidiControl.WindowHandle := Value;
end;
end.
|
unit BufferInterpreter.NVMe.Intel;
interface
uses
SysUtils,
BufferInterpreter, BufferInterpreter.NVMe, Device.SMART.List;
type
ESmallBufferException = class(ENotImplemented);
TSMARTValueID = (
CriticalWarning,
TemperatureInKelvin,
AvailableSpare,
PercentageUsed,
DataUnitsReadInLBA,
DataUnitsWrittenInLBA,
HostReadCommands,
HostWriteCommands,
ControllerBusyTime,
PowerCycles,
PowerOnHours,
UnsafeShutdowns,
MediaErrors,
NumberOfErrorInformationLogEntries);
TIntelBufferInterpreter = class(TBufferInterpreter)
public
function BufferToIdentifyDeviceResult(
const Buffer: TSmallBuffer): TIdentifyDeviceResult; override;
function BufferToSMARTValueList(
const Buffer: TSmallBuffer): TSMARTValueList; override;
function LargeBufferToIdentifyDeviceResult(
const Buffer: TLargeBuffer): TIdentifyDeviceResult; override;
function LargeBufferToSMARTValueList(
const Buffer: TLargeBuffer): TSMARTValueList; override;
function BufferToCapacityAndLBA(const Buffer: TLargeBuffer):
TIdentifyDeviceResult;
function VendorSpecificSMARTValueList(
const Buffer: TLargeBuffer): TSMARTValueList;
constructor Create;
destructor Destroy; override;
private
NVMeInterpreter: TNVMeBufferInterpreter;
SMARTValueList: TSMARTValueList;
BufferInterpreting: TLargeBuffer;
procedure IfValidSMARTAddToList(CurrentRow: Integer);
function GetCurrentOfRow(CurrentRowStart: Integer): Byte;
function GetIDOfRow(CurrentRowStart: Integer): Byte;
function GetRAWOfRow(CurrentRowStart: Integer): UInt64;
function AdditionalSMARTValueList(const Buffer: TLargeBuffer):
TSMARTValueList;
function TemperatureSMARTValueList(const Buffer: TLargeBuffer):
TSMARTValueList;
procedure AddTemperatureToList(const CurrentRow, StartPoint,
LengthOfValue: Integer);
end;
implementation
{ TNVMeBufferInterpreter }
function TIntelBufferInterpreter.BufferToIdentifyDeviceResult(
const Buffer: TSmallBuffer): TIdentifyDeviceResult;
begin
raise ESmallBufferException.Create('Small Buffer cannot be interpreted in ' +
'Intel NVMe Way');
end;
function TIntelBufferInterpreter.BufferToSMARTValueList(
const Buffer: TSmallBuffer): TSMARTValueList;
begin
raise ESmallBufferException.Create('Small Buffer cannot be interpreted in ' +
'Intel NVMe Way');
end;
constructor TIntelBufferInterpreter.Create;
begin
inherited Create;
NVMeInterpreter := TNVMeBufferInterpreter.Create;
end;
destructor TIntelBufferInterpreter.Destroy;
begin
FreeAndNil(NVMeInterpreter);
inherited;
end;
function TIntelBufferInterpreter.LargeBufferToIdentifyDeviceResult(
const Buffer: TLargeBuffer): TIdentifyDeviceResult;
begin
result := NVMeInterpreter.LargeBufferToIdentifyDeviceResult(Buffer);
end;
function TIntelBufferInterpreter.LargeBufferToSMARTValueList(
const Buffer: TLargeBuffer): TSMARTValueList;
begin
result := NVMeInterpreter.LargeBufferToSMARTValueList(Buffer);
end;
function TIntelBufferInterpreter.VendorSpecificSMARTValueList(
const Buffer: TLargeBuffer): TSMARTValueList;
const
FirstByteOfAdditionalAttribute = $AB;
begin
if Buffer[0] = FirstByteOfAdditionalAttribute then
result := AdditionalSMARTValueList(Buffer)
else
result := TemperatureSMARTValueList(Buffer);
end;
function TIntelBufferInterpreter.AdditionalSMARTValueList(
const Buffer: TLargeBuffer): TSMARTValueList;
const
SMARTValueLength = 12;
var
CurrentRow: Integer;
begin
SMARTValueList := TSMARTValueList.Create;
BufferInterpreting := Buffer;
for CurrentRow := 0 to Length(BufferInterpreting) div SMARTValueLength do
IfValidSMARTAddToList(CurrentRow * SMARTValueLength);
result := SMARTValueList;
end;
function TIntelBufferInterpreter.TemperatureSMARTValueList(
const Buffer: TLargeBuffer): TSMARTValueList;
const
TemperatureValueLength = 8;
CurrentTemperature = 0;
HighestTemperature = 24;
LowestTemperature = 32;
MaximumTemperature = 80;
MinimumTemperature = 96;
TemperatureStart = $40;
var
CurrentRow: Integer;
begin
SMARTValueList := TSMARTValueList.Create;
BufferInterpreting := Buffer;
CurrentRow := TemperatureStart;
AddTemperatureToList(CurrentRow, CurrentTemperature, TemperatureValueLength);
Inc(CurrentRow);
AddTemperatureToList(CurrentRow, HighestTemperature, TemperatureValueLength);
Inc(CurrentRow);
AddTemperatureToList(CurrentRow, LowestTemperature, TemperatureValueLength);
Inc(CurrentRow);
AddTemperatureToList(CurrentRow, MaximumTemperature, TemperatureValueLength);
Inc(CurrentRow);
AddTemperatureToList(CurrentRow, MinimumTemperature, TemperatureValueLength);
result := SMARTValueList;
end;
procedure TIntelBufferInterpreter.AddTemperatureToList(
const CurrentRow, StartPoint, LengthOfValue: Integer);
var
Entry: TSMARTValueEntry;
RAWStart, RAWEnd, CurrentRAW: Integer;
begin
Entry.ID := CurrentRow;
Entry.Current := 0;
Entry.Worst := 0;
Entry.Threshold := 0;
Entry.RAW := 0;
RAWStart := StartPoint;
RAWEnd := RAWStart + LengthOfValue - 1;
for CurrentRAW := RAWEnd downto RAWStart do
begin
Entry.RAW := Entry.RAW shl 8;
Entry.RAW :=
Entry.RAW +
BufferInterpreting[CurrentRAW];
end;
SMARTValueList.Add(Entry);
end;
procedure TIntelBufferInterpreter.IfValidSMARTAddToList(CurrentRow: Integer);
var
SMARTValueEntry: TSMARTValueEntry;
begin
SMARTValueEntry.ID := GetIDOfRow(CurrentRow);
if SMARTValueEntry.ID = 0 then
exit;
SMARTValueEntry.Worst := 0;
SMARTValueEntry.Threshold := 0;
SMARTValueEntry.Current := GetCurrentOfRow(CurrentRow);
SMARTValueEntry.RAW := GetRAWOfRow(CurrentRow);
SMARTValueList.Add(SMARTValueEntry);
end;
function TIntelBufferInterpreter.GetIDOfRow(CurrentRowStart: Integer): Byte;
begin
result := BufferInterpreting[CurrentRowStart];
end;
function TIntelBufferInterpreter.GetCurrentOfRow(CurrentRowStart: Integer): Byte;
const
CurrentValuePosition = 3;
begin
result := BufferInterpreting[CurrentRowStart + CurrentValuePosition];
end;
function TIntelBufferInterpreter.GetRAWOfRow(CurrentRowStart: Integer): UInt64;
const
RAWValueStart = 5;
RAWValueLength = 6;
var
RAWStart, RAWEnd: Integer;
CurrentRAW: Integer;
begin
RAWStart := CurrentRowStart + RAWValueStart;
RAWEnd := RAWStart + RAWValueLength - 1;
result := 0;
for CurrentRAW := RAWEnd downto RAWStart do
begin
result := result shl 8;
result :=
result +
BufferInterpreting[CurrentRAW];
end;
end;
function TIntelBufferInterpreter.BufferToCapacityAndLBA(
const Buffer: TLargeBuffer): TIdentifyDeviceResult;
begin
result := NVMeInterpreter.BufferToCapacityAndLBA(Buffer);
end;
end.
|
unit Security4D.UnitTest;
interface
uses
TestFramework,
System.Classes,
System.SysUtils,
Aspect4D,
Aspect4D.Impl,
Security4D,
Security4D.Impl,
Security4D.Aspect,
Security4D.UnitTest.Authenticator,
Security4D.UnitTest.Credential,
Security4D.UnitTest.Authorizer,
Security4D.UnitTest.Car;
type
TTestSecurity4D = class(TTestCase)
private
fSecurityContext: ISecurityContext;
fAspectContext: IAspectContext;
fCar: TCar;
procedure CheckLoggedIn;
procedure LoginInvalidUser;
procedure CarInsert;
procedure CarUpdate;
procedure CarDelete;
procedure CarView;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestAuthentication;
procedure TestPermissions;
procedure TestNotLogged;
procedure TestAfterLoginSuccessful;
procedure TestAfterLogoutSuccessful;
procedure TestSecurityAspect;
end;
implementation
{ TTestSecurity4D }
procedure TTestSecurity4D.CarDelete;
begin
fCar.Delete;
end;
procedure TTestSecurity4D.CarInsert;
begin
fCar.Insert;
end;
procedure TTestSecurity4D.CarUpdate;
begin
fCar.Update;
end;
procedure TTestSecurity4D.CarView;
begin
fCar.View;
end;
procedure TTestSecurity4D.CheckLoggedIn;
begin
fSecurityContext.CheckLoggedIn;
end;
procedure TTestSecurity4D.LoginInvalidUser;
begin
if fSecurityContext.IsLoggedIn then
fSecurityContext.Logout;
fSecurityContext.Login(TUser.Create('user', TCredential.Create('user', 'user', ROLE_ADMIN)));
end;
procedure TTestSecurity4D.SetUp;
begin
inherited;
fSecurityContext := TSecurityContext.Create;
fSecurityContext.RegisterAuthenticator(TAuthenticator.Create(fSecurityContext));
fSecurityContext.RegisterAuthorizer(TAuthorizer.Create(fSecurityContext));
fAspectContext := TAspectContext.Create;
fAspectContext.Register(TSecurityAspect.Create(fSecurityContext));
fCar := TCar.Create;
fAspectContext.Weaver.Proxify(fCar);
end;
procedure TTestSecurity4D.TearDown;
begin
inherited;
fAspectContext.Weaver.Unproxify(fCar);
fCar.Free;
end;
procedure TTestSecurity4D.TestAfterLoginSuccessful;
var
msg: string;
begin
if fSecurityContext.IsLoggedIn then
fSecurityContext.Logout;
fSecurityContext.OnAfterLoginSuccessful(
procedure
begin
msg := 'Login Successful';
end);
fSecurityContext.Login(TUser.Create('bob', TCredential.Create('bob', 'bob', ROLE_ADMIN)));
CheckEquals('Login Successful', msg);
fSecurityContext.Logout;
fSecurityContext.OnAfterLoginSuccessful(nil);
end;
procedure TTestSecurity4D.TestAfterLogoutSuccessful;
var
msg: string;
begin
if fSecurityContext.IsLoggedIn then
fSecurityContext.Logout;
fSecurityContext.OnAfterLogoutSuccessful(
procedure
begin
msg := 'Logout Successful';
end);
fSecurityContext.Login(TUser.Create('bob', TCredential.Create('bob', 'bob', ROLE_ADMIN)));
fSecurityContext.Logout;
CheckEquals('Logout Successful', msg);
fSecurityContext.OnAfterLoginSuccessful(nil);
end;
procedure TTestSecurity4D.TestAuthentication;
begin
if fSecurityContext.IsLoggedIn then
fSecurityContext.Logout;
fSecurityContext.Login(TUser.Create('bob', TCredential.Create('bob', 'bob', ROLE_ADMIN)));
CheckTrue(fSecurityContext.IsLoggedIn);
fSecurityContext.CheckLoggedIn;
fSecurityContext.Logout;
CheckFalse(fSecurityContext.IsLoggedIn);
fSecurityContext.Login(TUser.Create('jeff', TCredential.Create('jeff', 'jeff', ROLE_MANAGER)));
CheckTrue(fSecurityContext.IsLoggedIn);
fSecurityContext.CheckLoggedIn;
fSecurityContext.Logout;
CheckFalse(fSecurityContext.IsLoggedIn);
fSecurityContext.Login(TUser.Create('nick', TCredential.Create('nick', 'nick', ROLE_NORMAL)));
CheckTrue(fSecurityContext.IsLoggedIn);
fSecurityContext.CheckLoggedIn;
fSecurityContext.Logout;
CheckFalse(fSecurityContext.IsLoggedIn);
CheckException(LoginInvalidUser, EAuthorizationException);
end;
procedure TTestSecurity4D.TestSecurityAspect;
begin
if fSecurityContext.IsLoggedIn then
fSecurityContext.Logout;
fSecurityContext.Login(TUser.Create('nick', TCredential.Create('nick', 'nick', ROLE_NORMAL)));
CheckException(CarInsert, EAuthorizationException);
CheckException(CarUpdate, EAuthorizationException);
CheckException(CarDelete, EAuthorizationException);
CarView();
fSecurityContext.Logout;
fSecurityContext.Login(TUser.Create('bob', TCredential.Create('bob', 'bob', ROLE_ADMIN)));
CarInsert();
CarUpdate();
CarDelete();
CarView();
end;
procedure TTestSecurity4D.TestNotLogged;
begin
if fSecurityContext.IsLoggedIn then
fSecurityContext.Logout;
CheckException(CheckLoggedIn, EAuthorizationException);
end;
procedure TTestSecurity4D.TestPermissions;
begin
if fSecurityContext.IsLoggedIn then
fSecurityContext.Logout;
fSecurityContext.Login(TUser.Create('bob', TCredential.Create('bob', 'bob', ROLE_ADMIN)));
CheckTrue(fSecurityContext.IsLoggedIn);
fSecurityContext.CheckLoggedIn;
CheckTrue(fSecurityContext.HasRole(ROLE_ADMIN));
CheckTrue(fSecurityContext.HasPermission('Car', 'Insert'));
CheckTrue(fSecurityContext.HasPermission('Car', 'Update'));
CheckTrue(fSecurityContext.HasPermission('Car', 'Delete'));
CheckTrue(fSecurityContext.HasPermission('Car', 'View'));
fSecurityContext.Logout;
CheckFalse(fSecurityContext.IsLoggedIn);
fSecurityContext.Login(TUser.Create('jeff', TCredential.Create('jeff', 'jeff', ROLE_MANAGER)));
CheckTrue(fSecurityContext.IsLoggedIn);
fSecurityContext.CheckLoggedIn;
CheckTrue(fSecurityContext.HasRole(ROLE_MANAGER));
CheckTrue(fSecurityContext.HasPermission('Car', 'Insert'));
CheckTrue(fSecurityContext.HasPermission('Car', 'Update'));
CheckTrue(fSecurityContext.HasPermission('Car', 'Delete'));
CheckTrue(fSecurityContext.HasPermission('Car', 'View'));
fSecurityContext.Logout;
CheckFalse(fSecurityContext.IsLoggedIn);
fSecurityContext.Login(TUser.Create('nick', TCredential.Create('nick', 'nick', ROLE_NORMAL)));
CheckTrue(fSecurityContext.IsLoggedIn);
fSecurityContext.CheckLoggedIn;
CheckTrue(fSecurityContext.HasRole(ROLE_NORMAL));
CheckFalse(fSecurityContext.HasPermission('Car', 'Insert'));
CheckFalse(fSecurityContext.HasPermission('Car', 'Update'));
CheckFalse(fSecurityContext.HasPermission('Car', 'Delete'));
CheckTrue(fSecurityContext.HasPermission('Car', 'View'));
fSecurityContext.Logout;
CheckFalse(fSecurityContext.IsLoggedIn);
end;
initialization
RegisterTest(TTestSecurity4D.Suite);
end.
|
(*******************************************************************************
Author:
-> Jean-Pierre LESUEUR (@DarkCoderSc)
https://github.com/DarkCoderSc
https://gist.github.com/DarkCoderSc
https://www.phrozen.io/
License:
-> MIT
*******************************************************************************)
unit UntProcess;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.Menus;
type
TFrmProcess = class(TForm)
lstprocess: TListView;
lstmodules: TListView;
Splitter1: TSplitter;
popmodules: TPopupMenu;
ShowDLLExports1: TMenuItem;
procedure FormShow(Sender: TObject);
procedure lstprocessClick(Sender: TObject);
procedure lstprocessCustomDrawItem(Sender: TCustomListView; Item: TListItem;
State: TCustomDrawState; var DefaultDraw: Boolean);
procedure lstmodulesCustomDrawItem(Sender: TCustomListView; Item: TListItem;
State: TCustomDrawState; var DefaultDraw: Boolean);
procedure lstmodulesDblClick(Sender: TObject);
procedure ShowDLLExports1Click(Sender: TObject);
private
{ Private declarations }
procedure RefreshProcessList();
procedure RefreshProcessModules(AProcessId : Cardinal);
procedure LoadSelectedModule();
public
{ Public declarations }
end;
var
FrmProcess: TFrmProcess;
implementation
{$R *.dfm}
uses tlHelp32, Generics.Collections, UntEnumModules, UntMain;
{
https://www.phrozen.io/snippets/2020/03/enum-process-method-1-delphi/
}
function EnumProcess() : TDictionary<Integer {Process Id}, String {Process Name}>;
var ASnap : THandle;
AProcessEntry : TProcessEntry32;
AProcessName : String;
procedure AppendEntry();
begin
result.Add(AProcessEntry.th32ProcessID, AProcessEntry.szExeFile);
end;
begin
result := TDictionary<Integer, String>.Create();
///
ASnap := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if ASnap = INVALID_HANDLE_VALUE then
Exit();
try
ZeroMemory(@AProcessEntry, SizeOf(TProcessEntry32));
///
AProcessEntry.dwSize := SizeOf(TProcessEntry32);
if NOT Process32First(ASnap, AProcessEntry) then
Exit();
AppendEntry();
while True do begin
ZeroMemory(@AProcessEntry, SizeOf(TProcessEntry32));
///
AProcessEntry.dwSize := SizeOf(TProcessEntry32);
if NOT Process32Next(ASnap, AProcessEntry) then
break;
AppendEntry();
end;
finally
CloseHandle(ASnap);
end;
end;
procedure TFrmProcess.FormShow(Sender: TObject);
begin
RefreshProcessList();
end;
procedure TFrmProcess.lstmodulesCustomDrawItem(Sender: TCustomListView;
Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean);
begin
if Odd(Item.Index) then
Sender.Canvas.Brush.Color := RGB(245, 245, 245);
end;
procedure TFrmProcess.LoadSelectedModule();
begin
if self.lstmodules.selected <> nil then begin
FrmMain.OpenDDL(self.lstmodules.Selected.Caption);
Close();
end;
end;
procedure TFrmProcess.lstmodulesDblClick(Sender: TObject);
begin
LoadSelectedModule();
end;
procedure TFrmProcess.lstprocessClick(Sender: TObject);
var AProcessId : Integer;
begin
if self.lstprocess.Selected <> nil then begin
if TryStrToInt(self.lstprocess.Selected.SubItems[0], AProcessId) then
RefreshProcessModules(AProcessId);
end;
end;
procedure TFrmProcess.lstprocessCustomDrawItem(Sender: TCustomListView;
Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean);
begin
if Odd(Item.Index) then
Sender.Canvas.Brush.Color := RGB(245, 245, 245);
end;
procedure TFrmProcess.RefreshProcessList();
var AList : TDictionary<Integer, String>;
AItem : TListItem;
AProcessId : Cardinal;
AProcessName : String;
begin
self.lstprocess.Clear();
///
AList := EnumProcess();
try
for AProcessId in AList.Keys do begin
if NOT AList.TryGetValue(AProcessId, AProcessName) then
continue;
///
AItem := self.lstprocess.Items.Add;
AItem.Caption := AProcessName;
AItem.SubItems.Add(IntToStr(AProcessId));
end;
finally
if Assigned(AList) then
FreeAndNil(AList);
end;
end;
procedure TFrmProcess.RefreshProcessModules(AProcessId : Cardinal);
var AList : TList<TModuleEntry32>;
AModuleEntry : TModuleEntry32;
i : Integer;
AListItem : TListItem;
begin
AList := EnumModules(AProcessId);
self.lstmodules.Clear;
for i := 0 to AList.Count -1 do begin
AModuleEntry := AList.Items[i];
AListItem := self.lstmodules.Items.Add;
AListItem.Caption := AModuleEntry.szExePath;
end;
end;
procedure TFrmProcess.ShowDLLExports1Click(Sender: TObject);
begin
LoadSelectedModule();
end;
end.
|
{-------------------------------------------------------------------------------
// EasyComponents For Delphi 7
// 一轩软研第三方开发包
// @Copyright 2010 hehf
// ------------------------------------
//
// 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何
// 人不得外泄,否则后果自负.
//
// 使用权限以及相关解释请联系何海锋
//
//
// 网站地址:http://www.YiXuan-SoftWare.com
// 电子邮件:hehaifeng1984@126.com
// YiXuan-SoftWare@hotmail.com
// QQ :383530895
// MSN :YiXuan-SoftWare@hotmail.com
//------------------------------------------------------------------------------
//单元说明:
// 系统工作平台的资源管理
//主要实现:
主要生成各模块的权限资源、和多语言文件
//-----------------------------------------------------------------------------}
unit untEasyPlateResourceManage;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, untEasyPlateBaseForm, TypInfo, DB, DBClient, ImgList,
untEasyToolBar, untEasyToolBarStylers, untEasyPageControl, ExtCtrls,
untEasyGroupBox, StdCtrls, untEasyMemo, ComCtrls, untEasyTreeView, Menus,
untEasyMenus, untEasyMenuStylers;
type
TScreenForm = class
private
FGUID,
FFormName: string;
FCaption : string;
FFormIndex: Integer;
FFormCaption: string;
function GetFormIndex: Integer;
function GetFormName: string;
function GetGUID: string;
procedure SetFormIndex(const Value: Integer);
procedure SetFormName(const Value: string);
procedure SetGUID(const Value: string);
procedure SetFormCaption(const Value: string);
function GetFormCaption: string;
public
property GUID: string read GetGUID write SetGUID;
property FormCaption: string read GetFormCaption write SetFormCaption;
property FormName: string read GetFormName write SetFormName;
property FormIndex: Integer read GetFormIndex write SetFormIndex;
end;
TfrmEasyPlateResourceManage = class(TfrmEasyPlateBaseForm)
dkpDBForm: TEasyDockPanel;
tlbDBForm: TEasyToolBar;
btnLang: TEasyToolBarButton;
btnResource: TEasyToolBarButton;
btnExit: TEasyToolBarButton;
pnlContainer: TEasyPanel;
tlbStyDBForm: TEasyToolBarOfficeStyler;
imgTlbDBForm: TImageList;
cdsMain: TClientDataSet;
dsMain: TDataSource;
EasyPanel1: TEasyPanel;
Splitter1: TSplitter;
EasyPanel2: TEasyPanel;
tvResManage: TEasyTreeView;
mmResult: TEasyMemo;
EasyPopupMenu1: TEasyPopupMenu;
EasyMenuOfficeStyler1: TEasyMenuOfficeStyler;
pmShowHint: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure btnExitClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure pmShowHintClick(Sender: TObject);
procedure btnLangClick(Sender: TObject);
procedure btnResourceClick(Sender: TObject);
private
{ Private declarations }
FScreenFormList: TList;
procedure InitTvResManage;
procedure ShowFormCompsInfo_Lang(AForm: TForm);
procedure ShowFormCompsInfo_Res(AForm: TForm);
function FindResForm(ACaption: string): TForm;
public
{ Public declarations }
end;
var
frmEasyPlateResourceManage: TfrmEasyPlateResourceManage;
implementation
{$R *.dfm}
uses
untEasyUtilMethod;
procedure TfrmEasyPlateResourceManage.FormCreate(Sender: TObject);
begin
inherited;
FormId := '{BF3F23E6-A928-4F85-8805-437FF90211A7}';
FScreenFormList := TList.Create;
end;
procedure TfrmEasyPlateResourceManage.btnExitClick(Sender: TObject);
begin
inherited;
Close;
end;
procedure TfrmEasyPlateResourceManage.InitTvResManage;
var
I: Integer;
AScreenForm: TScreenForm;
ATmpTreeNode: TTreeNode;
begin
for I := 0 to Screen.FormCount - 1 do
begin
AScreenForm := TScreenForm.Create;
with AScreenForm do
begin
GUID := TfrmEasyPlateBaseForm(Screen.Forms[I]).FormId;
FormName := TfrmEasyPlateBaseForm(Screen.Forms[I]).Name;
FormIndex := I;
FormCaption := TfrmEasyPlateBaseForm(Screen.Forms[I]).Caption;
ATmpTreeNode := tvResManage.Items.AddChild(nil, FormCaption);
ATmpTreeNode.Data := AScreenForm;
end;
end;
end;
{ TScreenForm }
function TScreenForm.GetFormCaption: string;
begin
Result := FFormCaption;
end;
function TScreenForm.GetFormIndex: Integer;
begin
Result := FFormIndex;
end;
function TScreenForm.GetFormName: string;
begin
Result := FFormName;
end;
function TScreenForm.GetGUID: string;
begin
Result := FGUID;
end;
procedure TScreenForm.SetFormCaption(const Value: string);
begin
FFormCaption := Value;
end;
procedure TScreenForm.SetFormIndex(const Value: Integer);
begin
FFormIndex := Value;
end;
procedure TScreenForm.SetFormName(const Value: string);
begin
FFormName := Value;
end;
procedure TScreenForm.SetGUID(const Value: string);
begin
FGUID := Value;
end;
procedure TfrmEasyPlateResourceManage.FormDestroy(Sender: TObject);
var
I: Integer;
begin
for I := 0 to FScreenFormList.Count - 1 do
begin
TScreenForm(FScreenFormList.Items[I]).Free;
end;
FScreenFormList.Clear;
inherited;
end;
procedure TfrmEasyPlateResourceManage.ShowFormCompsInfo_Lang(AForm: TForm);
var
I: Integer;
begin
if AForm = nil then Exit;
mmResult.Lines.Clear;
mmResult.Lines.Add(TfrmEasyPlateBaseForm(AForm).Name +
TfrmEasyPlateBaseForm(AForm).FormId);
for I := 0 to AForm.ComponentCount - 1 do
begin
if GetPropInfo(AForm.Components[I], 'Caption') <> nil then
mmResult.Lines.Add(AForm.Components[I].Name +'.Caption='+
GetPropValue(AForm.Components[I], 'Caption'))
else
if GetPropInfo(AForm.Components[I], 'Text') <> nil then
mmResult.Lines.Add(AForm.Components[I].Name +'.Text='+
GetPropValue(AForm.Components[I], 'Text'));
if pmShowHint.Checked then
begin
if GetPropInfo(AForm.Components[I], 'Hint') <> nil then
mmResult.Lines.Add(AForm.Components[I].Name +'.Hint='+
GetPropValue(AForm.Components[I], 'Hint'));
end;
end;
end;
procedure TfrmEasyPlateResourceManage.ShowFormCompsInfo_Res(AForm: TForm);
var
I : Integer;
ATmpGUID,
ARootSQL,
ASQL : string;
begin
if AForm = nil then Exit;
mmResult.Lines.Clear;
ATmpGUID := TfrmEasyPlateBaseForm(AForm).FormId;
mmResult.Lines.Add(TfrmEasyPlateBaseForm(AForm).Name + ATmpGUID);
ASQL := ' INSERT INTO sysResource([GUID], ResourceGUID, sResourceID, sResourceName,'
+ 'sParentResourceGUID, iOrder) VALUES (';
ARootSQL := ASQL + QuotedStr(GenerateGUID) + ','
+ QuotedStr(ATmpGUID) + ','
+ QuotedStr(AForm.Name) + ','
+ QuotedStr(AForm.Caption) + ','
+ QuotedStr('{00000000-0000-0000-0000-000000000003}') + ', 0);';
mmResult.Lines.Add(ARootSQL);
for I := 0 to AForm.ComponentCount - 1 do
begin
if (AForm.Components[I] is TEasyToolBarButton) then
begin
ASQL := ' INSERT INTO sysResource ([GUID], ResourceGUID, sResourceID, sResourceName,'
+ 'sParentResourceGUID, iOrder) VALUES (';
ASQL := ASQL + QuotedStr(GenerateGUID) + ',';
ASQL := ASQL + QuotedStr(GenerateGUID) + ',';
ASQL := ASQL + QuotedStr(AForm.Components[I].Name) + ',';
// if GetPropInfo(AForm.Components[I], 'Caption') <> nil then
ASQL := ASQL + QuotedStr(GetPropValue(AForm.Components[I], 'Caption')) + ',';
// else
// if GetPropInfo(AForm.Components[I], 'Text') <> nil then
// ASQL := ASQL + QuotedStr(GetPropValue(AForm.Components[I], 'Text')) + ','
// else
ASQL := ASQL + QuotedStr(ATmpGUID) + ', 0);';
mmResult.Lines.Add(ASQL);
end;
end;
end;
procedure TfrmEasyPlateResourceManage.FormShow(Sender: TObject);
begin
inherited;
InitTvResManage;
pmShowHint.Checked := True;
end;
function TfrmEasyPlateResourceManage.FindResForm(ACaption: string): TForm;
var
I: Integer;
begin
Result := nil;
for I := 0 to Screen.FormCount - 1 do
begin
if Screen.Forms[I].Caption = ACaption then
begin
Result := Screen.Forms[I];
Break;
end;
end;
end;
procedure TfrmEasyPlateResourceManage.pmShowHintClick(Sender: TObject);
begin
inherited;
pmShowHint.Checked := not pmShowHint.Checked;
end;
procedure TfrmEasyPlateResourceManage.btnLangClick(Sender: TObject);
begin
inherited;
if tvResManage.Selected <> nil then
ShowFormCompsInfo_Lang(FindResForm(TScreenForm(tvResManage.Selected.Data).FormCaption));
end;
procedure TfrmEasyPlateResourceManage.btnResourceClick(Sender: TObject);
begin
inherited;
if tvResManage.Selected <> nil then
ShowFormCompsInfo_Res(FindResForm(TScreenForm(tvResManage.Selected.Data).FormCaption));
end;
end.
|
unit ArticleWebDTOU;
interface
type TArticleWebDTO=class
private
Flastprixachat: double;
Flastqteachat: double;
Fqtestock: double;
Fidarticle: string;
Fdesarticle: string;
Fprixvente: double;
Fuart: string;
procedure Setdesarticle(const Value: string);
procedure Setidarticle(const Value: string);
procedure Setlastprixachat(const Value: double);
procedure Setlastqteachat(const Value: double);
procedure Setprixvente(const Value: double);
procedure Setqtestock(const Value: double);
procedure Setuart(const Value: string);
public
property lastprixachat: double read Flastprixachat write Setlastprixachat;
property lastqteachat: double read Flastqteachat write Setlastqteachat;
property qtestock: double read Fqtestock write Setqtestock;
property idarticle: string read Fidarticle write Setidarticle;
property desarticle: string read Fdesarticle write Setdesarticle;
property prixvente: double read Fprixvente write Setprixvente;
property uart: string read Fuart write Setuart;
constructor create (id:string); overload;
constructor create();overload;
end;
implementation
{ TArticleWebDTO }
constructor TArticleWebDTO.create(id: string);
begin
Self.idarticle:=id;
end;
constructor TArticleWebDTO.create;
begin
end;
procedure TArticleWebDTO.Setdesarticle(const Value: string);
begin
Fdesarticle := Value;
end;
procedure TArticleWebDTO.Setidarticle(const Value: string);
begin
Fidarticle := Value;
end;
procedure TArticleWebDTO.Setlastprixachat(const Value: double);
begin
Flastprixachat := Value;
end;
procedure TArticleWebDTO.Setlastqteachat(const Value: double);
begin
Flastqteachat := Value;
end;
procedure TArticleWebDTO.Setprixvente(const Value: double);
begin
Fprixvente := Value;
end;
procedure TArticleWebDTO.Setqtestock(const Value: double);
begin
Fqtestock := Value;
end;
procedure TArticleWebDTO.Setuart(const Value: string);
begin
Fuart := Value;
end;
end.
|
unit SortList;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses SysUtils, Classes, RTLConsts;
type
TSortList = class(TList)
FSorted: Boolean;
FDuplicates: TDuplicates;
procedure SetSorted(Value: Boolean);
protected
function CompareItems(const I1, I2: Pointer): Integer; virtual; abstract;
public
function Add(Item: Pointer): Integer; overload;
function Find(const Item: Pointer; var Index: Integer): Boolean; virtual;
procedure QuickSort(L, R: Integer);
function IndexOf(Item: Pointer): Integer; overload;
property Duplicates: TDuplicates read FDuplicates write FDuplicates;
property Sorted: Boolean read FSorted write SetSorted;
end;
implementation
{ TSortList }
function TSortList.Add(Item: Pointer): Integer;
begin
if not Sorted then Result := inherited IndexOf(Item) else
begin
if Find(Item, Result) then
case Duplicates of
dupIgnore: Exit;
dupError: Error(SDuplicateItem, Integer(Item));
end;
Insert(Result,Item)
end;
end;
function TSortList.Find(const Item: Pointer; var Index: Integer): Boolean;
var
L, H, I, C: Integer;
begin
Result := False;
L := 0;
H := Count - 1;
while L <= H do
begin
I := (L + H) shr 1;
C := CompareItems(Items[I], Item);
if C < 0 then L := I + 1 else
begin
H := I - 1;
if C = 0 then
begin
Result := True;
if Duplicates <> dupAccept then L := I;
end;
end;
end;
Index := L;
end;
function TSortList.IndexOf(Item: Pointer): Integer;
begin
if not Sorted then Result := inherited IndexOf(Item) else
if not Find(Item, Result) then Result := -1;
end;
procedure TSortList.SetSorted(Value: Boolean);
begin
if FSorted <> Value then
begin
if Value and (Count > 0) then QuickSort(0,Count-1);
FSorted := Value;
end;
end;
procedure TSortList.QuickSort(L, R: Integer);
var
I, J, P: Integer;
T : Pointer;
begin
repeat
I := L;
J := R;
P := (L + R) shr 1;
repeat
while CompareItems(Items[I], Items[P]) < 0 do Inc(I);
while CompareItems(Items[J], Items[P]) > 0 do Dec(J);
if I <= J then
begin
T := Items[I];
Items[I] := Items[J];
Items[J] := T;
if P = I then
P := J
else if P = J then
P := I;
Inc(I);
Dec(J);
end;
until I > J;
if L < J then QuickSort(L, J);
L := I;
until I >= R;
end;
end.
|
unit ufrmMain;
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.Edit, FMX.Layouts, FMX.Controls.Presentation, FMX.ScrollBox,
FMX.Memo, System.SyncObjs, ncSources;
type
TfrmMain = class(TForm)
memLog: TMemo;
ltMain: TLayout;
edtText: TEdit;
btnSend: TButton;
Client: TncClientSource;
tmrUpdateLog: TTimer;
edtClientName: TEdit;
ToolBar1: TToolBar;
btnActivateClient: TButton;
edtHost: TEdit;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnSendClick(Sender: TObject);
procedure tmrUpdateLogTimer(Sender: TObject);
function ClientHandleCommand(Sender: TObject; aLine: TncLine; aCmd: Integer;
const aData: TArray<System.Byte>; aRequiresResult: Boolean;
const aSenderComponent, aReceiverComponent: string): TArray<System.Byte>;
procedure edtTextEnter(Sender: TObject);
procedure edtTextExit(Sender: TObject);
procedure btnActivateClientClick(Sender: TObject);
procedure ClientConnected(Sender: TObject; aLine: TncLine);
procedure ClientDisconnected(Sender: TObject; aLine: TncLine);
procedure ClientReconnected(Sender: TObject; aLine: TncLine);
procedure edtHostChange(Sender: TObject);
private
LogLock: TCriticalSection;
LogLines, LogLinesCopy: TStringList;
public
procedure Log(aStr: string);
end;
var
frmMain: TfrmMain;
implementation
{$R *.fmx}
procedure TfrmMain.FormCreate(Sender: TObject);
begin
LogLock := TCriticalSection.Create;
LogLines := TStringList.Create;
LogLinesCopy := TStringList.Create;
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
Client.Active := False;
LogLinesCopy.Free;
LogLines.Free;
LogLock.Free;
end;
procedure TfrmMain.Log(aStr: string);
begin
// This is thread safe
LogLock.Acquire;
try
LogLines.Add (aStr);
finally
LogLock.Release;
end;
end;
procedure TfrmMain.tmrUpdateLogTimer(Sender: TObject);
var
i: Integer;
begin
// Update the memLog from LogLines
LogLock.Acquire;
try
LogLinesCopy.Assign(LogLines);
LogLines.Clear;
finally
LogLock.Release;
end;
for i := 0 to LogLinesCopy.Count - 1 do
begin
memLog.Lines.Add(LogLinesCopy.Strings[i]);
memLog.SelStart := Length(memLog.Text);
end;
LogLinesCopy.Clear;
end;
procedure TfrmMain.btnActivateClientClick(Sender: TObject);
begin
Client.Active := not Client.Active;
end;
procedure TfrmMain.btnSendClick(Sender: TObject);
begin
Client.ExecCommand(0, BytesOf (edtClientName.Text + ': ' + edtText.Text));
edtText.Text := '';
end;
procedure TfrmMain.edtHostChange(Sender: TObject);
begin
if not Client.Active then
Client.Host := edtHost.Text;
end;
procedure TfrmMain.edtTextEnter(Sender: TObject);
begin
btnSend.Default := True;
end;
procedure TfrmMain.edtTextExit(Sender: TObject);
begin
btnSend.Default := False;
end;
procedure TfrmMain.ClientConnected(Sender: TObject; aLine: TncLine);
begin
Log ('Client connected to peer: ' + aLine.PeerIP);
TThread.Synchronize(nil,
procedure
begin
btnActivateClient.Text := 'Deactivate client';
end);
end;
procedure TfrmMain.ClientDisconnected(Sender: TObject; aLine: TncLine);
begin
Log ('Client disconnected from peer: ' + aLine.PeerIP);
TThread.Synchronize(nil,
procedure
begin
btnActivateClient.Text := 'Activate client';
end);
end;
procedure TfrmMain.ClientReconnected(Sender: TObject; aLine: TncLine);
begin
Log ('Client was reconnected to peer: ' + aLine.PeerIP);
end;
function TfrmMain.ClientHandleCommand(Sender: TObject; aLine: TncLine;
aCmd: Integer; const aData: TArray<System.Byte>; aRequiresResult: Boolean;
const aSenderComponent, aReceiverComponent: string): TArray<System.Byte>;
begin
Log (Stringof (aData));
end;
end.
|
{*******************************************************}
{ }
{ Delphi LiveBindings Framework }
{ }
{ Copyright(c) 2011-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit BindCompDesigners;
interface
uses System.Classes, System.SysUtils, Data.Bind.Components, ColnEdit,
Generics.Collections, BindCompDsnResStrs, System.Bindings.EvalProtocol;
procedure Register;
type
TBindCompDesigner = class(TInterfacedObject, IBindCompDesigner)
private
protected
function FormatDisplayText(ABindComponent: TCommonBindComponent;
const AFormatString: string): string; overload;
function FormatDisplayText(ABindComponent: TCommonBindComponent;
const AFormatString: string; const ASourceMemberName: string): string; overload;
function FormatDisplayText(ABindComponent: TCommonBindComponent;
const AFormatString: string; ACount: Integer): string; overload;
function IsReadOnly(ABindComp: TContainedBindComponent; AExpression: TBindCompDesignExpression): Boolean; overload; virtual;
function IsReadOnly(ABindComp: TContainedBindComponent; AItem: TCollectionItem): Boolean; overload; virtual;
function IsReadOnly(ABindComp: TContainedBindComponent; ACollection: TCollection): Boolean; overload; virtual;
function GetDescription(ADataBinding: TContainedBindComponent): string; virtual;
function CanBindComponent(ADataBindingClass: TContainedBindCompClass; AComponent: TComponent;
ADesigner: IInterface): Boolean; virtual;
function BindsComponent(ADataBinding: TContainedBindComponent; AComponent: TComponent): Boolean; virtual;
function BindsComponentPropertyName(ADataBinding: TContainedBindComponent; const APropertyName: string): Boolean; virtual;
function GetExpressions(ADataBinding: TContainedBindComponent; out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>; virtual;
function GetExpressionCollections(ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>; virtual;
end;
TReadOnlyBindCompDelegateDesigner = class(TBindCompDesigner)
protected
procedure DeleteEmptyCollections(AList: TList<TBindCompDesignExpressionCollection>);
function IsReadOnly(ABindComp: TContainedBindComponent; AExpression: TBindCompDesignExpression): Boolean; overload; override;
function IsReadOnly(ABindComp: TContainedBindComponent; AItem: TCollectionItem): Boolean; overload; override;
function IsReadOnly(ABindComp: TContainedBindComponent; ACollection: TCollection): Boolean; overload; override;
end;
TBindCompDelegateDesigner = class(TReadOnlyBindCompDelegateDesigner)
private
function TryGetDelegates(ADataBinding: TContainedBindComponent;
out ADelegateComponent: TContainedBindComponent;
out ADelegateDesigner: IBindCompDesigner): Boolean;
protected
function GetDelegate(ADataBinding: TContainedBindComponent): TContainedBindComponent; virtual; abstract;
function GetDescription(ADataBinding: TContainedBindComponent): string; override;
function GetExpressions(ADataBinding: TContainedBindComponent; out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>; override;
function GetExpressionCollections(ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>; override;
end;
TBindCompDelegatesDesigner = class(TReadOnlyBindCompDelegateDesigner)
private
function TryGetDelegates(ADataBinding: TContainedBindComponent;
out ADelegateComponents: TArray<TContainedBindComponent>;
out ADelegateDesigners: TArray<IBindCompDesigner>): Boolean;
protected
function GetDelegates(ADataBinding: TContainedBindComponent): TArray<TContainedBindComponent>; virtual; abstract;
function GetDescription(ADataBinding: TContainedBindComponent): string; override;
function GetExpressions(ADataBinding: TContainedBindComponent; out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>; override;
function GetExpressionCollections(ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>; override;
end;
TBindDBFieldLinkDesigner = class(TBindCompDelegateDesigner)
protected
function GetDelegate(ADataBinding: TContainedBindComponent): TContainedBindComponent; override;
end;
TBindDBFieldLinkDesigner_NoParse = class(TBindDBFieldLinkDesigner)
protected
function GetExpressionCollections(ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>; override;
end;
TCommonBindComponentDesigner = class(TBindCompDesigner)
private
protected
// function FormatDisplayText(ABindComponent: TCommonBindComponent;
// const AFormatString: string): string; overload;
// function FormatDisplayText(ABindComponent: TCommonBindComponent;
// const AFormatString: string; const ASourceMemberName: string): string; overload;
// function FormatDisplayText(ABindComponent: TCommonBindComponent;
// const AFormatString: string; ACount: Integer): string; overload;
procedure ExecuteAssignToControlExpression(ABindComp: TCommonBindComponent;
const AControlExpression, ASourceExpression: string;
ACallback: TProc<IValue>; AType: TBindCompExpressionType = exprUnspecified);
procedure ExecuteAssignToSourceExpression(ABindComp: TCommonBindComponent;
const AControlExpression, ASourceExpression: string;
ACallback: TProc<IValue>; AType: TBindCompExpressionType = exprUnspecified);
function ControlScopeName(ABindComp: TCommonBindComponent): string;
function SourceScopeName(ABindComp: TCommonBindComponent): string;
function SourceMemberScopeName(ABindComp: TCommonBindComponent): string;
end;
TBindLinkDesigner = class(TCommonBindComponentDesigner)
protected
function GetDescription(ADataBinding: TContainedBindComponent): string; override;
function GetExpressions(ADataBinding: TContainedBindComponent; out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>; override;
function GetExpressionCollections(ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>; override;
end;
TQuickBindingDesigner = class(TBindCompDelegateDesigner)
protected
function GetDelegate(ADataBinding: TContainedBindComponent): TContainedBindComponent; override;
end;
TQuickBindingDesignerMultiDelegates = class(TBindCompDelegatesDesigner)
protected
function GetDelegates(ADataBinding: TContainedBindComponent): TArray<TContainedBindComponent>; override;
end;
TLinkControlToFieldDesigner = class(TQuickBindingDesigner)
end;
TLinkFillControlToFieldDesigner = class(TQuickBindingDesignerMultiDelegates)
end;
TLinkControlToPropertyDesigner = class(TQuickBindingDesigner)
protected
function GetDescription(ADataBinding: TContainedBindComponent): string; override;
end;
TLinkFillControlToPropertyDesigner = class(TQuickBindingDesignerMultiDelegates)
end;
TLinkListControlToFieldDesigner = class(TQuickBindingDesigner)
end;
TLinkPropertyToFieldDesigner = class(TQuickBindingDesigner)
end;
TBindExpressionDesigner = class(TCommonBindComponentDesigner)
protected
function GetDescription(ADataBinding: TContainedBindComponent): string; override;
function GetExpressions(ADataBinding: TContainedBindComponent; out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>; override;
function GetExpressionCollections(ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>; override;
end;
TBindExprItemsDesigner = class(TCommonBindComponentDesigner)
protected
function GetDescription(ADataBinding: TContainedBindComponent): string; override;
function GetExpressions(ADataBinding: TContainedBindComponent; out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>; override;
function GetExpressionCollections(ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>; override;
end;
TBindListDesigner = class(TCommonBindComponentDesigner)
private
protected
// function FormatDisplayText(ABindList: TCustomBindList; const AFormatString: string): string;
procedure AddExpressions(ABindComp: TCustomBindList;
const AControlScopeName, ASourceScopeName, ASourceMemberScopeName: string;
AList: TList<TBindCompDesignExpression>); virtual;
procedure AddExpressionCollections(ABindList: TCustomBindList;
AList: TList<TBindCompDesignExpressionCollection>); virtual;
{ IBindCompDesigner }
function GetDescription(ADataBinding: TContainedBindComponent): string; override;
function GetExpressions(ADataBinding: TContainedBindComponent; out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>; override;
function GetExpressionCollections(ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>; override;
end;
TBindListLinkDesigner = class(TBindListDesigner)
protected
procedure AddExpressions(ABindComp: TCustomBindList;
const AControlScopeName, ASourceScopeName, ASourceMemberScopeName: string;
AList: TList<TBindCompDesignExpression>); override;
procedure AddExpressionCollections(ABindList: TCustomBindList;
AList: TList<TBindCompDesignExpressionCollection>); override;
function GetDescription(ADataBinding: TContainedBindComponent): string; override;
end;
TBindPositionDesigner = class(TCommonBindComponentDesigner)
protected
function GetDescription(ADataBinding: TContainedBindComponent): string; override;
function GetExpressions(ADataBinding: TContainedBindComponent; out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>; override;
function GetExpressionCollections(ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>; override;
end;
TExpressionsBindComponentDesigner = class(TCommonBindComponentDesigner)
protected
function GetDescription(ADataBinding: TContainedBindComponent): string; override;
function GetExpressions(ADataBinding: TContainedBindComponent; out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>; override;
function GetExpressionCollections(ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>; override;
end;
TBindControlValueDesigner = class(TCommonBindComponentDesigner)
protected
function GetDescription(ADataBinding: TContainedBindComponent): string; override;
function GetExpressions(ADataBinding: TContainedBindComponent; out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>; override;
function GetExpressionCollections(ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>; override;
end;
TBindGridListDesigner = class(TCommonBindComponentDesigner)
protected
procedure AddExpressions(ABindComp: TCustomBindGridList;
const AControlScopeName, ASourceScopeName, ASourceMemberScopeName: string;
AList: TList<TBindCompDesignExpression>); virtual;
procedure AddExpressionCollections(ABindList: TCustomBindGridList;
AList: TList<TBindCompDesignExpressionCollection>); virtual;
function GetDescription(ADataBinding: TContainedBindComponent): string; override;
function GetExpressions(ADataBinding: TContainedBindComponent; out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>; override;
function GetExpressionCollections(ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>; override;
end;
TBindGridListLinkDesigner = class(TBindGridListDesigner)
protected
procedure AddExpressions(ABindComp: TCustomBindGridList;
const AControlScopeName, ASourceScopeName, ASourceMemberScopeName: string;
AList: TList<TBindCompDesignExpression>); override;
procedure AddExpressionCollections(ABindList: TCustomBindGridList;
AList: TList<TBindCompDesignExpressionCollection>); override;
function GetDescription(ADataBinding: TContainedBindComponent): string; override;
end;
TBindGridLinkDesigner = class(TCommonBindComponentDesigner)
protected
function GetDescription(ADataBinding: TContainedBindComponent): string; override;
function GetExpressions(ADataBinding: TContainedBindComponent; out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>; override;
function GetExpressionCollections(ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>; override;
end;
implementation
uses Data.Bind.DBLinks;
{ TBindCompDesigner }
function TBindCompDesigner.BindsComponent(
ADataBinding: TContainedBindComponent; AComponent: TComponent): Boolean;
begin
Assert(AComponent <> nil);
Result := ADataBinding.ControlComponent = AComponent;
end;
function TBindCompDesigner.BindsComponentPropertyName(
ADataBinding: TContainedBindComponent; const APropertyName: string): Boolean;
begin
Result := APropertyName = 'ControlComponent'; // Do not localize
end;
function TBindCompDesigner.CanBindComponent(ADataBindingClass: TContainedBindCompClass; AComponent: TComponent;
ADesigner: IInterface): Boolean;
begin
Result := True;
end;
function TBindCompDesigner.GetDescription(ADataBinding: TContainedBindComponent): string;
begin
Result := '';
end;
function TBindCompDesigner.GetExpressionCollections(
ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>;
begin
SetLength(Result, 0);
end;
function TBindCompDesigner.GetExpressions(ADataBinding: TContainedBindComponent; out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>;
begin
ATypes := [TBindCompDesignerExpressionType.exprSourceToControl];
SetLength(Result, 0);
end;
function TBindCompDesigner.IsReadOnly(ABindComp: TContainedBindComponent;
AExpression: TBindCompDesignExpression): Boolean;
begin
Result := False;
end;
function TBindCompDesigner.IsReadOnly(ABindComp: TContainedBindComponent; AItem: TCollectionItem): Boolean;
begin
Result := False;
end;
function TBindCompDesigner.IsReadOnly(ABindComp: TContainedBindComponent; ACollection: TCollection): Boolean;
begin
Result := False;
end;
{ TBindExpressionDesigner }
function TBindExpressionDesigner.GetDescription(
ADataBinding: TContainedBindComponent): string;
begin
Assert(ADataBinding is TCustomBindExpression);
Result := FormatDisplayText(TCommonBindComponent(ADataBinding),
sBindExpressionDescription);
end;
function TBindExpressionDesigner.GetExpressionCollections(
ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>;
begin
SetLength(Result, 0);
end;
function TBindExpressionDesigner.GetExpressions(ADataBinding: TContainedBindComponent; out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>;
var
LList: TList<TBindCompDesignExpression>;
LBindComp: TCustomBindExpression;
LControlScope: string;
LSourceScope: string;
LExpressionType: TBindCompDesignerExpressionType;
begin
LBindComp := TCustomBindExpression(ADataBinding);
Assert(LBindComp is TCustomBindExpression);
ATypes := [exprSourceToControl, exprControlToSource, exprBidirectional];
LList := TList<TBindCompDesignExpression>.Create;
LControlScope := ControlScopeName(LBindComp);
LSourceScope := SourceScopeName(LBindComp);
try
LExpressionType := exprBidirectional;
case LBindComp.Direction of
dirSourceToControl:
LExpressionType := exprSourceToControl;
dirControlToSource:
LExpressionType := exprControlToSource;
dirBidirectional:
LExpressionType := exprBidirectional;
else
Assert(False);
end;
// if LBindComp.Bidirectional then
// LExpressionType := TBindCompDesignerExpressionType.exprBidirectional
// else
// LExpressionType := TBindCompDesignerExpressionType.exprSourceToControl;
LList.Add(TBindCompDesignExpression.Create(
sFormat, LControlScope, LBindComp.ControlExpression,
LSourceScope, LBindComp.SourceExpression,
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
Assert((LBindComp.Direction = dirSourceToControl) or
(LBindComp.Direction = dirBidirectional));
ExecuteAssignToControlExpression(LBindComp, AControlExpression, ASourceExpression, ACallback);
// LBindComp.ExecuteAssignToControlExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// begin
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// if AValue <> nil then
// LBindComp.EvaluateControlExpression(AControlExpression, ACallback)
// else
// ACallback(AValue);
// end);
end,
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
//Assert(LBindComp.Bidirectional);
Assert((LBindComp.Direction = dirControlToSource) or
(LBindComp.Direction = dirBidirectional));
ExecuteAssignToSourceExpression(LBindComp, AControlExpression, ASourceExpression, ACallback);
// LBindComp.ExecuteAssignToSourceExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// begin
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// if AValue <> nil then
// LBindComp.EvaluateSourceExpression(ASourceExpression, ACallback)
// else
// ACallback(AValue)
// end);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression, ACallback);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression, ACallback);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
LBindComp.ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
LBindComp.SourceExpression := AExpression;
end,
nil, // collectionitem);
sExpression,
nil, // parent collection item\
LExpressionType));
Result := LList.ToArray;
finally
LList.Free;
end;
end;
{ TBindExprItemsDesigner }
function TBindExprItemsDesigner.GetDescription(
ADataBinding: TContainedBindComponent): string;
var
LBindComp: TCustomBindExprItems;
LCount: Integer;
begin
Assert(ADataBinding is TCustomBindExprItems);
LBindComp := TCustomBindExprItems(ADataBinding);
LCount := LBindComp.FormatExpressions.Count + LBindComp.ClearExpressions.Count;
Result := FormatDisplayText(LBindComp, sBindExprItemsDescription, LCount)
end;
function TBindExprItemsDesigner.GetExpressionCollections(
ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>;
begin
SetLength(Result, 2);
Assert(ADataBinding is TCustomBindExprItems);
Result[0] := TBindCompDesignExpressionCollection.Create(sFormat, TCustomBindExprItems(ADataBinding).FormatExpressions);
Result[1] := TBindCompDesignExpressionCollection.Create(sClear, TCustomBindExprItems(ADataBinding).ClearExpressions);
end;
function TBindExprItemsDesigner.GetExpressions(ADataBinding: TContainedBindComponent; out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>;
var
LList: TList<TBindCompDesignExpression>;
LBindComp: TCustomBindExprItems;
LControlScope: string;
LSourceScope: string;
LIndex: Integer;
LExpression: TExpressionItemDir;
LExpressionType: TBindCompDesignerExpressionType;
begin
LBindComp := TCustomBindExprItems(ADataBinding);
Assert(LBindComp is TCustomBindExprItems);
ATypes := [exprSourceToControl, exprControlToSource, exprBidirectional];
LList := TList<TBindCompDesignExpression>.Create;
LControlScope := ControlScopeName(LBindComp);
LSourceScope := SourceScopeName(LBindComp);
try
for LIndex := 0 to LBindComp.FormatExpressions.Count - 1 do
begin
LExpression := LBindComp.FormatExpressions[LIndex];
LExpressionType := exprBidirectional;
case LExpression.Direction of
dirSourceToControl:
LExpressionType := exprSourceToControl;
dirControlToSource:
LExpressionType := exprControlToSource;
dirBidirectional:
LExpressionType := exprBidirectional;
else
Assert(False);
end;
LList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index), LControlScope, LExpression.ControlExpression,
LSourceScope, LExpression.SourceExpression,
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
// Assert((LBindComp.Direction = dirSourceToControl) or
// (LBindComp.Direction = dirBidirectional));
ExecuteAssignToControlExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback);
// LBindComp.ExecuteAssignToControlExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// begin
// if AValue <> nil then
// LBindComp.EvaluateControlExpression(AControlExpression, ACallback)
// else
// ACallback(AValue);
// end);
end,
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
// Assert((LBindComp.Direction = dirControlToSource) or
// (LBindComp.Direction = dirBidirectional));
ExecuteAssignToSourceExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback);
// LBindComp.ExecuteAssignToSourceExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// begin // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// if AValue <> nil then
// LBindComp.EvaluateSourceExpression(ASourceExpression, ACallback)
// else
// ACallback(AValue)
// end);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression, ACallback);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression, ACallback);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
// Anon capture doesn't seem to work here for LIndex, so use name
LBindComp.FormatExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
LBindComp.FormatExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression, // collectionitem);
sFormat,
nil, // parent collection item
LExpressionType));
end;
for LIndex := 0 to LBindComp.ClearExpressions.Count - 1 do
begin
LExpression := LBindComp.ClearExpressions[LIndex];
LExpressionType := exprBidirectional;
case LExpression.Direction of
dirSourceToControl,
dirBidirectional:
LExpressionType := exprSourceToControl;
dirControlToSource:
LExpressionType := exprControlToSource;
else
Assert(False);
end;
LList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index), LControlScope, LExpression.ControlExpression,
LSourceScope, LExpression.SourceExpression,
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToControlExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback);
// LBindComp.ExecuteAssignToControlExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// begin
// if AValue <> nil then
// LBindComp.EvaluateControlExpression(AControlExpression, ACallback)
// else
// ACallback(AValue);
// end);
end,
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToSourceExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression, ACallback);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression, ACallback);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
// Anon capture doesn't seem to work here for LIndex, so use name
LBindComp.ClearExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
LBindComp.ClearExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression, // collectionitem);
sClear,
nil, // parent collection item
LExpressionType));
end;
Result := LList.ToArray;
finally
LList.Free;
end;
end;
{ TBindLinkDesigner }
function TBindLinkDesigner.GetDescription(
ADataBinding: TContainedBindComponent): string;
var
LBindLink: TCustomBindLink;
begin
Assert(ADataBinding is TCustomBindLink);
LBindLink := TCustomBindLink(ADataBinding);
Result := FormatDisplayText(LBindLink, sBindLinkDescription);
end;
function TBindLinkDesigner.GetExpressionCollections(
ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>;
begin
SetLength(Result, 3);
Assert(ADataBinding is TCustomBindLink);
Result[0] := TBindCompDesignExpressionCollection.Create(sFormat, TCustomBindLink(ADataBinding).FormatExpressions);
Result[1] := TBindCompDesignExpressionCollection.Create(sParse, TCustomBindLink(ADataBinding).ParseExpressions);
Result[2] := TBindCompDesignExpressionCollection.Create(sClear, TCustomBindLink(ADataBinding).ClearExpressions);
end;
function TBindLinkDesigner.GetExpressions(ADataBinding: TContainedBindComponent; out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>;
var
LList: TList<TBindCompDesignExpression>;
LBindComp: TCustomBindLink;
LControlScope: string;
LSourceScope: string;
LIndex: Integer;
LExpression: TExpressionItem;
begin
LBindComp := TCustomBindLink(ADataBinding);
Assert(LBindComp is TCustomBindLink);
ATypes := [TBindCompDesignerExpressionType.exprControlToSource, TBindCompDesignerExpressionType.exprSourceToControl];
LList := TList<TBindCompDesignExpression>.Create;
LControlScope := ControlScopeName(LBindComp);
LSourceScope := SourceMemberScopeName(LBindComp);
try
for LIndex := 0 to LBindComp.FormatExpressions.Count - 1 do
begin
LExpression := LBindComp.FormatExpressions[LIndex];
LList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index), LControlScope, LExpression.ControlExpression,
LSourceScope, LExpression.SourceExpression,
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToControlExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback);
// LBindComp.ExecuteAssignToControlExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// begin // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// if AValue <> nil then
// LBindComp.EvaluateControlExpression(AControlExpression, ACallback)
// else
// ACallback(AValue)
// end);
end,
nil,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression, ACallback);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression, ACallback);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
// Anon capture doesn't seem to work here for LIndex, so use name
LBindComp.FormatExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
LBindComp.FormatExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
SFormat,
nil, // parent collection item
exprSourceToControl));
end;
for LIndex := 0 to LBindComp.ParseExpressions.Count - 1 do
begin
LExpression := LBindComp.ParseExpressions[LIndex];
LList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index),
LControlScope, LExpression.ControlExpression,
LSourceScope, LExpression.SourceExpression,
nil,
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToSourceExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback);
// LBindComp.ExecuteAssignToSourceExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// begin
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// if AValue <> nil then
// LBindComp.EvaluateSourceExpression(ASourceExpression, ACallback)
// else
// ACallback(AValue)
// end);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression, ACallback);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression, ACallback);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
LBindComp.ParseExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
LBindComp.ParseExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
SParse,
nil, // parent collection item
exprControlToSource));
end;
for LIndex := 0 to LBindComp.ClearExpressions.Count - 1 do
begin
LExpression := LBindComp.ClearExpressions[LIndex];
LList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index),
LControlScope, LExpression.ControlExpression,
'', LExpression.SourceExpression,
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToControlExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback);
// LBindComp.ExecuteAssignToControlExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// begin
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// if AValue <> nil then
// LBindComp.EvaluateControlExpression(AControlExpression, ACallback)
// else
// ACallback(AValue)
// end);
end,
nil,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression, ACallback);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression, ACallback);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
LBindComp.ClearExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
LBindComp.ClearExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
SClear,
nil, // parent collection item
exprSourceToControl));
end;
Result := LList.ToArray;
finally
LList.Free;
end;
end;
{ TBindListDesigner }
function TBindListDesigner.GetDescription(
ADataBinding: TContainedBindComponent): string;
var
LBindList: TCustomBindList;
begin
Assert(ADataBinding is TCustomBindList);
LBindList := TCustomBindList(ADataBinding);
Result := FormatDisplayText(LBindList, sBindListDescription);
end;
procedure TBindListDesigner.AddExpressionCollections(
ABindList: TCustomBindList; AList: TList<TBindCompDesignExpressionCollection>);
begin
AList.Add(TBindCompDesignExpressionCollection.Create(sFormatControl, ABindList.FormatControlExpressions));
AList.Add(TBindCompDesignExpressionCollection.Create(sClearControl, ABindList.ClearControlExpressions));
AList.Add(TBindCompDesignExpressionCollection.Create(sFormat, ABindList.FormatExpressions));
end;
function TBindListDesigner.GetExpressionCollections(
ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>;
var
LList: TList<TBindCompDesignExpressionCollection>;
begin
LList := TList<TBindCompDesignExpressionCollection>.Create;
try
AddExpressionCollections(ADataBinding as TCustomBindList, LList);
Result := LList.ToArray;
finally
LList.Free;
end;
end;
procedure TBindListDesigner.AddExpressions(ABindComp: TCustomBindList;
const AControlScopeName, ASourceScopeName, ASourceMemberScopeName: string; AList: TList<TBindCompDesignExpression>);
var
LExpression: TExpressionItem;
LIndex: Integer;
begin
for LIndex := 0 to ABindComp.FormatExpressions.Count - 1 do
begin
LExpression := ABindComp.FormatExpressions[LIndex];
AList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index), AControlScopeName, LExpression.ControlExpression,
ASourceMemberScopeName, LExpression.SourceExpression,
nil,
nil,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
ABindComp.EvaluateControlExpression(AExpression,
ACallback, TBindCompExpressionType.exprFill);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
ABindComp.EvaluateSourceExpression(AExpression,
ACallback,
TBindCompExpressionType.exprFill);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
// Anon capture doesn't seem to work here for LIndex, so use name
ABindComp.FormatExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
ABindComp.FormatExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
'',
nil, // parent collection item
exprSourceToControl
));
end;
for LIndex := 0 to ABindComp.FormatControlExpressions.Count - 1 do
begin
LExpression := ABindComp.FormatControlExpressions[LIndex];
AList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index), AControlScopeName, LExpression.ControlExpression, // output
ASourceScopeName, LExpression.SourceExpression, // value
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToControlExpression(ABindComp, AControlExpression, ASourceExpression,
ACallback, TBindCompExpressionType.exprFormatControl);
// ABindComp.ExecuteAssignToControlExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// begin
// if AValue <> nil then
// ABindComp.EvaluateControlExpression(AControlExpression,
// ACallback, TBindCompExpressionType.exprPosControl)
// else
// ACallback(AValue)
// end,
// TBindCompExpressionType.exprPosControl);
end,
nil,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
ABindComp.EvaluateControlExpression(AExpression,
ACallback, TBindCompExpressionType.exprFormatControl);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
ABindComp.EvaluateSourceExpression(AExpression,
ACallback, TBindCompExpressionType.exprFormatControl);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
// Anon capture doesn't seem to work here for LIndex, so use name
ABindComp.FormatControlExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
ABindComp.FormatControlExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
'',
nil, // parent collection item
exprSourceToControl
));
end;
for LIndex := 0 to ABindComp.ClearControlExpressions.Count - 1 do
begin
LExpression := ABindComp.ClearControlExpressions[LIndex];
AList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index), AControlScopeName, LExpression.ControlExpression, // output
ASourceScopeName, LExpression.SourceExpression, // value
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToControlExpression(ABindComp, AControlExpression, ASourceExpression,
ACallback, TBindCompExpressionType.exprFormatControl);
// ABindComp.ExecuteAssignToControlExpression(AControlExpression, ASourceExpression,
// procedure(AValue:IValue)
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// begin
// if AValue <> nil then
// ABindComp.EvaluateControlExpression(AControlExpression,
// ACallback, TBindCompExpressionType.exprPosControl)
// else
// ACallback(AValue)
// end,
// TBindCompExpressionType.exprPosControl);
end,
nil,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
ABindComp.EvaluateControlExpression(AExpression,
ACallback, TBindCompExpressionType.exprFormatControl);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
ABindComp.EvaluateSourceExpression(AExpression,
ACallback,
TBindCompExpressionType.exprFormatControl);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
// Anon capture doesn't seem to work here for LIndex, so use name
ABindComp.ClearControlExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
ABindComp.ClearControlExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
'',
nil, // parent collection item
exprSourceToControl
));
end;
end;
function TBindListDesigner.GetExpressions(ADataBinding: TContainedBindComponent; out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>;
var
LList: TList<TBindCompDesignExpression>;
LBindComp: TCustomBindList;
LControlScope: string;
LSourceScope: string;
LSourceMemberScope: string;
begin
LBindComp := TCustomBindList(ADataBinding);
Assert(LBindComp is TCustomBindList);
ATypes := [TBindCompDesignerExpressionType.exprSourceToControl];
LList := TList<TBindCompDesignExpression>.Create;
LControlScope := ControlScopeName(LBindComp);
LSourceScope := SourceScopeName(LBindComp);
LSourceMemberScope := SourceMemberScopeName(LBindComp);
try
AddExpressions(LBindComp, LControlScope, LSourceScope, LSourceMemberScope, LList);
Result := LList.ToArray;
finally
LList.Free;
end;
end;
{ TBindPositionDesigner }
function TBindPositionDesigner.GetDescription(
ADataBinding: TContainedBindComponent): string;
var
LBindComp: TCustomBindPosition;
begin
Assert(ADataBinding is TCustomBindPosition);
LBindComp := TCustomBindPosition(ADataBinding);
Result := FormatDisplayText(LBindComp, sBindPositionDescription);
end;
function TBindPositionDesigner.GetExpressionCollections(
ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>;
begin
SetLength(Result, 3);
Assert(ADataBinding is TCustomBindPosition);
Result[0] := TBindCompDesignExpressionCollection.Create(sPosControl, TCustomBindPosition(ADataBinding).PosControlExpressions);
Result[1] := TBindCompDesignExpressionCollection.Create(sPosSource, TCustomBindPosition(ADataBinding).PosSourceExpressions);
Result[2] := TBindCompDesignExpressionCollection.Create(sPosClear, TCustomBindPosition(ADataBinding).PosClearExpressions);
end;
function TBindPositionDesigner.GetExpressions(ADataBinding: TContainedBindComponent; out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>;
var
LList: TList<TBindCompDesignExpression>;
LBindComp: TCustomBindPosition;
LControlScope: string;
LSourceScope: string;
LExpression: TExpressionItem;
LIndex: Integer;
begin
LBindComp := TCustomBindPosition(ADataBinding);
Assert(LBindComp is TCustomBindPosition);
ATypes := [TBindCompDesignerExpressionType.exprControlToSource, TBindCompDesignerExpressionType.exprSourceToControl];
LList := TList<TBindCompDesignExpression>.Create;
LControlScope := ControlScopeName(LBindComp);
LSourceScope := SourceMemberScopeName(LBindComp);
SetLength(Result, 0);
try
for LIndex := 0 to LBindComp.PosControlExpressions.Count - 1 do
begin
LExpression := LBindComp.PosControlExpressions[LIndex];
LList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index), LControlScope, LExpression.ControlExpression, // output
LSourceScope, LExpression.SourceExpression, // value
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToControlExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback, TBindCompExpressionType.exprPosControl);
// LBindComp.ExecuteAssignToControlExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// begin
// if AValue <> nil then
// LBindComp.EvaluateControlExpression(AControlExpression,
// ACallback, TBindCompExpressionType.exprPosControl)
// else
// ACallback(AValue)
// end,
// TBindCompExpressionType.exprPosControl);
end,
nil,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression,
ACallback, TBindCompExpressionType.exprPosControl);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression,
ACallback, TBindCompExpressionType.exprPosControl);
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
// Anon capture doesn't seem to work here for LIndex, so use name
LBindComp.PosControlExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
LBindComp.PosControlExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
'',
nil, // parent collection item
exprSourceToControl
));
end;
for LIndex := 0 to LBindComp.PosClearExpressions.Count - 1 do
begin
LExpression := LBindComp.PosClearExpressions[LIndex];
LList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index), LControlScope, LExpression.ControlExpression, // output
LSourceScope, LExpression.SourceExpression, // value
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToControlExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback, TBindCompExpressionType.exprPosControl);
// LBindComp.ExecuteAssignToControlExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// begin
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// if AValue <> nil then
// LBindComp.EvaluateControlExpression(AControlExpression,
// ACallback, TBindCompExpressionType.exprPosControl)
// else
// ACallback(AValue)
// end,
// TBindCompExpressionType.exprPosControl);
end,
nil,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression,
ACallback, TBindCompExpressionType.exprPosControl);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression,
ACallback,
TBindCompExpressionType.exprPosControl);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
// Anon capture doesn't seem to work here for LIndex, so use name
LBindComp.PosClearExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
LBindComp.PosClearExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
'',
nil, // parent collection item
exprSourceToControl
));
end;
for LIndex := 0 to LBindComp.PosSourceExpressions.Count - 1 do
begin
LExpression := LBindComp.PosSourceExpressions[LIndex];
LList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index),
LControlScope, LExpression.ControlExpression,
LSourceScope, LExpression.SourceExpression,
nil,
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToSourceExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback, TBindCompExpressionType.exprPosSource);
// LBindComp.ExecuteAssignToSourceExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// begin
// if AValue <> nil then
// LBindComp.EvaluateSourceExpression(ASourceExpression,
// ACallback, TBindCompExpressionType.exprPosSource)
// else
// ACallback(AValue)
// end,
// TBindCompExpressionType.exprPosSource);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression,
ACallback,
TBindCompExpressionType.exprPosSource);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression,
ACallback, TBindCompExpressionType.exprPosSource);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
// Anon capture doesn't seem to work here for LIndex, so use name
LBindComp.PosSourceExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
LBindComp.PosSourceExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
'',
nil, // parent collection item
exprControlToSource
));
end;
Result := LList.ToArray;
finally
LList.Free;
end;
end;
{ TExpressionsBindComponentDesigner }
function TExpressionsBindComponentDesigner.GetExpressionCollections(
ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>;
begin
SetLength(Result, 3);
Assert(ADataBinding is TExpressionsBindComponent);
Result[0] := TBindCompDesignExpressionCollection.Create(sFormat, TExpressionsBindComponent(ADataBinding).FormatExpressions);
Result[1] := TBindCompDesignExpressionCollection.Create(sParse, TExpressionsBindComponent(ADataBinding).ParseExpressions);
Result[2] := TBindCompDesignExpressionCollection.Create(sClear, TExpressionsBindComponent(ADataBinding).ClearExpressions);
end;
function TExpressionsBindComponentDesigner.GetExpressions(ADataBinding: TContainedBindComponent; out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>;
var
LList: TList<TBindCompDesignExpression>;
LBindComp: TExpressionsBindComponent;
LControlScope: string;
LSourceScope: string;
LIndex: Integer;
LExpression: TExpressionItem;
begin
LBindComp := TExpressionsBindComponent(ADataBinding);
Assert(LBindComp is TExpressionsBindComponent);
ATypes := [TBindCompDesignerExpressionType.exprControlToSource, TBindCompDesignerExpressionType.exprSourceToControl];
LList := TList<TBindCompDesignExpression>.Create;
LControlScope := ControlScopeName(LBindComp);
LSourceScope := SourceMemberScopeName(LBindComp);
try
for LIndex := 0 to LBindComp.FormatExpressions.Count - 1 do
begin
LExpression := LBindComp.FormatExpressions[LIndex];
LList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index), LControlScope, LExpression.ControlExpression,
LSourceScope, LExpression.SourceExpression,
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToControlExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback);
end,
nil,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression, ACallback);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression, ACallback);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
// Anon capture doesn't seem to work here for LIndex, so use name
LBindComp.FormatExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
LBindComp.FormatExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
SFormat,
nil, // parent collection item
exprSourceToControl));
end;
for LIndex := 0 to LBindComp.ParseExpressions.Count - 1 do
begin
LExpression := LBindComp.ParseExpressions[LIndex];
LList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index),
LControlScope, LExpression.ControlExpression,
LSourceScope, LExpression.SourceExpression,
nil,
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToSourceExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression, ACallback);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression, ACallback);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
LBindComp.ParseExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
LBindComp.ParseExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
SParse,
nil, // parent collection item
exprControlToSource));
end;
for LIndex := 0 to LBindComp.ClearExpressions.Count - 1 do
begin
LExpression := LBindComp.ClearExpressions[LIndex];
LList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index),
LControlScope, LExpression.ControlExpression,
'', LExpression.SourceExpression,
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToControlExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback);
end,
nil,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression, ACallback);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression, ACallback);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
LBindComp.ClearExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
LBindComp.ClearExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
SClear,
nil, // parent collection item
exprSourceToControl));
end;
Result := LList.ToArray;
finally
LList.Free;
end;
end;
function TExpressionsBindComponentDesigner.GetDescription(
ADataBinding: TContainedBindComponent): string;
var
LBindComp: TExpressionsBindComponent;
begin
Assert(ADataBinding is TExpressionsBindComponent);
LBindComp := TExpressionsBindComponent(ADataBinding);
Result := FormatDisplayText(LBindComp, sExpressionsBindCompDesc);
end;
{ TBindControlValueDesigner }
function TBindControlValueDesigner.GetDescription(
ADataBinding: TContainedBindComponent): string;
var
LBindComp: TCustomBindControlValue;
begin
Assert(ADataBinding is TCustomBindControlValue);
LBindComp := TCustomBindControlValue(ADataBinding);
Result := FormatDisplayText(LBindComp, sBindControlValueDescription);
end;
function TBindControlValueDesigner.GetExpressionCollections(
ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>;
begin
SetLength(Result, 3);
Assert(ADataBinding is TCustomBindControlValue);
Result[0] := TBindCompDesignExpressionCollection.Create(sFormat, TCustomBindControlValue(ADataBinding).FormatExpressions);
Result[1] := TBindCompDesignExpressionCollection.Create(sParse, TCustomBindControlValue(ADataBinding).ParseExpressions);
Result[2] := TBindCompDesignExpressionCollection.Create(sClear, TCustomBindControlValue(ADataBinding).ClearExpressions);
end;
function TBindControlValueDesigner.GetExpressions(ADataBinding: TContainedBindComponent; out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>;
var
LList: TList<TBindCompDesignExpression>;
LBindComp: TCustomBindControlValue;
LControlScope: string;
LSourceScope: string;
LExpression: TExpressionItem;
LIndex: Integer;
begin
LBindComp := TCustomBindControlValue(ADataBinding);
Assert(LBindComp is TCustomBindControlValue);
ATypes := [TBindCompDesignerExpressionType.exprControlToSource, TBindCompDesignerExpressionType.exprSourceToControl];
LList := TList<TBindCompDesignExpression>.Create;
LControlScope := ControlScopeName(LBindComp);
LSourceScope := SourceMemberScopeName(LBindComp);
SetLength(Result, 0);
try
for LIndex := 0 to LBindComp.ParseExpressions.Count - 1 do
begin
LExpression := LBindComp.ParseExpressions[LIndex];
LList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index), LControlScope, LExpression.ControlExpression, // output
LSourceScope, LExpression.SourceExpression, // value
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToControlExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback, TBindCompExpressionType.exprFormat);
// LBindComp.ExecuteAssignToControlExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// begin
// if AValue <> nil then
// LBindComp.EvaluateControlExpression(AControlExpression,
// ACallback, TBindCompExpressionType.exprParse)
// else
// ACallback(AValue)
// end,
// TBindCompExpressionType.exprParse);
end,
nil,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression,
ACallback, TBindCompExpressionType.exprParse);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression,
ACallback, TBindCompExpressionType.exprParse);
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
// Anon capture doesn't seem to work here for LIndex, so use name
LBindComp.ParseExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
LBindComp.ParseExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
'',
nil, // parent collection item
exprSourceToControl
));
end;
for LIndex := 0 to LBindComp.ClearExpressions.Count - 1 do
begin
LExpression := LBindComp.ClearExpressions[LIndex];
LList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index), LControlScope, LExpression.ControlExpression, // output
LSourceScope, LExpression.SourceExpression, // value
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToControlExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback, TBindCompExpressionType.exprFormat);
// LBindComp.ExecuteAssignToControlExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// begin
// if AValue <> nil then
// LBindComp.EvaluateControlExpression(AControlExpression,
// ACallback, TBindCompExpressionType.exprParse)
// else
// ACallback(AValue)
// end,
// TBindCompExpressionType.exprParse);
end,
nil,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression,
ACallback, TBindCompExpressionType.exprParse);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression,
ACallback, TBindCompExpressionType.exprParse);
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
// Anon capture doesn't seem to work here for LIndex, so use name
LBindComp.ClearExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
LBindComp.ClearExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
'',
nil, // parent collection item
exprSourceToControl
));
end;
// for LIndex := 0 to LBindComp.PosClearExpressions.Count - 1 do
// begin
// LExpression := LBindComp.PosClearExpressions[LIndex];
// LList.Add(TBindCompDesignExpression.Create(
// IntToStr(LExpression.Index), LControlScope, LExpression.ControlExpression, // output
// LSourceScope, LExpression.SourceExpression, // value
// procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
// begin
// ExecuteAssignToControlExpression(LBindComp, AControlExpression, ASourceExpression,
// ACallback, TBindCompExpressionType.exprPosControl);
//// LBindComp.ExecuteAssignToControlExpression(AControlExpression, ASourceExpression,
//// procedure(AValue: IValue)
//// begin
//// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
//// if AValue <> nil then
//// LBindComp.EvaluateControlExpression(AControlExpression,
//// ACallback, TBindCompExpressionType.exprPosControl)
//// else
//// ACallback(AValue)
//// end,
//// TBindCompExpressionType.exprPosControl);
// end,
// nil,
// procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
// begin
// LBindComp.EvaluateControlExpression(AExpression,
// ACallback, TBindCompExpressionType.exprPosControl); // TODO: support nested
// end,
// procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
// begin
// LBindComp.EvaluateSourceExpression(AExpression,
// ACallback,
// TBindCompExpressionType.exprPosControl); // TODO: support nested
// end,
// procedure(const AName: string; const AExpression: string) // Save Control
// begin
// // Anon capture doesn't seem to work here for LIndex, so use name
// LBindComp.PosClearExpressions[StrToInt(AName)].ControlExpression := AExpression;
// end,
// procedure(const AName: string; const AExpression: string) // Save Source
// begin
// LBindComp.PosClearExpressions[StrToInt(AName)].SourceExpression := AExpression;
// end,
// LExpression,
// '',
// nil, // parent collection item
// exprSourceToControl
//));
// end;
for LIndex := 0 to LBindComp.FormatExpressions.Count - 1 do
begin
LExpression := LBindComp.FormatExpressions[LIndex];
LList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index),
LControlScope, LExpression.ControlExpression,
LSourceScope, LExpression.SourceExpression,
nil,
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToSourceExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback, TBindCompExpressionType.exprFormat);
// LBindComp.ExecuteAssignToSourceExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// begin
// if AValue <> nil then
// LBindComp.EvaluateSourceExpression(ASourceExpression,
// ACallback, TBindCompExpressionType.exprFormat)
// else
// ACallback(AValue)
// end,
// TBindCompExpressionType.exprFormat);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression,
ACallback,
TBindCompExpressionType.exprFormat);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression,
ACallback, TBindCompExpressionType.exprFormat);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
// Anon capture doesn't seem to work here for LIndex, so use name
LBindComp.FormatExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
LBindComp.FormatExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
'',
nil, // parent collection item
exprControlToSource
));
end;
Result := LList.ToArray;
finally
LList.Free;
end;
end;
{ TBindColumnListDesigner }
procedure TBindGridListDesigner.AddExpressionCollections(
ABindList: TCustomBindGridList;
AList: TList<TBindCompDesignExpressionCollection>);
var
I: Integer;
LColumnExpressionItem: TColumnFormatExpressionItem;
begin
AList.Add(TBindCompDesignExpressionCollection.Create(sFormatControl, ABindList.FormatControlExpressions));
AList.Add(TBindCompDesignExpressionCollection.Create(sClearControl, ABindList.ClearControlExpressions));
AList.Add(TBindCompDesignExpressionCollection.Create
(sColumns, ABindList.ColumnExpressions, nil, colCollections));
for I := 0 to ABindList.ColumnExpressions.Count - 1 do
begin
LColumnExpressionItem := TColumnFormatExpressionItem(ABindList.ColumnExpressions[I]);
AList.Add(TBindCompDesignExpressionCollection.Create
(sFormatColumn, LColumnExpressionItem.FormatColumnExpressions, LColumnExpressionItem));
AList.Add(TBindCompDesignExpressionCollection.Create
(sFormatCell, LColumnExpressionItem.FormatCellExpressions, LColumnExpressionItem));
end;
end;
procedure TBindGridListDesigner.AddExpressions(ABindComp: TCustomBindGridList;
const AControlScopeName, ASourceScopeName, ASourceMemberScopeName: string;
AList: TList<TBindCompDesignExpression>);
function GetSaveControlExpressionProc(AExpressionItem: TExpressionItem): TBindCompDesignExpression.TSaveDesignExpression;
begin
Result :=
procedure(const AName: string; const AExpressionText: string) // Save Output
begin
AExpressionItem.ControlExpression := AExpressionText;
end;
end;
function GetSaveSourceExpressionProc(AExpressionItem: TExpressionItem): TBindCompDesignExpression.TSaveDesignExpression;
begin
Result :=
procedure(const AName: string; const AExpressionText: string) // Save Output
begin
AExpressionItem.SourceExpression := AExpressionText;
end;
end;
procedure AddExpressions(AList: TList<TBindCompDesignExpression>; AColumnExpressionItem: TColumnFormatExpressionItem;
const AName: string; AExpressions: TExpressions; AType: TBindCompExpressionType;
ADirection: TBindCompDesignerExpressionType);
var
LControlScope: string;
LSourceScope: string;
LExpression: TExpressionItem;
LIndex: Integer;
LSaveControl: TBindCompDesignExpression.TSaveDesignExpression;
LSaveSource: TBindCompDesignExpression.TSaveDesignExpression;
LAssignToControlProc: TBindCompDesignExpression.TExecuteDesignExpression2;
LAssignToSourceProc: TBindCompDesignExpression.TExecuteDesignExpression2;
begin
// if ABindComp.ControlComponent <> nil then
// LControlScope := ABindComp.ControlComponent.Name
// else
// LControlScope := '';
// if ABindComp.SourceComponent <> nil then
// LSourceScope := ABindComp.SourceComponent.Name
// else
// LSourceScope := '';
LControlScope := ControlScopeName(ABindComp);
LSourceScope := SourceScopeName(ABindComp);
if AColumnExpressionItem.SourceMemberName <> '' then
LSourceScope := LSourceScope + ', ' + AColumnExpressionItem.SourceMemberName;
if AType = TBindCompExpressionType.exprFormatColumn then
begin
LAssignToControlProc :=
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ABindComp.ExecuteAssignToControlExpression(AColumnExpressionItem, AControlExpression, ASourceExpression,
procedure(AValue: IValue)
begin
// Display value of output expression in case it is a TObject. This allows visualizers work on TObject
if AValue <> nil then
ABindComp.EvaluateControlExpression(AColumnExpressionItem, AControlExpression,
ACallback, AType)
else
ACallback(AValue)
end, AType);
end;
LAssignToSourceProc :=
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ABindComp.ExecuteAssignToSourceExpression(AColumnExpressionItem, AControlExpression, ASourceExpression,
procedure(AValue: IValue)
begin
// Display value of output expression in case it is a TObject. This allows visualizers work on TObject
if AValue <> nil then
ABindComp.EvaluateSourceExpression(AColumnExpressionItem, ASourceExpression,
ACallback, AType)
else
ACallback(AValue)
end, AType);
end;
end
else
begin
LAssignToControlProc := nil;
LAssignToSourceProc := nil;
end;
for LIndex := 0 to AExpressions.Count - 1 do
begin
LExpression := AExpressions[LIndex];
LSaveSource := GetSaveSourceExpressionProc(LExpression);
LSaveControl := GetSaveControlExpressionProc(LExpression);
AList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index), LControlScope, LExpression.ControlExpression,
LSourceScope, LExpression.SourceExpression,
LAssignToControlProc,
LAssignToSourceProc,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
ABindComp.EvaluateControlExpression(AColumnExpressionItem, AExpression,
ACallback, AType);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
ABindComp.EvaluateSourceExpression(AColumnExpressionItem, AExpression,
ACallback, AType);
end,
LSaveControl, // Save Control
LSaveSource, // Save Source
LExpression,
AName,
AColumnExpressionItem, // parent collection item
ADirection));
end;
end;
procedure AddControlExpressions(LList: TList<TBindCompDesignExpression>);
var
LIndex: Integer;
LExpression: TExpressionItem;
LSourceScope: string;
LControlScope: string;
begin
// if ABindComp.ControlComponent <> nil then
// LControlScope := ABindComp.ControlComponent.Name
// else
// LControlScope := '';
// if ABindComp.SourceComponent <> nil then
// LSourceScope := ABindComp.SourceComponent.Name
// else
// LSourceScope := '';
LControlScope := ControlScopeName(ABindComp);
LSourceScope := SourceScopeName(ABindComp);
for LIndex := 0 to ABindComp.FormatControlExpressions.Count - 1 do
begin
LExpression := ABindComp.FormatControlExpressions[LIndex];
LList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index), LControlScope, LExpression.ControlExpression, // output
LSourceScope, LExpression.SourceExpression, // value
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToControlExpression(ABindComp, AControlExpression, ASourceExpression,
ACallback, TBindCompExpressionType.exprFormatControl);
// ABindComp.ExecuteAssignToControlExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// begin
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// if AValue <> nil then
// ABindComp.EvaluateControlExpression(AControlExpression, ACallback, TBindCompExpressionType.exprPosControl)
// else
// ACallback(AValue)
// end, TBindCompExpressionType.exprFormatControl);
end,
nil,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
ABindComp.EvaluateControlExpression(AExpression,
ACallback, TBindCompExpressionType.exprFormatControl);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
ABindComp.EvaluateSourceExpression(AExpression,
ACallback, TBindCompExpressionType.exprFormatControl);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
// Anon capture doesn't seem to work here for LIndex, so use name
ABindComp.FormatControlExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
ABindComp.FormatControlExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
'',
nil, // parent collection item
exprSourceToControl));
end;
for LIndex := 0 to ABindComp.ClearControlExpressions.Count - 1 do
begin
LExpression := ABindComp.ClearControlExpressions[LIndex];
LList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index), LControlScope, LExpression.ControlExpression, // output
LSourceScope, LExpression.SourceExpression, // value
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToControlExpression(ABindComp, AControlExpression, ASourceExpression,
ACallback, TBindCompExpressionType.exprFormatControl);
// ABindComp.ExecuteAssignToControlExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// begin // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// if AValue <> nil then
// ABindComp.EvaluateControlExpression(AControlExpression,
// ACallback, TBindCompExpressionType.exprPosControl)
// else
// ACallback(AValue);
// end, TBindCompExpressionType.exprPosControl);
end,
nil,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
ABindComp.EvaluateControlExpression(AExpression,
ACallback, TBindCompExpressionType.exprFormatControl);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
ABindComp.EvaluateSourceExpression(AExpression,
ACallback,
TBindCompExpressionType.exprPosControl);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
// Anon capture doesn't seem to work here for LIndex, so use name
ABindComp.ClearControlExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
ABindComp.ClearControlExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
'',
nil, // parent collection item
exprSourceToControl));
end;
end;
var
I: Integer;
LColumnExpressionItem: TColumnFormatExpressionItem;
begin
for I := 0 to ABindComp.ColumnExpressions.Count - 1 do
begin
LColumnExpressionItem := TColumnFormatExpressionItem(ABindComp.ColumnExpressions[I]);
AddExpressions(AList, LColumnExpressionItem, sFormatColumn,
LColumnExpressionItem.FormatColumnExpressions, TBindCompExpressionType.exprFormatColumn,
exprSourceToControl);
AddExpressions(AList, LColumnExpressionItem, sFormatCell,
LColumnExpressionItem.FormatCellExpressions, TBindCompExpressionType.exprFill,
exprSourceToControl);
end;
AddControlExpressions(AList);
end;
function TBindGridListDesigner.GetDescription(
ADataBinding: TContainedBindComponent): string;
var
LBindColumns: TCustomBindGridList;
begin
Assert(ADataBinding is TCustomBindGridList);
LBindColumns := TCustomBindGridList(ADataBinding);
Result := FormatDisplayText(LBindColumns, sBindListDescription);
end;
function TBindGridListDesigner.GetExpressionCollections(
ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>;
var
// I: Integer;
LBindComp: TCustomBindGridList;
// LColumnExpressionItem: TColumnFormatExpressionItem;
LList: TList<TBindCompDesignExpressionCollection>;
begin
Assert(ADataBinding is TCustomBindGridList);
LBindComp := TCustomBindGridList(ADataBinding);
LList := TList<TBindCompDesignExpressionCollection>.Create;
try
AddExpressionCollections(LBindComp, LList);
// LList.Add(TBindCompDesignExpressionCollection.Create(sFormatControl, LBindComp.FormatControlExpressions));
// LList.Add(TBindCompDesignExpressionCollection.Create(sClearControl, LBindComp.ClearControlExpressions));
// LList.Add(TBindCompDesignExpressionCollection.Create
// (sColumns, LBindComp.ColumnExpressions, nil, colCollections));
// for I := 0 to LBindComp.ColumnExpressions.Count - 1 do
// begin
// LColumnExpressionItem := TColumnFormatExpressionItem(LBindComp.ColumnExpressions[I]);
// LList.Add(TBindCompDesignExpressionCollection.Create
// (sFormatColumn, LColumnExpressionItem.FormatColumnExpressions, LColumnExpressionItem));
// LList.Add(TBindCompDesignExpressionCollection.Create
// (sFormatCell, LColumnExpressionItem.FormatCellExpressions, LColumnExpressionItem));
// end;
Result := LList.ToArray;
finally
LList.Free;
end;
end;
function TBindGridListDesigner.GetExpressions(ADataBinding: TContainedBindComponent; out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>;
var
LBindComp: TCustomBindGridList;
// function GetSaveControlExpressionProc(AExpressionItem: TExpressionItem): TBindCompDesignExpression.TSaveDesignExpression;
// begin
// Result :=
// procedure(const AName: string; const AExpressionText: string) // Save Output
// begin
// AExpressionItem.ControlExpression := AExpressionText;
// end;
// end;
//
// function GetSaveSourceExpressionProc(AExpressionItem: TExpressionItem): TBindCompDesignExpression.TSaveDesignExpression;
// begin
// Result :=
// procedure(const AName: string; const AExpressionText: string) // Save Output
// begin
// AExpressionItem.SourceExpression := AExpressionText;
// end;
// end;
// procedure AddExpressions(AList: TList<TBindCompDesignExpression>; AColumnExpressionItem: TColumnFormatExpressionItem;
// const AName: string; AExpressions: TExpressions; AType: TBindCompExpressionType;
// ADirection: TBindCompDesignerExpressionType);
// var
// LControlScope: string;
// LSourceScope: string;
// LExpression: TExpressionItem;
// LIndex: Integer;
// LSaveControl: TBindCompDesignExpression.TSaveDesignExpression;
// LSaveSource: TBindCompDesignExpression.TSaveDesignExpression;
// begin
//// if LBindComp.ControlComponent <> nil then
//// LControlScope := LBindComp.ControlComponent.Name
//// else
//// LControlScope := '';
//// if LBindComp.SourceComponent <> nil then
//// LSourceScope := LBindComp.SourceComponent.Name
//// else
//// LSourceScope := '';
// LControlScope := ControlScopeName(LBindComp);
// LSourceScope := SourceScopeName(LBindComp);
// if AColumnExpressionItem.SourceMemberName <> '' then
// LSourceScope := LSourceScope + ', ' + AColumnExpressionItem.SourceMemberName;
//
// for LIndex := 0 to AExpressions.Count - 1 do
// begin
// LExpression := AExpressions[LIndex];
// LSaveSource := GetSaveSourceExpressionProc(LExpression);
// LSaveControl := GetSaveControlExpressionProc(LExpression);
//
// AList.Add(TBindCompDesignExpression.Create(
// IntToStr(LExpression.Index), LControlScope, LExpression.ControlExpression,
// LSourceScope, LExpression.SourceExpression,
// procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
// begin
// LBindComp.ExecuteAssignToControlExpression(AColumnExpressionItem, AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// begin
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// if AValue <> nil then
// LBindComp.EvaluateControlExpression(AColumnExpressionItem, AControlExpression,
// ACallback, AType)
// else
// ACallback(AValue)
// end, AType);
// end,
// procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
// begin
// LBindComp.ExecuteAssignToSourceExpression(AColumnExpressionItem, AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// begin
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// if AValue <> nil then
// LBindComp.EvaluateSourceExpression(AColumnExpressionItem, ASourceExpression,
// ACallback, AType)
// else
// ACallback(AValue)
// end, AType);
// end,
// procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
// begin
// LBindComp.EvaluateControlExpression(AColumnExpressionItem, AExpression,
// ACallback, AType);
// end,
// procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
// begin
// LBindComp.EvaluateSourceExpression(AColumnExpressionItem, AExpression,
// ACallback, AType);
// end,
// LSaveControl, // Save Control
// LSaveSource, // Save Source
// LExpression,
// AName,
// AColumnExpressionItem, // parent collection item
// ADirection));
// end;
// end;
//
// procedure AddControlExpressions(LList: TList<TBindCompDesignExpression>);
// var
// LIndex: Integer;
// LExpression: TExpressionItem;
// LSourceScope: string;
// LControlScope: string;
// begin
//// if LBindComp.ControlComponent <> nil then
//// LControlScope := LBindComp.ControlComponent.Name
//// else
//// LControlScope := '';
//// if LBindComp.SourceComponent <> nil then
//// LSourceScope := LBindComp.SourceComponent.Name
//// else
//// LSourceScope := '';
//
// LControlScope := ControlScopeName(LBindComp);
// LSourceScope := SourceScopeName(LBindComp);
// for LIndex := 0 to LBindComp.FormatControlExpressions.Count - 1 do
// begin
// LExpression := LBindComp.FormatControlExpressions[LIndex];
// LList.Add(TBindCompDesignExpression.Create(
// IntToStr(LExpression.Index), LControlScope, LExpression.ControlExpression, // output
// LSourceScope, LExpression.SourceExpression, // value
// procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
// begin
// ExecuteAssignToControlExpression(LBindComp, AControlExpression, ASourceExpression,
// ACallback, TBindCompExpressionType.exprFormatControl);
//// LBindComp.ExecuteAssignToControlExpression(AControlExpression, ASourceExpression,
//// procedure(AValue: IValue)
//// begin
//// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
//// if AValue <> nil then
//// LBindComp.EvaluateControlExpression(AControlExpression, ACallback, TBindCompExpressionType.exprPosControl)
//// else
//// ACallback(AValue)
//// end, TBindCompExpressionType.exprFormatControl);
// end,
// nil,
// procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
// begin
// LBindComp.EvaluateControlExpression(AExpression,
// ACallback, TBindCompExpressionType.exprFormatControl); // TODO: support nested
// end,
// procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
// begin
// LBindComp.EvaluateSourceExpression(AExpression,
// ACallback, TBindCompExpressionType.exprFormatControl); // TODO: support nested
// end,
// procedure(const AName: string; const AExpression: string) // Save Control
// begin
// // Anon capture doesn't seem to work here for LIndex, so use name
// LBindComp.FormatControlExpressions[StrToInt(AName)].ControlExpression := AExpression;
// end,
// procedure(const AName: string; const AExpression: string) // Save Source
// begin
// LBindComp.FormatControlExpressions[StrToInt(AName)].SourceExpression := AExpression;
// end,
// LExpression,
// '',
// nil, // parent collection item
// exprSourceToControl));
// end;
//
// for LIndex := 0 to LBindComp.ClearControlExpressions.Count - 1 do
// begin
// LExpression := LBindComp.ClearControlExpressions[LIndex];
// LList.Add(TBindCompDesignExpression.Create(
// IntToStr(LExpression.Index), LControlScope, LExpression.ControlExpression, // output
// LSourceScope, LExpression.SourceExpression, // value
// procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
// begin
// ExecuteAssignToControlExpression(LBindComp, AControlExpression, ASourceExpression,
// ACallback, TBindCompExpressionType.exprFormatControl);
//// LBindComp.ExecuteAssignToControlExpression(AControlExpression, ASourceExpression,
//// procedure(AValue: IValue)
//// begin // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
//// if AValue <> nil then
//// LBindComp.EvaluateControlExpression(AControlExpression,
//// ACallback, TBindCompExpressionType.exprPosControl)
//// else
//// ACallback(AValue);
//// end, TBindCompExpressionType.exprPosControl);
// end,
// nil,
// procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
// begin
// LBindComp.EvaluateControlExpression(AExpression,
// ACallback, TBindCompExpressionType.exprFormatControl); // TODO: support nested
// end,
// procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
// begin
// LBindComp.EvaluateSourceExpression(AExpression,
// ACallback,
// TBindCompExpressionType.exprPosControl); // TODO: support nested
// end,
// procedure(const AName: string; const AExpression: string) // Save Control
// begin
// // Anon capture doesn't seem to work here for LIndex, so use name
// LBindComp.ClearControlExpressions[StrToInt(AName)].ControlExpression := AExpression;
// end,
// procedure(const AName: string; const AExpression: string) // Save Source
// begin
// LBindComp.ClearControlExpressions[StrToInt(AName)].SourceExpression := AExpression;
// end,
// LExpression,
// '',
// nil, // parent collection item
// exprSourceToControl));
// end;
//
//
// end;
var
LList: TList<TBindCompDesignExpression>;
LControlScope: string;
LSourceScope: string;
LSourceMemberScope: string;
begin
LBindComp := TCustomBindGridList(ADataBinding);
Assert(LBindComp is TCustomBindGridList);
ATypes := [TBindCompDesignerExpressionType.exprSourceToControl];
LList := TList<TBindCompDesignExpression>.Create;
SetLength(Result, 0);
LControlScope := ControlScopeName(LBindComp);
LSourceScope := SourceScopeName(LBindComp);
LSourceMemberScope := SourceMemberScopeName(LBindComp);
try
// for I := 0 to LBindComp.ColumnExpressions.Count - 1 do
// begin
// LColumnExpressionItem := TColumnFormatExpressionItem(LBindComp.ColumnExpressions[I]);
// AddExpressions(LList, LColumnExpressionItem, sFormatColumn,
// LColumnExpressionItem.FormatColumnExpressions, TBindCompExpressionType.exprFormatColumn,
// exprSourceToControl);
// AddExpressions(LList, LColumnExpressionItem, sFormatCell,
// LColumnExpressionItem.FormatCellExpressions, TBindCompExpressionType.exprFill,
// exprSourceToControl);
// end;
//
//
// AddControlExpressions(LList);
AddExpressions(LBindComp, LControlScope, LSourceScope, LSourceMemberScope, LList);
Result := LList.ToArray;
finally
LList.Free;
end;
end;
{ TBindColumnDesigner }
function TBindGridLinkDesigner.GetDescription(
ADataBinding: TContainedBindComponent): string;
var
LBindColumns: TCustomBindGridLink;
begin
Assert(ADataBinding is TCustomBindGridLink);
LBindColumns := TCustomBindGridLink(ADataBinding);
Result := FormatDisplayText(LBindColumns, sBindGridLinkDescription);
end;
function TBindGridLinkDesigner.GetExpressionCollections(
ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>;
var
I: Integer;
LBindComp: TCustomBindGridLink;
LColumnExpressionItem: TColumnLinkExpressionItem;
LList: TList<TBindCompDesignExpressionCollection>;
begin
Assert(ADataBinding is TCustomBindGridLink);
LBindComp := TCustomBindGridLink(ADataBinding);
LList := TList<TBindCompDesignExpressionCollection>.Create;
try
LList.Add(TBindCompDesignExpressionCollection.Create(sFormatControl, LBindComp.FormatControlExpressions));
LList.Add(TBindCompDesignExpressionCollection.Create(sClearControl, LBindComp.ClearControlExpressions));
LList.Add(TBindCompDesignExpressionCollection.Create(sPosControl, LBindComp.PosControlExpressions));
LList.Add(TBindCompDesignExpressionCollection.Create(sPosSource, LBindComp.PosSourceExpressions));
LList.Add(TBindCompDesignExpressionCollection.Create
(sColumns, LBindComp.ColumnExpressions, nil, colCollections));
for I := 0 to LBindComp.ColumnExpressions.Count - 1 do
begin
LColumnExpressionItem := TColumnLinkExpressionItem(LBindComp.ColumnExpressions[I]);
LList.Add(TBindCompDesignExpressionCollection.Create
(sFormatColumn, LColumnExpressionItem.FormatColumnExpressions, LColumnExpressionItem));
LList.Add(TBindCompDesignExpressionCollection.Create
(sFormatCell, LColumnExpressionItem.FormatCellExpressions, LColumnExpressionItem));
LList.Add(TBindCompDesignExpressionCollection.Create
(sParseCell, LColumnExpressionItem.ParseCellExpressions, LColumnExpressionItem));
end;
Result := LList.ToArray;
finally
LList.Free;
end;
end;
function TBindGridLinkDesigner.GetExpressions(ADataBinding: TContainedBindComponent; out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>;
var
LBindComp: TCustomBindGridLink;
function GetSaveControlExpressionProc(AExpressionItem: TExpressionItem): TBindCompDesignExpression.TSaveDesignExpression;
begin
Result :=
procedure(const AName: string; const AExpressionText: string) // Save Output
begin
AExpressionItem.ControlExpression := AExpressionText;
end;
end;
function GetSaveSourceExpressionProc(AExpressionItem: TExpressionItem): TBindCompDesignExpression.TSaveDesignExpression;
begin
Result :=
procedure(const AName: string; const AExpressionText: string) // Save Output
begin
AExpressionItem.SourceExpression := AExpressionText;
end;
end;
procedure AddExpressions(AList: TList<TBindCompDesignExpression>; AColumnExpressionItem: TColumnLinkExpressionItem;
const AName: string; AExpressions: TExpressions; AType: TBindCompExpressionType;
ADirection: TBindCompDesignerExpressionType);
var
LControlScope: string;
LSourceScope: string;
LExpression: TExpressionItem;
LIndex: Integer;
LSaveControl: TBindCompDesignExpression.TSaveDesignExpression;
LSaveSource: TBindCompDesignExpression.TSaveDesignExpression;
LAssignToControlProc: TBindCompDesignExpression.TExecuteDesignExpression2;
LAssignToSourceProc: TBindCompDesignExpression.TExecuteDesignExpression2;
begin
// if LBindComp.ControlComponent <> nil then
// LControlScope := LBindComp.ControlComponent.Name
// else
// LControlScope := '';
// if LBindComp.SourceComponent <> nil then
// LSourceScope := LBindComp.SourceComponent.Name
// else
// LSourceScope := '';
LControlScope := ControlScopeName(LBindComp);
LSourceScope := SourceScopeName(LBindComp);
if AColumnExpressionItem.SourceMemberName <> '' then
LSourceScope := LSourceScope + ', ' + AColumnExpressionItem.SourceMemberName;
if AType = TBindCompExpressionType.exprFormatColumn then
begin
LAssignToControlProc :=
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
LBindComp.ExecuteAssignToControlExpression(AColumnExpressionItem, AControlExpression, ASourceExpression,
procedure(AValue:IValue)
begin
// Display value of output expression in case it is a TObject. This allows visualizers work on TObject
if AValue <> nil then
LBindComp.EvaluateControlExpression(AColumnExpressionItem, AControlExpression, ACallback, AType)
else
ACallback(AValue)
end, AType);
end;
LAssignToSourceProc :=
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
LBindComp.ExecuteAssignItemToSourceExpression(AColumnExpressionItem, AControlExpression, ASourceExpression,
procedure(AValue: IValue)
begin
// Display value of output expression in case it is a TObject. This allows visualizers work on TObject
if AValue <> nil then
LBindComp.EvaluateSourceExpression(AColumnExpressionItem, ASourceExpression,
ACallback, AType)
else
ACallback(AValue)
end, AType);
end;
end
else
begin
LAssignToControlProc := nil;
LAssignToSourceProc := nil;
end;
for LIndex := 0 to AExpressions.Count - 1 do
begin
LExpression := AExpressions[LIndex];
LSaveSource := GetSaveSourceExpressionProc(LExpression);
LSaveControl := GetSaveControlExpressionProc(LExpression);
AList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index), LControlScope, LExpression.ControlExpression,
LSourceScope, LExpression.SourceExpression,
LAssignToControlProc,
LAssignToSourceProc,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AColumnExpressionItem, AExpression,
ACallback, AType)
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AColumnExpressionItem, AExpression,
ACallback, AType);
end,
LSaveControl, // Save Control
LSaveSource, // Save Source
LExpression,
AName,
AColumnExpressionItem, // parent collection item
ADirection));
end;
end;
procedure AddControlExpressions(LList: TList<TBindCompDesignExpression>);
var
LIndex: Integer;
LExpression: TExpressionItem;
LSourceScope: string;
LControlScope: string;
begin
// if LBindComp.ControlComponent <> nil then
// LControlScope := LBindComp.ControlComponent.Name
// else
// LControlScope := '';
// if LBindComp.SourceComponent <> nil then
// LSourceScope := LBindComp.SourceComponent.Name
// else
// LSourceScope := '';
LControlScope := ControlScopeName(LBindComp);
LSourceScope := SourceScopeName(LBindComp);
for LIndex := 0 to LBindComp.FormatControlExpressions.Count - 1 do
begin
LExpression := LBindComp.FormatControlExpressions[LIndex];
LList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index), LControlScope, LExpression.ControlExpression, // output
LSourceScope, LExpression.SourceExpression, // value
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToControlExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback, TBindCompExpressionType.exprFormatControl);
// LBindComp.ExecuteAssignToControlExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// begin
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// if AValue <> nil then
// LBindComp.EvaluateControlExpression(AControlExpression,
// ACallback, TBindCompExpressionType.exprPosControl)
// else
// ACallback(AValue)
// end,
// TBindCompExpressionType.exprPosControl);
end,
nil,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression,
ACallback, TBindCompExpressionType.exprFormatControl);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression,
ACallback,
TBindCompExpressionType.exprFormatControl);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
// Anon capture doesn't seem to work here for LIndex, so use name
LBindComp.FormatControlExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
LBindComp.FormatControlExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
'',
nil, // parent collection item
exprSourceToControl));
end;
for LIndex := 0 to LBindComp.ClearControlExpressions.Count - 1 do
begin
LExpression := LBindComp.ClearControlExpressions[LIndex];
LList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index), LControlScope, LExpression.ControlExpression, // output
LSourceScope, LExpression.SourceExpression, // value
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToControlExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback, TBindCompExpressionType.exprFormatControl);
// LBindComp.ExecuteAssignToControlExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// begin // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// if AValue <> nil then
// LBindComp.EvaluateControlExpression(AControlExpression,
// ACallback, TBindCompExpressionType.exprPosControl)
// else
// ACallback(AValue)
// end,
// TBindCompExpressionType.exprPosControl);
end,
nil,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression,
ACallback, TBindCompExpressionType.exprFormatControl)
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression,
ACallback,
TBindCompExpressionType.exprFormatControl);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
// Anon capture doesn't seem to work here for LIndex, so use name
LBindComp.ClearControlExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
LBindComp.ClearControlExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
'',
nil, // parent collection item
exprSourceToControl));
end;
end;
procedure AddPosExpressions(LList: TList<TBindCompDesignExpression>);
var
LIndex: Integer;
LExpression: TExpressionItem;
LSourceScope: string;
LControlScope: string;
begin
// if LBindComp.ControlComponent <> nil then
// LControlScope := LBindComp.ControlComponent.Name
// else
// LControlScope := '';
// if LBindComp.SourceComponent <> nil then
// LSourceScope := LBindComp.SourceComponent.Name
// else
// LSourceScope := '';
LControlScope := ControlScopeName(LBindComp);
LSourceScope := SourceScopeName(LBindComp);
for LIndex := 0 to LBindComp.PosControlExpressions.Count - 1 do
begin
LExpression := LBindComp.PosControlExpressions[LIndex];
LList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index), LControlScope, LExpression.ControlExpression, // output
LSourceScope, LExpression.SourceExpression, // value
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToControlExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback, TBindCompExpressionType.exprPosControl);
// LBindComp.ExecuteAssignToControlExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// begin
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// if AValue <> nil then
// LBindComp.EvaluateControlExpression(AControlExpression,
// ACallback, TBindCompExpressionType.exprPosControl)
// else
// ACallback(AValue)
// end,
// TBindCompExpressionType.exprPosControl);
end,
nil,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression,
ACallback, TBindCompExpressionType.exprPosControl);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression,
ACallback,
TBindCompExpressionType.exprPosControl);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
// Anon capture doesn't seem to work here for LIndex, so use name
LBindComp.PosControlExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
LBindComp.PosControlExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
'',
nil, // parent collection item
exprSourceToControl));
end;
for LIndex := 0 to LBindComp.PosSourceExpressions.Count - 1 do
begin
LExpression := LBindComp.PosSourceExpressions[LIndex];
LList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index),
LControlScope, LExpression.ControlExpression,
LSourceScope, LExpression.SourceExpression,
nil,
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToSourceExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback, TBindCompExpressionType.exprPosSource);
// LBindComp.ExecuteAssignToSourceExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// begin
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// if AValue <> nil then
// LBindComp.EvaluateSourceExpression(ASourceExpression,
// ACallback, TBindCompExpressionType.exprPosSource)
// else
// ACallback(AValue)
// end, TBindCompExpressionType.exprPosSource);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression,
ACallback,
TBindCompExpressionType.exprPosSource);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression,
ACallback, TBindCompExpressionType.exprPosSource);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
LBindComp.PosSourceExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
// Anon capture doesn't seem to work here for LIndex, so use name
LBindComp.PosSourceExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
'',
nil, // parent collection item
exprControlToSource));
end;
end;
var
LList: TList<TBindCompDesignExpression>;
I: Integer;
LColumnExpressionItem: TColumnLinkExpressionItem;
begin
LBindComp := TCustomBindGridLink(ADataBinding);
Assert(LBindComp is TCustomBindGridLink);
ATypes := [TBindCompDesignerExpressionType.exprControlToSource,
TBindCompDesignerExpressionType.exprSourceToControl];
LList := TList<TBindCompDesignExpression>.Create;
SetLength(Result, 0);
try
for I := 0 to LBindComp.ColumnExpressions.Count - 1 do
begin
LColumnExpressionItem := TColumnLinkExpressionItem(LBindComp.ColumnExpressions[I]);
AddExpressions(LList, LColumnExpressionItem, sFormatColumn,
LColumnExpressionItem.FormatColumnExpressions, TBindCompExpressionType.exprFormatColumn,
exprSourceToControl);
AddExpressions(LList, LColumnExpressionItem, sFormatCell,
LColumnExpressionItem.FormatCellExpressions, TBindCompExpressionType.exprFill,
exprSourceToControl);
AddExpressions(LList, LColumnExpressionItem, sParseCell,
LColumnExpressionItem.ParseCellExpressions, TBindCompExpressionType.exprParse,
exprControlToSource);
end;
AddControlExpressions(LList);
AddPosExpressions(LList);
Result := LList.ToArray;
finally
LList.Free;
end;
end;
{ TBindListLinkDesigner }
procedure TBindListLinkDesigner.AddExpressionCollections(
ABindList: TCustomBindList;
AList: TList<TBindCompDesignExpressionCollection>);
begin
inherited;
AList.Add(TBindCompDesignExpressionCollection.Create(sPosControl, (ABindList as TCustomBindListLink).PosControlExpressions));
AList.Add(TBindCompDesignExpressionCollection.Create(sPosSource, (ABindList as TCustomBindListLink).PosSourceExpressions));
AList.Add(TBindCompDesignExpressionCollection.Create(sParse, (ABindList as TCustomBindListLink).ParseExpressions));
end;
procedure TBindListLinkDesigner.AddExpressions(ABindComp: TCustomBindList;
const AControlScopeName, ASourceScopeName, ASourceMemberScopeName: string;
AList: TList<TBindCompDesignExpression>);
var
LBindComp: TCustomBindListLink;
LIndex: Integer;
LExpression: TExpressionItem;
begin
inherited;
LBindComp := ABindComp as TCustomBindListLink;
for LIndex := 0 to LBindComp.PosControlExpressions.Count - 1 do
begin
LExpression := LBindComp.PosControlExpressions[LIndex];
AList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index), AControlScopeName, LExpression.ControlExpression, // output
ASourceScopeName, LExpression.SourceExpression, // value
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToControlExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback, TBindCompExpressionType.exprPosControl);
// LBindComp.ExecuteAssignToControlExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// begin
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// if AValue <> nil then
// LBindComp.EvaluateControlExpression(AControlExpression,
// ACallback, TBindCompExpressionType.exprPosControl)
// else
// ACallback(AValue)
// end,
// TBindCompExpressionType.exprPosControl);
end,
nil,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression,
ACallback, TBindCompExpressionType.exprPosControl);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression,
ACallback, TBindCompExpressionType.exprPosControl);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
// Anon capture doesn't seem to work here for LIndex, so use name
LBindComp.PosControlExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
LBindComp.PosControlExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
'',
nil, // parent collection item
exprSourceToControl));
end;
for LIndex := 0 to LBindComp.PosSourceExpressions.Count - 1 do
begin
LExpression := LBindComp.PosSourceExpressions[LIndex];
AList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index),
AControlScopeName, LExpression.ControlExpression,
ASourceScopeName, LExpression.SourceExpression,
nil,
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToSourceExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback, TBindCompExpressionType.exprPosSource);
// LBindComp.ExecuteAssignToSourceExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// begin
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// if AValue <> nil then
// LBindComp.EvaluateControlExpression(ASourceExpression,
// ACallback, TBindCompExpressionType.exprPosSource)
// else
// ACallback(AValue)
// end,
// TBindCompExpressionType.exprPosSource);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression,
ACallback, TBindCompExpressionType.exprPosSource);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression,
ACallback, TBindCompExpressionType.exprPosSource);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
LBindComp.PosSourceExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
// Anon capture doesn't seem to work here for LIndex, so use name
LBindComp.PosSourceExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
'',
nil, // parent collection item
exprControlToSource));
end;
for LIndex := 0 to LBindComp.ParseExpressions.Count - 1 do
begin
LExpression := LBindComp.ParseExpressions[LIndex];
AList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index),
AControlScopeName, LExpression.ControlExpression,
ASourceScopeName, LExpression.SourceExpression,
nil,
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToSourceExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback, TBindCompExpressionType.exprParse);
// LBindComp.ExecuteAssignToSourceExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// begin
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// if AValue <> nil then
// LBindComp.EvaluateSourceExpression(AControlExpression, ACallback,
// TBindCompExpressionType.exprParse)
// else
// ACallback(AValue)
// end,
// TBindCompExpressionType.exprParse);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression,
ACallback, TBindCompExpressionType.exprParse);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression,
ACallback, TBindCompExpressionType.exprParse);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
LBindComp.ParseExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
// Anon capture doesn't seem to work here for LIndex, so use name
LBindComp.ParseExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
SParse,
nil, // parent collection item
exprSourceToControl));
end;
end;
function TBindListLinkDesigner.GetDescription(
ADataBinding: TContainedBindComponent): string;
var
LBindList: TCustomBindList;
begin
Assert(ADataBinding is TCustomBindList);
LBindList := TCustomBindList(ADataBinding);
Result := FormatDisplayText(LBindList, sBindLinkDescription);
end;
{ TBindGridListLinkDesigner }
procedure TBindGridListLinkDesigner.AddExpressionCollections(
ABindList: TCustomBindGridList;
AList: TList<TBindCompDesignExpressionCollection>);
begin
inherited;
AList.Add(TBindCompDesignExpressionCollection.Create(sPosControl, (ABindList as TCustomBindGridListLink).PosControlExpressions));
AList.Add(TBindCompDesignExpressionCollection.Create(sPosSource, (ABindList as TCustomBindGridListLink).PosSourceExpressions));
AList.Add(TBindCompDesignExpressionCollection.Create(sParse, (ABindList as TCustomBindGridListLink).ParseExpressions));
end;
procedure TBindGridListLinkDesigner.AddExpressions(ABindComp: TCustomBindGridList;
const AControlScopeName, ASourceScopeName, ASourceMemberScopeName: string;
AList: TList<TBindCompDesignExpression>);
var
LBindComp: TCustomBindGridListLink;
LIndex: Integer;
LExpression: TExpressionItem;
begin
inherited;
LBindComp := ABindComp as TCustomBindGridListLink;
for LIndex := 0 to LBindComp.PosControlExpressions.Count - 1 do
begin
LExpression := LBindComp.PosControlExpressions[LIndex];
AList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index), AControlScopeName, LExpression.ControlExpression, // output
ASourceScopeName, LExpression.SourceExpression, // value
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToControlExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback, TBindCompExpressionType.exprPosControl);
// LBindComp.ExecuteAssignToControlExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// begin
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// if AValue <> nil then
// LBindComp.EvaluateControlExpression(AControlExpression,
// ACallback, TBindCompExpressionType.exprPosControl)
// else
// ACallback(AValue)
// end,
// TBindCompExpressionType.exprPosControl);
end,
nil,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression,
ACallback, TBindCompExpressionType.exprPosControl);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression,
ACallback, TBindCompExpressionType.exprPosControl);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
// Anon capture doesn't seem to work here for LIndex, so use name
LBindComp.PosControlExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
LBindComp.PosControlExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
'',
nil, // parent collection item
exprSourceToControl));
end;
for LIndex := 0 to LBindComp.PosSourceExpressions.Count - 1 do
begin
LExpression := LBindComp.PosSourceExpressions[LIndex];
AList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index),
AControlScopeName, LExpression.ControlExpression,
ASourceScopeName, LExpression.SourceExpression,
nil,
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToSourceExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback, TBindCompExpressionType.exprPosSource);
// LBindComp.ExecuteAssignToSourceExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// begin
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// if AValue <> nil then
// LBindComp.EvaluateControlExpression(ASourceExpression,
// ACallback, TBindCompExpressionType.exprPosSource)
// else
// ACallback(AValue)
// end,
// TBindCompExpressionType.exprPosSource);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression,
ACallback, TBindCompExpressionType.exprPosSource);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression,
ACallback, TBindCompExpressionType.exprPosSource);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
LBindComp.PosSourceExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
// Anon capture doesn't seem to work here for LIndex, so use name
LBindComp.PosSourceExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
'',
nil, // parent collection item
exprControlToSource));
end;
for LIndex := 0 to LBindComp.ParseExpressions.Count - 1 do
begin
LExpression := LBindComp.ParseExpressions[LIndex];
AList.Add(TBindCompDesignExpression.Create(
IntToStr(LExpression.Index),
AControlScopeName, LExpression.ControlExpression,
ASourceScopeName, LExpression.SourceExpression,
nil,
procedure(const AName: string; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>) // Execute
begin
ExecuteAssignToSourceExpression(LBindComp, AControlExpression, ASourceExpression,
ACallback, TBindCompExpressionType.exprParse);
// LBindComp.ExecuteAssignToSourceExpression(AControlExpression, ASourceExpression,
// procedure(AValue: IValue)
// begin
// // Display value of output expression in case it is a TObject. This allows visualizers work on TObject
// if AValue <> nil then
// LBindComp.EvaluateSourceExpression(AControlExpression, ACallback,
// TBindCompExpressionType.exprParse)
// else
// ACallback(AValue)
// end,
// TBindCompExpressionType.exprParse);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Control
begin
LBindComp.EvaluateControlExpression(AExpression,
ACallback, TBindCompExpressionType.exprParse);
end,
procedure(const AName: string; const AExpression: string; ACallback: TProc<IValue>) // Execute Source
begin
LBindComp.EvaluateSourceExpression(AExpression,
ACallback, TBindCompExpressionType.exprParse);
end,
procedure(const AName: string; const AExpression: string) // Save Control
begin
LBindComp.ParseExpressions[StrToInt(AName)].ControlExpression := AExpression;
end,
procedure(const AName: string; const AExpression: string) // Save Source
begin
// Anon capture doesn't seem to work here for LIndex, so use name
LBindComp.ParseExpressions[StrToInt(AName)].SourceExpression := AExpression;
end,
LExpression,
SParse,
nil, // parent collection item
exprSourceToControl));
end;
end;
function TBindGridListLinkDesigner.GetDescription(
ADataBinding: TContainedBindComponent): string;
var
LBindList: TCustomBindGridListLink;
begin
Assert(ADataBinding is TCustomBindGridListLink);
LBindList := TCustomBindGridListLink(ADataBinding);
Result := FormatDisplayText(LBindList, sBindLinkDescription);
end;
{ TBindCompDelegateDesigner }
function TBindCompDelegateDesigner.TryGetDelegates(ADataBinding: TContainedBindComponent;
out ADelegateComponent: TContainedBindComponent; out ADelegateDesigner: IBindCompDesigner): Boolean;
begin
ADelegateComponent := GetDelegate(ADataBinding);
if ADelegateComponent <> nil then
ADelegateDesigner := Data.Bind.Components.GetBindCompDesigner(TContainedBindCompClass(ADelegateComponent.ClassType))
else
ADelegateDesigner := nil;
Result := (ADelegateComponent <> nil) and (ADelegateDesigner <> nil);
end;
function TBindCompDelegateDesigner.GetDescription(
ADataBinding: TContainedBindComponent): string;
var
LDelegateDesigner: IBindCompDesigner;
LDelegateComponent: TContainedBindComponent;
begin
if TryGetDelegates(ADataBinding, LDelegateComponent, LDelegateDesigner) then
Result := LDelegateDesigner.GetDescription(LDelegateComponent)
else
Result := '';
end;
function TBindCompDelegateDesigner.GetExpressionCollections(
ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>;
var
LDelegateDesigner: IBindCompDesigner;
LDelegateComponent: TContainedBindComponent;
LCollections: TList<TBindCompDesignExpressionCollection>;
begin
LCollections := TList<TBindCompDesignExpressionCollection>.Create;
try
if TryGetDelegates(ADataBinding, LDelegateComponent, LDelegateDesigner) then
begin
LCollections.AddRange(LDelegateDesigner.GetExpressionCollections(LDelegateComponent));
DeleteEmptyCollections(LCollections);
end;
Result := LCollections.ToArray;
finally
LCollections.Free;
end;
end;
function TBindCompDelegateDesigner.GetExpressions(
ADataBinding: TContainedBindComponent;
out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>;
var
LDelegateDesigner: IBindCompDesigner;
LDelegateComponent: TContainedBindComponent;
begin
if TryGetDelegates(ADataBinding, LDelegateComponent, LDelegateDesigner) then
Result := LDelegateDesigner.GetExpressions(LDelegateComponent, ATypes)
else
SetLength(Result, 0);
end;
{ TReadOnlyBindCompDelegateDesigner }
function TReadOnlyBindCompDelegateDesigner.IsReadOnly(ABindComp: TContainedBindComponent;
AExpression: TBindCompDesignExpression): Boolean;
begin
Result := True;
end;
function TReadOnlyBindCompDelegateDesigner.IsReadOnly(ABindComp: TContainedBindComponent; AItem: TCollectionItem): Boolean;
begin
Result := True;
end;
procedure TReadOnlyBindCompDelegateDesigner.DeleteEmptyCollections(
AList: TList<TBindCompDesignExpressionCollection>);
var
I: Integer;
begin
for I := AList.Count - 1 downto 0 do // Remove empty collections
if AList[I].Collection.Count = 0 then
AList.Delete(I);
end;
function TReadOnlyBindCompDelegateDesigner.IsReadOnly(ABindComp: TContainedBindComponent;
ACollection: TCollection): Boolean;
begin
Result := True;
end;
{ TBindCompDelegatesDesigner }
function TBindCompDelegatesDesigner.TryGetDelegates(ADataBinding: TContainedBindComponent;
out ADelegateComponents: TArray<TContainedBindComponent>; out ADelegateDesigners: TArray<IBindCompDesigner>): Boolean;
var
LComponent: TContainedBindComponent;
LDesigners: TList<IBindCompDesigner>;
begin
LDesigners := TList<IBindCompDesigner>.Create;
try
ADelegateComponents := GetDelegates(ADataBinding);
for LComponent in ADelegateComponents do
if LComponent <> nil then
LDesigners.Add(Data.Bind.Components.GetBindCompDesigner(TContainedBindCompClass(LComponent.ClassType)));
ADelegateDesigners := LDesigners.ToArray;
Result := (Length(ADelegateComponents) <> 0) and (Length(ADelegateDesigners) <> 0);
finally
LDesigners.Free;
end;
end;
function TBindCompDelegatesDesigner.GetDescription(
ADataBinding: TContainedBindComponent): string;
var
LDelegateDesigners: TArray<IBindCompDesigner>;
LDelegateComponents: TArray<TContainedBindComponent>;
begin
if TryGetDelegates(ADataBinding, LDelegateComponents, LDelegateDesigners) and
(LDelegateDesigners[0] <> nil) then
Result := LDelegateDesigners[0].GetDescription(LDelegateComponents[0])
else
Result := '';
end;
function TBindCompDelegatesDesigner.GetExpressionCollections(
ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>;
var
LDelegateDesigners: TArray<IBindCompDesigner>;
LDelegateComponents: TArray<TContainedBindComponent>;
LCollections: TList<TBindCompDesignExpressionCollection>;
I: Integer;
begin
if TryGetDelegates(ADataBinding, LDelegateComponents, LDelegateDesigners) then
begin
LCollections := TList<TBindCompDesignExpressionCollection>.Create;
try
Assert(Length(LDelegateDesigners) = Length(LDelegateComponents));
for I := 0 to Length(LDelegateDesigners) - 1 do
if LDelegateDesigners[I] <> nil then
LCollections.AddRange(LDelegateDesigners[I].GetExpressionCollections(LDelegateComponents[I]));
DeleteEmptyCollections(LCollections);
// for I := LCollections.Count - 1 downto 0 do // Remove empty collections
// if LCollections[I].Collection.Count = 0 then
// if IsReadOnly(ADataBinding, LCollections[I].Collection) then
// LCollections.Delete(I);
Result := LCollections.ToArray;
finally
LCollections.Free;
end;
end
else
SetLength(Result, 0);
end;
function TBindCompDelegatesDesigner.GetExpressions(
ADataBinding: TContainedBindComponent;
out ATypes: TBindCompDesignerExpressionTypes): TArray<TBindCompDesignExpression>;
var
LDelegateDesigners: TArray<IBindCompDesigner>;
LDelegateComponents: TArray<TContainedBindComponent>;
LExpressions: TList<TBindCompDesignExpression>;
I: Integer;
begin
if TryGetDelegates(ADataBinding, LDelegateComponents, LDelegateDesigners) then
begin
LExpressions := TList<TBindCompDesignExpression>.Create;
try
Assert(Length(LDelegateDesigners) = Length(LDelegateComponents));
for I := 0 to Length(LDelegateDesigners) - 1 do
if LDelegateDesigners[I] <> nil then
LExpressions.AddRange(LDelegateDesigners[I].GetExpressions(LDelegateComponents[I], ATypes));
Result := LExpressions.ToArray;
finally
LExpressions.Free;
end;
end
else
SetLength(Result, 0);
end;
{ TCustomBindDBFieldLinkDesigner }
function TBindDBFieldLinkDesigner.GetDelegate(
ADataBinding: TContainedBindComponent): TContainedBindComponent;
var
LComponent: TBaseBindDBControlLink;
begin
LComponent := ADataBinding as TBaseBindDBControlLink;
Result := LComponent.GetDelegates[0];
end;
{ TBindDBFieldLinkDesigner_NoParse }
function TBindDBFieldLinkDesigner_NoParse.GetExpressionCollections(
ADataBinding: TContainedBindComponent): TArray<TBindCompDesignExpressionCollection>;
var
LCollection: TBindCompDesignExpressionCollection;
LList: TList<TBindCompDesignExpressionCollection>;
begin
Result := inherited;
// Exclude Parse collection because can't write label text to field
LList := TList<TBindCompDesignExpressionCollection>.Create;
try
for LCollection in Result do
begin
if LCollection.Name = sParse then
continue;
LList.Add(LCollection);
end;
Result := LList.ToArray;
finally
LList.Free;
end;
end;
procedure Register;
begin
RegisterBindCompDesigner(TCustomBindExpression, TBindExpressionDesigner.Create);
RegisterBindCompDesigner(TCustomBindExprItems, TBindExprItemsDesigner.Create);
RegisterBindCompDesigner(TCustomBindLink, TBindLinkDesigner.Create);
RegisterBindCompDesigner(TCustomLinkControlToField, TLinkControlToFieldDesigner.Create);
RegisterBindCompDesigner(TCustomLinkFillControlToField, TLinkFillControlToFieldDesigner.Create);
RegisterBindCompDesigner(TCustomLinkControlToProperty, TLinkControlToPropertyDesigner.Create);
RegisterBindCompDesigner(TCustomLinkFillControlToProperty, TLinkFillControlToPropertyDesigner.Create);
RegisterBindCompDesigner(TCustomLinkListControlToField, TLinkListControlToFieldDesigner.Create);
RegisterBindCompDesigner(TCustomLinkPropertyToField, TLinkPropertyToFieldDesigner.Create);
RegisterBindCompDesigner(TCustomBindList, TBindListDesigner.Create);
RegisterBindCompDesigner(TCustomBindGridLink, TBindGridLinkDesigner.Create);
RegisterBindCompDesigner(TCustomBindListLink, TBindListLinkDesigner.Create);
RegisterBindCompDesigner(TCustomBindGridList, TBindGridListDesigner.Create);
RegisterBindCompDesigner(TCustomBindGridListLink, TBindGridListLinkDesigner.Create);
RegisterBindCompDesigner(TCustomBindPosition, TBindPositionDesigner.Create);
RegisterBindCompDesigner(TCustomBindControlValue, TBindControlValueDesigner.Create);
RegisterBindCompDesigner(TExpressionsBindComponent, TExpressionsBindComponentDesigner.Create);
end;
{ TCommonBindComponentDesigner }
function TBindCompDesigner.FormatDisplayText(
ABindComponent: TCommonBindComponent; const AFormatString: string): string;
begin
Result := FormatDisplayText(ABindComponent, AFormatString,
ABindComponent.SourceMemberName);
end;
function TBindCompDesigner.FormatDisplayText(
ABindComponent: TCommonBindComponent; const AFormatString: string;
const ASourceMemberName: string): string;
var
LControlScope: string;
LSourceScope: string;
begin
if ABindComponent.SourceComponent <> nil then
LSourceScope := ABindComponent.SourceComponent.Name;
if ASourceMemberName <> '' then
LSourceScope := LSourceScope + ', ' + ASourceMemberName;
if ABindComponent.ControlComponent <> nil then
LControlScope := ABindComponent.ControlComponent.Name;
Result := Format(AFormatString (*sBindListDescription*), [LControlScope, LSourceScope]);
end;
function TBindCompDesigner.FormatDisplayText(
ABindComponent: TCommonBindComponent; const AFormatString: string; ACount: Integer): string;
var
LControlScope: string;
LSourceScope: string;
begin
if ABindComponent.SourceComponent <> nil then
LSourceScope := ABindComponent.SourceComponent.Name;
if ABindComponent.SourceMemberName <> '' then
LSourceScope := LSourceScope + ', ' + ABindComponent.SourceMemberName;
if ABindComponent.ControlComponent <> nil then
LControlScope := ABindComponent.ControlComponent.Name;
Result := Format(AFormatString (*sBindListDescription*), [LControlScope, LSourceScope, ACount]);
end;
function TCommonBindComponentDesigner.ControlScopeName(
ABindComp: TCommonBindComponent): string;
begin
if ABindComp.ControlComponent <> nil then
Result := ABindComp.ControlComponent.Name
else
Result := '';
end;
function TCommonBindComponentDesigner.SourceScopeName(
ABindComp: TCommonBindComponent): string;
begin
if ABindComp.SourceComponent <> nil then
Result := ABindComp.SourceComponent.Name
else
Result := '';
end;
function TCommonBindComponentDesigner.SourceMemberScopeName(
ABindComp: TCommonBindComponent): string;
begin
Result := SourceScopeName(ABindComp);
if ABindComp.SourceMemberName <> '' then
Result := Result + ', ' + ABindComp.SourceMemberName;
end;
procedure TCommonBindComponentDesigner.ExecuteAssignToControlExpression(
ABindComp: TCommonBindComponent; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>;
AType: TBindCompExpressionType);
begin
ABindComp.ExecuteAssignToControlExpression(AControlExpression, ASourceExpression,
procedure(AValue: IValue)
begin
// Display value of output expression in case it is a TObject. This allows visualizers work on TObject
if AValue <> nil then
ABindComp.EvaluateControlExpression(AControlExpression, ACallback)
else
ACallback(AValue);
end);
end;
procedure TCommonBindComponentDesigner.ExecuteAssignToSourceExpression(
ABindComp: TCommonBindComponent; const AControlExpression, ASourceExpression: string; ACallback: TProc<IValue>;
AType: TBindCompExpressionType);
begin
ABindComp.ExecuteAssignToSourceExpression(AControlExpression, ASourceExpression,
procedure(AValue: IValue)
begin
// Display value of output expression in case it is a TObject. This allows visualizers work on TObject
if AValue <> nil then
ABindComp.EvaluateSourceExpression(ASourceExpression, ACallback, AType)
else
ACallback(AValue)
end, AType);
end;
{ TQuickBindLinkDesigner }
function TQuickBindingDesigner.GetDelegate(
ADataBinding: TContainedBindComponent): TContainedBindComponent;
var
LComponent: TBindComponentDelegate;
begin
LComponent := ADataBinding as TBindComponentDelegate;
Result := LComponent.GetDelegates[0];
end;
{ TBindControlToPropertyDesigner }
function TLinkControlToPropertyDesigner.GetDescription(
ADataBinding: TContainedBindComponent): string;
var
LBinding: TCustomLinkControlToProperty;
begin
Assert(ADataBinding is TCustomLinkControlToProperty);
LBinding := TCustomLinkControlToProperty(ADataBinding);
Result := FormatDisplayText(LBinding.GetDelegates[0], sBindControlValueDescription,
LBinding.ComponentProperty);
end;
{ TQuickBindingDesignerMultiDelegates }
function TQuickBindingDesignerMultiDelegates.GetDelegates(
ADataBinding: TContainedBindComponent): TArray<TContainedBindComponent>;
var
LComponents: TArray<TCommonBindComponent>;
LComponent: TContainedBindComponent;
LResult: TList<TContainedBindComponent>;
begin
LResult := TList<TContainedBindComponent>.Create;
try
LComponents := (ADataBinding as TBindComponentDelegate).GetDelegates;
for LComponent in LComponents do
begin
LResult.Add(LComponent);
end;
Result := LResult.ToArray;
finally
LResult.Free;
end;
end;
end.
|
//******************************************************************************
//*** SCRIPT VCL FUNCTIONS ***
//*** ***
//*** (c) Massimo Magnano 2006 ***
//*** ***
//*** ***
//******************************************************************************
// File : Lua_Controls.pas (rev. 1.0)
//
// Description : Access from Lua scripts to Class declared in "Controls.pas"
//
//******************************************************************************
// TO-DO : Record like TRect, TPoint property how can i return in variant(lua)
unit Script_Controls;
interface
uses TypInfo, Script_Classes;
type
TScriptControl = class(TScriptComponent)
protected
class function GetPublicPropertyAccessClass :TClass; override;
end;
TScriptWinControl = class(TScriptControl)
protected
class function GetPublicPropertyAccessClass :TClass; override;
public
function GetArrayPropType(Name :String; index :Variant) :PTypeInfo; override;
function GetArrayProp(Name :String; index :Variant) :Variant; override;
function GetElementType(Name :String) :PTypeInfo; override;
end;
implementation
uses Classes, Controls, SysUtils, Variants, Script_System;
type
TControlAccess = class(TControl)
published
property Enabled;
property Action;
property Align;
property Anchors;
property BiDiMode;
property BoundsRect;
property ClientHeight;
property ClientOrigin;
property ClientRect;
property ClientWidth;
property Constraints;
property ControlState;
property ControlStyle;
property DockOrientation;
property Floating;
property FloatingDockSiteClass;
property HostDockSite;
property LRDockWidth;
property Parent;
property ShowHint;
property TBDockHeight;
property UndockHeight;
property UndockWidth;
property Visible;
//property WindowProc; pericolosa.
end;
TWinControlAccess = class(TWinControl)
published
// See Comment on TScriptObject.GetPublicPropInfo, it explain why i have no need
// to redeclare also the public property of TControl
property DockClientCount;
property DockSite;
property DockManager;
property DoubleBuffered;
property AlignDisabled;
property VisibleDockClientCount;
property Brush;
property ControlCount;
property Handle;
property ParentWindow;
property Showing;
property TabOrder;
property TabStop;
property UseDockManager;
end;
class function TScriptControl.GetPublicPropertyAccessClass :TClass;
begin
Result :=TControlAccess;
end;
//==============================================================================
//
class function TScriptWinControl.GetPublicPropertyAccessClass :TClass;
begin
Result :=TWinControlAccess;
end;
function TScriptWinControl.GetArrayPropType(Name :String; index :Variant) :PTypeInfo;
begin
Name :=Uppercase(Name);
Result :=nil;
if (Name='CONTROLS')
then begin
if (TWinControl(InstanceObj).Controls[index]<>nil)
then Result :=TypeInfo(TControl);
end
else
if (Name='DOCKCLIENTS')
then begin
if (TWinControl(InstanceObj).DockClients[index]<>nil)
then Result :=TypeInfo(TControl);
end
else
Result :=inherited GetArrayPropType(Name, index);
end;
function TScriptWinControl.GetArrayProp(Name :String; index :Variant) :Variant;
begin
Name :=Uppercase(Name);
if (Name='CONTROLS')
then begin
if (TWinControl(InstanceObj).Controls[index]<>nil)
then Result :=Integer(TWinControl(InstanceObj).Controls[index])
else Result :=NULL;
end
else
if (Name='DOCKCLIENTS')
then begin
if (TWinControl(InstanceObj).DockClients[index]<>nil)
then Result :=Integer(TWinControl(InstanceObj).DockClients[index])
else Result :=NULL;
end
else
Result := inherited GetArrayProp(name, index)
end;
function TScriptWinControl.GetElementType(Name :String) :PTypeInfo;
Var
upName :String;
begin
upName :=Uppercase(Name);
if (upName='CONTROLS') or (upName='DOCKCLIENTS')
then Result :=@TypeInfoArray
else Result :=inherited GetElementType(Name);
end;
initialization
Script_System.RegisterClass(TControl, TScriptControl);
Script_System.RegisterClass(TWinControl, TScriptWinControl);
end.
|
unit EnumHelper;
{$IFDEF FPC}{$MODE DELPHI}{$ENDIF}
interface
type
TEnumHelper<T> = class
class function EnumToStr(const Value: T): String;
class function StrToEnum(const Value: String): T;
class procedure CheckArraysEqual(const Left, Right: array of T);
class function ArrayToString(const Arr: array of T): String;
end;
implementation
uses
typinfo, fpcunit;
class function TEnumHelper<T>.EnumToStr(const Value: T): String;
var
TInfo : PTypeInfo;
begin
TInfo := TypeInfo(T);
Result := GetEnumName(TInfo, PByte(@Value)^);
end;
class function TEnumHelper<T>.StrToEnum(const Value: String): T;
var
TInfo : PTypeInfo;
i : Byte;
pt : ^T;
begin
TInfo := TypeInfo(T);
i := GetEnumValue(TInfo, Value);
pt := @i;
Result := pt^;
end;
class procedure TEnumHelper<T>.CheckArraysEqual(const Left, Right: array of T);
begin
TAssert.AssertEquals(ArrayToString(Left), ArrayToString(Right));
end;
class function TEnumHelper<T>.ArrayToString(const Arr: array of T): String;
var
ElementList, ElementString: String;
Element: T;
begin
ElementList := '';
for Element in Arr do
begin
if ElementList <> '' then
ElementList := ElementList + ', ';
ElementString := EnumToStr(Element);
ElementList := ElementList + ElementString;
end;
Result := '[' + ElementList + ']';
end;
end. |
{***************************************************************************}
{ }
{ XML Data Binding }
{ }
{ Generated on: 6/11/2002 12:51:22 PM }
{ Generated from: http://schemas.xmlsoap.org/ws/2001/10/inspection/ }
{ }
{***************************************************************************}
unit Soap.WSILIntf;
interface
uses Xml.xmldom, Xml.XMLDoc, Xml.XMLIntf;
type
{ Forward Decls }
IXMLItemWithAbstracts = interface;
IXMLServiceType = interface;
IXMLServiceTypeList = interface;
IXMLNameType = interface;
IXMLNameTypeList = interface;
IXMLReferenceType = interface;
IXMLLinkType = interface;
IXMLLinkTypeList = interface;
IXMLTypeOfAbstract = interface;
IXMLInspection = interface;
IXMLDescriptionType = interface;
IXMLDescriptionTypeList = interface;
{ IXMLItemWithAbstracts }
IXMLItemWithAbstracts = interface(IXMLNodeCollection)
['{33E53FE0-14E5-4D18-A0AE-19FEE8CF6403}']
{ Property Accessors }
function Get_Abstract(Index: Integer): IXMLTypeOfAbstract;
{ Methods & Properties }
function Add: IXMLTypeOfAbstract;
function Insert(const Index: Integer): IXMLTypeOfAbstract;
property Abstract[Index: Integer]: IXMLTypeOfAbstract read Get_Abstract; default;
end;
{ IXMLServiceType }
IXMLServiceType = interface(IXMLItemWithAbstracts)
['{EC832C01-CF74-4207-9884-4027134D80F2}']
{ Property Accessors }
function Get_Name: IXMLNameTypeList;
function Get_Description: IXMLDescriptionTypeList;
{ Methods & Properties }
property Name: IXMLNameTypeList read Get_Name;
property Description: IXMLDescriptionTypeList read Get_Description;
end;
{ IXMLServiceTypeList }
IXMLServiceTypeList = interface(IXMLNodeCollection)
['{3E5EC7EF-3355-4D9A-8987-7067A9CAFBC7}']
{ Methods & Properties }
function Add: IXMLServiceType;
function Insert(const Index: Integer): IXMLServiceType;
function Get_Item(Index: Integer): IXMLServiceType;
property Items[Index: Integer]: IXMLServiceType read Get_Item; default;
end;
{ IXMLNameType }
IXMLNameType = interface(IXMLNode)
['{60F42F94-6754-40EB-8889-00D7BD607240}']
{ Property Accessors }
function Get_Lang: WideString;
procedure Set_Lang(Value: WideString);
{ Methods & Properties }
property Lang: WideString read Get_Lang write Set_Lang;
end;
{ IXMLNameTypeList }
IXMLNameTypeList = interface(IXMLNodeCollection)
['{5DAA8A82-A27D-49DF-A154-52351CBB8A7F}']
{ Methods & Properties }
function Add: IXMLNameType;
function Insert(const Index: Integer): IXMLNameType;
function Get_Item(Index: Integer): IXMLNameType;
property Items[Index: Integer]: IXMLNameType read Get_Item; default;
end;
{ IXMLReferenceType }
IXMLReferenceType = interface(IXMLItemWithAbstracts)
['{94130F0C-0F07-4FDE-9A59-C5079D7952A0}']
{ Property Accessors }
function Get_ReferencedNamespace: WideString;
function Get_Location: WideString;
procedure Set_ReferencedNamespace(Value: WideString);
procedure Set_Location(Value: WideString);
{ Methods & Properties }
property ReferencedNamespace: WideString read Get_ReferencedNamespace write Set_ReferencedNamespace;
property Location: WideString read Get_Location write Set_Location;
end;
{ IXMLLinkType }
IXMLLinkType = interface(IXMLReferenceType)
['{84A1F2BC-E4CA-4187-8B62-DEBB01F8BE8F}']
end;
{ IXMLLinkTypeList }
IXMLLinkTypeList = interface(IXMLNodeCollection)
['{64415871-3494-4B46-A34C-A47BF53AABEE}']
{ Methods & Properties }
function Add: IXMLLinkType;
function Insert(const Index: Integer): IXMLLinkType;
function Get_Item(Index: Integer): IXMLLinkType;
property Items[Index: Integer]: IXMLLinkType read Get_Item; default;
end;
{ IXMLTypeOfAbstract }
IXMLTypeOfAbstract = interface(IXMLNode)
['{49BD4FF9-04D5-41C4-B08C-66A17F7DCB18}']
{ Property Accessors }
function Get_Lang: WideString;
procedure Set_Lang(Value: WideString);
{ Methods & Properties }
property Lang: WideString read Get_Lang write Set_Lang;
end;
{ IXMLInspection }
IXMLInspection = interface(IXMLItemWithAbstracts)
['{9188C201-D00D-44B9-80A6-6C55D820879F}']
{ Property Accessors }
function Get_Service: IXMLServiceTypeList;
function Get_Link: IXMLLinkTypeList;
{ Methods & Properties }
property Service: IXMLServiceTypeList read Get_Service;
property Link: IXMLLinkTypeList read Get_Link;
end;
{ IXMLDescriptionType }
IXMLDescriptionType = interface(IXMLReferenceType)
['{620E7125-E033-4B8B-B5AE-A18F26864411}']
end;
{ IXMLDescriptionTypeList }
IXMLDescriptionTypeList = interface(IXMLNodeCollection)
['{9A62AF8B-F404-4655-8175-1E899C78F668}']
{ Methods & Properties }
function Add: IXMLDescriptionType;
function Insert(const Index: Integer): IXMLDescriptionType;
function Get_Item(Index: Integer): IXMLDescriptionType;
property Items[Index: Integer]: IXMLDescriptionType read Get_Item; default;
end;
{ Forward Decls }
TXMLItemWithAbstracts = class;
TXMLServiceType = class;
TXMLServiceTypeList = class;
TXMLNameType = class;
TXMLNameTypeList = class;
TXMLReferenceType = class;
TXMLLinkType = class;
TXMLLinkTypeList = class;
TXMLTypeOfAbstract = class;
TXMLInspection = class;
TXMLDescriptionType = class;
TXMLDescriptionTypeList = class;
{ TXMLItemWithAbstracts }
TXMLItemWithAbstracts = class(TXMLNodeCollection, IXMLItemWithAbstracts)
protected
{ IXMLItemWithAbstracts }
function Get_Abstract(Index: Integer): IXMLTypeOfAbstract;
function Add: IXMLTypeOfAbstract;
function Insert(const Index: Integer): IXMLTypeOfAbstract;
public
procedure AfterConstruction; override;
end;
{ TXMLServiceType }
TXMLServiceType = class(TXMLItemWithAbstracts, IXMLServiceType)
private
FName: IXMLNameTypeList;
FDescription: IXMLDescriptionTypeList;
protected
{ IXMLServiceType }
function Get_Name: IXMLNameTypeList;
function Get_Description: IXMLDescriptionTypeList;
public
procedure AfterConstruction; override;
end;
{ TXMLServiceTypeList }
TXMLServiceTypeList = class(TXMLNodeCollection, IXMLServiceTypeList)
protected
{ IXMLServiceTypeList }
function Add: IXMLServiceType;
function Insert(const Index: Integer): IXMLServiceType;
function Get_Item(Index: Integer): IXMLServiceType;
end;
{ TXMLNameType }
TXMLNameType = class(TXMLNode, IXMLNameType)
protected
{ IXMLNameType }
function Get_Lang: WideString;
procedure Set_Lang(Value: WideString);
end;
{ TXMLNameTypeList }
TXMLNameTypeList = class(TXMLNodeCollection, IXMLNameTypeList)
protected
{ IXMLNameTypeList }
function Add: IXMLNameType;
function Insert(const Index: Integer): IXMLNameType;
function Get_Item(Index: Integer): IXMLNameType;
end;
{ TXMLReferenceType }
TXMLReferenceType = class(TXMLItemWithAbstracts, IXMLReferenceType)
protected
{ IXMLReferenceType }
function Get_ReferencedNamespace: WideString;
function Get_Location: WideString;
procedure Set_ReferencedNamespace(Value: WideString);
procedure Set_Location(Value: WideString);
end;
{ TXMLLinkType }
TXMLLinkType = class(TXMLReferenceType, IXMLLinkType)
protected
{ IXMLLinkType }
end;
{ TXMLLinkTypeList }
TXMLLinkTypeList = class(TXMLNodeCollection, IXMLLinkTypeList)
protected
{ IXMLLinkTypeList }
function Add: IXMLLinkType;
function Insert(const Index: Integer): IXMLLinkType;
function Get_Item(Index: Integer): IXMLLinkType;
end;
{ TXMLTypeOfAbstract }
TXMLTypeOfAbstract = class(TXMLNode, IXMLTypeOfAbstract)
protected
{ IXMLTypeOfAbstract }
function Get_Lang: WideString;
procedure Set_Lang(Value: WideString);
end;
{ TXMLInspection }
TXMLInspection = class(TXMLItemWithAbstracts, IXMLInspection)
private
FService: IXMLServiceTypeList;
FLink: IXMLLinkTypeList;
protected
{ IXMLInspection }
function Get_Service: IXMLServiceTypeList;
function Get_Link: IXMLLinkTypeList;
public
procedure AfterConstruction; override;
end;
{ TXMLDescriptionType }
TXMLDescriptionType = class(TXMLReferenceType, IXMLDescriptionType)
protected
{ IXMLDescriptionType }
end;
{ TXMLDescriptionTypeList }
TXMLDescriptionTypeList = class(TXMLReferenceType, IXMLDescriptionTypeList)
protected
{ IXMLDescriptionTypeList }
function Add: IXMLDescriptionType;
function Insert(const Index: Integer): IXMLDescriptionType;
function Get_Item(Index: Integer): IXMLDescriptionType;
end;
{ Global Functions }
function Getinspection(Doc: IXMLDocument): IXMLInspection;
function Loadinspection(const FileName: WideString): IXMLInspection;
function Newinspection: IXMLInspection;
const
SInspectionNS = 'http://schemas.xmlsoap.org/ws/2001/10/inspection/';
implementation
{ Global Functions }
function Getinspection(Doc: IXMLDocument): IXMLInspection;
begin
Result := Doc.GetDocBinding('inspection', TXMLInspection, SInspectionNS) as IXMLInspection;
end;
function Loadinspection(const FileName: WideString): IXMLInspection;
begin
Result := LoadXMLDocument(FileName).GetDocBinding('inspection', TXMLInspection, SInspectionNS) as IXMLInspection;
end;
function Newinspection: IXMLInspection;
begin
Result := NewXMLDocument.GetDocBinding('inspection', TXMLInspection, SInspectionNS) as IXMLInspection;
end;
{ TXMLItemWithAbstracts }
procedure TXMLItemWithAbstracts.AfterConstruction;
begin
RegisterChildNode('abstract', TXMLTypeOfAbstract);
ItemTag := 'abstract';
ItemNS := SInspectionNS;
ItemInterface := IXMLTypeOfAbstract;
inherited;
end;
function TXMLItemWithAbstracts.Get_Abstract(Index: Integer): IXMLTypeOfAbstract;
begin
Result := List[Index] as IXMLTypeOfAbstract;
end;
function TXMLItemWithAbstracts.Add: IXMLTypeOfAbstract;
begin
Result := AddItem(-1) as IXMLTypeOfAbstract;
end;
function TXMLItemWithAbstracts.Insert(const Index: Integer): IXMLTypeOfAbstract;
begin
Result := AddItem(Index) as IXMLTypeOfAbstract;
end;
{ TXMLServiceType }
procedure TXMLServiceType.AfterConstruction;
begin
RegisterChildNode('name', TXMLNameType);
RegisterChildNode('description', TXMLDescriptionType);
FName := CreateCollection(TXMLNameTypeList, IXMLNameType, 'name') as IXMLNameTypeList;
FDescription := CreateCollection(TXMLDescriptionTypeList, IXMLDescriptionType, 'description') as IXMLDescriptionTypeList;
inherited;
end;
function TXMLServiceType.Get_Name: IXMLNameTypeList;
begin
Result := FName;
end;
function TXMLServiceType.Get_Description: IXMLDescriptionTypeList;
begin
Result := FDescription;
end;
{ TXMLServiceTypeList }
function TXMLServiceTypeList.Add: IXMLServiceType;
begin
Result := AddItem(-1) as IXMLServiceType;
end;
function TXMLServiceTypeList.Insert(const Index: Integer): IXMLServiceType;
begin
Result := AddItem(Index) as IXMLServiceType;
end;
function TXMLServiceTypeList.Get_Item(Index: Integer): IXMLServiceType;
begin
Result := List[Index] as IXMLServiceType;
end;
{ TXMLNameType }
function TXMLNameType.Get_Lang: WideString;
begin
Result := AttributeNodes['xml:lang'].Text;
end;
procedure TXMLNameType.Set_Lang(Value: WideString);
begin
SetAttribute('xml:lang', Value);
end;
{ TXMLNameTypeList }
function TXMLNameTypeList.Add: IXMLNameType;
begin
Result := AddItem(-1) as IXMLNameType;
end;
function TXMLNameTypeList.Insert(const Index: Integer): IXMLNameType;
begin
Result := AddItem(Index) as IXMLNameType;
end;
function TXMLNameTypeList.Get_Item(Index: Integer): IXMLNameType;
begin
Result := List[Index] as IXMLNameType;
end;
{ TXMLReferenceType }
function TXMLReferenceType.Get_ReferencedNamespace: WideString;
begin
Result := AttributeNodes['referencedNamespace'].Text;
end;
procedure TXMLReferenceType.Set_ReferencedNamespace(Value: WideString);
begin
SetAttribute('referencedNamespace', Value);
end;
function TXMLReferenceType.Get_Location: WideString;
begin
Result := AttributeNodes['location'].Text;
end;
procedure TXMLReferenceType.Set_Location(Value: WideString);
begin
SetAttribute('location', Value);
end;
{ TXMLLinkType }
{ TXMLLinkTypeList }
function TXMLLinkTypeList.Add: IXMLLinkType;
begin
Result := AddItem(-1) as IXMLLinkType;
end;
function TXMLLinkTypeList.Insert(const Index: Integer): IXMLLinkType;
begin
Result := AddItem(Index) as IXMLLinkType;
end;
function TXMLLinkTypeList.Get_Item(Index: Integer): IXMLLinkType;
begin
Result := List[Index] as IXMLLinkType;
end;
{ TXMLTypeOfAbstract }
function TXMLTypeOfAbstract.Get_Lang: WideString;
begin
Result := AttributeNodes['xml:lang'].Text;
end;
procedure TXMLTypeOfAbstract.Set_Lang(Value: WideString);
begin
SetAttribute('xml:lang', Value);
end;
{ TXMLInspection }
procedure TXMLInspection.AfterConstruction;
begin
RegisterChildNode('service', TXMLServiceType);
RegisterChildNode('link', TXMLLinkType);
FService := CreateCollection(TXMLServiceTypeList, IXMLServiceType, 'service') as IXMLServiceTypeList;
FLink := CreateCollection(TXMLLinkTypeList, IXMLLinkType, 'link') as IXMLLinkTypeList;
inherited;
end;
function TXMLInspection.Get_Service: IXMLServiceTypeList;
begin
Result := FService;
end;
function TXMLInspection.Get_Link: IXMLLinkTypeList;
begin
Result := FLink;
end;
{ TXMLDescriptionType }
{ TXMLDescriptionTypeList }
function TXMLDescriptionTypeList.Add: IXMLDescriptionType;
begin
Result := AddItem(-1) as IXMLDescriptionType;
end;
function TXMLDescriptionTypeList.Insert(const Index: Integer): IXMLDescriptionType;
begin
Result := AddItem(Index) as IXMLDescriptionType;
end;
function TXMLDescriptionTypeList.Get_Item(Index: Integer): IXMLDescriptionType;
begin
Result := List[Index] as IXMLDescriptionType;
end;
end. |
{ $Log: C:\PROGRAM FILES\GP-VERSION LITE\Archives\Reve64\Source\ReveTypes.paV
{
{ Rev 1.0 28/09/03 20:28:22 Dgrava
{ Initial Revision
}
{
Rev 1.5 16-6-2003 21:13:13 DGrava
NegaScout refinement applied
}
{
Rev 1.4 15-6-2003 20:38:29 DGrava
Disabled forward pruning. Added Quiescens check.
}
{
Rev 1.3 10-3-2003 21:46:25 DGrava
Little enhancements.
}
{
Rev 1.2 20-2-2003 16:38:47 DGrava
Forward pruning implemented. Extending capture sequences
with conditional defines
}
{
Rev 1.1 6-2-2003 11:48:02 DGrava
Introduction of QuickEval component.
}
{
Rev 1.0 24-1-2003 21:12:24 DGrava
Eerste Check in.
Versie 0.27
}
{}
unit ReveTypes;
{This unit contains the native types and consts of my checker engine.}
interface
uses
CBTypes;
const
ENGINE_NAME = 'Reve64';
ENGINE_VERSION = '0.43'{$IFDEF QUIESCENSE_SEARCH}+'+'{$ENDIF}{$IFDEF DEBUG_REVE}+'Debug mode'{$ENDIF};
type
THashKey = Int64;
TBoard = array [1..32] of Integer;
TBoardStruct = record
Board : TBoard;
ColorToMove : Integer;
QuickEval : Integer;
HashKey : THashKey;
BlackMen : Integer;
BlackKings : Integer;
WhiteMen : Integer;
WhiteKings : Integer;
Tempo : Integer;
end;
const
// value for reve pieces
RP_WHITE = CB_WHITE; // 1
RP_BLACK = CB_BLACK; // 2
RP_MAN = CB_MAN; // 4
RP_KING = CB_KING; // 8
RP_FREE = 0;// CB_FREE; // 16
RP_BLACKMAN = RP_BLACK or RP_MAN;
RP_WHITEMAN = RP_WHITE or RP_MAN;
RP_BLACKKING = RP_BLACK or RP_KING;
RP_WHITEKING = RP_WHITE or RP_KING;
RP_KILLED = 32;
RP_CHANGECOLOR = 3;
// Evaluation values
WIN = 30000;
LOSS = - WIN;
MAN_VALUE = 1000;
KING_VALUE = 1300;
// Tempo values
BLACK_TEMPO : array [1..32] of Integer = (
-7, -7, -7, -7,
-6, -6, -6, -6,
-5, -5, -5, -5,
-4, -4, -4, -4,
-3, -3, -3, -3,
-2, -2, -2, -2,
-1, -1, -1, -1,
0, 0, 0, 0
);
WHITE_TEMPO : array [1..32] of Integer = (
0, 0, 0, 0,
-1, -1, -1, -1,
-2, -2, -2, -2,
-3, -3, -3, -3,
-4, -4, -4, -4,
-5, -5, -5, -5,
-6, -6, -6, -6,
-7, -7, -7, -7
);
implementation
{ $Log
25-11-2002, DG : Created.
}
end.
|
unit dm_Organisation;
interface
uses
SysUtils, Classes, DB, DBClient, ADODB;
type
TdmOrganisation = class(TDataModule)
Cities: TClientDataSet;
CitiesID: TFloatField;
CitiesEKATTE: TStringField;
CitiesName: TStringField;
CitiesKmetstvo: TStringField;
CitiesOblast: TStringField;
CitiesObstina: TStringField;
CitiesClone: TClientDataSet;
Organisations: TClientDataSet;
OrganisationsName: TStringField;
OrganisationsLevel: TIntegerField;
OrganisationsCode: TFloatField;
OrganisationsParent: TFloatField;
OrganisationsFullName: TStringField;
OrganisationsPhone: TStringField;
OrganisationsPhone2: TStringField;
OrganisationsPhone3: TStringField;
OrganisationsPosition: TStringField;
Positions: TClientDataSet;
PositionsCode1: TStringField;
PositionsCode2: TStringField;
PositionsCode: TStringField;
PositionsPositionName: TStringField;
PositionsClone: TClientDataSet;
OrganisationsEMail: TStringField;
OrganisationsNewCode: TFloatField;
CitiesKind: TIntegerField;
CitiesCategory: TIntegerField;
CitiesAltitude: TIntegerField;
CitiesDocument: TStringField;
CitiesTsb: TStringField;
CitiesRegion: TStringField;
CitiesPostCode: TStringField;
CitiesPhoneCode: TStringField;
CitiesLongitude: TStringField;
CitiesLatitude: TStringField;
CitiesLastChange: TDateTimeField;
OrganisationsDTMF: TStringField;
OrganisationsName2: TStringField;
OrganisationsName3: TStringField;
OrganisationsSite: TStringField;
Altitude: TClientDataSet;
Altitudealtitude: TStringField;
Altitudename: TStringField;
Kind: TClientDataSet;
Kindkind: TStringField;
Kindname: TStringField;
Kindfullname: TStringField;
Region: TClientDataSet;
Regionregion: TStringField;
Regionekatte: TStringField;
Regionname: TStringField;
Regiondocument: TStringField;
TSB: TClientDataSet;
TSBtsb: TStringField;
TSBname: TStringField;
OrganisationsObstina1: TStringField;
OrganisationsOblast1: TStringField;
OrganisationsObstina2: TStringField;
OrganisationsOblast2: TStringField;
OrganisationsCity1: TStringField;
OrganisationsCity2: TStringField;
CitiesNameHex: TStringField;
Raion: TClientDataSet;
Raionraion: TStringField;
Raionname: TStringField;
OrganisationsRaion1: TStringField;
OrganisationsRaion2: TStringField;
RaionClone: TClientDataSet;
Raionnamehex: TStringField;
OrganisationsAddress1: TStringField;
OrganisationsAddress2: TStringField;
procedure CitiesAfterOpen(DataSet: TDataSet);
procedure CitiesBeforePost(DataSet: TDataSet);
procedure OrganisationsCalcFields(DataSet: TDataSet);
procedure PositionsCode1SetText(Sender: TField; const Text: string);
procedure PositionsCode2SetText(Sender: TField; const Text: string);
procedure PositionsAfterOpen(DataSet: TDataSet);
procedure CitiesCloneFilterRecord(DataSet: TDataSet; var Accept: Boolean);
procedure DataModuleCreate(Sender: TObject);
procedure CitiesOblastSetText(Sender: TField; const Text: string);
procedure CitiesObstinaSetText(Sender: TField; const Text: string);
procedure CitiesOblastGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
procedure CitiesObstinaGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
procedure OrganisationsOblast1GetText(Sender: TField; var Text: string;
DisplayText: Boolean);
procedure OrganisationsObstina1GetText(Sender: TField; var Text: string;
DisplayText: Boolean);
procedure OrganisationsObstina2GetText(Sender: TField; var Text: string;
DisplayText: Boolean);
procedure OrganisationsOblast2GetText(Sender: TField; var Text: string;
DisplayText: Boolean);
procedure OrganisationsCity1Change(Sender: TField);
procedure OrganisationsCity2Change(Sender: TField);
procedure RaionAfterOpen(DataSet: TDataSet);
procedure RaionCloneBeforePost(DataSet: TDataSet);
procedure OrganisationsPositionChange(Sender: TField);
private
CitiesCloneKmetstvo:TField;
procedure OpenData(C:TClientDataSet);
function CityName(ID:Double):String;
function CityID(EKATTE:String):Double;
function Hex(S: String): String;
public
{ Public declarations }
end;
var
dmOrganisation: TdmOrganisation;
function StrToID(S:String):String;
implementation
uses StrUtils, Variants, Windows;
{$R *.dfm}
function StrToID(S:String):String;
var I:Integer;
begin
Result:='';
S:=UpperCase(S);
for I := 1 to Length(S) do
if (Ord(S[I])<99) and (Ord(S[I])>0) then
Result:=Result+Format('%2.2d',[Ord(S[I])])
else
Result:=Result+'32';
end;
procedure TdmOrganisation.CitiesAfterOpen(DataSet: TDataSet);
begin
CitiesClone.Filtered:=False;
CitiesClone.CloneCursor(Cities,False,True);
CitiesClone.FieldByName('Name').DisplayWidth:=20;
CitiesClone.FieldByName('EKATTE').DisplayWidth:=6;
CitiesClone.FieldByName('Kmetstvo').DisplayWidth:=6;
CitiesCloneKmetstvo:=CitiesClone.FieldByName('Kmetstvo');
CitiesClone.IndexFieldNames:='NameHex';
CitiesClone.First;
CitiesClone.Filtered:=True;
end;
function TdmOrganisation.Hex(S:String):String;
begin
if S<>'' then
begin
SetLength(Result,Length(S)*2);
BinToHex(@S[1],@Result[1],Length(S));
end
else Result:='';
end;
procedure TdmOrganisation.CitiesBeforePost(DataSet: TDataSet);
var S:String;
begin
S:=StrToID(Copy(CitiesKmetstvo.AsString,1,3));
if Length(CitiesKmetstvo.AsString)>3 then S:=S+Copy(CitiesKmetstvo.AsString,4,2);
if Length(CitiesKmetstvo.AsString)>6 then S:=S+Copy(CitiesKmetstvo.AsString,7,2)+CitiesEKATTE.AsString;
CitiesID.AsString:=S;
CitiesNameHex.AsString:=Hex(CitiesName.AsString);
end;
procedure TdmOrganisation.CitiesCloneFilterRecord(DataSet: TDataSet;
var Accept: Boolean);
begin
Accept:=Length(CitiesCloneKmetstvo.AsString)>5;
end;
procedure TdmOrganisation.CitiesOblastGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
begin
Text:=Copy(CitiesKmetstvo.AsString,1,3);
Text:=CityName(StrToFloatDef(StrToID(Text),0));
end;
procedure TdmOrganisation.CitiesOblastSetText(Sender: TField;
const Text: string);
begin
if Length(CitiesKmetstvo.AsString)<Length(Text) then CitiesKmetstvo.AsString:=Text;
end;
procedure TdmOrganisation.CitiesObstinaGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
begin
Text:=Copy(CitiesKmetstvo.AsString,1,3);
Text:=CityName(StrToFloatDef(StrToID(Text)+Copy(CitiesKmetstvo.AsString,4,2),0));
end;
procedure TdmOrganisation.CitiesObstinaSetText(Sender: TField;
const Text: string);
begin
if Length(CitiesKmetstvo.AsString)<Length(Text) then CitiesKmetstvo.AsString:=Text;
end;
function TdmOrganisation.CityID(EKATTE: String): Double;
var V:Variant;
begin
if Trim(EKATTE)='' then Result:=0 else
begin
V:=CitiesClone.Lookup('EKATTE',EKATTE,'ID');
if not VarIsNull(V) then
Result:=V
else
Result:=0;
end;
end;
function TdmOrganisation.CityName(ID: Double): String;
begin
if ID<=0 then
Result:=''
else
Result:=VarToStr(Cities.Lookup('ID',ID,'Name'));
end;
procedure TdmOrganisation.DataModuleCreate(Sender: TObject);
begin
OpenData(Altitude);
OpenData(Kind);
OpenData(Region);
OpenData(TSB);
OpenData(Cities);
OpenData(Positions);
OpenData(Raion);
OpenData(Organisations);
end;
procedure TdmOrganisation.OpenData(C: TClientDataSet);
begin
if not FileExists(C.FileName) then
C.CreateDataSet
else
C.Open;
C.LogChanges:=False;
C.MergeChangeLog;
end;
procedure TdmOrganisation.OrganisationsCalcFields(DataSet: TDataSet);
var I:Int64;
begin
I:=Trunc(OrganisationsCode.AsFloat/100);
while (I>0) and ((I mod 100)=0) do I:=I div 100;
OrganisationsParent.AsFloat:=I;
end;
procedure TdmOrganisation.OrganisationsCity1Change(Sender: TField);
begin
OrganisationsOblast1.AsString:=OrganisationsOblast1.Text;
OrganisationsObstina1.AsString:=OrganisationsObstina1.Text;
end;
procedure TdmOrganisation.OrganisationsCity2Change(Sender: TField);
begin
OrganisationsOblast2.AsString:=OrganisationsOblast2.Text;
OrganisationsObstina2.AsString:=OrganisationsObstina2.Text;
end;
procedure TdmOrganisation.OrganisationsOblast1GetText(Sender: TField;
var Text: string; DisplayText: Boolean);
begin
Text:=CityName(Trunc(CityID(OrganisationsCity1.AsString)) div 1000000000);
end;
procedure TdmOrganisation.OrganisationsOblast2GetText(Sender: TField;
var Text: string; DisplayText: Boolean);
begin
Text:=CityName(Trunc(CityID(OrganisationsCity2.AsString)) div 1000000000);
end;
procedure TdmOrganisation.OrganisationsObstina1GetText(Sender: TField;
var Text: string; DisplayText: Boolean);
begin
Text:=CityName(Trunc(CityID(OrganisationsCity1.AsString)) div 10000000);
end;
procedure TdmOrganisation.OrganisationsObstina2GetText(Sender: TField;
var Text: string; DisplayText: Boolean);
begin
Text:=CityName(Trunc(CityID(OrganisationsCity2.AsString)) div 10000000);
end;
procedure TdmOrganisation.OrganisationsPositionChange(Sender: TField);
begin
if (OrganisationsName.AsString='')
or (AnsiCompareText(OrganisationsName.AsString,'нова длъжност')=0)
or (AnsiCompareText(VarToStr(OrganisationsName.OldValue),'нова длъжност')=0) then
OrganisationsName.AsString:=VarToStr(PositionsClone.Lookup('Code',OrganisationsPosition.Value,'PositionName'));
end;
procedure TdmOrganisation.PositionsAfterOpen(DataSet: TDataSet);
begin
PositionsClone.CloneCursor(Positions,False,True);
PositionsClone.FieldByName('PositionName').DisplayWidth:=50;
PositionsClone.FieldByName('Code').DisplayWidth:=6;
PositionsClone.IndexFieldNames:='Code';
PositionsClone.First;
end;
procedure TdmOrganisation.PositionsCode1SetText(Sender: TField;
const Text: string);
begin
PositionsCode.AsString:=LeftStr(Text,4)+RightStr('0000'+PositionsCode.AsString,4);
end;
procedure TdmOrganisation.PositionsCode2SetText(Sender: TField;
const Text: string);
begin
PositionsCode.AsString:=LeftStr(PositionsCode.AsString+'0000',4)+LeftStr(Text,4);
end;
procedure TdmOrganisation.RaionAfterOpen(DataSet: TDataSet);
begin
RaionClone.Filtered:=False;
RaionClone.CloneCursor(Raion,False,True);
RaionClone.IndexFieldNames:='NameHex';
RaionClone.FieldByName('namehex').Visible:=False;
RaionClone.FieldByName('name').DisplayWidth:=20;
end;
procedure TdmOrganisation.RaionCloneBeforePost(DataSet: TDataSet);
begin
DataSet.FieldByName('namehex').AsString:=Hex(DataSet.FieldByName('name').AsString);
end;
end.
|
(*============================================================================
COSNaming Client Demo for VisiBroker 4 for Delphi
The naming service changed significantly from VisiBroker 3.3 to VisiBroker 4.
Now it is a java application that must be started with a command line that
tells the Name Service which port to use for communications. In addition,
all clients and servers must use the same command line parameter as well. The
command line is used to "bootstrap" the Orb so that it knows which port to
use for the Name Service.
The naming service must be started before either the client or server. Once
the Name Service is up and running in a command window, its IOR will be
displayed in the window. Then the server and the client can be started (in
that order). Sample batch files have been provided with this example to
show how to start each application.
In a DOS window, run StartNS.bat first. This brings up the Naming Service.
Then run StartServer.bat. After the server is up and running, run
StartClient.bat
The client demo shows two different ways to bind to an object. The first is
the more "traditional" way, using the OSAgent (or SmartAgent). The other
way is to use the Name Service. In order to do that, the application must
first resolve the reference to the Naming Service. This gets a reference
to the RootContext. Create a Name Component to tell the Naming Service
which object to retrieve. Then narrow that object to the Account type.
===========================================================================*)
unit ClientMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Corba, COSNaming, Account_c, Account_i, StdCtrls;
type
TForm1 = class(TForm)
GroupBox1: TGroupBox;
btnOSAgentBalance: TButton;
Label1: TLabel;
GroupBox2: TGroupBox;
btnBindNS: TButton;
Label2: TLabel;
btnNSBalance: TButton;
Label3: TLabel;
procedure FormCreate(Sender: TObject);
procedure btnOSAgentBalanceClick(Sender: TObject);
procedure btnBindNSClick(Sender: TObject);
procedure btnNSBalanceClick(Sender: TObject);
private
{ private declarations }
protected
Acct : Account; // Object that will use OSAgent for Binding
AcctNS : Account; // Object that will use Naming Service for Binding
RootContext : NamingContext;
nameComp : NameComponent;
nameArray : COSNaming.Name;
procedure InitCorba;
{ protected declarations }
public
{ public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.InitCorba;
begin
CorbaInitialize;
Acct := TAccountHelper.bind;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
InitCorba;
end;
procedure TForm1.btnOSAgentBalanceClick(Sender: TObject);
begin
Label1.Caption := FormatFloat('Balance = $##,##0.00', Acct.balance);
end;
procedure TForm1.btnBindNSClick(Sender: TObject);
begin
//bind to the Root Context of the NS via the orb
RootContext := TNamingContextHelper.Narrow(Orb.ResolveInitialReferences('NameService'), True);
//create the naming component -- match server id and kind values
nameComp := TNameComponent.Create('Account', 'Jack B Quick');
//set up the Name sequence
SetLength(NameArray, 1);
NameArray[0] := nameComp;
//Resolve the account object
AcctNS := TAccountHelper.narrow(RootContext.resolve(NameArray), True);
//handle changing the GUI controls
btnBindNS.Enabled := False;
if AcctNS <> nil then
begin
Label2.Caption := 'Successfully resolved Account object';
btnNSBalance.Enabled := True;
end
else
Label2.Caption := 'Error -- could not resolve Account object';
Label2.Visible := True;
end;
procedure TForm1.btnNSBalanceClick(Sender: TObject);
begin
if AcctNS <> nil then
Label3.Caption := FormatFloat('Balance = $##,##0.00', AcctNS.balance)
else Label3.Caption := 'Account object not bound';
Label3.Visible := True;
end;
end. |
{ $Log: C:\PROGRAM FILES\GP-VERSION LITE\Archives\Reve64\Source\Search.paV
{
{ Rev 1.1 28/09/03 20:32:05 Dgrava
}
{
Rev 1.5 16-6-2003 21:13:14 DGrava
NegaScout refinement applied
}
{
Rev 1.4 15-6-2003 20:38:29 DGrava
Disabled forward pruning. Added Quiescens check.
}
{
Rev 1.3 10-3-2003 21:46:25 DGrava
Little enhancements.
}
{
Rev 1.2 20-2-2003 16:38:48 DGrava
Forward pruning implemented. Extending capture sequences
with conditional defines
}
{
Rev 1.1 6-2-2003 11:48:03 DGrava
Introduction of QuickEval component.
}
{
Rev 1.0 24-1-2003 21:12:24 DGrava
Eerste Check in.
Versie 0.27
}
{}
unit Search;
interface
uses
ReveTypes, SearchTypes, MoveGenerator, HashTable;
var
GLOBAL_NumAlphaBetas : Integer;
const
UNKNOWN = -1;
function AlphaBetaSearch(
var aBoard : TBoardStruct;
aMaxTime : cardinal;
aOutput : PChar;
var aPlayNow : boolean;
var aHashTable: THashTable;
aDepth : Integer
): Integer;
implementation
uses
Windows{for GetTickCount :(}, SysUtils, Evaluation
{$IFDEF DEBUG_REVE}
, DebugUtils
{$ENDIF}
;
const
ALPHABETA_FRAME = KING_VALUE - MAN_VALUE;
function AlphaBeta(
var aBoard : TBoardStruct;
var aMoveList : TMoveList;
aDepth : Integer;
aAlpha : Integer;
aBeta : Integer;
aDepthFromRoot : Integer;
var aBestLine : TMoveLine;
var aHashTable : THashTable
): Integer; forward;
function AlphaBetaSearch(
var aBoard : TBoardStruct;
aMaxTime : Cardinal;
aOutput : PChar;
var aPlayNow : Boolean;
var aHashTable: THashTable;
aDepth : Integer
): Integer;
{NOTE aMaxTime is specified in ms.}
var
moveList : TMoveList;
startTime : cardinal;
depth : Integer;
numMoves : Integer;
temp : string;
alfa, beta : Integer;
searchResults : TSearchResults;
maxTime : Cardinal;
maxDepth : Integer;
begin
result := UNKNOWN;
GLOBAL_NumAlphaBetas := 0;
GLOBAL_NumEvaluations := 0;
moveList.AtMove := Low(moveList.Moves);
moveList.AtJump := Low(moveList.KilledPieces);
InitSearchResults(searchResults);
startTime := GetTickCount;
GenerateMoves(moveList, aBoard.Board, aBoard.ColorToMove);
{ NOTE Check number of moves.
If no moves then break and return loss;
if only one move then execute move without further searching;
if more than one move then perform alpha beta search.
}
numMoves := moveList.AtMove - Low(moveList.Moves);
if numMoves = 0 then begin
result := LOSS;
Exit;
end
else if numMoves = 1 then begin
ExecuteMove(moveList, aBoard, 1);
StrCopy(aOutput, #0);
Exit;
end;
// Main flow
alfa := LOSS - 1;
beta := WIN + 1;
if aDepth > 0 then begin
maxDepth := aDepth;
maxTime := 1000 * 60 * 30; // = 30 minutes
end
else begin
maxDepth := MAX_DEPTH;
maxTime := aMaxTime;
end;
hashTable_Initialize(aHashTable);
depth := 2;
while depth <= maxDepth do begin
moveList.AtMove := Low(moveList.Moves);
moveList.AtJump := Low(moveList.KilledPieces);
result := AlphaBeta(
aBoard,
moveList,
depth,
alfa,
beta,
0,
searchResults.bestLine,
aHashTable
);
if (result <= alfa) or (result >= beta) then begin
{Fail high or fail low situation,
research with full alfa beta window.}
alfa := LOSS - 1;
beta := WIN + 1;
result := AlphaBeta(
aBoard,
moveList,
depth,
alfa,
beta,
0,
searchResults.bestLine,
aHashTable
);
end;
FillSearchResults (
searchResults, depth, GLOBAL_NumAlphaBetas, GLOBAL_NumEvaluations, result div 10, GetTickCount - startTime + 1
);
SearchResultsToString(searchResults, temp);
StrCopy(aOutput, @temp[1]);
if (
((GetTickCount - StartTime) > maxTime) or
aPlayNow or
(Abs(result) = WIN)
) then begin
Break;
end;
{Set alfa beta window}
alfa := result - ALPHABETA_FRAME;
beta := result + ALPHABETA_FRAME;
Inc(depth);
end; // for
ExecuteMove(
moveList,
aBoard,
FindMove(
moveList,
Low(moveList.Moves),
High(moveList.Moves),
searchResults.bestLine.Moves[searchResults.bestLine.AtMove - 1].FromSquare,
searchResults.bestLine.Moves[searchResults.bestLine.AtMove - 1].ToSquare
)
);
end; // AlphaBetaSearch
function AlphaBeta(
var aBoard : TBoardStruct;
var aMoveList : TMoveList;
aDepth : Integer;
aAlpha : Integer;
aBeta : Integer;
aDepthFromRoot : Integer;
var aBestLine : TMoveLine;
var aHashTable : THashTable
): Integer;
const
NO_SQUARE = 0;
var
firstMove : Integer;
firstJump : Integer;
i, j : Integer;
value : Integer;
newLine : TMoveLine;
pHEntry : PHashEntry;
resultType : TValueType;
bestFrom : Integer;
bestTo : Integer;
{$IFDEF DEBUG_REVE}
tmpBoard : TBoardStruct;
{$ENDIF}
begin
Inc(GLOBAL_NumAlphaBetas);
{ NOTE
If the other color threatens to take at the next move then we add a penalty
to the score, so that it might not give a good score to a variant that is
a dead loss.
This appeared to introduce a lot of instability (search results changing with
great amounts on consecutive search depths) in the search.
Instead of giving a penalty we might also extend the search depth. This may
seem to lead to better evaluations of the position, but instead it might end
up in an infinite loop in case of kings.
For example the following position:
Black: 3, K10
White: K2
White to move.
It will loop inifinitely with the following variant:
2-7 (10-6) white king threatened 7-2 black king threatened (6-10) 7-2 etc.
As the engine does not recognize move repititions at this moment it will
keep on repeating this variant and extending the search depth.
So what we might need to do is to just search 1 extra level to check if
the piece is not immediately taken.
We will abuse the search depth param by assigning it a special value.
}
{$IFDEF QUIESCENSE_SEARCH}
if (aDepth = 0) and IsThreatPresent(aBoard.Board, aBoard.ColorToMove xor RP_CHANGECOLOR) then begin
aDepth := -1;
end;
if aDepth = -2 then begin
{ search depth is -2 then we come from a non stable terminal node. Evaluate it.}
aDepth := 0;
end;
{$ENDIF}
if (aDepth = 0) then begin
result := Evaluate(aBoard);
Exit;
end;
bestFrom := NO_SQUARE;
bestTo := NO_SQUARE;
{Lookup position in hashtable before doing anything else.
if found there we can simply return the value and skip the search.}
pHEntry := hashTable_GetEntry(aHashTable, aBoard.HashKey);
if (pHEntry <> nil) and (pHEntry^.ColorToMove = aBoard.ColorToMove) then begin
if pHEntry^.Depth >= aDepth then begin
case pHEntry^.ValueType of
vtExact : begin
result := pHEntry^.Value;
Exit;
end;
vtLowerBound : begin
if pHEntry^.Value >= aBeta then begin
result := pHEntry^.Value;
Exit;
end
else begin
{ Smart trick from PubliCake:
You can narrow the alpha beta frame with the upper and lower bound
values from the hash table.
In some positions it results in significant improvements of
the search results, but in most positions it costs a little
performance.
}
if pHEntry^.Value > aAlpha then begin
aAlpha := pHEntry^.Value;
end;
bestFrom := pHEntry^.FromSquare;
bestTo := pHEntry^.ToSquare;
end;
end;
vtUpperBound : begin
if pHEntry^.Value <= aAlpha then begin
result := pHEntry^.Value;
Exit;
end
else begin
if pHEntry^.Value < aBeta then begin
aBeta := pHEntry^.Value;
end;
end;
end;
end; // case
end
else begin
bestFrom := pHEntry^.FromSquare;
bestTo := pHEntry^.ToSquare;
end;
end;
firstMove := aMoveList.AtMove;
firstJump := aMoveList.AtJump;
GenerateMoves(aMoveList, aBoard.Board, aBoard.ColorToMove);
{Check if there are any moves!!!}
if aMoveList.AtMove = firstMove then begin
result := LOSS;
resultType := vtExact;
hashTable_AddEntry(
aHashTable,
aBoard.HashKey,
aDepth,
aBoard.ColorToMove,
resultType,
result,
NO_SQUARE,
NO_SQUARE
);
Exit;
end;
// Main Flow
{Put move from main line in front.}
// if aMainLine.AtMove >= Low(aMainLine.Moves) then begin
if bestFrom <> NO_SQUARE then begin
SwapMoves(
aMoveList,
firstMove,
FindMove(
aMoveList,
firstMove,
aMoveList.AtMove -1,
bestFrom,
bestTo
)
);
//Dec(aMainLine.AtMove);
end;
result := aAlpha;
resultType := vtUpperBound;
i := firstMove;
while i < (aMoveList.AtMove) do begin
{$IFDEF DEBUG_REVE}
CopyBoard(aBoard, tmpBoard);
{$ENDIF}
ExecuteMove(aMoveList, aBoard, i);
// Test code
if aMoveList.AtMove - 1 = firstMove then begin
// There is just one move extend depth
Inc (aDepth);
end;
if i = firstMove then begin
newLine.AtMove := 1;
value := - AlphaBeta(
aBoard,
aMoveList,
aDepth - 1,
- aBeta,
- result,
aDepthFromRoot + 1,
newLine,
aHashTable
);
end
else begin
// Negascout refinement
{ NOTE
Tests revealed that the window should realy be minimal (=1). Otherwise
performance drops rapidly.
}
newLine.AtMove := 1;
value := - AlphaBeta(
aBoard,
aMoveList,
aDepth - 1,
- result - 1,
- result,
aDepthFromRoot + 1,
newLine,
aHashTable
);
if (value > result) and (value < aBeta) then begin
newLine.AtMove := 1;
value := - AlphaBeta(
aBoard,
aMoveList,
aDepth - 1,
- aBeta,
- result,
aDepthFromRoot + 1,
newLine,
aHashTable
);
end;
end;
UndoMove(aMoveList, aBoard, i);
{$IFDEF DEBUG_REVE}
CompareBoard(aBoard, tmpBoard);
{$ENDIF}
// Check alpha beta prune
if value >= aBeta then begin
result := value;
resultType := vtLowerBound;
bestFrom := aMoveList.Moves[i].FromSquare;
bestTo := aMoveList.Moves[i].ToSquare;
Break;
end;
// Check if it is the best move so far
if value > result then begin
resultType := vtExact;
result := value;
// copy new line to best line
for j := 1 to newLine.AtMove - 1 do begin
aBestLine.Moves[j].FromSquare := newLine.Moves[j].FromSquare;
aBestLine.Moves[j].ToSquare := newLine.Moves[j].ToSquare;
end;
aBestLine.AtMove := newLine.AtMove;
// Add the new move
aBestLine.Moves[aBestLine.AtMove].FromSquare := aMoveList.Moves[i].FromSquare;
bestFrom := aMoveList.Moves[i].FromSquare;
aBestLine.Moves[aBestLine.AtMove].ToSquare := aMoveList.Moves[i].ToSquare;
bestTo := aMoveList.Moves[i].ToSquare;
Inc(aBestLine.AtMove);
{NOTE
copying the new moveline to best moveline.
Costs some performance (not a lot: between 0.5-2.0%).
You can restrict this performence penalty by having an array of movelines;
for every ply one + a best line. In case of a better line you simply
swap the pointers of the best line and the current line of that ply level.
}
end;
Inc(i);
end; // while
// Reset list pointer
aMoveList.AtJump := firstJump;
aMoveList.AtMove := firstMove;
hashTable_AddEntry(
aHashTable,
aBoard.HashKey,
aDepth,
aBoard.ColorToMove,
resultType,
result,
bestFrom,
bestTo
);
{$IFDEF DEBUG_REVE}
CheckCertainPositions(aBoard, aBestLine, aDepth, result, aAlpha, aBeta, resultType);
{$ENDIF}
end; // AlphaBeta
{
$Log
06-12-2002, DG : Created.
09-12-2002, DG : First working version.
10-12-2002, DG : Fixed several bugs.
11-12-2002, DG : AlphaBeta did not return best value.
18-12-2002, DG : Adjusted for new MoveList implementation.
04-01-2002, DG : Saving principle variation for display.
12-01-2003, DG : Added ab windowing.
}
end.
|
unit ncIPAddr;
{Object to retrieve local IP addresses}
{Note:
- Each thread is permited to have a single HostEnt structure. Therefore
we need to copy the info we need.
}
interface
uses
WinSock,
Classes, SysUtils;
type
pPInAddr = ^PInAddr;
TIPAddress = String[35];
pTIPAddress = ^TIPAddress;
TLocalIPObj = class(TObject)
private
IPList : TList;
{property vars}
fHostName : String;
fIsIpAddresses : Boolean;
function GetIPCount : Integer;
public
constructor Create;
destructor Destroy; override;
function GetLocalIPAddress : String;
function GetIPFromList(ThisIPIndex:Integer) : String;
property IPCount : Integer read GetIpCount;
property HostName : String read fHostName;
property HaveIP : Boolean read fIsIPAddresses;
end;
implementation
constructor TLocalIPObj.Create;
var
pIPAddress : pTIPAddress;
aHostName : TIPAddress;
apHostENT : PHostEnt;
Ptr : pPInAddr;
{ struct hostent {
char FAR * h_name;
char FAR * FAR * h_aliases;
short h_addrtype;
short h_length;
char FAR * FAR * h_addr_list;
}
begin
inherited;
IPList:= TList.Create;
fHostName:= '';
fIsIPAddresses:= false;
{Retrieve the local IP addresses for this machine}
aHostName:= ' ' +#0; {20 blanks and one #0}
if (GetHostName(@aHostName[1], 20) = 0) then
begin
fHostName:= StrPas(@aHostName[1]);
apHostEnt:= GetHostByName(@aHostName[1]);
if (apHostEnt <> nil) then
begin
Ptr:= Pointer(apHostEnt^.h_addr_list);
while (Ptr <> nil) and (Ptr^ <> nil) do
begin
{}
new(pIPAddress);
pIPAddress^:= StrPas(inet_ntoa(Ptr^^));
IPList.Add(pIPAddress);
inc(Ptr);
end; {while}
fIsIPAddresses:= true;
end
else
fIsIPAddresses:= false;
end;
// Pchar(inet_ntoa(pinaddr(apHostEnt^.h_addr_list^)^));
// IntToStr(ORd(Pchar(apHostEnt^.h_addr^)[0]))+'.'+
// IntToStr(ORd(Pchar(apHostEnt^.h_addr^)[1]))+'.'+
// IntToStr(ORd(Pchar(apHostEnt^.h_addr^)[2]))+'.'+
// IntToStr(ORd(Pchar(apHostEnt^.h_addr^)[3]));
end; {Create}
destructor TLocalIPObj.Destroy;
begin
while (IPList.Count > 0) do
begin
Dispose(pTIPAddress(IPList[0]));
IPList.Delete(0);
end; {while}
IPList.Free;
inherited;
end; {Destroy}
{ ***** Property rtns ***** }
function TLocalIPObj.GetIPCount : Integer;
begin
result:= IPList.Count;
end; {Get IP Count}
{ ***** Other Rtns ***** }
function TLocalIPObj.GetLocalIPAddress : String;
{Get the first IP address from the list}
begin
result:= GetIPFromList(0);
end; {Get Local IP Address}
function TLocalIPObj.GetIPFromList(ThisIPIndex:Integer) : String;
{Get the IP address from the list at index ThisIPIndex}
begin
if (ThisIPIndex < IPList.Count) then
result:= pTIPAddress(IPList[ThisIPIndex])^
else
result:= '000.000.000.000';
end; {Get IP From List}
end.unit Unit1;
interface
implementation
end.
|
unit MailCrypt;
{$mode objfpc}{$H+}
interface
uses
Classes, MainCrypt,{ mimeinln,} mimemess, mimepart, pop3send, smtpsend, Dialogs,
SysUtils, ExtCtrls, Forms, Controls, synacode;
const
RET_ERROR_STR = 'Error';
ATTACHMENT_STR = 'attachment';
type
{ TMailCrypt }
TMailCrypt = class(TMainCrypt)
private
fMailHead: boolean;
fMailAuth: boolean;
fMailText: TStringList;
fMailIndex: integer;
fHost: string;
Pop3: TPOP3Send;
MailMessage: TMimeMess;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
//* ======================================================================== *//
function ConnectMail: boolean;
function SendMail(pHost, pSubject, pTo, pFrom, pTextBody, pHTMLBody: string;
files: TStrings): boolean;
function GetMailCount: integer;
function GetMail(AIndex: integer): string;
function GetMailHead(AIndex: integer): string;
procedure LoadMailFromText(AIndex: integer; AText: string);
//* ======================================================================== *//
// Кем отправлено
function GetMailFrom(AIndex: integer): string;
// Кому отпралено
function GetMailTo(AIndex: integer): string;
// Тема письма
function GetMailSubject(AIndex: integer): string;
// Время отправки
function GetMailDate(AIndex: integer): TDateTime;
//* ======================================================================== *//
function GetAttachCount(AIndex: integer): integer;
function GetAttachName(AMailIndex, AIndex: integer): string;
function SaveAttachToFile(AMailIndex, AIndex: integer; AFileName: string): boolean;
//* ======================================================================== *//
function FindMail(AFriendMail: string; AStartIndex: integer): integer;
function ExtractEmail(AText: string): string;
public
function AddFriend(AFriend: TFriendEntry): boolean; override;
function GetMailCommand(Index: integer): string;
published
property Host: string Read fHost Write fHost;
end;
implementation
{ TMailCrypt }
constructor TMailCrypt.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Pop3 := TPOP3Send.Create;
MailMessage := TMimeMess.Create;
fMailAuth := False;
fMailText := TStringList.Create;
fMailIndex := -1;
fMailHead := False;
end;
destructor TMailCrypt.Destroy;
begin
MailMessage.Free;
fMailText.Free;
Pop3.Free;
inherited Destroy;
end;
function TMailCrypt.ConnectMail: boolean;
var
UsrInf: TUserEntry;
begin
Result := False;
UsrInf := GetUserInfo;
Pop3.TargetHost := fHost;
Pop3.UserName := UsrInf.Email;
Pop3.Password := UsrInf.HashPwd;
if Pop3.Login then
Result := True
else
raise Exception.Create('Соединение не удалось. Проверьте логин/пароль/порт.');
fMailAuth := Result;
end;
function TMailCrypt.SendMail(pHost, pSubject, pTo, pFrom, pTextBody, pHTMLBody: string;
files: TStrings): boolean;
var
tmpMsg: TMimeMess;
tmpStringList: TStringList;
tmpMIMEPart: TMimePart;
fItem: string;
UsrInf: TUserEntry;
begin
Result := True;
tmpMsg := TMimeMess.Create;
tmpStringList := TStringList.Create;
try
try
tmpMsg.Header.Subject := pSubject;
tmpMsg.Header.From := pFrom;
tmpMsg.Header.ToList.Add(pTo);
tmpMIMEPart := tmpMsg.AddPartMultipart('alternate', nil);
if length(pTextBody) > 0 then
begin
tmpStringList.Text := pTextBody;
tmpMsg.AddPartText(tmpStringList, tmpMIMEPart);
end
else
begin
tmpStringList.Text := pHTMLBody;
tmpMsg.AddPartHTML(tmpStringList, tmpMIMEPart);
end;
for fItem in files do
tmpMsg.AddPartBinaryFromFile(fItem, tmpMIMEPart);
tmpMsg.EncodeMessage;
UsrInf := GetUserInfo;
smtpsend.SendToRaw(pFrom, pTo, pHost, tmpMsg.Lines, UsrInf.Email, UsrInf.HashPwd);
except
Result := False;
end;
finally
tmpMsg.Free;
tmpStringList.Free;
end;
end;
function TMailCrypt.GetMailCount: integer;
begin
Result := -1;
if fMailAuth then
if Pop3.Stat then
Result := Pop3.StatCount;
end;
function TMailCrypt.GetMail(AIndex: integer): string;
begin
Result := RET_ERROR_STR;
if fMailAuth then
if Pop3.Retr(AIndex) then
begin
Result := Pop3.FullResult.Text;
fMailText.Assign(Pop3.FullResult);
fMailIndex := AIndex;
fMailHead := False;
end;
end;
function TMailCrypt.GetMailHead(AIndex: integer): string;
begin
// Разделить Top и Полное письмо
Result := RET_ERROR_STR;
if not fMailAuth then
Exit;
if AIndex <> fMailIndex then
if fMailAuth then
if Pop3.Top(AIndex, 1) then
begin
Result := Pop3.FullResult.Text;
fMailText.Assign(Pop3.FullResult);
fMailIndex := AIndex;
fMailHead := True;
end
else
exit;
MailMessage.Lines.Assign(fMailText);
MailMessage.DecodeMessage;
Result := MailMessage.Header.CustomHeaders.Text;
end;
procedure TMailCrypt.LoadMailFromText(AIndex: integer; AText: string);
begin
fMailText.Text := AText;
fMailIndex := AIndex;
fMailHead := True;
end;
function TMailCrypt.GetMailFrom(AIndex: integer): string;
begin
Result := RET_ERROR_STR;
if not fMailAuth then
Exit;
if AIndex <> fMailIndex then
if GetMailHead(AIndex) = RET_ERROR_STR then
exit;
MailMessage.Lines.Assign(fMailText);
MailMessage.DecodeMessage;
Result := MailMessage.Header.From;
end;
function TMailCrypt.GetMailTo(AIndex: integer): string;
begin
Result := RET_ERROR_STR;
if not fMailAuth then
Exit;
if AIndex <> fMailIndex then
if GetMailHead(AIndex) = RET_ERROR_STR then
exit;
MailMessage.Lines.Assign(fMailText);
MailMessage.DecodeMessage;
Result := MailMessage.Header.ToList[0];
end;
function TMailCrypt.GetMailSubject(AIndex: integer): string;
begin
Result := RET_ERROR_STR;
if not fMailAuth then
Exit;
if AIndex <> fMailIndex then
if GetMailHead(AIndex) = RET_ERROR_STR then
exit;
fMailHead:= true;
MailMessage.Lines.Assign(fMailText);
MailMessage.DecodeMessage;
Result := MailMessage.Header.Subject;
end;
function TMailCrypt.GetMailDate(AIndex: integer): TDateTime;
begin
Result := TDateTime(0);
if not fMailAuth then
Exit;
if AIndex <> fMailIndex then
if GetMailHead(AIndex) = RET_ERROR_STR then
exit;
MailMessage.Lines.Assign(fMailText);
MailMessage.DecodeMessage;
Result := MailMessage.Header.Date;
end;
function TMailCrypt.GetAttachCount(AIndex: integer): integer;
var
MimePart: TMimePart;
i: integer;
begin
Result := -1;
if not fMailAuth then
Exit;
if (AIndex <> fMailIndex) and not fMailHead then
if GetMail(AIndex) = RET_ERROR_STR then
exit;
MailMessage.Lines.Assign(fMailText);
MailMessage.DecodeMessage;
for i := 0 to MailMessage.MessagePart.GetSubPartCount - 1 do
begin
MimePart := MailMessage.MessagePart.GetSubPart(i);
if SameText(MimePart.Disposition, ATTACHMENT_STR) then
Inc(Result, 1);
// ShowMessage(MimePart.Disposition);
end;
end;
function TMailCrypt.GetAttachName(AMailIndex, AIndex: integer): string;
var
MimePart: TMimePart;
i, CountAttach: integer;
begin
Result := RET_ERROR_STR;
CountAttach := -1;
if not fMailAuth then
Exit;
if (AMailIndex <> fMailIndex) and not fMailHead then
if GetMail(AMailIndex) = RET_ERROR_STR then
exit;
MailMessage.Lines.Assign(fMailText);
MailMessage.DecodeMessage;
for i := 0 to MailMessage.MessagePart.GetSubPartCount - 1 do
begin
MimePart := MailMessage.MessagePart.GetSubPart(i);
if SameText(MimePart.Disposition, ATTACHMENT_STR) then
begin
Inc(CountAttach, 1);
if CountAttach = AIndex then
Result := MimePart.FileName;
end;
end;
end;
function TMailCrypt.SaveAttachToFile(AMailIndex, AIndex: integer;
AFileName: string): boolean;
procedure SaveToFile(szData, szPath: string);
var
hFile: TextFile;
begin
AssignFile(hFile, szPath);
Rewrite(hFile);
Write(hFile, szData);
CloseFile(hFile);
end;
var
MimePart: TMimePart;
i, CountAttach: integer;
Stream: TStringStream;
begin
Result := False;
CountAttach := -1;
if not fMailAuth then
Exit;
if (AMailIndex <> fMailIndex) and not fMailHead then
if GetMail(AIndex) = RET_ERROR_STR then
exit;
MailMessage.Lines.Assign(fMailText);
MailMessage.DecodeMessage;
for i := 0 to MailMessage.MessagePart.GetSubPartCount - 1 do
begin
MimePart := MailMessage.MessagePart.GetSubPart(i);
if SameText(MimePart.Disposition, ATTACHMENT_STR) then
begin
Inc(CountAttach, 1);
if CountAttach = AIndex then
begin
Stream := TStringStream.Create('');
try
Stream.WriteString(DecodeBase64(MimePart.PartBody.Text));
SaveToFile(Stream.DataString, AFileName);
// Stream.SaveToFile(ExtractFilePath(Application.ExeName) + '/Mail/'+ Sender.FileName);
finally
Stream.Free;
Result:= True;
end;
end;
end;
end;
end;
function TMailCrypt.FindMail(AFriendMail: string; AStartIndex: integer): integer;
var
i, unCount: integer; // UnUsed mails
begin
Result := -1;
unCount := 0;
for i := AStartIndex to GetMailCount do
if (pos(AFriendMail, GetMailFrom(i)) <> 0) or
(pos(AFriendMail, GetMailTo(i)) <> 0) then
begin
Result := i;
unCount := -1;
break;
end
else if unCount > 20 then
break
else
Inc(unCount, 1);
end;
function TMailCrypt.ExtractEmail(AText: string): string;
var
ch: char;
flag: boolean;
begin
Result := '';
flag := False;
for ch in AText do
begin
if ch = '>' then
flag := False;
if Flag then
Result += ch;
if ch = '<' then
flag := True;
end;
if Result = '' then
Result := AText;
end;
//*****************************************************************************//
// Задачи ниже лежащго кода сводятся к обмену по сети информацией
//*****************************************************************************//
function TMailCrypt.AddFriend(AFriend: TFriendEntry): boolean;
const
// Сообщения всегда имеют эту тему
CHAT_MAIN_SUBJECT = '{6D78D26F-347E-4D57-9E9C-03C82139CD38}';
// Имя открытого ключа
CHAT_NAME_OPEN_KEY = '{5898E436-3B1D-47D1-86CC-2FFF6C27FF77}';
// Запрос на добавления в друзья
CHAT_REQUEST_ADD_FRIEND = '{138C7A7C-8F74-4DAF-838B-21E6842A031D}';
var
files: TStringList;
PathSec, PathOpn: string;
Amsg: TMessageEntry;
begin
{ TODO : Задачи для TMailCrypt.AddFriend:
1. Создать паруключей
2. Отправить пиьмо, содержащее:
2.1. Открытый ключ
2.2. Юид отвечающий на запрос о авторизации
3. Ответ должен содержать:
3.1. Юид подтверждающий аутентификацию
3.2. Открытый ключ
3.3. Первое сообщение (опционально) }
Files := TStringList.Create;
// Генерируем ключи
PathSec := '/tmp/private.key';
PathOpn := '/tmp/' + CHAT_NAME_OPEN_KEY;
GenRsaKeys(PathSec, PathOpn, 2048);
files.Add('/tmp/' + CHAT_NAME_OPEN_KEY);
// Стучимся на почтовый сервер
Host := 'pop.yandex.ru';
// Отправляем письмо
if ConnectMail then
begin
if not SendMail('smtp.yandex.ru', CHAT_MAIN_SUBJECT, AFriend.Email,
GetUserInfo.Email, CHAT_REQUEST_ADD_FRIEND, '', files) then
begin
raise Exception.Create('Не могу отправить приглашение на аутентификацию');
abort;
end;
end
else
begin
raise Exception.Create('Не могу подключиться к почтовому серверу');
abort;
end;
// Добавляем в бд друга
Result := inherited AddFriend(AFriend);
// Добавляем сообщение в бд - нужно будет перенести в MakeFirstMail из MainCrypt
Amsg.ID_FRIEND := GetCountFriend;
Amsg.ID_USER := GetUserInfo.ID_USER;
Amsg.Date := Now;
Amsg.Files := '';
Amsg.Message := '';
Amsg.IsMyMsg := True;
AMsg.OpenKey := TextReadFile('/tmp/' + CHAT_NAME_OPEN_KEY);
AMsg.SecretKey := Base64ReadFile('/tmp/private.key');
AMsg.BFKey := '';
Amsg.XID := 1;
if not AddMessage(Amsg) then
raise Exception.Create('Ошибка добавления сообщения в БД');
// Заметаем за собой
DeleteFile('/tmp/private.key');
DeleteFile('/tmp/open.key');
Files.Free;
end;
function TMailCrypt.GetMailCommand(Index: integer): string;
var
MimePart: TMimePart;
i: integer;
begin
Result:= '';
if not fMailAuth then
Exit;
if (Index <> fMailIndex) and not fMailHead then
if GetMail(Index) = RET_ERROR_STR then
exit;
MailMessage.Lines.Assign(fMailText);
MailMessage.DecodeMessage;
for i := 0 to MailMessage.MessagePart.GetSubPartCount - 1 do
begin
MimePart := MailMessage.MessagePart.GetSubPart(i);
if SameText('inline', MimePart.Disposition) then
begin
Result+= MimePart.PartBody.Text;
end;
end;
end;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls;
type
{ TfrmStudyGroups }
TfrmStudyGroups = class(TForm)
btnNextName: TButton;
gpbGroup: TGroupBox;
lblGroup: TLabel;
procedure btnNextNameClick(Sender: TObject);
procedure gpbGroupClick(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
frmStudyGroups: TfrmStudyGroups;
implementation
{$R *.lfm}
{ TfrmStudyGroups }
procedure TfrmStudyGroups.gpbGroupClick(Sender: TObject);
begin
end;
procedure TfrmStudyGroups.btnNextNameClick(Sender: TObject);
var
FirstLetter, Group: Char;
Surname: String;
begin
Surname:=InputBox('User input', 'Enter a surname', '');
if Surname <> '' then
begin
FirstLetter:=UpCase(Surname[1]);
case FirstLetter of
'A'..'H' : Group:='1';
'I'..'L', 'N'..'P' : Group:='2';
'Q'..'U', 'W'..'Z' : Group:='3';
'M', 'V' : Group:='4';
else
Group:='?';
end;
if Group = '?' then
ShowMessage('Invalid surname entered')
else
begin
lblGroup.Caption:='Group ' + Group;
gpbGroup.Caption:=Surname;
end;
end //if surname
else //user pressed cancel or left input box blank
ShowMessage('No surname provided');
end;
end.
|
unit xVideo;
{
xVideo 1.2 Delphi unit
Copyright (c) 2009-2010 Cristea Aurel Ionut.
Check http://surodev.com for updates
}
interface
uses
Windows;
const
{DLL NAME}
DLLNAME = 'xVideo.dll';
{xVideo Plugin CLSID}
CLSID_DSHOWPLUGIN: TGUID = '{00000000-0000-0000-0000-000000000000}';
{xVideo Version}
xVideo_VERSION = $10200; // API version
xVideo_VERSIONTEXT = '1.2.0'; //TEXT version
type
DWORD = LongWord;
BOOL = LongBool;
FLOAT = Single;
QWORD = Int64;
HWINDOW = DWORD; //multi video handle
HSTREAM = DWORD; // playing sample's channel handle
HRECORD = DWORD; // recording handle
HSYNC = DWORD; // synchronizer handle
HDSP = DWORD; // DSP handle
SYNCPROC = procedure(handle: HSYNC; channel, data: DWORD; user: Pointer); stdcall;
{
Sync callback function. NOTE: a sync callback function should be very
quick as other syncs cannot be processed until it has finished. If the
sync is a "mixtime" sync, then other streams and MOD musics can not be
mixed until it's finished either.
handle : The sync that has occured
channel: Channel that the sync occured in
data : Additional data associated with the sync's occurance
user : The 'user' parameter given when calling xVideo_ChannelSetSync
}
DSPPROC = procedure(handle: HDSP; channel: DWORD; buffer: Pointer; length: DWORD; user: Pointer); stdcall;
{
DSP callback function. NOTE: A DSP function should obviously be as quick
as possible... other DSP functions, streams and MOD musics can not be
processed until it's finished.
handle : The DSP handle
channel: Channel that the DSP is being applied to
buffer : Buffer to apply the DSP to
length : Number of bytes in the buffer
user : The 'user' parameter given when calling xVideo_ChannelSetDSP
}
DRAWPROC = procedure(handle: HDC;channel: HSTREAM; user: Pointer); stdcall;
//for Mix_StreamCreate function
PTMixingFiles = ^TMixingFiles ;
TMixingFiles = array[0..14] of PCHAR;
/////////////CALLBACKS///////////////////
///
TCallBackEnumEncoderFilter = function(Filter : Pointer; FilterName: PChar) : BOOL; stdcall;
{
Filter- the instance of a IBaseFilter;
FilterName - The name of the Filter
}
TCallBackConnectedFilters = function(Filter : Pointer; FilterName: PChar;pp:BOOL;user:pointer) : BOOL; stdcall;
{
Filter- the instance of a IBaseFilter;
FilterName - The name of the Filter
pp - Boolean, Filter supports or not Property Pages
user - The 'user' parameter
}
TCallBackEnumDevices = function(device: PChar;user:Pointer) : BOOL; stdcall; TCallBackChannelDVDChange = function(oldChan:HSTREAM;newChan:HSTREAM;user: Pointer):BOOL;stdcall;
{
device - the device name
user - The 'user' parameter
}
/////////////////////////////////////////
//for xVideo_ChannelGetInfo function
xVideo_ChannelInfo= ^TxVideo_ChannelInfo;
TxVideo_ChannelInfo = record
AvgTimePerFrame : Double; //average Time per frame (i.e 23.97 - it will draw 23.97 frames per seconds);
Height, Width : integer; //video size;
Channels: integer; //number of channels (i.e.1= mono,2= stereo...)
freq: DWORD; //sample rate
wBits: DWORD; // number of bits per sample of mono data */
ftpoint: BOOL;//true if audio is 32 bit floating point, false else
end;
//for xVideo_ChannelSetConfig function
TextOverlayStruct = ^TTextOverlayStruct;
TTextOverlayStruct = record
x: integer; //x position
y: integer; //y position
red: integer; //0 ..255
green: integer; //0 ..255
blue : integer; //0 ..255
txtfont: HFONT; //handle of a Font
end;
VideoColors = ^TVideoColors;
TVideoColors=record
HUE: integer; //-180...180
Contrast: integer; //0...128
Brightness: integer; //-128...128.
Saturation: integer; //0...128
end;
///////xVideo_ChannelSetAttribute/GetAttribute Constants
const
xVideo_ATTRIB_VOL = 1; //used to set Audio Volume
xVideo_ATTRIB_PAN = 2; //used to set Audio Pan
xVideo_ATTRIB_RATE = 3; //used to set Graph Rate
xVideo_ATTRIB_AspectRatio = 4; //used to set Aspect Ratio
xVideo_Ratio_4p3 = 1010;
xVideo_Ratio_16p9 = 1011;
xVideo_ATTRIB_PITCH = 5; //used to set Audio Pitch
xVideo_ATTRIB_AVSync = 6; //used to set Audio/Video Delay
xVideo_ATTRIB_TEMPO = 7; //used to set Audio Tempo
xVideo_ATTRIB_ChanProcess = 8; //used to set audio channel to be processed
{
value: 0 - process as stereo
1 - process right channel
2 - process left channel
}
//xVideo_SetConfig configs and values
xVideo_FLOATDSP = $1003; //use this to enable/disable floating point DSP Processing
xVideo_WindowLessStreams = $1002; //use this to set the number of streams in a VMR7/9 Windowsless mode
xVideo_WindowLessHandle = $1001; //VMR7/VMR9 WindowLess Mode need an initial window so set a HWND to use properly VMR
xVideo_VideoRenderer = $1000;
xVideo_VMR7 = 1; //pass this to select VMR7 Windowed render
xVideo_Overlay = 2; //pass this to select overlay video render
xVideo_VMR9 = 3; //pass this to select VMR9 Windowed render
xVideo_NULL = 4; //pass this to select NULL Video Renderer
xVideo_VMR7WindowsLess = 5; //pass this to select VMR7 window less render
xVideo_VMR9WindowsLess = 6; //pass this to select VMR9 window less render
xVideo_EVR = 7; //pass this to select Enhanced Video Renderer
//for xVideo_DVDSetOption
xVideo_DVD_TITLEMENU = 100;
xVideo_DVD_ROOT = 101; //go to DVD root
xVideo_DVD_NEXTCHAPTER = 102; //go to dvd next chapter
xVideo_DVD_PREVCHAPTER = 103; //go to dvd previous chapter
xVideo_DVD_TITLE = 104; //set the playing title
xVideo_DVD_TITLECHAPTER = 105; //set chapter in title
//for xVideo_DVDGetProp
xVideo_DVDCurrentTitle =$10010; //used in prop
xVideo_DVDTitles =$10020; //used in prop
xVideo_DVDTitleChapters =$10030; //used in prop
xVideo_DVDCurrentTitleTime = 145; //uses to get current DVD title Length
xVideo_DVDCurrentTitlePosition = 146; //uses to get current DVD title position
//for xVideo_MultiVideoSetOption
xVideo_MultivideoParent = 432 ;
////////xVideo_MIX_ChanOptions //////////////////////
xVideo_MixRect = 2000;
xVideo_MixAlpha = 2001;
///Recorder Flags///
Record_AudioDevices = 5000;
Record_VideoDevices = 5001;
//ERROR CODES
xVideo_Unknown = -1; //unknown error
xVideo_OK = 0; //all is ok
xVideo_BADFILENAME = 2; //file don't exists or the filename parameter is NULL
xVideo_INVALIDCHAN = 5; //invalid channel
xVideo_ERROR1 = 107; //this is returned by set dvd menu function
xVideo_ERROR2 = 108; // next chapter failed
xVideo_ERROR3 = 109; //prev chapter failed
xVideo_ERROR4 = 110; // title menu failed
xVideo_ERROR5 = 111; //graph creation failed
xVideo_ERROR6 = 112; //DVD Graph creation failed
xVideo_ERROR7 = 114;
xVideo_ERROR8 = 115; //NO DVD Decoder found
//xVideo_ChannelGetLenght/SetPosition/GetPosition: modes
xVideo_POS_SEC = 0; //position in seconds
xVideo_POS_FRAME = 1; //position in frames
xVideo_POS_MILISEC = 2; //position in miliseconds
//xVideo_ChannelSetSync types
xVideo_SYNC_POS = 0;
xVideo_SYNC_END = 1;
xVideo_SYNC_SLIDE = 2;
xVideo_SYNC_FREE = 3;
xVideo_SYNC_SETPOS = 4;
//xVideo_ChannelGetState return values
xVideo_STATE_STOPPED = 0; //channel is stopped
xVideo_STATE_PLAYING = 1; //channel is playing
xVideo_STATE_PAUSED = 2; //channel is paused
//xVideo_DVD_Menu option parameters list
xVideo_DVDSelAtPos =21; //use this to select button at a TPoint
xVideo_DVDActAtPos =22; //use this to activate button at a TPoint
xVideo_DVDActivBut =23; //use this to activate selected button
xVideo_DVDSeleButton =24;
/////
xVideo_UNICODE = $80000000; //pass this flag when use UNICODE strings
xVideo_STREAM_AUTOFREE = $7000000; //put this flag to free the stream when it completes
xVideo_STREAM_DECODE = $600000; //put this flag to set the channnel as a encoding one
function xVideo_GetVersion(): DWORD; stdcall; external DLLNAME;
function xVideo_StreamCreateURL( str: PCHAR;flags: DWORD): HSTREAM; stdcall; external DLLNAME;
function xVideo_StreamCreateFile(str: PCHAR;position: DWORD;flags: DWORD):HSTREAM;stdcall; external DLLNAME;
function xVideo_Init(handle: HWND):bool;stdcall; external DLLNAME;
procedure xVideo_ChannelSetPosition(chan: HSTREAM;pos: Double;mode: DWORD);stdcall; external DLLNAME;
function xVideo_ChannelGetLength(chan: HSTREAM;mode: DWORD): Double; stdcall; external DLLNAME;
function xVideo_ChannelGetPosition(chan: HSTREAM;mode: DWORD): Double; stdcall; external DLLNAME;
procedure xVideo_ChannelSetWindow(chan: HSTREAM;handle: HWND);stdcall; external DLLNAME;
procedure xVideo_ChannelResizeWindow(chan: HSTREAM;left,top,right,bottom: integer);stdcall; external DLLNAME;
procedure xVideo_ChannelSetFullscreen(chan: HSTREAM;value: boolean);stdcall; external DLLNAME;
function xVideo_ChannelPlay(chan: HSTREAM):bool;stdcall; external DLLNAME;
function xVideo_ChannelPause(chan: HSTREAM):bool;stdcall; external DLLNAME;
function xVideo_StreamFree(chan: HStream): bool; stdcall; external DLLNAME;
function xVideo_ChannelStop(chan: HStream): bool; stdcall; external DLLNAME;
procedure xVideo_ChannelGetInfo(chan: HSTREAM;value: Pointer);stdcall; external DLLNAME;
function xVideo_StreamCreateDVD(dvdfile: Pointer;flags:DWORD):HSTREAM;stdcall; external DLLNAME;
function xVideo_DVDSetOption(chan: HStream;option: DWORD;value: DWORD): bool; stdcall; external DLLNAME;
function xVideo_DVDGetProp(Chan: HSTREAM; prop: DWORD; value: DWORD): DWORD; stdcall; external DLLNAME;
procedure xVideo_SetConfig(config: integer;value: integer); stdcall; external DLLNAME;
function xVideo_ErrorGetCode(): integer; stdcall; external DLLNAME;
procedure xVideo_LoadPlugin(str: pchar;guid :TGUID;name: PCHAR); stdcall; external DLLNAME;
procedure xVideo_LoadPlugin2(str: Pointer;guid :Pointer;name: Pointer;flags: DWORD); stdcall; external DLLNAME;
function xVideo_Free(): BOOL; stdcall; external DLLNAME;
procedure xVideo_ChannelGetConnectedFilters(chan: HSTREAM;callback :Pointer;user:Pointer);stdcall; external DLLNAME; //2.4.1
procedure xVideo_ShowFilterPropertyPage(chan:HSTREAM;filter:DWORD;hndparent: HWND); stdcall; external DLLNAME; //2.4.1
function xVideo_MIX_StreamCreateFile(files: TMixingFiles;fileno: integer;flags: DWORD): HSTREAM; stdcall; external DLLNAME;
function xVideo_MIX_ChanOptions(chan: HSTREAM;option:DWORD;value: DWORD;value2: DWORD;rect: TRECT): BOOL; stdcall; external DLLNAME;
procedure xVideo_ChannelSetTextOverlay(chan: HSTREAM ;text:PCHAR;x, y, red, green, blue: integer;font :HFONT); stdcall; external DLLNAME;
function xVideo_GetGraph(chan: HSTREAM): Pointer; stdcall; external DLLNAME;
///////
function xVideo_Record_GetDevices(devicetype: DWORD;callback: Pointer;user: Pointer): integer; stdcall; external DLLNAME;
function xVideo_RecordStart(audiodevice: Integer;videodevice: Integer;devicetype: DWORD;flags: DWORD): HRECORD; stdcall; external DLLNAME;
function xVideo_RecordFree(rec: HRECORD): BOOL; stdcall; external DLLNAME;
function xVideo_ChannelAddWindow( chan:HSTREAM;win:HWND): HWINDOW; stdcall; external DLLNAME;
function xVideo_ChannelRemoveWindow(chan:HSTREAM;window:HWINDOW):BOOL;stdcall; external DLLNAME;
procedure xVideo_MultiVideoResize(chan:HSTREAM;window:HWINDOW;left,top,width,height: integer); stdcall; external DLLNAME;
procedure xVideo_MultiVideoSetOption(chan: HSTREAM; window: HWINDOW; option: DWORD; value: DWORD);stdcall; external DLLNAME;
function xVideo_ChannelGetFrame(chan: HSTREAM): HBITMAP; stdcall; external DLLNAME;
procedure xVideo_ChannelSetAttribute(chan: HSTREAM; option: DWORD;value: Double); stdcall; external DLLNAME;
procedure xVideo_ChannelGetAttribute(chan: HSTREAM; option: DWORD;var value: Double); stdcall; external DLLNAME;
function xVideo_ChannelSetSync(chan: HSTREAM;typo: DWORD;param: QWORD;proc: Pointer;user: Pointer): HSYNC; stdcall; external DLLNAME;
function xVideo_ChannelRemoveSync(chan: HSTREAM; sync: HSYNC): BOOL; stdcall; external DLLNAME;
function xVideo_ChannelSetDSP(chan: HSTREAM;proc: Pointer;user: Pointer): HDSP; stdcall; external DLLNAME;
function xVideo_ChannelRemoveDSP(chan: HSTREAM;dsp: HDSP): BOOL; stdcall; external DLLNAME;
function xVideo_ChannelGetData(chan: HSTREAM;data: Pointer;size: DWORD): DWORD; stdcall; external DLLNAME;
function xVideo_ChannelGetState(chan: HSTREAM): DWORD; stdcall; external DLLNAME;
function xVideo_ChannelSlideAttribute(chan: HSTREAM;typo: DWORD;param: double):BOOL;stdcall; external DLLNAME;
function xVideo_DVD_Menu(chan: HSTREAM;option: DWORD;value1: integer;value2: integer):BOOL; stdcall; external DLLNAME;
function xVideo_ChannelSetDrawCallback(chan: HSTREAM; proc: Pointer; user: Pointer):BOOL; stdcall; external DLLNAME;
function xVideo_ChannelRepaint(Chan: HSTREAM; handle: HWND; dc: HDC): BOOL; stdcall; external DLLNAME;
function xVideo_LoadPlugin3(str: pchar;flags: DWORD):Boolean; stdcall; external DLLNAME;
implementation
// END OF FILE /////////////////////////////////////////////////////////////////
end.
|
unit osCalculaFormulas;
interface
uses
SysUtils, Classes, osParser, osMaquina, osGrafo, Controls, RegExpr,
osParserErrorHand;
type
{Classe Principal : TosCalculaFormulas }
TosCalculaFormulas = class(TGrafo)
Parser: TosParser;
Maquina: TosMaquina;
FListaErros : TListErro;
private
FTextoErro: TCaption;
FArestasInicializadas: boolean;
// Erros
function RecuperaErro(Index: Integer): TNodoErro;
function RecuperaNumeroErros: Integer;
// calcula nodos e arestas para o grafo usado para calcular resultados
function Inicializa : boolean;
public
constructor Create;
function Calcula: Boolean; override;
procedure AdicionaFormula(Conteudo: TConteudoGrafoDep; pChave: String);
// Funcoes auxiliares
function Imprime : TCaption;
// Propriedades
property TextoErro: TCaption read FTextoErro;
property ListaErros: TListErro read FListaErros;
property Erros[Index: integer]: TNodoErro read RecuperaErro;
property nErros: Integer read RecuperaNumeroErros;
end;
{ Representa uma variavel }
TosFormulaVariavel = class
FNome: String;
FValor: Double;
public
property Nome: String read FNome write FNome;
property Valor: Double read FValor write FValor;
end;
{ Representa uma formula de um sistema de formulas que nao e calculada }
TosFormula = class(TConteudoGrafoDep)
// Parser
FParser: TosParser;
// Informacoes sobre formula
FRotulo: WideString;
FVariavel: TosFormulaVariavel; // Variavel armazenada no nodo
FFormula: WideString; // Formula para calcular resultado
// Erros de parsing da expressao
FListaErrosExpr: TListErro;
private
// Recupera n-esimo erro de parsing e a quantidade de erros
function LeErrosExpr(Index: Integer): TNodoErro;
function NumErrosExpr: Integer;
public
constructor Create(MathParser: TosParser); virtual;
function Processa(Dependencias: TListaElementos): Boolean; override;
// erros de parsing (expressao mal formada)
property ListaErrosExpr: TListErro read FListaErrosExpr;
property nErrosExpr: Integer read NumErrosExpr;
property ErrosExpr[Index: Integer]: TNodoErro read LeErrosExpr;
// formula e nome da variavel
property Formula: WideString read FFormula write FFormula;
property Variavel: TosFormulaVariavel read FVariavel write FVariavel;
property Rotulo: WideString read FRotulo write FRotulo;
end;
{ Representa uma formula que tem seu valor determinado }
TosFormulaCalc = class(TosFormula)
FMaquina: TosMaquina;
FResultadoCalc: Double;
// Erros de parsing da expressao
FListaErrosCalc: TListErro;
private
// Recupera n-esimo erro de calculo e a quantidade de erros
function NumErrosCalc: Integer;
function LeErrosCalc(Index: Integer): TNodoErro;
public
constructor Create(MathParser: TosParser); override;
function Processa(Dependencias: TListaElementos): Boolean; override;
// erros de calculo
property ListaErrosCalc: TListErro read FListaErrosCalc;
property nErrosCalc: Integer read NumErrosCalc;
property ErrosCalc[Index: Integer]: TNodoErro read LeErrosCalc;
// resultado do calculo da formula
property Resultado: Double read FResultadoCalc;
end;
TerrFormula =
(efErroParsing = 1,
efDivisaoPorZero);
{ Funcao para imprimir conteudo de uma lista de formulas }
function ImprimeLista(Lista: TListaElementos): TCaption;
implementation
{ Funcao para imprimir conteudo de uma lista de elementos }
function ImprimeLista(Lista: TListaElementos): TCaption;
var i: Integer;
TextoR: TCaption;
begin
TextoR := '';
i := 0;
while i < Lista.Count do
begin
TextoR :=
TextoR + TosFormula(Lista.Elementos[i]).Variavel.Nome;
if (i+1)<Lista.Count then
TextoR := TextoR + ', ';
i := i + 1;
end;
TextoR := TextoR + #13#10;
ImprimeLista := TextoR;
end;
{ TosCalculaFormulas }
constructor TosCalculaFormulas.Create;
begin
inherited;
Parser := TosParser.Create;
FListaErros := TListErro.Create;
FArestasInicializadas := False;
end;
// Obtencao de erros
function TosCalculaFormulas.RecuperaErro(Index: Integer): TNodoErro;
begin
Result := FListaErros.Items[Index];
end;
function TosCalculaFormulas.RecuperaNumeroErros: Integer;
begin
Result := FListaErros.Count;
end;
// baseado nos vertices atuais, cria as arestas necessarias
// gera lista de erros de valiaveis não existentes
// Retorna False se ocorreu algum erro
function TosCalculaFormulas.Inicializa : boolean;
var
Index, i: Integer;
DestVert: Integer;
begin
Index := 0;
while Index < Count do
begin
// atribui expressao para que o parser processe-a
Parser.Expressao := AnsiString(String(TosFormula(Elementos[Index]).Formula));
if Parser.Expressao <> '' then
begin
// compila a expressao
Parser.Compile;
for i := 0 to Parser.nVariaveis-1 do
begin
DestVert := IndexOf(Parser.Variavel[i]);
// se DestVert for -1, significa que a variavel nao existe
if (DestVert = -1) then
FListaErros.Add(epWarning, i, 'Atributo ''%s'', Variável ''%s'' não definida.',
[TosFormula(Elementos[Index]).Rotulo, Parser.Variavel[i]])
else
if (DestVert <> Index) then
AdicionaAresta(Index, DestVert);
end;
end;
Inc(Index);
end;
FArestasInicializadas := True;
Result := (FListaErros.Count = 0);
end;
// Adiciona nova formula no sistema
procedure TosCalculaFormulas.AdicionaFormula(Conteudo: TConteudoGrafoDep;
pChave: String);
var
Vertice: TVertice;
begin
FArestasInicializadas := False;
Vertice := TVertice.Create(Conteudo, pChave);
Self.AddObject(pChave, Vertice);
end;
// "imprime" o grafo de calculo; somente para debug
function TosCalculaFormulas.Imprime: TCaption;
var i, j: Integer;
Arestas : TListaElementos;
TextoR: TCaption;
begin
TextoR := '';
i := 0;
while i < Count do
begin
Arestas := TVertice(Objects[i]).Arestas;
TextoR :=
TextoR + TosFormula(Elementos[i]).Variavel.Nome + ': ';
j := 0;
while j < Arestas.Count do
begin
TextoR :=
TextoR +
TosFormula(TVertice(Arestas.Objects[j]).Conteudo).Variavel.Nome;
if (j+1) < Arestas.Count then
TextoR := TextoR + ', ';
j := j + 1;
end;
TextoR := TextoR + #13#10;
i := i + 1;
end;
Imprime := TextoR;
end;
function TosCalculaFormulas.Calcula: Boolean;
begin
if not(FArestasInicializadas) then
Result := Inicializa // inicializa arestas verifica Variaveis
else
Result := True;
// se não houve erros na inicialização então Calcula
if Result then
Result := inherited Calcula;
end;
{ TosFormula }
constructor TosFormula.Create(MathParser: TosParser);
begin
FParser := MathParser;
FVariavel := TosFormulaVariavel.Create;
FVariavel.Nome := '';
FVariavel.Valor := 0;
FListaErrosExpr := TListErro.Create;
end;
function TosFormula.LeErrosExpr(Index: Integer): TNodoErro;
begin
Result := FListaErrosExpr.Items[Index];
end;
function TosFormula.NumErrosExpr: Integer;
begin
Result := FListaErrosExpr.Count;
end;
function TosFormula.Processa(Dependencias: TListaElementos): Boolean;
begin
FParser.Expressao := AnsiString(String(FFormula));
if not(FParser.Compile) then
FListaErrosExpr.Assign(FParser.ListaErros);
Result := FListaErrosExpr.Count = 0;
end;
{ TosFormulaCalc }
constructor TosFormulaCalc.Create(MathParser: TosParser);
begin
inherited;
FResultadoCalc := 0;
FMaquina := TosMaquina.Create;
FMaquina.Parser := MathParser;
FListaErrosCalc := TListErro.Create;
end;
function TosFormulaCalc.LeErrosCalc(Index: Integer): TNodoErro;
begin
Result := FListaErrosCalc.Items[Index];
end;
function TosFormulaCalc.NumErrosCalc: Integer;
begin
Result := FListaErrosCalc.Count;
end;
function TosFormulaCalc.Processa(Dependencias: TListaElementos): Boolean;
var
Index : Integer;
VariavelAdj : TosFormulaVariavel;
begin
// avaliacao da expressao
FParser.Expressao := AnsiString(String(FFormula));
if not(FParser.Compile) then
FListaErrosExpr.Assign(FParser.ListaErros);
Result := FListaErrosExpr.Count = 0;
if not(Result) then
Exit;
FResultadoCalc := Variavel.Valor;
if Formula <> '' then
begin
// Seta variaveis na formula com respectivos valores dos vertices adj.
Index := 0;
while Index < Dependencias.Count do
begin
VariavelAdj := TosFormulaCalc(Dependencias.Elementos[Index]).Variavel;
FResultadoCalc := TosFormulaCalc(Dependencias.Elementos[Index]).Resultado;
FMaquina.SetaVariavel(AnsiUpperCase(VariavelAdj.Nome), FResultadoCalc);
Index := Index + 1;
end;
// Atribui o valor a variavel
FMaquina.SetaVariavel(AnsiUpperCase(Variavel.Nome), Variavel.Valor);
// tenta calcular o resultado
try
if not(FMaquina.Exec) then
FListaErrosCalc.Assign(FMaquina.ListaErros)
else
FResultadoCalc := FMaquina.Resultado;
except
// Excecoes em operacoes matematicas
on EZeroDivide do FListaErrosCalc.Add(epError, Ord(efDivisaoPorZero),
'Erro de divisão por zero.', []);
end;
Result := (FMaquina.nErros = 0);
end;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2013-2018 Kike P�rez
Unit : Quick.ImageFX.GR32
Description : Image manipulation with GR32
Author : Kike P�rez
Version : 4.0
Created : 10/04/2013
Modified : 11/08/2018
This file is part of QuickImageFX: https://github.com/exilon/QuickImageFX
Third-party libraries used:
Graphics32 (https://github.com/graphics32/graphics32)
CCR-Exif from Chris Rolliston (https://code.google.com/archive/p/ccr-exif)
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.ImageFX.GR32;
interface
uses
Windows,
Classes,
Controls,
Vcl.ImgList,
System.SysUtils,
Vcl.Graphics,
Winapi.ShellAPI,
System.Math,
GR32,
GR32_Resamplers,
GR32_Image,
GR32_Filters,
GR32_Transforms,
GR32_Math,
GDIPAPI,
GDIPOBJ,
GDIPUTIL,
Vcl.Imaging.pngimage,
Vcl.Imaging.jpeg,
Vcl.Imaging.GIFImg,
Quick.Base64,
Quick.ImageFX,
Quick.ImageFX.Types;
const
MaxPixelCountA = MaxInt Div SizeOf (TRGBQuad);
type
TScanlineMode = (smHorizontal, smVertical);
PRGBAArray = ^TRGBAArray;
TRGBAArray = Array [0..MaxPixelCountA -1] Of TRGBQuad;
PGPColorArr = ^TGPColorArr;
TGPColorArr = array[0..500] of TGPColor;
pRGBQuadArray = ^TRGBQuadArray;
TRGBQuadArray = ARRAY [0 .. $EFFFFFF] OF TRGBQuad;
TRGBArray = ARRAY[0..32767] OF TRGBTriple;
pRGBArray = ^TRGBArray;
TImageFXGR32 = class(TImageFX,IImageFX)
private
fBitmap : TBitmap32;
procedure DoScanlines(ScanlineMode : TScanlineMode);
function ResizeImage(w, h : Integer; ResizeOptions : TResizeOptions) : IImageFX;
procedure GPBitmapToBitmap(gpbmp : TGPBitmap; bmp : TBitmap32);
function GetFileInfo(AExt : string; var AInfo : TSHFileInfo; ALargeIcon : Boolean = false) : boolean;
procedure SetPixelImage(const x, y: Integer; const P: TPixelInfo; bmp32 : TBitmap32);
function GetPixelImage(const x, y: Integer; bmp32 : TBitmap32): TPixelInfo;
protected
function GetPixel(const x, y: Integer): TPixelInfo;
procedure SetPixel(const x, y: Integer; const P: TPixelInfo);
public
property AsBitmap32 : TBitmap32 read fBitmap write fBitmap;
constructor Create; overload; override;
destructor Destroy; override;
function NewBitmap(w, h : Integer) : IImageFX;
property Pixel[const x, y: Integer]: TPixelInfo read GetPixel write SetPixel;
function IsEmpty : Boolean;
function LoadFromFile(const fromfile : string; CheckIfFileExists : Boolean = False) : IImageFX;
function LoadFromStream(stream : TStream) : IImageFX;
function LoadFromString(const str : string) : IImageFX;
function LoadFromImageList(imgList : TImageList; ImageIndex : Integer) : IImageFX;
function LoadFromIcon(Icon : TIcon) : IImageFX;
function LoadFromFileIcon(const FileName : string; IconIndex : Word) : IImageFX;
function LoadFromFileExtension(const aFilename : string; LargeIcon : Boolean) : IImageFX;
function LoadFromResource(const ResourceName : string) : IImageFX;
function Clone : IImageFX;
function IsGray : Boolean;
procedure Assign(Graphic : TGraphic);
procedure GetResolution(var x,y : Integer); overload;
function GetResolution : string; overload;
function AspectRatio : Double;
function Clear(pcolor : TColor = clNone) : IImageFX;
function Resize(w, h : Integer) : IImageFX; overload;
function Resize(w, h : Integer; ResizeMode : TResizeMode; ResizeFlags : TResizeFlags = []; ResampleMode : TResamplerMode = rsLinear) : IImageFX; overload;
procedure GraphicToBitmap32(Graphic : TGraphic; var bmp32 : TBitmap32);
function Draw(Graphic : TGraphic; x, y : Integer; alpha : Double = 1) : IImageFX; overload;
function Draw(stream: TStream; x: Integer; y: Integer; alpha: Double = 1) : IImageFX; overload;
function DrawCentered(Graphic : TGraphic; alpha : Double = 1) : IImageFX; overload;
function DrawCentered(stream: TStream; alpha : Double = 1) : IImageFX; overload;
function Rotate90 : IImageFX;
function Rotate180 : IImageFX;
function Rotate270 : IImageFX;
function RotateAngle(RotAngle : Single) : IImageFX;
function RotateBy(RoundAngle : Integer) : IImageFX;
function FlipX : IImageFX;
function FlipY : IImageFX;
function GrayScale : IImageFX;
function ScanlineH : IImageFX;
function ScanlineV : IImageFX;
function Lighten(StrenghtPercent : Integer = 30) : IImageFX;
function Darken(StrenghtPercent : Integer = 30) : IImageFX;
function Tint(mColor : TColor) : IImageFX;
function TintAdd(R, G , B : Integer) : IImageFX;
function TintBlue : IImageFX;
function TintRed : IImageFX;
function TintGreen : IImageFX;
function Solarize : IImageFX;
function Rounded(RoundLevel : Integer = 27) : IImageFX;
function AntiAliasing : IImageFX;
function SetAlpha(Alpha : Byte) : IImageFX;
procedure SaveToPNG(const outfile : string);
procedure SaveToJPG(const outfile : string);
procedure SaveToBMP(const outfile : string);
procedure SaveToGIF(const outfile : string);
function AsBitmap : TBitmap;
function AsString(imgFormat : TImageFormat = ifJPG) : string;
procedure SaveToStream(stream : TStream; imgFormat : TImageFormat = ifJPG);
function AsPNG : TPngImage;
function AsJPG : TJpegImage;
function AsGIF : TGifImage;
end;
implementation
constructor TImageFXGR32.Create;
begin
inherited Create;
fBitmap := TBitmap32.Create;
end;
destructor TImageFXGR32.Destroy;
begin
if Assigned(fBitmap) then fBitmap.Free;
inherited;
end;
{function TImageFXGR32.LoadFromFile(fromfile: string) : TImageFX;
var
fs: TFileStream;
FirstBytes: AnsiString;
Graphic: TGraphic;
bmp : TBitmap;
begin
Result := Self;
if not FileExists(fromfile) then
begin
fLastResult := arFileNotExist;
Exit;
end;
Graphic := nil;
fs := TFileStream.Create(fromfile, fmOpenRead);
try
SetLength(FirstBytes, 8);
fs.Read(FirstBytes[1], 8);
if Copy(FirstBytes, 1, 2) = 'BM' then
begin
Graphic := TBitmap.Create;
end else
if FirstBytes = #137'PNG'#13#10#26#10 then
begin
Graphic := TPngImage.Create;
end else
if Copy(FirstBytes, 1, 3) = 'GIF' then
begin
Graphic := TGIFImage.Create;
end else
if Copy(FirstBytes, 1, 2) = #$FF#$D8 then
begin
Graphic := TJPEGImage.Create;
end;
if Assigned(Graphic) then
begin
try
fs.Seek(0, soFromBeginning);
Graphic.LoadFromStream(fs);
bmp := TBitmap.Create;
try
InitBitmap(bmp);
bmp.Assign(Graphic);
fBitmap.Assign(bmp);
fLastResult := arOk;
finally
bmp.Free;
end;
except
end;
Graphic.Free;
end;
finally
fs.Free;
end;
end;}
function TImageFXGR32.LoadFromFile(const fromfile: string; CheckIfFileExists : Boolean = False) : IImageFX;
var
fs : TFileStream;
begin
Result := Self;
if (CheckIfFileExists) and (not FileExists(fromfile)) then
begin
LastResult := arFileNotExist;
Exit;
end;
//loads file into stream
fs := TFileStream.Create(fromfile,fmShareDenyWrite);
try
Self.LoadFromStream(fs);
finally
fs.Free;
end;
end;
function TImageFXGR32.LoadFromStream(stream: TStream) : IImageFX;
var
Graphic : TGraphic;
GraphicClass : TGraphicClass;
begin
Result := Self;
if (not Assigned(stream)) or (stream.Size = 0) then
begin
LastResult := arZeroBytes;
raise Exception.Create('Stream is empty!');
end;
stream.Seek(0,soBeginning);
if not FindGraphicClass(Stream,GraphicClass) then raise EInvalidGraphic.Create('Unknow Graphic format');
Graphic := GraphicClass.Create;
try
stream.Seek(0,soBeginning);
Graphic.LoadFromStream(stream);
if (Graphic.Transparent) and (not (Graphic is TGIFImage)) then GraphicToBitmap32(Graphic,fBitmap)
else fBitmap.Assign(Graphic);
if ExifRotation then ProcessEXIFRotation(stream);
LastResult := arOk;
finally
Graphic.Free;
end;
end;
function TImageFXGR32.LoadFromString(const str: string) : IImageFX;
var
stream : TStringStream;
begin
Result := Self;
if str = '' then
begin
LastResult := arZeroBytes;
Exit;
end;
stream := TStringStream.Create(Base64Decode(str));
try
LoadFromStream(stream);
LastResult := arOk;
finally
stream.Free;
end;
end;
function TImageFXGR32.LoadFromFileIcon(const FileName : string; IconIndex : Word) : IImageFX;
var
Icon : TIcon;
begin
Result := Self;
Icon := TIcon.Create;
try
Icon.Handle := ExtractAssociatedIcon(hInstance,pChar(FileName),IconIndex);
Icon.Transparent := True;
fBitmap.Assign(Icon);
finally
Icon.Free;
end;
end;
function TImageFXGR32.LoadFromResource(const ResourceName : string) : IImageFX;
var
icon : TIcon;
GPBitmap : TGPBitmap;
begin
Result := Self;
icon:=TIcon.Create;
try
icon.LoadFromResourceName(HInstance,ResourceName);
icon.Transparent:=True;
GPBitmap := TGPBitmap.Create(Icon.Handle);
try
GPBitmapToBitmap(GPBitmap,fBitmap);
finally
if Assigned(GPBitmap) then GPBitmap.Free;
end;
finally
icon.Free;
end;
//png:=TPngImage.CreateBlank(COLOR_RGBALPHA,16,Icon.Width,Icon.Height);
//png.Canvas.Draw(0,0,Icon);
//DrawIcon(png.Canvas.Handle, 0, 0, Icon.Handle);
end;
function TImageFXGR32.LoadFromImageList(imgList : TImageList; ImageIndex : Integer) : IImageFX;
var
icon : TIcon;
begin
Result := Self;
//imgList.ColorDepth := cd32bit;
//imgList.DrawingStyle := dsTransparent;
icon := TIcon.Create;
try
imgList.GetIcon(ImageIndex,icon);
fBitmap.Assign(Icon);
finally
icon.Free;
end;
end;
function TImageFXGR32.LoadFromIcon(Icon : TIcon) : IImageFX;
begin
Result := Self;
fBitmap.Assign(Icon);
end;
function TImageFXGR32.LoadFromFileExtension(const aFilename : string; LargeIcon : Boolean) : IImageFX;
var
icon : TIcon;
aInfo : TSHFileInfo;
begin
Result := Self;
LastResult := arUnknowFmtType;
if GetFileInfo(ExtractFileExt(aFilename),aInfo,LargeIcon) then
begin
icon := TIcon.Create;
try
Icon.Handle := AInfo.hIcon;
Icon.Transparent := True;
fBitmap.Assign(Icon);
LastResult := arOk;
finally
icon.Free;
DestroyIcon(aInfo.hIcon);
end;
end;
end;
function TImageFXGR32.AspectRatio : Double;
begin
if Assigned(fBitmap) then Result := fBitmap.width / fBitmap.Height
else Result := 0;
end;
procedure TImageFXGR32.GetResolution(var x,y : Integer);
begin
if Assigned(fBitmap) then
begin
x := fBitmap.Width;
y := fBitmap.Height;
LastResult := arOk;
end
else
begin
x := -1;
y := -1;
LastResult := arCorruptedData;
end;
end;
function TImageFXGR32.Clear(pcolor : TColor = clNone) : IImageFX;
begin
Result := Self;
fBitmap.Clear;
fBitmap.FillRect(0,0,fBitmap.Width,fBitmap.Height,pColor);
LastResult := arOk;
end;
function TImageFXGR32.Clone : IImageFX;
begin
Result := TImageFXGR32.Create;
(Result as TImageFXGR32).fBitmap.Assign(Self.fBitmap);
CloneValues(Result);
end;
function TImageFXGR32.ResizeImage(w, h : Integer; ResizeOptions : TResizeOptions) : IImageFX;
var
bmp32 : TBitmap32;
Resam : TCustomResampler;
srcRect,
tgtRect : TRect;
crop : Integer;
srcRatio : Double;
nw, nh : Integer;
begin
Result := Self;
LastResult := arResizeError;
if (not Assigned(fBitmap)) or ((fBitmap.Width * fBitmap.Height) = 0) then
begin
LastResult := arZeroBytes;
Exit;
end;
//if any value is 0, calculates proportionaly
if (w * h) = 0 then
begin
//scales max w or h
if ResizeOptions.ResizeMode = rmScale then
begin
if (h = 0) and (fBitmap.Height > fBitmap.Width) then
begin
h := w;
w := 0;
end;
end
else ResizeOptions.ResizeMode := rmFitToBounds;
begin
if w > h then
begin
nh := (w * fBitmap.Height) div fBitmap.Width;
h := nh;
nw := w;
end
else
begin
nw := (h * fBitmap.Width) div fBitmap.Height;
w := nw;
nh := h;
end;
end;
end;
case ResizeOptions.ResizeMode of
rmScale: //recalculate width or height target size to preserve original aspect ratio
begin
if fBitmap.Width > fBitmap.Height then
begin
nh := (w * fBitmap.Height) div fBitmap.Width;
h := nh;
nw := w;
end
else
begin
nw := (h * fBitmap.Width) div fBitmap.Height;
w := nw;
nh := h;
end;
srcRect := Rect(0,0,fBitmap.Width,fBitmap.Height);
end;
rmCropToFill: //preserve target aspect ratio cropping original image to fill whole size
begin
nw := w;
nh := h;
crop := Round(h / w * fBitmap.Width);
if crop < fBitmap.Height then
begin
//target image is wider, so crop top and bottom
srcRect.Left := 0;
srcRect.Top := (fBitmap.Height - crop) div 2;
srcRect.Width := fBitmap.Width;
srcRect.Height := crop;
end
else
begin
//target image is narrower, so crop left and right
crop := Round(w / h * fBitmap.Height);
srcRect.Left := (fBitmap.Width - crop) div 2;
srcRect.Top := 0;
srcRect.Width := crop;
srcRect.Height := fBitmap.Height;
end;
end;
rmFitToBounds: //resize image to fit max bounds of target size
begin
srcRatio := fBitmap.Width / fBitmap.Height;
if fBitmap.Width > fBitmap.Height then
begin
nw := w;
nh := Round(w / srcRatio);
if nh > h then //too big
begin
nh := h;
nw := Round(h * srcRatio);
end;
end
else
begin
nh := h;
nw := Round(h * srcRatio);
if nw > w then //too big
begin
nw := w;
nh := Round(w / srcRatio);
end;
end;
srcRect := Rect(0,0,fBitmap.Width,fBitmap.Height);
end;
else
begin
nw := w;
nh := h;
srcRect := Rect(0,0,fBitmap.Width,fBitmap.Height);
end;
end;
//if image is smaller no upsizes
if ResizeOptions.NoMagnify then
begin
if (fBitmap.Width < nw) or (fBitmap.Height < nh) then
begin
//if FitToBounds then preserve original size
if ResizeOptions.ResizeMode = rmFitToBounds then
begin
nw := fBitmap.Width;
nh := fBitmap.Height;
end
else
begin
//all cases no resizes, but CropToFill needs to grow to fill target size
if ResizeOptions.ResizeMode <> rmCropToFill then
begin
if not ResizeOptions.SkipSmaller then
begin
LastResult := arAlreadyOptim;
nw := srcRect.Width;
nh := srcRect.Height;
w := nw;
h := nh;
end
else Exit;
end;
end;
end;
end;
if ResizeOptions.Center then
begin
tgtRect.Top := (h - nh) div 2;
tgtRect.Left := (w - nw) div 2;
tgtRect.Width := nw;
tgtRect.Height := nh;
end
else tgtRect := Rect(0,0,nw,nh);
//selects resampler algorithm
case ResizeOptions.ResamplerMode of
rsAuto :
begin
if (w < fBitmap.Width ) or (h < fBitmap.Height) then Resam := TDraftResampler.Create
else Resam := TLinearResampler.Create;
end;
rsNearest : Resam := TNearestResampler.Create;
rsGR32Draft : Resam := TDraftResampler.Create;
rsGR32Kernel : Resam := TKernelResampler.Create;
rsLinear : Resam := TLinearResampler.Create;
else Resam := TKernelResampler.Create;
end;
try
bmp32 := TBitmap32.Create;
try
bmp32.Width := w;
bmp32.Height := h;
if ResizeOptions.FillBorders then bmp32.FillRect(0,0,w,h,Color32(ResizeOptions.BorderColor));
StretchTransfer(bmp32,tgtRect,tgtRect,fBitmap,srcRect,Resam,dmOpaque,nil);
try
fBitmap.Assign(bmp32);
LastResult := arOk;
except
LastResult := arCorruptedData;
end;
finally
bmp32.Free;
end;
finally
Resam.Free;
end;
end;
function TImageFXGR32.Resize(w, h : Integer) : IImageFX;
begin
Result := ResizeImage(w,h,ResizeOptions);
end;
function TImageFXGR32.Resize(w, h : Integer; ResizeMode : TResizeMode; ResizeFlags : TResizeFlags = []; ResampleMode : TResamplerMode = rsLinear) : IImageFX;
var
ResizeOptions : TResizeOptions;
begin
ResizeOptions := TResizeOptions.Create;
try
if (rfNoMagnify in ResizeFlags) then ResizeOptions.NoMagnify := True else ResizeOptions.NoMagnify := False;
if (rfCenter in ResizeFlags) then ResizeOptions.Center := True else ResizeOptions.Center := False;
if (rfFillBorders in ResizeFlags) then ResizeOptions.FillBorders := True else ResizeOptions.FillBorders := False;
Result := ResizeImage(w,h,ResizeOptions);
finally
ResizeOptions.Free;
end;
end;
procedure TImageFXGR32.Assign(Graphic : TGraphic);
var
ms : TMemoryStream;
begin
ms := TMemoryStream.Create;
try
Graphic.SaveToStream(ms);
ms.Seek(0,soBeginning);
LoadFromStream(ms);
finally
ms.Free;
end;
end;
function TImageFXGR32.Draw(Graphic : TGraphic; x, y : Integer; alpha : Double = 1) : IImageFX;
var
bmp : TBitmap32;
begin
Result := Self;
if alpha = 1 then
begin
fBitmap.Canvas.Draw(x,y,Graphic);
end
else
begin
bmp := TBitmap32.Create;
try
GraphicToBitmap32(Graphic,bmp);
bmp.MasterAlpha := Round(255 * alpha);
bmp.DrawMode := TDrawMode.dmBlend;
bmp.DrawTo(fBitmap,x,y);
finally
bmp.Free;
end;
end;
end;
procedure TImageFXGR32.GraphicToBitmap32(Graphic : TGraphic; var bmp32 : TBitmap32);
begin
bmp32.Width := Graphic.Width;
bmp32.Height := Graphic.Height;
bmp32.Canvas.Draw(0,0,Graphic);
end;
function TImageFXGR32.Draw(stream: TStream; x: Integer; y: Integer; alpha: Double = 1) : IImageFX;
var
GraphicClass : TGraphicClass;
overlay : TGraphic;
begin
//get overlay image
stream.Seek(0,soBeginning);
if not FindGraphicClass(stream,GraphicClass) then raise Exception.Create('overlary unknow graphic format');
overlay := GraphicClass.Create;
try
stream.Seek(0,soBeginning);
overlay.LoadFromStream(stream);
if overlay.Empty then raise Exception.Create('Overlay error!');
//needs x or y center image
if x = -1 then x := (fBitmap.Width - overlay.Width) div 2;
if y = -1 then y := (fBitmap.Height - overlay.Height) div 2;
Result := Draw(overlay,x,y,alpha);
finally
overlay.Free;
end;
end;
function TImageFXGR32.DrawCentered(Graphic : TGraphic; alpha : Double = 1) : IImageFX;
begin
Result := Draw(Graphic,(fBitmap.Width - Graphic.Width) div 2, (fBitmap.Height - Graphic.Height) div 2,alpha);
end;
function TImageFXGR32.DrawCentered(stream: TStream; alpha : Double = 1) : IImageFX;
begin
Result := Draw(stream,-1,-1,alpha);
end;
function TImageFXGR32.NewBitmap(w, h: Integer): IImageFX;
begin
if Assigned(Self.fBitmap) then
begin
Self.fBitmap.Clear;
Self.fBitmap.SetSize(w, h);
end
else Result := Self;
end;
function TImageFXGR32.IsEmpty : Boolean;
begin
Result := fBitmap.Empty;
end;
function TImageFXGR32.Rotate90 : IImageFX;
var
bmp32 : TBitmap32;
begin
Result := Self;
LastResult := arRotateError;
bmp32 := TBitmap32.Create;
try
bmp32.Assign(fBitmap);
bmp32.Rotate90(fBitmap);
LastResult := arOk;
finally
bmp32.Free;
end;
end;
function TImageFXGR32.Rotate180 : IImageFX;
var
bmp32 : TBitmap32;
begin
Result := Self;
LastResult := arRotateError;
bmp32 := TBitmap32.Create;
try
bmp32.Assign(fBitmap);
bmp32.Rotate180(fBitmap);
LastResult := arOk;
finally
bmp32.Free;
end;
end;
function TImageFXGR32.RotateAngle(RotAngle: Single) : IImageFX;
var
SrcR: Integer;
SrcB: Integer;
T: TAffineTransformation;
Sn, Cn: TFloat;
Sx, Sy, Scale: Single;
bmp32 : TBitmap32;
begin
Result := Self;
LastResult := arRotateError;
//SetBorderTransparent(fBitmap, fBitmap.BoundsRect);
SrcR := fBitmap.Width - 1;
SrcB := fBitmap.Height - 1;
T := TAffineTransformation.Create;
T.SrcRect := FloatRect(0, 0, SrcR + 1, SrcB + 1);
try
// shift the origin
T.Clear;
// move the origin to a center for scaling and rotation
T.Translate(-SrcR * 0.5, -SrcB * 0.5);
T.Rotate(0, 0, RotAngle);
RotAngle := RotAngle * PI / 180;
// get the width and height of rotated image (without scaling)
GR32_Math.SinCos(RotAngle, Sn, Cn);
Sx := Abs(SrcR * Cn) + Abs(SrcB * Sn);
Sy := Abs(SrcR * Sn) + Abs(SrcB * Cn);
// calculate a new scale so that the image fits in original boundaries
Sx := fBitmap.Width / Sx;
Sy := fBitmap.Height / Sy;
Scale := Min(Sx, Sy);
T.Scale(Scale);
// move the origin back
T.Translate(SrcR * 0.5, SrcB * 0.5);
// transform the bitmap
bmp32 := TBitmap32.Create;
bmp32.SetSize(fBitmap.Width,fBitmap.Height);
try
//bmp32.Clear(clBlack32);
Transform(bmp32, fBitmap, T);
fBitmap.Assign(bmp32);
LastResult := arOk;
finally
bmp32.Free;
end;
finally
T.Free;
end;
end;
function TImageFXGR32.RotateBy(RoundAngle: Integer): IImageFX;
begin
Result := RotateAngle(RoundAngle);
LastResult := arOk;
end;
function TImageFXGR32.Rotate270 : IImageFX;
var
bmp32 : TBitmap32;
begin
Result := Self;
LastResult := arRotateError;
bmp32 := TBitmap32.Create;
try
bmp32.Assign(fBitmap);
bmp32.Rotate270(fBitmap);
LastResult := arOk;
finally
bmp32.Free;
end;
end;
function TImageFXGR32.FlipX : IImageFX;
var
bmp32 : TBitmap32;
begin
Result := Self;
LastResult := arRotateError;
bmp32 := TBitmap32.Create;
try
bmp32.Assign(fBitmap);
bmp32.FlipHorz(fBitmap);
LastResult := arOk;
finally
bmp32.Free;
end;
end;
function TImageFXGR32.FlipY : IImageFX;
var
bmp32 : TBitmap32;
begin
Result := Self;
LastResult := arRotateError;
bmp32 := TBitmap32.Create;
try
bmp32.Assign(fBitmap);
bmp32.FlipVert(fBitmap);
LastResult := arOk;
finally
bmp32.Free;
end;
end;
function TImageFXGR32.GrayScale : IImageFX;
begin
Result := Self;
LastResult := arColorizeError;
ColorToGrayScale(fBitmap,fBitmap,True);
LastResult := arOk;
end;
function TImageFXGR32.IsGray: Boolean;
begin
raise ENotImplemented.Create('Not implemented!');
end;
function TImageFXGR32.Lighten(StrenghtPercent : Integer = 30) : IImageFX;
var
Bits: PColor32Entry;
I, J: Integer;
begin
Result := Self;
LastResult := arColorizeError;
Bits := @fBitmap.Bits[0];
fBitmap.BeginUpdate;
try
for I := 0 to fBitmap.Height - 1 do
begin
for J := 0 to fBitmap.Width - 1 do
begin
if Bits.R + 5 < 255 then Bits.R := Bits.R + 5;
if Bits.G + 5 < 255 then Bits.G := Bits.G + 5;
if Bits.B + 5 < 255 then Bits.B := Bits.B + 5;
Inc(Bits);
end;
end;
LastResult := arOk;
finally
fBitmap.EndUpdate;
fBitmap.Changed;
end;
end;
function TImageFXGR32.Darken(StrenghtPercent : Integer = 30) : IImageFX;
var
Bits: PColor32Entry;
I, J: Integer;
Percent: Single;
Brightness: Integer;
begin
Result := Self;
LastResult := arColorizeError;
Percent := (100 - StrenghtPercent) / 100;
Bits := @fBitmap.Bits[0];
fBitmap.BeginUpdate;
try
for I := 0 to fBitmap.Height - 1 do
begin
for J := 0 to fBitmap.Width - 1 do
begin
Brightness := Round((Bits.R+Bits.G+Bits.B)/765);
Bits.R := Lerp(Bits.R, Brightness, Percent);
Bits.G := Lerp(Bits.G, Brightness, Percent);
Bits.B := Lerp(Bits.B, Brightness, Percent);
Inc(Bits);
end;
end;
LastResult := arOk;
finally
fBitmap.EndUpdate;
fBitmap.Changed;
end;
end;
function TImageFXGR32.Tint(mColor : TColor) : IImageFX;
var
Bits: PColor32Entry;
Color: TColor32Entry;
I, J: Integer;
Percent: Single;
Brightness: Single;
begin
Result := Self;
LastResult := arColorizeError;
Color.ARGB := Color32(mColor);
Percent := 10 / 100;
Bits := @fBitmap.Bits[0];
fBitmap.BeginUpdate;
try
for I := 0 to fBitmap.Height - 1 do
begin
for J := 0 to fBitmap.Width - 1 do
begin
Brightness := (Bits.R+Bits.G+Bits.B)/765;
Bits.R := Lerp(Bits.R, Round(Brightness * Color.R), Percent);
Bits.G := Lerp(Bits.G, Round(Brightness * Color.G), Percent);
Bits.B := Lerp(Bits.B, Round(Brightness * Color.B), Percent);
Inc(Bits);
end;
end;
LastResult := arOk;
finally
fBitmap.EndUpdate;
fBitmap.Changed;
end;
end;
function TImageFXGR32.TintAdd(R, G , B : Integer) : IImageFX;
var
Bits: PColor32Entry;
I, J: Integer;
begin
Result := Self;
LastResult := arColorizeError;
Bits := @fBitmap.Bits[0];
fBitmap.BeginUpdate;
try
for I := 0 to fBitmap.Height - 1 do
begin
for J := 0 to fBitmap.Width - 1 do
begin
//Brightness := (Bits.R+Bits.G+Bits.B)/765;
if R > -1 then Bits.R := Bits.R + R;
if G > -1 then Bits.G := Bits.G + G;
if B > -1 then Bits.B := Bits.B + B;
Inc(Bits);
end;
end;
LastResult := arOk;
finally
fBitmap.EndUpdate;
fBitmap.Changed;
end;
end;
function TImageFXGR32.TintBlue : IImageFX;
begin
Result := Tint(clBlue);
end;
function TImageFXGR32.TintRed : IImageFX;
begin
Result := Tint(clRed);
end;
function TImageFXGR32.TintGreen : IImageFX;
begin
Result := Tint(clGreen);
end;
function TImageFXGR32.Solarize : IImageFX;
begin
Result := TintAdd(255,-1,-1);
end;
function TImageFXGR32.ScanlineH;
begin
Result := Self;
DoScanLines(smHorizontal);
end;
function TImageFXGR32.ScanlineV;
begin
Result := Self;
DoScanLines(smVertical);
end;
procedure TImageFXGR32.DoScanLines(ScanLineMode : TScanlineMode);
var
Bits: PColor32Entry;
Color: TColor32Entry;
I, J: Integer;
DoLine : Boolean;
begin
LastResult := arColorizeError;
Color.ARGB := Color32(clBlack);
Bits := @fBitmap.Bits[0];
fBitmap.BeginUpdate;
try
for I := 0 to fBitmap.Height - 1 do
begin
for J := 0 to fBitmap.Width - 1 do
begin
DoLine := False;
if ScanLineMode = smHorizontal then
begin
if Odd(I) then DoLine := True;
end
else
begin
if Odd(J) then DoLine := True;
end;
if DoLine then
begin
Bits.R := Round(Bits.R-((Bits.R/255)*100));;// Lerp(Bits.R, Round(Brightness * Color.R), Percent);
Bits.G := Round(Bits.G-((Bits.G/255)*100));;//Lerp(Bits.G, Round(Brightness * Color.G), Percent);
Bits.B := Round(Bits.B-((Bits.B/255)*100));;//Lerp(Bits.B, Round(Brightness * Color.B), Percent);
end;
Inc(Bits);
end;
end;
LastResult := arOk;
finally
fBitmap.EndUpdate;
fBitmap.Changed;
end;
end;
procedure TImageFXGR32.SaveToPNG(const outfile : string);
var
png : TPngImage;
begin
LastResult := arConversionError;
png := AsPNG;
try
png.SaveToFile(outfile);
finally
png.Free;
end;
LastResult := arOk;
end;
procedure TImageFXGR32.SaveToJPG(const outfile : string);
var
jpg : TJPEGImage;
begin
LastResult := arConversionError;
jpg := AsJPG;
try
jpg.SaveToFile(outfile);
finally
jpg.Free;
end;
LastResult := arOk;
end;
procedure TImageFXGR32.SaveToBMP(const outfile : string);
var
bmp : TBitmap;
begin
LastResult := arConversionError;
bmp := AsBitmap;
try
bmp.SaveToFile(outfile);
finally
bmp.Free;
end;
LastResult := arOk;
end;
procedure TImageFXGR32.SaveToGIF(const outfile : string);
var
gif : TGIFImage;
begin
LastResult := arConversionError;
gif := AsGIF;
try
gif.SaveToFile(outfile);
finally
gif.Free;
end;
LastResult := arOk;
end;
procedure TImageFXGR32.SaveToStream(stream : TStream; imgFormat : TImageFormat = ifJPG);
var
graf : TGraphic;
begin
if stream.Position > 0 then stream.Seek(0,soBeginning);
case imgFormat of
ifBMP:
begin
graf := TBitmap.Create;
try
graf := Self.AsBitmap;
graf.SaveToStream(stream);
finally
graf.Free;
end;
end;
ifJPG:
begin
graf := TJPEGImage.Create;
try
graf := Self.AsJPG;
graf.SaveToStream(stream);
finally
graf.Free;
end;
end;
ifPNG:
begin
graf := TPngImage.Create;
try
graf := Self.AsPNG;
graf.SaveToStream(stream);
finally
graf.Free;
end;
end;
ifGIF:
begin
graf := TGIFImage.Create;
try
graf := Self.AsGIF;
graf.SaveToStream(stream);
finally
graf.Free;
end;
end;
end;
end;
procedure TImageFXGR32.GPBitmapToBitmap(gpbmp : TGPBitmap; bmp : TBitmap32);
var
Graphics : TGPGraphics;
begin
//bmp.PixelFormat := pf32bit;
//bmp.HandleType := bmDIB;
//bmp.AlphaFormat := afDefined;
bmp.Width := gpbmp.GetWidth;
bmp.Height := gpbmp.GetHeight;
Graphics := TGPGraphics.Create(bmp.Canvas.Handle);
try
Graphics.Clear(ColorRefToARGB(ColorToRGB(clNone)));
// set the composition mode to copy
Graphics.SetCompositingMode(CompositingModeSourceCopy);
// set high quality rendering modes
Graphics.SetInterpolationMode(InterpolationModeHighQualityBicubic);
Graphics.SetPixelOffsetMode(PixelOffsetModeHighQuality);
Graphics.SetSmoothingMode(SmoothingModeHighQuality);
// draw the input image on the output in modified size
Graphics.DrawImage(gpbmp,0,0,gpbmp.GetWidth,gpbmp.GetHeight);
finally
Graphics.Free;
end;
end;
function TImageFXGR32.GetFileInfo(AExt : string; var AInfo : TSHFileInfo; ALargeIcon : Boolean = False) : Boolean;
var uFlags : integer;
begin
FillMemory(@AInfo,SizeOf(TSHFileInfo),0);
uFlags := SHGFI_ICON+SHGFI_TYPENAME+SHGFI_USEFILEATTRIBUTES;
if ALargeIcon then uFlags := uFlags + SHGFI_LARGEICON
else uFlags := uFlags + SHGFI_SMALLICON;
if SHGetFileInfo(PChar(AExt),FILE_ATTRIBUTE_NORMAL,AInfo,SizeOf(TSHFileInfo),uFlags) = 0 then Result := False
else Result := True;
end;
function TImageFXGR32.AsBitmap : TBitmap;
begin
LastResult := arConversionError;
Result := TBitmap.Create;
InitBitmap(Result);
Result.Assign(fBitmap);
LastResult := arOk;
end;
function TImageFXGR32.AsPNG: TPngImage;
var
n, a: Integer;
PNB: TPngImage;
FFF: PRGBAArray;
AAA: pByteArray;
bmp : TBitmap;
begin
LastResult := arConversionError;
Result := TPngImage.CreateBlank(COLOR_RGBALPHA,16,fBitmap.Width,fBitmap.Height);
PNB := TPngImage.Create;
try
PNB.CompressionLevel := PNGCompressionLevel;
Result.CompressionLevel := PNGCompressionLevel;
bmp := AsBitmap;
try
PNB.Assign(bmp);
PNB.CreateAlpha;
for a := 0 to bmp.Height - 1 do
begin
FFF := bmp.ScanLine[a];
AAA := PNB.AlphaScanline[a];
for n := 0 to bmp.Width - 1 do
begin
AAA[n] := FFF[n].rgbReserved;
end;
end;
finally
bmp.Free;
end;
Result.Assign(PNB);
LastResult := arOk;
finally
PNB.Free;
end;
end;
function TImageFXGR32.AsJPG : TJPEGImage;
var
jpg : TJPEGImage;
bmp : TBitmap;
begin
LastResult := arConversionError;
jpg := TJPEGImage.Create;
jpg.ProgressiveEncoding := ProgressiveJPG;
jpg.CompressionQuality := JPGQualityPercent;
bmp := AsBitmap;
try
jpg.Assign(bmp);
finally
bmp.Free;
end;
Result := jpg;
LastResult := arOk;
end;
function TImageFXGR32.AsGIF : TGifImage;
var
gif : TGIFImage;
bmp : TBitmap;
begin
LastResult := arConversionError;
gif := TGIFImage.Create;
bmp := AsBitmap;
try
gif.Assign(bmp);
finally
bmp.Free;
end;
Result := gif;
LastResult := arOk;
end;
function TImageFXGR32.AsString(imgFormat : TImageFormat = ifJPG) : string;
var
ss : TStringStream;
begin
LastResult := arConversionError;
ss := TStringStream.Create;
try
case imgFormat of
ifBMP : fBitmap.SaveToStream(ss);
ifJPG : Self.AsJPG.SaveToStream(ss);
ifPNG : Self.AsPNG.SaveToStream(ss);
ifGIF : Self.AsGIF.SaveToStream(ss);
else raise Exception.Create('Format unknow!');
end;
Result := Base64Encode(ss.DataString);
LastResult := arOk;
finally
ss.Free;
end;
end;
function TImageFXGR32.GetPixel(const x, y: Integer): TPixelInfo;
begin
Result := GetPixelImage(x,y,fBitmap);
end;
function TImageFXGR32.Rounded(RoundLevel : Integer = 27) : IImageFX;
var
rgn : HRGN;
auxbmp : TBitmap;
begin
Result := Self;
auxbmp := TBitmap.Create;
try
auxbmp.Assign(fBitmap);
fBitmap.Clear($00FFFFFF);
with fBitmap.Canvas do
begin
Brush.Style:=bsClear;
//Brush.Color:=clTransp;
Brush.Color:=clNone;
FillRect(Rect(0,0,auxbmp.Width,auxbmp.Height));
rgn := CreateRoundRectRgn(0,0,auxbmp.width + 1,auxbmp.height + 1,RoundLevel,RoundLevel);
SelectClipRgn(Handle,rgn);
Draw(0,0,auxbmp);
DeleteObject(Rgn);
end;
//bmp32.Assign(auxbmp);
finally
FreeAndNil(auxbmp);
end;
end;
function TImageFXGR32.AntiAliasing : IImageFX;
var
bmp : TBitmap;
begin
Result := Self;
bmp := TBitmap.Create;
try
//DoAntialias(fBitmap,bmp);
fBitmap.Assign(bmp);
finally
bmp.Free;
end;
end;
function TImageFXGR32.SetAlpha(Alpha : Byte) : IImageFX;
begin
Result := Self;
//DoAlpha(fBitmap,Alpha);
end;
procedure TImageFXGR32.SetPixel(const x, y: Integer; const P: TPixelInfo);
begin
SetPixelImage(x,y,P,fBitmap);
end;
procedure TImageFXGR32.SetPixelImage(const x, y: Integer; const P: TPixelInfo; bmp32 : TBitmap32);
begin
bmp32.Pixel[x,y] := RGB(P.R,P.G,P.B);
end;
function TImageFXGR32.GetPixelImage(const x, y: Integer; bmp32 : TBitmap32) : TPixelInfo;
var
lRGB : TRGB;
begin
lRGB := ColorToRGBValues(bmp32.Pixel[x,y]);
Result.R := lRGB.R;
Result.G := lRGB.G;
Result.B := lRGB.B;
end;
function TImageFXGR32.GetResolution: string;
begin
end;
end.
|
unit fAlertForward;
interface
uses Windows, Messages, SysUtils, Classes, Graphics, Forms, Controls,
Dialogs, StdCtrls, Buttons, ORCtrls, ORfn, ExtCtrls, fAutoSz, ComCtrls, fBase508Form,
VA508AccessibilityManager;
type
TfrmAlertForward = class(TfrmBase508Form)
cmdOK: TButton;
cmdCancel: TButton;
cboSrcList: TORComboBox;
DstList: TORListBox;
SrcLabel: TLabel;
DstLabel: TLabel;
pnlBase: TORAutoPanel;
memAlert: TMemo;
Label1: TLabel;
memComment: TMemo;
btnAddAlert: TButton;
btnRemoveAlertFwrd: TButton;
btnRemoveAllAlertFwrd: TButton;
procedure btnRemoveAlertFwrdClick(Sender: TObject);
procedure btnAddAlertClick(Sender: TObject);
procedure cboSrcListNeedData(Sender: TObject; const StartFrom: String;
Direction, InsertAt: Integer);
procedure cmdOKClick(Sender: TObject);
procedure cmdCancelClick(Sender: TObject);
procedure cboSrcListKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure cboSrcListMouseClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure cboSrcListChange(Sender: TObject);
procedure DstListChange(Sender: TObject);
procedure btnRemoveAllAlertFwrdClick(Sender: TObject);
private
RemovingAll: boolean;
end;
function ForwardAlertTo(Alert: String): Boolean;
implementation
{$R *.DFM}
uses rCore, uCore, VA508AccessibilityRouter, VAUtils;
const
TX_DUP_RECIP = 'You have already selected that recipient.';
TX_RECIP_CAP = 'Error adding recipient';
var XQAID: string;
function ForwardAlertTo(Alert: String): Boolean;
var
frmAlertForward: TfrmAlertForward;
begin
frmAlertForward := TfrmAlertForward.Create(Application);
try
ResizeAnchoredFormToFont(frmAlertForward);
with frmAlertForward do
begin
memAlert.SetTextBuf(PChar(Piece(Alert, U, 2)));
XQAID := Piece(Alert, U, 1);
ShowModal;
end;
finally
frmAlertForward.Release;
Result := True;
end;
end;
procedure TfrmAlertForward.FormCreate(Sender: TObject);
begin
inherited;
if ScreenReaderSystemActive then
memAlert.TabStop := TRUE;
cboSrcList.InitLongList('');
end;
procedure TfrmAlertForward.cboSrcListNeedData(Sender: TObject;
const StartFrom: String; Direction, InsertAt: Integer);
begin
(Sender as TORComboBox).ForDataUse(SubSetOfPersons(StartFrom, Direction));
end;
procedure TfrmAlertForward.cmdCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfrmAlertForward.cmdOKClick(Sender: TObject);
var
i: integer ;
Recip: string;
begin
for i := 0 to DstList.Items.Count-1 do
begin
Recip := Piece(DstList.Items[i], U, 1);
memComment.Text := StringReplace(memComment.Text, CRLF, ' ', [rfReplaceAll]);
ForwardAlert(XQAID, Recip, 'A', memComment.Text);
end;
Close;
end;
procedure TfrmAlertForward.DstListChange(Sender: TObject);
var
HasFocus: boolean;
begin
inherited;
if DstList.SelCount = 1 then
if Piece(DstList.Items[0], '^', 1) = '' then
begin
btnRemoveAlertFwrd.Enabled := false;
btnRemoveAllAlertFwrd.Enabled := false;
exit;
end;
HasFocus := btnRemoveAlertFwrd.Focused;
if Not HasFocus then
HasFocus := btnRemoveAllAlertFwrd.Focused;
btnRemoveAlertFwrd.Enabled := DstList.SelCount > 0;
btnRemoveAllAlertFwrd.Enabled := DstList.Items.Count > 0;
if HasFocus and (DstList.SelCount = 0) then
btnAddAlert.SetFocus;
end;
procedure TfrmAlertForward.btnAddAlertClick(Sender: TObject);
begin
inherited;
cboSrcListMouseClick(btnAddAlert);
end;
procedure TfrmAlertForward.btnRemoveAlertFwrdClick(Sender: TObject);
var
i: integer;
begin
with DstList do
begin
if ItemIndex = -1 then exit ;
for i := Items.Count-1 downto 0 do
if Selected[i] then
begin
if ScreenReaderSystemActive and (not RemovingAll) then
GetScreenReader.Speak(Piece(DstList.Items[i],U,2) +
' Removed from ' + DstLabel.Caption);
Items.Delete(i) ;
end;
end;
end;
procedure TfrmAlertForward.btnRemoveAllAlertFwrdClick(Sender: TObject);
begin
inherited;
DstList.SelectAll;
RemovingAll := TRUE;
try
btnRemoveAlertFwrdClick(self);
if ScreenReaderSystemActive then
GetScreenReader.Speak(DstLabel.Caption + ' Cleared');
finally
RemovingAll := FALSE;
end;
end;
procedure TfrmAlertForward.cboSrcListChange(Sender: TObject);
begin
inherited;
btnAddAlert.Enabled := CboSrcList.ItemIndex > -1;
end;
procedure TfrmAlertForward.cboSrcListKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
begin
cboSrcListMouseClick(Self);
end;
end;
procedure TfrmAlertForward.cboSrcListMouseClick(Sender: TObject);
begin
if cboSrcList.ItemIndex = -1 then exit;
if (DstList.SelectByID(cboSrcList.ItemID) <> -1) then
begin
InfoBox(TX_DUP_RECIP, TX_RECIP_CAP, MB_OK or MB_ICONWARNING);
Exit;
end;
DstList.Items.Add(cboSrcList.Items[cboSrcList.Itemindex]);
if ScreenReaderSystemActive then
GetScreenReader.Speak(Piece(cboSrcList.Items[cboSrcList.Itemindex],U,2) +
' Added to ' + DstLabel.Caption);
btnRemoveAlertFwrd.Enabled := DstList.SelCount > 0;
btnRemoveAllAlertFwrd.Enabled := DstList.Items.Count > 0;
end;
end.
|
unit uDCSumm;
interface
uses SysUtils, Classes, ORNet, ORFn, rCore, uCore, uConst;
type
TEditDCSummRec = record
Title: Integer;
DocType: integer;
Addend: integer;
EditIEN: integer;
AdmitDateTime: TFMDateTime;
DischargeDateTime: TFMDateTime;
TitleName: string;
DictDateTime: TFMDateTime;
Dictator: Int64;
DictatorName: string;
Cosigner: Int64;
CosignerName: string;
Transcriptionist: int64;
TranscriptionistName: string;
Attending: int64;
AttendingName: string;
Urgency: string;
UrgencyName: string;
Location: Integer;
LocationName: string;
VisitStr: string;
NeedCPT: Boolean;
Status: integer;
LastCosigner: Int64;
LastCosignerName: string;
IDParent: integer;
Lines: TStrings;
end;
TDCSummRec = TEditDCSummRec;
TAdmitRec = record
AdmitDateTime: TFMDateTime;
Location: integer;
LocationName: string;
VisitStr: string;
end;
TDCSummTitles = class
public
DfltTitle: Integer;
DfltTitleName: string;
ShortList: TStringList;
constructor Create;
destructor Destroy; override;
end;
TDCSummPrefs = class
public
DfltLoc: Integer;
DfltLocName: string;
SortAscending: Boolean;
AskCosigner: Boolean;
DfltCosigner: Int64;
DfltCosignerName: string;
MaxSumms: Integer;
end;
function MakeDCSummDisplayText(RawText: string): string;
implementation
function MakeDCSummDisplayText(RawText: string): string;
var
x: string;
begin
x := RawText;
if Copy(Piece(x, U, 9), 1, 4) = ' ' then SetPiece(x, U, 9, 'Dis: ');
if CharInSet(Piece(x, U, 1)[1], ['A', 'N', 'E']) then
Result := Piece(x, U, 2)
else
Result := FormatFMDateTime('mmm dd,yy', MakeFMDateTime(Piece(x, U, 3))) + ' ' +
Piece(x, U, 2) + ', ' + Piece(x, U, 6) + ', ' + Piece(Piece(x, U, 5), ';', 2) +
' (' + Piece(x,U,7) + '), ' + Piece(Piece(x, U, 8), ';', 1) + ', ' +
Piece(Piece(x, U, 9), ';', 1);
end;
{ Discharge Summary Titles -------------------------------------------------------------------- }
constructor TDCSummTitles.Create;
{ creates an object to store Discharge Summary titles so only obtained from server once }
begin
inherited Create;
ShortList := TStringList.Create;
end;
destructor TDCSummTitles.Destroy;
{ frees the lists that were used to store the Discharge Summary titles }
begin
ShortList.Free;
inherited Destroy;
end;
end.
|
unit Common.Utils;
interface
uses
System.Classes, System.SysUtils, Vcl.Forms, Winapi.Windows, Vcl.Controls,
System.Generics.Collections, Winapi.ShellAPI, Winapi.ActiveX;
const
// cGDriveKey = 'Bearer ya29.GlsUBKDsCD6SbtcN8J9JTdMszZLjLrsHxQmnzZ6GWPXXP00ky7t5fDLEFmFO7yEnKZpe9dZsK801VBxTPNy4FAaigvRo-h3sim9EMCV5XU4A6aANYPEwfQNoIrGY';
cGDriveKey = 'Bearer ya29.GlsUBAgw23z37pHrliQjH2ro0s59haDvLW42E0qjQ6sfh_eMPb2hzkiOOrlbamiBv6EFPmhG-j4QREM6SRzCZElLUdh61NlHPZKo6-bO-11_Oi0LbbBE3XEEaWj-';
type
TFileRecord = record
FileName: string;
FilePath: string;
end;
TFileRecordList = TList<TFileRecord>;
TEditMode = (emAppend, emEdit);
procedure FindAllFiles(FilesList: TFileRecordList; StartDir: string; const FileMasks: array of string);
procedure ShowError(AMsg: string);
procedure ShowErrorFmt(AMsg: string; Params: array of const);
function ShowConfirm(AMsg: string): Boolean;
function ShowConfirmFmt(AMsg: string; Params: array of const): Boolean;
procedure ShowInfo(AMsg: string);
procedure ShowInfoFmt(AMsg: string; Params: array of const);
procedure ShellExecute(const AWnd: HWND; const AOperation, AFileName: String;
const AParameters: String = ''; const ADirectory: String = '';
const AShowCmd: Integer = SW_SHOWNORMAL);
implementation
uses
System.StrUtils;
procedure ShellExecute(const AWnd: HWND; const AOperation, AFileName: String;
const AParameters: String = ''; const ADirectory: String = '';
const AShowCmd: Integer = SW_SHOWNORMAL);
var
ExecInfo: TShellExecuteInfo;
NeedUnitialize: Boolean;
begin
Assert(AFileName <> '');
NeedUnitialize := Succeeded(CoInitializeEx(nil, COINIT_APARTMENTTHREADED or COINIT_DISABLE_OLE1DDE));
try
FillChar(ExecInfo, SizeOf(ExecInfo), 0);
ExecInfo.cbSize := SizeOf(ExecInfo);
ExecInfo.Wnd := AWnd;
ExecInfo.lpVerb := Pointer(AOperation);
ExecInfo.lpFile := PChar(AFileName);
ExecInfo.lpParameters := Pointer(AParameters);
ExecInfo.lpDirectory := Pointer(ADirectory);
ExecInfo.nShow := AShowCmd;
ExecInfo.fMask := SEE_MASK_NOASYNC { = SEE_MASK_FLAG_DDEWAIT для старых версий Delphi }
or SEE_MASK_FLAG_NO_UI;
{$IFDEF UNICODE}
// Необязательно, см. http://www.transl-gunsmoker.ru/2015/01/what-does-SEEMASKUNICODE-flag-in-ShellExecuteEx-actually-do.html
ExecInfo.fMask := ExecInfo.fMask or SEE_MASK_UNICODE;
{$ENDIF}
{$WARN SYMBOL_PLATFORM OFF}
Win32Check(ShellExecuteEx(@ExecInfo));
{$WARN SYMBOL_PLATFORM ON}
finally
if NeedUnitialize then
CoUninitialize;
end;
end;
procedure FindAllFiles(FilesList: TFileRecordList; StartDir: string; const FileMasks: array of string);
var
SR: TSearchRec;
DirList: TStringList;
IsFound: Boolean;
i: integer;
FR: TFileRecord;
FileMask, FileExt: string;
begin
if (StartDir[Length(StartDir)] <> '\') then
StartDir := StartDir + '\';
// Формирование списка файлов (не каталогов!!!) по маске
FileMask := '*.*';
IsFound := FindFirst(StartDir + FileMask, faAnyFile - faDirectory, SR) = 0;
while IsFound do begin
FR.FileName := SR.Name;
FR.FilePath := StartDir + SR.Name;
// проверка по маске
FileExt := ExtractFileExt(SR.Name);
if FileExt > '' then
FileExt := Copy(FileExt, 2, Length(FileExt) - 1);
if MatchText(FileExt, FileMasks) then
FilesList.Add( FR );
IsFound := FindNext(SR) = 0;
end;
System.SysUtils.FindClose(SR);
// Формирование списка подкаталогов
DirList := TStringList.Create;
IsFound := FindFirst(StartDir + '*.*', faAnyFile, SR) = 0;
while IsFound do begin
if ((SR.Attr = faDirectory)) and (SR.Name[ 1 ] <> '.') then
DirList.Add( SR.Name );
IsFound := FindNext(SR) = 0;
end;
System.SysUtils.FindClose(SR);
// Рекурсивное сканирование подкаталогов
for i := 0 to Pred(DirList.Count) do
FindAllFiles( FilesList, StartDir + DirList[i], FileMasks );
DirList.Free;
end;
procedure ShowError(AMsg: string);
begin
Application.MessageBox(PChar(AMsg), 'Ошибка', MB_OK + MB_ICONSTOP);
end;
procedure ShowErrorFmt(AMsg: string; Params: array of const);
begin
Application.MessageBox(PChar(Format(AMsg, Params)), 'Ошибка', MB_OK + MB_ICONSTOP);
end;
function ShowConfirm(AMsg: string): Boolean;
begin
Result := Application.MessageBox(PChar(AMsg), 'Подтверждение', MB_OKCANCEL + MB_ICONQUESTION) = mrOK;
end;
function ShowConfirmFmt(AMsg: string; Params: array of const): Boolean;
begin
Result := Application.MessageBox(PChar(Format(AMsg, Params)), 'Подтверждение', MB_OKCANCEL + MB_ICONQUESTION) = mrOk;
end;
procedure ShowInfo(AMsg: string);
begin
Application.MessageBox(PChar(AMsg), 'Информация', MB_OK + MB_ICONINFORMATION);
end;
procedure ShowInfoFmt(AMsg: string; Params: array of const);
begin
Application.MessageBox(PChar(Format(AMsg, Params)), 'Информация', MB_OK + MB_ICONINFORMATION);
end;
end.
|
{ *******************************************************
Threading utilities for Delphi 2009 and above
Utilidad para programación concurrente.
*******************************************************
2012 Ángel Fernández Pineda. Madrid. Spain.
This work is licensed under the Creative Commons
Attribution-ShareAlike 3.0 Unported License. To
view a copy of this license,
visit http://creativecommons.org/licenses/by-sa/3.0/
or send a letter to Creative Commons,
444 Castro Street, Suite 900,
Mountain View, California, 94041, USA.
******************************************************* }
unit ThreadUtils;
{
SUMMARY:
- TCustomThread<ArgType>: simplify the writing of thread code,
avoiding the need to derive a new class.
- TThreadKillerHelper: introduces Kill(Timeout,ExitCode) to TThread.
- TParallel: run code in a thread pool (current implementation
uses "old" Windows pool API)
}
interface
uses
Classes, SysUtils, System.SyncObjs;
{ TCustomThread<ArgType>
PURPOUSE:
To simplify the writing of thread code, avoiding the need to derive a new
class. Thread code is written as an event handler or as a reference to
procedure. Custom data of ArgType will be passed at thread initialization.
GENERAL USAGE:
- Write an event handler (TNotifyEvent) or a reference to procedure.
- Create a TCustomThread instance. Custom data may be passed to the newly
created thread, which may be accessed later thanks to the CustomData
property.
- Use it as any other TThread instance.
THREAD PROPERTIES:
Protected TThread properties and methods are made public so you can check
for thread termination or call the synchronize method.
EVENT HANDLER, example:
The argument to TNotifyEvent should be typecasted to TCustomThread<ArgType>.
procedure TMyClass.ThreadBody(Sender: TObject);
begin
with Sender as TCustomThread<integer> do
while (not Terminated) do
begin
...
procedure TMyClass.Other;
begin
thread := TCustomThread<integer>.Create(true,1,ThreadBody);
...
REFERENCE TO PROCEDURE, example:
thread := TCustomThread<integer>.Create(
true,1,
procedure(instance: TCustomThread<integer>)
begin
with instance do
while (not terminated) do
begin
...
end)
...
}
type
TCustomThread<ArgType> = class(TThread)
private
FOnExecute1: TNotifyEvent;
FOnExecute2: TProc<TCustomThread<ArgType>>;
FCustomData: ArgType;
protected
procedure Execute; override;
public
constructor Create(CreateSuspended: boolean; InitialData: ArgType;
OnExecute: TNotifyEvent); overload;
constructor Create(CreateSuspended: boolean; InitialData: ArgType;
OnExecute: TProc < TCustomThread < ArgType >> ); overload;
procedure Synchronize(AMethod: TThreadMethod); overload;
procedure Synchronize(AThreadProc: TThreadProcedure); overload;
property CustomData: ArgType read FCustomData;
property Terminated;
end;
TCustomThread = TCustomThread<TObject>;
{
TThreadKillerHelper
PURPOUSE:
Introduces a new method to TThread class:
Kill(Timeout,ExitCode) will signal the thread to terminate,
then it will wait for Timeout (milliseconds).
After that, if the thread has not been terminated, it will force its
destruction using an operating system primitive.
Note: usage of Kill may lead to resources not been
properly deallocated.
}
type
TThreadKillerHelper = class helper for TThread
public
procedure Kill(Timeout: cardinal = 0; ExitCode: cardinal = 9999);
end;
{
TParallel
PURPOUSE:
Run some code in a thread pool. There is no need to manage threads.
USAGE:
- Call Run to execute some code in another thread.
- Call ActiveWaitFor to wait termination of parallel code (at Run/RunFor).
The calling thread will not freeze, so you must provide some code to run
while waiting.
- Check WorkCount to know if code is already running.
EXAMPLE:
Tparallel.Run(Procedure1);
Tparallel.Run(Instace.Procedure2);
Tparallel.Run(procedure begin ... end);
...
Tparallel.ActiveWaitFor(Application.ProcessMessages);
INDEXED LOOPS:
Use TParallelFor or TParallel<integer> to parallelize loop iterations
For example:
for i := 0 to count-1 do
TParallelFor.Run(
procedure (index: integer)
begin
// Do something with index
// DO NOT use "i" as index
end);
NOTES:
- There is no sense in creating TParallel instances.
- There is a sperate workcount for each TParallel<T> instance.
Do not call TParallel.ActiveWaitFor instead of TParallel<T>.ActiveWaitFor
}
{$IFDEF MSWINDOWS}
type
TParallel = class
private
code: TProc;
private
class var FWorkCount: cardinal;
class function ProcFunc(Param: pointer): integer stdcall; static;
public
class constructor Create;
class procedure Run(const code: TProc; const mayRunLong: boolean = true);
class procedure ActiveWaitFor(const WaitCode: TProc;
const Interval: cardinal = 150);
class property WorkCount: cardinal read FWorkCount;
end;
type
TParallel<T> = class
private
code: TProc<T>;
data: T;
private
class var FWorkCount: cardinal;
class function ProcFunc(Param: pointer): integer stdcall; static;
class function GetFlags(const mayRunLong: boolean): cardinal;
public
class constructor Create;
class procedure Run(const arg: T; const code: TProc<T>;
const mayRunLong: boolean = true);
class procedure ActiveWaitFor(const WaitCode: TProc;
const Interval: cardinal = 150);
class property WorkCount: cardinal read FWorkCount;
end;
TParallelFor = TParallel<integer>;
{$ENDIF}
// -----------------------------------------------------------------------------
implementation
{$IFDEF MSWINDOWS}
uses
Windows;
{$ENDIF}
// -----------------------------------------------------------------------------
// TCustomThread
// -----------------------------------------------------------------------------
constructor TCustomThread<ArgType>.Create(CreateSuspended: boolean;
InitialData: ArgType; OnExecute: TNotifyEvent);
begin
FOnExecute1 := OnExecute;
FOnExecute2 := nil;
FCustomData := InitialData;
inherited Create(CreateSuspended);
end;
// -----------------------------------------------------------------------------
constructor TCustomThread<ArgType>.Create(CreateSuspended: boolean;
InitialData: ArgType; OnExecute: TProc < TCustomThread < ArgType >> );
begin
FOnExecute1 := nil;
FOnExecute2 := OnExecute;
FCustomData := InitialData;
inherited Create(CreateSuspended);
end;
// -----------------------------------------------------------------------------
procedure TCustomThread<ArgType>.Execute;
begin
if (Assigned(FOnExecute1)) then
FOnExecute1(self)
else if (Assigned(FOnExecute2)) then
FOnExecute2(self);
end;
// -----------------------------------------------------------------------------
procedure TCustomThread<ArgType>.Synchronize(AMethod: TThreadMethod);
begin
inherited Synchronize(AMethod);
end;
// -----------------------------------------------------------------------------
procedure TCustomThread<ArgType>.Synchronize(AThreadProc: TThreadProcedure);
begin
inherited Synchronize(AThreadProc);
end;
// -----------------------------------------------------------------------------
// TThreadKillerHelper
// -----------------------------------------------------------------------------
procedure TThreadKillerHelper.Kill(Timeout: cardinal; ExitCode: cardinal);
begin
Terminate;
sleep(Timeout);
if (not Terminated) then
TerminateThread(self.Handle, ExitCode);
end;
// -----------------------------------------------------------------------------
// TParallel
// -----------------------------------------------------------------------------
function GetFlags(const mayRunLong: boolean): cardinal;
begin
if (mayRunLong) then
Result := WT_EXECUTEDEFAULT or WT_EXECUTELONGFUNCTION
else
Result := WT_EXECUTEDEFAULT;
end;
// -----------------------------------------------------------------------------
class constructor TParallel.Create;
begin
TParallel.FWorkCount := 0;
end;
// -----------------------------------------------------------------------------
class function TParallel.ProcFunc(Param: pointer): integer stdcall;
var
Item: TParallel;
begin
Item := TParallel(Param);
Result := -1;
try
Item.code.Invoke;
finally
Item.Free;
dec(TParallel.FWorkCount);
end;
end;
// -----------------------------------------------------------------------------
class procedure TParallel.Run(const code: TProc; const mayRunLong: boolean);
var
Item: TParallel;
begin
if not Assigned(code) then
Exit;
Item := TParallel.Create;
Item.code := code;
inc(TParallel.FWorkCount);
if (not QueueUserWorkItem(ProcFunc, pointer(Item), GetFlags(mayRunLong))) then
begin
dec(TParallel.FWorkCount);
Item.Free;
raise Exception.Create('Unable to queue work');
end;
end;
// -----------------------------------------------------------------------------
class procedure TParallel.ActiveWaitFor(const WaitCode: TProc;
const Interval: cardinal);
begin
while (TParallel.FWorkCount > 0) do
begin
sleep(Interval);
if (Assigned(WaitCode)) then
WaitCode;
end;
end;
{$IFDEF MSWINDOWS}
// -----------------------------------------------------------------------------
// TParallel<T>
// -----------------------------------------------------------------------------
class constructor TParallel<T>.Create;
begin
TParallel<T>.FWorkCount := 0;
end;
// -----------------------------------------------------------------------------
class function TParallel<T>.GetFlags(const mayRunLong: boolean): cardinal;
begin
if (mayRunLong) then
Result := WT_EXECUTEDEFAULT or WT_EXECUTELONGFUNCTION
else
Result := WT_EXECUTEDEFAULT;
end;
// -----------------------------------------------------------------------------
class function TParallel<T>.ProcFunc(Param: pointer): integer stdcall;
var
Item: TParallel<T>;
begin
Item := TParallel<T>(Param);
Result := -1;
try
Item.code(Item.data);
finally
Item.Free;
dec(TParallel<T>.FWorkCount);
end;
end;
// -----------------------------------------------------------------------------
class procedure TParallel<T>.Run(const arg: T; const code: TProc<T>;
const mayRunLong: boolean = true);
var
Item: TParallel<T>;
begin
if not Assigned(code) then
Exit;
Item := TParallel<T>.Create;
Item.code := code;
Item.data := arg;
inc(TParallel<T>.FWorkCount);
if (not QueueUserWorkItem(ProcFunc, pointer(Item), GetFlags(mayRunLong))) then
begin
dec(TParallel<T>.FWorkCount);
Item.Free;
raise Exception.Create('Unable to queue work');
end;
end;
// -----------------------------------------------------------------------------
class procedure TParallel<T>.ActiveWaitFor(const WaitCode: TProc;
const Interval: cardinal);
begin
while (TParallel<T>.FWorkCount > 0) do
begin
sleep(Interval);
if (Assigned(WaitCode)) then
WaitCode;
end;
end;
// -----------------------------------------------------------------------------
{$ENDIF}
end.
|
{***************************************************************
*
* Project : MapsDemo
* Unit Name: mapsMain
* Purpose : Demonstrates checking domain against "Mail Abuse Prevention System"
* Version : 1.0
* Date : Wed 25 Apr 2001 - 01:29:36
* Author : <unknown>
* History :
* Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com>
*
****************************************************************}
(*
MAPS - Mail Abuse Prevention System http://mail-abuse.org/
RBL - Realtime Blackhole List
DUL - Dial-up User List
RSS - Relay Spam Stopper
ORBS - Open Relay Behaviour-modification System http://www.orbs.org/
Here are some site that you can test with - they are known spammers
209.132.59.86
209.211.253.248
160.79.241.223 ; internetsales.net (UU.NET/9netave.com)
198.30.222.8 ; intouch2001.com (OAR.NET/oar.net)
199.93.70.41 ; yug.com (BBNPLANET.COM/burlee.com)
200.38.11.82 ; bulk-email-company.com (TELNOR.COM/telnor.com)
200.49.75.17 ; bulklist.com (METRORED.COM.AR/metrored.com.ar)
204.213.85.162 ; webmole.com (SPRINTLINK.NET/oltronics.net)
204.83.230.164 ; apex-pi.com (SPRINTLINK.NET/sasktel.sk.ca)
205.147.234.77 ; bizzmaker.com (FAST.NET/fast.net)
205.238.206.132 ; realcybersex.com (EPIX.NET/datamg.com)
206.67.55.130 ; internetmarketers.net (UU.NET/media3.net)
206.67.58.127 ; emailtools.net (UU.NET/media3.net)
206.67.63.41 ; emailtools.com (UU.NET/media3.net)
207.180.29.196 ; kingcard.com (ICI.NET/ici.net)
207.198.74.82 ; bulkemail.cc (NETLIMITED.NET/netservers.net)
207.213.224.154 ; archmarketing.com (PBI.NET/ahnet.net)
207.23.186.230 ; market-2-sales.com (BC.NET/junction.net)
207.87.193.201 ; bulk-email-mailer.com (QWEST.NET/conninc.com)
208.135.196.4 ; outboundusa.com (CW.NET/cw.net)
208.161.191.177 ; americaint.com (CW.NET/y2kisp.com)
208.171.120.18 ; emailemailemail.com (CW.NET/digihost.com)
208.171.120.87 ; moneyfun.com (CW.NET/digihost.com)
208.178.185.81 ; ezonetrade.com (GBLX.NET/directnic.com)
208.221.168.112 ; rlyeh.com (UU.NET/dynatek.net)
208.234.13.9 ; w3-lightspeed.com (UU.NET/aitcom.net)
208.234.15.37 ; webmasterszone.net (UU.NET/aitcom.net)
208.234.16.236 ; websitesint.com/ (UU.NET/aitcom.net)
208.234.29.141 ; 4uservers.com (UU.NET/aitcom.net)
208.234.4.123 ; cyberlink1.com (UU.NET/aitcom.net)
*)
unit mapsMain;
interface
uses
{$IFDEF Linux}
QGraphics, QControls, QForms, QDialogs, QStdCtrls,
{$ELSE}
windows, messages, graphics, controls, forms, dialogs, stdctrls,
{$ENDIF}
SysUtils, Classes, IdBaseComponent, IdComponent, IdUDPBase, IdUDPClient,
IdDNSResolver;
type
TForm1 = class(TForm)
btnCheckIP: TButton;
cboList: TComboBox;
IdDNSResolver1: TIdDNSResolver;
Label1: TLabel;
Memo1: TMemo;
Memo2: TMemo;
txtDNSServer: TEdit;
Label2: TLabel;
Label3: TLabel;
procedure btnCheckIPClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FillCombo;
private
{ Private declarations }
procedure Check_ORBS;
procedure Check_RSS;
procedure Check_DUL;
procedure Check_RBL;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF}
uses IdGlobal;
const
// stMAPS_DNS = 'smtp.wvnet.edu';
// stMAPS_DNS = 'blackholes.mail-abuse.org';
stRBL = '.rbl.maps.vix.com';
stDUL = '.dul.maps.vix.com';
stRSS = '.relays.mail-abuse.org';
stORBS = '.relays.orbs.org';
function ReverseIPAddress(IPAddress: string): string;
var Part1, Part2, Part3, Part4: string;
begin
Part1 := Fetch(IPAddress, '.');
Part2 := Fetch(IPAddress, '.');
Part3 := Fetch(IPAddress, '.');
Part4 := Fetch(IPAddress);
Result := Part4 + '.' + Part3 + '.' + Part2 + '.' + Part1;
end;
procedure TForm1.Check_RBL;
var idx: Integer;
begin
IdDNSResolver1.RequestedRecords := [cA];
try
{MAPS RBL - Real Time Blackhole list}
IdDNSResolver1.ResolveDomain(ReverseIPAddress(cboList.Text) + stRBL);
for idx := 0 to Pred(IdDNSResolver1.Answers.Count) do
begin
try
if IdDNSResolver1.DNSAnList[idx].AType = cA then
begin
// Memo1.Lines.Add(IdDNSResolver1.DNSAnList[idx].RData.DomainName + ' is in the MAPS RBL');
Memo1.Lines.Add(cboList.Text + ' is in the MAPS RBL');
end;
except
end;
end;
{Now get a helpful bounce message}
IdDNSResolver1.RequestedRecords := [cTXT];
try
IdDNSResolver1.ResolveDomain(ReverseIPAddress(cboList.Text) + stRBL {'.rbl.maps.vix.com'});
for idx := 0 to Pred(IdDNSResolver1.DNSAnList.Count) do
begin
try
if IdDNSResolver1.DNSAnList[idx].AType = cTXT then
begin
Memo1.Lines.Add('Bounce Message: ' + IdDNSResolver1.DNSAnList[idx].StarData);
end;
except
end;
end;
finally
end;
except
Memo1.Lines.Add('Not in MAPS RBL');
end;
end;
procedure TForm1.Check_DUL;
var idx: Integer;
begin
IdDNSResolver1.RequestedRecords := [cA];
try
{MAPS DUL - Dial-Up User List}
IdDNSResolver1.ResolveDomain(ReverseIPAddress(cboList.Text) + stDUL);
for idx := 0 to Pred(IdDNSResolver1.Answers.Count) do
begin
try
if IdDNSResolver1.DNSAnList[idx].AType = cA then
begin
// Memo1.Lines.Add(IdDNSResolver1.DNSAnList[idx].RData.DomainName + ' is in the MAPS DUL');
Memo1.Lines.Add(cboList.Text + ' is in the MAPS DUL');
end;
except
end;
end;
{Now get a helpful bounce message}
IdDNSResolver1.RequestedRecords := [cTXT];
try
IdDNSResolver1.ResolveDomain(ReverseIPAddress(cboList.Text) + stDUL);
for idx := 0 to Pred(IdDNSResolver1.Answers.Count) do
begin
try
if IdDNSResolver1.DNSAnList[idx].AType = cTXT then
begin
Memo1.Lines.Add('Bounce Message: ' + IdDNSResolver1.DNSAnList[idx].StarData);
end;
except
end;
end;
finally
end;
except
Memo1.Lines.Add('Not in MAPS DUL');
end;
end;
procedure TForm1.Check_RSS;
var idx: Integer;
begin
IdDNSResolver1.RequestedRecords := [cA];
try
{MAPS RSS - Relay Spam Stopper}
IdDNSResolver1.ResolveDomain(cboList.Text + stRSS);
for idx := 0 to Pred(IdDNSResolver1.Answers.Count) do
begin
try
if IdDNSResolver1.DNSAnList[idx].AType = cA then
begin
// Memo1.Lines.Add(IdDNSResolver1.DNSAnList[idx].RData.DomainName + ' is in the MAPS RRS');
Memo1.Lines.Add(cboList.Text + ' is in the MAPS RRS');
end;
except
end;
end;
IdDNSResolver1.RequestedRecords := [cTXT];
try
IdDNSResolver1.ResolveDomain(cboList.Text + stRSS);
for idx := 0 to Pred(IdDNSResolver1.Answers.Count) do
begin
try
if IdDNSResolver1.DNSAnList[idx].AType = cTXT then
begin
// Memo1.Lines.Add(IdDNSResolver1.DNSAnList[idx].StarData + ' is in the MAPS RBL');
Memo1.Lines.Add(cboList.Text + ' is in the MAPS RBL');
end;
except
end;
end;
finally
end;
except
Memo1.Lines.Add('Not in MAPS RSS');
end;
end;
procedure TForm1.Check_ORBS;
var idx: Integer;
begin
IdDNSResolver1.RequestedRecords := [cA];
try
{ORBS http://www.orbs.org}
IdDNSResolver1.ResolveDomain(ReverseIPAddress(cboList.Text) + stORBS);
for idx := 0 to Pred(IdDNSResolver1.Answers.Count) do
begin
try
if IdDNSResolver1.DNSAnList[idx].AType = cA then
begin
Memo1.Lines.Add(cboList.Text + ' is in ORBS');
end;
except
end;
end;
except
Memo1.Lines.Add('Not in ORBS');
end;
end;
procedure TForm1.btnCheckIPClick(Sender: TObject);
begin
Memo1.Clear;
if (cboList.Text = '') then exit;
application.processmessages;
IdDNSResolver1.ClearVars;
IdDNSResolver1.Host := txtDNSServer.text;
Memo1.Lines.Add('Checking ' + cboList.Text);
Check_RBL;
Check_DUL;
Check_RSS;
Check_ORBS;
Memo1.Lines.Add('------- finished -------');
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FillCombo;
end;
procedure TForm1.FillCombo;
begin
with cboList do
begin
clear;
items.add('127.0.0.2'); //test RBL, ORBS
items.add('127.0.0.3'); //test DUL
items.add('209.132.59.86'); //RBL
items.add('209.211.253.248'); //RBL ORBS
items.add('160.79.241.223'); //RBL
items.add('198.30.222.8'); //in nothing
items.add('205.147.234.77'); //ORBS
items.add('206.67.55.130'); //RBL
items.add('206.67.58.127'); //RBL
text := '127.0.0.2';
end;
end;
end.
|
unit TQuotes_U;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;
type
TQuotes = class
private
{ Private declarations }
clientName : string ;
totalCost : real ;
public
{ Public declarations }
Constructor Create (pClientName : string ; pTotalCost : real );
Function GetClientName : string ;
Function GetTotalCost : real ;
end;
implementation
{ TQuotes }
constructor TQuotes.Create(pClientName: string; pTotalCost: real);
begin
clientName := pClientName ;
totalCost := pTotalCost ;
end;
function TQuotes.GetClientName: string;
begin
Result := clientName ;
end;
function TQuotes.GetTotalCost: real;
begin
Result := totalCost ;
end;
end.
|
{DLL 封装的窗体专用,不同于主程序}
unit ZsbDLL2;
interface
uses Forms,Windows,Graphics;
function Get16MD5ForString(str: WideString): WideString; stdcall; external 'MD5FromDelphi.dll';
function GetVersionString(FileName: WideString): WideString; stdcall; external 'GetVersion.dll';
function GetStringFromIni(FromFile,Section, Ident:WideString): WideString;stdcall; external 'OperIniFile.dll';
function SetStringToIni(ToFile,Section,Ident,strValue:WideString): Boolean;stdcall; external 'OperIniFile.dll';
function SimpleMSNPopUpShow(strText: string;iStartX,iStartY:SmallInt): Boolean; stdcall;external 'MSNPopUpHelper.dll';
function SimpleMSNPopUpShowMoreVar(strText: string;iStartX,iStartY,iWidth,iHeight,iShowTime:SmallInt;cColor1:TColor;cColor2:TColor): Boolean; stdcall;external 'MSNPopUpHelper.dll';
function MSNPopUpShow(strText: string; strTitle: string = '提示信息'; iShowTime: SmallInt = 10;
iHeight: SmallInt = 100; iWidth: SmallInt = 200): Boolean;stdcall;external 'MSNPopUpHelper.dll';
procedure ShowInfoTips(h: HWND; strShowMess: string; IconType: Integer = 1; strShowCaption: string = '提示信息'; bAutoClose: Boolean = True; iShowTime: Integer = 2000); stdcall; external 'InfoTips.dll';
//NoApp DLL窗体用 有App的主程序用
procedure ZsbMsgBoxInfoNoApp(ParentForm: TForm;stsShow:string); stdcall;external 'ZsbMessageBox.dll';
procedure ZsbMsgBoxInfo(var App: TApplication;ParentForm: TForm;stsShow:string); stdcall;external 'ZsbMessageBox.dll';
procedure ZsbMsgErrorInfo(var App: TApplication; ParentForm: TForm; stsShow: string); stdcall; external 'ZsbMessageBox.dll';
procedure ZsbMsgErrorInfoNoApp(ParentForm: TForm; stsShow: string); stdcall; external 'ZsbMessageBox.dll';
function ZsbMsgBoxOkNoApp(ParentForm: TForm; stsShow: string): Boolean; stdcall; external 'ZsbMessageBox.dll';
function ZsbMsgBoxOk(var App: TApplication; ParentForm: TForm; stsShow: string): Boolean; stdcall; external 'ZsbMessageBox.dll';
function CreateQRDCodeBMP_PChar(PCharSaveFileName: PChar;PCharCode: PChar): Boolean; stdcall;external 'QRCodeDLLFromDelphi.dll';
procedure ZsbShowMessageNoApp(ParentForm: TForm; stsShow: string); stdcall; external 'ZsbShowMessage.dll';
implementation
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Datasnap.DSCommonTable;
interface
uses
Data.DBXCommonTable;
type
/// <summary>
/// Collection of server classes.
/// </summary>
TDSClassEntity = class(TDBXTableEntity)
public
constructor Create(const Table: TDBXTable; const OwnTable: Boolean); overload;
constructor Create(const OwnTable: Boolean); overload;
protected
function GetPackageName: UnicodeString;
procedure SetPackageName(const PackageName: UnicodeString);
function GetServerClassName: UnicodeString;
procedure SetServerClassName(const ClassName: UnicodeString);
function GetRoleName: UnicodeString;
procedure SetRoleName(const RoleName: UnicodeString);
function GetLifeCycle: UnicodeString;
procedure SetLifeCycle(const LifeCycle: UnicodeString);
private
class function CreateClassTable: TDBXTable; static;
public
property PackageName: UnicodeString read GetPackageName write SetPackageName;
property ServerClassName: UnicodeString read GetServerClassName write SetServerClassName;
property RoleName: UnicodeString read GetRoleName write SetRoleName;
property LifeCycle: UnicodeString read GetLifeCycle write SetLifeCycle;
end;
/// <summary>
/// Collection containing information on available connections
/// </summary>
/// <remarks>
/// </remarks>
TDSConnectionEntity = class(TDBXTableEntity)
public
constructor Create(const Table: TDBXTable; const OwnTable: Boolean); overload;
constructor Create(const OwnTable: Boolean); overload;
protected
function GetConnectionName: UnicodeString;
procedure SetConnectionName(const ConnectionName: UnicodeString);
function GetConnectionProperties: UnicodeString;
procedure SetConnectionProperties(const ConnectionProperties: UnicodeString);
function GetDriverName: UnicodeString;
procedure SetDriverName(const DriverName: UnicodeString);
function GetDriverProperties: UnicodeString;
procedure SetDriverProperties(const DriverProperties: UnicodeString);
private
class function CreateClassTable: TDBXTable; static;
public
property ConnectionName: UnicodeString read GetConnectionName write SetConnectionName;
property ConnectionProperties: UnicodeString read GetConnectionProperties write SetConnectionProperties;
property DriverName: UnicodeString read GetDriverName write SetDriverName;
property DriverProperties: UnicodeString read GetDriverProperties write SetDriverProperties;
end;
/// <summary> Collection containing information on methods.
/// </summary>
TDSMethodEntity = class(TDBXTableEntity)
public
constructor Create(const Table: TDBXTable; const OwnTable: Boolean); overload;
constructor Create(const OwnTable: Boolean); overload;
protected
function GetMethodAlias: UnicodeString;
procedure SetMethodAlias(const ClassName: UnicodeString);
function GetServerClassName: UnicodeString;
procedure SetServerClassName(const ClassName: UnicodeString);
function GetServerMethodName: UnicodeString;
procedure SetServerMethodName(const ClassName: UnicodeString);
function GetRoleName: UnicodeString;
procedure SetRoleName(const ClassName: UnicodeString);
private
class function CreateMethodTable: TDBXTable; static;
public
property MethodAlias: UnicodeString read GetMethodAlias write SetMethodAlias;
property ServerClassName: UnicodeString read GetServerClassName write SetServerClassName;
property ServerMethodName: UnicodeString read GetServerMethodName write SetServerMethodName;
property RoleName: UnicodeString read GetRoleName write SetRoleName;
end;
/// <summary>
/// Collection containing information on packages.
/// </summary>
TDSPackageEntity = class(TDBXTableEntity)
public
constructor Create(const Table: TDBXTable; const OwnTable: Boolean); overload;
constructor Create(const OwnTable: Boolean); overload;
protected
function GetPackageName: UnicodeString;
procedure SetPackageName(const PackageName: UnicodeString);
private
class function CreatePackageTable: TDBXTable; static;
public
property PackageName: UnicodeString read GetPackageName write SetPackageName;
end;
/// <summary>
/// This entity has the same fields as <see cref="TDBXProceduresColumns"/>
/// It is used to show Server methods in a table structure as the one
/// used by the dbExpress <see cref="TDBXMetaDataCommands.GetProcedures"/>
/// metadata command.<p>
/// When a <see cref="TDBXMetaDataCommands.GetProcedures"/> metadata command is
/// executed against a DataSnap server, the result will include all registered
/// server methods.</p>
/// </summary>
/// <remarks> It will also include any existing stored procedures
/// from the database connection specified by the <see cref="TDBXPropertyNames.ServerConnection"/>
/// if the <see cref="TDBXPropertyNames.ServerConnection"/> property was set in the connection
/// properties used to connect to the DataSnap server.
///
/// </remarks>
TDSProcedureEntity = class(TDBXTableEntity)
public
constructor Create(const Table: TDBXTable; const OwnTable: Boolean); overload;
constructor Create(const OwnTable: Boolean); overload;
protected
function GetCatalogName: UnicodeString;
procedure SetCatalogName(const CatalogName: UnicodeString);
function GetSchemaName: UnicodeString;
procedure SetSchemaName(const SchemaName: UnicodeString);
function GetProcedureName: UnicodeString;
procedure SetProcedureName(const ProcedureName: UnicodeString);
function GetProcedureType: UnicodeString;
procedure SetProcedureType(const ClassName: UnicodeString);
private
class function CreateProcedureTable: TDBXTable; static;
public
property CatalogName: UnicodeString read GetCatalogName write SetCatalogName;
property SchemaName: UnicodeString read GetSchemaName write SetSchemaName;
property ProcedureName: UnicodeString read GetProcedureName write SetProcedureName;
property ProcedureType: UnicodeString read GetProcedureType write SetProcedureType;
end;
/// <summary>
/// Collection containing information on procedure parameters.
/// </summary>
TDSProcedureParametersEntity = class(TDBXTableEntity)
public
constructor Create(const Table: TDBXTable; const OwnTable: Boolean); overload;
constructor Create(const OwnTable: Boolean); overload;
function IsNullable: Boolean;
function GetUnsigned: Boolean;
protected
function GetCatalogName: UnicodeString;
procedure SetCatalogName(const CatalogName: UnicodeString);
function GetSchemaName: UnicodeString;
procedure SetSchemaName(const SchemaName: UnicodeString);
function GetProcedureName: UnicodeString;
procedure SetProceduredName(const ProcedureName: UnicodeString);
function GetParameterName: UnicodeString;
procedure SetParameterName(const ParameterName: UnicodeString);
function GetParameterMode: UnicodeString;
procedure SetParameterMode(const ParameterMode: UnicodeString);
function GetTypeName: UnicodeString;
procedure SetTypeName(const TypeName: UnicodeString);
function GetPrecision: Integer;
procedure SetPrecision(const Precision: Integer);
function GetScale: Integer;
procedure SetScale(const Scale: Integer);
function GetOrdinal: Integer;
procedure SetOrdinal(const Ordinal: Integer);
procedure SetNullable(const Nullable: Boolean);
function GetDBXDataType: Integer;
procedure SetDBXDataType(const DataType: Integer);
function IsFixedLength: Boolean;
procedure SetFixedLength(const FixedLength: Boolean);
function IsUnicode: Boolean;
procedure SetUnicode(const IsUnicode: Boolean);
function IsLong: Boolean;
procedure SetLong(const IsLong: Boolean);
procedure SetUnsigned(const IsUnsigned: Boolean);
private
class function CreateProcedureParmetersTable: TDBXTable; static;
public
property CatalogName: UnicodeString read GetCatalogName write SetCatalogName;
property SchemaName: UnicodeString read GetSchemaName write SetSchemaName;
property ProcedureName: UnicodeString read GetProcedureName;
property ProceduredName: UnicodeString write SetProceduredName;
property ParameterName: UnicodeString read GetParameterName write SetParameterName;
property ParameterMode: UnicodeString read GetParameterMode write SetParameterMode;
property TypeName: UnicodeString read GetTypeName write SetTypeName;
property Precision: Integer read GetPrecision write SetPrecision;
property Scale: Integer read GetScale write SetScale;
property Ordinal: Integer read GetOrdinal write SetOrdinal;
property Nullable: Boolean write SetNullable;
property DBXDataType: Integer read GetDBXDataType write SetDBXDataType;
property FixedLength: Boolean read IsFixedLength write SetFixedLength;
property Unicode: Boolean read IsUnicode write SetUnicode;
property Long: Boolean read IsLong write SetLong;
property Unsigned: Boolean write SetUnsigned;
end;
implementation
uses
Data.DBXCommon,
Data.DBXMetaDataNames,
Data.DBXMetaDataReader,
Data.DBXTableFactory,
Datasnap.DSNames;
constructor TDSClassEntity.Create(const Table: TDBXTable; const OwnTable: Boolean);
begin
inherited Create(Table, OwnTable);
end;
constructor TDSClassEntity.Create(const OwnTable: Boolean);
begin
inherited Create(CreateClassTable, OwnTable);
end;
class function TDSClassEntity.CreateClassTable: TDBXTable;
var
Table: TDBXTable;
ReturnList: TDBXValueTypeArray;
DeployName: TDBXValueType;
ClassName: TDBXValueType;
RoleName: TDBXValueType;
LifeCycle: TDBXValueType;
begin
Table := TDBXTableFactory.CreateDBXTable;
Table.DBXTableName := 'ClassTable';
DeployName := TDBXValueType.Create;
DeployName.Name := TDSClassColumns.PackageName;
DeployName.DisplayName := TDSClassColumns.PackageName;
DeployName.DataType := TDBXDataTypes.WideStringType;
DeployName.Size := 256;
ClassName := TDBXValueType.Create;
ClassName.Name := TDSClassColumns.ServerClassName;
ClassName.DisplayName := TDSClassColumns.ServerClassName;
ClassName.DataType := TDBXDataTypes.WideStringType;
ClassName.Size := 256;
RoleName := TDBXValueType.Create;
RoleName.Name := TDSClassColumns.RoleName;
RoleName.DisplayName := TDSClassColumns.RoleName;
RoleName.DataType := TDBXDataTypes.WideStringType;
RoleName.Size := 256;
LifeCycle := TDBXValueType.Create;
LifeCycle.Name := TDSClassColumns.LifeCycle;
LifeCycle.DisplayName := TDSClassColumns.LifeCycle;
LifeCycle.DataType := TDBXDataTypes.WideStringType;
LifeCycle.Size := 256;
SetLength(ReturnList,4);
ReturnList[0] := DeployName;
ReturnList[1] := ClassName;
ReturnList[2] := RoleName;
ReturnList[3] := LifeCycle;
Table.Columns := ReturnList;
Result := Table;
end;
function TDSClassEntity.GetPackageName: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDSClassColumns.PackageName)].AsString;
end;
procedure TDSClassEntity.SetPackageName(const PackageName: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDSClassColumns.PackageName)].AsString := PackageName;
end;
function TDSClassEntity.GetServerClassName: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDSClassColumns.ServerClassName)].AsString;
end;
procedure TDSClassEntity.SetServerClassName(const ClassName: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDSClassColumns.ServerClassName)].AsString := ClassName;
end;
function TDSClassEntity.GetRoleName: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDSClassColumns.RoleName)].AsString;
end;
procedure TDSClassEntity.SetRoleName(const RoleName: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDSClassColumns.RoleName)].AsString := RoleName;
end;
function TDSClassEntity.GetLifeCycle: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDSClassColumns.LifeCycle)].AsString;
end;
procedure TDSClassEntity.SetLifeCycle(const LifeCycle: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDSClassColumns.LifeCycle)].AsString := LifeCycle;
end;
constructor TDSConnectionEntity.Create(const Table: TDBXTable; const OwnTable: Boolean);
begin
inherited Create(Table, OwnTable);
end;
constructor TDSConnectionEntity.Create(const OwnTable: Boolean);
begin
inherited Create(CreateClassTable, OwnTable);
end;
class function TDSConnectionEntity.CreateClassTable: TDBXTable;
var
Table: TDBXTable;
ReturnList: TDBXValueTypeArray;
ConnectionName: TDBXValueType;
ConnectionProperties: TDBXValueType;
DriverName: TDBXValueType;
DriverProperties: TDBXValueType;
begin
Table := TDBXTableFactory.CreateDBXTable;
Table.DBXTableName := 'ConnectionTable';
ConnectionName := TDBXValueType.Create;
ConnectionName.Name := TDSConnectionColumns.ConnectionName;
ConnectionName.DisplayName := TDSConnectionColumns.ConnectionName;
ConnectionName.DataType := TDBXDataTypes.WideStringType;
ConnectionName.Size := 128;
ConnectionProperties := TDBXValueType.Create;
ConnectionProperties.Name := TDSConnectionColumns.ConnectionProperties;
ConnectionProperties.DisplayName := TDSConnectionColumns.ConnectionProperties;
ConnectionProperties.DataType := TDBXDataTypes.WideStringType;
ConnectionProperties.Size := 2048;
DriverName := TDBXValueType.Create;
DriverName.Name := TDSConnectionColumns.DriverName;
DriverName.DisplayName := TDSConnectionColumns.DriverName;
DriverName.DataType := TDBXDataTypes.WideStringType;
DriverName.Size := 128;
DriverProperties := TDBXValueType.Create;
DriverProperties.Name := TDSConnectionColumns.DriverProperties;
DriverProperties.DisplayName := TDSConnectionColumns.DriverProperties;
DriverProperties.DataType := TDBXDataTypes.WideStringType;
DriverProperties.Size := 2048;
SetLength(ReturnList,4);
ReturnList[0] := ConnectionName;
ReturnList[1] := ConnectionProperties;
ReturnList[2] := DriverName;
ReturnList[3] := DriverProperties;
Table.Columns := ReturnList;
Result := Table;
end;
function TDSConnectionEntity.GetConnectionName: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDSConnectionColumns.ConnectionName)].AsString;
end;
procedure TDSConnectionEntity.SetConnectionName(const ConnectionName: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDSConnectionColumns.ConnectionName)].AsString := ConnectionName;
end;
function TDSConnectionEntity.GetConnectionProperties: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDSConnectionColumns.ConnectionProperties)].AsString;
end;
procedure TDSConnectionEntity.SetConnectionProperties(const ConnectionProperties: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDSConnectionColumns.ConnectionProperties)].AsString := ConnectionProperties;
end;
function TDSConnectionEntity.GetDriverName: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDSConnectionColumns.DriverName)].AsString;
end;
procedure TDSConnectionEntity.SetDriverName(const DriverName: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDSConnectionColumns.DriverName)].AsString := DriverName;
end;
function TDSConnectionEntity.GetDriverProperties: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDSConnectionColumns.DriverProperties)].AsString;
end;
procedure TDSConnectionEntity.SetDriverProperties(const DriverProperties: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDSConnectionColumns.DriverProperties)].AsString := DriverProperties;
end;
constructor TDSMethodEntity.Create(const Table: TDBXTable; const OwnTable: Boolean);
begin
inherited Create(Table, OwnTable);
end;
constructor TDSMethodEntity.Create(const OwnTable: Boolean);
begin
inherited Create(CreateMethodTable, OwnTable);
end;
class function TDSMethodEntity.CreateMethodTable: TDBXTable;
var
Table: TDBXTable;
MethodAlias: TDBXValueType;
ClassName: TDBXValueType;
MethodName: TDBXValueType;
RoleName: TDBXValueType;
TypeList: TDBXValueTypeArray;
begin
Table := TDBXTableFactory.CreateDBXTable;
Table.DBXTableName := 'MethodTable';
MethodAlias := TDBXValueType.Create;
MethodAlias.Name := TDSMethodColumns.MethodAlias;
MethodAlias.DisplayName := TDSMethodColumns.MethodAlias;
MethodAlias.DataType := TDBXDataTypes.WideStringType;
MethodAlias.Size := 256;
ClassName := TDBXValueType.Create;
ClassName.Name := TDSMethodColumns.ServerClassName;
ClassName.DisplayName := TDSMethodColumns.ServerClassName;
ClassName.DataType := TDBXDataTypes.WideStringType;
ClassName.Size := 256;
MethodName := TDBXValueType.Create;
MethodName.Name := TDSMethodColumns.ServerMethodName;
MethodName.DisplayName := TDSMethodColumns.ServerMethodName;
MethodName.DataType := TDBXDataTypes.WideStringType;
MethodName.Size := 256;
RoleName := TDBXValueType.Create;
RoleName.Name := TDSMethodColumns.RoleName;
RoleName.DisplayName := TDSMethodColumns.RoleName;
RoleName.DataType := TDBXDataTypes.WideStringType;
RoleName.Size := 256;
SetLength(TypeList,4);
TypeList[0] := MethodAlias;
TypeList[1] := ClassName;
TypeList[2] := MethodName;
TypeList[3] := RoleName;
Table.Columns := TypeList;
Result := Table;
end;
function TDSMethodEntity.GetMethodAlias: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDSMethodColumns.MethodAlias)].AsString;
end;
procedure TDSMethodEntity.SetMethodAlias(const ClassName: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDSMethodColumns.MethodAlias)].AsString := ClassName;
end;
function TDSMethodEntity.GetServerClassName: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDSMethodColumns.ServerClassName)].AsString;
end;
procedure TDSMethodEntity.SetServerClassName(const ClassName: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDSMethodColumns.ServerClassName)].AsString := ClassName;
end;
function TDSMethodEntity.GetServerMethodName: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDSMethodColumns.ServerMethodName)].AsString;
end;
procedure TDSMethodEntity.SetServerMethodName(const ClassName: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDSMethodColumns.ServerMethodName)].AsString := ClassName;
end;
function TDSMethodEntity.GetRoleName: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDSMethodColumns.RoleName)].AsString;
end;
procedure TDSMethodEntity.SetRoleName(const ClassName: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDSMethodColumns.RoleName)].AsString := ClassName;
end;
constructor TDSPackageEntity.Create(const Table: TDBXTable; const OwnTable: Boolean);
begin
inherited Create(Table, OwnTable);
end;
constructor TDSPackageEntity.Create(const OwnTable: Boolean);
begin
inherited Create(CreatePackageTable, OwnTable);
end;
class function TDSPackageEntity.CreatePackageTable: TDBXTable;
var
Table: TDBXTable;
PackageName: TDBXValueType;
TypeList: TDBXValueTypeArray;
begin
Table := TDBXTableFactory.CreateDBXTable;
Table.DBXTableName := 'PackageTable';
PackageName := TDBXValueType.Create;
PackageName.Name := TDSPackageColumns.PackageName;
PackageName.DisplayName := TDSPackageColumns.PackageName;
PackageName.DataType := TDBXDataTypes.WideStringType;
PackageName.Size := 256;
SetLength(TypeList,1);
TypeList[0] := PackageName;
Table.Columns := TypeList;
Result := Table;
end;
function TDSPackageEntity.GetPackageName: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDSPackageColumns.PackageName)].AsString;
end;
procedure TDSPackageEntity.SetPackageName(const PackageName: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDSPackageColumns.PackageName)].AsString := PackageName;
end;
constructor TDSProcedureEntity.Create(const Table: TDBXTable; const OwnTable: Boolean);
begin
inherited Create(Table, OwnTable);
end;
constructor TDSProcedureEntity.Create(const OwnTable: Boolean);
begin
inherited Create(CreateProcedureTable, OwnTable);
end;
class function TDSProcedureEntity.CreateProcedureTable: TDBXTable;
var
Table: TDBXTable;
begin
Table := TDBXTableFactory.CreateDBXTable;
Table.DBXTableName := 'ProceduresTable';
Table.Columns := TDBXMetaDataCollectionColumns.CreateProceduresColumns;
Result := Table;
end;
function TDSProcedureEntity.GetCatalogName: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDBXProceduresColumns.CatalogName)].AsString;
end;
procedure TDSProcedureEntity.SetCatalogName(const CatalogName: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDBXProceduresColumns.CatalogName)].AsString := CatalogName;
end;
function TDSProcedureEntity.GetSchemaName: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDBXProceduresColumns.SchemaName)].AsString;
end;
procedure TDSProcedureEntity.SetSchemaName(const SchemaName: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDBXProceduresColumns.SchemaName)].AsString := SchemaName;
end;
function TDSProcedureEntity.GetProcedureName: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDBXProceduresColumns.ProcedureName)].AsString;
end;
procedure TDSProcedureEntity.SetProcedureName(const ProcedureName: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDBXProceduresColumns.ProcedureName)].AsString := ProcedureName;
end;
function TDSProcedureEntity.GetProcedureType: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDBXProceduresColumns.ProcedureType)].AsString;
end;
procedure TDSProcedureEntity.SetProcedureType(const ClassName: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDBXProceduresColumns.ProcedureType)].AsString := ClassName;
end;
constructor TDSProcedureParametersEntity.Create(const Table: TDBXTable; const OwnTable: Boolean);
begin
inherited Create(Table, OwnTable);
end;
constructor TDSProcedureParametersEntity.Create(const OwnTable: Boolean);
begin
inherited Create(CreateProcedureParmetersTable, OwnTable);
end;
class function TDSProcedureParametersEntity.CreateProcedureParmetersTable: TDBXTable;
var
Table: TDBXTable;
begin
Table := TDBXTableFactory.CreateDBXTable;
Table.DBXTableName := 'ProcedureParameters';
Table.Columns := TDBXMetaDataCollectionColumns.CreateProcedureParametersColumns;
Result := Table;
end;
function TDSProcedureParametersEntity.GetCatalogName: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.CatalogName)].AsString;
end;
procedure TDSProcedureParametersEntity.SetCatalogName(const CatalogName: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.CatalogName)].AsString := CatalogName;
end;
function TDSProcedureParametersEntity.GetSchemaName: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.SchemaName)].AsString;
end;
procedure TDSProcedureParametersEntity.SetSchemaName(const SchemaName: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.SchemaName)].AsString := SchemaName;
end;
function TDSProcedureParametersEntity.GetProcedureName: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.ProcedureName)].AsString;
end;
procedure TDSProcedureParametersEntity.SetProceduredName(const ProcedureName: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.ProcedureName)].AsString := ProcedureName;
end;
function TDSProcedureParametersEntity.GetParameterName: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.ParameterName)].AsString;
end;
procedure TDSProcedureParametersEntity.SetParameterName(const ParameterName: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.ParameterName)].AsString := ParameterName;
end;
function TDSProcedureParametersEntity.GetParameterMode: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.ParameterMode)].AsString;
end;
procedure TDSProcedureParametersEntity.SetParameterMode(const ParameterMode: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.ParameterMode)].AsString := ParameterMode;
end;
function TDSProcedureParametersEntity.GetTypeName: UnicodeString;
begin
Result := Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.TypeName)].AsString;
end;
procedure TDSProcedureParametersEntity.SetTypeName(const TypeName: UnicodeString);
begin
Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.TypeName)].AsString := TypeName;
end;
function TDSProcedureParametersEntity.GetPrecision: Integer;
begin
Result := Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.Precision)].AsInt32;
end;
procedure TDSProcedureParametersEntity.SetPrecision(const Precision: Integer);
begin
Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.Precision)].AsInt32 := Precision;
end;
function TDSProcedureParametersEntity.GetScale: Integer;
begin
Result := Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.Scale)].AsInt32;
end;
procedure TDSProcedureParametersEntity.SetScale(const Scale: Integer);
begin
Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.Scale)].AsInt32 := Scale;
end;
function TDSProcedureParametersEntity.GetOrdinal: Integer;
begin
Result := Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.Ordinal)].AsInt32;
end;
procedure TDSProcedureParametersEntity.SetOrdinal(const Ordinal: Integer);
begin
Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.Ordinal)].AsInt32 := Ordinal;
end;
function TDSProcedureParametersEntity.IsNullable: Boolean;
begin
Result := Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.IsNullable)].GetBoolean;
end;
procedure TDSProcedureParametersEntity.SetNullable(const Nullable: Boolean);
begin
Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.IsNullable)].AsBoolean := Nullable;
end;
function TDSProcedureParametersEntity.GetDBXDataType: Integer;
begin
Result := Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.DbxDataType)].AsInt32;
end;
procedure TDSProcedureParametersEntity.SetDBXDataType(const DataType: Integer);
begin
Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.DbxDataType)].AsInt32 := DataType;
end;
function TDSProcedureParametersEntity.IsFixedLength: Boolean;
begin
Result := Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.IsFixedLength)].GetBoolean;
end;
procedure TDSProcedureParametersEntity.SetFixedLength(const FixedLength: Boolean);
begin
Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.IsFixedLength)].AsBoolean := FixedLength;
end;
function TDSProcedureParametersEntity.IsUnicode: Boolean;
begin
Result := Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.IsUnicode)].GetBoolean;
end;
procedure TDSProcedureParametersEntity.SetUnicode(const IsUnicode: Boolean);
begin
Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.IsUnicode)].AsBoolean := IsUnicode;
end;
function TDSProcedureParametersEntity.IsLong: Boolean;
begin
Result := Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.IsLong)].GetBoolean;
end;
procedure TDSProcedureParametersEntity.SetLong(const IsLong: Boolean);
begin
Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.IsLong)].AsBoolean := IsLong;
end;
function TDSProcedureParametersEntity.GetUnsigned: Boolean;
begin
Result := Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.IsUnsigned)].GetBoolean;
end;
procedure TDSProcedureParametersEntity.SetUnsigned(const IsUnsigned: Boolean);
begin
Table.Value[Table.GetOrdinal(TDBXProcedureParametersColumns.IsUnsigned)].AsBoolean := IsUnsigned;
end;
end.
|
{
This unit is part of the LaKraven Studios Standard Library (LKSL).
Copyright (C) 2011, LaKraven Studios Ltd.
Copyright Protection Packet(s): LKSL001
--------------------------------------------------------------------
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.
--------------------------------------------------------------------
Unit: LKSL.Managed.Arrays.pas
Created: 31st October 2011
Modified: 16th November 2011
Changelog:
16th November 2011
- Added an Integer-indexed Managed Array
- Added an Object-indexed Managed Array
- Added a Variant-indexed Managed Array
- Added an Int64-indexed Managed Array
- Added a Single-indexed Managed Array
- Added a Double-indexed Managed Array
- Added an Extended-indexed Managed Array
- Added a TDate-indexed Managed Array
- Added a TTime-indexed Managed Array
- Added a TDateTime-indexed Managed Array
15th November 2011
- Added Base Classes, modified all Array Types to use common Base
behaviors
7th November 2011
- Added conditional "Uses" declaration for Delphi XE2 and above.
}
unit LKSL.Managed.Arrays;
interface
{$I LKSL.inc}
uses
{$IFDEF SCOPED}
System.Classes, System.StrUtils;
{$ELSE}
Classes, StrUtils;
{$ENDIF}
type
{ Forward Declarations }
TBaseArrayManager = class; // Base Class for all Array Managers
TBaseArrayObject = class; // Base Class for all Managed Array Objects (Item)
TStringArrayManager = class; // A Manager for String-Indexed Arrays
TStringArrayObject = class; // A String-Indexed Managed Array Object (Item)
TIntegerArrayManager = class; // A Manager for Integer-Indexed Arrays
TIntegerArrayObject = class; // An Integer-Indexed Managed Array Object (Item)
TObjectArrayManager = class; // A Manager for Object-Indexed Arrays
TObjectArrayObject = class; // An Object-Indexed Managed Array Object (Item)
TVariantArrayManager = class; // A Manager for Variant-Indexed Arrays
TVariantArrayObject = class; // A Variant-Indexed Managed Array Object (Item)
TInt64ArrayManager = class; // A Manager for Int64-Indexed Arrays
TInt64ArrayObject = class; // An Int64-Indexed Managed Array Object (Item)
TSingleArrayManager = class; // A Manager for Single-indexed Arrays
TSingleArrayObject = class; // A Single-Indexed Managed Array Object (Item)
TDoubleArrayManager = class; // A Manager for Double-indexed Arrays
TDoubleArrayObject = class; // A Double-Indexed Managed Array Object (Item)
TExtendedArrayManager = class; // A Manager for Extended-indexed Arrays
TExtendedArrayObject = class; // An Extended-Indexed Managed Array Object (Item)
TDateArrayManager = class; // A Manager for Date-indexed Arrays
TDateArrayObject = class; // A Date-Indexed Managed Array Object (Item)
TTimeArrayManager = class; // A Manager for Time-indexed Arrays
TTimeArrayObject = class; // A Time-Indexed Managed Array Object (Item)
TDateTimeArrayManager = class; // A Manager for DateTime-indexed Arrays
TDateTimeArrayObject = class; // A DateTime-Indexed Managed Array Object (Item)
{ Class Ref Declarations }
TArrayObjectClass = class of TBaseArrayObject; // Class declaration (for memory allocation/release purposes)
{ Array Declarations }
TArrayObjectArray = Array of TBaseArrayObject; // Base Array Type
{
TBaseArrayManager
- A Base Class for all Array Managers
}
TBaseArrayManager = class(TPersistent)
protected
FCount: Integer;
FObjects: TArrayObjectArray;
FObjectType: TArrayObjectClass;
function GetObjectByIndex(const AIndex: Integer): TStringArrayObject; virtual;
procedure DeleteObject(const AIndex: Integer); virtual;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Clear; virtual;
published
property Count: Integer read FCount;
end;
{
TBaseArrayObject
- A Base Class for all Managed Array Objects
}
TBaseArrayObject = class(TPersistent)
protected
FIndex: Integer;
FManager: TBaseArrayManager;
public
constructor Create(const AIndex: Integer; const AManager: TBaseArrayManager); virtual;
destructor Destroy; override;
published
property Index: Integer read FIndex;
end;
{
TStringArrayManager
- A String-indexed Array Manager
}
TStringArrayManager = class(TBaseArrayManager)
protected
function AddObject(const AName: String): TStringArrayObject; virtual;
function GetObjectByName(const AName: String): TStringArrayObject; virtual;
function GetObjectIndexByName(const AName: String): Integer; virtual;
public
constructor Create; override;
end;
{
TStringArrayObject
- A String-indexed Array Object, housed within a TStringArrayManager
}
TStringArrayObject = class(TBaseArrayObject)
protected
FName: String;
published
property Name: String read FName;
end;
{
TIntegerArrayManager
- An Integer-indexed Array Manager
}
TIntegerArrayManager = class(TBaseArrayManager)
protected
function AddObject(const AID: Integer): TIntegerArrayObject; virtual;
function GetObjectByID(const AID: Integer): TIntegerArrayObject; virtual;
function GetObjectIndexByID(const AID: Integer): Integer; virtual;
public
constructor Create; override;
end;
{
TIntegerArrayObject
- An Integer-indexed Array Object, housed within a TIntegerArrayManager
}
TIntegerArrayObject = class(TBaseArrayObject)
protected
FID: Integer;
published
property ID: Integer read FID;
end;
{
TObjectArrayManager
- An Object-indexed Array Manager
}
TObjectArrayManager = class(TBaseArrayManager)
protected
function AddObject(const AObject: TObject): TObjectArrayObject; virtual;
function GetObjectByID(const AObject: NativeInt): TObjectArrayObject; virtual;
function GetObjectIndexByID(const AObject: NativeInt): Integer; virtual;
public
constructor Create; override;
end;
{
TObjectArrayObject
- An Object-indexed Array Object, housed within a TObjectArrayManager
}
TObjectArrayObject = class(TBaseArrayObject)
protected
FObject: NativeInt;
function GetObject: TObject; virtual;
published
property IDObject: TObject read GetObject; // Had to use "IDObject" because "Object" is a reserved word!
end;
{
TVariantArrayManager
- A Variant-indexed Array Manager
}
TVariantArrayManager = class(TBaseArrayManager)
protected
function AddObject(const AID: Variant): TVariantArrayObject; virtual;
function GetObjectByID(const AID: Variant): TVariantArrayObject; virtual;
function GetObjectIndexByID(const AID: Variant): Integer; virtual;
public
constructor Create; override;
end;
{
TVariantArrayObject
- A Variant-indexed Array Object, housed within a TVariantArrayManager
}
TVariantArrayObject = class(TBaseArrayObject)
protected
FID: Variant;
published
property ID: Variant read FID;
end;
{
TInt64ArrayManager
- An Int64-indexed Array Manager
}
TInt64ArrayManager = class(TBaseArrayManager)
protected
function AddObject(const AID: Int64): TInt64ArrayObject; virtual;
function GetObjectByID(const AID: Int64): TInt64ArrayObject; virtual;
function GetObjectIndexByID(const AID: Int64): Integer; virtual;
public
constructor Create; override;
end;
{
TInt64ArrayObject
- An Int64-indexed Array Object, housed within a TInt64ArrayManager
}
TInt64ArrayObject = class(TBaseArrayObject)
protected
FID: Int64;
published
property ID: Int64 read FID;
end;
{
TSingleArrayManager
- A Single-indexed Array Manager
}
TSingleArrayManager = class(TBaseArrayManager)
protected
function AddObject(const AID: Single): TSingleArrayObject; virtual;
function GetObjectByID(const AID: Single): TSingleArrayObject; virtual;
function GetObjectIndexByID(const AID: Single): Integer; virtual;
public
constructor Create; override;
end;
{
TSingleArrayObject
- A Single-indexed Array Object, housed within a TSingleArrayManager
}
TSingleArrayObject = class(TBaseArrayObject)
protected
FID: Single;
published
property ID: Single read FID;
end;
{
TDoubleArrayManager
- A Double-indexed Array Manager
}
TDoubleArrayManager = class(TBaseArrayManager)
protected
function AddObject(const AID: Double): TDoubleArrayObject; virtual;
function GetObjectByID(const AID: Double): TDoubleArrayObject; virtual;
function GetObjectIndexByID(const AID: Double): Integer; virtual;
public
constructor Create; override;
end;
{
TDoubleArrayObject
- A Double-indexed Array Object, housed within a TDoubleArrayManager
}
TDoubleArrayObject = class(TBaseArrayObject)
protected
FID: Double;
published
property ID: Double read FID;
end;
{
TExtendedArrayManager
- An Extended-indexed Array Manager
}
TExtendedArrayManager = class(TBaseArrayManager)
protected
function AddObject(const AID: Extended): TExtendedArrayObject; virtual;
function GetObjectByID(const AID: Extended): TExtendedArrayObject; virtual;
function GetObjectIndexByID(const AID: Extended): Integer; virtual;
public
constructor Create; override;
end;
{
TExtendedArrayObject
- An Extended-indexed Array Object, housed within a TExtendedArrayManager
}
TExtendedArrayObject = class(TBaseArrayObject)
protected
FID: Extended;
published
property ID: Extended read FID;
end;
{
TDateArrayManager
- A TDate-indexed Array Manager
}
TDateArrayManager = class(TBaseArrayManager)
protected
function AddObject(const AID: TDate): TDateArrayObject; virtual;
function GetObjectByID(const AID: TDate): TDateArrayObject; virtual;
function GetObjectIndexByID(const AID: TDate): Integer; virtual;
public
constructor Create; override;
end;
{
TDateArrayObject
- A TDate-indexed Array Object, housed within a TDateArrayManager
}
TDateArrayObject = class(TBaseArrayObject)
protected
FID: TDate;
published
property ID: TDate read FID;
end;
{
TTimeArrayManager
- A TTime-indexed Array Manager
}
TTimeArrayManager = class(TBaseArrayManager)
protected
function AddObject(const AID: TTime): TTimeArrayObject; virtual;
function GetObjectByID(const AID: TTime): TTimeArrayObject; virtual;
function GetObjectIndexByID(const AID: TTime): Integer; virtual;
public
constructor Create; override;
end;
{
TTimeArrayObject
- A TTime-indexed Array Object, housed within a TTimeArrayManager
}
TTimeArrayObject = class(TBaseArrayObject)
protected
FID: TTime;
published
property ID: TTime read FID;
end;
{
TDateTimeArrayManager
- A TDateTime-indexed Array Manager
}
TDateTimeArrayManager = class(TBaseArrayManager)
protected
function AddObject(const AID: TDateTime): TDateTimeArrayObject; virtual;
function GetObjectByID(const AID: TDateTime): TDateTimeArrayObject; virtual;
function GetObjectIndexByID(const AID: TDateTime): Integer; virtual;
public
constructor Create; override;
end;
{
TDateTimeArrayObject
- A TDateTime-indexed Array Object, housed within a TDateTimeArrayManager
}
TDateTimeArrayObject = class(TBaseArrayObject)
protected
FID: TDateTime;
published
property ID: TDateTime read FID;
end;
implementation
{ TBaseArrayManager }
procedure TBaseArrayManager.Clear;
begin
while FCount > 0 do
FObjects[FCount - 1].Free;
end;
constructor TBaseArrayManager.Create;
begin
inherited;
FCount := 0;
end;
procedure TBaseArrayManager.DeleteObject(const AIndex: Integer);
var
LCount, I: Integer;
begin
LCount := Length(FObjects);
if (AIndex < 0) or (AIndex > LCount - 1) then
Exit;
if (AIndex < (LCount - 1)) then
for I := AIndex to LCount - 2 do
begin
FObjects[I] := FObjects[I + 1];
FObjects[I].FIndex := I;
end;
SetLength(FObjects, LCount - 1);
FCount := LCount - 1;
end;
destructor TBaseArrayManager.Destroy;
begin
Clear;
inherited;
end;
function TBaseArrayManager.GetObjectByIndex(const AIndex: Integer): TStringArrayObject;
begin
if (AIndex > -1) and (AIndex < FCount) then
Result := TStringArrayObject(FObjects[AIndex])
else
Result := nil;
end;
{ TBaseArrayObject }
constructor TBaseArrayObject.Create(const AIndex: Integer; const AManager: TBaseArrayManager);
begin
inherited Create;
FIndex := AIndex;
FManager := AManager;
end;
destructor TBaseArrayObject.Destroy;
begin
FManager.DeleteObject(FIndex);
inherited;
end;
{ TStringArrayManager }
function TStringArrayManager.AddObject(const AName: String): TStringArrayObject;
function GetSortedPosition(const AName: String): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := 0;
LLow := 0;
LHigh := Length(FObjects) - 1;
if LHigh = - 1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if AName <= TStringArrayObject(FObjects[LIndex]).FName then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if (TStringArrayObject(FObjects[LHigh]).FName < AName) then
Result := LHigh + 1
else if (TStringArrayObject(FObjects[LLow]).FName < AName) then
Result := LLow + 1
else
Result := LLow;
end;
var
I, LIndex: Integer;
begin
LIndex := GetObjectIndexByName(AName);
if LIndex = -1 then
begin
LIndex := GetSortedPosition(AName);
SetLength(FObjects, Length(FObjects) + 1);
// Shift elements RIGHT
if LIndex < Length(FObjects) - 1 then
for I := Length(FObjects) - 1 downto LIndex + 1 do
begin
FObjects[I] := FObjects[I - 1];
FObjects[I].FIndex := I;
end;
// Insert new item now
FObjects[LIndex] := FObjectType.Create(LIndex, Self);
TStringArrayObject(FObjects[LIndex]).FName := AName;
Result := TStringArrayObject(FObjects[LIndex]);
FCount := Length(FObjects);
end else
Result := TStringArrayObject(FObjects[LIndex]);
end;
constructor TStringArrayManager.Create;
begin
inherited;
FObjectType := TStringArrayObject;
end;
function TStringArrayManager.GetObjectByName(const AName: String): TStringArrayObject;
var
LIndex: Integer;
begin
LIndex := GetObjectIndexByName(AName);
if LIndex = -1 then
Result := nil
else
Result := TStringArrayObject(FObjects[LIndex]);
end;
function TStringArrayManager.GetObjectIndexByName(const AName: String): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := -1;
LLow := 0;
LHigh := Length(FObjects) - 1;
if LHigh = -1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if AName <= TStringArrayObject(FObjects[LIndex]).FName then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if (TStringArrayObject(FObjects[LHigh]).FName = AName) then
Result := LHigh
else if (TStringArrayObject(FObjects[LLow]).FName = AName) then
Result := LLow;
end;
{ TIntegerArrayManager }
function TIntegerArrayManager.AddObject(const AID: Integer): TIntegerArrayObject;
function GetSortedPosition(const AID: Integer): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := 0;
LLow := 0;
LHigh := Length(FObjects) - 1;
if LHigh = - 1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if AID <= TIntegerArrayObject(FObjects[LIndex]).FID then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if (TIntegerArrayObject(FObjects[LHigh]).FID < AID) then
Result := LHigh + 1
else if (TIntegerArrayObject(FObjects[LLow]).FID < AID) then
Result := LLow + 1
else
Result := LLow;
end;
var
I, LIndex: Integer;
begin
LIndex := GetObjectIndexByID(AID);
if LIndex = -1 then
begin
LIndex := GetSortedPosition(AID);
SetLength(FObjects, Length(FObjects) + 1);
// Shift elements RIGHT
if LIndex < Length(FObjects) - 1 then
for I := Length(FObjects) - 1 downto LIndex + 1 do
begin
FObjects[I] := FObjects[I - 1];
FObjects[I].FIndex := I;
end;
// Insert new item now
FObjects[LIndex] := FObjectType.Create(LIndex, Self);
TIntegerArrayObject(FObjects[LIndex]).FID := AID;
Result := TIntegerArrayObject(FObjects[LIndex]);
FCount := Length(FObjects);
end else
Result := TIntegerArrayObject(FObjects[LIndex]);
end;
constructor TIntegerArrayManager.Create;
begin
inherited;
FObjectType := TIntegerArrayObject;
end;
function TIntegerArrayManager.GetObjectByID(const AID: Integer): TIntegerArrayObject;
var
LIndex: Integer;
begin
LIndex := GetObjectIndexByID(AID);
if LIndex = -1 then
Result := nil
else
Result := TIntegerArrayObject(FObjects[LIndex]);
end;
function TIntegerArrayManager.GetObjectIndexByID(const AID: Integer): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := -1;
LLow := 0;
LHigh := Length(FObjects) - 1;
if LHigh = -1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if AID <= TIntegerArrayObject(FObjects[LIndex]).FID then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if (TIntegerArrayObject(FObjects[LHigh]).FID = AID) then
Result := LHigh
else if (TIntegerArrayObject(FObjects[LLow]).FID = AID) then
Result := LLow;
end;
{ TObjectArrayManager }
function TObjectArrayManager.AddObject(const AObject: TObject): TObjectArrayObject;
function GetSortedPosition(const AObject: NativeInt): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := 0;
LLow := 0;
LHigh := Length(FObjects) - 1;
if LHigh = - 1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if AObject <= TObjectArrayObject(FObjects[LIndex]).FObject then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if (TObjectArrayObject(FObjects[LHigh]).FObject < AObject) then
Result := LHigh + 1
else if (TObjectArrayObject(FObjects[LLow]).FObject < AObject) then
Result := LLow + 1
else
Result := LLow;
end;
var
I, LIndex: Integer;
LStoredID: NativeInt;
begin
LStoredID := NativeInt(@AObject);
LIndex := GetObjectIndexByID(LStoredID);
if LIndex = -1 then
begin
LIndex := GetSortedPosition(LStoredID);
SetLength(FObjects, Length(FObjects) + 1);
// Shift elements RIGHT
if LIndex < Length(FObjects) - 1 then
for I := Length(FObjects) - 1 downto LIndex + 1 do
begin
FObjects[I] := FObjects[I - 1];
FObjects[I].FIndex := I;
end;
// Insert new item now
FObjects[LIndex] := FObjectType.Create(LIndex, Self);
TObjectArrayObject(FObjects[LIndex]).FObject := LStoredID;
Result := TObjectArrayObject(FObjects[LIndex]);
FCount := Length(FObjects);
end else
Result := TObjectArrayObject(FObjects[LIndex]);
end;
constructor TObjectArrayManager.Create;
begin
inherited;
FObjectType := TObjectArrayObject;
end;
function TObjectArrayManager.GetObjectByID(const AObject: NativeInt): TObjectArrayObject;
var
LIndex: Integer;
begin
LIndex := GetObjectIndexByID(AObject);
if LIndex = -1 then
Result := nil
else
Result := TObjectArrayObject(FObjects[LIndex]);
end;
function TObjectArrayManager.GetObjectIndexByID(const AObject: NativeInt): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := -1;
LLow := 0;
LHigh := Length(FObjects) - 1;
if LHigh = -1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if AObject <= TObjectArrayObject(FObjects[LIndex]).FObject then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if (TObjectArrayObject(FObjects[LHigh]).FObject = AObject) then
Result := LHigh
else if (TObjectArrayObject(FObjects[LLow]).FObject = AObject) then
Result := LLow;
end;
{ TObjectArrayObject }
function TObjectArrayObject.GetObject: TObject;
begin
Result := TObject(Pointer(FObject)^);
end;
{ TVariantArrayManager }
function TVariantArrayManager.AddObject(const AID: Variant): TVariantArrayObject;
function GetSortedPosition(const AID: Variant): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := 0;
LLow := 0;
LHigh := Length(FObjects) - 1;
if LHigh = - 1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if AID <= TIntegerArrayObject(FObjects[LIndex]).FID then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if (TIntegerArrayObject(FObjects[LHigh]).FID < AID) then
Result := LHigh + 1
else if (TIntegerArrayObject(FObjects[LLow]).FID < AID) then
Result := LLow + 1
else
Result := LLow;
end;
var
I, LIndex: Integer;
begin
LIndex := GetObjectIndexByID(AID);
if LIndex = -1 then
begin
LIndex := GetSortedPosition(AID);
SetLength(FObjects, Length(FObjects) + 1);
// Shift elements RIGHT
if LIndex < Length(FObjects) - 1 then
for I := Length(FObjects) - 1 downto LIndex + 1 do
begin
FObjects[I] := FObjects[I - 1];
FObjects[I].FIndex := I;
end;
// Insert new item now
FObjects[LIndex] := FObjectType.Create(LIndex, Self);
TIntegerArrayObject(FObjects[LIndex]).FID := AID;
Result := TVariantArrayObject(FObjects[LIndex]);
FCount := Length(FObjects);
end else
Result := TVariantArrayObject(FObjects[LIndex]);
end;
constructor TVariantArrayManager.Create;
begin
inherited;
FObjectType := TVariantArrayObject;
end;
function TVariantArrayManager.GetObjectByID(const AID: Variant): TVariantArrayObject;
var
LIndex: Integer;
begin
LIndex := GetObjectIndexByID(AID);
if LIndex = -1 then
Result := nil
else
Result := TVariantArrayObject(FObjects[LIndex]);
end;
function TVariantArrayManager.GetObjectIndexByID(const AID: Variant): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := -1;
LLow := 0;
LHigh := Length(FObjects) - 1;
if LHigh = -1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if AID <= TVariantArrayObject(FObjects[LIndex]).FID then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if (TVariantArrayObject(FObjects[LHigh]).FID = AID) then
Result := LHigh
else if (TVariantArrayObject(FObjects[LLow]).FID = AID) then
Result := LLow;
end;
{ TInt64ArrayManager }
function TInt64ArrayManager.AddObject(const AID: Int64): TInt64ArrayObject;
function GetSortedPosition(const AID: Int64): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := 0;
LLow := 0;
LHigh := Length(FObjects) - 1;
if LHigh = - 1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if AID <= TInt64ArrayObject(FObjects[LIndex]).FID then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if (TInt64ArrayObject(FObjects[LHigh]).FID < AID) then
Result := LHigh + 1
else if (TInt64ArrayObject(FObjects[LLow]).FID < AID) then
Result := LLow + 1
else
Result := LLow;
end;
var
I, LIndex: Integer;
begin
LIndex := GetObjectIndexByID(AID);
if LIndex = -1 then
begin
LIndex := GetSortedPosition(AID);
SetLength(FObjects, Length(FObjects) + 1);
// Shift elements RIGHT
if LIndex < Length(FObjects) - 1 then
for I := Length(FObjects) - 1 downto LIndex + 1 do
begin
FObjects[I] := FObjects[I - 1];
FObjects[I].FIndex := I;
end;
// Insert new item now
FObjects[LIndex] := FObjectType.Create(LIndex, Self);
TInt64ArrayObject(FObjects[LIndex]).FID := AID;
Result := TInt64ArrayObject(FObjects[LIndex]);
FCount := Length(FObjects);
end else
Result := TInt64ArrayObject(FObjects[LIndex]);
end;
constructor TInt64ArrayManager.Create;
begin
inherited;
FObjectType := TInt64ArrayObject;
end;
function TInt64ArrayManager.GetObjectByID(const AID: Int64): TInt64ArrayObject;
var
LIndex: Integer;
begin
LIndex := GetObjectIndexByID(AID);
if LIndex = -1 then
Result := nil
else
Result := TInt64ArrayObject(FObjects[LIndex]);
end;
function TInt64ArrayManager.GetObjectIndexByID(const AID: Int64): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := -1;
LLow := 0;
LHigh := Length(FObjects) - 1;
if LHigh = -1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if AID <= TInt64ArrayObject(FObjects[LIndex]).FID then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if (TInt64ArrayObject(FObjects[LHigh]).FID = AID) then
Result := LHigh
else if (TInt64ArrayObject(FObjects[LLow]).FID = AID) then
Result := LLow;
end;
{ TSingleArrayManager }
function TSingleArrayManager.AddObject(const AID: Single): TSingleArrayObject;
function GetSortedPosition(const AID: Single): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := 0;
LLow := 0;
LHigh := Length(FObjects) - 1;
if LHigh = - 1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if AID <= TSingleArrayObject(FObjects[LIndex]).FID then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if (TSingleArrayObject(FObjects[LHigh]).FID < AID) then
Result := LHigh + 1
else if (TSingleArrayObject(FObjects[LLow]).FID < AID) then
Result := LLow + 1
else
Result := LLow;
end;
var
I, LIndex: Integer;
begin
LIndex := GetObjectIndexByID(AID);
if LIndex = -1 then
begin
LIndex := GetSortedPosition(AID);
SetLength(FObjects, Length(FObjects) + 1);
// Shift elements RIGHT
if LIndex < Length(FObjects) - 1 then
for I := Length(FObjects) - 1 downto LIndex + 1 do
begin
FObjects[I] := FObjects[I - 1];
FObjects[I].FIndex := I;
end;
// Insert new item now
FObjects[LIndex] := FObjectType.Create(LIndex, Self);
TSingleArrayObject(FObjects[LIndex]).FID := AID;
Result := TSingleArrayObject(FObjects[LIndex]);
FCount := Length(FObjects);
end else
Result := TSingleArrayObject(FObjects[LIndex]);
end;
constructor TSingleArrayManager.Create;
begin
inherited;
FObjectType := TSingleArrayObject;
end;
function TSingleArrayManager.GetObjectByID(const AID: Single): TSingleArrayObject;
var
LIndex: Integer;
begin
LIndex := GetObjectIndexByID(AID);
if LIndex = -1 then
Result := nil
else
Result := TSingleArrayObject(FObjects[LIndex]);
end;
function TSingleArrayManager.GetObjectIndexByID(const AID: Single): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := -1;
LLow := 0;
LHigh := Length(FObjects) - 1;
if LHigh = -1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if AID <= TSingleArrayObject(FObjects[LIndex]).FID then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if (TSingleArrayObject(FObjects[LHigh]).FID = AID) then
Result := LHigh
else if (TSingleArrayObject(FObjects[LLow]).FID = AID) then
Result := LLow;
end;
{ TDoubleArrayManager }
function TDoubleArrayManager.AddObject(const AID: Double): TDoubleArrayObject;
function GetSortedPosition(const AID: Double): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := 0;
LLow := 0;
LHigh := Length(FObjects) - 1;
if LHigh = - 1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if AID <= TDoubleArrayObject(FObjects[LIndex]).FID then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if (TDoubleArrayObject(FObjects[LHigh]).FID < AID) then
Result := LHigh + 1
else if (TDoubleArrayObject(FObjects[LLow]).FID < AID) then
Result := LLow + 1
else
Result := LLow;
end;
var
I, LIndex: Integer;
begin
LIndex := GetObjectIndexByID(AID);
if LIndex = -1 then
begin
LIndex := GetSortedPosition(AID);
SetLength(FObjects, Length(FObjects) + 1);
// Shift elements RIGHT
if LIndex < Length(FObjects) - 1 then
for I := Length(FObjects) - 1 downto LIndex + 1 do
begin
FObjects[I] := FObjects[I - 1];
FObjects[I].FIndex := I;
end;
// Insert new item now
FObjects[LIndex] := FObjectType.Create(LIndex, Self);
TDoubleArrayObject(FObjects[LIndex]).FID := AID;
Result := TDoubleArrayObject(FObjects[LIndex]);
FCount := Length(FObjects);
end else
Result := TDoubleArrayObject(FObjects[LIndex]);
end;
constructor TDoubleArrayManager.Create;
begin
inherited;
FObjectType := TDoubleArrayObject;
end;
function TDoubleArrayManager.GetObjectByID(const AID: Double): TDoubleArrayObject;
var
LIndex: Integer;
begin
LIndex := GetObjectIndexByID(AID);
if LIndex = -1 then
Result := nil
else
Result := TDoubleArrayObject(FObjects[LIndex]);
end;
function TDoubleArrayManager.GetObjectIndexByID(const AID: Double): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := -1;
LLow := 0;
LHigh := Length(FObjects) - 1;
if LHigh = -1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if AID <= TDoubleArrayObject(FObjects[LIndex]).FID then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if (TDoubleArrayObject(FObjects[LHigh]).FID = AID) then
Result := LHigh
else if (TDoubleArrayObject(FObjects[LLow]).FID = AID) then
Result := LLow;
end;
{ TExtendedArrayManager }
function TExtendedArrayManager.AddObject(const AID: Extended): TExtendedArrayObject;
function GetSortedPosition(const AID: Extended): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := 0;
LLow := 0;
LHigh := Length(FObjects) - 1;
if LHigh = - 1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if AID <= TExtendedArrayObject(FObjects[LIndex]).FID then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if (TExtendedArrayObject(FObjects[LHigh]).FID < AID) then
Result := LHigh + 1
else if (TExtendedArrayObject(FObjects[LLow]).FID < AID) then
Result := LLow + 1
else
Result := LLow;
end;
var
I, LIndex: Integer;
begin
LIndex := GetObjectIndexByID(AID);
if LIndex = -1 then
begin
LIndex := GetSortedPosition(AID);
SetLength(FObjects, Length(FObjects) + 1);
// Shift elements RIGHT
if LIndex < Length(FObjects) - 1 then
for I := Length(FObjects) - 1 downto LIndex + 1 do
begin
FObjects[I] := FObjects[I - 1];
FObjects[I].FIndex := I;
end;
// Insert new item now
FObjects[LIndex] := FObjectType.Create(LIndex, Self);
TExtendedArrayObject(FObjects[LIndex]).FID := AID;
Result := TExtendedArrayObject(FObjects[LIndex]);
FCount := Length(FObjects);
end else
Result := TExtendedArrayObject(FObjects[LIndex]);
end;
constructor TExtendedArrayManager.Create;
begin
inherited;
FObjectType := TExtendedArrayObject;
end;
function TExtendedArrayManager.GetObjectByID(const AID: Extended): TExtendedArrayObject;
var
LIndex: Integer;
begin
LIndex := GetObjectIndexByID(AID);
if LIndex = -1 then
Result := nil
else
Result := TExtendedArrayObject(FObjects[LIndex]);
end;
function TExtendedArrayManager.GetObjectIndexByID(const AID: Extended): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := -1;
LLow := 0;
LHigh := Length(FObjects) - 1;
if LHigh = -1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if AID <= TExtendedArrayObject(FObjects[LIndex]).FID then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if (TExtendedArrayObject(FObjects[LHigh]).FID = AID) then
Result := LHigh
else if (TExtendedArrayObject(FObjects[LLow]).FID = AID) then
Result := LLow;
end;
{ TDateArrayManager }
function TDateArrayManager.AddObject(const AID: TDate): TDateArrayObject;
function GetSortedPosition(const AID: TDate): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := 0;
LLow := 0;
LHigh := Length(FObjects) - 1;
if LHigh = - 1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if AID <= TDateArrayObject(FObjects[LIndex]).FID then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if (TDateArrayObject(FObjects[LHigh]).FID < AID) then
Result := LHigh + 1
else if (TDateArrayObject(FObjects[LLow]).FID < AID) then
Result := LLow + 1
else
Result := LLow;
end;
var
I, LIndex: Integer;
begin
LIndex := GetObjectIndexByID(AID);
if LIndex = -1 then
begin
LIndex := GetSortedPosition(AID);
SetLength(FObjects, Length(FObjects) + 1);
// Shift elements RIGHT
if LIndex < Length(FObjects) - 1 then
for I := Length(FObjects) - 1 downto LIndex + 1 do
begin
FObjects[I] := FObjects[I - 1];
FObjects[I].FIndex := I;
end;
// Insert new item now
FObjects[LIndex] := FObjectType.Create(LIndex, Self);
TDateArrayObject(FObjects[LIndex]).FID := AID;
Result := TDateArrayObject(FObjects[LIndex]);
FCount := Length(FObjects);
end else
Result := TDateArrayObject(FObjects[LIndex]);
end;
constructor TDateArrayManager.Create;
begin
inherited;
FObjectType := TDateArrayObject;
end;
function TDateArrayManager.GetObjectByID(const AID: TDate): TDateArrayObject;
var
LIndex: Integer;
begin
LIndex := GetObjectIndexByID(AID);
if LIndex = -1 then
Result := nil
else
Result := TDateArrayObject(FObjects[LIndex]);
end;
function TDateArrayManager.GetObjectIndexByID(const AID: TDate): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := -1;
LLow := 0;
LHigh := Length(FObjects) - 1;
if LHigh = -1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if AID <= TDateArrayObject(FObjects[LIndex]).FID then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if (TDateArrayObject(FObjects[LHigh]).FID = AID) then
Result := LHigh
else if (TDateArrayObject(FObjects[LLow]).FID = AID) then
Result := LLow;
end;
{ TTimeArrayManager }
function TTimeArrayManager.AddObject(const AID: TTime): TTimeArrayObject;
function GetSortedPosition(const AID: TTime): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := 0;
LLow := 0;
LHigh := Length(FObjects) - 1;
if LHigh = - 1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if AID <= TTimeArrayObject(FObjects[LIndex]).FID then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if (TTimeArrayObject(FObjects[LHigh]).FID < AID) then
Result := LHigh + 1
else if (TTimeArrayObject(FObjects[LLow]).FID < AID) then
Result := LLow + 1
else
Result := LLow;
end;
var
I, LIndex: Integer;
begin
LIndex := GetObjectIndexByID(AID);
if LIndex = -1 then
begin
LIndex := GetSortedPosition(AID);
SetLength(FObjects, Length(FObjects) + 1);
// Shift elements RIGHT
if LIndex < Length(FObjects) - 1 then
for I := Length(FObjects) - 1 downto LIndex + 1 do
begin
FObjects[I] := FObjects[I - 1];
FObjects[I].FIndex := I;
end;
// Insert new item now
FObjects[LIndex] := FObjectType.Create(LIndex, Self);
TTimeArrayObject(FObjects[LIndex]).FID := AID;
Result := TTimeArrayObject(FObjects[LIndex]);
FCount := Length(FObjects);
end else
Result := TTimeArrayObject(FObjects[LIndex]);
end;
constructor TTimeArrayManager.Create;
begin
inherited;
FObjectType := TTimeArrayObject;
end;
function TTimeArrayManager.GetObjectByID(const AID: TTime): TTimeArrayObject;
var
LIndex: Integer;
begin
LIndex := GetObjectIndexByID(AID);
if LIndex = -1 then
Result := nil
else
Result := TTimeArrayObject(FObjects[LIndex]);
end;
function TTimeArrayManager.GetObjectIndexByID(const AID: TTime): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := -1;
LLow := 0;
LHigh := Length(FObjects) - 1;
if LHigh = -1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if AID <= TTimeArrayObject(FObjects[LIndex]).FID then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if (TTimeArrayObject(FObjects[LHigh]).FID = AID) then
Result := LHigh
else if (TTimeArrayObject(FObjects[LLow]).FID = AID) then
Result := LLow;
end;
{ TDateTimeArrayManager }
function TDateTimeArrayManager.AddObject(const AID: TDateTime): TDateTimeArrayObject;
function GetSortedPosition(const AID: TDateTime): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := 0;
LLow := 0;
LHigh := Length(FObjects) - 1;
if LHigh = - 1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if AID <= TDateTimeArrayObject(FObjects[LIndex]).FID then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if (TDateTimeArrayObject(FObjects[LHigh]).FID < AID) then
Result := LHigh + 1
else if (TDateTimeArrayObject(FObjects[LLow]).FID < AID) then
Result := LLow + 1
else
Result := LLow;
end;
var
I, LIndex: Integer;
begin
LIndex := GetObjectIndexByID(AID);
if LIndex = -1 then
begin
LIndex := GetSortedPosition(AID);
SetLength(FObjects, Length(FObjects) + 1);
// Shift elements RIGHT
if LIndex < Length(FObjects) - 1 then
for I := Length(FObjects) - 1 downto LIndex + 1 do
begin
FObjects[I] := FObjects[I - 1];
FObjects[I].FIndex := I;
end;
// Insert new item now
FObjects[LIndex] := FObjectType.Create(LIndex, Self);
TDateTimeArrayObject(FObjects[LIndex]).FID := AID;
Result := TDateTimeArrayObject(FObjects[LIndex]);
FCount := Length(FObjects);
end else
Result := TDateTimeArrayObject(FObjects[LIndex]);
end;
constructor TDateTimeArrayManager.Create;
begin
inherited;
FObjectType := TDateTimeArrayObject;
end;
function TDateTimeArrayManager.GetObjectByID(const AID: TDateTime): TDateTimeArrayObject;
var
LIndex: Integer;
begin
LIndex := GetObjectIndexByID(AID);
if LIndex = -1 then
Result := nil
else
Result := TDateTimeArrayObject(FObjects[LIndex]);
end;
function TDateTimeArrayManager.GetObjectIndexByID(const AID: TDateTime): Integer;
var
LIndex, LLow, LHigh: Integer;
begin
Result := -1;
LLow := 0;
LHigh := Length(FObjects) - 1;
if LHigh = -1 then
Exit;
if LLow < LHigh then
begin
while (LHigh - LLow > 1) do
begin
LIndex := (LHigh + LLow) div 2;
if AID <= TDateTimeArrayObject(FObjects[LIndex]).FID then
LHigh := LIndex
else
LLow := LIndex;
end;
end;
if (TDateTimeArrayObject(FObjects[LHigh]).FID = AID) then
Result := LHigh
else if (TDateTimeArrayObject(FObjects[LLow]).FID = AID) then
Result := LLow;
end;
end.
|
{
Copyright (c) 2013-2017, RealThinClient components - http://www.realthinclient.com
Copyright (c) Independent JPEG group - http://www.ijg.org
Copyright (c) 2006, Luc Saillard <luc@saillard.org>
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
@exclude }
unit rtcXJPEGDecode;
{$INCLUDE rtcDefs.inc}
interface
uses
rtcTypes,
rtcXJPEGConst,
rtcXBmpUtils;
function JPEGToBitmap(const JPEG:RtcByteArray; var bmp:TRtcBitmapInfo):boolean;
function JPEGDiffToBitmap(const JPEGHeader, JPEGData:RtcByteArray; var bmp:TRtcBitmapInfo):boolean;
implementation
const
TINYJPEG_FLAGS_MJPEG_TABLE = 2;
HUFFMAN_BITS_SIZE = 256;
HUFFMAN_HASH_NBITS = 9;
HUFFMAN_HASH_SIZE = 1 shl HUFFMAN_HASH_NBITS;
HUFFMAN_HASH_MASK = HUFFMAN_HASH_SIZE - 1;
HUFFMAN_TABLES = 4;
JPEG_COMPONENTS = 3;
JPEG_MAX_WIDTH = 4096;
JPEG_MAX_HEIGHT = 4096;
type
huffman_table = {packed} record
(* Fast look up table, using HUFFMAN_HASH_NBITS bits we can have directly the symbol,
* if the symbol is <0, then we need to look into the tree table *)
lookup: array [0 .. HUFFMAN_HASH_SIZE - 1] of smallint;
(* code size: give the number of bits of a symbol is encoded *)
code_size: array [0 .. HUFFMAN_HASH_SIZE - 1] of byte;
(* some place to store value that is not encoded in the lookup table
* FIXME: Calculate if 256 value is enough to store all values *)
slowtable: array [0 .. 16 - HUFFMAN_HASH_NBITS - 1] of WordArr256;
end;
jpeg_component = {packed} record
Hfactor: longword;
Vfactor: longword;
Q_table: LongIntArr64; // FLOAT Pointer to the quantisation table to use
Q_table2: LongIntArr64; // FLOAT Pointer to the quantisation table to use
AC_table: huffman_table;
DC_table: huffman_table;
prev_DC,
prev_DC2: smallint; // Previous DC coefficient
DCT: SmallIntArr64; // DCT coef
end;
PLongInt = ^longint;
jdec_private = {packed} record
// Public variables
width, height: longword; // Size of the image
flags: longword;
// Private variables
stream_begin, stream_end: PByte;
stream_length: longword;
stream: PByte; // Pointer to the current stream
reservoir: longint;
nbits_in_reservoir: byte;
component_infos: array [0 .. JPEG_COMPONENTS - 1] of jpeg_component;
Q_tables: array [0 .. JPEG_COMPONENTS - 1] of LongIntArr64; // FLOAT
Q_tables2: array [0 .. JPEG_COMPONENTS - 1] of LongIntArr64; // FLOAT
// quantization tables
HTDC: array [0 .. HUFFMAN_TABLES - 1] of huffman_table; // DC huffman tables
HTAC: array [0 .. HUFFMAN_TABLES - 1] of huffman_table; // AC huffman tables
default_huffman_table_initialized: longint;
restart_interval: longint;
restarts_to_go: longint; // MCUs left in this restart interval
last_rst_marker_seen: longint; // Rst marker is incremented each time
// Temp space used after the IDCT to store each components
Y: array [0 .. 64 * 4 - 1] of longint;
Cr: array [0 .. 63] of longint;
Cb: array [0 .. 63] of longint;
// jmp_buf jump_state;
// Internal Pointer use for colorspace conversion, do not modify it !!!
location: longword;
end;
TRtcJPEGDecoder=class(TObject)
private
Buffer_Type:BufferType;
Bitmap_Line:integer;
Bitmap_Width:word;
Info_Buffer:PByte;
RGB24_buffer:PRGB24_buffer;
RGB32_buffer:PRGB32_buffer;
BGR24_buffer:PBGR24_buffer;
BGR32_buffer:PBGR32_buffer;
ConvertToBitmap:procedure(colorMin,colorMax:longint) of object;
Ximage, Yimage: longint;
priv: jdec_private;
protected
JPEG_HQMode:boolean;
function descale_and_clamp_3(x: longint): longint;
procedure IDCT(const indata:SmallIntArr64; const quantdata:LongIntArr64; output_buf: PLongInt);
procedure fill_nbits(var reservoir: longint; var nbits_in_reservoir: byte;
var stream: PByte; const nbits_wanted: byte);
procedure get_nbits(var reservoir: longint; var nbits_in_reservoir: byte;
var stream: PByte; const nbits_wanted: byte; var Result: longint);
procedure look_nbits(var reservoir: longint; var nbits_in_reservoir: byte;
var stream: PByte; const nbits_wanted: byte; var Result: longint);
procedure skip_nbits(var reservoir: longint; var nbits_in_reservoir: byte;
var stream: PByte; const nbits_wanted: byte);
function get_one_bit(var reservoir: longint; var nbits_in_reservoir: byte; var stream: PByte):boolean;
function be16_to_cpu(x: PByte): word;
function get_next_huffman_code(var huffman_tbl: huffman_table): longint;
function process_Huffman_data_unit(component: longint; var previous_DC:SmallInt):boolean;
procedure build_huffman_table(const bits: ByteArr17; vals: PByte;
var table: huffman_table);
procedure build_default_huffman_tables;
procedure convert_to_BGR24(ColorMin,ColorMax:longint);
procedure convert_to_RGB24(ColorMin,ColorMax:longint);
procedure convert_to_BGR32(ColorMin,ColorMax:longint);
procedure convert_to_RGB32(ColorMin,ColorMax:longint);
function decode_MCU:shortint;
procedure build_quantization_table(var qtable: LongIntArr64; ref_table: PByteArr64);
procedure parse_DQT(stream: PByte);
procedure parse_SOF(stream: PByte);
procedure parse_DHT(stream: PByte);
procedure parse_DRI(stream: PByte);
procedure resync;
procedure find_next_rst_marker;
function parse_JFIF(stream: PByte):boolean;
procedure tinyjpeg_init;
function tinyjpeg_parse_header(buf: PByte; size: longword):boolean;
function tinyjpeg_parse_header_diff(bufHeader, buffData: PByte; sizeHeader, sizeData: longword):boolean;
function tinyjpeg_decode:boolean;
function tinyjpeg_decode_diff:boolean;
procedure tinyjpeg_get_size(var width,height: integer);
function tinyjpeg_set_flags(flags: longint): longint;
procedure LoadBitmap(Bmp: TRtcBitmapInfo);
procedure UnLoadBitmap;
public
constructor Create; virtual;
destructor Destroy; override;
function JPEGToBitmap(const JPEG:RtcByteArray; var bmp:TRtcBitmapInfo):boolean;
function JPEGDiffToBitmap(const JPEGHeader, JPEGData:RtcByteArray; var bmp:TRtcBitmapInfo):boolean;
end;
function JPEGToBitmap(const JPEG:RtcByteArray; var bmp:TRtcBitmapInfo):boolean;
var
jpg:TRtcJPEGDecoder;
begin
jpg:=TRtcJPEGDecoder.Create;
try
Result:=jpg.JPEGToBitmap(JPEG, bmp);
finally
jpg.Free;
end;
end;
function JPEGDiffToBitmap(const JPEGHeader, JPEGData:RtcByteArray; var bmp:TRtcBitmapInfo):boolean;
var
jpg:TRtcJPEGDecoder;
begin
jpg:=TRtcJPEGDecoder.Create;
try
Result:=jpg.JPEGDiffToBitmap(JPEGHeader, JPEGData, bmp);
finally
jpg.Free;
end;
end;
const
// std_markers
DQT = $DB; // Define Quantization Table */
SOF = $C0; // Start of Frame (size information) */
DHT = $C4; // Huffman Table */
SOI = $D8; // Start of Image */
SOS = $DA; // Start of Scan */
RST = $D0; // Reset Marker d0 -> .. */
RST7 = $D7; // Reset Marker .. -> d7 */
EOI = $D9; // End of Image */
DRI = $DD; // Define Restart Interval */
APP0 = $E0;
cY = 0;
cCb = 1;
cCr = 2;
const
COLOR_SCALEBITS = 10; // 50% color, 50% detail
MAX_SCALEBITS = 18;
FLOAT_SCALEBITS = MAX_SCALEBITS;
COLOR_EXTRABITS = MAX_SCALEBITS - COLOR_SCALEBITS;
FLOAT_SCALE = 1 shl FLOAT_SCALEBITS;
FLOAT_SHIFT = FLOAT_SCALEBITS + 3 - COLOR_EXTRABITS;
FLOAT_LIMIT = longint(255) shl COLOR_EXTRABITS;
DESCALE_CENTER = FLOAT_SCALE shl 3 * 128;
mul_t12 = LongInt(trunc( 1.414213562 * FLOAT_SCALE +0.5));
mul_t11 = LongInt(trunc( 1.414213562 * FLOAT_SCALE +0.5));
mul_z5 = LongInt(trunc( 1.847759065 * FLOAT_SCALE +0.5)); // 2*c2
mul_z12 = LongInt(trunc( 1.082392200 * FLOAT_SCALE +0.5)); // 2*(c2-c6)
mul_z10 = LongInt(trunc(-2.613125930 * FLOAT_SCALE +0.5)); // -2*(c2+c6)
COLOR_DESCALEBITS = COLOR_SCALEBITS + COLOR_EXTRABITS;
COLOR_SCALECENTER = 128 shl COLOR_EXTRABITS;
ONE_HALF = 1 shl (COLOR_SCALEBITS-1);
FIX_R: longint = trunc(1.40200 * ONE_HALF * 2 + 0.5);
FIX_G1: longint = trunc(0.34414 * ONE_HALF * 2 + 0.5);
FIX_G2: longint = trunc(0.71414 * ONE_HALF * 2 + 0.5);
FIX_B: longint = trunc(1.77200 * ONE_HALF * 2 + 0.5);
JPEG_HQCOLOR_MAX: longint = (127+127) shl COLOR_DESCALEBITS;
JPEG_HQCOLOR_MIN: longint = (128-127) shl COLOR_DESCALEBITS;
JPEG_COLOR_MAX: longint = (127+127) shl COLOR_DESCALEBITS;
JPEG_COLOR_MIN: longint = (128-127) shl COLOR_DESCALEBITS;
function TRtcJPEGDecoder.descale_and_clamp_3(x: longint): longint;
begin
Inc(x,DESCALE_CENTER);
if x<=0 then
Result:=0
else
begin
x:=x shr FLOAT_SHIFT;
if x>FLOAT_LIMIT then
Result:=FLOAT_LIMIT
else
Result:=x;
end;
end;
(*
* Perform dequantization and inverse DCT on one block of coefficients.
*)
procedure TRtcJPEGDecoder.IDCT(const indata:SmallIntArr64; const quantdata:LongIntArr64; output_buf: PLongInt);
var
tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7,
tmp10, tmp11, tmp12, tmp13,
z5, z10, z11, z12, z13: LongInt;
outptr: PLongInt;
i, ctr: byte;
dcval: LongInt; // JPEG_Float;
wspace: LongIntArr64; // FLOAT buffers data between passes
begin
// Pass 1: process columns from input, store into work array.
for ctr := 0 to 7 do
begin
//inptr := Addr(compptr.DCT[ctr]);
//quantptr := Addr(compptr.Q_table[ctr]);
// wsptr := Addr(workspace[ctr]);
(* Due to quantization, we will usually find that many of the input
* coefficients are zero, especially the AC terms. We can exploit this
* by short-circuiting the IDCT calculation for any column in which all
* the AC terms are zero. In that case each output is equal to the
* DC coefficient (with scale factor as needed).
* With typical images and quantization tables, half or more of the
* column DCT calculations can be simplified this way.
*)
if (indata[ctr+8] = 0) and (indata[ctr+8 * 2] = 0) and
(indata[ctr+8 * 3] = 0) and (indata[ctr+8 * 4] = 0) and
(indata[ctr+8 * 5] = 0) and (indata[ctr+8 * 6] = 0) and
(indata[ctr+8 * 7] = 0) then
begin
// AC terms all zero
dcval := indata[ctr] * quantdata[ctr]; // *65536
wspace[ctr] := dcval;
wspace[ctr+8] := dcval;
wspace[ctr+8 * 2] := dcval;
wspace[ctr+8 * 3] := dcval;
wspace[ctr+8 * 4] := dcval;
wspace[ctr+8 * 5] := dcval;
wspace[ctr+8 * 6] := dcval;
wspace[ctr+8 * 7] := dcval;
end
else
begin
// Even part
tmp0 := indata[ctr] * quantdata[ctr]; // *65536
tmp1 := indata[ctr+8 * 2] * quantdata[ctr+8 * 2]; // *65536
tmp2 := indata[ctr+8 * 4] * quantdata[ctr+8 * 4]; // *65536
tmp3 := indata[ctr+8 * 6] * quantdata[ctr+8 * 6]; // *65536
tmp10 := tmp0 + tmp2; // phase 3
tmp11 := tmp0 - tmp2;
tmp13 := tmp1 + tmp3; // phases 5-3
tmp12 := ((tmp1 - tmp3) div FLOAT_SCALE) * mul_t12 - tmp13; // 2*c4
tmp0 := tmp10 + tmp13; // phase 2
tmp3 := tmp10 - tmp13;
tmp1 := tmp11 + tmp12;
tmp2 := tmp11 - tmp12;
// Odd part
tmp4 := indata[ctr+8] * quantdata[ctr+8]; // *65536
tmp5 := indata[ctr+8 * 3] * quantdata[ctr+8 * 3]; // *65536
tmp6 := indata[ctr+8 * 5] * quantdata[ctr+8 * 5]; // *65536
tmp7 := indata[ctr+8 * 7] * quantdata[ctr+8 * 7]; // *65536
z13 := tmp6 + tmp5; // phase 6
z10 := tmp6 - tmp5;
z11 := tmp4 + tmp7;
z12 := tmp4 - tmp7;
tmp7 := z11 + z13; // phase 5
tmp11 := ((z11 - z13) div FLOAT_SCALE) * mul_t11; // 2*c4
z5 := ((z10 + z12) div FLOAT_SCALE) * mul_z5; // 2*c2
tmp10 := (z12 div FLOAT_SCALE) * mul_z12 - z5; // 2*(c2-c6)
tmp12 := (z10 div FLOAT_SCALE) * mul_z10 + z5; // -2*(c2+c6)
tmp6 := tmp12 - tmp7; // phase 2
tmp5 := tmp11 - tmp6;
tmp4 := tmp10 + tmp5;
wspace[ctr] := tmp0 + tmp7;
wspace[ctr+8 * 7] := tmp0 - tmp7;
wspace[ctr+8] := tmp1 + tmp6;
wspace[ctr+8 * 6] := tmp1 - tmp6;
wspace[ctr+8 * 2] := tmp2 + tmp5;
wspace[ctr+8 * 5] := tmp2 - tmp5;
wspace[ctr+8 * 4] := tmp3 + tmp4;
wspace[ctr+8 * 3] := tmp3 - tmp4;
end;
end;
// Pass 2: process rows from work array, store into output array.
// Note that we must descale the results by a factor of 8 == 2**3.
i := 0;
outptr := output_buf;
for ctr := 0 to 7 do
begin
//wsptr := Addr(workspace[i]);
(* Rows of zeroes can be exploited in the same way as we did with columns.
* However, the column calculation has created many nonzero AC terms, so
* the simplification applies less often (typically 5% to 10% of the time).
* And testing floats for zero is relatively expensive, so we don't bother.
*)
// Even part
tmp10 := wspace[i] + wspace[i+4];
tmp11 := wspace[i] - wspace[i+4];
tmp13 := wspace[i+2] + wspace[i+6];
tmp12 := ((wspace[i+2] - wspace[i+6]) div FLOAT_SCALE) * mul_t12 - tmp13;
tmp0 := tmp10 + tmp13;
tmp3 := tmp10 - tmp13;
tmp1 := tmp11 + tmp12;
tmp2 := tmp11 - tmp12;
// Odd part
z13 := wspace[i+5] + wspace[i+3];
z10 := wspace[i+5] - wspace[i+3];
z11 := wspace[i+1] + wspace[i+7];
z12 := wspace[i+1] - wspace[i+7];
tmp7 := z11 + z13;
tmp11 := ((z11 - z13) div FLOAT_SCALE) * mul_t11;
z5 := ((z10 + z12) div FLOAT_SCALE) * mul_z5; // 2*c2
tmp10 := (z12 div FLOAT_SCALE) * mul_z12 - z5; // 2*(c2-c6)
tmp12 := (z10 div FLOAT_SCALE) * mul_z10 + z5; // -2*(c2+c6)
tmp6 := tmp12 - tmp7;
tmp5 := tmp11 - tmp6;
tmp4 := tmp10 + tmp5;
// Final output stage: scale down by a factor of 8 and range-limit
outptr^ := descale_and_clamp_3(tmp0 + tmp7);
Inc(outptr);
outptr^ := descale_and_clamp_3(tmp1 + tmp6);
Inc(outptr);
outptr^ := descale_and_clamp_3(tmp2 + tmp5);
Inc(outptr);
outptr^ := descale_and_clamp_3(tmp3 - tmp4);
Inc(outptr);
outptr^ := descale_and_clamp_3(tmp3 + tmp4);
Inc(outptr);
outptr^ := descale_and_clamp_3(tmp2 - tmp5);
Inc(outptr);
outptr^ := descale_and_clamp_3(tmp1 - tmp6);
Inc(outptr);
outptr^ := descale_and_clamp_3(tmp0 - tmp7);
Inc(outptr);
Inc(i, 8);
end;
end;
(*
* 4 functions to manage the stream
*
* fill_nbits: put at least nbits in the reservoir of bits.
* But convert any 0xff,0x00 into 0xff
* get_nbits: read nbits from the stream, and put it in result,
* bits is removed from the stream and the reservoir is filled
* automaticaly. The result is signed according to the number of
* bits.
* look_nbits: read nbits from the stream without marking as read.
* skip_nbits: read nbits from the stream but do not return the result.
*
* stream: current pointer in the jpeg data (read bytes per bytes)
* nbits_in_reservoir: number of bits filled into the reservoir
* reservoir: register that contains bits information. Only nbits_in_reservoir
* is valid.
* nbits_in_reservoir
* <-- 17 bits -->
* Ex: 0000 0000 1010 0000 1111 0000 <== reservoir
* ^
* bit 1
* To get two bits from this example
* result = (reservoir >> 15) & 3
*
*)
procedure TRtcJPEGDecoder.fill_nbits(var reservoir: longint; var nbits_in_reservoir: byte;
var stream: PByte; const nbits_wanted: byte);
var
c: byte;
begin
while (nbits_in_reservoir < nbits_wanted) do
begin
c := stream^;
Inc(stream);
reservoir := reservoir shl 8;
if (c = $FF) and (stream^ = $00) then
Inc(stream);
reservoir := reservoir or c;
Inc(nbits_in_reservoir, 8);
end;
end;
(* Signed version !!!! *)
procedure TRtcJPEGDecoder.get_nbits(var reservoir: longint; var nbits_in_reservoir: byte;
var stream: PByte; const nbits_wanted: byte; var Result: longint);
begin
fill_nbits(reservoir, nbits_in_reservoir, stream, nbits_wanted);
Result := reservoir shr (nbits_in_reservoir - nbits_wanted);
Dec(nbits_in_reservoir, nbits_wanted);
reservoir := reservoir and ((longint(1) shl nbits_in_reservoir) - 1);
if Result < (longint(1) shl (nbits_wanted - 1)) then
Inc(Result, ($FFFFFFFF shl nbits_wanted) + 1);
end;
procedure TRtcJPEGDecoder.look_nbits(var reservoir: longint; var nbits_in_reservoir: byte;
var stream: PByte; const nbits_wanted: byte; var Result: longint);
begin
fill_nbits(reservoir, nbits_in_reservoir, stream, nbits_wanted);
Result := reservoir shr (nbits_in_reservoir - nbits_wanted);
end;
(* To speed up the decoding, we assume that the reservoir have enough bit
* slow version:
* #define skip_nbits(reservoir,nbits_in_reservoir,stream,nbits_wanted) do { \
* fill_nbits(reservoir,nbits_in_reservoir,stream,(nbits_wanted)); \
* nbits_in_reservoir -= (nbits_wanted); \
* reservoir &= ((1U<<nbits_in_reservoir)-1); \
* } while(0);
*)
procedure TRtcJPEGDecoder.skip_nbits(var reservoir: longint; var nbits_in_reservoir: byte;
var stream: PByte; const nbits_wanted: byte);
begin
// fill_nbits(reservoir,nbits_in_reservoir,stream,nbits_wanted);
Dec(nbits_in_reservoir, nbits_wanted);
reservoir := reservoir and ((longint(1) shl nbits_in_reservoir) - 1);
end;
function TRtcJPEGDecoder.get_one_bit(var reservoir: longint; var nbits_in_reservoir: byte; var stream: PByte):boolean;
begin
fill_nbits(reservoir, nbits_in_reservoir, stream, 1);
Result := (reservoir shr (nbits_in_reservoir - 1))>0;
Dec(nbits_in_reservoir, 1);
reservoir := reservoir and ((longint(1) shl nbits_in_reservoir) - 1);
end;
function TRtcJPEGDecoder.be16_to_cpu(x: PByte): word;
begin
Result := x^ shl 8;
Inc(x);
Result := Result or x^;
end;
(* *
* Get the next (valid) huffman code in the stream.
*
* To speedup the procedure, we look HUFFMAN_HASH_NBITS bits and the code is
* lower than HUFFMAN_HASH_NBITS we have automaticaly the length of the code
* and the value by using two lookup table.
* Else if the value is not found, just search (linear) into an array for each
* bits is the code is present.
*
* If the code is not present for any reason, -1 is return.
*)
function TRtcJPEGDecoder.get_next_huffman_code(var huffman_tbl: huffman_table): longint;
var
value: smallint;
hcode: longint;
extra_nbits, nbits: longint;
slowtable: ^word;
code_size: longword;
begin
look_nbits(priv.reservoir, priv.nbits_in_reservoir, priv.stream,
HUFFMAN_HASH_NBITS, hcode);
value := huffman_tbl.lookup[hcode];
if (value >= 0) then
begin
code_size := huffman_tbl.code_size[value];
skip_nbits(priv.reservoir, priv.nbits_in_reservoir, priv.stream, code_size);
Result := value;
end
else
begin
// Decode more bits each time ...
for extra_nbits := 0 to 16 - HUFFMAN_HASH_NBITS - 1 do
begin
nbits := HUFFMAN_HASH_NBITS + 1 + extra_nbits;
look_nbits(priv.reservoir, priv.nbits_in_reservoir, priv.stream,
nbits, hcode);
slowtable := Addr(huffman_tbl.slowtable[extra_nbits]);
// Search if the code is in this array
while slowtable^ <> 0 do
begin
if (slowtable^ = hcode) then
begin
skip_nbits(priv.reservoir, priv.nbits_in_reservoir,
priv.stream, nbits);
Inc(slowtable);
Result := slowtable^;
Exit;
end;
Inc(slowtable, 2);
end;
end;
Result := 0;
end;
end;
(* *
*
* Decode a single block that contains the DCT coefficients.
* The table coefficients is already dezigzaged at the end of the operation.
*
*)
function TRtcJPEGDecoder.process_Huffman_data_unit(component: longint; var previous_DC:SmallInt):boolean;
var
j: byte;
huff_code: longword;
size_val, count_0: byte;
DCT: array [0 .. 63] of longint;
c: ^jpeg_component;
begin
c := Addr(priv.component_infos[component]);
// Initialize the DCT coef table
FillChar(DCT[0], SizeOf(DCT), 0);
// DC coefficient decoding
huff_code := get_next_huffman_code(c^.DC_table);
if huff_code <> 0 then
begin
get_nbits(priv.reservoir, priv.nbits_in_reservoir, priv.stream, huff_code, DCT[0]);
Inc(DCT[0], previous_DC);
previous_DC := DCT[0];
end
else
DCT[0] := previous_DC;
// AC coefficient decoding
j := 1;
while (j < 64) do
begin
huff_code := get_next_huffman_code(c^.AC_table);
size_val := huff_code and $F;
count_0 := huff_code shr 4;
if size_val = 0 then
begin
// RLE
if count_0 = 0 then
break // EOB found, go out
else if count_0 = $F then
Inc(j, 16); // skip 16 zeros
end
else
begin
Inc(j, count_0); // skip count_0 zeroes
if (j >= 64) then
begin
Result:=False;
Exit; // raise Exception.Create('Bad huffman data');
end;
get_nbits(priv.reservoir, priv.nbits_in_reservoir, priv.stream, size_val, DCT[j]);
Inc(j);
end;
end;
for j := 0 to 63 do
c.DCT[j] := DCT[zigzag[j]];
Result:=True;
end;
(*
* Takes two array of bits, and build the huffman table for size, and code
*
* lookup will return the symbol if the code is less or equal than HUFFMAN_HASH_NBITS.
* code_size will be used to known how many bits this symbol is encoded.
* slowtable will be used when the first lookup didn't give the result.
*)
procedure TRtcJPEGDecoder.build_huffman_table(const bits: ByteArr17; vals: PByte;
var table: huffman_table);
var
i, j, code, code_size, val, nbits: longword;
huffsize: array [0 .. HUFFMAN_BITS_SIZE] of byte;
hz: ^byte;
huffcode: array [0 .. HUFFMAN_BITS_SIZE] of word;
hc: ^word;
// next_free_entry:longint;
rep: longint;
slowtable: ^word;
begin
(*
* Build a temp array
* huffsize[X] => numbers of bits to write vals[X]
*)
hz := Addr(huffsize);
for i := 1 to 16 do
begin
for j := 1 to bits[i] do
begin
hz^ := i;
Inc(hz);
end;
end;
hz^ := 0;
FillChar(table.lookup, SizeOf(table.lookup), $FF);
for i := 0 to 16 - HUFFMAN_HASH_NBITS - 1 do
table.slowtable[i][0] := 0;
// Build a temp array, huffcode[X] => code used to write vals[X]
code := 0;
hc := Addr(huffcode[0]);
hz := Addr(huffsize[0]);
nbits := hz^;
while (hz^ <> 0) do
begin
while (hz^ = nbits) do
begin
hc^ := code;
Inc(hc);
Inc(code);
Inc(hz);
end;
code := code shl 1;
Inc(nbits);
end;
// Build the lookup table, and the slowtable if needed.
// next_free_entry := -1;
i := 0;
while huffsize[i] <> 0 do
begin
val := vals^;
code := huffcode[i];
code_size := huffsize[i];
table.code_size[val] := code_size;
if (code_size <= HUFFMAN_HASH_NBITS) then
begin
// Good: val can be put in the lookup table, so fill all value of this column with value val
rep := longword(1) shl (HUFFMAN_HASH_NBITS - code_size);
code := code shl (HUFFMAN_HASH_NBITS - code_size);
while rep <> 0 do
begin
Dec(rep);
table.lookup[code] := val;
Inc(code);
end;
end
else
begin
// Perhaps sorting the array will be an optimization
slowtable := Addr(table.slowtable[code_size - HUFFMAN_HASH_NBITS - 1]);
while slowtable^ <> 0 do
Inc(slowtable, 2);
slowtable^ := code;
Inc(slowtable);
slowtable^ := val;
Inc(slowtable);
slowtable^ := 0;
// TODO: NEED TO CHECK FOR AN OVERFLOW OF THE TABLE */
end;
Inc(vals);
Inc(i);
end;
end;
procedure TRtcJPEGDecoder.build_default_huffman_tables;
begin
if ((priv.flags and TINYJPEG_FLAGS_MJPEG_TABLE) <> 0) and
(priv.default_huffman_table_initialized <> 0) then
Exit;
build_huffman_table(std_dc_luminance_nrcodes, Addr(std_dc_luminance_values),
priv.HTDC[0]);
build_huffman_table(std_ac_luminance_nrcodes, Addr(std_ac_luminance_values),
priv.HTAC[0]);
build_huffman_table(std_dc_chrominance_nrcodes,
Addr(std_dc_chrominance_values), priv.HTDC[1]);
build_huffman_table(std_ac_chrominance_nrcodes,
Addr(std_ac_chrominance_values), priv.HTAC[1]);
priv.default_huffman_table_initialized := 1;
end;
(* ******************************************************************************
*
* Colorspace conversion routine
*
*
* Note:
* YCbCr is defined per CCIR 601-1, except that Cb and Cr are
* normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
* The conversion equations to be implemented are therefore
* R = Y + 1.40200 * Cr
* G = Y - 0.34414 * Cb - 0.71414 * Cr
* B = Y + 1.77200 * Cb
*
***************************************************************************** *)
procedure TRtcJPEGDecoder.convert_to_BGR24(ColorMin,ColorMax:longint);
var
Y, Cb, Cr: PLongInt;
loc: longword;
i, j: longint;
_y, _cb, _cr: longint;
add_r, add_g, add_b: longint;
r, g, b: longint;
begin
loc := priv.location;
Y := Addr(priv.Y);
Cb := Addr(priv.Cb);
Cr := Addr(priv.Cr);
for i := 0 to 7 do
begin
for j := 0 to 7 do
begin
_y := longint(Y^) shl COLOR_SCALEBITS;
Inc(Y);
_cb := longint(Cb^) - COLOR_SCALECENTER;
Inc(Cb);
_cr := longint(Cr^) - COLOR_SCALECENTER;
Inc(Cr);
add_r := FIX_R * _cr + ONE_HALF;
add_g := -FIX_G1 * _cb - FIX_G2 * _cr + ONE_HALF;
add_b := FIX_B * _cb + ONE_HALF;
r := _y + add_r;
if r < colorMin then
BGR24_buffer[loc].R := 0
else if r > colorMax then
BGR24_buffer[loc].R := 255
else
BGR24_buffer[loc].R := r shr COLOR_DESCALEBITS;
g := _y + add_g;
if g < colorMin then
BGR24_buffer[loc].G := 0
else if g > colorMax then
BGR24_buffer[loc].G := 255
else
BGR24_buffer[loc].G := g shr COLOR_DESCALEBITS;
b := _y + add_b;
if b < colorMin then
BGR24_buffer[loc].B := 0
else if b > colorMax then
BGR24_buffer[loc].B := 255
else
BGR24_buffer[loc].B := b shr COLOR_DESCALEBITS;
Inc(loc);
end;
Inc(loc, Bitmap_Line - 8);
end;
end;
procedure TRtcJPEGDecoder.convert_to_RGB24(ColorMin,ColorMax:longint);
var
Y, Cb, Cr: PLongInt;
loc: longword;
i, j: longint;
_y, _cb, _cr: longint;
add_r, add_g, add_b: longint;
r, g, b: longint;
begin
loc := priv.location;
Y := Addr(priv.Y);
Cb := Addr(priv.Cb);
Cr := Addr(priv.Cr);
for i := 0 to 7 do
begin
for j := 0 to 7 do
begin
_y := longint(Y^) shl COLOR_SCALEBITS;
Inc(Y);
_cb := longint(Cb^) - COLOR_SCALECENTER;
Inc(Cb);
_cr := longint(Cr^) - COLOR_SCALECENTER;
Inc(Cr);
add_r := FIX_R * _cr + ONE_HALF;
add_g := -FIX_G1 * _cb - FIX_G2 * _cr + ONE_HALF;
add_b := FIX_B * _cb + ONE_HALF;
r := _y + add_r;
if r < colorMin then
RGB24_buffer[loc].R := 0
else if r > colorMax then
RGB24_buffer[loc].R := 255
else
RGB24_buffer[loc].R := r shr COLOR_DESCALEBITS;
g := _y + add_g;
if g < colorMin then
RGB24_buffer[loc].G := 0
else if g > colorMax then
RGB24_buffer[loc].G := 255
else
RGB24_buffer[loc].G := g shr COLOR_DESCALEBITS;
b := _y + add_b;
if b < colorMin then
RGB24_buffer[loc].B := 0
else if b > colorMax then
RGB24_buffer[loc].B := 255
else
RGB24_buffer[loc].B := b shr COLOR_DESCALEBITS;
Inc(loc);
end;
Inc(loc, Bitmap_Line - 8);
end;
end;
procedure TRtcJPEGDecoder.convert_to_BGR32(ColorMin,ColorMax:longint);
var
Y, Cb, Cr: PLongInt;
loc: longword;
i, j: longint;
_y, _cb, _cr: longint;
add_r, add_g, add_b: longint;
r, g, b: longint;
begin
loc := priv.location;
Y := Addr(priv.Y);
Cb := Addr(priv.Cb);
Cr := Addr(priv.Cr);
for i := 0 to 7 do
begin
for j := 0 to 7 do
begin
_y := longint(Y^) shl COLOR_SCALEBITS;
Inc(Y);
_cb := longint(Cb^) - COLOR_SCALECENTER;
Inc(Cb);
_cr := longint(Cr^) - COLOR_SCALECENTER;
Inc(Cr);
add_r := FIX_R * _cr + ONE_HALF;
add_g := -FIX_G1 * _cb - FIX_G2 * _cr + ONE_HALF;
add_b := FIX_B * _cb + ONE_HALF;
r := _y + add_r;
if r < colorMin then
BGR32_buffer[loc].R := 0
else if r > colorMax then
BGR32_buffer[loc].R := 255
else
BGR32_buffer[loc].R := r shr COLOR_DESCALEBITS;
g := _y + add_g;
if g < colorMin then
BGR32_buffer[loc].G := 0
else if g > colorMax then
BGR32_buffer[loc].G := 255
else
BGR32_buffer[loc].G := g shr COLOR_DESCALEBITS;
b := _y + add_b;
if b < colorMin then
BGR32_buffer[loc].B := 0
else if b > colorMax then
BGR32_buffer[loc].B := 255
else
BGR32_buffer[loc].B := b shr COLOR_DESCALEBITS;
BGR32_buffer[loc].A:=255;
Inc(loc);
end;
Inc(loc, Bitmap_Line - 8);
end;
end;
procedure TRtcJPEGDecoder.convert_to_RGB32(ColorMin,ColorMax:longint);
var
Y, Cb, Cr: PLongInt;
loc: longword;
i, j: longint;
_y, _cb, _cr: longint;
add_r, add_g, add_b: longint;
r, g, b: longint;
begin
loc := priv.location;
Y := Addr(priv.Y);
Cb := Addr(priv.Cb);
Cr := Addr(priv.Cr);
for i := 0 to 7 do
begin
for j := 0 to 7 do
begin
_y := longint(Y^) shl COLOR_SCALEBITS;
Inc(Y);
_cb := longint(Cb^) - COLOR_SCALECENTER;
Inc(Cb);
_cr := longint(Cr^) - COLOR_SCALECENTER;
Inc(Cr);
add_r := FIX_R * _cr + ONE_HALF;
add_g := -FIX_G1 * _cb - FIX_G2 * _cr + ONE_HALF;
add_b := FIX_B * _cb + ONE_HALF;
r := _y + add_r;
if r < colorMin then
RGB32_buffer[loc].R := 0
else if r > colorMax then
RGB32_buffer[loc].R := 255
else
RGB32_buffer[loc].R := r shr COLOR_DESCALEBITS;
g := _y + add_g;
if g < colorMin then
RGB32_buffer[loc].G := 0
else if g > colorMax then
RGB32_buffer[loc].G := 255
else
RGB32_buffer[loc].G := g shr COLOR_DESCALEBITS;
b := _y + add_b;
if b < colorMin then
RGB32_buffer[loc].B := 0
else if b > colorMax then
RGB32_buffer[loc].B := 255
else
RGB32_buffer[loc].B := b shr COLOR_DESCALEBITS;
RGB32_buffer[loc].A:=255;
Inc(loc);
end;
Inc(loc, Bitmap_Line - 8);
end;
end;
function TRtcJPEGDecoder.decode_MCU:shortint;
begin
if JPEG_HQMode then
begin
if get_one_bit(priv.reservoir, priv.nbits_in_reservoir, priv.stream) then
Result:=1
else
Result:=0;
end
else
Result:=0;
if JPEG_HQMode and (Result>0) then
begin
// Y
if not process_Huffman_data_unit(cY, priv.component_infos[cY].prev_DC2) then
begin
Result:=-1;
Exit;
end;
IDCT(priv.component_infos[cY].DCT, priv.component_infos[cY].Q_Table2, Addr(priv.Y));
// Cb
if not process_Huffman_data_unit(cCb, priv.component_infos[cCb].prev_DC2) then
begin
Result:=-1;
Exit;
end;
IDCT(priv.component_infos[cCb].DCT, priv.component_infos[cCb].Q_Table2, Addr(priv.Cb));
// Cr
if not process_Huffman_data_unit(cCr, priv.component_infos[cCr].prev_DC2) then
begin
Result:=-1;
Exit;
end;
IDCT(priv.component_infos[cCr].DCT, priv.component_infos[cCr].Q_Table2, Addr(priv.Cr));
end
else
begin
// Y
if not process_Huffman_data_unit(cY, priv.component_infos[cY].prev_DC) then
begin
Result:=-1;
Exit;
end;
IDCT(priv.component_infos[cY].DCT, priv.component_infos[cY].Q_Table, Addr(priv.Y));
// Cb
if not process_Huffman_data_unit(cCb, priv.component_infos[cCb].prev_DC) then
begin
Result:=-1;
Exit;
end;
IDCT(priv.component_infos[cCb].DCT, priv.component_infos[cCb].Q_Table, Addr(priv.Cb));
// Cr
if not process_Huffman_data_unit(cCr, priv.component_infos[cCr].prev_DC) then
begin
Result:=-1;
Exit;
end;
IDCT(priv.component_infos[cCr].DCT, priv.component_infos[cCr].Q_Table, Addr(priv.Cr));
end;
end;
(* ******************************************************************************
*
* JPEG/JFIF Parsing functions
*
* Note: only a small subset of the jpeg file format is supported. No markers,
* nor progressive stream is supported.
*
***************************************************************************** *)
procedure TRtcJPEGDecoder.build_quantization_table(var qtable: LongIntArr64; ref_table: PByteArr64);
const
aanscalefactor: array [0 .. 7] of JPEG_Float =
(1.0, 1.387039845, 1.306562965, 1.175875602,
1.0, 0.785694958, 0.541196100, 0.275899379);
var
i, j: longint;
k :byte;
begin
(* Taken from libjpeg. Copyright Independent JPEG Group's LLM idct.
* For float AA&N IDCT method, divisors are equal to quantization
* coefficients scaled by scalefactor[row]*scalefactor[col], where
* scalefactor[0] = 1
* scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
* We apply a further scale factor of 8.
* What's actually stored is 1/divisor so that the inner loop can
* use a multiplication rather than a division.
*)
k:=0;
for i := 0 to 7 do
for j := 0 to 7 do
begin
qtable[k] := trunc(ref_table[zigzag[k]] * aanscalefactor[i] * aanscalefactor[j] * FLOAT_SCALE);
Inc(k);
end;
end;
procedure TRtcJPEGDecoder.parse_DQT(stream: PByte);
var
len,qi: longint;
dqt_block_end: PByte;
begin
dqt_block_end := stream;
len:=be16_to_cpu(stream);
Inc(dqt_block_end, len);
JPEG_HQMode:=len>200;
Inc(stream, 2); // Skip length
while (stream <> dqt_block_end) do
begin
qi := stream^;
Inc(stream);
build_quantization_table(priv.Q_tables[qi], PByteArr64(stream));
Inc(stream, 64);
if JPEG_HQMode then
begin
build_quantization_table(priv.Q_tables2[qi], PByteArr64(stream));
Inc(stream, 64);
end;
end;
end;
procedure TRtcJPEGDecoder.parse_SOF(stream: PByte);
var
i, width, height, sampling_factor: longint;
Q_table: longint;
c: ^jpeg_component;
begin
Inc(stream, 2);
height := be16_to_cpu(stream);
Inc(stream, 2);
width := be16_to_cpu(stream);
sampling_factor := $11;
i:=0;
Q_table := 0;
c := Addr(priv.component_infos[i]);
c^.Vfactor := sampling_factor and $F;
c^.Hfactor := sampling_factor shr 4;
c^.Q_table := priv.Q_tables[Q_table];
c^.Q_table2 := priv.Q_tables2[Q_table];
i:=1;
Q_table := 1;
c := Addr(priv.component_infos[i]);
c^.Vfactor := sampling_factor and $F;
c^.Hfactor := sampling_factor shr 4;
c^.Q_table := priv.Q_tables[Q_table];
c^.Q_table2 := priv.Q_tables2[Q_table];
i:=2;
Q_table := 1;
c := Addr(priv.component_infos[i]);
c^.Vfactor := sampling_factor and $F;
c^.Hfactor := sampling_factor shr 4;
c^.Q_table := priv.Q_tables[Q_table];
c^.Q_table2 := priv.Q_tables2[Q_table];
priv.width := width;
priv.height := height;
end;
procedure TRtcJPEGDecoder.parse_DHT(stream: PByte);
var
count, i: longword;
huff_bits: ByteArr17;
table, length, index: longint;
begin
length := be16_to_cpu(stream) - 2;
Inc(stream, 2); // Skip length
while (length > 0) do
begin
index := stream^;
Inc(stream);
// We need to calculate the number of bytes 'vals' will takes
huff_bits[0] := 0;
count := 0;
for i := 1 to 16 do
begin
huff_bits[i] := stream^;
Inc(stream);
Inc(count, huff_bits[i]);
end;
if (index and $F0) <> 0 then
build_huffman_table(huff_bits, stream, priv.HTAC[index and $F])
else
build_huffman_table(huff_bits, stream, priv.HTDC[index and $F]);
Dec(length, 1);
Dec(length, 16);
Dec(length, count);
Inc(stream, count);
end;
i := 0;
table := 0;
priv.component_infos[i].AC_table := priv.HTAC[table and $F];
priv.component_infos[i].DC_table := priv.HTDC[table shr 4];
i := 1;
table := $11;
priv.component_infos[i].AC_table := priv.HTAC[table and $F];
priv.component_infos[i].DC_table := priv.HTDC[table shr 4];
i := 2;
table := $11;
priv.component_infos[i].AC_table := priv.HTAC[table and $F];
priv.component_infos[i].DC_table := priv.HTDC[table shr 4];
priv.stream := stream;
end;
procedure TRtcJPEGDecoder.parse_DRI(stream: PByte);
// var len:LongWord;
begin
// len := be16_to_cpu(stream);
Inc(stream, 2);
priv.restart_interval := be16_to_cpu(stream);
end;
procedure TRtcJPEGDecoder.resync;
var
i: longint;
begin
// Init DC coefficients
for i := 0 to JPEG_COMPONENTS - 1 do
begin
priv.component_infos[i].prev_DC := 0;
priv.component_infos[i].prev_DC2 := 0;
end;
priv.reservoir := 0;
priv.nbits_in_reservoir := 0;
if priv.restart_interval > 0 then
priv.restarts_to_go := priv.restart_interval
else
priv.restarts_to_go := -1;
end;
procedure TRtcJPEGDecoder.find_next_rst_marker;
var
rst_marker_found: longint;
marker: longint;
stream: PByte;
begin
rst_marker_found := 0;
stream := priv.stream;
// Parse marker
while (rst_marker_found = 0) do
begin
while (stream^ <> $FF) do
Inc(stream);
// Skip any padding ff byte (this is normal)
while (stream^ = $FF) do
Inc(stream);
marker := stream^;
Inc(stream);
if ((RST + priv.last_rst_marker_seen) = marker) then
rst_marker_found := 1
else if (marker = EOI) then
Exit;
end;
priv.stream := stream;
Inc(priv.last_rst_marker_seen);
priv.last_rst_marker_seen := priv.last_rst_marker_seen and 7;
end;
function TRtcJPEGDecoder.parse_JFIF(stream: PByte):boolean;
var
chuck_len: longint;
marker: longint;
dht_marker_found: longint;
next_chunck: PByte;
begin
dht_marker_found := 0;
// Parse marker
while (dht_marker_found = 0) do
begin
if (stream^ <> $FF) then
begin
Result:=False;
Exit; // raise Exception.Create('JPEG read error');
end;
Inc(stream);
// Skip any padding ff byte (this is normal)
while (stream^ = $FF) do
Inc(stream);
marker := stream^;
Inc(stream);
chuck_len := be16_to_cpu(stream);
next_chunck := stream;
Inc(next_chunck, chuck_len);
case marker of
SOF:
parse_SOF(stream);
DQT:
parse_DQT(stream);
DHT:
begin
parse_DHT(stream);
dht_marker_found := 1;
end;
DRI:
parse_DRI(stream);
end;
stream := next_chunck;
end;
if (dht_marker_found = 0) then
build_default_huffman_tables;
Result:=True;
end;
(* ******************************************************************************
*
* Functions exported of the library.
*
* Note: Some applications can access directly to internal pointer of the
* structure. It's is not recommended, but if you have many images to
* uncompress with the same parameters, some functions can be called to speedup
* the decoding.
*
***************************************************************************** *)
(* *
* Allocate a new tinyjpeg decoder object.
*
* Before calling any other functions, an object need to be called.
*)
procedure TRtcJPEGDecoder.tinyjpeg_init;
begin
FillChar(priv, SizeOf(priv), 0);
end;
(* *
* Initialize the tinyjpeg object and prepare the decoding of the stream.
*
* Check if the jpeg can be decoded with this jpeg decoder.
* Fill some table used for preprocessing.
*)
function TRtcJPEGDecoder.tinyjpeg_parse_header(buf: PByte; size: longword):boolean;
begin
Inc(buf, 2);
priv.stream_begin := buf;
priv.stream_length := size - 2;
priv.stream_end := priv.stream_begin;
Inc(priv.stream_end, priv.stream_length);
Result:=parse_JFIF(priv.stream_begin);
end;
function TRtcJPEGDecoder.tinyjpeg_parse_header_diff(bufHeader, buffData: PByte; sizeHeader, sizeData: longword):boolean;
begin
Inc(bufHeader, 2);
priv.stream_begin := bufHeader;
priv.stream_length := sizeHeader - 2;
priv.stream_end := priv.stream_begin;
Inc(priv.stream_end, priv.stream_length);
Result:=parse_JFIF(priv.stream_begin);
if Result then
begin
priv.stream_begin := buffData;
priv.stream_length := sizeData;
priv.stream_end := priv.stream_begin;
priv.stream:=priv.stream_begin;
Inc(priv.stream_end, priv.stream_length);
end;
end;
(*
static const decode_MCU_fct decode_mcu_3comp_table = decode_MCU_1x1_3planes;
static const decode_MCU_fct decode_mcu_1comp_table = decode_MCU_1x1_1plane;
static const convert_colorspace_fct convert_colorspace_rgb24 = YCrCB_to_RGB24_1x1;
*)
function TRtcJPEGDecoder.tinyjpeg_decode:boolean;
var
Xpos, Ypos: integer;
dm: shortint;
begin
resync;
// Just decode the image by macroblock (size is 8x8, 8x16, or 16x16)
for Ypos := 0 to (Yimage shr 3) - 1 do
begin
if Bitmap_Line<0 then
priv.location := (Yimage-1-(ypos shl 3)) * Bitmap_Width
else
priv.location := (ypos shl 3)* Bitmap_Width;
for Xpos:=0 to (Ximage shr 3)-1 do
begin
dm:=decode_MCU;
if dm>0 then
ConvertToBitmap(JPEG_HQCOLOR_MIN, JPEG_HQCOLOR_MAX)
else if dm=0 then
ConvertToBitmap(JPEG_COLOR_MIN, JPEG_COLOR_MAX)
else
begin
Result:=False;
Exit;
end;
if (priv.restarts_to_go > 0) then
begin
Dec(priv.restarts_to_go);
if (priv.restarts_to_go = 0) then
begin
Dec(priv.stream, priv.nbits_in_reservoir div 8);
resync;
find_next_rst_marker;
end;
end;
Inc(priv.location,8);
end;
end;
Result:=True;
end;
function TRtcJPEGDecoder.tinyjpeg_decode_diff:boolean;
var
Xpos, Ypos: integer;
Xlen, Ylen: word;
b:Byte;
w:Word;
d:LongWord;
toSkip,toPaint:LongWord;
dm:shortint;
function nextnumber2:longword;
begin
b:=Info_Buffer^;Inc(Info_Buffer);
if b<254 then
Result:=b
else if b=254 then
begin
w:=Info_Buffer^; Inc(Info_Buffer);
w:=(w shl 8) or Info_Buffer^; Inc(Info_Buffer);
Result:=w;
end
else
begin
d:=Info_Buffer^; Inc(Info_Buffer);
d:=(d shl 8) or Info_Buffer^; Inc(Info_Buffer);
d:=(d shl 8) or Info_Buffer^; Inc(Info_Buffer);
d:=(d shl 8) or Info_Buffer^; Inc(Info_Buffer);
Result:=d;
end;
end;
begin
resync;
// Just decode the image by macroblock (size is 8x8, 8x16, or 16x16)
toSkip:=nextnumber2;
if toSkip>0 then
toPaint:=0
else
toPaint:=nextnumber2;
Xlen:=Ximage shr 3;
Ylen:=Yimage shr 3;
for Ypos := 0 to Ylen - 1 do
begin
if toSkip>=XLen then
begin
Dec(toSkip,XLen);
if toSkip=0 then
toPaint:=nextnumber2;
end
else
begin
if Bitmap_Line<0 then
priv.location := (Yimage-1-(ypos shl 3)) * Bitmap_Width
else
priv.location := (ypos shl 3)* Bitmap_Width;
for Xpos:=0 to XLen-1 do
begin
if toSkip>0 then
begin
Dec(toSkip);
if toSkip=0 then
toPaint:=nextnumber2;
end
else
begin
dm:=decode_MCU;
if dm>0 then
ConvertToBitmap(JPEG_HQCOLOR_MIN, JPEG_HQCOLOR_MAX)
else if dm=0 then
ConvertToBitmap(JPEG_COLOR_MIN, JPEG_COLOR_MAX)
else
begin
Result:=False;
Exit;
end;
if (priv.restarts_to_go > 0) then
begin
Dec(priv.restarts_to_go);
if (priv.restarts_to_go = 0) then
begin
Dec(priv.stream, priv.nbits_in_reservoir div 8);
resync;
find_next_rst_marker;
end;
end;
Dec(toPaint);
if toPaint=0 then
toSkip:=nextnumber2;
end;
Inc(priv.location,8);
end;
end;
end;
Result:=True;
end;
procedure TRtcJPEGDecoder.tinyjpeg_get_size(var width,height: integer);
begin
width := priv.width;
height := priv.height;
end;
function TRtcJPEGDecoder.tinyjpeg_set_flags(flags: longint): longint;
begin
Result := priv.flags;
priv.flags := flags;
end;
procedure TRtcJPEGDecoder.LoadBitmap(Bmp: TRtcBitmapInfo);
begin
Ximage := Bmp.width;
Yimage := Bmp.height;
Buffer_Type:=Bmp.BuffType;
case Buffer_Type of
btBGR24:
begin
BGR24_buffer:=Bmp.Data;
ConvertToBitmap:=convert_to_BGR24;
end;
btBGRA32:
begin
BGR32_buffer:=Bmp.Data;
ConvertToBitmap:=convert_to_BGR32;
end;
btRGBA32:
begin
RGB32_buffer:=Bmp.Data;
ConvertToBitmap:=convert_to_RGB32;
end;
end;
Bitmap_Width:=Ximage;
if Bmp.Reverse then
Bitmap_Line:=-Bitmap_Width
else
Bitmap_Line:=Bitmap_Width;
end;
procedure TRtcJPegDecoder.UnLoadBitmap;
begin
BGR24_buffer:=nil;
BGR32_buffer:=nil;
RGB24_buffer:=nil;
RGB32_buffer:=nil;
end;
function TRtcJPEGDecoder.JPEGToBitmap(const JPEG:RtcByteArray; var bmp:TRtcBitmapInfo):boolean;
var
width, height: integer;
begin
tinyjpeg_init;
tinyjpeg_parse_header(PByte(Addr(JPEG[0])), length(JPEG));
tinyjpeg_get_size(width, height);
if width<>bmp.Width then
begin
Result:=False;
Exit;
end;
if height<>bmp.Height then
begin
Result:=False;
Exit;
end;
LoadBitmap(bmp);
try
Result:=tinyjpeg_decode;
finally
UnLoadBitmap;
end;
end;
function TRtcJPEGDecoder.JPEGDiffToBitmap(const JPEGHeader, JPEGData:RtcByteArray; var bmp:TRtcBitmapInfo):boolean;
var
width, height: integer;
jpeg_len,
info_len: longword;
begin
tinyjpeg_init;
jpeg_len:=length(JPEGData);
info_len:=JPEGData[jpeg_len-4];
info_len:=(info_len shl 8) or JPEGData[jpeg_len-3];
info_len:=(info_len shl 8) or JPEGData[jpeg_len-2];
info_len:=(info_len shl 8) or JPEGData[jpeg_len-1];
jpeg_len:=longword(length(JPEGData))-info_len-4;
if length(JPEGHeader)>0 then
Result:=tinyjpeg_parse_header_diff(PByte(Addr(JPEGHeader[0])), PByte(Addr(JPEGData[0])), length(JPEGHeader), jpeg_len)
else
Result:=tinyjpeg_parse_header(PByte(Addr(JPEGData[0])), jpeg_len);
if not Result then Exit;
if info_len>0 then
begin
Result:=False;
tinyjpeg_get_size(width, height);
if width<>bmp.Width then Exit;
if height<>bmp.Height then Exit;
LoadBitmap(bmp);
try
Info_Buffer:=PByte(Addr(JPEGData[jpeg_len]));
if tinyjpeg_decode_diff then Result:=True;
finally
UnLoadBitmap;
end;
end;
end;
constructor TRtcJPEGDecoder.Create;
begin
JPEG_HQMode:=False;
end;
destructor TRtcJPEGDecoder.Destroy;
begin
inherited;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Run-time Library }
{ Win32 LZ compresion interface unit }
{ }
{ Copyright (c) 1996,98 Inprise Corporation }
{ }
{*******************************************************}
unit LZExpand;
{$WEAKPACKAGEUNIT}
{$HPPEMIT '#include <lzexpand.h>'}
interface
uses Windows;
{ Error Return Codes }
const
{$EXTERNALSYM LZERROR_BADINHANDLE}
LZERROR_BADINHANDLE = -1; { invalid input handle }
{$EXTERNALSYM LZERROR_BADOUTHANDLE}
LZERROR_BADOUTHANDLE = -2; { invalid output handle }
{$EXTERNALSYM LZERROR_READ}
LZERROR_READ = -3; { corrupt compressed file format }
{$EXTERNALSYM LZERROR_WRITE}
LZERROR_WRITE = -4; { out of space for output file }
{$EXTERNALSYM LZERROR_GLOBALLOC}
LZERROR_GLOBALLOC = -5; { insufficient memory for LZFile struct }
{$EXTERNALSYM LZERROR_GLOBLOCK}
LZERROR_GLOBLOCK = -6; { bad global handle }
{$EXTERNALSYM LZERROR_BADVALUE}
LZERROR_BADVALUE = -7; { input parameter out of acceptable range }
{$EXTERNALSYM LZERROR_UNKNOWNALG}
LZERROR_UNKNOWNALG = -8; { compression algorithm not recognized }
{ Prototypes }
{$EXTERNALSYM LZCopy}
function LZCopy(Source, Dest: Integer): Longint; stdcall;
{$EXTERNALSYM LZInit}
function LZInit(Source: Integer): Integer; stdcall;
{$EXTERNALSYM GetExpandedNameA}
function GetExpandedNameA(Source, Buffer: PAnsiChar): Integer; stdcall;
{$EXTERNALSYM GetExpandedNameW}
function GetExpandedNameW(Source, Buffer: PWideChar): Integer; stdcall;
{$EXTERNALSYM GetExpandedName}
function GetExpandedName(Source, Buffer: PChar): Integer; stdcall;
{$EXTERNALSYM LZOpenFileA}
function LZOpenFileA(Filename: PAnsiChar; var ReOpenBuff: TOFStruct; Style: Word): Integer; stdcall;
{$EXTERNALSYM LZOpenFileW}
function LZOpenFileW(Filename: PWideChar; var ReOpenBuff: TOFStruct; Style: Word): Integer; stdcall;
{$EXTERNALSYM LZOpenFile}
function LZOpenFile(Filename: PChar; var ReOpenBuff: TOFStruct; Style: Word): Integer; stdcall;
{$EXTERNALSYM LZSeek}
function LZSeek(hFile: Integer; Offset: Longint; Origin: Integer): Longint; stdcall;
{$EXTERNALSYM LZRead}
function LZRead(hFile: Integer; Buffer: LPSTR; Count: Integer): Integer; stdcall;
{$EXTERNALSYM LZClose}
procedure LZClose(hFile: Integer); stdcall;
implementation
const
lz32 = 'LZ32.DLL';
function GetExpandedNameA; external lz32 name 'GetExpandedNameA';
function GetExpandedNameW; external lz32 name 'GetExpandedNameW';
function GetExpandedName; external lz32 name 'GetExpandedNameA';
procedure LZClose; external lz32 name 'LZClose';
function LZCopy; external lz32 name 'LZCopy';
function LZInit; external lz32 name 'LZInit';
function LZOpenFileA; external lz32 name 'LZOpenFileA';
function LZOpenFileW; external lz32 name 'LZOpenFileW';
function LZOpenFile; external lz32 name 'LZOpenFileA';
function LZRead; external lz32 name 'LZRead';
function LZSeek; external lz32 name 'LZSeek';
end.
|
unit typename_3;
interface
implementation
type
TRec = record
function GetName: string;
end;
function TRec.GetName: string;
begin
Result := typename(self);
end;
var S: string;
procedure Test;
var
R: TRec;
begin
S := R.GetName();
end;
initialization
Test();
finalization
Assert(S = 'TRec');
end. |
unit BandsInfo;
interface
uses
cxGridBandedTableView, System.Generics.Collections, System.Generics.Defaults,
ParameterKindEnum, cxGridDBBandedTableView, System.SysUtils;
type
TIDList = class(TList<Integer>)
public
procedure Assign(AArray: TArray<Integer>);
function eq(AArray: TArray<Integer>): Boolean;
function IsSame(AArray: TArray<Integer>): Boolean;
end;
TBandInfo = class(TObject)
private
FBand: TcxGridBand;
FDefaultCreated: Boolean;
FDefaultVisible: Boolean;
FIDList: TIDList;
FColIndex: Integer;
FIDParameter: Integer;
FIDParameterKind: Integer;
FIsDefault: Boolean;
FIDParamSubParam: Integer;
FPos: Integer;
protected
public
constructor Create(const ABand: TcxGridBand;
AIDList: TArray<Integer>); overload;
destructor Destroy; override;
procedure FreeBand; virtual;
function HaveBand(OtherBand: TcxGridBand): Boolean; virtual;
procedure Hide; virtual;
procedure RestoreBandPosition;
procedure SaveBandPosition;
procedure UpdateBandPosition(AColIndex: Integer); virtual;
property Band: TcxGridBand read FBand write FBand;
property DefaultCreated: Boolean read FDefaultCreated write FDefaultCreated;
property DefaultVisible: Boolean read FDefaultVisible write FDefaultVisible;
property IDList: TIDList read FIDList;
property ColIndex: Integer read FColIndex write FColIndex;
property IDParameter: Integer read FIDParameter write FIDParameter;
property IDParameterKind: Integer read FIDParameterKind
write FIDParameterKind;
property IsDefault: Boolean read FIsDefault write FIsDefault;
property IDParamSubParam: Integer read FIDParamSubParam
write FIDParamSubParam;
property Pos: Integer read FPos write FPos;
end;
TBandsInfo = class(TObjectList<TBandInfo>)
private
protected
public
procedure FreeNotDefaultBands;
function GetChangedColIndex: TBandsInfo;
procedure HideDefaultBands;
procedure FreeBand(ABandInfo: TBandInfo);
function HaveDifferentPos: Boolean;
procedure RestoreBandPosition;
procedure SaveBandPosition;
function Search(ABand: TcxGridBand; TestResult: Boolean = False)
: TBandInfo; overload;
function SearchByColIndex(AColIndex: Integer; TestResult: Boolean = False)
: TBandInfo;
function SearchByIDList(const AIDList: TArray<Integer>;
TestResult: Boolean = False): TBandInfo;
function SearchByID(const AID: Integer; TestResult: Boolean = False)
: TBandInfo;
function SearchByIDParamSubParam(AIDParamSubParam: Integer;
TestResult: Boolean = False): TBandInfo;
end;
TDescComparer = class(TComparer<TBandInfo>)
public
function Compare(const Left, Right: TBandInfo): Integer; override;
end;
TColumnInfo = class(TObject)
private
FColIndex: Integer;
FBandIndex: Integer;
FGeneralColIndex: Integer;
FColumn: TcxGridDBBandedColumn;
FDefaultCreated: Boolean;
FOldGeneralColIndex: Integer;
FIDCategoryParam: Integer;
FIsDefault: Boolean;
FOrder: Integer;
public
constructor Create(AColumn: TcxGridDBBandedColumn;
AIDCategoryParam, AOrder: Integer;
ADefaultCreated, AIsDefault: Boolean); overload;
procedure FreeColumn; virtual;
function HaveColumn(OtherColumn: TcxGridBandedColumn): Boolean; virtual;
procedure RestoreColumnPosition;
procedure SetColumnPosition(ABandIndex, AColIndex: Integer); virtual;
procedure SaveColumnPosition;
property ColIndex: Integer read FColIndex write FColIndex;
property BandIndex: Integer read FBandIndex write FBandIndex;
property GeneralColIndex: Integer read FGeneralColIndex
write FGeneralColIndex;
property Column: TcxGridDBBandedColumn read FColumn write FColumn;
property DefaultCreated: Boolean read FDefaultCreated write FDefaultCreated;
property OldGeneralColIndex: Integer read FOldGeneralColIndex
write FOldGeneralColIndex;
property IDCategoryParam: Integer read FIDCategoryParam
write FIDCategoryParam;
property IsDefault: Boolean read FIsDefault write FIsDefault;
property Order: Integer read FOrder write FOrder;
end;
TColumnsInfo = class(TObjectList<TColumnInfo>)
protected
public
procedure FreeNotDefaultColumns;
function GetChangedGeneralColIndex: TArray<TColumnInfo>;
procedure RestoreColumnPosition;
function Search(AColumn: TcxGridDBBandedColumn; TestResult: Boolean = False)
: TColumnInfo; overload;
function Search(AIDCategoryParam: Integer; TestResult: Boolean = False)
: TColumnInfo; overload;
procedure UpdateGeneralIndexes(AColumns: TArray<TcxGridDBBandedColumn>);
procedure SaveColumnPosition;
end;
TBandInfoEx = class(TBandInfo)
private
FBands: TArray<TcxGridBand>;
protected
public
constructor Create(ABands: TArray<TcxGridBand>;
const AIDList: TArray<Integer>); reintroduce; overload;
constructor CreateAsDefault(AIDParamSubParam: Integer;
ABands: TArray<TcxGridBand>);
procedure FreeBand; override;
function HaveBand(OtherBand: TcxGridBand): Boolean; override;
procedure Hide; override;
procedure UpdateBandPosition(AColIndex: Integer); override;
property Bands: TArray<TcxGridBand> read FBands write FBands;
end;
TColumnInfoEx = class(TColumnInfo)
private
FColumns: TArray<TcxGridDBBandedColumn>;
public
constructor Create(AColumns: TArray<TcxGridDBBandedColumn>;
AIDCategoryParam, AOrder: Integer; ADefaultCreated, AIsDefault: Boolean);
reintroduce; overload;
procedure FreeColumn; override;
function HaveColumn(OtherColumn: TcxGridBandedColumn): Boolean; override;
procedure SetColumnPosition(ABandIndex, AColIndex: Integer); override;
property Columns: TArray<TcxGridDBBandedColumn> read FColumns
write FColumns;
end;
implementation
constructor TBandInfo.Create(const ABand: TcxGridBand;
AIDList: TArray<Integer>);
begin
inherited Create;
Assert(ABand <> nil);
FBand := ABand;
FIDList := TIDList.Create;
FIDList.AddRange(AIDList);
end;
destructor TBandInfo.Destroy;
begin
FreeAndNil(FIDList);
inherited;
end;
procedure TBandInfo.FreeBand;
begin
// разрушаем связанный с описанием бэнд
Band.Free;
Band := nil;
end;
function TBandInfo.HaveBand(OtherBand: TcxGridBand): Boolean;
begin
Assert(OtherBand <> nil);
Result := FBand = OtherBand;
end;
procedure TBandInfo.Hide;
begin
Band.Visible := False;
Band.VisibleForCustomization := False;
end;
procedure TBandInfo.RestoreBandPosition;
begin
// Восстанавливаем позицию бэнда
Band.Position.ColIndex := ColIndex;
end;
procedure TBandInfo.SaveBandPosition;
begin
// Сохраняем позицию бэнда
ColIndex := Band.Position.ColIndex;
end;
procedure TBandInfo.UpdateBandPosition(AColIndex: Integer);
begin
AColIndex := AColIndex;
Band.Position.ColIndex := AColIndex;
end;
procedure TBandsInfo.FreeNotDefaultBands;
var
ABandInfo: TBandInfo;
i: Integer;
begin
for i := Count - 1 downto 0 do
begin
ABandInfo := Items[i];
if ABandInfo.DefaultCreated then
Continue;
FreeBand(ABandInfo);
end;
end;
function TBandsInfo.GetChangedColIndex: TBandsInfo;
var
ABandInfo: TBandInfo;
begin
Result := TBandsInfo.Create;
Result.OwnsObjects := False;
for ABandInfo in Self do
begin
if ABandInfo.ColIndex <> ABandInfo.Band.Position.ColIndex then
Result.Add(ABandInfo);
end;
end;
function TBandsInfo.HaveDifferentPos: Boolean;
var
ABI: TBandInfo;
APos: Integer;
begin
Result := True;
APos := First.Pos;
for ABI in Self do
begin
if ABI.Pos <> APos then
Exit;
end;
Result := False;
end;
procedure TBandsInfo.HideDefaultBands;
var
ABandInfo: TBandInfo;
begin
for ABandInfo in Self do
if ABandInfo.DefaultCreated then
begin
ABandInfo.Hide;
end;
end;
procedure TBandsInfo.FreeBand(ABandInfo: TBandInfo);
begin
Assert(ABandInfo <> nil);
Assert(not ABandInfo.DefaultCreated);
// разрушаем бэнд
ABandInfo.FreeBand;
// Удаляем описание этого бэнда из списка
Remove(ABandInfo);
// Удаляем описание бэнда
// ABandInfo.Free;
end;
procedure TBandsInfo.RestoreBandPosition;
var
ABandInfo: TBandInfo;
begin
// Восстанавливаем позицию бэнда
for ABandInfo in Self do
ABandInfo.RestoreBandPosition;
end;
procedure TBandsInfo.SaveBandPosition;
var
ABandInfo: TBandInfo;
begin
// Сохраняем позицию бэнда
for ABandInfo in Self do
ABandInfo.SaveBandPosition;
end;
function TBandsInfo.Search(ABand: TcxGridBand; TestResult: Boolean = False)
: TBandInfo;
begin
Assert(ABand <> nil);
for Result in Self do
begin
if Result.HaveBand(ABand) then
Exit;
end;
Result := nil;
if TestResult then
Assert(False);
end;
function TBandsInfo.SearchByColIndex(AColIndex: Integer;
TestResult: Boolean = False): TBandInfo;
begin
Assert(AColIndex > 0);
for Result in Self do
begin
if Result.ColIndex = AColIndex then
Exit;
end;
Result := nil;
if TestResult then
Assert(False);
end;
function TBandsInfo.SearchByIDList(const AIDList: TArray<Integer>;
TestResult: Boolean = False): TBandInfo;
begin
for Result in Self do
begin
if Result.IDList.eq(AIDList) then
Exit;
end;
Result := nil;
if TestResult then
begin
Assert(False);
end;
end;
function TBandsInfo.SearchByID(const AID: Integer; TestResult: Boolean = False)
: TBandInfo;
begin
for Result in Self do
begin
if Result.IDList.IndexOf(AID) >= 0 then
Exit;
end;
Result := nil;
if TestResult then
Assert(False);
end;
function TBandsInfo.SearchByIDParamSubParam(AIDParamSubParam: Integer;
TestResult: Boolean = False): TBandInfo;
begin
Assert(AIDParamSubParam > 0);
for Result in Self do
begin
if (Result.IDParamSubParam = AIDParamSubParam) and (Result.IsDefault = True)
then
Exit;
end;
Result := nil;
if TestResult then
Assert(False);
end;
function TDescComparer.Compare(const Left, Right: TBandInfo): Integer;
begin
// Сортировка в обратном порядке
Result := -1 * (Left.ColIndex - Right.ColIndex);
end;
constructor TColumnInfo.Create(AColumn: TcxGridDBBandedColumn;
AIDCategoryParam, AOrder: Integer; ADefaultCreated, AIsDefault: Boolean);
begin
Assert(AColumn <> nil);
Assert(AIDCategoryParam > 0);
Assert(AOrder > 0);
FColumn := AColumn;
FIDCategoryParam := AIDCategoryParam;
FOrder := AOrder;
FDefaultCreated := ADefaultCreated;
FIsDefault := AIsDefault;
// Запоминаем позицию колонки
SaveColumnPosition;
end;
procedure TColumnInfo.FreeColumn;
begin
FColumn.Free;
end;
function TColumnInfo.HaveColumn(OtherColumn: TcxGridBandedColumn): Boolean;
begin
Result := FColumn = OtherColumn;
end;
procedure TColumnInfo.RestoreColumnPosition;
begin
// восстанавливаем позиции, в которых находились наши колонки
Column.Position.BandIndex := BandIndex;
Column.Position.ColIndex := ColIndex;
end;
procedure TColumnInfo.SetColumnPosition(ABandIndex, AColIndex: Integer);
begin
Column.Position.BandIndex := ABandIndex;
Column.Position.ColIndex := AColIndex;
// запоминаем, в какой позиции находятся наши колонки
// SaveColumnPosition;
end;
procedure TColumnInfo.SaveColumnPosition;
begin
// запоминаем, в какой позиции находятся наши колонки
BandIndex := Column.Position.BandIndex;
ColIndex := Column.Position.ColIndex;
end;
procedure TColumnsInfo.FreeNotDefaultColumns;
var
ACI: TColumnInfo;
i: Integer;
begin
for i := Count - 1 downto 0 do
begin
ACI := Items[i];
if ACI.DefaultCreated then
Continue;
// разрушаем колонку
ACI.FreeColumn;
// Удаляем описание этой колонки
Remove(ACI); // Тут описание должно разрушиться
//ACI.Free;
end;
end;
function TColumnsInfo.GetChangedGeneralColIndex: TArray<TColumnInfo>;
var
ACI: TColumnInfo;
L: TList<TColumnInfo>;
begin
L := TList<TColumnInfo>.Create;
try
for ACI in Self do
begin
if ACI.OldGeneralColIndex <> ACI.GeneralColIndex then
L.Add(ACI);
end;
Result := L.ToArray;
finally
FreeAndNil(L);
end;
end;
procedure TColumnsInfo.RestoreColumnPosition;
var
ACI: TColumnInfo;
begin
for ACI in Self do
begin
// Восстанавливаем позиции колонок
ACI.RestoreColumnPosition;
end;
end;
function TColumnsInfo.Search(AColumn: TcxGridDBBandedColumn;
TestResult: Boolean = False): TColumnInfo;
begin
Assert(AColumn <> nil);
for Result in Self do
begin
if Result.HaveColumn(AColumn) then
Exit;
end;
Result := nil;
if TestResult then
Assert(False);
end;
function TColumnsInfo.Search(AIDCategoryParam: Integer;
TestResult: Boolean = False): TColumnInfo;
begin
for Result in Self do
begin
if Result.IDCategoryParam = AIDCategoryParam then
Exit;
end;
Result := nil;
if TestResult then
Assert(False);
end;
procedure TColumnsInfo.UpdateGeneralIndexes
(AColumns: TArray<TcxGridDBBandedColumn>);
var
ACI: TColumnInfo;
AColumn: TcxGridDBBandedColumn;
i: Integer;
begin
i := 0;
for AColumn in AColumns do
begin
ACI := Search(AColumn);
// Если эта колонка не является колонкой-подпараметром
if ACI = nil then
Continue;
ACI.OldGeneralColIndex := ACI.GeneralColIndex;
ACI.GeneralColIndex := i;
Inc(i);
end;
end;
procedure TColumnsInfo.SaveColumnPosition;
var
ACI: TColumnInfo;
begin
for ACI in Self do
begin
// запоминаем, в какой позиции находятся наши колонки
ACI.SaveColumnPosition;
end;
end;
constructor TBandInfoEx.Create(ABands: TArray<TcxGridBand>;
const AIDList: TArray<Integer>);
begin
// В массиве должен быть хотя-бы один бэнд
Assert(Length(ABands) > 0);
inherited Create(ABands[0], AIDList);
// Все бэнды
FBands := ABands;
end;
constructor TBandInfoEx.CreateAsDefault(AIDParamSubParam: Integer;
ABands: TArray<TcxGridBand>);
begin
// В массиве должен быть хотя-бы один бэнд
Assert(Length(ABands) > 0);
Assert(AIDParamSubParam > 0);
// Главный бэнд
FBand := ABands[0];
// Все бэнды
FBands := ABands;
IsDefault := True;
DefaultCreated := True;
FIDParamSubParam := AIDParamSubParam;
FIDList := TIDList.Create;
end;
procedure TBandInfoEx.FreeBand;
var
ABand: TcxGridBand;
begin
// разрушаем связанные с описанием бэнды
for ABand in FBands do
begin
ABand.Free;
end;
// В массиве больше нет ссылок на бэнды
SetLength(FBands, 0);
end;
function TBandInfoEx.HaveBand(OtherBand: TcxGridBand): Boolean;
var
ABand: TcxGridBand;
begin
Assert(OtherBand <> nil);
Result := False;
for ABand in FBands do
begin
if ABand = OtherBand then
begin
Result := True;
Exit;
end;
end;
end;
procedure TBandInfoEx.Hide;
var
ABand: TcxGridBand;
begin
for ABand in FBands do
begin
ABand.Visible := False;
ABand.VisibleForCustomization := False;
end;
end;
procedure TBandInfoEx.UpdateBandPosition(AColIndex: Integer);
var
ABand: TcxGridBand;
begin
inherited;
for ABand in Bands do
ABand.Position.ColIndex := AColIndex;
end;
constructor TColumnInfoEx.Create(AColumns: TArray<TcxGridDBBandedColumn>;
AIDCategoryParam, AOrder: Integer; ADefaultCreated, AIsDefault: Boolean);
begin
// В массиве колонок должна быть хотя бы одна колонка
Assert(Length(AColumns) > 0);
Create(AColumns[0], AIDCategoryParam, AOrder, ADefaultCreated, AIsDefault);
FColumns := AColumns;
end;
procedure TColumnInfoEx.FreeColumn;
var
AColumn: TcxGridBandedColumn;
begin
for AColumn in FColumns do
begin
AColumn.Free;
end;
SetLength(FColumns, 0);
end;
function TColumnInfoEx.HaveColumn(OtherColumn: TcxGridBandedColumn): Boolean;
var
AColumn: TcxGridBandedColumn;
begin
Result := False;
for AColumn in FColumns do
begin
if AColumn = OtherColumn then
begin
Result := True;
Exit;
end;
end;
end;
procedure TColumnInfoEx.SetColumnPosition(ABandIndex, AColIndex: Integer);
var
AColumn: TcxGridDBBandedColumn;
begin
inherited;
for AColumn in Columns do
begin
AColumn.Position.BandIndex := ABandIndex;
AColumn.Position.ColIndex := AColIndex;
end;
end;
procedure TIDList.Assign(AArray: TArray<Integer>);
begin
Self.Clear;
Self.AddRange(AArray);
end;
function TIDList.eq(AArray: TArray<Integer>): Boolean;
var
i: Integer;
begin
Result := Self.Count = Length(AArray);
if not Result then
Exit;
for i := 0 to Self.Count - 1 do
begin
Result := Items[i] = AArray[i];
if not Result then
Exit;
end;
end;
function TIDList.IsSame(AArray: TArray<Integer>): Boolean;
var
i: Integer;
begin
Result := Self.Count = Length(AArray);
if not Result then
Exit;
for i := 0 to high(AArray) do
begin
Result := (IndexOf(AArray[i]) >= 0);
if not Result then
Exit;
end;
end;
end.
|
unit SFV;
interface
uses
Classes, Common;
type
TCheckSumFileSFV = class(TCheckSumFile)
protected
sfvFile: string;
public
constructor Create(AFileName: string); override;
procedure ToStringList(slOut: TStringList); override;
function SingleFileChecksum(AFileName: string): string; override;
function MergeLine(AFileName, ACheckSum: string): string; override;
end;
function CalcFileCRC32(filename: string): string; overload;
procedure SFVFileToStringList(aSFVFile: string; slOut: TStringList);
implementation
uses
Windows, SysUtils, CRC32, LongFilenameOperations;
function CalcFileCRC32(filename: string): string; overload;
var
checksum: DWORD;
totalbytes: TInteger8;
error: Word;
begin
CRC32.CalcFileCRC32(filename, checksum, totalbytes, error);
if error = 0 then
result := IntToHex(checksum, 8)
else
result := '';
end;
procedure SFVFileToStringList(aSFVFile: string; slOut: TStringList);
var
sLine: string;
originalFilename: string;
expectedChecksum: string;
fil: THandle;
csum: TChecksum;
firstLinePassed: boolean;
forceUTF8: boolean;
begin
if not FileExists(aSFVFile) then
exit;
MyAssignFile(fil, aSFVFile);
try
MyReset(fil);
firstLinePassed := false;
forceUTF8 := false;
while not MyEOF(fil) do
begin
MyReadLn(fil, sLine);
{$REGION 'Try UTF8 decode'}
if not firstLinePassed and (length(sLine)>2) and (sLine[1]=#$EF) and (sLine[2]=#$BB) and (sLine[3]=#$BF) then
begin
delete(sLine,1,3); // Remove BOM
forceUTF8 := true;
end;
firstLinePassed := true;
if forceUTF8 or (Pos(#$FFFD, Utf8ToString(RawByteString(sLine))) = 0) then
sLine := Utf8ToString(RawByteString(sLine));
{$ENDREGION}
if Copy(Trim(sLine),1,1) = ';' then continue;
// Example.doc 4323C92B
sLine := TrimRight(sLine); // Trim right, because file names may have leading white spaces
if sLine = '' then
continue;
expectedChecksum := Copy(sLine, 1+Length(sLine)-8, 8);
sLine := TrimRight(Copy(sLine, 1, Length(sLine)-8)); // Trim right, because file names may have leading white spaces
originalFilename := sLine;
//slOut.Values[originalFilename] := expectedChecksum; // <-- with this, files cannot have an equal sign
slOut.OwnsObjects := true;
csum := TChecksum.Create;
csum.checksum := expectedChecksum;
slOut.AddObject(originalFilename, csum);
end;
finally
MyCloseFile(fil);
end;
end;
{ TCheckSumFileSFV }
constructor TCheckSumFileSFV.Create(AFileName: string);
begin
inherited;
sfvFile := AFileName;
if not SameText(ExtractFileExt(AFileName),'.sfv') then
raise Exception.Create('Invalid checksum file extension.');
end;
function TCheckSumFileSFV.MergeLine(AFileName, ACheckSum: string): string;
begin
result := AFileName + ' ' + ACheckSum;
end;
function TCheckSumFileSFV.SingleFileChecksum(AFileName: string): string;
begin
result := CalcFileCRC32(AFileName);
end;
procedure TCheckSumFileSFV.ToStringList(slOut: TStringList);
begin
inherited;
SFVFileToStringList(sfvFile, slOut);
end;
end.
|
unit ExpenseMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseDocked, Vcl.StdCtrls, RzLabel,
Vcl.ExtCtrls, RzPanel, Vcl.Mask, RzEdit, RzDBEdit, Vcl.DBCtrls, RzDBCmbo,
RzBtnEdt, Data.DB, Vcl.Grids, Vcl.DBGrids, RzDBGrid, ExpenseController, SaveIntf,
RzCmboBx, RzGrids, Vcl.Imaging.pngimage, RzTabs, RzLstBox, RzButton;
type
TfrmExpenseMain = class(TfrmBaseDocked, ISave)
Label1: TLabel;
Label2: TLabel;
dtePaymentDate: TRzDBDateTimeEdit;
edReceipt: TRzDBEdit;
pnlDetail: TRzPanel;
grDetailStringGrid: TRzStringGrid;
grDetail: TRzDBGrid;
pnlAddPayment: TRzPanel;
imgAddExpense: TImage;
pnlDeletePayment: TRzPanel;
imgDeleteExpense: TImage;
RzPageControl1: TRzPageControl;
tsDetail: TRzTabSheet;
TabSheet2: TRzTabSheet;
RzTabSheet1: TRzTabSheet;
Label5: TLabel;
dbluLoanClass: TRzDBLookupComboBox;
Label7: TLabel;
edAppAmount: TRzDBNumericEdit;
RzDBNumericEdit1: TRzDBNumericEdit;
Label3: TLabel;
Label4: TLabel;
RzDBNumericEdit2: TRzDBNumericEdit;
mmDescription: TRzDBMemo;
Label6: TLabel;
lbGroups: TRzListBox;
pnlAdd: TRzPanel;
sbtnAdd: TRzShapeButton;
RzPanel1: TRzPanel;
RzShapeButton1: TRzShapeButton;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
FController: TExpenseController;
procedure PopulateItems;
public
{ Public declarations }
function Save: boolean;
procedure Cancel;
end;
implementation
{$R *.dfm}
uses
ExpenseData, FormsUtil, AccountTitle, IFinanceGlobal;
procedure TfrmExpenseMain.Cancel;
begin
end;
procedure TfrmExpenseMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FController.Free;
inherited;
end;
procedure TfrmExpenseMain.FormCreate(Sender: TObject);
begin
inherited;
dmExpense := TdmExpense.Create(self);
FController := TExpenseController.Create(dmExpense);
FController.Add;
// dteExpenseDate.Date := ifn.AppDate;
PopulateItems;
OpenDropdownDataSources(tsDetail);
end;
procedure TfrmExpenseMain.PopulateItems;
var
item: TAccountTitle;
begin
for item in FController.Titles do
begin
//cmbItem.AddItemValue(item.Name,item.Code);
end;
end;
function TfrmExpenseMain.Save: boolean;
begin
with FController do
begin
//Expense.ExpenseDate := dteExpenseDate.Date;
//Expense.TitleName := cmbItem.Text;
//Expense.Amount := edExpenseAmount.Value;
//Expense.Cash := edCash.Value;
//Expense.Check := edCheck.Value;
Save;
end;
end;
end.
|
////////////////////////////////////////////
// Блок привязки одного канала для редактора объектов
////////////////////////////////////////////
unit Frame.EditPrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, GMGlobals, INIFiles, ExtCtrls, VirtualTrees, Frame.ObjectTree,
StrUtils, GMDBClasses, ConfigXML,
cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxScrollBox,
dxSkinsCore, cxLabel, cxTextEdit, cxMaskEdit, cxSplitter, cxColorComboBox, cxMemo, cxProgressBar,
cxDropDownEdit, cxCalendar, dxSkinscxPCPainter, dxBarBuiltInMenu, cxPC, cxTimeEdit, cxRadioGroup,
cxGroupBox, cxSpinEdit, cxCheckBox, cxButtonEdit, cxButtons, cxCheckListBox, cxListBox, cxListView,
cxImage, dxBevel, dxSkinOffice2010Silver;
type
TEditPrmWithDevicesFrm = class(TFrame)
Label1: TcxLabel;
cbDiagram: TcxCheckBox;
leDiagramMin: TcxTextEdit;
leDiagramMax: TcxTextEdit;
Bevel1: TdxBevel;
lNPrm: TcxLabel;
lePrefix: TcxTextEdit;
cmbImage: TcxComboBox;
Label2: TcxLabel;
Label3: TcxLabel;
leBarFloat: TcxTextEdit;
Label5: TcxLabel;
cmbDigits: TcxComboBox;
ePumpDownParam: TcxTextEdit;
eMainParam: TcxTextEdit;
lBarFloat: TcxLabel;
Label6: TcxLabel;
Label7: TcxLabel;
Label8: TcxLabel;
procedure leDevMinExit(Sender: TObject);
procedure ePumpDownParamDragOver(Sender, Source: TObject; X,
Y: Integer; State: TDragState; var Accept: Boolean);
procedure ePumpDownParamDragDrop(Sender, Source: TObject; X,
Y: Integer);
procedure eMainParamDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
procedure eMainParamDragDrop(Sender, Source: TObject; X, Y: Integer);
procedure eMainParamDblClick(Sender: TObject);
procedure ePumpDownParamKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
FXmlNode: IGMConfigChannelType;
function AcceptOnlyParams: bool;
procedure AssignID_PrmWithEdit(Edit: TcxTextEdit; prm: TGMBaseParam);
procedure AssignParamWithEdit(Edit: TcxTextEdit);
procedure ChekDelParam(Sender: TObject; Key: Word);
procedure LoadFromINI();
procedure InitControls();
protected
procedure SaveControlToINI(Sender: TObject);
procedure SetXMLNode(const Value: IGMConfigChannelType);
public
{ Public declarations }
frmTree: TObjTreeFrame;
property XmlNode: IGMConfigChannelType read FXmlNode write SetXMLNode;
procedure SaveToINI(Section: string);
constructor Create(AOwner: TComponent); override;
end;
implementation
{$R *.dfm}
{ TEditPrmFrm }
constructor TEditPrmWithDevicesFrm.Create(AOwner: TComponent);
begin
inherited;
Width := Bevel1.Width + 1;
Height := Bevel1.Top + Bevel1.Height + 1;
end;
procedure TEditPrmWithDevicesFrm.LoadFromINI();
begin
if XmlNode = nil then Exit;
InitControls();
leDiagramMin.Text := MyFloatToStr(XmlNode.Dmin);
leDiagramMax.Text := MyFloatToStr(XmlNode.Dmax);
lePrefix.Text := XmlNode.Prefix;
leBarFloat.Text := XmlNode.Barfloat;
cbDiagram.Checked := XmlNode.Diagram > 0;
AssignID_PrmWithEdit(eMainParam, ParamOrNodeChannel(XmlNode.DataChnType, XmlNode.Id_prm));
AssignID_PrmWithEdit(ePumpDownParam, GMNodeChannels.ByID(XmlNode.Pump_prm));
SelectCmbObject(cmbImage, XmlNode.Showtype, 0);
cmbDigits.ItemIndex := XmlNode.Digits;
end;
procedure TEditPrmWithDevicesFrm.SaveControlToINI(Sender: TObject);
begin
if Sender = ePumpDownParam then
begin
XmlNode.Pump_prm := 0;
if ePumpDownParam.Tag > 0 then
XmlNode.Pump_prm := TGMParam(ePumpDownParam.Tag).ID_Prm;
end;
if Sender = eMainParam then
begin
XmlNode.Id_prm := 0;
if eMainParam.Tag > 0 then
begin
XmlNode.Id_prm := TGMBaseParam(eMainParam.Tag).ID_Prm;
XmlNode.DataChnType := TGMBaseParam(eMainParam.Tag).DataChannelType;
end;
end;
if Sender = lePrefix then
XmlNode.Prefix := lePrefix.Text;
if Sender = leDiagramMin then
XmlNode.Dmin := EditToDouble(leDiagramMin);
if Sender = leDiagramMax then
XmlNode.Dmax := EditToDouble(leDiagramMax);
if Sender = leBarFloat then
XmlNode.Barfloat := MyFloatToStr(EditToDouble(leBarFloat));
if Sender = cmbDigits then
XmlNode.Digits := cmbDigits.ItemIndex;
if Sender = cmbImage then
XmlNode.Showtype := CmbSelectedObj(cmbImage);
if Sender = cbDiagram then
XmlNode.Diagram := int(cbDiagram.Checked);
end;
procedure TEditPrmWithDevicesFrm.SaveToINI(Section: string);
var i: int;
begin
for i := 0 to ControlCount - 1 do
SaveControlToINI(Controls[i]);
end;
procedure TEditPrmWithDevicesFrm.InitControls();
begin
cmbImage.Properties.Items.Clear();
if XmlNode.Num = 0 then
begin
// Это трэкбар
Label2.Caption := 'Бегунок';
cmbImage.Properties.Items.AddObject('Превышение', TObject(0));
cmbImage.Properties.Items.AddObject('Понижение', TObject(2));
cmbImage.Properties.Items.AddObject('Гистерезис', TObject(1));
ePumpDownParam.Visible:=false;
Label3.Visible:=false;
end
else
begin
// Это Edit
cmbImage.Properties.Items.AddObject('Цифра', TObject(0));
cmbImage.Properties.Items.AddObject('Насос', TObject(1));
leBarFloat.Visible := false;
lBarFloat.Visible := false;
end;
cmbImage.ItemIndex:=0;
lePrefix.Visible := XmlNode.Num > 0;
Label5.Visible := XmlNode.Num > 0;
cmbDigits.Visible := XmlNode.Num > 0;
lNPrm.Caption := IfThen( XmlNode.Num > 0, 'Цифровой индикатор ' + IntToStr(XmlNode.Num), 'Шкальный индикатор');
end;
procedure TEditPrmWithDevicesFrm.leDevMinExit(Sender: TObject);
begin
SaveControlToINI(Sender);
end;
procedure TEditPrmWithDevicesFrm.ePumpDownParamDragOver(Sender,
Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean);
begin
Accept := AcceptOnlyParams();
end;
procedure TEditPrmWithDevicesFrm.eMainParamDragOver(Sender,
Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean);
begin
Accept := AcceptOnlyParams();
end;
procedure TEditPrmWithDevicesFrm.ePumpDownParamDragDrop(Sender,
Source: TObject; X, Y: Integer);
begin
if frmTree.SelectedParam() is TGMParam then
AssignParamWithEdit(TcxTextEdit(Sender));
end;
procedure TEditPrmWithDevicesFrm.eMainParamDragDrop(Sender,
Source: TObject; X, Y: Integer);
begin
AssignParamWithEdit(TcxTextEdit(Sender));
end;
procedure TEditPrmWithDevicesFrm.eMainParamDblClick(Sender: TObject);
begin
frmTree.FindObject(TGMBaseParam(TCustomEdit(Sender).Tag));
end;
procedure TEditPrmWithDevicesFrm.ePumpDownParamKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
ChekDelParam(Sender, Key);
end;
procedure TEditPrmWithDevicesFrm.AssignID_PrmWithEdit(Edit: TcxTextEdit; prm: TGMBaseParam);
begin
Edit.Text := '';
Edit.Hint := '';
Edit.Tag := NativeInt(prm);
if prm <> nil then
begin
Edit.Text := prm.GetNameWithPath([ppcDev]);
Edit.Hint := prm.GetNameWithPath([ppcID, ppcSrc, ppcDev, ppcPT]);
end;
end;
procedure TEditPrmWithDevicesFrm.AssignParamWithEdit(Edit: TcxTextEdit);
begin
AssignID_PrmWithEdit(Edit, frmTree.SelectedParam());
SaveControlToINI(Edit);
end;
function TEditPrmWithDevicesFrm.AcceptOnlyParams(): bool;
begin
Result := frmTree.IsParamSelected();
end;
procedure TEditPrmWithDevicesFrm.ChekDelParam(Sender: TObject; Key: Word);
begin
if Key = VK_DELETE then
begin
TCustomEdit(Sender).Tag := 0;
TCustomEdit(Sender).Text := '';
TCustomEdit(Sender).Hint := '';
SaveControlToINI(Sender);
end;
end;
procedure TEditPrmWithDevicesFrm.SetXMLNode(const Value: IGMConfigChannelType);
begin
FXmlNode := Value;
LoadFromINI();
end;
end.
|
unit Test_FIToolkit.Reports.Parser.Messages;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework,
FIToolkit.Reports.Parser.Messages, FIToolkit.Reports.Parser.Types;
type
// Test methods for class TFixInsightMessages
TestTFixInsightMessages = class(TTestCase)
strict private
FFixInsightMessages: TFixInsightMessages;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestBeginEndUpdate;
procedure TestContains;
procedure TestSorted;
end;
implementation
uses
System.SysUtils;
procedure TestTFixInsightMessages.SetUp;
begin
FFixInsightMessages := TFixInsightMessages.Create;
end;
procedure TestTFixInsightMessages.TearDown;
begin
FFixInsightMessages.Free;
FFixInsightMessages := nil;
end;
procedure TestTFixInsightMessages.TestBeginEndUpdate;
begin
FFixInsightMessages.Sorted := True;
FFixInsightMessages.BeginUpdate;
try
CheckEquals(1, FFixInsightMessages.UpdateCount, 'UpdateCount = 1');
FFixInsightMessages.Add(TFixInsightMessage.Create(String.Empty, 4, 0, String.Empty, String.Empty));
FFixInsightMessages.Add(TFixInsightMessage.Create(String.Empty, 3, 0, String.Empty, String.Empty));
FFixInsightMessages.Add(TFixInsightMessage.Create(String.Empty, 2, 0, String.Empty, String.Empty));
FFixInsightMessages.Add(TFixInsightMessage.Create(String.Empty, 1, 0, String.Empty, String.Empty));
CheckEquals(1, FFixInsightMessages.Last.Line, 'Last.Line = 1');
finally
FFixInsightMessages.EndUpdate;
end;
CheckEquals(0, FFixInsightMessages.UpdateCount, 'UpdateCount = 0');
CheckEquals(1, FFixInsightMessages.First.Line, 'First.Line = 1');
end;
procedure TestTFixInsightMessages.TestContains;
var
Msg : TFixInsightMessage;
begin
FFixInsightMessages.Add(TFixInsightMessage.Create(String.Empty, 4, 0, String.Empty, String.Empty));
FFixInsightMessages.Add(TFixInsightMessage.Create(String.Empty, 3, 0, String.Empty, String.Empty));
FFixInsightMessages.Add(TFixInsightMessage.Create(String.Empty, 2, 0, String.Empty, String.Empty));
FFixInsightMessages.Add(TFixInsightMessage.Create(String.Empty, 1, 0, String.Empty, String.Empty));
Msg := FFixInsightMessages[3];
CheckTrue(FFixInsightMessages.Contains(Msg), 'CheckTrue::Contains(Msg)<Sorted = False>');
FFixInsightMessages.Sorted := True;
CheckTrue(FFixInsightMessages.Contains(Msg), 'CheckTrue::Contains(Msg)<Sorted = True>');
FFixInsightMessages.Remove(Msg);
CheckFalse(FFixInsightMessages.Contains(Msg), 'CheckFalse::Contains(Msg)');
end;
procedure TestTFixInsightMessages.TestSorted;
begin
FFixInsightMessages.Add(TFixInsightMessage.Create(String.Empty, 3, 0, String.Empty, String.Empty));
FFixInsightMessages.Add(TFixInsightMessage.Create(String.Empty, 2, 0, String.Empty, String.Empty));
CheckTrue((FFixInsightMessages[0].Line = 3) and (FFixInsightMessages[1].Line = 2), '[0] = 3 && [1] = 2');
FFixInsightMessages.Sorted := True;
CheckTrue((FFixInsightMessages[0].Line = 2) and (FFixInsightMessages[1].Line = 3), '[0] = 2 && [1] = 3');
FFixInsightMessages.Add(TFixInsightMessage.Create(String.Empty, 1, 0, String.Empty, String.Empty));
CheckTrue((FFixInsightMessages[0].Line = 1) and (FFixInsightMessages[1].Line = 2), '[0] = 1 && [1] = 2');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTFixInsightMessages.Suite);
end.
|
// Copyright 2021 Darian Miller, Licensed under Apache-2.0
// SPDX-License-Identifier: Apache-2.0
// More info: www.radprogrammer.com
unit radRTL.TOTP;
interface
uses
System.SysUtils,
radRTL.HOTP;
type
TTOTP = class(THOTP)
private const
TimeStepWindow = 30; // 30 is recommended value. "The prover and verifier MUST use the same time-step"
protected
class function GetCurrentUnixTimestamp():Int64;
public
/// <summary> TOTP: Time-Based One-Time Password Algorithm (most commonly used by Google Authenticaor)</summary>
class function GeneratePassword(const pBase32EncodedSecretKey:string; const pOutputLength:TOTPLength = TOTPLength.SixDigits):string; overload;
end;
implementation
uses
System.DateUtils;
class function TTOTP.GetCurrentUnixTimestamp():Int64;
begin
Result := DateTimeToUnix(TTimeZone.Local.ToUniversalTime(Now)) div TTOTP.TimeStepWindow;
end;
// https://datatracker.ietf.org/doc/html/rfc6238
class function TTOTP.GeneratePassword(const pBase32EncodedSecretKey:string; const pOutputLength:TOTPLength = TOTPLength.SixDigits):string;
begin
Result := THOTP.GeneratePassword(pBase32EncodedSecretKey, GetCurrentUnixTimestamp, pOutputLength);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.DBXCommonIndy;
interface
uses
System.SysUtils,
Data.DBXCommon,
IPPeerAPI
;
type
/// <summary>Indy wrapper implementation of TX500Principal.</summary>
TX500PrincipalIndy = class(TX500Principal)
protected
FIdX509Name : IIPX509Name;
FInstanceOwner : Boolean;
public
constructor Create(idX509Name: IIPX509Name; instanceOwner: Boolean = False); virtual;
destructor Destroy; override;
function GetName: string; override;
function GetEncoded: Longint; override;
end;
/// <summary>Indy wrapper implementation of TX509Certificate.</summary>
TX509CertificateIndy = class(TX509Certificate)
protected
FIdX509: IIPX509;
FSubjectPrincipal: TX500PrincipalIndy;
FIssuerPrincipal: TX500PrincipalIndy;
FInstanceOwner : Boolean;
public
constructor Create(CertFile: string); overload; virtual;
constructor Create(CertFile: string; const AIPImplementationID: string); overload; virtual;
constructor Create(CertFile: string; const AIPImplementationID: string; const certpassword: string); overload; virtual;
constructor Create(idX509: IIPX509; instanceOwner: Boolean = False); overload; virtual;
destructor Destroy; override;
{Inherited from the base Certificate class}
function GetEncoded: TArray<Byte>; override;
function GetPublicKey: TPublicKey; override;
function Verify(key: TPublicKey): Boolean; override;
{Inherited from the X.509 Certificate class}
procedure CheckValidity; overload; override;
procedure CheckValidity(ADate: TDateTime); overload; override;
function GetNotAfter: TDateTime; override;
function GetNotBefore: TDateTime; override;
function GetBasicConstraints: Integer; override;
function GetSerialNumber: string; override;
function GetVersion: LongInt; override;
function GetSigAlgName: string; override;
function GetSignature: string; override;
function GetIssuerX500Principal: TX500Principal; override;
function GetSubjectX500Principal: TX500Principal; override;
///<summary>
/// Determines the certificate file type, based on the file extension. Returns a TDBXX509_Filetypes integer constant
///</summary>
function GetFileType(CertFile: string): Integer;
end;
implementation
uses
System.Classes,
Data.DBXClientResStrs
;
type
TX509PublicKey = class(TPublicKey)
private
FIdX509: IIPX509;
public
constructor Create(IPX509: IIPX509);
function GetAlgorithm: string; override;
function GetFormat: string; override;
function GetEncoded: TArray<Byte>; override;
end;
{ TX509CertificateIndy }
constructor TX509CertificateIndy.Create(CertFile: string);
begin
Create(CertFile, '', '');
end;
constructor TX509CertificateIndy.Create(CertFile: string; const AIPImplementationID: string);
begin
Create(CertFile, AIPImplementationID, '');
end;
constructor TX509CertificateIndy.Create(CertFile: string; const AIPImplementationID: string; const certpassword: string);
var
data: TArray<Byte>;
dataPPtr: PPByte;
LInterface: IInterface;
filetype: Integer;
LM: TMemoryStream;
begin
Assert(FileExists(CertFile));
filetype := GetFileType(CertFile);
LM := TMemoryStream.Create;
try
try
LM.LoadFromFile(CertFile);
except
raise ECertificateParsingException.Create(SCertInvalidFile);
end;
case filetype of
TDBXX509_Filetypes.SSL_FILETYPE_DER:
begin
SetLength(data, LM.Size);
LM.Read(data[0], LM.Size);
dataPPtr := Addr(PByte(data));
LInterface := PeerFactory.CreatePeer(AIPImplementationID, IIPX509, IPProcs(AIPImplementationID)._d2i_X509(nil, dataPPtr, Length(data)),True);
end;
TDBXX509_Filetypes.SSL_FILETYPE_PEM:
begin
LInterface := PeerFactory.CreatePeer(AIPImplementationID, IIPX509, IPProcs(AIPImplementationID)._PEM_read_bio_X509(LM.Memory, LM.Size),True);
end;
TDBXX509_Filetypes.SSL_FILETYPE_P12:
begin
LInterface := PeerFactory.CreatePeer(AIPImplementationID, IIPX509, IPProcs(AIPImplementationID)._d2i_PKCS12_bio(LM.Memory, LM.Size, certpassword),True);
end;
end;
Create(LInterface as IIPX509, True);
finally
LM.Free;
end;
end;
constructor TX509CertificateIndy.Create(idX509: IIPX509; instanceOwner: Boolean = False);
begin
Assert(idX509 <> nil);
FIdX509 := idX509;
FInstanceOwner := instanceOwner;
end;
destructor TX509CertificateIndy.Destroy;
begin
if FInstanceOwner then
FIdX509 := nil;
FreeAndNil(FSubjectPrincipal);
FreeAndNil(FIssuerPrincipal);
inherited;
end;
function TX509CertificateIndy.GetFileType(CertFile: string): Integer;
var
CIn: TFileStream;
LCount: Integer;
CData: Byte;
begin
if SameFileName(ExtractFileExt(CertFile),'.p12') or SameFileName(ExtractFileExt(CertFile),'.pfx') then
Result := TDBXX509_Filetypes.SSL_FILETYPE_P12
else
if SameFileName(ExtractFileExt(CertFile),'.pem') then
Result := TDBXX509_Filetypes.SSL_FILETYPE_PEM
else
if SameFileName(ExtractFileExt(CertFile),'.der') then
Result := TDBXX509_Filetypes.SSL_FILETYPE_DER
else
if SameFileName(ExtractFileExt(CertFile),'.crt') or SameFileName(ExtractFileExt(CertFile),'.cet') then
begin //could be PEM or DER. check if file has binary (DER) or ascii contents (PEM)
Result := TDBXX509_Filetypes.SSL_FILETYPE_PEM;
CIn := TFileStream.Create(CertFile, fmOpenRead or fmShareDenyNone);
try
for LCount := 1 to CIn.Size do
begin
CIn.Read(CData, 1);
if (CData) > 127 then
begin
Result:= TDBXX509_Filetypes.SSL_FILETYPE_DER;
break;
end;
end;
finally
CIn.Free;
end;
end
else
raise ECertificateParsingException.Create(SCertInvalidFile);
end;
procedure TX509CertificateIndy.CheckValidity;
begin
CheckValidity(Now);
end;
procedure TX509CertificateIndy.CheckValidity(ADate: TDateTime);
begin
if ADate > FIdX509.notAfter then
raise ECertificateExpiredException.Create(SCertExpired);
if ADate < FIdX509.notBefore then
raise ECertificateNotYetValidException.Create(SCertNotYetValid);
end;
function TX509CertificateIndy.GetBasicConstraints: Integer;
begin
Result := FIdX509.BasicConstraints;
end;
function TX509CertificateIndy.GetEncoded: TArray<Byte>;
begin
Result := FIdX509.EncodedCertificate;
end;
function TX509CertificateIndy.GetIssuerX500Principal: TX500Principal;
begin
if FIssuerPrincipal = nil then
begin
FIssuerPrincipal := TX500PrincipalIndy.Create(FIdX509.Issuer);
end;
Result := FIssuerPrincipal;
end;
function TX509CertificateIndy.GetSubjectX500Principal: TX500Principal;
begin
if FSubjectPrincipal = nil then
begin
FSubjectPrincipal := TX500PrincipalIndy.Create(FIdX509.Subject);
end;
Result := FSubjectPrincipal;
end;
function TX509CertificateIndy.GetNotAfter: TDateTime;
begin
Result := FIdX509.notAfter;
end;
function TX509CertificateIndy.GetNotBefore: TDateTime;
begin
Result := FIdX509.notBefore;
end;
function TX509CertificateIndy.GetPublicKey: TPublicKey;
begin
Result := TX509PublicKey.Create(FIdX509);
end;
function TX509CertificateIndy.GetSerialNumber: string;
begin
Result := FIdX509.SerialNumber;
end;
function TX509CertificateIndy.GetSigAlgName: string;
begin
Result := FIdX509.SigInfo.SigTypeAsString;
end;
function TX509CertificateIndy.GetSignature: string;
begin
Result := FIdX509.SigInfo.Signature;
end;
function TX509CertificateIndy.GetVersion: LongInt;
begin
Result := FIdX509.Version;
end;
function TX509CertificateIndy.Verify(key: TPublicKey): Boolean;
begin
Result := FIdX509.Verify(TX509PublicKey(key).FIdX509);
end;
{ TX500PrincipalIndy }
constructor TX500PrincipalIndy.Create(idX509Name: IIPX509Name; instanceOwner: Boolean = False);
begin
Assert(idX509Name <> nil);
FIdX509Name := idX509Name;
FInstanceOwner := instanceOwner;
end;
destructor TX500PrincipalIndy.Destroy;
begin
if FInstanceOwner then
begin
FIdX509Name := nil;
end;
inherited;
end;
function TX500PrincipalIndy.GetEncoded: Longint;
begin
Result := FIdX509Name.Hash.L1;
end;
function TX500PrincipalIndy.GetName: string;
begin
Result := FIdX509Name.OneLine;
end;
{ TX509PublicKey }
constructor TX509PublicKey.Create(IPX509: IIPX509);
begin
inherited Create;
FIdX509 := IPX509;
end;
function TX509PublicKey.GetAlgorithm: string;
begin
Result := FIdX509.KeyAlgorithm;
end;
function TX509PublicKey.GetEncoded: TArray<Byte>;
begin
Result := FIdX509.EncodedKey;
end;
function TX509PublicKey.GetFormat: string;
begin
Result := FIdX509.KeyFormat;
end;
end.
|
unit RequestList;
interface
uses Windows, GMGenerics, GMGlobals, GM485, Generics.Collections;
type
TRequestCollection = class(TGMThreadSafeCollection<TSpecDevReqListItem>)
public
procedure ClearProcessed();
function HasRequestsWithPriority(priority: TRequestPriority): bool;
function CountRequestsWithPriority(priority: TRequestPriority): int;
function MaxPriority(): TRequestPriority;
procedure Add(reqDetails: TRequestDetails); reintroduce;
procedure EnlistRequestsWithPriority(list: TList<TSpecDevReqListItem>; priority: TRequestPriority; maxCount: int = 0);
procedure SortByPriority;
end;
implementation
uses
System.Generics.Defaults, System.Math;
{ TRequestCollection }
procedure TRequestCollection.ClearProcessed;
var i: int;
begin
Lock.BeginWrite();
try
for i := Count - 1 downto 0 do
if Items[i].Processed then
Delete(i);
finally
Lock.EndWrite();
end;
end;
function TRequestCollection.CountRequestsWithPriority(priority: TRequestPriority): int;
var
ri: TSpecDevReqListItem;
begin
Lock.BeginRead();
try
Result := 0;
for ri in self do
begin
if not ri.Processed and (ri.ReqDetails.Priority = priority) then
inc(Result);
end;
finally
Lock.EndRead();
end;
end;
procedure TRequestCollection.EnlistRequestsWithPriority(list: TList<TSpecDevReqListItem>; priority: TRequestPriority; maxCount: int = 0);
var
ri: TSpecDevReqListItem;
begin
Lock.BeginRead();
try
for ri in self do
begin
if (maxCount > 0) and (list.Count >= maxCount) then Exit;
if not ri.Processed and (ri.ReqDetails.Priority = priority) then
list.Add(ri);
end;
finally
Lock.EndRead();
end;
end;
function TRequestCollection.HasRequestsWithPriority(priority: TRequestPriority): bool;
begin
Result := CountRequestsWithPriority(priority) > 0;
end;
function TRequestCollection.MaxPriority: TRequestPriority;
var
ri: TSpecDevReqListItem;
begin
Lock.BeginRead();
try
Result := rqprNone;
for ri in self do
if not ri.Processed and (ri.ReqDetails.Priority > Result) then
Result := ri.ReqDetails.Priority;
finally
Lock.EndRead();
end;
end;
procedure TRequestCollection.SortByPriority;
begin
Sort(TComparer<TSpecDevReqListItem>.Construct(
function (const item1, item2: TSpecDevReqListItem): integer
begin
Result := CompareValue(ord(item1.ReqDetails.Priority), ord(item2.ReqDetails.Priority));
if Result = 0 then
Result := CompareValue(item1.ReqDetails.ID_Device, item2.ReqDetails.ID_Device);
end));
end;
procedure TRequestCollection.Add(reqDetails: TRequestDetails);
begin
Lock.BeginWrite();
try
inherited Add().ReqDetails := ReqDetails;
finally
Lock.EndWrite();
end;
end;
end.
|
unit darray_procs_2;
interface
implementation
var G: Int32;
procedure IncG(Delta: Int32);
begin
Inc(G, Delta);
end;
procedure DecG(Delta: Int32);
begin
Dec(G, Delta);
end;
procedure Test;
var
Arr: array of procedure(Delta: Int32);
begin
SetLength(Arr, 2);
Arr[0] := IncG;
Arr[1] := DecG;
Arr[0](5);
Arr[1](6);
end;
initialization
Test();
finalization
Assert(G = -1);
end. |
unit xTestDataInfo;
interface
uses System.Classes, System.SysUtils;
type
/// <summary>
/// 相线类别
/// </summary>
TPhaseType = ( tptThree, // 三相三线
tptFour // 三相四线
);
type
TSequenceType = (stABC, // 三线时为 AC
stACB,
stBAC,
stBCA,
stCAB,
stCBA // 三线时为 CA
);
type
/// <summary>
/// 三相功率状态
/// </summary>
TTestDataInfo = class
private
FPhaseType: TPhaseType;
FOU2U3: Double;
FOU1U2: Double;
FOU1U3: Double;
FU2: Double;
FU3: Double;
FU1: Double;
FI2: Double;
FI3: Double;
FO2: Double;
FO3: Double;
FI1: Double;
FO1: Double;
FIsCT2Reverse: Boolean;
FIsCT3Reverse: Boolean;
FUSequence: TSequenceType;
FIsCT1Reverse: Boolean;
FISequence: TSequenceType;
FIsPT2Reverse: Boolean;
FIsPT3Reverse: Boolean;
FIsPT1Reverse: Boolean;
FIsLoadL: Boolean;
procedure SetI1(const Value: Double);
procedure SetI2(const Value: Double);
procedure SetI3(const Value: Double);
procedure SetO1(const Value: Double);
procedure SetO2(const Value: Double);
procedure SetO3(const Value: Double);
procedure SetOU1U2(const Value: Double);
procedure SetOU1U3(const Value: Double);
procedure SetOU2U3(const Value: Double);
procedure SetU1(const Value: Double);
procedure SetU2(const Value: Double);
procedure SetU3(const Value: Double);
procedure SetIsCT1Reverse(const Value: Boolean);
procedure SetIsCT2Reverse(const Value: Boolean);
procedure SetIsCT3Reverse(const Value: Boolean);
procedure SetISequence(const Value: TSequenceType);
procedure SetIsPT1Reverse(const Value: Boolean);
procedure SetIsPT2Reverse(const Value: Boolean);
procedure SetIsPT3Reverse(const Value: Boolean);
procedure SetUSequence(const Value: TSequenceType);
procedure SetLoadL(const Value: Boolean);
public
/// <summary>
/// 相线类型
/// </summary>
property PhaseType : TPhaseType read FPhaseType write FPhaseType;
/// <summary>
/// 电压,电流
/// </summary>
property U1 : Double read FU1 write SetU1; // 三线时为U12
property U2 : Double read FU2 write SetU2; // 三线时为U32
property U3 : Double read FU3 write SetU3; // 三线时为U13
property I1 : Double read FI1 write SetI1;
property I2 : Double read FI2 write SetI2; // 三线时不用
property I3 : Double read FI3 write SetI3;
property O1 : Double read FO1 write SetO1; // 三线时为U12, I1夹角
property O2 : Double read FO2 write SetO2; // 三线时不用
property O3 : Double read FO3 write SetO3; // 三线时为U32, I3夹角
/// <summary>
/// 电压与电压之间夹角
/// </summary>
property OU1U2 : Double read FOU1U2 write SetOU1U2; // 三线时为U12, U32夹角
property OU1U3 : Double read FOU1U3 write SetOU1U3;
property OU2U3 : Double read FOU2U3 write SetOU2U3;
/// <summary>
/// 电压相序
/// </summary>
property USequence : TSequenceType read FUSequence write SetUSequence;
/// <summary>
/// 电流相序
/// </summary>
property ISequence : TSequenceType read FISequence write SetISequence;
/// <summary>
/// 负载性质 是否是容性
/// </summary>
property IsLoadL : Boolean read FIsLoadL write SetLoadL;
/// <summary>
/// PT1极性反
/// </summary>
property IsPT1Reverse : Boolean read FIsPT1Reverse write SetIsPT1Reverse;
/// <summary>
/// PT2极性反
/// </summary>
property IsPT2Reverse : Boolean read FIsPT2Reverse write SetIsPT2Reverse;
/// <summary>
/// PT3极性反
/// </summary>
property IsPT3Reverse : Boolean read FIsPT3Reverse write SetIsPT3Reverse;
/// <summary>
/// CT1极性反
/// </summary>
property IsCT1Reverse : Boolean read FIsCT1Reverse write SetIsCT1Reverse;
/// <summary>
/// CT2极性反
/// </summary>
property IsCT2Reverse : Boolean read FIsCT2Reverse write SetIsCT2Reverse;
/// <summary>
/// CT3极性反
/// </summary>
property IsCT3Reverse : Boolean read FIsCT3Reverse write SetIsCT3Reverse;
public
constructor Create;
/// <summary>
/// 清除
/// </summary>
procedure Clear;
end;
implementation
{ TTestDataInfo }
procedure TTestDataInfo.Clear;
begin
FU1 := 0;
FU2 := 0;
FU3 := 0;
FI1 := 0;
FI2 := 0;
FI3 := 0;
FO1 := 0;
FO2 := 0;
FO3 := 0;
FOU1U2 := 0;
FOU1U3 := 0;
FOU2U3 := 0;
end;
constructor TTestDataInfo.Create;
begin
FPhaseType := tptThree;
FIsPT1Reverse:= False;
FIsPT2Reverse:= False;
FIsPT3Reverse:= False;
FIsCT1Reverse:= False;
FIsCT2Reverse:= False;
FIsCT3Reverse:= False;
end;
procedure TTestDataInfo.SetI1(const Value: Double);
begin
end;
procedure TTestDataInfo.SetI2(const Value: Double);
begin
end;
procedure TTestDataInfo.SetI3(const Value: Double);
begin
end;
procedure TTestDataInfo.SetIsCT1Reverse(const Value: Boolean);
begin
FIsCT1Reverse := Value;
end;
procedure TTestDataInfo.SetIsCT2Reverse(const Value: Boolean);
begin
FIsCT2Reverse := Value;
end;
procedure TTestDataInfo.SetIsCT3Reverse(const Value: Boolean);
begin
FIsCT3Reverse := Value;
end;
procedure TTestDataInfo.SetISequence(const Value: TSequenceType);
begin
FISequence := Value;
end;
procedure TTestDataInfo.SetIsPT1Reverse(const Value: Boolean);
begin
FIsPT1Reverse := Value;
end;
procedure TTestDataInfo.SetIsPT2Reverse(const Value: Boolean);
begin
FIsPT2Reverse := Value;
end;
procedure TTestDataInfo.SetIsPT3Reverse(const Value: Boolean);
begin
FIsPT3Reverse := Value;
end;
procedure TTestDataInfo.SetLoadL(const Value: Boolean);
begin
FIsLoadL := Value;
end;
procedure TTestDataInfo.SetO1(const Value: Double);
begin
end;
procedure TTestDataInfo.SetO2(const Value: Double);
begin
end;
procedure TTestDataInfo.SetO3(const Value: Double);
begin
end;
procedure TTestDataInfo.SetOU1U2(const Value: Double);
begin
end;
procedure TTestDataInfo.SetOU1U3(const Value: Double);
begin
end;
procedure TTestDataInfo.SetOU2U3(const Value: Double);
begin
end;
procedure TTestDataInfo.SetU1(const Value: Double);
begin
end;
procedure TTestDataInfo.SetU2(const Value: Double);
begin
end;
procedure TTestDataInfo.SetU3(const Value: Double);
begin
end;
procedure TTestDataInfo.SetUSequence(const Value: TSequenceType);
begin
FUSequence := Value;
end;
end.
|
{На каждый чекбокс или другой элемент опций вешается процедура,
которая записывает его состояние во временный конфиг
Запись имён опций ведется по хинту с валидным для ini именем опции}
unit uOptions;
interface
uses
Windows, SysUtils, Classes, FileCtrl, Controls, Forms, StdCtrls, Vcl.ComCtrls,
uSettings, uLog, System.ImageList, Vcl.ImgList, Vcl.Buttons, Vcl.Menus,
Vcl.Imaging.pngimage, Vcl.ExtCtrls,uLocalization;
type
TfrmOptions = class(TForm)
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
btnOK: TButton;
chkMakeBackups: TCheckBox;
chkGenNewPass: TCheckBox;
chkPlaySounds: TCheckBox;
TabSheet3: TTabSheet;
chkReaskPass: TCheckBox;
chkClearClipOnMin: TCheckBox;
chkMinOnCopy: TCheckBox;
chkMinOnLink: TCheckBox;
chkAnvansedEdit: TCheckBox;
imlOptions: TImageList;
chkResizeTree: TCheckBox;
TabSheet4: TTabSheet;
btnCancel: TButton;
CheckBox1: TCheckBox;
Label1: TLabel;
udAutoLoginTime: TUpDown;
txtAutoLoginCount: TEdit;
lblBackupsCount: TLabel;
udBackupsCount: TUpDown;
txtBackupsCount: TEdit;
txtBackupFolder: TEdit;
lblBackupFolder: TLabel;
btnSelBackupFolder: TSpeedButton;
btnBackupNow: TButton;
Label2: TLabel;
imgBackup: TImage;
chkTreeRowSelect: TCheckBox;
CheckBox3: TCheckBox;
Edit1: TEdit;
UpDown1: TUpDown;
Label3: TLabel;
chkMakeBackupsCh: TCheckBox;
bhBackup: TBalloonHint;
btnAssociateFiles: TButton;
Label4: TLabel;
cmbLanguages: TComboBox;
lblLanguages: TLabel;
procedure FormShow(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
constructor Create(AOwner: TComponent; tempSettings: TSettings); reintroduce;
procedure ChangeValue(Sender: TObject);
procedure udBackupsCountClick(Sender: TObject; Button: TUDBtnType);
procedure btnSelBackupFolderClick(Sender: TObject);
procedure chkMakeBackupsClick(Sender: TObject);
procedure btnBackupNowClick(Sender: TObject);
procedure txtBackupFolderExit(Sender: TObject);
procedure txtBackupFolderChange(Sender: TObject);
procedure imgBackupClick(Sender: TObject);
procedure btnAssociateFilesClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
Cfg: TSettings;
procedure ReadConfiguration;
public
{ Public declarations }
end;
var
frmOptions: TfrmOptions;
implementation
uses Logic, uStrings, RyMenus;
{$R *.dfm}
procedure TfrmOptions.btnSelBackupFolderClick(Sender: TObject);
var
ChosenDir: String;
begin
//ChosenDir:= ExtractFilePath(Application.ExeName);
if SelectDirectory(rsSelectBackupDirectoryDialog, '', ChosenDir) then
txtBackupFolder.Text:=ChosenDir;
end;
procedure TfrmOptions.ChangeValue(Sender: TObject);
begin
if not Self.Visible then Exit;
if (Sender is TCheckBox) then
with (Sender as TCheckBox) do Cfg.SetValue(Hint, BoolToStr(Checked, True));
if (Sender is TEdit) then
with (Sender as TEdit) do Cfg.SetValue(Hint, Text);
if (Sender is TUpDown) then
with (Sender as TUpDown) do Cfg.SetValue(Hint, Position);
if (Sender is TComboBox) then
with (Sender as TComboBox) do begin
if Hint = 'Language' then //Особый случай, нужен не индекс а имя
Cfg.SetValue(Hint, appLoc.Languages[ItemIndex].ShortName)
else
Cfg.SetValue(Hint, ItemIndex);
end;
end;
procedure TfrmOptions.chkMakeBackupsClick(Sender: TObject);
begin
txtBackupFolder.Enabled:= chkMakeBackups.Checked or chkMakeBackupsCh.Checked;
btnSelBackupFolder.Enabled:= chkMakeBackups.Checked or chkMakeBackupsCh.Checked;
txtBackupsCount.Enabled:= chkMakeBackups.Checked or chkMakeBackupsCh.Checked;
udBackupsCount.Enabled:= chkMakeBackups.Checked or chkMakeBackupsCh.Checked;
lblBackupFolder.Enabled:= chkMakeBackups.Checked or chkMakeBackupsCh.Checked;
lblBackupsCount.Enabled:= chkMakeBackups.Checked or chkMakeBackupsCh.Checked;
ChangeValue(Sender);
end;
constructor TfrmOptions.Create(AOwner: TComponent; tempSettings: TSettings);
begin
inherited Create(AOwner);
Cfg:= tempSettings;
ReadConfiguration;
end;
procedure TfrmOptions.ReadConfiguration;
procedure ReadValues(Com: TComponent);
//(RootNode.ChildNodes.FindNode(Section) <> nil)
begin
if Com is TCheckBox then with (Com as TCheckBox) do
if Cfg.HasOption(Hint) then
Checked:= Boolean(Cfg.GetValue(Hint, False));
if Com is TEdit then with (Com as TEdit) do
if Cfg.HasOption(Hint) then
Text:= String(Cfg.GetValue(Hint, ''));
if Com is TUpDown then with (Com as TUpDown) do
if Cfg.HasOption(Hint) then
Position:= Integer(Cfg.GetValue(Hint, Min));
end;
var i: Integer;
begin
//Заполняем чекбоксы в соответствии с текущими настройками.
for i := 0 to Self.ComponentCount - 1 do ReadValues(Self.Components[i]);
end;
procedure TfrmOptions.txtBackupFolderChange(Sender: TObject);
var
fullPath: String;
begin
CheckBackupFolder(txtBackupFolder.Text, fullPath);
//btnSelBackupFolder.Hint:= 'Current path: ' + fullPath;
bhBackup.Description := fullPath;
end;
procedure TfrmOptions.txtBackupFolderExit(Sender: TObject);
var
fullPath: String;
begin
if not CheckBackupFolder(txtBackupFolder.Text, fullPath, True) then
case MessageBox(Self.Handle,
PWideChar(Format(rsWrongBackupFolder, [fullPath])),
PWideChar(rsWrongBackupFolderTitle),
MB_YESNOCANCEL + MB_ICONWARNING) of
ID_NO: begin
txtBackupFolder.Show;
txtBackupFolder.SetFocus;
end;
ID_YES: begin
txtBackupFolder.Text:=strDefaultBackupFolder;
// txtBackupFolder.Show;
// txtBackupFolder.SetFocus;
end;
ID_CANCEL:begin
txtBackupFolder.Text:=xmlCfg.GetValue('BackupFolder', strDefaultBackupFolder);
// txtBackupFolder.Show;
// txtBackupFolder.SetFocus;
end;
end;
ChangeValue(Sender);
end;
procedure TfrmOptions.udBackupsCountClick(Sender: TObject; Button: TUDBtnType);
begin
ChangeValue(Sender);
end;
procedure TfrmOptions.btnAssociateFilesClick(Sender: TObject);
begin
AssociateFileTypes(True);
end;
procedure TfrmOptions.btnBackupNowClick(Sender: TObject);
begin
MakeDocumentBackup;
Beep;
end;
procedure TfrmOptions.btnOKClick(Sender: TObject);
begin
Self.ModalResult:=mrOk;
end;
procedure TfrmOptions.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Self.BorderIcons:=[];
Self.Caption:='';
end;
procedure TfrmOptions.FormCreate(Sender: TObject);
var
Lng:TLocalization.TLanguage;
begin
for Lng in appLoc.Languages do
cmbLanguages.Items.Add(Lng.Name);
cmbLanguages.ItemIndex:= appLoc.Languages.IndexOf(appLoc.CurrentLanguage);
end;
procedure TfrmOptions.FormShow(Sender: TObject);
begin
WindowsOnTop(bWindowsOnTop, Self);
appLoc.TranslateForm(Self);
SetButtonImg(btnSelBackupFolder, imlOptions, 4);
chkMakeBackupsClick(nil); //Для enable-disable зависимых контролов
txtBackupFolderChange(nil); //Для заполнения bhBackup
end;
procedure TfrmOptions.imgBackupClick(Sender: TObject);
var
Point:TPoint;
begin
// if bhBackup.ShowingHint then begin //Нестабильно
// bhBackup.HideHint;
// Exit;
// end;
bhBackup.Title := rsBackupHintTitle;
bhBackup.ImageIndex:= 5;
point.X := txtBackupFolder.Width div 2;
point.Y := txtBackupFolder.Height;
bhBackup.ShowHint(txtBackupFolder.ClientToScreen(point));
end;
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db, Grids, DBGrids, SMDBGrid, DBTables, StdCtrls, ExtCtrls;
type
TfrmMain = class(TForm)
DataSource1: TDataSource;
Table1: TTable;
SMDBGrid1: TSMDBGrid;
Table1OrderNo: TFloatField;
Table1CustNo: TFloatField;
Table1SaleDate: TDateTimeField;
Table1PaymentMethod: TStringField;
Table1ItemsTotal: TCurrencyField;
Table1TaxRate: TFloatField;
Table1AmountPaid: TCurrencyField;
Table2: TTable;
Table2CustNo: TFloatField;
Table2Company: TStringField;
Table2Addr1: TStringField;
Table2Addr2: TStringField;
Table2City: TStringField;
Table2State: TStringField;
Table2Zip: TStringField;
Table2Country: TStringField;
Table2Phone: TStringField;
Table2FAX: TStringField;
Table2TaxRate: TFloatField;
Table2Contact: TStringField;
Table2LastInvoiceDate: TDateTimeField;
lblDescription: TLabel;
lblURL: TLabel;
Image1: TImage;
procedure Table1AfterScroll(DataSet: TDataSet);
procedure lblURLClick(Sender: TObject);
procedure SMDBGrid1DrawFooterCell(Sender: TObject; Canvas: TCanvas;
FooterCellRect: TRect; Field: TField; var FooterText: String;
var DefaultDrawing: Boolean);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.DFM}
uses ShellAPI;
procedure TfrmMain.Table1AfterScroll(DataSet: TDataSet);
var
i: Integer;
begin
for i := 0 to SMDBGrid1.Columns.Count-1 do
with SMDBGrid1.Columns[i] as TSMDBColumn do
if FieldName = 'AmountPaid' then
FooterValue := 'Payment: ' + Table1.FieldByName('PaymentMethod').AsString
else
if FieldName = 'CustNo' then
begin
if Table2.Active and Table2.Locate('CustNo', Field.AsInteger, []) then
FooterValue := 'Company: ' + Table2.FieldByName('Company').AsString
else
FooterValue := ''
end;
end;
procedure TfrmMain.lblURLClick(Sender: TObject);
begin
ShellExecute(0, 'open', PChar((Sender as TLabel).Caption), nil, nil, SW_SHOWNORMAL);
end;
procedure TfrmMain.SMDBGrid1DrawFooterCell(Sender: TObject;
Canvas: TCanvas; FooterCellRect: TRect; Field: TField;
var FooterText: String; var DefaultDrawing: Boolean);
begin
if Assigned(Field) and (Field.FieldName = 'AmountPaid') then
begin
DefaultDrawing := False;
Canvas.FillRect(FooterCellRect);
Canvas.Draw(FooterCellRect.Left + 2, FooterCellRect.Top + 2, Image1.Picture.Graphic);
FooterCellRect.Left := FooterCellRect.Left + Image1.Width + 5;
FooterCellRect.Top := FooterCellRect.Top + 2;
DrawText(Canvas.Handle, PChar(FooterText), Length(FooterText), FooterCellRect, DT_LEFT or DT_WORDBREAK or DT_EXPANDTABS or DT_NOPREFIX or DT_VCENTER)
end
end;
end.
|
{Ejercicio 7
Dada la definición de tipo para representar cadenas de caracteres de largo M y N :
CONST N = . . .;
CONST M = . . .; M < N
. . .
TYPE
CadenaM = ARRAY[1..M] Of Char;
CadenaN = ARRAY[1..N] Of Char;
Implementar un programa que lea dos cadenas de la entrada estándar de largo M y N respectivamente,
y determine si la primer cadena ocurre como parte de la segunda cadena. El programa debe funcionar
para cualquier valor positivo que puedan tomar M y N, considerando la restricción M < N.
Ejemplo de entrada para N=6, M=3:
tor
totora
Ejemplo de salida:
El texto 'tor' se encuentra dentro del texto 'totora'.
Ejemplo de entrada:
tos
totora
Ejemplo de salida:
El texto 'tos' no se encuentra dentro del texto 'totora'.}
program ejercicio7;
const M = 3;
const N = 6;
type
rangoM = 1..M;
rangoN = 1..N;
cadenaM = array[rangoM] of char;
cadenaN = array[rangoN] of char;
var
k : integer;
j : rangoM;
b : cadenaM;
i : rangoN;
a : cadenaN;
temp : boolean;
begin
// writeln('Ingrese una palabra de ', N,' letras.');
for i := 1 to N do
begin
read(a[i]);
// writeln(a[i]);
end;
writeln('--------------------------');
// writeln('Ingrese una palabra de ', M,' letras.');
read(b[1]);
for j := 1 to M do
begin
read(b[j]);
// writeln(b[j]);
end;
writeln('--------------------------');
writeln(a,'<----Entrada1');
writeln(b,'<----Entrada2');
temp := false;
for i := 1 to M do
begin
k := 1;
for j := 1 to M do
begin
// i := 1;
while (a[k] = b[j]) and (k <= M) do
begin
temp := true;
k := k + 1;
end;
end;
if (k > M) then
writeln('Si')
else
writeln('No');
end;
end. |
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1995-2001 Borland Software Corporation }
{ }
{*******************************************************}
unit SvcMgr;
{$J+,H+,X+}
interface
uses
Windows, Messages, SysUtils, Classes, WinSvc;
type
{ TEventLogger }
TEventLogger = class(TObject)
private
FName: String;
FEventLog: Integer;
public
constructor Create(Name: String);
destructor Destroy; override;
procedure LogMessage(Message: String; EventType: DWord = 1;
Category: Word = 0; ID: DWord = 0);
end;
{ TDependency }
TDependency = class(TCollectionItem)
private
FName: String;
FIsGroup: Boolean;
protected
function GetDisplayName: string; override;
published
property Name: String read FName write FName;
property IsGroup: Boolean read FIsGroup write FIsGroup;
end;
{ TDependencies }
TDependencies = class(TCollection)
private
FOwner: TPersistent;
function GetItem(Index: Integer): TDependency;
procedure SetItem(Index: Integer; Value: TDependency);
protected
function GetOwner: TPersistent; override;
public
constructor Create(Owner: TPersistent);
property Items[Index: Integer]: TDependency read GetItem write SetItem; default;
end;
{ TServiceThread }
const
CM_SERVICE_CONTROL_CODE = WM_USER + 1;
type
TService = class;
TServiceThread = class(TThread)
private
FService: TService;
protected
procedure Execute; override;
public
constructor Create(Service: TService);
procedure ProcessRequests(WaitForMessage: Boolean);
end;
{ TService }
TServiceController = procedure(CtrlCode: DWord); stdcall;
TServiceType = (stWin32, stDevice, stFileSystem);
TCurrentStatus = (csStopped, csStartPending, csStopPending, csRunning,
csContinuePending, csPausePending, csPaused);
TErrorSeverity = (esIgnore, esNormal, esSevere, esCritical);
TStartType = (stBoot, stSystem, stAuto, stManual, stDisabled);
TServiceEvent = procedure(Sender: TService) of object;
TContinueEvent = procedure(Sender: TService; var Continued: Boolean) of object;
TPauseEvent = procedure(Sender: TService; var Paused: Boolean) of object;
TStartEvent = procedure(Sender: TService; var Started: Boolean) of object;
TStopEvent = procedure(Sender: TService; var Stopped: Boolean) of object;
TService = class(TDataModule)
private
FAllowStop: Boolean;
FAllowPause: Boolean;
FDependencies: TDependencies;
FDisplayName: String;
FErrCode: DWord;
FErrorSeverity: TErrorSeverity;
FEventLogger: TEventLogger;
FInteractive: Boolean;
FLoadGroup: String;
FParams: TStringList;
FPassword: String;
FServiceStartName: String;
FServiceThread: TServiceThread;
FServiceType: TServiceType;
FStartType: TStartType;
FStatus: TCurrentStatus;
FStatusHandle: THandle;
FTagID: DWord;
FWaitHint: Integer;
FWin32ErrorCode: DWord;
FBeforeInstall: TServiceEvent;
FAfterInstall: TServiceEvent;
FBeforeUninstall: TServiceEvent;
FAfterUninstall: TServiceEvent;
FOnContinue: TContinueEvent;
FOnExecute: TServiceEvent;
FOnPause: TPauseEvent;
FOnShutdown: TServiceEvent;
FOnStart: TStartEvent;
FOnStop: TStopEvent;
function GetDisplayName: String;
function GetParamCount: Integer;
function GetParam(Index: Integer): String;
procedure SetStatus(Value: TCurrentStatus);
procedure SetDependencies(Value: TDependencies);
function GetNTDependencies: String;
function GetNTServiceType: Integer;
function GetNTStartType: Integer;
function GetNTErrorSeverity: Integer;
function GetNTControlsAccepted: Integer;
procedure SetOnContinue(Value: TContinueEvent);
procedure SetOnPause(Value: TPauseEvent);
procedure SetOnStop(Value: TStopEvent);
function GetTerminated: Boolean;
function AreDependenciesStored: Boolean;
procedure SetInteractive(Value: Boolean);
procedure SetPassword(const Value: string);
procedure SetServiceStartName(const Value: string);
protected
procedure Main(Argc: DWord; Argv: PLPSTR);
procedure Controller(CtrlCode: DWord);
procedure DoStart; virtual;
function DoStop: Boolean; virtual;
function DoPause: Boolean; virtual;
function DoContinue: Boolean; virtual;
procedure DoInterrogate; virtual;
procedure DoShutdown; virtual;
function DoCustomControl(CtrlCode: DWord): Boolean; virtual;
public
constructor CreateNew(AOwner: TComponent; Dummy: Integer); override;
destructor Destroy; override;
function GetServiceController: TServiceController; virtual; abstract;
procedure ReportStatus;
procedure LogMessage(Message: String; EventType: DWord = 1;
Category: Integer = 0; ID: Integer = 0);
property ErrCode: DWord read FErrCode write FErrCode;
property ParamCount: Integer read GetParamCount;
property Param[Index: Integer]: String read GetParam;
property ServiceThread: TServiceThread read FServiceThread;
property Status: TCurrentStatus read FStatus write SetStatus;
property Terminated: Boolean read GetTerminated;
property Win32ErrCode: DWord read FWin32ErrorCode write FWin32ErrorCode;
published
property AllowStop: Boolean read FAllowStop write FAllowStop default True;
property AllowPause: Boolean read FAllowPause write FAllowPause default True;
property Dependencies: TDependencies read FDependencies write SetDependencies stored AreDependenciesStored;
property DisplayName: String read GetDisplayName write FDisplayName;
property ErrorSeverity: TErrorSeverity read FErrorSeverity write FErrorSeverity default esNormal;
property Interactive: Boolean read FInteractive write SetInteractive default False;
property LoadGroup: String read FLoadGroup write FLoadGroup;
property Password: String read FPassword write SetPassword;
property ServiceStartName: String read FServiceStartName write SetServiceStartName;
property ServiceType: TServiceType read FServiceType write FServiceType default stWin32;
property StartType: TStartType read FStartType write FStartType default stAuto;
property TagID: DWord read FTagID write FTagID default 0;
property WaitHint: Integer read FWaitHint write FWaitHint default 5000;
property BeforeInstall: TServiceEvent read FBeforeInstall write FBeforeInstall;
property AfterInstall: TServiceEvent read FAfterInstall write FAfterInstall;
property BeforeUninstall: TServiceEvent read FBeforeUninstall write FBeforeUninstall;
property AfterUninstall: TServiceEvent read FAfterUninstall write FAfterUninstall;
property OnContinue: TContinueEvent read FOnContinue write SetOnContinue;
property OnExecute: TServiceEvent read FOnExecute write FOnExecute;
property OnPause: TPauseEvent read FOnPause write SetOnPause;
property OnShutdown: TServiceEvent read FOnShutdown write FOnShutdown;
property OnStart: TStartEvent read FOnStart write FOnStart;
property OnStop: TStopEvent read FOnStop write SetOnStop;
end;
{ TServiceApplication }
TServiceApplication = class(TComponent)
private
FEventLogger: TEventLogger;
FTitle: string;
procedure OnExceptionHandler(Sender: TObject; E: Exception);
function GetServiceCount: Integer;
protected
procedure DoHandleException(E: Exception); dynamic;
procedure RegisterServices(Install, Silent: Boolean);
procedure DispatchServiceMain(Argc: DWord; Argv: PLPSTR);
function Hook(var Message: TMessage): Boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property ServiceCount: Integer read GetServiceCount;
// The following uses the current behaviour of the IDE module manager
procedure CreateForm(InstanceClass: TComponentClass; var Reference); virtual;
procedure Initialize; virtual;
procedure Run; virtual;
property Title: string read FTitle write FTitle;
end;
var
Application: TServiceApplication = nil;
implementation
uses
Forms, Dialogs, Consts;
{ TEventLogger }
constructor TEventLogger.Create(Name: String);
begin
FName := Name;
FEventLog := 0;
end;
destructor TEventLogger.Destroy;
begin
if FEventLog <> 0 then
DeregisterEventSource(FEventLog);
inherited Destroy;
end;
procedure TEventLogger.LogMessage(Message: String; EventType: DWord;
Category: Word; ID: DWord);
var
P: Pointer;
begin
P := PChar(Message);
if FEventLog = 0 then
FEventLog := RegisterEventSource(nil, PChar(FName));
ReportEvent(FEventLog, EventType, Category, ID, nil, 1, 0, @P, nil);
end;
{ TDependency }
function TDependency.GetDisplayName: string;
begin
if Name <> '' then
Result := Name else
Result := inherited GetDisplayName;
end;
{ TDependencies }
constructor TDependencies.Create(Owner: TPersistent);
begin
FOwner := Owner;
inherited Create(TDependency);
end;
function TDependencies.GetItem(Index: Integer): TDependency;
begin
Result := TDependency(inherited GetItem(Index));
end;
procedure TDependencies.SetItem(Index: Integer; Value: TDependency);
begin
inherited SetItem(Index, TCollectionItem(Value));
end;
function TDependencies.GetOwner: TPersistent;
begin
Result := FOwner;
end;
{ TServiceThread }
constructor TServiceThread.Create(Service: TService);
begin
FService := Service;
inherited Create(True);
end;
procedure TServiceThread.Execute;
var
msg: TMsg;
Started: Boolean;
begin
PeekMessage(msg, 0, WM_USER, WM_USER, PM_NOREMOVE); { Create message queue }
try
FService.Status := csStartPending;
Started := True;
if Assigned(FService.OnStart) then FService.OnStart(FService, Started);
if not Started then Exit;
try
FService.Status := csRunning;
if Assigned(FService.OnExecute) then
FService.OnExecute(FService)
else
ProcessRequests(True);
ProcessRequests(False);
except
on E: Exception do
FService.LogMessage(Format(SServiceFailed,[SExecute, E.Message]));
end;
except
on E: Exception do
FService.LogMessage(Format(SServiceFailed,[SStart, E.Message]));
end;
end;
procedure TServiceThread.ProcessRequests(WaitForMessage: Boolean);
const
ActionStr: array[1..5] of String = (SStop, SPause, SContinue, SInterrogate,
SShutdown);
var
msg: TMsg;
OldStatus: TCurrentStatus;
ErrorMsg: String;
ActionOK, Rslt: Boolean;
begin
while True do
begin
if Terminated and WaitForMessage then break;
if WaitForMessage then
Rslt := GetMessage(msg, 0, 0, 0)
else
Rslt := PeekMessage(msg, 0, 0, 0, PM_REMOVE);
if not Rslt then break;
if msg.hwnd = 0 then { Thread message }
begin
if msg.message = CM_SERVICE_CONTROL_CODE then
begin
OldStatus := FService.Status;
try
ActionOK := True;
case msg.wParam of
SERVICE_CONTROL_STOP: ActionOK := FService.DoStop;
SERVICE_CONTROL_PAUSE: ActionOK := FService.DoPause;
SERVICE_CONTROL_CONTINUE: ActionOK := FService.DoContinue;
SERVICE_CONTROL_SHUTDOWN: FService.DoShutDown;
SERVICE_CONTROL_INTERROGATE: FService.DoInterrogate;
else
ActionOK := FService.DoCustomControl(msg.wParam);
end;
if not ActionOK then
FService.Status := OldStatus;
except
on E: Exception do
begin
if msg.wParam <> SERVICE_CONTROL_SHUTDOWN then
FService.Status := OldStatus;
if msg.wParam in [1..5] then
ErrorMsg := Format(SServiceFailed, [ActionStr[msg.wParam], E.Message])
else
ErrorMsg := Format(SCustomError,[msg.wParam, E.Message]);
FService.LogMessage(ErrorMsg);
end;
end;
end else
DispatchMessage(msg);
end else
DispatchMessage(msg);
end;
end;
{ TService }
constructor TService.CreateNew(AOwner: TComponent; Dummy: Integer);
begin
inherited CreateNew(AOwner);
FWaitHint := 5000;
FInteractive := False;
FServiceType := stWin32;
FParams := TStringList.Create;
FDependencies := TDependencies.Create(Self);
FErrorSeverity := esNormal;
FStartType := stAuto;
FTagID := 0;
FAllowStop := True;
FAllowPause := True;
end;
destructor TService.Destroy;
begin
FDependencies.Free;
FParams.Free;
FEventLogger.Free;
inherited Destroy;
end;
function TService.GetDisplayName: String;
begin
if FDisplayName <> '' then
Result := FDisplayName
else
Result := Name;
end;
procedure TService.SetInteractive(Value: Boolean);
begin
if Value = FInteractive then Exit;
if Value then
begin
Password := '';
ServiceStartName := '';
end;
FInteractive := Value;
end;
procedure TService.SetPassword(const Value: string);
begin
if Value = FPassword then Exit;
if Value <> '' then
Interactive := False;
FPassword := Value;
end;
procedure TService.SetServiceStartName(const Value: string);
begin
if Value = FServiceStartName then Exit;
if Value <> '' then
Interactive := False;
FServiceStartName := Value;
end;
procedure TService.SetDependencies(Value: TDependencies);
begin
FDependencies.Assign(Value);
end;
function TService.AreDependenciesStored: Boolean;
begin
Result := FDependencies.Count > 0;
end;
function TService.GetParamCount: Integer;
begin
Result := FParams.Count;
end;
function TService.GetParam(Index: Integer): String;
begin
Result := FParams[Index];
end;
procedure TService.SetOnContinue(Value: TContinueEvent);
begin
FOnContinue := Value;
AllowPause := True;
end;
procedure TService.SetOnPause(Value: TPauseEvent);
begin
FOnPause := Value;
AllowPause := True;
end;
procedure TService.SetOnStop(Value: TStopEvent);
begin
FOnStop := Value;
AllowStop := True;
end;
function TService.GetTerminated: Boolean;
begin
Result := False;
if Assigned(FServiceThread) then
Result := FServiceThread.Terminated;
end;
function TService.GetNTDependencies: String;
var
i, Len: Integer;
P: PChar;
begin
Result := '';
Len := 0;
for i := 0 to Dependencies.Count - 1 do
begin
Inc(Len, Length(Dependencies[i].Name) + 1); // For null-terminator
if Dependencies[i].IsGroup then Inc(Len);
end;
if Len <> 0 then
begin
Inc(Len); // For final null-terminator;
SetLength(Result, Len);
P := @Result[1];
for i := 0 to Dependencies.Count - 1 do
begin
if Dependencies[i].IsGroup then
begin
P^ := SC_GROUP_IDENTIFIER;
Inc(P);
end;
P := StrECopy(P, PChar(Dependencies[i].Name));
Inc(P);
end;
P^ := #0;
end;
end;
function TService.GetNTServiceType: Integer;
const
NTServiceType: array[TServiceType] of Integer = ( SERVICE_WIN32_OWN_PROCESS,
SERVICE_KERNEL_DRIVER, SERVICE_FILE_SYSTEM_DRIVER);
begin
Result := NTServiceType[FServiceType];
if (FServiceType = stWin32) and Interactive then
Result := Result or SERVICE_INTERACTIVE_PROCESS;
if (FServiceType = stWin32) and (Application.ServiceCount > 1) then
Result := (Result xor SERVICE_WIN32_OWN_PROCESS) or SERVICE_WIN32_SHARE_PROCESS;
end;
function TService.GetNTStartType: Integer;
const
NTStartType: array[TStartType] of Integer = (SERVICE_BOOT_START,
SERVICE_SYSTEM_START, SERVICE_AUTO_START, SERVICE_DEMAND_START,
SERVICE_DISABLED);
begin
Result := NTStartType[FStartType];
if (FStartType in [stBoot, stSystem]) and (FServiceType <> stDevice) then
Result := SERVICE_AUTO_START;
end;
function TService.GetNTErrorSeverity: Integer;
const
NTErrorSeverity: array[TErrorSeverity] of Integer = (SERVICE_ERROR_IGNORE,
SERVICE_ERROR_NORMAL, SERVICE_ERROR_SEVERE, SERVICE_ERROR_CRITICAL);
begin
Result := NTErrorSeverity[FErrorSeverity];
end;
function TService.GetNTControlsAccepted: Integer;
begin
Result := SERVICE_ACCEPT_SHUTDOWN;
if AllowStop then Result := Result or SERVICE_ACCEPT_STOP;
if AllowPause then Result := Result or SERVICE_ACCEPT_PAUSE_CONTINUE;
end;
procedure TService.LogMessage(Message: String; EventType: DWord; Category, ID: Integer);
begin
if FEventLogger = nil then
FEventLogger := TEventLogger.Create(Name);
FEventLogger.LogMessage(Message, EventType, Category, ID);
end;
procedure TService.ReportStatus;
const
LastStatus: TCurrentStatus = csStartPending;
NTServiceStatus: array[TCurrentStatus] of Integer = (SERVICE_STOPPED,
SERVICE_START_PENDING, SERVICE_STOP_PENDING, SERVICE_RUNNING,
SERVICE_CONTINUE_PENDING, SERVICE_PAUSE_PENDING, SERVICE_PAUSED);
PendingStatus: set of TCurrentStatus = [csStartPending, csStopPending,
csContinuePending, csPausePending];
var
ServiceStatus: TServiceStatus;
begin
with ServiceStatus do
begin
dwWaitHint := FWaitHint;
dwServiceType := GetNTServiceType;
if FStatus = csStartPending then
dwControlsAccepted := 0 else
dwControlsAccepted := GetNTControlsAccepted;
if (FStatus in PendingStatus) and (FStatus = LastStatus) then
Inc(dwCheckPoint) else
dwCheckPoint := 0;
LastStatus := FStatus;
dwCurrentState := NTServiceStatus[FStatus];
dwWin32ExitCode := Win32ErrCode;
dwServiceSpecificExitCode := ErrCode;
if ErrCode <> 0 then
dwWin32ExitCode := ERROR_SERVICE_SPECIFIC_ERROR;
if not SetServiceStatus(FStatusHandle, ServiceStatus) then
LogMessage(SysErrorMessage(GetLastError));
end;
end;
procedure TService.SetStatus(Value: TCurrentStatus);
begin
FStatus := Value;
if not (csDesigning in ComponentState) then
ReportStatus;
end;
procedure TService.Main(Argc: DWord; Argv: PLPSTR);
type
PPCharArray = ^TPCharArray;
TPCharArray = array [0..1024] of PChar;
var
i: Integer;
Controller: TServiceController;
begin
for i := 0 to Argc - 1 do
FParams.Add(PPCharArray(Argv)[i]);
Controller := GetServiceController();
FStatusHandle := RegisterServiceCtrlHandler(PChar(Name), @Controller);
if (FStatusHandle = 0) then
LogMessage(SysErrorMessage(GetLastError)) else
DoStart;
end;
procedure TService.Controller(CtrlCode: DWord);
begin
PostThreadMessage(ServiceThread.ThreadID, CM_SERVICE_CONTROL_CODE, CtrlCode, 0);
if ServiceThread.Suspended then ServiceThread.Resume;
end;
procedure TService.DoStart;
begin
try
Status := csStartPending;
try
FServiceThread := TServiceThread.Create(Self);
FServiceThread.Resume;
FServiceThread.WaitFor;
FreeAndNil(FServiceThread);
finally
Status := csStopped;
end;
except
on E: Exception do
LogMessage(Format(SServiceFailed,[SExecute, E.Message]));
end;
end;
function TService.DoStop: Boolean;
begin
Result := True;
Status := csStopPending;
if Assigned(FOnStop) then FOnStop(Self, Result);
if Result then ServiceThread.Terminate;
end;
function TService.DoPause: Boolean;
begin
Result := True;
Status := csPausePending;
if Assigned(FOnPause) then FOnPause(Self, Result);
if Result then
begin
Status := csPaused;
ServiceThread.Suspend;
end;
end;
function TService.DoContinue: Boolean;
begin
Result := True;
Status := csContinuePending;
if Assigned(FOnContinue) then FOnContinue(Self, Result);
if Result then
Status := csRunning;
end;
procedure TService.DoInterrogate;
begin
ReportStatus;
end;
procedure TService.DoShutdown;
begin
Status := csStopPending;
try
if Assigned(FOnShutdown) then FOnShutdown(Self);
finally
{ Shutdown cannot abort, it must stop regardless of any exception }
ServiceThread.Terminate;
end;
end;
function TService.DoCustomControl(CtrlCode: DWord): Boolean;
begin
Result := True;
end;
{ TServiceApplication }
type
TServiceClass = class of TService;
procedure ServiceMain(Argc: DWord; Argv: PLPSTR); stdcall;
begin
Application.DispatchServiceMain(Argc, Argv);
end;
procedure DoneServiceApplication;
begin
with Forms.Application do
begin
if Handle <> 0 then ShowOwnedPopups(Handle, False);
ShowHint := False;
Destroying;
DestroyComponents;
end;
with Application do
begin
Destroying;
DestroyComponents;
end;
end;
constructor TServiceApplication.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FEventLogger := TEventLogger.Create(ExtractFileName(ParamStr(0)));
Forms.Application.HookMainWindow(Hook);
end;
destructor TServiceApplication.Destroy;
begin
FEventLogger.Free;
Forms.Application.OnException := nil;
Forms.Application.UnhookMainWindow(Hook);
inherited Destroy;
end;
procedure TServiceApplication.DispatchServiceMain(Argc: DWord; Argv: PLPSTR);
var
i: Integer;
begin
for i := 0 to ComponentCount - 1 do
if (Components[i] is TService) and
(AnsiCompareText(PChar(Argv^), Components[i].Name) = 0) then
begin
TService(Components[i]).Main(Argc, Argv);
break;
end;
end;
function TServiceApplication.GetServiceCount: Integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to ComponentCount - 1 do
if Components[i] is TService then
Inc(Result);
end;
procedure TServiceApplication.RegisterServices(Install, Silent: Boolean);
procedure InstallService(Service: TService; SvcMgr: Integer);
var
TmpTagID, Svc: Integer;
PTag, PSSN: Pointer;
Path: string;
begin
Path := ParamStr(0);
with Service do
begin
if Assigned(BeforeInstall) then BeforeInstall(Service);
TmpTagID := TagID;
if TmpTagID > 0 then PTag := @TmpTagID else PTag := nil;
if ServiceStartName = '' then
PSSN := nil else
PSSN := PChar(ServiceStartName);
Svc := CreateService(SvcMgr, PChar(Name), PChar(DisplayName),
SERVICE_ALL_ACCESS, GetNTServiceType, GetNTStartType, GetNTErrorSeverity,
PChar(Path), PChar(LoadGroup), PTag, PChar(GetNTDependencies),
PSSN, PChar(Password));
TagID := TmpTagID;
if Svc = 0 then
RaiseLastOSError;
try
try
if Assigned(AfterInstall) then AfterInstall(Service);
except
on E: Exception do
begin
DeleteService(Svc);
raise;
end;
end;
finally
CloseServiceHandle(Svc);
end;
end;
end;
procedure UninstallService(Service: TService; SvcMgr: Integer);
var
Svc: Integer;
begin
with Service do
begin
if Assigned(BeforeUninstall) then BeforeUninstall(Service);
Svc := OpenService(SvcMgr, PChar(Name), SERVICE_ALL_ACCESS);
if Svc = 0 then RaiseLastOSError;
try
if not DeleteService(Svc) then RaiseLastOSError;
finally
CloseServiceHandle(Svc);
end;
if Assigned(AfterUninstall) then AfterUninstall(Service);
end;
end;
var
SvcMgr: Integer;
i: Integer;
Success: Boolean;
Msg: string;
begin
Success := True;
SvcMgr := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
if SvcMgr = 0 then RaiseLastOSError;
try
for i := 0 to ComponentCount - 1 do
if Components[i] is TService then
try
if Install then
InstallService(TService(Components[i]), SvcMgr) else
UninstallService(TService(Components[i]), SvcMgr)
except
on E: Exception do
begin
Success := False;
if Install then
Msg := SServiceInstallFailed else
Msg := SServiceUninstallFailed;
with TService(Components[i]) do
MessageDlg(Format(Msg, [DisplayName, E.Message]), mtError, [mbOK],0);
end;
end;
if Success and not Silent then
if Install then
MessageDlg(SServiceInstallOK, mtInformation, [mbOk], 0) else
MessageDlg(SServiceUninstallOK, mtInformation, [mbOk], 0);
finally
CloseServiceHandle(SvcMgr);
end;
end;
function TServiceApplication.Hook(var Message: TMessage): Boolean;
begin
Result := Message.Msg = WM_ENDSESSION;
end;
procedure TServiceApplication.CreateForm(InstanceClass: TComponentClass;
var Reference);
begin
if InstanceClass.InheritsFrom(TService) then
begin
try
TComponent(Reference) := InstanceClass.Create(Self);
except
TComponent(Reference) := nil;
raise;
end;
end else
Forms.Application.CreateForm(InstanceClass, Reference);
end;
procedure TServiceApplication.DoHandleException(E: Exception);
begin
FEventLogger.LogMessage(E.Message);
end;
procedure TServiceApplication.Initialize;
begin
Forms.Application.ShowMainForm :=False;
Forms.Application.Initialize;
end;
procedure TServiceApplication.OnExceptionHandler(Sender: TObject; E: Exception);
begin
DoHandleException(E);
end;
type
TServiceTableEntryArray = array of TServiceTableEntry;
TServiceStartThread = class(TThread)
private
FServiceStartTable: TServiceTableEntryArray;
protected
procedure DoTerminate; override;
procedure Execute; override;
public
constructor Create(Services: TServiceTableEntryArray);
end;
constructor TServiceStartThread.Create(Services: TServiceTableEntryArray);
begin
FreeOnTerminate := False;
ReturnValue := 0;
FServiceStartTable := Services;
inherited Create(False);
end;
procedure TServiceStartThread.DoTerminate;
begin
inherited DoTerminate;
PostMessage(Forms.Application.Handle, WM_QUIT, 0, 0);
end;
procedure TServiceStartThread.Execute;
begin
if StartServiceCtrlDispatcher(FServiceStartTable[0]) then
ReturnValue := 0
else
ReturnValue := GetLastError;
end;
procedure TServiceApplication.Run;
function FindSwitch(const Switch: string): Boolean;
begin
Result := FindCmdLineSwitch(Switch, ['-', '/'], True);
end;
var
ServiceStartTable: TServiceTableEntryArray;
ServiceCount, i, J: Integer;
StartThread: TServiceStartThread;
begin
AddExitProc(DoneServiceApplication);
if FindSwitch('INSTALL') then
RegisterServices(True, FindSwitch('SILENT'))
else if FindSwitch('UNINSTALL') then
RegisterServices(False, FindSwitch('SILENT'))
else
begin
Forms.Application.OnException := OnExceptionHandler;
ServiceCount := 0;
for i := 0 to ComponentCount - 1 do
if Components[i] is TService then Inc(ServiceCount);
SetLength(ServiceStartTable, ServiceCount + 1);
FillChar(ServiceStartTable[0], SizeOf(TServiceTableEntry) * (ServiceCount + 1), 0);
J := 0;
for i := 0 to ComponentCount - 1 do
if Components[i] is TService then
begin
ServiceStartTable[J].lpServiceName := PChar(Components[i].Name);
ServiceStartTable[J].lpServiceProc := @ServiceMain;
Inc(J);
end;
StartThread := TServiceStartThread.Create(ServiceStartTable);
try
while not Forms.Application.Terminated do
Forms.Application.HandleMessage;
Forms.Application.Terminate;
if StartThread.ReturnValue <> 0 then
FEventLogger.LogMessage(SysErrorMessage(StartThread.ReturnValue));
finally
StartThread.Free;
end;
end;
end;
procedure InitApplication;
begin
Application := TServiceApplication.Create(nil);
end;
procedure DoneApplication;
begin
Application.Free;
Application := nil;
end;
initialization
InitApplication;
finalization
DoneApplication;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 2018-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Vcl.ImageCollection;
interface
uses
Winapi.Windows, Winapi.Messages, System.Classes, System.Messaging,
Vcl.Graphics, Vcl.Controls, Winapi.Wincodec,
Vcl.BaseImageCollection;
type
TImageCollection = class;
TImageCollectionItem = class;
/// <summary>
/// Item to store one image.
/// </summary>
TImageCollectionSourceItem = class(TCollectionItem)
private
FImage: TWICImage;
procedure SetImage(Value: TWICImage);
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
published
/// <summary>
/// TWICImage property to store image in native format.
/// </summary>
property Image: TWICImage
read FImage write SetImage;
end;
/// <summary>
/// Collection to store images with different sizes for one item from TImageCollection.
/// </summary>
TImageCollectionItemSources = class(TOwnedCollection)
private
function GetItem(Index: Integer): TImageCollectionSourceItem;
procedure SetItem(Index: Integer; Value: TImageCollectionSourceItem);
public
function Add: TImageCollectionSourceItem;
property Items[Index: Integer]: TImageCollectionSourceItem read GetItem write SetItem; default;
end;
/// <summary>
/// Item for TImageCollection, which has name and list of source images.
/// </summary>
TImageCollectionItem = class(TCollectionItem)
private
FName: String;
FSourceImages: TImageCollectionItemSources;
FData: TCustomData;
procedure SetName(const Value: String);
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
/// <summary>
/// Use CheckSources to sort images by size after you loading them.
/// Function return True if it reordered items in SourceImages property.
/// </summary>
function CheckSources: Boolean;
/// <summary>
/// Property to link some abstract data for item.
/// </summary>
property Data: TCustomData read FData write FData;
/// <summary>
/// Call Change method from specific item to process messaging that item was changed.
/// CheckSources method is called in this method automatically.
/// </summary>
procedure Change;
published
/// <summary>
/// Item name, which can includes Category.
/// Category name placed at the beginning of the name and separated by the symbol "\".
/// </summary>
property Name: String read FName write SetName;
/// <summary>
/// Collection of source images.
/// TImageCollection chooses one source image for optimal scaling.
/// </summary>
property SourceImages: TImageCollectionItemSources
read FSourceImages write FSourceImages;
end;
/// <summary>
/// Collection of items for TImageCollection
/// </summary>
TImageCollectionItems = class(TOwnedCollection)
private
function GetItem(Index: Integer): TImageCollectionItem;
procedure SetItem(Index: Integer; Value: TImageCollectionItem);
public
function Add: TImageCollectionItem;
property Items[Index: Integer]: TImageCollectionItem read GetItem write SetItem; default;
end;
/// <summary>
/// Interpolation modes for TImageCollection.
/// </summary>
TImageCollectionInterpolationMode = (icIMModeHighQualityCubic, icIMFant,
icIMLinear, icIMCubic, icIMModeNearestNeighbor);
/// <summary>
/// Event type to create create TBitmap from TWICImage with custom algorithm.
/// </summary>
TImageCollectionOnGetBitmapEvent = procedure(ASourceImage: TWICImage;
AWidth, AHeight: Integer; out ABitmap: TBitmap) of object;
/// <summary>
/// Event type to draw image from collection with custom code.
/// </summary>
TImageCollectionOnDrawEvent = procedure(ASourceImage: TWICImage;
ACanvas: TCanvas; ARect: TRect; AProportional: Boolean = False) of object;
/// <summary>
/// Component to store, scale and draw images.
/// </summary>
TImageCollection = class(TCustomImageCollection)
private
FImages: TImageCollectionItems;
FInterpolationMode: TImageCollectionInterpolationMode;
FOnGetBitmap: TImageCollectionOnGetBitmapEvent;
FOnDraw: TImageCollectionOnDrawEvent;
procedure SetImages(Value: TImageCollectionItems);
procedure SetInterpolationMode(Value: TImageCollectionInterpolationMode);
protected
function GetCount: Integer; override;
function GetSourceImageIndex(AIndex: Integer; AWidth, AHeight: Integer): Integer;
function GetSourceImageByIndex(AIndex, ASourceIndex: Integer): TWICImage;
procedure DoDraw(ACanvas: TCanvas; ARect: TRect; AIndex: Integer; AProportional: Boolean);
function GetScaledImage(ASourceImage: TWICImage; ANewWidth, ANewHeight: Integer): TWICImage;
procedure LoadFromCollection(AImageCollection: TImageCollection);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
function IsIndexAvailable(AIndex: Integer): Boolean; override;
function GetIndexByName(const AName: String): Integer; override;
function GetNameByIndex(AIndex: Integer): String; override;
/// <summary>
/// Get source TWICImage, which optimal for scaling to AWdith and AHeight sizes.
/// </summary>
function GetSourceImage(AIndex: Integer; AWidth, AHeight: Integer): TWICImage;
/// <summary>
/// Get scaled to specific size TBitmap from item with specific index.
/// </summary>
function GetBitmap(AIndex: Integer; AWidth, AHeight: Integer): TBitmap; overload; override;
/// <summary>
/// Get scaled to specific size TBitmap from item with specific name.
/// </summary>
function GetBitmap(const AName: String; AWidth, AHeight: Integer; AEnabled: Boolean = True): TBitmap; overload;
/// <summary>
/// Directly draw specific image from Item.SourceImages collection.
/// </summary>
procedure DrawSource(ACanvas: TCanvas; ARect: TRect; AIndex: Integer; ASourceIndex: Integer; AProportional: Boolean = False);
/// <summary>
/// Draw image from collection item with specific index to specific rect and proportional parameter.
/// </summary>
procedure Draw(ACanvas: TCanvas; ARect: TRect; AIndex: Integer; AProportional: Boolean = False); overload; override;
/// <summary>
/// Draw image from collection item with specific name to specific rect and proportional parameter.
/// </summary>
procedure Draw(ACanvas: TCanvas; ARect: TRect; const AName: String; AProportional: Boolean = False); overload;
published
/// <summary>
/// Collection of items with source images.
/// </summary>
property Images: TImageCollectionItems read FImages write SetImages;
/// <summary>
/// Interpolation mode, which will be used to scale images.
/// </summary>
property InterpolationMode: TImageCollectionInterpolationMode
read FInterpolationMode write SetInterpolationMode default icIMModeHighQualityCubic;
/// <summary>
/// Use OnDraw event with your code to draw image.
/// </summary>
property OnDraw: TImageCollectionOnDrawEvent
read FOnDraw write FOnDraw;
/// <summary>
/// Use OnGetBitmap event with your code to get TBitmap from item.
/// </summary>
property OnGetBitmap: TImageCollectionOnGetBitmapEvent
read FOnGetBitmap write FOnGetBitmap;
end;
implementation
Uses System.Math, System.SysUtils;
function UpdateRectForProportionalSize(ARect: TRect; AWidth, AHeight: Integer; AStretch: Boolean): TRect;
var
w, h, cw, ch: Integer;
xyaspect: Double;
begin
Result := ARect;
if AWidth * AHeight = 0 then
Exit;
w := AWidth;
h := AHeight;
cw := ARect.Width;
ch := ARect.Height;
if AStretch or ((w > cw) or (h > ch)) then
begin
xyaspect := w / h;
if w > h then
begin
w := cw;
h := Trunc(cw / xyaspect);
if h > ch then
begin
h := ch;
w := Trunc(ch * xyaspect);
end;
end
else
begin
h := ch;
w := Trunc(ch * xyaspect);
if w > cw then
begin
w := cw;
h := Trunc(cw / xyaspect);
end;
end;
end;
Result := Rect(0, 0, w, h);
OffsetRect(Result, ARect.Left + (cw - w) div 2, ARect.Top + (ch - h) div 2);
end;
constructor TImageCollectionSourceItem.Create(Collection: TCollection);
begin
inherited;
FImage := TWICImage.Create;
end;
destructor TImageCollectionSourceItem.Destroy;
begin
FImage.Free;
inherited;
end;
procedure TImageCollectionSourceItem.SetImage(Value: TWICImage);
begin
FImage.Assign(Value);
end;
function TImageCollectionItemSources.GetItem(Index: Integer): TImageCollectionSourceItem;
begin
Result := TImageCollectionSourceItem(inherited GetItem(Index));
end;
procedure TImageCollectionItemSources.SetItem(Index: Integer; Value: TImageCollectionSourceItem);
begin
inherited SetItem(Index, Value);
end;
function TImageCollectionItemSources.Add: TImageCollectionSourceItem;
begin
Result := TImageCollectionSourceItem(inherited Add);
end;
constructor TImageCollectionItem.Create(Collection: TCollection);
begin
inherited Create(Collection);
FSourceImages := TImageCollectionItemSources.Create(Self, TImageCollectionSourceItem);
FName := '';
end;
destructor TImageCollectionItem.Destroy;
begin
FSourceImages.Free;
inherited;
end;
procedure TImageCollectionItem.Change;
begin
CheckSources;
if Collection.Owner is TImageCollection then
TMessageManager.DefaultManager.SendMessage(nil,
TImageCollectionChangedMessage.Create(TImageCollection(Collection.Owner), Index, Name));
end;
procedure TImageCollectionItem.SetName(const Value: String);
begin
FName := Value;
end;
function TImageCollectionItem.CheckSources: Boolean;
var
I, J: Integer;
begin
Result := False;
if SourceImages.Count < 2 then
Exit;
for I := 0 to SourceImages.Count - 2 do
for J := 0 to SourceImages.Count - 2 - I do
if Max(SourceImages[J].Image.Width, SourceImages[J].Image.Height) >
Max(SourceImages[J + 1].Image.Width, SourceImages[J + 1].Image.Height) then
begin
Result := True;
SourceImages[J].Index := J + 1;
end;
end;
function TImageCollectionItems.GetItem(Index: Integer): TImageCollectionItem;
begin
Result := TImageCollectionItem(inherited GetItem(Index));
end;
procedure TImageCollectionItems.SetItem(Index: Integer; Value: TImageCollectionItem);
begin
inherited SetItem(Index, Value);
end;
function TImageCollectionItems.Add: TImageCollectionItem;
begin
Result := TImageCollectionItem(inherited Add);
end;
constructor TImageCollection.Create(AOwner: TComponent);
begin
inherited;
FImages := TImageCollectionItems.Create(Self, TImageCollectionItem);
FInterpolationMode := icIMModeHighQualityCubic;
end;
destructor TImageCollection.Destroy;
begin
FImages.Free;
inherited;
end;
procedure TImageCollection.SetInterpolationMode(Value: TImageCollectionInterpolationMode);
begin
FInterpolationMode := Value;
end;
procedure TImageCollection.SetImages(Value: TImageCollectionItems);
begin
FImages := Value;
end;
function TImageCollection.GetCount: Integer;
begin
Result := FImages.Count;
end;
function TImageCollection.GetNameByIndex(AIndex: Integer): String;
begin
if (AIndex >= 0) and (AIndex < Count) then
Result := Images[AIndex].Name;
end;
function TImageCollection.GetIndexByName(const AName: String): Integer;
var
I: Integer;
S: String;
begin
Result := -1;
S := LowerCase(AName);
for I := 0 to FImages.Count - 1 do
if LowerCase(FImages[I].Name) = S then
Exit(I);
end;
function TImageCollection.IsIndexAvailable(AIndex: Integer): Boolean;
begin
Result := (Count > 0) and (AIndex >= 0) and (AIndex < Count) and
(FImages[AIndex].SourceImages.Count > 0);
end;
function TImageCollection.GetSourceImageByIndex(AIndex, ASourceIndex: Integer): TWICImage;
begin
if IsIndexAvailable(AIndex) and (ASourceIndex >= 0) and (ASourceIndex < Images[AIndex].SourceImages.Count) then
Result := Images[AIndex].SourceImages[ASourceIndex].Image
else
Result := nil;
end;
function TImageCollection.GetSourceImageIndex(AIndex: Integer; AWidth, AHeight: Integer): Integer;
var
I: Integer;
begin
Result := -1;
if IsIndexAvailable(AIndex) then
begin
if (Images[AIndex].SourceImages.Count = 1) and
not Images[AIndex].SourceImages[0].Image.Empty
then
Result := 0
else
begin
Images[AIndex].CheckSources;
for I := 0 to Images[AIndex].SourceImages.Count - 1 do
if (Max(Images[AIndex].SourceImages[I].Image.Width, Images[AIndex].SourceImages[I].Image.Height) >=
Max(AWidth, AHeight)) or (I = Images[AIndex].SourceImages.Count - 1) then
Exit(I);
end;
end;
end;
function TImageCollection.GetSourceImage(AIndex: Integer; AWidth, AHeight: Integer): TWICImage;
var
FIndex: Integer;
begin
if AIndex < 0 then
Result := nil
else
begin
FIndex := GetSourceImageIndex(AIndex, AWidth, AHeight);
if FIndex >= 0 then
Result := Images[AIndex].SourceImages[FIndex].FImage
else
Result := nil;
end;
end;
function TImageCollection.GetScaledImage(ASourceImage: TWICImage; ANewWidth, ANewHeight: Integer): TWICImage;
const
IMMode: array[TImageCollectionInterpolationMode] of Integer =
(WICBitmapInterpolationModeHighQualityCubic,
WICBitmapInterpolationModeFant,
WICBitmapInterpolationModeLinear,
WICBitmapInterpolationModeCubic,
WICBitmapInterpolationModeNearestNeighbor);
var
Factory: IWICImagingFactory;
Scaler: IWICBitmapScaler;
begin
Result := TWICImage.Create;
Factory := Result.ImagingFactory;
Factory.CreateBitmapScaler(Scaler);
Scaler.Initialize(ASourceImage.Handle, ANewWidth, ANewHeight, IMMode[FInterpolationMode]);
Result.Handle := IWICBitmap(Scaler);
Scaler := nil;
Factory := nil;
end;
function TImageCollection.GetBitmap(AIndex: Integer; AWidth, AHeight: Integer): TBitmap;
var
SourceImage: TWICImage;
BufferImage: TWICImage;
begin
Result := nil;
if AIndex < 0 then
Exit;
SourceImage := GetSourceImage(AIndex, AWidth, AHeight);
if SourceImage <> nil then
if Assigned(FOnGetBitmap) then
FOnGetBitmap(SourceImage, AWidth, AHeight, Result)
else
begin
Result := TBitmap.Create;
if (SourceImage.Width = AWidth) and (SourceImage.Height = AHeight) then
begin
Result.Assign(SourceImage);
if Result.PixelFormat = pf32bit then
Result.AlphaFormat := afIgnored;
end
else
begin
BufferImage := GetScaledImage(SourceImage, AWidth, AHeight);
try
Result.Assign(BufferImage);
if Result.PixelFormat = pf32bit then
Result.AlphaFormat := afIgnored;
finally
BufferImage.Free;
end;
end;
end;
end;
function TImageCollection.GetBitmap(const AName: String; AWidth, AHeight: Integer; AEnabled: Boolean = True): TBitmap;
begin
Result := GetBitmap(GetIndexByName(AName), AWidth, AHeight);
end;
procedure TImageCollection.DrawSource(ACanvas: TCanvas; ARect: TRect; AIndex: Integer; ASourceIndex: Integer; AProportional: Boolean = False);
var
SourceImage, BufferImage: TWICImage;
begin
if ARect.IsEmpty then
Exit;
SourceImage := GetSourceImageByIndex(AIndex, ASourceIndex);
if SourceImage <> nil then
begin
if AProportional then
ARect := UpdateRectForProportionalSize(ARect, SourceImage.Width, SourceImage.Height, False);
BufferImage := GetScaledImage(SourceImage, ARect.Width, ARect.Height);
try
ACanvas.Draw(ARect.Left, ARect.Top, BufferImage);
finally
BufferImage.Free;
end;
end;
end;
procedure TImageCollection.DoDraw(ACanvas: TCanvas; ARect: TRect; AIndex: Integer; AProportional: Boolean);
var
SourceImage, BufferImage: TWICImage;
begin
if ARect.IsEmpty then
Exit;
SourceImage := GetSourceImage(AIndex, ARect.Width, ARect.Height);
if SourceImage <> nil then
begin
if AProportional then
ARect := UpdateRectForProportionalSize(ARect, SourceImage.Width, SourceImage.Height, True);
BufferImage := GetScaledImage(SourceImage, ARect.Width, ARect.Height);
try
ACanvas.Draw(ARect.Left, ARect.Top, BufferImage);
finally
BufferImage.Free;
end;
end;
end;
procedure TImageCollection.Draw(ACanvas: TCanvas; ARect: TRect; AIndex: Integer; AProportional: Boolean = False);
begin
if Assigned(FOnDraw) then
FOnDraw(GetSourceImage(AIndex, ARect.Width, ARect.Height), ACanvas, ARect, AProportional)
else
DoDraw(ACanvas, ARect, AIndex, AProportional);
end;
procedure TImageCollection.Draw(ACanvas: TCanvas; ARect: TRect; const AName: String; AProportional: Boolean = False);
begin
if Assigned(FOnDraw) then
FOnDraw(GetSourceImage(GetIndexByName(AName), ARect.Width, ARect.Height),
ACanvas, ARect, AProportional)
else
DoDraw(ACanvas, ARect, GetIndexByName(AName), AProportional);
end;
procedure TImageCollection.Assign(Source: TPersistent);
begin
if Source is TImageCollection then
begin
FInterpolationMode := TImageCollection(Source).InterpolationMode;
LoadFromCollection(TImageCollection(Source));
end
else
inherited;
end;
procedure TImageCollection.LoadFromCollection(AImageCollection: TImageCollection);
var
I, J: Integer;
Item: TImageCollectionItem;
SourceItem: TImageCollectionSourceItem;
begin
FImages.BeginUpdate;
try
FImages.Clear;
for I := 0 to AImageCollection.Count - 1 do
begin
Item := FImages.Add;
Item.Name := AImageCollection.Images[I].Name;
for J := 0 to AImageCollection.Images[I].SourceImages.Count - 1 do
begin
SourceItem := FImages[I].SourceImages.Add;
SourceItem.FImage.Assign(AImageCollection.Images[I].SourceImages[J].FImage);
end;
end;
finally
FImages.EndUpdate;
Change;
end;
end;
initialization
StartClassGroup(TControl);
ActivateClassGroup(TControl);
GroupDescendentsWith(TImageCollection, Vcl.Controls.TControl);
end.
|
unit Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.ExtCtrls, Vcl.StdCtrls,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Redis.Commons,
Redis.Client,
Redis.NetLib.INDY,
Redis.Values
;
type
TForm5 = class(TForm)
Timer1: TTimer;
Panel1: TPanel;
Panel2: TPanel;
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
{ Private declarations }
FRedis: IRedisClient;
public
{ Public declarations }
end;
var
Form5: TForm5;
implementation
{$R *.dfm}
procedure TForm5.FormCreate(Sender: TObject);
begin
Self.FRedis := TRedisClient.Create('localhost', 6379);
Self.FRedis.Connect;
Self.Timer1.Enabled := True;
end;
procedure TForm5.Timer1Timer(Sender: TObject);
var
oSalas: TRedisArray;
oSala: TRedisString;
oRanking: TRedisArray;
oItem: TRedisString;
iPos: Integer;
sJogador: string;
sPonto: string;
begin
Self.Timer1.Enabled := False;
Self.Memo1.Clear;
try
oSalas := Self.FRedis.KEYS('RANKING:JOGO:SALA:*');
if oSalas.IsNull then
begin
Exit;
end;
for oSala in oSalas.Value do
begin
Self.Memo1.Lines.Add(Format('Sala: %s', [oSala.Value]));
Self.Memo1.Lines.Add('');
oRanking := Self.FRedis.ZREVRANGE(oSala.Value, 0, 2, TRedisScoreMode.WithScores);
for iPos := 1 to Length(oRanking.Value) do
begin
oItem := oRanking.Value[iPos - 1];
if Odd(iPos) then
begin
sPonto := oItem.Value;
end
else
begin
sJogador := oItem.Value;
Self.Memo1.Lines.Add(Format('%s -> %s', [sPonto, sJogador]));
end;
end;
Self.Memo1.Lines.Add('');
Self.Memo1.Lines.Add('<---------------------------------------->');
Self.Memo1.Lines.Add('');
end;
finally
Self.Timer1.Enabled := True;
end;
end;
end.
|
unit BrickCamp.RemoteInterface;
interface
uses
System.JSON,
Data.DB,
Datasnap.DBClient,
BrickCamp.Model;
type
TBrickCampRemoteInterface = class
public
function GetDataset(const Resource: TResourceType): TClientDataset;
function GetOne(const Resource: TResourceType): TJSONObject;
procedure Delete(const Id: Integer);
procedure Post(const Resource: TResourceType; const JSONObject: TJSONObject);
procedure Put(const Resource: TResourceType; const JSONObject: TJSONObject);
function LoginUser(const Name: string): Integer;
function GetQuestionsByProduct(const ProductId: Integer): TClientDataSet;
function GetAnswersByQuestion(const QuestionId: Integer): TClientDataSet;
end;
implementation
uses
System.SysUtils,
Data.Bind.EngExt, Data.Bind.Components, Data.Bind.ObjectScope,
Data.Bind.GenData, IPPeerClient, REST.Client, MARS.Client.Client,
REST.Response.Adapter, Data.Bind.DBScope, FireDAC.Stan.Intf, REST.Types,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Comp.DataSet,
FireDAC.Comp.Client,
FMX.Dialogs
;
const
BASEURL: string = 'http://localhost:8080/rest/cb';
{ TBrickCampRemoteInterface }
procedure TBrickCampRemoteInterface.Delete(const Id: Integer);
var
RestClient: TRESTClient;
Request: TRESTRequest;
Response: TRESTResponse;
begin
RestClient := TRESTClient.Create(BASEURL + RESOURCESTRINGS[rQuestion] + DELETE_GENERIC + '/' + IntToStr(Id));
Request := TRESTRequest.Create(nil);
Response := TRESTResponse.Create(nil);
try
Request.Client := RestClient;
Request.Response := Response;
Request.Method := rmDELETE;
Request.Execute;
finally
Response.Free;
Request.Free;
RestClient.Free;
end;
end;
function TBrickCampRemoteInterface.GetAnswersByQuestion(const QuestionId: Integer): TClientDataSet;
var
RestClient: TRESTClient;
Request: TRESTRequest;
Response: TRESTResponse;
DataSetAdapter: TRESTResponseDataSetAdapter;
begin
RestClient := TRESTClient.Create(BASEURL + RESOURCESTRINGS[rQuestion] + GET_ANSWER_GETLISTBYQUESTION + '/' + IntToStr(QuestionId));
Request := TRESTRequest.Create(nil);
Response := TRESTResponse.Create(nil);
DataSetAdapter := TRESTResponseDataSetAdapter.Create(nil);
Result := TClientDataSet.Create(nil);
try
Request.Client := RestClient;
Request.Response := Response;
Request.Method := rmGET;
DataSetAdapter.Response := Response;
DataSetAdapter.Dataset := Result;
Request.Execute;
finally
DataSetAdapter.Free;
Response.Free;
Request.Free;
RestClient.Free;
end;
end;
function TBrickCampRemoteInterface.GetDataset(const Resource: TResourceType): TClientDataset;
var
RestClient: TRESTClient;
Request: TRESTRequest;
Response: TRESTResponse;
DataSetAdapter: TRESTResponseDataSetAdapter;
begin
RestClient := TRESTClient.Create(BASEURL + RESOURCESTRINGS[Resource] + GET_GENERIC_GETLIST);
Request := TRESTRequest.Create(nil);
Response := TRESTResponse.Create(nil);
DataSetAdapter := TRESTResponseDataSetAdapter.Create(nil);
Result := TClientDataSet.Create(nil);
try
Request.Client := RestClient;
Request.Response := Response;
Request.Method := rmGET;
DataSetAdapter.Response := Response;
DataSetAdapter.Dataset := Result;
Request.Execute;
finally
DataSetAdapter.Free;
Response.Free;
Request.Free;
RestClient.Free;
end;
end;
function TBrickCampRemoteInterface.GetOne(const Resource: TResourceType): TJSONObject;
var
RestClient: TRESTClient;
Request: TRESTRequest;
Response: TRESTResponse;
begin
RestClient := TRESTClient.Create(BASEURL + RESOURCESTRINGS[Resource] + GET_GENERIC_GETONE);
Request := TRESTRequest.Create(nil);
Response := TRESTResponse.Create(nil);
try
Request.Client := RestClient;
Request.Response := Response;
Request.Method := rmGET;
Request.Execute;
Result := TJSONObject.ParseJSONValue(Response.Content) as TJSONObject;
finally
Response.Free;
Request.Free;
RestClient.Free;
end;
end;
function TBrickCampRemoteInterface.GetQuestionsByProduct(const ProductId: Integer): TClientDataSet;
var
RestClient: TRESTClient;
Request: TRESTRequest;
Response: TRESTResponse;
DataSetAdapter: TRESTResponseDataSetAdapter;
begin
RestClient := TRESTClient.Create(BASEURL + RESOURCESTRINGS[rQuestion] + GET_QUESTION_GETLISTBYPRODUCT + '/' + IntToStr(ProductId));
Request := TRESTRequest.Create(nil);
Response := TRESTResponse.Create(nil);
DataSetAdapter := TRESTResponseDataSetAdapter.Create(nil);
Result := TClientDataSet.Create(nil);
try
Request.Client := RestClient;
Request.Response := Response;
Request.Method := rmGET;
DataSetAdapter.Response := Response;
DataSetAdapter.Dataset := Result;
Request.Execute;
finally
DataSetAdapter.Free;
Response.Free;
Request.Free;
RestClient.Free;
end;
end;
function TBrickCampRemoteInterface.LoginUser(const Name: string): Integer;
var
RestClient: TRESTClient;
Request: TRESTRequest;
Response: TRESTResponse;
JSONObject: TJSONObject;
begin
Result := -1;
RestClient := TRESTClient.Create(BASEURL + RESOURCESTRINGS[rUser] + GET_USER_ONEBYNAME + '/' + Name);
Request := TRESTRequest.Create(nil);
Response := TRESTResponse.Create(nil);
try
Request.Client := RestClient;
Request.Response := Response;
Request.Method := rmGET;
Request.Execute;
JSONObject := JSONObject.ParseJSONValue(Response.Content) as TJSONObject;
try
if Assigned(JSONObject) then
Result := StrToIntDef(JSONObject.GetValue('ID').Value, -1);
finally
JSONObject.Free;
end;
finally
Response.Free;
Request.Free;
RestClient.Free;
end;
end;
procedure TBrickCampRemoteInterface.Post(const Resource: TResourceType; const JSONObject: TJSONObject);
var
RestClient: TRESTClient;
Request: TRESTRequest;
Response: TRESTResponse;
begin
RestClient := TRESTClient.Create(BASEURL + RESOURCESTRINGS[Resource] + POST_GENERIC);
Request := TRESTRequest.Create(nil);
Response := TRESTResponse.Create(nil);
try
Request.Client := RestClient;
Request.Response := Response;
Request.Method := rmPost;
Request.Body.JSONWriter.WriteRaw(JSONObject.ToString);
Request.Execute;
finally
Response.Free;
Request.Free;
RestClient.Free;
end;
end;
procedure TBrickCampRemoteInterface.Put(const Resource: TResourceType; const JSONObject: TJSONObject);
var
RestClient: TRESTClient;
Request: TRESTRequest;
Response: TRESTResponse;
begin
RestClient := TRESTClient.Create(BASEURL + RESOURCESTRINGS[Resource] + PUT_GENERIC);
Request := TRESTRequest.Create(nil);
Response := TRESTResponse.Create(nil);
try
Request.Client := RestClient;
Request.Response := Response;
Request.Method := rmPut;
Request.Body.JSONWriter.WriteRaw(JSONObject.ToString);
Request.Execute;
finally
Response.Free;
Request.Free;
RestClient.Free;
end;
end;
end.
|
program odwrota_notacja_polska;
const MAX_S = 100; // definiuje rozmiar stosu
var
S : array[0..MAX_S-1] of double; // stos
p : integer; // wskaźnik stosu
e : string; // element wyrażenia ONP
v1,v2 : double; // argumenty operacji
c : word; // pozycja błędu przy konwersji
begin
p := 0; // inicjujemy stos;
repeat // w pętli przetwarzamy wyrażenie ONP
readln(e); // odczytujemy element wyrażenia ONP
if e = '=' then break;
val(e,v1,c); // dokonujemy konwersji
if c = 0 then
begin // liczba
S[p] := v1; // umieszczamy ją na stosie
inc(p); // zwiększamy wskaźnik stosu
end
else
begin // operator
v1 := S[p-2]; // pobieramy ze stosu dwa argumenty
v2 := S[p-1];
case e of // wykonujemy operacje wg operatora
'+' : v1 := v1 + v2;
'-' : v1 := v1 - v2;
'*' : v1 := v1 * v2;
'/' : v1 := v1 / v2;
end;
S[p-2] := v1; // wynik umieszczamy na stosie
dec(p); // ze stosu zniknęła jedna liczba
end;
until false;
writeln(S[p-1]:0:6); // wypisujemy wynik ze szczytu stosu
end.
|
unit SimpleDemo.View.Page.Cadastros.Sub;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts,
Router4D.Interfaces;
type
TSubCadastros = class(TForm, iRouter4DComponent)
Layout1: TLayout;
Label1: TLabel;
private
{ Private declarations }
public
{ Public declarations }
function Render : TFMXObject;
procedure UnRender;
end;
var
SubCadastros: TSubCadastros;
implementation
uses
Router4D.History;
{$R *.fmx}
{ TSubCadastros }
function TSubCadastros.Render: TFMXObject;
begin
Result := Layout1;
end;
procedure TSubCadastros.UnRender;
begin
//
end;
end.
|
unit TestTextAfterUnitEnd;
{ AFS Noc 2003
Test text after unit end }
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is TestTextAfterUnitEnd, released nov 2003.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 2003 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
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/NPL/
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.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
uses
TestFrameWork,
BaseTestProcess;
type
TTestTextAfterUnitEnd = class(TBaseTestProcess)
private
fiSaveLines: integer;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestTooFew;
procedure TestTooMany;
procedure TestComment;
procedure TestText;
procedure TestMoreText;
procedure TestText3;
procedure TestText4;
end;
implementation
uses
JcfStringUtils,
JcfSettings,
ReturnsAfterFinalEnd;
const
TEST_UNIT = UNIT_HEADER + UNIT_FOOTER;
procedure TTestTextAfterUnitEnd.Setup;
begin
inherited;
fiSaveLines := JcfFormatSettings.Returns.NumReturnsAfterFinalEnd;
end;
procedure TTestTextAfterUnitEnd.Teardown;
begin
inherited;
JcfFormatSettings.Returns.NumReturnsAfterFinalEnd := fiSaveLines;
end;
procedure TTestTextAfterUnitEnd.TestTooFew;
const
IN_UNIT_TEXT = TEST_UNIT;
OUT_UNIT_TEXT = TEST_UNIT + NativeLineBreak + NativeLineBreak;
begin
JcfFormatSettings.Returns.NumReturnsAfterFinalEnd := 3;
TestProcessResult(TReturnsAfterFinalEnd, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestTextAfterUnitEnd.TestTooMany;
const
IN_UNIT_TEXT = TEST_UNIT + NativeLineBreak + NativeLineBreak + NativeLineBreak + NativeLineBreak;
OUT_UNIT_TEXT = TEST_UNIT + NativeLineBreak + NativeLineBreak;
begin
JcfFormatSettings.Returns.NumReturnsAfterFinalEnd := 3;
TestProcessResult(TReturnsAfterFinalEnd, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestTextAfterUnitEnd.TestComment;
const
IN_UNIT_TEXT = TEST_UNIT + NativeLineBreak + '//foo' + NativeLineBreak + NativeLineBreak + NativeLineBreak;
OUT_UNIT_TEXT = TEST_UNIT + NativeLineBreak + '//foo' + NativeLineBreak;
begin
JcfFormatSettings.Returns.NumReturnsAfterFinalEnd := 3;
TestProcessResult(TReturnsAfterFinalEnd, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestTextAfterUnitEnd.TestText;
const
IN_UNIT_TEXT = TEST_UNIT + NativeLineBreak + 'junk' + NativeLineBreak +
NativeLineBreak + NativeLineBreak;
OUT_UNIT_TEXT = TEST_UNIT + NativeLineBreak + 'junk' + NativeLineBreak;
begin
JcfFormatSettings.Returns.NumReturnsAfterFinalEnd := 3;
TestProcessResult(TReturnsAfterFinalEnd, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestTextAfterUnitEnd.TestMoreText;
const
IN_UNIT_TEXT = TEST_UNIT + NativeLineBreak + 'junk' + NativeLineBreak +
'more junk' + NativeLineBreak + NativeLineBreak;
OUT_UNIT_TEXT = TEST_UNIT + NativeLineBreak + 'junk' + NativeLineBreak +
'more junk';
begin
JcfFormatSettings.Returns.NumReturnsAfterFinalEnd := 3;
TestProcessResult(TReturnsAfterFinalEnd, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestTextAfterUnitEnd.TestText3;
const
IN_UNIT_TEXT = TEST_UNIT + NativeLineBreak + 'junk' + NativeLineBreak +
'more junk' + NativeLineBreak +
'warrawak' + NativeLineBreak +
NativeLineBreak;
OUT_UNIT_TEXT = TEST_UNIT + NativeLineBreak + 'junk' + NativeLineBreak +
'more junk' + NativeLineBreak +
'warrawak';
begin
JcfFormatSettings.Returns.NumReturnsAfterFinalEnd := 3;
TestProcessResult(TReturnsAfterFinalEnd, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
procedure TTestTextAfterUnitEnd.TestText4;
const
IN_UNIT_TEXT = TEST_UNIT + NativeLineBreak + 'junk' + NativeLineBreak +
'more junk' + NativeLineBreak +
'warrawak' + NativeLineBreak +
'narrank' + NativeLineBreak +
NativeLineBreak;
OUT_UNIT_TEXT = TEST_UNIT + NativeLineBreak + 'junk' + NativeLineBreak +
'more junk' + NativeLineBreak +
'warrawak' + NativeLineBreak +
'narrank';
begin
JcfFormatSettings.Returns.NumReturnsAfterFinalEnd := 3;
TestProcessResult(TReturnsAfterFinalEnd, IN_UNIT_TEXT, OUT_UNIT_TEXT);
end;
initialization
TestFramework.RegisterTest('Processes', TTestTextAfterUnitEnd.Suite);
end.
|
unit FIToolkit.Config.FixInsight;
interface
uses
System.SysUtils, System.Types,
FIToolkit.Commons.Types, FIToolkit.Config.Types, FIToolkit.Config.TypedDefaults, FIToolkit.Config.Consts;
type
DefaultCompilerDefines = class (TDefaultStringArrayValue); //FI:C104
DefaultOutputFileName = class (TDefaultFileNameValue); //FI:C104
DefaultOutputFormat = class (TDefaultOutputFormatValue); //FI:C104
DefaultSettingsFileName = class (TDefaultFileNameValue); //FI:C104
DefaultSilent = class (TDefaultBooleanValue); //FI:C104
TFixInsightOptions = class sealed
strict private
FCompilerDefines : TStringDynArray;
FOutputFileName : TAssignableFileName;
FOutputFormat : TFixInsightOutputFormat;
FProjectFileName : TAssignableFileName;
FSettingsFileName : TAssignableFileName;
FSilent : Boolean;
FValidate : Boolean;
private
function FormatCompilerDefines : String;
function FormatOutputFileName : String;
function FormatOutputFormat : String;
function FormatProjectFileName : String;
function FormatSettingsFileName : String;
function FormatSilent : String;
procedure ValidateOutputFileName(const Value : TFileName);
procedure ValidateProjectFileName(const Value : TFileName);
procedure ValidateSettingsFileName(const Value : TFileName);
function GetOutputFileName : TFileName;
function GetProjectFileName : TFileName;
function GetSettingsFileName : TFileName;
procedure SetOutputFileName(const Value : TFileName);
procedure SetProjectFileName(const Value : TFileName);
procedure SetSettingsFileName(const Value : TFileName);
public
function ToString : String; override; final;
public
procedure Assign(Source : TFixInsightOptions; CheckValid : Boolean);
[FixInsightParam(STR_CFG_VALUE_ARR_DELIM_DEFAULT), DefaultCompilerDefines]
property CompilerDefines : TStringDynArray read FCompilerDefines write FCompilerDefines;
[FixInsightParam(False), DefaultOutputFileName(DEF_FIO_STR_OUTPUT_FILENAME)]
property OutputFileName : TFileName read GetOutputFileName write SetOutputFileName;
[FixInsightParam(False), DefaultOutputFormat(DEF_FIO_ENUM_OUTPUT_FORMAT)]
property OutputFormat : TFixInsightOutputFormat read FOutputFormat write FOutputFormat;
[FixInsightParam(False)]
property ProjectFileName : TFileName read GetProjectFileName write SetProjectFileName;
[FixInsightParam, DefaultSettingsFileName(DEF_FIO_STR_SETTINGS_FILENAME)]
property SettingsFileName : TFileName read GetSettingsFileName write SetSettingsFileName;
[FixInsightParam(False), DefaultSilent(DEF_FIO_BOOL_SILENT)]
property Silent : Boolean read FSilent write FSilent;
property Validate : Boolean read FValidate write FValidate;
end;
implementation
uses
System.IOUtils, System.Rtti,
FIToolkit.Config.Exceptions, FIToolkit.Config.Defaults, FIToolkit.Commons.Utils, FIToolkit.CommandLine.Types;
{ TFixInsightOptions }
procedure TFixInsightOptions.Assign(Source : TFixInsightOptions; CheckValid : Boolean);
var
bValidate : Boolean;
begin
if Assigned(Source) then
begin
bValidate := FValidate;
FValidate := CheckValid;
try
TObjectProperties<TFixInsightOptions>.Copy(Source, Self,
function (Instance : TObject; Prop : TRttiProperty) : Boolean
var
Attr : TCustomAttribute;
begin
Result := False;
for Attr in Prop.GetAttributes do
if Attr is FixInsightParam then
Exit(True);
end
);
finally
FValidate := bValidate;
end;
end;
end;
function TFixInsightOptions.FormatCompilerDefines : String;
begin
Result := String.Join(STR_FIPARAM_VALUES_DELIM, FCompilerDefines);
if not Result.IsEmpty then
Result := STR_FIPARAM_DEFINES + Result;
end;
function TFixInsightOptions.FormatOutputFileName : String;
begin
Result := STR_FIPARAM_OUTPUT + TPath.GetQuotedPath(FOutputFileName, TCLIOptionString.CHR_QUOTE);
end;
function TFixInsightOptions.FormatOutputFormat : String;
begin
Result := String.Empty;
case FOutputFormat of
fiofPlainText:
Result := String.Empty;
fiofXML:
Result := STR_FIPARAM_XML;
else
Assert(False, 'Unhandled FixInsight output format type while converting to string.');
end;
end;
function TFixInsightOptions.FormatProjectFileName : String;
begin
if TFile.Exists(FProjectFileName) then
Result := TPath.GetFullPath(FProjectFileName)
else
Result := FProjectFileName;
Result := STR_FIPARAM_PROJECT + TPath.GetQuotedPath(Result, TCLIOptionString.CHR_QUOTE);
end;
function TFixInsightOptions.FormatSettingsFileName : String;
begin
if String(FSettingsFileName).IsEmpty then
Result := String.Empty
else
Result := STR_FIPARAM_SETTINGS + TPath.GetQuotedPath(FSettingsFileName, TCLIOptionString.CHR_QUOTE);
end;
function TFixInsightOptions.FormatSilent : String;
begin
Result := Iff.Get<String>(FSilent, STR_FIPARAM_SILENT, String.Empty);
end;
function TFixInsightOptions.GetOutputFileName : TFileName;
begin
Result := FOutputFileName;
end;
function TFixInsightOptions.GetProjectFileName : TFileName;
begin
Result := FProjectFileName;
end;
function TFixInsightOptions.GetSettingsFileName : TFileName;
begin
Result := FSettingsFileName;
end;
procedure TFixInsightOptions.SetOutputFileName(const Value : TFileName);
begin
if not FOutputFileName.Assigned or (FOutputFileName <> Value) then
begin
if FValidate then
ValidateOutputFileName(Value);
FOutputFileName := Value;
end;
end;
procedure TFixInsightOptions.SetProjectFileName(const Value : TFileName);
begin
if not FProjectFileName.Assigned or (FProjectFileName <> Value) then
begin
if FValidate then
ValidateProjectFileName(Value);
FProjectFileName := Value;
end;
end;
procedure TFixInsightOptions.SetSettingsFileName(const Value : TFileName);
begin
if not FSettingsFileName.Assigned or (FSettingsFileName <> Value) then
begin
if FValidate then
ValidateSettingsFileName(Value);
FSettingsFileName := Value;
end;
end;
function TFixInsightOptions.ToString : String;
begin
if FValidate then
begin
ValidateOutputFileName(FOutputFileName);
ValidateProjectFileName(FProjectFileName);
ValidateSettingsFileName(FSettingsFileName);
end;
Result := Trim(Format('%s %s %s %s %s %s',
[FormatProjectFileName, FormatCompilerDefines, FormatSettingsFileName,
FormatOutputFileName, FormatOutputFormat, FormatSilent]));
end;
procedure TFixInsightOptions.ValidateOutputFileName(const Value : TFileName);
begin
if String.IsNullOrWhiteSpace(Value) then
raise EFIOEmptyOutputFileName.Create;
if not TDirectory.Exists(ExtractFilePath(Value)) then
raise EFIOOutputDirectoryNotFound.Create;
if not TPath.IsApplicableFileName(ExtractFileName(Value)) then
raise EFIOInvalidOutputFileName.Create;
end;
procedure TFixInsightOptions.ValidateProjectFileName(const Value : TFileName);
begin
if not TFile.Exists(Value) then
raise EFIOProjectFileNotFound.Create;
end;
procedure TFixInsightOptions.ValidateSettingsFileName(const Value : TFileName);
begin
if not (Value.IsEmpty or TFile.Exists(Value)) then
raise EFIOSettingsFileNotFound.Create;
end;
initialization
RegisterDefaultValue(DefaultCompilerDefines, TValue.From<TStringDynArray>(DEF_FIO_ARR_COMPILER_DEFINES));
end.
|
unit uXplControl;
interface
uses MemMap, uXplCommon, Classes;
type
TXPLcontrol = class
private
fMM: TMemMap;
pBuffer: PXplComRecord;
fVars: TStringList;
fCommands: TStringList;
fActiveDuringCompilation: Boolean;
procedure DebugLog(Value: String);
function GetCustomXplVariable(pName: String; pIndex: Integer; isArray: Boolean): Variant;
procedure SetCustomXplVariable(pName: String; pIndex: Integer; pValue: Variant; isArray: Boolean; pToggleCommand: Integer);
procedure WaitForXplane(mSec: Integer = 500);
procedure WaitForXplaneSlot(pSlot: Integer; mSec: Integer = 500);
function GetLatitude: double;
function GetLongitude: double;
function GetHeading: double;
function GetElevation: double;
function GetPosRefreshInterval: Integer;
procedure SetPosRefreshInterval(const Value: Integer);
function GetFreeComSlot: Integer;
public
{ Public declarations }
constructor Create(pOwner: TObject);
destructor Destroy; Override;
function IsXplaneReady: Boolean;
function isXplaneConnected: Boolean;
function GetXplVariable(pName: String): Variant;
function GetXplArrayItem(pName: String; pIndex: Integer): Variant;
procedure SetXplVariable(pName: String; pValue: Variant);
procedure SetXplArrayItem(pName: String; pIndex: Integer; pValue: Variant);
procedure ExecuteCommand(pCmdName: String; pMode: Byte = HDMC_EXEC_COMMAND);
procedure AddCommands(l : TStrings);
procedure ToggleDataRef(pName: String; pValues: String; pCommand: Integer);
procedure DrawText(pText: String; pPos: Single = 0; pSec: Integer = 5);
property ActiveDuringCompilation: Boolean read fActiveDuringCompilation write fActiveDuringCompilation;
property Latitude: double read GetLatitude;
property Longitude: double read GetLongitude;
property Heading: double read GetHeading;
property Elevation: double read GetElevation;
property PosRefreshInterval: Integer read GetPosRefreshInterval write SetPosRefreshInterval;
end;
TXPLRefHolder = class
private
fData: Pointer8b;
public
property Data: Pointer8b read fData write fData;
end;
implementation
uses SysUtils, uGlobals, Windows, Forms, Variants, XPLMDataAccess,
XPLMUtilities;
{ TXPLcontrol }
constructor TXPLcontrol.Create(pOwner: TObject);
var
lGlb: THDMGlobals;
begin
lGlb := (pOwner as THDMGlobals);
lGlb.DebugLog('Xplane control created.', 'XPL');
fVars := TStringList.Create;
fVars.CaseSensitive := False;
fCommands := TStringList.Create;
fCommands.CaseSensitive := False;
fActiveDuringCompilation := False;
fMM := TMemMap.Create(XPL_MEM_FILE, SizeOf(TXplComRecord));
if fMM.Memory <> nil then
begin
pBuffer := fMM.Memory;
//DebugLog(Format('pBuffer addr is %s.', [IntToStr(ULong(pBuffer))]));
if pBuffer^.XplConnected > 0 then
lGlb.DebugLog('Xplane already connected to shared memory.', 'XPL')
else
lGlb.DebugLog('Xplane not yet connected to shared memory.', 'XPL');
pBuffer^.HdmConnected := 1;
pBuffer^.ComSlots[0].HDMcommand := 0; // NOP, just ping
pBuffer^.ComSlots[0].XplRequestFlag := 1;
pBuffer^.XplRequestFlag := 1; // ask XPL for response
end;
lGlb.DebugLog(Format('Slot size: %d, mem size: %d', [SizeOf(TXplComSlot), SizeOf(TXplComRecord)]), 'XPL');
end;
procedure TXPLcontrol.DebugLog(Value: String);
begin
if Glb <> nil then
Glb.DebugLog(Value, 'XPL');
end;
destructor TXPLcontrol.Destroy;
var I: Integer;
begin
for I := 0 to fVars.Count - 1 do
fVars.Objects[I].Free;
fVars.Free;
for I := 0 to fCommands.Count - 1 do
fCommands.Objects[I].Free;
fCommands.Free;
fMM.Free;
inherited;
end;
procedure TXPLcontrol.ExecuteCommand(pCmdName: String; pMode: Byte = HDMC_EXEC_COMMAND);
var
lCommandIndex: Integer;
//lCommand: XPLMCommandRef;
lCommand: Pointer8b;
lStr: String;
lUnregistered: Boolean;
lSlot: Integer;
lRef: TXPLRefHolder;
begin
if (fMM.Memory = nil) or (not isXplaneConnected) then
exit;
if (not fActiveDuringCompilation) and (Glb.ScriptEngine.Compiling) then
exit;
lSlot := GetFreeComSlot;
if lSlot < 0 then
begin
WaitForXplane;
lSlot := GetFreeComSlot;
if lSlot < 0 then
begin
DebugLog('Can''t execute command, Xplane not listening.');
exit;
end;
end;
if Glb.IsModuleLogged('XPL') then
pBuffer^.Debug := True;
lCommandIndex := fCommands.IndexOf(pCmdName);
if lCommandIndex > -1 then
begin
lCommand := TXPLRefHolder(fCommands.Objects[lCommandIndex]).Data;
pBuffer^.ComSlots[lSlot].CommandRef := lCommand;
lUnregistered := False;
end
else
begin
// find out first
StrPCopy(pBuffer^.ComSlots[lSlot].ValueName, pCmdName);
pBuffer^.ComSlots[lSlot].CommandRef := 0;
lUnregistered := True;
end;
pBuffer^.ComSlots[lSlot].HDMcommand := pMode;
pBuffer^.ComSlots[lSlot].XplRequestFlag := 1; // trigger xpl
pBuffer^.XplRequestFlag := 1;
// if unregistered, wait for result and note down the address
if lUnregistered then
begin
WaitForXplaneSlot(lSlot);
if pBuffer^.ComSlots[lSlot].XplRequestFlag = 0 then
begin
lCommand := pBuffer^.ComSlots[lSlot].CommandRef;
if lCommand = 0 then
Glb.LogError(Format('Command %s not recognized by Xplane.', [pCmdName]))
else
begin
lRef := TXPLRefHolder.Create;
lRef.Data := lCommand;
fCommands.AddObject(pCmdName, lRef);
DebugLog(Format('Registered command %s as address %x.', [pCmdName, pBuffer^.ComSlots[lSlot].CommandRef]));
end;
end;
end;
end;
procedure TXPLcontrol.DrawText(pText: String; pPos: Single = 0; pSec: Integer = 5);
var
lSlot: Integer;
begin
if (fMM.Memory = nil) or (not isXplaneConnected) then
exit;
if (not fActiveDuringCompilation) and (Glb.ScriptEngine.Compiling) then
exit;
lSlot := GetFreeComSlot;
if lSlot < 0 then
begin
WaitForXplane;
lSlot := GetFreeComSlot;
if lSlot < 0 then
begin
DebugLog('Can''t draw text, Xplane not listening.');
exit;
end;
end;
if Glb.IsModuleLogged('XPL') then
pBuffer^.Debug := True;
// find out first
StrPCopy(pBuffer^.ComSlots[lSlot].StringBuffer, pText);
pBuffer^.ComSlots[lSlot].HDMcommand := HDMC_SHOW_TEXT;
pBuffer^.ComSlots[lSlot].Value.floatData := pPos;
pBuffer^.ComSlots[lSlot].Length := pSec;
DebugLog(Format('Sending DrawText command for text %s at pos %f.', [pText, pPos]));
pBuffer^.ComSlots[lSlot].XplRequestFlag := 1; // trigger xpl
pBuffer^.XplRequestFlag := 1;
end;
function TXPLcontrol.GetCustomXplVariable(pName: String; pIndex: Integer;
isArray: Boolean): Variant;
var
lVarIndex: Integer;
lVar: TXplVariable;
lSecCounter: Integer;
lRes: String;
lSlot: Integer;
lVariant: Variant;
begin
Result := 0;
if (fMM.Memory = nil) or (not isXplaneConnected) then
exit;
if (not fActiveDuringCompilation) and (Glb.ScriptEngine.Compiling) then
exit;
lSlot := GetFreeComSlot;
if lSlot < 0 then
begin
WaitForXplane;
lSlot := GetFreeComSlot;
if lSlot < 0 then
begin
DebugLog('Can''t get variable, Xplane not listening.');
exit;
end;
end;
if Glb.IsModuleLogged('XPL') then
pBuffer^.Debug := True;
lVarIndex := fVars.IndexOf(pName);
if lVarIndex > -1 then
begin
lVar := fVars.Objects[lVarIndex] as TXplVariable;
pBuffer^.ComSlots[lSlot].DataRef := lVar.DataRef;
pBuffer^.ComSlots[lSlot].DataType := lVar.DataType;
end
else
begin
// find out first
StrPCopy(pBuffer^.ComSlots[lSlot].ValueName, pName);
pBuffer^.ComSlots[lSlot].DataRef := 0;
end;
if isArray then
pBuffer^.ComSlots[lSlot].Index := pIndex;
pBuffer^.ComSlots[lSlot].HDMcommand := HDMC_GET_VAR;
pBuffer^.ComSlots[lSlot].XplRequestFlag := 1; // trigger xpl
pBuffer^.XplRequestFlag := 1;
// wait for response
WaitForXplaneSlot(lSlot);
if pBuffer^.ComSlots[lSlot].XplRequestFlag = 0 then
begin
if pBuffer^.ComSlots[lSlot].DataType <> xplmType_Data then
begin
case pBuffer^.ComSlots[lSlot].DataType of
xplmType_Float: Result := pBuffer^.ComSlots[lSlot].Value.floatData;
xplmType_Double: Result := pBuffer^.ComSlots[lSlot].Value.doubleData;
xplmType_Int: Result := pBuffer^.ComSlots[lSlot].Value.intData;
xplmType_IntArray: Result := pBuffer^.ComSlots[lSlot].Value.intData;
xplmType_FloatArray: Result := pBuffer^.ComSlots[lSlot].Value.floatData;
end;
end
else
begin
// string
pBuffer^.ComSlots[lSlot].StringBuffer[XPL_MAX_STRING_SIZE -1] := #0; // for sure
lRes := pBuffer^.ComSlots[lSlot].StringBuffer;
DebugLog('Received string result ' + lRes);
Result := lRes;
end;
if lVarIndex < 0 then
begin
// register returned variable ref
if (pBuffer^.ComSlots[lSlot].DataRef = 0) then
DebugLog('WARNING: no dataref received from Xplane for variable ' + pName + '.')
else
begin
lVar := TXplVariable.Create;
lVar.Name := pName;
lVar.DataRef := pBuffer^.ComSlots[lSlot].DataRef;
lVar.DataType := pBuffer^.ComSlots[lSlot].DataType;
lVar.Writable := pBuffer^.ComSlots[lSlot].Writable;
if lVar.IsArray then
lVar.Length := pBuffer^.ComSlots[lSlot].Length
else
lVar.Length := 0;
fVars.AddObject(pName, lVar);
DebugLog(Format('Registered var %s at address %x.', [pName, pBuffer^.ComSlots[lSlot].DataRef]))
end;
end;
end
else
begin
DebugLog('Variable ' + pName + ' timed out - no response from Xplane.');
end;
end;
function TXPLcontrol.GetElevation: double;
begin
Result := pBuffer^.Height;
end;
function TXPLcontrol.GetFreeComSlot: Integer;
var I: Integer;
begin
for I := 0 to COM_SLOTS_COUNT - 1 do
if pBuffer^.ComSlots[I].XplRequestFlag = 0 then
begin
Result := I;
exit;
end;
Result := -1;
end;
function TXPLcontrol.GetHeading: double;
begin
Result := pBuffer^.Heading;
end;
function TXPLcontrol.GetLatitude: double;
begin
Result := pBuffer^.Latitude;
end;
function TXPLcontrol.GetLongitude: double;
begin
Result := pBuffer^.Longitude;
end;
function TXPLcontrol.GetPosRefreshInterval: Integer;
begin
Result := pBuffer^.PosInterval;
end;
function TXPLcontrol.GetXplArrayItem(pName: String; pIndex: Integer): Variant;
begin
Result := GetCustomXplVariable(pName, pIndex, True);
end;
function TXPLcontrol.GetXplVariable(pName: String): Variant;
begin
Result := GetCustomXplVariable(pName, 0, False);
end;
function TXPLcontrol.isXplaneConnected: Boolean;
begin
Result := (pBuffer <> nil) and (pBuffer^.XplConnected = 1);
end;
function TXPLcontrol.IsXplaneReady: Boolean;
begin
Result := (pBuffer <> nil) and (pBuffer^.XplRequestFlag = 0);
end;
procedure TXPLcontrol.SetCustomXplVariable(pName: String; pIndex: Integer;
pValue: Variant; isArray: Boolean; pToggleCommand: Integer);
var
lVarIndex: Integer;
lVar: TXplVariable;
lSecCounter: Integer;
lEndMsec: Cardinal;
lIsString: Boolean;
lStr: String;
lUnregistered: Boolean;
lSlot: Integer;
begin
if (fMM.Memory = nil) or (not isXplaneConnected) then
exit;
if (not fActiveDuringCompilation) and (Glb.ScriptEngine.Compiling) then
exit;
lSlot := GetFreeComSlot;
if lSlot < 0 then
begin
WaitForXplane;
lSlot := GetFreeComSlot;
if lSlot < 0 then
begin
DebugLog('Can''t set variable '+pName+', Xplane not listening.');
exit;
end;
end;
if Glb.IsModuleLogged('XPL') then
pBuffer^.Debug := True;
lIsString := VarType(pValue) = varOleStr;
lVarIndex := fVars.IndexOf(pName);
if lVarIndex > -1 then
begin
lVar := fVars.Objects[lVarIndex] as TXplVariable;
pBuffer^.ComSlots[lSlot].DataRef := lVar.DataRef;
pBuffer^.ComSlots[lSlot].DataType := lVar.DataType;
lIsString := pBuffer^.ComSlots[lSlot].DataType = xplmType_Data;
lUnregistered := False;
end
else
begin
// find out first
StrPCopy(pBuffer^.ComSlots[lSlot].ValueName, pName);
pBuffer^.ComSlots[lSlot].DataRef := 0;
lUnregistered := True;
end;
if isArray then
pBuffer^.ComSlots[lSlot].Index := pIndex;
lStr := pValue;
if lIsString then
begin
StrLCopy(pBuffer^.ComSlots[lSlot].StringBuffer, PChar(lStr), XPL_MAX_STRING_SIZE);
//pBuffer^.Length := Length(lStr); // keep always value from Xplane
DebugLog('Setting string variable to ' + lStr);
end
else
//pBuffer^.ComSlots[lSlot].Value := Variant2VariantBuffer(pValue);
StrLCopy(pBuffer^.ComSlots[lSlot].ValueUntyped, PChar(lStr), 255);
if pToggleCommand > 0 then
pBuffer^.ComSlots[lSlot].HDMcommand := pToggleCommand
else
pBuffer^.ComSlots[lSlot].HDMcommand := HDMC_SET_VAR;
pBuffer^.ComSlots[lSlot].XplRequestFlag := 1;
pBuffer^.XplRequestFlag := 1; // trigger xpl
// if unregistered, wait for result and note down the address
if lUnregistered then
begin
WaitForXplaneSlot(lSlot);
if pBuffer^.ComSlots[lSlot].XplRequestFlag = 0 then
begin
lVar := TXplVariable.Create;
lVar.Name := pName;
lVar.DataRef := pBuffer^.ComSlots[lSlot].DataRef;
lVar.DataType := pBuffer^.ComSlots[lSlot].DataType;
lVar.Writable := pBuffer^.ComSlots[lSlot].Writable;
if lVar.IsArray or lVar.IsString then
lVar.Length := pBuffer^.ComSlots[lSlot].Length
else
lVar.Length := 0;
fVars.AddObject(pName, lVar);
DebugLog(Format('Registered var %s at address %x.', [pName, pBuffer^.ComSlots[lSlot].DataRef]))
end;
end;
end;
procedure TXPLcontrol.SetPosRefreshInterval(const Value: Integer);
var
lSlot: Integer;
begin
if (fMM.Memory = nil) or (not isXplaneConnected) then
exit;
if (not fActiveDuringCompilation) and (Glb.ScriptEngine.Compiling) then
exit;
lSlot := GetFreeComSlot;
if lSlot < 0 then
begin
WaitForXplane;
lSlot := GetFreeComSlot;
if lSlot < 0 then
begin
DebugLog('Can''t set moving map refresh interval, Xplane not listening.');
exit;
end;
end;
if Glb.IsModuleLogged('XPL') then
pBuffer^.Debug := True;
pBuffer^.ComSlots[lSlot].HDMcommand := HDMC_SET_POSINTERVAL;
pBuffer^.PosInterval := Value;
pBuffer^.ComSlots[lSlot].XplRequestFlag := 1; // trigger xpl
pBuffer^.XplRequestFlag := 1; // trigger xpl
// if unregistered, wait for result and note down the address
//WaitForXplaneSlot(lSlot);
end;
procedure TXPLcontrol.SetXplArrayItem(pName: String; pIndex: Integer;
pValue: Variant);
begin
SetCustomXplVariable(pName, pIndex, pValue, True, 0);
end;
procedure TXPLcontrol.SetXplVariable(pName: String; pValue: Variant);
begin
SetCustomXplVariable(pName, 0, pValue, False, 0);
end;
procedure TXPLcontrol.ToggleDataRef(pName, pValues: String; pCommand: Integer);
begin
SetCustomXplVariable(pName, 0, pValues, False, pCommand);
end;
procedure TXPLcontrol.WaitForXplane(mSec: Integer = 500);
var
lEndMsec: Cardinal;
begin
if fMM.Memory = nil then
exit;
lEndMsec := GetTickCount + mSec;
while (GetTickCount < lEndMsec) and (pBuffer^.XplRequestFlag = 1) do
Application.ProcessMessages;
//Sleep(10);
end;
procedure TXPLcontrol.WaitForXplaneSlot(pSlot, mSec: Integer);
var
lEndMsec: Cardinal;
begin
if fMM.Memory = nil then
exit;
lEndMsec := GetTickCount + mSec;
while (GetTickCount < lEndMsec) and (pBuffer^.ComSlots[pSlot].XplRequestFlag = 1) do
Application.ProcessMessages;
//Sleep(10);
end;
procedure TXPLcontrol.AddCommands(l: TStrings);
begin
// l.Add('');
l.Add('sim/none/none');
l.Add('sim/operation/quit');
l.Add('sim/fadec/fadec_toggle');
l.Add('sim/engines/governor_toggle');
l.Add('sim/engines/clutch_toggle');
l.Add('sim/engines/engage_starters');
l.Add('sim/engines/throttle_down');
l.Add('sim/engines/throttle_up');
l.Add('sim/engines/prop_down');
l.Add('sim/engines/prop_up');
l.Add('sim/engines/mixture_down');
l.Add('sim/engines/mixture_up');
l.Add('sim/engines/mixture_min');
l.Add('sim/engines/mixture_max');
l.Add('sim/engines/carb_heat_on');
l.Add('sim/engines/carb_heat_off');
l.Add('sim/engines/carb_heat_toggle');
l.Add('sim/engines/idle_hi_lo_toggle');
l.Add('sim/engines/TOGA_power');
l.Add('sim/engines/thrust_reverse_toggle');
l.Add('sim/engines/thrust_reverse_hold');
l.Add('sim/magnetos/magnetos_off');
l.Add('sim/magnetos/magnetos_both');
l.Add('sim/starters/engage_start_run');
l.Add('sim/starters/shut_down');
l.Add('sim/magnetos/magnetos_off_1');
l.Add('sim/magnetos/magnetos_off_2');
l.Add('sim/magnetos/magnetos_off_3');
l.Add('sim/magnetos/magnetos_off_4');
l.Add('sim/magnetos/magnetos_off_5');
l.Add('sim/magnetos/magnetos_off_6');
l.Add('sim/magnetos/magnetos_off_7');
l.Add('sim/magnetos/magnetos_off_8');
l.Add('sim/magnetos/magnetos_down_1');
l.Add('sim/magnetos/magnetos_down_2');
l.Add('sim/magnetos/magnetos_down_3');
l.Add('sim/magnetos/magnetos_down_4');
l.Add('sim/magnetos/magnetos_down_5');
l.Add('sim/magnetos/magnetos_down_6');
l.Add('sim/magnetos/magnetos_down_7');
l.Add('sim/magnetos/magnetos_down_8');
l.Add('sim/magnetos/magnetos_up_1');
l.Add('sim/magnetos/magnetos_up_2');
l.Add('sim/magnetos/magnetos_up_3');
l.Add('sim/magnetos/magnetos_up_4');
l.Add('sim/magnetos/magnetos_up_5');
l.Add('sim/magnetos/magnetos_up_6');
l.Add('sim/magnetos/magnetos_up_7');
l.Add('sim/magnetos/magnetos_up_8');
l.Add('sim/magnetos/magnetos_left_1');
l.Add('sim/magnetos/magnetos_left_2');
l.Add('sim/magnetos/magnetos_left_3');
l.Add('sim/magnetos/magnetos_left_4');
l.Add('sim/magnetos/magnetos_left_5');
l.Add('sim/magnetos/magnetos_left_6');
l.Add('sim/magnetos/magnetos_left_7');
l.Add('sim/magnetos/magnetos_left_8');
l.Add('sim/magnetos/magnetos_right_1');
l.Add('sim/magnetos/magnetos_right_2');
l.Add('sim/magnetos/magnetos_right_3');
l.Add('sim/magnetos/magnetos_right_4');
l.Add('sim/magnetos/magnetos_right_5');
l.Add('sim/magnetos/magnetos_right_6');
l.Add('sim/magnetos/magnetos_right_7');
l.Add('sim/magnetos/magnetos_right_8');
l.Add('sim/magnetos/magnetos_both_1');
l.Add('sim/magnetos/magnetos_both_2');
l.Add('sim/magnetos/magnetos_both_3');
l.Add('sim/magnetos/magnetos_both_4');
l.Add('sim/magnetos/magnetos_both_5');
l.Add('sim/magnetos/magnetos_both_6');
l.Add('sim/magnetos/magnetos_both_7');
l.Add('sim/magnetos/magnetos_both_8');
l.Add('sim/starters/engage_starter_1');
l.Add('sim/starters/engage_starter_2');
l.Add('sim/starters/engage_starter_3');
l.Add('sim/starters/engage_starter_4');
l.Add('sim/starters/engage_starter_5');
l.Add('sim/starters/engage_starter_6');
l.Add('sim/starters/engage_starter_7');
l.Add('sim/starters/engage_starter_8');
l.Add('sim/starters/engage_start_run_1');
l.Add('sim/starters/engage_start_run_2');
l.Add('sim/starters/engage_start_run_3');
l.Add('sim/starters/engage_start_run_4');
l.Add('sim/starters/engage_start_run_5');
l.Add('sim/starters/engage_start_run_6');
l.Add('sim/starters/engage_start_run_7');
l.Add('sim/starters/engage_start_run_8');
l.Add('sim/starters/shut_down_1');
l.Add('sim/starters/shut_down_2');
l.Add('sim/starters/shut_down_3');
l.Add('sim/starters/shut_down_4');
l.Add('sim/starters/shut_down_5');
l.Add('sim/starters/shut_down_6');
l.Add('sim/starters/shut_down_7');
l.Add('sim/starters/shut_down_8');
l.Add('sim/igniters/igniter_arm_on_1');
l.Add('sim/igniters/igniter_arm_on_2');
l.Add('sim/igniters/igniter_arm_on_3');
l.Add('sim/igniters/igniter_arm_on_4');
l.Add('sim/igniters/igniter_arm_on_5');
l.Add('sim/igniters/igniter_arm_on_6');
l.Add('sim/igniters/igniter_arm_on_7');
l.Add('sim/igniters/igniter_arm_on_8');
l.Add('sim/igniters/igniter_arm_off_1');
l.Add('sim/igniters/igniter_arm_off_2');
l.Add('sim/igniters/igniter_arm_off_3');
l.Add('sim/igniters/igniter_arm_off_4');
l.Add('sim/igniters/igniter_arm_off_5');
l.Add('sim/igniters/igniter_arm_off_6');
l.Add('sim/igniters/igniter_arm_off_7');
l.Add('sim/igniters/igniter_arm_off_8');
l.Add('sim/igniters/igniter_contin_on_1');
l.Add('sim/igniters/igniter_contin_on_2');
l.Add('sim/igniters/igniter_contin_on_3');
l.Add('sim/igniters/igniter_contin_on_4');
l.Add('sim/igniters/igniter_contin_on_5');
l.Add('sim/igniters/igniter_contin_on_6');
l.Add('sim/igniters/igniter_contin_on_7');
l.Add('sim/igniters/igniter_contin_on_8');
l.Add('sim/igniters/igniter_contin_off_1');
l.Add('sim/igniters/igniter_contin_off_2');
l.Add('sim/igniters/igniter_contin_off_3');
l.Add('sim/igniters/igniter_contin_off_4');
l.Add('sim/igniters/igniter_contin_off_5');
l.Add('sim/igniters/igniter_contin_off_6');
l.Add('sim/igniters/igniter_contin_off_7');
l.Add('sim/igniters/igniter_contin_off_8');
l.Add('sim/fadec/fadec_1_on');
l.Add('sim/fadec/fadec_2_on');
l.Add('sim/fadec/fadec_3_on');
l.Add('sim/fadec/fadec_4_on');
l.Add('sim/fadec/fadec_5_on');
l.Add('sim/fadec/fadec_6_on');
l.Add('sim/fadec/fadec_7_on');
l.Add('sim/fadec/fadec_8_on');
l.Add('sim/fadec/fadec_1_off');
l.Add('sim/fadec/fadec_2_off');
l.Add('sim/fadec/fadec_3_off');
l.Add('sim/fadec/fadec_4_off');
l.Add('sim/fadec/fadec_5_off');
l.Add('sim/fadec/fadec_6_off');
l.Add('sim/fadec/fadec_7_off');
l.Add('sim/fadec/fadec_8_off');
l.Add('sim/engines/fire_ext_1_on');
l.Add('sim/engines/fire_ext_2_on');
l.Add('sim/engines/fire_ext_3_on');
l.Add('sim/engines/fire_ext_4_on');
l.Add('sim/engines/fire_ext_5_on');
l.Add('sim/engines/fire_ext_6_on');
l.Add('sim/engines/fire_ext_7_on');
l.Add('sim/engines/fire_ext_8_on');
l.Add('sim/engines/fire_ext_1_off');
l.Add('sim/engines/fire_ext_2_off');
l.Add('sim/engines/fire_ext_3_off');
l.Add('sim/engines/fire_ext_4_off');
l.Add('sim/engines/fire_ext_5_off');
l.Add('sim/engines/fire_ext_6_off');
l.Add('sim/engines/fire_ext_7_off');
l.Add('sim/engines/fire_ext_8_off');
l.Add('sim/electrical/generator_1_on');
l.Add('sim/electrical/generator_2_on');
l.Add('sim/electrical/generator_3_on');
l.Add('sim/electrical/generator_4_on');
l.Add('sim/electrical/generator_5_on');
l.Add('sim/electrical/generator_6_on');
l.Add('sim/electrical/generator_7_on');
l.Add('sim/electrical/generator_8_on');
l.Add('sim/electrical/generator_1_off');
l.Add('sim/electrical/generator_2_off');
l.Add('sim/electrical/generator_3_off');
l.Add('sim/electrical/generator_4_off');
l.Add('sim/electrical/generator_5_off');
l.Add('sim/electrical/generator_6_off');
l.Add('sim/electrical/generator_7_off');
l.Add('sim/electrical/generator_8_off');
l.Add('sim/electrical/generator_1_reset');
l.Add('sim/electrical/generator_2_reset');
l.Add('sim/electrical/generator_3_reset');
l.Add('sim/electrical/generator_4_reset');
l.Add('sim/electrical/generator_5_reset');
l.Add('sim/electrical/generator_6_reset');
l.Add('sim/electrical/generator_7_reset');
l.Add('sim/electrical/generator_8_reset');
l.Add('sim/altair/alternate_air_on_1');
l.Add('sim/altair/alternate_air_on_2');
l.Add('sim/altair/alternate_air_on_3');
l.Add('sim/altair/alternate_air_on_4');
l.Add('sim/altair/alternate_air_on_5');
l.Add('sim/altair/alternate_air_on_6');
l.Add('sim/altair/alternate_air_on_7');
l.Add('sim/altair/alternate_air_on_8');
l.Add('sim/altair/alternate_air_off_1');
l.Add('sim/altair/alternate_air_off_2');
l.Add('sim/altair/alternate_air_off_3');
l.Add('sim/altair/alternate_air_off_4');
l.Add('sim/altair/alternate_air_off_5');
l.Add('sim/altair/alternate_air_off_6');
l.Add('sim/altair/alternate_air_off_7');
l.Add('sim/altair/alternate_air_off_8');
l.Add('sim/altair/alternate_air_backup_on_1');
l.Add('sim/altair/alternate_air_backup_on_2');
l.Add('sim/altair/alternate_air_backup_on_3');
l.Add('sim/altair/alternate_air_backup_on_4');
l.Add('sim/altair/alternate_air_backup_on_5');
l.Add('sim/altair/alternate_air_backup_on_6');
l.Add('sim/altair/alternate_air_backup_on_7');
l.Add('sim/altair/alternate_air_backup_on_8');
l.Add('sim/altair/alternate_air_backup_off_1');
l.Add('sim/altair/alternate_air_backup_off_2');
l.Add('sim/altair/alternate_air_backup_off_3');
l.Add('sim/altair/alternate_air_backup_off_4');
l.Add('sim/altair/alternate_air_backup_off_5');
l.Add('sim/altair/alternate_air_backup_off_6');
l.Add('sim/altair/alternate_air_backup_off_7');
l.Add('sim/altair/alternate_air_backup_off_8');
l.Add('sim/engines/throttle_down_1');
l.Add('sim/engines/throttle_down_2');
l.Add('sim/engines/throttle_down_3');
l.Add('sim/engines/throttle_down_4');
l.Add('sim/engines/throttle_down_5');
l.Add('sim/engines/throttle_down_6');
l.Add('sim/engines/throttle_down_7');
l.Add('sim/engines/throttle_down_8');
l.Add('sim/engines/throttle_up_1');
l.Add('sim/engines/throttle_up_2');
l.Add('sim/engines/throttle_up_3');
l.Add('sim/engines/throttle_up_4');
l.Add('sim/engines/throttle_up_5');
l.Add('sim/engines/throttle_up_6');
l.Add('sim/engines/throttle_up_7');
l.Add('sim/engines/throttle_up_8');
l.Add('sim/engines/prop_down_1');
l.Add('sim/engines/prop_down_2');
l.Add('sim/engines/prop_down_3');
l.Add('sim/engines/prop_down_4');
l.Add('sim/engines/prop_down_5');
l.Add('sim/engines/prop_down_6');
l.Add('sim/engines/prop_down_7');
l.Add('sim/engines/prop_down_8');
l.Add('sim/engines/prop_up_1');
l.Add('sim/engines/prop_up_2');
l.Add('sim/engines/prop_up_3');
l.Add('sim/engines/prop_up_4');
l.Add('sim/engines/prop_up_5');
l.Add('sim/engines/prop_up_6');
l.Add('sim/engines/prop_up_7');
l.Add('sim/engines/prop_up_8');
l.Add('sim/engines/mixture_down_1');
l.Add('sim/engines/mixture_down_2');
l.Add('sim/engines/mixture_down_3');
l.Add('sim/engines/mixture_down_4');
l.Add('sim/engines/mixture_down_5');
l.Add('sim/engines/mixture_down_6');
l.Add('sim/engines/mixture_down_7');
l.Add('sim/engines/mixture_down_8');
l.Add('sim/engines/mixture_up_1');
l.Add('sim/engines/mixture_up_2');
l.Add('sim/engines/mixture_up_3');
l.Add('sim/engines/mixture_up_4');
l.Add('sim/engines/mixture_up_5');
l.Add('sim/engines/mixture_up_6');
l.Add('sim/engines/mixture_up_7');
l.Add('sim/engines/mixture_up_8');
l.Add('sim/flight_controls/pitch_trim_up');
l.Add('sim/flight_controls/pitch_trim_takeoff');
l.Add('sim/flight_controls/pitch_trim_down');
l.Add('sim/flight_controls/rudder_trim_left');
l.Add('sim/flight_controls/rudder_trim_center');
l.Add('sim/flight_controls/rudder_trim_right');
l.Add('sim/flight_controls/aileron_trim_left');
l.Add('sim/flight_controls/aileron_trim_center');
l.Add('sim/flight_controls/aileron_trim_right');
l.Add('sim/flight_controls/gyro_rotor_trim_up');
l.Add('sim/flight_controls/gyro_rotor_trim_down');
l.Add('sim/flight_controls/rudder_lft');
l.Add('sim/flight_controls/rudder_ctr');
l.Add('sim/flight_controls/rudder_rgt');
l.Add('sim/view/forward');
l.Add('sim/view/pan_up');
l.Add('sim/view/pan_down');
l.Add('sim/view/pan_up_fast');
l.Add('sim/view/pan_down_fast');
l.Add('sim/view/pan_left');
l.Add('sim/view/pan_right');
l.Add('sim/view/pan_left_fast');
l.Add('sim/view/pan_right_fast');
l.Add('sim/view/glance_left');
l.Add('sim/view/glance_right');
l.Add('sim/view/straight_up');
l.Add('sim/view/straight_down');
l.Add('sim/view/back');
l.Add('sim/view/left_up');
l.Add('sim/view/right_up');
l.Add('sim/view/forward_no_hud');
l.Add('sim/view/forward_with_hud');
l.Add('sim/view/tower');
l.Add('sim/view/runway');
l.Add('sim/view/chase');
l.Add('sim/view/circle');
l.Add('sim/view/circle_with_panel');
l.Add('sim/view/spot');
l.Add('sim/view/linear_spot');
l.Add('sim/view/center');
l.Add('sim/view/track_weapon');
l.Add('sim/view/cinema_verite');
l.Add('sim/view/sunglasses');
l.Add('sim/view/night_vision_toggle');
l.Add('sim/view/transparent_panel');
l.Add('sim/view/3d_cockpit');
l.Add('sim/view/3d_cockpit_toggle');
l.Add('sim/view/3d_cockpit_mouse_look');
l.Add('sim/view/free_view_toggle');
l.Add('sim/view/show_physics_model');
l.Add('sim/view/3d_path_toggle');
l.Add('sim/view/mouse_click_regions_toggle');
l.Add('sim/view/instrument_descriptions_toggle');
l.Add('sim/view/hold_3d_angle');
l.Add('sim/flight_controls/flaps_down');
l.Add('sim/flight_controls/flaps_up');
l.Add('sim/flight_controls/cowl_flaps_closed');
l.Add('sim/flight_controls/cowl_flaps_open');
l.Add('sim/flight_controls/landing_gear_down');
l.Add('sim/flight_controls/landing_gear_up');
l.Add('sim/flight_controls/landing_gear_toggle');
l.Add('sim/flight_controls/pump_flaps_and_gear');
l.Add('sim/flight_controls/nwheel_steer_toggle');
l.Add('sim/flight_controls/speed_brakes_down_one');
l.Add('sim/flight_controls/speed_brakes_up_one');
l.Add('sim/flight_controls/speed_brakes_down_all');
l.Add('sim/flight_controls/speed_brakes_up_all');
l.Add('sim/flight_controls/speed_brakes_toggle');
l.Add('sim/flight_controls/brakes_toggle_regular');
l.Add('sim/flight_controls/brakes_toggle_max');
l.Add('sim/flight_controls/brakes_regular');
l.Add('sim/flight_controls/brakes_max');
l.Add('sim/flight_controls/left_brake');
l.Add('sim/flight_controls/right_brake');
l.Add('sim/flight_controls/vector_sweep_aft');
l.Add('sim/flight_controls/vector_sweep_forward');
l.Add('sim/flight_controls/blimp_lift_down');
l.Add('sim/flight_controls/blimp_lift_up');
l.Add('sim/fuel/indicate_aux');
l.Add('sim/fuel/fuel_tank_selector_lft_one');
l.Add('sim/fuel/fuel_tank_selector_rgt_one');
l.Add('sim/fuel/fuel_selector_none');
l.Add('sim/fuel/fuel_selector_lft');
l.Add('sim/fuel/fuel_selector_ctr');
l.Add('sim/fuel/fuel_selector_rgt');
l.Add('sim/fuel/fuel_selector_all');
l.Add('sim/fuel/fuel_transfer_to_lft');
l.Add('sim/fuel/fuel_transfer_to_ctr');
l.Add('sim/fuel/fuel_transfer_to_rgt');
l.Add('sim/fuel/fuel_transfer_to_off');
l.Add('sim/fuel/fuel_transfer_from_lft');
l.Add('sim/fuel/fuel_transfer_from_ctr');
l.Add('sim/fuel/fuel_transfer_from_rgt');
l.Add('sim/fuel/fuel_transfer_from_off');
l.Add('sim/fuel/fuel_crossfeed_from_lft_tank');
l.Add('sim/fuel/fuel_crossfeed_off');
l.Add('sim/fuel/fuel_crossfeed_from_rgt_tank');
l.Add('sim/fuel/fuel_firewall_valve_lft_open');
l.Add('sim/fuel/fuel_firewall_valve_lft_closed');
l.Add('sim/fuel/fuel_firewall_valve_rgt_open');
l.Add('sim/fuel/fuel_firewall_valve_rgt_closed');
l.Add('sim/fuel/fuel_pump_1_on');
l.Add('sim/fuel/fuel_pump_2_on');
l.Add('sim/fuel/fuel_pump_3_on');
l.Add('sim/fuel/fuel_pump_4_on');
l.Add('sim/fuel/fuel_pump_5_on');
l.Add('sim/fuel/fuel_pump_6_on');
l.Add('sim/fuel/fuel_pump_7_on');
l.Add('sim/fuel/fuel_pump_8_on');
l.Add('sim/fuel/fuel_pump_1_off');
l.Add('sim/fuel/fuel_pump_2_off');
l.Add('sim/fuel/fuel_pump_3_off');
l.Add('sim/fuel/fuel_pump_4_off');
l.Add('sim/fuel/fuel_pump_5_off');
l.Add('sim/fuel/fuel_pump_6_off');
l.Add('sim/fuel/fuel_pump_7_off');
l.Add('sim/fuel/fuel_pump_8_off');
l.Add('sim/fuel/fuel_pump_1_prime');
l.Add('sim/fuel/fuel_pump_2_prime');
l.Add('sim/fuel/fuel_pump_3_prime');
l.Add('sim/fuel/fuel_pump_4_prime');
l.Add('sim/fuel/fuel_pump_5_prime');
l.Add('sim/fuel/fuel_pump_6_prime');
l.Add('sim/fuel/fuel_pump_7_prime');
l.Add('sim/fuel/fuel_pump_8_prime');
l.Add('sim/engines/rockets_up');
l.Add('sim/engines/rockets_down');
l.Add('sim/engines/rockets_left');
l.Add('sim/engines/rockets_right');
l.Add('sim/engines/rockets_forward');
l.Add('sim/engines/rockets_aft');
l.Add('sim/lights/landing_lights_on');
l.Add('sim/lights/landing_lights_off');
l.Add('sim/lights/landing_lights_toggle');
l.Add('sim/lights/taxi_lights_on');
l.Add('sim/lights/taxi_lights_off');
l.Add('sim/lights/taxi_lights_toggle');
l.Add('sim/lights/strobe_lights_on');
l.Add('sim/lights/strobe_lights_off');
l.Add('sim/lights/strobe_lights_toggle');
l.Add('sim/lights/nav_lights_on');
l.Add('sim/lights/nav_lights_off');
l.Add('sim/lights/nav_lights_toggle');
l.Add('sim/lights/beacon_lights_on');
l.Add('sim/lights/beacon_lights_off');
l.Add('sim/lights/beacon_lights_toggle');
l.Add('sim/lights/landing_light_left');
l.Add('sim/lights/landing_light_right');
l.Add('sim/lights/landing_light_up');
l.Add('sim/lights/landing_light_down');
l.Add('sim/lights/landing_light_center');
l.Add('sim/annunciator/test_all_annunciators');
l.Add('sim/annunciator/test_stall');
l.Add('sim/annunciator/test_fire_L_annun');
l.Add('sim/annunciator/test_fire_R_annun');
l.Add('sim/annunciator/clear_master_caution');
l.Add('sim/annunciator/clear_master_warning');
l.Add('sim/annunciator/clear_master_accept');
l.Add('sim/annunciator/gear_warning_mute');
l.Add('sim/electrical/dc_volt_ext');
l.Add('sim/electrical/dc_volt_ctr');
l.Add('sim/electrical/dc_volt_lft');
l.Add('sim/electrical/dc_volt_rgt');
l.Add('sim/electrical/dc_volt_tpl');
l.Add('sim/electrical/dc_volt_bat');
l.Add('sim/electrical/inverters_on');
l.Add('sim/electrical/inverters_off');
l.Add('sim/electrical/inverters_toggle');
l.Add('sim/electrical/inverter_1_on');
l.Add('sim/electrical/inverter_1_off');
l.Add('sim/electrical/inverter_1_toggle');
l.Add('sim/electrical/inverter_2_on');
l.Add('sim/electrical/inverter_2_off');
l.Add('sim/electrical/inverter_2_toggle');
l.Add('sim/electrical/cross_tie_on');
l.Add('sim/electrical/cross_tie_off');
l.Add('sim/electrical/cross_tie_toggle');
l.Add('sim/electrical/battery_1_on');
l.Add('sim/electrical/battery_1_off');
l.Add('sim/electrical/battery_2_on');
l.Add('sim/electrical/battery_2_off');
l.Add('sim/electrical/batteries_toggle');
l.Add('sim/electrical/generators_toggle');
l.Add('sim/electrical/APU_on');
l.Add('sim/electrical/APU_off');
l.Add('sim/electrical/APU_start');
l.Add('sim/electrical/GPU_on');
l.Add('sim/electrical/GPU_off');
l.Add('sim/electrical/GPU_toggle');
l.Add('sim/systems/avionics_on');
l.Add('sim/systems/avionics_off');
l.Add('sim/systems/avionics_toggle');
l.Add('sim/systems/yaw_damper_on');
l.Add('sim/systems/yaw_damper_off');
l.Add('sim/systems/yaw_damper_toggle');
l.Add('sim/systems/prop_sync_on');
l.Add('sim/systems/prop_sync_off');
l.Add('sim/systems/prop_sync_toggle');
l.Add('sim/systems/feather_mode_off');
l.Add('sim/systems/feather_mode_arm');
l.Add('sim/systems/feather_mode_test');
l.Add('sim/systems/overspeed_test');
l.Add('sim/systems/artificial_stability_toggle');
l.Add('sim/systems/pre_rotate_toggle');
l.Add('sim/systems/total_energy_audio_toggle');
l.Add('sim/bleed_air/bleed_air_left');
l.Add('sim/bleed_air/bleed_air_auto');
l.Add('sim/bleed_air/bleed_air_right');
l.Add('sim/bleed_air/bleed_air_off');
l.Add('sim/bleed_air/bleed_air_left_on');
l.Add('sim/bleed_air/bleed_air_left_ins_only');
l.Add('sim/bleed_air/bleed_air_left_off');
l.Add('sim/bleed_air/bleed_air_right_on');
l.Add('sim/bleed_air/bleed_air_right_ins_only');
l.Add('sim/bleed_air/bleed_air_right_off');
l.Add('sim/pressurization/dump_on');
l.Add('sim/pressurization/dump_off');
l.Add('sim/pressurization/vvi_down');
l.Add('sim/pressurization/vvi_up');
l.Add('sim/pressurization/cabin_alt_down');
l.Add('sim/pressurization/cabin_alt_up');
l.Add('sim/pressurization/test');
l.Add('sim/ice/alternate_static_port');
l.Add('sim/ice/anti_ice_toggle');
l.Add('sim/ice/inlet_heat0_on');
l.Add('sim/ice/inlet_heat0_off');
l.Add('sim/ice/inlet_heat1_on');
l.Add('sim/ice/inlet_heat1_off');
l.Add('sim/ice/prop_heat_on');
l.Add('sim/ice/prop_heat_off');
l.Add('sim/ice/window_heat_on');
l.Add('sim/ice/window_heat_off');
l.Add('sim/ice/pitot_heat_on');
l.Add('sim/ice/pitot_heat_off');
l.Add('sim/ice/AOA_heat_on');
l.Add('sim/ice/AOA_heat_off');
l.Add('sim/ice/wing_heat0_on');
l.Add('sim/ice/wing_heat0_off');
l.Add('sim/ice/wing_heat1_on');
l.Add('sim/ice/wing_heat1_off');
l.Add('sim/ice/detect_on');
l.Add('sim/ice/detect_off');
l.Add('sim/ice/brake_on');
l.Add('sim/ice/brake_off');
l.Add('sim/HUD/power_toggle');
l.Add('sim/HUD/brightness_toggle');
l.Add('sim/instruments/map_zoom_in');
l.Add('sim/instruments/map_zoom_out');
l.Add('sim/instruments/EFIS_wxr');
l.Add('sim/instruments/EFIS_tcas');
l.Add('sim/instruments/EFIS_apt');
l.Add('sim/instruments/EFIS_fix');
l.Add('sim/instruments/EFIS_vor');
l.Add('sim/instruments/EFIS_ndb');
l.Add('sim/instruments/panel_bright_down');
l.Add('sim/instruments/panel_bright_up');
l.Add('sim/instruments/instrument_bright_down');
l.Add('sim/instruments/instrument_bright_up');
l.Add('sim/instruments/timer_start_stop');
l.Add('sim/instruments/timer_reset');
l.Add('sim/instruments/timer_show_date');
l.Add('sim/instruments/timer_is_GMT');
l.Add('sim/instruments/thermo_units_toggle');
l.Add('sim/instruments/barometer_down');
l.Add('sim/instruments/barometer_up');
l.Add('sim/instruments/barometer_2992');
l.Add('sim/instruments/ah_ref_down');
l.Add('sim/instruments/ah_ref_up');
l.Add('sim/instruments/dh_ref_down');
l.Add('sim/instruments/dh_ref_up');
l.Add('sim/instruments/asi_bug_down');
l.Add('sim/instruments/asi_bug_up');
l.Add('sim/flight_controls/tailhook_down');
l.Add('sim/flight_controls/tailhook_up');
l.Add('sim/flight_controls/tailhook_toggle');
l.Add('sim/flight_controls/canopy_open');
l.Add('sim/flight_controls/canopy_close');
l.Add('sim/flight_controls/canopy_toggle');
l.Add('sim/flight_controls/smoke_toggle');
l.Add('sim/flight_controls/water_scoop_toggle');
l.Add('sim/weapons/master_arm_on');
l.Add('sim/weapons/master_arm_off');
l.Add('sim/weapons/weapon_select_down');
l.Add('sim/weapons/weapon_select_up');
l.Add('sim/weapons/weapon_target_down');
l.Add('sim/weapons/weapon_target_up');
l.Add('sim/weapons/fire_guns');
l.Add('sim/weapons/fire_air_to_air');
l.Add('sim/weapons/fire_air_to_ground');
l.Add('sim/weapons/fire_any_armed');
l.Add('sim/weapons/deploy_chaff');
l.Add('sim/weapons/deploy_flares');
l.Add('sim/flight_controls/parachute_flares');
l.Add('sim/flight_controls/ignite_jato');
l.Add('sim/flight_controls/jettison_payload');
l.Add('sim/flight_controls/dump_fuel_toggle');
l.Add('sim/flight_controls/drop_tank');
l.Add('sim/flight_controls/deploy_parachute');
l.Add('sim/flight_controls/eject');
l.Add('sim/flight_controls/glider_tow_release');
l.Add('sim/flight_controls/winch_release');
l.Add('sim/flight_controls/carrier_ILS');
l.Add('sim/systems/seatbelt_sign_toggle');
l.Add('sim/systems/no_smoking_toggle');
l.Add('sim/autopilot/hsi_select_nav_1');
l.Add('sim/autopilot/hsi_select_nav_2');
l.Add('sim/autopilot/hsi_select_gps');
l.Add('sim/autopilot/flight_dir_on_only');
l.Add('sim/autopilot/servos_and_flight_dir_on');
l.Add('sim/autopilot/servos_and_flight_dir_off');
l.Add('sim/autopilot/servos_fdir_yawd_off');
l.Add('sim/autopilot/servos_fdir_yawd_trim_off');
l.Add('sim/autopilot/fdir_servos_down_one');
l.Add('sim/autopilot/fdir_servos_up_one');
l.Add('sim/autopilot/fdir_servos_toggle');
l.Add('sim/autopilot/control_wheel_steer');
l.Add('sim/autopilot/autothrottle_on');
l.Add('sim/autopilot/autothrottle_off');
l.Add('sim/autopilot/autothrottle_toggle');
l.Add('sim/autopilot/wing_leveler');
l.Add('sim/autopilot/heading');
l.Add('sim/autopilot/NAV');
l.Add('sim/autopilot/pitch_sync');
l.Add('sim/autopilot/level_change');
l.Add('sim/autopilot/vertical_speed');
l.Add('sim/autopilot/altitude_hold');
l.Add('sim/autopilot/altitude_arm');
l.Add('sim/autopilot/vnav');
l.Add('sim/autopilot/FMS');
l.Add('sim/autopilot/glide_slope');
l.Add('sim/autopilot/back_course');
l.Add('sim/autopilot/approach');
l.Add('sim/autopilot/take_off_go_around');
l.Add('sim/autopilot/reentry');
l.Add('sim/autopilot/terrain_following');
l.Add('sim/autopilot/hdg_alt_spd_on');
l.Add('sim/autopilot/hdg_alt_spd_off');
l.Add('sim/autopilot/airspeed_down');
l.Add('sim/autopilot/airspeed_up');
l.Add('sim/autopilot/airspeed_sync');
l.Add('sim/autopilot/heading_down');
l.Add('sim/autopilot/heading_up');
l.Add('sim/autopilot/heading_sync');
l.Add('sim/autopilot/vertical_speed_down');
l.Add('sim/autopilot/vertical_speed_up');
l.Add('sim/autopilot/vertical_speed_sync');
l.Add('sim/autopilot/altitude_down');
l.Add('sim/autopilot/altitude_up');
l.Add('sim/autopilot/altitude_sync');
l.Add('sim/autopilot/nose_down');
l.Add('sim/autopilot/nose_up');
l.Add('sim/autopilot/nose_down_pitch_mode');
l.Add('sim/autopilot/nose_up_pitch_mode');
l.Add('sim/autopilot/override_left');
l.Add('sim/autopilot/override_right');
l.Add('sim/autopilot/override_up');
l.Add('sim/autopilot/override_down');
l.Add('sim/autopilot/bank_limit_toggle');
l.Add('sim/autopilot/soft_ride_toggle');
l.Add('sim/autopilot/listen_g430_1');
l.Add('sim/autopilot/listen_g430_2');
l.Add('sim/autopilot/test_auto_annunciators');
l.Add('sim/radios/obs1_down');
l.Add('sim/radios/obs1_up');
l.Add('sim/radios/obs2_down');
l.Add('sim/radios/obs2_up');
l.Add('sim/radios/obs_HSI_down');
l.Add('sim/radios/obs_HSI_up');
l.Add('sim/radios/RMI_L_tog');
l.Add('sim/radios/RMI_R_tog');
l.Add('sim/radios/copilot_obs1_down');
l.Add('sim/radios/copilot_obs1_up');
l.Add('sim/radios/copilot_obs2_down');
l.Add('sim/radios/copilot_obs2_up');
l.Add('sim/radios/copilot_obs_HSI_down');
l.Add('sim/radios/copilot_obs_HSI_up');
l.Add('sim/radios/copilot_RMI_L_tog_cop');
l.Add('sim/radios/copilot_RMI_R_tog_cop');
l.Add('sim/radios/nav1_standy_flip');
l.Add('sim/radios/nav2_standy_flip');
l.Add('sim/radios/com1_standy_flip');
l.Add('sim/radios/com2_standy_flip');
l.Add('sim/radios/adf1_standy_flip');
l.Add('sim/radios/adf2_standy_flip');
l.Add('sim/radios/dme_standby_flip');
l.Add('sim/radios/actv_com1_coarse_down');
l.Add('sim/radios/actv_com1_coarse_up');
l.Add('sim/radios/actv_com1_fine_down');
l.Add('sim/radios/actv_com1_fine_up');
l.Add('sim/radios/actv_nav1_coarse_down');
l.Add('sim/radios/actv_nav1_coarse_up');
l.Add('sim/radios/actv_nav1_fine_down');
l.Add('sim/radios/actv_nav1_fine_up');
l.Add('sim/radios/actv_adf1_hundreds_down');
l.Add('sim/radios/actv_adf1_hundreds_up');
l.Add('sim/radios/actv_adf1_tens_down');
l.Add('sim/radios/actv_adf1_tens_up');
l.Add('sim/radios/actv_adf1_ones_down');
l.Add('sim/radios/actv_adf1_ones_up');
l.Add('sim/radios/actv_adf2_hundreds_down');
l.Add('sim/radios/actv_com2_coarse_down');
l.Add('sim/radios/actv_com2_coarse_up');
l.Add('sim/radios/actv_com2_fine_down');
l.Add('sim/radios/actv_com2_fine_up');
l.Add('sim/radios/actv_nav2_coarse_down');
l.Add('sim/radios/actv_nav2_coarse_up');
l.Add('sim/radios/actv_nav2_fine_down');
l.Add('sim/radios/actv_nav2_fine_up');
l.Add('sim/radios/actv_adf2_hundreds_up');
l.Add('sim/radios/actv_adf2_tens_down');
l.Add('sim/radios/actv_adf2_tens_up');
l.Add('sim/radios/actv_adf2_ones_down');
l.Add('sim/radios/actv_adf2_ones_up');
l.Add('sim/radios/stby_com1_coarse_down');
l.Add('sim/radios/stby_com1_coarse_up');
l.Add('sim/radios/stby_com1_fine_down');
l.Add('sim/radios/stby_com1_fine_up');
l.Add('sim/radios/stby_nav1_coarse_down');
l.Add('sim/radios/stby_nav1_coarse_up');
l.Add('sim/radios/stby_nav1_fine_down');
l.Add('sim/radios/stby_nav1_fine_up');
l.Add('sim/radios/stby_adf1_hundreds_down');
l.Add('sim/radios/stby_adf1_hundreds_up');
l.Add('sim/radios/stby_adf1_tens_down');
l.Add('sim/radios/stby_adf1_tens_up');
l.Add('sim/radios/stby_adf1_ones_down');
l.Add('sim/radios/stby_adf1_ones_up');
l.Add('sim/radios/stby_com2_coarse_down');
l.Add('sim/radios/stby_com2_coarse_up');
l.Add('sim/radios/stby_com2_fine_down');
l.Add('sim/radios/stby_com2_fine_up');
l.Add('sim/radios/stby_nav2_coarse_down');
l.Add('sim/radios/stby_nav2_coarse_up');
l.Add('sim/radios/stby_nav2_fine_down');
l.Add('sim/radios/stby_nav2_fine_up');
l.Add('sim/radios/stby_adf2_hundreds_down');
l.Add('sim/radios/stby_adf2_hundreds_up');
l.Add('sim/radios/stby_adf2_tens_down');
l.Add('sim/radios/stby_adf2_tens_up');
l.Add('sim/radios/stby_adf2_ones_down');
l.Add('sim/radios/stby_adf2_ones_up');
l.Add('sim/transponder/transponder_ident');
l.Add('sim/transponder/transponder_off');
l.Add('sim/transponder/transponder_standby');
l.Add('sim/transponder/transponder_on');
l.Add('sim/transponder/transponder_alt');
l.Add('sim/transponder/transponder_test');
l.Add('sim/transponder/transponder_ground');
l.Add('sim/transponder/transponder_thousands_down');
l.Add('sim/transponder/transponder_thousands_up');
l.Add('sim/transponder/transponder_hundreds_down');
l.Add('sim/transponder/transponder_hundreds_up');
l.Add('sim/transponder/transponder_tens_down');
l.Add('sim/transponder/transponder_tens_up');
l.Add('sim/transponder/transponder_ones_down');
l.Add('sim/transponder/transponder_ones_up');
l.Add('sim/audio_panel/select_audio_nav1');
l.Add('sim/audio_panel/select_audio_nav2');
l.Add('sim/audio_panel/select_audio_com1');
l.Add('sim/audio_panel/select_audio_com2');
l.Add('sim/audio_panel/select_audio_adf1');
l.Add('sim/audio_panel/select_audio_adf2');
l.Add('sim/GPS/mode_airport');
l.Add('sim/GPS/mode_VOR');
l.Add('sim/GPS/mode_NDB');
l.Add('sim/GPS/mode_waypoint');
l.Add('sim/GPS/fine_select_down');
l.Add('sim/GPS/fine_select_up');
l.Add('sim/GPS/coarse_select_down');
l.Add('sim/GPS/coarse_select_up');
l.Add('sim/GPS/g430n1_zoom_in');
l.Add('sim/GPS/g430n1_zoom_out');
l.Add('sim/GPS/g430n1_nav_com_tog');
l.Add('sim/GPS/g430n1_cdi');
l.Add('sim/GPS/g430n1_obs');
l.Add('sim/GPS/g430n1_msg');
l.Add('sim/GPS/g430n1_fpl');
l.Add('sim/GPS/g430n1_proc');
l.Add('sim/GPS/g430n1_direct');
l.Add('sim/GPS/g430n1_menu');
l.Add('sim/GPS/g430n1_clr');
l.Add('sim/GPS/g430n1_ent');
l.Add('sim/GPS/g430n1_com_ff');
l.Add('sim/GPS/g430n1_nav_ff');
l.Add('sim/GPS/g430n1_chapter_up');
l.Add('sim/GPS/g430n1_chapter_dn');
l.Add('sim/GPS/g430n1_page_up');
l.Add('sim/GPS/g430n1_page_dn');
l.Add('sim/GPS/g430n2_zoom_in');
l.Add('sim/GPS/g430n2_zoom_out');
l.Add('sim/GPS/g430n2_nav_com_tog');
l.Add('sim/GPS/g430n2_cdi');
l.Add('sim/GPS/g430n2_obs');
l.Add('sim/GPS/g430n2_msg');
l.Add('sim/GPS/g430n2_fpl');
l.Add('sim/GPS/g430n2_proc');
l.Add('sim/GPS/g430n2_direct');
l.Add('sim/GPS/g430n2_menu');
l.Add('sim/GPS/g430n2_clr');
l.Add('sim/GPS/g430n2_ent');
l.Add('sim/GPS/g430n2_com_ff');
l.Add('sim/GPS/g430n2_nav_ff');
l.Add('sim/GPS/g430n2_chapter_up');
l.Add('sim/GPS/g430n2_chapter_dn');
l.Add('sim/GPS/g430n2_page_up');
l.Add('sim/GPS/g430n2_page_dn');
l.Add('sim/FMS/ls_1l');
l.Add('sim/FMS/ls_2l');
l.Add('sim/FMS/ls_3l');
l.Add('sim/FMS/ls_4l');
l.Add('sim/FMS/ls_5l');
l.Add('sim/FMS/ls_1r');
l.Add('sim/FMS/ls_2r');
l.Add('sim/FMS/ls_3r');
l.Add('sim/FMS/ls_4r');
l.Add('sim/FMS/ls_5r');
l.Add('sim/FMS/init');
l.Add('sim/FMS/prev');
l.Add('sim/FMS/next');
l.Add('sim/FMS/clear');
l.Add('sim/FMS/direct');
l.Add('sim/FMS/sign');
l.Add('sim/FMS/type_apt');
l.Add('sim/FMS/type_vor');
l.Add('sim/FMS/type_ndb');
l.Add('sim/FMS/type_fix');
l.Add('sim/FMS/type_latlon');
l.Add('sim/FMS/key_0');
l.Add('sim/FMS/key_1');
l.Add('sim/FMS/key_2');
l.Add('sim/FMS/key_3');
l.Add('sim/FMS/key_4');
l.Add('sim/FMS/key_5');
l.Add('sim/FMS/key_6');
l.Add('sim/FMS/key_7');
l.Add('sim/FMS/key_8');
l.Add('sim/FMS/key_9');
l.Add('sim/FMS/key_A');
l.Add('sim/FMS/key_B');
l.Add('sim/FMS/key_C');
l.Add('sim/FMS/key_D');
l.Add('sim/FMS/key_E');
l.Add('sim/FMS/key_F');
l.Add('sim/FMS/key_G');
l.Add('sim/FMS/key_H');
l.Add('sim/FMS/key_I');
l.Add('sim/FMS/key_J');
l.Add('sim/FMS/key_K');
l.Add('sim/FMS/key_L');
l.Add('sim/FMS/key_M');
l.Add('sim/FMS/key_N');
l.Add('sim/FMS/key_O');
l.Add('sim/FMS/key_P');
l.Add('sim/FMS/key_Q');
l.Add('sim/FMS/key_R');
l.Add('sim/FMS/key_S');
l.Add('sim/FMS/key_T');
l.Add('sim/FMS/key_U');
l.Add('sim/FMS/key_V');
l.Add('sim/FMS/key_W');
l.Add('sim/FMS/key_X');
l.Add('sim/FMS/key_Y');
l.Add('sim/FMS/key_Z');
l.Add('sim/FMS/key_back');
l.Add('sim/FMS/key_space');
l.Add('sim/FMS/key_load');
l.Add('sim/FMS/key_save');
l.Add('sim/FMS/fix_next');
l.Add('sim/FMS/fix_prev');
l.Add('sim/operation/pause_toggle');
l.Add('sim/operation/ground_speed_change');
l.Add('sim/operation/flightmodel_speed_change');
l.Add('sim/operation/load_situation_1');
l.Add('sim/operation/load_situation_2');
l.Add('sim/operation/load_situation_3');
l.Add('sim/general/action');
l.Add('sim/general/left');
l.Add('sim/general/right');
l.Add('sim/general/up');
l.Add('sim/general/down');
l.Add('sim/general/forward');
l.Add('sim/general/backward');
l.Add('sim/general/zoom_in');
l.Add('sim/general/zoom_out');
l.Add('sim/general/left_fast');
l.Add('sim/general/right_fast');
l.Add('sim/general/up_fast');
l.Add('sim/general/down_fast');
l.Add('sim/general/forward_fast');
l.Add('sim/general/backward_fast');
l.Add('sim/general/zoom_in_fast');
l.Add('sim/general/zoom_out_fast');
l.Add('sim/map/show_low_enroute');
l.Add('sim/map/show_high_enroute');
l.Add('sim/map/show_sectional');
l.Add('sim/map/show_textured');
l.Add('sim/operation/time_down');
l.Add('sim/operation/time_up');
l.Add('sim/operation/date_down');
l.Add('sim/operation/date_up');
l.Add('sim/operation/contact_atc');
l.Add('sim/operation/go_to_default');
l.Add('sim/operation/reset_to_runway');
l.Add('sim/operation/reset_3d_path');
l.Add('sim/operation/fail_system');
l.Add('sim/operation/fix_all_systems');
l.Add('sim/operation/show_instructions');
l.Add('sim/operation/text_file_toggle');
l.Add('sim/operation/checklist_toggle');
l.Add('sim/operation/checklist_next');
l.Add('sim/operation/checklist_previous');
l.Add('sim/operation/cycle_dump');
l.Add('sim/operation/screenshot');
l.Add('sim/operation/quicktime_record_toggle');
l.Add('sim/operation/make_panel_previews');
l.Add('sim/operation/stab_deriv_heading');
l.Add('sim/operation/stab_deriv_pitch');
l.Add('sim/operation/create_snap_marker');
l.Add('sim/operation/test_data_ref');
l.Add('sim/operation/slider_01');
l.Add('sim/operation/slider_02');
l.Add('sim/operation/slider_03');
l.Add('sim/operation/slider_04');
l.Add('sim/operation/slider_05');
l.Add('sim/operation/slider_06');
l.Add('sim/operation/slider_07');
l.Add('sim/operation/slider_08');
l.Add('sim/operation/slider_09');
l.Add('sim/operation/slider_10');
l.Add('sim/operation/slider_11');
l.Add('sim/operation/slider_12');
l.Add('sim/operation/slider_13');
l.Add('sim/operation/slider_14');
l.Add('sim/operation/slider_15');
l.Add('sim/operation/slider_16');
l.Add('sim/operation/slider_17');
l.Add('sim/operation/slider_18');
l.Add('sim/operation/slider_19');
l.Add('sim/operation/slider_20');
l.Add('sim/replay/replay_toggle');
l.Add('sim/replay/rep_begin');
l.Add('sim/replay/rep_play_fr');
l.Add('sim/replay/rep_play_rr');
l.Add('sim/replay/rep_play_sr');
l.Add('sim/replay/rep_pause');
l.Add('sim/replay/rep_play_sf');
l.Add('sim/replay/rep_play_rf');
l.Add('sim/replay/rep_play_ff');
l.Add('sim/replay/rep_end');
end;
end.
|
unit Providers.Frames.Cliente;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Objects, FMX.Controls.Presentation;
type
TFrameCliente = class(TFrame)
retContent: TRectangle;
lblEmail: TLabel;
lblNome: TLabel;
crlDelete: TCircle;
imgDelete: TPath;
lineSeparator: TLine;
end;
implementation
{$R *.fmx}
end.
|
unit UFrmAdvertencias;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Buttons,
System.StrUtils, Vcl.ExtDlgs;
type
TFrmAdvertencias = class(TForm)
PnBot: TPanel;
Btn_Fechar: TBitBtn;
Btn_Salvar: TBitBtn;
MemAdvertencias: TMemo;
SaveText: TSaveTextFileDialog;
procedure Btn_FecharClick(Sender: TObject);
procedure Btn_SalvarClick(Sender: TObject);
private
FLista: TStringList;
public
constructor Create(AOwner: TComponent; ACaption: String; ALista: TStringList); reintroduce;
end;
var
FrmAdvertencias: TFrmAdvertencias;
implementation
{$R *.dfm}
procedure TFrmAdvertencias.Btn_FecharClick(Sender: TObject);
begin
Close;
end;
procedure TFrmAdvertencias.Btn_SalvarClick(Sender: TObject);
begin
if SaveText.Execute then
FLista.SaveToFile(SaveText.FileName);
end;
constructor TFrmAdvertencias.Create(AOwner: TComponent; ACaption: String; ALista: TStringList);
begin
inherited Create(AOwner);
Self.Caption := ACaption;
FLista := TStringList.Create;
FLista := ALista;
MemAdvertencias.Lines := FLista;
end;
end.
|
{ ---------------------------------------------------------------------------- }
{ BulbTracer for MB3D }
{ Copyright (C) 2016-2017 Andreas Maschke }
{ ---------------------------------------------------------------------------- }
unit ObjectScanner;
interface
uses
SysUtils, Classes, Contnrs, VectorMath, TypeDefinitions, BulbTracerConfig,
VertexList, Generics.Collections;
type
TObjectScannerConfig = class
protected
FJitter: Double;
FIteration3Dext: TIteration3Dext;
FVertexGenConfig: TVertexGenConfig;
FMCTparas: TMCTparameter;
FM3Vfile: TM3Vfile;
FLightVals: TLightVals;
FXMin, FXMax, FYMin, FYMax, FZMin, FZMax, FCentreX, FCentreY, FCentreZ: Double;
FStepSize, FScale, FMaxRayDist: Double;
end;
TRayCaster = class
protected
function IsInsideBulb(const FConfig: TObjectScannerConfig; const X, Y, Z: Double ): Boolean; overload;
function IsInsideBulb(const FConfig: TObjectScannerConfig; const X, Y, Z: Double; const DoCalcColor: Boolean; var ColorR, ColorG, ColorB: Double ): Boolean; overload;
function CalculateNormal(const FConfig: TObjectScannerConfig; const Direction, FacePos: TD3Vector; const N: TPD3Vector; const WasInside: Boolean ): Boolean;
public
procedure CastRay(const FConfig: TObjectScannerConfig; const FromPos, Direction: TD3Vector); virtual; abstract;
end;
TCreatePointCloudRayCaster = class (TRayCaster)
private
FVertexList: TPS3VectorList;
FNormalsList, FColorList: TPSMI3VectorList;
public
constructor Create(VertexList: TPS3VectorList; const NormalsList, ColorList: TPSMI3VectorList);
procedure CastRay(const FConfig: TObjectScannerConfig; const FromPos, Direction: TD3Vector); override;
end;
TCreateMeshRayCaster = class (TRayCaster)
private
FISOValue: Double;
FFacesList: TFacesList;
public
constructor Create(FacesList: TFacesList; const ISOValue: Double);
procedure CastRay(const FConfig: TObjectScannerConfig; const FromPos, Direction: TD3Vector); override;
end;
TIterationCallback = procedure (const Idx: Integer) of Object;
TObjectScanner = class
protected
FConfig: TObjectScannerConfig;
FUseShuffledWorkList: Boolean;
FRayCaster: TRayCaster;
FIterationIdx: Integer;
FIterationCallback: TIterationCallback;
procedure Init;
procedure ScannerInit; virtual; abstract;
procedure ScannerScan; virtual; abstract;
public
constructor Create(const VertexGenConfig: TVertexGenConfig; const MCTparas: TMCTparameter; const M3Vfile: TM3Vfile; const RayCaster: TRayCaster);
destructor Destroy;override;
procedure Scan;
function GetWorkList: TList; virtual; abstract;
property UseShuffledWorkList: Boolean read FUseShuffledWorkList;
property IterationIdx: Integer read FIterationIdx write FIterationIdx;
property IterationCallback: TIterationCallback read FIterationCallback write FIterationCallback;
end;
TSphericalScanner = class (TObjectScanner)
protected
FSlicesTheta, FSlicesPhi: Integer;
FThetaMin, FPhiMin: Double;
FThetaMinIndex: Integer;
FDTheta, FDPhi: Double;
FRadius, FStartDist: Double;
procedure ScannerInit; override;
procedure ScannerScan; override;
function GetWorkList: TList; override;
end;
TParallelScanner = class (TObjectScanner)
protected
FSlicesU, FSlicesV: Integer;
FUMin, FVMin: Double;
FUMinIndex: Integer;
FDU, FDV: Double;
protected
procedure ScannerInit; override;
procedure ScannerScan; override;
function GetWorkList: TList; override;
end;
TCubicScanner = class (TObjectScanner)
protected
FSlicesU, FSlicesV: Integer;
FUMinIndex: Integer;
FVMin_XY, FVMin_ZY, FVMin_XZ: Double;
FDV_XY, FDV_ZY, FDV_XZ: Double;
protected
procedure ScannerInit; override;
procedure ScannerScan; override;
function GetWorkList: TList; override;
end;
const
JITTER_MIN = 0.001;
implementation
uses
Windows, Math, Math3D, Calc, BulbTracer, DivUtils, HeaderTrafos;
{ ------------------------------ TObjectScanner ------------------------------ }
constructor TObjectScanner.Create(const VertexGenConfig: TVertexGenConfig; const MCTparas: TMCTparameter; const M3Vfile: TM3Vfile; const RayCaster: TRayCaster);
begin
inherited Create;
FConfig := TObjectScannerConfig.Create;
with FConfig do begin
FVertexGenConfig := VertexGenConfig;
FMCTparas := MCTparas;
FM3Vfile := M3Vfile;
IniIt3D(@FMCTparas, @FIteration3Dext);
MakeLightValsFromHeaderLight(@FM3Vfile.VHeader, @FLightVals, 1, FM3Vfile.VHeader.bStereoMode);
case FVertexGenConfig.MeshType of
mtPointCloud:
begin
FConfig.FJitter := Max( 0.0, Min( 2.0, VertexGenConfig.SampleJitter ) );
FUseShuffledWorkList := True;
end;
mtMesh:
begin
FConfig.FJitter := 0.0;
FUseShuffledWorkList := False;
end;
end;
end;
FRayCaster := RayCaster;
end;
destructor TObjectScanner.Destroy;
begin
FConfig.Free;
inherited Destroy;
end;
procedure TObjectScanner.Init;
begin
with FConfig do begin
FXMin := 0.0;
FXMax := Max(FM3Vfile.VHeader.Width, FM3Vfile.VHeader.Height);
FCentreX := FXMin + (FXMax - FXMin) * 0.5;
FYMin := 0.0;
FYMax := FXMax;
FCentreY := FYMin + (FYMax - FYMin) * 0.5;
FZMin := 0.0;
FZMax := FXMax;
FCentreZ := FZMin + (FZMax - FZMin) * 0.5;
FScale := 2.2 / (FM3Vfile.VHeader.dZoom * FM3Vfile.Zscale * (FZMax - 1)); //new stepwidth
end;
ScannerInit;
end;
procedure TObjectScanner.Scan;
begin
Init;
ScannerScan;
end;
{ ----------------------------- TSphericalScanner ---------------------------- }
procedure TSphericalScanner.ScannerInit;
begin
with FConfig do begin
with FVertexGenConfig.URange, FMCTparas do begin
FSlicesTheta := CalcStepCount(iThreadID, PCalcThreadStats.iTotalThreadCount);
if FSlicesTheta < 1 then
exit;
FThetaMin := CalcRangeMin(iThreadID, PCalcThreadStats.iTotalThreadCount) * DegToRad( 360.0 );
FThetaMinIndex := CalcRangeMinIndex(iThreadID, PCalcThreadStats.iTotalThreadCount);
FDTheta := StepSize * DegToRad(360.0) ;
end;
with FVertexGenConfig.VRange do begin
FSlicesPhi := StepCount;
FPhiMin := RangeMin * DegToRad( 360.0 );
FDPhi := StepSize * DegToRad(360.0);
end;
FRadius := Sqrt(Sqr(FXMax-FXMin) + Sqr(FYMax-FYMin) + Sqr(FZMax-FZMin)) / 2.0;
FStepSize := FRadius / FSlicesPhi;
FStartDist := FRadius + 1.5 * FStepSize;
FMaxRayDist := FStartDist;
end;
end;
function TSphericalScanner.GetWorkList: TList;
var
I: Integer;
Theta, DTheta: Double;
begin
Init;
Result := TObjectList.Create;
try
DTheta := FConfig.FVertexGenConfig.URange.StepSize * DegToRad(360.0) ;
Theta := 0.0;
for I := 0 to FConfig.FVertexGenConfig.URange.StepCount do begin
Result.Add( TDoubleWrapper.Create( Theta ) );
Theta := Theta + DTheta;
end;
except
Result.Free;
raise;
end;
end;
procedure TSphericalScanner.ScannerScan;
var
I, J: Integer;
Theta, SinTheta, CosTheta: Double;
Phi, SinPhi, CosPhi: Double;
CurrPos, Dir: TD3Vector;
begin
with FConfig do begin
Theta := FThetaMin;
for I := 0 to FSlicesTheta - 1 do begin
Sleep(1);
if FJitter > JITTER_MIN then begin
SinCos(Theta + FDTheta * ( 0.5 - Random ) * FJitter, SinTheta, CosTheta);
end
else begin
SinCos(Theta, SinTheta, CosTheta);
end;
Phi := FPhiMin;
for J := 0 to FSlicesPhi - 1 do begin
if FJitter > JITTER_MIN then begin
SinCos(Phi + FDPhi * ( 0.5 - Random ) * FJitter, SinPhi, CosPhi);
end
else begin
SinCos(Phi, SinPhi, CosPhi);
end;
Dir.X := - SinTheta * CosPhi * FStepSize;
Dir.Y := - SinTheta * SinPhi * FStepSize;
Dir.Z := CosTheta * FStepSize;
CurrPos.X := FCentreX + FStartDist * SinTheta * CosPhi;
CurrPos.Y := FCentreY + FStartDist * SinTheta * SinPhi;
CurrPos.Z := FCentreZ - FStartDist * CosTheta;
FRayCaster.CastRay(FConfig, CurrPos, Dir);
Phi := Phi + FDPhi;
with FMCTparas do begin
if PCalcThreadStats.CTrecords[iThreadID].iDEAvrCount < 0 then begin
PCalcThreadStats.CTrecords[iThreadID].iActualYpos := FSlicesTheta;
exit;
end;
end;
end;
Theta := Theta + FDTheta;
with FMCTparas do begin
PCalcThreadStats.CTrecords[iThreadID].iActualYpos := Round(I * 100.0 / FSlicesTheta);
end;
end;
end;
end;
{ ----------------------------- TParallelScanner ----------------------------- }
procedure TParallelScanner.ScannerInit;
begin
with FConfig do begin
with FVertexGenConfig.URange, FMCTparas do begin
FSlicesU := CalcStepCount(iThreadID, PCalcThreadStats.iTotalThreadCount);
if FSlicesU < 1 then
exit;
FUMin := FXMin + CalcRangeMin(iThreadID, PCalcThreadStats.iTotalThreadCount) * (FXMax - FXMin);
FUMinIndex := CalcRangeMinIndex(iThreadID, PCalcThreadStats.iTotalThreadCount);
FDU := StepSize * (FXMax - FXMin);
end;
with FVertexGenConfig.VRange do begin
FSlicesV := StepCount;
FVMin := FYMin + RangeMin * (FYMax - FYMin);
FDV := StepSize * (FYMax - FYMin);
end;
FMaxRayDist := FZMax - FZMin;
FStepSize := (FXMax - FXMin) / (FSlicesV - 1);
end;
end;
function TParallelScanner.GetWorkList: TList;
var
I: Integer;
U, DU: Double;
begin
Init;
Result := TObjectList.Create;
try
DU := FConfig.FVertexGenConfig.URange.StepSize * (FConfig.FXMax - FConfig.FXMin);
U := FConfig.FXMin;
for I := 0 to FConfig.FVertexGenConfig.URange.StepCount do begin
Result.Add( TDoubleWrapper.Create( U ) );
U := U + DU;
end;
except
Result.Free;
raise;
end;
end;
procedure TParallelScanner.ScannerScan;
var
I, J, Idx: Integer;
U, V: Double;
CurrPos, Dir: TD3Vector;
begin
with FConfig do begin
U := FUMin;
for I := 0 to FSlicesU - 1 do begin
Sleep(1);
if FUseShuffledWorkList then begin
Idx := I + FUMinIndex;
if ( Idx < 0 ) or ( Idx >= FConfig.FVertexGenConfig.SharedWorkList.Count ) then
OutputDebugString(PChar('###################'+IntToStr(Idx)+' '+IntToStr( FUMinIndex ) + ' '+IntToStr(FConfig.FVertexGenConfig.SharedWorkList.Count)));
U := TDoubleWrapper( FConfig.FVertexGenConfig.SharedWorkList[ Idx ] ).Value;
end;
V := FVMin;
for J := 0 to FSlicesV - 1 do begin
Dir.X := 0.0;
Dir.Y := 0.0;
Dir.Z := FStepSize;
if FJitter > JITTER_MIN then begin
CurrPos.X := U + FDV * ( 0.5 - Random ) * FJitter;
CurrPos.Y := V + FDV * ( 0.5 - Random ) * FJitter;
CurrPos.Z := FZMin;
end
else begin
CurrPos.X := U;
CurrPos.Y := V;
CurrPos.Z := FZMin;
end;
FRayCaster.CastRay(FConfig, CurrPos, Dir);
V := V + FDV;
if Assigned( IterationCallback ) then
IterationCallback( IterationIdx );
with FMCTparas do begin
if PCalcThreadStats.CTrecords[iThreadID].iDEAvrCount < 0 then begin
PCalcThreadStats.CTrecords[iThreadID].iActualYpos := FSlicesU;
exit;
end;
end;
end;
U := U + FDU;
with FMCTparas do begin
PCalcThreadStats.CTrecords[iThreadID].iActualYpos := Round(I * 100.0 / FSlicesU);
end;
end;
end;
end;
{ ------------------------------- TCubicScanner ------------------------------ }
procedure TCubicScanner.ScannerInit;
begin
with FConfig do begin
with FVertexGenConfig.URange, FMCTparas do begin
FSlicesU := CalcStepCount(iThreadID, PCalcThreadStats.iTotalThreadCount);
if FSlicesU < 1 then
exit;
FUMinIndex := CalcRangeMinIndex(iThreadID, PCalcThreadStats.iTotalThreadCount);
end;
with FVertexGenConfig.VRange do begin
FSlicesV := StepCount;
FVMin_XY := FYMin + RangeMin * (FYMax - FYMin);
FDV_XY := StepSize * (FYMax - FYMin);
FVMin_ZY := FYMin + RangeMin * (FYMax - FYMin);
FDV_ZY := StepSize * (FYMax - FYMin);
FVMin_ZY := FVMin_ZY + FDV_ZY / 2.0;
FVMin_XZ := FZMin + RangeMin * (FZMax - FZMin);
FDV_XZ := StepSize * (FZMax - FZMin);
FVMin_XZ := FVMin_XZ + FDV_XZ / 2.0;
end;
FMaxRayDist := FZMax - FZMin;
FStepSize := (FXMax - FXMin) / (FSlicesV - 1);
end;
end;
function TCubicScanner.GetWorkList: TList;
var
I: Integer;
U_XY, U_ZY, U_XZ, DU_XY, DU_ZY, DU_XZ: Double;
begin
Init;
Result := TObjectList.Create;
try
DU_XY := FConfig.FVertexGenConfig.URange.StepSize * (FConfig.FXMax - FConfig.FXMin);
DU_ZY := FConfig.FVertexGenConfig.URange.StepSize * (FConfig.FZMax - FConfig.FZMin);
DU_XZ := FConfig.FVertexGenConfig.URange.StepSize * (FConfig.FXMax - FConfig.FXMin);
U_XY := FConfig.FXMin;
U_ZY := FConfig.FZMin + DU_ZY / 2.0;
U_XZ := FConfig.FXMin + DU_XZ / 2.0;
for I := 0 to FConfig.FVertexGenConfig.URange.StepCount do begin
Result.Add( TXYZWrapper.Create( U_XY, U_ZY, U_XZ ) );
U_XY := U_XY + DU_XY;
U_ZY := U_ZY + DU_ZY;
U_XZ := U_XZ + DU_XZ;
end;
except
Result.Free;
raise;
end;
end;
procedure TCubicScanner.ScannerScan;
var
I, Idx: Integer;
procedure ScanXY( const ScanForward: Boolean );
var
J: Integer;
U, V: Double;
CurrPos, Dir: TD3Vector;
begin
with FConfig do begin
U := TXYZWrapper( FConfig.FVertexGenConfig.SharedWorkList[ Idx ] ).X;
V := FVMin_XY;
for J := 0 to FSlicesV - 1 do begin
Dir.X := 0.0;
Dir.Y := 0.0;
if ScanForward then
Dir.Z := FStepSize
else
Dir.Z := -FStepSize;
if FJitter > JITTER_MIN then begin
CurrPos.X := U + FDV_XY * ( 0.5 - Random ) * FJitter;
CurrPos.Y := V + FDV_XY * ( 0.5 - Random ) * FJitter;
if ScanForward then
CurrPos.Z := FZMin + FDV_XY * ( 0.5 - Random ) * FJitter
else
CurrPos.Z := FZMax - FDV_XY * ( 0.5 - Random ) * FJitter;
end
else begin
CurrPos.X := U;
CurrPos.Y := V;
if ScanForward then
CurrPos.Z := FZMin
else
CurrPos.Z := FZMax;
end;
FRayCaster.CastRay(FConfig, CurrPos, Dir);
V := V + FDV_XY;
with FMCTparas do begin
if PCalcThreadStats.CTrecords[iThreadID].iDEAvrCount < 0 then begin
PCalcThreadStats.CTrecords[iThreadID].iActualYpos := FSlicesU;
exit;
end;
end;
end;
end;
end;
procedure ScanZY( const ScanForward: Boolean );
var
J: Integer;
U, V: Double;
CurrPos, Dir: TD3Vector;
begin
with FConfig do begin
U := TXYZWrapper( FConfig.FVertexGenConfig.SharedWorkList[ Idx ] ).Y;
V := FVMin_ZY + FDV_ZY / 2.0;
for J := 0 to FSlicesV - 1 do begin
if ScanForward then
Dir.X := -FStepSize
else
Dir.X := FStepSize;
Dir.Y := 0.0;
Dir.Z := 0.0;
if FJitter > JITTER_MIN then begin
CurrPos.Y := U + FDV_ZY * ( 0.5 - Random ) * FJitter;
CurrPos.Z := V + FDV_ZY * ( 0.5 - Random ) * FJitter;
if ScanForward then
CurrPos.X := FXMax + FDV_ZY * ( 0.5 - Random ) * FJitter
else
CurrPos.X := FXMin - FDV_ZY * ( 0.5 - Random ) * FJitter;
end
else begin
CurrPos.Y := U;
CurrPos.Z := V;
if ScanForward then
CurrPos.X := FXMax
else
CurrPos.X := FXMin;
end;
FRayCaster.CastRay(FConfig, CurrPos, Dir);
V := V + FDV_ZY;
with FMCTparas do begin
if PCalcThreadStats.CTrecords[iThreadID].iDEAvrCount < 0 then begin
PCalcThreadStats.CTrecords[iThreadID].iActualYpos := FSlicesU;
exit;
end;
end;
end;
end;
end;
procedure ScanXZ( const ScanForward: Boolean );
var
J: Integer;
U, V: Double;
CurrPos, Dir: TD3Vector;
begin
with FConfig do begin
U := TXYZWrapper( FConfig.FVertexGenConfig.SharedWorkList[ Idx ] ).Z;
V := FVMin_XZ + FDV_XZ / 2.0;
for J := 0 to FSlicesV - 1 do begin
Dir.X := 0.0;
if ScanForward then
Dir.Y := -FStepSize
else
Dir.Y := FStepSize;
Dir.Z := 0;
if FJitter > JITTER_MIN then begin
CurrPos.X := U + FDV_XZ * ( 0.5 - Random ) * FJitter;
CurrPos.Z := V + FDV_XZ * ( 0.5 - Random ) * FJitter;
if ScanForward then
CurrPos.Y := FYMax + FDV_XZ * ( 0.5 - Random ) * FJitter
else
CurrPos.Y := FYMin - FDV_XZ * ( 0.5 - Random ) * FJitter;
end
else begin
CurrPos.X := U;
CurrPos.Z := V;
if ScanForward then
CurrPos.Y := FYMax
else
CurrPos.Y := FYMin;
end;
FRayCaster.CastRay(FConfig, CurrPos, Dir);
V := V + FDV_XZ;
with FMCTparas do begin
if PCalcThreadStats.CTrecords[iThreadID].iDEAvrCount < 0 then begin
PCalcThreadStats.CTrecords[iThreadID].iActualYpos := FSlicesU;
exit;
end;
end;
end;
end;
end;
begin
with FConfig do begin
for I := 0 to FSlicesU - 1 do begin
Sleep(1);
Idx := I + FUMinIndex;
if ( Idx < 0 ) or ( Idx >= FConfig.FVertexGenConfig.SharedWorkList.Count ) then
OutputDebugString(PChar('###################'+IntToStr(Idx)+' '+IntToStr( FUMinIndex ) + ' '+IntToStr(FConfig.FVertexGenConfig.SharedWorkList.Count)));
ScanXY( True );
ScanZY( True );
ScanXZ( True );
if FJitter > JITTER_MIN then begin
ScanXY( False );
ScanZY( False );
ScanXZ( False );
end;
with FMCTparas do begin
PCalcThreadStats.CTrecords[iThreadID].iActualYpos := Round(I * 100.0 / FSlicesU);
end;
end;
end;
end;
{ --------------------------------- TRayCaster ------------------------------- }
var
DummyColorR, DummyColorG, DummyColorB: Double;
function TRayCaster.IsInsideBulb(const FConfig: TObjectScannerConfig; const X, Y, Z: Double ): Boolean;
begin
Result := IsInsideBulb( FConfig, X, Y, Z, False, DummyColorR, DummyColorG, DummyColorB);
end;
function TRayCaster.IsInsideBulb(const FConfig: TObjectScannerConfig; const X, Y, Z: Double; const DoCalcColor: Boolean; var ColorR, ColorG, ColorB: Double ): Boolean;
var
de: Double;
CC: TVec3D;
s: Single;
psiLight: TsiLight5;
iDif: TSVec;
LightParas: TPLightingParas9;
xx: Single;
procedure CalcColors(iDif: TPSVec; PsiLight: TPsiLight5; PLVals: TPLightVals);
var stmp: Single;
ir, iL1, iL2: Integer;
begin
with PLVals^ do begin
if (iColOnOT and 1) = 0 then ir := PsiLight.SIgradient
else ir := PsiLight.OTrap and $7FFF;
ir := Round(MinMaxCS(-1e9, ((ir - sCStart) * sCmul + iDif[0]) * 16384, 1e9));
iL2 := 5;
if bColCycling then ir := ir and 32767 else
begin
if ir < 0 then
begin
iDif^ := PLValigned.ColDif[0];
Exit;
end
else if ir >= ColPos[9] then
begin
iDif^ := PLValigned.ColDif[9];
Exit;
end;
end;
if ColPos[iL2] < ir then
begin
repeat Inc(iL2) until (iL2 = 10) or (ColPos[iL2] >= ir);
end
else while (ColPos[iL2 - 1] >= ir) and (iL2 > 1) do Dec(iL2);
if bNoColIpol then
begin
iDif^ := PLValigned.ColDif[iL2 - 1];
end
else
begin
iL1 := iL2 - 1;
if iL2 > 9 then iL2 := 0;
stmp := (ir - ColPos[iL1]) * sCDiv[iL1];
iDif^ := LinInterpolate2SVecs(PLValigned.ColDif[iL2], PLValigned.ColDif[iL1], stmp);
end;
end;
end;
procedure CalcSIgradient1;
begin
with FConfig do begin
if FMCTparas.ColorOnIt <> 0 then
RMdoColorOnIt(@FMCTparas);
RMdoColor(@FMCTparas);
if FMCTparas.FormulaType > 0 then begin //col on DE:
s := Abs(FMCTparas.CalcDE(@FIteration3Dext, @FMCTparas) * 40);
if FIteration3Dext.ItResultI < FMCTparas.MaxItsResult then begin
MinMaxClip15bit(s, FMCTparas.mPsiLight.SIgradient);
FMCTparas.mPsiLight.NormalY := 5000;
end
else
FMCTparas.mPsiLight.SIgradient := Round(Min0MaxCS(s, 32767)) + 32768;
end
else begin
if FIteration3Dext.ItResultI < FMCTparas.iMaxIt then begin //MaxItResult not intit without calcDE!
s := FIteration3Dext.SmoothItD * 32767 / FMCTparas.iMaxIt;
MinMaxClip15bit(s, FMCTparas.mPsiLight.SIgradient);
FMCTparas.mPsiLight.NormalY := 5000;
end
else
FMCTparas.mPsiLight.SIgradient := FMCTparas.mPsiLight.OTrap + 32768;
end;
end;
end;
procedure CalcSIgradient2;
var
RSFmul: Single;
itmp: Integer;
begin
with FConfig do begin
if FMCTparas.ColorOnIt <> 0 then
RMdoColorOnIt(@FMCTparas);
RMdoColor(@FMCTparas); //here for otrap
if FMCTparas.ColorOption > 4 then FMCTparas.mPsiLight.SIgradient := 32768 or FMCTparas.mPsiLight.SIgradient else
if FMCTparas.bInsideRendering then begin
FIteration3Dext.CalcSIT := True;
FMCTparas.CalcDE(@FIteration3Dext, @FMCTparas);
RSFmul := FIteration3Dext.SmoothItD * FMCTparas.mctsM;
MinMaxClip15bit(RSFmul, FMCTparas.mPsiLight.SIgradient);
FMCTparas.mPsiLight.SIgradient := 32768 or FMCTparas.mPsiLight.SIgradient;
end
else FMCTparas.mPsiLight.SIgradient := 32768 + Round(32767 * Clamp01S(FIteration3Dext.Rout / FMCTparas.dRStop));
end;
end;
procedure CalcSIgradient3;
var
RSFmul: Single;
itmp: Integer;
begin
with FConfig do begin
if FMCTparas.ColorOnIt <> 0 then
RMdoColorOnIt(@FMCTparas);
RMdoColor(@FMCTparas); //here for otrap
if FMCTparas.ColorOption > 4 then FMCTparas.mPsiLight.SIgradient := 32768 or FMCTparas.mPsiLight.SIgradient else
FIteration3Dext.CalcSIT := True;
FMCTparas.CalcDE(@FIteration3Dext, @FMCTparas);
RSFmul := FIteration3Dext.SmoothItD * FMCTparas.mctsM;
MinMaxClip15bit(RSFmul, FMCTparas.mPsiLight.SIgradient);
FMCTparas.mPsiLight.SIgradient := 32768 or FMCTparas.mPsiLight.SIgradient;
end;
end;
begin
with FConfig do begin
LightParas := @FM3Vfile.VHeader.Light;
FMCTparas.mPsiLight := TPsiLight5(@psiLight);
FMCTparas.Ystart := TPVec3D(@FM3Vfile.VHeader.dXmid)^; //abs offs!
mAddVecWeight(@FMCTparas.Ystart, @FMCTparas.Vgrads[0], FM3Vfile.VHeader.Width * -0.5 + FM3Vfile.Xoff / FScale);
mAddVecWeight(@FMCTparas.Ystart, @FMCTparas.Vgrads[1], FM3Vfile.VHeader.Height * -0.5 + FM3Vfile.Yoff / FScale);
mAddVecWeight(@FMCTparas.Ystart, @FMCTparas.Vgrads[2], Z - FM3Vfile.Zslices * 0.5 + FM3Vfile.Zoff / FScale);
mCopyAddVecWeight(@CC, @FMCTparas.Ystart, @FMCTparas.Vgrads[1], Y);
FIteration3Dext.CalcSIT := False;
mCopyAddVecWeight(@FIteration3Dext.C1, @CC, @FMCTparas.Vgrads[0], X);
if FMCTparas.iSliceCalc = 0 then //on maxits , does not work in DEcomb mode!
begin
if FMCTparas.DEoption > 19 then
FMCTparas.mMandFunctionDE(@FIteration3Dext.C1)
else
FMCTparas.mMandFunction(@FIteration3Dext.C1);
if FMCTparas.bInAndOutside then begin
if (FIteration3Dext.ItResultI < FMCTparas.iMaxIt) and
(FIteration3Dext.ItResultI >= FMCTparas.AOdither) then
Result := True
else
Result := False;
end
else
begin
if FIteration3Dext.ItResultI < FMCTparas.iMaxIt then
Result := False
else
Result := True;
if FMCTparas.bInsideRendering then Result := not Result;
end;
end
else
begin
de := FMCTparas.CalcDE(@FIteration3Dext, @FMCTparas); //in+outside: only if d between dmin and dmax
if de < FMCTparas.DEstop then begin
if FMCTparas.bInAndOutside and (de < FMCTparas.DEAOmaxL) then
Result := False
else
Result := True;
end
else
Result := False;
end;
if Result and DoCalcColor then begin
CalcSIgradient3;
CalcColors(@iDif, @psiLight, @FLightVals);
ColorR := iDif[0];
ColorG := iDif[1];
ColorB := iDif[2];
end
else begin
ColorR := 0;
ColorG := 0;
ColorB := 0;
end;
end;
end;
function TRayCaster.CalculateNormal(const FConfig: TObjectScannerConfig; const Direction, FacePos: TD3Vector; const N: TPD3Vector; const WasInside: Boolean): Boolean;
const
EPS = 1.0e-5;
SAMPLES = 6;
var
I: Integer;
Axis, A, N1, N2: TD3Vector;
Angle, DAngle, SinA, CosA: Double;
T: Array[0..SAMPLES - 1] of TD3Vector;
NT: Array[0..SAMPLES - 1] of TD3Vector;
NTValid: Array[0..SAMPLES - 1] of Boolean;
IM, L, LL, B, SinA_L, CosA_LL, Tmp: TD3Matrix;
TV, StartPos, NDirection, NDirectionB, CurrPos: TD3Vector;
NStepSize, RayDist, MaxRayDist: Double;
PrevInside, CurrInside: Boolean;
P1, P2: TD3Vector;
L1, L2: Double;
NTCount: Integer;
begin
TDVectorMath.Assign(@Axis, @Direction);
TDVectorMath.Normalize(@Axis);
TDVectorMath.NonParallel(@A, @Axis);
TDVectorMath.CrossProduct(@A, @Axis, @T[0]);
TDVectorMath.Normalize(@T[0]);
DAngle := DegToRad(360.0 / SAMPLES);
Angle := DAngle;
NStepSize := FConfig.FStepSize / 100.0;
(*
http://steve.hollasch.net/cgindex/math/rotvec.html
let
[v] = [vx, vy, vz] the vector to be rotated.
[l] = [lx, ly, lz] the vector about rotation
| 1 0 0|
[i] = | 0 1 0| the identity matrix
| 0 0 1|
| 0 lz -ly |
[L] = | -lz 0 lx |
| ly -lx 0 |
d = sqrt(lx*lx + ly*ly + lz*lz)
a the angle of rotation
then
matrix operations gives:
[v] = [v]x{[i] + sin(a)/d*[L] + ((1 - cos(a))/(d*d)*([L]x[L]))}
*)
TDMatrixMath.Identity(@IM);
with L do begin
M[0, 0] := 0.0;
M[0, 1] := Axis.Z;
M[0, 2] := -Axis.Y;
M[1, 0] := -Axis.Z;
M[1, 1] := 0.0;
M[1, 2] := Axis.X;
M[2, 0] := Axis.Y;
M[2, 1] := -Axis.X;
M[2, 2] := 0.0;
end;
TDMatrixMath.Multiply(@L, @L, @LL);
for I := 1 to SAMPLES - 1 do begin
SinCos(Angle, SinA, CosA);
TDMatrixMath.ScalarMul(SinA, @L, @SinA_L);
TDMatrixMath.ScalarMul(1.0 - CosA, @LL, @CosA_LL);
TDMatrixMath.Add(@IM, @SinA_L, @Tmp);
TDMatrixMath.Add(@Tmp, @CosA_LL, @B);
TDMatrixMath.VMultiply(@T[0], @B, @T[I]);
Angle := Angle + DAngle;
end;
TDVectorMath.Assign(@NDirection, @Axis);
TDVectorMath.ScalarMul(NStepSize, @NDirection, @NDirection);
TDVectorMath.Assign(@NDirectionB, @NDirection);
TDVectorMath.ScalarMul(-1.0, @NDirectionB, @NDirectionB);
MaxRayDist := FConfig.FStepSize * 0.75;
NTCount := 0;
for I := 0 to SAMPLES - 1 do begin
TDVectorMath.ScalarMul(NStepSize, @T[I], @TV);
TDVectorMath.Add(@FacePos, @TV, @StartPos);
NTValid[I] := False;
L1 := -1;
RayDist := NStepSize;
TDVectorMath.Assign(@CurrPos, @StartPos);
TDVectorMath.AddTo(@CurrPos, @NDirection);
while(RayDist < MaxRayDist) do begin
CurrInside := IsInsideBulb(FConfig, CurrPos.X, CurrPos.Y, CurrPos.Z);
if WasInside <> CurrInside then begin
L1 := RayDist;
TDVectorMath.Assign(@P1, @CurrPos);
break;
end;
RayDist := RayDist + NStepSize;
TDVectorMath.AddTo(@CurrPos, @NDirection);
end;
L2 := -1;
RayDist := NStepSize;
TDVectorMath.Assign(@CurrPos, @StartPos);
TDVectorMath.AddTo(@CurrPos, @NDirectionB);
while(RayDist < MaxRayDist) do begin
CurrInside := IsInsideBulb(FConfig, CurrPos.X, CurrPos.Y, CurrPos.Z);
if WasInside <> CurrInside then begin
L2 := RayDist;
TDVectorMath.Assign(@P2, @CurrPos);
break;
end;
RayDist := RayDist + NStepSize;
TDVectorMath.AddTo(@CurrPos, @NDirectionB);
end;
if (L1 >= 0.0) and (L2 < 0.0) then begin
TDVectorMath.Assign(@NT[I], @P1);
NTValid[I] := True;
end
else if (L1 < 0.0) and (L2 >= 0.0) then begin
TDVectorMath.Assign(@NT[I], @P2);
NTValid[I] := True;
end
else if (L1 >= 0.0) and (L2 >= 0.0) then begin
if L1 < L2 then
TDVectorMath.Assign(@NT[I], @P1)
else
TDVectorMath.Assign(@NT[I], @P2);
NTValid[I] := True;
end
else begin
TDVectorMath.Assign(@NT[I], @StartPos);
NTValid[I] := True;
end;
end;
TDVectorMath.Clear(N);
for I := 0 to SAMPLES - 2 do begin
N1.X := NT[I+1].X - FacePos.X;
N1.Y := NT[I+1].Y - FacePos.Y;
N1.Z := NT[I+1].Z - FacePos.Z;
N2.X := NT[I].X - FacePos.X;
N2.Y := NT[I].Y - FacePos.Y;
N2.Z := NT[I].Z - FacePos.Z;
TDVectorMath.CrossProduct(@N1, @N2, @TV);
TDVectorMath.AddTo(N, @TV);
end;
N1.X := NT[0].X - FacePos.X;
N1.Y := NT[0].Y - FacePos.Y;
N1.Z := NT[0].Z - FacePos.Z;
N2.X := NT[SAMPLES - 1].X - FacePos.X;
N2.Y := NT[SAMPLES - 1].Y - FacePos.Y;
N2.Z := NT[SAMPLES - 1].Z - FacePos.Z;
TDVectorMath.CrossProduct(@N1, @N2, @TV);
TDVectorMath.AddTo(N, @TV);
TDVectorMath.Normalize(N);
// TDVectorMath.ScalarMul(0.1, N, N);
if WasInside then
TDVectorMath.Flip(N);
Result := True;
end;
{ ---------------------- TCreatePointCloudRayCaster -------------------------- }
constructor TCreatePointCloudRayCaster.Create(VertexList: TPS3VectorList; const NormalsList, ColorList: TPSMI3VectorList);
begin
inherited Create;
FVertexList := VertexList;
FNormalsList := NormalsList;
FColorList := ColorList;
end;
procedure TCreatePointCloudRayCaster.CastRay(const FConfig: TObjectScannerConfig; const FromPos, Direction: TD3Vector);
const
ColorScale = 2.0;
var
PrevInside, CurrInside: Boolean;
RayDist: Double;
CurrPos, N: TD3Vector;
R, G, B, LastInsideR, LastInsideG, LastInsideB: Double;
LColor, RColor, LPosition, RPosition: Cardinal;
CScale: Double;
I: Integer;
HasRanges, ValidPoint: Boolean;
begin
RayDist := FConfig.FStepSize;
PrevInside := False;
LastInsideR := 0.0;
LastInsideG := 0.0;
LastInsideB := 0.0;
TDVectorMath.Assign(@CurrPos, @FromPos);
TDVectorMath.AddTo(@CurrPos, @Direction);
HasRanges := FConfig.FVertexGenConfig.TraceRanges.Count > 0;
while(RayDist < FConfig.FMaxRayDist) do begin
CurrInside := IsInsideBulb(FConfig, CurrPos.X, CurrPos.Y, CurrPos.Z, FConfig.FVertexGenConfig.CalcColors, R, G, B);
if CurrInside then begin
LastInsideR := R;
LastInsideG := G;
LastInsideB := B;
end;
if PrevInside <> CurrInside then begin
if (CurrPos.X >= FConfig.FXMin) and (CurrPos.X <= FConfig.FXMax) and (CurrPos.Y >= FConfig.FYMin) and (CurrPos.Y <= FConfig.FYMax) and (CurrPos.Z >= FConfig.FZMin) and (CurrPos.Z <= FConfig.FZMax) then begin
ValidPoint := True;
if HasRanges then begin
for I := 0 to FConfig.FVertexGenConfig.TraceRanges.Count - 1 do begin
if TTraceRange( FConfig.FVertexGenConfig.TraceRanges[ I ] ).Evaluate( CurrPos.X, CurrPos.Y, CurrPos.Z ) then begin
ValidPoint := False;
break;
end;
end;
end;
if ValidPoint then begin
if FConfig.FVertexGenConfig.CalcNormals then begin
if CalculateNormal(FConfig, Direction, CurrPos, @N, CurrInside) then begin
FNormalsList.AddVertex(N.X, N.Y, N.Z);
FVertexList.AddVertex(CurrPos);
if FConfig.FVertexGenConfig.CalcColors then
FColorList.AddVertex(LastInsideR, LastInsideG, LastInsideB);
end;
end
else begin
FVertexList.AddVertex(CurrPos);
if FConfig.FVertexGenConfig.CalcColors then
FColorList.AddVertex(LastInsideR, LastInsideG, LastInsideB);
end;
end;
end;
PrevInside := CurrInside;
end;
RayDist := RayDist + FConfig.FStepSize;
TDVectorMath.AddTo(@CurrPos, @Direction);
end;
end;
{ ------------------------- TCreateMeshRayCaster ----------------------------- }
constructor TCreateMeshRayCaster.Create(FacesList: TFacesList; const ISOValue: Double);
begin
inherited Create;
FFacesList := FacesList;
FISOValue := ISOValue;
end;
procedure TCreateMeshRayCaster.CastRay(const FConfig: TObjectScannerConfig; const FromPos, Direction: TD3Vector);
var
I: Integer;
RayDist: Double;
CurrPos: TD3Vector;
MCCube: TMCCube;
D: Double;
function CalculateDensity1(const Position: TPD3Vector): Single;
begin
Result := Ord(IsInsideBulb(FConfig, Position^.X, Position^.Y, Position^.Z));
end;
function CalculateDensity8(const Position: TPD3Vector): Single;
begin
Result := (
Ord(IsInsideBulb(FConfig, Position^.X - D , Position^.Y - D, Position^.Z - D)) +
Ord(IsInsideBulb(FConfig, Position^.X + D , Position^.Y - D, Position^.Z - D)) +
Ord(IsInsideBulb(FConfig, Position^.X - D , Position^.Y + D, Position^.Z - D)) +
Ord(IsInsideBulb(FConfig, Position^.X + D , Position^.Y + D, Position^.Z - D)) +
Ord(IsInsideBulb(FConfig, Position^.X - D , Position^.Y - D, Position^.Z + D)) +
Ord(IsInsideBulb(FConfig, Position^.X + D , Position^.Y - D, Position^.Z + D)) +
Ord(IsInsideBulb(FConfig, Position^.X - D , Position^.Y + D, Position^.Z + D)) +
Ord(IsInsideBulb(FConfig, Position^.X + D , Position^.Y + D, Position^.Z + D))
) / 8.0;
end;
function CalculateDensityG8(const Position: TPD3Vector): Single;
begin
Result := (
4.0 * Ord(IsInsideBulb(FConfig, Position^.X, Position^.Y, Position^.Z)) +
Ord(IsInsideBulb(FConfig, Position^.X - D , Position^.Y - D, Position^.Z - D)) +
Ord(IsInsideBulb(FConfig, Position^.X + D , Position^.Y - D, Position^.Z - D)) +
Ord(IsInsideBulb(FConfig, Position^.X - D , Position^.Y + D, Position^.Z - D)) +
Ord(IsInsideBulb(FConfig, Position^.X + D , Position^.Y + D, Position^.Z - D)) +
Ord(IsInsideBulb(FConfig, Position^.X - D , Position^.Y - D, Position^.Z + D)) +
Ord(IsInsideBulb(FConfig, Position^.X + D , Position^.Y - D, Position^.Z + D)) +
Ord(IsInsideBulb(FConfig, Position^.X - D , Position^.Y + D, Position^.Z + D)) +
Ord(IsInsideBulb(FConfig, Position^.X + D , Position^.Y + D, Position^.Z + D))
) / 12.0;
end;
function CalculateDensity27(const Position: TPD3Vector): Single;
begin
Result := (
Ord(IsInsideBulb(FConfig, Position^.X - D , Position^.Y - D, Position^.Z - D)) +
Ord(IsInsideBulb(FConfig, Position^.X , Position^.Y - D, Position^.Z - D)) +
Ord(IsInsideBulb(FConfig, Position^.X + D , Position^.Y - D, Position^.Z - D)) +
Ord(IsInsideBulb(FConfig, Position^.X - D , Position^.Y, Position^.Z - D)) +
Ord(IsInsideBulb(FConfig, Position^.X , Position^.Y, Position^.Z - D)) +
Ord(IsInsideBulb(FConfig, Position^.X + D , Position^.Y, Position^.Z - D)) +
Ord(IsInsideBulb(FConfig, Position^.X - D , Position^.Y + D, Position^.Z - D)) +
Ord(IsInsideBulb(FConfig, Position^.X , Position^.Y + D, Position^.Z - D)) +
Ord(IsInsideBulb(FConfig, Position^.X + D , Position^.Y + D, Position^.Z - D)) +
Ord(IsInsideBulb(FConfig, Position^.X - D , Position^.Y - D, Position^.Z)) +
Ord(IsInsideBulb(FConfig, Position^.X , Position^.Y - D, Position^.Z)) +
Ord(IsInsideBulb(FConfig, Position^.X + D , Position^.Y - D, Position^.Z)) +
Ord(IsInsideBulb(FConfig, Position^.X - D , Position^.Y, Position^.Z)) +
Ord(IsInsideBulb(FConfig, Position^.X , Position^.Y, Position^.Z)) +
Ord(IsInsideBulb(FConfig, Position^.X + D , Position^.Y, Position^.Z)) +
Ord(IsInsideBulb(FConfig, Position^.X - D , Position^.Y + D, Position^.Z)) +
Ord(IsInsideBulb(FConfig, Position^.X , Position^.Y + D, Position^.Z)) +
Ord(IsInsideBulb(FConfig, Position^.X + D , Position^.Y + D, Position^.Z)) +
Ord(IsInsideBulb(FConfig, Position^.X - D , Position^.Y - D, Position^.Z + D)) +
Ord(IsInsideBulb(FConfig, Position^.X , Position^.Y - D, Position^.Z + D)) +
Ord(IsInsideBulb(FConfig, Position^.X + D , Position^.Y - D, Position^.Z + D)) +
Ord(IsInsideBulb(FConfig, Position^.X - D , Position^.Y, Position^.Z + D)) +
Ord(IsInsideBulb(FConfig, Position^.X , Position^.Y, Position^.Z + D)) +
Ord(IsInsideBulb(FConfig, Position^.X + D , Position^.Y, Position^.Z + D)) +
Ord(IsInsideBulb(FConfig, Position^.X - D , Position^.Y + D, Position^.Z + D)) +
Ord(IsInsideBulb(FConfig, Position^.X , Position^.Y + D, Position^.Z + D)) +
Ord(IsInsideBulb(FConfig, Position^.X + D , Position^.Y + D, Position^.Z + D))
) / 27.0;
end;
function CalculateDensity(const Position: TPD3Vector): Single;
begin
case FConfig.FVertexGenConfig.Oversampling of
osNone: Result := CalculateDensity1(Position);
os2x2x2: Result := CalculateDensity8(Position);
os3x3x3: Result := CalculateDensity27(Position);
end;
end;
begin
RayDist := 0.0;
TDVectorMath.Assign(@CurrPos, @FromPos);
D := FConfig.FStepSize / 2.0;
while(RayDist <= FConfig.FMaxRayDist) do begin
TMCCubes.InitializeCube(@MCCube, @CurrPos, FConfig.FStepSize);
for I := 0 to 7 do begin
MCCube.V[I].Weight := CalculateDensity(@MCCube.V[I].Position);
end;
TMCCubes.CreateFacesForCube(@MCCube, FISOValue, FFacesList);
RayDist := RayDist + FConfig.FStepSize;
TDVectorMath.AddTo(@CurrPos, @Direction);
end;
end;
end.
|
{
Implementation of the digest authentication as specified in
RFC2617
(See NOTE below for details of what is exactly implemented)
Author: Doychin Bondzhev (doychin@dsoft-bg.com)
Copyright: (c) Chad Z. Hower and The Winshoes Working Group.
NOTE:
This is compleatly untested authtentication. Use it on your own risk.
I'm sure it won't work from the first time like all normal programs wich
have never been tested in real life ;-))))
I'm still looking for web server that I could use to make these tests.
If you have or know such server and wish to help me in this, just send
me an e-mail with account informationa (login and password) and the server URL.<G>
Doychin Bondzhev (doychin@dsoft-bg.com)
}
unit IdAuthenticationDigest;
interface
Uses
Classes,
SysUtils,
IdException,
IdGlobal,
IdAuthentication,
IdHashMessageDigest,
IdHeaderList;
Type
EIdInvalidAlgorithm = class(EIdException);
TIdDigestAuthentication = class(TIDAuthentication)
protected
FRealm: String;
FStale: Boolean;
FOpaque: String;
FDomain: TStringList;
Fnonce: String;
FAlgorithm: String;
FQopOptions: TStringList;
FOther: TStringList;
function DoNext: TIdAuthWhatsNext; override;
public
destructor Destroy; override;
function Authentication: String; override;
end;
implementation
uses
IdHash, IdResourceStrings;
{ TIdDigestAuthentication }
destructor TIdDigestAuthentication.Destroy;
begin
if Assigned(FDomain) then
FDomain.Free;
if Assigned(FQopOptions) then
FQopOptions.Free;
inherited Destroy;
end;
function TIdDigestAuthentication.Authentication: String;
function ResultString(s: String): String;
Var
MDValue: T4x4LongWordRecord;
PC: PChar;
i: Integer;
S1: String;
begin
with TIdHashMessageDigest5.Create do begin
MDValue := HashValue(S);
Free;
end;
PC := PChar(@MDValue[0]);
for i := 0 to 15 do begin
S1 := S1 + Format('%02x', [Byte(PC[i])]);
end;
while Pos(' ', S1) > 0 do S1[Pos(' ', S1)] := '0';
result := S1;
end;
begin
result := 'Digest ' + {do not localize}
'username="' + Username + '" ' + {do not localize}
'realm="' + FRealm + '" ' + {do not localize}
'result="' + ResultString('') + '"';
end;
function TIdDigestAuthentication.DoNext: TIdAuthWhatsNext;
Var
S: String;
Params: TStringList;
begin
result := wnAskTheProgram;
case FCurrentStep of
0: begin
if not Assigned(FDomain) then begin
FDomain := TStringList.Create;
end
else FDomain.Clear;
if not Assigned(FQopOptions) then begin
FQopOptions := TStringList.Create;
end
else
FQopOptions.Clear;
S := ReadAuthInfo('Digest');
Fetch(S);
Params := TStringList.Create;
while Length(S) > 0 do begin
Params.Add(Fetch(S, ', '));
end;
FRealm := Copy(Params.Values['realm'], 2, Length(Params.Values['realm']) - 2);
Fnonce := Copy(Params.Values['nonce'], 2, Length(Params.Values['nonce']) - 2);
S := Copy(Params.Values['domain'], 2, Length(Params.Values['domain']) - 2);
while Length(S) > 0 do
FDomain.Add(Fetch(S));
Fopaque := Copy(Params.Values['opaque'], 2, Length(Params.Values['opaque']) - 2);
FStale := (Copy(Params.Values['stale'], 2, Length(Params.Values['stale']) - 2) = 'true');
FAlgorithm := Params.Values['algorithm'];
FQopOptions.CommaText := Copy(Params.Values['qop'], 2, Length(Params.Values['qop']) - 2);
if not AnsiSameText(FAlgorithm, 'MD5') then begin
raise EIdInvalidAlgorithm.Create(RSHTTPAuthInvalidHash);
end;
Params.Free;
result := wnAskTheProgram;
FCurrentStep := 1;
end;
1: begin
result := wnDoRequest;
FCurrentStep := 0;
end;
end;
end;
initialization
// This comment will be removed when the Digest authentication is ready
// RegisterAuthenticationMethod('Digest', TIdDigestAuthentication);
end.
|
{
Search & Replace dialog
for lazarus converted from SynEdit by
Radek Cervinka, radek.cervinka@centrum.cz
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 Library 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., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
based on SynEdit demo, original license:
-------------------------------------------------------------------------------
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: dlgSearchText.pas, released 2000-06-23.
The Original Code is part of the SearchReplaceDemo project, written by
Michael Hieke for the SynEdit component suite.
All Rights Reserved.
Contributors to the SynEdit project are listed in the Contributors.txt file.
Alternatively, the contents of this file may be used under the terms of the
GNU General Public License Version 2 or later (the "GPL"), in which case
the provisions of the GPL are applicable instead of those above.
If you wish to allow use of your version of this file only under the terms
of the GPL and not to allow others to use your version of this file
under the MPL, indicate your decision by deleting the provisions above and
replace them with the notice and other provisions required by the GPL.
If you do not delete the provisions above, a recipient may use your version
of this file under either the MPL or the GPL.
$Id: dlgSearchText.pas,v 1.3 2002/08/01 05:44:05 etrusco Exp $
You may retrieve the latest version of this file at the SynEdit home page,
located at http://SynEdit.SourceForge.net
Known Issues:
-------------------------------------------------------------------------------}
unit fEditSearch;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, StdCtrls, ExtCtrls, Buttons, ButtonPanel,
uOSForms, DCClassesUtf8;
type
{ TEditSearchDialogOption }
//Not only it helps to show what we want to offer to user, it will help to determine the default
//When used as parameters of function, place on required.
//When used as a returned value, we'll include the status of all.
TEditSearchDialogOption = set of (eswoCaseSensitiveChecked, eswoCaseSensitiveUnchecked,
eswoWholeWordChecked, eswoWholeWordUnchecked,
eswoSelectedTextChecked, eswoSelectedTextUnchecked,
eswoSearchFromCursorChecked, eswoSearchFromCursorUnchecked,
eswoRegularExpressChecked, eswoRegularExpressUnchecked,
eswoDirectionDisabled, eswoDirectionEnabledForward, eswoDirectionEnabledBackward);
{ TfrmEditSearchReplace }
TfrmEditSearchReplace = class(TModalForm)
ButtonPanel: TButtonPanel;
cbSearchText: TComboBox;
cbSearchCaseSensitive: TCheckBox;
cbSearchWholeWords: TCheckBox;
cbSearchSelectedOnly: TCheckBox;
cbSearchFromCursor: TCheckBox;
cbSearchRegExp: TCheckBox;
cbReplaceText: TComboBox;
gbSearchOptions: TGroupBox;
lblReplaceWith: TLabel;
lblSearchFor: TLabel;
rgSearchDirection: TRadioGroup;
procedure btnOKClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: boolean);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure RequestAlign(Data: PtrInt);
private
function GetSearchBackwards: boolean;
function GetSearchCaseSensitive: boolean;
function GetSearchFromCursor: boolean;
function GetSearchInSelection: boolean;
function GetSearchText: string;
function GetSearchTextHistory: string;
function GetSearchWholeWords: boolean;
function GetSearchRegExp: boolean;
function GetReplaceText: string;
function GetReplaceTextHistory: string;
procedure SetSearchBackwards(Value: boolean);
procedure SetSearchCaseSensitive(Value: boolean);
procedure SetSearchFromCursor(Value: boolean);
procedure SetSearchInSelection(Value: boolean);
procedure SetSearchText(Value: string);
procedure SetSearchTextHistory(Value: string);
procedure SetSearchWholeWords(Value: boolean);
procedure SetSearchRegExp(Value: boolean);
procedure SetReplaceText(Value: string);
procedure SetReplaceTextHistory(Value: string);
function GetTextSearchOptions: UIntPtr;
public
constructor Create(AOwner: TComponent; AReplace: Boolean); reintroduce;
property SearchBackwards: boolean read GetSearchBackwards
write SetSearchBackwards;
property SearchCaseSensitive: boolean read GetSearchCaseSensitive
write SetSearchCaseSensitive;
property SearchFromCursor: boolean read GetSearchFromCursor
write SetSearchFromCursor;
property SearchInSelectionOnly: boolean read GetSearchInSelection
write SetSearchInSelection;
property SearchText: string read GetSearchText write SetSearchText;
property SearchTextHistory: string read GetSearchTextHistory
write SetSearchTextHistory;
property SearchWholeWords: boolean read GetSearchWholeWords
write SetSearchWholeWords;
property SearchRegExp: boolean read GetSearchRegExp
write SetSearchRegExp;
property ReplaceText: string read GetReplaceText write SetReplaceText;
property ReplaceTextHistory: string read GetReplaceTextHistory
write SetReplaceTextHistory;
end;
function GetSimpleSearchAndReplaceString(AOwner:TComponent; OptionAllowed:TEditSearchDialogOption; var sSearchText:string; var sReplaceText:string; var OptionsToReturn:TEditSearchDialogOption; PastSearchList:TStringListEx; PastReplaceList:TStringListEx):boolean;
implementation
{$R *.lfm}
uses
Math, Graphics, uGlobs, uLng, uDCUtils, uFindFiles;
function GetSimpleSearchAndReplaceString(AOwner:TComponent; OptionAllowed:TEditSearchDialogOption; var sSearchText:string; var sReplaceText:string; var OptionsToReturn:TEditSearchDialogOption; PastSearchList:TStringListEx; PastReplaceList:TStringListEx):boolean;
var
dlg: TfrmEditSearchReplace;
begin
result:=FALSE;
OptionsToReturn:=[];
dlg := TfrmEditSearchReplace.Create(AOwner, TRUE);
try
with dlg do
begin
//1. Let's enable to options host wanted to offer to user
cbSearchCaseSensitive.Enabled := ((eswoCaseSensitiveChecked in OptionAllowed) OR (eswoCaseSensitiveUnchecked in OptionAllowed));
cbSearchWholeWords.Enabled := ((eswoWholeWordChecked in OptionAllowed) OR (eswoWholeWordUnchecked in OptionAllowed));
cbSearchSelectedOnly.Enabled := ((eswoSelectedTextChecked in OptionAllowed) OR (eswoSelectedTextUnchecked in OptionAllowed));
cbSearchFromCursor.Enabled := ((eswoSearchFromCursorChecked in OptionAllowed) OR (eswoSearchFromCursorUnchecked in OptionAllowed));
cbSearchRegExp.Enabled := ((eswoRegularExpressChecked in OptionAllowed) OR (eswoRegularExpressUnchecked in OptionAllowed));
rgSearchDirection.Enabled := ((eswoDirectionEnabledForward in OptionAllowed) OR (eswoDirectionEnabledBackward in OptionAllowed));
//2. Let's set the option to their default according to what host wants to offer
cbSearchCaseSensitive.Checked := (eswoCaseSensitiveChecked in OptionAllowed);
cbSearchWholeWords.Checked := (eswoWholeWordChecked in OptionAllowed);
cbSearchSelectedOnly.Checked := (eswoSelectedTextChecked in OptionAllowed);
cbSearchFromCursor.Checked := (eswoSearchFromCursorChecked in OptionAllowed);
cbSearchRegExp.Checked := (eswoRegularExpressChecked in OptionAllowed);
rgSearchDirection.ItemIndex:=ifthen((eswoDirectionEnabledBackward in OptionAllowed),1,0);
//3. Setup the SEARCH info
if sSearchText='' then sSearchText:=rsEditSearchCaption;
SearchTextHistory:=PastSearchList.Text;
cbSearchText.Text:=sSearchText;
//4. Setup the REPLACE info
if sReplaceText='' then sReplaceText:=rsEditSearchReplace;
ReplaceTextHistory:=PastReplaceList.Text;
cbReplaceText.Text:=sReplaceText;
//5. Get feedback from user
if ShowModal=mrOk then
begin
//6. Let's set the options wanted by the user
if cbSearchCaseSensitive.Enabled then
if cbSearchCaseSensitive.Checked then OptionsToReturn:=OptionsToReturn+[eswoCaseSensitiveChecked] else OptionsToReturn:=OptionsToReturn+[eswoCaseSensitiveUnchecked];
if cbSearchWholeWords.Enabled then
if cbSearchWholeWords.Checked then OptionsToReturn:=OptionsToReturn+[eswoWholeWordChecked] else OptionsToReturn:=OptionsToReturn+[eswoWholeWordUnchecked];
if cbSearchSelectedOnly.Enabled then
if cbSearchSelectedOnly.Checked then OptionsToReturn:=OptionsToReturn+[eswoSelectedTextChecked] else OptionsToReturn:=OptionsToReturn+[eswoSelectedTextUnchecked];
if cbSearchFromCursor.Enabled then
if cbSearchFromCursor.Checked then OptionsToReturn:=OptionsToReturn+[eswoSearchFromCursorChecked] else OptionsToReturn:=OptionsToReturn+[eswoSearchFromCursorUnchecked];
if cbSearchRegExp.Enabled then
if cbSearchRegExp.Checked then OptionsToReturn:=OptionsToReturn+[eswoRegularExpressChecked] else OptionsToReturn:=OptionsToReturn+[eswoRegularExpressUnchecked];
if rgSearchDirection.Enabled then
if rgSearchDirection.ItemIndex=1 then OptionsToReturn:=OptionsToReturn+[eswoDirectionEnabledBackward] else OptionsToReturn:=OptionsToReturn+[eswoDirectionEnabledForward];
//7. Let's set our history
PastSearchList.Text:=SearchTextHistory;
PastReplaceList.Text:=ReplaceTextHistory;
//8. And FINALLY, our valuable text to search we wanted to replace!
sSearchText:=cbSearchText.Text;
sReplaceText:=cbReplaceText.Text;
result:=((sSearchText<>sReplaceText) AND (sSearchText<>''));
end;
end;
finally
FreeAndNil(Dlg);
end;
end;
{ TfrmEditSearchReplace }
procedure TfrmEditSearchReplace.btnOKClick(Sender: TObject);
begin
InsertFirstItem(cbSearchText.Text, cbSearchText, GetTextSearchOptions);
ModalResult := mrOK
end;
procedure TfrmEditSearchReplace.FormCloseQuery(Sender: TObject;
var CanClose: boolean);
begin
if ModalResult = mrOK then
InsertFirstItem(cbReplaceText.Text, cbReplaceText, GetTextSearchOptions);
end;
procedure TfrmEditSearchReplace.FormCreate(Sender: TObject);
begin
InitPropStorage(Self);
end;
procedure TfrmEditSearchReplace.FormShow(Sender: TObject);
begin
if cbSearchText.Text = EmptyStr then
begin
if cbSearchText.Items.Count > 0 then
cbSearchText.Text:= cbSearchText.Items[0];
end;
cbSearchText.SelectAll;
// Fixes AutoSize under Qt
Application.QueueAsyncCall(@RequestAlign, 0);
end;
procedure TfrmEditSearchReplace.RequestAlign(Data: PtrInt);
begin
Width := Width + 1;
Width := Width - 1;
end;
function TfrmEditSearchReplace.GetSearchBackwards: boolean;
begin
Result := rgSearchDirection.ItemIndex = 1;
end;
function TfrmEditSearchReplace.GetSearchCaseSensitive: boolean;
begin
Result := cbSearchCaseSensitive.Checked;
end;
function TfrmEditSearchReplace.GetSearchFromCursor: boolean;
begin
Result := cbSearchFromCursor.Checked;
end;
function TfrmEditSearchReplace.GetSearchInSelection: boolean;
begin
Result := cbSearchSelectedOnly.Checked;
end;
function TfrmEditSearchReplace.GetSearchText: string;
begin
Result := cbSearchText.Text;
end;
function TfrmEditSearchReplace.GetSearchTextHistory: string;
var
i: integer;
begin
for i:= cbSearchText.Items.Count - 1 downto 25 do
cbSearchText.Items.Delete(i);
Result:=cbSearchText.Items.Text;
end;
function TfrmEditSearchReplace.GetSearchWholeWords: boolean;
begin
Result := cbSearchWholeWords.Checked;
end;
function TfrmEditSearchReplace.GetSearchRegExp: boolean;
begin
Result:= cbSearchRegExp.Checked;
end;
function TfrmEditSearchReplace.GetReplaceText: string;
begin
Result := cbReplaceText.Text;
end;
function TfrmEditSearchReplace.GetReplaceTextHistory: string;
var
i: integer;
begin
for i:= cbSearchText.Items.Count - 1 downto 25 do
cbReplaceText.Items.Delete(i);
Result:=cbReplaceText.Items.Text;
end;
procedure TfrmEditSearchReplace.SetSearchBackwards(Value: boolean);
begin
rgSearchDirection.ItemIndex := Ord(Value);
end;
procedure TfrmEditSearchReplace.SetSearchCaseSensitive(Value: boolean);
begin
cbSearchCaseSensitive.Checked := Value;
end;
procedure TfrmEditSearchReplace.SetSearchFromCursor(Value: boolean);
begin
cbSearchFromCursor.Checked := Value;
end;
procedure TfrmEditSearchReplace.SetSearchInSelection(Value: boolean);
begin
cbSearchSelectedOnly.Checked := Value;
end;
procedure TfrmEditSearchReplace.SetSearchText(Value: string);
begin
cbSearchText.Text := Value;
end;
procedure TfrmEditSearchReplace.SetSearchTextHistory(Value: string);
begin
cbSearchText.Items.Text := Value;
end;
procedure TfrmEditSearchReplace.SetSearchWholeWords(Value: boolean);
begin
cbSearchWholeWords.Checked := Value;
end;
procedure TfrmEditSearchReplace.SetSearchRegExp(Value: boolean);
begin
cbSearchRegExp.Checked:= Value;
end;
procedure TfrmEditSearchReplace.SetReplaceText(Value: string);
begin
cbReplaceText.Items.Text := Value;
end;
procedure TfrmEditSearchReplace.SetReplaceTextHistory(Value: string);
begin
cbReplaceText.Items.Text := Value;
end;
function TfrmEditSearchReplace.GetTextSearchOptions: UIntPtr;
var
Options: TTextSearchOptions absolute Result;
begin
Result:= 0;
if cbSearchCaseSensitive.Checked then
Include(Options, tsoMatchCase);
if cbSearchRegExp.Checked then
Include(Options, tsoRegExpr);
end;
constructor TfrmEditSearchReplace.Create(AOwner: TComponent; AReplace: Boolean);
begin
inherited Create(AOwner);
Color:= clForm;
if AReplace then
begin
Caption:= rsEditSearchReplace;
lblReplaceWith.Visible:= True;
cbReplaceText.Visible:= True;
end
else
begin
Caption:= rsEditSearchCaption;
lblReplaceWith.Visible:= False;
cbReplaceText.Visible:= False;
Height:= Height - cbReplaceText.Height;
end;
rgSearchDirection.Items.Strings[0]:= rsEditSearchFrw;
rgSearchDirection.Items.Strings[1]:= rsEditSearchBack;
end;
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:
related to datetime, used by many units to visually display formatted time eg: 00:00:00
}
unit helper_datetime;
interface
uses
sysutils,windows;
const
UnixStartDate : tdatetime = 25569.0;
TENTHOFSEC=100;
SECOND=1000;
MINUTE=60000;
HOUR=3600000;
DAY=86400000;
SECONDSPERDAY=86400;
function UnixToDelphiDateTime(USec:longint):TDateTime;
function DelphiDateTimeToUnix(ConvDate:TdateTime):longint;
function format_time(secs:integer):string;
function DelphiDateTimeSince1900(ConvDate:TdateTime):longint;
function time_now:cardinal;
function HR2S(hours:single):cardinal;
function SEC(seconds:integer):cardinal;
function MIN2S(minutes:single):cardinal;
function DateTimeToUnixTime(const DateTime: TDateTime): cardinal;
function UnixTimeToDateTime(const UnixTime: cardinal): TDateTime;
implementation
function DateTimeToUnixTime(const DateTime:TDateTime): cardinal;
var
FileTime:TFileTime;
SystemTime:TSystemTime;
I:Int64;
begin
// first convert datetime to Win32 file time
DateTimeToSystemTime(DateTime, SystemTime);
SystemTimeToFileTime(SystemTime, FileTime);
// simple maths to go from Win32 time to Unix time
I:=Int64(FileTime.dwHighDateTime) shl 32 + FileTime.dwLowDateTime;
Result:=(I - 116444736000000000) div Int64(10000000);
end;
function UnixTimeToDateTime(const UnixTime: cardinal): TDateTime;
var
FileTime:TFileTime;
SystemTime:TSystemTime;
I:Int64;
begin
// first convert unix time to a Win32 file time
I:=Int64(UnixTime) * Int64(10000000) + 116444736000000000;
FileTime.dwLowDateTime:=DWORD(I);
FileTime.dwHighDateTime:=I shr 32;
// now convert to system time
FileTimeToSystemTime(FileTime,SystemTime);
// and finally convert the system time to TDateTime
Result:=SystemTimeToDateTime(SystemTime);
end;
function format_time(secs:integer):string;
var
ore,minuti,secondi,variabile:integer;
begin
if secs>0 then begin
if secs<60 then begin
ore:=0;
minuti:=0;
secondi:=secs;
end
else if secs<3600 then begin
ore:=0;
minuti:=(secs div 60);
secondi:=(secs-((secs div 60)*60));
end
else begin
ore:=(secs div 3600);
variabile:=(secs-((secs div 3600)*3600)); //minuti avanzati
minuti:=variabile div 60;
secondi:=variabile-((minuti )* 60);
end;
if ore=0 then result:='' else result:=inttostr(ore)+':';
if ((minuti=0) and (ore=0)) then result:='0:' else begin
if minuti<10 then begin
if ore=0 then result:=inttostr(minuti)+':'
else result:=result+'0'+inttostr(minuti)+':';
end else result:=result+inttostr(minuti)+':';
end;
if secondi<10 then result:=result+'0'+inttostr(secondi)
else result:=result+inttostr(secondi);
end else result:='0:00'; // fake tempo se non ho niente nella var
end;
function DelphiDateTimeToUnix(ConvDate:TdateTime):longint;
// Converts Delphi TDateTime to Unix seconds,
// ConvDate = the Date and Time that you want to convert
// example: UnixSeconds:=DelphiDateTimeToUnix(Now);
begin
Result:=round((ConvDate-UnixStartDate)*SECONDSPERDAY);
end;
function UnixToDelphiDateTime(USec:longint):TDateTime;
{Converts Unix seconds to Delphi TDateTime,
USec = the Unix Date Time that you want to convert
example: DelphiTimeDate:=UnixToDelphiTimeDate(693596);}
begin
Result:=(Usec/SECONDSPERDAY)+UnixStartDate;
end;
function time_now:cardinal;
begin
result:=DelphiDateTimeSince1900(now);
end;
function HR2S(hours:single):cardinal;
begin
result:=MIN2S(hours*60);
end;
function SEC(seconds:integer):cardinal;
begin
result:=seconds;
end;
function MIN2S(minutes:single):cardinal;
begin
result:=round(minutes * 60);
end;
function DelphiDateTimeSince1900(ConvDate:TdateTime):longint;
// Converts Delphi TDateTime to Unix seconds,
// ConvDate = the Date and Time that you want to convert
// example: UnixSeconds:=DelphiDateTimeToUnix(Now);
begin
Result:=round((ConvDate-1.5)*86400);
end;
end.
|
unit LuiJSONHelpers;
{$mode objfpc}{$H+}
interface
uses
fpjson;
type
{ TJSONObjectHelper }
TJSONObjectHelper = class helper for TJSONObject
public
function Find(const PropName: String; out PropData: TJSONData): Boolean; overload;
function Find(const PropName: String; out PropData: TJSONObject): Boolean; overload;
function Find(const PropName: String; out PropData: TJSONArray): Boolean; overload;
function Find(const PropName: String; out PropValue: Integer): Boolean; overload;
function Find(const PropName: String; out PropValue: Int64): Boolean; overload;
function Find(const PropName: String; out PropValue: Double): Boolean; overload;
function Find(const PropName: String; out PropValue: Boolean): Boolean; overload;
function Find(const PropName: String; out PropValue: String): Boolean; overload;
end;
{ TJSONArrayHelper }
TJSONArrayHelper = class helper for TJSONArray
public
function IndexOf(const ItemValue: Variant): Integer; overload;
function IndexOf(const Properties: array of Variant): Integer; overload;
end;
implementation
uses
sysutils, LuiJSONUtils;
type
JSONHelperException = class(Exception);
{ TJSONObjectHelper }
function TJSONObjectHelper.Find(const PropName: String; out PropData: TJSONData): Boolean;
begin
PropData := Self.Find(PropName);
Result := PropData <> nil;
end;
function TJSONObjectHelper.Find(const PropName: String; out PropData: TJSONObject): Boolean;
var
Data: TJSONData absolute PropData;
begin
Data := Self.Find(PropName, jtObject);
Result := PropData <> nil;
end;
function TJSONObjectHelper.Find(const PropName: String; out PropData: TJSONArray): Boolean;
var
Data: TJSONData absolute PropData;
begin
Data := Self.Find(PropName, jtArray);
Result := PropData <> nil;
end;
function TJSONObjectHelper.Find(const PropName: String; out PropValue: Integer): Boolean;
var
Data: TJSONData;
begin
Data := Self.Find(PropName, jtNumber);
Result := Data <> nil;
if Result then
PropValue := Data.AsInteger
else
PropValue := 0;
end;
function TJSONObjectHelper.Find(const PropName: String; out PropValue: Int64): Boolean;
var
Data: TJSONData;
begin
Data := Self.Find(PropName, jtNumber);
Result := Data <> nil;
if Result then
PropValue := Data.AsInt64
else
PropValue := 0;
end;
function TJSONObjectHelper.Find(const PropName: String; out PropValue: Double): Boolean;
var
Data: TJSONData;
begin
Data := Self.Find(PropName, jtNumber);
Result := Data <> nil;
if Result then
PropValue := Data.AsFloat
else
PropValue := 0;
end;
function TJSONObjectHelper.Find(const PropName: String; out PropValue: Boolean): Boolean;
var
Data: TJSONData;
begin
Data := Self.Find(PropName, jtBoolean);
Result := Data <> nil;
if Result then
PropValue := Data.AsBoolean
else
PropValue := False;
end;
function TJSONObjectHelper.Find(const PropName: String; out PropValue: String): Boolean;
var
Data: TJSONData;
begin
Data := Self.Find(PropName, jtString);
Result := Data <> nil;
if Result then
PropValue := Data.AsString
else
PropValue := '';
end;
{ TJSONArrayHelper }
function TJSONArrayHelper.IndexOf(const ItemValue: Variant): Integer;
begin
for Result := 0 to Count - 1 do
begin
if SameValue(Items[Result], ItemValue) then
Exit;
end;
Result := -1;
end;
function TJSONArrayHelper.IndexOf(const Properties: array of Variant): Integer;
var
PropCount, i: Integer;
ItemData, PropData: TJSONData;
ObjMatches: Boolean;
begin
PropCount := Length(Properties);
Result := -1;
if odd(PropCount) then
raise JSONHelperException.Create('Properties must have even length');
PropCount := PropCount div 2;
for Result := 0 to Self.Count - 1 do
begin
ItemData := Self.Items[Result];
ObjMatches := False;
if ItemData.JSONType = jtObject then
begin
for i := 0 to PropCount - 1 do
begin
PropData := ItemData.FindPath(Properties[i * 2]);
ObjMatches := (PropData <> nil) and SameValue(PropData, Properties[(i * 2) + 1]);
if not ObjMatches then
break;
end;
end;
if ObjMatches then
Exit;
end;
Result := -1;
end;
end.
|
{ **************************************************************
Package: XWB - Kernel RPCBroker
Date Created: Sept 18, 1997 (Version 1.1)
Site Name: Oakland, OI Field Office, Dept of Veteran Affairs
Developers: Danila Manapsal, Don Craven, Joel Ivey
Description: Contains TRPCBroker and related components.
Unit: XlfSid Thread or Process security in Windows.
Current Release: Version 1.1 Patch 65
*************************************************************** }
{ **************************************************
Changes in v1.1.65 (HGW 08/05/2015) XWB*1.1*65
1. None.
Changes in v1.1.60 (HGW 07/16/2013) XWB*1.1*60
1. None.
Changes in v1.1.50 (JLI 09/01/2011) XWB*1.1*50
1. None.
************************************************** }
unit XlfSid;
//*******************************************************
//These functions get their data from the Thread
// or Process security ID in Windows.
// GetNTLogonUser returns the Domain\Username that
// authenticated the user/
// GetNTLogonSid returns a string with the users SID.
//********************************************************
interface
uses
{System}
SysUtils,
{WinApi}
Windows;
type {From MSDN}
StringSid = ^LPTSTR;
function ConvertSidToStringSid(Sid: {THandle}PSID; var StrSid: LPTSTR): BOOL stdcall;
function GetNTLogonUser(): string;
function GetNTLogonSid(): string;
implementation
function ConvertSidToStringSid; external advapi32 name 'ConvertSidToStringSidW';
function GetNTLogonUser(): string;
var
hToken: THANDLE;
tic: TTokenInformationClass;
ptkUser: PSIDAndAttributes;
P: pointer;
buf: PChar;
cbti: DWORD;
Name: PChar;
cbName: DWORD;
RDN: PChar;
cbRDN: DWORD;
snu: DWORD;
begin
Result := '';
tic := TokenUser;
Name := '';
RDN := '';
try
//Get the calling thread's access token
if not OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, longbool(true), hToken) then
if (GetLastError() <> ERROR_NO_TOKEN) then exit
// Retry against process token if no thread token exist.
else
if not OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY, hToken) then exit;
// Obtain the size of the user info in the token
// Call should fail due to zero-length buffer
if GetTokenInformation(hToken, tic, nil, 0, cbti) then exit;
// Allocate buffer for user Info
buf := StrAlloc(cbti);
// Retrive the user info from the token.
if not GetTokenInformation(hToken, tic, buf, cbti, cbti) then exit;
cbName := 0;
cbRDN := 0;
snu := 0;
P := buf; //Use pointer to recast PChar
ptkUser := PSIDAndAttributes(P);
//call to get the size of name and RDN.
LookupAccountSid( nil, ptkUser.Sid, Name, cbName
, RDN, cbRDN, snu);
Name := StrAlloc(cbName);
RDN := StrAlloc(cbRDN);
//Call to fillin Name and RDN
LookupAccountSid( nil, ptkUser.Sid, Name, cbName
, RDN, cbRDN, snu);
Result := string(RDN) + '\' + string(Name);
StrDispose(Name);
StrDispose(RDN);
finally
if (hToken <> 0) then CloseHandle(hToken);
end;
end;
function GetNTLogonSid(): string;
var
hToken: THANDLE;
tic: TTokenInformationClass;
ptkUser: PSIDAndAttributes;
P: pointer;
buf: PChar;
StrSid: PChar;
cbti: DWORD;
// cbName: DWORD;
// cbRDN: DWORD;
// snu: DWORD;
begin
Result := '';
tic := TokenUser;
try
//Get the calling thread's access token
if not OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, longbool(true), hToken) then
if (GetLastError() <> ERROR_NO_TOKEN) then exit
// Retry against process token if no thread token exist.
else
if not OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY, hToken) then exit;
// Obtain the size of the user info in the token
// Call should fail due to zero-length buffer
if GetTokenInformation(hToken, tic, nil, 0, cbti) then exit;
// Allocate buffer for user Info
buf := StrAlloc(cbti);
// Retrive the user info from the token.
if not GetTokenInformation(hToken, tic, buf, cbti, cbti) then exit;
P := buf; //Use pointer to recast PChar
ptkUser := PSIDAndAttributes(P);
// P := nil;
if ConvertSidToStringSid(ptkUser.sid, StrSid) = true then
begin
Result := PChar(StrSid);
localFree(Cardinal(StrSid));
end;
finally
if (hToken <> 0) then CloseHandle(hToken);
end;
end;
end.
|
unit UDMMongo;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.MongoDB,
FireDAC.Phys.MongoDBDef, System.Rtti, System.JSON.Types, System.JSON.Readers,
System.JSON.BSON, System.JSON.Builders, FireDAC.Phys.MongoDBWrapper,
FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.Client, IniFiles, Forms,
FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf,
FireDAC.Phys.MongoDBDataSet, FireDAC.Comp.DataSet, ULogData, ULogType;
type
TDMMongo = class(TDataModule)
Connection: TFDConnection;
MongoDriverLink: TFDPhysMongoDriverLink;
MongoDataSet: TFDMongoDataSet;
MongoQuery: TFDMongoQuery;
MongoPipeline: TFDMongoPipeline;
private
{ Private declarations }
FMongoEnv : TMongoEnv;
FMongoCon : TMongoConnection;
FDataBase : String;
procedure LoadParams;
procedure PrepareConnection;
public
{ Public declarations }
function TestConnection : Boolean;
function SearchAll(CollectionName: String) : IMongoCursor;
function Search(CollectionName: String; Query : TMongoQuery) : IMongoCursor;
function GetNewDocument: TMongoDocument;
function Insert(CollectionName: String; Doc: TMongoDocument): boolean;
end;
var
DMMongo: TDMMongo;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TDMMongo }
function TDMMongo.GetNewDocument: TMongoDocument;
begin
if not Connection.Connected then
PrepareConnection;
Result := FMongoEnv.NewDoc;
end;
function TDMMongo.Insert(CollectionName: String; Doc: TMongoDocument): boolean;
begin
try
if not Connection.Connected then
PrepareConnection;
FMongoCon[FDataBase][CollectionName].Insert(Doc);
Result := true;
except
on E: Exception do
begin
Result := false;
end;
end
end;
procedure TDMMongo.LoadParams;
var
ArqIni: TIniFile;
Params : TStringList;
begin
ArqIni := TIniFile.Create(ExtractFileDir(Application.ExeName) + '\Connection.ini');
Params := TStringList.Create;
Params.Add('DriverID=Mongo');
Params.Add('Server=' + ArqIni.ReadString('MongoDB','Server','localhost'));
Params.Add('Database=' + ArqIni.ReadString('MongoDB','Database',''));
Params.Add('Port=' + ArqIni.ReadString('MongoDB','Port','27017'));
Connection.Params.Clear;
Connection.Params.AddStrings(Params);
FDataBase := ArqIni.ReadString('MongoDB','Database','');
end;
procedure TDMMongo.PrepareConnection;
begin
try
LoadParams;
Connection.Connected := True;
FMongoCon := TMongoConnection(Connection.CliObj);
FMongoEnv := FMongoCon.Env;
except
on E:Exception do
begin
TLogData.SaveLog(E.Message,'Teste de conex„o com Mongo',ltError);
end;
end;
end;
function TDMMongo.Search(CollectionName: String;
Query: TMongoQuery): IMongoCursor;
begin
end;
function TDMMongo.SearchAll(CollectionName: String): IMongoCursor;
begin
if not Connection.Connected then
PrepareConnection;
Result := FMongoCon[FDataBase][CollectionName].Find();
end;
function TDMMongo.TestConnection: Boolean;
begin
try
LoadParams;
Connection.Connected := True;
Result := True;
Connection.Connected := False;
except
on E:Exception do
begin
TLogData.SaveLog(E.Message,'Teste de conex„o com Mongo',ltError);
Result := False;
end;
end;
end;
end.
|
{*******************************************************************************
* *
* TksFormTransition - Push/Pop Form Queue Component *
* *
* https://bitbucket.org/gmurt/kscomponents *
* *
* Copyright 2017 Graham Murt *
* *
* email: graham@kernow-software.co.uk *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* *
*******************************************************************************}
unit ksFormTransition;
interface
{$I ksComponents.inc}
uses System.UITypes, FMX.Controls, FMX.Layouts, FMX.Objects, System.Classes,
FMX.Types, FMX.Graphics, System.UIConsts, FMX.Effects,
FMX.StdCtrls, System.Types, FMX.Forms, ksTypes, System.Generics.Collections;
const
{$IFDEF ANDROID}
C_TRANSITION_DURATION = 0.2;
{$ELSE}
C_TRANSITION_DURATION = 0.2;
{$ENDIF}
C_FADE_OPACITY = 0.5;
type
TksTransitionMethod = (ksTmPush, ksTmPop);
IksFormTransition = interface
['{34A12E50-B52C-4A49-B081-9CB67CA5FD6E}']
procedure BeforeTransition(AType: TksTransitionMethod);
end;
IksPostFormTransition = interface
['{CD11BABA-8659-4F42-A6BC-5E03B74690EE}']
procedure AfterTransition(AType: TksTransitionMethod);
end;
TksTransitionType = (ksFtSlideInFromLeft,
ksFtSlideInFromTop,
ksFtSlideInFromRight,
ksFtSlideInFromBottom,
ksFtSlideOutToLeft,
ksFtSlideOutToTop,
ksFtSlideOutToRight,
ksFtSlideOutToBottom,
ksFtNoTransition);
TksFormTransitionItem = class
[weak]FFromForm: TCommonCustomForm;
[weak]FToForm: TCommonCustomForm;
FTransition: TksTransitionType;
public
property FromForm: TCommonCustomForm read FFromForm;
property ToForm: TCommonCustomForm read FToForm;
property Transition: TksTransitionType read FTransition write FTransition;
end;
TksFormTransitionList = class(TObjectList<TksFormTransitionItem>)
public
end;
[ComponentPlatformsAttribute(
pidWin32 or
pidWin64 or
{$IFDEF XE8_OR_NEWER} pidiOSDevice32 or pidiOSDevice64 {$ELSE} pidiOSDevice {$ENDIF} or
{$IFDEF XE10_3_OR_NEWER} pidiOSSimulator32 or pidiOSSimulator64 {$ELSE} pidiOSSimulator {$ENDIF} or
{$IFDEF XE10_3_OR_NEWER} pidAndroid32Arm or pidAndroid64Arm {$ELSE} pidAndroid {$ENDIF}
)]
TksFormTransition = class(TksComponent)
private
FInitalizedForms: TList<TCommonCustomForm>;
function GetTransitionList: TksFormTransitionList;
function TransitionExists(AFrom, ATo: TCommonCustomForm): Boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetFormDepth(AForm: TCommonCustomForm): integer;
procedure Push(AForm: TCommonCustomForm;
const ATransition: TksTransitionType = ksFtSlideInFromRight;
const ARecordPush: Boolean = True);
procedure Pop;
procedure PopTo(AFormClass: string);
procedure PopAllForms;
property TransitionList: TksFormTransitionList read GetTransitionList;
end;
//{$R *.dcr}
procedure Push(AForm: TCommonCustomForm; const ATransition: TksTransitionType = ksFtSlideInFromRight; const ARecordPush: Boolean = True);
procedure Pop;
procedure PopTo(AFormClass: string);
procedure PopAllForms;
procedure ClearFormTransitionStack;
procedure ClearLastFormTransition;
procedure Register;
var
ShowLoadingIndicatorOnTransition: Boolean;
DisableTransitions: Boolean;
implementation
uses FMX.Ani, SysUtils, ksCommon, DateUtils, ksFormTransitionUI, ksToolbar,
ksPickers, ksLoadingIndicator
{$IFDEF IOS}
, IOSApi.UIKit
{$ENDIF}
;
var
_InternalTransitionList: TksFormTransitionList;
_InTransition: Boolean;
procedure Register;
begin
RegisterComponents('Kernow Software FMX', [TksFormTransition]);
end;
function IsIPad: Boolean;
begin
{$IFDEF IOS}
Result := TUIDevice.Wrap( TUIDevice.OCClass.currentDevice ).userInterfaceIdiom = UIUserInterfaceIdiomPad;
{$ELSE}
Result := False;
{$ENDIF}
end;
procedure Push(AForm: TCommonCustomForm; const ATransition: TksTransitionType = ksFtSlideInFromRight; const ARecordPush: Boolean = True);
var
ATran: TksFormTransition;
begin
ATran := TksFormTransition.Create(nil);
try
// prevent animation on ipad...
if IsIPad then
ATran.Push(AForm, ksFtNoTransition, ARecordPush)
else
{$IFDEF ANDROID}
ATran.Push(AForm, ksFtNoTransition, ARecordPush)
{$ELSE}
ATran.Push(AForm, ATransition, ARecordPush);
{$ENDIF}
finally
FreeAndNil(ATran);
end;
HideLoadingIndicator(AForm);
end;
procedure Pop;
var
ATran: TksFormTransition;
begin
ATran := TksFormTransition.Create(nil);
try
ATran.Pop;
finally
FreeAndNil(ATran);
end;
end;
procedure PopTo(AFormClass: string);
var
ATran: TksFormTransition;
begin
ATran := TksFormTransition.Create(nil);
try
ATran.PopTo(AFormClass);
finally
FreeAndNil(ATran);
end;
end;
procedure PopAllForms;
var
ATran: TksFormTransition;
begin
ATran := TksFormTransition.Create(nil);
try
ATran.PopAllForms;
finally
FreeAndNil(ATran);
end;
end;
procedure ClearFormTransitionStack;
begin
_InternalTransitionList.Clear;
end;
procedure ClearLastFormTransition;
begin
_InternalTransitionList.Delete(_InternalTransitionList.Count-1);
end;
{ TksFormTransition }
constructor TksFormTransition.Create(AOwner: TComponent);
begin
inherited;
FInitalizedForms := TList<TCommonCustomForm>.Create;
end;
destructor TksFormTransition.Destroy;
begin
FreeAndNil(FInitalizedForms);
inherited;
end;
function TksFormTransition.GetFormDepth(AForm: TCommonCustomForm): integer;
var
ICount: integer;
begin
Result := 0;
for ICount := 0 to TransitionList.Count-1 do
begin
if TransitionList[ICount].ToForm = AForm then
begin
Result := ICount+1;
end;
end;
end;
function TksFormTransition.GetTransitionList: TksFormTransitionList;
begin
Result := _InternalTransitionList;
end;
procedure TksFormTransition.Pop;
begin
PopTo('');
end;
procedure TksFormTransition.PopAllForms;
var
AInfo: TksFormTransitionItem;
AFrom, ATo: TCommonCustomForm;
AAnimateForm: TfrmFormTransitionUI;
AFormIntf: IksFormTransition;
begin
if _InternalTransitionList.Count = 0 then
Exit;
if _InTransition then
Exit;
_InTransition := True;
try
AAnimateForm := TfrmFormTransitionUI.Create(nil);
try
AInfo := _InternalTransitionList.Last;
AFrom := AInfo.FToForm;
ATo := _InternalTransitionList.First.FFromForm;
{$IFDEF XE10_2_OR_NEWER}
AAnimateForm.SystemStatusBar.Assign(AFrom.SystemStatusBar);
{$ENDIF}
{if Supports(ATo, IksFormTransition, AFormIntf) then
AFormIntf.BeforeTransition(ksTmPop); }
// moved to here...
if Supports(ATo, IksFormTransition, AFormIntf) then
AFormIntf.BeforeTransition(ksTmPop);
AAnimateForm.Initialise(AFrom, ATo);
AAnimateForm.Visible := True;
AAnimateForm.Animate(AInfo.FTransition, True);
ATo.Visible := True;
AAnimateForm.Visible := False;
// moved to here...
//if Supports(ATo, IksFormTransition, AFormIntf) then
// AFormIntf.BeforeTransition(ksTmPop);
AFrom.Visible := False;
ATo.Activate;
{$IFDEF MSWINDOWS}
ATo.SetBounds(AFrom.Left, AFrom.Top, AFrom.Width, AFrom.Height);
{$ENDIF}
_InternalTransitionList.Clear;//(_InternalTransitionList.Count-1);
finally
AAnimateForm.DisposeOf;
end;
finally
_InTransition := False;
end;
end;
procedure TksFormTransition.PopTo(AFormClass: string);
var
AInfo: TksFormTransitionItem;
AFrom, ATo: TCommonCustomForm;
AAnimateForm: TfrmFormTransitionUI;
AFormIntf: IksFormTransition;
ALevels: Integer;
ICount: integer;
ALastTransition: TksTransitionType;
begin
Screen.ActiveForm.Focused := nil;
ALevels := 1;
if _InternalTransitionList.Count < 1 then
Exit;
if _InTransition then
Exit;
_InTransition := True;
AInfo := _InternalTransitionList.Last;
AFrom := AInfo.FToForm;
ATo := AInfo.FFromForm;
ALastTransition := _InternalTransitionList.Last.FTransition;
if AFormClass <> '' then
begin
while ATo.ClassName <> AFormClass do
begin
AInfo := _InternalTransitionList.Items[_InternalTransitionList.IndexOf(AInfo)-1];
ATo := AInfo.FFromForm;
Inc(ALevels);
end;
end;
AInfo.Transition := ALastTransition;
if ShowLoadingIndicatorOnTransition then
ShowLoadingIndicator(AFrom);
try
if Supports(ATo, IksFormTransition, AFormIntf) then
AFormIntf.BeforeTransition(ksTmPop);
{$IFNDEF ANDROID}
AAnimateForm := TfrmFormTransitionUI.Create(nil);
try
{$IFDEF XE10_2_OR_NEWER}
AAnimateForm.SystemStatusBar.Assign(AFrom.SystemStatusBar);
{$ENDIF}
// moved to here...
AAnimateForm.Initialise(AFrom, ATo);
AAnimateForm.Visible := True;
AAnimateForm.Animate(AInfo.FTransition, True);
ATo.Visible := True;
AAnimateForm.Visible := False;
AFrom.Visible := False;
ATo.Activate;
{$IFDEF MSWINDOWS}
ATo.SetBounds(AFrom.Left, AFrom.Top, AFrom.Width, AFrom.Height);
{$ENDIF}
for ICount := ALevels downto 1 do
_InternalTransitionList.Delete(_InternalTransitionList.Count-1);
finally
AAnimateForm.DisposeOf;
end;
{$ELSE}
ATo.Visible := True;
AFrom.Visible := False;
ATo.Activate;
for ICount := ALevels downto 1 do
_InternalTransitionList.Delete(_InternalTransitionList.Count-1);
{$ENDIF}
finally
if ShowLoadingIndicatorOnTransition then
HideLoadingIndicator(AFrom);
_InTransition := False;
end;
end;
procedure TksFormTransition.Push(AForm: TCommonCustomForm;
const ATransition: TksTransitionType = ksFtSlideInFromRight;
const ARecordPush: Boolean = True);
var
AInfo: TksFormTransitionItem;
AFrom, ATo: TCommonCustomForm;
AAnimateForm: TfrmFormTransitionUI;
AFormIntf: IksFormTransition;
APostFormIntf: IksPostFormTransition;
ATran: TksTransitionType;
begin
if _InTransition then
Exit;
ATran := ATransition;
if DisableTransitions then
ATran := ksFtNoTransition;
if (Screen.ActiveForm = nil) then // can happen when main form calls push in onShow in Android
Exit;
AFrom := Screen.ActiveForm;
//(AFrom);
ATo := AForm;
{$IFDEF MSWINDOWS}
{$IFDEF XE10_OR_NEWER}
if AFrom <> nil then
ATo.Bounds := AFrom.Bounds;
{$ENDIF}
{$ENDIF}
_InTransition := True;
if (ShowLoadingIndicatorOnTransition) and (AFrom <> nil) then
ShowLoadingIndicator(AFrom);
try
PickerService.HidePickers;
{$IFDEF ANDROID}
// fix for Android initial form size
if FInitalizedForms.IndexOf(AFrom) = -1 then
FInitalizedForms.Add(AFrom);
if FInitalizedForms.IndexOf(ATo) = -1 then
begin
FInitalizedForms.Add(ATo);
end;
{$ENDIF}
if (AFrom = ATo) then
Exit;
if TransitionExists(AFrom, ATo) then
Exit;
AInfo := TksFormTransitionItem.Create;
AInfo.FFromForm := AFrom;
AInfo.FToForm := ATo;
AInfo.FTransition := ATran;
if ARecordPush then
_InternalTransitionList.Add(AInfo);
if (ATran <> TksTransitionType.ksFtNoTransition) and (DisableTransitions = False) then
begin
AAnimateForm := TfrmFormTransitionUI.Create(nil);
try
{$IFDEF XE10_2_OR_NEWER}
if AFrom.SystemStatusBar <> nil then
AAnimateForm.SystemStatusBar.Assign(AFrom.SystemStatusBar);
{$ENDIF}
AAnimateForm.Initialise(AFrom, ATo);
AAnimateForm.Visible := True;
AAnimateForm.Animate(AInfo.FTransition, False);
// moved to here...
if Supports(ATo, IksFormTransition, AFormIntf) then
AFormIntf.BeforeTransition(ksTmPush);
AForm.Visible := True;
AAnimateForm.Visible := False;
AFrom.Visible := False;
AForm.Activate;
{$IFDEF MSWINDOWS}
AForm.SetBounds(AFrom.Left, AFrom.Top, AFrom.Width, AFrom.Height);
{$ENDIF}
finally
AAnimateForm.DisposeOf;
end;
end
else
begin
// no animation...
if Supports(ATo, IksFormTransition, AFormIntf) then
AFormIntf.BeforeTransition(ksTmPush);
AForm.Visible := True;
if AFrom <> nil then
AFrom.Visible := False;
end;
if Supports(ATo, IksPostFormTransition, APostFormIntf) then
APostFormIntf.AfterTransition(ksTmPush);
finally
if not ARecordPush then
FreeAndNil(AInfo);
_InTransition := False;
if (ShowLoadingIndicatorOnTransition) and (AFrom <> nil) then
HideLoadingIndicator(AFrom);
end;
end;
function TksFormTransition.TransitionExists(AFrom,
ATo: TCommonCustomForm): Boolean;
var
ICount: integer;
AItem: TksFormTransitionItem;
begin
Result := False;
for ICount := 0 to GetTransitionList.Count-1 do
begin
AItem := GetTransitionList.Items[ICount];
if (AItem.FromForm = AFrom) and (AItem.ToForm = ATo) then
begin
Result := True;
Exit;
end;
end;
end;
initialization
{$IFDEF IOS}
ShowLoadingIndicatorOnTransition := True;
{$ELSE}
ShowLoadingIndicatorOnTransition := True;
{$ENDIF}
_InternalTransitionList := TksFormTransitionList.Create(True);
_InTransition := False;
DisableTransitions := False;
finalization
FreeAndNil(_InternalTransitionList);
end.
|
{***************************************************************
*
* Project : ParseURI
* Unit Name: main
* Purpose : Demonstrates the URL parser component
* Date : 21/01/2001 - 14:38:56
* History :
*
****************************************************************}
unit main;
interface
uses
{$IFDEF Linux}
QControls, QGraphics, QForms, QDialogs, QStdCtrls,
{$ELSE}
windows, messages, graphics, controls, forms, dialogs, stdctrls,
{$ENDIF}
SysUtils, Classes;
type
TfrmDemo = class(TForm)
edtURI: TEdit;
edtProtocol: TEdit;
edtHost: TEdit;
edtPort: TEdit;
lblProtocol: TLabel;
lblHost: TLabel;
lblPort: TLabel;
lblPath: TLabel;
lblDocument: TLabel;
edtPath: TEdit;
edtDocument: TEdit;
btnDoIt: TButton;
lblURI: TLabel;
lblInstructions: TLabel;
procedure btnDoItClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmDemo: TfrmDemo;
implementation
uses IdURI;
{$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF}
procedure TfrmDemo.btnDoItClick(Sender: TObject);
var URI : TIdURI;
begin
URI := TIdURI.Create(edtURI.Text);
try
edtProtocol.Text := URI.Protocol;
edtHost.Text := URI.Host;
edtPort.Text := URI.Port;
edtPath.Text := URI.Path;
edtDocument.Text := URI.Document;
finally
URI.Free;
end;
end;
end.
|
unit BaseProductsViewModel1;
interface
uses
BaseProductsViewModel, ProductsBaseQuery0, ProductsBaseQuery,
ExtraChargeGroupUnit;
type
TBaseProductsViewModel1 = class(TBaseProductsViewModel)
private
FExtraChargeGroup: TExtraChargeGroup;
function GetExtraChargeGroup: TExtraChargeGroup;
function GetqProductsBase: TQueryProductsBase;
protected
function CreateProductsQuery: TQryProductsBase0; override;
public
property ExtraChargeGroup: TExtraChargeGroup read GetExtraChargeGroup;
property qProductsBase: TQueryProductsBase read GetqProductsBase;
end;
implementation
function TBaseProductsViewModel1.CreateProductsQuery: TQryProductsBase0;
begin
Result := TQueryProductsBase.Create(Self, ProducersGroup);
end;
function TBaseProductsViewModel1.GetExtraChargeGroup: TExtraChargeGroup;
begin
if FExtraChargeGroup = nil then
begin
FExtraChargeGroup := TExtraChargeGroup.Create(Self);
FExtraChargeGroup.ReOpen;
end;
Result := FExtraChargeGroup;
end;
function TBaseProductsViewModel1.GetqProductsBase: TQueryProductsBase;
begin
Result := qProductsBase0 as TQueryProductsBase;
end;
end.
|
unit FIToolkit.ExecutionStates;
interface
uses
System.Classes, System.SysUtils, System.Generics.Collections, System.TimeSpan,
FIToolkit.Types,
FIToolkit.Commons.FiniteStateMachine.FSM, //TODO: remove when "F2084 Internal Error: URW1175" fixed
FIToolkit.Commons.StateMachine,
FIToolkit.Config.Data, FIToolkit.ProjectGroupParser.Parser, FIToolkit.Runner.Tasks,
FIToolkit.Reports.Parser.XMLOutputParser, FIToolkit.Reports.Parser.Messages, FIToolkit.Reports.Parser.Types,
FIToolkit.Reports.Builder.Types, FIToolkit.Reports.Builder.Intf;
type
TWorkflowStateHolder = class sealed
private
{ Primary logical entities }
FConfigData : TConfigData;
FFixInsightXMLParser : TFixInsightXMLParser;
FProjectGroupParser : TProjectGroupParser;
FProjectParser : TProjectParser;
FReportBuilder : IReportBuilder;
FTaskManager : TTaskManager;
{ Supporting infrastructure }
FDeduplicator : TFixInsightMessages;
FInputFileType : TInputFileType;
FMessages : TDictionary<TFileName, TArray<TFixInsightMessage>>;
FProjects : TArray<TFileName>;
FReportFileName : TFileName;
FReportOutput : TStreamWriter;
FReports : TArray<TPair<TFileName, TFileName>>;
FStartTime : TDateTime;
FTotalDuration : TTimeSpan;
FTotalMessages : Integer;
private
procedure InitReportBuilder;
public
constructor Create(ConfigData : TConfigData);
destructor Destroy; override;
property TotalDuration : TTimeSpan read FTotalDuration;
property TotalMessages : Integer read FTotalMessages;
end;
TExecutiveTransitionsProvider = class sealed
private
type
//TODO: replace when "F2084 Internal Error: URW1175" fixed
IStateMachine = IFiniteStateMachine<TApplicationState, TApplicationCommand, EStateMachineError>;
public
class procedure PrepareWorkflow(const StateMachine : IStateMachine; StateHolder : TWorkflowStateHolder);
end;
implementation
uses
System.IOUtils, System.RegularExpressions, System.Zip, System.Rtti, System.Math,
FIToolkit.Exceptions, FIToolkit.Utils, FIToolkit.Consts,
FIToolkit.Commons.Utils,
FIToolkit.Reports.Builder.Consts, FIToolkit.Reports.Builder.HTML,
FIToolkit.Logger.Default;
type
TWorkflowHelper = class (TLoggable)
private
class function CalcProjectSummary(StateHolder : TWorkflowStateHolder; const Project : TFileName) : TArray<TSummaryItem>;
class function CalcSummary(StateHolder : TWorkflowStateHolder; const ProjectFilter : String) : TArray<TSummaryItem>;
class function CalcTotalSummary(StateHolder : TWorkflowStateHolder) : TArray<TSummaryItem>;
class function ExtractSnippet(const FileName : TFileName; Line, Size : Integer) : String;
class function FormatProjectTitle(StateHolder : TWorkflowStateHolder; const Project : TFileName) : String;
class function FormatReportTitle(StateHolder : TWorkflowStateHolder) : String;
class function FormatSnippet(const Snippet : String; TargetLine, FirstLine, LastLine : Integer) : String;
class function MakeRecord(StateHolder : TWorkflowStateHolder; const Project : TFileName;
Msg : TFixInsightMessage) : TReportRecord;
end;
{ TWorkflowStateHolder }
constructor TWorkflowStateHolder.Create(ConfigData : TConfigData);
begin
inherited Create;
FDeduplicator := TFixInsightMessages.Create;
FMessages := TDictionary<TFileName, TArray<TFixInsightMessage>>.Create;
FReportFileName := TPath.Combine(ConfigData.OutputDirectory, ConfigData.OutputFileName);
FReportOutput := TFile.CreateText(FReportFileName);
FConfigData := ConfigData;
FFixInsightXMLParser := TFixInsightXMLParser.Create;
InitReportBuilder;
end;
destructor TWorkflowStateHolder.Destroy;
begin
FreeAndNil(FFixInsightXMLParser);
FreeAndNil(FProjectGroupParser);
FreeAndNil(FProjectParser);
FreeAndNil(FTaskManager);
FreeAndNil(FDeduplicator);
FreeAndNil(FMessages);
FreeAndNil(FReportOutput);
inherited Destroy;
end;
procedure TWorkflowStateHolder.InitReportBuilder;
var
Template : IHTMLReportTemplate;
Report : THTMLReportBuilder;
begin
if FConfigData.CustomTemplateFileName.IsEmpty then
Template := THTMLReportDefaultTemplate.Create
else
Template := THTMLReportCustomTemplate.Create(FConfigData.CustomTemplateFileName);
Report := THTMLReportBuilder.Create(FReportOutput.BaseStream);
Report.SetTemplate(Template);
FReportBuilder := Report;
end;
{ TExecutiveTransitionsProvider }
class procedure TExecutiveTransitionsProvider.PrepareWorkflow(const StateMachine : IStateMachine;
StateHolder : TWorkflowStateHolder);
begin //FI:C101
StateMachine
.AddTransition(asInitial, asProjectsExtracted, acExtractProjects,
procedure (const PreviousState, CurrentState : TApplicationState; const UsedCommand : TApplicationCommand)
begin
Log.EnterSection(RSExtractingProjects);
with StateHolder do
begin
FStartTime := Now;
FInputFileType := GetInputFileType(FConfigData.InputFileName);
Log.DebugVal(['StateHolder.FInputFileType = ', TValue.From<TInputFileType>(FInputFileType)]);
case FInputFileType of
iftDPR, iftDPK:
begin
FProjects := [FConfigData.InputFileName];
end;
iftDPROJ:
begin
FProjectParser := TProjectParser.Create(FConfigData.InputFileName);
FProjects := [FProjectParser.GetMainSourceFileName];
end;
iftGROUPPROJ:
begin
FProjectGroupParser := TProjectGroupParser.Create(FConfigData.InputFileName);
FProjects := FProjectGroupParser.GetIncludedProjectsFiles;
TArray.Sort<TFileName>(FProjects, TFileName.GetComparer);
end;
else
raise EUnknownInputFileType.Create;
end;
end;
Log.LeaveSection(RSProjectsExtracted);
end
)
.AddTransition(asProjectsExtracted, asProjectsExcluded, acExcludeProjects,
procedure (const PreviousState, CurrentState : TApplicationState; const UsedCommand : TApplicationCommand)
var
LProjects : TList<TFileName>;
sPattern, sProject : String;
begin
Log.EnterSection(RSExcludingProjects);
LProjects := TList<TFileName>.Create;
try
with StateHolder do
begin
LProjects.AddRange(FProjects);
for sPattern in FConfigData.ExcludeProjectPatterns do
for sProject in FProjects do
if TRegEx.IsMatch(sProject, sPattern, [roIgnoreCase]) then
begin
LProjects.Remove(sProject);
Log.InfoFmt(RSProjectExcluded, [sProject]);
end;
if LProjects.Count < Length(FProjects) then
FProjects := LProjects.ToArray;
end;
finally
LProjects.Free;
end;
Log.LeaveSection(RSProjectsExcluded);
end
)
.AddTransition(asProjectsExcluded, asFixInsightRan, acRunFixInsight,
procedure (const PreviousState, CurrentState : TApplicationState; const UsedCommand : TApplicationCommand)
begin
Log.EnterSection(RSRunningFixInsight);
with StateHolder do
begin
Log.DebugFmt('Length(FProjects) = %d', [Length(FProjects)]);
FTaskManager := TTaskManager.Create(FConfigData.FixInsightExe, FConfigData.FixInsightOptions,
FProjects, FConfigData.TempDirectory);
FReports := FTaskManager.RunAndGetOutput;
end;
Log.LeaveSection(RSFixInsightRan);
end
)
.AddTransition(asFixInsightRan, asReportsParsed, acParseReports,
procedure (const PreviousState, CurrentState : TApplicationState; const UsedCommand : TApplicationCommand)
var
R : TPair<TFileName, TFileName>;
i : Integer;
begin
Log.EnterSection(RSParsingReports);
Log.DebugVal(['FConfigData.Deduplicate = ', StateHolder.FConfigData.Deduplicate]);
with StateHolder do
for R in FReports do
if TFile.Exists(R.Value) then
begin
if not FConfigData.Deduplicate then
FFixInsightXMLParser.Parse(R.Value, False)
else
begin
FFixInsightXMLParser.Parse(R.Value, R.Key, False);
for i := FFixInsightXMLParser.Messages.Count - 1 downto 0 do
if FDeduplicator.Contains(FFixInsightXMLParser.Messages[i]) then
FFixInsightXMLParser.Messages.Delete(i);
FDeduplicator.AddRange(FFixInsightXMLParser.Messages.ToArray);
end;
FFixInsightXMLParser.Messages.Sort;
FMessages.Add(R.Key, FFixInsightXMLParser.Messages.ToArray);
end
else
begin
FMessages.Add(R.Key, nil);
Log.ErrorFmt(RSReportNotFound, [R.Key]);
end;
Log.LeaveSection(RSReportsParsed);
end
)
.AddTransition(asReportsParsed, asUnitsExcluded, acExcludeUnits,
procedure (const PreviousState, CurrentState : TApplicationState; const UsedCommand : TApplicationCommand)
var
LProjectMessages : TFixInsightMessages;
LExcludedUnits : TList<TFileName>;
sPattern : String;
F : TFileName;
Msg : TFixInsightMessage;
begin
Log.EnterSection(RSExcludingUnits);
LProjectMessages := TFixInsightMessages.Create;
LExcludedUnits := TList<TFileName>.Create;
try
with StateHolder do
for sPattern in FConfigData.ExcludeUnitPatterns do
for F in FProjects do
if Assigned(FMessages[F]) then
begin
LProjectMessages.Clear;
LProjectMessages.AddRange(FMessages[F]);
for Msg in FMessages[F] do
if TRegEx.IsMatch(Msg.FileName, sPattern, [roIgnoreCase]) then
begin
LProjectMessages.Remove(Msg);
if not LExcludedUnits.Contains(Msg.FileName) then
LExcludedUnits.Add(Msg.FileName);
end;
if LProjectMessages.Count < Length(FMessages[F]) then
FMessages[F] := LProjectMessages.ToArray;
end;
for F in LExcludedUnits do
Log.InfoFmt(RSUnitExcluded, [F]);
finally
LExcludedUnits.Free;
LProjectMessages.Free;
end;
Log.LeaveSection(RSUnitsExcluded);
end
)
.AddTransition(asUnitsExcluded, asReportBuilt, acBuildReport,
procedure (const PreviousState, CurrentState : TApplicationState; const UsedCommand : TApplicationCommand)
var
F : TFileName;
Msg : TFixInsightMessage;
begin
Log.EnterSection(RSBuildingReport);
with StateHolder do
begin
FReportBuilder.BeginReport;
FReportBuilder.AddHeader(TWorkflowHelper.FormatReportTitle(StateHolder), FStartTime);
FReportBuilder.AddTotalSummary(TWorkflowHelper.CalcTotalSummary(StateHolder));
for F in FProjects do
if Assigned(FMessages[F]) then
begin
FReportBuilder.BeginProjectSection(
TWorkflowHelper.FormatProjectTitle(StateHolder, F),
TWorkflowHelper.CalcProjectSummary(StateHolder, F)
);
for Msg in FMessages[F] do
FReportBuilder.AppendRecord(TWorkflowHelper.MakeRecord(StateHolder, F, Msg));
FReportBuilder.EndProjectSection;
end;
FReportBuilder.AddFooter(Now);
FReportBuilder.EndReport;
FReportOutput.Close;
end;
Log.LeaveSection(RSReportBuilt);
end
)
.AddTransition(asReportBuilt, asArchiveMade, acMakeArchive,
procedure (const PreviousState, CurrentState : TApplicationState; const UsedCommand : TApplicationCommand)
var
sArchiveFileName : TFileName;
ZF : TZipFile;
begin
Log.EnterSection(RSMakingArchive);
Log.DebugVal(['FConfigData.MakeArchive = ', StateHolder.FConfigData.MakeArchive]);
with StateHolder do
if FConfigData.MakeArchive then
begin
sArchiveFileName := FReportFileName + STR_ARCHIVE_FILE_EXT;
Log.DebugFmt('sArchiveFileName = "%s"', [sArchiveFileName]);
Log.DebugVal(['TFile.Exists(sArchiveFileName) = ', TFile.Exists(sArchiveFileName)]);
if TFile.Exists(sArchiveFileName) then
TFile.Delete(sArchiveFileName);
ZF := TZipFile.Create;
try
ZF.Open(sArchiveFileName, zmWrite);
ZF.Add(FReportFileName);
ZF.Close;
finally
ZF.Free;
end;
DeleteFile(FReportFileName);
end;
Log.LeaveSection(RSArchiveMade);
end
)
.AddTransition(asArchiveMade, asFinal, acTerminate,
procedure (const PreviousState, CurrentState : TApplicationState; const UsedCommand : TApplicationCommand)
var
R : TPair<TFileName, TFileName>;
begin
Log.EnterSection(RSTerminating);
with StateHolder do
begin
for R in FReports do
begin
Inc(FTotalMessages, Length(FMessages[R.Key]));
DeleteFile(R.Value);
end;
FTotalDuration := TTimeSpan.Subtract(Now, FStartTime);
end;
Log.LeaveSection(RSTerminated);
end
);
end;
{ TWorkflowHelper }
class function TWorkflowHelper.CalcProjectSummary(StateHolder : TWorkflowStateHolder;
const Project : TFileName) : TArray<TSummaryItem>;
begin
Result := CalcSummary(StateHolder, Project);
end;
class function TWorkflowHelper.CalcSummary(StateHolder : TWorkflowStateHolder;
const ProjectFilter : String) : TArray<TSummaryItem>;
var
arrSummary : array [TFixInsightMessageType] of TSummaryItem;
procedure CalcProjectMessages(Project : TFileName);
var
Msg : TFixInsightMessage;
begin
for Msg in StateHolder.FMessages[Project] do
Inc(arrSummary[Msg.MsgType].MessageCount);
end;
var
MT : TFixInsightMessageType;
F : TFileName;
begin
Result := nil;
for MT := Low(TFixInsightMessageType) to High(TFixInsightMessageType) do
with arrSummary[MT] do
begin
MessageCount := 0;
MessageTypeKeyword := ARR_MSGTYPE_TO_MSGKEYWORD_MAPPING[MT];
MessageTypeName := ARR_MSGTYPE_TO_MSGNAME_MAPPING[MT];
end;
if not ProjectFilter.IsEmpty then
CalcProjectMessages(ProjectFilter)
else
for F in StateHolder.FProjects do
CalcProjectMessages(F);
for MT := Low(arrSummary) to High(arrSummary) do
if arrSummary[MT].MessageCount > 0 then
Result := Result + [arrSummary[MT]];
end;
class function TWorkflowHelper.CalcTotalSummary(StateHolder : TWorkflowStateHolder) : TArray<TSummaryItem>;
begin
Result := CalcSummary(StateHolder, String.Empty);
end;
class function TWorkflowHelper.ExtractSnippet(const FileName : TFileName; Line, Size : Integer) : String;
var
iFirstLine, iLastLine : Integer;
begin
Log.EnterMethod(TWorkflowHelper, @TWorkflowHelper.ExtractSnippet, [FileName, Line, Size]);
iFirstLine := Line - Size div 2;
iLastLine := Line + Size div 2;
Result := FormatSnippet(ReadSmallTextFile(FileName, iFirstLine, iLastLine), Line, iFirstLine, iLastLine);
Log.LeaveMethod(TWorkflowHelper, @TWorkflowHelper.ExtractSnippet, Result.Length);
end;
class function TWorkflowHelper.FormatProjectTitle(StateHolder : TWorkflowStateHolder; const Project : TFileName) : String;
begin
Result := String(Project).Replace(
TPath.GetDirectoryName(StateHolder.FConfigData.InputFileName, True), String.Empty, [rfIgnoreCase]);
end;
class function TWorkflowHelper.FormatReportTitle(StateHolder : TWorkflowStateHolder) : String;
begin
Result := TPath.GetFileName(StateHolder.FConfigData.InputFileName);
end;
class function TWorkflowHelper.FormatSnippet(const Snippet : String; TargetLine, FirstLine, LastLine : Integer) : String;
const
INT_PREFIX_LENGTH = Length(STR_CSO_TARGET_LINE_NUMBER_PREFIX);
var
iLineNumMaxLen : Integer;
arrSnippetLines, arrResult : TArray<String>;
i, iLineNum : Integer;
sLineNum : String;
begin
iLineNumMaxLen := LastLine.ToString.Length + INT_PREFIX_LENGTH;
arrSnippetLines := Snippet.Split([sLineBreak], TStringSplitOptions.None);
{$IF CompilerVersion < 33.0} // RSP-11302
if Snippet.EndsWith(sLineBreak) then
arrSnippetLines := arrSnippetLines + [String.Empty];
{$ENDIF}
SetLength(arrResult, Length(arrSnippetLines));
iLineNum := Max(FirstLine, 1);
for i := 0 to High(arrSnippetLines) do
begin
sLineNum := iLineNum.ToString;
if iLineNum <> TargetLine then
sLineNum := sLineNum.PadLeft(iLineNumMaxLen)
else
sLineNum := STR_CSO_TARGET_LINE_NUMBER_PREFIX + sLineNum.PadLeft(iLineNumMaxLen - INT_PREFIX_LENGTH);
arrResult[i] := Format(FMT_CSO_LINE_NUMBER, [sLineNum]) + arrSnippetLines[i];
Inc(iLineNum);
end;
Result := String.Join(sLineBreak, arrResult);
end;
class function TWorkflowHelper.MakeRecord(StateHolder : TWorkflowStateHolder; const Project : TFileName;
Msg : TFixInsightMessage) : TReportRecord;
begin
Result.Column := Msg.Column;
Result.FileName := Msg.FileName;
Result.Line := Msg.Line;
Result.MessageText := Msg.Text;
Result.MessageTypeKeyword := ARR_MSGTYPE_TO_MSGKEYWORD_MAPPING[Msg.MsgType];
Result.MessageTypeName := ARR_MSGTYPE_TO_MSGNAME_MAPPING[Msg.MsgType];
with StateHolder do
if FConfigData.SnippetSize > 0 then
Result.Snippet := ExtractSnippet(
TPath.Combine(TPath.GetDirectoryName(Project), Msg.FileName), Msg.Line, FConfigData.SnippetSize);
end;
end.
|
unit Test_FIToolkit.Utils;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework,
FIToolkit.Utils;
type
TestFIToolkitUtils = class (TGenericTestCase)
published
procedure TestGetAppVersionInfo;
procedure TestGetCLIOptionProcessingOrder;
procedure TestIsCaseSensitiveCLIOption;
procedure TestTryCLIOptionToAppCommand;
end;
implementation
uses
System.SysUtils,
FIToolkit.Types, FIToolkit.Consts,
TestUtils;
{ TestFIToolkitUtils }
procedure TestFIToolkitUtils.TestGetAppVersionInfo;
var
ReturnValue : String;
begin
ReturnValue := GetAppVersionInfo;
CheckFalse(ReturnValue.IsEmpty, 'CheckFalse::IsEmpty');
CheckTrue(ReturnValue.Contains(STR_APP_TITLE), 'CheckTrue::Contains(%s)', [STR_APP_TITLE]);
end;
procedure TestFIToolkitUtils.TestGetCLIOptionProcessingOrder;
var
ReturnValue : Integer;
S : String;
begin
ReturnValue := GetCLIOptionProcessingOrder(String.Empty, False);
CheckEquals(-1, ReturnValue, '(ReturnValue = -1)::<empty>');
ReturnValue := GetCLIOptionProcessingOrder(' ', True);
CheckEquals(-1, ReturnValue, '(ReturnValue = -1)::<space>');
for S in ARR_CLIOPTION_PROCESSING_ORDER do
begin
ReturnValue := GetCLIOptionProcessingOrder(S, True);
CheckTrue(ReturnValue >= 0, 'CheckTrue::(%d >= 0)<case insensitive>', [ReturnValue]);
ReturnValue := GetCLIOptionProcessingOrder(S, False);
CheckTrue(ReturnValue >= 0, 'CheckTrue::(%d >= 0)<case sensitive>', [ReturnValue]);
end;
end;
procedure TestFIToolkitUtils.TestIsCaseSensitiveCLIOption;
var
ReturnValue : Boolean;
begin
ReturnValue := IsCaseSensitiveCLIOption(String.Empty);
CheckFalse(ReturnValue, 'CheckFalse::ReturnValue<empty>');
ReturnValue := IsCaseSensitiveCLIOption(' ');
CheckFalse(ReturnValue, 'CheckFalse::ReturnValue<space>');
end;
procedure TestFIToolkitUtils.TestTryCLIOptionToAppCommand;
var
Cmd, C : TApplicationCommand;
ReturnValue : Boolean;
begin
ReturnValue := TryCLIOptionToAppCommand(String.Empty, False, Cmd);
CheckFalse(ReturnValue, 'CheckFalse::ReturnValue<empty>');
ReturnValue := TryCLIOptionToAppCommand(' ', True, Cmd);
CheckFalse(ReturnValue, 'CheckFalse::ReturnValue<space>');
for C := Low(ARR_APPCOMMAND_TO_CLIOPTION_MAPPING) to High(ARR_APPCOMMAND_TO_CLIOPTION_MAPPING) do
if not ARR_APPCOMMAND_TO_CLIOPTION_MAPPING[C].IsEmpty then
begin
ReturnValue := TryCLIOptionToAppCommand(ARR_APPCOMMAND_TO_CLIOPTION_MAPPING[C], True, Cmd);
CheckTrue(ReturnValue, 'CheckTrue::ReturnValue<case insensitive>');
ReturnValue := TryCLIOptionToAppCommand(ARR_APPCOMMAND_TO_CLIOPTION_MAPPING[C], False, Cmd);
CheckTrue(ReturnValue, 'CheckTrue::ReturnValue<case sensitive>');
end;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestFIToolkitUtils.Suite);
end.
|
program helico;
uses crt, SDL2, SDL2_image;
const
sdlWw1 = 1280;
sdlWh1 = 960;
sdlWw2 = 500;
sdlWh2 = 500;
var
sdlWindow1 : PSDL_Window;
sdlWindow2 : PSDL_Window;
sdlRenderer : PSDL_Renderer;
sdlRenderer2 : PSDL_Renderer;
sdlSurface1 : PSDL_Surface;
sdlSurface2 : PSDL_Surface;
sdlSurfaceRect : PSDL_Surface;
sdlTexture1 : PSDL_Texture;
sdlTexture2 : PSDL_Texture;
sdlTextureRect : PSDL_Texture;
sdlHelicArea : TSDL_Rect;
sdlRiderArea : TSDL_Rect;
sdlRect : TSDL_Rect;
sdlView : TSDL_Rect;
sdlView2 : TSDL_Rect;
sdlEvent : PSDL_Event;
programState : boolean;
sdlKeyboardStateEvent: PUInt8;
i : INTEGER;
procedure sColor(color : STRING); //Procedure personnalisee pour le changement de couleur texte console
begin
case color of
'blue': TextColor(blue);
'red': TextColor(red);
'white': TextColor(white);
'yellow': TextColor(yellow);
'black': TextColor(black);
'green': TextColor(green);
'magenta': TextColor(magenta);
'cyan': TextColor(cyan);
end;
end;
procedure rColor(); //Procedure personnalisee pour la reinitialisation de couleur texte console (blanc)
begin
TextColor(white);
end;
procedure introduction(); //procedure introduction difference sdl sdl2
begin
sColor('red');//Rouge
writeln('SDL2 Introduction');
writeln('/*/*/*/ Simple DirectMedia Layer /*/*/*/ ');
rColor();//Reset -> Blanc.
writeln('-----------------------------------------------');
Delay(500);
sColor('green');//Vert
writeln('Diff'#233'rence entre SDL et SDL2'); rColor();
Delay(500);
sColor('cyan');//Bleu cyan
writeln('1. Performance : SDL2 > SDL');
Delay(250);
writeln('2. >SDL< 1998-2001 Developpement par Sam Lantinga. Entreprise "Loki Games".');
Delay(250);
writeln('3. >SDL2< 2013: D'#233'veloppement de la SDL2.');
Delay(250);
writeln('4. >SDL2< Inclus: Nouvelles fonctionalit'#233'es, permettant le d'#233'veloppement plus performant/large.');
Delay(250);
writeln('5. >SDL2< Biblioth'#232'ques traduites en Pascal. Ce qui fait de se language un puissant outil pour les D'#233'veloppeurs Pascal.');
rColor();
end;
procedure sdlErrorInit();
begin
sColor('red');
writeln('--------------------------');
writeln('D'#233'sol'#233', une erreur est survenue.');
writeln('--------------------------');
rColor();
Delay(2000);
end;
BEGIN
clrscr;
introduction(); //Messages d'introduction, differences SDL/SDL2
readln();//readln qui s'affiche dans la console par clique droit (???)
if SDL_Init(SDL_INIT_VIDEO) < 0 then HALT(1);
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION,'Ouverture','WELCOME',nil);
sdlWindow1 := SDL_CreateWindow('SDL',50,50,sdlWw1,sdlWh1,SDL_WINDOW_SHOWN);
sdlRenderer := SDL_CreateRenderer(sdlWindow1,-1,SDL_RENDERER_SOFTWARE);
sdlWindow2 := SDL_CreateWindow('BitmapSDL',50,50,sdlWw2,sdlWh2,SDL_WINDOW_SHOWN);
sdlRenderer2 := SDL_CreateRenderer(sdlWindow2,-1,SDL_RENDERER_SOFTWARE);
sdlRect.x := 12;
sdlRect.y := 25;
sdlRect.w := 178;
sdlRect.h := 116;
new(sdlEvent);
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY,'nearest');
sdlHelicArea.x := 25;
sdlHelicArea.y := 50;
sdlHelicArea.w := 250;
sdlHelicArea.h := 100;
sdlRiderArea.x := 0;
sdlRiderArea.y := 0;
sdlHelicArea.w := 123;
sdlHelicArea.h := 87;
sdlSurface1 := IMG_Load('helicopter.png');
if sdlSurface1 = nil then;
sdlSurface2 := SDL_LoadBMP('rider.bmp');
if sdlSurface1 = nil then Halt;
sdlSurfaceRect := SDL_LoadBMP('fpsdl.bmp');
if sdlSurfaceRect = nil then HALT;
sdlTexture1 := SDL_CreateTextureFromSurface(sdlRenderer,sdlSurface1);
if sdlTexture1 = nil then Halt;
sdlTexture2 := SDL_CreateTextureFromSurface(sdlRenderer2, sdlSurface2);
if sdlTexture2 = nil then Halt;
sdlTextureRect := SDL_CreateTextureFromSurface(sdlRenderer,sdlSurfaceRect);
if sdlTextureRect = nil then Halt;
sdlView.x := 0;
sdlView.y := 0;
sdlView.w := 128;
sdlView.h := 55;
sdlView2.x := 0;
sdlView2.y := 0;
sdlView2.w := 123;
sdlView2.h := 87;
SDL_RenderPresent(sdlRenderer);
SDL_RenderPresent(sdlRenderer2);
//SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION,'D‚marrage du programme.','SDL HELICO - PROJET LUDUS ACADEMIE.',nil);
writeln;
while programState = false do
begin
SDL_PumpEvents;
sdlKeyboardStateEvent := SDL_GetKeyboardState(nil);
if sdlKeyboardStateEvent[SDL_SCANCODE_ESCAPE] = 1 then
programState := true;
if sdlKeyboardStateEvent[SDL_SCANCODE_W] = 1 then
sdlHelicArea.y :=sdlHelicArea.y-10;
if sdlKeyboardStateEvent[SDL_SCANCODE_A] = 1 then
sdlHelicArea.x := sdlHelicArea.x -10;
if sdlKeyboardStateEvent[SDL_SCANCODE_S] = 1 then
sdlHelicArea.y := sdlHelicArea.y + 10;
if sdlKeyboardStateEvent[SDL_SCANCODE_D] = 1 then
sdlHelicArea.x := sdlHelicArea.x + 10;
if sdlKeyboardStateEvent[SDL_SCANCODE_F] = 1 then
begin
writeln('Coordonn‚e X de l''helico : ', sdlHelicArea.x);
writeln('Coordonn‚e Y de l''helico : ', sdlHelicArea.y);
end;
if sdlHelicArea.x > (sdlWw1 - sdlHelicArea.w) then
sdlHelicArea.x := (sdlWw1 - sdlHelicArea.w);
if sdlHelicArea.x < 0 then
sdlHelicArea.x := 0;
if sdlHelicArea.y > (sdlWh1 - sdlHelicArea.h) then
sdlHelicArea.y := (sdlWh1 - sdlHelicArea.h);
if sdlHelicArea.y < 0 then
sdlHelicArea.y := 0;
sdlView.x := sdlView.x + 128;
if sdlView.x > 512 then
begin
sdlView.x := 0;
end;
SDL_RenderCopy(sdlRenderer,sdlTextureRect,@sdlRect,@sdlRect);
SDL_RenderCopy(sdlRenderer,sdlTexture1,@sdlView, @sdlHelicArea);
SDL_RenderCopy(sdlRenderer2,sdlTexture2,nil,nil);
SDL_RenderPresent(sdlRenderer);
SDL_RenderPresent(sdlRenderer2);
SDL_Delay(20);
SDL_RenderClear(sdlRenderer);
SDL_RenderClear(sdlRenderer2);
end;
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION,'Quitter','Fin du programme.',nil);
dispose(sdlEvent);
SDL_DestroyTexture(sdlTexture1);
SDL_DestroyTexture(sdlTexture2);
SDL_DestroyTexture(sdlTextureRect);
SDL_FreeSurface(sdlSurface1);
SDL_FreeSurface(sdlSurface2);
SDL_FreeSurface(sdlSurfaceRect);
SDL_DestroyRenderer(sdlRenderer);
SDL_DestroyRenderer(sdlRenderer2);
SDL_DestroyWindow(sdlWindow1);
SDL_DestroyWindow(sdlWindow2);
SDL_Quit;
END.
|
unit TAudioFileOutDemo;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Buttons, ExtCtrls, FileCtrl, StdCtrls, UAFDefs, AudioIO,
ComCtrls;
type
TForm1 = class(TForm)
Panel1: TPanel;
PlaySpeedButton: TSpeedButton;
AudioOut1: TAudioOut;
DriveComboBox1: TDriveComboBox;
DirectoryListBox1: TDirectoryListBox;
FileListBox1: TFileListBox;
FilterComboBox1: TFilterComboBox;
Edit1: TEdit;
Label1: TLabel;
TypeLabel: TLabel;
FormatLabel: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
PropertyLabel: TLabel;
Bevel2: TBevel;
Label5: TLabel;
SizeLabel: TLabel;
TimeLabel: TLabel;
ProgressBar1: TProgressBar;
Timer1: TTimer;
procedure PlaySpeedButtonClick(Sender: TObject);
function AudioOut1FillBuffer(B: PChar; Var N: Integer): Boolean;
procedure FileListBox1Click(Sender: TObject);
procedure AudioOut1Stop(Sender: TObject);
Procedure UpdateAudioInfo(FileName : String);
procedure AudioOut1Start(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
{ Private declarations }
WasStereo : Boolean;
ReadSize : Integer;
UAF : UAF_File;
Buffer : ^Integer;
lPos : Integer;
public
{ Public declarations }
Function SetupStart(FileName : String) :Boolean;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.PlaySpeedButtonClick(Sender: TObject);
begin
If (PlaySpeedButton.Down) Then
Begin
If (Not SetupStart(Edit1.Text)) Then
Begin
ShowMessage('Failed to setup start, because:' + ^m + AudioOut1.ErrorMessage);
Exit;
End;
If (Not AudioOut1.Start(AudioOut1)) Then
ShowMessage('Failed to start audio, because:' + ^m + AudioOut1.ErrorMessage);
End
Else
Begin
AudioOut1.StopAtOnce;
End;
PlaySpeedButton.Down := AudioOut1.Active;
end;
function TForm1.AudioOut1FillBuffer(B: PChar; Var N: Integer): Boolean;
Var
SP, DP, SPL, SPR, DPR, DPL : ^SmallInt;
vl, vr : Smallint;
br, i : Integer;
x : Real;
begin
{ This will happen on an error }
If (N <= 0) or (Not Active) Then
Begin
Result := FALSE;
Exit;
End;
{ Read in a buffer }
FillMemory(Buffer,ReadSize, 0);
br := UAF_Read(UAF, Buffer, ReadSize div UAF.FrameSize, lPos);
If (Br = 0) Then
Begin
Result := FALSE;
Exit;
End;
lPos := lPos + br;
{ The input for UAF files is ALWAYS PCM, Signed Small Integer }
{ If the file was mono, fade left to right }
If (Not WasStereo) Then
Begin
SP := Pointer(Buffer);
DP := Pointer(B);
{ NOTE! we change the size of N, BE careful, only do so if you really
want a less number of points to be played }
N := br*2*UAF.FrameSize;
For i := 0 to (N div (2*UAF.FrameSize))-1 Do
Begin
{ Now compute the fade rate from one channel to another. Not interesting }
x := ((AudioOut1.FilledBuffers*ReadSize div UAF.FrameSize) + i) / UAF.Frames;
DP^ := Round((1-x)*SP^);
Inc(DP);
DP^ := Round(x*SP^);
Inc(DP);
Inc(SP);
End;
End
Else
{ File is stereo, just mix left into right and visa versa }
Begin
SPL := Pointer(Buffer);
SPR := SPL;
Inc(SPR);
DPL := Pointer(B);
DPR := DPL;
Inc(DPR);
{ NOTE! we change the size of N, BE careful, only do so if you really
want a less number of points to be played }
N := br*UAF.FrameSize;
For i := 0 to (N div 4) - 1 Do
Begin
{ Now compute the fade rate from one channel to another. Not interesting }
x := ((AudioOut1.FilledBuffers*ReadSize div UAF.FrameSize) + i) / UAF.Frames;
vl := SPL^;
vr := SPR^;
DPL^ := Round((1-x)*vr + x*vl);
DPR^ := Round(x*vr + (1-x)*vl);
Inc(SPR,2); Inc(SPL,2);
Inc(DPR,2); Inc(DPL,2);
End;
End;
Result := TRUE;
end;
procedure TForm1.FileListBox1Click(Sender: TObject);
begin
PlaySpeedButton.Enabled := TRUE;
UpdateAudioInfo(FileListBox1.Items[FileListBox1.ItemIndex]);
end;
procedure TForm1.AudioOut1Stop(Sender: TObject);
begin
PlaySpeedButton.Down := FALSE;
// Timer1.Enabled := FALSE;
If (Buffer <> Nil) Then FreeMem(Buffer, ReadSize);
Buffer := Nil;
UAF_Close(UAF);
end;
Function TForm1.SetupStart(FileName : String) :Boolean;
begin
If (Not UAF_Open(UAF, FileName, 'r', UAF_TYPE_UNKNOWN)) Then
Begin
AudioOut1.ErrorMessage := UAF_ErrorMessage;
Result := FALSE;
Exit;
End;
{ Setup all the sampling parameters }
lPos := 0;
AudioOut1.FrameRate := Round(UAF.FrameRate);
AudioOut1.Stereo := (UAF.Channels <> 1);
AudioOut1.Quantization := 16;
WasStereo := AudioOut1.Stereo;
If (WasStereo) Then
ReadSize := AudioOut1.BufferSize
Else
ReadSize := AudioOut1.BufferSize Div 2;
GetMem(Buffer, ReadSize);
If (Buffer = Nil) Then
Begin
AudioOut1.ErrorMessage := 'Could Not alloc buffer';
Result := FALSE;
Exit;
End;
AudioOut1.Stereo := TRUE;
Result := TRUE;
end;
{--------UpdateAudioInfo------------------John Mertus---May 97---}
Procedure TForm1.UpdateAudioInfo(FileName : String);
{ This procedure does all the hard work of opening the file and }
{ fillings in the information about the file into the form }
{ }
{****************************************************************}
{ UAF variables }
Var
UAFIn : UAF_File;
Fin : File of Byte;
S : String;
xFS : LongInt;
Begin
{ Find the file size }
AssignFile(fin,FileName);
Reset(fin);
xFS := FileSize(fin);
CloseFile(fin);
{ Open the file }
If (Not UAF_Open(UAFIn, FileName, 'r', UAF_TYPE_UNKNOWN)) Then
Begin
TypeLabel.Caption := UAF_ErrorMessage;
FormatLabel.Caption := '';
PropertyLabel.Caption := '';
Exit;
End;
TypeLabel.Caption := String(UAF_Identity(UAFIn));
{ Finish up with the rate and bits }
FormatLabel.Caption := UAF_Description(UAFIn);
S := Format('%0.0n Hz, %d Bit ',[UAFIn.FrameRate, UAFIn.Quantization]);
If (UAFIn.Channels = 1) Then
S := S + 'Mono'
Else if (UAFIn.Channels = 2) Then
S := S + 'Stereo'
Else
S := S + Format('%d Channels',[UAFIn.Channels]);
PropertyLabel.Caption := S;
SizeLabel.Caption := Format('%0.3n Seconds (%0.0n Bytes) ',
[UAFIn.Frames/UAFIn.FrameRate, xFS*1.0]);
UAF_Close(UAFIn);
End;
procedure TForm1.AudioOut1Start(Sender: TObject);
begin
Timer1.Enabled := TRUE;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
Var
x : Real;
begin
x := AudioOut1.ElapsedTime;
TimeLabel.Caption := Format('%0.3n Seconds', [x]);
ProgressBar1.Position := Round(100*x*UAF.FrameRate/UAF.Frames);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Datasnap.DSHTTPCommon;
interface
uses
System.Classes,
Data.DBXCommon,
Data.DbxDatasnap,
Data.DBXJSON,
Data.DBXJSONReflect,
Data.DBXPlatform,
Data.DBXTransport,
Datasnap.DSAuth,
Datasnap.DSCommonServer,
Datasnap.DSServer,
Datasnap.DSService,
Datasnap.DSTransport,
System.Generics.Collections,
System.SysUtils;
type
/// <summary> HTTP command types processed by DataSnap
/// </summary>
TDSHTTPCommandType = (hcUnknown, hcGET, hcPOST, hcDELETE, hcPUT, hcOther);
/// <summary>Abstract DataSnap HTTP Context
/// </summary>
TDSHTTPContext = class
public
function Connected: Boolean; virtual; abstract;
end;
/// <summary>Abstract DataSnap HTTP Request
/// </summary>
TDSHTTPRequest = class
protected
function GetCommand: string; virtual; abstract;
function GetCommandType: TDSHTTPCommandType; virtual; abstract;
function GetDocument: string; virtual; abstract;
function GetParams: TStrings; virtual; abstract;
function GetPostStream: TStream; virtual; abstract;
function GetAuthUserName: string; virtual; abstract;
function GetAuthPassword: string; virtual; abstract;
function GetURI: string; virtual; abstract;
function GetPragma: string; virtual; abstract;
function GetAccept: string; virtual; abstract;
function GetRemoteIP: string; virtual; abstract;
function GetUserAgent: string; virtual; abstract;
function GetProtocolVersion: string; virtual; abstract;
public
property CommandType: TDSHTTPCommandType read GetCommandType;
property Document: string read GetDocument; // writable for isapi compatibility. Use with care
property Params: TStrings read GetParams;
property PostStream: TStream read GetPostStream;
property AuthUserName: string read GetAuthUserName;
property AuthPassword: string read GetAuthPassword;
property Command: string read GetCommand;
property URI: string read GetURI;
property Pragma: string read GetPragma;
property Accept: string read GetAccept;
property RemoteIP: string read GetRemoteIP;
property UserAgent: string read GetUserAgent;
property ProtocolVersion: string read GetProtocolVersion;
end;
/// <summary>Abstract DataSnap HTTP Response
/// </summary>
TDSHTTPResponse = class
protected
function GetContentStream: TStream; virtual; abstract;
function GetResponseNo: Integer; virtual; abstract;
function GetResponseText: String; virtual; abstract;
procedure SetContentStream(const Value: TStream); virtual; abstract;
procedure SetResponseNo(const Value: Integer); virtual; abstract;
procedure SetResponseText(const Value: String); virtual; abstract;
function GetContentText: string; virtual; abstract;
procedure SetContentText(const Value: string); virtual; abstract;
function GetContentLength: Int64; virtual; abstract;
procedure SetContentLength(const Value: Int64); virtual; abstract;
function GetCloseConnection: Boolean; virtual; abstract;
procedure SetCloseConnection(const Value: Boolean); virtual; abstract;
function GetPragma: string; virtual; abstract;
procedure SetPragma(const Value: string); virtual; abstract;
function GetContentType: string; virtual; abstract;
procedure SetContentType(const Value: string); virtual; abstract;
function GetFreeContentStream: Boolean; virtual; abstract;
procedure SetFreeContentStream(const Value: Boolean); virtual; abstract;
public
procedure SetHeaderAuthentication(const Value: String; const Realm: String); virtual; abstract;
property FreeContentStream: Boolean read GetFreeContentStream write SetFreeContentStream;
property ResponseNo: Integer read GetResponseNo write SetResponseNo;
property ResponseText: String read GetResponseText write SetResponseText;
property ContentType: String read GetContentType write SetContentType;
property ContentStream: TStream read GetContentStream write SetContentStream;
property ContentText: string read GetContentText write SetContentText;
property ContentLength: Int64 read GetContentLength write SetContentLength;
property CloseConnection: Boolean read GetCloseConnection write SetCloseConnection;
property Pragma: string read GetPragma write SetPragma;
end;
/// <summary> User event for logging http requests
/// </summary>
TDSHTTPServiceTraceEvent = procedure(Sender: TObject; AContext: TDSHTTPContext;
ARequest: TDSHTTPRequest;
AResponse: TDSHTTPResponse) of object;
/// <summary> User event for capturing and optionally modifying REST results before they are returned.
/// </summary>
/// <remarks>The JSON value passed in is not wrapped in a 'result' object. If Handled is set to false,
/// then the caller will wrap the value of ResultVal like this: {'result':ResultVal}.
/// Note also that the value passed in may (and probably will) be a JSON Array, containing
/// one or more return values, depending on the method having been invoked.
/// If you change the value held by ResultVal, the new value will be returned.
/// </remarks>
/// <param name="Sender">The instance invoking the event.</param>
/// <param name="ResultVal">The JSON value being returned</param>
/// <param name="Command">The command being executed</param>
/// <param name="Handled">Set to true if the event handled the formatting of the result.</param>
TDSRESTResultEvent = procedure(Sender: TObject; var ResultVal: TJSONValue;
const Command: TDBXCommand;
var Handled: Boolean) of object;
/// <summary> Serves a response to a datasnap/cache request, for supported request types: GET and DELETE
/// </summary>
TDSHTTPCacheContextService = class(TDSRequestFilterManager)
private
FSession: TDSSession;
FLocalConnection: Boolean;
/// <summary> Parses the request for the desired Cache item ID, command index and parameter index.
/// Any of these can be -1 instead of an actual value, as long as the ones after it are also -1.
/// </summary>
function ParseRequst(Request: String; out CacheId, CommandIndex, ParameterIndex: Integer): Boolean;
procedure InvalidRequest(Response: TDSHTTPResponse; Request: String);
/// <summary> Returns the Cache Item IDs as held by the cache </summary>
procedure GetCacheContents(out Value: TJSONValue);
/// <summary> Returns the number of commands held by the item. (Usually 1)
/// </summary>
procedure GetCacheItemContents(const CacheId: Integer; out Value: TJSONValue);
/// <summary> Returns the number of parameters held by the command
/// </summary>
procedure GetCommandContents(const CacheId: Integer; const CommandIndex: Integer; out Value: TJSONValue);
/// <summary> Returns the parameter value as either JSON or TStream, depending on the request
/// </summary>
procedure GetParameterValue(const RequestInfo: TDSHTTPRequest; const CacheId: Integer;
const CommandIndex: Integer; const ParameterIndex: Integer;
out Response: TJSONValue; out ResponseStream: TStream; out IsError: Boolean);
/// <summary> Returns the parameter index for the given command. </summary>
function GetOriginalParamIndex(const Command: TDBXCommand; const Parameter: TDBXParameter): Integer;
/// <summary> Returns true if Streams should be returned as JSON, false to return them as content stream
/// </summary>
function StreamsAsJSON(const RequestInfo: TDSHTTPRequest): Boolean;
function ByteContent(JsonValue: TJSONValue): TBytes;
public
constructor Create(Session: TDSSession; LocalConnection: Boolean); reintroduce; Virtual;
/// <summary> Uses the given Request string to deterine which part of the cache the client is interested in,
/// and populates the result accordingly.
/// </summary>
procedure ProcessGETRequest(const RequestInfo: TDSHTTPRequest; Response: TDSHTTPResponse; Request: String);
/// <summary> Uses the given Request string to deterine which part of the cache the client wants to delete,
/// and populates the result accordingly after performing the deletion.
/// </summary>
procedure ProcessDELETERequest(const RequestInfo: TDSHTTPRequest; Response: TDSHTTPResponse; Request: String);
end;
/// <summary> Wrapper for an execution response which can manage a Command populated with results,
/// or an error message, but not both.
/// </summary>
TDSExecutionResponse = class
protected
FCommand: TDBXCommand;
FDBXConnection: TDBXConnection;
FErrorMessage: String;
FLocalConnection: Boolean;
public
constructor Create(Command: TDBXCommand; DBXConnection: TDBXConnection; LocalConnection: Boolean); Overload; Virtual;
constructor Create(ErrorMessage: String); Overload; Virtual;
destructor Destroy(); Override;
property Command: TDBXCommand read FCommand;
property ErrorMessage: String read FErrorMessage;
end;
/// <summary> Abstract class for common functionality of Response Handlers,
/// which uses the result of a TDBXCommand to populate a TDSHTTPResponse object appropriately.
/// </summary>
TDSServiceResponseHandler = class abstract(TRequestCommandHandler)
protected
FCommandType: TDSHTTPCommandType;
FCommandList: TList<TDSExecutionResponse>;
FLocalConnection: Boolean;
FForceResultArray: Boolean;
function ByteContent(JsonValue: TJSONValue): TBytes; Virtual;
/// <summary> Returns the number of output parameters/errors combined in all of the managed commands.
/// </summary>
function GetResultCount: Integer; Virtual;
/// <summary> Populates errors into the response, if any. Returning true if errors were populated.
/// </summary>
function GetOKStatus: Integer; Virtual;
public
constructor Create(CommandType: TDSHTTPCommandType; LocalConnection: Boolean); Overload; Virtual;
destructor Destroy; override;
/// <summary> Adds an error message to the handler.
/// </summary>
procedure AddCommandError(ErrorMessage: String); Override;
/// <summary> Adds a TDBXCommand for this handler to use when populating the response.
/// </summary>
/// <remarks> Multiple commands will exist if a batch execution was done instead fo a single invocation.
/// This assumes ownership of the commands.
/// </remarks>
procedure AddCommand(Command: TDBXCommand; DBXConnection: TDBXConnection); Override;
/// <summary> Clears the stored commands/errors
/// </summary>
procedure ClearCommands(); Override;
/// <summary> Populates either Response or ResponseStream
/// </summary>
procedure GetResponse(out Response: TJSONValue; out ResponseStream: TStream; out ContainsErrors: boolean); Virtual; Abstract;
/// <summary> Populate the given response using the previously specified command and any
/// appropriate invocation metadata passed in.
/// </summary>
procedure PopulateResponse(AResponseInfo: TDSHTTPResponse;
InvokeMetadata: TDSInvocationMetadata); Virtual; Abstract;
/// <summary> Handles the closing, or transitioning of the response handler.
/// </summary>
/// <remarks> Calling this releases the holder of responsibility to manage the memory of this instance
/// any further. However, there is no guarantee that the instance will be destroyed when this is called.
/// </remarks>
procedure Close(); Virtual; Abstract;
/// <summary> True to pass the result object back in an array even if there was only one command executed,
/// false to only pass back the result objects in an array if there was more than one command executed.
/// Defaults to false.
/// </summary>
property ForceResultArray: Boolean read FForceResultArray write FForceResultArray;
end;
/// <summary> Information mapping to a specific Tunnel, which is to be associated with a session.
/// </summary>
TDSSessionTunnelInfo = record
/// <summary> The Channel Name associated with the tunnel. </summary>
ChannelName: String;
/// <summary> The ID of the tunnel, as specified by the client. </summary>
ClientChannelId: String;
/// <summary> Security token associated with the tunnel, for authorised modification. </summary>
SecurityToken: String;
/// <summary> The User associated with the tunnel. </summary>
AuthUser: String;
/// <summary> The password of the user associated with the tunnel. </summary>
AuthPassword: String;
end;
/// <summary> Datasnap specific HTTP server. Provides DS specific
/// implementations for different command types
/// </summary>
TDSHTTPServer = class
strict private
/// <summary> Name of a DSServer in the current process </summary>
FDSServerName: string;
/// <summary> DS host name. Only used if DSServerName is not specified </summary>
FDSHostname: String;
/// <summary> DS host port number. Only used if DSServerName is not specified </summary>
FDSPort: Integer;
/// <summary> Filter reference </summary>
FFilters: TTransportFilterCollection;
/// <summary>true if the user credentials are passed through remote DS instance</summary>
FCredentialsPassThrough: boolean;
/// <summary>DS user credentials, they work in tandem with the pass through</summary>
FDSAuthUser: String;
FDSAuthPassword: String;
/// <summary> Time in miliseconds a session will remain valid. </summary>
/// <remarks> After this time passes, the session is marked as expired and eventually removed.
/// If 0 is specified, the session never expires.
/// </remarks>
FSessionTimeout: Integer;
FSessionEvent: TDSSessionEvent;
FProtocolHandlerFactory: TDSJSONProtocolHandlerFactory;
FDSHTTPAuthenticationManager: TDSCustomAuthenticationManager;
FIPImplementationID: string;
private
FRESTContext: String;
FDSContext: String;
FCacheContext: String;
FTunnelService: TDSTunnelService;
FTrace: TDSHTTPServiceTraceEvent;
FResultEvent: TDSRESTResultEvent;
function GetRestContext: String;
function GetDsContext: String;
function GetCacheContext: String;
procedure SetRestContext(const ctx: String);
procedure SetDsContext(const ctx: String);
procedure SetCacheContext(const ctx: String);
/// <summary> Tries to consume the prefix out of the context. Returns what
/// is left of it, nil if the prefix is not found.
/// <param name="prefix">prefix string, not null or empty</param>
/// <param name="context">current context, never null or empty</param>
/// <param name="unused">unused part of the context</param>
/// <return>true if the context has the prefix</return>
/// </summary>
function Consume(const Prefix: String; const Context: String; out Unused: String): boolean;
function ByteContent(DataStream: TStream): TBytes; overload;
function ByteContent(JsonValue: TJSONValue): TBytes; overload;
property RESTContext: String read GetRestContext write SetRESTContext;
property DSContext: String read GetDSContext write SetDSContext;
property CacheContext: String read GetCacheContext write SetCacheContext;
procedure SetDSHostname(AHostname: String);
procedure SetDSPort(APort: Integer);
procedure SetDSServerName(AName: String);
procedure SetFilters(AFilterCollection: TTransportFilterCollection);
procedure SetAuthenticationManager(AuthenticationManager: TDSCustomAuthenticationManager);
function GetTunnelService: TDSTunnelService;
procedure CloseAllTunnelSessions;
/// <summary> Checks the request for a Session ID and returns it if one is found. </summary>
/// <remarks> Checks the Pragama header and optionally the query parameter of the url.
/// If checking both places, the URL parameter takes priority if both locations have values specified.
/// </remarks>
/// <returns> The found session ID or empty string if none found. </returns>
function GetRequestSessionId(const ARequestInfo: TDSHTTPRequest; const CheckURLParams: boolean = True): String;
/// <summary> Loads the session with the given session ID and sets it into the thread. </summary>
/// <remarks> Pass in an empty string to create a new session </remarks>
/// <returns> True if successful, false if passed an expired or invalid session ID </returns>
function LoadSession(const SessionId: String; const UserName: String; out IsNewSession: boolean): boolean;
function IsClosingSession(Request: String): boolean;
function IsOpeningClientChannel(Request: String): boolean;
function IsClosingClientChannel(Request: String): boolean;
function GetClientChannelInfo(Request: String; out ChannelName, ClientChannelId, SecurityToken: String): boolean;
procedure UpdateSessionTunnelHook(Request: String; Session: TDSSession; RequestInfo: TDSHTTPRequest);
procedure CloseSessionTunnels(Session: TDSSession);
procedure CloseRESTSession(Session: TDSSession; ResponseInfo: TDSHTTPResponse);
function CreateRESTService(const AuthUserName, AuthPassword: String): TDSRESTService;
strict protected
procedure DoDSRESTCommand(ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse; Request: String);
procedure DoDSCacheCommand(ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse; Request: String;
LocalConnection: Boolean);
procedure DoJSONCommand(ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse; Request: String);
procedure DoTunnelCommand(AContext: TDSHTTPContext; ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse);
procedure DoCommand(AContext: TDSHTTPContext; ARequestInfo: TDSHTTPRequest;
AResponseInfo: TDSHTTPResponse);
procedure DoCommandOtherContext(AContext: TDSHTTPContext; ARequestInfo: TDSHTTPRequest;
AResponseInfo: TDSHTTPResponse; const ARequest: string); virtual;
protected
function Decode(Data: string): string; virtual; abstract;
public
constructor Create; overload;
constructor Create(const AIPImplementationID: string); overload;
destructor Destroy; override;
procedure CreateProtocolHandlerFactory(ATransport: TDSServerTransport);
procedure ClearProtocolHandlerFactory;
property TunnelService: TDSTunnelService read GetTunnelService;
property DSHostname: String read FDSHostname write SetDSHostname;
property DSPort: Integer read FDSPort write SetDSPort;
property DSServerName: String read FDSServerName write SetDSServerName;
property Filters: TTransportFilterCollection read FFilters write SetFilters;
property DSAuthenticationManager: TDSCustomAuthenticationManager read FDSHTTPAuthenticationManager
write SetAuthenticationManager;
property CredentialsPassThrough: boolean read FCredentialsPassThrough write FCredentialsPassThrough;
property SessionTimeout: Integer read FSessionTimeout write FSessiontimeout;
property DSAuthUser: String read FDSAuthUSer write FDSAuthUser;
property DSAuthPassword: String read FDSAuthPassword write FDSAuthPassword;
property IPImplementationID: string read FIPImplementationID;
/// <summary>Event to call when a REST call is having its result built, to be returned.</summary>
property ResultEvent: TDSRESTResultEvent read FResultEvent write FResultEvent;
end;
/// <summary> Datasnap Server HTTP service provider class.
/// Provides lightweight http services for Datasnap technology. Implements
/// internet protocols such as REST.
/// </summary>
TDSHTTPServerTransport = class(TDSServerTransport)
strict protected
FHttpServer: TDSHTTPServer;
strict private
{ Private declarations }
FCredentialsPassthrough: Boolean;
FSessionTimeout: Integer;
FDSAuthPassword: string;
FDSAuthUser: string;
FDSContext: string;
FDSCacheContext: string;
FDSRestContext: string;
FDSPort: Integer;
FDSHostName: string;
FAuthenticationManager: TDSCustomAuthenticationManager;
FTrace: TDSHTTPServiceTraceEvent;
FResultEvent: TDSRESTResultEvent;
private
function GetHttpServer: TDSHTTPServer;
procedure UpdateDSServerName;
protected
procedure Loaded; override;
procedure RequiresServer;
function CreateHttpServer: TDSHTTPServer; virtual; abstract;
procedure InitializeHttpServer; virtual;
{ Protected declarations }
procedure SetRESTContext(const Ctx: String );
procedure SetDSContext(const Ctx: String);
procedure SetCacheContext(const Ctx: String);
procedure SetTraceEvent(Event: TDSHTTPServiceTraceEvent );
procedure SetDSHostname(Host: String );
procedure SetDSPort(Port: Integer);
procedure SetServer(const AServer: TDSCustomServer); override;
procedure SetAuthenticationManager(const AuthenticationManager: TDSCustomAuthenticationManager);
procedure SetResultEvent(const RestEvent: TDSRESTResultEvent);
function GetRESTContext: String;
function GetDSContext: String;
function GetCacheContext: String;
function GetTraceEvent: TDSHTTPServiceTraceEvent;
function GetDSHostname: String;
function GetDSPort: Integer;
function GetAuthenticationManager: TDSCustomAuthenticationManager;
function GetResultEvent: TDSRESTResultEvent;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure SetFilters(const Value: TTransportFilterCollection); override;
procedure ServerCloseAllTunnelSessions;
procedure SetCredentialsPassThrough(const AFlag: boolean); virtual;
procedure SetDSAuthUser(const UserName: String); virtual;
procedure SetDSAuthPassword(const UserPassword: String); virtual;
function GetCredentialsPassThrough: boolean;
function GetDSAuthUser: String; virtual;
function GetDSAuthPassword: String; virtual;
function GetSessionTimeout: Integer; virtual;
procedure SetSessionTimeout(const Milliseconds: Integer); virtual;
function GetIPImplementationID: string; override;
published
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property HttpServer: TDSHTTPServer read GetHttpServer;
published
{ Published declarations }
property DSContext: String read GetDSContext write SetDSContext;
/// <summary> REST URL context like in http://my.site.com/datasnap/rest/...
/// In the example above rest denotes that the request is a REST request
/// and is processed by REST service
/// </summary>
property RESTContext: String read GetRESTContext write SetRESTContext;
/// <summary> Cache URL context, like in http://my.site.com/datasnap/cache/...
/// </summary>
property CacheContext: String read GetCacheContext write SetCacheContext;
/// <summary> User trace code might go here
/// </summary>
property Trace: TDSHTTPServiceTraceEvent read GetTraceEvent write SetTraceEvent;
/// <summary>Event to call when a REST call is having its result built.</summary>
/// <remarks>The result can be modified by this event, changing its format or content.</remarks>
property FormatResult: TDSRESTResultEvent read GetResultEvent write SetResultEvent;
/// <summary> Server software, read only
/// </summary>
//property ServerSoftware: String read GetServerSoftware;
/// <summary> Datasnap Server. If set, takes precedence over hostname and port </summary>
property Server;
/// <summary> Datasnap Server machine name. Only used when DSServer is not set </summary>
property DSHostname: String read GetDSHostname write SetDSHostname;
/// <summary> Datasnap Server port number. Only used when DSServer is not set </summary>
property DSPort: Integer read GetDSPort write SetDSPort;
/// <summary> Datasnap communication filters for in-process instance</summary>
property Filters;
property AuthenticationManager: TDSCustomAuthenticationManager read GetAuthenticationManager
write SetAuthenticationManager;
/// <summary> true if the user credentials are authenticated at the endpoint </summary>
property CredentialsPassThrough: boolean read GetCredentialsPassThrough write SetCredentialsPassThrough;
property DSAuthUser: String read GetDSAuthUser write SetDSAuthUser;
property DSAuthPassword: String read GetDSAuthPassword write SetDSAuthPassword;
/// <summary> Time in miliseconds a session will remain valid. </summary>
/// <remarks> After this time passes, the session is marked as expired and eventually removed.
/// If 0 is specified, the session never expires.
/// </remarks>
property SessionTimeout: Integer read GetSessionTimeout write SetSessionTimeout;
end;
TDSCallbackChannelEvent = procedure(Sender: TObject) of object;
/// <summary> A callback and TStringList pairing, where the callback is one of the client's
/// channel callbacks, and the 'Channels' member is a list of channel names, aside from
/// the ChannelName if the TDSClientCallbackChannelManager, that the callback listens on.
/// </summary>
TDSCallbackItem = class
private
FServerChannelName: String;
FCallback: TDBXCallback;
FChannels: TStrings;
public
constructor Create(ServerChannelName: String; Callback: TDBXCallback; Channels: TStrings = nil); overload;
constructor Create(ServerChannelName: String; Callback: TDBXCallback; Channels: String = ''); overload;
destructor Destroy; override;
/// <summary>Returns true if this callback is 'listening' to the given Channel name.
/// Specifically, if the channel name is the server channel name, or in the Channels list.
/// </summary>
function ListeningOn(ChannelName: String): Boolean;
/// <summary>Name of the channel the manager this item is in listens on.</summary>
property ServerChannelName: String read FServerChannelName;
/// <summary>The callback wrapped by this item.</summary>
property Callback: TDBXCallback read FCallback;
/// <summary>A list of channel names this specific callback is interested in, or nil</summary>
property Channels: TStrings read FChannels;
end;
TDSClientCallbackChannelManager = class;
/// <summary> Event Item passed in through the TDSClientChannelManagerEvent,
/// for providing tunnel event info.
/// </summary>
TDSClientChannelEventItem = record
///<summary>The type of event occurring for a tunnel (channel.)</summary>
EventType: TDSCallbackTunnelEventType;
///<summary>The ID of the tunnel (Channel) being acted on.</summary>
TunnelId: String;
///<summary>The tunnel (Channel) being acted on.</summary>
Tunnel: TDSClientCallbackChannelManager;
///<summary>The ServerChannelName of the tunnel (Channel) being acted on.</summary>
TunnelChannelName: String;
/// <summary>The ID of the callback being added or removed. Empty string if tunnel is beign closed.
/// </summary>
CallbackId: String;
/// <summary>The callback item which wraps the callback this event is for. nil if tunnel is being closed.
/// </summary>
CallbackItem: TDSCallbackItem;
end;
/// <summary> User event for notification of channel events, such as create and close. </summary>
TDSClientChannelManagerEvent =
procedure(Sender: TObject; const EventItem: TDSClientChannelEventItem) of object;
/// <summary> Used to specify if a tunnel has failed or not. </summary>
TDSChannelThreadState = (ctsStopped, ctsStarted, ctsFailed);
/// <summary> Client callback manager handles the client callbacks that are registered
/// with a specific DS Server instance (DSHostname, DSPort, Communication protocol).
///
/// ChannelName property value will determine the server channel the callbacks will
/// be registered to. DS Server can handle multiple callback channels based on a name.
/// Callbacks can respond to messages posted to a channel asynchronously.
///
/// Manager Id is an unique identifier within a channel that will make possible
/// peer-to-peer callbacks.
/// </summary>
TDSClientCallbackChannelManager = class(TComponent)
strict private
FSecurityToken: String;
FDSHostname: String;
FDSPort: String;
FDSPath: String;
FCommunicationProtocol: String;
FChannelName: String;
FManagerId: String;
FConnectionTimeout: String;
FCommunicationTimeout: String;
FStopped: Boolean;
FUserName: String;
FPassword: String;
FProxyHost: String;
FProxyPort: Integer;
FProxyUsername: String;
FProxyPassword: String;
FIPImplementationID: String;
//Unique ID of the callback as the Key, and the callback item wrapping the callback as the value
FLocalCallbackRepo: TObjectDictionary<String, TDSCallbackItem>;
private
FChannelManagerEvent: TDSClientChannelManagerEvent;
procedure NotifyChange(EventType: TDSCallbackTunnelEventType; const CallbackId: String;
Item: TDSCallbackItem);
protected
type
TDSChannelInvokeEvent = procedure (const Id: String; Data: TJSONValue; out Response: TJSONValue) of object;
TDSChannelBroadcastEvent = procedure (Data: TJSONValue; ChannelName: String) of object;
TParamSetup = reference to procedure (Params: TDBXParameterList);
TDSWorker = reference to procedure;
TDSChannelCallback = class(TDBXCallback)
private
FInvokeEvent: TDSChannelInvokeEvent;
FInvokeObjectEvent: TDSChannelInvokeEvent;
FBroadcastEvent: TDSChannelBroadcastEvent;
FBroadcastObjectEvent: TDSChannelBroadcastEvent;
public
constructor Create(const InvokeEvent: TDSChannelInvokeEvent;
const InvokeObjectEvent: TDSChannelInvokeEvent;
const BroadcastEvent: TDSChannelBroadcastEvent;
const BroadcastObjectEvent: TDSChannelBroadcastEvent); overload;
destructor Destroy; override;
function Execute(const Arg: TJSONValue): TJSONValue; override;
end;
TDSChannelThread = class(TThread)
private
FWorker: TDSWorker;
FManager: TDSClientCallbackChannelManager;
protected
procedure Execute; override;
public
constructor Create(Worker: TDSWorker; Manager: TDSClientCallbackChannelManager = nil);
destructor Destroy; override;
end;
/// <summary>
/// Thread for execution of a Callback. This is done in its own thread so that if
/// the callback takes too long to return then the thread can be abandoned
/// and the client/server won't hang.
/// </summary>
TDSExecuteThread = class(TThread)
protected
FCallback: TDBXCallback;
FData: TJSONValue;
FResponse: TJSONValue;
procedure Execute; override;
public
constructor Create(Callback: TDBXCallback; Data: TJSONValue);
destructor Destroy; override;
property Response: TJSONValue read FResponse;
end;
strict private
FChannelCallback: TDSChannelCallback;
FOnServerConnectionError: TDSCallbackChannelEvent;
FOnServerConnectionTerminate: TDSCallbackChannelEvent;
FRegConverters: TObjectDictionary<String, TConverterEvent>;
FRegReverters: TObjectDictionary<String, TReverterEvent>;
protected
/// <summary> The current state of the tunnel thread </summary>
FState: TDSChannelThreadState;
/// <summary> If State is failed, this may hold a meaningful error message. </summary>
FStateError: String;
/// <summary> Creates the DBX DataSnap properties map from local fields
/// </summary>
function DBXConnectionProperties(NoTimeout: boolean = false): TDBXDatasnapProperties;
/// <summary> Generic method for remote invocation
/// </summary>
procedure ExecuteRemote(const AClassName, AMethodName: String; ParamSetup: TParamSetup;
ParamCheckup: TParamSetup; NoTimeout: boolean = false);
procedure Broadcast(Data: TJSONValue; ChannelName: String);
procedure BroadcastObject(Data: TJSONValue; ChannelName: String);
procedure Invoke(const Id: String; Data: TJSONValue; out Response: TJSONValue);
procedure InvokeObject(const Id: String; Data: TJSONValue; out Response: TJSONValue);
function GetIPImplementationID: string; virtual;
procedure SetIPImplementationID(const AIPImplementationID: string); virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
/// <summary>Returns a list of all callback Ids registered with this manager.</summary>
function GetCallbackIds: TArray<String>;
/// <summary>Returns the item (and true) if one with the given Id exists. nil (and false) otherwise.
/// </summary>
function GetCallbackItem(const CallbackId: String; out Item: TDSCallbackItem): boolean;
/// <summary> Registers a callback with the channel manager. The callback id
/// uniquely identifies it and it is used for peer-to-peer message exchange.
///
/// It returns false if the registration failed (there is already a callback with
/// the same id, invalid arguments, connection with DS Server failed, etc)
/// </summary>
function RegisterCallback(const CallbackId: String;
const Callback: TDBXCallback): boolean; overload;
function RegisterCallback(const CallbackId, ChannelNames: String;
const Callback: TDBXCallback): boolean; overload;
/// <summary> Registers a callback with the channel manager. The callback's name
/// uniquely identifies it and it is used for peer-to-peer message exchange.
///
/// It returns false if the registration failed (there is already a callback with
/// the same name, invalid arguments, connection with DS Server failed, etc)
/// </summary>
function RegisterCallback(const ChannelNames: String; const Callback: TDBXNamedCallback): boolean; overload;
function RegisterCallback(const Callback: TDBXNamedCallback): boolean; overload;
/// <summary> Unregisters a callback from the channel manager given the callback's unique Id (name)
/// </summary>
function UnregisterCallback(const CallbackId: String): boolean;
/// <summary> Closes the client channel, which will internally unregister all callbacks.
/// </summary>
function CloseClientChannel(): Boolean;
/// <summary> Broadcasts a message to all callbacks of the channel this is registered with.
/// </summary>
/// <remarks>
/// Function takes ownership of the argument
/// </remarks>
function BroadcastToChannel(const Msg: TJSONValue; ChannelName: String = ''): boolean;
/// <summary> Broadcasts a message to all callbacks of the channel this is registered with.
/// </summary>
/// <remarks>
/// Function takes ownership of the argument
/// </remarks>
function BroadcastObjectToChannel(const Msg: TObject; ChannelName: String = ''): boolean;
/// <summary> Notifies a client callback with the specified message </summary>
/// <remarks>
/// Function takes ownership of the input message argument
/// </remarks>
function NotifyCallback(const CallbackId, ManagerId: String;
const Msg: TJSONValue; out Response: TJSONValue): boolean;
/// <summary> Notifies a client callback with the specified message </summary>
/// <remarks>
/// Function takes ownership of the input message argument
/// </remarks>
function NotifyObjectCallback(const CallbackId, ManagerId: String;
const Msg: TObject; out Response: TObject): boolean;
function GetJSONMarshaler: TJSONMarshal;
function GetJSONUnMarshaler: TJSONUnMarshal;
procedure AddConverter(event: TConverterEvent);
procedure AddReverter(event: TReverterEvent);
/// <summary> Marshal argument using local marshaler</summary>
function MarshalData(Data: TObject): TJSONValue;
/// <summary> UnMarshal argument using local unmarshaler</summary>
function UnMarshalJSON(Data: TJSONValue): TObject;
/// <summary> Makes a copy of this manager, without any of its registered callbacks.</summary>
function Copy: TDSClientCallbackChannelManager;
/// <summary> The current state of the tunnel thread. </summary>
property State: TDSChannelThreadState read FState;
/// <summary> If State is failed, this may hold a meaningful error message. </summary>
property StateError: String read FStateError;
published
property DSHostname: String read FDSHostname write FDSHostname;
property DSPort: String read FDSPort write FDSPort;
property DSPath: String read FDSPath write FDSPath;
property CommunicationProtocol: String read FCommunicationProtocol write FCommunicationProtocol;
property ChannelName: String read FChannelName write FChannelName;
property ManagerId: String read FManagerId write FManagerId;
property OnServerConnectionError: TDSCallbackChannelEvent read FOnServerConnectionError
write FOnServerConnectionError;
property OnServerConnectionTerminate: TDSCallbackChannelEvent read FOnServerConnectionTerminate
write FOnServerConnectionTerminate;
/// <summary>miliseconds expected for the connection to be established</summary>
property ConnectionTimeout: String read FConnectionTimeout write FConnectionTimeout;
property CommunicationTimeout: String read FCommunicationTimeout write FCommunicationTimeout;
/// <summary>User name to authenticate with.</summary>
property UserName: String read FUserName write FUserName;
/// <summary>Password to authenticate with.</summary>
property Password: String read FPassword write FPassword;
/// <summary>The host to proxy requests through, or empty string to not use a proxy.</summary>
property ProxyHost: String read FProxyHost write FProxyHost;
/// <summary>The port on the proxy host to proxy requests through. Ignored if DSProxyHost isn't set.
/// </summary>
property ProxyPort: Integer read FProxyPort write FProxyPort default 8888;
/// <summary>The user name for authentication with the specified proxy.</summary>
property ProxyUsername: String read FProxyUsername write FProxyUsername;
/// <summary>The password for authentication with the specified proxy.</summary>
property ProxyPassword: String read FProxyPassword write FProxyPassword;
property IPImplementationID: string read GetIPImplementationID write SetIPImplementationID;
/// <summary>Event to be notified when the channel is opened or closed and when callbacks are added and removed.
/// </summary>
property OnChannelStateChange: TDSClientChannelManagerEvent read FChannelManagerEvent write FChannelManagerEvent;
end;
/// <summary> Base class for handlers which will translate the DBXCommand into Json in some fashion
/// </summary>
TDSJsonResponseHandler = class abstract(TDSServiceResponseHandler)
protected
FDSService: TDSService;
FServiceInstanceOwner: Boolean;
FAllowStream: boolean;
FResultEvent: TDSRESTResultEvent;
procedure GetCommandResponse(Command: TDBXCommand; out Response: TJSONValue; out ResponseStream: TStream);
/// <summary> Allows subclasses to handle each parameter as they see fit, or return False and allow
/// the base class to transform the parameter into a JSON representation.
/// </summary>
function HandleParameter(const Command: TDBXCommand; const Parameter: TDBXParameter;
out Response: TJSONValue; var ResponseStream: TStream): Boolean; Virtual; Abstract;
procedure PopulateContent(ResponseInfo: TDSHTTPResponse; Response: TJSONValue;
ResponseStream: TStream); Virtual; Abstract;
procedure ProcessResultObject(var ResultObj: TJSONObject; Command: TDBXCommand); Virtual;
public
constructor Create(CommandType: TDSHTTPCommandType; DSService: TDSService;
ServiceInstanceOwner: Boolean = True); Overload; Virtual;
destructor Destroy; override;
procedure GetResponse(out Response: TJSONValue; out ResponseStream: TStream;
out ContainsErrors: boolean); Override;
procedure PopulateResponse(ResponseInfo: TDSHTTPResponse;
InvokeMetadata: TDSInvocationMetadata); Override;
/// <summary>Event to call when a REST call is having its result built, to be returned.</summary>
property ResultEvent: TDSRESTResultEvent read FResultEvent write FResultEvent;
end;
/// <summary> Default implementation of a Response Handler, which returns JSON for all data types,
/// except for the case where the user specifies they want TStream to be returned in the response
/// stream when the TStream is the only output/response parameter of the method being invoked.
/// </summary>
TDSDefaultResponseHandler = class(TDSJsonResponseHandler)
private
FStoreHandler: Boolean;
protected
function HandleParameter(const Command: TDBXCommand; const Parameter: TDBXParameter;
out Response: TJSONValue; var ResponseStream: TStream): Boolean; Override;
procedure PopulateContent(ResponseInfo: TDSHTTPResponse; Response: TJSONValue;
ResponseStream: TStream); Override;
public
constructor Create(AllowBinaryStream: boolean; DSService: TDSService; CommandType: TDSHTTPCommandType;
ServiceInstanceOwner: Boolean = True);
destructor Destroy; override;
procedure Close(); override;
end;
/// <summary> Used internally for implementations of TResultCommandHandler
/// </summary>
TDSCommandComplexParams = class
private
FCommand: TDBXCommand;
FParameters: TList<TDBXParameter>;
public
constructor Create(Command: TDBXCommand); Virtual;
destructor Destroy; override;
function GetParameterCount: Integer;
function GetParameter(Index: Integer): TDBXParameter;
function AddParameter(Parameter: TDBXParameter): Integer;
property Command: TDBXCommand read FCommand;
end;
/// <summary> Wraps an instance of TRequestCommandHandler which wants to make itself cacheable.
/// </summary>
TDSCacheResultCommandHandler = class(TResultCommandHandler)
protected
FCommandWrapper: TRequestCommandHandler;
FCacheCommands: TList<TDSCommandComplexParams>;
public
constructor Create(CommandWrapper: TRequestCommandHandler); Virtual;
destructor Destroy; override;
function GetCommandCount: Integer; Override;
function GetParameterCount(Index: Integer): Integer; Override;
function GetCommand(Index: Integer): TDBXCommand; Override;
function GetCommandParameter(CommandIndex: Integer; ParameterIndex: Integer): TDBXParameter; Overload; Override;
function GetCommandParameter(Command: TDBXCommand; Index: Integer): TDBXParameter; Overload; Override;
property CacheCommands: TList<TDSCommandComplexParams> read FCacheCommands write FCacheCommands;
end;
/// <summary> Request Handler when you don't care about getting any response from an execution.
/// </summary>
TDSNullResponseHandler = class(TDSJsonResponseHandler)
protected
function HandleParameter(const Command: TDBXCommand; const Parameter: TDBXParameter;
out Response: TJSONValue; var ResponseStream: TStream): Boolean; Override;
procedure PopulateContent(ResponseInfo: TDSHTTPResponse; Response: TJSONValue;
ResponseStream: TStream); Override;
public
constructor Create(DSService: TDSService; CommandType: TDSHTTPCommandType; ServiceInstanceOwner: Boolean = True);
procedure Close(); override;
end;
/// <summary> Implementation of response handler for the case when complex datatypes are stored on
/// the server in a cache, and a URL to the object in the cache is passed back to the user instead
/// of the value of the cached object.
/// </summary>
TDSCacheResponseHandler = class(TDSJsonResponseHandler)
protected
FResultHandler: TDSCacheResultCommandHandler;
FCacheId: Integer;
function GetCacheObject: TDSCacheResultCommandHandler;
function HandleParameter(const Command: TDBXCommand; const Parameter: TDBXParameter;
out Response: TJSONValue; var ResponseStream: TStream): Boolean; Override;
procedure PopulateContent(ResponseInfo: TDSHTTPResponse; Response: TJSONValue;
ResponseStream: TStream); Override;
function GetComplexParams(Command: TDBXCommand; out Index: Integer;
AddIfNotFound: Boolean = True): TDSCommandComplexParams;
procedure ProcessResultObject(var ResultObj: TJSONObject; Command: TDBXCommand); Override;
public
constructor Create(DSService: TDSService; CommandType: TDSHTTPCommandType; ServiceInstanceOwner: Boolean = True);
destructor Destroy; override;
procedure Close(); override;
end;
/// <summary> Factory for creating an appropriate instance of TDSServiceResponseHandler
/// </summary>
TDSResponseHandlerFactory = class
public
/// <summary> Returns a new instance of the appropriate TDSServiceResponseHandler implementation,
/// based on the provided information.
/// </summary>
class function CreateResponseHandler(DSService: TDSService;
RequestInfo: TDSHTTPRequest;
CommandType: TDSHTTPCommandType = hcUnknown;
HTTPServer: TDSHTTPServer = nil): TDSServiceResponseHandler;
end;
implementation
uses
{$IFNDEF POSIX}
Winapi.ActiveX,
System.Win.ComObj,
{$ENDIF}
Data.DBXClientResStrs,
Data.DBXJSONCommon,
System.StrUtils;
const
DATASNAP_CONTEXT = 'datasnap';
CMD_ERROR = 'error';
TUNNEL_CONTEXT = 'tunnel';
TUNNEL_INFO_LIST = 'tunnelinfolist';
CHANNEL_NAME = 'ChannelName';
CLIENT_CHANNEL_ID = 'ClientChannelId';
SECURITY_TOKEN = 'SecurityToken';
AUTH_USER = 'AuthUserName';
AUTH_PASSWORD = 'AuthPassword';
//temporary replacement for the TDSHTTPServer.LoadSession helper function, to avoid
//interface breaking changes in XE2 update builds.
function LoadSessionUpdate(const SessionId: String; const UserName: String;
const SessionTimeout: Integer; const TunnelService: TDSTunnelService;
const AuthManager: TDSCustomAuthenticationManager;
const ARequestInfo: TDSHTTPRequest;
out IsNewSession: boolean): boolean;
var
Session: TDSSession;
begin
TDSSessionManager.ClearThreadSession;
//if session id wasn't specified then create a new session
if SessionID = '' then
begin
IsNewSession := True;
Session := TDSSessionManager.Instance.CreateSession<TDSRESTSession>(function: TDSSession begin
Result := TDSRESTSession.Create(AuthManager);
Result.ObjectCreator := TunnelService;
//populate session data while creating, so session event tires with data already populated
if ARequestInfo <> nil then
begin
if ARequestInfo.RemoteIP <> EmptyStr then
Result.PutData('RemoteIP', ARequestInfo.RemoteIP);
Result.PutData('RemoteAppName', ARequestInfo.UserAgent);
Result.PutData('CommunicationProtocol', ARequestInfo.ProtocolVersion);
Result.PutData('ProtocolSubType', 'rest');
end;
end, UserName);
//must have activity at least once every X minutes to be valid
if SessionTimeout > 0 then
begin
Session.LifeDuration := SessionTimeout;
Session.ScheduleInactiveTerminationEvent;
end;
end
else
begin
IsNewSession := False;
//check if the Session ID is valid by trying to get it's matching session from the manager
Session := TDSSessionManager.Instance.Session[SessionID];
//if the session ID wasn't valid, return false showing session retrieval failed
if (Session = nil) or (not Session.IsValid) then
begin
exit(False);
end
else
Session.MarkActivity; //session is being used again, so mark as active
end;
if Session <> nil then
TDSSessionManager.SetAsThreadSession(Session);
exit(True);
end;
{TDSHTTPServer}
constructor TDSHTTPServer.Create;
begin
Create('');
end;
constructor TDSHTTPServer.Create(const AIPImplementationID: string);
begin
inherited Create;
FIPImplementationID := AIPImplementationID;
// Default values defined elsewhere
// FRESTContext := REST_CONTEXT;
// FCacheContext := CACHE_CONTEXT;
// FDSContext := DATASNAP_CONTEXT;
// FDSHostname := 'localhost';
// FDSPort := 211;
// FCredentialsPassThrough := false;
// FSessionTimeout := 1200000;
// FDSAuthUser := EmptyStr;
// FDSAuthPassword := EmptyStr;
FResultEvent := nil;
FProtocolHandlerFactory := nil;
FTunnelService := TDSTunnelService.Create(FDSHostname, FDSPort, FFilters, FProtocolHandlerFactory);
//Listen for a session closing event and close the session's tunnel, if one exists
FSessionEvent :=
procedure(Sender: TObject; const EventType: TDSSessionEventType; const Session: TDSSession)
begin
case EventType of
SessionClose:
CloseSessionTunnels(Session);
end;
end;
TDSSessionManager.Instance.AddSessionEvent(FSessionEvent);
end;
destructor TDSHTTPServer.Destroy;
begin
if Assigned(FSessionEvent) then
TDSSessionManager.Instance.RemoveSessionEvent(FSessionEvent);
FreeAndNil(FTunnelService);
FreeAndNil(FProtocolHandlerFactory);
inherited;
end;
procedure TDSHTTPServer.CreateProtocolHandlerFactory(ATransport: TDSServerTransport);
begin
FreeAndNil(FProtocolHandlerFactory);
FProtocolHandlerFactory := TDSJSONProtocolHandlerFactory.Create(ATransport);
TunnelService.ProtocolHandlerFactory := FProtocolHandlerFactory;
end;
procedure TDSHTTPServer.ClearProtocolHandlerFactory;
begin
FreeAndNil(FProtocolHandlerFactory);
TunnelService.ProtocolHandlerFactory := nil;
end;
function TDSHTTPServer.GetTunnelService: TDSTunnelService;
begin
if FTunnelService = nil then
FTunnelService := TDSTunnelService.Create(FDSHostname, FDSPort, FFilters, FProtocolHandlerFactory);
Result := FTunnelService;
end;
procedure TDSHTTPServer.CloseAllTunnelSessions;
begin
if FTunnelService <> nil then
FTunnelService.TerminateAllSessions;
end;
procedure TDSHTTPServer.CloseRESTSession(Session: TDSSession; ResponseInfo: TDSHTTPResponse);
begin
Assert(ResponseInfo <> nil);
if (Session <> nil) then
begin
try
TDSSessionManager.Instance.CloseSession(Session.SessionName);
ResponseInfo.ResponseNo := 200;
ResponseInfo.ResponseText := '{"result":[true]}';
except
end;
end
else
begin
ResponseInfo.ResponseNo := 400;
ResponseInfo.ResponseText := SSessionExpiredMsg;
end;
end;
function TDSHTTPServer.GetCacheContext: String;
begin
Result := FCacheContext + '/';
end;
function TDSHTTPServer.IsClosingSession(Request: String): boolean;
begin
Result := AnsiStartsText('/CloseSession/', Request);
end;
function TDSHTTPServer.IsClosingClientChannel(Request: String): boolean;
begin
Result := AnsiStartsText('/DSAdmin/CloseClientChannel/', Request) or
AnsiStartsText('/DSAdmin/%22CloseClientChannel%22/', Request);
end;
function TDSHTTPServer.IsOpeningClientChannel(Request: String): boolean;
begin
Result := AnsiStartsText('/DSAdmin/ConsumeClientChannel/', Request) or
AnsiStartsText('/DSAdmin/%22ConsumeClientChannel%22/', Request);
end;
function TDSHTTPServer.GetClientChannelInfo(Request: String;
out ChannelName, ClientChannelId, SecurityToken: String): boolean;
var
OpeningClientChannel: Boolean;
Tokens: TStringList;
begin
Result := False;
OpeningClientChannel := IsOpeningClientChannel(Request);
if OpeningClientChannel or IsClosingClientChannel(Request) then
begin
Tokens := TStringList.Create;
Tokens.Delimiter := '/';
Tokens.DelimitedText := Request;
try
if (OpeningClientChannel and (Tokens.Count > 7)) or (Tokens.Count > 5) then
begin
ChannelName := Tokens[3];
ClientChannelId := Tokens[4];
if OpeningClientChannel then
SecurityToken := Tokens[7]
else
SecurityToken := Tokens[5];
Result := ClientChannelId <> EmptyStr;
end;
finally
FreeAndNil(Tokens);
end;
end;
end;
function TDSHTTPServer.GetDsContext: String;
begin
Result := FDSContext + '/';
end;
function TDSHTTPServer.GetRestContext: String;
begin
Result := FRESTContext + '/';
end;
procedure TDSHTTPServer.SetAuthenticationManager(
AuthenticationManager: TDSCustomAuthenticationManager);
begin
FDSHTTPAuthenticationManager := AuthenticationManager;
if FTunnelService <> nil then
FTunnelService.DSAuthenticationManager := AuthenticationManager;
end;
procedure TDSHTTPServer.SetCacheContext(const ctx: String);
begin
if (ctx <> EmptyStr) and
(ctx[Length(ctx)] = '/') then
FCacheContext := Copy(ctx, 1, Length(ctx)-1)
else
FCacheContext := ctx;
end;
procedure TDSHTTPServer.SetDsContext(const ctx: String);
begin
if (ctx <> EmptyStr) and
(ctx[Length(ctx)] = '/') then
FDSContext := Copy(ctx, 1, Length(ctx)-1)
else
FDSContext := ctx;
end;
procedure TDSHTTPServer.SetDSHostname(AHostname: string);
begin
FDSHostname := AHostname;
TunnelService.DSHostname := AHostname;
end;
procedure TDSHTTPServer.SetDSPort(APort: Integer);
begin
FDSPort := Aport;
TunnelService.DSPort := APort;
end;
procedure TDSHTTPServer.SetDSServerName(AName: string);
begin
FDSServerName := AName;
TunnelService.HasLocalServer := AName <> EmptyStr;
end;
procedure TDSHTTPServer.SetFilters(AFilterCollection: TTransportFilterCollection);
begin
FFilters := AFilterCollection;
TunnelService.Filters := AFilterCollection;
end;
procedure TDSHTTPServer.SetRestContext(const ctx: String);
begin
if (ctx <> EmptyStr) and
(ctx[Length(ctx)] = '/') then
FRESTContext := Copy(ctx, 1, Length(ctx)-1)
else
FRESTContext := ctx;
end;
procedure TDSHTTPServer.CloseSessionTunnels(Session: TDSSession);
var
RESTService: TDSRESTService;
CloseTunnelRequest: String;
RespHandler: TDSServiceResponseHandler;
Obj: TObject;
InfoList: TList<TDSSessionTunnelInfo>;
Info: TDSSessionTunnelInfo;
I: Integer;
begin
InfoList := nil;
if Session.HasObject(TUNNEL_INFO_LIST) then
begin
Obj := Session.GetObject(TUNNEL_INFO_LIST);
if Obj Is TList<TDSSessionTunnelInfo> then
InfoList := TList<TDSSessionTunnelInfo>(Obj);
end;
if (Session <> nil) and (InfoList <> nil) then
begin
for I := 0 to (InfoList.Count - 1) do
begin
Info := InfoList.Items[I];
CloseTunnelRequest :=
Format('/DSAdmin/CloseClientChannel/%s/%s/', [Info.ClientChannelId, Info.SecurityToken]);
RESTService := CreateRESTService(Info.AuthUser, Info.AuthPassword);
RespHandler := TDSResponseHandlerFactory.CreateResponseHandler(RESTService, nil, hcGET);
try
try
RESTService.ProcessGETRequest(CloseTunnelRequest, nil, nil, RespHandler);
except
end;
finally
FreeAndNil(RespHandler);
end;
end;
end;
end;
procedure TDSHTTPServer.UpdateSessionTunnelHook(Request: String; Session: TDSSession; RequestInfo: TDSHTTPRequest);
var
SessionChannelName: String;
SessionClientChannelId: String;
SessionSecurityToken: String;
Obj: TObject;
Info: TDSSessionTunnelInfo;
InfoList: TList<TDSSessionTunnelInfo>;
I: Integer;
begin
Assert(Session <> nil);
Assert(RequestInfo <> nil);
if IsOpeningClientChannel(Request) then
begin
if GetClientChannelInfo(Request, SessionChannelName, SessionClientChannelId, SessionSecurityToken) then
begin
Info.ChannelName := SessionChannelName;
Info.ClientChannelId := SessionClientChannelId;
Info.SecurityToken := SessionSecurityToken;
Info.AuthUser := RequestInfo.AuthUserName;
Info.AuthPassword := RequestInfo.AuthPassword;
if not Session.HasObject(TUNNEL_INFO_LIST) then
Session.PutObject(TUNNEL_INFO_LIST, TList<TDSSessionTunnelInfo>.Create);
Obj := Session.GetObject(TUNNEL_INFO_LIST) ;
if (Obj Is TList<TDSSessionTunnelInfo>) then
TList<TDSSessionTunnelInfo>(Obj).Add(Info);
end;
end
else if IsClosingClientChannel(Request) then
begin
if GetClientChannelInfo(Request, SessionChannelName, SessionClientChannelId, SessionSecurityToken) then
begin
Obj := Session.GetObject(TUNNEL_INFO_LIST); //SessionClientChannelId
if Obj Is TList<TDSSessionTunnelInfo> then
begin
InfoList := TList<TDSSessionTunnelInfo>(Obj);
for I := 0 to (InfoList.Count - 1) do
begin
Info := InfoList.Items[I];
if (SessionClientChannelId = Info.ClientChannelId) and (SessionSecurityToken = Info.SecurityToken) then
begin
InfoList.Delete(I);
Exit;
end;
end;
end;
end;
end;
end;
function TDSHTTPServer.ByteContent(DataStream: TStream): TBytes;
var
Buffer: TBytes;
begin
if not Assigned(DataStream) then
exit(nil);
SetLength(Buffer, DataStream.Size);
// the content may have been read
DataStream.Position := 0;
if DataStream.Size > 0 then
DataStream.Read(Buffer[0], DataStream.Size);
Result := Buffer;
end;
function TDSHTTPServer.ByteContent(JsonValue: TJSONValue): TBytes;
var
Buffer: TBytes;
begin
SetLength(Buffer, JsonValue.EstimatedByteSize);
SetLength(Buffer, JsonValue.ToBytes(Buffer, 0));
Result := Buffer;
end;
function TDSHTTPServer.GetRequestSessionId(const ARequestInfo: TDSHTTPRequest;
const CheckURLParams: boolean): String;
var
SessionID: String;
PragmaStr: String;
PragmaList: TStringList;
begin
//empty string will be returned for session ID unless found in Pragma header
SessionID := '';
if CheckURLParams then
begin
SessionID := ARequestInfo.Params.Values['SESSIONID'];
if SessionID = '' then
SessionID := ARequestInfo.Params.Values['sid'];
end;
//if no session ID is given in the URL, then try to load it from the Pragma header field
if SessionID = '' then
begin
PragmaStr := ARequestInfo.Pragma;
if PragmaStr <> '' then
begin
PragmaList := TStringList.Create;
PragmaList.CommaText := PragmaStr;
//Pragma is a comma-separaged list of keys with optional value pairings.
//session id is stored as a key/value pair with "dssession" as the key
SessionID := PragmaList.Values['dssession'];
FreeAndNil(PragmaList);
end;
end;
Result := SessionID;
end;
function TDSHTTPServer.LoadSession(const SessionId: String; const UserName: String;
out IsNewSession: boolean): boolean;
var
Session: TDSSession;
begin
TDSSessionManager.ClearThreadSession;
//if session id wasn't specified then create a new session
if SessionID = '' then
begin
IsNewSession := True;
Session := TDSSessionManager.Instance.CreateSession<TDSRESTSession>(function: TDSSession begin
Result := TDSRESTSession.Create(FDSHTTPAuthenticationManager);
Result.ObjectCreator := FTunnelService;
end, UserName);
//must have activity at least once every X minutes to be valid
if FSessionTimeout > 0 then
begin
Session.LifeDuration := FSessionTimeout;
Session.ScheduleInactiveTerminationEvent;
end;
end
else
begin
IsNewSession := False;
//check if the Session ID is valid by trying to get it's matching session from the manager
Session := TDSSessionManager.Instance.Session[SessionID];
//if the session ID wasn't valid, return false showing session retrieval failed
if (Session = nil) or (not Session.IsValid) then
begin
exit(False);
end
else
Session.MarkActivity; //session is being used again, so mark as active
end;
if Session <> nil then
TDSSessionManager.SetAsThreadSession(Session);
exit(True);
end;
procedure TDSHTTPServer.DoDSCacheCommand(ARequestInfo: TDSHTTPRequest;
AResponseInfo: TDSHTTPResponse;
Request: String;
LocalConnection: Boolean);
var
CmdType: TDSHTTPCommandType;
SessionID: String;
Session: TDSSession;
IsNewSession: Boolean;
SessionFailure: Boolean;
CacheService: TDSHTTPCacheContextService;
Len: Integer;
ParamName: String;
begin
CacheService := nil;
CmdType := ARequestInfo.CommandType;
//if no session ID is given in the URL, then try to load it from the Pragma header field
SessionID := GetRequestSessionId(aRequestInfo, True);
//Try to load the session with the given session ID into the current thread
SessionFailure :=
not LoadSessionUpdate(SessionID, ARequestInfo.AuthUserName, FSessionTimeout,
FTunnelService, FDSHTTPAuthenticationManager, ARequestInfo,
IsNewSession);
Session := TDSSessionManager.GetThreadSession;
//free any stream which was stored from a previous execution
if Session <> nil then
begin
Session.LastResultStream.Free;
Session.LastResultStream := nil;
end;
try
if (Session = nil) or SessionFailure then
begin
AResponseInfo.ResponseNo := 403; //Forbidden
AResponseInfo.ResponseText := SSessionExpiredTitle;
AResponseInfo.ContentText := '{"SessionExpired":"' + SSessionExpiredMsg + '"}';
end
else
begin
CacheService := TDSHTTPCacheContextService.Create(Session, LocalConnection);
Len := 0;
while (Len < ARequestInfo.Params.Count) do
begin
try
ParamName := ARequestInfo.Params.Names[Len];
CacheService.ProcessQueryParameter(ParamName, ARequestInfo.Params.Values[ParamName]);
finally
Inc(Len);
end;
end;
// dispatch to the appropriate service
case CmdType of
hcGET: CacheService.ProcessGETRequest(ARequestInfo, AResponseInfo, Request);
hcDELETE: CacheService.ProcessDELETERequest(ARequestInfo, AResponseInfo, Request);
else
begin
AResponseInfo.ResponseNo := 501;
AResponseInfo.ContentText := Format(SCommandNotSupported, [ARequestInfo.Command]);
end;
end;
end;
finally
CacheService.Free;
AResponseInfo.CloseConnection := true;
TDSSessionManager.ClearThreadSession;
end;
end;
function TDSHTTPServer.CreateRESTService(const AuthUserName, AuthPassword: String): TDSRESTService;
begin
if FCredentialsPassthrough then
Result := TDSRESTService.Create(FDSServerName, FDSHostname, FDSPort, AuthUserName, AuthPassword, IPImplementationID)
else
Result := TDSRESTService.Create(FDSServerName, FDSHostname, FDSPort, FDSAuthUser, FDSAuthPassword, IPImplementationID);
end;
procedure TDSHTTPServer.DoDSRESTCommand(ARequestInfo: TDSHTTPRequest;
AResponseInfo: TDSHTTPResponse;
Request: String);
var
CmdType: TDSHTTPCommandType;
ResponseOk: Integer;
RESTService: TDSRESTService;
Len: Integer;
ParamName: String;
SessionID: String;
Session: TDSSession;
IsNewSession: Boolean;
SessionFailure: Boolean;
RespHandler: TDSServiceResponseHandler;
OwnService: Boolean;
begin
OwnService := True;
RespHandler := nil;
CmdType := ARequestInfo.CommandType;
ResponseOk := 200;
RESTService := CreateRESTService(ARequestInfo.AuthUserName, ARequestInfo.AuthPassword);
// process query parameters
Len := 0;
while (Len < ARequestInfo.Params.Count) and (ResponseOk < 300) do
begin
ParamName := ARequestInfo.Params.Names[Len];
//check for session ID parameter in the URL
if (Uppercase(ParamName) = 'SESSIONID') or (Uppercase(ParamName) = 'SID') then
begin
SessionID := ARequestInfo.Params.Values[ParamName]
end
else if not RESTService.ProcessQueryParameter(ParamName, ARequestInfo.Params.ValueFromIndex[Len]) then
begin
ResponseOK := 409;
AResponseInfo.ResponseText := Format(SCannotProcessParam, [ARequestInfo.Params.Names[Len],
ARequestInfo.Params.Values[ARequestInfo.Params.Names[Len]]]);
end;
Inc(Len);
end;
if (ResponseOK < 300) and not RESTService.CheckConvertersForConsistency then
begin
// 409 - Indicates that the request could not be processed because of conflict in the request
AResponseInfo.ResponseNo := 409;
AResponseInfo.ResponseText := SConflictQueryParam;
end;
//if no session ID is given in the URL, then try to load it from the Pragma header field
if SessionID = EmptyStr then
begin
SessionID := GetRequestSessionId(aRequestInfo, False);
end;
//Try to load the session with the given session ID into the current thread
SessionFailure :=
not LoadSessionUpdate(SessionID, ARequestInfo.AuthUserName, FSessionTimeout,
FTunnelService, FDSHTTPAuthenticationManager, ARequestInfo,
IsNewSession);
Session := TDSSessionManager.GetThreadSession;
//free any stream which was stored from a previous execution
if Session <> nil then
begin
Session.LastResultStream.Free;
Session.LastResultStream := nil;
if not SessionFailure then
UpdateSessionTunnelHook(Request, Session, ARequestInfo);
end;
if not SessionFailure and IsClosingSession(Request) then
begin
try
CloseRESTSession(Session, AResponseInfo);
finally
FreeAndNil(RESTService);
TDSSessionManager.ClearThreadSession;
end;
exit;
end;
try
if SessionFailure then
begin
AResponseInfo.ResponseNo := 403; //Forbidden
AResponseInfo.ResponseText := SSessionExpiredTitle;
AResponseInfo.ContentText := '{"SessionExpired":"' + SSessionExpiredMsg + '"}';
end
else if ResponseOK >= 300 then
begin
// pre-parsing failed and the decision is in ResponseOK, response text already set
AResponseInfo.ResponseNo := ResponseOK;
end
//don't need to authenticate if returning to a previously authenticated session
else if (FDSHTTPAuthenticationManager <> nil) and IsNewSession and not FDSHTTPAuthenticationManager.Authenticate(
DATASNAP_CONTEXT, RESTContext, ARequestInfo.AuthUserName, ARequestInfo.AuthPassword,
ARequestInfo, AResponseInfo) then
if ARequestInfo.AuthUserName <> EmptyStr then
AResponseInfo.ResponseNo := 403
else
begin
AResponseInfo.SetHeaderAuthentication('Basic', 'REST');
AResponseInfo.ResponseNo := 401
end
else
begin
if Session <> nil then
begin
AResponseInfo.Pragma := 'dssession=' + Session.SessionName;
AResponseInfo.Pragma := AResponseInfo.Pragma + ',dssessionexpires=' + IntToStr(Session.ExpiresIn);
end;
OwnService := False;
//create the response handler for populating the response info
RespHandler := TDSResponseHandlerFactory.CreateResponseHandler(RESTService, ARequestInfo, hcUnknown, Self);
if RespHandler = nil then
begin
AResponseInfo.ResponseNo := 406; //Not Acceptable
end
else
begin
//add the query parameters to invocation metadata
if ARequestInfo.Params.Count > 0 then
GetInvocationMetadata().QueryParams.AddStrings(ARequestInfo.Params);
// dispatch to the appropriate service
case CmdType of
hcGET:
RESTService.ProcessGETRequest(Request, nil, nil, RespHandler);
hcPOST:
RESTService.ProcessPOSTRequest(Request, ARequestInfo.Params, byteContent( ARequestInfo.PostStream ),
RespHandler);
hcPUT:
begin
RESTService.ProcessPUTRequest(Request, ARequestInfo.Params, byteContent( ARequestInfo.PostStream ),
RespHandler);
end;
hcDELETE:
RESTService.ProcessDELETERequest(Request, nil, nil, RespHandler);
else
begin
GetInvocationMetadata().ResponseCode := 501;
GetInvocationMetadata().ResponseContent := Format(SCommandNotSupported, [ARequestInfo.Command]);
end;
end;
//populate the Response Info from the execution result
RespHandler.PopulateResponse(AResponseInfo, GetInvocationMetadata());
end;
end;
finally
if RespHandler = nil then
FreeAndNil(RESTService);
if RespHandler <> nil then
RespHandler.Close;
if OwnService then
FreeAndNil(RESTService);
if (GetInvocationMetadata(False) <> nil) and
GetInvocationMetadata.CloseSession and
(TDSSessionManager.GetThreadSession <> nil) then
TDSSessionManager.Instance.CloseSession(TDSSessionManager.GetThreadSession.SessionName);
TDSSessionManager.ClearThreadSession;
end;
end;
procedure TDSHTTPServer.DoJSONCommand(ARequestInfo: TDSHTTPRequest;
AResponseInfo: TDSHTTPResponse;
Request: String);
var
CmdType: TDSHTTPCommandType;
JSONService: TDSJSONService;
RespHandler: TDSServiceResponseHandler;
SessionID: String;
SessionFailure: Boolean;
IsNewSession: Boolean;
begin
if FCredentialsPassThrough then
JSONService := TDSJSONService.Create(FDSServerName, FDSHostname, FDSPort, ARequestInfo.AuthUserName, ARequestInfo.AuthPassword, IPImplementationID)
else
JSONService := TDSJSONService.Create(FDSServerName, FDSHostname, FDSPort, FDSAuthUser, FDSAuthPassword, IPImplementationID);
SessionID := GetRequestSessionId(aRequestInfo, True);
SessionFailure :=
not LoadSessionUpdate(SessionID, ARequestInfo.AuthUserName, FSessionTimeout,
FTunnelService, FDSHTTPAuthenticationManager, ARequestInfo,
IsNewSession);
//create the response handler for populating the response info
RespHandler := TDSResponseHandlerFactory.CreateResponseHandler(JSONService, ARequestInfo, hcUnknown, Self);
CmdType := ARequestInfo.CommandType;
try
if SessionFailure then
begin
AResponseInfo.ResponseNo := 403; //Forbidden
AResponseInfo.ResponseText := SSessionExpiredTitle;
AResponseInfo.ContentText := '{"SessionExpired":"' + SSessionExpiredMsg + '"}';
end
else if RespHandler = nil then
begin
AResponseInfo.ResponseNo := 406; //Not Acceptable
end
else
begin
try
//Even if only executing a single command, the result will be an array of result objects.
RespHandler.ForceResultArray := True;
case CmdType of
hcGET:
JSONService.ProcessGETRequest(Request, nil, ByteContent(ARequestInfo.PostStream),
RespHandler);
hcPOST:
JSONService.ProcessPOSTRequest(Request, nil, ByteContent(ARequestInfo.PostStream),
RespHandler);
hcPUT:
JSONService.ProcessPUTRequest(Request, nil, ByteContent(ARequestInfo.PostStream),
RespHandler);
hcDElETE:
JSONService.ProcessDELETERequest(Request, nil, ByteContent(ARequestInfo.PostStream),
RespHandler);
else
begin
GetInvocationMetadata().ResponseCode := 501;
GetInvocationMetadata().ResponseContent := Format(SCommandNotSupported, [ARequestInfo.Command]);
end;
end;
//populate the Response Info from the execution result
RespHandler.PopulateResponse(AResponseInfo, GetInvocationMetadata());
except on Ex: Exception do
begin
AResponseInfo.ResponseNo := 500;
AResponseInfo.ResponseText := Ex.Message;
end;
end;
end;
finally
if RespHandler = nil then
FreeAndNil(JSONService);
if RespHandler <> nil then
RespHandler.Close;
end;
end;
procedure TDSHTTPServer.DoTunnelCommand(AContext: TDSHTTPContext; ARequestInfo: TDSHTTPRequest;
AResponseInfo: TDSHTTPResponse);
var
CmdType: TDSHTTPCommandType;
JsonResponse: TJSONValue;
Len: Integer;
NeedsAuthentication: Boolean;
CloseConnection: boolean;
ClientInfo: TDBXClientInfo;
begin
JsonResponse := nil;
CmdType := ARequestInfo.CommandType;
// Note that CredentialsPassthrough, DSAuthUser and DSAuthPassword properties
// do not apply when tunneling using a DBX connection (which is what is happening in this method).
// Instead, the DBX connection string credentials from the client are passed though the
// tunnel without modification.
// The CredentialsPassthrough, DSAuthUser and DSAuthPassword properties
// do apply when tunneling using a REST connection. See TDSHTTPServer.DoJSONCommand.
// Optionally, the client may send user/password in HTTP headers in addition to the
// credentials in the DBX connection string. If the tunnel is between processea, this gives
// the HTTP end of the tunnel a chance to authenticate before the TCP/IP end.
// HTTP authentication is ignored when tunneling in-process because authentication will take place
// when the DBX connection string is received from the client.
NeedsAuthentication := (not FTunnelService.HasLocalServer) and FTunnelService.NeedsAuthentication(ARequestInfo.Params);
ClientInfo.IpAddress := ARequestInfo.RemoteIP;
ClientInfo.Protocol := ARequestInfo.ProtocolVersion;
ClientInfo.AppName := ARequestInfo.UserAgent;
//initialize the session so that it will be available when authenticating.
FTunnelService.InitializeSession(ARequestInfo.Params, ClientInfo);
try
try
if (FDSHTTPAuthenticationManager <> nil) and NeedsAuthentication and
not FDSHTTPAuthenticationManager.Authenticate(DATASNAP_CONTEXT, TUNNEL_CONTEXT,
ARequestInfo.AuthUserName, ARequestInfo.AuthPassword, ARequestInfo, AResponseInfo) then
AResponseInfo.ResponseNo := 401
else
begin
case CmdType of
hcGET:
begin
Len := 0;
AResponseInfo.ContentStream := FTunnelService.ProcessGET(ARequestInfo.Params, Len, CloseConnection);
AResponseInfo.ContentLength := Len;
AResponseInfo.CloseConnection := CloseConnection;
if Len = 0 then
begin
// no data are available from DS - server error
AResponseInfo.ResponseNo := 500;
AResponseInfo.ResponseText := SNoServerData;
AResponseInfo.CloseConnection := true;
end;
end;
hcPUT, hcPOST:
begin
FTunnelService.ProcessPOST(ARequestInfo.Params, ByteContent(ARequestInfo.PostStream),
JsonResponse, CloseConnection);
AResponseInfo.CloseConnection := CloseConnection;
end;
hcDELETE:
begin
AResponseInfo.ResponseNo := 501;
AResponseInfo.ResponseText := Format(SProtocolCommandNotSupported, [ARequestInfo.Command]);
AResponseInfo.CloseConnection := true;
end
else
begin
AResponseInfo.ResponseNo := 501;
AResponseInfo.ResponseText := Format(SProtocolCommandNotSupported, [ARequestInfo.Command]);
AResponseInfo.CloseConnection := true;
end;
end;
if JsonResponse <> nil then
begin
AResponseInfo.ResponseNo := 200;
AResponseInfo.ContentText := StringOf(ByteContent(JsonResponse));
end;
end;
except on Ex: Exception do
begin
AResponseInfo.ResponseNo := 500;
AResponseInfo.ResponseText := Ex.message;
AResponseInfo.CloseConnection := true;
end;
end;
finally
JsonResponse.Free;
// if client dropped the connection session can be terminated.
try
if not AContext.Connected then
TDSTunnelService.TerminateSession(ARequestInfo.Params);
except on Exception do
TDSTunnelService.TerminateSession(ARequestInfo.Params);
end;
end;
end;
procedure TDSHTTPServer.DoCommand(AContext: TDSHTTPContext; ARequestInfo: TDSHTTPRequest;
AResponseInfo: TDSHTTPResponse);
var
Request: String;
NextRequest: String;
RestCtxt: String;
begin
{$IFNDEF POSIX}
if CoInitFlags = -1 then
CoInitializeEx(nil, COINIT_MULTITHREADED)
else
CoInitializeEx(nil, CoInitFlags);
{$ENDIF}
try
// check for context, if not found send the appropriate error message
Request := ARequestInfo.URI;
if Consume(FDSContext, Request, NextRequest) then
begin
Request := NextRequest;
if Consume(JSON_CONTEXT, Request, NextRequest) then
begin
//json (batch execution)
DoJSONCommand(ARequestInfo, AResponseInfo, NextRequest);
end
else if Consume(TUNNEL_CONTEXT, Request, NextRequest) then
begin
//tunnel
DoTunnelCommand(AContext, ARequestInfo, AResponseInfo);
end
else if Consume(FRESTContext, Request, NextRequest) then
begin
// datasnap/rest
DoDSRESTCommand(ARequestInfo, AResponseInfo, NextRequest);
end
else if Consume(FCacheContext, Request, NextRequest) then
begin
// datasnap/cache
DoDSCacheCommand(ARequestInfo, AResponseInfo, NextRequest, FDSServerName <> EmptyStr);
end
else
begin
RestCtxt := Trim(FRESTContext);
if RestCtxt = EmptyStr then
RestCtxt := SProtocolRestEmpty;
AResponseInfo.ResponseNo := 501; {rest or other service not found in URI}
AResponseInfo.ContentText := Format(SProtocolNotSupported, [Request, RestCtxt]);
AResponseInfo.CloseConnection := true;
end;
end
else
begin
DoCommandOtherContext(AContext, ARequestInfo, AResponseInfo, Request);
end;
if Assigned(Self.FTrace ) then
begin
FTrace(Self, AContext, ARequestInfo, AResponseInfo);
end;
finally
ClearInvocationMetadata();
{$IFNDEF POSIX}
CoUnInitialize;
{$ENDIF}
end;
end;
procedure TDSHTTPServer.DoCommandOtherContext(AContext: TDSHTTPContext; ARequestInfo: TDSHTTPRequest;
AResponseInfo: TDSHTTPResponse; const ARequest: string);
begin
AResponseInfo.ResponseNo := 404; {datasnap not found}
AResponseInfo.ResponseText := Format(SInvalidDatasnapServerContext, [ARequest]);
AResponseInfo.CloseConnection := true;
end;
function TDSHTTPServer.Consume(const Prefix: string; const Context: string; out Unused: String): boolean;
var
SlashDel, StartIdx: Integer;
Ctx: String;
begin
// empty prefix is accepted
if Prefix = '' then
begin
Unused := Context;
exit(true);
end;
// find first and the second REQUEST_DELIMITER indexes
StartIdx := 1;
SlashDel := Pos(REQUEST_DELIMITER, Context);
if SlashDel = 1 then
begin
StartIdx := 2;
SlashDel := PosEx(REQUEST_DELIMITER, Context, StartIdx + 1);
end;
if SlashDel = 0 then
SlashDel := PosEx(REQUEST_PARAM_DELIMITER, Context, StartIdx + 1);
if SlashDel = 0 then
SlashDel := Length(Context) + 1;
Ctx := Decode(Copy(Context, StartIdx, SlashDel-StartIdx));
if AnsiCompareText(Prefix, Ctx) = 0 then
begin
Unused := Copy(Context, SlashDel, Length(Context)-SlashDel+1);
Result := true;
end
else
Result := false; // prefix not found
end;
{TDSHTTPServerTransport}
constructor TDSHTTPServerTransport.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDSRESTContext := REST_CONTEXT;
FDSCacheContext := CACHE_CONTEXT;
FDSContext := DATASNAP_CONTEXT;
FDSHostname := 'localhost';
FDSPort := 211;
FCredentialsPassThrough := false;
FSessionTimeout := 1200000;
FDSAuthUser := EmptyStr;
FDSAuthPassword := EmptyStr;
FResultEvent := nil;
end;
destructor TDSHTTPServerTransport.Destroy;
begin
Server := nil;
FreeAndNil(FHttpServer);
//FreeAndNil(FDSHTTPAuthenticationManager);
inherited;
end;
function TDSHTTPServerTransport.GetResultEvent: TDSRESTResultEvent;
begin
if FHttpServer <> nil then
Result := FHTTPServer.ResultEvent
else
Result := FResultEvent;
end;
procedure TDSHTTPServerTransport.SetResultEvent(const RestEvent: TDSRESTResultEvent);
begin
FResultEvent := RestEvent;
if FHttpServer <> nil then
FHTTPServer.ResultEvent := RestEvent;
end;
function TDSHTTPServerTransport.GetRESTContext;
begin
if FHttpServer <> nil then
Result := FHTTPServer.RESTContext
else
Result := FDSRestContext + '/';
end;
procedure TDSHTTPServerTransport.SetRESTContext(const Ctx: string);
begin
if (Ctx <> EmptyStr) and
(Ctx[Length(Ctx)] = '/') then
FDSRestContext := Copy(Ctx, 1, Length(Ctx)-1)
else
FDSRestContext := Ctx;
if FHttpServer <> nil then
FHTTPServer.RESTContext := Ctx;
end;
procedure TDSHTTPServerTransport.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) then
if (AComponent = Server) then
Server := nil
else if (Assigned(FHttpServer)) and (AComponent = FHttpServer.DSAuthenticationManager) then
FHttpServer.DSAuthenticationManager := nil;
if AComponent = FAuthenticationManager then
FAuthenticationManager := nil;
end;
procedure TDSHTTPServerTransport.SetTraceEvent(Event: TDSHTTPServiceTraceEvent);
begin
FTrace := Event;
if FHttpServer <> nil then
FHttpServer.FTrace := Event;
end;
function TDSHTTPServerTransport.GetTraceEvent;
begin
if FHttpServer <> nil then
Result := FHttpServer.FTrace
else
Result := FTrace;
end;
procedure TDSHTTPServerTransport.InitializeHttpServer;
begin
FHttpServer.Filters := Filters;
FHTTPServer.CredentialsPassThrough := FCredentialsPassthrough;
FHTTPServer.DSAuthUser := FDSAuthUser;
FHTTPServer.DSAuthPassword := FDSAuthPassword;
FHTTPServer.SessionTimeout := FSessionTimeout;
FHTTPServer.DSPort := FDSPort;
FHTTPServer.DSHostname := FDSHostname;
FHTTPServer.DSContext := FDSContext;
FHTTPServer.CacheContext := FDSCacheContext;
FHTTPServer.RESTContext := FDSRestContext;
FHTTPServer.ResultEvent := FResultEvent;
FHTTPServer.DSAuthenticationManager := FAuthenticationManager;
FHTTPServer.FTrace := FTrace;
UpdateDSServerName;
end;
procedure TDSHTTPServerTransport.Loaded;
begin
inherited;
// Initialize server after properties have been loaded
RequiresServer;
end;
procedure TDSHTTPServerTransport.SetAuthenticationManager(
const AuthenticationManager: TDSCustomAuthenticationManager);
begin
FAuthenticationManager := AuthenticationManager;
if FHttpServer <> nil then
FHttpServer.DSAuthenticationManager := AuthenticationManager;
end;
procedure TDSHTTPServerTransport.SetCacheContext(const Ctx: String);
begin
if (Ctx <> EmptyStr) and
(Ctx[Length(Ctx)] = '/') then
FDSCacheContext := Copy(Ctx, 1, Length(Ctx)-1)
else
FDSCacheContext := Ctx;
if FHttpServer <> nil then
FHttpServer.CacheContext := Ctx;
end;
procedure TDSHTTPServerTransport.SetDSContext(const Ctx: String);
begin
if (Ctx <> EmptyStr) and
(Ctx[Length(Ctx)] = '/') then
FDSContext := Copy(Ctx, 1, Length(Ctx)-1)
else
FDSContext := Ctx;
if FHttpServer <> nil then
FHttpServer.DSContext := Ctx;
end;
procedure TDSHTTPServerTransport.SetDSHostname(Host: String);
begin
FDSHostname := Host;
if FHttpServer <> nil then
FHttpServer.DSHostname := Host;
end;
function TDSHTTPServerTransport.GetAuthenticationManager: TDSCustomAuthenticationManager;
begin
if FHttpServer <> nil then
Result := FHttpServer.DSAuthenticationManager
else
Result := FAuthenticationManager;
end;
function TDSHTTPServerTransport.GetCacheContext: String;
begin
if FHttpServer <> nil then
Result := FHttpServer.CacheContext
else
Result := FDSCacheContext + '/';
end;
function TDSHTTPServerTransport.GetDSContext: String;
begin
if FHttpServer <> nil then
Result := FHttpServer.DSContext
else
Result := FDSContext + '/';
end;
function TDSHTTPServerTransport.GetDSHostname: String;
begin
if FHttpServer <> nil then
Result := FHttpServer.DSHostname
else
Result := FDSHostname;
end;
procedure TDSHTTPServerTransport.SetDSPort(Port: Integer);
begin
FDSPort := Port;
if FHttpServer <> nil then
FHttpServer.DSPort := Port;
end;
procedure TDSHTTPServerTransport.SetServer(const AServer: TDSCustomServer);
begin
if AServer <> Server then
begin
if Server <> nil then
Server.RemoveFreeNotification(Self);
if AServer <> nil then
AServer.FreeNotification(Self);
inherited SetServer(AServer);
if FHttpServer <> nil then
UpdateDSServerName;
end;
end;
procedure TDSHTTPServerTransport.UpdateDSServerName;
begin
if Server <> nil then
begin
FHttpServer.DSServerName := Server.Name;
FHttpServer.CreateProtocolHandlerFactory(self)
end
else
begin
FHttpServer.DSServerName := EmptyStr;
FHttpServer.ClearProtocolHandlerFactory
end;
end;
function TDSHTTPServerTransport.GetDSPort: Integer;
begin
if Assigned(FHttpServer) then
Result := FHttpServer.DSPort
else
Result := FDSPort;
end;
procedure TDSHTTPServerTransport.RequiresServer;
begin
if FHttpServer = nil then
begin
FHTTPServer := CreateHttpServer;
InitializeHttpServer;
end;
end;
function TDSHTTPServerTransport.GetHttpServer: TDSHTTPServer;
begin
RequiresServer;
// Should not create during loading process because properties of transport may determine type of http server
Assert(not (csLoading in ComponentState));
Result := FHTTPServer;
end;
procedure TDSHTTPServerTransport.SetFilters(const Value: TTransportFilterCollection);
begin
inherited SetFilters(Value);
if FHttpServer <> nil then
FHttpServer.Filters := GetFilters;
end;
procedure TDSHTTPServerTransport.ServerCloseAllTunnelSessions;
begin
// Call private method of FHttpServer
if FHttpServer <> nil then
FHttpServer.CloseAllTunnelSessions;
end;
function TDSHTTPServerTransport.GetCredentialsPassThrough: boolean;
begin
if FHttpServer <> nil then
Result := FHttpServer.CredentialsPassThrough
else
Result := FCredentialsPassThrough;
end;
function TDSHTTPServerTransport.GetDSAuthPassword: String;
begin
if FHttpServer <> nil then
Result := FHttpServer.DSAuthPassword
else
Result := FDSAuthPassword;
end;
function TDSHTTPServerTransport.GetDSAuthUser: String;
begin
if FHttpServer <> nil then
Result := FHttpServer.DSAuthUser
else
Result := FDSAuthUser;
end;
procedure TDSHTTPServerTransport.SetCredentialsPassThrough(const AFlag: boolean);
begin
FCredentialsPassThrough := AFlag;
if FHttpServer <> nil then
FHttpServer.CredentialsPassThrough := AFlag
end;
procedure TDSHTTPServerTransport.SetDSAuthPassword(const UserPassword: String);
begin
FDSAuthPassword := UserPassword;
if FHttpServer <> nil then
FHttpServer.DSAuthPassword := UserPassword
end;
procedure TDSHTTPServerTransport.SetDSAuthUser(const UserName: String);
begin
FDSAuthUser := UserName;
if FHttpServer <> nil then
FHttpServer.DSAuthUser := UserName
end;
procedure TDSHTTPServerTransport.SetSessionTimeout(const Milliseconds: Integer);
begin
FSessionTimeout := Milliseconds;
if FHttpServer <> nil then
FHttpServer.SessionTimeout := Milliseconds;
end;
function TDSHTTPServerTransport.GetSessionTimeout: Integer;
begin
if FHttpServer <> nil then
Result := FHttpServer.SessionTimeout
else
Result := FSessionTimeout
end;
function TDSHTTPServerTransport.GetIPImplementationID: string;
begin
if FHttpServer <> nil then
Result := FHttpServer.IPImplementationID
else
Result := inherited;
end;
{ TDSClientCallbackChannelManager }
procedure TDSClientCallbackChannelManager.Broadcast(Data: TJSONValue; ChannelName: String);
var
ValEnum: TEnumerator<TDSCallbackItem>;
DoForAll: Boolean;
begin
TMonitor.Enter(FLocalCallbackRepo);
try
// get the values enumerator
ValEnum := FLocalCallbackRepo.Values.GetEnumerator;
try
DoForAll := (ChannelName = '') or (FChannelName = ChannelName);
// invoke execute of each callback
while ValEnum.MoveNext do
if DoForAll or ValEnum.Current.ListeningOn(ChannelName) then
ValEnum.Current.Callback.Execute(Data).Free;
finally
ValEnum.Free;
end;
finally
TMonitor.Exit(FLocalCallbackRepo);
end;
end;
procedure TDSClientCallbackChannelManager.BroadcastObject(Data: TJSONValue; ChannelName: String);
var
ValEnum: TEnumerator<TDSCallbackItem>;
DataObj: TObject;
DoForAll: Boolean;
begin
DataObj := UnMarshalJSON(Data);
try
TMonitor.Enter(FLocalCallbackRepo);
try
// get the values enumerator
ValEnum := FLocalCallbackRepo.Values.GetEnumerator;
try
DoForAll := (ChannelName = '') or (FChannelName = ChannelName);
// invoke execute of each callback
while ValEnum.MoveNext do
if DoForAll or ValEnum.Current.ListeningOn(ChannelName) then
ValEnum.Current.Callback.Execute(DataObj).Free;
finally
ValEnum.Free;
end;
finally
TMonitor.Exit(FLocalCallbackRepo);
end
finally
DataObj.Free
end
end;
function TDSClientCallbackChannelManager.CloseClientChannel: Boolean;
var
Status : Boolean;
begin
try
//if the manager has been started, then we need to close it
if State = ctsStarted then
begin
ExecuteRemote('DSAdmin', 'CloseClientChannel',
procedure (Params: TDBXParameterList) begin
Params[0].Value.AsString := FManagerId;
Params[1].Value.AsString := FSecurityToken;
end,
procedure (Params: TDBXParameterList) begin
Status := Params[2].Value.AsBoolean;
end);
end;
Result := Status;
//If the close command is successful, clear all local callback references
if Status then
begin
FLocalCallbackRepo.Clear;
FState := ctsStopped;
FStateError := EmptyStr;
NotifyChange(TunnelClose, EmptyStr, nil);
end;
except
Result := false;
end;
end;
function TDSClientCallbackChannelManager.Copy: TDSClientCallbackChannelManager;
begin
Result := TDSClientCallbackChannelManager.Create(nil);
Result.FDSHostname := FDSHostname;
Result.FDSPort := FDSPort;
Result.FDSPath := FDSPath;
Result.FCommunicationProtocol := FCommunicationProtocol;
Result.FChannelName := FChannelName;
Result.FConnectionTimeout := FConnectionTimeout;
Result.FCommunicationTimeout := FCommunicationTimeout;
Result.FUserName := FUserName;
Result.FPassword := FPassword;
Result.FProxyHost := FProxyHost;
Result.FProxyPort := FProxyPort;
Result.FProxyUsername := FProxyUsername;
Result.FProxyPassword := FProxyPassword;
Result.OnServerConnectionTerminate := OnServerConnectionTerminate;
Result.OnServerConnectionError := OnServerConnectionError;
Result.OnChannelStateChange := OnChannelStateChange;
end;
constructor TDSClientCallbackChannelManager.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FIPImplementationID := '';
FManagerId := TDSTunnelSession.GenerateSessionId;
FLocalCallbackRepo := TObjectDictionary<String, TDSCallbackItem>.Create([doOwnsValues]);
FChannelCallback := TDSChannelCallback.Create(Invoke, InvokeObject, Broadcast, BroadcastObject);
FChannelCallback.AddRef; // take ownership
FRegConverters := TObjectDictionary<String, TConverterEvent>.Create([doOwnsValues]);
FRegReverters := TObjectDictionary<String, TReverterEvent>.Create([doOwnsValues]);
FSecurityToken := IntToStr(Random(100000)) + '.' + IntToStr(Random(100000));
FChannelManagerEvent := nil;
FState := ctsStopped;
FStateError := EmptyStr;
FProxyPort := 8888;
end;
function TDSClientCallbackChannelManager.DBXConnectionProperties(NoTimeout: boolean): TDBXDatasnapProperties;
begin
Result := TDBXDatasnapProperties.Create(nil);
Result.Values[TDBXPropertyNames.DriverName] := 'Datasnap';
Result.Values[TDBXPropertyNames.HostName] := FDSHostname;
Result.Values[TDBXPropertyNames.CommunicationProtocol] := FCommunicationProtocol;
Result.Values[TDBXPropertyNames.Port] := FDSPort;
Result.Values[TDBXPropertyNames.URLPath] := FDSPath;
Result.Values[TDBXPropertyNames.DSAuthenticationUser] := FUserName;
Result.Values[TDBXPropertyNames.DSAuthenticationPassword] := FPassword;
Result.Values[TDBXPropertyNames.DSProxyHost] := FProxyHost;
Result.Values[TDBXPropertyNames.DSProxyPort] := IntToStr(FProxyPort);
Result.Values[TDBXPropertyNames.DSProxyUsername] := FProxyUsername;
Result.Values[TDBXPropertyNames.DSProxyPassword] := FProxyPassword;
if not NoTimeout then
begin
Result.Values[TDBXPropertyNames.ConnectTimeout] := FConnectionTimeout;
Result.Values[TDBXPropertyNames.CommunicationTimeout] := FCommunicationTimeout
end
end;
destructor TDSClientCallbackChannelManager.Destroy;
begin
try
// unregister all outstanding callbacks
CloseClientChannel();
except
// igonore I/O errors at this point
end;
// free the repo
FreeAndNil( FLocalCallbackRepo );
// release the callback
FChannelCallback.Release;
FreeAndNil(FRegConverters);
FreeAndNil(FRegReverters);
inherited;
end;
procedure TDSClientCallbackChannelManager.ExecuteRemote(const AClassName,
AMethodName: String; ParamSetup, ParamCheckup: TParamSetup; NoTimeout: boolean);
var
DBXConnection: TDBXConnection;
DBXProperties: TDBXDatasnapProperties;
DBXCommand: TDBXCommand;
begin
DBXProperties := DBXConnectionProperties(NoTimeout);
try
DBXConnection := TDBXConnectionFactory.GetConnectionFactory.GetConnection(DBXProperties);
try
DBXCommand := DBXConnection.CreateCommand;
try
DBXCommand.CommandType := TDBXCommandTypes.DSServerMethod;
DBXCommand.Text := Format('%s.%s', [AClassName, AMethodName]);
DBXCommand.Prepare;
ParamSetup(DBXCommand.Parameters);
DBXCommand.ExecuteUpdate;
ParamCheckup(DBXCommand.Parameters);
finally
try
DBXCommand.Close;
except
// ignore closing exceptions
end;
DBXCommand.Free;
end;
finally
try
DBXConnection.Close;
except
// ignore it
end;
DBXConnection.Free;
end;
finally
DBXProperties.Free;
end;
end;
procedure TDSClientCallbackChannelManager.Invoke(const Id: String;
Data: TJSONValue; out Response: TJSONValue);
var
Item: TDSCallbackItem;
Callback: TDBXCallback;
ExecThread: TDSExecuteThread;
begin
TMonitor.Enter(FLocalCallbackRepo);
try
if FLocalCallbackRepo.TryGetValue(Id, Item) then
begin
Callback := Item.Callback;
try
TMonitor.Enter(Callback);
ExecThread := TDSExecuteThread.Create(Callback, Data);
if not TMonitor.Wait(Callback, 5000) then
ExecThread.Terminate;
Response := ExecThread.Response;
finally
TMonitor.Exit(Callback);
FreeAndNil(ExecThread);
end;
end
else
raise TDSServiceException.Create(Format(SNoRegisteredCallbackForId, [Id]));
finally
TMonitor.Exit(FLocalCallbackRepo);
end;
end;
procedure TDSClientCallbackChannelManager.InvokeObject(const Id: String;
Data: TJSONValue; out Response: TJSONValue);
var
Item: TDSCallbackItem;
Callback: TDBXCallback;
ResponseObj: TObject;
DataObj: TObject;
begin
DataObj := UnMarshalJSON(Data);
try
TMonitor.Enter(FLocalCallbackRepo);
try
if FLocalCallbackRepo.TryGetValue(Id, Item) then
begin
Callback := Item.Callback;
ResponseObj := Callback.Execute(DataObj);
try
Response := MarshalData(ResponseObj)
finally
ResponseObj.Free
end
end
else
raise TDSServiceException.Create(Format(SNoRegisteredCallbackForId, [Id]));
finally
TMonitor.Exit(FLocalCallbackRepo);
end;
finally
DataObj.Free;
end
end;
function TDSClientCallbackChannelManager.RegisterCallback(const ChannelNames: String;
const Callback: TDBXNamedCallback): boolean;
begin
Result := RegisterCallback(Callback.Name, ChannelNames, Callback);
end;
function TDSClientCallbackChannelManager.RegisterCallback(const CallbackId: String;
const Callback: TDBXCallback): boolean;
begin
Result := RegisterCallback(CallbackId, '', Callback);
end;
function TDSClientCallbackChannelManager.RegisterCallback(
const CallbackId, ChannelNames: String; const Callback: TDBXCallback): boolean;
var
Status: boolean;
Item, LItem: TDSCallbackItem;
begin
TMonitor.Enter(FLocalCallbackRepo);
try
if not FLocalCallbackRepo.ContainsKey(CallbackId) then
begin
Item := TDSCallbackItem.Create(FChannelName, Callback, ChannelNames);
FLocalCallbackRepo.Add(CallbackId, Item);
if FLocalCallbackRepo.Count = 1 then
begin
FState := ctsStarted;
FStateError := EmptyStr;
// start a thread if this is the first registered callback (check if there an active one)
TDSChannelThread.Create(
procedure
begin
try
ExecuteRemote('DSAdmin', 'ConnectClientChannel',
procedure (Params: TDBXParameterList)
begin
Params[0].Value.AsString := FChannelName;
Params[1].Value.AsString := FManagerId;
Params[2].Value.AsString := CallbackId;
Params[3].Value.AsString := ChannelNames;
Params[4].Value.AsString := FSecurityToken;
Params[5].Value.SetCallbackValue(FChannelCallback);
end,
procedure (Params: TDBXParameterList)
begin
end,
true);
except
on E: Exception do
begin
//remove callback, because it wasn't added successfully
FLocalCallbackRepo.Remove(CallbackId);
FState := ctsFailed;
FStateError := E.Message;
//don't pass item because we want it out of the callback repo list before sending the notification
//this is because if the person receiving the notification tries to re-create the tunnel,
//we need to be sure the tunnel repo is empty
NotifyChange(TunnelClosedByServer, CallbackId, nil);
end;
end;
end,
Self);
Status := true;
if FLocalCallbackRepo.TryGetValue(CallbackId, LItem) then
NotifyChange(TunnelCreate, CallbackId, LItem);
end
else
begin
Status := False;
ExecuteRemote('DSAdmin', 'RegisterClientCallback',
procedure (Params: TDBXParameterList) begin
Params[0].Value.AsString := FManagerId;
Params[1].Value.AsString := CallbackId;
Params[2].Value.AsString := ChannelNames;
Params[3].Value.AsString := FSecurityToken;
Params[4].Value.SetCallbackValue(FChannelCallback);
end,
procedure (Params: TDBXParameterList) begin
Status := Params[5].Value.AsBoolean;
end);
if Status then
NotifyChange(CallbackAdded, CallbackId, Item);
end;
//remove callback, because it wasn't added successfully
if not Status then
FLocalCallbackRepo.Remove(CallbackId);
Result := Status;
end
else
Result := false;
finally
TMonitor.Exit(FLocalCallbackRepo);
end;
end;
function TDSClientCallbackChannelManager.UnregisterCallback(const CallbackId: String): boolean;
var
Status: boolean;
Item: TDSCallbackItem;
begin
TMonitor.Enter(FLocalCallbackRepo);
try
if FLocalCallbackRepo.ContainsKey(CallbackId) then
begin
ExecuteRemote('DSAdmin', 'UnregisterClientCallback',
procedure (Params: TDBXParameterList) begin
Params[0].Value.AsString := FManagerId;
Params[1].Value.AsString := CallbackId;
Params[2].Value.AsString := FSecurityToken;
end,
procedure (Params: TDBXParameterList) begin
Status := Params[3].Value.AsBoolean;
end);
if Status then
begin
FLocalCallbackRepo.TryGetValue(CallbackId, Item);
//notify of removal before it happens, so client has access to the Item.
NotifyChange(CallbackRemoved, CallbackId, Item);
FLocalCallbackRepo.Remove(CallbackId);
// close the channel if no other callbacks are registered
if FLocalCallbackRepo.Count = 0 then
begin
ExecuteRemote('DSAdmin', 'CloseClientChannel',
procedure (Params: TDBXParameterList) begin
Params[0].Value.AsString := FManagerId;
Params[1].Value.AsString := FSecurityToken;
end,
procedure (Params: TDBXParameterList) begin
Status := Params[2].Value.AsBoolean;
end);
if Status then
begin
FState := ctsStopped;
FStateError := EmptyStr;
NotifyChange(TunnelClose, CallbackId, nil);
end;
end;
end;
Result := Status;
end
else
Result := false
finally
TMonitor.Exit(FLocalCallbackRepo);
end;
end;
function TDSClientCallbackChannelManager.BroadcastToChannel(const Msg: TJSONValue;
ChannelName: String): boolean;
var
Status: boolean;
begin
if ChannelName = EmptyStr then
ChannelName := FChannelName;
Status := false;
ExecuteRemote('DSAdmin', 'BroadcastToChannel',
procedure (Params: TDBXParameterList) begin
Params[0].Value.AsString := ChannelName;
Params[1].Value.SetJSONValue(Msg, True);
end,
procedure (Params: TDBXParameterList) begin
Status := Params[2].Value.AsBoolean;
end);
Result := Status;
end;
function TDSClientCallbackChannelManager.BroadcastObjectToChannel(const Msg: TObject; ChannelName: String): boolean;
var
Status: boolean;
begin
if ChannelName = EmptyStr then
ChannelName := FChannelName;
Status := false;
ExecuteRemote('DSAdmin', 'BroadcastObjectToChannel',
procedure (Params: TDBXParameterList) begin
Params[0].Value.AsString := ChannelName;
Params[1].Value.SetJSONValue(MarshalData(Msg), True);
Msg.Free
end,
procedure (Params: TDBXParameterList) begin
Status := Params[2].Value.AsBoolean;
end);
Result := Status;
end;
function TDSClientCallbackChannelManager.NotifyCallback(const CallbackId, ManagerId: String; const Msg: TJSONValue;
out Response: TJSONValue): boolean;
var
Status: boolean;
Resp: TJSONValue;
begin
Status := false;
ExecuteRemote('DSAdmin', 'NotifyCallback',
procedure (Params: TDBXParameterList) begin
Params[0].Value.AsString := ManagerId;
Params[1].Value.AsString := CallbackId;
Params[2].Value.SetJSONValue(Msg, True);
end,
procedure (Params: TDBXParameterList) begin
Resp := Params[3].Value.GetJSONValue;
Status := Params[4].Value.AsBoolean;
end);
Response := Resp;
Result := Status;
end;
procedure TDSClientCallbackChannelManager.NotifyChange(EventType: TDSCallbackTunnelEventType;
const CallbackId: String;
Item: TDSCallbackItem);
var
Event: TDSClientChannelEventItem;
begin
//If the tunnel is stopped and the event isn't a tunnel create, then ignore it.
if FStopped and (EventType <> TunnelCreate) then
Exit;
//if the current event is a stop event, then mark the channel as stopped
FStopped := (EventType = TunnelClose) or (EventType = TunnelClosedByServer);
if Assigned(FChannelManagerEvent) then
begin
Event.EventType := EventType;
Event.TunnelId := FManagerId;
Event.Tunnel := Self;
Event.TunnelChannelName := FChannelName;
Event.CallbackId := CallbackId;
Event.CallbackItem := Item;
try
FChannelManagerEvent(Self, Event);
except
end;
end;
end;
function TDSClientCallbackChannelManager.NotifyObjectCallback(const CallbackId, ManagerId: String; const Msg: TObject;
out Response: TObject): boolean;
var
Status: boolean;
Resp: TJSONValue;
begin
Status := false;
try
ExecuteRemote('DSAdmin', 'NotifyObject',
procedure (Params: TDBXParameterList) begin
Params[0].Value.AsString := ManagerId;
Params[1].Value.AsString := CallbackId;
Params[2].Value.SetJSONValue(MarshalData(Msg), True);
Msg.Free;
end,
procedure (Params: TDBXParameterList) begin
Resp := Params[3].Value.GetJSONValue;
Status := Params[4].Value.AsBoolean;
end);
Response := UnMarshalJSON(Resp);
finally
Resp.Free
end;
Result := Status;
end;
function TDSClientCallbackChannelManager.GetCallbackIds: TArray<String>;
begin
if FLocalCallbackRepo <> nil then
Result := FLocalCallbackRepo.Keys.ToArray
else
Result := nil;
end;
function TDSClientCallbackChannelManager.GetCallbackItem(const CallbackId: String;
out Item: TDSCallbackItem): boolean;
begin
Result := False;
Item := nil;
if (FLocalCallbackRepo <> nil) and FLocalCallbackRepo.TryGetValue(CallbackId, Item) then
Exit(True);
end;
function TDSClientCallbackChannelManager.GetIPImplementationID: string;
begin
Result := FIPImplementationID;
end;
function TDSClientCallbackChannelManager.GetJSONMarshaler: TJSONMarshal;
begin
// Get marshaller with registered converters
Result := TJSONConverters.GetJSONMarshaler;
end;
function TDSClientCallbackChannelManager.GetJSONUnMarshaler: TJSONUnMarshal;
begin
// Get unmarshaller with registered reverters
Result := TJSONConverters.GetJSONUnMarshaler;
end;
procedure TDSClientCallbackChannelManager.AddConverter(event: TConverterEvent);
begin
FRegConverters.Add(TJSONMarshal.ComposeKey(event.FieldClassType, event.FieldName), event);
end;
procedure TDSClientCallbackChannelManager.AddReverter(event: TReverterEvent);
begin
FRegReverters.Add(TJSONMarshal.ComposeKey(event.FieldClassType, event.FieldName), event);
end;
function TDSClientCallbackChannelManager.MarshalData(Data: TObject): TJSONValue;
var
marshal: TJSONMarshal;
begin
marshal := GetJSONMarshaler;
try
Result := marshal.Marshal(Data);
finally
marshal.Free;
end;
end;
function TDSClientCallbackChannelManager.UnMarshalJSON(Data: TJSONValue): TObject;
var
unmarshal: TJSONUnMarshal;
begin
unmarshal := GetJSONUnMarshaler;
try
Result := unmarshal.UnMarshal(Data);
finally
unmarshal.Free;
end;
end;
function TDSClientCallbackChannelManager.RegisterCallback(const Callback: TDBXNamedCallback): boolean;
begin
Result := RegisterCallback('', Callback);
end;
procedure TDSClientCallbackChannelManager.SetIPImplementationID(
const AIPImplementationID: string);
begin
FIPImplementationID := AIPImplementationID;
end;
{ TDSClientCallbackChannelManager.TDSChannelCallback }
constructor TDSClientCallbackChannelManager.TDSChannelCallback.Create(
const InvokeEvent: TDSChannelInvokeEvent;
const InvokeObjectEvent: TDSChannelInvokeEvent;
const BroadcastEvent: TDSChannelBroadcastEvent;
const BroadcastObjectEvent: TDSChannelBroadcastEvent);
begin
FInvokeEvent := InvokeEvent;
FInvokeObjectEvent := InvokeObjectEvent;
FBroadcastEvent := BroadcastEvent;
FBroadcastObjectEvent := BroadcastObjectEvent;
end;
destructor TDSClientCallbackChannelManager.TDSChannelCallback.Destroy;
begin
inherited;
end;
function TDSClientCallbackChannelManager.TDSChannelCallback.Execute(
const Arg: TJSONValue): TJSONValue;
var
Data: TJSONObject;
Cmd: TJSONPair;
ChannelPair: TJSONPair;
ArgType: Integer;
ChannelName: String;
begin
if not (Arg is TJSONObject) then
raise TDSServiceException.Create(SJSONValueNotObject);
Data := TJSONObject(Arg);
Cmd := Data.Get('invoke');
if Cmd = nil then
Cmd := Data.Get('broadcast');
ChannelPair := Data.Get('channel');
if (Cmd <> nil) and (AnsiCompareText('invoke', Cmd.JsonString.Value) = 0) then
begin
ArgType := ((Cmd.JsonValue as TJSONArray).Get(2) as TJSONNumber).AsInt;
if ArgType = TDBXCallback.ArgObject then
FInvokeObjectEvent((Cmd.JsonValue as TJSONArray).Get(0).Value, (Cmd.JsonValue as TJSONArray).Get(1),
Result)
else
FInvokeEvent((Cmd.JsonValue as TJSONArray).Get(0).Value, (Cmd.JsonValue as TJSONArray).Get(1),
Result);
end
else if (Cmd <> nil) and (AnsiCompareText('broadcast', Cmd.JsonString.Value) = 0) then
begin
//get the value of 'channel' if there is one, and pass it into the broadcast event
if ChannelPair <> nil then
ChannelName := ChannelPair.JsonValue.Value;
ArgType := ((Cmd.JsonValue as TJSONArray).Get(1) as TJSONNumber).AsInt;
if ArgType = TDBXCallback.ArgObject then
FBroadcastObjectEvent((Cmd.JsonValue as TJSONArray).Get(0), ChannelName)
else
FBroadcastEvent((Cmd.JsonValue as TJSONArray).Get(0), ChannelName);
Result := TJSONTrue.Create;
end
else
raise TDSServiceException.Create(Format(SCommandNotImplemented, [Cmd.JsonString]));
end;
{ TDSClientCallbackChannelManager.TDSChannelThread }
constructor TDSClientCallbackChannelManager.TDSChannelThread.Create(
Worker: TDSWorker; Manager: TDSClientCallbackChannelManager);
begin
FWorker := Worker;
FManager := Manager;
FreeOnTerminate := true;
inherited Create(false);
end;
destructor TDSClientCallbackChannelManager.TDSChannelThread.Destroy;
begin
try
if FManager <> nil then
FManager.NotifyChange(TunnelClosedByServer, EmptyStr, nil);
finally
inherited;
end;
end;
procedure TDSClientCallbackChannelManager.TDSChannelThread.Execute;
begin
try
FWorker
finally
end;
end;
{ TDSDefaultResponseHandler }
procedure TDSDefaultResponseHandler.Close;
var
Session: TDSSession;
begin
//cache the Handler, so the stream isn't killed before the response is sent
if FStoreHandler then
begin
Session := TDSSessionManager.Instance.GetThreadSession;
if Session = nil then
Raise TDSServiceException.Create(SNoSessionFound);
if Session.LastResultStream <> nil then
begin
Session.LastResultStream.Free;
Session.LastResultStream := nil;
end;
Session.LastResultStream := Self;
end
else
Free;
end;
constructor TDSDefaultResponseHandler.Create(AllowBinaryStream: boolean; DSService: TDSService;
CommandType: TDSHTTPCommandType; ServiceInstanceOwner: Boolean);
begin
inherited Create(CommandType, DSService, ServiceInstanceOwner);
FStoreHandler := False;
FDSService := DSService;
end;
destructor TDSDefaultResponseHandler.Destroy;
begin
ClearCommands();
inherited;
end;
function TDSDefaultResponseHandler.HandleParameter(const Command: TDBXCommand;
const Parameter: TDBXParameter; out Response: TJSONValue; var ResponseStream: TStream): Boolean;
begin
{If there is only one output/return parameter and it is a Stream, return it as a stream}
if (not FDSService.StreamAsJSON) and FAllowStream and
(Parameter.DataType = TDBXDataTypes.BinaryBlobType) then
begin
//if FAllowStream is true there should be no case where we are
//setting a value for stream when it already has a value
Assert(ResponseStream = nil);
ResponseStream := Parameter.Value.GetStream(True);
if ResponseStream <> nil then
begin
//set this object to store itself in the Session, to be freed later,
//after the stream it holds is no longer required by the REST response sent to the client.
FStoreHandler := True;
end
else
Response := TJSONNull.Create;
exit(True);
end;
Result := False;
end;
procedure TDSDefaultResponseHandler.PopulateContent(ResponseInfo: TDSHTTPResponse; Response: TJSONValue;
ResponseStream: TStream);
begin
if (ResponseStream = nil) and Assigned(Response) then
ResponseInfo.ContentText := StringOf(ByteContent(Response))
else if (ResponseStream <> nil) then
begin
ResponseInfo.ContentStream := ResponseStream;
ResponseInfo.FreeContentStream := False;
end;
end;
{ TDSResponseHandlerFactory }
class function TDSResponseHandlerFactory.CreateResponseHandler(DSService: TDSService;
RequestInfo: TDSHTTPRequest; CommandType: TDSHTTPCommandType;
HTTPServer: TDSHTTPServer): TDSServiceResponseHandler;
var
Accept: String;
begin
if RequestInfo <> nil then
Accept := RequestInfo.Accept;
if (CommandType = hcUnknown) and (RequestInfo <> nil) then
CommandType := RequestInfo.CommandType;
if RequestInfo = nil then
Result := TDSNullResponseHandler.Create(DSService, CommandType)
else if (AnsiContainsStr(Accept, 'application/rest')) then
Result := TDSCacheResponseHandler.Create(DSService, CommandType)
else
begin
Result := TDSDefaultResponseHandler.Create(not DSService.StreamAsJSON, DSService, CommandType);
if Assigned(HTTPServer) and Assigned(HTTPServer.ResultEvent) then
TDSDefaultResponseHandler(Result).ResultEvent := HTTPServer.ResultEvent;
end;
end;
{ TDSServiceResponseHandler }
constructor TDSServiceResponseHandler.Create(CommandType: TDSHTTPCommandType; LocalConnection: Boolean);
begin
FCommandType := CommandType;
FCommandList := TList<TDSExecutionResponse>.Create;
FLocalConnection := LocalConnection;
ForceResultArray := False;
end;
destructor TDSServiceResponseHandler.Destroy;
begin
try
ClearCommands();
try
FreeAndNil(FCommandList);
except
end;
finally
inherited;
end;
end;
function TDSServiceResponseHandler.GetOKStatus: Integer;
begin
case FCommandType of
hcGET, hcDELETE, hcPOST: Result := 200;
hcPUT: Result := 201;
else
Result := 501;
end;
end;
function TDSServiceResponseHandler.GetResultCount: Integer;
var
CommandWrapper: TDSExecutionResponse;
Command: TDBXCommand;
Count: Integer;
ParamDirection: TDBXParameterDirection;
I: Integer;
begin
Count := 0;
TMonitor.Enter(FCommandList);
try
for CommandWrapper in FCommandList do
begin
if CommandWrapper.Command = nil then
Inc(Count)
else
begin
Command := CommandWrapper.Command;
for I := 0 to Command.Parameters.Count - 1 do
begin
// select the output and return parameters for the response
ParamDirection := Command.Parameters[I].ParameterDirection;
if (ParamDirection = TDBXParameterDirections.OutParameter) or
(ParamDirection = TDBXParameterDirections.InOutParameter) or
(ParamDirection = TDBXParameterDirections.ReturnParameter) then
begin
Inc(Count);
end;
end;
end;
end;
finally
TMonitor.Exit(FCommandList);
Result := Count;
end;
end;
procedure TDSServiceResponseHandler.AddCommand(Command: TDBXCommand; DBXConnection: TDBXConnection);
begin
if (Command <> nil) and (DBXConnection <> nil) then
begin
TMonitor.Enter(FCommandList);
try
FCommandList.Add(TDSExecutionResponse.Create(Command, DBXConnection, FLocalConnection));
finally
TMonitor.Exit(FCommandList);
end;
end;
end;
procedure TDSServiceResponseHandler.ClearCommands;
var
Command: TDSExecutionResponse;
begin
TMonitor.Enter(FCommandList);
try
for Command in FCommandList do
begin
Command.Free;
end;
FCommandList.Clear;
finally
TMonitor.Exit(FCommandList);
end;
end;
procedure TDSServiceResponseHandler.AddCommandError(ErrorMessage: String);
begin
if (ErrorMessage <> '') then
begin
TMonitor.Enter(FCommandList);
try
FCommandList.Add(TDSExecutionResponse.create(ErrorMessage));
finally
TMonitor.Exit(FCommandList);
end;
end;
end;
function TDSServiceResponseHandler.ByteContent(JsonValue: TJSONValue): TBytes;
var
Buffer: TBytes;
begin
if Assigned(JsonValue) then
begin
SetLength(Buffer, JsonValue.EstimatedByteSize);
SetLength(Buffer, JsonValue.ToBytes(Buffer, 0));
end;
Result := Buffer;
end;
{ TDSExecutionResponse }
constructor TDSExecutionResponse.Create(Command: TDBXCommand; DBXConnection: TDBXConnection;
LocalConnection: boolean);
begin
FCommand := Command;
FDBXConnection := DBXConnection;
FLocalConnection := LocalConnection;
FErrorMessage := '';
end;
constructor TDSExecutionResponse.Create(ErrorMessage: String);
begin
FCommand := nil;
FDBXConnection := nil;
FErrorMessage := ErrorMessage;
end;
destructor TDSExecutionResponse.Destroy;
begin
if FCommand <> nil then
FCommand.Close;
if FDBXConnection <> nil then
FDBXConnection.Close;
FCommand.Free;
if FLocalConnection and (FDBXConnection <> nil) then
TDSServerConnection(FDBXConnection).ServerConnectionHandler.Free
else
FDBXConnection.Free;
inherited;
end;
{ TDSCacheResponseHandler }
constructor TDSCacheResponseHandler.Create(DSService: TDSService; CommandType: TDSHTTPCommandType;
ServiceInstanceOwner: Boolean);
begin
Inherited Create(CommandType, DSService, ServiceInstanceOwner);
FCacheId := -1;
end;
destructor TDSCacheResponseHandler.Destroy;
begin
inherited;
end;
function TDSCacheResponseHandler.GetCacheObject: TDSCacheResultCommandHandler;
begin
if (FResultHandler = nil) then
FResultHandler := TDSCacheResultCommandHandler.Create(Self);
Result := FResultHandler;
end;
function TDSCacheResponseHandler.GetComplexParams(Command: TDBXCommand; out Index: Integer;
AddIfNotFound: Boolean): TDSCommandComplexParams;
var
CP: TDSCommandComplexParams;
I: Integer;
begin
Result := nil;
Index := -1;
for I := 0 to GetCacheObject.CacheCommands.Count - 1 do
begin
CP := GetCacheObject.CacheCommands[I];
if CP.Command = Command then
begin
Index := I;
Exit(CP);
end;
end;
if AddIfNotFound then
begin
Index := GetCacheObject.CacheCommands.Count;
CP := TDSCommandComplexParams.Create(Command);
GetCacheObject.CacheCommands.Add(CP);
Result := CP;
end;
end;
procedure TDSCacheResponseHandler.Close;
begin
//If FCacheId is not specified then this object isn't stored in the Session Cache, so should be freed here.
if FCacheId = -1 then
Free;
end;
function TDSCacheResponseHandler.HandleParameter(const Command: TDBXCommand; const Parameter: TDBXParameter;
out Response: TJSONValue; var ResponseStream: TStream): Boolean;
var
CP: TDSCommandComplexParams;
DataType: Integer;
CommandIndex: Integer;
ParameterIndex: Integer;
Session: TDSSession;
Cache: TDSSessionCache;
UrlString: UnicodeString;
begin
Result := False;
Session := TDSSessionManager.GetThreadSession;
if (Session <> nil) and (Parameter <> nil) then
begin
DataType := Parameter.DataType;
if ((DataType = TDBXDataTypes.TableType) or
(DataType = TDBXDataTypes.ObjectType) or
((DataType = TDBXDataTypes.JsonValueType) and
(SameText(Parameter.TypeName, 'TJSONArray') or SameText(Parameter.TypeName, 'TJSONValue') or (SameText(Parameter.TypeName, 'TJSONObject') or
(not SameText(Copy(Parameter.TypeName,0+1,5-(0)), 'TJSON'))))) or
(DataType = TDBXDataTypes.BlobType) or
(DataType = TDBXDataTypes.BinaryBlobType)) then
begin
CP := GetComplexParams(Command, CommandIndex);
if (CP <> nil) then
begin
ParameterIndex := CP.AddParameter(Parameter);
Cache := Session.ParameterCache;
if (Cache <> nil) and (ParameterIndex > -1) then
begin
if FCacheId = -1 then
FCacheId := Cache.AddItem(GetCacheObject());
if FCacheId > -1 then
begin
Result := True;
UrlString := (IntToStr(FCacheId) + '/' + IntToStr(CommandIndex) + '/' + IntToStr(ParameterIndex));
Response := TJSONString.Create(UrlString);
end;
end;
end;
end;
end;
end;
procedure TDSCacheResponseHandler.PopulateContent(ResponseInfo: TDSHTTPResponse; Response: TJSONValue;
ResponseStream: TStream);
begin
//ResponseStream should NEVER be assigned in this case,
//as any streams should instead be stored in the session cache
Assert(ResponseStream = nil);
if Response <> nil then
begin
ResponseInfo.ContentText := StringOf(ByteContent(Response));
ResponseInfo.ContentType := 'application/rest';
end;
end;
procedure TDSCacheResponseHandler.ProcessResultObject(var ResultObj: TJSONObject; Command: TDBXCommand);
var
CommandIndex: Integer;
begin
if (ResultObj <> nil) and (FResultHandler <> nil) and
(FResultHandler.CacheCommands.Count > 0) and (FCacheId > -1) then
begin
GetComplexParams(Command, CommandIndex, False);
//Add to the result object two key/value pairs: cacheId and cmdIndex.
//These can later be used to construct URLs into different levels of the Session Parameter cache
if (CommandIndex > -1) then
begin
ResultObj.AddPair(TJSONPair.Create('cacheId', TJSONNumber.Create(FCacheId)));
ResultObj.AddPair(TJSONPair.Create('cmdIndex', TJSONNumber.Create(CommandIndex)));
end;
end;
end;
{ TDSJsonResponseHandler }
constructor TDSJsonResponseHandler.Create(CommandType: TDSHTTPCommandType; DSService: TDSService;
ServiceInstanceOwner: Boolean);
begin
if not Assigned(DSService) then
Raise TDSServiceException.Create(SRESTServiceMissing);
inherited Create(CommandType, DSService.LocalConnection);
FDSService := DSService;
FServiceInstanceOwner := ServiceInstanceOwner;
end;
destructor TDSJsonResponseHandler.Destroy;
begin
if FServiceInstanceOwner then
FreeAndNil(FDSService);
inherited;
end;
procedure TDSJsonResponseHandler.GetCommandResponse(Command: TDBXCommand; out Response: TJSONValue;
out ResponseStream: TStream);
var
JsonParams: TJSONArray;
JsonParam: TJSONValue;
I: Integer;
ParamDirection: TDBXParameterDirection;
OwnParams: boolean;
ConvList: TObjectList<TDBXRequestFilter>;
ResponseObj: TJSONObject;
Handled: boolean;
begin
JsonParams := nil;
OwnParams := false;
ConvList := nil;
ResponseStream := nil;
Handled := False;
try
// collect the output/return parameters
JsonParams := TJSONArray.Create;
OwnParams := true;
ConvList := TObjectList<TDBXRequestFilter>.Create(false);
for I := 0 to Command.Parameters.Count - 1 do
begin
// select the output and return parameters for the response
ParamDirection := Command.Parameters[I].ParameterDirection;
if (ParamDirection = TDBXParameterDirections.OutParameter) or
(ParamDirection = TDBXParameterDirections.InOutParameter) or
(ParamDirection = TDBXParameterDirections.ReturnParameter) then
begin
JsonParam := nil;
ConvList.Clear;
{If a subclass doesn't handle the parameter themselves, then manage the parameter by either
applying a filter on the result, or passing back the pure JSON representation}
if not HandleParameter(Command, Command.Parameters[I], JsonParam, ResponseStream) then
begin
FDSService.FiltersForCriteria([I], I = Command.Parameters.Count - 1, ConvList);
if ConvList.Count = 1 then
begin
if not ConvList.Items[0].CanConvert(Command.Parameters[I].Value) then
Raise TDSServiceException.Create(Format(SCannotConvertParam, [I, ConvList.Items[0].Name]));
JsonParam := ConvList.Items[0].ToJSON(Command.Parameters[I].Value, FDSService.LocalConnection);
end
else
begin
JsonParam := TDBXJSONTools.DBXToJSON(Command.Parameters[I].Value,
Command.Parameters[I].DataType, FDSService.LocalConnection);
end;
end;
if JsonParam <> nil then
JsonParams.AddElement(JsonParam);
end;
end;
//Store the result array as a JSON Value, to make it more generic for the event and result object
JsonParam := JsonParams;
if Assigned(FResultEvent) then
FResultEvent(Self, JsonParam, Command, Handled);
if not Handled then
begin
ResponseObj := TJSONObject.Create(TJSONPair.Create(TJSONString.Create('result'), JsonParam));
//allow subclasses to add to the result object if they wish
ProcessResultObject(ResponseObj, Command);
Response := ResponseObj;
end
else
Response := JsonParam;
OwnParams := false;
finally
FreeAndNil(ConvList);
if OwnParams then
JsonParams.Free;
end;
end;
procedure TDSJsonResponseHandler.GetResponse(out Response: TJSONValue; out ResponseStream: TStream; out ContainsErrors: Boolean);
var
CommandWrapper: TDSExecutionResponse;
Command: TDBXCommand;
SubResponse: TJSONValue;
ResultArr: TJSONArray;
ErrObj: TJSONObject;
begin
ContainsErrors := false;
ResponseStream := nil;
ResultArr := nil;
if ForceResultArray or (FCommandList.Count > 1) then
begin
ResultArr := TJSONArray.Create;
end;
try
for CommandWrapper in FCommandList do
begin
//handle error message
if CommandWrapper.Command = nil then
begin
ContainsErrors := True;
ErrObj := TJSONObject.Create;
ErrObj.AddPair(TJSONPair.Create(CMD_ERROR, CommandWrapper.ErrorMessage));
if ResultArr <> nil then
begin
ResultArr.AddElement(ErrObj);
end
else
begin
Response := ErrObj;
//there is only one command if ResultArr is nil but break here anyway just to be clear
break;
end;
end
//handle DBXCommand with results populated
else
begin
SubResponse := nil;
Command := CommandWrapper.Command;
try
GetCommandResponse(Command, SubResponse, ResponseStream);
except on E: Exception do
begin
ContainsErrors := True;
SubResponse := TJSONString.Create(E.Message);
end;
end;
if ResponseStream <> nil then
begin
//ignore the content returned and free it, because the response content will be a stream
FreeAndNil(SubResponse);
end
else
begin
if ResultArr <> nil then
begin
if SubResponse <> nil then
ResultArr.AddElement(SubResponse);
end
else
begin
Response := SubResponse;
//there is only one command if ResultArr is nil but break here anyway just to be clear
break;
end;
end;
end;
end;
finally
if (ResponseStream = nil) and (ResultArr <> nil) then
begin
Response := ResultArr;
end
else
begin
ResultArr.Free;
end;
end;
end;
procedure TDSJsonResponseHandler.PopulateResponse(ResponseInfo: TDSHTTPResponse;
InvokeMetadata: TDSInvocationMetadata);
var
JsonResponse: TJSONValue;
ResponseStream: TStream;
ContainsErrors: Boolean;
begin
JsonResponse := nil;
ContainsErrors := False;
FAllowStream := (GetResultCount = 1);
if (not Assigned(FCommandList)) or (FCommandList.Count = 0) then
Raise TDSServiceException.Create(SCommandUnassigned);
try
//only parse the Command for output if no content is specified in the invocation metadata
if (InvokeMetadata <> nil) and (InvokeMetadata.ResponseContent <> '') then
begin
if (InvokeMetadata.ResponseContent = ' ') then
InvokeMetadata.ResponseContent := '';
ResponseInfo.ContentText := InvokeMetadata.ResponseContent;
ResponseInfo.ContentLength := Length(ResponseInfo.ContentText);
end
else
begin
GetResponse(JsonResponse, ResponseStream, ContainsErrors);
PopulateContent(ResponseInfo, JsonResponse, ResponseStream);
end;
if (InvokeMetadata <> nil) and (InvokeMetadata.ResponseCode <> 0) then
ResponseInfo.ResponseNo := InvokeMetadata.ResponseCode
else if ContainsErrors then
ResponseInfo.ResponseNo := 500
else
ResponseInfo.ResponseNo := GetOKStatus;
if (InvokeMetadata <> nil) and (InvokeMetadata.ResponseMessage <> '') then
ResponseInfo.ResponseText := InvokeMetadata.ResponseMessage;
if (InvokeMetadata <> nil) and (InvokeMetadata.ResponseContentType <> '') then
ResponseInfo.ContentType := InvokeMetadata.ResponseContentType;
finally
FreeAndNil(JsonResponse);
end;
end;
procedure TDSJsonResponseHandler.ProcessResultObject(var ResultObj: TJSONObject; Command: TDBXCommand);
begin
//default implementation does nothing
end;
{ TDSCommandComplexParams }
constructor TDSCommandComplexParams.Create(Command: TDBXCommand);
begin
if Command = nil then
Raise TDSServiceException.Create(SCommandUnassigned);
FCommand := Command;
FParameters := TList<TDBXParameter>.Create;
end;
destructor TDSCommandComplexParams.Destroy;
begin
//Parameters in the list are managed by externally
FParameters.Clear;
FreeAndNil(FParameters);
inherited;
end;
function TDSCommandComplexParams.AddParameter(Parameter: TDBXParameter): Integer;
begin
Result := FParameters.Count;
FParameters.Add(Parameter);
end;
function TDSCommandComplexParams.GetParameter(Index: Integer): TDBXParameter;
begin
if (Index > -1) and (Index < FParameters.Count) then
begin
Result := FParameters[Index];
end
else
Exit(nil);
end;
function TDSCommandComplexParams.GetParameterCount: Integer;
begin
Result := FParameters.Count;
end;
{ TDSCacheResultCommandHandler }
constructor TDSCacheResultCommandHandler.Create(CommandWrapper: TRequestCommandHandler);
begin
Assert(CommandWrapper <> nil);
FCommandWrapper := CommandWrapper;
FCacheCommands := TList<TDSCommandComplexParams>.Create;
end;
destructor TDSCacheResultCommandHandler.Destroy;
var
CP: TDSCommandComplexParams;
begin
for CP in FCacheCommands do
CP.Free;
FCacheCommands.Clear;
FreeAndNil(FCacheCommands);
FreeAndNil(FCommandWrapper);
inherited;
end;
function TDSCacheResultCommandHandler.GetCommand(Index: Integer): TDBXCommand;
begin
if (Index > -1) and (Index < GetCommandCount) then
Exit(FCacheCommands[Index].Command)
else
Exit(nil);
end;
function TDSCacheResultCommandHandler.GetCommandCount: Integer;
begin
Result := FCacheCommands.Count;
end;
function TDSCacheResultCommandHandler.GetCommandParameter(Command: TDBXCommand; Index: Integer): TDBXParameter;
var
Ccp: TDSCommandComplexParams;
begin
Result := nil;
if (Command <> nil) and (Index > -1) then
begin
//Search for the ComplexParams item wrapping the given Command
for Ccp in FCacheCommands do
begin
//Command cound, break the loop, regardless of if parameter is found or not
if Ccp.Command = Command then
begin
if Index < Ccp.GetParameterCount then
begin
Exit(Ccp.GetParameter(Index));
end;
Break;
end;
end;
end;
end;
function TDSCacheResultCommandHandler.GetCommandParameter(CommandIndex, ParameterIndex: Integer): TDBXParameter;
var
PList: TDSCommandComplexParams;
begin
if (CommandIndex > -1) and (CommandIndex < GetCommandCount) then
begin
PList := FCacheCommands[CommandIndex];
Exit(PList.GetParameter(ParameterIndex));
end;
Exit(nil);
end;
function TDSCacheResultCommandHandler.GetParameterCount(Index: Integer): Integer;
begin
if GetCommand(Index) <> nil then
begin
Exit(FCacheCommands[Index].GetParameterCount);
end;
Exit(0);
end;
{ TDSHTTPCacheContextService }
constructor TDSHTTPCacheContextService.Create(Session: TDSSession; LocalConnection: Boolean);
begin
Assert(Session <> nil);
inherited Create;
FSession := Session;
FLocalConnection := LocalConnection;
end;
function TDSHTTPCacheContextService.ParseRequst(Request: String; out CacheId, CommandIndex,
ParameterIndex: Integer): Boolean;
var
SlashLeft, SlashRight, SlashAux: Integer;
begin
CacheId := -1;
CommandIndex := -1;
ParameterIndex := -1;
Result := True;
SlashLeft := Pos(REQUEST_DELIMITER, Request);
if SlashLeft = 0 then
begin
//the user is interested in the cache as a whole, and not any specific object
Exit(True);
end;
if SlashLeft > 1 then
begin
// first / is missing
SlashRight := SlashLeft;
SlashLeft := 1;
end
else
begin
SlashRight := PosEx(REQUEST_DELIMITER, Request, SlashLeft+1);
end;
SlashAux := SlashRight;
if SlashAux < 1 then
SlashAux := Length(Request) + 1;
if SlashAux > (SlashLeft + 1) then
begin
try
CacheId := StrToInt(Copy(Request, Slashleft+1, SlashAux-SlashLeft-1));
except
Exit(False);
end;
if SlashRight = SlashAux then
begin
SlashAux := PosEx(REQUEST_DELIMITER, Request, SlashRight+1);
SlashLeft := SlashRight;
SlashRight := SlashAux;
if SlashAux < SlashLeft then
SlashAux := Length(Request) + 1;
if SlashAux > (SlashLeft + 1) then
begin
try
CommandIndex := StrToInt(Copy(Request, Slashleft+1, SlashAux-SlashLeft-1));
except
Exit(False);
end;
if SlashRight = SlashAux then
begin
SlashAux := PosEx(REQUEST_DELIMITER, Request, SlashRight+1);
SlashLeft := SlashRight;
if SlashAux < SlashLeft then
SlashAux := Length(Request) + 1;
if SlashAux > (SlashLeft + 1) then
begin
try
ParameterIndex := StrToInt(Copy(Request, Slashleft+1, SlashAux-SlashLeft-1));
except
Exit(False);
end;
end;
end;
end;
end;
end;
end;
procedure TDSHTTPCacheContextService.GetCacheContents(out Value: TJSONValue);
var
Ids: TList<Integer>;
Key: Integer;
Aux: TJSONValue;
begin
Value := TJSONObject.Create;
Ids := FSession.ParameterCache.GetItemIDs;
for Key in Ids do
begin
GetCacheItemContents(Key, Aux);
TJSONObject(Value).AddPair(TJSONPair.Create(IntToStr(Key), Aux));
end;
FreeAndNil(Ids);
end;
procedure TDSHTTPCacheContextService.GetCacheItemContents(const CacheId: Integer; out Value: TJSONValue);
var
Item: TResultCommandHandler;
CmdArray: TJSONArray;
Aux: TJSONValue;
I: Integer;
begin
Item := FSession.ParameterCache.GetItem(CacheId);
if Item = nil then
begin
Value := TJSONNull.Create;
Exit;
end;
CmdArray := TJSONArray.Create;
for I := 0 to Item.GetCommandCount - 1 do
begin
Aux := nil;
GetCommandContents(CacheId, I, Aux);
if Aux <> nil then
CmdArray.Add(TJSONObject(Aux));
end;
Value := TJSONObject.Create;
TJSONObject(Value).AddPair(TJSONPair.Create('commands', CmdArray));
end;
procedure TDSHTTPCacheContextService.GetCommandContents(const CacheId: Integer; const CommandIndex: Integer;
out Value: TJSONValue);
var
Item: TResultCommandHandler;
Param: TDBXParameter;
TypeNames: TJSONArray;
Count: Integer;
I: Integer;
begin
Item := FSession.ParameterCache.GetItem(CacheId);
if Item = nil then
begin
Value := TJSONNull.Create;
Exit;
end;
Count := Item.GetParameterCount(CommandIndex);
Value := TJSONObject.Create;
TypeNames := TJSONArray.Create;
for I := 0 to Count - 1 do
begin
Param := Item.GetCommandParameter(CommandIndex, I);
TypeNames.Add(Param.Name);
end;
TJSONObject(Value).AddPair(TJSONPair.Create('parameters', TypeNames));
end;
function TDSHTTPCacheContextService.GetOriginalParamIndex(const Command: TDBXCommand;
const Parameter: TDBXParameter): Integer;
var
I: Integer;
begin
Result := -1;
if (Command <> nil) and (Parameter <> nil) then
begin
for I := 0 to Command.Parameters.Count - 1 do
begin
if Command.Parameters[I] = Parameter then
Exit(I);
end;
end;
end;
procedure TDSHTTPCacheContextService.InvalidRequest(Response: TDSHTTPResponse; Request: String);
begin
if Response <> nil then
begin
Response.ResponseNo := 400; //Bad Request
Response.ResponseText := Format(SInvalidRequest, [Request]);
Response.CloseConnection := true;
end;
end;
procedure TDSHTTPCacheContextService.ProcessDELETERequest(const RequestInfo: TDSHTTPRequest;
Response: TDSHTTPResponse; Request: String);
var
CacheId, CommandIndex, ParameterIndex: Integer;
begin
//DELETE only allowed on cache as a whole, or on a whole cache item, not individual Commands or Parameters.
if not ParseRequst(Request, CacheId, CommandIndex, ParameterIndex) or
(CommandIndex <> -1) or (ParameterIndex <> -1) then
begin
InvalidRequest(Response, Request);
Exit;
end;
if (CacheId = -1) then
FSession.ParameterCache.ClearAllItems
else
FSession.ParameterCache.RemoveItem(CacheId);
end;
function TDSHTTPCacheContextService.StreamsAsJSON(const RequestInfo: TDSHTTPRequest): Boolean;
var
StreamAsJson: Boolean;
UrlParamValue: String;
begin
StreamAsJson := False;
UrlParamValue := RequestInfo.Params.Values['json'];
if UrlParamValue <> '' then
begin
try
StreamAsJSON := StrToBool(UrlParamValue);
except
end;
end
else
begin
StreamAsJSON := AnsiContainsStr(RequestInfo.Accept, 'application/json');
end;
Result := StreamAsJSON;
end;
procedure TDSHTTPCacheContextService.GetParameterValue(const RequestInfo: TDSHTTPRequest; const CacheId,
CommandIndex, ParameterIndex: Integer; out Response: TJSONValue; out ResponseStream: TStream; out IsError: Boolean);
var
Item: TResultCommandHandler;
Command: TDBXCommand;
Parameter: TDBXParameter;
ConvList: TObjectList<TDBXRequestFilter>;
OriginalIndex: Integer;
begin
Item := FSession.ParameterCache.GetItem(CacheId);
IsError := False;
if Item = nil then
begin
Response := TJSONString.Create(Format(SNoCachItem, [CacheId]));
IsError := True;
Exit;
end;
Parameter := Item.GetCommandParameter(CommandIndex, ParameterIndex);
if Parameter = nil then
begin
Response := TJSONString.Create(Format(SNoCacheParameter, [CommandIndex, ParameterIndex]));
IsError := True;
Exit;
end;
if not StreamsAsJSON(RequestInfo) and (Parameter.DataType = TDBXDataTypes.BinaryBlobType) then
begin
ResponseStream := Parameter.Value.GetStream(True);
if ResponseStream = nil then
Response := TJSONNull.Create;
end
else
begin
ConvList := TObjectList<TDBXRequestFilter>.Create(false);
Command := Item.GetCommand(CommandIndex);
OriginalIndex := GetOriginalParamIndex(Command, Parameter);
try
Response := nil;
//use a request filter on the returned data, if one was specified
if OriginalIndex > -1 then
begin
FiltersForCriteria([OriginalIndex+1], OriginalIndex = Command.Parameters.Count - 1, ConvList);
if ConvList.Count = 1 then
begin
if not ConvList.Items[0].CanConvert(Command.Parameters[OriginalIndex].Value) then
Raise TDSServiceException.Create(Format(SCannotConvertParam, [OriginalIndex, ConvList.Items[0].Name]));
Response := ConvList.Items[0].ToJSON(Command.Parameters[OriginalIndex].Value, FLocalConnection)
end;
end;
if Response = nil then
Response := TDBXJSONTools.DBXToJSON(Parameter.Value, Parameter.DataType, FLocalConnection);
finally
FreeAndNil(ConvList);
end;
end;
end;
function TDSHTTPCacheContextService.ByteContent(JsonValue: TJSONValue): TBytes;
var
Buffer: TBytes;
begin
SetLength(Buffer, JsonValue.EstimatedByteSize);
SetLength(Buffer, JsonValue.ToBytes(Buffer, 0));
Result := Buffer;
end;
procedure TDSHTTPCacheContextService.ProcessGETRequest(const RequestInfo: TDSHTTPRequest;
Response: TDSHTTPResponse; Request: String);
var
CacheId, CommandIndex, ParameterIndex: Integer;
ResultObj: TJSONObject;
SubResult: TJSONValue;
ResultStream: TStream;
IsError: Boolean;
ResultStr: String;
begin
ResultObj := nil;
SubResult := nil;
ResultStream := nil;
IsError := False;
if not ParseRequst(Request, CacheId, CommandIndex, ParameterIndex) then
begin
InvalidRequest(Response, Request);
Exit;
end;
//datasnap/cache
if (CacheId = -1) then
begin
GetCacheContents(SubResult);
end
//datasnap/cache/CacheId
else if (CommandIndex = -1) then
begin
GetCacheItemContents(CacheId, SubResult);
end
//datasnap/cache/CacheId/CommandIndex
else if (ParameterIndex = -1) then
begin
GetCommandContents(CacheId, CommandIndex, SubResult);
end
//datasnap/cache/CacheId/CommandIndex/ParameterIndex
else
begin
GetParameterValue(RequestInfo, CacheId, CommandIndex, ParameterIndex, SubResult, ResultStream, IsError);
end;
try
if Assigned(ResultStream) then
begin
Response.ContentStream := ResultStream;
Response.FreeContentStream := False;
end
else if Assigned(SubResult) then
begin
if IsError then
ResultStr := 'error'
else
ResultStr := 'result';
ResultObj := TJSONObject.Create;
ResultObj.AddPair(TJSONPair.Create(ResultStr, SubResult));
Response.ContentText := StringOf(ByteContent(ResultObj))
end;
finally
//Only free SubResult if it hasn't been added to ResultObj
if ResultObj <> nil then
ResultObj.Free
else if Assigned(SubResult) then
SubResult.Free;
end;
end;
{ TDSClientCallbackChannelManager.TDSExecuteThread }
constructor TDSClientCallbackChannelManager.TDSExecuteThread.Create(Callback: TDBXCallback; Data: TJSONValue);
begin
FreeOnTerminate := False;
FCallback := Callback;
FData := Data;
FResponse := nil;
inherited Create;
end;
destructor TDSClientCallbackChannelManager.TDSExecuteThread.Destroy;
begin
inherited;
end;
procedure TDSClientCallbackChannelManager.TDSExecuteThread.Execute;
begin
inherited;
TMonitor.Enter(FCallback);
TMonitor.Exit(FCallback);
try
FResponse := FCallback.Execute(FData);
finally
if not Terminated then
TMonitor.Pulse(FCallback);
end;
end;
{ TDSNullResponseHandler }
procedure TDSNullResponseHandler.Close;
begin
//do nothing
end;
constructor TDSNullResponseHandler.Create(DSService: TDSService; CommandType: TDSHTTPCommandType;
ServiceInstanceOwner: Boolean);
begin
Inherited Create(CommandType, DSService, ServiceInstanceOwner);
end;
function TDSNullResponseHandler.HandleParameter(const Command: TDBXCommand; const Parameter: TDBXParameter;
out Response: TJSONValue; var ResponseStream: TStream): Boolean;
begin
Result := False;
end;
procedure TDSNullResponseHandler.PopulateContent(ResponseInfo: TDSHTTPResponse; Response: TJSONValue;
ResponseStream: TStream);
begin
//do nothing
end;
{ TDSCallbackItem }
constructor TDSCallbackItem.Create(ServerChannelName: String; Callback: TDBXCallback; Channels: TStrings);
begin
FServerChannelName := ServerChannelName;
FCallback := Callback;
FChannels := Channels;
end;
constructor TDSCallbackItem.Create(ServerChannelName: String; Callback: TDBXCallback; Channels: String);
begin
FServerChannelName := ServerChannelName;
FCallback := Callback;
FChannels := nil;
if Channels <> EmptyStr then
begin
FChannels := TStringList.Create;
FChannels.CommaText := Channels;
end;
end;
destructor TDSCallbackItem.Destroy;
begin
FreeAndNil(FCallback);
FreeAndNil(FChannels);
inherited;
end;
function TDSCallbackItem.ListeningOn(ChannelName: String): Boolean;
begin
Result := (ChannelName = FServerChannelName) or
((FChannels <> nil) and (ChannelName <> '') and (FChannels.IndexOf(ChannelName) > -1));
end;
end.
|
unit ReferenceSearch;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseSearch, Data.DB, Vcl.StdCtrls,
Vcl.Grids, Vcl.DBGrids, RzDBGrid, Vcl.Mask, RzEdit, RzLabel,
Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel, RzButton;
type
TfrmReferenceSearch = class(TfrmBaseSearch)
private
{ Private declarations }
public
{ Public declarations }
protected
{ Protected declarations }
procedure SearchList; override;
procedure SetReturn; override;
procedure Add; override;
procedure Cancel; override;
end;
implementation
{$R *.dfm}
uses
RefData, Reference, ReferenceDetail;
procedure TfrmReferenceSearch.SearchList;
var
filter: string;
begin
inherited;
if Trim(edSearchKey.Text) <> '' then
filter := 'name like ''*' + edSearchKey.Text + '*'''
else
filter := '';
grSearch.DataSource.DataSet.Filter := filter;
end;
procedure TfrmReferenceSearch.SetReturn;
var
id, firstname, lastname, middlename: string;
begin
with grSearch.DataSource.DataSet do
begin
id := FieldByName('entity_id').AsString;
firstname := FieldByName('firstname').AsString;
lastname := FieldByName('lastname').AsString;
middlename := FieldByName('middlename').AsString;
refc := TReference.Create(id,firstname,lastname,middlename);
end;
end;
procedure TfrmReferenceSearch.Add;
begin
with TfrmReferenceDetail.Create(self) do
begin
refc := TReference.Create;
refc.Add;
ShowModal;
if ModalResult = mrOK then
begin
// refresh the grid
with grSearch.DataSource.DataSet do
begin
DisableControls;
Close;
Open;
Locate('entity_id',refc.Id,[]);
EnableControls;
end;
end;
refc.Free;
end;
end;
procedure TfrmReferenceSearch.Cancel;
begin
end;
end.
|
(*
String related utils
Original code by Rafael Guimarăes de Sá pushished at Micro Sistemas (year XIII,
number 140, july 1994, p. 42 - 44).
*)
Unit StringUtils;
Interface
(**
* Add slash to the end of the pathname.
*
* @param Name Pathname to be added the slash (/)
* @return Pathname with a slash in the end.
*)
Function Slash(Name : String) : String;
(**
* Return a string with the percentage of xPar in relation to xTot.
*
* @param xPar Sample selection count.
* @param xTotal Sample size.
* @return Percentage of selection into sample.
*)
Function Percent(xPar, xTot : Real) : String;
(**
* Remove the pathname for a filename.
*
* @param Filename Filename
* @return The file's basename.
*)
Function Basename(Filename : String) : String;
(**
* Copy a file.
*
* @param InputFilename Name of the file to be copied.
* @param OutputFilename Name of the destination file.
*)
Procedure CopyFile(InputFilename, OutputFilename : String);
(**
* Return the string in lowercase.
*
* @param S String
* @return S in lowercase
*)
Function Lower(S : String) : String;
(**
* Return the string in uppercase.
*
* @param S String
* @return S in uppercase
*)
Function Upper(S : String) : String;
(**
* Return the string capitalized.
*
* @param S String
* @return S capitalized
*)
Function Capitalize(Str1 : String) : String;
(**
* Write a string to a given position in the screen.
*
* @param X Horizontal position (0 is the left of the screen)
* @param Y Vertical position (0 is the top of the screen)
* @param S String to be written
*)
Procedure WriteXY(X, Y : Integer; Str : String);
Implementation
uses Crt;
Function StrEsp(Sz : Integer; Xz : Byte) : String;
Var
Lz : String;
Begin
Sz := Abs(sz);
Str(Sz, Lz);
While Length(Lz) < Xz do
Insert(' ', Lz, 1);
StrEsp := Lz;
End;
Function Slash(Name : String) : String;
Begin
If Copy(Name, Length(Name), 1) <> '\' Then
Name := Name + '\';
Slash := Name;
End;
Function Percent(xPar, xTot : Real) : String;
Var
xRet1 : Real;
xRet2 : String;
Begin
If xTot = 0 then
Begin
xRet1 := 0;
xRet2 := ' 0 %';
End
Else
Begin
xRet1 := (xPar / xTot) * 100;
xRet2 := StrEsp(Round(xRet1), 3) + ' %';
End;
Percent := xRet2;
End;
Function Basename(Filename : String) : String;
Var
Str1 : String;
Count1 : Integer;
Begin
Str1 := Filename;
For Count1 := Length(Str1) DownTo (Length(Str1) - 12) Do
Begin
If Copy(Str1, Count1, 1) = '\' Then
Begin
Basename := Copy(Str1, Count1 + 1, 13);
Count1 := Length(Str1) - 12;
End;
End;
End;
Procedure CopyFile(InputFilename, OutputFilename : String);
Var
InputFile, OutputFile : File;
NumRead, NumWritten : Word;
Buffer : array[1..2048] of Char;
Begin
Assign(InputFile, InputFilename);
Reset(InputFile, 1);
Assign(OutputFile, OutputFilename);
Reset(OutputFile, 1);
Repeat
BlockRead(InputFIle, buffer, SizeOf(buffer), NumRead);
BlockWrite(OutputFile, buffer, NumRead, NumWritten);
until (NumRead = 0) or (NumWritten <> NumRead);
Close(InputFile);
Close(OutputFile);
End;
Function Lower(S : String) : String;
Var
x : Byte;
Begin
For x := 1 to Length(s) do
Begin
If Ord(s[x]) in [65..90] Then
s[x] := Chr(Ord(s[x]) + 32);
End;
Lower := s;
End;
Function Upper(S : String) : String;
Var
x : Byte;
Begin
If s <> ' ' Then
For x := 1 to Length(s) do
s[x] := Upcase(s[x]);
Upper := s;
End;
Function Capitalize(Str1 : String) : String;
Var
Str : Array[1..201] of String[1];
Cnt1 : Integer;
Cp : String;
Begin
Str1 := Lower(Str1);
Cp := '';
If Length(Str1) > 200 Then Halt;
For Cnt1 := 1 to Length(Str1) do
Begin
Str[Cnt1] := Copy(Str1, Cnt1, 1);
End;
Str[1] := Upper(Str[1]);
For Cnt1 := 2 to Length(Str1) + 1 do
Begin
If Str[Cnt1] = ' ' Then
Str[cnt1 + 1] := Upper(Str[Cnt1 + 1]);
End;
For Cnt1 := 1 to Length(Str1) do
Cp := Cp + Str[Cnt1];
Capitalize := Cp;
End;
Procedure WriteXY(X, Y : Integer; Str : String);
Begin
GotoXY(X, Y);
Writeln(Str);
End;
Begin
End.
|
unit HistoricoCorteReligacao;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Padrao1, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus,
cxControls, cxStyles, dxSkinsCore, dxSkinsDefaultPainters, dxSkinscxPCPainter,
cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, FMTBcd,
DBClient, Provider, SqlExpr, cxGridLevel, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid,
StdCtrls, cxButtons, ExtCtrls, cxContainer, Buttons, cxTextEdit, cxMaskEdit,
cxLabel, fmeUnidConsumidora, cxCurrencyEdit, frxClass, frxDBSet, frxExportXML,
frxExportRTF, frxExportPDF, StrUtils, Mask, DBCtrls;
type
TfrmHistCorteRelig = class(TfrmPadrao1)
Panel1: TPanel;
GridTable: TcxGrid;
GridTableDBTableView1: TcxGridDBTableView;
GridTableDBTableView1Column7: TcxGridDBColumn;
GridTableDBTableView1Column8: TcxGridDBColumn;
GridTableLevel1: TcxGridLevel;
qryHistCorteRelig: TSQLQuery;
provHistCorteRelig: TDataSetProvider;
cdsHistCorteRelig: TClientDataSet;
dsHistCorteRelig: TDataSource;
GridTableDBTableView1Column1: TcxGridDBColumn;
GridTableDBTableView1Column2: TcxGridDBColumn;
BitBtn5: TBitBtn;
cdsHistCorteReligID: TIntegerField;
cdsHistCorteReligTIPO_MOVIM: TStringField;
cdsHistCorteReligDT_MOVIM: TDateField;
cdsHistCorteReligID_UNID_CONSUM: TIntegerField;
cdsHistCorteReligMOTIVO: TIntegerField;
cdsHistCorteReligID_SERVID_EXECUT: TIntegerField;
cdsHistCorteReligOBSERVACAO: TStringField;
cdsHistCorteReligNOME_PESSOA: TStringField;
cdsHistCorteReligDESCR_CATEGORIA: TStringField;
cdsHistCorteReligCPF_CNPJ: TStringField;
cdsHistCorteReligDESCR_TIPO_MOVIM: TStringField;
cdsHistCorteReligANO_MES: TStringField;
cdsHistCorteReligENDER_ID_LOGRAD: TIntegerField;
cdsHistCorteReligENDER_DESCR_LOGRAD: TStringField;
cdsHistCorteReligENDER_COMPLEMENTO: TStringField;
cdsHistCorteReligENDER_NUM_LETRA: TStringField;
cdsHistCorteReligENDER_ID_BAIRRO: TIntegerField;
cdsHistCorteReligENDER_DESCR_BAIRRO: TStringField;
cdsHistCorteReligENDER_ID_DISTRITO: TIntegerField;
cdsHistCorteReligENDER_DESCR_DISTRITO: TStringField;
cdsHistCorteReligENDER_DESCR_LOGRADOURO: TStringField;
cdsHistCorteReligENDER_UC_NUM_LETRA: TStringField;
cdsHistCorteReligENDER_COMPLEMENTO_1: TStringField;
cdsHistCorteReligENDER_DESCR_BAIRRO_1: TStringField;
cdsHistCorteReligENDER_DESCR_DISTRITO_1: TStringField;
qryUC: TSQLQuery;
dsUC: TDataSource;
qryUCID: TIntegerField;
qryUCID_PESSOA: TIntegerField;
qryUCTIPO_PESSOA: TStringField;
qryUCNUM_LIGACAO: TStringField;
qryUCDT_LIGACAO: TDateField;
qryUCSITUACAO: TStringField;
qryUCENDER_ID_LOGRAD: TIntegerField;
qryUCENDER_NUM: TIntegerField;
qryUCENDER_NUM_LETRA: TStringField;
qryUCENDER_COMPLEMENTO: TStringField;
qryUCENDER_ID_BAIRRO: TIntegerField;
qryUCENDER_ID_DISTRITO: TIntegerField;
qryUCENDER_ID_LOGRAD2: TIntegerField;
qryUCENDER_NUM2: TIntegerField;
qryUCENDER_NUM_LETRA2: TStringField;
qryUCENDER_COMPLEMENTO2: TStringField;
qryUCENDER_ID_BAIRRO2: TIntegerField;
qryUCENDER_ID_DISTRITO2: TIntegerField;
qryUCTIPO_UNID_CONSUM: TStringField;
qryUCFORMA_CALCULO: TStringField;
qryUCNUM_HIDROMETRO: TStringField;
qryUCDT_INSTAL_HIDROM: TDateField;
qryUCQTD_TORNEIRA: TIntegerField;
qryUCMULTIPLICADOR: TIntegerField;
qryUCOBSERV_FATURA: TStringField;
qryUCOBSERVACAO: TMemoField;
qryUCENDER_DESCR_BAIRRO: TStringField;
qryUCENDER_DESCR_LOGRADOURO: TStringField;
qryUCENDER_DESCR_BAIRRO2: TStringField;
qryUCENDER_DESCR_LOGRADOURO2: TStringField;
qryUCNOME_PESSOA: TStringField;
qryUCCPF_CNPJ: TStringField;
qryUCCPF_CNPJ_FTDO: TStringField;
qryUCDESCR_TIPO_PESSOA: TStringField;
qryUCNOME_FANTASIA: TStringField;
qryUCRG_NUM: TStringField;
qryUCRG_ORGAO_EMISSOR: TStringField;
qryUCRG_UF: TStringField;
qryUCRG_DT_EMISSAO: TDateField;
qryUCENDER_DESCR_DISTRITO: TStringField;
qryUCENDER_DESCR_DISTRITO2: TStringField;
qryUCENDER_DESCR_LOGRAD: TStringField;
qryUCENDER_DESCR_LOGRAD2: TStringField;
qryUCDESCR_FORMA_CALCULO: TStringField;
qryUCDESCR_TIPO_UNID_CONSUM: TStringField;
qryUCDESCR_SITUACAO: TStringField;
qryUCENDER_UC_NUM_LETRA: TStringField;
qryUCENDER_UC_NUM_LETRA2: TStringField;
qryUCDT_ULT_CORTE: TDateField;
qryUCDT_ULT_RELIG: TDateField;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
DBEdit2: TDBEdit;
DBEdit3: TDBEdit;
DBEdit4: TDBEdit;
DBEdit5: TDBEdit;
DBEdit6: TDBEdit;
DBEdit7: TDBEdit;
DBEdit8: TDBEdit;
DBEdit9: TDBEdit;
edIdUC: TEdit;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure BitBtn5Click(Sender: TObject);
private
{ Private declarations }
pv_sPathRel : string;
procedure HabilitaBotoes(lOpcao: Boolean);
public
{ Public declarations }
pb_iIdUnidConsum: Integer;
end;
var
frmHistCorteRelig: TfrmHistCorteRelig;
implementation
uses udmPrincipal, gsLib, DetalhaFatura, VarGlobais, udmRelDoctos;
{$R *.dfm}
procedure TfrmHistCorteRelig.BitBtn5Click(Sender: TObject);
begin
Close;
end;
procedure TfrmHistCorteRelig.FormClose(Sender: TObject; var Action: TCloseAction);
begin
cdsHistCorteRelig.Close;
qryUC.Close;
end;
procedure TfrmHistCorteRelig.FormShow(Sender: TObject);
Var
iTam: Integer;
begin
inherited;
qryUC.Close;
qryUC.Params[0].Value := pb_iIdUnidConsum;
qryUC.Open;
iTam := Length(qryUCID.AsString);
edIdUC.Text := LeftStr(qryUCID.AsString,iTam-1)+'-'+RightStr(qryUCID.AsString,1);
cdsHistCorteRelig.Close;
qryHistCorteRelig.ParamByName('pIdUC').Value := pb_iIdUnidConsum;
cdsHistCorteRelig.Open;
end;
procedure TfrmHistCorteRelig.HabilitaBotoes(lOpcao: Boolean);
begin
end;
end.
|
unit uConexaoFTPPgn;
interface
uses IdFTP, System.Classes, System.SysUtils;
type TConexaoFtpPgn = class
private
_IdFtp : TIdFTP;
Fpassivo: Boolean;
Fsenha: string;
Fhost: string;
Fusuario: string;
Fendereco: string;
procedure Setendereco(const Value: string);
procedure Sethost(const Value: string);
procedure Setpassivo(const Value: Boolean);
procedure Setsenha(const Value: string);
procedure Setusuario(const Value: string);
procedure configuraFTP;
public
property usuario : string read Fusuario write Setusuario;
property senha : string read Fsenha write Setsenha;
property hostname: string read Fhost write Sethost;
property endereco: string read Fendereco write Setendereco;
property passivo : Boolean read Fpassivo write Setpassivo;
function conectar : Boolean;
function desconectar: Boolean;
function salvarFTP(AFileName: String): Boolean;
constructor Create; overload;
constructor create(
AUsuario : string;
ASenha : string;
AHost : string;
AEndereco: string;
APassivo : Boolean = True
); overload;
end;
implementation
{ TConexaoFtpPgn }
constructor TConexaoFtpPgn.Create;
begin
_IdFtp := TIdFTP.Create(nil);
end;
function TConexaoFtpPgn.conectar: Boolean;
begin
try
result := False;
configuraFTP;
_IdFtp.Connect;
result := True;
except
on e : Exception do
raise Exception.Create('Erro ao conectar FTP: ' + e.Message);
end;
end;
procedure TConexaoFtpPgn.configuraFTP;
begin
with _IdFtp do
begin
if Connected then
Disconnect;
Username := usuario;
Password := senha;
Host := hostname;
Passive := passivo;
end;
end;
constructor TConexaoFtpPgn.Create(AUsuario, ASenha, AHost, AEndereco: string; APassivo: Boolean);
begin
_IdFtp := TIdFTP.Create(nil);
Self.usuario := AUsuario;
Self.senha := ASenha;
Self.hostname:= AHost;
Self.endereco:= AEndereco;
Self.passivo := APassivo;
end;
function TConexaoFtpPgn.desconectar: Boolean;
begin
if _IdFtp.Connected then
_IdFtp.Disconnect;
end;
function TConexaoFtpPgn.salvarFTP(AFileName: String): Boolean;
begin
try
try
// Configurar Parâmetros de Acesso FTP
configuraFTP;
// Conectar
conectar;
// Vai para o diretório FTP
_IdFtp.ChangeDir(endereco);
// Salvar no FTP
_IdFtp.Put(AFileName, ExtractFileName(AFileName));
except
try
// Salvar no FTP com Append, caso a primeira tentativa dê algum erro
_IdFtp.Put(AFileName, ExtractFileName(AFileName), True);
except
on e : Exception do
raise Exception.Create(e.Message);
end;
end;
finally
desconectar;
end;
end;
procedure TConexaoFtpPgn.Setendereco(const Value: string);
begin
Fendereco := Value;
end;
procedure TConexaoFtpPgn.Sethost(const Value: string);
begin
Fhost := Value;
end;
procedure TConexaoFtpPgn.Setpassivo(const Value: Boolean);
begin
Fpassivo := Value;
end;
procedure TConexaoFtpPgn.Setsenha(const Value: string);
begin
Fsenha := Value;
end;
procedure TConexaoFtpPgn.Setusuario(const Value: string);
begin
Fusuario := Value;
end;
end.
|
{ ---------------------------------------------------------------------------- }
{ BulbTracer for MB3D }
{ Copyright (C) 2016-2017 Andreas Maschke }
{ ---------------------------------------------------------------------------- }
unit MeshPreview;
interface
uses
SysUtils, Classes, Windows, dglOpenGL, Vcl.Graphics, VertexList, VectorMath,
OpenGLPreviewUtil, ShaderUtil;
type
TMeshAppearance = class
private
procedure InitColors;
public
WireframeColor: TS3Vector;
SurfaceColor: TS3Vector;
EdgesColor: TS3Vector;
PointsColor: TS3Vector;
LightingEnabled: Boolean;
MatAmbient: TS3Vector;
MatSpecular: TS3Vector;
MatShininess: Single;
MatDiffuse: TS3Vector;
LightAmbient: TS3Vector;
LightDiffuse: TS3Vector;
LightPosition: TS3Vector;
LightConstantAttenuation: Single;
LightLinearAttenuation: Single;
LightQuadraticAttenuation: Single;
constructor Create;
end;
TOpenGLHelper = class( TBaseOpenGLHelper )
private
FMeshAppearance: TMeshAppearance;
procedure SetupLighting;
procedure DrawBackground; override;
procedure ApplicationEventsIdle(Sender: TObject; var Done: Boolean); override;
public
constructor Create(const Canvas: TCanvas);
destructor Destroy; override;
procedure UpdateMesh(const FacesList: TFacesList); override;
procedure UpdateMesh(const VertexList: TPS3VectorList; const ColorList: TPSMI3VectorList); override;
property MeshAppearance: TMeshAppearance read FMeshAppearance;
end;
implementation
uses
Forms, Math, DateUtils;
const
WindowTitle = 'Mesh Preview';
{ ------------------------------ TOpenGLHelper ------------------------------- }
constructor TOpenGLHelper.Create(const Canvas: TCanvas);
begin
inherited Create( Canvas );
FMeshAppearance := TMeshAppearance.Create;
end;
destructor TOpenGLHelper.Destroy;
begin
FMeshAppearance.Free;
inherited Destroy;
end;
procedure TOpenGLHelper.DrawBackground;
begin
//Gradient background
glMatrixMode (GL_MODELVIEW);
glPushMatrix ();
glLoadIdentity ();
glMatrixMode (GL_PROJECTION);
glPushMatrix ();
glLoadIdentity ();
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
glBegin (GL_QUADS);
glColor3f(0.78039215686274509803921568627451, 0.65882352941176470588235294117647, 0.54509803921568627450980392156863);
glVertex3f (-1.0, -1.0, -1.0);
glColor3f(0.78039215686274509803921568627451, 0.65882352941176470588235294117647, 0.54509803921568627450980392156863);
glVertex3f (1.0, -1.0, -1.0);
glColor3f(0.21960784313725490196078431372549, 0.34509803921568627450980392156863, 0.56470588235294117647058823529412);
glVertex3f (1.0, 1.0, -1.0);
glColor3f(0.21960784313725490196078431372549, 0.34509803921568627450980392156863, 0.56470588235294117647058823529412);
glVertex3f (-1.0, 1.0, -1.0);
glEnd ();
glEnable(GL_LIGHTING);
glEnable(GL_DEPTH_TEST);
glPopMatrix ();
glMatrixMode (GL_MODELVIEW);
glPopMatrix ();
end;
procedure TOpenGLHelper.ApplicationEventsIdle(Sender: TObject; var Done: Boolean);
const
ZOffset: Double = -7.0;
var
Error, I : LongInt;
X, Y, Z: Double;
V: TPS3Vector;
Face: TPFace;
Scl: Double;
begin
if FRC = 0 then Exit;
Done := False;
glClearColor(0,0,0,0);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
if FFaces <> nil then
DrawBackground();
glLoadIdentity;
glTranslatef( FPosition.X, FPosition.Y, ZOffset);
glRotatef( FAngle.X, 0.0, 1.0, 0.0);
glRotatef( - FAngle.Y, 1.0, 0.0, 1.0);
Scl := FScale * 3.0/FMaxObjectSize;
glScalef(Scl, Scl, Scl);
glTranslatef( 0.0, 0.0, FPosition.Z);
glDisable(GL_LIGHTING);
glDisableClientState (GL_VERTEX_ARRAY);
glDisableClientState (GL_COLOR_ARRAY);
if FFaces <> nil then begin
glEnableClientState (GL_VERTEX_ARRAY);
glVertexPointer( 3, GL_FLOAT, SizeOf(TGLVertex), FVertices);
if FNormals <> nil then begin
glEnableClientState( GL_NORMAL_ARRAY );
glNormalPointer( GL_FLOAT, SizeOf(TGLVertex), FNormals);
end;
case FDisplayStyle of
dsPoints:
begin
glShadeModel(GL_FLAT);
glPointSize(5.0);
glColor3f(FMeshAppearance.PointsColor.X, FMeshAppearance.PointsColor.Y, FMeshAppearance.PointsColor.Z);
glDrawElements( GL_POINTS, FFaceCount * 3, GL_UNSIGNED_INT, FFaces );
end;
dsWireframe:
begin
glShadeModel(GL_FLAT);
if FEdges<>nil then begin
glLineWidth(1.0);
glColor3f(FMeshAppearance.WireframeColor.X, FMeshAppearance.WireframeColor.Y, FMeshAppearance.WireframeColor.Z);
glDrawElements( GL_LINES, FEdgeCount * 2, GL_UNSIGNED_INT, FEdges );
end;
end;
dsFlatSolid:
begin
SetupLighting;
glShadeModel(GL_FLAT);
glColor3f(FMeshAppearance.SurfaceColor.X, FMeshAppearance.SurfaceColor.Y, FMeshAppearance.SurfaceColor.Z);
glDrawElements( GL_TRIANGLES, FFaceCount * 3, GL_UNSIGNED_INT, FFaces );
end;
dsFlatSolidWithEdges:
begin
SetupLighting;
glShadeModel(GL_FLAT);
glColor3f(FMeshAppearance.SurfaceColor.X, FMeshAppearance.SurfaceColor.Y, FMeshAppearance.SurfaceColor.Z);
glDrawElements( GL_TRIANGLES, FFaceCount * 3, GL_UNSIGNED_INT, FFaces );
if FEdges<>nil then begin
glDisable(GL_LIGHTING);
glLineWidth(1.5);
glColor3f(FMeshAppearance.EdgesColor.X, FMeshAppearance.EdgesColor.Y, FMeshAppearance.EdgesColor.Z);
glDrawElements( GL_LINES, FEdgeCount * 2, GL_UNSIGNED_INT, FEdges );
end;
end;
dsSmoothSolid:
begin
SetupLighting;
glShadeModel(GL_SMOOTH);
glColor3f(FMeshAppearance.SurfaceColor.X, FMeshAppearance.SurfaceColor.Y, FMeshAppearance.SurfaceColor.Z);
glDrawElements( GL_TRIANGLES, FFaceCount * 3, GL_UNSIGNED_INT, FFaces );
end;
dsSmoothSolidWithEdges:
begin
SetupLighting;
glShadeModel(GL_SMOOTH);
glColor3f(FMeshAppearance.SurfaceColor.X, FMeshAppearance.SurfaceColor.Y, FMeshAppearance.SurfaceColor.Z);
glDrawElements( GL_TRIANGLES, FFaceCount * 3, GL_UNSIGNED_INT, FFaces );
if FEdges<>nil then begin
glDisable(GL_LIGHTING);
glLineWidth(1.5);
glColor3f(FMeshAppearance.EdgesColor.X, FMeshAppearance.EdgesColor.Y, FMeshAppearance.EdgesColor.Z);
glDrawElements( GL_LINES, FEdgeCount * 2, GL_UNSIGNED_INT, FEdges );
end;
end;
end;
end
else if FVertices <> nil then begin
glEnableClientState (GL_VERTEX_ARRAY);
if FVertexColors<>nil then
glEnableClientState (GL_COLOR_ARRAY);
glVertexPointer( 3, GL_FLOAT, SizeOf(TGLVertex), FVertices);
if FVertexColors<>nil then
glColorPointer( 3, GL_FLOAT, SizeOf(TGLVertex), FVertexColors);
glShadeModel(GL_FLAT);
glPointSize(1.25);
glColor3f(FMeshAppearance.PointsColor.X, FMeshAppearance.PointsColor.Y, FMeshAppearance.PointsColor.Z);
glDrawArrays (GL_POINTS, 0, FVerticesCount);
end;
//Error Handler
Error := glgetError;
if Error <> GL_NO_ERROR then begin
if Assigned(FSetWindowCaptionEvent) then
FSetWindowCaptionEvent( gluErrorString(Error) );
Done := True;
FlashWindow(FCanvas.Handle, True)
end;
//Frame Counter
Inc(FFrames);
if (GetTickCount - FStartTick >= 500) and (FFrames >= 10) and Assigned(FSetWindowCaptionEvent) then begin
FSetWindowCaptionEvent( Format('%s [%f FPS, %d Vertices, %d Faces]', [WindowTitle, FFrames/(GetTickCount - FStartTick)*1000, FVerticesCount, FFaceCount]));
FFrames := 0;
FStartTick := GetTickCount;
end;
SwapBuffers(FCanvas.Handle);
Sleep(1);
end;
procedure TOpenGLHelper.UpdateMesh(const VertexList: TPS3VectorList; const ColorList: TPSMI3VectorList);
var
I: Integer;
T0, T00: Int64;
GLVertices, GLVertex: TPGLVertex;
GLVertexColors, GLVertexColor: TPGLVertex;
Vertex: TPS3Vector;
procedure AddVertex(const Idx: Integer);
var
Vertex: TPS3Vector;
VertexColor: TPSMI3Vector;
begin
Vertex := VertexList.GetVertex(Idx);
if Vertex^.X < FSizeMin.X then
FSizeMin.X := Vertex^.X
else if Vertex^.X > FSizeMax.X then
FSizeMax.X := Vertex^.X;
if Vertex^.Y < FSizeMin.Y then
FSizeMin.Y := Vertex^.Y
else if Vertex^.Y > FSizeMax.Y then
FSizeMax.Y := Vertex^.Y;
if Vertex^.Z < FSizeMin.Z then
FSizeMin.Z := Vertex^.Z
else if Vertex^.Z > FSizeMax.Z then
FSizeMax.Z := Vertex^.Z;
GLVertex^.X := Vertex^.X;
GLVertex^.Y := -Vertex^.Y;
GLVertex^.Z := -Vertex^.Z;
GLVertex := Pointer(Longint(GLVertex)+SizeOf(TGLVertex));
if GLVertexColors <> nil then begin
VertexColor := ColorList.GetVertex(Idx);
GLVertexColor^.X := TPSMI3VectorList.SMIToFloat( VertexColor^.X );
GLVertexColor^.Y := TPSMI3VectorList.SMIToFloat( VertexColor^.Y );
GLVertexColor^.Z := TPSMI3VectorList.SMIToFloat( VertexColor^.Z );
GLVertexColor := Pointer(Longint(GLVertexColor)+SizeOf(TGLVertex));
end;
end;
begin
T0 := DateUtils.MilliSecondsBetween(Now, 0);
T00 := T0;
FreeVertices;
if VertexList.Count > 0 then begin
T0 := DateUtils.MilliSecondsBetween(Now, 0);
GetMem(GLVertices, VertexList.Count * SizeOf(TGLVertex));
try
GLVertex := GLVertices;
if ColorList <> nil then
GetMem(GLVertexColors, VertexList.Count * SizeOf(TGLVertex))
else
GLVertexColors := nil;
try
GLVertexColor := GLVertexColors;
Vertex := VertexList.GetVertex(0);
FSizeMin.X := Vertex^.X;
FSizeMax.X := FSizeMin.X;
FSizeMin.Y := Vertex^.Y;
FSizeMax.Y := FSizeMin.Y;
FSizeMin.Z := Vertex^.Z;
FSizeMax.Z := FSizeMin.Z;
for I := 0 to VertexList.Count - 1 do
AddVertex(I);
ShowDebugInfo('OpenGL.AddVertices', T0);
T0 := DateUtils.MilliSecondsBetween(Now, 0);
FMaxObjectSize := Max(FSizeMax.X - FSizeMin.X, Max(FSizeMax.Y - FSizeMin.Y, FSizeMax.Z - FSizeMin.Z ));
ShowDebugInfo('OpenGL.AddFaces', T0);
T0 := DateUtils.MilliSecondsBetween(Now, 0);
FFaceCount := 0;
FVerticesCount := VertexList.Count;
FEdgeCount := 0;
FVertices := GLVertices;
FVertexColors := GLVertexColors;
FNormals := nil;
FFaces := nil;
FEdges := nil;
except
if GLVertexColors <> nil then
FreeMem( GLVertexColors );
raise;
end;
except
FreeMem(GLVertices);
raise;
end;
end;
ShowDebugInfo('OpenGL.TOTAL', T00);
end;
procedure TOpenGLHelper.UpdateMesh(const FacesList: TFacesList);
var
T0, T00: Int64;
I: Integer;
Key: String;
GLVertices, GLVertex: TPGLVertex;
GLNormals, GLNormal: TPGLVertex;
GLEdges, GLEdge: TPGLEdge;
GLFaces, GLFace: TPGLFace;
EdgesList: TStringList;
EdgeCount: Integer;
Vertex: TPS3Vector;
Normals: TPS3VectorList;
procedure AddVertex(const Idx: Integer);
var
Vertex: TPS3Vector;
begin
Vertex := FacesList.GetVertex(Idx);
if Vertex^.X < FSizeMin.X then
FSizeMin.X := Vertex^.X
else if Vertex^.X > FSizeMax.X then
FSizeMax.X := Vertex^.X;
if Vertex^.Y < FSizeMin.Y then
FSizeMin.Y := Vertex^.Y
else if Vertex^.Y > FSizeMax.Y then
FSizeMax.Y := Vertex^.Y;
if Vertex^.Z < FSizeMin.Z then
FSizeMin.Z := Vertex^.Z
else if Vertex^.Z > FSizeMax.Z then
FSizeMax.Z := Vertex^.Z;
GLVertex^.X := Vertex^.X;
GLVertex^.Y := -Vertex^.Y;
GLVertex^.Z := -Vertex^.Z;
GLVertex := Pointer(Longint(GLVertex)+SizeOf(TGLVertex));
end;
procedure AddNormal(const Idx: Integer);
var
Vertex: TPS3Vector;
begin
Vertex := Normals.GetVertex(Idx);
GLNormal^.X := Vertex^.X;
GLNormal^.Y := Vertex^.Y;
GLNormal^.Z := -Vertex^.Z;
GLNormal := Pointer(Longint(GLNormal)+SizeOf(TGLVertex));
end;
procedure AddFace(const Idx: Integer);
var
Face: TPFace;
begin
Face := FacesList.GetFace(Idx);
GLFace^.V1 := Face^.Vertex1;
GLFace^.V2 := Face^.Vertex2;
GLFace^.V3 := Face^.Vertex3;
GLFace := Pointer(Longint(GLFace)+SizeOf(TGLFace));
end;
procedure AddEdgeFromList(const Idx: Integer);
var
P: Integer;
Key: String;
begin
Key := EdgesList[I];
P := Pos('#', Key);
GLEdge^.V1 := StrToInt(Copy(Key, 1, P - 1));
GLEdge^.V2 := StrToInt(Copy(Key, P+1, Length(Key) - P));
GLEdge := Pointer(Longint(GLEdge)+SizeOf(TGLEdge));
end;
procedure AddEdgesToList(const Idx: Integer);
var
Face: TPFace;
(*
procedure AddEdge(const V1, V2: Integer);
var
Key: String;
begin
if V1 < V2 then
Key := IntToStr(V1)+'#'+IntToStr(V2)
else
Key := IntToStr(V2)+'#'+IntToStr(V1);
if EdgesList.IndexOf(Key) < 0 then
EdgesList.Add(Key);
end;
*)
procedure FastAddEdge(const V1, V2: Integer);
var
Key: String;
begin
Key := IntToStr(V1)+'#'+IntToStr(V2);
EdgesList.Add(Key);
end;
begin
Face := FacesList.GetFace(Idx);
FastAddEdge(Face^.Vertex1, Face^.Vertex2);
if (EdgesList.Count mod 2) = 0 then
FastAddEdge(Face^.Vertex2, Face^.Vertex3)
else
FastAddEdge(Face^.Vertex3, Face^.Vertex1);
(*
AddEdge(Face^.Vertex1, Face^.Vertex2);
AddEdge(Face^.Vertex2, Face^.Vertex3);
AddEdge(Face^.Vertex3, Face^.Vertex1);
*)
end;
begin
// TODO downsample
T0 := DateUtils.MilliSecondsBetween(Now, 0);
T00 := T0;
// TODO create data (e.g. edges) only on demand ?
FreeVertices;
if FacesList.Count > 0 then begin
EdgesList := TStringList.Create;
try
EdgesList.Duplicates := dupAccept;
EdgesList.Sorted := False;
for I := 0 to FacesList.Count - 1 do
AddEdgesToList(I);
EdgesList.Sorted := True;
EdgeCount := EdgesList.Count;
ShowDebugInfo('OpenGL.AddEdgesPh1('+IntToStr(EdgeCount)+')', T0);
T0 := DateUtils.MilliSecondsBetween(Now, 0);
GetMem(GLEdges, EdgeCount * SizeOf(TGLEdge));
try
GLEdge := GLEdges;
for I := 0 to EdgeCount - 1 do
AddEdgeFromList(I);
except
FreeMem(GLEdges);
raise;
end;
finally
EdgesList.Free;
end;
ShowDebugInfo('OpenGL.AddEdgesPh2', T0);
T0 := DateUtils.MilliSecondsBetween(Now, 0);
try
GetMem(GLVertices, FacesList.VertexCount * SizeOf(TGLVertex));
try
GetMem(GLFaces, FacesList.Count * Sizeof(TGLFace));
try
GLVertex := GLVertices;
Vertex := FacesList.GetVertex(0);
FSizeMin.X := Vertex^.X;
FSizeMax.X := FSizeMin.X;
FSizeMin.Y := Vertex^.Y;
FSizeMax.Y := FSizeMin.Y;
FSizeMin.Z := Vertex^.Z;
FSizeMax.Z := FSizeMin.Z;
for I := 0 to FacesList.VertexCount - 1 do
AddVertex(I);
ShowDebugInfo('OpenGL.AddVertices', T0);
T0 := DateUtils.MilliSecondsBetween(Now, 0);
FMaxObjectSize := Max(FSizeMax.X - FSizeMin.X, Max(FSizeMax.Y - FSizeMin.Y, FSizeMax.Z - FSizeMin.Z ));
GLFace := GLFaces;
for I := 0 to FacesList.Count - 1 do
AddFace(I);
ShowDebugInfo('OpenGL.AddFaces', T0);
T0 := DateUtils.MilliSecondsBetween(Now, 0);
FFaceCount := FacesList.Count;
FVerticesCount := FacesList.VertexCount;
FEdgeCount := EdgeCount;
FVertices := GLVertices;
try
GetMem(GLNormals, FVerticesCount * SizeOf(TGLVertex));
try
GLNormal := GLNormals;
Normals := FacesList.CalculateVertexNormals;
try
if Normals.Count <> FVerticesCount then
raise Exception.Create('Invalid normals');
for I := 0 to Normals.Count - 1 do
AddNormal(I);
finally
Normals.Free;
end;
except
FreeMem(GLNormals);
raise;
end;
except
GLNormals := nil;
// Hide error as normals are optional
end;
FNormals := GLNormals;
FFaces := GLFaces;
FEdges := GLEdges;
except
FreeMem(GLFaces);
raise;
end;
except
FreeMem(GLVertices);
raise;
end;
except
FreeMem(GLEdges);
raise;
end;
end;
ShowDebugInfo('OpenGL.AddNormals', T0);
ShowDebugInfo('OpenGL.TOTAL', T00);
end;
procedure TOpenGLHelper.SetupLighting;
var
mat_ambient : Array[0..3] of GlFloat;
mat_specular : Array[0..3] of GlFloat;
mat_shininess : Array[0..0] of GlFloat;
mat_diffuse : Array[0..3] of GlFloat;
light_position : Array[0..3] of GlFloat;
light_ambient : Array[0..3] of GlFloat;
light_diffuse : Array[0..3] of GlFloat;
procedure SetValue(const Src: TS3Vector; const Dst: PGLfloat); overload;
var
P: PGLfloat;
begin
P := Dst;
P^ := Src.X;
P := Pointer(Integer(P)+SizeOf(GLfloat));
P^ := Src.Y;
P := Pointer(Integer(P)+SizeOf(GLfloat));
P^ := Src.Z;
P := Pointer(Integer(P)+SizeOf(GLfloat));
P^ := 1.0;
end;
procedure SetValue(const Src: Double; const Dst: PGLfloat); overload;
begin
Dst^ := Src;
end;
begin
with FMeshAppearance do begin
if LightingEnabled then begin
glEnable(GL_LIGHTING);
SetValue(MatAmbient, @mat_ambient[0]);
glMaterialfv(GL_FRONT, GL_AMBIENT, @mat_ambient[0]);
SetValue(MatSpecular, @mat_specular[0]);
mat_specular[3] := 0.5;
glMaterialfv(GL_FRONT, GL_SPECULAR, @mat_specular[0]);
SetValue(MatShininess, @mat_shininess[0]);
glMaterialfv(GL_FRONT, GL_SHININESS, @mat_shininess[0]);
SetValue(MatDiffuse, @mat_diffuse[0]);
glMaterialfv(GL_FRONT, GL_DIFFUSE, @mat_diffuse[0]);
glEnable(GL_LIGHT0);
SetValue(LightAmbient, @light_ambient[0]);
glLightfv(GL_LIGHT0, GL_AMBIENT, @light_ambient[0]);
SetValue(LightDiffuse, @light_diffuse[0]);
glLightfv(GL_LIGHT0, GL_DIFFUSE, @light_diffuse[0]);
SetValue(LightPosition, @light_position[0]);
light_position[3] := 1.0;
glLightfv(GL_LIGHT0, GL_POSITION, @light_position[0]);
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, LightConstantAttenuation);
glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, LightLinearAttenuation);
glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, LightQuadraticAttenuation);
end
else begin
glDisable(GL_LIGHTING);
end;
end;
end;
{ ----------------------------- TMeshAppearance ------------------------------ }
constructor TMeshAppearance.Create;
begin
inherited Create;
InitColors;
end;
procedure TMeshAppearance.InitColors;
begin
TSVectorMath.SetValue(@WireframeColor, 0.2, 0.2, 0.7);
TSVectorMath.SetValue(@SurfaceColor, 0.77647058823529411764705882352941, 0.76470588235294117647058823529412, 0.71764705882352941176470588235294);
TSVectorMath.SetValue(@EdgesColor, 0.2, 0.2, 0.2);
TSVectorMath.SetValue(@PointsColor, 0.2, 0.7, 0.2);
// TSVectorMath.SetValue(@MatAmbient, 65.0 / 255.0, 93.0 / 255.0, 144.0 / 255.0);
TSVectorMath.SetValue(@MatAmbient, 0.0, 0.0, 0.0);
TSVectorMath.SetValue(@MatSpecular, 0.0 / 255.0, 0.0 / 255.0, 0.0 / 255.0);
MatShininess := 10.0;
TSVectorMath.SetValue(@MatDiffuse, 0.49, 0.49, 0.55);
TSVectorMath.SetValue(@LightAmbient, 0.36, 0.36, 0.26);
TSVectorMath.SetValue(@LightDiffuse, 0.8, 0.8, 0.8);
TSVectorMath.SetValue(@LightPosition, 1.0, 11.0, 17.0);
(*
LightConstantAttenuation := 1.4;
LightLinearAttenuation := 0.001;
LightQuadraticAttenuation := 0.004;
*)
LightConstantAttenuation := 0.02;
LightLinearAttenuation := 0.00;
LightQuadraticAttenuation := 0.00;
LightingEnabled := True;
end;
end.
|
unit CDConst;
interface
const
mtUNKNOWN = 0;
mtMESSAGE = 1;
mtWARNING = 2;
mtNONFATALERROR = 3;
mtFATALERROR = 4;
resourcestring
ERR_AS_00_00 = 'NO ADDITIONAL SENSE INFORMATION';
ERR_AS_00_06 = 'I/O PROCESS TERMINATED';
ERR_AS_00_11 = 'AUDIO PLAY OPERATION IN PROGRESS';
ERR_AS_00_12 = 'AUDIO PLAY OPERATION PAUSED';
ERR_AS_00_13 = 'AUDIO PLAY OPERATION SUCCESSFULLY COMPLETED';
ERR_AS_00_14 = 'AUDIO PLAY OPERATION STOPPED DUE TO ERROR';
ERR_AS_00_15 = 'NO CURRENT AUDIO STATUS TO RETURN';
ERR_AS_00_16 = 'OPERATION IN PROGRESS';
ERR_AS_00_17 = 'CLEANING REQUESTED';
ERR_AS_02_00 = 'NO SEEK COMPLETE';
ERR_AS_04_00 = 'LOGICAL UNIT NOT READY, CAUSE NOT REPORTABLE';
ERR_AS_04_01 = 'LOGICAL UNIT IS IN PROCESS OF BECOMING READY';
ERR_AS_04_02 = 'LOGICAL UNIT NOT READY, INITIALIZING CMD. REQUIRED';
ERR_AS_04_03 = 'LOGICAL UNIT NOT READY, MANUAL INTERVENTION REQUIRED';
ERR_AS_04_04 = 'LOGICAL UNIT NOT READY, FORMAT IN PROGRESS';
ERR_AS_04_07 = 'LOGICAL UNIT NOT READY, OPERATION IN PROGRESS';
ERR_AS_04_08 = 'LOGICAL UNIT NOT READY, LONG WRITE IN PROGRESS';
ERR_AS_04_09 = 'LOGICAL UNIT NOT READY, SELF-TEST IN PROGRESS';
ERR_AS_05_00 = 'LOGICAL UNIT DOES NOT RESPOND TO SELECTION';
ERR_AS_06_00 = 'NO REFERENCE POSITION FOUND';
ERR_AS_07_00 = 'MULTIPLE PERIPHERAL DEVICES SELECTED';
ERR_AS_08_00 = 'LOGICAL UNIT COMMUNICATION FAILURE';
ERR_AS_08_01 = 'LOGICAL UNIT COMMUNICATION TIME-OUT';
ERR_AS_08_02 = 'LOGICAL UNIT COMMUNICATION PARITY ERROR';
ERR_AS_08_03 = 'LOGICAL UNIT COMMUNICATION CRC ERROR (ULTRA-DMA/32)';
ERR_AS_08_04 = 'UNREACHABLE COPY TARGET';
ERR_AS_09_00 = 'TRACK FOLLOWING ERROR';
ERR_AS_09_01 = 'TRACKING SERVO FAILURE';
ERR_AS_09_02 = 'FOCUS SERVO FAILURE';
ERR_AS_09_03 = 'SPINDLE SERVO FAILURE';
ERR_AS_09_04 = 'HEAD SELECT FAULT';
ERR_AS_0A_00 = 'ERROR LOG OVERFLOW';
ERR_AS_0B_00 = 'WARNING';
ERR_AS_0B_01 = 'WARNING - SPECIFIED TEMPERATURE EXCEEDED';
ERR_AS_0B_02 = 'WARNING - ENCLOSURE DEGRADED';
ERR_AS_0C_00 = 'WRITE ERROR';
ERR_AS_0C_07 = 'WRITE ERROR - RECOVERY NEEDED';
ERR_AS_0C_08 = 'WRITE ERROR - RECOVERY FAILED';
ERR_AS_0C_09 = 'WRITE ERROR - LOSS OF STREAMING';
ERR_AS_0C_0A = 'WRITE ERROR - PADDING BLOCKS ADDED';
ERR_AS_0D_00 = 'ERROR DETECTED BY THIRD PARTY TEMPORARY INITIATOR';
ERR_AS_0D_01 = 'THIRD PARTY DEVICE FAILURE';
ERR_AS_0D_02 = 'COPY TARGET DEVICE NOT REACHABLE';
ERR_AS_0D_03 = 'INCORRECT COPY TARGET DEVICE TYPE';
ERR_AS_0D_04 = 'COPY TARGET DEVICE DATA UNDERRUN';
ERR_AS_0D_05 = 'COPY TARGET DEVICE DATA OVERRUN';
ERR_AS_11_00 = 'UNRECOVERED READ ERROR';
ERR_AS_11_01 = 'READ RETRIES EXHAUSTED';
ERR_AS_11_02 = 'ERROR TOO LONG TO CORRECT';
ERR_AS_11_05 = 'L-EC UNCORRECTABLE ERROR';
ERR_AS_11_06 = 'CIRC UNRECOVERED ERROR';
ERR_AS_11_0D = 'DE-COMPRESSION CRC ERROR';
ERR_AS_11_0E = 'CANNOT DECOMPRESS USING DECLARED ALGORITHM';
ERR_AS_11_0F = 'ERROR READING UPC/EAN NUMBER';
ERR_AS_11_10 = 'ERROR READING ISRC NUMBER';
ERR_AS_11_11 = 'READ ERROR - LOSS OF STREAMING';
ERR_AS_14_00 = 'RECORDED ENTITY NOT FOUND';
ERR_AS_14_01 = 'RECORD NOT FOUND';
ERR_AS_15_00 = 'RANDOM POSITIONING ERROR';
ERR_AS_15_01 = 'MECHANICAL POSITIONING ERROR';
ERR_AS_15_02 = 'POSITIONING ERROR DETECTED BY READ OF MEDIUM';
ERR_AS_17_00 = 'RECOVERED DATA WITH NO ERROR CORRECTION APPLIED';
ERR_AS_17_01 = 'RECOVERED DATA WITH RETRIES';
ERR_AS_17_02 = 'RECOVERED DATA WITH POSITIVE HEAD OFFSET';
ERR_AS_17_03 = 'RECOVERED DATA WITH NEGATIVE HEAD OFFSET';
ERR_AS_17_04 = 'RECOVERED DATA WITH RETRIES AND/OR CIRC APPLIED';
ERR_AS_17_05 = 'RECOVERED DATA USING PREVIOUS SECTOR ID';
ERR_AS_17_07 = 'RECOVERED DATA WITHOUT ECC - RECOMMEND REASSIGNMENT';
ERR_AS_17_08 = 'RECOVERED DATA WITHOUT ECC - RECOMMEND REWRITE';
ERR_AS_17_09 = 'RECOVERED DATA WITHOUT ECC - DATA REWRITTEN';
ERR_AS_18_00 = 'RECOVERED DATA WITH ERROR CORRECTION APPLIED';
ERR_AS_18_01 = 'RECOVERED DATA WITH ERROR CORR. & RETRIES APPLIED';
ERR_AS_18_02 = 'RECOVERED DATA - DATA AUTO-REALLOCATED';
ERR_AS_18_03 = 'RECOVERED DATA WITH CIRC';
ERR_AS_18_04 = 'RECOVERED DATA WITH L-EC';
ERR_AS_18_05 = 'RECOVERED DATA - RECOMMEND REASSIGNMENT';
ERR_AS_18_06 = 'RECOVERED DATA - RECOMMEND REWRITE';
ERR_AS_18_08 = 'RECOVERED DATA WITH LINKING';
ERR_AS_1A_00 = 'PARAMETER LIST LENGTH ERROR';
ERR_AS_1B_00 = 'SYNCHRONOUS DATA TRANSFER ERROR';
ERR_AS_1D_00 = 'MISCOMPARE DURING VERIFY OPERATION';
ERR_AS_20_00 = 'INVALID COMMAND OPERATION CODE';
ERR_AS_21_00 = 'LOGICAL BLOCK ADDRESS OUT OF RANGE';
ERR_AS_21_01 = 'INVALID ELEMENT ADDRESS';
ERR_AS_21_02 = 'INVALID ADDRESS FOR WRITE';
ERR_AS_24_00 = 'INVALID FIELD IN CDB';
ERR_AS_24_01 = 'CDB DECRYPTION ERROR';
ERR_AS_25_00 = 'LOGICAL UNIT NOT SUPPORTED';
ERR_AS_26_00 = 'INVALID FIELD IN PARAMETER LIST';
ERR_AS_26_01 = 'PARAMETER NOT SUPPORTED';
ERR_AS_26_02 = 'PARAMETER VALUE INVALID';
ERR_AS_26_03 = 'THRESHOLD PARAMETERS NOT SUPPORTED';
ERR_AS_26_04 = 'INVALID RELEASE OF PERSISTENT RESERVATION';
ERR_AS_26_05 = 'DATA DECRYPTION ERROR';
ERR_AS_26_06 = 'TOO MANY TARGET DESCRIPTORS';
ERR_AS_26_07 = 'UNSUPPORTED TARGET DESCRIPTOR TYPE CODE';
ERR_AS_26_08 = 'TOO MANY SEGMENT DESCRIPTORS';
ERR_AS_26_09 = 'UNSUPPORTED SEGMENT DESCRIPTOR TYPE CODE';
ERR_AS_26_0A = 'UNEXPECTED INEXACT SEGMENT';
ERR_AS_26_0B = 'INLINE DATA LENGTH EXCEEDED';
ERR_AS_26_0C = 'INVALID OPERATION FOR COPY SOURCE OR DESTINATION';
ERR_AS_26_0D = 'COPY SEGMENT GRANULARITY VIOLATION';
ERR_AS_27_00 = 'WRITE PROTECTED';
ERR_AS_27_01 = 'HARDWARE WRITE PROTECTED';
ERR_AS_27_02 = 'LOGICAL UNIT SOFTWARE WRITE PROTECTED';
ERR_AS_27_03 = 'ASSOCIATED WRITE PROTECT';
ERR_AS_27_04 = 'PERSISTENT WRITE PROTECT';
ERR_AS_27_05 = 'PERMANENT WRITE PROTECT';
ERR_AS_27_06 = 'CONDITIONAL WRITE PROTECT';
ERR_AS_28_00 = 'NOT READY TO READY CHANGE, MEDIUM MAY HAVE CHANGED';
ERR_AS_28_01 = 'IMPORT OR EXPORT ELEMENT ACCESSED';
ERR_AS_29_00 = 'POWER ON, RESET, OR BUS DEVICE RESET OCCURRED';
ERR_AS_29_01 = 'POWER ON OCCURRED';
ERR_AS_29_02 = 'SCSI BUS RESET OCCURRED';
ERR_AS_29_03 = 'BUS DEVICE RESET FUNCTION OCCURRED';
ERR_AS_29_04 = 'DEVICE INTERNAL RESET';
ERR_AS_29_05 = 'TRANSCEIVER MODE CHANGED TO SINGLE-ENDED';
ERR_AS_29_06 = 'TRANSCEIVER MODE CHANGED TO LVD';
ERR_AS_2A_00 = 'PARAMETERS CHANGED';
ERR_AS_2A_01 = 'MODE PARAMETERS CHANGED';
ERR_AS_2A_02 = 'LOG PARAMETERS CHANGED';
ERR_AS_2A_03 = 'RESERVATIONS PREEMPTED';
ERR_AS_2A_04 = 'RESERVATIONS RELEASED';
ERR_AS_2A_05 = 'REGISTRATIONS PREEMPTED';
ERR_AS_2B_00 = 'COPY CANNOT EXECUTE SINCE HOST CANNOT DISCONNECT';
ERR_AS_2C_00 = 'COMMAND SEQUENCE ERROR';
ERR_AS_2C_03 = 'CURRENT PROGRAM AREA IS NOT EMPTY';
ERR_AS_2C_04 = 'CURRENT PROGRAM AREA IS EMPTY';
ERR_AS_2C_06 = 'PERSISTENT PREVENT CONFLICT';
ERR_AS_2E_00 = 'INSUFFICIENT TIME FOR OPERATION';
ERR_AS_2F_00 = 'COMMANDS CLEARED BY ANOTHER INITIATOR';
ERR_AS_30_00 = 'INCOMPATIBLE MEDIUM INSTALLED';
ERR_AS_30_01 = 'CANNOT READ MEDIUM - UNKNOWN FORMAT';
ERR_AS_30_02 = 'CANNOT READ MEDIUM - INCOMPATIBLE FORMAT';
ERR_AS_30_03 = 'CLEANING CARTRIDGE INSTALLED';
ERR_AS_30_04 = 'CANNOT WRITE MEDIUM - UNKNOWN FORMAT';
ERR_AS_30_05 = 'CANNOT WRITE MEDIUM - INCOMPATIBLE FORMAT';
ERR_AS_30_06 = 'CANNOT FORMAT MEDIUM - INCOMPATIBLE MEDIUM';
ERR_AS_30_07 = 'CLEANING FAILURE';
ERR_AS_30_08 = 'CANNOT WRITE - APPLICATION CODE MISMATCH';
ERR_AS_30_09 = 'CURRENT SESSION NOT FIXATED FOR APPEND';
ERR_AS_30_10 = 'MEDIUM NOT FORMATTED';
ERR_AS_31_00 = 'MEDIUM FORMAT CORRUPTED';
ERR_AS_31_01 = 'FORMAT COMMAND FAILED';
ERR_AS_31_02 = 'ZONED FORMATTING FAILED DUE TO SPARE LINKING';
ERR_AS_34_00 = 'ENCLOSURE FAILURE';
ERR_AS_35_00 = 'ENCLOSURE SERVICES FAILURE';
ERR_AS_35_01 = 'UNSUPPORTED ENCLOSURE FUNCTION';
ERR_AS_35_02 = 'ENCLOSURE SERVICES UNAVAILABLE';
ERR_AS_35_03 = 'ENCLOSURE SERVICES TRANSFER FAILURE';
ERR_AS_35_04 = 'ENCLOSURE SERVICES TRANSFER REFUSED';
ERR_AS_37_00 = 'ROUNDED PARAMETER';
ERR_AS_39_00 = 'SAVING PARAMETERS NOT SUPPORTED';
ERR_AS_3A_00 = 'MEDIUM NOT PRESENT';
ERR_AS_3A_01 = 'MEDIUM NOT PRESENT - TRAY CLOSED';
ERR_AS_3A_02 = 'MEDIUM NOT PRESENT - TRAY OPEN';
ERR_AS_3A_03 = 'MEDIUM NOT PRESENT - LOADABLE';
ERR_AS_3A_04 = 'MEDIUM NOT PRESENT - MEDIUM AUXILIARY MEMORY ACCESSIBLE';
ERR_AS_3B_0D = 'MEDIUM DESTINATION ELEMENT FULL';
ERR_AS_3B_0E = 'MEDIUM SOURCE ELEMENT EMPTY';
ERR_AS_3B_0F = 'END OF MEDIUM REACHED';
ERR_AS_3B_11 = 'MEDIUM MAGAZINE NOT ACCESSIBLE';
ERR_AS_3B_12 = 'MEDIUM MAGAZINE REMOVED';
ERR_AS_3B_13 = 'MEDIUM MAGAZINE INSERTED';
ERR_AS_3B_14 = 'MEDIUM MAGAZINE LOCKED';
ERR_AS_3B_15 = 'MEDIUM MAGAZINE UNLOCKED';
ERR_AS_3B_16 = 'MECHANICAL POSITIONING OR CHANGER ERROR';
ERR_AS_3D_00 = 'INVALID BITS IN IDENTIFY MESSAGE';
ERR_AS_3E_00 = 'LOGICAL UNIT HAS NOT SELF-CONFIGURED YET';
ERR_AS_3E_01 = 'LOGICAL UNIT FAILURE';
ERR_AS_3E_02 = 'TIMEOUT ON LOGICAL UNIT';
ERR_AS_3E_03 = 'LOGICAL UNIT FAILED SELF-TEST';
ERR_AS_3E_04 = 'LOGICAL UNIT UNABLE TO UPDATE SELF-TEST LOG';
ERR_AS_3F_00 = 'TARGET OPERATING CONDITIONS HAVE CHANGED';
ERR_AS_3F_01 = 'MICROCODE HAS BEEN CHANGED';
ERR_AS_3F_02 = 'CHANGED OPERATING DEFINITION';
ERR_AS_3F_03 = 'INQUIRY DATA HAS CHANGED';
ERR_AS_3F_04 = 'COMPONENT DEVICE ATTACHED';
ERR_AS_3F_05 = 'DEVICE IDENTIFIER CHANGED';
ERR_AS_3F_06 = 'REDUNDANCY GROUP CREATED OR MODIFIED';
ERR_AS_3F_07 = 'REDUNDANCY GROUP DELETED';
ERR_AS_3F_08 = 'SPARE CREATED OR MODIFIED';
ERR_AS_3F_09 = 'SPARE DELETED';
ERR_AS_3F_0A = 'VOLUME SET CREATED OR MODIFIED';
ERR_AS_3F_0B = 'VOLUME SET DELETED';
ERR_AS_3F_0C = 'VOLUME SET DEASSIGNED';
ERR_AS_3F_0D = 'VOLUME SET REASSIGNED';
ERR_AS_3F_0E = 'REPORTED LUNS DATA HAS CHANGED';
ERR_AS_3F_0F = 'ECHO BUFFER OVERWRITTEN';
ERR_AS_3F_10 = 'MEDIUM LOADABLE';
ERR_AS_3F_11 = 'MEDIUM AUXILIARY MEMORY ACCESSIBLE';
ERR_AS_43_00 = 'MESSAGE ERROR';
ERR_AS_44_00 = 'INTERNAL TARGET FAILURE';
ERR_AS_45_00 = 'SELECT OR RESELECT FAILURE';
ERR_AS_46_00 = 'UNSUCCESSFUL SOFT RESET';
ERR_AS_47_00 = 'SCSI PARITY ERROR';
ERR_AS_47_01 = 'DATA PHASE CRC ERROR DETECTED';
ERR_AS_47_02 = 'SCSI PARITY ERROR DETECTED DURING ST DATA PHASE';
ERR_AS_47_03 = 'INFORMATION UNIT CRC ERROR DETECTED';
ERR_AS_47_04 = 'ASYNCHRONOUS INFORMATION PROTECTION ERROR DETECTED';
ERR_AS_48_00 = 'INITIATOR DETECTED ERROR MESSAGE RECEIVED';
ERR_AS_49_00 = 'INVALID MESSAGE ERROR';
ERR_AS_4A_00 = 'COMMAND PHASE ERROR';
ERR_AS_4B_00 = 'DATA PHASE ERROR';
ERR_AS_4C_00 = 'LOGICAL UNIT FAILED SELF-CONFIGURATION';
ERR_AS_4E_00 = 'OVERLAPPED COMMANDS ATTEMPTED';
ERR_AS_51_00 = 'ERASE FAILURE';
ERR_AS_51_01 = 'ERASE FAILURE - INCOMPLETE ERASE OPERATION DETECTED';
ERR_AS_53_00 = 'MEDIA LOAD OR EJECT FAILED';
ERR_AS_53_02 = 'MEDIUM REMOVAL PREVENTED';
ERR_AS_55_02 = 'INSUFFICIENT RESERVATION RESOURCES';
ERR_AS_55_03 = 'INSUFFICIENT RESOURCES';
ERR_AS_55_04 = 'INSUFFICIENT REGISTRATION RESOURCES';
ERR_AS_57_00 = 'UNABLE TO RECOVER TABLE-OF-CONTENTS';
ERR_AS_5A_00 = 'OPERATOR REQUEST OR STATE CHANGE INPUT';
ERR_AS_5A_01 = 'OPERATOR MEDIUM REMOVAL REQUEST';
ERR_AS_5A_02 = 'OPERATOR SELECTED WRITE PROTECT';
ERR_AS_5A_03 = 'OPERATOR SELECTED WRITE PERMIT';
ERR_AS_5B_00 = 'LOG EXCEPTION';
ERR_AS_5B_01 = 'THRESHOLD CONDITION MET';
ERR_AS_5B_02 = 'LOG COUNTER AT MAXIMUM';
ERR_AS_5B_03 = 'LOG LIST CODES EXHAUSTED';
ERR_AS_5D_00 = 'FAILURE PREDICTION THRESHOLD EXCEEDED';
ERR_AS_5D_01 = 'MEDIA FAILURE PREDICTION THRESHOLD EXCEEDED';
ERR_AS_5D_02 = 'LOGICAL UNIT FAILURE PREDICTION THRESHOLD EXCEEDED';
ERR_AS_5D_03 = 'SPARE AREA EXHAUSTION PREDICTION THRESHOLD EXCEEDED';
ERR_AS_5D_FF = 'FAILURE PREDICTION THRESHOLD EXCEEDED (FALSE)';
ERR_AS_5E_00 = 'LOW POWER CONDITION ON';
ERR_AS_5E_01 = 'IDLE CONDITION ACTIVATED BY TIMER';
ERR_AS_5E_02 = 'STANDBY CONDITION ACTIVATED BY TIMER';
ERR_AS_5E_03 = 'IDLE CONDITION ACTIVATED BY COMMAND';
ERR_AS_5E_04 = 'STANDBY CONDITION ACTIVATED BY COMMAND';
ERR_AS_63_00 = 'END OF USER AREA ENCOUNTERED ON THIS TRACK';
ERR_AS_63_01 = 'PACKET DOES NOT FIT IN AVAILABLE SPACE';
ERR_AS_64_00 = 'ILLEGAL MODE FOR THIS TRACK';
ERR_AS_64_01 = 'INVALID PACKET SIZE';
ERR_AS_65_00 = 'VOLTAGE FAULT';
ERR_AS_6F_00 = 'COPY PROTECTION KEY EXCHANGE FAILURE - AUTHENTICATION FAILURE';
ERR_AS_6F_01 = 'COPY PROTECTION KEY EXCHANGE FAILURE - KEY NOT PRESENT';
ERR_AS_6F_02 = 'COPY PROTECTION KEY EXCHANGE FAILURE - KEY NOT ESTABLISHED';
ERR_AS_6F_03 = 'READ OF SCRAMBLED SECTOR WITHOUT AUTHENTICATION';
ERR_AS_6F_04 = 'MEDIA REGION CODE IS MISMATCHED TO LOGICAL UNIT REGION';
ERR_AS_6F_05 = 'DRIVE REGION MUST BE PERMANENT/REGION RESET COUNT ERROR';
ERR_AS_72_00 = 'SESSION FIXATION ERROR';
ERR_AS_72_01 = 'SESSION FIXATION ERROR WRITING LEAD-IN';
ERR_AS_72_02 = 'SESSION FIXATION ERROR WRITING LEAD-OUT';
ERR_AS_72_03 = 'SESSION FIXATION ERROR - INCOMPLETE TRACK IN SESSION';
ERR_AS_72_04 = 'EMPTY OR PARTIALLY WRITTEN RESERVED TRACK';
ERR_AS_72_05 = 'NO MORE TRACK RESERVATIONS ALLOWED';
ERR_AS_73_00 = 'CD CONTROL ERROR';
ERR_AS_73_01 = 'POWER CALIBRATION AREA ALMOST FULL';
ERR_AS_73_02 = 'POWER CALIBRATION AREA IS FULL';
ERR_AS_73_03 = 'POWER CALIBRATION AREA ERROR';
ERR_AS_73_04 = 'PROGRAM MEMORY AREA UPDATE FAILURE';
ERR_AS_73_05 = 'PROGRAM MEMORY AREA IS FULL';
ERR_AS_73_06 = 'RMA/PMA IS ALMOST FULL';
ERR_INVALIDREQUEST = 'INVALID REQUEST';
ERR_INVALIDHA = 'INVALID HOST ADAPTER';
ERR_NODEVICE = 'NO DEVICE';
ERR_INVALIDSRB = 'INVALID SRB';
ERR_BUFFERALIGNMENT = 'BUFFER ALIGNMENT';
ERR_ASPIBUSY = 'ASPI IS BUSY';
ERR_BUFFERTOOBIG = 'BUFFER TOO BIG';
ERR_TIMEOUT = 'COMMAND TIMEOUT';
ERR_SRBTIMEOUT = 'SRB TIMEOUT';
ERR_MESSAGEREJECT = 'MESSAGE REJECT';
ERR_BUSRESET = 'BUS RESET';
ERR_PARITYERR = 'PARITY ERROR';
ERR_REQUESTSENSEFAILED = 'REQUEST SENSE FAILED';
ERR_SELECTIONTIMEOUT = 'SELECTION TIMEOUT';
ERR_DATAOVERRUN = 'DATA OVERRUN';
ERR_UNEXPECTEDBUSFREE= 'UNEXPECTED BUS FREE';
ERR_CHECKCONDITION = 'CHECK CONDITION';
ERR_TARGETBUSY = 'TARGET BUSY';
ERR_TARGETCONFLICT = 'TARGET RESERVATION CONFLICT';
ERR_QUEFULL = 'TARGET QUEUE FULL';
ERR_RECOVEREDERROR = 'RECOVERED ERROR';
ERR_NOTREADY = 'NOT READY';
ERR_MEDIUMERROR = 'MEDIUM ERROR';
ERR_HARDWAREERROR = 'HARDWARE ERROR';
ERR_ILLEGALREQUEST = 'ILLEGAL REQUEST';
ERR_UNITATTENTION = 'UNIT ATTENTION';
ERR_DATAPROTECT = 'DATA PROTECT';
ERR_ERASECHECK = 'ERASE CHECK';
ERR_COPYABORTED = 'COPYABORTED';
ERR_ABORTEDCOMMAND = 'ABORTED COMMAND';
ERR_VOLUMEOVERFLOW = 'VOLUME OVERFLOW';
ERR_MISCOMPARE = 'MISCOMPARE';
ERR_RESERVED = 'RESERVED';
ERR_FILEMARK = 'FILEMARK';
ERR_ENDOFMEDIA = 'END OF MEDIA';
ERR_ILLEGALLENGTH = 'ILLEGAL LENGTH';
ERR_INCORRECTLENGTH = 'INCORRECT LENGTH';
ERR_NONE = '';
ERR_UNKNOWN = 'UNKNOWN';
ERR_NOERROR = 'NO ERROR';
ERR_ABORTED = 'OPERATION ABORTED BY USER';
ERR_FILEINUSE = 'CAN''T OPEN FILE "%s" OR FILE IS IN USES BY OTHER SOFTWARE';
ERR_CREATEFILE = 'CAN''T CREATE FILE "%s"';
ERR_DEVICEBUSY = 'WRITER BUSY/BUFFER FULL';
ERR_WRITEERROR = 'WRITER ERROR';
ERR_INVALIDDEVICE = 'INVALID DEVICE ID / NOT A CD OR DVD DRIVE';
ERR_NOTSUPPORTED = 'NOT SUPPORTED';
ERR_NEXTADRESS = 'ERROR GETTING NEXT WRITABLE ADDRESS';
ERR_TOOMUCHDATA = 'TOO MUCH DATA FOR THIS MODE';
ERR_MAXDIRS = 'MAXIMUM DIRECTORIES CAN BE %d';
ERR_MAXFILES = 'MAXIMUM FILES CAN BE %d';
ERR_INVALIDDESTDIR = 'INVALID DESTINATION PATH';
ERR_INVALIDFILENAME = 'ERROR IMPORTING SESSION, FILE NAME LENGTH EXCEEDS 120 CHARS';
ERR_IMPORTSESSION = 'ERROR IMPORTING SESSION';
ERR_ISOIMAGENOTFOUND = 'ERROR IMPORTING SESSION %d (ISO IMAGE NOT FOUND)';
ERR_1 = 'INTERNAL ERROR 0001';
ERR_2 = 'INTERNAL ERROR 0002';
ERR_3 = 'INTERNAL ERROR 0003';
ERR_4 = 'INTERNAL ERROR 0004';
ERR_5 = 'INTERNAL ERROR 0005';
ERR_NONEMPTYDISC = 'NEED EMPTY DISC FOR ISO BURNING';
ERR_SREADERROR = 'Stream read error';
ERR_SWRITEERROR = 'Stream write error';
ERR_SInvalidImage = 'Invalid stream format';
CUESEND_ERR = 'SEND CUE SHEET FAILED';
CUEFILE_ERR_1 = 'UNEXPECTED END OF LINE';
CUEFILE_ERR_2 = 'INVALID FIELD "%s" IN PARAMETER LIST';
CUEFILE_ERR_3 = 'FILE NOT FOUND';
CUEFILE_ERR_4 = 'INVALID COMMAND "%s"';
MSG_WAIT15MIN = 'WRITING LEAD-OUT (THIS CAN TAKE APPROXIMATELY 15-20 MINUTES)';
MSG_WRITESTART = 'STARTING WRITE PROCESS ON %s AT %s';
MSG_ERASESTART = 'STARTING ERASE PROCESS ON %s AT %s';
MSG_EXTRACTING_FILE = 'EXTRACTING FILE %s TO %s';
MSG_TESTWRITE = 'TEST/DUMMY WRITE';
MSG_IMPORTINGSESSION = 'IMPORTING SESSION # %d';
implementation
end.
|
{$G+}
Unit Alloc;
{
Memory allocation and deallocation routines (C type), without using Heap
by Maple Leaf, 1996
-------------------
386 registers used.
Last update: 2nd May 1996
}
Interface
{ --------<<< Conventional memory >>>---------- }
Const
UseUMB : Boolean = True; { If TRUE, the malloc routine will try to allocate
the memory block into the Upper Memory (if possible) }
function malloc(size:LongInt):pointer;
{ Allocates a memory block, returns a pointer to it. Offset is always 0. (paragraph alligned) }
function calloc(size:LongInt):pointer;
{ Like MALLOC, but it does initialize the block with 0 }
function halloc(size:LongInt):word;
{ Like MALLOC, returns the segment nr. of the allocated block }
function realloc(var MemPtr:Pointer; size:LongInt):LongInt;
{ Reallocates a memory block, returns the new maximal possible size (could be with up to 16 bytes greater than SIZE) }
{ Warning: if returned value is less than SIZE, then the reallocation IS NOT DONE, you must
do it by yourself using this value as a parameter in realloc function. }
function free(var MemPtr:pointer):boolean;
{ Deallocates a memory block, returns True if successful }
function hfree(var MemSeg:word):boolean;
{ Like FREE, uses block's seg, returns True if successful }
function mavail:LongInt;
{ Returns the amount of bytes in the greatest possible block }
function umblink(LinkStatus:boolean):boolean;
{ Returns the current status of UMB linkage and set it to LinkStatus }
Implementation
function _malloc(size:LongInt):pointer;assembler;
asm
db 66h; mov ax,word ptr Size
test ax,0Fh
pushf
db 66h; shr ax,4
popf
jz @1
db 66h; inc ax
@1: db 66h; mov bx,ax { ebx:=((size div 16) + 1) paragraphs }
mov ah,48h
clc
int 21h {Allocate memory}
jc @Error
xor dx,dx
xchg ax,dx
jmp @Exit
@Error:
xor dx,dx
xor ax,ax
@Exit:
end;
function _realloc(var MemPtr:Pointer;size:LongInt):LongInt;assembler;
asm
les di,MemPtr
les di,es:[di]
db 66h; mov ax,word ptr Size
test ax,0Fh
pushf
db 66h; shr ax,4
popf
jz @1
db 66h; inc ax
@1: db 66h; mov bx,ax { ebx:=(NewSize div 16)+1) paragraphs }
clc
mov ah,4ah
int 21h
db 66h; rol bx,16
xor bx,bx
db 66h; rol bx,16+4
mov ax,bx
db 66h; shr bx,16
mov dx,bx
@Exit:
end;
function _free(var MemPtr:pointer):boolean;assembler;
asm
les di,MemPtr
les di,es:[di]
mov ax,es
or ax,ax
jz @Exit
mov ah,49h
clc
int 21h
mov ax,0
jc @Exit
les di,MemPtr
mov word ptr es:[di],0
mov word ptr es:[di+2],0
mov ax,1
@Exit:
end;
function _mavail:LongInt;assembler;
asm
mov ax,4800h
mov bx,0FFFFh
clc
int 21h
clc
xor dx,dx
mov ax,bx
mov cx,16
mul cx
end;
function umblink(LinkStatus:boolean):boolean;assembler;
asm
mov ax,5802h
int 21h
mov ah,0
jc @getout
mov ah,al
push ax
mov ax,5803h
xor bh,bh
mov bl,LinkStatus
int 21h
pop ax
@getout:
mov al,ah
end;
function malloc;
var SaveLink:Boolean;
begin
if UseUMB then SaveLink:=umblink(true);
malloc:=_malloc(size);
if UseUMB then umblink(SaveLink);
end;
function free;
var SaveLink:Boolean;
begin
if UseUMB then SaveLink:=umblink(true);
free:=_free(MemPtr);
if UseUMB then umblink(SaveLink);
end;
function realloc;
var SaveLink:Boolean;
begin
if UseUMB then SaveLink:=umblink(true);
realloc:=_realloc(MemPtr,Size);
if UseUMB then umblink(SaveLink);
end;
function mavail;
var SaveLink:Boolean;
begin
if UseUMB then SaveLink:=umblink(true);
mavail:=_mavail;
if UseUMB then umblink(SaveLink);
end;
function calloc;
var p:pointer;
begin
p:=malloc(size);
asm
cmp word ptr p[2],0 {nil ?}
je @getout
db 66h; mov cx,word ptr size
les di,p
mov ax,1000h
@1: mov es:[di],al
dec ah
jg @2
mov ah,10h
mov di,es
inc di
mov es,di
xor di,di
@2: db 66h; dec cx {ecx}
db 66h; jnz @1
@getout:
end;
calloc:=p;
end;
function halloc;
var p:pointer;
begin
p:=malloc(size);
halloc:=word(longint(p) shr 16);
end;
function hfree;
var p:pointer;
begin
p:=ptr(MemSeg,0);
MemSeg:=0;
hfree:=free(p);
end;
begin
end. |
unit ccCylindricalCapFrame;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, ExtCtrls, StdCtrls, IniFiles,
ccBaseFrame, ccSphericalCapFrame;
type
{ TCylindricalCapFrame }
TCylindricalCapFrame = class(TSphericalCapFrame)
CbLengthUnits: TComboBox;
EdLength: TEdit;
LblCapaPerLength: TLabel;
LblLength: TLabel;
TxtCapaPerLength: TEdit;
TxtCapaPerLengthUnits: TLabel;
private
{ private declarations }
protected
procedure ClearResults; override;
procedure SetEditLeft(AValue: Integer); override;
public
{ public declarations }
constructor Create(AOwner: TComponent); override;
procedure Calculate; override;
procedure ReadFromIni(ini: TCustomIniFile); override;
function ValidData(out AMsg: String; out AControl: TWinControl): Boolean; override;
procedure WriteToIni(ini: TCustomIniFile); override;
end;
implementation
{$R *.lfm}
uses
ccGlobal;
constructor TCylindricalCapFrame.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FIniKey := 'Cylindrical';
end;
procedure TCylindricalCapFrame.Calculate;
var
ra, rb, eps, L, A, capa : extended;
fa, fc, fL : double;
capaFmt: String;
capaUnits, areaUnits, lengthUnits: string;
begin
try
if (EdRadiusA.Text = '') or not TryStrToFloat(EdRadiusA.Text, ra) then exit;
if ra <= 0 then exit;
if (EdRadiusB.Text = '') or not TryStrToFloat(EdRadiusB.Text, rb) then exit;
if (ra <= 0) or (rb <= 0) or (ra >= rb) then exit;
if (EdLength.Text = '') or not TryStrToFloat(EdLength.Text, L) then exit;
if (EdEps.Text = '') or not TryStrToFloat(EdEps.Text, eps) then exit;
if CbRadiusAUnits.ItemIndex = -1 then exit;
if CbRadiusBUnits.ItemIndex = -1 then exit;
if CbLengthUnits.ItemIndex = -1 then exit;
if CbAreaUnits.ItemIndex = -1 then exit;
if CbCapaUnits.ItemIndex = -1 then exit;
ra := ra * Lenfactor[TLenUnits(CbRadiusAUnits.ItemIndex)];
rb := rb * LenFactor[TLenUnits(CbRadiusBUnits.ItemIndex)];
L := L * Lenfactor[TLenUnits(CbLengthUnits.ItemIndex)];
fL := LenFactor[TLenUnits(CbLengthUnits.ItemIndex)];
fa := AreaFactor[TAreaUnits(CbAreaUnits.ItemIndex)];
fc := CapaFactor[TCapaUnits(CbCapaUnits.ItemIndex)];
A := pi * (ra + rb) * L;
Capa := TwoPi * eps0 * eps * L / ln(rb / ra);
if CbCapaUnits.Text='F' then
capaFmt := CapaExpFormat else
capaFmt := CapaStdFormat;
capaUnits := CbCapaUnits.Items[CbCapaUnits.ItemIndex];
areaUnits := CbAreaUnits.Items[CbAreaUnits.ItemIndex];
lengthUnits := CbLengthUnits.Items[CbLengthUnits.ItemIndex];
// Area
TxtArea.Text := FormatFloat(AreaStdFormat, A / fa);
// Capacitance
TxtCapa.Text := FormatFloat(capafmt, capa / fc);
// Capacitance per area
TxtCapaPerArea.Text := FormatFloat(CapaPerAreaFormat, (capa / A) * (fa / fc));
TxtCapaPerAreaUnits.Caption := Format('%s/%s', [capaUnits, areaUnits]);
// Capacitance per length
TxtCapaPerLengthUnits.caption := Format('%s/%s', [capaUnits, lengthUnits]);
TxtCapaPerLength.Text := FormatFloat(CapaPerLengthFormat, (capa / L) * (fL / fc));
except
ClearResults;
end;
end;
procedure TCylindricalCapFrame.ClearResults;
begin
inherited;
TxtCapaPerLength.Clear;
end;
procedure TCylindricalCapFrame.ReadFromIni(ini: TCustomIniFile);
var
fs: TFormatSettings;
s: String;
value: Extended;
begin
inherited ReadFromIni(ini);
fs := DefaultFormatSettings;
fs.DecimalSeparator := '.';
s := ini.ReadString(FIniKey, 'Length', '');
if (s <> '') and TryStrToFloat(s, value, fs) then
EdLength.Text := FloatToStr(value) else
EdLength.Clear;
s := ini.ReadString(FIniKey, 'Length units', '');
if (s <> '') then
CbLengthUnits.ItemIndex := CbLengthUnits.Items.IndexOf(s) else
CbLengthUnits.ItemIndex := -1;
Calculate;
end;
procedure TcylindricalCapFrame.SetEditLeft(AValue: Integer);
begin
if AValue = FEditLeft then exit;
inherited;
Panel1. Height := TxtCapaPerLength.Top + TxtCapaPerLength.Height + TxtArea.Top;
end;
function TCylindricalCapFrame.ValidData(out AMsg: String; out AControl: TWinControl
): Boolean;
begin
Result := inherited ValidData(AMsg, AControl);
if not Result then
exit;
if not IsValidNumber(EdLength, AMsg) then begin
AControl := EdLength;
exit;
end;
Result := true;
end;
procedure TCylindricalCapFrame.WriteToIni(ini: TCustomIniFile);
var
fs: TFormatSettings;
value: Extended;
begin
inherited WriteToIni(ini);
fs := DefaultFormatSettings;
fs.DecimalSeparator := '.';
if (EdLength.Text <> '') and TryStrToFloat(EdLength.Text, value) then
ini.WriteString(FIniKey, 'Length', FloatToStr(value, fs));
if CbLengthUnits.ItemIndex >= 0 then
ini.WriteString(FIniKey, 'Length units', CbLengthUnits.Items[CbLengthUnits.ItemIndex]);
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC Teradata driver }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$HPPEMIT LINKUNIT}
unit FireDAC.Phys.TData;
interface
uses
System.Classes,
FireDAC.Stan.Intf, FireDAC.Stan.Error,
FireDAC.Phys, FireDAC.Phys.ODBCCli, FireDAC.Phys.ODBCWrapper, FireDAC.Phys.ODBCBase;
type
ETDataNativeException = class;
TFDPhysTDataDriverLink = class;
/// <summary> ETDataNativeException class representing a Teradata driver exception.
/// Use this class to handle Teradata driver specific exception. </summary>
ETDataNativeException = class(EODBCNativeException)
public
function AppendError(AHandle: TODBCHandle; ARecNum: SQLSmallint;
const ASQLState: String; ANativeError: SQLInteger; const ADiagMessage,
AResultMessage, ACommandText, AObject: String;
AKind: TFDCommandExceptionKind; ACmdOffset, ARowIndex: Integer): TFDDBError; override;
end;
/// <summary> Use the TFDPhysTDataDriverLink component to link the Teradata driver
/// to an application and to set it up. Generally, it is enough to include the
/// FireDAC.Phys.TData unit in your application uses clause. </summary>
[ComponentPlatformsAttribute(pfidWindows or pfidOSX or pfidLinux)]
TFDPhysTDataDriverLink = class(TFDPhysODBCBaseDriverLink)
protected
function GetBaseDriverID: String; override;
end;
{-------------------------------------------------------------------------------}
implementation
uses
System.SysUtils, System.Variants, Data.DB,
FireDAC.Stan.Consts, FireDAC.Stan.Util, FireDAC.Stan.Param, FireDAC.Stan.Option,
FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys.SQLGenerator, FireDAC.Phys.TDataMeta,
FireDAC.Phys.TDataDef;
const
C_CharSets = 'ASCII;UTF8;UTF16;LATIN1252_0A;LATIN9_0A;LATIN1_0A;KANJISJIS_0S;' +
'KANJIEUC_0U;TCHBIG5_1R0;SCHGB2312_1T0;HANGULKSC5601_2R4';
C_Teradata = 'Teradata';
C_ANSI = 'ANSI';
type
TFDPhysTDataDriver = class;
TFDPhysTDataConnection = class;
TFDPhysTDataCommand = class;
TFDPhysTDataDriver = class(TFDPhysODBCDriverBase)
protected
class function GetBaseDriverID: String; override;
class function GetBaseDriverDesc: String; override;
class function GetRDBMSKind: TFDRDBMSKind; override;
class function GetConnectionDefParamsClass: TFDConnectionDefParamsClass; override;
procedure InternalLoad; override;
function InternalCreateConnection(AConnHost: TFDPhysConnectionHost): TFDPhysConnection; override;
procedure GetODBCConnectStringKeywords(AKeywords: TStrings); override;
function BuildODBCConnectString(const AConnectionDef: IFDStanConnectionDef): String; override;
function GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable; override;
end;
TFDPhysTDataConnection = class(TFDPhysODBCConnectionBase)
private
FExtendedMetadata: Boolean;
FSessionMode: TFDTDataSessionMode;
FCharacterSet: String;
function QueryValue(const ASQL: String): String;
procedure UpdateCurrentSchema;
protected
function InternalCreateCommand: TFDPhysCommand; override;
function InternalCreateCommandGenerator(const ACommand:
IFDPhysCommand): TFDPhysCommandGenerator; override;
function InternalCreateMetadata: TObject; override;
procedure GetStrsMaxSizes(AStrDataType: SQLSmallint; AFixedLen: Boolean;
out ACharSize, AByteSize: Integer); override;
function GetExceptionClass: EODBCNativeExceptionClass; override;
procedure InternalConnect; override;
procedure InternalSetMeta; override;
procedure InternalChangePassword(const AUserName, AOldPassword,
ANewPassword: String); override;
function GetLastAutoGenValue(const AName: String): Variant; override;
end;
TFDPhysTDataCommand = class(TFDPhysODBCCommand)
private
FAGKR: Integer;
FAutoGenCol: TODBCColumn;
procedure DoExtendedDescribe;
procedure DoINTODescribe;
procedure UpdateInfoAfterExecution;
protected
// TFDPhysODBCCommand
procedure CreateDescribeInfos; override;
// TFDPhysCommand
function InternalUseStandardMetadata: Boolean; override;
procedure InternalPrepare; override;
procedure InternalUnprepare; override;
procedure InternalExecute(ATimes, AOffset: Integer; var ACount: TFDCounter); override;
function InternalOpen(var ACount: TFDCounter): Boolean; override;
end;
{-------------------------------------------------------------------------------}
{ ETDataNativeException }
{-------------------------------------------------------------------------------}
function ETDataNativeException.AppendError(AHandle: TODBCHandle;
ARecNum: SQLSmallint; const ASQLState: String; ANativeError: SQLInteger;
const ADiagMessage, AResultMessage, ACommandText, AObject: String;
AKind: TFDCommandExceptionKind; ACmdOffset, ARowIndex: Integer): TFDDBError;
var
sObj: String;
procedure ExtractObjName1;
var
i1, i2: Integer;
begin
// first 'xxxx' - object name
i1 := Pos('''', ADiagMessage);
if i1 <> 0 then begin
i2 := Pos('''', ADiagMessage, i1 + 1);
if i2 <> 0 then
sObj := Copy(ADiagMessage, i1 + 1, i2 - i1 - 1);
end;
end;
procedure ExtractObjName2;
var
i: Integer;
begin
// ... in 'xxxx' - object name
i := Pos('in ', ADiagMessage);
if i <> 0 then
sObj := Copy(ADiagMessage, i + 3, Length(ADiagMessage));
end;
begin
// ekNoDataFound
// ekTooManyRows
// ekServerOutput
// ekArrExecMalfunc
sObj := AObject;
case ANativeError of
-3807,
-5495:
begin
ExtractObjName1;
AKind := ekObjNotExists;
end;
-8017:
AKind := ekUserPwdInvalid;
-3032:
AKind := ekUserPwdExpired;
-2802,
-2803:
begin
ExtractObjName2;
AKind := ekUKViolated;
end;
-2700,
-3513:
AKind := ekFKViolated;
-2631,
-7423:
AKind := ekRecordLocked;
-3939,
-3812,
-3813:
// In some cases (eg N "?" markers and M TFDParam's, where N > M)
// Teradata ODBC raises Access Violation.
AKind := ekInvalidParams;
end;
Result := inherited AppendError(AHandle, ARecNum, ASQLState, ANativeError,
ADiagMessage, AResultMessage, ACommandText, sObj, AKind, ACmdOffset, ARowIndex);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysTDataDriverLink }
{-------------------------------------------------------------------------------}
function TFDPhysTDataDriverLink.GetBaseDriverID: String;
begin
Result := S_FD_TDataId;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysTDataDriver }
{-------------------------------------------------------------------------------}
class function TFDPhysTDataDriver.GetBaseDriverID: String;
begin
Result := S_FD_TDataId;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysTDataDriver.GetBaseDriverDesc: String;
begin
Result := 'Teradata';
end;
{-------------------------------------------------------------------------------}
class function TFDPhysTDataDriver.GetRDBMSKind: TFDRDBMSKind;
begin
Result := TFDRDBMSKinds.Teradata;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysTDataDriver.GetConnectionDefParamsClass: TFDConnectionDefParamsClass;
begin
Result := TFDPhysTDataConnectionDefParams;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataDriver.InternalLoad;
begin
inherited InternalLoad;
if ODBCDriver = '' then
ODBCDriver := FindBestDriver(['Teradata']);
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDataDriver.InternalCreateConnection(
AConnHost: TFDPhysConnectionHost): TFDPhysConnection;
begin
Result := TFDPhysTDataConnection.Create(Self, AConnHost);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataDriver.GetODBCConnectStringKeywords(AKeywords: TStrings);
begin
inherited GetODBCConnectStringKeywords(AKeywords);
AKeywords.Add(S_FD_ConnParam_Common_Server + '=DBCNAME');
AKeywords.Add(S_FD_ConnParam_Common_Database);
AKeywords.Add(S_FD_ConnParam_Common_CharacterSet);
AKeywords.Add(S_FD_ConnParam_Common_NewPassword + '=PWD2');
AKeywords.Add(S_FD_ConnParam_Common_OSAuthent + '=UseIntegratedSecurity');
AKeywords.Add(S_FD_ConnParam_TData_SessionMode);
AKeywords.Add(S_FD_ConnParam_TData_Encrypt + '=UseDataEncryption');
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDataDriver.BuildODBCConnectString(const AConnectionDef: IFDStanConnectionDef): String;
var
s: String;
begin
Result := inherited BuildODBCConnectString(AConnectionDef);
if TFDPhysTDataConnectionDefParams(AConnectionDef.Params).ExtendedMetadata then
s := S_FD_Yes
else
s := S_FD_No;
Result := Result + ';EnableExtendedStmtInfo=' + s;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDataDriver.GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable;
var
oView: TFDDatSView;
begin
Result := inherited GetConnParams(AKeys, AParams);
oView := Result.Select('Name=''' + S_FD_ConnParam_Common_Database + '''');
if oView.Rows.Count = 1 then begin
oView.Rows[0].BeginEdit;
oView.Rows[0].SetValues('LoginIndex', 4);
oView.Rows[0].EndEdit;
end;
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Server, '@S', '', S_FD_ConnParam_Common_Server, 3]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_OSAuthent, '@Y', S_FD_No, S_FD_ConnParam_Common_OSAuthent, 2]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_CharacterSet, C_CharSets, 'ASCII', S_FD_ConnParam_Common_CharacterSet, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_TData_SessionMode, C_Teradata + ';' + C_ANSI, C_Teradata, S_FD_ConnParam_TData_SessionMode, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_TData_Encrypt, '@Y', S_FD_No, S_FD_ConnParam_TData_Encrypt, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_ExtendedMetadata, '@L', S_FD_False, S_FD_ConnParam_Common_ExtendedMetadata, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaDefSchema, '@S', '', S_FD_ConnParam_Common_MetaDefSchema, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaCurSchema, '@S', '', S_FD_ConnParam_Common_MetaCurSchema, -1]);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysTDataConnection }
{-------------------------------------------------------------------------------}
function TFDPhysTDataConnection.InternalCreateCommand: TFDPhysCommand;
begin
Result := TFDPhysTDataCommand.Create(Self);
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDataConnection.InternalCreateCommandGenerator(
const ACommand: IFDPhysCommand): TFDPhysCommandGenerator;
begin
if ACommand <> nil then
Result := TFDPhysTDataCommandGenerator.Create(ACommand)
else
Result := TFDPhysTDataCommandGenerator.Create(Self);
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDataConnection.InternalCreateMetadata: TObject;
var
iSrvVer, iClntVer: TFDVersion;
begin
GetVersions(iSrvVer, iClntVer);
Result := TFDPhysTDataMetadata.Create(Self, iSrvVer, iClntVer, GetKeywords,
FExtendedMetadata, FSessionMode, FCharacterSet);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataConnection.GetStrsMaxSizes(AStrDataType: SQLSmallint;
AFixedLen: Boolean; out ACharSize, AByteSize: Integer);
begin
// CHAR - 64000
// CHAR CHARACTER SET UNICODE - 32000
// VARCHAR - 64000
// VARCHAR CHARACTER SET UNICODE - 32000
// BYTE - 64000
// VARBYTE - 64000
case AStrDataType of
SQL_C_CHAR,
SQL_C_BINARY:
begin
AByteSize := 64000;
ACharSize := AByteSize;
end;
SQL_C_WCHAR:
begin
AByteSize := 64000;
ACharSize := AByteSize div SizeOf(SQLWChar);
end;
else
FDCapabilityNotSupported(Self, [S_FD_LPhys, S_FD_TDataId]);
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDataConnection.GetExceptionClass: EODBCNativeExceptionClass;
begin
Result := ETDataNativeException;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataConnection.InternalConnect;
var
oPrevChanging: TNotifyEvent;
oParams: TFDPhysTDataConnectionDefParams;
begin
inherited InternalConnect;
oParams := ConnectionDef.Params as TFDPhysTDataConnectionDefParams;
if oParams.NewPassword <> '' then begin
oPrevChanging := ConnectionDef.OnChanging;
ConnectionDef.OnChanging := nil;
oParams.Password := oParams.NewPassword;
oParams.NewPassword := '';
ConnectionDef.OnChanging := oPrevChanging;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDataConnection.QueryValue(const ASQL: String): String;
var
oStmt: TODBCCommandStatement;
oCol1: TODBCColumn;
begin
oStmt := TODBCCommandStatement.Create(ODBCConnection, Self);
try
oStmt.Open(1, ASQL);
oCol1 := oStmt.AddCol(1, SQL_WVARCHAR, SQL_C_WCHAR, 128);
oStmt.Fetch(1);
Result := oCol1.AsStrings[0];
finally
FDFree(oStmt);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataConnection.InternalSetMeta;
var
oPars: TFDPhysTDataConnectionDefParams;
begin
inherited InternalSetMeta;
oPars := TFDPhysTDataConnectionDefParams(ConnectionDef.Params);
FExtendedMetadata := oPars.ExtendedMetadata;
if FCurrentSchema = '' then
UpdateCurrentSchema;
if UpperCase(Trim(QueryValue('SELECT transaction_mode FROM dbc.SessionInfoV ' +
'WHERE SessionNo = SESSION'))) = 'T' then
FSessionMode := tmTeradata
else
FSessionMode := tmANSI;
FCharacterSet := ConnectionDef.AsString[S_FD_ConnParam_Common_CharacterSet];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataConnection.UpdateCurrentSchema;
begin
FCurrentSchema := QueryValue('SELECT DATABASE');
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataConnection.InternalChangePassword(const AUserName, AOldPassword,
ANewPassword: String);
begin
InternalExecuteDirect('MODIFY "' + AUserName + '" AS PASSWORD = "' + ANewPassword + '"', nil);
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDataConnection.GetLastAutoGenValue(const AName: String): Variant;
begin
if AName = '' then
Result := FLastAutoGenValue
else
Result := inherited GetLastAutoGenValue(AName);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysTDataCommand }
{-------------------------------------------------------------------------------}
function TFDPhysTDataCommand.InternalUseStandardMetadata: Boolean;
begin
Result := not TFDPhysTDataConnection(ODBCConnection).FExtendedMetadata;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataCommand.InternalPrepare;
var
i: Integer;
begin
FAGKR := SQL_AGKR_NO;
if (GetMetaInfoKind = mkNone) and (FOptions.UpdateOptions.RefreshMode <> rmManual) then
case GetCommandKind of
skSelect,
skSelectForLock,
skSelectForUnLock:
if (StrLIComp(PChar(FDbCommandText), PChar('INSERT'), 6) = 0) or
(StrLIComp(PChar(FDbCommandText), PChar('UPDATE'), 6) = 0) or
(StrLIComp(PChar(FDbCommandText), PChar('UPSERT'), 6) = 0) or
(StrLIComp(PChar(FDbCommandText), PChar('MERGE'), 5) = 0) then begin
i := Pos(C_FD_TDataINTO, FDbCommandText);
if i <> 0 then begin
Inc(i, Length(C_FD_TDataINTO));
if StrLComp(PChar(FDbCommandText) + i - 1, PChar(' * '), 3) = 0 then
FAGKR := SQL_AGKR_WHOLE_ROW
else if StrLComp(PChar(FDbCommandText) + i - 1, PChar(' # '), 3) = 0 then
FAGKR := SQL_AGKR_IDENTITY_COLUMN
else
FAGKR := SQL_AGKR_WHOLE_ROW;
end;
end;
skInsert,
skMerge:
FAGKR := SQL_AGKR_IDENTITY_COLUMN;
end;
inherited InternalPrepare;
if FAGKR <> SQL_AGKR_NO then
ODBCStatement.TDATA_AGKR := FAGKR;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataCommand.InternalUnprepare;
begin
FAutoGenCol := nil;
inherited InternalUnprepare;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataCommand.DoINTODescribe;
var
i1, i2, i3, i, j: Integer;
sNames: String;
pColInfo: PFDODBCColInfoRec;
begin
i1 := Pos(C_FD_TDataINTO, FDbCommandText);
if i1 > 0 then begin
Inc(i1, Length(C_FD_TDataINTO));
i2 := Pos('*/', FDbCommandText, i1);
if i2 > 0 then begin
i3 := Pos(' * ', FDbCommandText, i1);
if i3 = 0 then
i3 := Pos(' # ', FDbCommandText, i1);
if i3 > 0 then
Inc(i1, 3);
sNames := Trim(Copy(FDbCommandText, i1, i2 - i1));
j := 1;
for i := 0 to Length(FColInfos) - 1 do begin
pColInfo := @FColInfos[i];
pColInfo^.FName := FDExtractFieldName(sNames, j);
end;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataCommand.DoExtendedDescribe;
var
i, j, k: Integer;
oTabs: TFDStringList;
oConnMeta: IFDPhysConnectionMetadata;
pColInfo: PFDODBCColInfoRec;
oView: TFDDatSView;
oRow: TFDDatSRow;
begin
oTabs := TFDStringList.Create(dupIgnore, True, False);
try
for i := 0 to Length(FColInfos) - 1 do begin
pColInfo := @FColInfos[i];
if (pColInfo^.FOriginTabName <> '') and (pColInfo^.FOriginColName <> '') then
if oTabs.IndexOf(pColInfo^.FOriginTabName) = -1 then
oTabs.Add(pColInfo^.FOriginTabName);
end;
GetConnection.CreateMetadata(oConnMeta);
for k := 0 to oTabs.Count - 1 do begin
oView := oConnMeta.GetResultSetFields(UpperCase(oTabs[k]));
try
for i := 0 to Length(FColInfos) - 1 do begin
pColInfo := @FColInfos[i];
if (pColInfo^.FOriginTabName <> '') and (pColInfo^.FOriginColName <> '') then begin
j := oView.Find([pColInfo^.FOriginTabName, pColInfo^.FOriginColName],
'TABLE_NAME;COLUMN_NAME', []);
if j <> -1 then begin
oRow := oView.Rows[j];
if oRow.ValueS['ISIDENTITY'] = 1 then begin
Include(pColInfo^.FAttrs, caAutoInc);
Include(pColInfo^.FAttrs, caAllowNull);
end;
if oRow.ValueS['HASDEFAULT'] = 1 then
Include(pColInfo^.FAttrs, caDefault);
if oRow.ValueS['IN_PKEY'] = 1 then
pColInfo^.FInKey := True;
end;
end;
end;
finally
FDClearMetaView(oView, FOptions.FetchOptions);
end;
end;
finally
FDFree(oTabs);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataCommand.CreateDescribeInfos;
begin
inherited CreateDescribeInfos;
if (FAGKR = SQL_AGKR_NO) and (GetMetaInfoKind = mkNone) and
(fiMeta in FOptions.FetchOptions.Items) and
TFDPhysTDataConnection(ODBCConnection).FExtendedMetadata then
DoExtendedDescribe
else if FAGKR <> SQL_AGKR_NO then
DoINTODescribe;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataCommand.UpdateInfoAfterExecution;
var
pData: SQLPointer;
iLen: SQLLen;
begin
TFDPhysTDataConnection(ODBCConnection).SaveLastAutoGenValue(Null);
case GetCommandKind of
skSetSchema:
TFDPhysTDataConnection(ODBCConnection).UpdateCurrentSchema;
skInsert,
skMerge:
if (FAGKR = SQL_AGKR_IDENTITY_COLUMN) and
(ODBCStatement.NumResultCols = 1) and (Length(FColInfos) = 0) then begin
if FAutoGenCol = nil then
FAutoGenCol := ODBCStatement.AddCol(1, SQL_INTEGER, SQL_C_LONG);
if (ODBCStatement.Fetch(1) = 1) and FAutoGenCol.GetData(0, pData, iLen, True) then
TFDPhysTDataConnection(ODBCConnection).SaveLastAutoGenValue(PSQLInteger(pData)^);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysTDataCommand.InternalExecute(ATimes, AOffset: Integer;
var ACount: TFDCounter);
begin
inherited InternalExecute(ATimes, AOffset, ACount);
UpdateInfoAfterExecution;
end;
{-------------------------------------------------------------------------------}
function TFDPhysTDataCommand.InternalOpen(var ACount: TFDCounter): Boolean;
begin
Result := inherited InternalOpen(ACount);
UpdateInfoAfterExecution;
end;
{-------------------------------------------------------------------------------}
function TDataNativeExceptionLoad(const AStorage: IFDStanStorage): TObject;
begin
Result := ETDataNativeException.Create;
ETDataNativeException(Result).LoadFromStorage(AStorage);
end;
{-------------------------------------------------------------------------------}
initialization
FDRegisterDriverClass(TFDPhysTDataDriver);
FDStorageManager().RegisterClass(ETDataNativeException, 'TDataNativeException',
@TDataNativeExceptionLoad, @FDExceptionSave);
finalization
FDUnregisterDriverClass(TFDPhysTDataDriver);
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.DBXTransport;
interface
uses
System.Classes,
System.Generics.Collections,
Data.DBXCommon,
Data.DBXEncryption,
Data.DBXPlatform,
System.SysUtils;
type
TDBXChannelInfo = class;
TTransportFilterCollection = class;
TDbxChannel = class abstract
public
procedure Open; virtual; abstract;
procedure Close; virtual; abstract;
function Read(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer; virtual; abstract;
function Write(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer; virtual; abstract;
destructor Destroy; override;
protected
///<summary>Specifies if there is an open connection or not. By default, always
/// returns false. Descendent classes should override and implement check for active connection.
///</summary>
///<returns>False if connection is active.</returns>
function IsConnectionLost: Boolean; virtual;
function GetChannelInfo: TDBXChannelInfo; virtual; abstract;
function GetDBXProperties: TDBXProperties; virtual;
procedure SetDBXProperties(const Properties: TDBXProperties); virtual;
protected
FChannelInfo: TDBXChannelInfo;
private
[Weak]FDbxProperties: TDBXProperties;
public
property ChannelInfo: TDBXChannelInfo read GetChannelInfo;
property DBXProperties: TDBXProperties read GetDBXProperties write SetDBXProperties;
///<summary>Flag which returns false if connected and true if not connected.</summary>
///<returns>False if connected, True if not connected</returns>
property ConnectionLost: Boolean read IsConnectionLost;
end;
/// <summary>Holds information about a connected client: its IP address,
/// communication port and protocol, and application name.</summary>
TDBXClientInfo = record
IpAddress: string;
ClientPort: string;
Protocol: string;
AppName: string;
end;
TDBXChannelInfo = class
public
constructor Create(const AId: Integer);
protected
function GetInfo: string; virtual;
private
FId: Integer;
FClientInfo: TDBXClientInfo;
public
property Id: Integer read FId;
property Info: string read GetInfo;
property ClientInfo: TDBXClientInfo read FClientInfo write FClientInfo;
end;
/// <summary>Represents a factory of various implementations of the
/// communication layer.</summary>
TDBXCommunicationLayerFactory = class
public
/// <summary> Returns the factory instance
///
/// </summary>
/// <returns>factory instance</returns>
class function Instance: TDBXCommunicationLayerFactory; static;
class procedure RegisterLayer(const CommLayerId: string; const CommLayerClass: TObjectClass); static;
class procedure UnregisterLayer(const CommLayerId: string); static;
class function CommunicationLayer(const Id: string): TDBXCommunicationLayer; static;
class function RegisteredLayerList: TDBXStringArray; static;
/// <summary> Default initializations
/// </summary>
constructor Create;
destructor Destroy; override;
private
class var
FSingleton: TDBXCommunicationLayerFactory;
FRegisteredLayers: TDictionary<string,TObjectClass>;
end;
/// <summary>Represents the channel for interfacing in-process data
/// processing. TDBXLocalChannel implements a two-process producer and
/// consumer paradigm, where data is exchanged in alternate steps.</summary>
TDBXLocalChannel = class(TDbxChannel)
public
constructor Create(const ServerName: string);
destructor Destroy; override;
/// <summary> see com.borland.dbx.transport.DbxChannel#close()
/// </summary>
procedure Close; override;
/// <summary> see com.borland.dbx.transport.DbxChannel#open()
/// </summary>
procedure Open; override;
/// <summary> see com.borland.dbx.transport.DbxChannel#read(byte[], int, int)
/// </summary>
function Read(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer; override;
function WriteLocalData(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer; virtual;
/// <summary> see com.borland.dbx.transport.DbxChannel#write(byte[], int, int)
/// </summary>
function Write(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer; override;
function ReadLocalData(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer; virtual;
function HasReadData: Boolean; virtual;
function HasWriteData: Boolean; virtual;
protected
/// <summary> see com.borland.dbx.transport.DbxChannel#getChannelInfo()
/// </summary>
function GetChannelInfo: TDBXChannelInfo; override;
private
FReadBuffer: TArray<Byte>;
FReadCount: Integer;
FReadOffset: Integer;
FHasReadData: Boolean;
FWriteBuffer: TArray<Byte>;
FWriteCount: Integer;
FWriteOffset: Integer;
FHasWriteData: Boolean;
end;
/// <summary>Transport channel information for socket-based
/// transport.</summary>
TDBXSocketChannelInfo = class(TDBXChannelInfo)
public
constructor Create(const AId: NativeInt; const AInfo: string);
protected
/// <summary> Provide general information on the channel.
/// </summary>
/// <returns>general information on the channel.</returns>
function GetInfo: string; override;
private
FInfo: string;
end;
/// <summary>Represents a collection of strings specifying the properties of a
/// TTransportFilterItem instance.</summary>
TFilterProperties = class(TBaseFilterProperties)
end;
/// <summary>Parent class for transport filters that are invokable if present
/// in the transport chain of the command filter list.</summary>
TTransportFilter = class abstract(TBaseTransportFilter)
public
/// <summary> Utility method, encodes a byte stream into a hex string
///
/// </summary>
/// <param name="data">byte array, never null</param>
/// <param name="pos">valid byte array position </param>
/// <param name="dataLength">valid length of byte array to be transformed into a string</param>
/// <returns>String representation of the byte array</returns>
class function Encode(const Data: TArray<Byte>; const Pos: Integer; const DataLength: Integer): string; static;
/// <summary> Decodes the encoded string into a byte array. The decoding only works if the byte array was originally encoded with encode(byte[],int,int)
/// </summary>
/// <remarks> The decoding only works if the byte array was originally encoded with encode(byte[],int,int)
///
/// </remarks>
/// <param name="strData">encoded string</param>
/// <returns>decoded string as byte array</returns>
class function Decode(const StrData: string): TArray<Byte>; static;
/// <summary> Default ctr, empty here
/// </summary>
constructor Create; override;
/// <summary> Returns the filter id, used by the filter factory to create an instance.
/// </summary>
/// <remarks> Filter id can be present multiple times in a transport filter chain.
///
/// </remarks>
/// <returns>String - filter id, never null</returns>
function Id: string; virtual; abstract;
/// <summary> Returns the parameter value as a String.
/// </summary>
/// <remarks>
///
/// It is the implementation responsibility to convert the parameter value from internal type to string and back.
///
/// </remarks>
/// <param name="paramName">String - filter parameter name</param>
/// <returns>String - filter parameter value
/// see #getParameters()</returns>
function GetParameterValue(const ParamName: string): string; virtual;
/// <summary> Provides the parameter value as a string. It is called with the values
/// </summary>
/// <remarks> It is called with the values
/// the developer sets during design time or runtime.
///
/// </remarks>
/// <param name="paramName">String - parameter name</param>
/// <param name="paramValue">byte[] - parameter value</param>
/// <returns>boolean - false if parameter value was not changed successfully
/// see #getUserParameters()
/// see #getParameterValue(String)</returns>
function SetParameterValue(const ParamName: string; const ParamValue: string): Boolean; virtual;
/// <summary> Called by the communication layer with the partner parameter values.
/// </summary>
/// <remarks>
/// Such values may contain public keys, shared secrets, authentication tokens
/// that can be used to encrypt/decrypt the messages.
///
/// The parameter names and values are obtained from getParameter* counter-part
/// methods. The implementation of this class should take care of the symmetry,
/// local parameter values are confederate at the other side and vice-versa.
///
/// </remarks>
/// <param name="paramName">String - parameter name</param>
/// <param name="paramValue">String - parameter value, as a string</param>
/// <returns>true if the parameter and value are valid. On false, the protocol
/// should not continue the communication. </returns>
function SetConfederateParameter(const ParamName: string; const ParamValue: string): Boolean; virtual;
/// <summary> Filters the "clear" input data bytes. If returns null, an error occurred.
/// </summary>
/// <remarks> If returns null, an error occurred.
/// Represents the inverse of processOutput.
///
/// </remarks>
/// <param name="data">byte[] - input data, never null</param>
/// <returns>byte[] - processed byte block, may be null</returns>
function ProcessInput(const Data: TArray<Byte>): TArray<Byte>; virtual; abstract;
/// <summary> Process the filtered data back into "clear" data bytes.
/// </summary>
/// <remarks>
///
/// Null result signals an error. Represents the inverse of processInput:
/// processOutput(processInput(data)) == data
///
/// </remarks>
/// <param name="data">byte[] - filtered data, never null</param>
/// <returns>byte[] - clear byte block, may be null on error
/// see #processInput(byte[])</returns>
function ProcessOutput(const Data: TArray<Byte>): TArray<Byte>; virtual; abstract;
/// <summary> Marks the beginning of the handshake process
/// </summary>
procedure StartHandshake; virtual;
/// <summary> Marks the end of the handshake process, returns the filter status
/// </summary>
/// <returns>boolean - true if all parameters match and the filter will be able
/// to process I/O data</returns>
function HandshakeComplete: Boolean; virtual;
function GetCollectionFilter(const FilterId: string): TTransportFilter; virtual;
protected
/// <summary> Returns a list of available/query-able parameters. This list contains the user parameters together with other parameters that may be needed by the handshake protocol.
/// </summary>
/// <remarks> This list contains the user parameters together with other parameters that may be needed by the handshake protocol.
///
/// The parameter's value will be passed to their counterparts during handshake protocol. The
/// parameters will be invoked in the provided order. If the same parameter is
/// present multiple times multiple calls will be made to get its value.
///
/// </remarks>
/// <returns>String[] - list of parameters, can be null</returns>
function GetParameters: TDBXStringArray; virtual;
/// <summary> Returns a list of parameters that user can change.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <returns>String[] - list of parameters, can be null</returns>
function GetUserParameters: TDBXStringArray; virtual;
procedure SetServerInstance(const IsServerSide: Boolean); virtual;
function IsPublicKeyCryptograph: Boolean; virtual;
function IsServerInstance: Boolean; virtual;
function IsClientInstance: Boolean; virtual;
function GetFilterCollection: TTransportFilterCollection; virtual;
procedure SetFilterCollection(const FilterCollection: TTransportFilterCollection); virtual;
/// <summary> Returns true if we are in the middle of the handshake process
/// </summary>
/// <returns>boolean - true if the handshake process is active</returns>
function IsHandshakeStarted: Boolean; virtual;
private
FServerInstance: Boolean;
[Weak]FFilterCollection: TTransportFilterCollection;
FHandshakeStarted: Boolean;
public
/// <summary> Returns a list of available/query-able parameters. This list contains the user parameters together with other parameters that may be needed by the handshake protocol.
/// </summary>
/// <remarks> This list contains the user parameters together with other parameters that may be needed by the handshake protocol.
///
/// The parameter's value will be passed to their counterparts during handshake protocol. The
/// parameters will be invoked in the provided order. If the same parameter is
/// present multiple times multiple calls will be made to get its value.
///
/// </remarks>
/// <returns>String[] - list of parameters, can be null</returns>
property Parameters: TDBXStringArray read GetParameters;
/// <summary> Returns a list of parameters that user can change.
/// </summary>
/// <remarks>
///
/// </remarks>
/// <returns>String[] - list of parameters, can be null</returns>
property UserParameters: TDBXStringArray read GetUserParameters;
property PublicKeyCryptograph: Boolean read IsPublicKeyCryptograph;
property ServerInstance: Boolean read IsServerInstance write SetServerInstance;
property ClientInstance: Boolean read IsClientInstance;
property FilterCollection: TTransportFilterCollection read GetFilterCollection write SetFilterCollection;
/// <summary> Returns true if we are in the middle of the handshake process
/// </summary>
/// <returns>boolean - true if the handshake process is active</returns>
property HandshakeStarted: Boolean read IsHandshakeStarted;
end;
/// <summary>Implements a dbExpress transport encryption filter based on the
/// PC1 algorithm.</summary>
TTransportCypherFilter = class sealed(TTransportFilter)
public
/// <summary> see TransportFilter#getParameterValue(String)
/// </summary>
function GetParameterValue(const ParamName: string): string; override;
/// <summary> Encrypts data in place. Original values will be lost.
/// </summary>
/// <remarks> Original values will be lost.
///
/// </remarks>
// / <seealso cref="TTransportFilter.processInput(TArray<Byte>)"/>
function ProcessInput(const Data: TArray<Byte>): TArray<Byte>; override;
/// <summary> Decrypts data in place. Original values will be lost.
/// </summary>
/// <remarks> Original values will be lost.
///
/// </remarks>
// / <seealso cref="TTransportFilter.processOutput(TArray<Byte>)"/>
function ProcessOutput(const Data: TArray<Byte>): TArray<Byte>; override;
/// <summary> see TransportFilter#setParameterValue(String, String)
/// </summary>
function SetParameterValue(const ParamName: string; const ParamValue: string): Boolean; override;
function SetConfederateParameter(const ParamName: string; const ParamValue: string): Boolean; override;
/// <summary> see TransportFilter#id()
/// </summary>
function Id: string; override;
protected
function GetClearKey: string;
/// <summary> see TransportFilter#getUserParameters()
/// </summary>
function GetUserParameters: TDBXStringArray; override;
/// <seealso cref="TTransportFilter.getParameters()"/>
function GetParameters: TDBXStringArray; override;
private
/// <summary> Initializes PC1 filter instance and returns it. Does so due to thread safety concerns
/// </summary>
/// <remarks> Does so due to thread safety concerns
///
/// </remarks>
/// <returns>PC1Cypher instance</returns>
function SetUp(const Key: string): TPC1Cypher;
/// <summary> Frees the cypher instance. Past this call the cypher should never be used again.
/// </summary>
/// <remarks> Past this call the cypher should never be used again.
///
/// </remarks>
/// <param name="cypher">PC1Cypher instance, never null</param>
procedure TearDown(var Cypher: TPC1Cypher);
private
FCypherKey: string;
FConfederateKey: string;
private
property ClearKey: string read GetClearKey;
private
const Key = 'Key';
const Code = 'CODE';
const Filterunit = 'FilterUnit';
end;
/// <summary> Collection of Transport Filters
/// </summary>
TTransportFilterCollection = class(TBaseTransportFilterCollection)
public
constructor Create;
/// <summary> Creates a new filter instance and adds it to the current list, returns the position where it was added.
/// </summary>
/// <remarks> Returns -1 if the parameter is null or empty. The list allows duplicates.
///
/// </remarks>
/// <param name="filterId">String - filter id, not null or empty</param>
/// <returns>integer - zero based index of the newly added filter id</returns>
function AddFilter(const FilterId: string): Integer; overload; virtual;
/// <summary> Adds an existing filter instance to the current list, returns the position where it was added.
/// </summary>
/// <remarks> Returns -1 if the parameter is null. The list allows duplicates.
///
/// </remarks>
/// <param name="filter">TTransportFilter - filter, not null or empty</param>
/// <returns>integer - zero based index of the newly added filter</returns>
function AddFilter(const Filter: TTransportFilter): Integer; overload; virtual;
/// <summary> Removes a filter id from the current list based on index. The entire list shifts "up" for all elements beyond argument.
/// </summary>
/// <remarks> The entire list shifts "up" for all elements beyond argument.
///
/// Returns false if the operation failed (index out of bounds for example).
///
/// </remarks>
/// <param name="index">integer - filter id position</param>
/// <returns>boolean - true if the removal was successful</returns>
function RemoveFilter(const Index: Integer): Boolean; virtual;
/// <summary> Returns the transport filter instance from a zero-based given position.
/// </summary>
/// <remarks>
/// Returns null is index is out of range.
///
/// </remarks>
/// <param name="pos">filter index, zero based</param>
/// <returns>transport filter index, null if the parameter is out of range</returns>
function GetFilter(const Pos: Integer): TTransportFilter; overload; virtual;
/// <summary> Returns the transport filter based on id.
/// </summary>
/// <remarks>
///
/// It is not recommended to use this method when filters sharing the same id
/// are present in the collection as only the first occurance will be returned.
///
/// </remarks>
/// <param name="id">- String : the filter id</param>
/// <returns>TransportFilter instance or null if not found</returns>
function GetFilter(const Id: string): TTransportFilter; overload; virtual;
/// <summary> Marks the end of the handshake phase and returns true if all filters
/// are accepting the parameters.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>boolean - true if the handshake was successful.</returns>
function HandshakeComplete: Boolean; virtual;
/// <summary> Start the handshake phase
/// </summary>
procedure StartHandshake; virtual;
/// <summary> Filter list as JSON string
/// </summary>
/// <returns>JSON string representation of filter list</returns>
function ToJSON: string; virtual;
/// <summary> Filter list from JSON string. </summary>
/// <returns>TTransportFilterCollection representation of the JSON string</returns>
class function FromJSON(const Json: string): TTransportFilterCollection; static;
protected
/// <summary> Returns the list of filters, result can be empty but never null.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>String[] - list of current filters</returns>
function GetFilterIdList: TDBXStringArray; virtual;
public
/// <summary> Returns the list of filters, result can be empty but never null.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>String[] - list of current filters</returns>
property FilterIdList: TDBXStringArray read GetFilterIdList;
end;
/// <summary>Represents a filter factory for transport filters.</summary>
TTransportFilterFactory = class
public
/// <summary> Returns the factory instance.
/// </summary>
/// <remarks>
/// Lazy initialization.
///
/// </remarks>
/// <returns>- filter factory instance</returns>
class function Instance: TTransportFilterFactory; static;
/// <summary> Creates a filter instance based on filter id.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="filterId">filter id, not null</param>
/// <returns>filter instance</returns>
class function CreateFilter(const FilterId: string): TTransportFilter; static;
/// <summary> Registers a filter metaclass with the transport filter factory.
/// </summary>
/// <remarks>
///
/// An filter instance can be obtained through createFilter.
///
/// </remarks>
/// <param name="filterId">filter id</param>
/// <param name="filterClass">filter metaclass
/// see TransportFilter#id()
/// see #createFilter(String)</param>
class procedure RegisterFilter(const FilterId: string; const FilterClass: TObjectClass); overload; static;
/// <summary> Registers the filter class with the factory.
/// </summary>
/// <remarks>
///
/// It uses the id function to obtain the registration key that is visible at the design time.
/// Throws runtime exception if the reflection fails
///
/// </remarks>
/// <param name="filterClass">filter class type</param>
class procedure RegisterFilter(const FilterClass: TObjectClass); overload; static;
/// <summary> Unregisters a filter from the filter factory using the filter id.
/// </summary>
/// <remarks>
/// No checks are made if the filter was previously defined.
///
/// </remarks>
/// <param name="filterId">filter id
/// see #registerFilter(String, Class)</param>
class procedure UnregisterFilter(const FilterId: string); overload; static;
/// <summary> Unregisters a filter type class from the factory.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="filterClass">registered filter class type </param>
class procedure UnregisterFilter(const FilterClass: TObjectClass); overload; static;
/// <summary> Returns the registered filter's id list
///
/// </summary>
/// <returns>filter's id list</returns>
class function RegisteredFiltersId: TDBXStringArray; static;
/// <summary> Default constructor
/// </summary>
constructor Create;
destructor Destroy; override;
private
class var
FSingleton: TTransportFilterFactory;
FRegisteredFilters: TDictionary<string,TObjectClass>;
end;
/// <summary>Represents a transport filter.</summary>
TTransportFilterItem = class(TBaseTransportFilterItem)
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
protected
procedure SetFilterId(const FilterId: string); virtual;
function GetFilterId: string; virtual;
function GetFilter: TTransportFilter; virtual;
procedure SetFilter(const Filter: TTransportFilter); virtual;
procedure SetProperties(const Value: TFilterProperties); virtual;
function GetProperties: TFilterProperties; virtual;
private
FFilterId: string;
FFilter: TTransportFilter;
FFilterProperties: TFilterProperties;
FFilterPropertiesChanged: Boolean;
procedure UpdateFilterProperties;
procedure UpdateFilter;
procedure OnFilterPropertiesChange(Sender: TObject);
public
property Filter: TTransportFilter read GetFilter write SetFilter;
published
property FilterId: string read GetFilterId write SetFilterId;
property Properties: TFilterProperties read GetProperties write SetProperties;
end;
/// <summary>Represents the utility class for data processing.</summary>
TTransportFilterTools = class
public
/// <summary> Compose a query filter, recognizable by isFilterQuery method.
/// </summary>
/// <remarks>
/// The processing is done "in place", i.e. the argument is changed and returned for convenience.
///
/// </remarks>
/// <param name="buffer">header byte[] container, normally with a length of HEADER_LEN</param>
/// <returns>the argument as query header, for convenience</returns>
class function FilterQuery(const Buffer: TArray<Byte>): TArray<Byte>; static;
/// <summary> Returns true if argument is a filter query
///
/// </summary>
/// <param name="buffer">header byte[] container, with a length of HEADER_LEN</param>
/// <returns>true if the header is a query header</returns>
class function IsFilterQuery(const Buffer: TArray<Byte>): Boolean; static;
/// <summary> Encodes header with "NO FILTER PRESENT" code.
/// </summary>
/// <remarks>
/// Method changes the argument, returns it for convenience.
///
/// </remarks>
/// <param name="buffer">byte[] header</param>
/// <returns>changed argument</returns>
class function NoFilter(const Buffer: TArray<Byte>): TArray<Byte>; static;
/// <summary> Returns true if the argument header is "NO FILTER PRESENT"
///
/// </summary>
/// <param name="buffer">byte[] header buffer</param>
/// <returns>true if the header means no filter</returns>
class function HasNoFilter(const Buffer: TArray<Byte>): Boolean; static;
/// <summary> Returns true if the header prefixes a public key message
/// </summary>
/// <param name="buffer">- public key header</param>
/// <returns>boolean - true if the header prefixes a public key, false otherwise</returns>
class function HasPublicKey(const Buffer: TArray<Byte>): Boolean; static;
/// <summary> Returns true if there is at least one public key cryptograph filter in
/// the filter list
///
/// </summary>
/// <param name="filterList">- filter list</param>
/// <returns>boolean</returns>
class function HasPublicKeyCryptography(const FilterList: TTransportFilterCollection): Boolean; static;
/// <summary> Serializes len argument into given byte container
///
/// </summary>
/// <param name="data">- byte container</param>
/// <param name="len">- integer</param>
class procedure EncodeDataLength(const Data: TArray<Byte>; const Len: Integer); static;
/// <summary> Serializes len argument into given byte container
///
/// </summary>
/// <param name="data">- byte container</param>
/// <param name="len">- integer</param>
class procedure EncodePublicKeyLength(const Data: TArray<Byte>; const Len: Integer); static;
/// <summary> Returns the encoded integer argument
///
/// </summary>
/// <param name="data">byte container</param>
/// <returns>int - encoded integer</returns>
class function DecodeDataLen(const Data: TArray<Byte>): Integer; static;
public
const HeaderLen = 5;
private
const HeaderFilter = 13;
const HeaderQuery = 5;
const HeaderNoFilter = 6;
const HeaderPublicKey = 7;
end;
implementation
uses
System.Generics.Defaults,
System.JSON,
Data.DBXCommonResStrs,
Data.DBXClientResStrs
;
function TDbxChannel.IsConnectionLost: Boolean;
begin
Exit(False);
end;
function TDbxChannel.GetDBXProperties: TDBXProperties;
begin
Result := FDbxProperties;
end;
procedure TDbxChannel.SetDBXProperties(const Properties: TDBXProperties);
begin
FDbxProperties := Properties;
end;
destructor TDbxChannel.Destroy;
begin
FreeAndNil(FChannelInfo);
inherited Destroy;
end;
constructor TDBXChannelInfo.Create(const AId: Integer);
begin
inherited Create;
FId := AId;
end;
function TDBXChannelInfo.GetInfo: string;
begin
Result := ToString;
end;
class function TDBXCommunicationLayerFactory.Instance: TDBXCommunicationLayerFactory;
begin
if FSingleton = nil then
FSingleton := TDBXCommunicationLayerFactory.Create;
Result := FSingleton;
end;
class procedure TDBXCommunicationLayerFactory.RegisterLayer(const CommLayerId: string; const CommLayerClass: TObjectClass);
begin
if Instance <> nil then
begin
if Instance.FRegisteredLayers.ContainsKey(CommLayerId) then
Instance.FRegisteredLayers.Items[CommLayerId] := CommLayerClass
else
Instance.FRegisteredLayers.Add(CommLayerId, CommLayerClass);
end;
end;
class procedure TDBXCommunicationLayerFactory.UnregisterLayer(const CommLayerId: string);
begin
if Instance <> nil then
begin
Instance.FRegisteredLayers.Remove(CommLayerId);
if Instance.FRegisteredLayers.Count = 0 then
FreeAndNil(FSingleton);
end;
end;
class function TDBXCommunicationLayerFactory.CommunicationLayer(const Id: string): TDBXCommunicationLayer;
var
Clazz: TObjectClass;
begin
if (Instance <> nil) and Instance.FRegisteredLayers.ContainsKey(Id) then
begin
Clazz := Instance.FRegisteredLayers[Id];
try
Exit(TDBXCommunicationLayer(Clazz.Create));
except
on E: Exception do
;
end;
Result := nil;
end
else
Result := nil;
end;
class function TDBXCommunicationLayerFactory.RegisteredLayerList: TDBXStringArray;
begin
if Instance <> nil then
Result := TDBXStringArray(Instance.FRegisteredLayers.Keys.ToArray)
else
SetLength(Result, 0);
end;
constructor TDBXCommunicationLayerFactory.Create;
begin
inherited Create;
FRegisteredLayers := TDictionary<string,TObjectClass>.Create(TIStringComparer.Ordinal);
end;
destructor TDBXCommunicationLayerFactory.Destroy;
begin
FreeAndNil(FRegisteredLayers);
FSingleton := nil;
inherited Destroy;
end;
constructor TDBXLocalChannel.Create(const ServerName: string);
begin
inherited Create;
FChannelInfo := TDBXSocketChannelInfo.Create(0, ServerName);
FHasReadData := False;
FHasWriteData := False;
end;
destructor TDBXLocalChannel.Destroy;
begin
FReadBuffer := nil;
FWriteBuffer := nil;
inherited Destroy;
end;
procedure TDBXLocalChannel.Close;
begin
end;
function TDBXLocalChannel.GetChannelInfo: TDBXChannelInfo;
begin
Result := FChannelInfo;
end;
procedure TDBXLocalChannel.Open;
begin
end;
function TDBXLocalChannel.Read(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer;
var
Size: Integer;
begin
if not FHasWriteData then
raise TDBXError.Create(0, SNoReadDataAvailable);
Size := Count;
if Count > FWriteCount then
Size := FWriteCount;
TDBXPlatform.CopyByteArray(FWriteBuffer, FWriteOffset, Buffer, Offset, Size);
FWriteCount := FWriteCount - Size;
FWriteOffset := FWriteOffset + Size;
if FWriteCount = 0 then
begin
FWriteBuffer := nil;
FHasWriteData := False;
end;
Result := Size;
end;
function TDBXLocalChannel.WriteLocalData(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer;
begin
if FHasWriteData then
raise TDBXError.Create(0, SNoWriteDataAvailable);
FWriteBuffer := Buffer;
FHasWriteData := True;
FWriteCount := Count;
FWriteOffset := Offset;
Result := Count;
end;
function TDBXLocalChannel.Write(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer;
begin
if FHasReadData then
raise TDBXError.Create(0, SNoWriteDataAvailable);
SetLength(FReadBuffer,Count - Offset);
TDBXPlatform.CopyByteArray(Buffer, Offset, FReadBuffer, 0, Count);
FHasReadData := True;
FReadCount := Count;
FReadOffset := 0;
Result := Count;
end;
function TDBXLocalChannel.ReadLocalData(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer;
var
Size: Integer;
begin
if not FHasReadData then
raise TDBXError.Create(0, SNoReadDataAvailable);
Size := Count;
if FReadCount < Count then
Size := FReadCount;
TDBXPlatform.CopyByteArray(FReadBuffer, FReadOffset, Buffer, Offset, Size);
FReadCount := FReadCount - Size;
FReadOffset := FReadOffset + Size;
if FReadCount = 0 then
begin
FReadBuffer := nil;
FHasReadData := False;
end;
Result := Size;
end;
function TDBXLocalChannel.HasReadData: Boolean;
begin
Result := FHasReadData;
end;
function TDBXLocalChannel.HasWriteData: Boolean;
begin
Result := FHasWriteData;
end;
constructor TDBXSocketChannelInfo.Create(const AId: NativeInt; const AInfo: string);
begin
inherited Create(Integer(AId));
FInfo := AInfo;
end;
function TDBXSocketChannelInfo.GetInfo: string;
begin
Result := FInfo;
end;
class function TTransportFilter.Encode(const Data: TArray<Byte>; const Pos: Integer; const DataLength: Integer): string;
var
StrBuf: TStringBuilder;
HexDig, I, Size: Integer;
begin
Size := DataLength;
if DataLength < 0 then
Size := Length(Data);
if Pos >= Size then
Exit('');
StrBuf := TStringBuilder.Create((Size - Pos) * 2);
try
for I := Pos to Size - 1 do
begin
HexDig := (Data[I] and 240) shr 4;
StrBuf.Append(Char(DecimalToHex(HexDig)));
HexDig := Data[I] and 15;
StrBuf.Append(Char(DecimalToHex(HexDig)));
end;
Result := StrBuf.ToString(True);
finally
StrBuf.Free;
end;
end;
class function TTransportFilter.Decode(const StrData: string): TArray<Byte>;
var
Data: TArray<Byte>;
I, J, Val: Integer;
begin
SetLength(Data, StrData.Length shr 1);
J := 0;
I := 0;
while I < StrData.Length do
begin
Val := HexToDecimal(Ord(StrData.Chars[IncrAfter(I)])) shl 4;
Val := Val or HexToDecimal(Ord(StrData.Chars[IncrAfter(I)]));
Data[IncrAfter(J)] := Byte(Val);
end;
Result := Data;
end;
constructor TTransportFilter.Create;
begin
inherited Create;
FHandshakeStarted := False;
end;
function TTransportFilter.GetParameters: TDBXStringArray;
begin
Result := nil;
end;
function TTransportFilter.GetUserParameters: TDBXStringArray;
begin
Result := nil;
end;
function TTransportFilter.GetParameterValue(const ParamName: string): string;
begin
Result := '';
end;
function TTransportFilter.SetParameterValue(const ParamName: string; const ParamValue: string): Boolean;
begin
Result := False;
end;
function TTransportFilter.SetConfederateParameter(const ParamName: string; const ParamValue: string): Boolean;
begin
Result := False;
end;
procedure TTransportFilter.SetServerInstance(const IsServerSide: Boolean);
begin
FServerInstance := IsServerSide;
end;
function TTransportFilter.IsPublicKeyCryptograph: Boolean;
begin
Result := False;
end;
function TTransportFilter.IsServerInstance: Boolean;
begin
Result := FServerInstance;
end;
function TTransportFilter.IsClientInstance: Boolean;
begin
Result := not ServerInstance;
end;
function TTransportFilter.GetFilterCollection: TTransportFilterCollection;
begin
Result := FFilterCollection;
end;
procedure TTransportFilter.SetFilterCollection(const FilterCollection: TTransportFilterCollection);
begin
FFilterCollection := FilterCollection;
end;
procedure TTransportFilter.StartHandshake;
begin
FHandshakeStarted := True;
end;
function TTransportFilter.IsHandshakeStarted: Boolean;
begin
Result := FHandshakeStarted;
end;
function TTransportFilter.HandshakeComplete: Boolean;
begin
FHandshakeStarted := False;
Result := True;
end;
function TTransportFilter.GetCollectionFilter(const FilterId: string): TTransportFilter;
begin
if FFilterCollection <> nil then
Exit(FFilterCollection.GetFilter(FilterId));
Result := nil;
end;
function TTransportCypherFilter.GetParameterValue(const ParamName: string): string;
var
Data: TArray<Byte>;
Cypher: TPC1Cypher;
I: Integer;
begin
if (Key = ParamName) then
Exit(ClearKey);
if (Code = ParamName) then
begin
SetLength(Data, 256);
Cypher := SetUp(FCypherKey);
for I := 0 to Length(Data) - 1 do
Data[I] := Cypher.Cypher(Byte(I));
TearDown(Cypher);
Exit(TTransportFilter.Encode(Data, 0, Length(Data)));
end;
if (Filterunit = ParamName) then
Exit('DbxSocketChannelNative');
Result := NullString;
end;
function TTransportCypherFilter.GetClearKey: string;
var
Cypher: TPC1Cypher;
begin
if FCypherKey.IsEmpty then
begin
Cypher := SetUp(NullString);
try
FCypherKey := Cypher.EncryptionKey;
finally
TearDown(Cypher);
end;
end;
Result := FCypherKey;
end;
function TTransportCypherFilter.GetUserParameters: TDBXStringArray;
var
Params: TDBXStringArray;
begin
SetLength(Params,1);
Params[0] := Key;
Result := Params;
end;
function TTransportCypherFilter.GetParameters: TDBXStringArray;
var
Params: TDBXStringArray;
begin
SetLength(Params,3);
Params[0] := Key;
Params[1] := Code;
Params[2] := Filterunit;
Result := Params;
end;
function TTransportCypherFilter.ProcessInput(const Data: TArray<Byte>): TArray<Byte>;
var
Cypher: TPC1Cypher;
I: Integer;
begin
Cypher := SetUp(FCypherKey);
for I := 0 to Length(Data) - 1 do
Data[I] := Cypher.Cypher(Data[I]);
TearDown(Cypher);
Result := Data;
end;
function TTransportCypherFilter.ProcessOutput(const Data: TArray<Byte>): TArray<Byte>;
var
Cypher: TPC1Cypher;
I: Integer;
begin
Cypher := SetUp(FConfederateKey);
for I := 0 to Length(Data) - 1 do
Data[I] := Cypher.Decypher(Data[I]);
TearDown(Cypher);
Result := Data;
end;
function TTransportCypherFilter.SetParameterValue(const ParamName: string; const ParamValue: string): Boolean;
begin
if (Key = ParamName) then
FCypherKey := ParamValue;
Result := True;
end;
function TTransportCypherFilter.SetConfederateParameter(const ParamName: string; const ParamValue: string): Boolean;
var
Data: TArray<Byte>;
Cypher: TPC1Cypher;
I: Integer;
begin
if (Code = ParamName) then
begin
Data := Decode(ParamValue);
Cypher := SetUp(FConfederateKey);
for I := 0 to Length(Data) - 1 do
begin
if (Byte(I)) <> Cypher.Decypher(Data[I]) then
begin
TearDown(Cypher);
Exit(False);
end;
end;
TearDown(Cypher);
end;
if (Key = ParamName) then
FConfederateKey := ParamValue;
Result := True;
end;
function TTransportCypherFilter.SetUp(const Key: string): TPC1Cypher;
begin
if Key.IsEmpty then
Result := TPC1Cypher.Create
else
Result := TPC1Cypher.Create(Key);
end;
procedure TTransportCypherFilter.TearDown(var Cypher: TPC1Cypher);
begin
Cypher.Free;
end;
function TTransportCypherFilter.Id: string;
begin
Result := 'PC1';
end;
constructor TTransportFilterCollection.Create;
begin
inherited Create(TTransportFilterItem);
end;
function TTransportFilterCollection.AddFilter(const FilterId: string): Integer;
var
FilterItem: TTransportFilterItem;
begin
if (not FilterId.IsEmpty) and (FilterId.Length <> 0) then
begin
FilterItem := TTransportFilterItem(Add);
try
FilterItem.FilterId := FilterId;
FilterItem.OnChangeNotify(self);
NotifyChange;
Exit(Count - 1);
except
on Ex: Exception do
Delete(Count - 1);
end;
end;
Result := -1;
end;
function TTransportFilterCollection.AddFilter(const Filter: TTransportFilter): Integer;
var
FilterItem: TTransportFilterItem;
begin
if Filter <> nil then
begin
FilterItem := TTransportFilterItem(Add);
FilterItem.Filter := Filter;
NotifyChange;
Exit(Count - 1);
end;
Result := -1;
end;
function TTransportFilterCollection.RemoveFilter(const Index: Integer): Boolean;
begin
if (Index >= 0) and (Index < Count) then
begin
Delete(Index);
NotifyChange;
Result := True;
end
else
Result := False;
end;
function TTransportFilterCollection.GetFilter(const Pos: Integer): TTransportFilter;
begin
if (Pos >= 0) and (Pos < Count) then
Exit((TTransportFilterItem(GetItem(Pos))).Filter);
Result := nil;
end;
function TTransportFilterCollection.GetFilter(const Id: string): TTransportFilter;
var
I: Integer;
begin
for I := 0 to Count - 1 do
begin
if (GetFilter(I).Id = Id) then
Exit(GetFilter(I));
end;
Result := nil;
end;
function TTransportFilterCollection.GetFilterIdList: TDBXStringArray;
var
Data: TDBXStringArray;
I: Integer;
begin
SetLength(Data, Count);
for I := 0 to Length(Data) - 1 do
Data[I] := GetFilter(I).Id;
Result := Data;
end;
function TTransportFilterCollection.HandshakeComplete: Boolean;
var
Status: Boolean;
I: Integer;
begin
Status := True;
for I := 0 to Count - 1 do
begin
if not GetFilter(I).HandshakeComplete then
Status := False;
end;
Result := Status;
end;
procedure TTransportFilterCollection.StartHandshake;
var
I: Integer;
begin
for I := 0 to Count - 1 do
GetFilter(I).StartHandshake;
end;
function TTransportFilterCollection.ToJSON: string;
var
FilterProps, Root: TJSONObject;
Data: TArray<Byte>;
Item: TTransportFilterItem;
Props: TFilterProperties;
I, J, Len: Integer;
begin
Root := TJSONObject.Create;
try
for I := 0 to Count - 1 do
begin
FilterProps := TJSONObject.Create;
Item := TTransportFilterItem(GetItem(I));
Root.AddPair(Item.FilterId, FilterProps);
Props := Item.Properties;
if Props <> nil then
for J := 0 to Props.Count - 1 do
FilterProps.AddPair(Props.GetName(J), Props.GetValue(J));
end;
SetLength(Data, Root.EstimatedByteSize);
Len := Root.ToBytes(Data, 0);
finally
Root.Free;
end;
Result := TDBXPlatform.StringOf(Data, Len);
end;
class function TTransportFilterCollection.FromJSON(const Json: string): TTransportFilterCollection;
var
Bytes: TArray<Byte>;
FilterPos: Integer;
FilterProps: TJSONObject;
PropName: string;
PropValue: string;
Filters: TTransportFilterCollection;
JsonCollection: TJSONObject;
I: Integer;
Props: TFilterProperties;
J: Integer;
begin
Filters := nil;
Bytes := BytesOf(Json);
JsonCollection := TJSONObject(TJSONObject.ParseJSONValue(Bytes, 0));
if JsonCollection <> nil then
begin
Filters := TTransportFilterCollection.Create;
for i := 0 to JsonCollection.Count - 1 do
begin
FilterPos := Filters.AddFilter(JsonCollection.Pairs[I].JsonString.Value);
Props := TFilterProperties.Create;
FilterProps := TJSONObject(JsonCollection.Pairs[I].JsonValue);
for j := 0 to FilterProps.Count - 1 do
begin
PropName := FilterProps.Pairs[J].JsonString.Value;
PropValue := TJSONString(FilterProps.Pairs[J].JsonValue).Value;
Props.Add(PropName, PropValue);
end;
(TTransportFilterItem(Filters.GetItem(FilterPos))).Properties := Props;
Props.Free;
end;
JsonCollection.Free;
end;
Result := Filters;
end;
class function TTransportFilterFactory.Instance: TTransportFilterFactory;
begin
if FSingleton = nil then
FSingleton := TTransportFilterFactory.Create;
Result := FSingleton;
end;
class function TTransportFilterFactory.CreateFilter(const FilterId: string): TTransportFilter;
var
Clazz: TObjectClass;
begin
Result := nil;
if FSingleton = nil then
Exit(nil);
if Instance.FRegisteredFilters.TryGetValue(FilterId,Clazz) then
begin
if Clazz <> nil then
begin
try
Exit(TTransportFilter(Clazz.Create));
except
on E: Exception do
;
end;
end;
end
else
raise TDBXError.Create(TDBXErrorCodes.InvalidReference, FilterId+' Filter not found');
end;
class procedure TTransportFilterFactory.RegisterFilter(const FilterId: string; const FilterClass: TObjectClass);
begin
if Instance <> nil then
begin
if Instance.FRegisteredFilters.ContainsKey(FilterId) then
Instance.FRegisteredFilters.Items[FilterId] := FilterClass
else
Instance.FRegisteredFilters.Add(FilterId, FilterClass);
end;
end;
class procedure TTransportFilterFactory.RegisterFilter(const FilterClass: TObjectClass);
var
LFilterId: string;
begin
if Instance <> nil then
begin
LFilterId := TBaseTransportFactoryTools.InvokeStringFunction(FilterClass, 'id');
if Instance.FRegisteredFilters.ContainsKey(LFilterId) then
Instance.FRegisteredFilters.Items[LFilterId] := FilterClass
else
Instance.FRegisteredFilters.Add(LFilterId, FilterClass);
end;
end;
class procedure TTransportFilterFactory.UnregisterFilter(const FilterId: string);
begin
if Instance <> nil then
begin
if Instance.FRegisteredFilters.ContainsKey(FilterId) then
Instance.FRegisteredFilters.Remove(FilterId);
if Instance.FRegisteredFilters.Count = 0 then
FreeAndNil(FSingleton);
end;
end;
class procedure TTransportFilterFactory.UnregisterFilter(const FilterClass: TObjectClass);
var
LStr: string;
begin
if Instance <> nil then
begin
LStr := TBaseTransportFactoryTools.InvokeStringFunction(FilterClass, 'id');
if Instance.FRegisteredFilters.ContainsKey(LStr) then
Instance.FRegisteredFilters.Remove(LStr);
if Instance.FRegisteredFilters.Count = 0 then
FreeAndNil(FSingleton);
end;
end;
class function TTransportFilterFactory.RegisteredFiltersId: TDBXStringArray;
begin
if Instance <> nil then
Result := TDBXStringArray(Instance.FRegisteredFilters.Keys.ToArray)
else
SetLength(Result, 0);
end;
constructor TTransportFilterFactory.Create;
begin
inherited Create;
FRegisteredFilters := TDictionary<string,TObjectClass>.Create(TIStringComparer.Ordinal);
end;
destructor TTransportFilterFactory.Destroy;
begin
FreeAndNil(FRegisteredFilters);
FSingleton := nil;
inherited Destroy;
end;
constructor TTransportFilterItem.Create(Collection: TCollection);
begin
inherited Create(Collection);
OnChangeNotify(TBaseTransportFilterCollection(Collection));
FFilterProperties := TFilterProperties.Create;
FFilterProperties.OnChange := OnFilterPropertiesChange;
end;
procedure TTransportFilterItem.OnFilterPropertiesChange(Sender: TObject);
begin
FFilterPropertiesChanged := True;
end;
destructor TTransportFilterItem.Destroy;
begin
FreeAndNil(FFilterProperties);
FreeAndNil(FFilter);
inherited Destroy;
end;
procedure TTransportFilterItem.SetFilterId(const FilterId: string);
begin
if FilterId <> self.FFilterId then
begin
FreeAndNil(self.FFilter);
self.FFilter := TTransportFilterFactory.CreateFilter(FilterId);
if self.FFilter = nil then
raise Exception.Create(SIllegalArgument);
self.FFilterId := FilterId;
UpdateFilterProperties;
NotifyChange;
end;
end;
function TTransportFilterItem.GetFilterId: string;
begin
Result := FFilterId;
end;
function TTransportFilterItem.GetFilter: TTransportFilter;
begin
if FFilter <> nil then
if FFilterPropertiesChanged then
UpdateFilter;
Result := FFilter;
end;
procedure TTransportFilterItem.SetFilter(const Filter: TTransportFilter);
begin
FreeAndNil(self.FFilter);
self.FFilter := Filter;
self.FFilterId := Filter.Id;
UpdateFilterProperties;
NotifyChange;
end;
procedure TTransportFilterItem.SetProperties(const Value: TFilterProperties);
begin
FFilterProperties.Assign(Value);
NotifyChange;
end;
// Make collection item properties have value of filter properties
procedure TTransportFilterItem.UpdateFilterProperties;
var
Params: TDBXStringArray;
I: Integer;
Value: string;
begin
FFilterProperties.Clear;
if FFilter <> nil then
begin
Params := FFilter.UserParameters;
for I := 0 to Length(Params) - 1 do
begin
Value := FFilter.GetParameterValue(Params[I]);
FFilterProperties.Add(Params[I], Value);
end;
end;
FFilterPropertiesChanged := False;
end;
// Make the filter properties have values of collection item properties
procedure TTransportFilterItem.UpdateFilter;
var
I: Integer;
begin
if FFilter <> nil then
for i := 0 to FFilterProperties.Count - 1 do
FFilter.SetParameterValue(FFilterProperties.GetName(I), FFilterProperties.GetValue(I));
FFilterPropertiesChanged := False;
end;
function TTransportFilterItem.GetProperties: TFilterProperties;
begin
Result := FFilterProperties;
end;
class function TTransportFilterTools.FilterQuery(const Buffer: TArray<Byte>): TArray<Byte>;
var
I: Integer;
begin
for I := 0 to Length(Buffer) - 1 do
Buffer[I] := Byte(HeaderQuery);
Result := Buffer;
end;
class function TTransportFilterTools.IsFilterQuery(const Buffer: TArray<Byte>): Boolean;
var
I: Integer;
begin
for I := 0 to Length(Buffer) - 1 do
begin
if Buffer[I] <> Byte(HeaderQuery) then
Exit(False);
end;
Result := True;
end;
class function TTransportFilterTools.NoFilter(const Buffer: TArray<Byte>): TArray<Byte>;
begin
Buffer[0] := Byte(HeaderNoFilter);
Buffer[1] := Byte(0);
Buffer[2] := Byte(0);
Buffer[3] := Byte(0);
Buffer[4] := Byte(0);
Result := Buffer;
end;
class function TTransportFilterTools.HasNoFilter(const Buffer: TArray<Byte>): Boolean;
begin
Result := (Buffer[0] = HeaderNoFilter) and (Buffer[1] = 0) and (Buffer[2] = 0) and (Buffer[3] = 0) and (Buffer[4] = 0);
end;
class function TTransportFilterTools.HasPublicKey(const Buffer: TArray<Byte>): Boolean;
begin
Result := Buffer[0] = HeaderPublicKey;
end;
class function TTransportFilterTools.HasPublicKeyCryptography(const FilterList: TTransportFilterCollection): Boolean;
var
Filter: TTransportFilter;
I: Integer;
begin
for i := 0 to FilterList.Count - 1 do
begin
Filter := FilterList.GetFilter(I);
if Filter.PublicKeyCryptograph then
Exit(True);
end;
Result := False;
end;
class procedure TTransportFilterTools.EncodeDataLength(const Data: TArray<Byte>; const Len: Integer);
begin
Data[0] := Byte(HeaderFilter);
Data[1] := Byte(((Len shr 24) and 255));
Data[2] := Byte(((Len shr 16) and 255));
Data[3] := Byte(((Len shr 8) and 255));
Data[4] := Byte((Len and 255));
end;
class procedure TTransportFilterTools.EncodePublicKeyLength(const Data: TArray<Byte>; const Len: Integer);
begin
Data[0] := Byte(HeaderPublicKey);
Data[1] := Byte(((Len shr 24) and 255));
Data[2] := Byte(((Len shr 16) and 255));
Data[3] := Byte(((Len shr 8) and 255));
Data[4] := Byte((Len and 255));
end;
class function TTransportFilterTools.DecodeDataLen(const Data: TArray<Byte>): Integer;
var
Size: Integer;
begin
if (Data[0] = HeaderFilter) or (Data[0] = HeaderPublicKey) then
begin
Size := Data[4] and 255;
Size := Size or (Data[1] and 255) shl 24;
Size := Size or (Data[2] and 255) shl 16;
Size := Size or (Data[3] and 255) shl 8;
Result := Size;
end
else
Result := -1;
end;
end.
|
{ Demostrates how to execute a query in a background thread. This
files contains the main user interface for this program. The background
query code is in ResltFrm }
unit QueryFrm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, IniFiles, ExtCtrls, DBTables;
type
TAdhocForm = class(TForm)
AliasCombo: TComboBox;
Label1: TLabel;
QueryEdit: TMemo;
Label2: TLabel;
NameEdit: TEdit;
PasswordEdit: TEdit;
Label3: TLabel;
Label4: TLabel;
ExecuteBtn: TButton;
CloseBtn: TButton;
SavedQueryCombo: TComboBox;
Label5: TLabel;
SaveBtn: TButton;
SaveAsBtn: TButton;
NewBtn: TButton;
Bevel1: TBevel;
procedure FormCreate(Sender: TObject);
procedure CloseBtnClick(Sender: TObject);
procedure ExecuteBtnClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure NewBtnClick(Sender: TObject);
procedure SaveBtnClick(Sender: TObject);
procedure SaveAsBtnClick(Sender: TObject);
procedure SavedQueryComboChange(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
{ Private declarations }
QueryName, OldAlias: string;
SavedQueries: TIniFile;
Unnamed: Boolean;
function IsModified: Boolean;
function CheckModified: Boolean;
procedure Unmodify;
procedure ReadQuery;
procedure SaveQuery;
procedure SaveQueryAs;
public
{ Public declarations }
end;
var
AdhocForm: TAdhocForm;
implementation
uses DB, ResltFrm, SaveQAs;
{$R *.DFM}
function StrToIniStr(const Str: string): string;
var
Buffer: array[0..4095] of Char;
B, S: PChar;
begin
if Length(Str) > SizeOf(Buffer) then
raise Exception.Create('String to large to save in INI file');
S := PChar(Str);
B := Buffer;
while S^ <> #0 do
case S^ of
#13, #10:
begin
if (S^ = #13) and (S[1] = #10) then Inc(S)
else if (S^ = #10) and (S[1] = #13) then Inc(S);
B^ := '\';
Inc(B);
B^ := 'n';
Inc(B);
Inc(S);
end;
else
B^ := S^;
Inc(B);
Inc(S);
end;
B^ := #0;
Result := Buffer;
end;
function IniStrToStr(const Str: string): string;
var
Buffer: array[0..4095] of Char;
B, S: PChar;
begin
if Length(Str) > SizeOf(Buffer) then
raise Exception.Create('String to read from an INI file');
S := PChar(Str);
B := Buffer;
while S^ <> #0 do
if (S[0] = '\') and (S[1] = 'n') then
begin
B^ := #13;
Inc(B);
B^ := #10;
Inc(B);
Inc(S);
Inc(S);
end
else
begin
B^ := S^;
Inc(B);
Inc(S);
end;
B^ := #0;
Result := Buffer;
end;
function TAdhocForm.IsModified: Boolean;
begin
Result := (AliasCombo.Text <> OldAlias) or NameEdit.Modified or
QueryEdit.Modified;
end;
function TAdhocForm.CheckModified: Boolean;
begin
Result := True;
if IsModified then
case MessageDlg(Format('Query %s modified, save?', [QueryName]),
mtConfirmation, mbYesNoCancel, 0) of
mrYes: SaveQuery;
mrCancel: Result := False;
end;
end;
procedure TAdhocForm.Unmodify;
begin
OldAlias := AliasCombo.Text;
NameEdit.Modified := False;
QueryEdit.Modified := False;
end;
procedure TAdhocForm.ReadQuery;
begin
if not CheckModified then Exit;
with SavedQueries do
begin
QueryName := SavedQueryCombo.Items[SavedQueryCombo.ItemIndex];
QueryEdit.Text := IniStrToStr(ReadString(QueryName, 'Query', ''));
AliasCombo.Text := ReadString(QueryName, 'Alias', '');
NameEdit.Text := ReadString(QueryName, 'Name', '');
end;
Unmodify;
if Showing then
if NameEdit.Text <> '' then
PasswordEdit.SetFocus else
QueryEdit.SetFocus;
end;
procedure TAdhocForm.SaveQueryAs;
begin
if GetNewName(QueryName) then
begin
Unnamed := False;
SaveQuery;
with SavedQueryCombo, Items do
begin
if IndexOf(QueryName) < 0 then Add(QueryName);
ItemIndex := IndexOf(QueryName);
end;
end;
end;
procedure TAdhocForm.SaveQuery;
begin
if Unnamed then
SaveQueryAs
else
with SavedQueries do
begin
WriteString(QueryName, 'Query', StrToIniStr(QueryEdit.Text));
WriteString(QueryName, 'Alias', AliasCombo.Text);
WriteString(QueryName, 'Name', NameEdit.Text);
Unmodify;
end;
end;
procedure TAdhocForm.FormCreate(Sender: TObject);
procedure CreateInitialIni;
const
VeryInefficientName = 'IB: Very Inefficient Query';
VeryInefficientQuery =
'select EMP_NO, Avg(Salary) as Salary\n'+
' from employee, employee, employee\n' +
' group by EMP_NO';
AmountDueName = 'DB: Amount Due By Customer';
AmountDueByCustomer =
'select Company, Sum(ItemsTotal) - Sum(AmountPaid) as AmountDue\n' +
' from customer, orders\n' +
' where Customer.CustNo = Orders.CustNo\n' +
' group by Company';
begin
{ Create initial INI file when one doesn't already exisit }
with SavedQueries do
begin
WriteString(VeryInefficientName, 'Query', VeryInefficientQuery);
WriteString(VeryInefficientName, 'Alias', 'IBLOCAL');
WriteString(VeryInefficientName, 'Name', 'SYSDBA');
SavedQueryCombo.Items.Add(VeryInefficientName);
WriteString(AmountDueName, 'Query', AmountDueByCustomer);
WriteString(AmountDueName, 'Alias', 'DBDEMOS');
WriteString(AmountDueName, 'Name', '');
SavedQueryCombo.Items.Add(AmountDueName);
end;
end;
begin
{ Grab session aliases }
Session.GetAliasNames(AliasCombo.Items);
{ Load in saved queries }
SavedQueries := TIniFile.Create('BKQUERY.INI');
SavedQueries.ReadSections(SavedQueryCombo.Items);
if SavedQueryCombo.Items.Count <= 0 then CreateInitialIni;
SavedQueryCombo.ItemIndex := 0;
QueryName := SavedQueryCombo.Items[0];
Unmodify;
ReadQuery;
end;
procedure TAdhocForm.FormDestroy(Sender: TObject);
begin
SavedQueries.Free;
end;
procedure TAdhocForm.CloseBtnClick(Sender: TObject);
begin
Close;
end;
procedure TAdhocForm.ExecuteBtnClick(Sender: TObject);
begin
BackgroundQuery(QueryName, AliasCombo.Text, NameEdit.Text, PasswordEdit.Text,
QueryEdit.Text);
BringToFront;
end;
procedure TAdhocForm.NewBtnClick(Sender: TObject);
function UniqueName: string;
var
I: Integer;
begin
I := 1;
repeat
Result := Format('Query%d', [I]);
Inc(I);
until SavedQueryCombo.Items.IndexOf(Result) < 0;
end;
begin
AliasCombo.Text := 'DBDEMOS';
NameEdit.Text := '';
PasswordEdit.Text := '';
QueryEdit.Text := '';
QueryEdit.SetFocus;
QueryName := UniqueName;
SavedQueryCombo.ItemIndex := -1;
Unnamed := True;
end;
procedure TAdhocForm.SaveBtnClick(Sender: TObject);
begin
SaveQuery;
end;
procedure TAdhocForm.SaveAsBtnClick(Sender: TObject);
begin
SaveQueryAs;
end;
procedure TAdhocForm.SavedQueryComboChange(Sender: TObject);
begin
ReadQuery;
end;
procedure TAdhocForm.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
CanClose := CheckModified;
end;
end.
|
unit frGoods;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, frListBase, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter,
cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData,
IBX.IBCustomDataSet, IBX.IBQuery, IBX.IBUpdateSQL, RzButton, RzPanel,
cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxClasses, cxGridCustomView, cxGrid, Vcl.ExtCtrls, cxDBLookupComboBox;
type
TFrameGoods = class(TFrameListBase)
grdPhoneDBTableView1: TcxGridDBTableView;
grdPhoneDBTableView1Column1: TcxGridDBColumn;
procedure btnEditClick(Sender: TObject);
private
procedure SetServices(ASource: TDataset);
public
function SaveData: Boolean; override;
end;
implementation
{$R *.dfm}
uses
formSelService, DM_Main;
procedure TFrameGoods.btnEditClick(Sender: TObject);
var
frm: TfrmSelectService;
begin
try
frm := TfrmSelectService.Create(self);
frm.DsServiceCli := Query;
frm.ShowModal;
SetServices(frm.MemServices);
finally
FreeAndNil(frm);
end;
end;
function TFrameGoods.SaveData: Boolean;
var
client_id, ind: Integer;
begin
ind := QueryParams.IndexOf('CLIENT_ID');
if ind > -1 then
client_id := TField(QueryParams.Objects[ind]).AsInteger;
Query.First;
while not Query.Eof do
begin
if Query.FieldByName('Client_id').AsInteger <> client_id then
begin
if Query.State = dsBrowse then
Query.Edit;
Query.FieldByName('Client_id').AsInteger := client_id;
end;
if Query.Modified then
Query.post;
Query.Next;
end;
result := inherited SaveData;
end;
procedure TFrameGoods.SetServices(ASource: TDataset);
begin
Query.First;
//проверка на снятие отметки
while not Query.Eof do
begin
if not ASource.Locate('id; sel', VarArrayOf([Query.FieldByName('service_id').AsInteger, 1]), []) then
Query.Delete;
Query.Next;
end;
ASource.First;
while not ASource.Eof do
begin
if ASource.FieldByName('sel').AsInteger = 1 then
begin
if not Query.Locate('service_id', ASource.FieldByName('id').AsInteger, []) then
with Query do
begin
Append;
FieldByName('service_id').AsInteger := ASource.FieldByName('id').AsInteger;
FieldByName('client_id').AsInteger := 0; //установка потом
Post;
end;
end;
ASource.Next;
end;
end;
end.
|
{: GLVerletSkeletonColliders<p>
Skeleton colliders for defining and controlling verlet
constraints.<p>
<b>History :</b><font size=-1><ul>
<li>11/12/03 - SG - Now uses AddToVerletWorld to build the constraints.
<li>08/10/03 - SG - Creation.
</ul></font>
}
unit GLVerletSkeletonColliders;
interface
uses
System.Classes,
//GLS
GLPersistentClasses, GLVectorGeometry, GLVectorFileObjects, GLVerletTypes,
GLVectorTypes;
type
// TSCVerletBase
//
{: Base verlet skeleton collider class. }
TSCVerletBase = class(TSkeletonCollider)
private
FVerletConstraint : TVerletConstraint;
public
procedure WriteToFiler(writer : TVirtualWriter); override;
procedure ReadFromFiler(reader : TVirtualReader); override;
procedure AddToVerletWorld(VerletWorld : TVerletWorld); virtual;
{: The verlet constraint is created through the AddToVerletWorld
procedure. }
property VerletConstraint : TVerletConstraint read FVerletConstraint;
end;
// TSCVerletSphere
//
{: Sphere shaped verlet constraint in a skeleton collider. }
TSCVerletSphere = class(TSCVerletBase)
private
FRadius : Single;
protected
procedure SetRadius(const val : Single);
public
constructor Create; override;
procedure WriteToFiler(writer : TVirtualWriter); override;
procedure ReadFromFiler(reader : TVirtualReader); override;
procedure AddToVerletWorld(VerletWorld : TVerletWorld); override;
procedure AlignCollider; override;
property Radius : Single read FRadius write SetRadius;
end;
// TSCVerletCapsule
//
{: Capsule shaped verlet constraint in a skeleton collider. }
TSCVerletCapsule = class(TSCVerletBase)
private
FRadius,
FLength : Single;
protected
procedure SetRadius(const val : Single);
procedure SetLength(const val : Single);
public
constructor Create; override;
procedure WriteToFiler(writer : TVirtualWriter); override;
procedure ReadFromFiler(reader : TVirtualReader); override;
procedure AddToVerletWorld(VerletWorld : TVerletWorld); override;
procedure AlignCollider; override;
property Radius : Single read FRadius write SetRadius;
property Length : Single read FLength write SetLength;
end;
{: After loading call this function to add all the constraints in a
skeleton collider list to a given verlet world. }
procedure AddSCVerletConstriantsToVerletWorld(
colliders : TSkeletonColliderList; world : TVerletWorld);
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------
// ------------------ Global methods ------------------
// ------------------
// AddSCVerletConstriantsToVerletWorld
//
procedure AddSCVerletConstriantsToVerletWorld(
colliders : TSkeletonColliderList; world : TVerletWorld);
var
i : Integer;
begin
for i:=0 to colliders.Count-1 do
if colliders[i] is TSCVerletBase then
TSCVerletBase(colliders[i]).AddToVerletWorld(world);
end;
// ------------------
// ------------------ TSCVerletBase ------------------
// ------------------
// WriteToFiler
//
procedure TSCVerletBase.WriteToFiler(writer : TVirtualWriter);
begin
inherited WriteToFiler(writer);
with writer do begin
WriteInteger(0); // Archive Version 0
end;
end;
// ReadFromFiler
//
procedure TSCVerletBase.ReadFromFiler(reader : TVirtualReader);
var
archiveVersion : integer;
begin
inherited ReadFromFiler(reader);
archiveVersion:=reader.ReadInteger;
if archiveVersion=0 then with reader do
// Nothing yet
else RaiseFilerException(archiveVersion);
end;
// AddToVerletWorld
//
procedure TSCVerletBase.AddToVerletWorld(VerletWorld : TVerletWorld);
begin
AlignCollider;
end;
// ------------------
// ------------------ TSCVerletSphere ------------------
// ------------------
// Create
//
constructor TSCVerletSphere.Create;
begin
inherited;
Radius:=0.5;
AlignCollider;
end;
// WriteToFiler
//
procedure TSCVerletSphere.WriteToFiler(writer : TVirtualWriter);
begin
inherited WriteToFiler(writer);
with writer do begin
WriteInteger(0); // Archive Version 0
WriteFloat(FRadius);
end;
end;
// ReadFromFiler
//
procedure TSCVerletSphere.ReadFromFiler(reader : TVirtualReader);
var
archiveVersion : integer;
begin
inherited ReadFromFiler(reader);
archiveVersion:=reader.ReadInteger;
if archiveVersion=0 then with reader do
Radius:=ReadFloat
else RaiseFilerException(archiveVersion);
end;
// AddToVerletWorld
//
procedure TSCVerletSphere.AddToVerletWorld(VerletWorld : TVerletWorld);
begin
FVerletConstraint:=TVCSphere.Create(VerletWorld);
TVCSphere(FVerletConstraint).Radius:=FRadius;
inherited;
end;
// AlignCollider
//
procedure TSCVerletSphere.AlignCollider;
begin
inherited;
if Assigned(FVerletConstraint) then
TVCSphere(FVerletConstraint).Location:=AffineVectorMake(GlobalMatrix.V[3]);
end;
// SetRadius
//
procedure TSCVerletSphere.SetRadius(const val : Single);
begin
if val<>FRadius then begin
FRadius:=val;
if Assigned(FVerletConstraint) then
TVCSphere(FVerletConstraint).Radius:=FRadius;
end;
end;
// ------------------
// ------------------ TSCVerletCapsule ------------------
// ------------------
// Create
//
constructor TSCVerletCapsule.Create;
begin
inherited;
Radius:=0.5;
Length:=1;
AlignCollider;
end;
// WriteToFiler
//
procedure TSCVerletCapsule.WriteToFiler(writer : TVirtualWriter);
begin
inherited WriteToFiler(writer);
with writer do begin
WriteInteger(0); // Archive Version 0
WriteFloat(FRadius);
WriteFloat(FLength);
end;
end;
// ReadFromFiler
//
procedure TSCVerletCapsule.ReadFromFiler(reader : TVirtualReader);
var
archiveVersion : integer;
begin
inherited ReadFromFiler(reader);
archiveVersion:=reader.ReadInteger;
if archiveVersion=0 then with reader do begin
Radius:=ReadFloat;
Length:=ReadFloat;
end else RaiseFilerException(archiveVersion);
end;
// AddToVerletWorld
//
procedure TSCVerletCapsule.AddToVerletWorld(VerletWorld : TVerletWorld);
begin
FVerletConstraint:=TVCCapsule.Create(VerletWorld);
TVCCapsule(FVerletConstraint).Radius:=FRadius;
TVCCapsule(FVerletConstraint).Length:=FLength;
inherited;
end;
// AlignCollider
//
procedure TSCVerletCapsule.AlignCollider;
begin
inherited;
if Assigned(FVerletConstraint) then begin
TVCCapsule(FVerletConstraint).Location:=AffineVectorMake(GlobalMatrix.V[3]);
TVCCapsule(FVerletConstraint).Axis:=AffineVectorMake(GlobalMatrix.V[1]);
end;
end;
// SetRadius
//
procedure TSCVerletCapsule.SetRadius(const val : Single);
begin
if val<>FRadius then begin
FRadius:=val;
if Assigned(FVerletConstraint) then
TVCCapsule(FVerletConstraint).Radius:=FRadius;
end;
end;
// SetLength
//
procedure TSCVerletCapsule.SetLength(const val : Single);
begin
if val<>FLength then begin
FLength:=val;
if Assigned(FVerletConstraint) then
TVCCapsule(FVerletConstraint).Length:=FLength;
end;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
RegisterClasses([TSCVerletBase,TSCVerletSphere,TSCVerletCapsule]);
end.
|
{ ****************************************************************************** }
{ * ics support * }
{ * written by QQ 600585@qq.com * }
{ * https://github.com/PassByYou888/CoreCipher * }
{ * https://github.com/PassByYou888/ZServer4D * }
{ * https://github.com/PassByYou888/zExpression * }
{ * https://github.com/PassByYou888/zTranslate * }
{ * https://github.com/PassByYou888/zSound * }
{ * https://github.com/PassByYou888/zAnalysis * }
{ * https://github.com/PassByYou888/zGameWare * }
{ * https://github.com/PassByYou888/zRasterization * }
{ ****************************************************************************** }
(*
update history
*)
unit CommunicationFramework_Server_ICSCustomSocket;
{$INCLUDE ..\zDefine.inc}
interface
uses
Messages, Windows,
SysUtils, Classes,
OverByteIcsWSocket, OverbyteIcsWinsock;
type
TCustomICS = class(TWSocket)
public
end;
function WSAInfo: string;
function WSAIPList: TStrings;
procedure ProcessICSMessages;
implementation
function WSAInfo: string;
var
_D: TWSADATA;
ipLst: TStrings;
begin
_D := WinsockInfo;
ipLst := LocalIPList(TSocketFamily.sfAny);
Result := Format('Version:%D' + #13#10 + 'High Version:%D' + #13#10 + 'Description:%S' + #13#10 + 'System Status:%S' + #13#10 + 'Vendor Information:%S' + #13#10 +
'Max Sockets:%D' + #13#10 + 'Max UDP:%D' + #13#10 + 'local host name:%s' + #13#10 + 'Local IP list:' + #13#10 + '%s', [
_D.wVersion, _D.wHighVersion,
StrPas(_D.szDescription),
StrPas(_D.szSystemStatus),
StrPas(_D.lpVendorInfo),
_D.iMaxSockets,
_D.iMaxUdpDg,
LocalHostName,
ipLst.Text]);
end;
function WSAIPList: TStrings;
begin
Result := LocalIPList(TSocketFamily.sfAny);
end;
var
ICSMessageProcessing: Boolean = False;
procedure ProcessICSMessages;
var
Msg: TMsg;
begin
if ICSMessageProcessing then
Exit;
ICSMessageProcessing := True;
try
while PeekMessage(Msg, 0, 0, 0, PM_REMOVE) do
begin
try
TranslateMessage(Msg);
DispatchMessage(Msg);
except
end;
end;
except
end;
ICSMessageProcessing := False;
end;
end.
|
unit JetDataFormats;
interface
uses SysUtils;
function JetFormatSettings: TFormatSettings;
function EncodeBin(data: PByte; size: integer): WideString; overload;
function EncodeBin(const data: array of byte): WideString; overload;
function EncodeOleBin(data: OleVariant): WideString;
function EncodeComment(str: WideString): WideString;
function DecodeComment(str: WideString): WideString;
function JetEncodeStr(const val: WideString): WideString;
function JetEncodeTypedValue(Value: OleVariant; DataType: integer): Widestring;
function JetEncodeValue(Value: OleVariant): WideString;
implementation
uses WideStrUtils, Variants, OleDB, JetCommon;
var
FJetFormatSettings: TFormatSettings;
FJetFormatSettingsInitialized: boolean = false;
function JetFormatSettings: TFormatSettings;
begin
if not FJetFormatSettingsInitialized then begin
FJetFormatSettings := TFormatSettings.Create();
with FJetFormatSettings do begin
DecimalSeparator := '.';
DateSeparator := '-';
TimeSeparator := ':';
ShortDateFormat := 'mm-dd-yyyy';
LongDateFormat := 'mm-dd-yyyy';
ShortTimeFormat := 'hh:nn:ss';
LongTimeFormat := 'hh:nn:ss';
end;
FJetFormatSettingsInitialized := true;
end;
Result := FJetFormatSettings;
end;
//Encodes binary data for inserting to SQL text.
//Presently unused (DEFAULT values are already escaped in the DB)
function EncodeBin(data: PByte; size: integer): WideString; overload;
const HexChars:WideString='0123456789ABCDEF';
var i: integer;
begin
if size<=0 then begin
Result := 'NULL';
exit;
end;
SetLength(Result, 2+size*2);
Result[1] := '0';
Result[2] := 'x';
for i := 0 to size - 1 do begin
Result[2+i*2+1] := HexChars[1+(data^ shr 4)];
Result[2+i*2+2] := HexChars[1+(data^ and $0F)];
Inc(data);
end;
end;
function EncodeBin(const data: array of byte): WideString; overload;
begin
Result := EncodeBin(@data[0], Length(data));
end;
function EncodeOleBin(data: OleVariant): WideString;
var bin_data: array of byte;
begin
if VarIsNil(data) then
Result := 'NULL'
else begin
bin_data := data;
Result := EncodeBin(bin_data);
end;
end;
//Encodes /**/ comment for inserting into SQL text. Escapes closure symbols.
//Replacements:
// \ == \\
// / == \/
//It's handy that you don't need a special parsing when looking for comment's end:
//dangerous combinations just get broken during the encoding.
function EncodeComment(str: WideString): WideString;
var pc: PWideChar;
i: integer;
c: WideChar;
begin
//We'll never need more than twice the size
SetLength(Result, 2*Length(str));
pc := @Result[1];
for i := 1 to Length(str) do begin
c := str[i];
if (c='\') or (c='/') then begin
pc^ := '\';
Inc(pc);
pc^ := c;
end else
begin
pc^ := c;
end;
Inc(pc);
end;
//Actual length
SetLength(Result, (integer(pc)-integer(@Result[1])) div 2);
end;
//Decodes comment.
function DecodeComment(str: WideString): WideString;
var pc: PWideChar;
i: integer;
c: WideChar;
SpecSymbol: boolean;
begin
//We'll never need more than the source size
SetLength(Result, Length(str));
pc := @Result[1];
SpecSymbol := false;
for i := 1 to Length(str) do begin
c := str[i];
if (not SpecSymbol) and (c='\') then begin
SpecSymbol := true;
continue;
end;
SpecSymbol := false;
pc^ := c;
Inc(pc);
end;
//Actual length
SetLength(Result, (integer(pc)-integer(@Result[1])) div 2);
end;
//Encodes a string value for inserting into Jet SQL text, escapes special symbols.
//Returns the encoded value, including quotes (when neccessary)
function JetEncodeStr(const val: WideString): WideString;
var isWeird, hasQuotes: boolean;
i: integer;
c: WideChar;
begin
//Jet SQL doesn't support backslash escapes. Quotes are escaped by doubling them:
// ' -> ''
// " -> ""
//but there seems to be no docs for anything else.
if val = '' then begin
Result := '''''';
exit;
end;
//If there's anything weird in the string that probably won't parse, store it
//as binary (this works fine).
isWeird := false;
hasQuotes := false;
for i := 1 to Length(val) do begin
c := val[i];
if c < #32 then begin
isWeird := true;
break;
end;
if c = '''' then
hasQuotes := true;
end;
if isWeird then begin
Result := EncodeBin(@val[1], Length(val)*SizeOf(val[1]));
exit;
end;
Result := val;
//Only escape 's. "s shouldn't be escaped when wrapping in 's
if hasQuotes then
Result := WideReplaceStr(Result, '''', ''''''); //Delphi also escapes quotes this way
Result := '''' + Result + '''';
end;
//Because Delphi does not allow int64(Value).
function uint_cast(Value: OleVariant): int64;
begin
Result := value;
end;
//Formats a field value according to it's type
//Presently unused (DEFAULT values are already escaped in the DB)
function JetEncodeTypedValue(Value: OleVariant; DataType: integer): Widestring;
begin
if VarIsNil(Value) then
Result := 'NULL'
else
case DataType of
DBTYPE_I1, DBTYPE_I2, DBTYPE_I4,
DBTYPE_UI1, DBTYPE_UI2, DBTYPE_UI4:
Result := IntToStr(integer(Value));
DBTYPE_I8, DBTYPE_UI8:
Result := IntToStr(uint_cast(Value));
DBTYPE_R4, DBTYPE_R8:
Result := FloatToStr(double(Value), JetFormatSettings);
DBTYPE_NUMERIC, DBTYPE_DECIMAL, DBTYPE_CY:
Result := FloatToStr(currency(Value), JetFormatSettings);
DBTYPE_GUID:
//Or else it's not GUID
Result := GuidToString(StringToGuid(Value));
DBTYPE_DATE:
Result := '#'+DatetimeToStr(Value, JetFormatSettings)+'#';
DBTYPE_BOOL:
Result := BoolToStr(Value, {UseBoolStrs=}true);
DBTYPE_BYTES:
Result := EncodeOleBin(Value);
DBTYPE_WSTR:
Result := JetEncodeStr(Value)
else
Result := JetEncodeStr(Value); //best guess
end;
end;
//Encodes a value according to it's variant type
//Presently unused (DEFAULT values are already escaped in the DB)
function JetEncodeValue(Value: OleVariant): WideString;
begin
if VarIsNil(Value) then
Result := 'NULL'
else
case VarType(Value) of
varSmallInt, varInteger, varShortInt,
varByte, varWord, varLongWord:
Result := IntToStr(integer(Value));
varInt64:
Result := IntToStr(uint_cast(Value));
varSingle, varDouble:
Result := FloatToStr(double(Value), JetFormatSettings);
varCurrency:
Result := FloatToStr(currency(Value), JetFormatSettings);
varDate:
Result := '#'+DatetimeToStr(Value, JetFormatSettings)+'#';
varOleStr, varString:
Result := JetEncodeStr(Value);
varBoolean:
Result := BoolToStr(Value, {UseBoolStrs=}true);
varArray:
Result := EncodeOleBin(Value);
else
Result := JetEncodeStr(Value); //best guess
end;
end;
end.
|
unit GernerarRecargosIntereses;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, UnitCuentaCredito;
type
TFormGenerarRecargosI = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Label1: TLabel;
LabelNumeroDeCuenta: TLabel;
Label2: TLabel;
LabelDeudaTotal: TLabel;
Label3: TLabel;
LabelNumeroDePagos: TLabel;
Label4: TLabel;
Label5: TLabel;
LabelMontoDelInteres: TLabel;
LabelMontoDelRecargo: TLabel;
Label6: TLabel;
Label7: TLabel;
procedure onShow(Sender: TObject);
procedure onClose(Sender: TObject; var Action: TCloseAction);
procedure clicCancelar(Sender: TObject);
procedure clicGenerarInteres(Sender: TObject);
procedure clicGenerarRecargo(Sender: TObject);
procedure sumarRecargoAcuenta();
procedure regresarMenuIntereses();
private
{ Private declarations }
public
numeroDeCuenta: string;
cuentaCredito: TCuentaCredito;
deudaTotal : Currency;
pagosRealizados : integer;
pagosFaltantes : integer;
pagoMensual : Currency;
montoRecargo : Currency;
montoInteres : Currency;
porcentageInteres : Currency;
porcengeRecargo : Currency;
currentDate : TDateTime;
totalIntereses : Currency;
deudaTotalIntereses: Currency;
{ Public declarations }
end;
var
FormGenerarRecargosI: TFormGenerarRecargosI;
implementation
uses MenuInteresesRecargos, DataAccesModule;
{$R *.dfm}
procedure TFormGenerarRecargosI.clicCancelar(Sender: TObject);
begin
regresarMenuIntereses;
end;
procedure TFormGenerarRecargosI.clicGenerarInteres(Sender: TObject);
begin
//GENERAR INTERES
deudaTotalIntereses := totalIntereses + montoInteres;
with DataAccesModule.DataAccesModule_.crearInteres do
begin
Open;
Refresh;
if FindKey([cuentaCredito.idCuentaCredito]) then
begin
Edit;
deudaTotal := deudaTotal + montoRecargo;
FieldByName('totalInteresesAcumulados').AsCurrency := deudaTotalIntereses;
Post;
end;
end;
showMessage('Interés generado exitosamente');
regresarMenuIntereses;
end;
procedure TFormGenerarRecargosI.clicGenerarRecargo(Sender: TObject);
begin
//Generar recargo
//showmessage(CurrToStrF(montoRecargo, ffCurrency, 2));
//cuentaCredito.registrarRecargo(montoRecargo);
//showmessage('Se ha generado el recargo con éxito');
currentDate := Now;
with DataAccesModule_.crearRecargo do
begin
Open;
Refresh;
Insert;
FieldByName('fecha').AsDateTime := currentDate;
FieldByName('monto').AsCurrency := montoRecargo;
FieldByName('idCuentaCredito').AsInteger := cuentaCredito.idCuentaCredito;
Post;
end;
sumarRecargoAcuenta;
showMessage('Recargo generado exitósamente');
regresarMenuIntereses;
end;
procedure TFormGenerarRecargosI.onClose(Sender: TObject;
var Action: TCloseAction);
begin
Application.Terminate;
end;
procedure TFormGenerarRecargosI.onShow(Sender: TObject);
begin
//Todo on show
numeroDeCuenta := MenuInteresesRecargos.FormMenuInteresesRecargos.numeroDeCuenta;
deudaTotal := MenuInteresesRecargos.FormMenuInteresesRecargos.deudaTotal;
LabelNumeroDeCuenta.Caption := numeroDeCuenta;
LabelDeudaTotal.Caption := CurrToStrF(deudaTotal, ffCurrency, 2);
cuentaCredito := TCuentaCredito.Create;
cuentaCredito.obtenerId(numeroDeCuenta);
pagosRealizados := cuentaCredito.getPagos;
LabelNumeroDePagos.Caption := inttostr(pagosRealizados);
if pagosRealizados < 12 then
begin
pagosFaltantes := 12 - pagosRealizados;
pagoMensual := deudaTotal / pagosFaltantes;
porcengeRecargo := 0.05;
porcentageInteres := 0.10;
montoRecargo := pagoMensual * porcengeRecargo;
montoInteres := pagoMensual * porcentageInteres;
end
else
begin
pagosFaltantes :=0;
pagoMensual := 0;
montoRecargo := 0;
montoInteres := 0;
end;
LabelMontoDelRecargo.Caption := CurrToStrF(montoRecargo, ffCurrency, 2);
LabelMontoDelInteres.Caption := CurrToStrF(montoInteres, ffCurrency, 2);
totalIntereses := MenuInteresesRecargos.FormMenuInteresesRecargos.totalIntereses;
end;
procedure TFormGenerarRecargosI.regresarMenuIntereses;
begin
MenuInteresesRecargos.FormMenuInteresesRecargos.Show;
FormGenerarRecargosI.Visible:= False;
end;
procedure TFormGenerarRecargosI.sumarRecargoAcuenta;
begin
with DataAccesModule.DataAccesModule_.updateCuentaCredito do
begin
Open;
Refresh;
if FindKey([cuentaCredito.idCuentaCredito]) then
begin
Edit;
deudaTotal := deudaTotal + montoRecargo;
FieldByName('deudaTotal').AsCurrency := deudaTotal;
Post;
end;
end;
end;
end.
|
unit DNASequenceAlignmentunit;
{$mode objfpc}{$H+}
interface
const
gap: Integer = -5;
//matriz similar para realizar el alineamineto
// A G C T
//A 10 -1 -3 -4
//G -1 7 -5 -3
//C -3 -5 9 0
//T -4 -3 0 8
similarityMatrix: array[0..3,0..3]of Integer =
((10,-1,-3,-4),(-1,7,-5,-3),(-3,-5,9,0),(-4,-3,0,8));
//valores de los nucleotidos en la matriz similar
A: Integer = 0;
G: Integer = 1;
C: Integer = 2;
T: Integer = 3;
var
namefile1: String;
namefile2: String;
sequence1: String;
sequence2: String;
match: Integer;
left: Integer;
up: Integer;
valueMax: Integer;
rowsM: Integer;
columnsM: Integer;
nucleotideI: Char;
nucleotideJ: Char;
result1: String;
result2: String;
iMM,jMM: Integer;
//debe haber una manera mas eficiente, pero me da error al poner
//los valores rows y columns en el arreglo
matrix: array[0..1500, 0..2000] of Integer;
//-------------------------------- Fin de Var y Const Globales----------------\\
//-------------------------------- Funciones y Procesos ----------------------\\
procedure getSequece(nameFile: String; var bufferS: String);
procedure generateMatrix(rows, columns: Integer);
procedure getAlignment(rows, columns: Integer);
implementation
uses
Classes, SysUtils, math, strutils;
//guarda el resultado en la variable bufferS
procedure getSequece(nameFile: String; var bufferS: String);
var
fileRead: TextFile;
begin
AssignFile(fileRead, nameFile);
Reset(fileRead);
while not eof(fileRead) do
begin
ReadLn(fileRead,bufferS);
end;
CloseFile(fileRead);
end;
//generar la matriz con las secuencias
procedure generateMatrix(rows, columns: Integer);
var
i,j,iSM,jSM: Integer;
begin
//Inicializa el gap en la matriz
for i:= 0 to rows do
matrix[i][0]:= gap * i;
for j:= 0 to columns do
matrix[0][j]:= gap * j;
for i:= 0 to (rows-1) do
begin
for j:= 0 to (columns-1) do
begin
nucleotideI:= sequence2[i+1];
case (nucleotideI) of
'A' : iSM:= A;
'G' : iSM:= G;
'C' : iSM:= C;
'T' : iSM:= T;
end;
nucleotideJ:= sequence1[j+1];
case (nucleotideJ) of
'A' : jSM:= A;
'G' : jSM:= G;
'C' : jSM:= C;
'T' : jSM:= T;
end;
//Write('comprobando ',nucleotideI, ' y ', nucleotideJ);
match:= matrix[i][j] + similarityMatrix[iSM][jSM];
up:= matrix[i][j+1] + gap;
valueMax:= Max(match, up);
left:= matrix[i+1][j] + gap;
valueMax:= Max(valueMax, left);
//Write(' ', valueMax, ' , ');
matrix[i+1][j+1]:= valueMax;
end;
end;
end;
procedure getAlignment(rows, columns: Integer);
var
i,j,iSM,jSM: Integer;
begin
WriteLn('creando la alineacion de secuencias');
i:= (rows); //sequecen2
j:= (columns); //sequence1
while ( (i > 0) and (j > 0) ) do
begin
nucleotideI:= sequence2[i];
case (nucleotideI) of
'A' : iSM:= A;
'G' : iSM:= G;
'C' : iSM:= C;
'T' : iSM:= T;
end;
nucleotideJ:= sequence1[j];
case (nucleotideJ) of
'A' : jSM:= A;
'G' : jSM:= G;
'C' : jSM:= C;
'T' : jSM:= T;
end;
match:= matrix[i-1][j-1] + similarityMatrix[iSM][jSM];
up:= matrix[i-1][j] + gap;
left:= matrix[i][j-1] + gap;
if(left = matrix[i][j]) then
begin
AppendStr(result1, '-');
AppendStr(result2, nucleotideJ);
j:= j-1;
end
else if(up = matrix[i][j]) then
begin
AppendStr(result1, nucleotideI);
AppendStr(result2, '-');
i:= i-1;
end
else
begin
AppendStr(result2, nucleotideI);
AppendStr(result1, nucleotideJ);
i:= i-1;
j:= j-1;
end;
end;
while (i > 0) do
begin
nucleotideI:= sequence2[i-1];
AppendStr(result2, nucleotideI);
AppendStr(result1, '-');
i:= i-1;
end;
while (j > 0) do
begin
nucleotideJ:= sequence1[j-1];
AppendStr(result2, '-');
AppendStr(result1, nucleotideJ);
j:= j-1;
end;
WriteLn('La alineacion Global se ha realizado: ');
WriteLn(ReverseString(result2));
WriteLn(ReverseString(result1));
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.